turcsanyip commented on code in PR #6200: URL: https://github.com/apache/nifi/pull/6200#discussion_r923026765
########## nifi-nar-bundles/nifi-gcp-bundle/nifi-gcp-processors/src/main/java/org/apache/nifi/processors/gcp/drive/ListGoogleDrive.java: ########## @@ -0,0 +1,351 @@ +/* + * 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.processors.gcp.drive; + +import com.google.api.client.http.HttpTransport; +import com.google.api.client.json.JsonFactory; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.drive.Drive; +import com.google.api.services.drive.DriveScopes; +import com.google.api.services.drive.model.File; +import com.google.api.services.drive.model.FileList; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import org.apache.nifi.annotation.behavior.InputRequirement; +import org.apache.nifi.annotation.behavior.InputRequirement.Requirement; +import org.apache.nifi.annotation.behavior.PrimaryNodeOnly; +import org.apache.nifi.annotation.behavior.Stateful; +import org.apache.nifi.annotation.behavior.TriggerSerially; +import org.apache.nifi.annotation.behavior.WritesAttribute; +import org.apache.nifi.annotation.behavior.WritesAttributes; +import org.apache.nifi.annotation.documentation.CapabilityDescription; +import org.apache.nifi.annotation.documentation.Tags; +import org.apache.nifi.annotation.lifecycle.OnScheduled; +import org.apache.nifi.components.PropertyDescriptor; +import org.apache.nifi.components.ValidationContext; +import org.apache.nifi.components.ValidationResult; +import org.apache.nifi.components.state.Scope; +import org.apache.nifi.context.PropertyContext; +import org.apache.nifi.expression.ExpressionLanguageScope; +import org.apache.nifi.gcp.credentials.service.GCPCredentialsService; +import org.apache.nifi.processor.ProcessContext; +import org.apache.nifi.processor.util.StandardValidators; +import org.apache.nifi.processor.util.list.AbstractListProcessor; +import org.apache.nifi.processor.util.list.ListedEntityTracker; +import org.apache.nifi.processors.gcp.ProxyAwareTransportFactory; +import org.apache.nifi.processors.gcp.util.GoogleUtils; +import org.apache.nifi.proxy.ProxyConfiguration; +import org.apache.nifi.serialization.record.RecordSchema; + +import java.io.IOException; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +@PrimaryNodeOnly +@TriggerSerially +@Tags({"google", "drive", "storage"}) +@CapabilityDescription("Lists files in a Google Drive folder. Listing details are attached to an empty FlowFile for use with FetchGoogleDrive. " + + "This Processor is designed to run on Primary Node only in a cluster. If the primary node changes, the new Primary Node will pick up where the " + + "previous node left off without duplicating all of the data.") +@InputRequirement(Requirement.INPUT_FORBIDDEN) +@WritesAttributes({@WritesAttribute(attribute = "drive.id", description = "The id of the file"), + @WritesAttribute(attribute = "filename", description = "The name of the file"), + @WritesAttribute(attribute = "drive.size", description = "The size of the file"), + @WritesAttribute(attribute = "drive.timestamp", description = "The last modified time or created time (whichever is greater) of the file"), Review Comment: The user can set the file's timestamp to a date in the future locally. I would consider to use the created date only which is assigned by Google Drive and seems to be consistent. ########## nifi-nar-bundles/nifi-gcp-bundle/nifi-gcp-processors/src/main/java/org/apache/nifi/processors/gcp/drive/ListGoogleDrive.java: ########## @@ -0,0 +1,351 @@ +/* + * 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.processors.gcp.drive; + +import com.google.api.client.http.HttpTransport; +import com.google.api.client.json.JsonFactory; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.drive.Drive; +import com.google.api.services.drive.DriveScopes; +import com.google.api.services.drive.model.File; +import com.google.api.services.drive.model.FileList; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import org.apache.nifi.annotation.behavior.InputRequirement; +import org.apache.nifi.annotation.behavior.InputRequirement.Requirement; +import org.apache.nifi.annotation.behavior.PrimaryNodeOnly; +import org.apache.nifi.annotation.behavior.Stateful; +import org.apache.nifi.annotation.behavior.TriggerSerially; +import org.apache.nifi.annotation.behavior.WritesAttribute; +import org.apache.nifi.annotation.behavior.WritesAttributes; +import org.apache.nifi.annotation.documentation.CapabilityDescription; +import org.apache.nifi.annotation.documentation.Tags; +import org.apache.nifi.annotation.lifecycle.OnScheduled; +import org.apache.nifi.components.PropertyDescriptor; +import org.apache.nifi.components.ValidationContext; +import org.apache.nifi.components.ValidationResult; +import org.apache.nifi.components.state.Scope; +import org.apache.nifi.context.PropertyContext; +import org.apache.nifi.expression.ExpressionLanguageScope; +import org.apache.nifi.gcp.credentials.service.GCPCredentialsService; +import org.apache.nifi.processor.ProcessContext; +import org.apache.nifi.processor.util.StandardValidators; +import org.apache.nifi.processor.util.list.AbstractListProcessor; +import org.apache.nifi.processor.util.list.ListedEntityTracker; +import org.apache.nifi.processors.gcp.ProxyAwareTransportFactory; +import org.apache.nifi.processors.gcp.util.GoogleUtils; +import org.apache.nifi.proxy.ProxyConfiguration; +import org.apache.nifi.serialization.record.RecordSchema; + +import java.io.IOException; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +@PrimaryNodeOnly +@TriggerSerially +@Tags({"google", "drive", "storage"}) +@CapabilityDescription("Lists files in a Google Drive folder. Listing details are attached to an empty FlowFile for use with FetchGoogleDrive. " + Review Comment: There is also another type of usage: use the Record Writer property and add the listing as a json in the FlowFile content. It could be mentioned in the documentation. ########## nifi-nar-bundles/nifi-gcp-bundle/nifi-gcp-processors/src/main/java/org/apache/nifi/processors/gcp/drive/ListGoogleDrive.java: ########## @@ -0,0 +1,351 @@ +/* + * 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.processors.gcp.drive; + +import com.google.api.client.http.HttpTransport; +import com.google.api.client.json.JsonFactory; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.drive.Drive; +import com.google.api.services.drive.DriveScopes; +import com.google.api.services.drive.model.File; +import com.google.api.services.drive.model.FileList; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import org.apache.nifi.annotation.behavior.InputRequirement; +import org.apache.nifi.annotation.behavior.InputRequirement.Requirement; +import org.apache.nifi.annotation.behavior.PrimaryNodeOnly; +import org.apache.nifi.annotation.behavior.Stateful; +import org.apache.nifi.annotation.behavior.TriggerSerially; +import org.apache.nifi.annotation.behavior.WritesAttribute; +import org.apache.nifi.annotation.behavior.WritesAttributes; +import org.apache.nifi.annotation.documentation.CapabilityDescription; +import org.apache.nifi.annotation.documentation.Tags; +import org.apache.nifi.annotation.lifecycle.OnScheduled; +import org.apache.nifi.components.PropertyDescriptor; +import org.apache.nifi.components.ValidationContext; +import org.apache.nifi.components.ValidationResult; +import org.apache.nifi.components.state.Scope; +import org.apache.nifi.context.PropertyContext; +import org.apache.nifi.expression.ExpressionLanguageScope; +import org.apache.nifi.gcp.credentials.service.GCPCredentialsService; +import org.apache.nifi.processor.ProcessContext; +import org.apache.nifi.processor.util.StandardValidators; +import org.apache.nifi.processor.util.list.AbstractListProcessor; +import org.apache.nifi.processor.util.list.ListedEntityTracker; +import org.apache.nifi.processors.gcp.ProxyAwareTransportFactory; +import org.apache.nifi.processors.gcp.util.GoogleUtils; +import org.apache.nifi.proxy.ProxyConfiguration; +import org.apache.nifi.serialization.record.RecordSchema; + +import java.io.IOException; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +@PrimaryNodeOnly +@TriggerSerially +@Tags({"google", "drive", "storage"}) +@CapabilityDescription("Lists files in a Google Drive folder. Listing details are attached to an empty FlowFile for use with FetchGoogleDrive. " + + "This Processor is designed to run on Primary Node only in a cluster. If the primary node changes, the new Primary Node will pick up where the " + + "previous node left off without duplicating all of the data.") +@InputRequirement(Requirement.INPUT_FORBIDDEN) +@WritesAttributes({@WritesAttribute(attribute = "drive.id", description = "The id of the file"), + @WritesAttribute(attribute = "filename", description = "The name of the file"), + @WritesAttribute(attribute = "drive.size", description = "The size of the file"), + @WritesAttribute(attribute = "drive.timestamp", description = "The last modified time or created time (whichever is greater) of the file"), + @WritesAttribute(attribute = "mime.type", description = "MimeType of the file")}) +@Stateful(scopes = {Scope.CLUSTER}, description = "After performing a listing of files, the timestamp of the newest file is stored. " + Review Comment: Storing the timestamp is only applicable to the Timestamp Tracking strategy. It could be highlighted in the documentation. ########## nifi-nar-bundles/nifi-gcp-bundle/nifi-gcp-processors/src/main/java/org/apache/nifi/processors/gcp/drive/ListGoogleDrive.java: ########## @@ -0,0 +1,351 @@ +/* + * 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.processors.gcp.drive; + +import com.google.api.client.http.HttpTransport; +import com.google.api.client.json.JsonFactory; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.drive.Drive; +import com.google.api.services.drive.DriveScopes; +import com.google.api.services.drive.model.File; +import com.google.api.services.drive.model.FileList; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import org.apache.nifi.annotation.behavior.InputRequirement; +import org.apache.nifi.annotation.behavior.InputRequirement.Requirement; +import org.apache.nifi.annotation.behavior.PrimaryNodeOnly; +import org.apache.nifi.annotation.behavior.Stateful; +import org.apache.nifi.annotation.behavior.TriggerSerially; +import org.apache.nifi.annotation.behavior.WritesAttribute; +import org.apache.nifi.annotation.behavior.WritesAttributes; +import org.apache.nifi.annotation.documentation.CapabilityDescription; +import org.apache.nifi.annotation.documentation.Tags; +import org.apache.nifi.annotation.lifecycle.OnScheduled; +import org.apache.nifi.components.PropertyDescriptor; +import org.apache.nifi.components.ValidationContext; +import org.apache.nifi.components.ValidationResult; +import org.apache.nifi.components.state.Scope; +import org.apache.nifi.context.PropertyContext; +import org.apache.nifi.expression.ExpressionLanguageScope; +import org.apache.nifi.gcp.credentials.service.GCPCredentialsService; +import org.apache.nifi.processor.ProcessContext; +import org.apache.nifi.processor.util.StandardValidators; +import org.apache.nifi.processor.util.list.AbstractListProcessor; +import org.apache.nifi.processor.util.list.ListedEntityTracker; +import org.apache.nifi.processors.gcp.ProxyAwareTransportFactory; +import org.apache.nifi.processors.gcp.util.GoogleUtils; +import org.apache.nifi.proxy.ProxyConfiguration; +import org.apache.nifi.serialization.record.RecordSchema; + +import java.io.IOException; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +@PrimaryNodeOnly +@TriggerSerially +@Tags({"google", "drive", "storage"}) +@CapabilityDescription("Lists files in a Google Drive folder. Listing details are attached to an empty FlowFile for use with FetchGoogleDrive. " + + "This Processor is designed to run on Primary Node only in a cluster. If the primary node changes, the new Primary Node will pick up where the " + + "previous node left off without duplicating all of the data.") +@InputRequirement(Requirement.INPUT_FORBIDDEN) +@WritesAttributes({@WritesAttribute(attribute = "drive.id", description = "The id of the file"), + @WritesAttribute(attribute = "filename", description = "The name of the file"), + @WritesAttribute(attribute = "drive.size", description = "The size of the file"), + @WritesAttribute(attribute = "drive.timestamp", description = "The last modified time or created time (whichever is greater) of the file"), + @WritesAttribute(attribute = "mime.type", description = "MimeType of the file")}) +@Stateful(scopes = {Scope.CLUSTER}, description = "After performing a listing of files, the timestamp of the newest file is stored. " + + "This allows the Processor to list only files that have been added or modified after this date the next time that the Processor is run. State is " + + "stored across the cluster so that this Processor can be run on Primary Node only and if a new Primary Node is selected, the new node can pick up " + + "where the previous node left off, without duplicating the data.") +public class ListGoogleDrive extends AbstractListProcessor<GoogleDriveFileInfo> { + private static final String APPLICATION_NAME = "NiFi"; + private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); + + private volatile HttpTransport httpTransport; + + public static final PropertyDescriptor FOLDER_ID = new PropertyDescriptor.Builder() + .name("folder-id") + .displayName("Folder ID") + .description("The ID of the folder from which to pull list of files. Needs to be shared with a Service Account.") + .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) + .expressionLanguageSupported(ExpressionLanguageScope.VARIABLE_REGISTRY) + .required(true) + .build(); + + public static final PropertyDescriptor RECURSIVE_SEARCH = new PropertyDescriptor.Builder() + .name("recursive-search") + .displayName("Search Recursively") + .description("When 'true', will include list of files from sub-folders. Otherwise, will return only files that have the defined 'Folder ID' as their parent directly.") + .required(true) + .defaultValue("true") + .allowableValues("true", "false") + .build(); + + public static final PropertyDescriptor MIN_AGE = new PropertyDescriptor.Builder() + .name("min-age") + .displayName("Minimum File Age") + .description("The minimum age a file must be in order to be considered; any files younger than this will be ignored") + .required(true) + .addValidator(StandardValidators.TIME_PERIOD_VALIDATOR) + .defaultValue("0 sec") + .build(); + + public static final PropertyDescriptor TRACKING_STATE_CACHE = new PropertyDescriptor.Builder() + .fromPropertyDescriptor(ListedEntityTracker.TRACKING_STATE_CACHE) + .dependsOn(LISTING_STRATEGY, BY_ENTITIES) + .build(); + + public static final PropertyDescriptor TRACKING_TIME_WINDOW = new PropertyDescriptor.Builder() + .fromPropertyDescriptor(ListedEntityTracker.TRACKING_TIME_WINDOW) + .dependsOn(LISTING_STRATEGY, BY_ENTITIES) + .build(); + + public static final PropertyDescriptor INITIAL_LISTING_TARGET = new PropertyDescriptor.Builder() + .fromPropertyDescriptor(ListedEntityTracker.INITIAL_LISTING_TARGET) + .dependsOn(LISTING_STRATEGY, BY_ENTITIES) + .build(); + + private static final List<PropertyDescriptor> PROPERTIES = Collections.unmodifiableList(Arrays.asList( + GoogleUtils.GCP_CREDENTIALS_PROVIDER_SERVICE, + FOLDER_ID, + RECURSIVE_SEARCH, + MIN_AGE, + LISTING_STRATEGY, + RECORD_WRITER, + TRACKING_STATE_CACHE, + TRACKING_TIME_WINDOW, + INITIAL_LISTING_TARGET, + ProxyConfiguration.createProxyConfigPropertyDescriptor(false, ProxyAwareTransportFactory.PROXY_SPECS) + )); + + @Override + protected List<PropertyDescriptor> getSupportedPropertyDescriptors() { + return PROPERTIES; + } + + @Override + protected void customValidate(ValidationContext validationContext, Collection<ValidationResult> results) { + } + + @Override + protected Map<String, String> createAttributes( + final GoogleDriveFileInfo entity, + final ProcessContext context + ) { + final Map<String, String> attributes = new HashMap<>(); + attributes.put("drive.id", entity.getId()); + attributes.put("filename", entity.getName()); + attributes.put("drive.size", String.valueOf(entity.getSize())); + attributes.put("drive.timestamp", String.valueOf(entity.getTimestamp())); + attributes.put("mime.type", entity.getMimeType()); + + return attributes; + } + + @OnScheduled + public void onScheduled(final ProcessContext context) throws IOException { + final ProxyConfiguration proxyConfiguration = ProxyConfiguration.getConfiguration(context); + httpTransport = new ProxyAwareTransportFactory(proxyConfiguration).create(); + } + + @Override + protected String getListingContainerName(final ProcessContext context) { + return String.format("Google Drive Folder [%s]", getPath(context)); + } + + @Override + protected String getPath(final ProcessContext context) { + return context.getProperty(FOLDER_ID).evaluateAttributeExpressions().getValue(); + } + + @Override + protected boolean isListingResetNecessary(final PropertyDescriptor property) { + return LISTING_STRATEGY.equals(property) + || FOLDER_ID.equals(property) + || RECURSIVE_SEARCH.equals(property); + } + + @Override + protected Scope getStateScope(final PropertyContext context) { + return Scope.CLUSTER; + } + + @Override + protected RecordSchema getRecordSchema() { + return GoogleDriveFileInfo.getRecordSchema(); + } + + @Override + protected String getDefaultTimePrecision() { + return PRECISION_SECONDS.getValue(); + } + + @Override + protected List<GoogleDriveFileInfo> performListing( + final ProcessContext context, + final Long minTimestamp, + final ListingMode listingMode + ) throws IOException { + final List<GoogleDriveFileInfo> listing = new ArrayList<>(); + + final String folderId = context.getProperty(FOLDER_ID).evaluateAttributeExpressions().getValue(); + final Boolean recursive = context.getProperty(RECURSIVE_SEARCH).asBoolean(); + final Long minAge = context.getProperty(MIN_AGE).asTimePeriod(TimeUnit.MILLISECONDS); + + Drive driveService = new Drive.Builder( + this.httpTransport, + JSON_FACTORY, + getHttpCredentialsAdapter( + context, + Arrays.asList(DriveScopes.DRIVE_METADATA_READONLY) + ) + ) + .setApplicationName(APPLICATION_NAME) + .build(); + + StringBuilder queryBuilder = new StringBuilder(); + queryBuilder.append(buildQueryForDirs(driveService, folderId, recursive)); + queryBuilder.append(" and (mimeType != 'application/vnd.google-apps.folder')"); + queryBuilder.append(" and (mimeType != 'application/vnd.google-apps.shortcut')"); Review Comment: Please document it for the user that shortcuts will not be followed. ########## nifi-nar-bundles/nifi-gcp-bundle/nifi-gcp-processors/src/main/java/org/apache/nifi/processors/gcp/drive/ListGoogleDrive.java: ########## @@ -0,0 +1,351 @@ +/* + * 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.processors.gcp.drive; + +import com.google.api.client.http.HttpTransport; +import com.google.api.client.json.JsonFactory; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.drive.Drive; +import com.google.api.services.drive.DriveScopes; +import com.google.api.services.drive.model.File; +import com.google.api.services.drive.model.FileList; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import org.apache.nifi.annotation.behavior.InputRequirement; +import org.apache.nifi.annotation.behavior.InputRequirement.Requirement; +import org.apache.nifi.annotation.behavior.PrimaryNodeOnly; +import org.apache.nifi.annotation.behavior.Stateful; +import org.apache.nifi.annotation.behavior.TriggerSerially; +import org.apache.nifi.annotation.behavior.WritesAttribute; +import org.apache.nifi.annotation.behavior.WritesAttributes; +import org.apache.nifi.annotation.documentation.CapabilityDescription; +import org.apache.nifi.annotation.documentation.Tags; +import org.apache.nifi.annotation.lifecycle.OnScheduled; +import org.apache.nifi.components.PropertyDescriptor; +import org.apache.nifi.components.ValidationContext; +import org.apache.nifi.components.ValidationResult; +import org.apache.nifi.components.state.Scope; +import org.apache.nifi.context.PropertyContext; +import org.apache.nifi.expression.ExpressionLanguageScope; +import org.apache.nifi.gcp.credentials.service.GCPCredentialsService; +import org.apache.nifi.processor.ProcessContext; +import org.apache.nifi.processor.util.StandardValidators; +import org.apache.nifi.processor.util.list.AbstractListProcessor; +import org.apache.nifi.processor.util.list.ListedEntityTracker; +import org.apache.nifi.processors.gcp.ProxyAwareTransportFactory; +import org.apache.nifi.processors.gcp.util.GoogleUtils; +import org.apache.nifi.proxy.ProxyConfiguration; +import org.apache.nifi.serialization.record.RecordSchema; + +import java.io.IOException; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +@PrimaryNodeOnly +@TriggerSerially +@Tags({"google", "drive", "storage"}) +@CapabilityDescription("Lists files in a Google Drive folder. Listing details are attached to an empty FlowFile for use with FetchGoogleDrive. " + + "This Processor is designed to run on Primary Node only in a cluster. If the primary node changes, the new Primary Node will pick up where the " + + "previous node left off without duplicating all of the data.") +@InputRequirement(Requirement.INPUT_FORBIDDEN) +@WritesAttributes({@WritesAttribute(attribute = "drive.id", description = "The id of the file"), + @WritesAttribute(attribute = "filename", description = "The name of the file"), + @WritesAttribute(attribute = "drive.size", description = "The size of the file"), + @WritesAttribute(attribute = "drive.timestamp", description = "The last modified time or created time (whichever is greater) of the file"), + @WritesAttribute(attribute = "mime.type", description = "MimeType of the file")}) +@Stateful(scopes = {Scope.CLUSTER}, description = "After performing a listing of files, the timestamp of the newest file is stored. " + + "This allows the Processor to list only files that have been added or modified after this date the next time that the Processor is run. State is " + + "stored across the cluster so that this Processor can be run on Primary Node only and if a new Primary Node is selected, the new node can pick up " + + "where the previous node left off, without duplicating the data.") +public class ListGoogleDrive extends AbstractListProcessor<GoogleDriveFileInfo> { + private static final String APPLICATION_NAME = "NiFi"; + private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); + + private volatile HttpTransport httpTransport; + + public static final PropertyDescriptor FOLDER_ID = new PropertyDescriptor.Builder() + .name("folder-id") + .displayName("Folder ID") + .description("The ID of the folder from which to pull list of files. Needs to be shared with a Service Account.") + .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) + .expressionLanguageSupported(ExpressionLanguageScope.VARIABLE_REGISTRY) + .required(true) + .build(); + + public static final PropertyDescriptor RECURSIVE_SEARCH = new PropertyDescriptor.Builder() + .name("recursive-search") + .displayName("Search Recursively") + .description("When 'true', will include list of files from sub-folders. Otherwise, will return only files that have the defined 'Folder ID' as their parent directly.") + .required(true) + .defaultValue("true") + .allowableValues("true", "false") + .build(); + + public static final PropertyDescriptor MIN_AGE = new PropertyDescriptor.Builder() + .name("min-age") + .displayName("Minimum File Age") + .description("The minimum age a file must be in order to be considered; any files younger than this will be ignored") + .required(true) + .addValidator(StandardValidators.TIME_PERIOD_VALIDATOR) + .defaultValue("0 sec") + .build(); + + public static final PropertyDescriptor TRACKING_STATE_CACHE = new PropertyDescriptor.Builder() + .fromPropertyDescriptor(ListedEntityTracker.TRACKING_STATE_CACHE) + .dependsOn(LISTING_STRATEGY, BY_ENTITIES) + .build(); + + public static final PropertyDescriptor TRACKING_TIME_WINDOW = new PropertyDescriptor.Builder() + .fromPropertyDescriptor(ListedEntityTracker.TRACKING_TIME_WINDOW) + .dependsOn(LISTING_STRATEGY, BY_ENTITIES) + .build(); + + public static final PropertyDescriptor INITIAL_LISTING_TARGET = new PropertyDescriptor.Builder() + .fromPropertyDescriptor(ListedEntityTracker.INITIAL_LISTING_TARGET) + .dependsOn(LISTING_STRATEGY, BY_ENTITIES) + .build(); + + private static final List<PropertyDescriptor> PROPERTIES = Collections.unmodifiableList(Arrays.asList( + GoogleUtils.GCP_CREDENTIALS_PROVIDER_SERVICE, + FOLDER_ID, + RECURSIVE_SEARCH, + MIN_AGE, + LISTING_STRATEGY, + RECORD_WRITER, + TRACKING_STATE_CACHE, + TRACKING_TIME_WINDOW, + INITIAL_LISTING_TARGET, + ProxyConfiguration.createProxyConfigPropertyDescriptor(false, ProxyAwareTransportFactory.PROXY_SPECS) + )); + + @Override + protected List<PropertyDescriptor> getSupportedPropertyDescriptors() { + return PROPERTIES; + } + + @Override + protected void customValidate(ValidationContext validationContext, Collection<ValidationResult> results) { + } + + @Override + protected Map<String, String> createAttributes( + final GoogleDriveFileInfo entity, + final ProcessContext context + ) { + final Map<String, String> attributes = new HashMap<>(); + attributes.put("drive.id", entity.getId()); + attributes.put("filename", entity.getName()); + attributes.put("drive.size", String.valueOf(entity.getSize())); + attributes.put("drive.timestamp", String.valueOf(entity.getTimestamp())); + attributes.put("mime.type", entity.getMimeType()); + + return attributes; + } + + @OnScheduled + public void onScheduled(final ProcessContext context) throws IOException { + final ProxyConfiguration proxyConfiguration = ProxyConfiguration.getConfiguration(context); + httpTransport = new ProxyAwareTransportFactory(proxyConfiguration).create(); + } + + @Override + protected String getListingContainerName(final ProcessContext context) { + return String.format("Google Drive Folder [%s]", getPath(context)); + } + + @Override + protected String getPath(final ProcessContext context) { + return context.getProperty(FOLDER_ID).evaluateAttributeExpressions().getValue(); + } + + @Override + protected boolean isListingResetNecessary(final PropertyDescriptor property) { + return LISTING_STRATEGY.equals(property) + || FOLDER_ID.equals(property) + || RECURSIVE_SEARCH.equals(property); + } + + @Override + protected Scope getStateScope(final PropertyContext context) { + return Scope.CLUSTER; + } + + @Override + protected RecordSchema getRecordSchema() { + return GoogleDriveFileInfo.getRecordSchema(); + } + + @Override + protected String getDefaultTimePrecision() { + return PRECISION_SECONDS.getValue(); + } + + @Override + protected List<GoogleDriveFileInfo> performListing( + final ProcessContext context, + final Long minTimestamp, + final ListingMode listingMode + ) throws IOException { + final List<GoogleDriveFileInfo> listing = new ArrayList<>(); + + final String folderId = context.getProperty(FOLDER_ID).evaluateAttributeExpressions().getValue(); + final Boolean recursive = context.getProperty(RECURSIVE_SEARCH).asBoolean(); + final Long minAge = context.getProperty(MIN_AGE).asTimePeriod(TimeUnit.MILLISECONDS); + + Drive driveService = new Drive.Builder( + this.httpTransport, + JSON_FACTORY, + getHttpCredentialsAdapter( + context, + Arrays.asList(DriveScopes.DRIVE_METADATA_READONLY) + ) + ) + .setApplicationName(APPLICATION_NAME) + .build(); + + StringBuilder queryBuilder = new StringBuilder(); + queryBuilder.append(buildQueryForDirs(driveService, folderId, recursive)); + queryBuilder.append(" and (mimeType != 'application/vnd.google-apps.folder')"); + queryBuilder.append(" and (mimeType != 'application/vnd.google-apps.shortcut')"); + queryBuilder.append(" and trashed = false"); + if (minTimestamp != null && minTimestamp > 0) { + String formattedMinTimestamp = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(OffsetDateTime.ofInstant(Instant.ofEpochMilli(minTimestamp), ZoneId.of("UTC"))); + + queryBuilder.append(" and ("); + queryBuilder.append("modifiedTime >= '" + formattedMinTimestamp + "'"); + queryBuilder.append(" or createdTime >= '" + formattedMinTimestamp + "'"); + queryBuilder.append(")"); + } + if (minAge != null && minAge > 0) { + long maxTimestamp = System.currentTimeMillis() - minAge; + String formattedMaxTimestamp = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(OffsetDateTime.ofInstant(Instant.ofEpochMilli(maxTimestamp), ZoneId.of("UTC"))); + + queryBuilder.append(" and modifiedTime < '" + formattedMaxTimestamp + "'"); + queryBuilder.append(" and createdTime < '" + formattedMaxTimestamp + "'"); + } + + String pageToken = null; + do { + FileList result = driveService.files() + .list() + .setQ(queryBuilder.toString()) Review Comment: There seems to be a limit for the length of the query string: 30000 characters. It means we can add 500-550 folders in this query. It should be documented for the user that they cannot list Google Drive shares with more than 500 subfolders. -- 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. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
