You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@nifi.apache.org by GitBox <gi...@apache.org> on 2019/04/16 05:57:01 UTC

[GitHub] [nifi] SandishKumarHN commented on a change in pull request #3387: NIFI-6009 ScanKudu Processor & KuduPut Processor Delete Operation

SandishKumarHN commented on a change in pull request #3387: NIFI-6009 ScanKudu Processor & KuduPut Processor Delete Operation
URL: https://github.com/apache/nifi/pull/3387#discussion_r275638331
 
 

 ##########
 File path: nifi-nar-bundles/nifi-kudu-bundle/nifi-kudu-client-services/src/main/java/org/apache/nifi/kudu/KuduControllerService.java
 ##########
 @@ -0,0 +1,344 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.kudu;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.apache.kudu.ColumnSchema;
+import org.apache.kudu.Schema;
+import org.apache.kudu.Type;
+import org.apache.kudu.client.AsyncKuduClient;
+import org.apache.kudu.client.AsyncKuduScanner;
+import org.apache.kudu.client.KuduClient;
+import org.apache.kudu.client.KuduTable;
+import org.apache.kudu.client.KuduSession;
+import org.apache.kudu.client.KuduPredicate;
+import org.apache.kudu.client.KuduException;
+import org.apache.kudu.client.OperationResponse;
+import org.apache.kudu.client.PartialRow;
+import org.apache.kudu.client.RowError;
+import org.apache.kudu.client.SessionConfiguration;
+import org.apache.nifi.annotation.documentation.CapabilityDescription;
+import org.apache.nifi.annotation.documentation.Tags;
+import org.apache.nifi.annotation.lifecycle.OnDisabled;
+import org.apache.nifi.kerberos.KerberosCredentialsService;
+import org.apache.nifi.annotation.lifecycle.OnEnabled;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.components.PropertyDescriptor.Builder;
+import org.apache.nifi.controller.AbstractControllerService;
+import org.apache.nifi.controller.ConfigurationContext;
+import org.apache.nifi.controller.ControllerServiceInitializationContext;
+import org.apache.nifi.expression.ExpressionLanguageScope;
+import org.apache.nifi.kudu.scan.ResultHandler;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.util.StandardValidators;
+import org.apache.nifi.security.krb.KerberosAction;
+import org.apache.nifi.security.krb.KerberosKeytabUser;
+import org.apache.nifi.security.krb.KerberosUser;
+import org.apache.nifi.serialization.record.Record;
+
+import javax.security.auth.login.LoginException;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Collections;
+
+@Tags({"kudu", "service"})
+@CapabilityDescription("Provides a controller service that configures a connection to Kudu and provides access to that connection to " + "other Kudu-related components.")
+public class KuduControllerService extends AbstractControllerService implements KuduClientService {
+
+    static final PropertyDescriptor KUDU_MASTERS = new Builder()
+            .name("Kudu Masters")
+            .description("List all kudu masters's ip with port (e.g. 7051), comma separated")
+            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+            .expressionLanguageSupported(ExpressionLanguageScope.VARIABLE_REGISTRY)
+            .build();
+
+    static final PropertyDescriptor KERBEROS_CREDENTIALS_SERVICE = new Builder()
+            .name("kerberos-credentials-service")
+            .displayName("Kerberos Credentials Service")
+            .description("Specifies the Kerberos Credentials to use for authentication")
+            .required(false)
+            .identifiesControllerService(KerberosCredentialsService.class)
+            .build();
+
+    static final PropertyDescriptor KUDU_OPERATION_TIMEOUTMS = new Builder()
+            .name("kudu-operations-timeoutms")
+            .displayName("Kudu Operation Timeout in MS")
+            .description("Default timeout used for user operations (using sessions and scanners)")
+            .required(false)
+            .defaultValue("30")
+            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+            .expressionLanguageSupported(ExpressionLanguageScope.VARIABLE_REGISTRY)
+            .build();
+
+    static final PropertyDescriptor KUDU_ADMIN_OPERATION_TIMEOUTMS = new Builder()
+            .name("kudu-admin-operation-timeout")
+            .displayName("Kudu Admin Operation Timeout in MS")
+            .description("Default timeout used for user operations")
+            .required(false)
+            .defaultValue("30")
+            .addValidator(StandardValidators.POSITIVE_INTEGER_VALIDATOR)
+            .expressionLanguageSupported(ExpressionLanguageScope.VARIABLE_REGISTRY)
+            .build();
+
+
+    private List<PropertyDescriptor> properties;
+
+    @Override
+    protected void init(ControllerServiceInitializationContext config) {
+        List<PropertyDescriptor> props = new ArrayList<>();
+        props.add(KUDU_MASTERS);
+        props.add(KERBEROS_CREDENTIALS_SERVICE);
+        props.add(KUDU_OPERATION_TIMEOUTMS);
+        props.add(KUDU_ADMIN_OPERATION_TIMEOUTMS);
+        this.properties = Collections.unmodifiableList(props);
+    }
+
+    @Override
+    protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
+        return properties;
+    }
+
+    protected KuduClient kuduClient;
+
+    protected AsyncKuduClient asyncKuduClient;
+
+    private volatile KerberosUser kerberosUser;
+
+    @Override
+    public KerberosUser getKerberosUser() {
+        return this.kerberosUser;
+    }
+
+    @Override
+    public KuduClient getKuduClient() {
+        return this.kuduClient;
+    }
+
+    @Override
+    public AsyncKuduClient getAsyncKuduClient() {
+        return this.asyncKuduClient;
+    }
+
+    @OnEnabled
+    public void onEnabled(final ConfigurationContext context) throws LoginException {
+        this.asyncKuduClient = createAsyncKuduClient(context);
+        this.kuduClient = this.asyncKuduClient.syncClient();
+
+        if(this.kuduClient != null) {
+            try {
+                this.kuduClient.getTablesList();
+            } catch (KuduException e) {
+                e.printStackTrace();
+            }
+        }
+    }
+
+    public AsyncKuduClient createAsyncKuduClient(ConfigurationContext context) throws
+            LoginException {
+        final String kuduMasters = context.getProperty(KUDU_MASTERS).evaluateAttributeExpressions().getValue();
+        final KerberosCredentialsService credentialsService = context.getProperty(KERBEROS_CREDENTIALS_SERVICE).asControllerService(KerberosCredentialsService.class);
+
+        if (credentialsService == null) {
+            return buildClient(kuduMasters, context);
+        }
+
+        final String keytab = credentialsService.getKeytab();
+        final String principal = credentialsService.getPrincipal();
+        kerberosUser = loginKerberosUser(principal, keytab);
+
+        final KerberosAction<AsyncKuduClient> kerberosAction = new KerberosAction<>(kerberosUser, () -> buildClient(kuduMasters, context), getLogger());
+        return kerberosAction.execute();
+    }
+
+    protected AsyncKuduClient buildClient(final String masters, final ConfigurationContext context) {
+        final String operationTimeout = context.getProperty(KUDU_OPERATION_TIMEOUTMS).evaluateAttributeExpressions().getValue();
+        final String adminOperationTimeout = context.getProperty(KUDU_ADMIN_OPERATION_TIMEOUTMS).evaluateAttributeExpressions().getValue();
+
+        return new AsyncKuduClient.AsyncKuduClientBuilder(masters)
+                .defaultOperationTimeoutMs(Integer.parseInt(operationTimeout))
+                .defaultAdminOperationTimeoutMs(Integer.parseInt(adminOperationTimeout))
+                .build();
+    }
+
+    public void flushKuduSession(final KuduSession kuduSession, boolean close, final List<RowError> rowErrors) throws KuduException {
+        final List<OperationResponse> responses = close ? kuduSession.close() : kuduSession.flush();
+
+        if (kuduSession.getFlushMode() == SessionConfiguration.FlushMode.AUTO_FLUSH_BACKGROUND) {
+            rowErrors.addAll(Arrays.asList(kuduSession.getPendingErrors().getRowErrors()));
+        } else {
+            responses.stream()
+                    .filter(OperationResponse::hasRowError)
+                    .map(OperationResponse::getRowError)
+                    .forEach(rowErrors::add);
+        }
+    }
+
+    protected KerberosUser loginKerberosUser(final String principal, final String keytab) throws LoginException {
+        final KerberosUser kerberosUser = new KerberosKeytabUser(principal, keytab);
+        kerberosUser.login();
+        return kerberosUser;
+    }
+
+    public final void closeClient() throws Exception {
+        try {
+            if (this.asyncKuduClient != null) {
+                getLogger().debug("Closing KuduClient");
+                this.asyncKuduClient .close();
+                this.asyncKuduClient  = null;
+            }
+        } finally {
+            if (kerberosUser != null) {
+                kerberosUser.logout();
+                kerberosUser = null;
+            }
+        }
+    }
+
+    @OnDisabled
+    public void shutdown() throws Exception {
+       this.closeClient();
+    }
+
+    public void scan(ProcessContext context, ProcessSession session, KuduTable kuduTable, String predicates, List<String> projectedColumnNames, ResultHandler handler) throws Exception {
+        AsyncKuduScanner.AsyncKuduScannerBuilder scannerBuilder = this.asyncKuduClient.newScannerBuilder(kuduTable);
+        final String[] arrayPredicates = (predicates == null || predicates.isEmpty() ? new String[0] : predicates.split(","));
+
+        for(String column : arrayPredicates){
+            if (column.contains(":")) {
+                final String[] parts = column.split(":");
+                addPredicate(scannerBuilder, kuduTable, parts[0], parts[1]);
+            }
+        }
+
+        if(!projectedColumnNames.isEmpty()){
+            scannerBuilder.setProjectedColumnNames(projectedColumnNames);
+        }
+
+        AsyncKuduScanner scanner = scannerBuilder.build();
+        while (scanner.hasMoreRows()) {
+            handler.handle(scanner.nextRows().join());
+        }
+    }
+
+    @VisibleForTesting
+    public void buildPartialRow(Schema schema, PartialRow row, Record record, List<String> fieldNames) {
+        for (String colName : fieldNames) {
+            int colIdx = this.getColumnIndex(schema, colName);
+            if (colIdx != -1) {
+                ColumnSchema colSchema = schema.getColumnByIndex(colIdx);
+                Type colType = colSchema.getType();
+
+                if (record.getValue(colName) == null) {
+                    row.setNull(colName);
+                    continue;
+                }
+
+                switch (colType.getDataType(colSchema.getTypeAttributes())) {
+                    case BOOL:
+                        row.addBoolean(colIdx, record.getAsBoolean(colName));
+                        break;
+                    case FLOAT:
+                        row.addFloat(colIdx, record.getAsFloat(colName));
+                        break;
+                    case DOUBLE:
+                        row.addDouble(colIdx, record.getAsDouble(colName));
+                        break;
+                    case BINARY:
+                        row.addBinary(colIdx, record.getAsString(colName).getBytes());
+                        break;
+                    case INT8:
+                        row.addByte(colIdx, record.getAsInt(colName).byteValue());
+                        break;
+                    case INT16:
+                        row.addShort(colIdx, record.getAsInt(colName).shortValue());
+                        break;
+                    case INT32:
+                        row.addInt(colIdx, record.getAsInt(colName));
+                        break;
+                    case INT64:
+                    case UNIXTIME_MICROS:
+                        row.addLong(colIdx, record.getAsLong(colName));
+                        break;
+                    case STRING:
+                        row.addString(colIdx, record.getAsString(colName));
+                        break;
+                    case DECIMAL32:
+                    case DECIMAL64:
+                    case DECIMAL128:
+                        row.addDecimal(colIdx, new BigDecimal(record.getAsString(colName)));
+                        break;
+                    default:
+                        throw new IllegalStateException(String.format("unknown column type %s", colType));
+                }
+            }
+        }
+    }
+
+    protected void addPredicate(AsyncKuduScanner.AsyncKuduScannerBuilder scannerBuilder, KuduTable kuduTable, String column, String value) {
 
 Review comment:
   For now, I kept it only Equals predicates, I will create separate JIRA for adding more predicted support, right now I'm not sure about NIFI expressions supported for other predicates. 

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services