org.apache.curator.framework.api.ACLProvider Java Examples

The following examples show how to use org.apache.curator.framework.api.ACLProvider. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CuratorClientFactoryImpl.java    From helios with Apache License 2.0 6 votes vote down vote up
@Override
public CuratorFramework newClient(String connectString,
                                  int sessionTimeoutMs,
                                  int connectionTimeoutMs,
                                  RetryPolicy retryPolicy,
                                  final ACLProvider aclProvider,
                                  final List<AuthInfo> authorization) {
  final Builder builder = CuratorFrameworkFactory.builder()
      .connectString(connectString)
      .sessionTimeoutMs(sessionTimeoutMs)
      .connectionTimeoutMs(connectionTimeoutMs)
      .retryPolicy(retryPolicy);

  if (aclProvider != null) {
    builder.aclProvider(aclProvider);
  }

  if (authorization != null && !authorization.isEmpty()) {
    builder.authorization(authorization);
  }

  return builder.build();
}
 
Example #2
Source File: CuratorFactory.java    From atlas with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
void enhanceBuilderWithSecurityParameters(HAConfiguration.ZookeeperProperties zookeeperProperties,
                                          CuratorFrameworkFactory.Builder builder) {

    ACLProvider aclProvider = getAclProvider(zookeeperProperties);

    AuthInfo authInfo = null;
    if (zookeeperProperties.hasAuth()) {
        authInfo = AtlasZookeeperSecurityProperties.parseAuth(zookeeperProperties.getAuth());
    }

    if (aclProvider != null) {
        LOG.info("Setting up acl provider.");
        builder.aclProvider(aclProvider);
        if (authInfo != null) {
            byte[] auth = authInfo.getAuth();
            LOG.info("Setting up auth provider with scheme: {} and id: {}", authInfo.getScheme(),
                    getIdForLogging(authInfo.getScheme(), new String(auth, Charsets.UTF_8)));
            builder.authorization(authInfo.getScheme(), auth);
        }
    }
}
 
Example #3
Source File: TestCuratorACLProviderFactory.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testSaslAuthSchemeHeadless(){
    final NiFiProperties nifiProperties;
    final CuratorACLProviderFactory factory;
    otherProps.put("nifi.zookeeper.kerberos.removeHostFromPrincipal", "true");
    otherProps.put("nifi.zookeeper.kerberos.removeRealmFromPrincipal", "true");
    otherProps.put("nifi.kerberos.service.principal","[email protected]");
    nifiProperties = NiFiProperties.createBasicNiFiProperties(propsFile, otherProps);
    factory = new CuratorACLProviderFactory();
    ZooKeeperClientConfig config = ZooKeeperClientConfig.createConfig(nifiProperties);
    ACLProvider provider = factory.create(config);
    assertFalse(provider instanceof DefaultACLProvider);
    List<ACL> acls = provider.getDefaultAcl();
    assertNotNull(acls);
    assertEquals(acls.get(0).getId().toString().trim(),"'sasl,'nifi");
}
 
Example #4
Source File: TestCuratorACLProviderFactory.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testSaslAuthSchemeNoHostWithRealm(){

    final NiFiProperties nifiProperties;
    final CuratorACLProviderFactory factory;
    otherProps.put("nifi.zookeeper.kerberos.removeHostFromPrincipal", "true");
    otherProps.put("nifi.zookeeper.kerberos.removeRealmFromPrincipal", "false");
    nifiProperties = NiFiProperties.createBasicNiFiProperties(propsFile, otherProps);
    factory = new CuratorACLProviderFactory();
    ZooKeeperClientConfig config = ZooKeeperClientConfig.createConfig(nifiProperties);
    ACLProvider provider = factory.create(config);
    assertFalse(provider instanceof DefaultACLProvider);
    List<ACL> acls = provider.getDefaultAcl();
    assertNotNull(acls);
    assertEquals(acls.get(0).getId().toString().trim(),"'sasl,'[email protected]");

}
 
Example #5
Source File: ExhibitorArguments.java    From exhibitor with Apache License 2.0 6 votes vote down vote up
public ExhibitorArguments(int connectionTimeOutMs, int logWindowSizeLines, int configCheckMs, String extraHeadingText, String thisJVMHostname, boolean allowNodeMutations, JQueryStyle jQueryStyle, int restPort, String restPath, String restScheme, Runnable shutdownProc, LogDirection logDirection, ACLProvider aclProvider, ServoRegistration servoRegistration, String preferencesPath, RemoteConnectionConfiguration remoteConnectionConfiguration, HttpsConfiguration httpsConfiguration)
{
    this.connectionTimeOutMs = connectionTimeOutMs;
    this.logWindowSizeLines = logWindowSizeLines;
    this.configCheckMs = configCheckMs;
    this.extraHeadingText = extraHeadingText;
    this.thisJVMHostname = thisJVMHostname;
    this.allowNodeMutations = allowNodeMutations;
    this.jQueryStyle = jQueryStyle;
    this.restPort = restPort;
    this.restPath = restPath;
    this.restScheme = restScheme;
    this.shutdownProc = shutdownProc;
    this.logDirection = logDirection;
    this.aclProvider = aclProvider;
    this.servoRegistration = servoRegistration;
    this.preferencesPath = preferencesPath;
    this.remoteConnectionConfiguration = remoteConnectionConfiguration;
    this.httpsConfiguration = httpsConfiguration;
}
 
Example #6
Source File: TestCuratorACLProviderFactory.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testSaslAuthSchemeWithHostNoRealm(){

    final NiFiProperties nifiProperties;
    final CuratorACLProviderFactory factory;
    otherProps.put("nifi.zookeeper.kerberos.removeHostFromPrincipal", "false");
    otherProps.put("nifi.zookeeper.kerberos.removeRealmFromPrincipal", "true");
    nifiProperties = NiFiProperties.createBasicNiFiProperties(propsFile, otherProps);
    factory = new CuratorACLProviderFactory();
    ZooKeeperClientConfig config = ZooKeeperClientConfig.createConfig(nifiProperties);
    ACLProvider provider = factory.create(config);
    assertFalse(provider instanceof DefaultACLProvider);
    List<ACL> acls = provider.getDefaultAcl();
    assertNotNull(acls);
    assertEquals(acls.get(0).getId().toString().trim(),"'sasl,'nifi/host");

}
 
Example #7
Source File: CuratorFactory.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
void enhanceBuilderWithSecurityParameters(HAConfiguration.ZookeeperProperties zookeeperProperties,
                                          CuratorFrameworkFactory.Builder builder) {

    ACLProvider aclProvider = getAclProvider(zookeeperProperties);

    AuthInfo authInfo = null;
    if (zookeeperProperties.hasAuth()) {
        authInfo = AtlasZookeeperSecurityProperties.parseAuth(zookeeperProperties.getAuth());
    }

    if (aclProvider != null) {
        LOG.info("Setting up acl provider.");
        builder.aclProvider(aclProvider);
        if (authInfo != null) {
            byte[] auth = authInfo.getAuth();
            LOG.info("Setting up auth provider with scheme: {} and id: {}", authInfo.getScheme(),
                    getIdForLogging(authInfo.getScheme(), new String(auth, Charsets.UTF_8)));
            builder.authorization(authInfo.getScheme(), auth);
        }
    }
}
 
Example #8
Source File: ZooKeeperAclInitializer.java    From helios with Apache License 2.0 6 votes vote down vote up
static void initializeAclRecursive(final ZooKeeperClient client, final String path,
                                   final ACLProvider aclProvider)
    throws KeeperException {
  try {
    final List<ACL> expected = aclProvider.getAclForPath(path);
    final List<ACL> actual = client.getAcl(path);

    if (newHashSet(expected).equals(newHashSet(actual))) {
      // actual ACL matches expected
    } else {
      client.setAcl(path, expected);
    }

    for (final String child : client.getChildren(path)) {
      initializeAclRecursive(client, path.replaceAll("/$", "") + "/" + child, aclProvider);
    }
  } catch (Exception e) {
    throwIfInstanceOf(e, KeeperException.class);
    throw new RuntimeException(e);
  }
}
 
Example #9
Source File: CuratorDiscoveryModuleTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Test
public void testSingleACLProvider() {
  ImmutableList<ACL> acl = ZooKeeperUtils.EVERYONE_READ_CREATOR_ALL;
  ACLProvider provider = new CuratorServiceDiscoveryModule.SingleACLProvider(acl);

  assertEquals(acl, provider.getDefaultAcl());
  assertEquals(acl, provider.getAclForPath("/random/path/1"));
  assertEquals(acl, provider.getAclForPath("/random/path/2"));
}
 
Example #10
Source File: CuratorPersister.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new {@link CuratorPersister} instance using the provided settings,
 * using reasonable defaults where custom values were not specified.
 */
public CuratorPersister build() {
  CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
      .connectString(zookeeperHostPort)
      .retryPolicy(retryPolicy);
  if (!username.isEmpty() && !password.isEmpty()) {
    List<ACL> acls = new ArrayList<ACL>();
    acls.addAll(ZooDefs.Ids.CREATOR_ALL_ACL);
    acls.addAll(ZooDefs.Ids.READ_ACL_UNSAFE);

    String authenticationString = username + ":" + password;
    builder.authorization("digest", authenticationString.getBytes(StandardCharsets.UTF_8))
        .aclProvider(new ACLProvider() {
          @Override
          public List<ACL> getDefaultAcl() {
            return acls;
          }

          @Override
          public List<ACL> getAclForPath(String path) {
            return acls;
          }
        });
  } else if (!username.isEmpty() || !password.isEmpty()) {
    throw new IllegalArgumentException(
        "username and password must both be provided, or both must be empty.");
  }

  if (lockEnabled) {
    // Lock curator (using a separate client created from this builder) BEFORE returning access
    // to persister
    CuratorLocker.lock(serviceName, builder);
  }

  CuratorPersister persister = new CuratorPersister(serviceName, builder.build());
  CuratorUtils.initServiceName(persister, serviceName);
  return persister;
}
 
Example #11
Source File: ZookeeperManager.java    From chronus with Apache License 2.0 5 votes vote down vote up
private void connect() throws Exception {
    RetryPolicy retryPolicy = new RetryUntilElapsed(Integer.MAX_VALUE, 10);
    String userName = properties.getProperty(keys.userName.toString());
    String zkConnectString = properties.getProperty(keys.zkConnectString.toString());
    int zkSessionTimeout = Integer.parseInt(properties.getProperty(keys.zkSessionTimeout.toString()));
    int zkConnectionTimeout = Integer.parseInt(properties.getProperty(keys.zkConnectionTimeout.toString()));
    boolean isCheckParentPath = Boolean.parseBoolean(properties.getProperty(keys.isCheckParentPath.toString(), "true"));
    String authString = userName + ":" + properties.getProperty(keys.password.toString());
    acl.clear();
    acl.add(new ACL(ZooDefs.Perms.ALL, new Id("digest", DigestAuthenticationProvider.generateDigest(authString))));
    acl.add(new ACL(ZooDefs.Perms.READ, Ids.ANYONE_ID_UNSAFE));
    log.info("----------------------------开始创建ZK连接----------------------------");
    log.info("zkConnectString:{}", zkConnectString);
    log.info("zkSessionTimeout:{}", zkSessionTimeout);
    log.info("zkConnectionTimeout:{}", zkConnectionTimeout);
    log.info("isCheckParentPath:{}", isCheckParentPath);
    log.info("userName:{}", userName);

    curator = CuratorFrameworkFactory.builder().connectString(zkConnectString)
            .sessionTimeoutMs(zkSessionTimeout)
            .connectionTimeoutMs(zkConnectionTimeout)
            .retryPolicy(retryPolicy).authorization("digest", authString.getBytes())
            .aclProvider(new ACLProvider() {
                @Override
                public List<ACL> getDefaultAcl() {
                    return ZooDefs.Ids.CREATOR_ALL_ACL;
                }

                @Override
                public List<ACL> getAclForPath(String path) {
                    return ZooDefs.Ids.CREATOR_ALL_ACL;
                }
            }).build();
    curator.start();
    log.info("----------------------------创建ZK连接成功----------------------------");
    this.isCheckParentPath = isCheckParentPath;
}
 
Example #12
Source File: CuratorUtil.java    From fluo with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a curator built using the given zookeeper connection string and timeout
 */
public static CuratorFramework newCurator(String zookeepers, int timeout, String secret) {

  final ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1000, 10);
  if (secret.isEmpty()) {
    return CuratorFrameworkFactory.newClient(zookeepers, timeout, timeout, retry);
  } else {
    return CuratorFrameworkFactory.builder().connectString(zookeepers)
        .connectionTimeoutMs(timeout).sessionTimeoutMs(timeout).retryPolicy(retry)
        .authorization("digest", ("fluo:" + secret).getBytes(StandardCharsets.UTF_8))
        .aclProvider(new ACLProvider() {
          @Override
          public List<ACL> getDefaultAcl() {
            return CREATOR_ALL_ACL;
          }

          @Override
          public List<ACL> getAclForPath(String path) {
            switch (path) {
              case ZookeeperPath.ORACLE_GC_TIMESTAMP:
                // The garbage collection iterator running in Accumulo tservers needs to read this
                // value w/o authenticating.
                return PUBLICLY_READABLE_ACL;
              default:
                return CREATOR_ALL_ACL;
            }
          }
        }).build();
  }
}
 
Example #13
Source File: CuratorUtils.java    From oodt with Apache License 2.0 5 votes vote down vote up
/**
 * Builds a {@link CuratorFramework} instance using the given connectString.
 *
 * @param connectString connection string to connect to zookeeper
 * @param logger        {@link Logger} instance of the calling class
 * @return Newly created CuratorFramework instance.
 */
public static CuratorFramework newCuratorFrameworkClient(String connectString, Logger logger) {
    int connectionTimeoutMs = Integer.parseInt(System.getProperty(Constants.Properties.ZK_CONNECTION_TIMEOUT, "15000"));
    int sessionTimeoutMs = Integer.parseInt(System.getProperty(Constants.Properties.ZK_CONNECTION_TIMEOUT, "60000"));
    int retryInitialWaitMs = Integer.parseInt(System.getProperty(Constants.Properties.ZK_CONNECTION_TIMEOUT, "1000"));
    int maxRetryCount = Integer.parseInt(System.getProperty(Constants.Properties.ZK_CONNECTION_TIMEOUT, "3"));

    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
            .namespace(NAMESPACE)
            .connectString(connectString)
            .retryPolicy(new ExponentialBackoffRetry(retryInitialWaitMs, maxRetryCount))
            .connectionTimeoutMs(connectionTimeoutMs)
            .sessionTimeoutMs(sessionTimeoutMs);

    /*
     * If authorization information is available, those will be added to the client. NOTE: These auth info are
     * for access control, therefore no authentication will happen when the client is being started. These
     * info will only be required whenever a client is accessing an already create ZNode. For another client of
     * another node to make use of a ZNode created by this node, it should also provide the same auth info.
     */
    if (System.getProperty(Constants.Properties.ZK_USERNAME) != null && System.getProperty(Constants.Properties.ZK_PASSWORD) != null) {
        String authenticationString = System.getProperty(Constants.Properties.ZK_USERNAME) + ":" + System.getProperty(Constants.Properties.ZK_PASSWORD);
        builder.authorization("digest", authenticationString.getBytes())
                .aclProvider(new ACLProvider() {
                    public List<ACL> getDefaultAcl() {
                        return ZooDefs.Ids.CREATOR_ALL_ACL;
                    }

                    public List<ACL> getAclForPath(String path) {
                        return ZooDefs.Ids.CREATOR_ALL_ACL;
                    }
                });
    }

    CuratorFramework client = builder.build();
    logger.debug("CuratorFramework client built successfully with connectString: {}, sessionTimeout: {} and connectionTimeout: {}",
            connectString, sessionTimeoutMs, connectionTimeoutMs);

    return client;
}
 
Example #14
Source File: ZKClusterCoordinator.java    From Bats with Apache License 2.0 5 votes vote down vote up
public ZKClusterCoordinator(DrillConfig config, String connect, ACLProvider aclProvider) {

    connect = connect == null || connect.isEmpty() ? config.getString(ExecConstants.ZK_CONNECTION) : connect;
    String clusterId = config.getString(ExecConstants.SERVICE_NAME);
    String zkRoot = config.getString(ExecConstants.ZK_ROOT);

    // check if this is a complex zk string.  If so, parse into components.
    Matcher m = ZK_COMPLEX_STRING.matcher(connect);
    if(m.matches()) {
      connect = m.group(1);
      zkRoot = m.group(2);
      clusterId = m.group(3);
    }

    logger.debug("Connect {}, zkRoot {}, clusterId: " + clusterId, connect, zkRoot);

    this.serviceName = clusterId;

    RetryPolicy rp = new RetryNTimes(config.getInt(ExecConstants.ZK_RETRY_TIMES),
      config.getInt(ExecConstants.ZK_RETRY_DELAY));
    curator = CuratorFrameworkFactory.builder()
      .namespace(zkRoot)
      .connectionTimeoutMs(config.getInt(ExecConstants.ZK_TIMEOUT))
      .retryPolicy(rp)
      .connectString(connect)
      .aclProvider(aclProvider)
      .build();
    curator.getConnectionStateListenable().addListener(new InitialConnectionListener());
    curator.start();
    discovery = newDiscovery();
    factory = CachingTransientStoreFactory.of(new ZkTransientStoreFactory(curator));
  }
 
Example #15
Source File: ZookeeperRegistry.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 获取默认的AclProvider
 * @return
 */
private ACLProvider getDefaultAclProvider() {
    return new ACLProvider() {
        @Override
        public List<ACL> getDefaultAcl() {
            return ZooDefs.Ids.CREATOR_ALL_ACL;
        }

        @Override
        public List<ACL> getAclForPath(String path) {
            return ZooDefs.Ids.CREATOR_ALL_ACL;
        }
    };
}
 
Example #16
Source File: HelloClientConfig.java    From jigsaw-payment with Apache License 2.0 5 votes vote down vote up
@Bean
public ACLProvider aclProvider() {
    return new ACLProvider() {
        @Override
        public List<ACL> getDefaultAcl() {
            return ZooDefs.Ids.CREATOR_ALL_ACL;
        }

        @Override
        public List<ACL> getAclForPath(String path) {
            return ZooDefs.Ids.CREATOR_ALL_ACL;
        }
    };
}
 
Example #17
Source File: ZookeeperAuthBoltServerTest.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 获取默认的AclProvider
 *
 * @return
 */
private static ACLProvider getDefaultAclProvider() {
    return new ACLProvider() {
        @Override
        public List<ACL> getDefaultAcl() {
            return ZooDefs.Ids.CREATOR_ALL_ACL;
        }

        @Override
        public List<ACL> getAclForPath(String path) {
            return ZooDefs.Ids.CREATOR_ALL_ACL;
        }
    };
}
 
Example #18
Source File: TestLockACLs.java    From xian with Apache License 2.0 5 votes vote down vote up
private CuratorFramework createClient(ACLProvider provider) throws Exception
{
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    CuratorFramework client = CuratorFrameworkFactory.builder()
        .namespace("ns")
        .connectString(server.getConnectString())
        .retryPolicy(retryPolicy)
        .aclProvider(provider)
        .build();
    client.start();
    return client;
}
 
Example #19
Source File: ZookeeperConfigActivator.java    From sofa-ark with Apache License 2.0 5 votes vote down vote up
/**
 * Get default AclProvider
 *
 * @return
 */
private ACLProvider getDefaultAclProvider() {
    return new ACLProvider() {
        @Override
        public List<ACL> getDefaultAcl() {
            return ZooDefs.Ids.CREATOR_ALL_ACL;
        }

        @Override
        public List<ACL> getAclForPath(String path) {
            return ZooDefs.Ids.CREATOR_ALL_ACL;
        }
    };
}
 
Example #20
Source File: CuratorFactoryTest.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAddAuthorization() {
    when(zookeeperProperties.hasAcl()).thenReturn(true);
    when(zookeeperProperties.getAcl()).thenReturn("sasl:[email protected]");
    when(zookeeperProperties.hasAuth()).thenReturn(true);
    when(zookeeperProperties.getAuth()).thenReturn("sasl:[email protected]");
    CuratorFactory curatorFactory = new CuratorFactory(configuration) {
        @Override
        protected void initializeCuratorFramework() {
        }
    };
    curatorFactory.enhanceBuilderWithSecurityParameters(zookeeperProperties, builder);
    verify(builder).aclProvider(any(ACLProvider.class));
    verify(builder).authorization(eq("sasl"), eq("[email protected]".getBytes(Charsets.UTF_8)));
}
 
Example #21
Source File: DelegationTokenKerberosFilter.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private ACLProvider createACLProvider(SolrZkClient zkClient) {
  final ZkACLProvider zkACLProvider = zkClient.getZkACLProvider();
  return new ACLProvider() {
    @Override
    public List<ACL> getDefaultAcl() {
      return zkACLProvider.getACLsToAdd(null);
    }

    @Override
    public List<ACL> getAclForPath(String path) {
      List<ACL> acls = null;

      // The logic in SecurityAwareZkACLProvider does not work when
      // the Solr zkPath is chrooted (e.g. /solr instead of /). This
      // due to the fact that the getACLsToAdd(..) callback provides
      // an absolute path (instead of relative path to the chroot) and
      // the string comparison in SecurityAwareZkACLProvider fails.
      if (zkACLProvider instanceof SecurityAwareZkACLProvider && zkChroot != null) {
        acls = zkACLProvider.getACLsToAdd(path.replace(zkChroot, ""));
      } else {
        acls = zkACLProvider.getACLsToAdd(path);
      }

      return acls;
    }
  };
}
 
Example #22
Source File: HadoopAuthFilter.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private ACLProvider createACLProvider(SolrZkClient zkClient) {
  final ZkACLProvider zkACLProvider = zkClient.getZkACLProvider();
  return new ACLProvider() {
    @Override
    public List<ACL> getDefaultAcl() {
      return zkACLProvider.getACLsToAdd(null);
    }

    @Override
    public List<ACL> getAclForPath(String path) {
      List<ACL> acls = null;

      // The logic in SecurityAwareZkACLProvider does not work when
      // the Solr zkPath is chrooted (e.g. /solr instead of /). This
      // due to the fact that the getACLsToAdd(..) callback provides
      // an absolute path (instead of relative path to the chroot) and
      // the string comparison in SecurityAwareZkACLProvider fails.
      if (zkACLProvider instanceof SecurityAwareZkACLProvider && zkChroot != null) {
        acls = zkACLProvider.getACLsToAdd(path.replace(zkChroot, ""));
      } else {
        acls = zkACLProvider.getACLsToAdd(path);
      }

      return acls;
    }
  };
}
 
Example #23
Source File: TestCuratorACLProviderFactory.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testSaslAuthSchemeNoHostNoRealm(){
    final NiFiProperties nifiProperties;
    final CuratorACLProviderFactory factory;
    otherProps.put("nifi.zookeeper.kerberos.removeHostFromPrincipal", "true");
    otherProps.put("nifi.zookeeper.kerberos.removeRealmFromPrincipal", "true");
    nifiProperties = NiFiProperties.createBasicNiFiProperties(propsFile, otherProps);
    factory = new CuratorACLProviderFactory();
    ZooKeeperClientConfig config = ZooKeeperClientConfig.createConfig(nifiProperties);
    ACLProvider provider = factory.create(config);
    assertFalse(provider instanceof DefaultACLProvider);
    List<ACL> acls = provider.getDefaultAcl();
    assertNotNull(acls);
    assertEquals(acls.get(0).getId().toString().trim(),"'sasl,'nifi");
}
 
Example #24
Source File: CuratorZookeeperCenterRepository.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
private CuratorFramework buildCuratorClient(final CenterConfiguration config, final ZookeeperProperties zookeeperProperties) {
    int retryIntervalMilliseconds = zookeeperProperties.getValue(ZookeeperPropertyKey.RETRY_INTERVAL_MILLISECONDS);
    int maxRetries = zookeeperProperties.getValue(ZookeeperPropertyKey.MAX_RETRIES);
    int timeToLiveSeconds = zookeeperProperties.getValue(ZookeeperPropertyKey.TIME_TO_LIVE_SECONDS);
    int operationTimeoutMilliseconds = zookeeperProperties.getValue(ZookeeperPropertyKey.OPERATION_TIMEOUT_MILLISECONDS);
    String digest = zookeeperProperties.getValue(ZookeeperPropertyKey.DIGEST);
    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
        .connectString(config.getServerLists())
        .retryPolicy(new ExponentialBackoffRetry(retryIntervalMilliseconds, maxRetries, retryIntervalMilliseconds * maxRetries))
        .namespace(config.getNamespace());
    if (0 != timeToLiveSeconds) {
        builder.sessionTimeoutMs(timeToLiveSeconds * 1000);
    }
    if (0 != operationTimeoutMilliseconds) {
        builder.connectionTimeoutMs(operationTimeoutMilliseconds);
    }
    if (!Strings.isNullOrEmpty(digest)) {
        builder.authorization("digest", digest.getBytes(Charsets.UTF_8))
            .aclProvider(new ACLProvider() {
                
                @Override
                public List<ACL> getDefaultAcl() {
                    return ZooDefs.Ids.CREATOR_ALL_ACL;
                }
                
                @Override
                public List<ACL> getAclForPath(final String path) {
                    return ZooDefs.Ids.CREATOR_ALL_ACL;
                }
            });
    }
    return builder.build();
}
 
Example #25
Source File: CuratorFactoryTest.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAddAuthorization() {
    when(zookeeperProperties.hasAcl()).thenReturn(true);
    when(zookeeperProperties.getAcl()).thenReturn("sasl:[email protected]");
    when(zookeeperProperties.hasAuth()).thenReturn(true);
    when(zookeeperProperties.getAuth()).thenReturn("sasl:[email protected]");
    CuratorFactory curatorFactory = new CuratorFactory(configuration) {
        @Override
        protected void initializeCuratorFramework() {
        }
    };
    curatorFactory.enhanceBuilderWithSecurityParameters(zookeeperProperties, builder);
    verify(builder).aclProvider(any(ACLProvider.class));
    verify(builder).authorization(eq("sasl"), eq("[email protected]".getBytes(Charsets.UTF_8)));
}
 
Example #26
Source File: ZooKeeperAclInitializer.java    From helios with Apache License 2.0 5 votes vote down vote up
static void initializeAcl(final String zooKeeperConnectionString,
                          final String zooKeeperClusterId,
                          final String masterUser,
                          final String masterPassword,
                          final String agentUser,
                          final String agentPassword)
    throws KeeperException {
  final ACLProvider aclProvider = heliosAclProvider(
      masterUser, digest(masterUser, masterPassword),
      agentUser, digest(agentUser, agentPassword));
  final List<AuthInfo> authorization = Lists.newArrayList(new AuthInfo(
      "digest", String.format("%s:%s", masterUser, masterPassword).getBytes()));

  final RetryPolicy zooKeeperRetryPolicy = new ExponentialBackoffRetry(1000, 3);
  final CuratorFramework curator = new CuratorClientFactoryImpl().newClient(
      zooKeeperConnectionString,
      (int) TimeUnit.SECONDS.toMillis(60),
      (int) TimeUnit.SECONDS.toMillis(15),
      zooKeeperRetryPolicy,
      aclProvider,
      authorization);

  final ZooKeeperClient client = new DefaultZooKeeperClient(curator, zooKeeperClusterId);
  try {
    client.start();
    initializeAclRecursive(client, "/", aclProvider);
  } finally {
    client.close();
  }
}
 
Example #27
Source File: MasterRespondsWithNoZkTest.java    From helios with Apache License 2.0 5 votes vote down vote up
@Override
public CuratorFramework newClient(final String connectString, final int sessionTimeoutMs,
                                  final int connectionTimeoutMs, final RetryPolicy retryPolicy,
                                  final ACLProvider aclProvider,
                                  final List<AuthInfo> authorization) {
  final CuratorFramework curator = mock(CuratorFramework.class);

  final RetryLoop retryLoop = mock(RetryLoop.class);
  when(retryLoop.shouldContinue()).thenReturn(false);

  final CuratorZookeeperClient czkClient = mock(CuratorZookeeperClient.class);
  when(czkClient.newRetryLoop()).thenReturn(retryLoop);

  when(curator.getZookeeperClient()).thenReturn(czkClient);

  @SuppressWarnings("unchecked") final Listenable<ConnectionStateListener> mockListener =
      (Listenable<ConnectionStateListener>) mock(Listenable.class);

  when(curator.getConnectionStateListenable()).thenReturn(mockListener);

  final GetChildrenBuilder builder = mock(GetChildrenBuilder.class);
  when(curator.getChildren()).thenReturn(builder);

  try {
    when(builder.forPath(anyString())).thenThrow(
        new KeeperException.ConnectionLossException());
  } catch (Exception ignored) {
    // never throws
  }
  when(curator.newNamespaceAwareEnsurePath(anyString())).thenReturn(mock(EnsurePath.class));

  return curator;
}
 
Example #28
Source File: TestLockACLs.java    From curator with Apache License 2.0 5 votes vote down vote up
private CuratorFramework createClient(ACLProvider provider) throws Exception
{
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    CuratorFramework client = CuratorFrameworkFactory.builder()
        .namespace("ns")
        .connectString(server.getConnectString())
        .retryPolicy(retryPolicy)
        .aclProvider(provider)
        .build();
    client.start();
    return client;
}
 
Example #29
Source File: TestExistsBuilder.java    From curator with Apache License 2.0 5 votes vote down vote up
private CuratorFramework createClient(ACLProvider aclProvider)
{
    return CuratorFrameworkFactory.builder().
            aclProvider(aclProvider).
            connectString(server.getConnectString()).
            retryPolicy(new RetryOneTime(1)).
            build();
}
 
Example #30
Source File: TestCreate.java    From curator with Apache License 2.0 5 votes vote down vote up
private CuratorFramework createClient(ACLProvider aclProvider)
{
    return CuratorFrameworkFactory.builder().
        aclProvider(aclProvider).
        connectString(server.getConnectString()).
        retryPolicy(new RetryOneTime(1)).
        build();
}