You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@nifi.apache.org by mans2singh <gi...@git.apache.org> on 2018/03/18 01:55:34 UTC

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

GitHub user mans2singh opened a pull request:

    https://github.com/apache/nifi/pull/2562

    NIFI-4927 - InfluxDB Query Processor

    Thank you for submitting a contribution to Apache NiFi.
    
    In order to streamline the review of the contribution we ask you
    to ensure the following steps have been taken:
    
    ### For all changes:
    - [x] Is there a JIRA ticket associated with this PR? Is it referenced 
         in the commit message?
    
    - [x] Does your PR title start with NIFI-XXXX where XXXX is the JIRA number you are trying to resolve? Pay particular attention to the hyphen "-" character.
    
    - [x] Has your PR been rebased against the latest commit within the target branch (typically master)?
    
    - [x] Is your initial contribution a single, squashed commit?
    
    ### For code changes:
    - [x] Have you ensured that the full suite of tests is executed via mvn -Pcontrib-check clean install at the root nifi folder?
    - [x] Have you written or updated unit tests to verify your changes?
    - [x] If adding new dependencies to the code, are these dependencies licensed in a way that is compatible for inclusion under [ASF 2.0](http://www.apache.org/legal/resolved.html#category-a)? 
    - [x] If applicable, have you updated the LICENSE file, including the main LICENSE file under nifi-assembly?
    - [x] If applicable, have you updated the NOTICE file, including the main NOTICE file found under nifi-assembly?
    - [x] If adding new Properties, have you added .displayName in addition to .name (programmatic access) for each of the new properties?
    
    ### For documentation related changes:
    - [x] Have you ensured that format looks appropriate for the output in which it is rendered?
    
    ### Note:
    Please ensure that once the PR is submitted, you check travis-ci for build issues and submit an update to your PR as soon as possible.


You can merge this pull request into a Git repository by running:

    $ git pull https://github.com/mans2singh/nifi NIFI-4927

Alternatively you can review and apply these changes as the patch at:

    https://github.com/apache/nifi/pull/2562.patch

To close this pull request, make a commit to your master/trunk branch
with (at least) the following in the commit message:

    This closes #2562
    
----
commit 7c607eacb1aadb15295bc646ba380fed952cce6e
Author: mans2singh <ma...@...>
Date:   2018-03-18T01:50:08Z

    NIFI-4927 - InfluxDB Query Processor

----


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r176524758
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,199 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    --- End diff --
    
    Making input optional could be quite useful. See ExecuteSQL and GetMongo for an example of how to support timer and event driving.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178480359
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/test/java/org/apache/nifi/processors/influxdb/ITExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,231 @@
    +/*
    + * 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.influxdb;
    +import static org.junit.Assert.assertEquals;
    +import org.junit.Assert;
    +import java.util.List;
    +import java.util.concurrent.TimeUnit;
    +
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.util.MockFlowFile;
    +import org.apache.nifi.util.TestRunners;
    +import org.influxdb.InfluxDB;
    +import org.influxdb.dto.QueryResult;
    +import org.junit.Before;
    +import org.junit.Test;
    +
    +/**
    + * Integration test for executing InfluxDB queries. Please ensure that the InfluxDB is running
    + * on local host with default port and has database test with table test. Please set user
    + * and password if applicable before running the integration tests.
    + */
    +public class ITExecuteInfluxDBQuery extends AbstractITInfluxDB {
    +
    +    @Before
    +    public void setUp() throws Exception {
    +        initInfluxDB();
    +        runner = TestRunners.newTestRunner(ExecuteInfluxDBQuery.class);
    +        initializeRunner();
    +    }
    +
    +    @Test
    +    public void testValidScheduleQueryWithNoIncoming() {
    +        String message = "water,country=US,city=newark rain=1,humidity=0.6 1501002274856668652";
    +        influxDB.write(dbName, DEFAULT_RETENTION_POLICY, InfluxDB.ConsistencyLevel.ONE, message);
    +
    +        String query = "select * from water";
    +        runner.setProperty(ExecuteInfluxDBQuery.INFLUX_DB_QUERY, query);
    +
    +        runner.setIncomingConnection(false);
    +        runner.run(1,true,true);
    +        runner.assertAllFlowFilesTransferred(ExecuteInfluxDBQuery.REL_SUCCESS, 1);
    +        List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(ExecuteInfluxDBQuery.REL_SUCCESS);
    +        assertEquals("Value should be equal", 1, flowFiles.size());
    +        assertEquals("Value should be equal",null, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_ERROR_MESSAGE));
    +        assertEquals("Value should be equal",query, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY));
    +        flowFiles.get(0).assertContentEquals(
    --- End diff --
    
    Updated to parse json and compare typed results.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178328915
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,258 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.io.IOException;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_ALLOWED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement", "get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile (preferred) or a scheduled query.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY = new PropertyDescriptor.Builder()
    +            .name("influxdb-query")
    +            .displayName("InfluxDB Query")
    +            .description("The InfluxDB query to execute. "
    +                    + "Note: If there are incoming connections, then the query is created from incoming FlowFile's content and scheduled query is ignored.")
    +            .required(false)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .expressionLanguageSupported(true)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(INFLUX_DB_QUERY);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +        // Either input connection or scheduled query is required
    +        if ( ! context.getProperty(INFLUX_DB_QUERY).isSet()
    +           && ! context.hasIncomingConnection() ) {
    +            String error = "The InfluxDB Query processor requires input connection or scheduled InfluxDB query";
    +            getLogger().error(error);
    +            throw new ProcessException(error);
    +        }
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +
    +        String query = null;
    +        String database = null;
    +        TimeUnit queryResultTimeunit = null;
    +        Charset charset = null;
    +        FlowFile outgoingFlowFile = null;
    +
    +        // If there are incoming connections, prepare query params from flow file
    +        if ( context.hasIncomingConnection() ) {
    +            FlowFile incomingFlowFile = session.get();
    +
    +            if ( incomingFlowFile == null && context.hasNonLoopConnection() ) {
    +                return;
    +            }
    +
    +            if ( incomingFlowFile.getSize() == 0) {
    +                getLogger().error("Empty query");
    +                incomingFlowFile = session.putAttribute(incomingFlowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + incomingFlowFile.getSize());
    +                session.transfer(incomingFlowFile, REL_FAILURE);
    +                return;
    +            }
    +
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +            try {
    +                ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +                session.exportTo(incomingFlowFile, baos);
    +                baos.close();
    +                query = new String(baos.toByteArray(), charset);
    +            } catch(IOException ioe) {
    +                getLogger().error("Exception while reading from FlowFile " + ioe.getLocalizedMessage(), ioe);
    +                throw new ProcessException(ioe);
    +            }
    +
    +            database = context.getProperty(DB_NAME).evaluateAttributeExpressions(incomingFlowFile).getValue();
    +            queryResultTimeunit = TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +
    +            outgoingFlowFile = incomingFlowFile;
    +        } else {
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions().getValue());
    +            query = context.getProperty(INFLUX_DB_QUERY).evaluateAttributeExpressions().getValue();
    +            database = context.getProperty(DB_NAME).evaluateAttributeExpressions().getValue();
    +            queryResultTimeunit = TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions().getValue());
    +
    +            outgoingFlowFile = session.create();
    +        }
    +
    +        try {
    +            long startTimeMillis = System.currentTimeMillis();
    +            QueryResult result = executeQuery(context, database, query, queryResultTimeunit);
    +
    +            if ( result == null ) {
    +                String message = "Query Result was " + result;
    +                getLogger().error(message);
    +                throw new NullPointerException(message);
    +            }
    +
    +            String json = gson.toJson(result);
    +
    +            if ( getLogger().isDebugEnabled() ) {
    +                getLogger().debug("Query result {} ", new Object[] {result});
    +            }
    +
    +            ByteArrayInputStream bais = new ByteArrayInputStream(json.getBytes(charset));
    +            session.importFrom(bais, outgoingFlowFile);
    +            bais.close();
    +
    +            final long endTimeMillis = System.currentTimeMillis();
    +
    +            if ( ! result.hasError() ) {
    +                outgoingFlowFile = session.putAttribute(outgoingFlowFile, INFLUX_DB_EXECUTED_QUERY, String.valueOf(query));
    +                session.transfer(outgoingFlowFile, REL_SUCCESS);
    +            } else {
    +                outgoingFlowFile = populateErrorAttributes(session, outgoingFlowFile, query, result.getError());
    +                session.transfer(outgoingFlowFile, REL_FAILURE);
    +            }
    +
    +            session.getProvenanceReporter().send(outgoingFlowFile, makeProvenanceUrl(context, database),
    --- End diff --
    
    You don't want to report provenance here if you have stuff sent to REL_FAILURE.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r176974503
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,199 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement","get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    --- End diff --
    
    Influx queries supports data queries, dml and schema exploration.  I've added integration tests for these.


---

[GitHub] nifi issue #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on the issue:

    https://github.com/apache/nifi/pull/2562
  
    @MikeThomsen - 
    
    I have updated the test cases regarding usage of assertions.  Let me know if there is anything else outstanding.
    
    Thanks


---

[GitHub] nifi issue #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on the issue:

    https://github.com/apache/nifi/pull/2562
  
    Approved and merged. Thanks @mans2singh 


---

[GitHub] nifi issue #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on the issue:

    https://github.com/apache/nifi/pull/2562
  
    @mans2singh Have you had a chance to work on any of these?


---

[GitHub] nifi issue #2562: NIFI-4927 - InfluxDB Query Processor

Posted by joewitt <gi...@git.apache.org>.
Github user joewitt commented on the issue:

    https://github.com/apache/nifi/pull/2562
  
    @mans2singh thanks for contributing.  What we need most right now is help reviewing outstanding PRs.  This involves reviewing code and validating as possible whether things are actually functioning.  For things like this it can be tougher because it means someone needs an environment with influx running/etc.. and familiarity on how to do so.  What can you do?  You can provide detailed instructions a reviewer could follow to verify functionality.  Perhaps a pointer to a docker container which eases the process.  And help with reviews on other items, for example.  Not saying someone wont look at this until then - they certainly might.  Just giving you tips to help ease the process.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r176974126
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,199 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement","get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +        FlowFile flowFile = session.get();
    +        if (flowFile == null) {
    +            return;
    +        }
    +        if ( flowFile.getSize() == 0) {
    +            getLogger().error("Empty query");
    +            flowFile = session.putAttribute(flowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + flowFile.getSize());
    +            session.transfer(flowFile, REL_FAILURE);
    +            return;
    +        }
    +
    +        Charset charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(flowFile).getValue());
    +        String database = context.getProperty(DB_NAME).evaluateAttributeExpressions(flowFile).getValue();
    +        TimeUnit queryResultTimeunit =
    +            TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(flowFile).getValue());
    +
    +        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +        session.exportTo(flowFile, baos);
    +        String query = new String(baos.toByteArray(), charset);
    +
    +        try {
    +            long startTimeMillis = System.currentTimeMillis();
    +            QueryResult result = executeQuery(context, database, query, queryResultTimeunit);
    +            String json = gson.toJson(result);
    --- End diff --
    
    If there is problem in executing query it throws an exception or returns true for `hasError` method and I check for them.  But if you think I should check for `null`, I can do that.  


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178328269
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,258 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.io.IOException;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_ALLOWED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement", "get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile (preferred) or a scheduled query.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY = new PropertyDescriptor.Builder()
    +            .name("influxdb-query")
    +            .displayName("InfluxDB Query")
    +            .description("The InfluxDB query to execute. "
    +                    + "Note: If there are incoming connections, then the query is created from incoming FlowFile's content and scheduled query is ignored.")
    +            .required(false)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .expressionLanguageSupported(true)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(INFLUX_DB_QUERY);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +        // Either input connection or scheduled query is required
    +        if ( ! context.getProperty(INFLUX_DB_QUERY).isSet()
    +           && ! context.hasIncomingConnection() ) {
    +            String error = "The InfluxDB Query processor requires input connection or scheduled InfluxDB query";
    +            getLogger().error(error);
    +            throw new ProcessException(error);
    +        }
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +
    +        String query = null;
    +        String database = null;
    +        TimeUnit queryResultTimeunit = null;
    +        Charset charset = null;
    +        FlowFile outgoingFlowFile = null;
    +
    +        // If there are incoming connections, prepare query params from flow file
    +        if ( context.hasIncomingConnection() ) {
    +            FlowFile incomingFlowFile = session.get();
    +
    +            if ( incomingFlowFile == null && context.hasNonLoopConnection() ) {
    +                return;
    +            }
    +
    +            if ( incomingFlowFile.getSize() == 0) {
    +                getLogger().error("Empty query");
    +                incomingFlowFile = session.putAttribute(incomingFlowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + incomingFlowFile.getSize());
    +                session.transfer(incomingFlowFile, REL_FAILURE);
    +                return;
    +            }
    +
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +            try {
    +                ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +                session.exportTo(incomingFlowFile, baos);
    +                baos.close();
    +                query = new String(baos.toByteArray(), charset);
    +            } catch(IOException ioe) {
    +                getLogger().error("Exception while reading from FlowFile " + ioe.getLocalizedMessage(), ioe);
    +                throw new ProcessException(ioe);
    +            }
    +
    +            database = context.getProperty(DB_NAME).evaluateAttributeExpressions(incomingFlowFile).getValue();
    +            queryResultTimeunit = TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +
    +            outgoingFlowFile = incomingFlowFile;
    +        } else {
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions().getValue());
    --- End diff --
    
    These should be evaluated against the flowfile's attributes with `evaluateAttributeExpressions(FlowFile)`. I think it will work if the flowfile is null. A test against that wouldn't hurt just to be safe as well.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r176974332
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,199 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement","get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +        FlowFile flowFile = session.get();
    +        if (flowFile == null) {
    +            return;
    +        }
    +        if ( flowFile.getSize() == 0) {
    +            getLogger().error("Empty query");
    +            flowFile = session.putAttribute(flowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + flowFile.getSize());
    +            session.transfer(flowFile, REL_FAILURE);
    +            return;
    +        }
    +
    +        Charset charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(flowFile).getValue());
    +        String database = context.getProperty(DB_NAME).evaluateAttributeExpressions(flowFile).getValue();
    +        TimeUnit queryResultTimeunit =
    +            TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(flowFile).getValue());
    +
    +        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +        session.exportTo(flowFile, baos);
    +        String query = new String(baos.toByteArray(), charset);
    +
    +        try {
    +            long startTimeMillis = System.currentTimeMillis();
    +            QueryResult result = executeQuery(context, database, query, queryResultTimeunit);
    +            String json = gson.toJson(result);
    +
    +            if ( getLogger().isDebugEnabled() ) {
    +                getLogger().debug("Query result {} ", new Object[] {result});
    +            }
    +
    +            ByteArrayInputStream bais = new ByteArrayInputStream(json.getBytes(charset));
    +            session.importFrom(bais, flowFile);
    +            final long endTimeMillis = System.currentTimeMillis();
    +
    +            if ( ! result.hasError() ) {
    +                flowFile = session.putAttribute(flowFile, INFLUX_DB_EXECUTED_QUERY, String.valueOf(query));
    +                session.transfer(flowFile, REL_SUCCESS);
    +            } else {
    +                flowFile = populateErrorAttributes(session, flowFile, query, result.getError());
    +                session.transfer(flowFile, REL_FAILURE);
    +            }
    +
    +            session.getProvenanceReporter().send(flowFile, new StringBuilder("influxdb://")
    +                .append(context.getProperty(INFLUX_DB_URL).evaluateAttributeExpressions().getValue()).append("/")
    +                .append(database).toString(),
    +                (endTimeMillis - startTimeMillis));
    +        } catch (Exception exception) {
    +            flowFile = populateErrorAttributes(session, flowFile, query, exception.getMessage());
    +            if ( exception.getCause() instanceof SocketTimeoutException ) {
    --- End diff --
    
    I did not find any documentation on any other network exception on invoking query.  But let me know if you have any recommendations.


---

[GitHub] nifi issue #2562: NIFI-4927 - InfluxDB Query Processor

Posted by timhallinflux <gi...@git.apache.org>.
Github user timhallinflux commented on the issue:

    https://github.com/apache/nifi/pull/2562
  
    This is great!  Thank you Mike and Mans.  Mans.... if you reach out to me at tim at influxdata dot com
    we would be happy to send you some stickers and a hoodie in appreciation for your efforts here.  


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178480131
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,258 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.io.IOException;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_ALLOWED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement", "get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile (preferred) or a scheduled query.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY = new PropertyDescriptor.Builder()
    +            .name("influxdb-query")
    +            .displayName("InfluxDB Query")
    +            .description("The InfluxDB query to execute. "
    +                    + "Note: If there are incoming connections, then the query is created from incoming FlowFile's content and scheduled query is ignored.")
    +            .required(false)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .expressionLanguageSupported(true)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(INFLUX_DB_QUERY);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +        // Either input connection or scheduled query is required
    +        if ( ! context.getProperty(INFLUX_DB_QUERY).isSet()
    +           && ! context.hasIncomingConnection() ) {
    +            String error = "The InfluxDB Query processor requires input connection or scheduled InfluxDB query";
    +            getLogger().error(error);
    +            throw new ProcessException(error);
    +        }
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +
    +        String query = null;
    +        String database = null;
    +        TimeUnit queryResultTimeunit = null;
    +        Charset charset = null;
    +        FlowFile outgoingFlowFile = null;
    +
    +        // If there are incoming connections, prepare query params from flow file
    +        if ( context.hasIncomingConnection() ) {
    +            FlowFile incomingFlowFile = session.get();
    +
    +            if ( incomingFlowFile == null && context.hasNonLoopConnection() ) {
    +                return;
    +            }
    +
    +            if ( incomingFlowFile.getSize() == 0) {
    +                getLogger().error("Empty query");
    +                incomingFlowFile = session.putAttribute(incomingFlowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + incomingFlowFile.getSize());
    +                session.transfer(incomingFlowFile, REL_FAILURE);
    +                return;
    +            }
    +
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +            try {
    +                ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +                session.exportTo(incomingFlowFile, baos);
    +                baos.close();
    +                query = new String(baos.toByteArray(), charset);
    +            } catch(IOException ioe) {
    +                getLogger().error("Exception while reading from FlowFile " + ioe.getLocalizedMessage(), ioe);
    +                throw new ProcessException(ioe);
    +            }
    +
    +            database = context.getProperty(DB_NAME).evaluateAttributeExpressions(incomingFlowFile).getValue();
    +            queryResultTimeunit = TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +
    +            outgoingFlowFile = incomingFlowFile;
    +        } else {
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions().getValue());
    +            query = context.getProperty(INFLUX_DB_QUERY).evaluateAttributeExpressions().getValue();
    +            database = context.getProperty(DB_NAME).evaluateAttributeExpressions().getValue();
    +            queryResultTimeunit = TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions().getValue());
    +
    +            outgoingFlowFile = session.create();
    +        }
    +
    +        try {
    +            long startTimeMillis = System.currentTimeMillis();
    +            QueryResult result = executeQuery(context, database, query, queryResultTimeunit);
    +
    +            if ( result == null ) {
    +                String message = "Query Result was " + result;
    +                getLogger().error(message);
    +                throw new NullPointerException(message);
    +            }
    +
    +            String json = gson.toJson(result);
    +
    +            if ( getLogger().isDebugEnabled() ) {
    +                getLogger().debug("Query result {} ", new Object[] {result});
    +            }
    +
    +            ByteArrayInputStream bais = new ByteArrayInputStream(json.getBytes(charset));
    +            session.importFrom(bais, outgoingFlowFile);
    +            bais.close();
    +
    +            final long endTimeMillis = System.currentTimeMillis();
    +
    +            if ( ! result.hasError() ) {
    +                outgoingFlowFile = session.putAttribute(outgoingFlowFile, INFLUX_DB_EXECUTED_QUERY, String.valueOf(query));
    +                session.transfer(outgoingFlowFile, REL_SUCCESS);
    +            } else {
    +                outgoingFlowFile = populateErrorAttributes(session, outgoingFlowFile, query, result.getError());
    +                session.transfer(outgoingFlowFile, REL_FAILURE);
    +            }
    +
    +            session.getProvenanceReporter().send(outgoingFlowFile, makeProvenanceUrl(context, database),
    +                (endTimeMillis - startTimeMillis));
    +        } catch (Exception exception) {
    +            outgoingFlowFile = populateErrorAttributes(session, outgoingFlowFile, query, exception.getMessage());
    +            if ( exception.getCause() instanceof SocketTimeoutException ) {
    +                getLogger().error("Failed to read from influxDB due SocketTimeoutException to {} and retrying",
    +                        new Object[]{exception.getCause().getLocalizedMessage()}, exception.getCause());
    +                session.transfer(outgoingFlowFile, REL_RETRY);
    +            } else {
    +                getLogger().error("Failed to read from influxDB due to {}",
    +                        new Object[]{exception.getLocalizedMessage()}, exception);
    +                session.transfer(outgoingFlowFile, REL_FAILURE);
    +            }
    +            context.yield();
    +        }
    +    }
    +
    +    protected String makeProvenanceUrl(final ProcessContext context, String database) {
    --- End diff --
    
    Added flow file parameter.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r176974380
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,199 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement","get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +        FlowFile flowFile = session.get();
    +        if (flowFile == null) {
    +            return;
    +        }
    +        if ( flowFile.getSize() == 0) {
    +            getLogger().error("Empty query");
    +            flowFile = session.putAttribute(flowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + flowFile.getSize());
    +            session.transfer(flowFile, REL_FAILURE);
    +            return;
    +        }
    +
    +        Charset charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(flowFile).getValue());
    +        String database = context.getProperty(DB_NAME).evaluateAttributeExpressions(flowFile).getValue();
    +        TimeUnit queryResultTimeunit =
    +            TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(flowFile).getValue());
    +
    +        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +        session.exportTo(flowFile, baos);
    +        String query = new String(baos.toByteArray(), charset);
    --- End diff --
    
    Corrected it.  


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178327791
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,258 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.io.IOException;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_ALLOWED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement", "get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile (preferred) or a scheduled query.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY = new PropertyDescriptor.Builder()
    +            .name("influxdb-query")
    +            .displayName("InfluxDB Query")
    +            .description("The InfluxDB query to execute. "
    +                    + "Note: If there are incoming connections, then the query is created from incoming FlowFile's content and scheduled query is ignored.")
    +            .required(false)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .expressionLanguageSupported(true)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(INFLUX_DB_QUERY);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +        // Either input connection or scheduled query is required
    +        if ( ! context.getProperty(INFLUX_DB_QUERY).isSet()
    +           && ! context.hasIncomingConnection() ) {
    +            String error = "The InfluxDB Query processor requires input connection or scheduled InfluxDB query";
    +            getLogger().error(error);
    +            throw new ProcessException(error);
    +        }
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +
    +        String query = null;
    +        String database = null;
    +        TimeUnit queryResultTimeunit = null;
    +        Charset charset = null;
    +        FlowFile outgoingFlowFile = null;
    +
    +        // If there are incoming connections, prepare query params from flow file
    +        if ( context.hasIncomingConnection() ) {
    +            FlowFile incomingFlowFile = session.get();
    +
    +            if ( incomingFlowFile == null && context.hasNonLoopConnection() ) {
    +                return;
    +            }
    +
    +            if ( incomingFlowFile.getSize() == 0) {
    --- End diff --
    
    A flowfile with no content could be used to supply attributes to the query parameter. So you should remove this check if the query param is set.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r176974260
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,199 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement","get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +        FlowFile flowFile = session.get();
    +        if (flowFile == null) {
    +            return;
    +        }
    +        if ( flowFile.getSize() == 0) {
    +            getLogger().error("Empty query");
    +            flowFile = session.putAttribute(flowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + flowFile.getSize());
    +            session.transfer(flowFile, REL_FAILURE);
    +            return;
    +        }
    +
    +        Charset charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(flowFile).getValue());
    +        String database = context.getProperty(DB_NAME).evaluateAttributeExpressions(flowFile).getValue();
    +        TimeUnit queryResultTimeunit =
    +            TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(flowFile).getValue());
    +
    +        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +        session.exportTo(flowFile, baos);
    +        String query = new String(baos.toByteArray(), charset);
    +
    +        try {
    +            long startTimeMillis = System.currentTimeMillis();
    +            QueryResult result = executeQuery(context, database, query, queryResultTimeunit);
    +            String json = gson.toJson(result);
    +
    +            if ( getLogger().isDebugEnabled() ) {
    +                getLogger().debug("Query result {} ", new Object[] {result});
    +            }
    +
    +            ByteArrayInputStream bais = new ByteArrayInputStream(json.getBytes(charset));
    +            session.importFrom(bais, flowFile);
    +            final long endTimeMillis = System.currentTimeMillis();
    +
    +            if ( ! result.hasError() ) {
    +                flowFile = session.putAttribute(flowFile, INFLUX_DB_EXECUTED_QUERY, String.valueOf(query));
    +                session.transfer(flowFile, REL_SUCCESS);
    +            } else {
    +                flowFile = populateErrorAttributes(session, flowFile, query, result.getError());
    +                session.transfer(flowFile, REL_FAILURE);
    +            }
    +
    +            session.getProvenanceReporter().send(flowFile, new StringBuilder("influxdb://")
    +                .append(context.getProperty(INFLUX_DB_URL).evaluateAttributeExpressions().getValue()).append("/")
    +                .append(database).toString(),
    +                (endTimeMillis - startTimeMillis));
    +        } catch (Exception exception) {
    +            flowFile = populateErrorAttributes(session, flowFile, query, exception.getMessage());
    +            if ( exception.getCause() instanceof SocketTimeoutException ) {
    +                getLogger().error("Failed to read from influxDB due SocketTimeoutException to {} and retrying",
    +                        new Object[]{exception.getLocalizedMessage()}, exception);
    +                session.transfer(flowFile, REL_RETRY);
    +            } else {
    +                getLogger().error("Failed to read from influxDB due to {}",
    +                        new Object[]{exception.getLocalizedMessage()}, exception);
    +                session.transfer(flowFile, REL_FAILURE);
    +            }
    +            context.yield();
    +        }
    +    }
    +
    +    protected QueryResult executeQuery(final ProcessContext context, String database, String query, TimeUnit timeunit) {
    +        return getInfluxDB(context).query(new Query(query, database),timeunit);
    +    }
    +
    +    protected FlowFile populateErrorAttributes(final ProcessSession session, FlowFile flowFile, String query,
    +            String message) {
    +        Map<String,String> attributes = new HashMap<>();
    +        attributes.put(INFLUX_DB_ERROR_MESSAGE, String.valueOf(message));
    --- End diff --
    
    String.valueOf is a null safe method, it returns string `null` in case string is null otherwise the string, so I can safely add it to the Map.


---

[GitHub] nifi issue #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on the issue:

    https://github.com/apache/nifi/pull/2562
  
    @timhallinflux Based on my extremely limited knowledge of what InfluxDB can do, I don't know if even the U or D from CRUD are really applicable to InfluxDB for example. What I'd like to see is some input that would help us mold this bundle to maxing out the reasonable use cases where NiFi and InfluxDB can sensibly work together if that makes sense.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r176525442
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,199 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement","get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    --- End diff --
    
    We've started making this user-defined in some other processors.


---

[GitHub] nifi issue #2562: NIFI-4927 - InfluxDB Query Processor

Posted by timhallinflux <gi...@git.apache.org>.
Github user timhallinflux commented on the issue:

    https://github.com/apache/nifi/pull/2562
  
    @joewitt and @MikeThomsen -- you can also just quickly spin up the TICK stack via the sandbox.
    Have a look here... https://github.com/influxdata/sandbox
    
    If @joewitt is no longer technical enough to run this, I'll be more than happy to do a screen share and help him out! :-)
    
    Thank you @mans2singh for contributing this!
    



---

[GitHub] nifi issue #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on the issue:

    https://github.com/apache/nifi/pull/2562
  
    Hi Nifi Team:
    
    Please let me know your suggestions/recommendations on this InfluxDB Query Processsor.
    
    Thanks


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r177296457
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/test/java/org/apache/nifi/processors/influxdb/AbstractITInfluxDB.java ---
    @@ -36,14 +36,7 @@
     
         protected void initInfluxDB() throws InterruptedException, Exception {
             influxDB = InfluxDBFactory.connect(dbUrl,user,password);
    -        if ( influxDB.databaseExists(dbName) ) {
    -            QueryResult result = influxDB.query(new Query("DROP measurement water", dbName));
    -            checkError(result);
    -            result = influxDB.query(new Query("DROP measurement testm", dbName));
    -            checkError(result);
    -            result = influxDB.query(new Query("DROP database " + dbName, dbName));
    -            Thread.sleep(1000);
    -        }
    +        cleanUpDatabase();
    --- End diff --
    
    I call the cleanup in setup as a precaution so that if there is any conflicting/previously existing data in the test database, it is removed and does not fail the integration test which depend on number of rows inserted.  If you think it is unnecessary, I can remove it.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by asfgit <gi...@git.apache.org>.
Github user asfgit closed the pull request at:

    https://github.com/apache/nifi/pull/2562


---

[GitHub] nifi issue #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on the issue:

    https://github.com/apache/nifi/pull/2562
  
    Hi @MikeThomsen - Thanks for your review and comments.  
    
    I will work on your and @joewitt 's recommendation this weekend.



---

[GitHub] nifi issue #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on the issue:

    https://github.com/apache/nifi/pull/2562
  
    @MikeThomsen - 
    
    I've updated the code (added expression language scope and updated tests) based your review comments.  The integration tests are passing.  
    
    Please let me know if there is any other comment.
    
    Thanks
    
    Mans


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178329491
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,258 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.io.IOException;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_ALLOWED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement", "get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile (preferred) or a scheduled query.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY = new PropertyDescriptor.Builder()
    +            .name("influxdb-query")
    +            .displayName("InfluxDB Query")
    +            .description("The InfluxDB query to execute. "
    +                    + "Note: If there are incoming connections, then the query is created from incoming FlowFile's content and scheduled query is ignored.")
    +            .required(false)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .expressionLanguageSupported(true)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(INFLUX_DB_QUERY);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +        // Either input connection or scheduled query is required
    +        if ( ! context.getProperty(INFLUX_DB_QUERY).isSet()
    +           && ! context.hasIncomingConnection() ) {
    +            String error = "The InfluxDB Query processor requires input connection or scheduled InfluxDB query";
    +            getLogger().error(error);
    +            throw new ProcessException(error);
    +        }
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +
    +        String query = null;
    +        String database = null;
    +        TimeUnit queryResultTimeunit = null;
    +        Charset charset = null;
    +        FlowFile outgoingFlowFile = null;
    +
    +        // If there are incoming connections, prepare query params from flow file
    +        if ( context.hasIncomingConnection() ) {
    +            FlowFile incomingFlowFile = session.get();
    +
    +            if ( incomingFlowFile == null && context.hasNonLoopConnection() ) {
    +                return;
    +            }
    +
    +            if ( incomingFlowFile.getSize() == 0) {
    +                getLogger().error("Empty query");
    +                incomingFlowFile = session.putAttribute(incomingFlowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + incomingFlowFile.getSize());
    +                session.transfer(incomingFlowFile, REL_FAILURE);
    +                return;
    +            }
    +
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +            try {
    +                ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +                session.exportTo(incomingFlowFile, baos);
    +                baos.close();
    +                query = new String(baos.toByteArray(), charset);
    +            } catch(IOException ioe) {
    +                getLogger().error("Exception while reading from FlowFile " + ioe.getLocalizedMessage(), ioe);
    +                throw new ProcessException(ioe);
    +            }
    +
    +            database = context.getProperty(DB_NAME).evaluateAttributeExpressions(incomingFlowFile).getValue();
    +            queryResultTimeunit = TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +
    +            outgoingFlowFile = incomingFlowFile;
    +        } else {
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions().getValue());
    +            query = context.getProperty(INFLUX_DB_QUERY).evaluateAttributeExpressions().getValue();
    +            database = context.getProperty(DB_NAME).evaluateAttributeExpressions().getValue();
    +            queryResultTimeunit = TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions().getValue());
    +
    +            outgoingFlowFile = session.create();
    +        }
    +
    +        try {
    +            long startTimeMillis = System.currentTimeMillis();
    +            QueryResult result = executeQuery(context, database, query, queryResultTimeunit);
    +
    +            if ( result == null ) {
    +                String message = "Query Result was " + result;
    +                getLogger().error(message);
    +                throw new NullPointerException(message);
    +            }
    +
    +            String json = gson.toJson(result);
    +
    +            if ( getLogger().isDebugEnabled() ) {
    +                getLogger().debug("Query result {} ", new Object[] {result});
    +            }
    +
    +            ByteArrayInputStream bais = new ByteArrayInputStream(json.getBytes(charset));
    +            session.importFrom(bais, outgoingFlowFile);
    +            bais.close();
    +
    +            final long endTimeMillis = System.currentTimeMillis();
    +
    +            if ( ! result.hasError() ) {
    +                outgoingFlowFile = session.putAttribute(outgoingFlowFile, INFLUX_DB_EXECUTED_QUERY, String.valueOf(query));
    +                session.transfer(outgoingFlowFile, REL_SUCCESS);
    +            } else {
    +                outgoingFlowFile = populateErrorAttributes(session, outgoingFlowFile, query, result.getError());
    +                session.transfer(outgoingFlowFile, REL_FAILURE);
    +            }
    +
    +            session.getProvenanceReporter().send(outgoingFlowFile, makeProvenanceUrl(context, database),
    +                (endTimeMillis - startTimeMillis));
    +        } catch (Exception exception) {
    +            outgoingFlowFile = populateErrorAttributes(session, outgoingFlowFile, query, exception.getMessage());
    +            if ( exception.getCause() instanceof SocketTimeoutException ) {
    --- End diff --
    
    For readability, I think you should break this out into two catch blocks since you're handling one specific version very differently.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178790606
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/test/java/org/apache/nifi/processors/influxdb/ITExecuteInfluxDBQuery.java ---
    @@ -110,8 +125,72 @@ public void testCreateDB() {
             assertEquals("Value should be equal",null, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_ERROR_MESSAGE));
             assertEquals("Value should be equal",query, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY));
     
    -        flowFiles.get(0).assertContentEquals("{\"results\":[{}]}");
    +        QueryResult queryResult = gson.fromJson(new StringReader(new String(flowFiles.get(0).toByteArray())), QueryResult.class);
    +        assertEquals("results array should be empty", 1, queryResult.getResults().size());
    +        assertEquals("No series", null, queryResult.getResults().get(0).getSeries());
    +    }
    +
    +    @Test
    +    public void testEmptyFlowFileQueryWithScheduledQuery() {
    +        String message = "water,country=US,city=newark rain=1,humidity=0.6 1501002274856668652";
    +        influxDB.write(dbName, DEFAULT_RETENTION_POLICY, InfluxDB.ConsistencyLevel.ONE, message);
    +
    +        String query = "select * from water";
    +        runner.setProperty(ExecuteInfluxDBQuery.INFLUX_DB_QUERY, query);
    +
    +        byte [] bytes = new byte [] {};
    --- End diff --
    
    Redundant because you can use `runner.enqueue("")` for cases like this where you're not examining the original input flowfile contents.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178330389
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/test/java/org/apache/nifi/processors/influxdb/ITExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,231 @@
    +/*
    + * 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.influxdb;
    +import static org.junit.Assert.assertEquals;
    +import org.junit.Assert;
    +import java.util.List;
    +import java.util.concurrent.TimeUnit;
    +
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.util.MockFlowFile;
    +import org.apache.nifi.util.TestRunners;
    +import org.influxdb.InfluxDB;
    +import org.influxdb.dto.QueryResult;
    +import org.junit.Before;
    +import org.junit.Test;
    +
    +/**
    + * Integration test for executing InfluxDB queries. Please ensure that the InfluxDB is running
    + * on local host with default port and has database test with table test. Please set user
    + * and password if applicable before running the integration tests.
    + */
    +public class ITExecuteInfluxDBQuery extends AbstractITInfluxDB {
    +
    +    @Before
    +    public void setUp() throws Exception {
    +        initInfluxDB();
    +        runner = TestRunners.newTestRunner(ExecuteInfluxDBQuery.class);
    +        initializeRunner();
    +    }
    +
    +    @Test
    +    public void testValidScheduleQueryWithNoIncoming() {
    +        String message = "water,country=US,city=newark rain=1,humidity=0.6 1501002274856668652";
    +        influxDB.write(dbName, DEFAULT_RETENTION_POLICY, InfluxDB.ConsistencyLevel.ONE, message);
    +
    +        String query = "select * from water";
    +        runner.setProperty(ExecuteInfluxDBQuery.INFLUX_DB_QUERY, query);
    +
    +        runner.setIncomingConnection(false);
    +        runner.run(1,true,true);
    +        runner.assertAllFlowFilesTransferred(ExecuteInfluxDBQuery.REL_SUCCESS, 1);
    +        List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(ExecuteInfluxDBQuery.REL_SUCCESS);
    +        assertEquals("Value should be equal", 1, flowFiles.size());
    +        assertEquals("Value should be equal",null, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_ERROR_MESSAGE));
    +        assertEquals("Value should be equal",query, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY));
    +        flowFiles.get(0).assertContentEquals(
    --- End diff --
    
    If you can parse this with Gson and evaluate it that way, the test will be less likely to be brittle as InfluxDB evolves.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r176974663
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/test/java/org/apache/nifi/processors/influxdb/ITExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,163 @@
    +/*
    + * 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.influxdb;
    +import static org.junit.Assert.assertEquals;
    +import java.util.List;
    +import java.util.concurrent.TimeUnit;
    +
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.util.MockFlowFile;
    +import org.apache.nifi.util.TestRunners;
    +import org.influxdb.InfluxDB;
    +import org.influxdb.dto.QueryResult;
    +import org.junit.Before;
    +import org.junit.Test;
    +
    +/**
    + * Integration test for executing InfluxDB queries. Please ensure that the InfluxDB is running
    + * on local host with default port and has database test with table test. Please set user
    + * and password if applicable before running the integration tests.
    + */
    +public class ITExecuteInfluxDBQuery extends AbstractITInfluxDB {
    +
    +    @Before
    +    public void setUp() throws Exception {
    +        runner = TestRunners.newTestRunner(ExecuteInfluxDBQuery.class);
    +        initializeRunner();
    --- End diff --
    
    I've changed the order and call init database before initializing runner.  Let me know if that is ok.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r177120294
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -72,6 +74,16 @@
                 .sensitive(false)
                 .build();
     
    +    public static final PropertyDescriptor INFLUX_DB_SCHEDULED_QUERY = new PropertyDescriptor.Builder()
    +            .name("influxdb-scheduled-query")
    +            .displayName("InfluxDB Schedued Query")
    --- End diff --
    
    I think calling it a "scheduled query" might be a bit confusing. In other places like `GetMongo` it's just `Query` and documents that this field will be used if it's filled in, otherwise it'll try to extract the query from the body. Might want to also note that you can use this w/ an incoming connection and use the flowfile to power the EL.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178789491
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -209,32 +204,40 @@ public void onTrigger(final ProcessContext context, final ProcessSession session
     
                 if ( ! result.hasError() ) {
                     outgoingFlowFile = session.putAttribute(outgoingFlowFile, INFLUX_DB_EXECUTED_QUERY, String.valueOf(query));
    +                session.getProvenanceReporter().send(outgoingFlowFile, makeProvenanceUrl(context, database, outgoingFlowFile),
    +                        (endTimeMillis - startTimeMillis));
                     session.transfer(outgoingFlowFile, REL_SUCCESS);
                 } else {
                     outgoingFlowFile = populateErrorAttributes(session, outgoingFlowFile, query, result.getError());
                     session.transfer(outgoingFlowFile, REL_FAILURE);
                 }
     
    -            session.getProvenanceReporter().send(outgoingFlowFile, makeProvenanceUrl(context, database),
    -                (endTimeMillis - startTimeMillis));
             } catch (Exception exception) {
                 outgoingFlowFile = populateErrorAttributes(session, outgoingFlowFile, query, exception.getMessage());
                 if ( exception.getCause() instanceof SocketTimeoutException ) {
    -                getLogger().error("Failed to read from influxDB due SocketTimeoutException to {} and retrying",
    +                getLogger().error("Failed to read from InfluxDB due SocketTimeoutException to {} and retrying",
                             new Object[]{exception.getCause().getLocalizedMessage()}, exception.getCause());
                     session.transfer(outgoingFlowFile, REL_RETRY);
                 } else {
    -                getLogger().error("Failed to read from influxDB due to {}",
    +                getLogger().error("Failed to read from InfluxDB due to {}",
                             new Object[]{exception.getLocalizedMessage()}, exception);
                     session.transfer(outgoingFlowFile, REL_FAILURE);
                 }
                 context.yield();
             }
         }
     
    -    protected String makeProvenanceUrl(final ProcessContext context, String database) {
    +    protected String getQuery(final ProcessSession session, Charset charset, FlowFile incomingFlowFile)
    +            throws IOException {
    --- End diff --
    
    What I have done in a few processors is something like this:
    ```
    String getQuery (final ProcessSession session, final ProcessContext context, Charset charset, FlowFile incomingFlowFile) throws IOException {
        if (context.getProperty(QUERY).isSet()) {
            return context.getProperty(QUERY).evaluateAttributeExpressions(incomingFlowFile).getValue();
        } else {
            //Load from file
           if (StringUtil.isBlank(query)) {
               throw new IOException("Query was missing from the flowfile body");
           } else {
               return query;
           }
        }
    }
    ```


---

[GitHub] nifi issue #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on the issue:

    https://github.com/apache/nifi/pull/2562
  
    @MikeThomsen - 
    
    I've updated the code based on your comments.  Let me know if you have any more recommendations.
    
    Thanks


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178479713
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,258 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.io.IOException;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_ALLOWED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement", "get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile (preferred) or a scheduled query.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY = new PropertyDescriptor.Builder()
    +            .name("influxdb-query")
    +            .displayName("InfluxDB Query")
    +            .description("The InfluxDB query to execute. "
    +                    + "Note: If there are incoming connections, then the query is created from incoming FlowFile's content and scheduled query is ignored.")
    +            .required(false)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .expressionLanguageSupported(true)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(INFLUX_DB_QUERY);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +        // Either input connection or scheduled query is required
    +        if ( ! context.getProperty(INFLUX_DB_QUERY).isSet()
    +           && ! context.hasIncomingConnection() ) {
    +            String error = "The InfluxDB Query processor requires input connection or scheduled InfluxDB query";
    +            getLogger().error(error);
    +            throw new ProcessException(error);
    +        }
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +
    +        String query = null;
    +        String database = null;
    +        TimeUnit queryResultTimeunit = null;
    +        Charset charset = null;
    +        FlowFile outgoingFlowFile = null;
    +
    +        // If there are incoming connections, prepare query params from flow file
    +        if ( context.hasIncomingConnection() ) {
    +            FlowFile incomingFlowFile = session.get();
    +
    +            if ( incomingFlowFile == null && context.hasNonLoopConnection() ) {
    +                return;
    +            }
    +
    +            if ( incomingFlowFile.getSize() == 0) {
    +                getLogger().error("Empty query");
    +                incomingFlowFile = session.putAttribute(incomingFlowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + incomingFlowFile.getSize());
    +                session.transfer(incomingFlowFile, REL_FAILURE);
    +                return;
    +            }
    +
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +            try {
    +                ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +                session.exportTo(incomingFlowFile, baos);
    +                baos.close();
    +                query = new String(baos.toByteArray(), charset);
    +            } catch(IOException ioe) {
    +                getLogger().error("Exception while reading from FlowFile " + ioe.getLocalizedMessage(), ioe);
    +                throw new ProcessException(ioe);
    +            }
    +
    +            database = context.getProperty(DB_NAME).evaluateAttributeExpressions(incomingFlowFile).getValue();
    +            queryResultTimeunit = TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +
    +            outgoingFlowFile = incomingFlowFile;
    +        } else {
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions().getValue());
    --- End diff --
    
    Updated to use flow file for EL.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r176525929
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,199 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement","get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +        FlowFile flowFile = session.get();
    +        if (flowFile == null) {
    +            return;
    +        }
    +        if ( flowFile.getSize() == 0) {
    +            getLogger().error("Empty query");
    +            flowFile = session.putAttribute(flowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + flowFile.getSize());
    +            session.transfer(flowFile, REL_FAILURE);
    +            return;
    +        }
    +
    +        Charset charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(flowFile).getValue());
    +        String database = context.getProperty(DB_NAME).evaluateAttributeExpressions(flowFile).getValue();
    +        TimeUnit queryResultTimeunit =
    +            TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(flowFile).getValue());
    +
    +        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +        session.exportTo(flowFile, baos);
    +        String query = new String(baos.toByteArray(), charset);
    --- End diff --
    
    Just to be safe, you might want to close `baos` before calling `toByteArray()`


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178329293
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,258 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.io.IOException;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_ALLOWED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement", "get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile (preferred) or a scheduled query.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY = new PropertyDescriptor.Builder()
    +            .name("influxdb-query")
    +            .displayName("InfluxDB Query")
    +            .description("The InfluxDB query to execute. "
    +                    + "Note: If there are incoming connections, then the query is created from incoming FlowFile's content and scheduled query is ignored.")
    +            .required(false)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .expressionLanguageSupported(true)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(INFLUX_DB_QUERY);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +        // Either input connection or scheduled query is required
    +        if ( ! context.getProperty(INFLUX_DB_QUERY).isSet()
    +           && ! context.hasIncomingConnection() ) {
    +            String error = "The InfluxDB Query processor requires input connection or scheduled InfluxDB query";
    +            getLogger().error(error);
    +            throw new ProcessException(error);
    +        }
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +
    +        String query = null;
    +        String database = null;
    +        TimeUnit queryResultTimeunit = null;
    +        Charset charset = null;
    +        FlowFile outgoingFlowFile = null;
    +
    +        // If there are incoming connections, prepare query params from flow file
    +        if ( context.hasIncomingConnection() ) {
    +            FlowFile incomingFlowFile = session.get();
    +
    +            if ( incomingFlowFile == null && context.hasNonLoopConnection() ) {
    +                return;
    +            }
    +
    +            if ( incomingFlowFile.getSize() == 0) {
    +                getLogger().error("Empty query");
    +                incomingFlowFile = session.putAttribute(incomingFlowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + incomingFlowFile.getSize());
    +                session.transfer(incomingFlowFile, REL_FAILURE);
    +                return;
    +            }
    +
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +            try {
    +                ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +                session.exportTo(incomingFlowFile, baos);
    +                baos.close();
    +                query = new String(baos.toByteArray(), charset);
    +            } catch(IOException ioe) {
    +                getLogger().error("Exception while reading from FlowFile " + ioe.getLocalizedMessage(), ioe);
    +                throw new ProcessException(ioe);
    +            }
    +
    +            database = context.getProperty(DB_NAME).evaluateAttributeExpressions(incomingFlowFile).getValue();
    +            queryResultTimeunit = TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +
    +            outgoingFlowFile = incomingFlowFile;
    +        } else {
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions().getValue());
    +            query = context.getProperty(INFLUX_DB_QUERY).evaluateAttributeExpressions().getValue();
    +            database = context.getProperty(DB_NAME).evaluateAttributeExpressions().getValue();
    +            queryResultTimeunit = TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions().getValue());
    +
    +            outgoingFlowFile = session.create();
    +        }
    +
    +        try {
    +            long startTimeMillis = System.currentTimeMillis();
    +            QueryResult result = executeQuery(context, database, query, queryResultTimeunit);
    +
    +            if ( result == null ) {
    +                String message = "Query Result was " + result;
    +                getLogger().error(message);
    +                throw new NullPointerException(message);
    +            }
    +
    +            String json = gson.toJson(result);
    +
    +            if ( getLogger().isDebugEnabled() ) {
    +                getLogger().debug("Query result {} ", new Object[] {result});
    +            }
    +
    +            ByteArrayInputStream bais = new ByteArrayInputStream(json.getBytes(charset));
    +            session.importFrom(bais, outgoingFlowFile);
    +            bais.close();
    +
    +            final long endTimeMillis = System.currentTimeMillis();
    +
    +            if ( ! result.hasError() ) {
    +                outgoingFlowFile = session.putAttribute(outgoingFlowFile, INFLUX_DB_EXECUTED_QUERY, String.valueOf(query));
    --- End diff --
    
    You might want to put this on the failure scenario too because there could be syntax errors getting reported. This is especially going to be helpful if the user is dynamically generating the query.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178480144
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/test/java/org/apache/nifi/processors/influxdb/AbstractITInfluxDB.java ---
    @@ -0,0 +1,84 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.util.TestRunner;
    +import org.influxdb.InfluxDB;
    +import org.influxdb.InfluxDBFactory;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import org.junit.After;
    +
    +/**
    + * Base integration test class for InfluxDB processors
    + */
    +public class AbstractITInfluxDB {
    +    protected TestRunner runner;
    +    protected InfluxDB influxDB;
    +    protected String dbName = "test";
    +    protected String dbUrl = "http://localhost:8086";
    +    protected String user = "admin";
    +    protected String password = "admin";
    +    protected static final String DEFAULT_RETENTION_POLICY = "autogen";
    +
    +    protected void initInfluxDB() throws InterruptedException, Exception {
    +        influxDB = InfluxDBFactory.connect(dbUrl,user,password);
    +        cleanUpDatabase();
    --- End diff --
    
    Removed as recommended.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r176529115
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/test/java/org/apache/nifi/processors/influxdb/ITExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,163 @@
    +/*
    + * 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.influxdb;
    +import static org.junit.Assert.assertEquals;
    +import java.util.List;
    +import java.util.concurrent.TimeUnit;
    +
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.util.MockFlowFile;
    +import org.apache.nifi.util.TestRunners;
    +import org.influxdb.InfluxDB;
    +import org.influxdb.dto.QueryResult;
    +import org.junit.Before;
    +import org.junit.Test;
    +
    +/**
    + * Integration test for executing InfluxDB queries. Please ensure that the InfluxDB is running
    + * on local host with default port and has database test with table test. Please set user
    + * and password if applicable before running the integration tests.
    + */
    +public class ITExecuteInfluxDBQuery extends AbstractITInfluxDB {
    +
    +    @Before
    +    public void setUp() throws Exception {
    +        runner = TestRunners.newTestRunner(ExecuteInfluxDBQuery.class);
    +        initializeRunner();
    --- End diff --
    
    This can be merged into the other init function. It should at least come after the database init code so that you don't spend any time spinning up testing infra on the NiFi side if the database isn't working.


---

[GitHub] nifi issue #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on the issue:

    https://github.com/apache/nifi/pull/2562
  
    @MikeThomsen  @joewitt - Thanks for your help in making this contribution possible.
    
    @timhallinflux - Please let me know if you have any additional enhancements possible.  I will contact you 
    via email.
    
    Thanks again everyone.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r179012098
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/test/java/org/apache/nifi/processors/influxdb/ITExecuteInfluxDBQuery.java ---
    @@ -110,8 +125,72 @@ public void testCreateDB() {
             assertEquals("Value should be equal",null, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_ERROR_MESSAGE));
             assertEquals("Value should be equal",query, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY));
     
    -        flowFiles.get(0).assertContentEquals("{\"results\":[{}]}");
    +        QueryResult queryResult = gson.fromJson(new StringReader(new String(flowFiles.get(0).toByteArray())), QueryResult.class);
    +        assertEquals("results array should be empty", 1, queryResult.getResults().size());
    +        assertEquals("No series", null, queryResult.getResults().get(0).getSeries());
    --- End diff --
    
    Corrected.


---

[GitHub] nifi issue #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on the issue:

    https://github.com/apache/nifi/pull/2562
  
    @timhallinflux @mans2singh already provided a decent enough Docker Compose test for it. So unless @joewitt or someone else sees something that I missed that's a show stopper, I think we're good to go on merging this to master when 1.6 is released into the wild.


---

[GitHub] nifi issue #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on the issue:

    https://github.com/apache/nifi/pull/2562
  
    @timhallinflux if you don't mind, please take some time to think about additional NiFi-related use cases and either post them to the dev mailing list or add them as Jira tickets.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r176974557
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,199 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    --- End diff --
    
    Added support for timer based queries based on ExecuteSQL processesor as you had recommended and updated test cases.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178790103
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/test/java/org/apache/nifi/processors/influxdb/ITExecuteInfluxDBQuery.java ---
    @@ -110,8 +125,72 @@ public void testCreateDB() {
             assertEquals("Value should be equal",null, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_ERROR_MESSAGE));
             assertEquals("Value should be equal",query, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY));
     
    -        flowFiles.get(0).assertContentEquals("{\"results\":[{}]}");
    +        QueryResult queryResult = gson.fromJson(new StringReader(new String(flowFiles.get(0).toByteArray())), QueryResult.class);
    +        assertEquals("results array should be empty", 1, queryResult.getResults().size());
    +        assertEquals("No series", null, queryResult.getResults().get(0).getSeries());
    --- End diff --
    
    Let's use `assertNull` here to make it a bit more readable.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r176526847
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,199 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement","get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +        FlowFile flowFile = session.get();
    +        if (flowFile == null) {
    +            return;
    +        }
    +        if ( flowFile.getSize() == 0) {
    +            getLogger().error("Empty query");
    +            flowFile = session.putAttribute(flowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + flowFile.getSize());
    +            session.transfer(flowFile, REL_FAILURE);
    +            return;
    +        }
    +
    +        Charset charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(flowFile).getValue());
    +        String database = context.getProperty(DB_NAME).evaluateAttributeExpressions(flowFile).getValue();
    +        TimeUnit queryResultTimeunit =
    +            TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(flowFile).getValue());
    +
    +        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +        session.exportTo(flowFile, baos);
    +        String query = new String(baos.toByteArray(), charset);
    +
    +        try {
    +            long startTimeMillis = System.currentTimeMillis();
    +            QueryResult result = executeQuery(context, database, query, queryResultTimeunit);
    +            String json = gson.toJson(result);
    +
    +            if ( getLogger().isDebugEnabled() ) {
    +                getLogger().debug("Query result {} ", new Object[] {result});
    +            }
    +
    +            ByteArrayInputStream bais = new ByteArrayInputStream(json.getBytes(charset));
    +            session.importFrom(bais, flowFile);
    +            final long endTimeMillis = System.currentTimeMillis();
    +
    +            if ( ! result.hasError() ) {
    +                flowFile = session.putAttribute(flowFile, INFLUX_DB_EXECUTED_QUERY, String.valueOf(query));
    +                session.transfer(flowFile, REL_SUCCESS);
    +            } else {
    +                flowFile = populateErrorAttributes(session, flowFile, query, result.getError());
    +                session.transfer(flowFile, REL_FAILURE);
    +            }
    +
    +            session.getProvenanceReporter().send(flowFile, new StringBuilder("influxdb://")
    +                .append(context.getProperty(INFLUX_DB_URL).evaluateAttributeExpressions().getValue()).append("/")
    +                .append(database).toString(),
    +                (endTimeMillis - startTimeMillis));
    +        } catch (Exception exception) {
    +            flowFile = populateErrorAttributes(session, flowFile, query, exception.getMessage());
    +            if ( exception.getCause() instanceof SocketTimeoutException ) {
    --- End diff --
    
    Are there any other network exceptions that need to be caught here?


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178480116
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,258 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.io.IOException;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_ALLOWED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement", "get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile (preferred) or a scheduled query.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY = new PropertyDescriptor.Builder()
    +            .name("influxdb-query")
    +            .displayName("InfluxDB Query")
    +            .description("The InfluxDB query to execute. "
    +                    + "Note: If there are incoming connections, then the query is created from incoming FlowFile's content and scheduled query is ignored.")
    +            .required(false)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .expressionLanguageSupported(true)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(INFLUX_DB_QUERY);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +        // Either input connection or scheduled query is required
    +        if ( ! context.getProperty(INFLUX_DB_QUERY).isSet()
    +           && ! context.hasIncomingConnection() ) {
    +            String error = "The InfluxDB Query processor requires input connection or scheduled InfluxDB query";
    +            getLogger().error(error);
    +            throw new ProcessException(error);
    +        }
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +
    +        String query = null;
    +        String database = null;
    +        TimeUnit queryResultTimeunit = null;
    +        Charset charset = null;
    +        FlowFile outgoingFlowFile = null;
    +
    +        // If there are incoming connections, prepare query params from flow file
    +        if ( context.hasIncomingConnection() ) {
    +            FlowFile incomingFlowFile = session.get();
    +
    +            if ( incomingFlowFile == null && context.hasNonLoopConnection() ) {
    +                return;
    +            }
    +
    +            if ( incomingFlowFile.getSize() == 0) {
    +                getLogger().error("Empty query");
    +                incomingFlowFile = session.putAttribute(incomingFlowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + incomingFlowFile.getSize());
    +                session.transfer(incomingFlowFile, REL_FAILURE);
    +                return;
    +            }
    +
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +            try {
    +                ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +                session.exportTo(incomingFlowFile, baos);
    +                baos.close();
    +                query = new String(baos.toByteArray(), charset);
    +            } catch(IOException ioe) {
    +                getLogger().error("Exception while reading from FlowFile " + ioe.getLocalizedMessage(), ioe);
    +                throw new ProcessException(ioe);
    +            }
    +
    +            database = context.getProperty(DB_NAME).evaluateAttributeExpressions(incomingFlowFile).getValue();
    +            queryResultTimeunit = TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +
    +            outgoingFlowFile = incomingFlowFile;
    +        } else {
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions().getValue());
    +            query = context.getProperty(INFLUX_DB_QUERY).evaluateAttributeExpressions().getValue();
    +            database = context.getProperty(DB_NAME).evaluateAttributeExpressions().getValue();
    +            queryResultTimeunit = TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions().getValue());
    +
    +            outgoingFlowFile = session.create();
    +        }
    +
    +        try {
    +            long startTimeMillis = System.currentTimeMillis();
    +            QueryResult result = executeQuery(context, database, query, queryResultTimeunit);
    +
    +            if ( result == null ) {
    +                String message = "Query Result was " + result;
    +                getLogger().error(message);
    +                throw new NullPointerException(message);
    +            }
    +
    +            String json = gson.toJson(result);
    +
    +            if ( getLogger().isDebugEnabled() ) {
    +                getLogger().debug("Query result {} ", new Object[] {result});
    +            }
    +
    +            ByteArrayInputStream bais = new ByteArrayInputStream(json.getBytes(charset));
    +            session.importFrom(bais, outgoingFlowFile);
    +            bais.close();
    +
    +            final long endTimeMillis = System.currentTimeMillis();
    +
    +            if ( ! result.hasError() ) {
    +                outgoingFlowFile = session.putAttribute(outgoingFlowFile, INFLUX_DB_EXECUTED_QUERY, String.valueOf(query));
    +                session.transfer(outgoingFlowFile, REL_SUCCESS);
    +            } else {
    +                outgoingFlowFile = populateErrorAttributes(session, outgoingFlowFile, query, result.getError());
    +                session.transfer(outgoingFlowFile, REL_FAILURE);
    +            }
    +
    +            session.getProvenanceReporter().send(outgoingFlowFile, makeProvenanceUrl(context, database),
    +                (endTimeMillis - startTimeMillis));
    +        } catch (Exception exception) {
    +            outgoingFlowFile = populateErrorAttributes(session, outgoingFlowFile, query, exception.getMessage());
    +            if ( exception.getCause() instanceof SocketTimeoutException ) {
    --- End diff --
    
    The query does not throw any exception - I just added this so that if there is a socket timeout, the flow file is transferred to retry relation rather than failure.


---

[GitHub] nifi issue #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on the issue:

    https://github.com/apache/nifi/pull/2562
  
    @joewitt @MikeThomsen - 
    
    I've updated the code based on your comments.  
    
    I've also added a docker gist [influxdb-compose.xml](https://gist.github.com/mans2singh/5ee90620314d4bcf26d6c65de2540c77#file-influxdb-compose-xml) based on docker compose xml mentioned by @MikeThomsen .  This docker compose starts a local influxdb and runs curl commands to create a `test` database and populate it with a metric every 5 seconds.  To launch it we need to run `docker-compose -f <file-name> up` on the local machine and then we can run the integration tests for the query processor or run Nifi locally with processor configured for scheduled query.
    
    I am also including two templates ([flow file driven](https://gist.github.com/mans2singh/5ee90620314d4bcf26d6c65de2540c77#file-nifi-influxdb-flow-file-driven-template) and [timer driven](https://gist.github.com/mans2singh/5ee90620314d4bcf26d6c65de2540c77#file-nifi-influxdb-scheduled-query-template)) to assist in testing the InfluxDB query processor.
    
    Please let me know if your comments/recommendations.
    
    Thanks again.
    



---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r176528433
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/test/java/org/apache/nifi/processors/influxdb/AbstractITInfluxDB.java ---
    @@ -0,0 +1,79 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.util.TestRunner;
    +import org.influxdb.InfluxDB;
    +import org.influxdb.InfluxDBFactory;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import org.junit.After;
    +
    +/**
    + * Base integration test class for InfluxDB processors
    + */
    +public class AbstractITInfluxDB {
    +    protected TestRunner runner;
    +    protected InfluxDB influxDB;
    +    protected String dbName = "test";
    +    protected String dbUrl = "http://localhost:8086";
    +    protected String user = "admin";
    +    protected String password = "admin";
    +    protected static final String DEFAULT_RETENTION_POLICY = "autogen";
    +
    +    protected void initInfluxDB() throws InterruptedException, Exception {
    +        influxDB = InfluxDBFactory.connect(dbUrl,user,password);
    +        if ( influxDB.databaseExists(dbName) ) {
    --- End diff --
    
    I would strongly suggest moving this to the `@After` section because it'll make everything behave in one clean arc of setup -> test -> cleanup.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178328792
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,258 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.io.IOException;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_ALLOWED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement", "get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile (preferred) or a scheduled query.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY = new PropertyDescriptor.Builder()
    +            .name("influxdb-query")
    +            .displayName("InfluxDB Query")
    +            .description("The InfluxDB query to execute. "
    +                    + "Note: If there are incoming connections, then the query is created from incoming FlowFile's content and scheduled query is ignored.")
    +            .required(false)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .expressionLanguageSupported(true)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(INFLUX_DB_QUERY);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +        // Either input connection or scheduled query is required
    +        if ( ! context.getProperty(INFLUX_DB_QUERY).isSet()
    +           && ! context.hasIncomingConnection() ) {
    +            String error = "The InfluxDB Query processor requires input connection or scheduled InfluxDB query";
    +            getLogger().error(error);
    +            throw new ProcessException(error);
    +        }
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +
    +        String query = null;
    +        String database = null;
    +        TimeUnit queryResultTimeunit = null;
    +        Charset charset = null;
    +        FlowFile outgoingFlowFile = null;
    +
    +        // If there are incoming connections, prepare query params from flow file
    +        if ( context.hasIncomingConnection() ) {
    +            FlowFile incomingFlowFile = session.get();
    +
    +            if ( incomingFlowFile == null && context.hasNonLoopConnection() ) {
    +                return;
    +            }
    +
    +            if ( incomingFlowFile.getSize() == 0) {
    +                getLogger().error("Empty query");
    +                incomingFlowFile = session.putAttribute(incomingFlowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + incomingFlowFile.getSize());
    +                session.transfer(incomingFlowFile, REL_FAILURE);
    +                return;
    +            }
    +
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +            try {
    +                ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +                session.exportTo(incomingFlowFile, baos);
    +                baos.close();
    +                query = new String(baos.toByteArray(), charset);
    +            } catch(IOException ioe) {
    +                getLogger().error("Exception while reading from FlowFile " + ioe.getLocalizedMessage(), ioe);
    +                throw new ProcessException(ioe);
    +            }
    +
    +            database = context.getProperty(DB_NAME).evaluateAttributeExpressions(incomingFlowFile).getValue();
    +            queryResultTimeunit = TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +
    +            outgoingFlowFile = incomingFlowFile;
    +        } else {
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions().getValue());
    +            query = context.getProperty(INFLUX_DB_QUERY).evaluateAttributeExpressions().getValue();
    +            database = context.getProperty(DB_NAME).evaluateAttributeExpressions().getValue();
    +            queryResultTimeunit = TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions().getValue());
    +
    +            outgoingFlowFile = session.create();
    +        }
    +
    +        try {
    +            long startTimeMillis = System.currentTimeMillis();
    +            QueryResult result = executeQuery(context, database, query, queryResultTimeunit);
    +
    +            if ( result == null ) {
    +                String message = "Query Result was " + result;
    +                getLogger().error(message);
    +                throw new NullPointerException(message);
    --- End diff --
    
    I don't think this really works, and you said you were pretty sure it won't return a null if it fails. So I'm fine with ripping this out.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178479664
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,258 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.io.IOException;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_ALLOWED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement", "get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile (preferred) or a scheduled query.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY = new PropertyDescriptor.Builder()
    +            .name("influxdb-query")
    +            .displayName("InfluxDB Query")
    +            .description("The InfluxDB query to execute. "
    +                    + "Note: If there are incoming connections, then the query is created from incoming FlowFile's content and scheduled query is ignored.")
    +            .required(false)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .expressionLanguageSupported(true)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(INFLUX_DB_QUERY);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +        // Either input connection or scheduled query is required
    +        if ( ! context.getProperty(INFLUX_DB_QUERY).isSet()
    +           && ! context.hasIncomingConnection() ) {
    +            String error = "The InfluxDB Query processor requires input connection or scheduled InfluxDB query";
    +            getLogger().error(error);
    +            throw new ProcessException(error);
    +        }
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +
    +        String query = null;
    +        String database = null;
    +        TimeUnit queryResultTimeunit = null;
    +        Charset charset = null;
    +        FlowFile outgoingFlowFile = null;
    +
    +        // If there are incoming connections, prepare query params from flow file
    +        if ( context.hasIncomingConnection() ) {
    +            FlowFile incomingFlowFile = session.get();
    +
    +            if ( incomingFlowFile == null && context.hasNonLoopConnection() ) {
    +                return;
    +            }
    +
    +            if ( incomingFlowFile.getSize() == 0) {
    --- End diff --
    
    Changed to use query property if flow file is empty.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r179012073
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/test/java/org/apache/nifi/processors/influxdb/ITExecuteInfluxDBQuery.java ---
    @@ -110,8 +125,72 @@ public void testCreateDB() {
             assertEquals("Value should be equal",null, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_ERROR_MESSAGE));
             assertEquals("Value should be equal",query, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY));
     
    -        flowFiles.get(0).assertContentEquals("{\"results\":[{}]}");
    +        QueryResult queryResult = gson.fromJson(new StringReader(new String(flowFiles.get(0).toByteArray())), QueryResult.class);
    +        assertEquals("results array should be empty", 1, queryResult.getResults().size());
    --- End diff --
    
    Corrected.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178791295
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/test/java/org/apache/nifi/processors/influxdb/TestExecutetInfluxDBQuery.java ---
    @@ -126,27 +131,28 @@ protected QueryResult executeQuery(ProcessContext context, String database, Stri
             byte [] bytes = "select * from /.*/".getBytes();
    --- End diff --
    
    You can do `runner.enqueue("select * from /.*/")` if you want.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r176526183
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,199 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement","get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +        FlowFile flowFile = session.get();
    +        if (flowFile == null) {
    +            return;
    +        }
    +        if ( flowFile.getSize() == 0) {
    +            getLogger().error("Empty query");
    +            flowFile = session.putAttribute(flowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + flowFile.getSize());
    +            session.transfer(flowFile, REL_FAILURE);
    +            return;
    +        }
    +
    +        Charset charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(flowFile).getValue());
    +        String database = context.getProperty(DB_NAME).evaluateAttributeExpressions(flowFile).getValue();
    +        TimeUnit queryResultTimeunit =
    +            TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(flowFile).getValue());
    +
    +        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +        session.exportTo(flowFile, baos);
    +        String query = new String(baos.toByteArray(), charset);
    +
    +        try {
    +            long startTimeMillis = System.currentTimeMillis();
    +            QueryResult result = executeQuery(context, database, query, queryResultTimeunit);
    +            String json = gson.toJson(result);
    --- End diff --
    
    Can you be sure that this will not be null and do you need to check for that?


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r176527325
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,199 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement","get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +        FlowFile flowFile = session.get();
    +        if (flowFile == null) {
    +            return;
    +        }
    +        if ( flowFile.getSize() == 0) {
    +            getLogger().error("Empty query");
    +            flowFile = session.putAttribute(flowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + flowFile.getSize());
    +            session.transfer(flowFile, REL_FAILURE);
    +            return;
    +        }
    +
    +        Charset charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(flowFile).getValue());
    +        String database = context.getProperty(DB_NAME).evaluateAttributeExpressions(flowFile).getValue();
    +        TimeUnit queryResultTimeunit =
    +            TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(flowFile).getValue());
    +
    +        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +        session.exportTo(flowFile, baos);
    +        String query = new String(baos.toByteArray(), charset);
    +
    +        try {
    +            long startTimeMillis = System.currentTimeMillis();
    +            QueryResult result = executeQuery(context, database, query, queryResultTimeunit);
    +            String json = gson.toJson(result);
    +
    +            if ( getLogger().isDebugEnabled() ) {
    +                getLogger().debug("Query result {} ", new Object[] {result});
    +            }
    +
    +            ByteArrayInputStream bais = new ByteArrayInputStream(json.getBytes(charset));
    +            session.importFrom(bais, flowFile);
    +            final long endTimeMillis = System.currentTimeMillis();
    +
    +            if ( ! result.hasError() ) {
    +                flowFile = session.putAttribute(flowFile, INFLUX_DB_EXECUTED_QUERY, String.valueOf(query));
    +                session.transfer(flowFile, REL_SUCCESS);
    +            } else {
    +                flowFile = populateErrorAttributes(session, flowFile, query, result.getError());
    +                session.transfer(flowFile, REL_FAILURE);
    +            }
    +
    +            session.getProvenanceReporter().send(flowFile, new StringBuilder("influxdb://")
    +                .append(context.getProperty(INFLUX_DB_URL).evaluateAttributeExpressions().getValue()).append("/")
    +                .append(database).toString(),
    +                (endTimeMillis - startTimeMillis));
    +        } catch (Exception exception) {
    +            flowFile = populateErrorAttributes(session, flowFile, query, exception.getMessage());
    +            if ( exception.getCause() instanceof SocketTimeoutException ) {
    +                getLogger().error("Failed to read from influxDB due SocketTimeoutException to {} and retrying",
    +                        new Object[]{exception.getLocalizedMessage()}, exception);
    +                session.transfer(flowFile, REL_RETRY);
    +            } else {
    +                getLogger().error("Failed to read from influxDB due to {}",
    +                        new Object[]{exception.getLocalizedMessage()}, exception);
    +                session.transfer(flowFile, REL_FAILURE);
    +            }
    +            context.yield();
    +        }
    +    }
    +
    +    protected QueryResult executeQuery(final ProcessContext context, String database, String query, TimeUnit timeunit) {
    +        return getInfluxDB(context).query(new Query(query, database),timeunit);
    +    }
    +
    +    protected FlowFile populateErrorAttributes(final ProcessSession session, FlowFile flowFile, String query,
    +            String message) {
    +        Map<String,String> attributes = new HashMap<>();
    +        attributes.put(INFLUX_DB_ERROR_MESSAGE, String.valueOf(message));
    --- End diff --
    
    What are you using `String.valueOf` here?


---

[GitHub] nifi issue #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on the issue:

    https://github.com/apache/nifi/pull/2562
  
    @MikeThomsen - I've updated the code based on your comments (added check for query result null, changed scheduled query property name).  One note, if we use the influxdb-compose.xml file for integration testing, we will need to change the name of the db (from test to something else) which the curl loader uses, since integration test use their own data.
    
    Please let me know your thoughts/recommendations.
    
    Thanks.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r176974419
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,199 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement","get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    --- End diff --
    
    Let me know if you have any recommendation for this.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178790398
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/test/java/org/apache/nifi/processors/influxdb/ITExecuteInfluxDBQuery.java ---
    @@ -110,8 +125,72 @@ public void testCreateDB() {
             assertEquals("Value should be equal",null, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_ERROR_MESSAGE));
             assertEquals("Value should be equal",query, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY));
     
    -        flowFiles.get(0).assertContentEquals("{\"results\":[{}]}");
    +        QueryResult queryResult = gson.fromJson(new StringReader(new String(flowFiles.get(0).toByteArray())), QueryResult.class);
    +        assertEquals("results array should be empty", 1, queryResult.getResults().size());
    --- End diff --
    
    I think it would be a good addition to have: `assertNotNull(queryResult.getResults())` before this.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178479729
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,258 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.io.IOException;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_ALLOWED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement", "get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile (preferred) or a scheduled query.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY = new PropertyDescriptor.Builder()
    +            .name("influxdb-query")
    +            .displayName("InfluxDB Query")
    +            .description("The InfluxDB query to execute. "
    +                    + "Note: If there are incoming connections, then the query is created from incoming FlowFile's content and scheduled query is ignored.")
    +            .required(false)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .expressionLanguageSupported(true)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(INFLUX_DB_QUERY);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +        // Either input connection or scheduled query is required
    +        if ( ! context.getProperty(INFLUX_DB_QUERY).isSet()
    +           && ! context.hasIncomingConnection() ) {
    +            String error = "The InfluxDB Query processor requires input connection or scheduled InfluxDB query";
    +            getLogger().error(error);
    +            throw new ProcessException(error);
    +        }
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +
    +        String query = null;
    +        String database = null;
    +        TimeUnit queryResultTimeunit = null;
    +        Charset charset = null;
    +        FlowFile outgoingFlowFile = null;
    +
    +        // If there are incoming connections, prepare query params from flow file
    +        if ( context.hasIncomingConnection() ) {
    +            FlowFile incomingFlowFile = session.get();
    +
    +            if ( incomingFlowFile == null && context.hasNonLoopConnection() ) {
    +                return;
    +            }
    +
    +            if ( incomingFlowFile.getSize() == 0) {
    +                getLogger().error("Empty query");
    +                incomingFlowFile = session.putAttribute(incomingFlowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + incomingFlowFile.getSize());
    +                session.transfer(incomingFlowFile, REL_FAILURE);
    +                return;
    +            }
    +
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +            try {
    +                ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +                session.exportTo(incomingFlowFile, baos);
    +                baos.close();
    +                query = new String(baos.toByteArray(), charset);
    +            } catch(IOException ioe) {
    +                getLogger().error("Exception while reading from FlowFile " + ioe.getLocalizedMessage(), ioe);
    +                throw new ProcessException(ioe);
    +            }
    +
    +            database = context.getProperty(DB_NAME).evaluateAttributeExpressions(incomingFlowFile).getValue();
    +            queryResultTimeunit = TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +
    +            outgoingFlowFile = incomingFlowFile;
    +        } else {
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions().getValue());
    +            query = context.getProperty(INFLUX_DB_QUERY).evaluateAttributeExpressions().getValue();
    +            database = context.getProperty(DB_NAME).evaluateAttributeExpressions().getValue();
    +            queryResultTimeunit = TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions().getValue());
    +
    +            outgoingFlowFile = session.create();
    +        }
    +
    +        try {
    +            long startTimeMillis = System.currentTimeMillis();
    +            QueryResult result = executeQuery(context, database, query, queryResultTimeunit);
    +
    +            if ( result == null ) {
    +                String message = "Query Result was " + result;
    +                getLogger().error(message);
    +                throw new NullPointerException(message);
    --- End diff --
    
    Removed check for null.


---

[GitHub] nifi issue #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on the issue:

    https://github.com/apache/nifi/pull/2562
  
    Forgot to add that a link to a comprehensive sandbox is appreciated @timhallinflux 


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r177119360
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,199 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement","get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +        FlowFile flowFile = session.get();
    +        if (flowFile == null) {
    +            return;
    +        }
    +        if ( flowFile.getSize() == 0) {
    +            getLogger().error("Empty query");
    +            flowFile = session.putAttribute(flowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + flowFile.getSize());
    +            session.transfer(flowFile, REL_FAILURE);
    +            return;
    +        }
    +
    +        Charset charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(flowFile).getValue());
    +        String database = context.getProperty(DB_NAME).evaluateAttributeExpressions(flowFile).getValue();
    +        TimeUnit queryResultTimeunit =
    +            TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(flowFile).getValue());
    +
    +        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +        session.exportTo(flowFile, baos);
    +        String query = new String(baos.toByteArray(), charset);
    +
    +        try {
    +            long startTimeMillis = System.currentTimeMillis();
    +            QueryResult result = executeQuery(context, database, query, queryResultTimeunit);
    +            String json = gson.toJson(result);
    --- End diff --
    
    If you're pretty confident that the client API isn't going to surprise you with a null response, I'm fine with that.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r179012036
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/test/java/org/apache/nifi/processors/influxdb/ITExecuteInfluxDBQuery.java ---
    @@ -110,8 +125,72 @@ public void testCreateDB() {
             assertEquals("Value should be equal",null, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_ERROR_MESSAGE));
             assertEquals("Value should be equal",query, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY));
     
    -        flowFiles.get(0).assertContentEquals("{\"results\":[{}]}");
    +        QueryResult queryResult = gson.fromJson(new StringReader(new String(flowFiles.get(0).toByteArray())), QueryResult.class);
    +        assertEquals("results array should be empty", 1, queryResult.getResults().size());
    +        assertEquals("No series", null, queryResult.getResults().get(0).getSeries());
    +    }
    +
    +    @Test
    +    public void testEmptyFlowFileQueryWithScheduledQuery() {
    +        String message = "water,country=US,city=newark rain=1,humidity=0.6 1501002274856668652";
    +        influxDB.write(dbName, DEFAULT_RETENTION_POLICY, InfluxDB.ConsistencyLevel.ONE, message);
    +
    +        String query = "select * from water";
    +        runner.setProperty(ExecuteInfluxDBQuery.INFLUX_DB_QUERY, query);
    +
    +        byte [] bytes = new byte [] {};
    +        runner.enqueue(bytes);
    +        runner.run(1,true,true);
    +        runner.assertAllFlowFilesTransferred(ExecuteInfluxDBQuery.REL_SUCCESS, 1);
    +
    +        List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(ExecuteInfluxDBQuery.REL_SUCCESS);
    +        assertEquals("Value should be equal", 1, flowFiles.size());
    +        assertEquals("Value should be equal",null, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_ERROR_MESSAGE));
    --- End diff --
    
    Corrected.


---

[GitHub] nifi issue #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on the issue:

    https://github.com/apache/nifi/pull/2562
  
    Thanks @MikeThomsen for your reveiw/advice.  Also thanks @timhallinflux for the pointers on influxdb sandbox.
    
    Please let me know if there is other feedback.
    
    Mans


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178330604
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/test/java/org/apache/nifi/processors/influxdb/ITExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,231 @@
    +/*
    + * 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.influxdb;
    +import static org.junit.Assert.assertEquals;
    +import org.junit.Assert;
    +import java.util.List;
    +import java.util.concurrent.TimeUnit;
    +
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.util.MockFlowFile;
    +import org.apache.nifi.util.TestRunners;
    +import org.influxdb.InfluxDB;
    +import org.influxdb.dto.QueryResult;
    +import org.junit.Before;
    +import org.junit.Test;
    +
    +/**
    + * Integration test for executing InfluxDB queries. Please ensure that the InfluxDB is running
    + * on local host with default port and has database test with table test. Please set user
    + * and password if applicable before running the integration tests.
    + */
    +public class ITExecuteInfluxDBQuery extends AbstractITInfluxDB {
    +
    +    @Before
    +    public void setUp() throws Exception {
    +        initInfluxDB();
    +        runner = TestRunners.newTestRunner(ExecuteInfluxDBQuery.class);
    +        initializeRunner();
    +    }
    +
    +    @Test
    +    public void testValidScheduleQueryWithNoIncoming() {
    +        String message = "water,country=US,city=newark rain=1,humidity=0.6 1501002274856668652";
    +        influxDB.write(dbName, DEFAULT_RETENTION_POLICY, InfluxDB.ConsistencyLevel.ONE, message);
    +
    +        String query = "select * from water";
    +        runner.setProperty(ExecuteInfluxDBQuery.INFLUX_DB_QUERY, query);
    +
    +        runner.setIncomingConnection(false);
    +        runner.run(1,true,true);
    +        runner.assertAllFlowFilesTransferred(ExecuteInfluxDBQuery.REL_SUCCESS, 1);
    +        List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(ExecuteInfluxDBQuery.REL_SUCCESS);
    +        assertEquals("Value should be equal", 1, flowFiles.size());
    +        assertEquals("Value should be equal",null, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_ERROR_MESSAGE));
    +        assertEquals("Value should be equal",query, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY));
    +        flowFiles.get(0).assertContentEquals(
    --- End diff --
    
    I should also mention that there are Groovy JUnits in the codebase already, so if you want to redo these tests w/ Groovy following other examples that is acceptable. I bring that up mainly because Groovy is a lot cleaner than Java for handling JSON, Maps, etc.


---

[GitHub] nifi issue #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on the issue:

    https://github.com/apache/nifi/pull/2562
  
    @joewitt @mans2singh [Here's a starting point](https://github.com/apache/nifi/pull/2101#issuecomment-361083921) on the Docker/Docker Compose


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178480026
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,258 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.io.IOException;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_ALLOWED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement", "get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile (preferred) or a scheduled query.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY = new PropertyDescriptor.Builder()
    +            .name("influxdb-query")
    +            .displayName("InfluxDB Query")
    +            .description("The InfluxDB query to execute. "
    +                    + "Note: If there are incoming connections, then the query is created from incoming FlowFile's content and scheduled query is ignored.")
    +            .required(false)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .expressionLanguageSupported(true)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(INFLUX_DB_QUERY);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +        // Either input connection or scheduled query is required
    +        if ( ! context.getProperty(INFLUX_DB_QUERY).isSet()
    +           && ! context.hasIncomingConnection() ) {
    +            String error = "The InfluxDB Query processor requires input connection or scheduled InfluxDB query";
    +            getLogger().error(error);
    +            throw new ProcessException(error);
    +        }
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +
    +        String query = null;
    +        String database = null;
    +        TimeUnit queryResultTimeunit = null;
    +        Charset charset = null;
    +        FlowFile outgoingFlowFile = null;
    +
    +        // If there are incoming connections, prepare query params from flow file
    +        if ( context.hasIncomingConnection() ) {
    +            FlowFile incomingFlowFile = session.get();
    +
    +            if ( incomingFlowFile == null && context.hasNonLoopConnection() ) {
    +                return;
    +            }
    +
    +            if ( incomingFlowFile.getSize() == 0) {
    +                getLogger().error("Empty query");
    +                incomingFlowFile = session.putAttribute(incomingFlowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + incomingFlowFile.getSize());
    +                session.transfer(incomingFlowFile, REL_FAILURE);
    +                return;
    +            }
    +
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +            try {
    +                ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +                session.exportTo(incomingFlowFile, baos);
    +                baos.close();
    +                query = new String(baos.toByteArray(), charset);
    +            } catch(IOException ioe) {
    +                getLogger().error("Exception while reading from FlowFile " + ioe.getLocalizedMessage(), ioe);
    +                throw new ProcessException(ioe);
    +            }
    +
    +            database = context.getProperty(DB_NAME).evaluateAttributeExpressions(incomingFlowFile).getValue();
    +            queryResultTimeunit = TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +
    +            outgoingFlowFile = incomingFlowFile;
    +        } else {
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions().getValue());
    +            query = context.getProperty(INFLUX_DB_QUERY).evaluateAttributeExpressions().getValue();
    +            database = context.getProperty(DB_NAME).evaluateAttributeExpressions().getValue();
    +            queryResultTimeunit = TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions().getValue());
    +
    +            outgoingFlowFile = session.create();
    +        }
    +
    +        try {
    +            long startTimeMillis = System.currentTimeMillis();
    +            QueryResult result = executeQuery(context, database, query, queryResultTimeunit);
    +
    +            if ( result == null ) {
    +                String message = "Query Result was " + result;
    +                getLogger().error(message);
    +                throw new NullPointerException(message);
    +            }
    +
    +            String json = gson.toJson(result);
    +
    +            if ( getLogger().isDebugEnabled() ) {
    +                getLogger().debug("Query result {} ", new Object[] {result});
    +            }
    +
    +            ByteArrayInputStream bais = new ByteArrayInputStream(json.getBytes(charset));
    +            session.importFrom(bais, outgoingFlowFile);
    +            bais.close();
    +
    +            final long endTimeMillis = System.currentTimeMillis();
    +
    +            if ( ! result.hasError() ) {
    +                outgoingFlowFile = session.putAttribute(outgoingFlowFile, INFLUX_DB_EXECUTED_QUERY, String.valueOf(query));
    --- End diff --
    
    If there is any error the `hasError` returns true and the flow file is transferred to success.  Let me know if I've missed anything.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r176974725
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/test/java/org/apache/nifi/processors/influxdb/AbstractITInfluxDB.java ---
    @@ -0,0 +1,79 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.util.TestRunner;
    +import org.influxdb.InfluxDB;
    +import org.influxdb.InfluxDBFactory;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import org.junit.After;
    +
    +/**
    + * Base integration test class for InfluxDB processors
    + */
    +public class AbstractITInfluxDB {
    +    protected TestRunner runner;
    +    protected InfluxDB influxDB;
    +    protected String dbName = "test";
    +    protected String dbUrl = "http://localhost:8086";
    +    protected String user = "admin";
    +    protected String password = "admin";
    +    protected static final String DEFAULT_RETENTION_POLICY = "autogen";
    +
    +    protected void initInfluxDB() throws InterruptedException, Exception {
    +        influxDB = InfluxDBFactory.connect(dbUrl,user,password);
    +        if ( influxDB.databaseExists(dbName) ) {
    --- End diff --
    
    I've refactored the code and call it both from `Before` and `After` to make sure that the test setup and tear down is clean.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r177296540
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,199 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement","get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +        FlowFile flowFile = session.get();
    +        if (flowFile == null) {
    +            return;
    +        }
    +        if ( flowFile.getSize() == 0) {
    +            getLogger().error("Empty query");
    +            flowFile = session.putAttribute(flowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + flowFile.getSize());
    +            session.transfer(flowFile, REL_FAILURE);
    +            return;
    +        }
    +
    +        Charset charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(flowFile).getValue());
    +        String database = context.getProperty(DB_NAME).evaluateAttributeExpressions(flowFile).getValue();
    +        TimeUnit queryResultTimeunit =
    +            TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(flowFile).getValue());
    +
    +        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +        session.exportTo(flowFile, baos);
    +        String query = new String(baos.toByteArray(), charset);
    +
    +        try {
    +            long startTimeMillis = System.currentTimeMillis();
    +            QueryResult result = executeQuery(context, database, query, queryResultTimeunit);
    +            String json = gson.toJson(result);
    --- End diff --
    
    Added check for null and unit test to support it.


---

[GitHub] nifi issue #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on the issue:

    https://github.com/apache/nifi/pull/2562
  
    @mans2singh I went to merge your changes this morning and found that you have some integration tests that are broken now with the changes made to EL support in the `PropertyDescriptor.Builder` class. It seems your breakage is limited mainly here:
    
    ```
    protected String makeProvenanceUrl(final ProcessContext context, String database, FlowFile flowFile) {
        return new StringBuilder("influxdb://")
            .append(context.getProperty(INFLUX_DB_URL).evaluateAttributeExpressions(flowFile).getValue()).append("/")
            .append(database).toString();
    }
    ```
    
    You marked that property as `VARIABLE_REGISTRY` and it is failing because you're applying it flowfiles. The existing calls to `expressionLanguageSupported(boolean)` in the abstract class also need to be fixed.
    
    So just do a rebase against the latest master and take care of those. If there are no regressions after your commit (ie your flows and tests run) IMO we're ready to merge.


---

[GitHub] nifi issue #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on the issue:

    https://github.com/apache/nifi/pull/2562
  
    Verified that both flows work against the Docker Compose configuration. Looking very good so far.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178330089
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/test/java/org/apache/nifi/processors/influxdb/AbstractITInfluxDB.java ---
    @@ -0,0 +1,84 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.util.TestRunner;
    +import org.influxdb.InfluxDB;
    +import org.influxdb.InfluxDBFactory;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import org.junit.After;
    +
    +/**
    + * Base integration test class for InfluxDB processors
    + */
    +public class AbstractITInfluxDB {
    +    protected TestRunner runner;
    +    protected InfluxDB influxDB;
    +    protected String dbName = "test";
    +    protected String dbUrl = "http://localhost:8086";
    +    protected String user = "admin";
    +    protected String password = "admin";
    +    protected static final String DEFAULT_RETENTION_POLICY = "autogen";
    +
    +    protected void initInfluxDB() throws InterruptedException, Exception {
    +        influxDB = InfluxDBFactory.connect(dbUrl,user,password);
    +        cleanUpDatabase();
    --- End diff --
    
    Not needed.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r176974361
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,199 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement","get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +        FlowFile flowFile = session.get();
    +        if (flowFile == null) {
    +            return;
    +        }
    +        if ( flowFile.getSize() == 0) {
    +            getLogger().error("Empty query");
    +            flowFile = session.putAttribute(flowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + flowFile.getSize());
    +            session.transfer(flowFile, REL_FAILURE);
    +            return;
    +        }
    +
    +        Charset charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(flowFile).getValue());
    +        String database = context.getProperty(DB_NAME).evaluateAttributeExpressions(flowFile).getValue();
    +        TimeUnit queryResultTimeunit =
    +            TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(flowFile).getValue());
    +
    +        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +        session.exportTo(flowFile, baos);
    +        String query = new String(baos.toByteArray(), charset);
    +
    +        try {
    +            long startTimeMillis = System.currentTimeMillis();
    +            QueryResult result = executeQuery(context, database, query, queryResultTimeunit);
    +            String json = gson.toJson(result);
    +
    +            if ( getLogger().isDebugEnabled() ) {
    +                getLogger().debug("Query result {} ", new Object[] {result});
    +            }
    +
    +            ByteArrayInputStream bais = new ByteArrayInputStream(json.getBytes(charset));
    +            session.importFrom(bais, flowFile);
    +            final long endTimeMillis = System.currentTimeMillis();
    +
    +            if ( ! result.hasError() ) {
    +                flowFile = session.putAttribute(flowFile, INFLUX_DB_EXECUTED_QUERY, String.valueOf(query));
    +                session.transfer(flowFile, REL_SUCCESS);
    +            } else {
    +                flowFile = populateErrorAttributes(session, flowFile, query, result.getError());
    +                session.transfer(flowFile, REL_FAILURE);
    +            }
    +
    +            session.getProvenanceReporter().send(flowFile, new StringBuilder("influxdb://")
    --- End diff --
    
    Refactored the string building to a method.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r176526551
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,199 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement","get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +        FlowFile flowFile = session.get();
    +        if (flowFile == null) {
    +            return;
    +        }
    +        if ( flowFile.getSize() == 0) {
    +            getLogger().error("Empty query");
    +            flowFile = session.putAttribute(flowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + flowFile.getSize());
    +            session.transfer(flowFile, REL_FAILURE);
    +            return;
    +        }
    +
    +        Charset charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(flowFile).getValue());
    +        String database = context.getProperty(DB_NAME).evaluateAttributeExpressions(flowFile).getValue();
    +        TimeUnit queryResultTimeunit =
    +            TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(flowFile).getValue());
    +
    +        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +        session.exportTo(flowFile, baos);
    +        String query = new String(baos.toByteArray(), charset);
    +
    +        try {
    +            long startTimeMillis = System.currentTimeMillis();
    +            QueryResult result = executeQuery(context, database, query, queryResultTimeunit);
    +            String json = gson.toJson(result);
    +
    +            if ( getLogger().isDebugEnabled() ) {
    +                getLogger().debug("Query result {} ", new Object[] {result});
    +            }
    +
    +            ByteArrayInputStream bais = new ByteArrayInputStream(json.getBytes(charset));
    +            session.importFrom(bais, flowFile);
    +            final long endTimeMillis = System.currentTimeMillis();
    +
    +            if ( ! result.hasError() ) {
    +                flowFile = session.putAttribute(flowFile, INFLUX_DB_EXECUTED_QUERY, String.valueOf(query));
    +                session.transfer(flowFile, REL_SUCCESS);
    +            } else {
    +                flowFile = populateErrorAttributes(session, flowFile, query, result.getError());
    +                session.transfer(flowFile, REL_FAILURE);
    +            }
    +
    +            session.getProvenanceReporter().send(flowFile, new StringBuilder("influxdb://")
    --- End diff --
    
    the `StringBuilder` part should be turned into a method call or broken up to make it easier to read, especially from within a debugger.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178479805
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,258 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.io.IOException;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_ALLOWED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement", "get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile (preferred) or a scheduled query.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY = new PropertyDescriptor.Builder()
    +            .name("influxdb-query")
    +            .displayName("InfluxDB Query")
    +            .description("The InfluxDB query to execute. "
    +                    + "Note: If there are incoming connections, then the query is created from incoming FlowFile's content and scheduled query is ignored.")
    +            .required(false)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .expressionLanguageSupported(true)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(INFLUX_DB_QUERY);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +        // Either input connection or scheduled query is required
    +        if ( ! context.getProperty(INFLUX_DB_QUERY).isSet()
    +           && ! context.hasIncomingConnection() ) {
    +            String error = "The InfluxDB Query processor requires input connection or scheduled InfluxDB query";
    +            getLogger().error(error);
    +            throw new ProcessException(error);
    +        }
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +
    +        String query = null;
    +        String database = null;
    +        TimeUnit queryResultTimeunit = null;
    +        Charset charset = null;
    +        FlowFile outgoingFlowFile = null;
    +
    +        // If there are incoming connections, prepare query params from flow file
    +        if ( context.hasIncomingConnection() ) {
    +            FlowFile incomingFlowFile = session.get();
    +
    +            if ( incomingFlowFile == null && context.hasNonLoopConnection() ) {
    +                return;
    +            }
    +
    +            if ( incomingFlowFile.getSize() == 0) {
    +                getLogger().error("Empty query");
    +                incomingFlowFile = session.putAttribute(incomingFlowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + incomingFlowFile.getSize());
    +                session.transfer(incomingFlowFile, REL_FAILURE);
    +                return;
    +            }
    +
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +            try {
    +                ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +                session.exportTo(incomingFlowFile, baos);
    +                baos.close();
    +                query = new String(baos.toByteArray(), charset);
    +            } catch(IOException ioe) {
    +                getLogger().error("Exception while reading from FlowFile " + ioe.getLocalizedMessage(), ioe);
    +                throw new ProcessException(ioe);
    +            }
    +
    +            database = context.getProperty(DB_NAME).evaluateAttributeExpressions(incomingFlowFile).getValue();
    +            queryResultTimeunit = TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +
    +            outgoingFlowFile = incomingFlowFile;
    +        } else {
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions().getValue());
    +            query = context.getProperty(INFLUX_DB_QUERY).evaluateAttributeExpressions().getValue();
    +            database = context.getProperty(DB_NAME).evaluateAttributeExpressions().getValue();
    +            queryResultTimeunit = TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions().getValue());
    +
    +            outgoingFlowFile = session.create();
    +        }
    +
    +        try {
    +            long startTimeMillis = System.currentTimeMillis();
    +            QueryResult result = executeQuery(context, database, query, queryResultTimeunit);
    +
    +            if ( result == null ) {
    +                String message = "Query Result was " + result;
    +                getLogger().error(message);
    +                throw new NullPointerException(message);
    +            }
    +
    +            String json = gson.toJson(result);
    +
    +            if ( getLogger().isDebugEnabled() ) {
    +                getLogger().debug("Query result {} ", new Object[] {result});
    +            }
    +
    +            ByteArrayInputStream bais = new ByteArrayInputStream(json.getBytes(charset));
    +            session.importFrom(bais, outgoingFlowFile);
    +            bais.close();
    +
    +            final long endTimeMillis = System.currentTimeMillis();
    +
    +            if ( ! result.hasError() ) {
    +                outgoingFlowFile = session.putAttribute(outgoingFlowFile, INFLUX_DB_EXECUTED_QUERY, String.valueOf(query));
    +                session.transfer(outgoingFlowFile, REL_SUCCESS);
    +            } else {
    +                outgoingFlowFile = populateErrorAttributes(session, outgoingFlowFile, query, result.getError());
    +                session.transfer(outgoingFlowFile, REL_FAILURE);
    +            }
    +
    +            session.getProvenanceReporter().send(outgoingFlowFile, makeProvenanceUrl(context, database),
    --- End diff --
    
    Removed provenance for failure scenario.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178329874
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,258 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.io.IOException;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_ALLOWED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement", "get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile (preferred) or a scheduled query.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    +@WritesAttributes({
    +    @WritesAttribute(attribute = AbstractInfluxDBProcessor.INFLUX_DB_ERROR_MESSAGE, description = "InfluxDB error message"),
    +    @WritesAttribute(attribute = ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY, description = "InfluxDB executed query"),
    +    })
    +public class ExecuteInfluxDBQuery extends AbstractInfluxDBProcessor {
    +
    +    public static final String INFLUX_DB_EXECUTED_QUERY = "influxdb.executed.query";
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY_RESULT_TIMEUNIT = new PropertyDescriptor.Builder()
    +            .name("influxdb-query-result-time-unit")
    +            .displayName("Query Result Time Units")
    +            .description("The time unit of query results from the InfluxDB")
    +            .defaultValue(TimeUnit.NANOSECONDS.name())
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .allowableValues(Arrays.stream(TimeUnit.values()).map( v -> v.name()).collect(Collectors.toSet()))
    +            .sensitive(false)
    +            .build();
    +
    +    public static final PropertyDescriptor INFLUX_DB_QUERY = new PropertyDescriptor.Builder()
    +            .name("influxdb-query")
    +            .displayName("InfluxDB Query")
    +            .description("The InfluxDB query to execute. "
    +                    + "Note: If there are incoming connections, then the query is created from incoming FlowFile's content and scheduled query is ignored.")
    +            .required(false)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .expressionLanguageSupported(true)
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder().name("success")
    +            .description("Successful InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_FAILURE = new Relationship.Builder().name("failure")
    +            .description("Falied InfluxDB queries are routed to this relationship").build();
    +
    +    static final Relationship REL_RETRY = new Relationship.Builder().name("retry")
    +            .description("Failed queries that are retryable exception are routed to this relationship").build();
    +
    +    private static final Set<Relationship> relationships;
    +    private static final List<PropertyDescriptor> propertyDescriptors;
    +    protected Gson gson = new Gson();
    +
    +    static {
    +        final Set<Relationship> tempRelationships = new HashSet<>();
    +        tempRelationships.add(REL_SUCCESS);
    +        tempRelationships.add(REL_FAILURE);
    +        tempRelationships.add(REL_RETRY);
    +        relationships = Collections.unmodifiableSet(tempRelationships);
    +        final List<PropertyDescriptor> tempDescriptors = new ArrayList<>();
    +        tempDescriptors.add(DB_NAME);
    +        tempDescriptors.add(INFLUX_DB_URL);
    +        tempDescriptors.add(INFLUX_DB_CONNECTION_TIMEOUT);
    +        tempDescriptors.add(INFLUX_DB_QUERY_RESULT_TIMEUNIT);
    +        tempDescriptors.add(INFLUX_DB_QUERY);
    +        tempDescriptors.add(USERNAME);
    +        tempDescriptors.add(PASSWORD);
    +        tempDescriptors.add(CHARSET);
    +        propertyDescriptors = Collections.unmodifiableList(tempDescriptors);
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return propertyDescriptors;
    +    }
    +
    +    @OnScheduled
    +    public void onScheduled(final ProcessContext context) {
    +        super.onScheduled(context);
    +        // Either input connection or scheduled query is required
    +        if ( ! context.getProperty(INFLUX_DB_QUERY).isSet()
    +           && ! context.hasIncomingConnection() ) {
    +            String error = "The InfluxDB Query processor requires input connection or scheduled InfluxDB query";
    +            getLogger().error(error);
    +            throw new ProcessException(error);
    +        }
    +    }
    +
    +    @Override
    +    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    +
    +        String query = null;
    +        String database = null;
    +        TimeUnit queryResultTimeunit = null;
    +        Charset charset = null;
    +        FlowFile outgoingFlowFile = null;
    +
    +        // If there are incoming connections, prepare query params from flow file
    +        if ( context.hasIncomingConnection() ) {
    +            FlowFile incomingFlowFile = session.get();
    +
    +            if ( incomingFlowFile == null && context.hasNonLoopConnection() ) {
    +                return;
    +            }
    +
    +            if ( incomingFlowFile.getSize() == 0) {
    +                getLogger().error("Empty query");
    +                incomingFlowFile = session.putAttribute(incomingFlowFile, INFLUX_DB_ERROR_MESSAGE, "Empty query size is " + incomingFlowFile.getSize());
    +                session.transfer(incomingFlowFile, REL_FAILURE);
    +                return;
    +            }
    +
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +            try {
    +                ByteArrayOutputStream baos = new ByteArrayOutputStream();
    +                session.exportTo(incomingFlowFile, baos);
    +                baos.close();
    +                query = new String(baos.toByteArray(), charset);
    +            } catch(IOException ioe) {
    +                getLogger().error("Exception while reading from FlowFile " + ioe.getLocalizedMessage(), ioe);
    +                throw new ProcessException(ioe);
    +            }
    +
    +            database = context.getProperty(DB_NAME).evaluateAttributeExpressions(incomingFlowFile).getValue();
    +            queryResultTimeunit = TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions(incomingFlowFile).getValue());
    +
    +            outgoingFlowFile = incomingFlowFile;
    +        } else {
    +            charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions().getValue());
    +            query = context.getProperty(INFLUX_DB_QUERY).evaluateAttributeExpressions().getValue();
    +            database = context.getProperty(DB_NAME).evaluateAttributeExpressions().getValue();
    +            queryResultTimeunit = TimeUnit.valueOf(context.getProperty(INFLUX_DB_QUERY_RESULT_TIMEUNIT).evaluateAttributeExpressions().getValue());
    +
    +            outgoingFlowFile = session.create();
    +        }
    +
    +        try {
    +            long startTimeMillis = System.currentTimeMillis();
    +            QueryResult result = executeQuery(context, database, query, queryResultTimeunit);
    +
    +            if ( result == null ) {
    +                String message = "Query Result was " + result;
    +                getLogger().error(message);
    +                throw new NullPointerException(message);
    +            }
    +
    +            String json = gson.toJson(result);
    +
    +            if ( getLogger().isDebugEnabled() ) {
    +                getLogger().debug("Query result {} ", new Object[] {result});
    +            }
    +
    +            ByteArrayInputStream bais = new ByteArrayInputStream(json.getBytes(charset));
    +            session.importFrom(bais, outgoingFlowFile);
    +            bais.close();
    +
    +            final long endTimeMillis = System.currentTimeMillis();
    +
    +            if ( ! result.hasError() ) {
    +                outgoingFlowFile = session.putAttribute(outgoingFlowFile, INFLUX_DB_EXECUTED_QUERY, String.valueOf(query));
    +                session.transfer(outgoingFlowFile, REL_SUCCESS);
    +            } else {
    +                outgoingFlowFile = populateErrorAttributes(session, outgoingFlowFile, query, result.getError());
    +                session.transfer(outgoingFlowFile, REL_FAILURE);
    +            }
    +
    +            session.getProvenanceReporter().send(outgoingFlowFile, makeProvenanceUrl(context, database),
    +                (endTimeMillis - startTimeMillis));
    +        } catch (Exception exception) {
    +            outgoingFlowFile = populateErrorAttributes(session, outgoingFlowFile, query, exception.getMessage());
    +            if ( exception.getCause() instanceof SocketTimeoutException ) {
    +                getLogger().error("Failed to read from influxDB due SocketTimeoutException to {} and retrying",
    +                        new Object[]{exception.getCause().getLocalizedMessage()}, exception.getCause());
    +                session.transfer(outgoingFlowFile, REL_RETRY);
    +            } else {
    +                getLogger().error("Failed to read from influxDB due to {}",
    +                        new Object[]{exception.getLocalizedMessage()}, exception);
    +                session.transfer(outgoingFlowFile, REL_FAILURE);
    +            }
    +            context.yield();
    +        }
    +    }
    +
    +    protected String makeProvenanceUrl(final ProcessContext context, String database) {
    --- End diff --
    
    Adding a flowfile parameter here would help with the EL support.


---

[GitHub] nifi issue #2562: NIFI-4927 - InfluxDB Query Processor

Posted by timhallinflux <gi...@git.apache.org>.
Github user timhallinflux commented on the issue:

    https://github.com/apache/nifi/pull/2562
  
    Yep.  Working on a blog post to highlight both parts...writer and reader.  
    
    U is not really possible. For D, both DELETE and/or DROP statements are allowed through InfluxQL.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by mans2singh <gi...@git.apache.org>.
Github user mans2singh commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r177296275
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -72,6 +74,16 @@
                 .sensitive(false)
                 .build();
     
    +    public static final PropertyDescriptor INFLUX_DB_SCHEDULED_QUERY = new PropertyDescriptor.Builder()
    +            .name("influxdb-scheduled-query")
    +            .displayName("InfluxDB Schedued Query")
    --- End diff --
    
    Changed the attribute to INFLUX_DB_QUERY.  The description mentions that flow files and timed query both are allowed.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r176524914
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -0,0 +1,199 @@
    +/*
    + * 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.influxdb;
    +import org.apache.nifi.annotation.behavior.EventDriven;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.SupportsBatching;
    +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.annotation.lifecycle.OnStopped;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.influxdb.dto.Query;
    +import org.influxdb.dto.QueryResult;
    +import com.google.gson.Gson;
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.net.SocketTimeoutException;
    +import java.nio.charset.Charset;
    +import java.util.ArrayList;
    +import java.util.Arrays;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.TimeUnit;
    +import java.util.stream.Collectors;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@EventDriven
    +@SupportsBatching
    +@Tags({"influxdb", "measurement","get", "read", "query", "timeseries"})
    +@CapabilityDescription("Processor to execute InfluxDB query from the content of a FlowFile.  Please check details of the supported queries in InfluxDB documentation (https://www.influxdb.com/).")
    --- End diff --
    
    Based on the wording, should a user assume that all influxdb queries are supported or only some?


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r177131556
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/test/java/org/apache/nifi/processors/influxdb/AbstractITInfluxDB.java ---
    @@ -36,14 +36,7 @@
     
         protected void initInfluxDB() throws InterruptedException, Exception {
             influxDB = InfluxDBFactory.connect(dbUrl,user,password);
    -        if ( influxDB.databaseExists(dbName) ) {
    -            QueryResult result = influxDB.query(new Query("DROP measurement water", dbName));
    -            checkError(result);
    -            result = influxDB.query(new Query("DROP measurement testm", dbName));
    -            checkError(result);
    -            result = influxDB.query(new Query("DROP database " + dbName, dbName));
    -            Thread.sleep(1000);
    -        }
    +        cleanUpDatabase();
    --- End diff --
    
    What I meant was that the cleanup functionality shouldn't be called in the init, but should be called from the `@After` annotated method.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178790742
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/test/java/org/apache/nifi/processors/influxdb/ITExecuteInfluxDBQuery.java ---
    @@ -110,8 +125,72 @@ public void testCreateDB() {
             assertEquals("Value should be equal",null, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_ERROR_MESSAGE));
             assertEquals("Value should be equal",query, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY));
     
    -        flowFiles.get(0).assertContentEquals("{\"results\":[{}]}");
    +        QueryResult queryResult = gson.fromJson(new StringReader(new String(flowFiles.get(0).toByteArray())), QueryResult.class);
    +        assertEquals("results array should be empty", 1, queryResult.getResults().size());
    +        assertEquals("No series", null, queryResult.getResults().get(0).getSeries());
    +    }
    +
    +    @Test
    +    public void testEmptyFlowFileQueryWithScheduledQuery() {
    +        String message = "water,country=US,city=newark rain=1,humidity=0.6 1501002274856668652";
    +        influxDB.write(dbName, DEFAULT_RETENTION_POLICY, InfluxDB.ConsistencyLevel.ONE, message);
    +
    +        String query = "select * from water";
    +        runner.setProperty(ExecuteInfluxDBQuery.INFLUX_DB_QUERY, query);
    +
    +        byte [] bytes = new byte [] {};
    +        runner.enqueue(bytes);
    +        runner.run(1,true,true);
    +        runner.assertAllFlowFilesTransferred(ExecuteInfluxDBQuery.REL_SUCCESS, 1);
    +
    +        List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(ExecuteInfluxDBQuery.REL_SUCCESS);
    +        assertEquals("Value should be equal", 1, flowFiles.size());
    +        assertEquals("Value should be equal",null, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_ERROR_MESSAGE));
    --- End diff --
    
    `assertNull` is a better choice here.


---

[GitHub] nifi pull request #2562: NIFI-4927 - InfluxDB Query Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2562#discussion_r178794242
  
    --- Diff: nifi-nar-bundles/nifi-influxdb-bundle/nifi-influxdb-processors/src/main/java/org/apache/nifi/processors/influxdb/ExecuteInfluxDBQuery.java ---
    @@ -209,32 +204,40 @@ public void onTrigger(final ProcessContext context, final ProcessSession session
     
                 if ( ! result.hasError() ) {
                     outgoingFlowFile = session.putAttribute(outgoingFlowFile, INFLUX_DB_EXECUTED_QUERY, String.valueOf(query));
    +                session.getProvenanceReporter().send(outgoingFlowFile, makeProvenanceUrl(context, database, outgoingFlowFile),
    +                        (endTimeMillis - startTimeMillis));
                     session.transfer(outgoingFlowFile, REL_SUCCESS);
                 } else {
                     outgoingFlowFile = populateErrorAttributes(session, outgoingFlowFile, query, result.getError());
                     session.transfer(outgoingFlowFile, REL_FAILURE);
                 }
     
    -            session.getProvenanceReporter().send(outgoingFlowFile, makeProvenanceUrl(context, database),
    -                (endTimeMillis - startTimeMillis));
             } catch (Exception exception) {
                 outgoingFlowFile = populateErrorAttributes(session, outgoingFlowFile, query, exception.getMessage());
                 if ( exception.getCause() instanceof SocketTimeoutException ) {
    -                getLogger().error("Failed to read from influxDB due SocketTimeoutException to {} and retrying",
    +                getLogger().error("Failed to read from InfluxDB due SocketTimeoutException to {} and retrying",
                             new Object[]{exception.getCause().getLocalizedMessage()}, exception.getCause());
                     session.transfer(outgoingFlowFile, REL_RETRY);
                 } else {
    -                getLogger().error("Failed to read from influxDB due to {}",
    +                getLogger().error("Failed to read from InfluxDB due to {}",
                             new Object[]{exception.getLocalizedMessage()}, exception);
                     session.transfer(outgoingFlowFile, REL_FAILURE);
                 }
                 context.yield();
             }
         }
     
    -    protected String makeProvenanceUrl(final ProcessContext context, String database) {
    +    protected String getQuery(final ProcessSession session, Charset charset, FlowFile incomingFlowFile)
    +            throws IOException {
    --- End diff --
    
    You don't have to redo it that way, it's just a suggestion.


---