You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@storm.apache.org by bastiliu <gi...@git.apache.org> on 2016/03/04 09:11:42 UTC

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

GitHub user bastiliu opened a pull request:

    https://github.com/apache/storm/pull/1185

    [STORM-1269] port backtype.storm.daemon.common to java

    1. Following clojure defined records in common, "Assignment, StormBase, SupervisorInfo, ExecutorStats", were not migrated here. There are corresponding classes of Thrift. So, we can just use the thrift class in the dependency modules after each module's migration.
    2. worker-context was not migrated. There is much more worker to convert the worker data between java and clojure now. But it is easy to do this after the worker data is migrated to java. So I recommend to leave the mirgation of worker context as a part of  worker module.

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

    $ git pull https://github.com/bastiliu/storm master

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

    https://github.com/apache/storm/pull/1185.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 #1185
    
----
commit c7241a67c23899ebb3d6c25cdccde758efb7a0ad
Author: basti.lj <ba...@alibaba-inc.com>
Date:   2016-03-04T07:16:59Z

    [STORM-1269] port backtype.storm.daemon.common to java

commit 0726c116ebd2ef27b5225027bdf3008e6156018d
Author: basti.lj <ba...@alibaba-inc.com>
Date:   2016-03-04T07:18:28Z

    Merge remote-tracking branch 'upstream/master'

----


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55002193
  
    --- Diff: storm-core/src/jvm/org/apache/storm/utils/Utils.java ---
    @@ -2302,4 +2302,54 @@ public Object call() {
         public static long bitXor(Long a, Long b) {
             return a ^ b;
         }
    +
    +    public static Integer parseInt(Object o) {
    +        if (o == null) {
    +            return null;
    +        }
    +
    +        if (o instanceof String) {
    +            return Integer.parseInt(String.valueOf(o));
    +        } else if (o instanceof Long) {
    +            long value = (Long) o;
    +            return (int) value;
    +        } else if (o instanceof Integer) {
    +            return (Integer) o;
    +        } else {
    +            throw new RuntimeException("Invalid value " + o.getClass().getName() + " " + o);
    +        }
    +    }
    +
    +    public static Integer parseInt(Object o, int defaultValue) {
    --- End diff --
    
    Utils has the methods . The name is getInt()


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55006975
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,605 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    +        } else if (common.get_inputs() == null) {
    +            return true;
    +        } else {
    +            return common.get_inputs().isEmpty();
    +        }
    +    }
    +
    +    public static Map<String, Object> allComponents(StormTopology topology) {
    +        Map<String, Object> components = new HashMap<String, Object>();
    +        List<StormTopology._Fields> topologyFields = Arrays.asList(Thrift.getTopologyFields());
    +        for (StormTopology._Fields field : topologyFields) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                components.putAll(((Map) topology.getFieldValue(field)));
    +            }
    +        }
    +        return components;
    +    }
    +
    +    public static Map componentConf(Object component) {
    +        Map<Object, Object> conf = new HashMap<Object, Object>();
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common != null) {
    +            String jconf = common.get_json_conf();
    +            if (jconf != null) {
    +                conf.putAll((Map<Object, Object>) JSONValue.parse(jconf));
    +            }
    +        }
    +        return conf;
    +    }
    +
    +    public static void validateBasic(StormTopology topology) throws InvalidTopologyException {
    +        validateIds(topology);
    +
    +        List<StormTopology._Fields> spoutFields = Arrays.asList(Thrift.getSpoutFields());
    +        for (StormTopology._Fields field : spoutFields) {
    +            Map<String, Object> spoutComponents = (Map<String, Object>) topology.getFieldValue(field);
    +            if (spoutComponents != null) {
    +                for (Object obj : spoutComponents.values()) {
    +                    ComponentCommon common = getComponentCommon(obj);
    +                    if (isEmptyInputs(common) == false) {
    +                        throw new InvalidTopologyException("May not declare inputs for a spout");
    +                    }
    +                }
    +            }
    +        }
    +
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Object componentObj : componentMap.values()) {
    +            Map conf = componentConf(componentObj);
    +            ComponentCommon common = getComponentCommon(componentObj);
    +            if (common != null) {
    +                int parallelismHintNum = Thrift.getParallelismHint(common);
    +                Integer taskNum = Utils.getInt(conf.get(Config.TOPOLOGY_TASKS), 0);
    +                if (taskNum > 0 && parallelismHintNum <= 0) {
    +                    throw new InvalidTopologyException("Number of executors must be greater than 0 when number of tasks is greater than 0");
    +                }
    +            }
    +        }
    +    }
    +
    +    private static Set<String> getStreamOutputFields(Map<String, StreamInfo> streams) {
    +        Set<String> outputFields = new HashSet<String>();
    +        if (streams != null) {
    +            for (StreamInfo streamInfo : streams.values()) {
    +                outputFields.addAll(streamInfo.get_output_fields());
    +            }
    +        }
    +        return outputFields;
    +    }
    +
    +    public static void validateStructure(StormTopology topology) throws InvalidTopologyException {
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Map.Entry<String, Object> entry : componentMap.entrySet()) {
    +            String componentId = entry.getKey();
    +            ComponentCommon common = getComponentCommon(entry.getValue());
    +            if (common != null) {
    +                Map<GlobalStreamId, Grouping> inputs = common.get_inputs();
    +                for (Map.Entry<GlobalStreamId, Grouping> input : inputs.entrySet()) {
    +                    String sourceStreamId = input.getKey().get_streamId();
    +                    String sourceComponentId = input.getKey().get_componentId();
    +                    if(componentMap.keySet().contains(sourceComponentId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent component [" + sourceComponentId + "]");
    +                    }
    +
    +                    ComponentCommon sourceComponent = getComponentCommon(componentMap.get(sourceComponentId));
    +                    if (sourceComponent == null || sourceComponent.get_streams().containsKey(sourceStreamId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent stream: " +
    +                                "[" + sourceStreamId + "] of component [" + sourceComponentId + "]");
    +                    }
    +
    +                    Grouping grouping = input.getValue();
    +                    if (Thrift.groupingType(grouping) == Grouping._Fields.FIELDS) {
    +                        List<String> fields = grouping.get_fields();
    +                        Map<String, StreamInfo> streams = sourceComponent.get_streams();
    +                        Set<String> sourceOutputFields = getStreamOutputFields(streams);
    +                        if (sourceOutputFields.containsAll(fields) == false) {
    +                            throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from stream: [" + sourceStreamId  +"] of component " +
    +                                    "[" + sourceComponentId + "] + with non-existent fields: " + fields);
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> ackerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> boltIds = topology.get_bolts().keySet();
    +        Set<String> spoutIds = topology.get_spouts().keySet();
    +
    +        for(String id : spoutIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_INIT_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +
    +        for(String id : boltIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_ACK_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_FAIL_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static String clusterId = null;
    +    public static IBolt makeAckerBolt() {
    +        return _instance.makeAckerBoltImpl();
    +    }
    +    public IBolt makeAckerBoltImpl() {
    +        return new Acker();
    --- End diff --
    
    This can be inlined. 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55284861
  
    --- Diff: storm-core/test/clj/org/apache/storm/messaging/netty_integration_test.clj ---
    @@ -1,4 +1,3 @@
    -
    --- End diff --
    
    Please revert the change to this file.  Not needed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55007255
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,605 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    --- End diff --
    
    We can directly use Acker/ACKER_COMPONENT_ID everywhere. Similarly for other stream names. 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55279265
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,605 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    +        } else if (common.get_inputs() == null) {
    +            return true;
    +        } else {
    +            return common.get_inputs().isEmpty();
    +        }
    +    }
    +
    +    public static Map<String, Object> allComponents(StormTopology topology) {
    +        Map<String, Object> components = new HashMap<String, Object>();
    +        List<StormTopology._Fields> topologyFields = Arrays.asList(Thrift.getTopologyFields());
    +        for (StormTopology._Fields field : topologyFields) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                components.putAll(((Map) topology.getFieldValue(field)));
    +            }
    +        }
    +        return components;
    +    }
    +
    +    public static Map componentConf(Object component) {
    +        Map<Object, Object> conf = new HashMap<Object, Object>();
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common != null) {
    +            String jconf = common.get_json_conf();
    +            if (jconf != null) {
    +                conf.putAll((Map<Object, Object>) JSONValue.parse(jconf));
    +            }
    +        }
    +        return conf;
    +    }
    +
    +    public static void validateBasic(StormTopology topology) throws InvalidTopologyException {
    +        validateIds(topology);
    +
    +        List<StormTopology._Fields> spoutFields = Arrays.asList(Thrift.getSpoutFields());
    +        for (StormTopology._Fields field : spoutFields) {
    +            Map<String, Object> spoutComponents = (Map<String, Object>) topology.getFieldValue(field);
    +            if (spoutComponents != null) {
    +                for (Object obj : spoutComponents.values()) {
    +                    ComponentCommon common = getComponentCommon(obj);
    +                    if (isEmptyInputs(common) == false) {
    +                        throw new InvalidTopologyException("May not declare inputs for a spout");
    +                    }
    +                }
    +            }
    +        }
    +
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Object componentObj : componentMap.values()) {
    +            Map conf = componentConf(componentObj);
    +            ComponentCommon common = getComponentCommon(componentObj);
    +            if (common != null) {
    +                int parallelismHintNum = Thrift.getParallelismHint(common);
    +                Integer taskNum = Utils.getInt(conf.get(Config.TOPOLOGY_TASKS), 0);
    +                if (taskNum > 0 && parallelismHintNum <= 0) {
    +                    throw new InvalidTopologyException("Number of executors must be greater than 0 when number of tasks is greater than 0");
    +                }
    +            }
    +        }
    +    }
    +
    +    private static Set<String> getStreamOutputFields(Map<String, StreamInfo> streams) {
    +        Set<String> outputFields = new HashSet<String>();
    +        if (streams != null) {
    +            for (StreamInfo streamInfo : streams.values()) {
    +                outputFields.addAll(streamInfo.get_output_fields());
    +            }
    +        }
    +        return outputFields;
    +    }
    +
    +    public static void validateStructure(StormTopology topology) throws InvalidTopologyException {
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Map.Entry<String, Object> entry : componentMap.entrySet()) {
    +            String componentId = entry.getKey();
    +            ComponentCommon common = getComponentCommon(entry.getValue());
    +            if (common != null) {
    +                Map<GlobalStreamId, Grouping> inputs = common.get_inputs();
    +                for (Map.Entry<GlobalStreamId, Grouping> input : inputs.entrySet()) {
    +                    String sourceStreamId = input.getKey().get_streamId();
    +                    String sourceComponentId = input.getKey().get_componentId();
    +                    if(componentMap.keySet().contains(sourceComponentId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent component [" + sourceComponentId + "]");
    +                    }
    +
    +                    ComponentCommon sourceComponent = getComponentCommon(componentMap.get(sourceComponentId));
    +                    if (sourceComponent == null || sourceComponent.get_streams().containsKey(sourceStreamId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent stream: " +
    +                                "[" + sourceStreamId + "] of component [" + sourceComponentId + "]");
    +                    }
    +
    +                    Grouping grouping = input.getValue();
    +                    if (Thrift.groupingType(grouping) == Grouping._Fields.FIELDS) {
    +                        List<String> fields = grouping.get_fields();
    +                        Map<String, StreamInfo> streams = sourceComponent.get_streams();
    +                        Set<String> sourceOutputFields = getStreamOutputFields(streams);
    +                        if (sourceOutputFields.containsAll(fields) == false) {
    +                            throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from stream: [" + sourceStreamId  +"] of component " +
    +                                    "[" + sourceComponentId + "] + with non-existent fields: " + fields);
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> ackerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> boltIds = topology.get_bolts().keySet();
    +        Set<String> spoutIds = topology.get_spouts().keySet();
    +
    +        for(String id : spoutIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_INIT_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +
    +        for(String id : boltIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_ACK_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_FAIL_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static String clusterId = null;
    +    public static IBolt makeAckerBolt() {
    +        return _instance.makeAckerBoltImpl();
    +    }
    +    public IBolt makeAckerBoltImpl() {
    +        return new Acker();
    --- End diff --
    
    No because it is mocked out in some cases.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55005929
  
    --- Diff: storm-core/src/jvm/org/apache/storm/utils/Utils.java ---
    @@ -2302,4 +2302,54 @@ public Object call() {
         public static long bitXor(Long a, Long b) {
             return a ^ b;
         }
    +
    +    public static Integer parseInt(Object o) {
    +        if (o == null) {
    +            return null;
    +        }
    +
    +        if (o instanceof String) {
    +            return Integer.parseInt(String.valueOf(o));
    +        } else if (o instanceof Long) {
    +            long value = (Long) o;
    +            return (int) value;
    +        } else if (o instanceof Integer) {
    +            return (Integer) o;
    +        } else {
    +            throw new RuntimeException("Invalid value " + o.getClass().getName() + " " + o);
    +        }
    +    }
    +
    +    public static Integer parseInt(Object o, int defaultValue) {
    --- End diff --
    
    Addressed


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55283874
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,604 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    +        } else if (common.get_inputs() == null) {
    +            return true;
    +        } else {
    +            return common.get_inputs().isEmpty();
    +        }
    +    }
    +
    +    public static Map<String, Object> allComponents(StormTopology topology) {
    +        Map<String, Object> components = new HashMap<String, Object>();
    +        List<StormTopology._Fields> topologyFields = Arrays.asList(Thrift.getTopologyFields());
    +        for (StormTopology._Fields field : topologyFields) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                components.putAll(((Map) topology.getFieldValue(field)));
    +            }
    +        }
    +        return components;
    +    }
    +
    +    public static Map componentConf(Object component) {
    +        Map<Object, Object> conf = new HashMap<Object, Object>();
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common != null) {
    +            String jconf = common.get_json_conf();
    +            if (jconf != null) {
    +                conf.putAll((Map<Object, Object>) JSONValue.parse(jconf));
    +            }
    +        }
    +        return conf;
    +    }
    +
    +    public static void validateBasic(StormTopology topology) throws InvalidTopologyException {
    +        validateIds(topology);
    +
    +        List<StormTopology._Fields> spoutFields = Arrays.asList(Thrift.getSpoutFields());
    +        for (StormTopology._Fields field : spoutFields) {
    +            Map<String, Object> spoutComponents = (Map<String, Object>) topology.getFieldValue(field);
    +            if (spoutComponents != null) {
    +                for (Object obj : spoutComponents.values()) {
    +                    ComponentCommon common = getComponentCommon(obj);
    +                    if (isEmptyInputs(common) == false) {
    +                        throw new InvalidTopologyException("May not declare inputs for a spout");
    +                    }
    +                }
    +            }
    +        }
    +
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Object componentObj : componentMap.values()) {
    +            Map conf = componentConf(componentObj);
    +            ComponentCommon common = getComponentCommon(componentObj);
    +            if (common != null) {
    +                int parallelismHintNum = Thrift.getParallelismHint(common);
    +                Integer taskNum = Utils.getInt(conf.get(Config.TOPOLOGY_TASKS), 0);
    +                if (taskNum > 0 && parallelismHintNum <= 0) {
    +                    throw new InvalidTopologyException("Number of executors must be greater than 0 when number of tasks is greater than 0");
    +                }
    +            }
    +        }
    +    }
    +
    +    private static Set<String> getStreamOutputFields(Map<String, StreamInfo> streams) {
    +        Set<String> outputFields = new HashSet<String>();
    +        if (streams != null) {
    +            for (StreamInfo streamInfo : streams.values()) {
    +                outputFields.addAll(streamInfo.get_output_fields());
    +            }
    +        }
    +        return outputFields;
    +    }
    +
    +    public static void validateStructure(StormTopology topology) throws InvalidTopologyException {
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Map.Entry<String, Object> entry : componentMap.entrySet()) {
    +            String componentId = entry.getKey();
    +            ComponentCommon common = getComponentCommon(entry.getValue());
    +            if (common != null) {
    +                Map<GlobalStreamId, Grouping> inputs = common.get_inputs();
    +                for (Map.Entry<GlobalStreamId, Grouping> input : inputs.entrySet()) {
    +                    String sourceStreamId = input.getKey().get_streamId();
    +                    String sourceComponentId = input.getKey().get_componentId();
    +                    if(componentMap.keySet().contains(sourceComponentId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent component [" + sourceComponentId + "]");
    +                    }
    +
    +                    ComponentCommon sourceComponent = getComponentCommon(componentMap.get(sourceComponentId));
    +                    if (sourceComponent == null || sourceComponent.get_streams().containsKey(sourceStreamId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent stream: " +
    +                                "[" + sourceStreamId + "] of component [" + sourceComponentId + "]");
    +                    }
    +
    +                    Grouping grouping = input.getValue();
    +                    if (Thrift.groupingType(grouping) == Grouping._Fields.FIELDS) {
    +                        List<String> fields = grouping.get_fields();
    +                        Map<String, StreamInfo> streams = sourceComponent.get_streams();
    +                        Set<String> sourceOutputFields = getStreamOutputFields(streams);
    +                        if (sourceOutputFields.containsAll(fields) == false) {
    +                            throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from stream: [" + sourceStreamId  +"] of component " +
    +                                    "[" + sourceComponentId + "] + with non-existent fields: " + fields);
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> ackerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> boltIds = topology.get_bolts().keySet();
    +        Set<String> spoutIds = topology.get_spouts().keySet();
    +
    +        for(String id : spoutIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_INIT_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +
    +        for(String id : boltIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_ACK_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_FAIL_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static IBolt makeAckerBolt() {
    +        return _instance.makeAckerBoltImpl();
    +    }
    +    public IBolt makeAckerBoltImpl() {
    +        return new Acker();
    +    }
    +
    +    public static void addAcker(Map conf, StormTopology topology) {
    +        int ackerNum = Utils.getInt(conf.get(Config.TOPOLOGY_ACKER_EXECUTORS), Utils.getInt(conf.get(Config.TOPOLOGY_WORKERS)));
    +        Map<GlobalStreamId, Grouping> inputs = ackerInputs(topology);
    +
    +        Map<String, StreamInfo> outputStreams = new HashMap<String, StreamInfo>();
    +        outputStreams.put(ACKER_ACK_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +        outputStreams.put(ACKER_FAIL_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +
    +        Map<String, Object> ackerConf = new HashMap<String, Object>();
    +        ackerConf.put(Config.TOPOLOGY_TASKS, ackerNum);
    +        ackerConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +
    +        Bolt acker = Thrift.prepareSerializedBoltDetails(inputs, makeAckerBolt(), outputStreams, ackerNum, ackerConf);
    +
    +        for(Bolt bolt : topology.get_bolts().values()) {
    +            ComponentCommon common = bolt.get_common();
    +            common.put_to_streams(ACKER_ACK_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "ack-val")));
    +            common.put_to_streams(ACKER_FAIL_STREAM_ID, Thrift.outputFields(Arrays.asList("id")));
    +        }
    +
    +        for (SpoutSpec spout : topology.get_spouts().values()) {
    +            ComponentCommon common = spout.get_common();
    +            Map spoutConf = componentConf(spout);
    +            spoutConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +            common.set_json_conf(JSONValue.toJSONString(spoutConf));
    +            common.put_to_streams(ACKER_INIT_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "init-val", "spout-task")));
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_ACK_STREAM_ID), Thrift.prepareDirectGrouping());
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_FAIL_STREAM_ID), Thrift.prepareDirectGrouping());
    +        }
    +
    +        topology.put_to_bolts(ACKER_COMPONENT_ID, acker);
    +    }
    +
    +    public static ComponentCommon getComponentCommon(Object component) {
    +        if (component == null) {
    +            return null;
    +        }
    +
    +        ComponentCommon common = null;
    +        if (component instanceof StateSpoutSpec) {
    +            common = ((StateSpoutSpec) component).get_common();
    +        } else if (component instanceof SpoutSpec) {
    +            common = ((SpoutSpec) component).get_common();
    +        } else if (component instanceof Bolt) {
    +            common = ((Bolt) component).get_common();
    +        }
    +        return common;
    +    }
    +
    +    public static void addMetricStreams(StormTopology topology) {
    +        for (Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                StreamInfo streamInfo = Thrift.outputFields(Arrays.asList("task-info", "data-points"));
    +                common.put_to_streams(Constants.METRICS_STREAM_ID, streamInfo);
    +            }
    +        }
    +    }
    +
    +    public static void addSystemStreams(StormTopology topology) {
    +        for (Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                StreamInfo streamInfo = Thrift.outputFields(Arrays.asList("event"));
    +                common.put_to_streams(SYSTEM_STREAM_ID, streamInfo);
    +            }
    +        }
    +    }
    +
    +    public static List<String> eventLoggerBoltFields() {
    +        List<String> fields = Arrays.asList(EventLoggerBolt.FIELD_COMPONENT_ID, EventLoggerBolt.FIELD_MESSAGE_ID, EventLoggerBolt.FIELD_TS,
    +                EventLoggerBolt.FIELD_VALUES);
    +        return fields;
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> eventLoggerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> allIds = new HashSet<String>();
    +        allIds.addAll(topology.get_bolts().keySet());
    +        allIds.addAll(topology.get_spouts().keySet());
    +
    +        for(String id : allIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, EVENTLOGGER_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("component-id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static void addEventLogger(Map conf, StormTopology topology) {
    +        Integer numExecutors = Utils.getInt(conf.get(Config.TOPOLOGY_EVENTLOGGER_EXECUTORS), Utils.getInt(conf.get(Config.TOPOLOGY_WORKERS)));
    +        HashMap<String, Object> componentConf = new HashMap<String, Object>();
    +        componentConf.put(Config.TOPOLOGY_TASKS, numExecutors);
    +        componentConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +        Bolt eventLoggerBolt = Thrift.prepareSerializedBoltDetails(eventLoggerInputs(topology), new EventLoggerBolt(), null, numExecutors, componentConf);
    +
    +        for(Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                common.put_to_streams(EVENTLOGGER_STREAM_ID, Thrift.outputFields(eventLoggerBoltFields()));
    +            }
    +        }
    +        topology.put_to_bolts(EVENTLOGGER_COMPONENT_ID, eventLoggerBolt);
    +    }
    +
    +    public static Map<String, Bolt> metricsConsumerBoltSpecs(Map conf, StormTopology topology) {
    +        Map<String, Bolt> metricsConsumerBolts = new HashMap<String, Bolt>();
    +
    +        Set<String> componentIdsEmitMetrics = new HashSet<String>();
    +        componentIdsEmitMetrics.addAll(allComponents(topology).keySet());
    +        componentIdsEmitMetrics.add(Constants.SYSTEM_COMPONENT_ID);
    +
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        for (String componentId : componentIdsEmitMetrics) {
    +            inputs.put(Utils.getGlobalStreamId(componentId, Constants.METRICS_STREAM_ID), Thrift.prepareShuffleGrouping());
    +        }
    +
    +        List<Map<String, Object>> registerInfo = (List<Map<String, Object>>) conf.get(Config.TOPOLOGY_METRICS_CONSUMER_REGISTER);
    +        if (registerInfo != null) {
    +            Map<String, Integer> classOccurrencesMap = new HashMap<String, Integer>();
    +            for (Map<String, Object> info : registerInfo) {
    +                String className = (String) info.get("class");
    +                Object argument = info.get("argument");
    +                Integer phintNum = Utils.getInt(info.get("parallelism.hint"), 1);
    +                Map<String, Object> metricsConsumerConf = new HashMap<String, Object>();
    +                metricsConsumerConf.put(Config.TOPOLOGY_TASKS, phintNum);
    +                Bolt metricsConsumerBolt = Thrift.prepareSerializedBoltDetails(inputs, new MetricsConsumerBolt(className, argument), null, phintNum, metricsConsumerConf);
    +
    +                String id = className;
    +                if (classOccurrencesMap.containsKey(className)) {
    +                    // e.g. [\"a\", \"b\", \"a\"]) => [\"a\", \"b\", \"a#2\"]"
    +                    int occurrenceNum = classOccurrencesMap.get(className);
    +                    occurrenceNum++;
    +                    classOccurrencesMap.put(className, occurrenceNum);
    +                    id = Constants.METRICS_COMPONENT_ID_PREFIX + className + "#" + occurrenceNum;
    +                } else {
    +                    classOccurrencesMap.put(className, 1);
    +                }
    +                metricsConsumerBolts.put(id, metricsConsumerBolt);
    +            }
    +        }
    +        return metricsConsumerBolts;
    +    }
    +
    +    public static void addMetricComponents(Map conf, StormTopology topology) {
    +        Map<String, Bolt> metricsConsumerBolts = metricsConsumerBoltSpecs(conf, topology);
    +        for (Map.Entry<String, Bolt> entry : metricsConsumerBolts.entrySet()) {
    +            topology.put_to_bolts(entry.getKey(), entry.getValue());
    +        }
    +    }
    +
    +    public static void addSystemComponents(Map conf, StormTopology topology) {
    +        Map<String, StreamInfo> outputStreams = new HashMap<String, StreamInfo>();
    +        outputStreams.put(Constants.SYSTEM_TICK_STREAM_ID, Thrift.outputFields(Arrays.asList("rate_secs")));
    +        outputStreams.put(Constants.METRICS_TICK_STREAM_ID, Thrift.outputFields(Arrays.asList("interval")));
    +        outputStreams.put(Constants.CREDENTIALS_CHANGED_STREAM_ID, Thrift.outputFields(Arrays.asList("creds")));
    +
    +        Map<String, Object> boltConf = new HashMap<String, Object>();
    +        boltConf.put(Config.TOPOLOGY_TASKS, 0);
    +
    +        Bolt systemBoltSpec = Thrift.prepareSerializedBoltDetails(null, new SystemBolt(), outputStreams, 0, boltConf);
    +        topology.put_to_bolts(Constants.SYSTEM_COMPONENT_ID, systemBoltSpec);
    +    }
    +
    +    public static StormTopology systemTopology(Map stormConf, StormTopology topology) throws InvalidTopologyException {
    +        return _instance.systemTopologyImpl(stormConf, topology);
    +    }
    +
    +    protected StormTopology systemTopologyImpl(Map stormConf, StormTopology topology) throws InvalidTopologyException {
    +        validateBasic(topology);
    +
    +        StormTopology ret = topology.deepCopy();
    +        addAcker(stormConf, ret);
    +        addEventLogger(stormConf, ret);
    +        addMetricComponents(stormConf, ret);
    +        addSystemComponents(stormConf, ret);
    +        addMetricStreams(ret);
    +        addSystemStreams(ret);
    +
    +        validateStructure(ret);
    +
    +        return ret;
    +    }
    +
    +    public static boolean hasAckers(Map stormConf) {
    +        Object ackerNum = stormConf.get(Config.TOPOLOGY_ACKER_EXECUTORS);
    +        if (ackerNum == null || Utils.getInt(ackerNum) > 0) {
    +            return true;
    +        } else {
    +            return false;
    +        }
    +    }
    +
    +    public static boolean hasEventLoggers(Map stormConf) {
    +        Object eventLoggerNum = stormConf.get(Config.TOPOLOGY_EVENTLOGGER_EXECUTORS);
    +        if (eventLoggerNum == null || Utils.getInt(eventLoggerNum) > 0) {
    +            return true;
    +        } else {
    +            return false;
    +        }
    +    }
    +
    +    public static int numStartExecutors(Object component) throws InvalidTopologyException {
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common == null) {
    +            throw new InvalidTopologyException("unknown component type " + component.getClass().getName());
    +        }
    +        int parallelismHintNum = Thrift.getParallelismHint(common);
    +        return parallelismHintNum;
    +    }
    +
    +    public static Map stormTaskInfo(StormTopology userTopology, Map stormConf) throws InvalidTopologyException {
    +        return _instance.stormTaskInfoImpl(userTopology, stormConf);
    +    }
    +    /*
    +     * Returns map from task -> componentId
    +     */
    +    protected Map stormTaskInfoImpl(StormTopology userTopology, Map stormConf) throws InvalidTopologyException {
    --- End diff --
    
    Can we add the generics to the return type?
    ```
    Map<Integer, String>
    ```


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55276746
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,604 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    +        } else if (common.get_inputs() == null) {
    +            return true;
    +        } else {
    +            return common.get_inputs().isEmpty();
    +        }
    +    }
    +
    +    public static Map<String, Object> allComponents(StormTopology topology) {
    +        Map<String, Object> components = new HashMap<String, Object>();
    +        List<StormTopology._Fields> topologyFields = Arrays.asList(Thrift.getTopologyFields());
    +        for (StormTopology._Fields field : topologyFields) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                components.putAll(((Map) topology.getFieldValue(field)));
    +            }
    +        }
    +        return components;
    +    }
    +
    +    public static Map componentConf(Object component) {
    +        Map<Object, Object> conf = new HashMap<Object, Object>();
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common != null) {
    +            String jconf = common.get_json_conf();
    +            if (jconf != null) {
    +                conf.putAll((Map<Object, Object>) JSONValue.parse(jconf));
    +            }
    +        }
    +        return conf;
    +    }
    +
    +    public static void validateBasic(StormTopology topology) throws InvalidTopologyException {
    +        validateIds(topology);
    +
    +        List<StormTopology._Fields> spoutFields = Arrays.asList(Thrift.getSpoutFields());
    +        for (StormTopology._Fields field : spoutFields) {
    --- End diff --
    
    There is no reason to convert the code to a list before iterating.
    
    ```
    for (StormTopology._Fields field: Thrift.getSpoutFields()) {
    ```


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

Posted by revans2 <gi...@git.apache.org>.
Github user revans2 commented on the pull request:

    https://github.com/apache/storm/pull/1185#issuecomment-193442125
  
    Please upmerge the metrics code has been moved to StormMetricsRegistry.java, and is causing conflicts now.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55280255
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,604 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    +        } else if (common.get_inputs() == null) {
    +            return true;
    +        } else {
    +            return common.get_inputs().isEmpty();
    +        }
    +    }
    +
    +    public static Map<String, Object> allComponents(StormTopology topology) {
    +        Map<String, Object> components = new HashMap<String, Object>();
    +        List<StormTopology._Fields> topologyFields = Arrays.asList(Thrift.getTopologyFields());
    +        for (StormTopology._Fields field : topologyFields) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                components.putAll(((Map) topology.getFieldValue(field)));
    +            }
    +        }
    +        return components;
    +    }
    +
    +    public static Map componentConf(Object component) {
    +        Map<Object, Object> conf = new HashMap<Object, Object>();
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common != null) {
    +            String jconf = common.get_json_conf();
    +            if (jconf != null) {
    +                conf.putAll((Map<Object, Object>) JSONValue.parse(jconf));
    +            }
    +        }
    +        return conf;
    +    }
    +
    +    public static void validateBasic(StormTopology topology) throws InvalidTopologyException {
    +        validateIds(topology);
    +
    +        List<StormTopology._Fields> spoutFields = Arrays.asList(Thrift.getSpoutFields());
    +        for (StormTopology._Fields field : spoutFields) {
    +            Map<String, Object> spoutComponents = (Map<String, Object>) topology.getFieldValue(field);
    +            if (spoutComponents != null) {
    +                for (Object obj : spoutComponents.values()) {
    +                    ComponentCommon common = getComponentCommon(obj);
    +                    if (isEmptyInputs(common) == false) {
    +                        throw new InvalidTopologyException("May not declare inputs for a spout");
    +                    }
    +                }
    +            }
    +        }
    +
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Object componentObj : componentMap.values()) {
    +            Map conf = componentConf(componentObj);
    +            ComponentCommon common = getComponentCommon(componentObj);
    +            if (common != null) {
    +                int parallelismHintNum = Thrift.getParallelismHint(common);
    +                Integer taskNum = Utils.getInt(conf.get(Config.TOPOLOGY_TASKS), 0);
    +                if (taskNum > 0 && parallelismHintNum <= 0) {
    +                    throw new InvalidTopologyException("Number of executors must be greater than 0 when number of tasks is greater than 0");
    +                }
    +            }
    +        }
    +    }
    +
    +    private static Set<String> getStreamOutputFields(Map<String, StreamInfo> streams) {
    +        Set<String> outputFields = new HashSet<String>();
    +        if (streams != null) {
    +            for (StreamInfo streamInfo : streams.values()) {
    +                outputFields.addAll(streamInfo.get_output_fields());
    +            }
    +        }
    +        return outputFields;
    +    }
    +
    +    public static void validateStructure(StormTopology topology) throws InvalidTopologyException {
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Map.Entry<String, Object> entry : componentMap.entrySet()) {
    +            String componentId = entry.getKey();
    +            ComponentCommon common = getComponentCommon(entry.getValue());
    +            if (common != null) {
    +                Map<GlobalStreamId, Grouping> inputs = common.get_inputs();
    +                for (Map.Entry<GlobalStreamId, Grouping> input : inputs.entrySet()) {
    +                    String sourceStreamId = input.getKey().get_streamId();
    +                    String sourceComponentId = input.getKey().get_componentId();
    +                    if(componentMap.keySet().contains(sourceComponentId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent component [" + sourceComponentId + "]");
    +                    }
    +
    +                    ComponentCommon sourceComponent = getComponentCommon(componentMap.get(sourceComponentId));
    +                    if (sourceComponent == null || sourceComponent.get_streams().containsKey(sourceStreamId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent stream: " +
    +                                "[" + sourceStreamId + "] of component [" + sourceComponentId + "]");
    +                    }
    +
    +                    Grouping grouping = input.getValue();
    +                    if (Thrift.groupingType(grouping) == Grouping._Fields.FIELDS) {
    +                        List<String> fields = grouping.get_fields();
    +                        Map<String, StreamInfo> streams = sourceComponent.get_streams();
    +                        Set<String> sourceOutputFields = getStreamOutputFields(streams);
    +                        if (sourceOutputFields.containsAll(fields) == false) {
    +                            throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from stream: [" + sourceStreamId  +"] of component " +
    +                                    "[" + sourceComponentId + "] + with non-existent fields: " + fields);
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> ackerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> boltIds = topology.get_bolts().keySet();
    +        Set<String> spoutIds = topology.get_spouts().keySet();
    +
    +        for(String id : spoutIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_INIT_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +
    +        for(String id : boltIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_ACK_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_FAIL_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static IBolt makeAckerBolt() {
    +        return _instance.makeAckerBoltImpl();
    +    }
    +    public IBolt makeAckerBoltImpl() {
    +        return new Acker();
    +    }
    +
    +    public static void addAcker(Map conf, StormTopology topology) {
    +        int ackerNum = Utils.getInt(conf.get(Config.TOPOLOGY_ACKER_EXECUTORS), Utils.getInt(conf.get(Config.TOPOLOGY_WORKERS)));
    +        Map<GlobalStreamId, Grouping> inputs = ackerInputs(topology);
    +
    +        Map<String, StreamInfo> outputStreams = new HashMap<String, StreamInfo>();
    +        outputStreams.put(ACKER_ACK_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +        outputStreams.put(ACKER_FAIL_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +
    +        Map<String, Object> ackerConf = new HashMap<String, Object>();
    +        ackerConf.put(Config.TOPOLOGY_TASKS, ackerNum);
    +        ackerConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +
    +        Bolt acker = Thrift.prepareSerializedBoltDetails(inputs, makeAckerBolt(), outputStreams, ackerNum, ackerConf);
    +
    +        for(Bolt bolt : topology.get_bolts().values()) {
    +            ComponentCommon common = bolt.get_common();
    +            common.put_to_streams(ACKER_ACK_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "ack-val")));
    +            common.put_to_streams(ACKER_FAIL_STREAM_ID, Thrift.outputFields(Arrays.asList("id")));
    +        }
    +
    +        for (SpoutSpec spout : topology.get_spouts().values()) {
    +            ComponentCommon common = spout.get_common();
    +            Map spoutConf = componentConf(spout);
    +            spoutConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +            common.set_json_conf(JSONValue.toJSONString(spoutConf));
    +            common.put_to_streams(ACKER_INIT_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "init-val", "spout-task")));
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_ACK_STREAM_ID), Thrift.prepareDirectGrouping());
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_FAIL_STREAM_ID), Thrift.prepareDirectGrouping());
    +        }
    +
    +        topology.put_to_bolts(ACKER_COMPONENT_ID, acker);
    +    }
    +
    +    public static ComponentCommon getComponentCommon(Object component) {
    +        if (component == null) {
    +            return null;
    +        }
    +
    +        ComponentCommon common = null;
    +        if (component instanceof StateSpoutSpec) {
    +            common = ((StateSpoutSpec) component).get_common();
    +        } else if (component instanceof SpoutSpec) {
    +            common = ((SpoutSpec) component).get_common();
    +        } else if (component instanceof Bolt) {
    +            common = ((Bolt) component).get_common();
    +        }
    +        return common;
    +    }
    +
    +    public static void addMetricStreams(StormTopology topology) {
    +        for (Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    --- End diff --
    
    This null check was not in the original code.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

Posted by revans2 <gi...@git.apache.org>.
Github user revans2 commented on the pull request:

    https://github.com/apache/storm/pull/1185#issuecomment-193490519
  
    For the most part things look really good.  Just a lots of null checks that were not in the original code.  In these cases where we are validating the structure of the topology I really would prefer to see the code blow up with an NPE in those cases instead of silently skip over them.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55489222
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,605 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    --- End diff --
    
    @revans2  Yes, the major purpose here is to reduce the access to zk. Anyway, I am OK for keeping consistent with the original code.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55502112
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,604 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    +        } else if (common.get_inputs() == null) {
    +            return true;
    +        } else {
    +            return common.get_inputs().isEmpty();
    +        }
    +    }
    +
    +    public static Map<String, Object> allComponents(StormTopology topology) {
    +        Map<String, Object> components = new HashMap<String, Object>();
    +        List<StormTopology._Fields> topologyFields = Arrays.asList(Thrift.getTopologyFields());
    +        for (StormTopology._Fields field : topologyFields) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                components.putAll(((Map) topology.getFieldValue(field)));
    +            }
    +        }
    +        return components;
    +    }
    +
    +    public static Map componentConf(Object component) {
    +        Map<Object, Object> conf = new HashMap<Object, Object>();
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common != null) {
    +            String jconf = common.get_json_conf();
    +            if (jconf != null) {
    +                conf.putAll((Map<Object, Object>) JSONValue.parse(jconf));
    +            }
    +        }
    +        return conf;
    +    }
    +
    +    public static void validateBasic(StormTopology topology) throws InvalidTopologyException {
    +        validateIds(topology);
    +
    +        List<StormTopology._Fields> spoutFields = Arrays.asList(Thrift.getSpoutFields());
    +        for (StormTopology._Fields field : spoutFields) {
    +            Map<String, Object> spoutComponents = (Map<String, Object>) topology.getFieldValue(field);
    +            if (spoutComponents != null) {
    +                for (Object obj : spoutComponents.values()) {
    +                    ComponentCommon common = getComponentCommon(obj);
    +                    if (isEmptyInputs(common) == false) {
    +                        throw new InvalidTopologyException("May not declare inputs for a spout");
    +                    }
    +                }
    +            }
    +        }
    +
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Object componentObj : componentMap.values()) {
    +            Map conf = componentConf(componentObj);
    +            ComponentCommon common = getComponentCommon(componentObj);
    +            if (common != null) {
    +                int parallelismHintNum = Thrift.getParallelismHint(common);
    +                Integer taskNum = Utils.getInt(conf.get(Config.TOPOLOGY_TASKS), 0);
    +                if (taskNum > 0 && parallelismHintNum <= 0) {
    +                    throw new InvalidTopologyException("Number of executors must be greater than 0 when number of tasks is greater than 0");
    +                }
    +            }
    +        }
    +    }
    +
    +    private static Set<String> getStreamOutputFields(Map<String, StreamInfo> streams) {
    +        Set<String> outputFields = new HashSet<String>();
    +        if (streams != null) {
    +            for (StreamInfo streamInfo : streams.values()) {
    +                outputFields.addAll(streamInfo.get_output_fields());
    +            }
    +        }
    +        return outputFields;
    +    }
    +
    +    public static void validateStructure(StormTopology topology) throws InvalidTopologyException {
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Map.Entry<String, Object> entry : componentMap.entrySet()) {
    +            String componentId = entry.getKey();
    +            ComponentCommon common = getComponentCommon(entry.getValue());
    +            if (common != null) {
    +                Map<GlobalStreamId, Grouping> inputs = common.get_inputs();
    +                for (Map.Entry<GlobalStreamId, Grouping> input : inputs.entrySet()) {
    +                    String sourceStreamId = input.getKey().get_streamId();
    +                    String sourceComponentId = input.getKey().get_componentId();
    +                    if(componentMap.keySet().contains(sourceComponentId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent component [" + sourceComponentId + "]");
    +                    }
    +
    +                    ComponentCommon sourceComponent = getComponentCommon(componentMap.get(sourceComponentId));
    +                    if (sourceComponent == null || sourceComponent.get_streams().containsKey(sourceStreamId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent stream: " +
    +                                "[" + sourceStreamId + "] of component [" + sourceComponentId + "]");
    +                    }
    +
    +                    Grouping grouping = input.getValue();
    +                    if (Thrift.groupingType(grouping) == Grouping._Fields.FIELDS) {
    +                        List<String> fields = grouping.get_fields();
    +                        Map<String, StreamInfo> streams = sourceComponent.get_streams();
    +                        Set<String> sourceOutputFields = getStreamOutputFields(streams);
    +                        if (sourceOutputFields.containsAll(fields) == false) {
    +                            throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from stream: [" + sourceStreamId  +"] of component " +
    +                                    "[" + sourceComponentId + "] + with non-existent fields: " + fields);
    --- End diff --
    
    Addressed


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

Posted by revans2 <gi...@git.apache.org>.
Github user revans2 commented on the pull request:

    https://github.com/apache/storm/pull/1185#issuecomment-194866571
  
    +1 looks good to me


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55279121
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,604 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    +        } else if (common.get_inputs() == null) {
    +            return true;
    +        } else {
    +            return common.get_inputs().isEmpty();
    +        }
    +    }
    +
    +    public static Map<String, Object> allComponents(StormTopology topology) {
    +        Map<String, Object> components = new HashMap<String, Object>();
    +        List<StormTopology._Fields> topologyFields = Arrays.asList(Thrift.getTopologyFields());
    +        for (StormTopology._Fields field : topologyFields) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                components.putAll(((Map) topology.getFieldValue(field)));
    +            }
    +        }
    +        return components;
    +    }
    +
    +    public static Map componentConf(Object component) {
    +        Map<Object, Object> conf = new HashMap<Object, Object>();
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common != null) {
    +            String jconf = common.get_json_conf();
    +            if (jconf != null) {
    +                conf.putAll((Map<Object, Object>) JSONValue.parse(jconf));
    +            }
    +        }
    +        return conf;
    +    }
    +
    +    public static void validateBasic(StormTopology topology) throws InvalidTopologyException {
    +        validateIds(topology);
    +
    +        List<StormTopology._Fields> spoutFields = Arrays.asList(Thrift.getSpoutFields());
    +        for (StormTopology._Fields field : spoutFields) {
    +            Map<String, Object> spoutComponents = (Map<String, Object>) topology.getFieldValue(field);
    +            if (spoutComponents != null) {
    +                for (Object obj : spoutComponents.values()) {
    +                    ComponentCommon common = getComponentCommon(obj);
    +                    if (isEmptyInputs(common) == false) {
    +                        throw new InvalidTopologyException("May not declare inputs for a spout");
    +                    }
    +                }
    +            }
    +        }
    +
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Object componentObj : componentMap.values()) {
    +            Map conf = componentConf(componentObj);
    +            ComponentCommon common = getComponentCommon(componentObj);
    +            if (common != null) {
    +                int parallelismHintNum = Thrift.getParallelismHint(common);
    +                Integer taskNum = Utils.getInt(conf.get(Config.TOPOLOGY_TASKS), 0);
    +                if (taskNum > 0 && parallelismHintNum <= 0) {
    +                    throw new InvalidTopologyException("Number of executors must be greater than 0 when number of tasks is greater than 0");
    +                }
    +            }
    +        }
    +    }
    +
    +    private static Set<String> getStreamOutputFields(Map<String, StreamInfo> streams) {
    +        Set<String> outputFields = new HashSet<String>();
    +        if (streams != null) {
    +            for (StreamInfo streamInfo : streams.values()) {
    +                outputFields.addAll(streamInfo.get_output_fields());
    +            }
    +        }
    +        return outputFields;
    +    }
    +
    +    public static void validateStructure(StormTopology topology) throws InvalidTopologyException {
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Map.Entry<String, Object> entry : componentMap.entrySet()) {
    +            String componentId = entry.getKey();
    +            ComponentCommon common = getComponentCommon(entry.getValue());
    +            if (common != null) {
    +                Map<GlobalStreamId, Grouping> inputs = common.get_inputs();
    +                for (Map.Entry<GlobalStreamId, Grouping> input : inputs.entrySet()) {
    +                    String sourceStreamId = input.getKey().get_streamId();
    +                    String sourceComponentId = input.getKey().get_componentId();
    +                    if(componentMap.keySet().contains(sourceComponentId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent component [" + sourceComponentId + "]");
    +                    }
    +
    +                    ComponentCommon sourceComponent = getComponentCommon(componentMap.get(sourceComponentId));
    +                    if (sourceComponent == null || sourceComponent.get_streams().containsKey(sourceStreamId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent stream: " +
    +                                "[" + sourceStreamId + "] of component [" + sourceComponentId + "]");
    +                    }
    +
    +                    Grouping grouping = input.getValue();
    +                    if (Thrift.groupingType(grouping) == Grouping._Fields.FIELDS) {
    +                        List<String> fields = grouping.get_fields();
    +                        Map<String, StreamInfo> streams = sourceComponent.get_streams();
    +                        Set<String> sourceOutputFields = getStreamOutputFields(streams);
    +                        if (sourceOutputFields.containsAll(fields) == false) {
    +                            throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from stream: [" + sourceStreamId  +"] of component " +
    +                                    "[" + sourceComponentId + "] + with non-existent fields: " + fields);
    --- End diff --
    
    In the original code the error message was just for the diff-fields.  The ones that were a problem, not all of the fields.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

Posted by bastiliu <gi...@git.apache.org>.
Github user bastiliu commented on the pull request:

    https://github.com/apache/storm/pull/1185#issuecomment-194271492
  
    I have updated the code according to your comments, and remove the unnecessary null checks.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

Posted by bastiliu <gi...@git.apache.org>.
Github user bastiliu commented on the pull request:

    https://github.com/apache/storm/pull/1185#issuecomment-194641160
  
    @revans2 @abhishekagarwal87 Thanks for your review. CommonInstaller was removed, and the drpc changes have been merged.  For SystemTopologyBuilder, maybe it is better to follow up in a new JIRA for enhancement or code restructuring, since this JIRA mainly focus on migration. 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55489803
  
    --- Diff: storm-core/src/clj/org/apache/storm/daemon/common.clj ---
    @@ -86,26 +40,6 @@
     (defn new-executor-stats []
       (ExecutorStats. 0 0 0 0 0))
    --- End diff --
    
    Yes, I recommend to just use the thrift classes directly when we work on relative modules. It can save much effort now for the converting between clojure and jave. Please refer to my comments at the beginning of this PR. 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55284177
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,604 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    +        } else if (common.get_inputs() == null) {
    +            return true;
    +        } else {
    +            return common.get_inputs().isEmpty();
    +        }
    +    }
    +
    +    public static Map<String, Object> allComponents(StormTopology topology) {
    +        Map<String, Object> components = new HashMap<String, Object>();
    +        List<StormTopology._Fields> topologyFields = Arrays.asList(Thrift.getTopologyFields());
    +        for (StormTopology._Fields field : topologyFields) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                components.putAll(((Map) topology.getFieldValue(field)));
    +            }
    +        }
    +        return components;
    +    }
    +
    +    public static Map componentConf(Object component) {
    +        Map<Object, Object> conf = new HashMap<Object, Object>();
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common != null) {
    +            String jconf = common.get_json_conf();
    +            if (jconf != null) {
    +                conf.putAll((Map<Object, Object>) JSONValue.parse(jconf));
    +            }
    +        }
    +        return conf;
    +    }
    +
    +    public static void validateBasic(StormTopology topology) throws InvalidTopologyException {
    +        validateIds(topology);
    +
    +        List<StormTopology._Fields> spoutFields = Arrays.asList(Thrift.getSpoutFields());
    +        for (StormTopology._Fields field : spoutFields) {
    +            Map<String, Object> spoutComponents = (Map<String, Object>) topology.getFieldValue(field);
    +            if (spoutComponents != null) {
    +                for (Object obj : spoutComponents.values()) {
    +                    ComponentCommon common = getComponentCommon(obj);
    +                    if (isEmptyInputs(common) == false) {
    +                        throw new InvalidTopologyException("May not declare inputs for a spout");
    +                    }
    +                }
    +            }
    +        }
    +
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Object componentObj : componentMap.values()) {
    +            Map conf = componentConf(componentObj);
    +            ComponentCommon common = getComponentCommon(componentObj);
    +            if (common != null) {
    +                int parallelismHintNum = Thrift.getParallelismHint(common);
    +                Integer taskNum = Utils.getInt(conf.get(Config.TOPOLOGY_TASKS), 0);
    +                if (taskNum > 0 && parallelismHintNum <= 0) {
    +                    throw new InvalidTopologyException("Number of executors must be greater than 0 when number of tasks is greater than 0");
    +                }
    +            }
    +        }
    +    }
    +
    +    private static Set<String> getStreamOutputFields(Map<String, StreamInfo> streams) {
    +        Set<String> outputFields = new HashSet<String>();
    +        if (streams != null) {
    +            for (StreamInfo streamInfo : streams.values()) {
    +                outputFields.addAll(streamInfo.get_output_fields());
    +            }
    +        }
    +        return outputFields;
    +    }
    +
    +    public static void validateStructure(StormTopology topology) throws InvalidTopologyException {
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Map.Entry<String, Object> entry : componentMap.entrySet()) {
    +            String componentId = entry.getKey();
    +            ComponentCommon common = getComponentCommon(entry.getValue());
    +            if (common != null) {
    +                Map<GlobalStreamId, Grouping> inputs = common.get_inputs();
    +                for (Map.Entry<GlobalStreamId, Grouping> input : inputs.entrySet()) {
    +                    String sourceStreamId = input.getKey().get_streamId();
    +                    String sourceComponentId = input.getKey().get_componentId();
    +                    if(componentMap.keySet().contains(sourceComponentId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent component [" + sourceComponentId + "]");
    +                    }
    +
    +                    ComponentCommon sourceComponent = getComponentCommon(componentMap.get(sourceComponentId));
    +                    if (sourceComponent == null || sourceComponent.get_streams().containsKey(sourceStreamId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent stream: " +
    +                                "[" + sourceStreamId + "] of component [" + sourceComponentId + "]");
    +                    }
    +
    +                    Grouping grouping = input.getValue();
    +                    if (Thrift.groupingType(grouping) == Grouping._Fields.FIELDS) {
    +                        List<String> fields = grouping.get_fields();
    +                        Map<String, StreamInfo> streams = sourceComponent.get_streams();
    +                        Set<String> sourceOutputFields = getStreamOutputFields(streams);
    +                        if (sourceOutputFields.containsAll(fields) == false) {
    +                            throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from stream: [" + sourceStreamId  +"] of component " +
    +                                    "[" + sourceComponentId + "] + with non-existent fields: " + fields);
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> ackerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> boltIds = topology.get_bolts().keySet();
    +        Set<String> spoutIds = topology.get_spouts().keySet();
    +
    +        for(String id : spoutIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_INIT_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +
    +        for(String id : boltIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_ACK_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_FAIL_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static IBolt makeAckerBolt() {
    +        return _instance.makeAckerBoltImpl();
    +    }
    +    public IBolt makeAckerBoltImpl() {
    +        return new Acker();
    +    }
    +
    +    public static void addAcker(Map conf, StormTopology topology) {
    +        int ackerNum = Utils.getInt(conf.get(Config.TOPOLOGY_ACKER_EXECUTORS), Utils.getInt(conf.get(Config.TOPOLOGY_WORKERS)));
    +        Map<GlobalStreamId, Grouping> inputs = ackerInputs(topology);
    +
    +        Map<String, StreamInfo> outputStreams = new HashMap<String, StreamInfo>();
    +        outputStreams.put(ACKER_ACK_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +        outputStreams.put(ACKER_FAIL_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +
    +        Map<String, Object> ackerConf = new HashMap<String, Object>();
    +        ackerConf.put(Config.TOPOLOGY_TASKS, ackerNum);
    +        ackerConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +
    +        Bolt acker = Thrift.prepareSerializedBoltDetails(inputs, makeAckerBolt(), outputStreams, ackerNum, ackerConf);
    +
    +        for(Bolt bolt : topology.get_bolts().values()) {
    +            ComponentCommon common = bolt.get_common();
    +            common.put_to_streams(ACKER_ACK_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "ack-val")));
    +            common.put_to_streams(ACKER_FAIL_STREAM_ID, Thrift.outputFields(Arrays.asList("id")));
    +        }
    +
    +        for (SpoutSpec spout : topology.get_spouts().values()) {
    +            ComponentCommon common = spout.get_common();
    +            Map spoutConf = componentConf(spout);
    +            spoutConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +            common.set_json_conf(JSONValue.toJSONString(spoutConf));
    +            common.put_to_streams(ACKER_INIT_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "init-val", "spout-task")));
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_ACK_STREAM_ID), Thrift.prepareDirectGrouping());
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_FAIL_STREAM_ID), Thrift.prepareDirectGrouping());
    +        }
    +
    +        topology.put_to_bolts(ACKER_COMPONENT_ID, acker);
    +    }
    +
    +    public static ComponentCommon getComponentCommon(Object component) {
    +        if (component == null) {
    +            return null;
    +        }
    +
    +        ComponentCommon common = null;
    +        if (component instanceof StateSpoutSpec) {
    +            common = ((StateSpoutSpec) component).get_common();
    +        } else if (component instanceof SpoutSpec) {
    +            common = ((SpoutSpec) component).get_common();
    +        } else if (component instanceof Bolt) {
    +            common = ((Bolt) component).get_common();
    +        }
    +        return common;
    +    }
    +
    +    public static void addMetricStreams(StormTopology topology) {
    +        for (Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                StreamInfo streamInfo = Thrift.outputFields(Arrays.asList("task-info", "data-points"));
    +                common.put_to_streams(Constants.METRICS_STREAM_ID, streamInfo);
    +            }
    +        }
    +    }
    +
    +    public static void addSystemStreams(StormTopology topology) {
    +        for (Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                StreamInfo streamInfo = Thrift.outputFields(Arrays.asList("event"));
    +                common.put_to_streams(SYSTEM_STREAM_ID, streamInfo);
    +            }
    +        }
    +    }
    +
    +    public static List<String> eventLoggerBoltFields() {
    +        List<String> fields = Arrays.asList(EventLoggerBolt.FIELD_COMPONENT_ID, EventLoggerBolt.FIELD_MESSAGE_ID, EventLoggerBolt.FIELD_TS,
    +                EventLoggerBolt.FIELD_VALUES);
    +        return fields;
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> eventLoggerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> allIds = new HashSet<String>();
    +        allIds.addAll(topology.get_bolts().keySet());
    +        allIds.addAll(topology.get_spouts().keySet());
    +
    +        for(String id : allIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, EVENTLOGGER_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("component-id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static void addEventLogger(Map conf, StormTopology topology) {
    +        Integer numExecutors = Utils.getInt(conf.get(Config.TOPOLOGY_EVENTLOGGER_EXECUTORS), Utils.getInt(conf.get(Config.TOPOLOGY_WORKERS)));
    +        HashMap<String, Object> componentConf = new HashMap<String, Object>();
    +        componentConf.put(Config.TOPOLOGY_TASKS, numExecutors);
    +        componentConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +        Bolt eventLoggerBolt = Thrift.prepareSerializedBoltDetails(eventLoggerInputs(topology), new EventLoggerBolt(), null, numExecutors, componentConf);
    +
    +        for(Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                common.put_to_streams(EVENTLOGGER_STREAM_ID, Thrift.outputFields(eventLoggerBoltFields()));
    +            }
    +        }
    +        topology.put_to_bolts(EVENTLOGGER_COMPONENT_ID, eventLoggerBolt);
    +    }
    +
    +    public static Map<String, Bolt> metricsConsumerBoltSpecs(Map conf, StormTopology topology) {
    +        Map<String, Bolt> metricsConsumerBolts = new HashMap<String, Bolt>();
    +
    +        Set<String> componentIdsEmitMetrics = new HashSet<String>();
    +        componentIdsEmitMetrics.addAll(allComponents(topology).keySet());
    +        componentIdsEmitMetrics.add(Constants.SYSTEM_COMPONENT_ID);
    +
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        for (String componentId : componentIdsEmitMetrics) {
    +            inputs.put(Utils.getGlobalStreamId(componentId, Constants.METRICS_STREAM_ID), Thrift.prepareShuffleGrouping());
    +        }
    +
    +        List<Map<String, Object>> registerInfo = (List<Map<String, Object>>) conf.get(Config.TOPOLOGY_METRICS_CONSUMER_REGISTER);
    +        if (registerInfo != null) {
    +            Map<String, Integer> classOccurrencesMap = new HashMap<String, Integer>();
    +            for (Map<String, Object> info : registerInfo) {
    +                String className = (String) info.get("class");
    +                Object argument = info.get("argument");
    +                Integer phintNum = Utils.getInt(info.get("parallelism.hint"), 1);
    +                Map<String, Object> metricsConsumerConf = new HashMap<String, Object>();
    +                metricsConsumerConf.put(Config.TOPOLOGY_TASKS, phintNum);
    +                Bolt metricsConsumerBolt = Thrift.prepareSerializedBoltDetails(inputs, new MetricsConsumerBolt(className, argument), null, phintNum, metricsConsumerConf);
    +
    +                String id = className;
    +                if (classOccurrencesMap.containsKey(className)) {
    +                    // e.g. [\"a\", \"b\", \"a\"]) => [\"a\", \"b\", \"a#2\"]"
    +                    int occurrenceNum = classOccurrencesMap.get(className);
    +                    occurrenceNum++;
    +                    classOccurrencesMap.put(className, occurrenceNum);
    +                    id = Constants.METRICS_COMPONENT_ID_PREFIX + className + "#" + occurrenceNum;
    +                } else {
    +                    classOccurrencesMap.put(className, 1);
    +                }
    +                metricsConsumerBolts.put(id, metricsConsumerBolt);
    +            }
    +        }
    +        return metricsConsumerBolts;
    +    }
    +
    +    public static void addMetricComponents(Map conf, StormTopology topology) {
    +        Map<String, Bolt> metricsConsumerBolts = metricsConsumerBoltSpecs(conf, topology);
    +        for (Map.Entry<String, Bolt> entry : metricsConsumerBolts.entrySet()) {
    +            topology.put_to_bolts(entry.getKey(), entry.getValue());
    +        }
    +    }
    +
    +    public static void addSystemComponents(Map conf, StormTopology topology) {
    +        Map<String, StreamInfo> outputStreams = new HashMap<String, StreamInfo>();
    +        outputStreams.put(Constants.SYSTEM_TICK_STREAM_ID, Thrift.outputFields(Arrays.asList("rate_secs")));
    +        outputStreams.put(Constants.METRICS_TICK_STREAM_ID, Thrift.outputFields(Arrays.asList("interval")));
    +        outputStreams.put(Constants.CREDENTIALS_CHANGED_STREAM_ID, Thrift.outputFields(Arrays.asList("creds")));
    +
    +        Map<String, Object> boltConf = new HashMap<String, Object>();
    +        boltConf.put(Config.TOPOLOGY_TASKS, 0);
    +
    +        Bolt systemBoltSpec = Thrift.prepareSerializedBoltDetails(null, new SystemBolt(), outputStreams, 0, boltConf);
    +        topology.put_to_bolts(Constants.SYSTEM_COMPONENT_ID, systemBoltSpec);
    +    }
    +
    +    public static StormTopology systemTopology(Map stormConf, StormTopology topology) throws InvalidTopologyException {
    +        return _instance.systemTopologyImpl(stormConf, topology);
    +    }
    +
    +    protected StormTopology systemTopologyImpl(Map stormConf, StormTopology topology) throws InvalidTopologyException {
    +        validateBasic(topology);
    +
    +        StormTopology ret = topology.deepCopy();
    +        addAcker(stormConf, ret);
    +        addEventLogger(stormConf, ret);
    +        addMetricComponents(stormConf, ret);
    +        addSystemComponents(stormConf, ret);
    +        addMetricStreams(ret);
    +        addSystemStreams(ret);
    +
    +        validateStructure(ret);
    +
    +        return ret;
    +    }
    +
    +    public static boolean hasAckers(Map stormConf) {
    +        Object ackerNum = stormConf.get(Config.TOPOLOGY_ACKER_EXECUTORS);
    +        if (ackerNum == null || Utils.getInt(ackerNum) > 0) {
    +            return true;
    +        } else {
    +            return false;
    +        }
    +    }
    +
    +    public static boolean hasEventLoggers(Map stormConf) {
    +        Object eventLoggerNum = stormConf.get(Config.TOPOLOGY_EVENTLOGGER_EXECUTORS);
    +        if (eventLoggerNum == null || Utils.getInt(eventLoggerNum) > 0) {
    +            return true;
    +        } else {
    +            return false;
    +        }
    +    }
    +
    +    public static int numStartExecutors(Object component) throws InvalidTopologyException {
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common == null) {
    +            throw new InvalidTopologyException("unknown component type " + component.getClass().getName());
    +        }
    +        int parallelismHintNum = Thrift.getParallelismHint(common);
    +        return parallelismHintNum;
    +    }
    +
    +    public static Map stormTaskInfo(StormTopology userTopology, Map stormConf) throws InvalidTopologyException {
    +        return _instance.stormTaskInfoImpl(userTopology, stormConf);
    +    }
    +    /*
    +     * Returns map from task -> componentId
    +     */
    +    protected Map stormTaskInfoImpl(StormTopology userTopology, Map stormConf) throws InvalidTopologyException {
    +        Map<Integer, String> taskIdToComponentId = new HashMap<Integer, String>();
    +
    +        StormTopology systemTopology = systemTopology(stormConf, userTopology);
    +        Map<String, Object> components = allComponents(systemTopology);
    +        Map<String, Integer> componentIdToTaskNum = new TreeMap<String, Integer>();
    +        for (Map.Entry<String, Object> entry : components.entrySet()) {
    +            Map conf = componentConf(entry.getValue());
    +            Object taskNum = conf.get(Config.TOPOLOGY_TASKS);
    +            if (taskNum != null) {
    --- End diff --
    
    This null check was not in the original code.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55285470
  
    --- Diff: storm-core/src/clj/org/apache/storm/daemon/executor.clj ---
    @@ -536,17 +536,17 @@
                                         (throw (RuntimeException. (str "Fatal error, mismatched task ids: " task-id " " stored-task-id))))
                                       (let [time-delta (if start-time-ms (Time/deltaMs start-time-ms))]
                                         (condp = stream-id
    -                                      ACKER-ACK-STREAM-ID (ack-spout-msg executor-data (get task-datas task-id)
    +                                      StormCommon/ACKER_ACK_STREAM_ID (ack-spout-msg executor-data (get task-datas task-id)
                                                                              spout-id tuple-finished-info time-delta id)
    -                                      ACKER-FAIL-STREAM-ID (fail-spout-msg executor-data (get task-datas task-id)
    +                                      StormCommon/ACKER_FAIL_STREAM_ID (fail-spout-msg executor-data (get task-datas task-id)
                                                                                spout-id tuple-finished-info time-delta "FAIL-STREAM" id)
                                           )))
                                     ;; TODO: on failure, emit tuple to failure stream
                                     ))))
             receive-queue (:receive-queue executor-data)
             event-handler (mk-task-receiver executor-data tuple-action-fn)
    -        has-ackers? (has-ackers? storm-conf)
    -        has-eventloggers? (has-eventloggers? storm-conf)
    +        has-ackers? (clojurify-structure (StormCommon/hasAckers storm-conf))
    +        has-eventloggers? (clojurify-structure (StormCommon/hasEventLoggers storm-conf))
    --- End diff --
    
    I don't think these should need the `clojurify-structure` calls.  Were you seeing errors without it?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55277280
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,604 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    --- End diff --
    
    The original code would throw an NPE if this was null.  In this case I can see it being a minor nit, but I still would prefer to keep the code the same if possible.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55565851
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,605 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    +        } else if (common.get_inputs() == null) {
    +            return true;
    +        } else {
    +            return common.get_inputs().isEmpty();
    +        }
    +    }
    +
    +    public static Map<String, Object> allComponents(StormTopology topology) {
    +        Map<String, Object> components = new HashMap<String, Object>();
    +        List<StormTopology._Fields> topologyFields = Arrays.asList(Thrift.getTopologyFields());
    +        for (StormTopology._Fields field : topologyFields) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                components.putAll(((Map) topology.getFieldValue(field)));
    +            }
    +        }
    +        return components;
    +    }
    +
    +    public static Map componentConf(Object component) {
    +        Map<Object, Object> conf = new HashMap<Object, Object>();
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common != null) {
    +            String jconf = common.get_json_conf();
    +            if (jconf != null) {
    +                conf.putAll((Map<Object, Object>) JSONValue.parse(jconf));
    +            }
    +        }
    +        return conf;
    +    }
    +
    +    public static void validateBasic(StormTopology topology) throws InvalidTopologyException {
    +        validateIds(topology);
    +
    +        List<StormTopology._Fields> spoutFields = Arrays.asList(Thrift.getSpoutFields());
    +        for (StormTopology._Fields field : spoutFields) {
    +            Map<String, Object> spoutComponents = (Map<String, Object>) topology.getFieldValue(field);
    +            if (spoutComponents != null) {
    +                for (Object obj : spoutComponents.values()) {
    +                    ComponentCommon common = getComponentCommon(obj);
    +                    if (isEmptyInputs(common) == false) {
    +                        throw new InvalidTopologyException("May not declare inputs for a spout");
    +                    }
    +                }
    +            }
    +        }
    +
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Object componentObj : componentMap.values()) {
    +            Map conf = componentConf(componentObj);
    +            ComponentCommon common = getComponentCommon(componentObj);
    +            if (common != null) {
    +                int parallelismHintNum = Thrift.getParallelismHint(common);
    +                Integer taskNum = Utils.getInt(conf.get(Config.TOPOLOGY_TASKS), 0);
    +                if (taskNum > 0 && parallelismHintNum <= 0) {
    +                    throw new InvalidTopologyException("Number of executors must be greater than 0 when number of tasks is greater than 0");
    +                }
    +            }
    +        }
    +    }
    +
    +    private static Set<String> getStreamOutputFields(Map<String, StreamInfo> streams) {
    +        Set<String> outputFields = new HashSet<String>();
    +        if (streams != null) {
    +            for (StreamInfo streamInfo : streams.values()) {
    +                outputFields.addAll(streamInfo.get_output_fields());
    +            }
    +        }
    +        return outputFields;
    +    }
    +
    +    public static void validateStructure(StormTopology topology) throws InvalidTopologyException {
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Map.Entry<String, Object> entry : componentMap.entrySet()) {
    +            String componentId = entry.getKey();
    +            ComponentCommon common = getComponentCommon(entry.getValue());
    +            if (common != null) {
    +                Map<GlobalStreamId, Grouping> inputs = common.get_inputs();
    +                for (Map.Entry<GlobalStreamId, Grouping> input : inputs.entrySet()) {
    +                    String sourceStreamId = input.getKey().get_streamId();
    +                    String sourceComponentId = input.getKey().get_componentId();
    +                    if(componentMap.keySet().contains(sourceComponentId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent component [" + sourceComponentId + "]");
    +                    }
    +
    +                    ComponentCommon sourceComponent = getComponentCommon(componentMap.get(sourceComponentId));
    +                    if (sourceComponent == null || sourceComponent.get_streams().containsKey(sourceStreamId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent stream: " +
    +                                "[" + sourceStreamId + "] of component [" + sourceComponentId + "]");
    +                    }
    +
    +                    Grouping grouping = input.getValue();
    +                    if (Thrift.groupingType(grouping) == Grouping._Fields.FIELDS) {
    +                        List<String> fields = grouping.get_fields();
    +                        Map<String, StreamInfo> streams = sourceComponent.get_streams();
    +                        Set<String> sourceOutputFields = getStreamOutputFields(streams);
    +                        if (sourceOutputFields.containsAll(fields) == false) {
    +                            throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from stream: [" + sourceStreamId  +"] of component " +
    +                                    "[" + sourceComponentId + "] + with non-existent fields: " + fields);
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> ackerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> boltIds = topology.get_bolts().keySet();
    +        Set<String> spoutIds = topology.get_spouts().keySet();
    +
    +        for(String id : spoutIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_INIT_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +
    +        for(String id : boltIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_ACK_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_FAIL_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static String clusterId = null;
    +    public static IBolt makeAckerBolt() {
    +        return _instance.makeAckerBoltImpl();
    +    }
    +    public IBolt makeAckerBoltImpl() {
    +        return new Acker();
    +    }
    +
    +    public static void addAcker(Map conf, StormTopology topology) {
    +        int ackerNum = Utils.getInt(conf.get(Config.TOPOLOGY_ACKER_EXECUTORS), Utils.getInt(conf.get(Config.TOPOLOGY_WORKERS)));
    +        Map<GlobalStreamId, Grouping> inputs = ackerInputs(topology);
    +
    +        Map<String, StreamInfo> outputStreams = new HashMap<String, StreamInfo>();
    +        outputStreams.put(ACKER_ACK_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +        outputStreams.put(ACKER_FAIL_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +
    +        Map<String, Object> ackerConf = new HashMap<String, Object>();
    +        ackerConf.put(Config.TOPOLOGY_TASKS, ackerNum);
    +        ackerConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +
    +        Bolt acker = Thrift.prepareSerializedBoltDetails(inputs, makeAckerBolt(), outputStreams, ackerNum, ackerConf);
    +
    +        for(Bolt bolt : topology.get_bolts().values()) {
    +            ComponentCommon common = bolt.get_common();
    +            common.put_to_streams(ACKER_ACK_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "ack-val")));
    +            common.put_to_streams(ACKER_FAIL_STREAM_ID, Thrift.outputFields(Arrays.asList("id")));
    +        }
    +
    +        for (SpoutSpec spout : topology.get_spouts().values()) {
    +            ComponentCommon common = spout.get_common();
    +            Map spoutConf = componentConf(spout);
    +            spoutConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +            common.set_json_conf(JSONValue.toJSONString(spoutConf));
    +            common.put_to_streams(ACKER_INIT_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "init-val", "spout-task")));
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_ACK_STREAM_ID), Thrift.prepareDirectGrouping());
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_FAIL_STREAM_ID), Thrift.prepareDirectGrouping());
    +        }
    +
    +        topology.put_to_bolts(ACKER_COMPONENT_ID, acker);
    +    }
    +
    +    public static ComponentCommon getComponentCommon(Object component) {
    +        if (component == null) {
    +            return null;
    +        }
    +
    +        ComponentCommon common = null;
    +        if (component instanceof StateSpoutSpec) {
    +            common = ((StateSpoutSpec) component).get_common();
    +        } else if (component instanceof SpoutSpec) {
    +            common = ((SpoutSpec) component).get_common();
    +        } else if (component instanceof Bolt) {
    +            common = ((Bolt) component).get_common();
    +        }
    +        return common;
    +    }
    +
    +    public static void addMetricStreams(StormTopology topology) {
    +        for (Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                StreamInfo streamInfo = Thrift.outputFields(Arrays.asList("task-info", "data-points"));
    +                common.put_to_streams(Constants.METRICS_STREAM_ID, streamInfo);
    +            }
    +        }
    +    }
    +
    +    public static void addSystemStreams(StormTopology topology) {
    +        for (Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                StreamInfo streamInfo = Thrift.outputFields(Arrays.asList("event"));
    +                common.put_to_streams(SYSTEM_STREAM_ID, streamInfo);
    +            }
    +        }
    +    }
    +
    +    public static List<String> eventLoggerBoltFields() {
    +        List<String> fields = Arrays.asList(EventLoggerBolt.FIELD_COMPONENT_ID, EventLoggerBolt.FIELD_MESSAGE_ID, EventLoggerBolt.FIELD_TS,
    +                EventLoggerBolt.FIELD_VALUES);
    +        return fields;
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> eventLoggerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> allIds = new HashSet<String>();
    +        allIds.addAll(topology.get_bolts().keySet());
    +        allIds.addAll(topology.get_spouts().keySet());
    +
    +        for(String id : allIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, EVENTLOGGER_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("component-id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static void addEventLogger(Map conf, StormTopology topology) {
    +        Integer numExecutors = Utils.getInt(conf.get(Config.TOPOLOGY_EVENTLOGGER_EXECUTORS), Utils.getInt(conf.get(Config.TOPOLOGY_WORKERS)));
    +        HashMap<String, Object> componentConf = new HashMap<String, Object>();
    +        componentConf.put(Config.TOPOLOGY_TASKS, numExecutors);
    +        componentConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +        Bolt eventLoggerBolt = Thrift.prepareSerializedBoltDetails(eventLoggerInputs(topology), new EventLoggerBolt(), null, numExecutors, componentConf);
    +
    +        for(Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                common.put_to_streams(EVENTLOGGER_STREAM_ID, Thrift.outputFields(eventLoggerBoltFields()));
    +            }
    +        }
    +        topology.put_to_bolts(EVENTLOGGER_COMPONENT_ID, eventLoggerBolt);
    +    }
    +
    +    public static Map<String, Bolt> metricsConsumerBoltSpecs(Map conf, StormTopology topology) {
    +        Map<String, Bolt> metricsConsumerBolts = new HashMap<String, Bolt>();
    +
    +        Set<String> componentIdsEmitMetrics = new HashSet<String>();
    +        componentIdsEmitMetrics.addAll(allComponents(topology).keySet());
    +        componentIdsEmitMetrics.add(Constants.SYSTEM_COMPONENT_ID);
    +
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        for (String componentId : componentIdsEmitMetrics) {
    +            inputs.put(Utils.getGlobalStreamId(componentId, Constants.METRICS_STREAM_ID), Thrift.prepareShuffleGrouping());
    +        }
    +
    +        List<Map<String, Object>> registerInfo = (List<Map<String, Object>>) conf.get(Config.TOPOLOGY_METRICS_CONSUMER_REGISTER);
    +        if (registerInfo != null) {
    +            Map<String, Integer> classOccurrencesMap = new HashMap<String, Integer>();
    +            for (Map<String, Object> info : registerInfo) {
    +                String className = (String) info.get("class");
    +                Object argument = info.get("argument");
    +                Integer phintNum = Utils.getInt(info.get("parallelism.hint"), 1);
    +                Map<String, Object> metricsConsumerConf = new HashMap<String, Object>();
    +                metricsConsumerConf.put(Config.TOPOLOGY_TASKS, phintNum);
    +                Bolt metricsConsumerBolt = Thrift.prepareSerializedBoltDetails(inputs, new MetricsConsumerBolt(className, argument), null, phintNum, metricsConsumerConf);
    +
    +                String id = className;
    +                if (classOccurrencesMap.containsKey(className)) {
    +                    // e.g. [\"a\", \"b\", \"a\"]) => [\"a\", \"b\", \"a#2\"]"
    +                    int occurrenceNum = classOccurrencesMap.get(className);
    +                    occurrenceNum++;
    +                    classOccurrencesMap.put(className, occurrenceNum);
    +                    id = Constants.METRICS_COMPONENT_ID_PREFIX + className + "#" + occurrenceNum;
    +                } else {
    +                    classOccurrencesMap.put(className, 1);
    +                }
    +                metricsConsumerBolts.put(id, metricsConsumerBolt);
    +            }
    +        }
    +        return metricsConsumerBolts;
    +    }
    +
    +    public static void addMetricComponents(Map conf, StormTopology topology) {
    +        Map<String, Bolt> metricsConsumerBolts = metricsConsumerBoltSpecs(conf, topology);
    +        for (Map.Entry<String, Bolt> entry : metricsConsumerBolts.entrySet()) {
    +            topology.put_to_bolts(entry.getKey(), entry.getValue());
    +        }
    +    }
    +
    +    public static void addSystemComponents(Map conf, StormTopology topology) {
    +        Map<String, StreamInfo> outputStreams = new HashMap<String, StreamInfo>();
    +        outputStreams.put(Constants.SYSTEM_TICK_STREAM_ID, Thrift.outputFields(Arrays.asList("rate_secs")));
    +        outputStreams.put(Constants.METRICS_TICK_STREAM_ID, Thrift.outputFields(Arrays.asList("interval")));
    +        outputStreams.put(Constants.CREDENTIALS_CHANGED_STREAM_ID, Thrift.outputFields(Arrays.asList("creds")));
    +
    +        Map<String, Object> boltConf = new HashMap<String, Object>();
    +        boltConf.put(Config.TOPOLOGY_TASKS, 0);
    +
    +        Bolt systemBoltSpec = Thrift.prepareSerializedBoltDetails(null, new SystemBolt(), outputStreams, 0, boltConf);
    +        topology.put_to_bolts(Constants.SYSTEM_COMPONENT_ID, systemBoltSpec);
    +    }
    +
    +    public static StormTopology systemTopology(Map stormConf, StormTopology topology) throws InvalidTopologyException {
    +        return _instance.systemTopologyImpl(stormConf, topology);
    +    }
    +
    +    protected StormTopology systemTopologyImpl(Map stormConf, StormTopology topology) throws InvalidTopologyException {
    --- End diff --
    
    That sounds fine, but could we do it in another follow on JIRA?  This is really close to being done.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55007937
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,605 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    +        } else if (common.get_inputs() == null) {
    +            return true;
    +        } else {
    +            return common.get_inputs().isEmpty();
    +        }
    +    }
    +
    +    public static Map<String, Object> allComponents(StormTopology topology) {
    +        Map<String, Object> components = new HashMap<String, Object>();
    +        List<StormTopology._Fields> topologyFields = Arrays.asList(Thrift.getTopologyFields());
    +        for (StormTopology._Fields field : topologyFields) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                components.putAll(((Map) topology.getFieldValue(field)));
    +            }
    +        }
    +        return components;
    +    }
    +
    +    public static Map componentConf(Object component) {
    +        Map<Object, Object> conf = new HashMap<Object, Object>();
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common != null) {
    +            String jconf = common.get_json_conf();
    +            if (jconf != null) {
    +                conf.putAll((Map<Object, Object>) JSONValue.parse(jconf));
    +            }
    +        }
    +        return conf;
    +    }
    +
    +    public static void validateBasic(StormTopology topology) throws InvalidTopologyException {
    +        validateIds(topology);
    +
    +        List<StormTopology._Fields> spoutFields = Arrays.asList(Thrift.getSpoutFields());
    +        for (StormTopology._Fields field : spoutFields) {
    +            Map<String, Object> spoutComponents = (Map<String, Object>) topology.getFieldValue(field);
    +            if (spoutComponents != null) {
    +                for (Object obj : spoutComponents.values()) {
    +                    ComponentCommon common = getComponentCommon(obj);
    +                    if (isEmptyInputs(common) == false) {
    +                        throw new InvalidTopologyException("May not declare inputs for a spout");
    +                    }
    +                }
    +            }
    +        }
    +
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Object componentObj : componentMap.values()) {
    +            Map conf = componentConf(componentObj);
    +            ComponentCommon common = getComponentCommon(componentObj);
    +            if (common != null) {
    +                int parallelismHintNum = Thrift.getParallelismHint(common);
    +                Integer taskNum = Utils.getInt(conf.get(Config.TOPOLOGY_TASKS), 0);
    +                if (taskNum > 0 && parallelismHintNum <= 0) {
    +                    throw new InvalidTopologyException("Number of executors must be greater than 0 when number of tasks is greater than 0");
    +                }
    +            }
    +        }
    +    }
    +
    +    private static Set<String> getStreamOutputFields(Map<String, StreamInfo> streams) {
    +        Set<String> outputFields = new HashSet<String>();
    +        if (streams != null) {
    +            for (StreamInfo streamInfo : streams.values()) {
    +                outputFields.addAll(streamInfo.get_output_fields());
    +            }
    +        }
    +        return outputFields;
    +    }
    +
    +    public static void validateStructure(StormTopology topology) throws InvalidTopologyException {
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Map.Entry<String, Object> entry : componentMap.entrySet()) {
    +            String componentId = entry.getKey();
    +            ComponentCommon common = getComponentCommon(entry.getValue());
    +            if (common != null) {
    +                Map<GlobalStreamId, Grouping> inputs = common.get_inputs();
    +                for (Map.Entry<GlobalStreamId, Grouping> input : inputs.entrySet()) {
    +                    String sourceStreamId = input.getKey().get_streamId();
    +                    String sourceComponentId = input.getKey().get_componentId();
    +                    if(componentMap.keySet().contains(sourceComponentId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent component [" + sourceComponentId + "]");
    +                    }
    +
    +                    ComponentCommon sourceComponent = getComponentCommon(componentMap.get(sourceComponentId));
    +                    if (sourceComponent == null || sourceComponent.get_streams().containsKey(sourceStreamId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent stream: " +
    +                                "[" + sourceStreamId + "] of component [" + sourceComponentId + "]");
    +                    }
    +
    +                    Grouping grouping = input.getValue();
    +                    if (Thrift.groupingType(grouping) == Grouping._Fields.FIELDS) {
    +                        List<String> fields = grouping.get_fields();
    +                        Map<String, StreamInfo> streams = sourceComponent.get_streams();
    +                        Set<String> sourceOutputFields = getStreamOutputFields(streams);
    +                        if (sourceOutputFields.containsAll(fields) == false) {
    +                            throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from stream: [" + sourceStreamId  +"] of component " +
    +                                    "[" + sourceComponentId + "] + with non-existent fields: " + fields);
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> ackerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> boltIds = topology.get_bolts().keySet();
    +        Set<String> spoutIds = topology.get_spouts().keySet();
    +
    +        for(String id : spoutIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_INIT_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +
    +        for(String id : boltIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_ACK_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_FAIL_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static String clusterId = null;
    +    public static IBolt makeAckerBolt() {
    +        return _instance.makeAckerBoltImpl();
    +    }
    +    public IBolt makeAckerBoltImpl() {
    +        return new Acker();
    +    }
    +
    +    public static void addAcker(Map conf, StormTopology topology) {
    +        int ackerNum = Utils.getInt(conf.get(Config.TOPOLOGY_ACKER_EXECUTORS), Utils.getInt(conf.get(Config.TOPOLOGY_WORKERS)));
    +        Map<GlobalStreamId, Grouping> inputs = ackerInputs(topology);
    +
    +        Map<String, StreamInfo> outputStreams = new HashMap<String, StreamInfo>();
    +        outputStreams.put(ACKER_ACK_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +        outputStreams.put(ACKER_FAIL_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +
    +        Map<String, Object> ackerConf = new HashMap<String, Object>();
    +        ackerConf.put(Config.TOPOLOGY_TASKS, ackerNum);
    +        ackerConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +
    +        Bolt acker = Thrift.prepareSerializedBoltDetails(inputs, makeAckerBolt(), outputStreams, ackerNum, ackerConf);
    +
    +        for(Bolt bolt : topology.get_bolts().values()) {
    +            ComponentCommon common = bolt.get_common();
    +            common.put_to_streams(ACKER_ACK_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "ack-val")));
    +            common.put_to_streams(ACKER_FAIL_STREAM_ID, Thrift.outputFields(Arrays.asList("id")));
    +        }
    +
    +        for (SpoutSpec spout : topology.get_spouts().values()) {
    +            ComponentCommon common = spout.get_common();
    +            Map spoutConf = componentConf(spout);
    +            spoutConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +            common.set_json_conf(JSONValue.toJSONString(spoutConf));
    +            common.put_to_streams(ACKER_INIT_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "init-val", "spout-task")));
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_ACK_STREAM_ID), Thrift.prepareDirectGrouping());
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_FAIL_STREAM_ID), Thrift.prepareDirectGrouping());
    +        }
    +
    +        topology.put_to_bolts(ACKER_COMPONENT_ID, acker);
    +    }
    +
    +    public static ComponentCommon getComponentCommon(Object component) {
    +        if (component == null) {
    +            return null;
    +        }
    +
    +        ComponentCommon common = null;
    +        if (component instanceof StateSpoutSpec) {
    +            common = ((StateSpoutSpec) component).get_common();
    +        } else if (component instanceof SpoutSpec) {
    +            common = ((SpoutSpec) component).get_common();
    +        } else if (component instanceof Bolt) {
    +            common = ((Bolt) component).get_common();
    +        }
    +        return common;
    +    }
    +
    +    public static void addMetricStreams(StormTopology topology) {
    +        for (Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                StreamInfo streamInfo = Thrift.outputFields(Arrays.asList("task-info", "data-points"));
    +                common.put_to_streams(Constants.METRICS_STREAM_ID, streamInfo);
    +            }
    +        }
    +    }
    +
    +    public static void addSystemStreams(StormTopology topology) {
    +        for (Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                StreamInfo streamInfo = Thrift.outputFields(Arrays.asList("event"));
    +                common.put_to_streams(SYSTEM_STREAM_ID, streamInfo);
    +            }
    +        }
    +    }
    +
    +    public static List<String> eventLoggerBoltFields() {
    +        List<String> fields = Arrays.asList(EventLoggerBolt.FIELD_COMPONENT_ID, EventLoggerBolt.FIELD_MESSAGE_ID, EventLoggerBolt.FIELD_TS,
    +                EventLoggerBolt.FIELD_VALUES);
    +        return fields;
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> eventLoggerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> allIds = new HashSet<String>();
    +        allIds.addAll(topology.get_bolts().keySet());
    +        allIds.addAll(topology.get_spouts().keySet());
    +
    +        for(String id : allIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, EVENTLOGGER_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("component-id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static void addEventLogger(Map conf, StormTopology topology) {
    +        Integer numExecutors = Utils.getInt(conf.get(Config.TOPOLOGY_EVENTLOGGER_EXECUTORS), Utils.getInt(conf.get(Config.TOPOLOGY_WORKERS)));
    +        HashMap<String, Object> componentConf = new HashMap<String, Object>();
    +        componentConf.put(Config.TOPOLOGY_TASKS, numExecutors);
    +        componentConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +        Bolt eventLoggerBolt = Thrift.prepareSerializedBoltDetails(eventLoggerInputs(topology), new EventLoggerBolt(), null, numExecutors, componentConf);
    +
    +        for(Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                common.put_to_streams(EVENTLOGGER_STREAM_ID, Thrift.outputFields(eventLoggerBoltFields()));
    +            }
    +        }
    +        topology.put_to_bolts(EVENTLOGGER_COMPONENT_ID, eventLoggerBolt);
    +    }
    +
    +    public static Map<String, Bolt> metricsConsumerBoltSpecs(Map conf, StormTopology topology) {
    +        Map<String, Bolt> metricsConsumerBolts = new HashMap<String, Bolt>();
    +
    +        Set<String> componentIdsEmitMetrics = new HashSet<String>();
    +        componentIdsEmitMetrics.addAll(allComponents(topology).keySet());
    +        componentIdsEmitMetrics.add(Constants.SYSTEM_COMPONENT_ID);
    +
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        for (String componentId : componentIdsEmitMetrics) {
    +            inputs.put(Utils.getGlobalStreamId(componentId, Constants.METRICS_STREAM_ID), Thrift.prepareShuffleGrouping());
    +        }
    +
    +        List<Map<String, Object>> registerInfo = (List<Map<String, Object>>) conf.get(Config.TOPOLOGY_METRICS_CONSUMER_REGISTER);
    +        if (registerInfo != null) {
    +            Map<String, Integer> classOccurrencesMap = new HashMap<String, Integer>();
    +            for (Map<String, Object> info : registerInfo) {
    +                String className = (String) info.get("class");
    +                Object argument = info.get("argument");
    +                Integer phintNum = Utils.getInt(info.get("parallelism.hint"), 1);
    +                Map<String, Object> metricsConsumerConf = new HashMap<String, Object>();
    +                metricsConsumerConf.put(Config.TOPOLOGY_TASKS, phintNum);
    +                Bolt metricsConsumerBolt = Thrift.prepareSerializedBoltDetails(inputs, new MetricsConsumerBolt(className, argument), null, phintNum, metricsConsumerConf);
    +
    +                String id = className;
    +                if (classOccurrencesMap.containsKey(className)) {
    +                    // e.g. [\"a\", \"b\", \"a\"]) => [\"a\", \"b\", \"a#2\"]"
    +                    int occurrenceNum = classOccurrencesMap.get(className);
    +                    occurrenceNum++;
    +                    classOccurrencesMap.put(className, occurrenceNum);
    +                    id = Constants.METRICS_COMPONENT_ID_PREFIX + className + "#" + occurrenceNum;
    +                } else {
    +                    classOccurrencesMap.put(className, 1);
    +                }
    +                metricsConsumerBolts.put(id, metricsConsumerBolt);
    +            }
    +        }
    +        return metricsConsumerBolts;
    +    }
    +
    +    public static void addMetricComponents(Map conf, StormTopology topology) {
    +        Map<String, Bolt> metricsConsumerBolts = metricsConsumerBoltSpecs(conf, topology);
    +        for (Map.Entry<String, Bolt> entry : metricsConsumerBolts.entrySet()) {
    +            topology.put_to_bolts(entry.getKey(), entry.getValue());
    +        }
    +    }
    +
    +    public static void addSystemComponents(Map conf, StormTopology topology) {
    +        Map<String, StreamInfo> outputStreams = new HashMap<String, StreamInfo>();
    +        outputStreams.put(Constants.SYSTEM_TICK_STREAM_ID, Thrift.outputFields(Arrays.asList("rate_secs")));
    +        outputStreams.put(Constants.METRICS_TICK_STREAM_ID, Thrift.outputFields(Arrays.asList("interval")));
    +        outputStreams.put(Constants.CREDENTIALS_CHANGED_STREAM_ID, Thrift.outputFields(Arrays.asList("creds")));
    +
    +        Map<String, Object> boltConf = new HashMap<String, Object>();
    +        boltConf.put(Config.TOPOLOGY_TASKS, 0);
    +
    +        Bolt systemBoltSpec = Thrift.prepareSerializedBoltDetails(null, new SystemBolt(), outputStreams, 0, boltConf);
    +        topology.put_to_bolts(Constants.SYSTEM_COMPONENT_ID, systemBoltSpec);
    +    }
    +
    +    public static StormTopology systemTopology(Map stormConf, StormTopology topology) throws InvalidTopologyException {
    +        return _instance.systemTopologyImpl(stormConf, topology);
    +    }
    +
    +    protected StormTopology systemTopologyImpl(Map stormConf, StormTopology topology) throws InvalidTopologyException {
    --- End diff --
    
    this function and the functions called by it can be moved to a different class SystemTopologyBuilder


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

Posted by abhishekagarwal87 <gi...@git.apache.org>.
Github user abhishekagarwal87 commented on the pull request:

    https://github.com/apache/storm/pull/1185#issuecomment-194748171
  
    I am fine with refactoring system topology builder in separate JIRA. 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55277889
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,604 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    +        } else if (common.get_inputs() == null) {
    +            return true;
    +        } else {
    +            return common.get_inputs().isEmpty();
    +        }
    +    }
    +
    +    public static Map<String, Object> allComponents(StormTopology topology) {
    +        Map<String, Object> components = new HashMap<String, Object>();
    +        List<StormTopology._Fields> topologyFields = Arrays.asList(Thrift.getTopologyFields());
    +        for (StormTopology._Fields field : topologyFields) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                components.putAll(((Map) topology.getFieldValue(field)));
    +            }
    +        }
    +        return components;
    +    }
    +
    +    public static Map componentConf(Object component) {
    +        Map<Object, Object> conf = new HashMap<Object, Object>();
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common != null) {
    +            String jconf = common.get_json_conf();
    +            if (jconf != null) {
    +                conf.putAll((Map<Object, Object>) JSONValue.parse(jconf));
    +            }
    +        }
    +        return conf;
    +    }
    +
    +    public static void validateBasic(StormTopology topology) throws InvalidTopologyException {
    +        validateIds(topology);
    +
    +        List<StormTopology._Fields> spoutFields = Arrays.asList(Thrift.getSpoutFields());
    +        for (StormTopology._Fields field : spoutFields) {
    +            Map<String, Object> spoutComponents = (Map<String, Object>) topology.getFieldValue(field);
    +            if (spoutComponents != null) {
    +                for (Object obj : spoutComponents.values()) {
    +                    ComponentCommon common = getComponentCommon(obj);
    +                    if (isEmptyInputs(common) == false) {
    +                        throw new InvalidTopologyException("May not declare inputs for a spout");
    +                    }
    +                }
    +            }
    +        }
    +
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Object componentObj : componentMap.values()) {
    +            Map conf = componentConf(componentObj);
    +            ComponentCommon common = getComponentCommon(componentObj);
    +            if (common != null) {
    +                int parallelismHintNum = Thrift.getParallelismHint(common);
    +                Integer taskNum = Utils.getInt(conf.get(Config.TOPOLOGY_TASKS), 0);
    +                if (taskNum > 0 && parallelismHintNum <= 0) {
    +                    throw new InvalidTopologyException("Number of executors must be greater than 0 when number of tasks is greater than 0");
    +                }
    +            }
    +        }
    +    }
    +
    +    private static Set<String> getStreamOutputFields(Map<String, StreamInfo> streams) {
    +        Set<String> outputFields = new HashSet<String>();
    +        if (streams != null) {
    +            for (StreamInfo streamInfo : streams.values()) {
    +                outputFields.addAll(streamInfo.get_output_fields());
    +            }
    +        }
    +        return outputFields;
    +    }
    +
    +    public static void validateStructure(StormTopology topology) throws InvalidTopologyException {
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Map.Entry<String, Object> entry : componentMap.entrySet()) {
    +            String componentId = entry.getKey();
    +            ComponentCommon common = getComponentCommon(entry.getValue());
    +            if (common != null) {
    --- End diff --
    
    This null check was not in the original code.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

Posted by revans2 <gi...@git.apache.org>.
Github user revans2 commented on the pull request:

    https://github.com/apache/storm/pull/1185#issuecomment-194443713
  
    The code looks really good an I am +1 for merging it in as is.  There are still a few nits though. one with CommonInstaller and another that @arunmahadevan pointed out for SystemTopologyBuilder that we need to come to a resolution on.
    
    Also you need to upmerge the drpc changes that went in have caused a minor conflict.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55280379
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,604 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    +        } else if (common.get_inputs() == null) {
    +            return true;
    +        } else {
    +            return common.get_inputs().isEmpty();
    +        }
    +    }
    +
    +    public static Map<String, Object> allComponents(StormTopology topology) {
    +        Map<String, Object> components = new HashMap<String, Object>();
    +        List<StormTopology._Fields> topologyFields = Arrays.asList(Thrift.getTopologyFields());
    +        for (StormTopology._Fields field : topologyFields) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                components.putAll(((Map) topology.getFieldValue(field)));
    +            }
    +        }
    +        return components;
    +    }
    +
    +    public static Map componentConf(Object component) {
    +        Map<Object, Object> conf = new HashMap<Object, Object>();
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common != null) {
    +            String jconf = common.get_json_conf();
    +            if (jconf != null) {
    +                conf.putAll((Map<Object, Object>) JSONValue.parse(jconf));
    +            }
    +        }
    +        return conf;
    +    }
    +
    +    public static void validateBasic(StormTopology topology) throws InvalidTopologyException {
    +        validateIds(topology);
    +
    +        List<StormTopology._Fields> spoutFields = Arrays.asList(Thrift.getSpoutFields());
    +        for (StormTopology._Fields field : spoutFields) {
    +            Map<String, Object> spoutComponents = (Map<String, Object>) topology.getFieldValue(field);
    +            if (spoutComponents != null) {
    +                for (Object obj : spoutComponents.values()) {
    +                    ComponentCommon common = getComponentCommon(obj);
    +                    if (isEmptyInputs(common) == false) {
    +                        throw new InvalidTopologyException("May not declare inputs for a spout");
    +                    }
    +                }
    +            }
    +        }
    +
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Object componentObj : componentMap.values()) {
    +            Map conf = componentConf(componentObj);
    +            ComponentCommon common = getComponentCommon(componentObj);
    +            if (common != null) {
    +                int parallelismHintNum = Thrift.getParallelismHint(common);
    +                Integer taskNum = Utils.getInt(conf.get(Config.TOPOLOGY_TASKS), 0);
    +                if (taskNum > 0 && parallelismHintNum <= 0) {
    +                    throw new InvalidTopologyException("Number of executors must be greater than 0 when number of tasks is greater than 0");
    +                }
    +            }
    +        }
    +    }
    +
    +    private static Set<String> getStreamOutputFields(Map<String, StreamInfo> streams) {
    +        Set<String> outputFields = new HashSet<String>();
    +        if (streams != null) {
    +            for (StreamInfo streamInfo : streams.values()) {
    +                outputFields.addAll(streamInfo.get_output_fields());
    +            }
    +        }
    +        return outputFields;
    +    }
    +
    +    public static void validateStructure(StormTopology topology) throws InvalidTopologyException {
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Map.Entry<String, Object> entry : componentMap.entrySet()) {
    +            String componentId = entry.getKey();
    +            ComponentCommon common = getComponentCommon(entry.getValue());
    +            if (common != null) {
    +                Map<GlobalStreamId, Grouping> inputs = common.get_inputs();
    +                for (Map.Entry<GlobalStreamId, Grouping> input : inputs.entrySet()) {
    +                    String sourceStreamId = input.getKey().get_streamId();
    +                    String sourceComponentId = input.getKey().get_componentId();
    +                    if(componentMap.keySet().contains(sourceComponentId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent component [" + sourceComponentId + "]");
    +                    }
    +
    +                    ComponentCommon sourceComponent = getComponentCommon(componentMap.get(sourceComponentId));
    +                    if (sourceComponent == null || sourceComponent.get_streams().containsKey(sourceStreamId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent stream: " +
    +                                "[" + sourceStreamId + "] of component [" + sourceComponentId + "]");
    +                    }
    +
    +                    Grouping grouping = input.getValue();
    +                    if (Thrift.groupingType(grouping) == Grouping._Fields.FIELDS) {
    +                        List<String> fields = grouping.get_fields();
    +                        Map<String, StreamInfo> streams = sourceComponent.get_streams();
    +                        Set<String> sourceOutputFields = getStreamOutputFields(streams);
    +                        if (sourceOutputFields.containsAll(fields) == false) {
    +                            throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from stream: [" + sourceStreamId  +"] of component " +
    +                                    "[" + sourceComponentId + "] + with non-existent fields: " + fields);
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> ackerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> boltIds = topology.get_bolts().keySet();
    +        Set<String> spoutIds = topology.get_spouts().keySet();
    +
    +        for(String id : spoutIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_INIT_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +
    +        for(String id : boltIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_ACK_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_FAIL_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static IBolt makeAckerBolt() {
    +        return _instance.makeAckerBoltImpl();
    +    }
    +    public IBolt makeAckerBoltImpl() {
    +        return new Acker();
    +    }
    +
    +    public static void addAcker(Map conf, StormTopology topology) {
    +        int ackerNum = Utils.getInt(conf.get(Config.TOPOLOGY_ACKER_EXECUTORS), Utils.getInt(conf.get(Config.TOPOLOGY_WORKERS)));
    +        Map<GlobalStreamId, Grouping> inputs = ackerInputs(topology);
    +
    +        Map<String, StreamInfo> outputStreams = new HashMap<String, StreamInfo>();
    +        outputStreams.put(ACKER_ACK_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +        outputStreams.put(ACKER_FAIL_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +
    +        Map<String, Object> ackerConf = new HashMap<String, Object>();
    +        ackerConf.put(Config.TOPOLOGY_TASKS, ackerNum);
    +        ackerConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +
    +        Bolt acker = Thrift.prepareSerializedBoltDetails(inputs, makeAckerBolt(), outputStreams, ackerNum, ackerConf);
    +
    +        for(Bolt bolt : topology.get_bolts().values()) {
    +            ComponentCommon common = bolt.get_common();
    +            common.put_to_streams(ACKER_ACK_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "ack-val")));
    +            common.put_to_streams(ACKER_FAIL_STREAM_ID, Thrift.outputFields(Arrays.asList("id")));
    +        }
    +
    +        for (SpoutSpec spout : topology.get_spouts().values()) {
    +            ComponentCommon common = spout.get_common();
    +            Map spoutConf = componentConf(spout);
    +            spoutConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +            common.set_json_conf(JSONValue.toJSONString(spoutConf));
    +            common.put_to_streams(ACKER_INIT_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "init-val", "spout-task")));
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_ACK_STREAM_ID), Thrift.prepareDirectGrouping());
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_FAIL_STREAM_ID), Thrift.prepareDirectGrouping());
    +        }
    +
    +        topology.put_to_bolts(ACKER_COMPONENT_ID, acker);
    +    }
    +
    +    public static ComponentCommon getComponentCommon(Object component) {
    +        if (component == null) {
    +            return null;
    +        }
    +
    +        ComponentCommon common = null;
    +        if (component instanceof StateSpoutSpec) {
    +            common = ((StateSpoutSpec) component).get_common();
    +        } else if (component instanceof SpoutSpec) {
    +            common = ((SpoutSpec) component).get_common();
    +        } else if (component instanceof Bolt) {
    +            common = ((Bolt) component).get_common();
    +        }
    +        return common;
    +    }
    +
    +    public static void addMetricStreams(StormTopology topology) {
    +        for (Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                StreamInfo streamInfo = Thrift.outputFields(Arrays.asList("task-info", "data-points"));
    +                common.put_to_streams(Constants.METRICS_STREAM_ID, streamInfo);
    +            }
    +        }
    +    }
    +
    +    public static void addSystemStreams(StormTopology topology) {
    +        for (Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    --- End diff --
    
    Again no null check in original code.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55285131
  
    --- Diff: storm-core/test/jvm/org/apache/storm/utils/staticmocking/CommonInstaller.java ---
    @@ -0,0 +1,38 @@
    +/**
    + * 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.storm.utils.staticmocking;
    +
    +import org.apache.storm.daemon.StormCommon;
    +
    +public class CommonInstaller implements AutoCloseable {
    --- End diff --
    
    Do we need this and StormCommonInstaller???


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55503834
  
    --- Diff: storm-core/test/jvm/org/apache/storm/utils/staticmocking/CommonInstaller.java ---
    @@ -0,0 +1,38 @@
    +/**
    + * 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.storm.utils.staticmocking;
    +
    +import org.apache.storm.daemon.StormCommon;
    +
    +public class CommonInstaller implements AutoCloseable {
    --- End diff --
    
    CommonInstaller is used for mocking in clojure testing. It is the same way of mocking as Utils and ConfigUtils. I am not sure if there is a better solution. Any suggestion?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55284650
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,604 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    +        } else if (common.get_inputs() == null) {
    +            return true;
    +        } else {
    +            return common.get_inputs().isEmpty();
    +        }
    +    }
    +
    +    public static Map<String, Object> allComponents(StormTopology topology) {
    +        Map<String, Object> components = new HashMap<String, Object>();
    +        List<StormTopology._Fields> topologyFields = Arrays.asList(Thrift.getTopologyFields());
    +        for (StormTopology._Fields field : topologyFields) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                components.putAll(((Map) topology.getFieldValue(field)));
    +            }
    +        }
    +        return components;
    +    }
    +
    +    public static Map componentConf(Object component) {
    +        Map<Object, Object> conf = new HashMap<Object, Object>();
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common != null) {
    +            String jconf = common.get_json_conf();
    +            if (jconf != null) {
    +                conf.putAll((Map<Object, Object>) JSONValue.parse(jconf));
    +            }
    +        }
    +        return conf;
    +    }
    +
    +    public static void validateBasic(StormTopology topology) throws InvalidTopologyException {
    +        validateIds(topology);
    +
    +        List<StormTopology._Fields> spoutFields = Arrays.asList(Thrift.getSpoutFields());
    +        for (StormTopology._Fields field : spoutFields) {
    +            Map<String, Object> spoutComponents = (Map<String, Object>) topology.getFieldValue(field);
    +            if (spoutComponents != null) {
    +                for (Object obj : spoutComponents.values()) {
    +                    ComponentCommon common = getComponentCommon(obj);
    +                    if (isEmptyInputs(common) == false) {
    +                        throw new InvalidTopologyException("May not declare inputs for a spout");
    +                    }
    +                }
    +            }
    +        }
    +
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Object componentObj : componentMap.values()) {
    +            Map conf = componentConf(componentObj);
    +            ComponentCommon common = getComponentCommon(componentObj);
    +            if (common != null) {
    +                int parallelismHintNum = Thrift.getParallelismHint(common);
    +                Integer taskNum = Utils.getInt(conf.get(Config.TOPOLOGY_TASKS), 0);
    +                if (taskNum > 0 && parallelismHintNum <= 0) {
    +                    throw new InvalidTopologyException("Number of executors must be greater than 0 when number of tasks is greater than 0");
    +                }
    +            }
    +        }
    +    }
    +
    +    private static Set<String> getStreamOutputFields(Map<String, StreamInfo> streams) {
    +        Set<String> outputFields = new HashSet<String>();
    +        if (streams != null) {
    +            for (StreamInfo streamInfo : streams.values()) {
    +                outputFields.addAll(streamInfo.get_output_fields());
    +            }
    +        }
    +        return outputFields;
    +    }
    +
    +    public static void validateStructure(StormTopology topology) throws InvalidTopologyException {
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Map.Entry<String, Object> entry : componentMap.entrySet()) {
    +            String componentId = entry.getKey();
    +            ComponentCommon common = getComponentCommon(entry.getValue());
    +            if (common != null) {
    +                Map<GlobalStreamId, Grouping> inputs = common.get_inputs();
    +                for (Map.Entry<GlobalStreamId, Grouping> input : inputs.entrySet()) {
    +                    String sourceStreamId = input.getKey().get_streamId();
    +                    String sourceComponentId = input.getKey().get_componentId();
    +                    if(componentMap.keySet().contains(sourceComponentId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent component [" + sourceComponentId + "]");
    +                    }
    +
    +                    ComponentCommon sourceComponent = getComponentCommon(componentMap.get(sourceComponentId));
    +                    if (sourceComponent == null || sourceComponent.get_streams().containsKey(sourceStreamId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent stream: " +
    +                                "[" + sourceStreamId + "] of component [" + sourceComponentId + "]");
    +                    }
    +
    +                    Grouping grouping = input.getValue();
    +                    if (Thrift.groupingType(grouping) == Grouping._Fields.FIELDS) {
    +                        List<String> fields = grouping.get_fields();
    +                        Map<String, StreamInfo> streams = sourceComponent.get_streams();
    +                        Set<String> sourceOutputFields = getStreamOutputFields(streams);
    +                        if (sourceOutputFields.containsAll(fields) == false) {
    +                            throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from stream: [" + sourceStreamId  +"] of component " +
    +                                    "[" + sourceComponentId + "] + with non-existent fields: " + fields);
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> ackerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> boltIds = topology.get_bolts().keySet();
    +        Set<String> spoutIds = topology.get_spouts().keySet();
    +
    +        for(String id : spoutIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_INIT_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +
    +        for(String id : boltIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_ACK_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_FAIL_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static IBolt makeAckerBolt() {
    +        return _instance.makeAckerBoltImpl();
    +    }
    +    public IBolt makeAckerBoltImpl() {
    +        return new Acker();
    +    }
    +
    +    public static void addAcker(Map conf, StormTopology topology) {
    +        int ackerNum = Utils.getInt(conf.get(Config.TOPOLOGY_ACKER_EXECUTORS), Utils.getInt(conf.get(Config.TOPOLOGY_WORKERS)));
    +        Map<GlobalStreamId, Grouping> inputs = ackerInputs(topology);
    +
    +        Map<String, StreamInfo> outputStreams = new HashMap<String, StreamInfo>();
    +        outputStreams.put(ACKER_ACK_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +        outputStreams.put(ACKER_FAIL_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +
    +        Map<String, Object> ackerConf = new HashMap<String, Object>();
    +        ackerConf.put(Config.TOPOLOGY_TASKS, ackerNum);
    +        ackerConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +
    +        Bolt acker = Thrift.prepareSerializedBoltDetails(inputs, makeAckerBolt(), outputStreams, ackerNum, ackerConf);
    +
    +        for(Bolt bolt : topology.get_bolts().values()) {
    +            ComponentCommon common = bolt.get_common();
    +            common.put_to_streams(ACKER_ACK_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "ack-val")));
    +            common.put_to_streams(ACKER_FAIL_STREAM_ID, Thrift.outputFields(Arrays.asList("id")));
    +        }
    +
    +        for (SpoutSpec spout : topology.get_spouts().values()) {
    +            ComponentCommon common = spout.get_common();
    +            Map spoutConf = componentConf(spout);
    +            spoutConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +            common.set_json_conf(JSONValue.toJSONString(spoutConf));
    +            common.put_to_streams(ACKER_INIT_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "init-val", "spout-task")));
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_ACK_STREAM_ID), Thrift.prepareDirectGrouping());
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_FAIL_STREAM_ID), Thrift.prepareDirectGrouping());
    +        }
    +
    +        topology.put_to_bolts(ACKER_COMPONENT_ID, acker);
    +    }
    +
    +    public static ComponentCommon getComponentCommon(Object component) {
    +        if (component == null) {
    +            return null;
    +        }
    +
    +        ComponentCommon common = null;
    +        if (component instanceof StateSpoutSpec) {
    +            common = ((StateSpoutSpec) component).get_common();
    +        } else if (component instanceof SpoutSpec) {
    +            common = ((SpoutSpec) component).get_common();
    +        } else if (component instanceof Bolt) {
    +            common = ((Bolt) component).get_common();
    +        }
    +        return common;
    +    }
    +
    +    public static void addMetricStreams(StormTopology topology) {
    +        for (Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                StreamInfo streamInfo = Thrift.outputFields(Arrays.asList("task-info", "data-points"));
    +                common.put_to_streams(Constants.METRICS_STREAM_ID, streamInfo);
    +            }
    +        }
    +    }
    +
    +    public static void addSystemStreams(StormTopology topology) {
    +        for (Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                StreamInfo streamInfo = Thrift.outputFields(Arrays.asList("event"));
    +                common.put_to_streams(SYSTEM_STREAM_ID, streamInfo);
    +            }
    +        }
    +    }
    +
    +    public static List<String> eventLoggerBoltFields() {
    +        List<String> fields = Arrays.asList(EventLoggerBolt.FIELD_COMPONENT_ID, EventLoggerBolt.FIELD_MESSAGE_ID, EventLoggerBolt.FIELD_TS,
    +                EventLoggerBolt.FIELD_VALUES);
    +        return fields;
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> eventLoggerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> allIds = new HashSet<String>();
    +        allIds.addAll(topology.get_bolts().keySet());
    +        allIds.addAll(topology.get_spouts().keySet());
    +
    +        for(String id : allIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, EVENTLOGGER_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("component-id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static void addEventLogger(Map conf, StormTopology topology) {
    +        Integer numExecutors = Utils.getInt(conf.get(Config.TOPOLOGY_EVENTLOGGER_EXECUTORS), Utils.getInt(conf.get(Config.TOPOLOGY_WORKERS)));
    +        HashMap<String, Object> componentConf = new HashMap<String, Object>();
    +        componentConf.put(Config.TOPOLOGY_TASKS, numExecutors);
    +        componentConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +        Bolt eventLoggerBolt = Thrift.prepareSerializedBoltDetails(eventLoggerInputs(topology), new EventLoggerBolt(), null, numExecutors, componentConf);
    +
    +        for(Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                common.put_to_streams(EVENTLOGGER_STREAM_ID, Thrift.outputFields(eventLoggerBoltFields()));
    +            }
    +        }
    +        topology.put_to_bolts(EVENTLOGGER_COMPONENT_ID, eventLoggerBolt);
    +    }
    +
    +    public static Map<String, Bolt> metricsConsumerBoltSpecs(Map conf, StormTopology topology) {
    +        Map<String, Bolt> metricsConsumerBolts = new HashMap<String, Bolt>();
    +
    +        Set<String> componentIdsEmitMetrics = new HashSet<String>();
    +        componentIdsEmitMetrics.addAll(allComponents(topology).keySet());
    +        componentIdsEmitMetrics.add(Constants.SYSTEM_COMPONENT_ID);
    +
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        for (String componentId : componentIdsEmitMetrics) {
    +            inputs.put(Utils.getGlobalStreamId(componentId, Constants.METRICS_STREAM_ID), Thrift.prepareShuffleGrouping());
    +        }
    +
    +        List<Map<String, Object>> registerInfo = (List<Map<String, Object>>) conf.get(Config.TOPOLOGY_METRICS_CONSUMER_REGISTER);
    +        if (registerInfo != null) {
    +            Map<String, Integer> classOccurrencesMap = new HashMap<String, Integer>();
    +            for (Map<String, Object> info : registerInfo) {
    +                String className = (String) info.get("class");
    +                Object argument = info.get("argument");
    +                Integer phintNum = Utils.getInt(info.get("parallelism.hint"), 1);
    +                Map<String, Object> metricsConsumerConf = new HashMap<String, Object>();
    +                metricsConsumerConf.put(Config.TOPOLOGY_TASKS, phintNum);
    +                Bolt metricsConsumerBolt = Thrift.prepareSerializedBoltDetails(inputs, new MetricsConsumerBolt(className, argument), null, phintNum, metricsConsumerConf);
    +
    +                String id = className;
    +                if (classOccurrencesMap.containsKey(className)) {
    +                    // e.g. [\"a\", \"b\", \"a\"]) => [\"a\", \"b\", \"a#2\"]"
    +                    int occurrenceNum = classOccurrencesMap.get(className);
    +                    occurrenceNum++;
    +                    classOccurrencesMap.put(className, occurrenceNum);
    +                    id = Constants.METRICS_COMPONENT_ID_PREFIX + className + "#" + occurrenceNum;
    +                } else {
    +                    classOccurrencesMap.put(className, 1);
    +                }
    +                metricsConsumerBolts.put(id, metricsConsumerBolt);
    +            }
    +        }
    +        return metricsConsumerBolts;
    +    }
    +
    +    public static void addMetricComponents(Map conf, StormTopology topology) {
    +        Map<String, Bolt> metricsConsumerBolts = metricsConsumerBoltSpecs(conf, topology);
    +        for (Map.Entry<String, Bolt> entry : metricsConsumerBolts.entrySet()) {
    +            topology.put_to_bolts(entry.getKey(), entry.getValue());
    +        }
    +    }
    +
    +    public static void addSystemComponents(Map conf, StormTopology topology) {
    +        Map<String, StreamInfo> outputStreams = new HashMap<String, StreamInfo>();
    +        outputStreams.put(Constants.SYSTEM_TICK_STREAM_ID, Thrift.outputFields(Arrays.asList("rate_secs")));
    +        outputStreams.put(Constants.METRICS_TICK_STREAM_ID, Thrift.outputFields(Arrays.asList("interval")));
    +        outputStreams.put(Constants.CREDENTIALS_CHANGED_STREAM_ID, Thrift.outputFields(Arrays.asList("creds")));
    +
    +        Map<String, Object> boltConf = new HashMap<String, Object>();
    +        boltConf.put(Config.TOPOLOGY_TASKS, 0);
    +
    +        Bolt systemBoltSpec = Thrift.prepareSerializedBoltDetails(null, new SystemBolt(), outputStreams, 0, boltConf);
    +        topology.put_to_bolts(Constants.SYSTEM_COMPONENT_ID, systemBoltSpec);
    +    }
    +
    +    public static StormTopology systemTopology(Map stormConf, StormTopology topology) throws InvalidTopologyException {
    +        return _instance.systemTopologyImpl(stormConf, topology);
    +    }
    +
    +    protected StormTopology systemTopologyImpl(Map stormConf, StormTopology topology) throws InvalidTopologyException {
    +        validateBasic(topology);
    +
    +        StormTopology ret = topology.deepCopy();
    +        addAcker(stormConf, ret);
    +        addEventLogger(stormConf, ret);
    +        addMetricComponents(stormConf, ret);
    +        addSystemComponents(stormConf, ret);
    +        addMetricStreams(ret);
    +        addSystemStreams(ret);
    +
    +        validateStructure(ret);
    +
    +        return ret;
    +    }
    +
    +    public static boolean hasAckers(Map stormConf) {
    +        Object ackerNum = stormConf.get(Config.TOPOLOGY_ACKER_EXECUTORS);
    +        if (ackerNum == null || Utils.getInt(ackerNum) > 0) {
    +            return true;
    +        } else {
    +            return false;
    +        }
    +    }
    +
    +    public static boolean hasEventLoggers(Map stormConf) {
    +        Object eventLoggerNum = stormConf.get(Config.TOPOLOGY_EVENTLOGGER_EXECUTORS);
    +        if (eventLoggerNum == null || Utils.getInt(eventLoggerNum) > 0) {
    +            return true;
    +        } else {
    +            return false;
    +        }
    +    }
    +
    +    public static int numStartExecutors(Object component) throws InvalidTopologyException {
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common == null) {
    +            throw new InvalidTopologyException("unknown component type " + component.getClass().getName());
    +        }
    +        int parallelismHintNum = Thrift.getParallelismHint(common);
    +        return parallelismHintNum;
    +    }
    +
    +    public static Map stormTaskInfo(StormTopology userTopology, Map stormConf) throws InvalidTopologyException {
    +        return _instance.stormTaskInfoImpl(userTopology, stormConf);
    +    }
    +    /*
    +     * Returns map from task -> componentId
    +     */
    +    protected Map stormTaskInfoImpl(StormTopology userTopology, Map stormConf) throws InvalidTopologyException {
    +        Map<Integer, String> taskIdToComponentId = new HashMap<Integer, String>();
    +
    +        StormTopology systemTopology = systemTopology(stormConf, userTopology);
    +        Map<String, Object> components = allComponents(systemTopology);
    +        Map<String, Integer> componentIdToTaskNum = new TreeMap<String, Integer>();
    +        for (Map.Entry<String, Object> entry : components.entrySet()) {
    +            Map conf = componentConf(entry.getValue());
    +            Object taskNum = conf.get(Config.TOPOLOGY_TASKS);
    +            if (taskNum != null) {
    +                componentIdToTaskNum.put(entry.getKey(), Utils.getInt(taskNum));
    +            }
    +        }
    +
    +        int taskId = 1;
    +        for (Map.Entry<String, Integer> entry : componentIdToTaskNum.entrySet()) {
    +            String componentId = entry.getKey();
    +            Integer taskNum = entry.getValue();
    +            while (taskNum > 0) {
    +                taskIdToComponentId.put(taskId, componentId);
    +                taskNum--;
    +                taskId++;
    +            }
    +        }
    +        return taskIdToComponentId;
    +    }
    +
    +    public static List<Integer> executorIdToTasks(List<Long> executorId) {
    +        List<Integer> taskIds = new ArrayList<Integer>();
    +        int taskId = executorId.get(0).intValue();
    +        while (taskId <= executorId.get(1).intValue()) {
    +            taskIds.add(taskId);
    +            taskId++;
    +        }
    +        return taskIds;
    +    }
    +
    +    public static Map<Integer, NodeInfo> taskToNodeport(Map<List<Long>, NodeInfo> executorToNodeport) {
    +        Map<Integer, NodeInfo> tasksToNodeport = new HashMap<Integer, NodeInfo>();
    +        for (Map.Entry<List<Long>, NodeInfo> entry : executorToNodeport.entrySet()) {
    +            List<Integer> taskIds = executorIdToTasks(entry.getKey());
    +            for (Integer taskId : taskIds) {
    +                tasksToNodeport.put(taskId, entry.getValue());
    +            }
    +        }
    +        return tasksToNodeport;
    +    }
    +
    +    public static IAuthorizer mkAuthorizationHandler(String klassName, Map conf) {
    +        return _instance.mkAuthorizationHandlerImpl(klassName, conf);
    +    }
    +
    +    protected IAuthorizer mkAuthorizationHandlerImpl(String klassName, Map conf) {
    +        IAuthorizer aznHandler = null;
    +        try {
    +            if (klassName != null) {
    +                Class aznClass = Class.forName(klassName);
    +                if (aznClass != null) {
    +                    aznHandler = (IAuthorizer) aznClass.newInstance();
    +                    if (aznHandler != null) {
    +                        aznHandler.prepare(conf);
    +                    }
    +                    LOG.debug("authorization class name:{}, class:{}, handler:{}",klassName, aznClass, aznHandler);
    +                }
    +            }
    +        } catch (Exception e) {
    +            LOG.error("Failed to make authorization handler, klassName:{}", klassName);
    +        }
    --- End diff --
    
    The original code did not catch any exceptions it just threw them.  We should do the same.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55281249
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,604 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    +        } else if (common.get_inputs() == null) {
    +            return true;
    +        } else {
    +            return common.get_inputs().isEmpty();
    +        }
    +    }
    +
    +    public static Map<String, Object> allComponents(StormTopology topology) {
    +        Map<String, Object> components = new HashMap<String, Object>();
    +        List<StormTopology._Fields> topologyFields = Arrays.asList(Thrift.getTopologyFields());
    +        for (StormTopology._Fields field : topologyFields) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                components.putAll(((Map) topology.getFieldValue(field)));
    +            }
    +        }
    +        return components;
    +    }
    +
    +    public static Map componentConf(Object component) {
    +        Map<Object, Object> conf = new HashMap<Object, Object>();
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common != null) {
    +            String jconf = common.get_json_conf();
    +            if (jconf != null) {
    +                conf.putAll((Map<Object, Object>) JSONValue.parse(jconf));
    +            }
    +        }
    +        return conf;
    +    }
    +
    +    public static void validateBasic(StormTopology topology) throws InvalidTopologyException {
    +        validateIds(topology);
    +
    +        List<StormTopology._Fields> spoutFields = Arrays.asList(Thrift.getSpoutFields());
    +        for (StormTopology._Fields field : spoutFields) {
    +            Map<String, Object> spoutComponents = (Map<String, Object>) topology.getFieldValue(field);
    +            if (spoutComponents != null) {
    +                for (Object obj : spoutComponents.values()) {
    +                    ComponentCommon common = getComponentCommon(obj);
    +                    if (isEmptyInputs(common) == false) {
    +                        throw new InvalidTopologyException("May not declare inputs for a spout");
    +                    }
    +                }
    +            }
    +        }
    +
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Object componentObj : componentMap.values()) {
    +            Map conf = componentConf(componentObj);
    +            ComponentCommon common = getComponentCommon(componentObj);
    +            if (common != null) {
    +                int parallelismHintNum = Thrift.getParallelismHint(common);
    +                Integer taskNum = Utils.getInt(conf.get(Config.TOPOLOGY_TASKS), 0);
    +                if (taskNum > 0 && parallelismHintNum <= 0) {
    +                    throw new InvalidTopologyException("Number of executors must be greater than 0 when number of tasks is greater than 0");
    +                }
    +            }
    +        }
    +    }
    +
    +    private static Set<String> getStreamOutputFields(Map<String, StreamInfo> streams) {
    +        Set<String> outputFields = new HashSet<String>();
    +        if (streams != null) {
    +            for (StreamInfo streamInfo : streams.values()) {
    +                outputFields.addAll(streamInfo.get_output_fields());
    +            }
    +        }
    +        return outputFields;
    +    }
    +
    +    public static void validateStructure(StormTopology topology) throws InvalidTopologyException {
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Map.Entry<String, Object> entry : componentMap.entrySet()) {
    +            String componentId = entry.getKey();
    +            ComponentCommon common = getComponentCommon(entry.getValue());
    +            if (common != null) {
    +                Map<GlobalStreamId, Grouping> inputs = common.get_inputs();
    +                for (Map.Entry<GlobalStreamId, Grouping> input : inputs.entrySet()) {
    +                    String sourceStreamId = input.getKey().get_streamId();
    +                    String sourceComponentId = input.getKey().get_componentId();
    +                    if(componentMap.keySet().contains(sourceComponentId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent component [" + sourceComponentId + "]");
    +                    }
    +
    +                    ComponentCommon sourceComponent = getComponentCommon(componentMap.get(sourceComponentId));
    +                    if (sourceComponent == null || sourceComponent.get_streams().containsKey(sourceStreamId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent stream: " +
    +                                "[" + sourceStreamId + "] of component [" + sourceComponentId + "]");
    +                    }
    +
    +                    Grouping grouping = input.getValue();
    +                    if (Thrift.groupingType(grouping) == Grouping._Fields.FIELDS) {
    +                        List<String> fields = grouping.get_fields();
    +                        Map<String, StreamInfo> streams = sourceComponent.get_streams();
    +                        Set<String> sourceOutputFields = getStreamOutputFields(streams);
    +                        if (sourceOutputFields.containsAll(fields) == false) {
    +                            throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from stream: [" + sourceStreamId  +"] of component " +
    +                                    "[" + sourceComponentId + "] + with non-existent fields: " + fields);
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> ackerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> boltIds = topology.get_bolts().keySet();
    +        Set<String> spoutIds = topology.get_spouts().keySet();
    +
    +        for(String id : spoutIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_INIT_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +
    +        for(String id : boltIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_ACK_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_FAIL_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static IBolt makeAckerBolt() {
    +        return _instance.makeAckerBoltImpl();
    +    }
    +    public IBolt makeAckerBoltImpl() {
    +        return new Acker();
    +    }
    +
    +    public static void addAcker(Map conf, StormTopology topology) {
    +        int ackerNum = Utils.getInt(conf.get(Config.TOPOLOGY_ACKER_EXECUTORS), Utils.getInt(conf.get(Config.TOPOLOGY_WORKERS)));
    +        Map<GlobalStreamId, Grouping> inputs = ackerInputs(topology);
    +
    +        Map<String, StreamInfo> outputStreams = new HashMap<String, StreamInfo>();
    +        outputStreams.put(ACKER_ACK_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +        outputStreams.put(ACKER_FAIL_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +
    +        Map<String, Object> ackerConf = new HashMap<String, Object>();
    +        ackerConf.put(Config.TOPOLOGY_TASKS, ackerNum);
    +        ackerConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +
    +        Bolt acker = Thrift.prepareSerializedBoltDetails(inputs, makeAckerBolt(), outputStreams, ackerNum, ackerConf);
    +
    +        for(Bolt bolt : topology.get_bolts().values()) {
    +            ComponentCommon common = bolt.get_common();
    +            common.put_to_streams(ACKER_ACK_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "ack-val")));
    +            common.put_to_streams(ACKER_FAIL_STREAM_ID, Thrift.outputFields(Arrays.asList("id")));
    +        }
    +
    +        for (SpoutSpec spout : topology.get_spouts().values()) {
    +            ComponentCommon common = spout.get_common();
    +            Map spoutConf = componentConf(spout);
    +            spoutConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +            common.set_json_conf(JSONValue.toJSONString(spoutConf));
    +            common.put_to_streams(ACKER_INIT_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "init-val", "spout-task")));
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_ACK_STREAM_ID), Thrift.prepareDirectGrouping());
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_FAIL_STREAM_ID), Thrift.prepareDirectGrouping());
    +        }
    +
    +        topology.put_to_bolts(ACKER_COMPONENT_ID, acker);
    +    }
    +
    +    public static ComponentCommon getComponentCommon(Object component) {
    +        if (component == null) {
    +            return null;
    +        }
    +
    +        ComponentCommon common = null;
    +        if (component instanceof StateSpoutSpec) {
    +            common = ((StateSpoutSpec) component).get_common();
    +        } else if (component instanceof SpoutSpec) {
    +            common = ((SpoutSpec) component).get_common();
    +        } else if (component instanceof Bolt) {
    +            common = ((Bolt) component).get_common();
    +        }
    +        return common;
    +    }
    +
    +    public static void addMetricStreams(StormTopology topology) {
    +        for (Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                StreamInfo streamInfo = Thrift.outputFields(Arrays.asList("task-info", "data-points"));
    +                common.put_to_streams(Constants.METRICS_STREAM_ID, streamInfo);
    +            }
    +        }
    +    }
    +
    +    public static void addSystemStreams(StormTopology topology) {
    +        for (Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                StreamInfo streamInfo = Thrift.outputFields(Arrays.asList("event"));
    +                common.put_to_streams(SYSTEM_STREAM_ID, streamInfo);
    +            }
    +        }
    +    }
    +
    +    public static List<String> eventLoggerBoltFields() {
    +        List<String> fields = Arrays.asList(EventLoggerBolt.FIELD_COMPONENT_ID, EventLoggerBolt.FIELD_MESSAGE_ID, EventLoggerBolt.FIELD_TS,
    +                EventLoggerBolt.FIELD_VALUES);
    +        return fields;
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> eventLoggerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> allIds = new HashSet<String>();
    +        allIds.addAll(topology.get_bolts().keySet());
    +        allIds.addAll(topology.get_spouts().keySet());
    +
    +        for(String id : allIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, EVENTLOGGER_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("component-id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static void addEventLogger(Map conf, StormTopology topology) {
    +        Integer numExecutors = Utils.getInt(conf.get(Config.TOPOLOGY_EVENTLOGGER_EXECUTORS), Utils.getInt(conf.get(Config.TOPOLOGY_WORKERS)));
    +        HashMap<String, Object> componentConf = new HashMap<String, Object>();
    +        componentConf.put(Config.TOPOLOGY_TASKS, numExecutors);
    +        componentConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +        Bolt eventLoggerBolt = Thrift.prepareSerializedBoltDetails(eventLoggerInputs(topology), new EventLoggerBolt(), null, numExecutors, componentConf);
    +
    +        for(Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    --- End diff --
    
    No null check in the original code.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55007994
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,605 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    +        } else if (common.get_inputs() == null) {
    +            return true;
    +        } else {
    +            return common.get_inputs().isEmpty();
    +        }
    +    }
    +
    +    public static Map<String, Object> allComponents(StormTopology topology) {
    +        Map<String, Object> components = new HashMap<String, Object>();
    +        List<StormTopology._Fields> topologyFields = Arrays.asList(Thrift.getTopologyFields());
    +        for (StormTopology._Fields field : topologyFields) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                components.putAll(((Map) topology.getFieldValue(field)));
    +            }
    +        }
    +        return components;
    +    }
    +
    +    public static Map componentConf(Object component) {
    +        Map<Object, Object> conf = new HashMap<Object, Object>();
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common != null) {
    +            String jconf = common.get_json_conf();
    +            if (jconf != null) {
    +                conf.putAll((Map<Object, Object>) JSONValue.parse(jconf));
    +            }
    +        }
    +        return conf;
    +    }
    +
    +    public static void validateBasic(StormTopology topology) throws InvalidTopologyException {
    +        validateIds(topology);
    +
    +        List<StormTopology._Fields> spoutFields = Arrays.asList(Thrift.getSpoutFields());
    +        for (StormTopology._Fields field : spoutFields) {
    +            Map<String, Object> spoutComponents = (Map<String, Object>) topology.getFieldValue(field);
    +            if (spoutComponents != null) {
    +                for (Object obj : spoutComponents.values()) {
    +                    ComponentCommon common = getComponentCommon(obj);
    +                    if (isEmptyInputs(common) == false) {
    +                        throw new InvalidTopologyException("May not declare inputs for a spout");
    +                    }
    +                }
    +            }
    +        }
    +
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Object componentObj : componentMap.values()) {
    +            Map conf = componentConf(componentObj);
    +            ComponentCommon common = getComponentCommon(componentObj);
    +            if (common != null) {
    +                int parallelismHintNum = Thrift.getParallelismHint(common);
    +                Integer taskNum = Utils.getInt(conf.get(Config.TOPOLOGY_TASKS), 0);
    +                if (taskNum > 0 && parallelismHintNum <= 0) {
    +                    throw new InvalidTopologyException("Number of executors must be greater than 0 when number of tasks is greater than 0");
    +                }
    +            }
    +        }
    +    }
    +
    +    private static Set<String> getStreamOutputFields(Map<String, StreamInfo> streams) {
    +        Set<String> outputFields = new HashSet<String>();
    +        if (streams != null) {
    +            for (StreamInfo streamInfo : streams.values()) {
    +                outputFields.addAll(streamInfo.get_output_fields());
    +            }
    +        }
    +        return outputFields;
    +    }
    +
    +    public static void validateStructure(StormTopology topology) throws InvalidTopologyException {
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Map.Entry<String, Object> entry : componentMap.entrySet()) {
    +            String componentId = entry.getKey();
    +            ComponentCommon common = getComponentCommon(entry.getValue());
    +            if (common != null) {
    +                Map<GlobalStreamId, Grouping> inputs = common.get_inputs();
    +                for (Map.Entry<GlobalStreamId, Grouping> input : inputs.entrySet()) {
    +                    String sourceStreamId = input.getKey().get_streamId();
    +                    String sourceComponentId = input.getKey().get_componentId();
    +                    if(componentMap.keySet().contains(sourceComponentId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent component [" + sourceComponentId + "]");
    +                    }
    +
    +                    ComponentCommon sourceComponent = getComponentCommon(componentMap.get(sourceComponentId));
    +                    if (sourceComponent == null || sourceComponent.get_streams().containsKey(sourceStreamId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent stream: " +
    +                                "[" + sourceStreamId + "] of component [" + sourceComponentId + "]");
    +                    }
    +
    +                    Grouping grouping = input.getValue();
    +                    if (Thrift.groupingType(grouping) == Grouping._Fields.FIELDS) {
    +                        List<String> fields = grouping.get_fields();
    +                        Map<String, StreamInfo> streams = sourceComponent.get_streams();
    +                        Set<String> sourceOutputFields = getStreamOutputFields(streams);
    +                        if (sourceOutputFields.containsAll(fields) == false) {
    +                            throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from stream: [" + sourceStreamId  +"] of component " +
    +                                    "[" + sourceComponentId + "] + with non-existent fields: " + fields);
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> ackerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> boltIds = topology.get_bolts().keySet();
    +        Set<String> spoutIds = topology.get_spouts().keySet();
    +
    +        for(String id : spoutIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_INIT_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +
    +        for(String id : boltIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_ACK_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_FAIL_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static String clusterId = null;
    +    public static IBolt makeAckerBolt() {
    +        return _instance.makeAckerBoltImpl();
    +    }
    +    public IBolt makeAckerBoltImpl() {
    +        return new Acker();
    +    }
    +
    +    public static void addAcker(Map conf, StormTopology topology) {
    +        int ackerNum = Utils.getInt(conf.get(Config.TOPOLOGY_ACKER_EXECUTORS), Utils.getInt(conf.get(Config.TOPOLOGY_WORKERS)));
    +        Map<GlobalStreamId, Grouping> inputs = ackerInputs(topology);
    +
    +        Map<String, StreamInfo> outputStreams = new HashMap<String, StreamInfo>();
    +        outputStreams.put(ACKER_ACK_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +        outputStreams.put(ACKER_FAIL_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +
    +        Map<String, Object> ackerConf = new HashMap<String, Object>();
    +        ackerConf.put(Config.TOPOLOGY_TASKS, ackerNum);
    +        ackerConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +
    +        Bolt acker = Thrift.prepareSerializedBoltDetails(inputs, makeAckerBolt(), outputStreams, ackerNum, ackerConf);
    +
    +        for(Bolt bolt : topology.get_bolts().values()) {
    +            ComponentCommon common = bolt.get_common();
    +            common.put_to_streams(ACKER_ACK_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "ack-val")));
    +            common.put_to_streams(ACKER_FAIL_STREAM_ID, Thrift.outputFields(Arrays.asList("id")));
    +        }
    +
    +        for (SpoutSpec spout : topology.get_spouts().values()) {
    +            ComponentCommon common = spout.get_common();
    +            Map spoutConf = componentConf(spout);
    +            spoutConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +            common.set_json_conf(JSONValue.toJSONString(spoutConf));
    +            common.put_to_streams(ACKER_INIT_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "init-val", "spout-task")));
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_ACK_STREAM_ID), Thrift.prepareDirectGrouping());
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_FAIL_STREAM_ID), Thrift.prepareDirectGrouping());
    +        }
    +
    +        topology.put_to_bolts(ACKER_COMPONENT_ID, acker);
    +    }
    +
    +    public static ComponentCommon getComponentCommon(Object component) {
    +        if (component == null) {
    +            return null;
    +        }
    +
    +        ComponentCommon common = null;
    +        if (component instanceof StateSpoutSpec) {
    +            common = ((StateSpoutSpec) component).get_common();
    +        } else if (component instanceof SpoutSpec) {
    +            common = ((SpoutSpec) component).get_common();
    +        } else if (component instanceof Bolt) {
    +            common = ((Bolt) component).get_common();
    +        }
    +        return common;
    +    }
    +
    +    public static void addMetricStreams(StormTopology topology) {
    +        for (Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                StreamInfo streamInfo = Thrift.outputFields(Arrays.asList("task-info", "data-points"));
    +                common.put_to_streams(Constants.METRICS_STREAM_ID, streamInfo);
    +            }
    +        }
    +    }
    +
    +    public static void addSystemStreams(StormTopology topology) {
    +        for (Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                StreamInfo streamInfo = Thrift.outputFields(Arrays.asList("event"));
    +                common.put_to_streams(SYSTEM_STREAM_ID, streamInfo);
    +            }
    +        }
    +    }
    +
    +    public static List<String> eventLoggerBoltFields() {
    +        List<String> fields = Arrays.asList(EventLoggerBolt.FIELD_COMPONENT_ID, EventLoggerBolt.FIELD_MESSAGE_ID, EventLoggerBolt.FIELD_TS,
    +                EventLoggerBolt.FIELD_VALUES);
    +        return fields;
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> eventLoggerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> allIds = new HashSet<String>();
    +        allIds.addAll(topology.get_bolts().keySet());
    +        allIds.addAll(topology.get_spouts().keySet());
    +
    +        for(String id : allIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, EVENTLOGGER_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("component-id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static void addEventLogger(Map conf, StormTopology topology) {
    +        Integer numExecutors = Utils.getInt(conf.get(Config.TOPOLOGY_EVENTLOGGER_EXECUTORS), Utils.getInt(conf.get(Config.TOPOLOGY_WORKERS)));
    +        HashMap<String, Object> componentConf = new HashMap<String, Object>();
    +        componentConf.put(Config.TOPOLOGY_TASKS, numExecutors);
    +        componentConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +        Bolt eventLoggerBolt = Thrift.prepareSerializedBoltDetails(eventLoggerInputs(topology), new EventLoggerBolt(), null, numExecutors, componentConf);
    +
    +        for(Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                common.put_to_streams(EVENTLOGGER_STREAM_ID, Thrift.outputFields(eventLoggerBoltFields()));
    +            }
    +        }
    +        topology.put_to_bolts(EVENTLOGGER_COMPONENT_ID, eventLoggerBolt);
    +    }
    +
    +    public static Map<String, Bolt> metricsConsumerBoltSpecs(Map conf, StormTopology topology) {
    +        Map<String, Bolt> metricsConsumerBolts = new HashMap<String, Bolt>();
    +
    +        Set<String> componentIdsEmitMetrics = new HashSet<String>();
    +        componentIdsEmitMetrics.addAll(allComponents(topology).keySet());
    +        componentIdsEmitMetrics.add(Constants.SYSTEM_COMPONENT_ID);
    +
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        for (String componentId : componentIdsEmitMetrics) {
    +            inputs.put(Utils.getGlobalStreamId(componentId, Constants.METRICS_STREAM_ID), Thrift.prepareShuffleGrouping());
    +        }
    +
    +        List<Map<String, Object>> registerInfo = (List<Map<String, Object>>) conf.get(Config.TOPOLOGY_METRICS_CONSUMER_REGISTER);
    +        if (registerInfo != null) {
    +            Map<String, Integer> classOccurrencesMap = new HashMap<String, Integer>();
    +            for (Map<String, Object> info : registerInfo) {
    +                String className = (String) info.get("class");
    +                Object argument = info.get("argument");
    +                Integer phintNum = Utils.getInt(info.get("parallelism.hint"), 1);
    +                Map<String, Object> metricsConsumerConf = new HashMap<String, Object>();
    +                metricsConsumerConf.put(Config.TOPOLOGY_TASKS, phintNum);
    +                Bolt metricsConsumerBolt = Thrift.prepareSerializedBoltDetails(inputs, new MetricsConsumerBolt(className, argument), null, phintNum, metricsConsumerConf);
    +
    +                String id = className;
    +                if (classOccurrencesMap.containsKey(className)) {
    +                    // e.g. [\"a\", \"b\", \"a\"]) => [\"a\", \"b\", \"a#2\"]"
    +                    int occurrenceNum = classOccurrencesMap.get(className);
    +                    occurrenceNum++;
    +                    classOccurrencesMap.put(className, occurrenceNum);
    +                    id = Constants.METRICS_COMPONENT_ID_PREFIX + className + "#" + occurrenceNum;
    +                } else {
    +                    classOccurrencesMap.put(className, 1);
    +                }
    +                metricsConsumerBolts.put(id, metricsConsumerBolt);
    +            }
    +        }
    +        return metricsConsumerBolts;
    +    }
    +
    +    public static void addMetricComponents(Map conf, StormTopology topology) {
    +        Map<String, Bolt> metricsConsumerBolts = metricsConsumerBoltSpecs(conf, topology);
    +        for (Map.Entry<String, Bolt> entry : metricsConsumerBolts.entrySet()) {
    +            topology.put_to_bolts(entry.getKey(), entry.getValue());
    +        }
    +    }
    +
    +    public static void addSystemComponents(Map conf, StormTopology topology) {
    +        Map<String, StreamInfo> outputStreams = new HashMap<String, StreamInfo>();
    +        outputStreams.put(Constants.SYSTEM_TICK_STREAM_ID, Thrift.outputFields(Arrays.asList("rate_secs")));
    +        outputStreams.put(Constants.METRICS_TICK_STREAM_ID, Thrift.outputFields(Arrays.asList("interval")));
    +        outputStreams.put(Constants.CREDENTIALS_CHANGED_STREAM_ID, Thrift.outputFields(Arrays.asList("creds")));
    +
    +        Map<String, Object> boltConf = new HashMap<String, Object>();
    +        boltConf.put(Config.TOPOLOGY_TASKS, 0);
    +
    +        Bolt systemBoltSpec = Thrift.prepareSerializedBoltDetails(null, new SystemBolt(), outputStreams, 0, boltConf);
    +        topology.put_to_bolts(Constants.SYSTEM_COMPONENT_ID, systemBoltSpec);
    +    }
    +
    +    public static StormTopology systemTopology(Map stormConf, StormTopology topology) throws InvalidTopologyException {
    +        return _instance.systemTopologyImpl(stormConf, topology);
    +    }
    +
    +    protected StormTopology systemTopologyImpl(Map stormConf, StormTopology topology) throws InvalidTopologyException {
    +        validateBasic(topology);
    +
    +        StormTopology ret = topology.deepCopy();
    +        addAcker(stormConf, ret);
    +        addEventLogger(stormConf, ret);
    +        addMetricComponents(stormConf, ret);
    +        addSystemComponents(stormConf, ret);
    +        addMetricStreams(ret);
    +        addSystemStreams(ret);
    +
    +        validateStructure(ret);
    +
    +        return ret;
    +    }
    +
    +    public static boolean hasAckers(Map stormConf) {
    --- End diff --
    
    hasAckers and hasEventLoggers is only called in executor so they can be moved there or you can move them to ConfigUtils.java since these functions solely operate on conf. 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

Posted by redsanket <gi...@git.apache.org>.
Github user redsanket commented on the pull request:

    https://github.com/apache/storm/pull/1185#issuecomment-192486048
  
    upmerge


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55285564
  
    --- Diff: storm-core/src/clj/org/apache/storm/daemon/executor.clj ---
    @@ -742,7 +742,7 @@
                                                                    (.getSourceComponent tuple)
                                                                    (.getSourceStreamId tuple)
                                                                    delta)))))))
    -        has-eventloggers? (has-eventloggers? storm-conf)
    +        has-eventloggers? (clojurify-structure (StormCommon/hasEventLoggers storm-conf))
    --- End diff --
    
    Here too I don't think `clojurify-structure` is needed.  Were you seeing errors without it?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55280156
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,604 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    +        } else if (common.get_inputs() == null) {
    +            return true;
    +        } else {
    +            return common.get_inputs().isEmpty();
    +        }
    +    }
    +
    +    public static Map<String, Object> allComponents(StormTopology topology) {
    +        Map<String, Object> components = new HashMap<String, Object>();
    +        List<StormTopology._Fields> topologyFields = Arrays.asList(Thrift.getTopologyFields());
    +        for (StormTopology._Fields field : topologyFields) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                components.putAll(((Map) topology.getFieldValue(field)));
    +            }
    +        }
    +        return components;
    +    }
    +
    +    public static Map componentConf(Object component) {
    +        Map<Object, Object> conf = new HashMap<Object, Object>();
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common != null) {
    +            String jconf = common.get_json_conf();
    +            if (jconf != null) {
    +                conf.putAll((Map<Object, Object>) JSONValue.parse(jconf));
    +            }
    +        }
    +        return conf;
    +    }
    +
    +    public static void validateBasic(StormTopology topology) throws InvalidTopologyException {
    +        validateIds(topology);
    +
    +        List<StormTopology._Fields> spoutFields = Arrays.asList(Thrift.getSpoutFields());
    +        for (StormTopology._Fields field : spoutFields) {
    +            Map<String, Object> spoutComponents = (Map<String, Object>) topology.getFieldValue(field);
    +            if (spoutComponents != null) {
    +                for (Object obj : spoutComponents.values()) {
    +                    ComponentCommon common = getComponentCommon(obj);
    +                    if (isEmptyInputs(common) == false) {
    +                        throw new InvalidTopologyException("May not declare inputs for a spout");
    +                    }
    +                }
    +            }
    +        }
    +
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Object componentObj : componentMap.values()) {
    +            Map conf = componentConf(componentObj);
    +            ComponentCommon common = getComponentCommon(componentObj);
    +            if (common != null) {
    +                int parallelismHintNum = Thrift.getParallelismHint(common);
    +                Integer taskNum = Utils.getInt(conf.get(Config.TOPOLOGY_TASKS), 0);
    +                if (taskNum > 0 && parallelismHintNum <= 0) {
    +                    throw new InvalidTopologyException("Number of executors must be greater than 0 when number of tasks is greater than 0");
    +                }
    +            }
    +        }
    +    }
    +
    +    private static Set<String> getStreamOutputFields(Map<String, StreamInfo> streams) {
    +        Set<String> outputFields = new HashSet<String>();
    +        if (streams != null) {
    +            for (StreamInfo streamInfo : streams.values()) {
    +                outputFields.addAll(streamInfo.get_output_fields());
    +            }
    +        }
    +        return outputFields;
    +    }
    +
    +    public static void validateStructure(StormTopology topology) throws InvalidTopologyException {
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Map.Entry<String, Object> entry : componentMap.entrySet()) {
    +            String componentId = entry.getKey();
    +            ComponentCommon common = getComponentCommon(entry.getValue());
    +            if (common != null) {
    +                Map<GlobalStreamId, Grouping> inputs = common.get_inputs();
    +                for (Map.Entry<GlobalStreamId, Grouping> input : inputs.entrySet()) {
    +                    String sourceStreamId = input.getKey().get_streamId();
    +                    String sourceComponentId = input.getKey().get_componentId();
    +                    if(componentMap.keySet().contains(sourceComponentId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent component [" + sourceComponentId + "]");
    +                    }
    +
    +                    ComponentCommon sourceComponent = getComponentCommon(componentMap.get(sourceComponentId));
    +                    if (sourceComponent == null || sourceComponent.get_streams().containsKey(sourceStreamId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent stream: " +
    +                                "[" + sourceStreamId + "] of component [" + sourceComponentId + "]");
    +                    }
    +
    +                    Grouping grouping = input.getValue();
    +                    if (Thrift.groupingType(grouping) == Grouping._Fields.FIELDS) {
    +                        List<String> fields = grouping.get_fields();
    +                        Map<String, StreamInfo> streams = sourceComponent.get_streams();
    +                        Set<String> sourceOutputFields = getStreamOutputFields(streams);
    +                        if (sourceOutputFields.containsAll(fields) == false) {
    +                            throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from stream: [" + sourceStreamId  +"] of component " +
    +                                    "[" + sourceComponentId + "] + with non-existent fields: " + fields);
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> ackerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> boltIds = topology.get_bolts().keySet();
    +        Set<String> spoutIds = topology.get_spouts().keySet();
    +
    +        for(String id : spoutIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_INIT_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +
    +        for(String id : boltIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_ACK_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_FAIL_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static IBolt makeAckerBolt() {
    +        return _instance.makeAckerBoltImpl();
    +    }
    +    public IBolt makeAckerBoltImpl() {
    +        return new Acker();
    +    }
    +
    +    public static void addAcker(Map conf, StormTopology topology) {
    +        int ackerNum = Utils.getInt(conf.get(Config.TOPOLOGY_ACKER_EXECUTORS), Utils.getInt(conf.get(Config.TOPOLOGY_WORKERS)));
    +        Map<GlobalStreamId, Grouping> inputs = ackerInputs(topology);
    +
    +        Map<String, StreamInfo> outputStreams = new HashMap<String, StreamInfo>();
    +        outputStreams.put(ACKER_ACK_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +        outputStreams.put(ACKER_FAIL_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +
    +        Map<String, Object> ackerConf = new HashMap<String, Object>();
    +        ackerConf.put(Config.TOPOLOGY_TASKS, ackerNum);
    +        ackerConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +
    +        Bolt acker = Thrift.prepareSerializedBoltDetails(inputs, makeAckerBolt(), outputStreams, ackerNum, ackerConf);
    +
    +        for(Bolt bolt : topology.get_bolts().values()) {
    +            ComponentCommon common = bolt.get_common();
    +            common.put_to_streams(ACKER_ACK_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "ack-val")));
    +            common.put_to_streams(ACKER_FAIL_STREAM_ID, Thrift.outputFields(Arrays.asList("id")));
    +        }
    +
    +        for (SpoutSpec spout : topology.get_spouts().values()) {
    +            ComponentCommon common = spout.get_common();
    +            Map spoutConf = componentConf(spout);
    +            spoutConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +            common.set_json_conf(JSONValue.toJSONString(spoutConf));
    +            common.put_to_streams(ACKER_INIT_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "init-val", "spout-task")));
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_ACK_STREAM_ID), Thrift.prepareDirectGrouping());
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_FAIL_STREAM_ID), Thrift.prepareDirectGrouping());
    +        }
    +
    +        topology.put_to_bolts(ACKER_COMPONENT_ID, acker);
    +    }
    +
    +    public static ComponentCommon getComponentCommon(Object component) {
    +        if (component == null) {
    --- End diff --
    
    This null check was not in the original code, but it is a minor nit here.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55269210
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,604 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    --- End diff --
    
    The metrics code has moved to another file already.  these are not needed any more.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55269157
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,605 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    --- End diff --
    
    +1


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55268410
  
    --- Diff: storm-core/src/clj/org/apache/storm/daemon/common.clj ---
    @@ -408,19 +69,3 @@
                               (:default-shared-resources worker)
                               (:user-shared-resources worker)
                               ))
    --- End diff --
    
    If we are leaving some methods in clojure, could you file a follow on JIRA to remove the file once we have the other code ported over to java?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55488575
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,605 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    --- End diff --
    
    OK. I will update it.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55271251
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,604 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    --- End diff --
    
    The original code didn't check for null here.  Is this needed?  Extra checks that fix things up like this make me nervous that be broke something somewhere and we are using this to work around it.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55277573
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,604 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    +        } else if (common.get_inputs() == null) {
    +            return true;
    +        } else {
    +            return common.get_inputs().isEmpty();
    +        }
    +    }
    +
    +    public static Map<String, Object> allComponents(StormTopology topology) {
    +        Map<String, Object> components = new HashMap<String, Object>();
    +        List<StormTopology._Fields> topologyFields = Arrays.asList(Thrift.getTopologyFields());
    +        for (StormTopology._Fields field : topologyFields) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                components.putAll(((Map) topology.getFieldValue(field)));
    +            }
    +        }
    +        return components;
    +    }
    +
    +    public static Map componentConf(Object component) {
    +        Map<Object, Object> conf = new HashMap<Object, Object>();
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common != null) {
    +            String jconf = common.get_json_conf();
    +            if (jconf != null) {
    +                conf.putAll((Map<Object, Object>) JSONValue.parse(jconf));
    +            }
    +        }
    +        return conf;
    +    }
    +
    +    public static void validateBasic(StormTopology topology) throws InvalidTopologyException {
    +        validateIds(topology);
    +
    +        List<StormTopology._Fields> spoutFields = Arrays.asList(Thrift.getSpoutFields());
    +        for (StormTopology._Fields field : spoutFields) {
    +            Map<String, Object> spoutComponents = (Map<String, Object>) topology.getFieldValue(field);
    +            if (spoutComponents != null) {
    +                for (Object obj : spoutComponents.values()) {
    +                    ComponentCommon common = getComponentCommon(obj);
    +                    if (isEmptyInputs(common) == false) {
    +                        throw new InvalidTopologyException("May not declare inputs for a spout");
    +                    }
    +                }
    +            }
    +        }
    +
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Object componentObj : componentMap.values()) {
    +            Map conf = componentConf(componentObj);
    +            ComponentCommon common = getComponentCommon(componentObj);
    +            if (common != null) {
    --- End diff --
    
    This null check was not in the original code.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55268203
  
    --- Diff: storm-core/src/clj/org/apache/storm/daemon/common.clj ---
    @@ -86,26 +40,6 @@
     (defn new-executor-stats []
       (ExecutorStats. 0 0 0 0 0))
    --- End diff --
    
    Why are we not moving ExecutorStats, SupervisorInfo, StormBase and Assignment to java?
    
    I know we have thrift equivalents of these already.  Is the plan to move them to java as we change the daemon code to use java?  If so I am fine with it, I just want to understand for sure what is happening.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55269119
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,604 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    --- End diff --
    
    Here we don't want to use a .* import.  We can pull in the wrong thing if we move to a newer version of java.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55269053
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,604 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    --- End diff --
    
    Don't need both the .* import and the StormBase import.  Usually we prefer to not use .* imports, but for me it is not that big of a deal.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55279184
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,604 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    +        } else if (common.get_inputs() == null) {
    +            return true;
    +        } else {
    +            return common.get_inputs().isEmpty();
    +        }
    +    }
    +
    +    public static Map<String, Object> allComponents(StormTopology topology) {
    +        Map<String, Object> components = new HashMap<String, Object>();
    +        List<StormTopology._Fields> topologyFields = Arrays.asList(Thrift.getTopologyFields());
    +        for (StormTopology._Fields field : topologyFields) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                components.putAll(((Map) topology.getFieldValue(field)));
    +            }
    +        }
    +        return components;
    +    }
    +
    +    public static Map componentConf(Object component) {
    +        Map<Object, Object> conf = new HashMap<Object, Object>();
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common != null) {
    +            String jconf = common.get_json_conf();
    +            if (jconf != null) {
    +                conf.putAll((Map<Object, Object>) JSONValue.parse(jconf));
    +            }
    +        }
    +        return conf;
    +    }
    +
    +    public static void validateBasic(StormTopology topology) throws InvalidTopologyException {
    +        validateIds(topology);
    +
    +        List<StormTopology._Fields> spoutFields = Arrays.asList(Thrift.getSpoutFields());
    +        for (StormTopology._Fields field : spoutFields) {
    +            Map<String, Object> spoutComponents = (Map<String, Object>) topology.getFieldValue(field);
    +            if (spoutComponents != null) {
    +                for (Object obj : spoutComponents.values()) {
    +                    ComponentCommon common = getComponentCommon(obj);
    +                    if (isEmptyInputs(common) == false) {
    +                        throw new InvalidTopologyException("May not declare inputs for a spout");
    +                    }
    +                }
    +            }
    +        }
    +
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Object componentObj : componentMap.values()) {
    +            Map conf = componentConf(componentObj);
    +            ComponentCommon common = getComponentCommon(componentObj);
    +            if (common != null) {
    +                int parallelismHintNum = Thrift.getParallelismHint(common);
    +                Integer taskNum = Utils.getInt(conf.get(Config.TOPOLOGY_TASKS), 0);
    +                if (taskNum > 0 && parallelismHintNum <= 0) {
    +                    throw new InvalidTopologyException("Number of executors must be greater than 0 when number of tasks is greater than 0");
    +                }
    +            }
    +        }
    +    }
    +
    +    private static Set<String> getStreamOutputFields(Map<String, StreamInfo> streams) {
    +        Set<String> outputFields = new HashSet<String>();
    +        if (streams != null) {
    --- End diff --
    
    In the original code if streams was null the return value was null.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55276131
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,604 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    +        } else if (common.get_inputs() == null) {
    +            return true;
    +        } else {
    +            return common.get_inputs().isEmpty();
    +        }
    +    }
    +
    +    public static Map<String, Object> allComponents(StormTopology topology) {
    +        Map<String, Object> components = new HashMap<String, Object>();
    +        List<StormTopology._Fields> topologyFields = Arrays.asList(Thrift.getTopologyFields());
    +        for (StormTopology._Fields field : topologyFields) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                components.putAll(((Map) topology.getFieldValue(field)));
    +            }
    +        }
    +        return components;
    +    }
    +
    +    public static Map componentConf(Object component) {
    +        Map<Object, Object> conf = new HashMap<Object, Object>();
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common != null) {
    --- End diff --
    
    The original code didn't check for null and would throw an NPE if we passed in a null.  We should do the same.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55283304
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,604 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    +        } else if (common.get_inputs() == null) {
    +            return true;
    +        } else {
    +            return common.get_inputs().isEmpty();
    +        }
    +    }
    +
    +    public static Map<String, Object> allComponents(StormTopology topology) {
    +        Map<String, Object> components = new HashMap<String, Object>();
    +        List<StormTopology._Fields> topologyFields = Arrays.asList(Thrift.getTopologyFields());
    +        for (StormTopology._Fields field : topologyFields) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                components.putAll(((Map) topology.getFieldValue(field)));
    +            }
    +        }
    +        return components;
    +    }
    +
    +    public static Map componentConf(Object component) {
    +        Map<Object, Object> conf = new HashMap<Object, Object>();
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common != null) {
    +            String jconf = common.get_json_conf();
    +            if (jconf != null) {
    +                conf.putAll((Map<Object, Object>) JSONValue.parse(jconf));
    +            }
    +        }
    +        return conf;
    +    }
    +
    +    public static void validateBasic(StormTopology topology) throws InvalidTopologyException {
    +        validateIds(topology);
    +
    +        List<StormTopology._Fields> spoutFields = Arrays.asList(Thrift.getSpoutFields());
    +        for (StormTopology._Fields field : spoutFields) {
    +            Map<String, Object> spoutComponents = (Map<String, Object>) topology.getFieldValue(field);
    +            if (spoutComponents != null) {
    +                for (Object obj : spoutComponents.values()) {
    +                    ComponentCommon common = getComponentCommon(obj);
    +                    if (isEmptyInputs(common) == false) {
    +                        throw new InvalidTopologyException("May not declare inputs for a spout");
    +                    }
    +                }
    +            }
    +        }
    +
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Object componentObj : componentMap.values()) {
    +            Map conf = componentConf(componentObj);
    +            ComponentCommon common = getComponentCommon(componentObj);
    +            if (common != null) {
    +                int parallelismHintNum = Thrift.getParallelismHint(common);
    +                Integer taskNum = Utils.getInt(conf.get(Config.TOPOLOGY_TASKS), 0);
    +                if (taskNum > 0 && parallelismHintNum <= 0) {
    +                    throw new InvalidTopologyException("Number of executors must be greater than 0 when number of tasks is greater than 0");
    +                }
    +            }
    +        }
    +    }
    +
    +    private static Set<String> getStreamOutputFields(Map<String, StreamInfo> streams) {
    +        Set<String> outputFields = new HashSet<String>();
    +        if (streams != null) {
    +            for (StreamInfo streamInfo : streams.values()) {
    +                outputFields.addAll(streamInfo.get_output_fields());
    +            }
    +        }
    +        return outputFields;
    +    }
    +
    +    public static void validateStructure(StormTopology topology) throws InvalidTopologyException {
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Map.Entry<String, Object> entry : componentMap.entrySet()) {
    +            String componentId = entry.getKey();
    +            ComponentCommon common = getComponentCommon(entry.getValue());
    +            if (common != null) {
    +                Map<GlobalStreamId, Grouping> inputs = common.get_inputs();
    +                for (Map.Entry<GlobalStreamId, Grouping> input : inputs.entrySet()) {
    +                    String sourceStreamId = input.getKey().get_streamId();
    +                    String sourceComponentId = input.getKey().get_componentId();
    +                    if(componentMap.keySet().contains(sourceComponentId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent component [" + sourceComponentId + "]");
    +                    }
    +
    +                    ComponentCommon sourceComponent = getComponentCommon(componentMap.get(sourceComponentId));
    +                    if (sourceComponent == null || sourceComponent.get_streams().containsKey(sourceStreamId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent stream: " +
    +                                "[" + sourceStreamId + "] of component [" + sourceComponentId + "]");
    +                    }
    +
    +                    Grouping grouping = input.getValue();
    +                    if (Thrift.groupingType(grouping) == Grouping._Fields.FIELDS) {
    +                        List<String> fields = grouping.get_fields();
    +                        Map<String, StreamInfo> streams = sourceComponent.get_streams();
    +                        Set<String> sourceOutputFields = getStreamOutputFields(streams);
    +                        if (sourceOutputFields.containsAll(fields) == false) {
    +                            throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from stream: [" + sourceStreamId  +"] of component " +
    +                                    "[" + sourceComponentId + "] + with non-existent fields: " + fields);
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> ackerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> boltIds = topology.get_bolts().keySet();
    +        Set<String> spoutIds = topology.get_spouts().keySet();
    +
    +        for(String id : spoutIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_INIT_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +
    +        for(String id : boltIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_ACK_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_FAIL_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static IBolt makeAckerBolt() {
    +        return _instance.makeAckerBoltImpl();
    +    }
    +    public IBolt makeAckerBoltImpl() {
    +        return new Acker();
    +    }
    +
    +    public static void addAcker(Map conf, StormTopology topology) {
    +        int ackerNum = Utils.getInt(conf.get(Config.TOPOLOGY_ACKER_EXECUTORS), Utils.getInt(conf.get(Config.TOPOLOGY_WORKERS)));
    +        Map<GlobalStreamId, Grouping> inputs = ackerInputs(topology);
    +
    +        Map<String, StreamInfo> outputStreams = new HashMap<String, StreamInfo>();
    +        outputStreams.put(ACKER_ACK_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +        outputStreams.put(ACKER_FAIL_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +
    +        Map<String, Object> ackerConf = new HashMap<String, Object>();
    +        ackerConf.put(Config.TOPOLOGY_TASKS, ackerNum);
    +        ackerConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +
    +        Bolt acker = Thrift.prepareSerializedBoltDetails(inputs, makeAckerBolt(), outputStreams, ackerNum, ackerConf);
    +
    +        for(Bolt bolt : topology.get_bolts().values()) {
    +            ComponentCommon common = bolt.get_common();
    +            common.put_to_streams(ACKER_ACK_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "ack-val")));
    +            common.put_to_streams(ACKER_FAIL_STREAM_ID, Thrift.outputFields(Arrays.asList("id")));
    +        }
    +
    +        for (SpoutSpec spout : topology.get_spouts().values()) {
    +            ComponentCommon common = spout.get_common();
    +            Map spoutConf = componentConf(spout);
    +            spoutConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +            common.set_json_conf(JSONValue.toJSONString(spoutConf));
    +            common.put_to_streams(ACKER_INIT_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "init-val", "spout-task")));
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_ACK_STREAM_ID), Thrift.prepareDirectGrouping());
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_FAIL_STREAM_ID), Thrift.prepareDirectGrouping());
    +        }
    +
    +        topology.put_to_bolts(ACKER_COMPONENT_ID, acker);
    +    }
    +
    +    public static ComponentCommon getComponentCommon(Object component) {
    +        if (component == null) {
    +            return null;
    +        }
    +
    +        ComponentCommon common = null;
    +        if (component instanceof StateSpoutSpec) {
    +            common = ((StateSpoutSpec) component).get_common();
    +        } else if (component instanceof SpoutSpec) {
    +            common = ((SpoutSpec) component).get_common();
    +        } else if (component instanceof Bolt) {
    +            common = ((Bolt) component).get_common();
    +        }
    +        return common;
    +    }
    +
    +    public static void addMetricStreams(StormTopology topology) {
    +        for (Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                StreamInfo streamInfo = Thrift.outputFields(Arrays.asList("task-info", "data-points"));
    +                common.put_to_streams(Constants.METRICS_STREAM_ID, streamInfo);
    +            }
    +        }
    +    }
    +
    +    public static void addSystemStreams(StormTopology topology) {
    +        for (Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                StreamInfo streamInfo = Thrift.outputFields(Arrays.asList("event"));
    +                common.put_to_streams(SYSTEM_STREAM_ID, streamInfo);
    +            }
    +        }
    +    }
    +
    +    public static List<String> eventLoggerBoltFields() {
    +        List<String> fields = Arrays.asList(EventLoggerBolt.FIELD_COMPONENT_ID, EventLoggerBolt.FIELD_MESSAGE_ID, EventLoggerBolt.FIELD_TS,
    +                EventLoggerBolt.FIELD_VALUES);
    +        return fields;
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> eventLoggerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> allIds = new HashSet<String>();
    +        allIds.addAll(topology.get_bolts().keySet());
    +        allIds.addAll(topology.get_spouts().keySet());
    +
    +        for(String id : allIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, EVENTLOGGER_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("component-id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static void addEventLogger(Map conf, StormTopology topology) {
    +        Integer numExecutors = Utils.getInt(conf.get(Config.TOPOLOGY_EVENTLOGGER_EXECUTORS), Utils.getInt(conf.get(Config.TOPOLOGY_WORKERS)));
    +        HashMap<String, Object> componentConf = new HashMap<String, Object>();
    +        componentConf.put(Config.TOPOLOGY_TASKS, numExecutors);
    +        componentConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +        Bolt eventLoggerBolt = Thrift.prepareSerializedBoltDetails(eventLoggerInputs(topology), new EventLoggerBolt(), null, numExecutors, componentConf);
    +
    +        for(Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                common.put_to_streams(EVENTLOGGER_STREAM_ID, Thrift.outputFields(eventLoggerBoltFields()));
    +            }
    +        }
    +        topology.put_to_bolts(EVENTLOGGER_COMPONENT_ID, eventLoggerBolt);
    +    }
    +
    +    public static Map<String, Bolt> metricsConsumerBoltSpecs(Map conf, StormTopology topology) {
    +        Map<String, Bolt> metricsConsumerBolts = new HashMap<String, Bolt>();
    +
    +        Set<String> componentIdsEmitMetrics = new HashSet<String>();
    +        componentIdsEmitMetrics.addAll(allComponents(topology).keySet());
    +        componentIdsEmitMetrics.add(Constants.SYSTEM_COMPONENT_ID);
    +
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        for (String componentId : componentIdsEmitMetrics) {
    +            inputs.put(Utils.getGlobalStreamId(componentId, Constants.METRICS_STREAM_ID), Thrift.prepareShuffleGrouping());
    +        }
    +
    +        List<Map<String, Object>> registerInfo = (List<Map<String, Object>>) conf.get(Config.TOPOLOGY_METRICS_CONSUMER_REGISTER);
    +        if (registerInfo != null) {
    +            Map<String, Integer> classOccurrencesMap = new HashMap<String, Integer>();
    +            for (Map<String, Object> info : registerInfo) {
    +                String className = (String) info.get("class");
    +                Object argument = info.get("argument");
    +                Integer phintNum = Utils.getInt(info.get("parallelism.hint"), 1);
    +                Map<String, Object> metricsConsumerConf = new HashMap<String, Object>();
    +                metricsConsumerConf.put(Config.TOPOLOGY_TASKS, phintNum);
    +                Bolt metricsConsumerBolt = Thrift.prepareSerializedBoltDetails(inputs, new MetricsConsumerBolt(className, argument), null, phintNum, metricsConsumerConf);
    +
    +                String id = className;
    +                if (classOccurrencesMap.containsKey(className)) {
    +                    // e.g. [\"a\", \"b\", \"a\"]) => [\"a\", \"b\", \"a#2\"]"
    +                    int occurrenceNum = classOccurrencesMap.get(className);
    +                    occurrenceNum++;
    +                    classOccurrencesMap.put(className, occurrenceNum);
    +                    id = Constants.METRICS_COMPONENT_ID_PREFIX + className + "#" + occurrenceNum;
    +                } else {
    +                    classOccurrencesMap.put(className, 1);
    +                }
    +                metricsConsumerBolts.put(id, metricsConsumerBolt);
    +            }
    +        }
    +        return metricsConsumerBolts;
    +    }
    +
    +    public static void addMetricComponents(Map conf, StormTopology topology) {
    +        Map<String, Bolt> metricsConsumerBolts = metricsConsumerBoltSpecs(conf, topology);
    +        for (Map.Entry<String, Bolt> entry : metricsConsumerBolts.entrySet()) {
    +            topology.put_to_bolts(entry.getKey(), entry.getValue());
    +        }
    +    }
    +
    +    public static void addSystemComponents(Map conf, StormTopology topology) {
    +        Map<String, StreamInfo> outputStreams = new HashMap<String, StreamInfo>();
    +        outputStreams.put(Constants.SYSTEM_TICK_STREAM_ID, Thrift.outputFields(Arrays.asList("rate_secs")));
    +        outputStreams.put(Constants.METRICS_TICK_STREAM_ID, Thrift.outputFields(Arrays.asList("interval")));
    +        outputStreams.put(Constants.CREDENTIALS_CHANGED_STREAM_ID, Thrift.outputFields(Arrays.asList("creds")));
    +
    +        Map<String, Object> boltConf = new HashMap<String, Object>();
    +        boltConf.put(Config.TOPOLOGY_TASKS, 0);
    +
    +        Bolt systemBoltSpec = Thrift.prepareSerializedBoltDetails(null, new SystemBolt(), outputStreams, 0, boltConf);
    +        topology.put_to_bolts(Constants.SYSTEM_COMPONENT_ID, systemBoltSpec);
    +    }
    +
    +    public static StormTopology systemTopology(Map stormConf, StormTopology topology) throws InvalidTopologyException {
    +        return _instance.systemTopologyImpl(stormConf, topology);
    +    }
    +
    +    protected StormTopology systemTopologyImpl(Map stormConf, StormTopology topology) throws InvalidTopologyException {
    +        validateBasic(topology);
    +
    +        StormTopology ret = topology.deepCopy();
    +        addAcker(stormConf, ret);
    +        addEventLogger(stormConf, ret);
    +        addMetricComponents(stormConf, ret);
    +        addSystemComponents(stormConf, ret);
    +        addMetricStreams(ret);
    +        addSystemStreams(ret);
    +
    +        validateStructure(ret);
    +
    +        return ret;
    +    }
    +
    +    public static boolean hasAckers(Map stormConf) {
    +        Object ackerNum = stormConf.get(Config.TOPOLOGY_ACKER_EXECUTORS);
    +        if (ackerNum == null || Utils.getInt(ackerNum) > 0) {
    +            return true;
    +        } else {
    +            return false;
    +        }
    +    }
    +
    +    public static boolean hasEventLoggers(Map stormConf) {
    +        Object eventLoggerNum = stormConf.get(Config.TOPOLOGY_EVENTLOGGER_EXECUTORS);
    +        if (eventLoggerNum == null || Utils.getInt(eventLoggerNum) > 0) {
    +            return true;
    +        } else {
    +            return false;
    +        }
    +    }
    +
    +    public static int numStartExecutors(Object component) throws InvalidTopologyException {
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common == null) {
    +            throw new InvalidTopologyException("unknown component type " + component.getClass().getName());
    +        }
    --- End diff --
    
    This null check didn't exist in the original code.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55490580
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,605 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    +        } else if (common.get_inputs() == null) {
    +            return true;
    +        } else {
    +            return common.get_inputs().isEmpty();
    +        }
    +    }
    +
    +    public static Map<String, Object> allComponents(StormTopology topology) {
    +        Map<String, Object> components = new HashMap<String, Object>();
    +        List<StormTopology._Fields> topologyFields = Arrays.asList(Thrift.getTopologyFields());
    +        for (StormTopology._Fields field : topologyFields) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                components.putAll(((Map) topology.getFieldValue(field)));
    +            }
    +        }
    +        return components;
    +    }
    +
    +    public static Map componentConf(Object component) {
    +        Map<Object, Object> conf = new HashMap<Object, Object>();
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common != null) {
    +            String jconf = common.get_json_conf();
    +            if (jconf != null) {
    +                conf.putAll((Map<Object, Object>) JSONValue.parse(jconf));
    +            }
    +        }
    +        return conf;
    +    }
    +
    +    public static void validateBasic(StormTopology topology) throws InvalidTopologyException {
    +        validateIds(topology);
    +
    +        List<StormTopology._Fields> spoutFields = Arrays.asList(Thrift.getSpoutFields());
    +        for (StormTopology._Fields field : spoutFields) {
    +            Map<String, Object> spoutComponents = (Map<String, Object>) topology.getFieldValue(field);
    +            if (spoutComponents != null) {
    +                for (Object obj : spoutComponents.values()) {
    +                    ComponentCommon common = getComponentCommon(obj);
    +                    if (isEmptyInputs(common) == false) {
    +                        throw new InvalidTopologyException("May not declare inputs for a spout");
    +                    }
    +                }
    +            }
    +        }
    +
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Object componentObj : componentMap.values()) {
    +            Map conf = componentConf(componentObj);
    +            ComponentCommon common = getComponentCommon(componentObj);
    +            if (common != null) {
    +                int parallelismHintNum = Thrift.getParallelismHint(common);
    +                Integer taskNum = Utils.getInt(conf.get(Config.TOPOLOGY_TASKS), 0);
    +                if (taskNum > 0 && parallelismHintNum <= 0) {
    +                    throw new InvalidTopologyException("Number of executors must be greater than 0 when number of tasks is greater than 0");
    +                }
    +            }
    +        }
    +    }
    +
    +    private static Set<String> getStreamOutputFields(Map<String, StreamInfo> streams) {
    +        Set<String> outputFields = new HashSet<String>();
    +        if (streams != null) {
    +            for (StreamInfo streamInfo : streams.values()) {
    +                outputFields.addAll(streamInfo.get_output_fields());
    +            }
    +        }
    +        return outputFields;
    +    }
    +
    +    public static void validateStructure(StormTopology topology) throws InvalidTopologyException {
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Map.Entry<String, Object> entry : componentMap.entrySet()) {
    +            String componentId = entry.getKey();
    +            ComponentCommon common = getComponentCommon(entry.getValue());
    +            if (common != null) {
    +                Map<GlobalStreamId, Grouping> inputs = common.get_inputs();
    +                for (Map.Entry<GlobalStreamId, Grouping> input : inputs.entrySet()) {
    +                    String sourceStreamId = input.getKey().get_streamId();
    +                    String sourceComponentId = input.getKey().get_componentId();
    +                    if(componentMap.keySet().contains(sourceComponentId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent component [" + sourceComponentId + "]");
    +                    }
    +
    +                    ComponentCommon sourceComponent = getComponentCommon(componentMap.get(sourceComponentId));
    +                    if (sourceComponent == null || sourceComponent.get_streams().containsKey(sourceStreamId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent stream: " +
    +                                "[" + sourceStreamId + "] of component [" + sourceComponentId + "]");
    +                    }
    +
    +                    Grouping grouping = input.getValue();
    +                    if (Thrift.groupingType(grouping) == Grouping._Fields.FIELDS) {
    +                        List<String> fields = grouping.get_fields();
    +                        Map<String, StreamInfo> streams = sourceComponent.get_streams();
    +                        Set<String> sourceOutputFields = getStreamOutputFields(streams);
    +                        if (sourceOutputFields.containsAll(fields) == false) {
    +                            throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from stream: [" + sourceStreamId  +"] of component " +
    +                                    "[" + sourceComponentId + "] + with non-existent fields: " + fields);
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> ackerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> boltIds = topology.get_bolts().keySet();
    +        Set<String> spoutIds = topology.get_spouts().keySet();
    +
    +        for(String id : spoutIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_INIT_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +
    +        for(String id : boltIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_ACK_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_FAIL_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static String clusterId = null;
    +    public static IBolt makeAckerBolt() {
    +        return _instance.makeAckerBoltImpl();
    +    }
    +    public IBolt makeAckerBoltImpl() {
    +        return new Acker();
    +    }
    +
    +    public static void addAcker(Map conf, StormTopology topology) {
    +        int ackerNum = Utils.getInt(conf.get(Config.TOPOLOGY_ACKER_EXECUTORS), Utils.getInt(conf.get(Config.TOPOLOGY_WORKERS)));
    +        Map<GlobalStreamId, Grouping> inputs = ackerInputs(topology);
    +
    +        Map<String, StreamInfo> outputStreams = new HashMap<String, StreamInfo>();
    +        outputStreams.put(ACKER_ACK_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +        outputStreams.put(ACKER_FAIL_STREAM_ID, Thrift.directOutputFields(Arrays.asList("id")));
    +
    +        Map<String, Object> ackerConf = new HashMap<String, Object>();
    +        ackerConf.put(Config.TOPOLOGY_TASKS, ackerNum);
    +        ackerConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +
    +        Bolt acker = Thrift.prepareSerializedBoltDetails(inputs, makeAckerBolt(), outputStreams, ackerNum, ackerConf);
    +
    +        for(Bolt bolt : topology.get_bolts().values()) {
    +            ComponentCommon common = bolt.get_common();
    +            common.put_to_streams(ACKER_ACK_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "ack-val")));
    +            common.put_to_streams(ACKER_FAIL_STREAM_ID, Thrift.outputFields(Arrays.asList("id")));
    +        }
    +
    +        for (SpoutSpec spout : topology.get_spouts().values()) {
    +            ComponentCommon common = spout.get_common();
    +            Map spoutConf = componentConf(spout);
    +            spoutConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +            common.set_json_conf(JSONValue.toJSONString(spoutConf));
    +            common.put_to_streams(ACKER_INIT_STREAM_ID, Thrift.outputFields(Arrays.asList("id", "init-val", "spout-task")));
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_ACK_STREAM_ID), Thrift.prepareDirectGrouping());
    +            common.put_to_inputs(Utils.getGlobalStreamId(ACKER_COMPONENT_ID, ACKER_FAIL_STREAM_ID), Thrift.prepareDirectGrouping());
    +        }
    +
    +        topology.put_to_bolts(ACKER_COMPONENT_ID, acker);
    +    }
    +
    +    public static ComponentCommon getComponentCommon(Object component) {
    +        if (component == null) {
    +            return null;
    +        }
    +
    +        ComponentCommon common = null;
    +        if (component instanceof StateSpoutSpec) {
    +            common = ((StateSpoutSpec) component).get_common();
    +        } else if (component instanceof SpoutSpec) {
    +            common = ((SpoutSpec) component).get_common();
    +        } else if (component instanceof Bolt) {
    +            common = ((Bolt) component).get_common();
    +        }
    +        return common;
    +    }
    +
    +    public static void addMetricStreams(StormTopology topology) {
    +        for (Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                StreamInfo streamInfo = Thrift.outputFields(Arrays.asList("task-info", "data-points"));
    +                common.put_to_streams(Constants.METRICS_STREAM_ID, streamInfo);
    +            }
    +        }
    +    }
    +
    +    public static void addSystemStreams(StormTopology topology) {
    +        for (Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                StreamInfo streamInfo = Thrift.outputFields(Arrays.asList("event"));
    +                common.put_to_streams(SYSTEM_STREAM_ID, streamInfo);
    +            }
    +        }
    +    }
    +
    +    public static List<String> eventLoggerBoltFields() {
    +        List<String> fields = Arrays.asList(EventLoggerBolt.FIELD_COMPONENT_ID, EventLoggerBolt.FIELD_MESSAGE_ID, EventLoggerBolt.FIELD_TS,
    +                EventLoggerBolt.FIELD_VALUES);
    +        return fields;
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> eventLoggerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> allIds = new HashSet<String>();
    +        allIds.addAll(topology.get_bolts().keySet());
    +        allIds.addAll(topology.get_spouts().keySet());
    +
    +        for(String id : allIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, EVENTLOGGER_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("component-id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static void addEventLogger(Map conf, StormTopology topology) {
    +        Integer numExecutors = Utils.getInt(conf.get(Config.TOPOLOGY_EVENTLOGGER_EXECUTORS), Utils.getInt(conf.get(Config.TOPOLOGY_WORKERS)));
    +        HashMap<String, Object> componentConf = new HashMap<String, Object>();
    +        componentConf.put(Config.TOPOLOGY_TASKS, numExecutors);
    +        componentConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, Utils.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)));
    +        Bolt eventLoggerBolt = Thrift.prepareSerializedBoltDetails(eventLoggerInputs(topology), new EventLoggerBolt(), null, numExecutors, componentConf);
    +
    +        for(Object component : allComponents(topology).values()) {
    +            ComponentCommon common = getComponentCommon(component);
    +            if (common != null) {
    +                common.put_to_streams(EVENTLOGGER_STREAM_ID, Thrift.outputFields(eventLoggerBoltFields()));
    +            }
    +        }
    +        topology.put_to_bolts(EVENTLOGGER_COMPONENT_ID, eventLoggerBolt);
    +    }
    +
    +    public static Map<String, Bolt> metricsConsumerBoltSpecs(Map conf, StormTopology topology) {
    +        Map<String, Bolt> metricsConsumerBolts = new HashMap<String, Bolt>();
    +
    +        Set<String> componentIdsEmitMetrics = new HashSet<String>();
    +        componentIdsEmitMetrics.addAll(allComponents(topology).keySet());
    +        componentIdsEmitMetrics.add(Constants.SYSTEM_COMPONENT_ID);
    +
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        for (String componentId : componentIdsEmitMetrics) {
    +            inputs.put(Utils.getGlobalStreamId(componentId, Constants.METRICS_STREAM_ID), Thrift.prepareShuffleGrouping());
    +        }
    +
    +        List<Map<String, Object>> registerInfo = (List<Map<String, Object>>) conf.get(Config.TOPOLOGY_METRICS_CONSUMER_REGISTER);
    +        if (registerInfo != null) {
    +            Map<String, Integer> classOccurrencesMap = new HashMap<String, Integer>();
    +            for (Map<String, Object> info : registerInfo) {
    +                String className = (String) info.get("class");
    +                Object argument = info.get("argument");
    +                Integer phintNum = Utils.getInt(info.get("parallelism.hint"), 1);
    +                Map<String, Object> metricsConsumerConf = new HashMap<String, Object>();
    +                metricsConsumerConf.put(Config.TOPOLOGY_TASKS, phintNum);
    +                Bolt metricsConsumerBolt = Thrift.prepareSerializedBoltDetails(inputs, new MetricsConsumerBolt(className, argument), null, phintNum, metricsConsumerConf);
    +
    +                String id = className;
    +                if (classOccurrencesMap.containsKey(className)) {
    +                    // e.g. [\"a\", \"b\", \"a\"]) => [\"a\", \"b\", \"a#2\"]"
    +                    int occurrenceNum = classOccurrencesMap.get(className);
    +                    occurrenceNum++;
    +                    classOccurrencesMap.put(className, occurrenceNum);
    +                    id = Constants.METRICS_COMPONENT_ID_PREFIX + className + "#" + occurrenceNum;
    +                } else {
    +                    classOccurrencesMap.put(className, 1);
    +                }
    +                metricsConsumerBolts.put(id, metricsConsumerBolt);
    +            }
    +        }
    +        return metricsConsumerBolts;
    +    }
    +
    +    public static void addMetricComponents(Map conf, StormTopology topology) {
    +        Map<String, Bolt> metricsConsumerBolts = metricsConsumerBoltSpecs(conf, topology);
    +        for (Map.Entry<String, Bolt> entry : metricsConsumerBolts.entrySet()) {
    +            topology.put_to_bolts(entry.getKey(), entry.getValue());
    +        }
    +    }
    +
    +    public static void addSystemComponents(Map conf, StormTopology topology) {
    +        Map<String, StreamInfo> outputStreams = new HashMap<String, StreamInfo>();
    +        outputStreams.put(Constants.SYSTEM_TICK_STREAM_ID, Thrift.outputFields(Arrays.asList("rate_secs")));
    +        outputStreams.put(Constants.METRICS_TICK_STREAM_ID, Thrift.outputFields(Arrays.asList("interval")));
    +        outputStreams.put(Constants.CREDENTIALS_CHANGED_STREAM_ID, Thrift.outputFields(Arrays.asList("creds")));
    +
    +        Map<String, Object> boltConf = new HashMap<String, Object>();
    +        boltConf.put(Config.TOPOLOGY_TASKS, 0);
    +
    +        Bolt systemBoltSpec = Thrift.prepareSerializedBoltDetails(null, new SystemBolt(), outputStreams, 0, boltConf);
    +        topology.put_to_bolts(Constants.SYSTEM_COMPONENT_ID, systemBoltSpec);
    +    }
    +
    +    public static StormTopology systemTopology(Map stormConf, StormTopology topology) throws InvalidTopologyException {
    +        return _instance.systemTopologyImpl(stormConf, topology);
    +    }
    +
    +    protected StormTopology systemTopologyImpl(Map stormConf, StormTopology topology) throws InvalidTopologyException {
    +        validateBasic(topology);
    +
    +        StormTopology ret = topology.deepCopy();
    +        addAcker(stormConf, ret);
    +        addEventLogger(stormConf, ret);
    +        addMetricComponents(stormConf, ret);
    +        addSystemComponents(stormConf, ret);
    +        addMetricStreams(ret);
    +        addSystemStreams(ret);
    +
    +        validateStructure(ret);
    +
    +        return ret;
    +    }
    +
    +    public static boolean hasAckers(Map stormConf) {
    --- End diff --
    
    I prefer to just keep the same with origin code since these functions are related to "topology component", not a utils function. It is better to keep these kind functions in common.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55488501
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,605 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    +        } else if (common.get_inputs() == null) {
    +            return true;
    +        } else {
    +            return common.get_inputs().isEmpty();
    +        }
    +    }
    +
    +    public static Map<String, Object> allComponents(StormTopology topology) {
    +        Map<String, Object> components = new HashMap<String, Object>();
    +        List<StormTopology._Fields> topologyFields = Arrays.asList(Thrift.getTopologyFields());
    +        for (StormTopology._Fields field : topologyFields) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                components.putAll(((Map) topology.getFieldValue(field)));
    +            }
    +        }
    +        return components;
    +    }
    +
    +    public static Map componentConf(Object component) {
    +        Map<Object, Object> conf = new HashMap<Object, Object>();
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common != null) {
    +            String jconf = common.get_json_conf();
    +            if (jconf != null) {
    +                conf.putAll((Map<Object, Object>) JSONValue.parse(jconf));
    +            }
    +        }
    +        return conf;
    +    }
    +
    +    public static void validateBasic(StormTopology topology) throws InvalidTopologyException {
    +        validateIds(topology);
    +
    +        List<StormTopology._Fields> spoutFields = Arrays.asList(Thrift.getSpoutFields());
    +        for (StormTopology._Fields field : spoutFields) {
    +            Map<String, Object> spoutComponents = (Map<String, Object>) topology.getFieldValue(field);
    +            if (spoutComponents != null) {
    +                for (Object obj : spoutComponents.values()) {
    +                    ComponentCommon common = getComponentCommon(obj);
    +                    if (isEmptyInputs(common) == false) {
    +                        throw new InvalidTopologyException("May not declare inputs for a spout");
    +                    }
    +                }
    +            }
    +        }
    +
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Object componentObj : componentMap.values()) {
    +            Map conf = componentConf(componentObj);
    +            ComponentCommon common = getComponentCommon(componentObj);
    +            if (common != null) {
    +                int parallelismHintNum = Thrift.getParallelismHint(common);
    +                Integer taskNum = Utils.getInt(conf.get(Config.TOPOLOGY_TASKS), 0);
    +                if (taskNum > 0 && parallelismHintNum <= 0) {
    +                    throw new InvalidTopologyException("Number of executors must be greater than 0 when number of tasks is greater than 0");
    +                }
    +            }
    +        }
    +    }
    +
    +    private static Set<String> getStreamOutputFields(Map<String, StreamInfo> streams) {
    +        Set<String> outputFields = new HashSet<String>();
    +        if (streams != null) {
    +            for (StreamInfo streamInfo : streams.values()) {
    +                outputFields.addAll(streamInfo.get_output_fields());
    +            }
    +        }
    +        return outputFields;
    +    }
    +
    +    public static void validateStructure(StormTopology topology) throws InvalidTopologyException {
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Map.Entry<String, Object> entry : componentMap.entrySet()) {
    +            String componentId = entry.getKey();
    +            ComponentCommon common = getComponentCommon(entry.getValue());
    +            if (common != null) {
    +                Map<GlobalStreamId, Grouping> inputs = common.get_inputs();
    +                for (Map.Entry<GlobalStreamId, Grouping> input : inputs.entrySet()) {
    +                    String sourceStreamId = input.getKey().get_streamId();
    +                    String sourceComponentId = input.getKey().get_componentId();
    +                    if(componentMap.keySet().contains(sourceComponentId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent component [" + sourceComponentId + "]");
    +                    }
    +
    +                    ComponentCommon sourceComponent = getComponentCommon(componentMap.get(sourceComponentId));
    +                    if (sourceComponent == null || sourceComponent.get_streams().containsKey(sourceStreamId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent stream: " +
    +                                "[" + sourceStreamId + "] of component [" + sourceComponentId + "]");
    +                    }
    +
    +                    Grouping grouping = input.getValue();
    +                    if (Thrift.groupingType(grouping) == Grouping._Fields.FIELDS) {
    +                        List<String> fields = grouping.get_fields();
    +                        Map<String, StreamInfo> streams = sourceComponent.get_streams();
    +                        Set<String> sourceOutputFields = getStreamOutputFields(streams);
    +                        if (sourceOutputFields.containsAll(fields) == false) {
    +                            throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from stream: [" + sourceStreamId  +"] of component " +
    +                                    "[" + sourceComponentId + "] + with non-existent fields: " + fields);
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +    }
    +
    +    public static Map<GlobalStreamId, Grouping> ackerInputs(StormTopology topology) {
    +        Map<GlobalStreamId, Grouping> inputs = new HashMap<GlobalStreamId, Grouping>();
    +        Set<String> boltIds = topology.get_bolts().keySet();
    +        Set<String> spoutIds = topology.get_spouts().keySet();
    +
    +        for(String id : spoutIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_INIT_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +
    +        for(String id : boltIds) {
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_ACK_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +            inputs.put(Utils.getGlobalStreamId(id, ACKER_FAIL_STREAM_ID), Thrift.prepareFieldsGrouping(Arrays.asList("id")));
    +        }
    +        return inputs;
    +    }
    +
    +    public static String clusterId = null;
    +    public static IBolt makeAckerBolt() {
    +        return _instance.makeAckerBoltImpl();
    +    }
    +    public IBolt makeAckerBoltImpl() {
    +        return new Acker();
    --- End diff --
    
    Yes, it is for mocking in with-tracked-cluster.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55566050
  
    --- Diff: storm-core/test/jvm/org/apache/storm/utils/staticmocking/CommonInstaller.java ---
    @@ -0,0 +1,38 @@
    +/**
    + * 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.storm.utils.staticmocking;
    +
    +import org.apache.storm.daemon.StormCommon;
    +
    +public class CommonInstaller implements AutoCloseable {
    --- End diff --
    
    I just thought that we didn't need both.  We could update the tests to use StormCommonInstaller and remove this.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55278586
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,604 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    +                    Map<String, Object> componentMap = (Map<String, Object>) value;
    +                    componentIds.addAll(componentMap.keySet());
    +
    +                    for (String id : componentMap.keySet()) {
    +                        if (Utils.isSystemId(id)) {
    +                            throw new InvalidTopologyException(id + " is not a valid component id.");
    +                        }
    +                    }
    +                    for (Object componentObj : componentMap.values()) {
    +                        ComponentCommon common = getComponentCommon(componentObj);
    +                        Set<String> streamIds = common.get_streams().keySet();
    +                        for (String id : streamIds) {
    +                            if (Utils.isSystemId(id)) {
    +                                throw new InvalidTopologyException(id + " is not a valid stream id.");
    +                            }
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        List<String> offending = Utils.getRepeat(componentIds);
    +        if (offending.isEmpty() == false) {
    +            throw new InvalidTopologyException("Duplicate component ids: " + offending);
    +        }
    +    }
    +
    +    private static boolean isEmptyInputs(ComponentCommon common) {
    +        if (common == null) {
    +            return true;
    +        } else if (common.get_inputs() == null) {
    +            return true;
    +        } else {
    +            return common.get_inputs().isEmpty();
    +        }
    +    }
    +
    +    public static Map<String, Object> allComponents(StormTopology topology) {
    +        Map<String, Object> components = new HashMap<String, Object>();
    +        List<StormTopology._Fields> topologyFields = Arrays.asList(Thrift.getTopologyFields());
    +        for (StormTopology._Fields field : topologyFields) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                components.putAll(((Map) topology.getFieldValue(field)));
    +            }
    +        }
    +        return components;
    +    }
    +
    +    public static Map componentConf(Object component) {
    +        Map<Object, Object> conf = new HashMap<Object, Object>();
    +        ComponentCommon common = getComponentCommon(component);
    +        if (common != null) {
    +            String jconf = common.get_json_conf();
    +            if (jconf != null) {
    +                conf.putAll((Map<Object, Object>) JSONValue.parse(jconf));
    +            }
    +        }
    +        return conf;
    +    }
    +
    +    public static void validateBasic(StormTopology topology) throws InvalidTopologyException {
    +        validateIds(topology);
    +
    +        List<StormTopology._Fields> spoutFields = Arrays.asList(Thrift.getSpoutFields());
    +        for (StormTopology._Fields field : spoutFields) {
    +            Map<String, Object> spoutComponents = (Map<String, Object>) topology.getFieldValue(field);
    +            if (spoutComponents != null) {
    +                for (Object obj : spoutComponents.values()) {
    +                    ComponentCommon common = getComponentCommon(obj);
    +                    if (isEmptyInputs(common) == false) {
    +                        throw new InvalidTopologyException("May not declare inputs for a spout");
    +                    }
    +                }
    +            }
    +        }
    +
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Object componentObj : componentMap.values()) {
    +            Map conf = componentConf(componentObj);
    +            ComponentCommon common = getComponentCommon(componentObj);
    +            if (common != null) {
    +                int parallelismHintNum = Thrift.getParallelismHint(common);
    +                Integer taskNum = Utils.getInt(conf.get(Config.TOPOLOGY_TASKS), 0);
    +                if (taskNum > 0 && parallelismHintNum <= 0) {
    +                    throw new InvalidTopologyException("Number of executors must be greater than 0 when number of tasks is greater than 0");
    +                }
    +            }
    +        }
    +    }
    +
    +    private static Set<String> getStreamOutputFields(Map<String, StreamInfo> streams) {
    +        Set<String> outputFields = new HashSet<String>();
    +        if (streams != null) {
    +            for (StreamInfo streamInfo : streams.values()) {
    +                outputFields.addAll(streamInfo.get_output_fields());
    +            }
    +        }
    +        return outputFields;
    +    }
    +
    +    public static void validateStructure(StormTopology topology) throws InvalidTopologyException {
    +        Map<String, Object> componentMap = allComponents(topology);
    +        for (Map.Entry<String, Object> entry : componentMap.entrySet()) {
    +            String componentId = entry.getKey();
    +            ComponentCommon common = getComponentCommon(entry.getValue());
    +            if (common != null) {
    +                Map<GlobalStreamId, Grouping> inputs = common.get_inputs();
    +                for (Map.Entry<GlobalStreamId, Grouping> input : inputs.entrySet()) {
    +                    String sourceStreamId = input.getKey().get_streamId();
    +                    String sourceComponentId = input.getKey().get_componentId();
    +                    if(componentMap.keySet().contains(sourceComponentId) == false) {
    +                        throw new InvalidTopologyException("Component: [" + componentId + "] subscribes from non-existent component [" + sourceComponentId + "]");
    +                    }
    +
    +                    ComponentCommon sourceComponent = getComponentCommon(componentMap.get(sourceComponentId));
    +                    if (sourceComponent == null || sourceComponent.get_streams().containsKey(sourceStreamId) == false) {
    --- End diff --
    
    The null check for sourceComponent was not in the original code, and if it were null it would not mean that we subscribed to a non-existent stream.  It would mean that our topology builder didn't do its job correctly.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55007696
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,605 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    --- End diff --
    
    In fact the above function can be removed since an invalid name is never expected. 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55489975
  
    --- Diff: storm-core/src/clj/org/apache/storm/daemon/common.clj ---
    @@ -408,19 +69,3 @@
                               (:default-shared-resources worker)
                               (:user-shared-resources worker)
                               ))
    --- End diff --
    
    OK, I will create one.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55275531
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,604 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    +            for (String topologyId : activeTopologys) {
    +                StormBase base = stormClusterState.stormBase(topologyId, null);
    +                if (base != null) {
    +                    stormBases.put(topologyId, base);
    +                }
    +            }
    +        }
    +        return stormBases;
    +    }
    +
    +    public static void validateDistributedMode(Map conf) {
    +        if (ConfigUtils.isLocalMode(conf)) {
    +            throw new IllegalArgumentException("Cannot start server in local mode!");
    +        }
    +    }
    +
    +    private static void validateIds(StormTopology topology) throws InvalidTopologyException {
    +        List<String> componentIds = new ArrayList<String>();
    +
    +        for (StormTopology._Fields field : Thrift.getTopologyFields()) {
    +            if (ThriftTopologyUtils.isWorkerHook(field) == false) {
    +                Object value = topology.getFieldValue(field);
    +                if (value != null) {
    --- End diff --
    
    Is this ever really null?  I don't see the null check even implicitly in the clojure code, if it is ever null I the clojure code would throw an NPE.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55270857
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,605 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    --- End diff --
    
    In fact the above function and this function are replacing 
    ```
    (.get_name (.stormBase storm-cluster-state  x nil)
    ```
    
    where `x` is the topology id.
    
    I get that this code is more efficient, but also more error prone, and so I would prefer we stick with the original code until we see a real reason to switch.
    
    ```
    for (String topologyId: stormClusterState.activeStorms()) {
        if (topologyName.equals(stormClusterState.stormBase(topologyId, null).get_name())) {
            return topologyId;
        }
        return null;
    }
    ```
    



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55285995
  
    --- Diff: storm-core/src/clj/org/apache/storm/daemon/worker.clj ---
    @@ -254,6 +254,9 @@
             (log-error e "Error when processing event")
             (Utils/exitProcess 20 "Error when processing an event")))))
     
    +(defn executor->tasks [executor-id]
    +  clojurify-structure (StormCommon/executorIdToTasks executor-id))
    --- End diff --
    
    Either we need to actually call `clojurify-structure` or we need to remove it.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55271310
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,604 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        IPredicate pred = new IPredicate<String>() {
    +            @Override
    +            public boolean test(String obj) {
    +                return obj != null ? getTopologyNameById(obj).equals(topologyName) : false;
    +            }
    +        };
    +        return Utils.findOne(pred, activeTopologys);
    +    }
    +
    +    public static Map<String, StormBase> topologyBases(IStormClusterState stormClusterState) {
    +        return _instance.topologyBasesImpl(stormClusterState);
    +    }
    +
    +    protected Map<String, StormBase> topologyBasesImpl(IStormClusterState stormClusterState) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    +        Map<String, StormBase> stormBases = new HashMap<String, StormBase>();
    +        if (activeTopologys != null) {
    --- End diff --
    
    The original code didn't check for null.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55007490
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,605 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    +        String ret = null;
    +        int index = topologyId.lastIndexOf('-');
    +        if (index != -1 && index > 2) {
    +            index = topologyId.lastIndexOf('-', index - 1);
    +            if (index != -1 && index > 0)
    +                ret = topologyId.substring(0, index);
    +            else
    +                throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        } else
    +            throw new InvalidTopologyException(topologyId + " is not a valid topologyId");
    +        return ret;
    +    }
    +
    +    public static String getStormId(IStormClusterState stormClusterState, final String topologyName) {
    +        List<String> activeTopologys = stormClusterState.activeStorms();
    --- End diff --
    
    nit. activeTopologies


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] storm pull request: [STORM-1269] port backtype.storm.daemon.common...

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

    https://github.com/apache/storm/pull/1185#discussion_r55007408
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/StormCommon.java ---
    @@ -0,0 +1,605 @@
    +/**
    + * 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.storm.daemon;
    +
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.storm.Config;
    +import org.apache.storm.Constants;
    +import org.apache.storm.Thrift;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.generated.StormBase;
    +import org.apache.storm.metric.EventLoggerBolt;
    +import org.apache.storm.metric.MetricsConsumerBolt;
    +import org.apache.storm.metric.SystemBolt;
    +import org.apache.storm.security.auth.IAuthorizer;
    +import org.apache.storm.task.IBolt;
    +import org.apache.storm.testing.NonRichBoltTracker;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.IPredicate;
    +import org.apache.storm.utils.ThriftTopologyUtils;
    +import org.apache.storm.utils.Utils;
    +import org.json.simple.JSONValue;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.*;
    +
    +public class StormCommon {
    +    // A singleton instance allows us to mock delegated static methods in our
    +    // tests by subclassing.
    +    private static StormCommon _instance = new StormCommon();
    +
    +    /**
    +     * Provide an instance of this class for delegates to use.  To mock out
    +     * delegated methods, provide an instance of a subclass that overrides the
    +     * implementation of the delegated method.
    +     * @param common a StormCommon instance
    +     * @return the previously set instance
    +     */
    +    public static StormCommon setInstance(StormCommon common) {
    +        StormCommon oldInstance = _instance;
    +        _instance = common;
    +        return oldInstance;
    +    }
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(StormCommon.class);
    +
    +    public static final String ACKER_COMPONENT_ID = Acker.ACKER_COMPONENT_ID;
    +    public static final String ACKER_INIT_STREAM_ID = Acker.ACKER_INIT_STREAM_ID;
    +    public static final String ACKER_ACK_STREAM_ID = Acker.ACKER_ACK_STREAM_ID;
    +    public static final String ACKER_FAIL_STREAM_ID = Acker.ACKER_FAIL_STREAM_ID;
    +
    +    public static final String SYSTEM_STREAM_ID = "__system";
    +
    +    public static final String EVENTLOGGER_COMPONENT_ID = "__eventlogger";
    +    public static final String EVENTLOGGER_STREAM_ID = "__eventlog";
    +
    +    public static void startMetricsReporter(PreparableReporter report, Map conf) {
    +        report.prepare(new MetricRegistry(), conf);
    +        report.start();
    +        LOG.info("Started statistics report plugin...");
    +    }
    +
    +    public static void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(conf);
    +        for (PreparableReporter reporter : reporters) {
    +            startMetricsReporter(reporter, conf);
    +        }
    +    }
    +
    +    public static String getTopologyNameById(String topologyId) {
    +        String topologyName = null;
    +        try {
    +            topologyName = topologyIdToName(topologyId);
    +        } catch (InvalidTopologyException e) {
    +            LOG.error("Invalid topologyId=" + topologyId);
    +        }
    +        return topologyName;
    +    }
    +
    +    /**
    +     * Convert topologyId to topologyName. TopologyId = topoloygName-counter-timeStamp
    +     *
    +     * @param topologyId
    +     * @return
    +     */
    +    public static String topologyIdToName(String topologyId) throws InvalidTopologyException {
    --- End diff --
    
    This and the function above can be merged. 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---