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

[GitHub] storm pull request: [STORM-1279] port backtype.storm.daemon.superv...

GitHub user hustfxj opened a pull request:

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

    [STORM-1279] port backtype.storm.daemon.supervisor to java

    1 port supervisor.clj to java;
    2 Update all the callings to supervisor;
    3 Supervisor's class hierarchy as follows:
          SupervisorManger is supervisor' manger which can clean and shutdown supervisor;
          SyncSupervisorEvent is responsible for downloading/removing assignments and topologys' files;
          SyncProcessEvent is responsible for starting/killing workers;
          SupervisorUtils have common methods;
    4. fix the fails on supervisor test in Windows 

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

    $ git pull https://github.com/hustfxj/storm supervisor

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

    https://github.com/apache/storm/pull/1184.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 #1184
    
----
commit 08934e29982d3936c9e247a8d7bac563053f869f
Author: xiaojian.fxj <xi...@alibaba-inc.com>
Date:   2016-02-26T04:38:23Z

    port Supervisor to java

commit b281c735f0089d24407af67586a1b41de45ac382
Author: xiaojian.fxj <xi...@alibaba-inc.com>
Date:   2016-02-26T05:15:56Z

    update supervisor's structure

commit 19fcafbd0fe1cbee49e797824c47ba1f6b727270
Author: xiaojian.fxj <xi...@alibaba-inc.com>
Date:   2016-03-02T01:00:37Z

    update test codes about supervisor

commit b09b4129d845aff6be285ea1748b842499c40e0b
Author: xiaojian.fxj <xi...@alibaba-inc.com>
Date:   2016-03-04T04:14:41Z

    Merge branch 'master' into supervisor

----


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55937596
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/timer/SupervisorHeartbeat.java ---
    @@ -0,0 +1,87 @@
    +/**
    + * 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.supervisor.timer;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.supervisor.SupervisorData;
    +import org.apache.storm.generated.SupervisorInfo;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +
    +import java.util.ArrayList;
    +import java.util.HashMap;
    +import java.util.List;
    +import java.util.Map;
    +
    +public class SupervisorHeartbeat implements Runnable {
    +
    +     private final IStormClusterState stormClusterState;
    +     private final String supervisorId;
    +     private final Map conf;
    +     private final SupervisorData supervisorData;
    +
    +    public SupervisorHeartbeat(Map conf, SupervisorData supervisorData) {
    +        this.stormClusterState = supervisorData.getStormClusterState();
    +        this.supervisorId = supervisorData.getSupervisorId();
    +        this.supervisorData = supervisorData;
    +        this.conf = conf;
    +    }
    +
    +    private SupervisorInfo update(Map conf, SupervisorData supervisorData) {
    --- End diff --
    
    can this be renamed to buildSupervisorInfo or constructSupervisorInfo?


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55602167
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorUtils.java ---
    @@ -0,0 +1,273 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.curator.utils.PathUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.localizer.LocalResource;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.IOException;
    +import java.net.URLDecoder;
    +import java.util.*;
    +
    +public class SupervisorUtils {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorUtils.class);
    +
    +    private static final SupervisorUtils INSTANCE = new SupervisorUtils();
    +    private static SupervisorUtils _instance = INSTANCE;
    +
    +    public static void setInstance(SupervisorUtils u) {
    +        _instance = u;
    +    }
    +
    +    public static void resetInstance() {
    +        _instance = INSTANCE;
    +    }
    +
    +    public static Process workerLauncher(Map conf, String user, List<String> args, Map<String, String> environment, final String logPreFix,
    +            final Utils.ExitCodeCallable exitCodeCallback, File dir) throws IOException {
    +        if (StringUtils.isBlank(user)) {
    +            throw new IllegalArgumentException("User cannot be blank when calling workerLauncher.");
    +        }
    +        String wlinitial = (String) (conf.get(Config.SUPERVISOR_WORKER_LAUNCHER));
    +        String stormHome = ConfigUtils.concatIfNotNull(System.getProperty("storm.home"));
    +        String wl;
    +        if (StringUtils.isNotBlank(wlinitial)) {
    +            wl = wlinitial;
    +        } else {
    +            wl = stormHome + "/bin/worker-launcher";
    +        }
    +        List<String> commands = new ArrayList<>();
    +        commands.add(wl);
    +        commands.add(user);
    +        commands.addAll(args);
    +        return Utils.launchProcess(commands, environment, logPreFix, exitCodeCallback, dir);
    +    }
    +
    +    public static int workerLauncherAndWait(Map conf, String user, List<String> args, final Map<String, String> environment, final String logPreFix)
    +            throws IOException {
    +        int ret = 0;
    +        Process process = workerLauncher(conf, user, args, environment, logPreFix, null, null);
    +        if (StringUtils.isNotBlank(logPreFix))
    +            Utils.readAndLogStream(logPreFix, process.getInputStream());
    +        try {
    +            process.waitFor();
    +        } catch (InterruptedException e) {
    +            LOG.info("{} interrupted.", logPreFix);
    +        }
    +        ret = process.exitValue();
    +        return ret;
    +    }
    +
    +    public static void setupStormCodeDir(Map conf, Map stormConf, String dir) throws IOException {
    +        if (Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false)) {
    +            String logPrefix = "setup conf for " + dir;
    +            List<String> commands = new ArrayList<>();
    +            commands.add("code-dir");
    +            commands.add(dir);
    +            workerLauncherAndWait(conf, (String) (stormConf.get(Config.TOPOLOGY_SUBMITTER_USER)), commands, null, logPrefix);
    +        }
    +    }
    +
    +    public static void rmrAsUser(Map conf, String id, String path) throws IOException {
    +        String user = Utils.getFileOwner(path);
    +        String logPreFix = "rmr " + id;
    +        List<String> commands = new ArrayList<>();
    +        commands.add("rmr");
    +        commands.add(path);
    +        SupervisorUtils.workerLauncherAndWait(conf, user, commands, null, logPreFix);
    +        if (Utils.checkFileExists(path)) {
    +            throw new RuntimeException(path + " was not deleted.");
    +        }
    +    }
    +
    +    /**
    +     * Given the blob information returns the value of the uncompress field, handling it either being a string or a boolean value, or if it's not specified then
    +     * returns false
    +     * 
    +     * @param blobInfo
    +     * @return
    +     */
    +    public static Boolean isShouldUncompressBlob(Map<String, Object> blobInfo) {
    +        return new Boolean((String) blobInfo.get("uncompress"));
    +    }
    +
    +    /**
    +     * Remove a reference to a blob when its no longer needed
    +     * 
    +     * @param blobstoreMap
    +     * @return
    +     */
    +    public static List<LocalResource> blobstoreMapToLocalresources(Map<String, Map<String, Object>> blobstoreMap) {
    +        List<LocalResource> localResourceList = new ArrayList<>();
    +        if (blobstoreMap != null) {
    +            for (Map.Entry<String, Map<String, Object>> map : blobstoreMap.entrySet()) {
    +                LocalResource localResource = new LocalResource(map.getKey(), isShouldUncompressBlob(map.getValue()));
    +                localResourceList.add(localResource);
    +            }
    +        }
    +        return localResourceList;
    +    }
    +
    +    /**
    +     * For each of the downloaded topologies, adds references to the blobs that the topologies are using. This is used to reconstruct the cache on restart.
    +     * 
    +     * @param localizer
    +     * @param stormId
    +     * @param conf
    +     */
    +    public static void addBlobReferences(Localizer localizer, String stormId, Map conf) throws IOException {
    +        Map stormConf = ConfigUtils.readSupervisorStormConf(conf, stormId);
    +        Map<String, Map<String, Object>> blobstoreMap = (Map<String, Map<String, Object>>) stormConf.get(Config.TOPOLOGY_BLOBSTORE_MAP);
    +        String user = (String) stormConf.get(Config.TOPOLOGY_SUBMITTER_USER);
    +        String topoName = (String) stormConf.get(Config.TOPOLOGY_NAME);
    +        List<LocalResource> localresources = SupervisorUtils.blobstoreMapToLocalresources(blobstoreMap);
    +        if (blobstoreMap != null) {
    +            localizer.addReferences(localresources, user, topoName);
    +        }
    +    }
    +
    +    public static Set<String> readDownLoadedStormIds(Map conf) throws IOException {
    +        Set<String> stormIds = new HashSet<>();
    +        String path = ConfigUtils.supervisorStormDistRoot(conf);
    +        Collection<String> rets = Utils.readDirContents(path);
    +        for (String ret : rets) {
    +            stormIds.add(URLDecoder.decode(ret));
    +        }
    +        return stormIds;
    +    }
    +
    +    public static Collection<String> supervisorWorkerIds(Map conf) {
    +        String workerRoot = ConfigUtils.workerRoot(conf);
    +        return Utils.readDirContents(workerRoot);
    +    }
    +
    +    public static boolean checkTopoFilesExist(Map conf, String stormId) throws IOException {
    +        String stormroot = ConfigUtils.supervisorStormDistRoot(conf, stormId);
    +        String stormjarpath = ConfigUtils.supervisorStormJarPath(stormroot);
    +        String stormcodepath = ConfigUtils.supervisorStormCodePath(stormroot);
    +        String stormconfpath = ConfigUtils.supervisorStormConfPath(stormroot);
    +        if (!Utils.checkFileExists(stormroot))
    +            return false;
    +        if (!Utils.checkFileExists(stormcodepath))
    +            return false;
    +        if (!Utils.checkFileExists(stormconfpath))
    +            return false;
    +        if (ConfigUtils.isLocalMode(conf) || Utils.checkFileExists(stormjarpath))
    +            return true;
    +        return false;
    +    }
    +
    +    public static Collection<String> myWorkerIds(Map conf){
    +        return  Utils.readDirContents(ConfigUtils.workerRoot(conf));
    +    }
    +
    +    /**
    +     * Returns map from worr id to heartbeat
    +     *
    +     * @param conf
    +     * @return
    +     * @throws Exception
    +     */
    +    public static Map<String, LSWorkerHeartbeat> readWorkerHeartbeats(Map conf) throws Exception {
    +        return _instance.readWorkerHeartbeatsImpl(conf);
    +    }
    +
    +    public  Map<String, LSWorkerHeartbeat> readWorkerHeartbeatsImpl(Map conf) throws Exception {
    +        Map<String, LSWorkerHeartbeat> workerHeartbeats = new HashMap<>();
    +
    +        Collection<String> workerIds = SupervisorUtils.supervisorWorkerIds(conf);
    +
    +        for (String workerId : workerIds) {
    +            LSWorkerHeartbeat whb = readWorkerHeartbeat(conf, workerId);
    +            // ATTENTION: whb can be null
    +            workerHeartbeats.put(workerId, whb);
    +        }
    +        return workerHeartbeats;
    +    }
    +
    +
    +    /**
    +     * get worker heartbeat by workerId
    +     *
    +     * @param conf
    +     * @param workerId
    +     * @return
    +     * @throws IOException
    +     */
    +    public static LSWorkerHeartbeat readWorkerHeartbeat(Map conf, String workerId) {
    +        return _instance.readWorkerHeartbeatImpl(conf, workerId);
    +    }
    +
    +    public  LSWorkerHeartbeat readWorkerHeartbeatImpl(Map conf, String workerId) {
    +        try {
    +            LocalState localState = ConfigUtils.workerState(conf, workerId);
    +            return localState.getWorkerHeartBeat();
    +        } catch (Exception e) {
    +            LOG.warn("Failed to read local heartbeat for workerId : {},Ignoring exception.", workerId, e);
    +            return null;
    +        }
    +    }
    +
    +    public static boolean  isWorkerHbTimedOut(int now, LSWorkerHeartbeat whb, Map conf) {
    +        return _instance.isWorkerHbTimedOutImpl(now, whb, conf);
    +    }
    +
    +    public  boolean  isWorkerHbTimedOutImpl(int now, LSWorkerHeartbeat whb, Map conf) {
    +        boolean result = false;
    +        if ((now - whb.get_time_secs()) > Utils.getInt(conf.get(Config.SUPERVISOR_WORKER_TIMEOUT_SECS))) {
    +            result = true;
    +        }
    +        return result;
    +    }
    +
    +    public static String javaCmd(String cmd) {
    +        return _instance.javaCmdImpl(cmd);
    +    }
    +
    +    public String javaCmdImpl(String cmd) {
    +        String ret = null;
    +        String javaHome = System.getenv().get("JAVA_HOME");
    +        if (StringUtils.isNotBlank(javaHome)) {
    +            ret = javaHome + Utils.FILE_PATH_SEPARATOR + "bin" + Utils.FILE_PATH_SEPARATOR + cmd;
    +        } else {
    +            ret = cmd;
    +        }
    +        return ret;
    +    }
    +    
    +    public static List<ACL> supervisorZkAcls() {
    --- End diff --
    
    In the original code this was a static final const value.  It is probably not that big of a deal, but it would be nice to keep it 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-1279] port backtype.storm.daemon.superv...

Posted by hustfxj <gi...@git.apache.org>.
GitHub user hustfxj reopened a pull request:

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

    [STORM-1279] port backtype.storm.daemon.supervisor to java

    1 port supervisor.clj to java;
    2 Update all the callings to supervisor;
    3 Supervisor's class hierarchy as follows:
          ``SupervisorManger is supervisor' manger which can clean and shutdown supervisor;``
          ``SyncSupervisorEvent is responsible for downloading/removing assignments and topologys' files;``
          ``SyncProcessEvent is responsible for starting/killing workers;``
          ``SupervisorUtils have common methods;``
    4 create local-supervisor.clj for local mode.
    5. fix the fails on supervisor test in Windows 

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

    $ git pull https://github.com/hustfxj/storm supervisor

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

    https://github.com/apache/storm/pull/1184.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 #1184
    
----
commit 08934e29982d3936c9e247a8d7bac563053f869f
Author: xiaojian.fxj <xi...@alibaba-inc.com>
Date:   2016-02-26T04:38:23Z

    port Supervisor to java

commit b281c735f0089d24407af67586a1b41de45ac382
Author: xiaojian.fxj <xi...@alibaba-inc.com>
Date:   2016-02-26T05:15:56Z

    update supervisor's structure

commit 19fcafbd0fe1cbee49e797824c47ba1f6b727270
Author: xiaojian.fxj <xi...@alibaba-inc.com>
Date:   2016-03-02T01:00:37Z

    update test codes about supervisor

commit b09b4129d845aff6be285ea1748b842499c40e0b
Author: xiaojian.fxj <xi...@alibaba-inc.com>
Date:   2016-03-04T04:14:41Z

    Merge branch 'master' into supervisor

commit 42bacde20ea86867b874395532aa034cfad4f120
Author: xiaojian.fxj <xi...@alibaba-inc.com>
Date:   2016-03-06T08:05:14Z

    Merge branch 'master' into supervisor

----


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55585701
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorData.java ---
    @@ -0,0 +1,339 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.cluster.ClusterStateContext;
    +import org.apache.storm.cluster.ClusterUtils;
    +import org.apache.storm.cluster.DaemonType;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.ProfileRequest;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +import java.net.UnknownHostException;
    +import java.util.ArrayList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.concurrent.ConcurrentHashMap;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SupervisorData {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorData.class);
    +
    +    private Map conf;
    +    private IContext sharedContext;
    +    private volatile boolean active;
    +    private ISupervisor iSupervisor;
    +    private Utils.UptimeComputer upTime;
    +    private String stormVersion;
    +
    +    private ConcurrentHashMap<String, String> workerThreadPidsAtom; // for local mode
    +
    +    private IStormClusterState stormClusterState;
    +
    +    private LocalState localState;
    +
    +    private String supervisorId;
    +
    +    private String assignmentId;
    +
    +    private String hostName;
    +
    +    // used for reporting used ports when heartbeating
    +    private ConcurrentHashMap<Long, LocalAssignment> currAssignment;
    +
    +    private StormTimer heartbeatTimer;
    +
    +    private StormTimer eventTimer;
    +
    +    private StormTimer blobUpdateTimer;
    +
    +    private Localizer localizer;
    +
    +    private ConcurrentHashMap<String, Map<String, Object>> assignmentVersions;
    +
    +    private AtomicInteger syncRetry;
    +
    +    private final Object downloadLock = new Object();
    +
    +    private ConcurrentHashMap<String, List<ProfileRequest>> stormIdToProfileActions;
    +
    +    private CgroupManager resourceIsolationManager;
    +
    +    private ConcurrentHashSet<String> deadWorkers;
    +
    +    public SupervisorData(Map conf, IContext sharedContext, ISupervisor iSupervisor) {
    +        this.conf = conf;
    +        this.sharedContext = sharedContext;
    +        this.iSupervisor = iSupervisor;
    +        this.active = true;
    +        this.upTime = Utils.makeUptimeComputer();
    +        this.stormVersion = VersionInfo.getVersion();
    +        this.workerThreadPidsAtom = new ConcurrentHashMap<String, String>();
    +        this.deadWorkers = new ConcurrentHashSet();
    +
    +        List<ACL> acls = null;
    +        if (Utils.isZkAuthenticationConfiguredStormServer(conf)) {
    +            acls = SupervisorUtils.supervisorZkAcls();
    +        }
    +
    +        try {
    +            this.stormClusterState = ClusterUtils.mkStormClusterState(conf, acls, new ClusterStateContext(DaemonType.SUPERVISOR));
    +        } catch (Exception e) {
    +            LOG.error("supervisor can't create stormClusterState");
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        try {
    +            this.localState = ConfigUtils.supervisorState(conf);
    +            this.localizer = Utils.createLocalizer(conf, ConfigUtils.supervisorLocalDir(conf));
    +        } catch (IOException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +        this.supervisorId = iSupervisor.getSupervisorId();
    +        this.assignmentId = iSupervisor.getAssignmentId();
    +
    +        try {
    +            this.hostName = Utils.hostname(conf);
    +        } catch (UnknownHostException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        this.currAssignment = new ConcurrentHashMap<>();
    +
    +        this.heartbeatTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.eventTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.blobUpdateTimer = new StormTimer("blob-update-timer", new DefaultUncaughtExceptionHandler());
    +
    +        this.assignmentVersions = new ConcurrentHashMap<>();
    +        this.syncRetry = new AtomicInteger(0);
    +        this.stormIdToProfileActions = new ConcurrentHashMap<>();
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            try {
    +                this.resourceIsolationManager = (CgroupManager) Utils.newInstance((String) conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN));
    +                this.resourceIsolationManager.prepare(conf);
    +                LOG.info("Using resource isolation plugin {} {}", conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN), resourceIsolationManager);
    +            } catch (IOException e) {
    +                throw Utils.wrapInRuntime(e);
    +            }
    +        } else {
    +            this.resourceIsolationManager = null;
    +        }
    +    }
    +
    +    public ConcurrentHashMap<String, List<ProfileRequest>> getStormIdToProfileActions() {
    +        return stormIdToProfileActions;
    +    }
    +
    +    public void setStormIdToProfileActions(Map<String, List<ProfileRequest>> stormIdToProfileActions) {
    +        this.stormIdToProfileActions.clear();
    +        this.stormIdToProfileActions.putAll(stormIdToProfileActions);
    +    }
    +
    +    public Map getConf() {
    +        return conf;
    +    }
    +
    +    public void setConf(Map conf) {
    +        this.conf = conf;
    +    }
    +
    +    public IContext getSharedContext() {
    +        return sharedContext;
    +    }
    +
    +    public void setSharedContext(IContext sharedContext) {
    +        this.sharedContext = sharedContext;
    +    }
    +
    +    public boolean isActive() {
    +        return active;
    +    }
    +
    +    public void setActive(boolean active) {
    +        this.active = active;
    +    }
    +
    +    public ISupervisor getiSupervisor() {
    +        return iSupervisor;
    +    }
    +
    +    public void setiSupervisor(ISupervisor iSupervisor) {
    +        this.iSupervisor = iSupervisor;
    +    }
    +
    +    public Utils.UptimeComputer getUpTime() {
    +        return upTime;
    +    }
    +
    +    public void setUpTime(Utils.UptimeComputer upTime) {
    +        this.upTime = upTime;
    +    }
    +
    +    public String getStormVersion() {
    +        return stormVersion;
    +    }
    +
    +    public void setStormVersion(String stormVersion) {
    +        this.stormVersion = stormVersion;
    +    }
    +
    +    public ConcurrentHashMap<String, String> getWorkerThreadPidsAtom() {
    +        return workerThreadPidsAtom;
    +    }
    +
    +    public void setWorkerThreadPidsAtom(ConcurrentHashMap<String, String> workerThreadPidsAtom) {
    +        this.workerThreadPidsAtom = workerThreadPidsAtom;
    +    }
    +
    +    public IStormClusterState getStormClusterState() {
    +        return stormClusterState;
    +    }
    +
    +    public void setStormClusterState(IStormClusterState stormClusterState) {
    +        this.stormClusterState = stormClusterState;
    +    }
    +
    +    public LocalState getLocalState() {
    +        return localState;
    +    }
    +
    +    public void setLocalState(LocalState localState) {
    +        this.localState = localState;
    +    }
    +
    +    public String getSupervisorId() {
    +        return supervisorId;
    +    }
    +
    +    public void setSupervisorId(String supervisorId) {
    +        this.supervisorId = supervisorId;
    +    }
    +
    +    public String getAssignmentId() {
    +        return assignmentId;
    +    }
    +
    +    public void setAssignmentId(String assignmentId) {
    +        this.assignmentId = assignmentId;
    +    }
    +
    +    public String getHostName() {
    +        return hostName;
    +    }
    +
    +    public void setHostName(String hostName) {
    +        this.hostName = hostName;
    +    }
    +
    +    public ConcurrentHashMap<Long, LocalAssignment> getCurrAssignment() {
    +        return currAssignment;
    +    }
    +
    +    public void setCurrAssignment(Map<Long, LocalAssignment> currAssignment) {
    +        this.currAssignment.clear();
    +        this.currAssignment.putAll(currAssignment);
    +    }
    +
    +    public StormTimer getHeartbeatTimer() {
    +        return heartbeatTimer;
    +    }
    +
    +    public void setHeartbeatTimer(StormTimer heartbeatTimer) {
    +        this.heartbeatTimer = heartbeatTimer;
    +    }
    +
    +    public StormTimer getEventTimer() {
    +        return eventTimer;
    +    }
    +
    +    public void setEventTimer(StormTimer eventTimer) {
    +        this.eventTimer = eventTimer;
    +    }
    +
    +    public StormTimer getBlobUpdateTimer() {
    +        return blobUpdateTimer;
    +    }
    +
    +    public void setBlobUpdateTimer(StormTimer blobUpdateTimer) {
    +        this.blobUpdateTimer = blobUpdateTimer;
    +    }
    +
    +    public Localizer getLocalizer() {
    +        return localizer;
    +    }
    +
    +    public void setLocalizer(Localizer localizer) {
    +        this.localizer = localizer;
    +    }
    +
    +    public AtomicInteger getSyncRetry() {
    +        return syncRetry;
    +    }
    +
    +    public void setSyncRetry(AtomicInteger syncRetry) {
    +        this.syncRetry = syncRetry;
    +    }
    +
    +    public ConcurrentHashMap<String, Map<String, Object>> getAssignmentVersions() {
    +        return assignmentVersions;
    +    }
    +
    +    public void setAssignmentVersions(Map<String, Map<String, Object>> assignmentVersions) {
    +        this.assignmentVersions.clear();
    +        this.assignmentVersions.putAll(assignmentVersions);
    +    }
    +
    +    public CgroupManager getResourceIsolationManager() {
    +        return resourceIsolationManager;
    +    }
    +
    +    public void setResourceIsolationManager(CgroupManager resourceIsolationManager) {
    --- End diff --
    
    Not used


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#issuecomment-197701084
  
    Found another bug in supervisor:
    
    https://github.com/apache/storm/pull/1226
    
    just another note here to make sure we remember to get in the fix whether in clojure or 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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55585379
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorData.java ---
    @@ -0,0 +1,339 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.cluster.ClusterStateContext;
    +import org.apache.storm.cluster.ClusterUtils;
    +import org.apache.storm.cluster.DaemonType;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.ProfileRequest;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +import java.net.UnknownHostException;
    +import java.util.ArrayList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.concurrent.ConcurrentHashMap;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SupervisorData {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorData.class);
    +
    +    private Map conf;
    +    private IContext sharedContext;
    +    private volatile boolean active;
    +    private ISupervisor iSupervisor;
    +    private Utils.UptimeComputer upTime;
    +    private String stormVersion;
    +
    +    private ConcurrentHashMap<String, String> workerThreadPidsAtom; // for local mode
    +
    +    private IStormClusterState stormClusterState;
    +
    +    private LocalState localState;
    +
    +    private String supervisorId;
    +
    +    private String assignmentId;
    +
    +    private String hostName;
    +
    +    // used for reporting used ports when heartbeating
    +    private ConcurrentHashMap<Long, LocalAssignment> currAssignment;
    +
    +    private StormTimer heartbeatTimer;
    +
    +    private StormTimer eventTimer;
    +
    +    private StormTimer blobUpdateTimer;
    +
    +    private Localizer localizer;
    +
    +    private ConcurrentHashMap<String, Map<String, Object>> assignmentVersions;
    +
    +    private AtomicInteger syncRetry;
    +
    +    private final Object downloadLock = new Object();
    +
    +    private ConcurrentHashMap<String, List<ProfileRequest>> stormIdToProfileActions;
    +
    +    private CgroupManager resourceIsolationManager;
    +
    +    private ConcurrentHashSet<String> deadWorkers;
    +
    +    public SupervisorData(Map conf, IContext sharedContext, ISupervisor iSupervisor) {
    +        this.conf = conf;
    +        this.sharedContext = sharedContext;
    +        this.iSupervisor = iSupervisor;
    +        this.active = true;
    +        this.upTime = Utils.makeUptimeComputer();
    +        this.stormVersion = VersionInfo.getVersion();
    +        this.workerThreadPidsAtom = new ConcurrentHashMap<String, String>();
    +        this.deadWorkers = new ConcurrentHashSet();
    +
    +        List<ACL> acls = null;
    +        if (Utils.isZkAuthenticationConfiguredStormServer(conf)) {
    +            acls = SupervisorUtils.supervisorZkAcls();
    +        }
    +
    +        try {
    +            this.stormClusterState = ClusterUtils.mkStormClusterState(conf, acls, new ClusterStateContext(DaemonType.SUPERVISOR));
    +        } catch (Exception e) {
    +            LOG.error("supervisor can't create stormClusterState");
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        try {
    +            this.localState = ConfigUtils.supervisorState(conf);
    +            this.localizer = Utils.createLocalizer(conf, ConfigUtils.supervisorLocalDir(conf));
    +        } catch (IOException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +        this.supervisorId = iSupervisor.getSupervisorId();
    +        this.assignmentId = iSupervisor.getAssignmentId();
    +
    +        try {
    +            this.hostName = Utils.hostname(conf);
    +        } catch (UnknownHostException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        this.currAssignment = new ConcurrentHashMap<>();
    +
    +        this.heartbeatTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.eventTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.blobUpdateTimer = new StormTimer("blob-update-timer", new DefaultUncaughtExceptionHandler());
    +
    +        this.assignmentVersions = new ConcurrentHashMap<>();
    +        this.syncRetry = new AtomicInteger(0);
    +        this.stormIdToProfileActions = new ConcurrentHashMap<>();
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            try {
    +                this.resourceIsolationManager = (CgroupManager) Utils.newInstance((String) conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN));
    +                this.resourceIsolationManager.prepare(conf);
    +                LOG.info("Using resource isolation plugin {} {}", conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN), resourceIsolationManager);
    +            } catch (IOException e) {
    +                throw Utils.wrapInRuntime(e);
    +            }
    +        } else {
    +            this.resourceIsolationManager = null;
    +        }
    +    }
    +
    +    public ConcurrentHashMap<String, List<ProfileRequest>> getStormIdToProfileActions() {
    +        return stormIdToProfileActions;
    +    }
    +
    +    public void setStormIdToProfileActions(Map<String, List<ProfileRequest>> stormIdToProfileActions) {
    +        this.stormIdToProfileActions.clear();
    +        this.stormIdToProfileActions.putAll(stormIdToProfileActions);
    +    }
    +
    +    public Map getConf() {
    +        return conf;
    +    }
    +
    +    public void setConf(Map conf) {
    +        this.conf = conf;
    +    }
    +
    +    public IContext getSharedContext() {
    +        return sharedContext;
    +    }
    +
    +    public void setSharedContext(IContext sharedContext) {
    +        this.sharedContext = sharedContext;
    +    }
    +
    +    public boolean isActive() {
    +        return active;
    +    }
    +
    +    public void setActive(boolean active) {
    +        this.active = active;
    +    }
    +
    +    public ISupervisor getiSupervisor() {
    +        return iSupervisor;
    +    }
    +
    +    public void setiSupervisor(ISupervisor iSupervisor) {
    +        this.iSupervisor = iSupervisor;
    +    }
    +
    +    public Utils.UptimeComputer getUpTime() {
    +        return upTime;
    +    }
    +
    +    public void setUpTime(Utils.UptimeComputer upTime) {
    +        this.upTime = upTime;
    +    }
    +
    +    public String getStormVersion() {
    +        return stormVersion;
    +    }
    +
    +    public void setStormVersion(String stormVersion) {
    +        this.stormVersion = stormVersion;
    +    }
    +
    +    public ConcurrentHashMap<String, String> getWorkerThreadPidsAtom() {
    +        return workerThreadPidsAtom;
    +    }
    +
    +    public void setWorkerThreadPidsAtom(ConcurrentHashMap<String, String> workerThreadPidsAtom) {
    +        this.workerThreadPidsAtom = workerThreadPidsAtom;
    +    }
    +
    +    public IStormClusterState getStormClusterState() {
    +        return stormClusterState;
    +    }
    +
    +    public void setStormClusterState(IStormClusterState stormClusterState) {
    +        this.stormClusterState = stormClusterState;
    +    }
    +
    +    public LocalState getLocalState() {
    +        return localState;
    +    }
    +
    +    public void setLocalState(LocalState localState) {
    +        this.localState = localState;
    +    }
    +
    +    public String getSupervisorId() {
    +        return supervisorId;
    +    }
    +
    +    public void setSupervisorId(String supervisorId) {
    +        this.supervisorId = supervisorId;
    +    }
    +
    +    public String getAssignmentId() {
    +        return assignmentId;
    +    }
    +
    +    public void setAssignmentId(String assignmentId) {
    +        this.assignmentId = assignmentId;
    +    }
    +
    +    public String getHostName() {
    +        return hostName;
    +    }
    +
    +    public void setHostName(String hostName) {
    +        this.hostName = hostName;
    +    }
    +
    +    public ConcurrentHashMap<Long, LocalAssignment> getCurrAssignment() {
    +        return currAssignment;
    +    }
    +
    +    public void setCurrAssignment(Map<Long, LocalAssignment> currAssignment) {
    +        this.currAssignment.clear();
    +        this.currAssignment.putAll(currAssignment);
    +    }
    +
    +    public StormTimer getHeartbeatTimer() {
    +        return heartbeatTimer;
    +    }
    +
    +    public void setHeartbeatTimer(StormTimer heartbeatTimer) {
    +        this.heartbeatTimer = heartbeatTimer;
    +    }
    +
    +    public StormTimer getEventTimer() {
    +        return eventTimer;
    +    }
    +
    +    public void setEventTimer(StormTimer eventTimer) {
    +        this.eventTimer = eventTimer;
    +    }
    +
    +    public StormTimer getBlobUpdateTimer() {
    +        return blobUpdateTimer;
    +    }
    +
    +    public void setBlobUpdateTimer(StormTimer blobUpdateTimer) {
    +        this.blobUpdateTimer = blobUpdateTimer;
    +    }
    +
    +    public Localizer getLocalizer() {
    +        return localizer;
    +    }
    +
    +    public void setLocalizer(Localizer localizer) {
    --- End diff --
    
    Not used


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55603896
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncProcessEvent.java ---
    @@ -0,0 +1,669 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.ExecutorInfo;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.WorkerResources;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +import org.yaml.snakeyaml.Yaml;
    +
    +import java.io.File;
    +import java.io.FileWriter;
    +import java.io.IOException;
    +import java.util.*;
    +
    +/**
    + * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file - rmr
    + * heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new worker
    + * ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait for workers
    + * launch
    + */
    +public class SyncProcessEvent extends ShutdownWork implements Runnable {
    +
    +    private static Logger LOG = LoggerFactory.getLogger(SyncProcessEvent.class);
    +
    +    private  LocalState localState;
    +
    +    private SupervisorData supervisorData;
    +
    +    private class ProcessExitCallback implements Utils.ExitCodeCallable {
    +        private final String logPrefix;
    +        private final String workerId;
    +
    +        public ProcessExitCallback(String logPrefix, String workerId) {
    +            this.logPrefix = logPrefix;
    +            this.workerId = workerId;
    +        }
    +
    +        @Override
    +        public Object call() throws Exception {
    +            return null;
    +        }
    +
    +        @Override
    +        public Object call(int exitCode) {
    +            LOG.info("{} exited with code: {}", logPrefix, exitCode);
    +            supervisorData.getDeadWorkers().add(workerId);
    +            return null;
    +        }
    +    }
    +
    +    public SyncProcessEvent(){
    +
    +    }
    +    public SyncProcessEvent(SupervisorData supervisorData) {
    +        init(supervisorData);
    +    }
    +
    +    //TODO: initData is intended to local supervisor, so we will remove them after porting worker.clj to java
    +    public void init(SupervisorData supervisorData){
    +        this.supervisorData = supervisorData;
    +        this.localState = supervisorData.getLocalState();
    +    }
    +
    +
    +    /**
    +     * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file -
    +     * rmr heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new
    +     * worker ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait
    +     * for workers launch
    +     */
    +    @Override
    +    public void run() {
    +        LOG.debug("Syncing processes");
    +        try {
    +            Map conf = supervisorData.getConf();
    +            Map<Integer, LocalAssignment> assignedExecutors = localState.getLocalAssignmentsMap();
    +
    +            if (assignedExecutors == null) {
    +                assignedExecutors = new HashMap<>();
    +            }
    +            int now = Time.currentTimeSecs();
    +
    +            Map<String, StateHeartbeat> localWorkerStats = getLocalWorkerStats(supervisorData, assignedExecutors, now);
    +
    +            Set<String> keeperWorkerIds = new HashSet<>();
    +            Set<Integer> keepPorts = new HashSet<>();
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() == State.valid) {
    +                    keeperWorkerIds.add(entry.getKey());
    +                    keepPorts.add(stateHeartbeat.getHeartbeat().get_port());
    +                }
    +            }
    +            Map<Integer, LocalAssignment> reassignExecutors = getReassignExecutors(assignedExecutors, keepPorts);
    +            Map<Integer, String> newWorkerIds = new HashMap<>();
    +            for (Integer port : reassignExecutors.keySet()) {
    +                newWorkerIds.put(port, Utils.uuid());
    +            }
    +            LOG.debug("Syncing processes");
    +            LOG.debug("Assigned executors: {}", assignedExecutors);
    +            LOG.debug("Allocated: {}", localWorkerStats);
    +
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() != State.valid) {
    +                    LOG.info("Shutting down and clearing state for id {}, Current supervisor time: {}, State: {}, Heartbeat: {}", entry.getKey(), now,
    +                            stateHeartbeat.getState(), stateHeartbeat.getHeartbeat());
    +                    shutWorker(supervisorData, entry.getKey());
    +                }
    +            }
    +            // start new workers
    +            Map<String, Integer> newWorkerPortToIds = startNewWorkers(newWorkerIds, reassignExecutors);
    +
    +            Map<String, Integer> allWorkerPortToIds = new HashMap<>();
    +            Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +            for (String keeper : keeperWorkerIds) {
    +                allWorkerPortToIds.put(keeper, approvedWorkers.get(keeper));
    +            }
    +            allWorkerPortToIds.putAll(newWorkerPortToIds);
    +            localState.setApprovedWorkers(allWorkerPortToIds);
    +            waitForWorkersLaunch(conf, newWorkerPortToIds.keySet());
    +
    +        } catch (Exception e) {
    +            LOG.error("Failed Sync Process", e);
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +    }
    +
    +    protected void waitForWorkersLaunch(Map conf, Set<String> workerIds) throws Exception {
    +        int startTime = Time.currentTimeSecs();
    +        int timeOut = (int) conf.get(Config.NIMBUS_SUPERVISOR_TIMEOUT_SECS);
    +        for (String workerId : workerIds) {
    +            LocalState localState = ConfigUtils.workerState(conf, workerId);
    +            while (true) {
    +                LSWorkerHeartbeat hb = localState.getWorkerHeartBeat();
    +                if (hb != null || (Time.currentTimeSecs() - startTime) > timeOut)
    +                    break;
    +                LOG.info("{} still hasn't started", workerId);
    +                Time.sleep(500);
    +            }
    +            if (localState.getWorkerHeartBeat() == null) {
    +                LOG.info("Worker {} failed to start", workerId);
    +            }
    +        }
    +    }
    +
    +    protected Map<Integer, LocalAssignment> getReassignExecutors(Map<Integer, LocalAssignment> assignExecutors, Set<Integer> keepPorts) {
    +        Map<Integer, LocalAssignment> reassignExecutors = new HashMap<>();
    +        reassignExecutors.putAll(assignExecutors);
    +        for (Integer port : keepPorts) {
    +            reassignExecutors.remove(port);
    +        }
    +        return reassignExecutors;
    +    }
    +
    +
    +
    +    /**
    +     * Returns map from worker id to worker heartbeat. if the heartbeat is nil, then the worker is dead
    +     * 
    +     * @param assignedExecutors
    +     * @return
    +     * @throws Exception
    +     */
    +    public Map<String, StateHeartbeat> getLocalWorkerStats(SupervisorData supervisorData, Map<Integer, LocalAssignment> assignedExecutors, int now) throws Exception {
    +        Map<String, StateHeartbeat> workerIdHbstate = new HashMap<>();
    +        Map conf = supervisorData.getConf();
    +        LocalState localState = supervisorData.getLocalState();
    +        Map<String, LSWorkerHeartbeat> idToHeartbeat = SupervisorUtils.readWorkerHeartbeats(conf);
    +        Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +        Set<String> approvedIds = new HashSet<>();
    +        if (approvedWorkers != null) {
    +            approvedIds.addAll(approvedWorkers.keySet());
    +        }
    +        for (Map.Entry<String, LSWorkerHeartbeat> entry : idToHeartbeat.entrySet()) {
    +            String workerId = entry.getKey();
    +            LSWorkerHeartbeat whb = entry.getValue();
    +            State state;
    +            if (whb == null) {
    +                state = State.notStarted;
    +            } else if (!approvedIds.contains(workerId) || !matchesAssignment(whb, assignedExecutors)) {
    +                state = State.disallowed;
    +            } else if (supervisorData.getDeadWorkers().contains(workerId)) {
    +                LOG.info("Worker Process {}as died", workerId);
    --- End diff --
    
    should be
    ```
                    LOG.info("Worker Process {} has died", workerId);
    ```


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55584755
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorData.java ---
    @@ -0,0 +1,339 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.cluster.ClusterStateContext;
    +import org.apache.storm.cluster.ClusterUtils;
    +import org.apache.storm.cluster.DaemonType;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.ProfileRequest;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +import java.net.UnknownHostException;
    +import java.util.ArrayList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.concurrent.ConcurrentHashMap;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SupervisorData {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorData.class);
    +
    +    private Map conf;
    +    private IContext sharedContext;
    +    private volatile boolean active;
    +    private ISupervisor iSupervisor;
    +    private Utils.UptimeComputer upTime;
    +    private String stormVersion;
    +
    +    private ConcurrentHashMap<String, String> workerThreadPidsAtom; // for local mode
    +
    +    private IStormClusterState stormClusterState;
    +
    +    private LocalState localState;
    +
    +    private String supervisorId;
    +
    +    private String assignmentId;
    +
    +    private String hostName;
    +
    +    // used for reporting used ports when heartbeating
    +    private ConcurrentHashMap<Long, LocalAssignment> currAssignment;
    +
    +    private StormTimer heartbeatTimer;
    +
    +    private StormTimer eventTimer;
    +
    +    private StormTimer blobUpdateTimer;
    +
    +    private Localizer localizer;
    +
    +    private ConcurrentHashMap<String, Map<String, Object>> assignmentVersions;
    +
    +    private AtomicInteger syncRetry;
    +
    +    private final Object downloadLock = new Object();
    +
    +    private ConcurrentHashMap<String, List<ProfileRequest>> stormIdToProfileActions;
    +
    +    private CgroupManager resourceIsolationManager;
    +
    +    private ConcurrentHashSet<String> deadWorkers;
    +
    +    public SupervisorData(Map conf, IContext sharedContext, ISupervisor iSupervisor) {
    +        this.conf = conf;
    +        this.sharedContext = sharedContext;
    +        this.iSupervisor = iSupervisor;
    +        this.active = true;
    +        this.upTime = Utils.makeUptimeComputer();
    +        this.stormVersion = VersionInfo.getVersion();
    +        this.workerThreadPidsAtom = new ConcurrentHashMap<String, String>();
    +        this.deadWorkers = new ConcurrentHashSet();
    +
    +        List<ACL> acls = null;
    +        if (Utils.isZkAuthenticationConfiguredStormServer(conf)) {
    +            acls = SupervisorUtils.supervisorZkAcls();
    +        }
    +
    +        try {
    +            this.stormClusterState = ClusterUtils.mkStormClusterState(conf, acls, new ClusterStateContext(DaemonType.SUPERVISOR));
    +        } catch (Exception e) {
    +            LOG.error("supervisor can't create stormClusterState");
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        try {
    +            this.localState = ConfigUtils.supervisorState(conf);
    +            this.localizer = Utils.createLocalizer(conf, ConfigUtils.supervisorLocalDir(conf));
    +        } catch (IOException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +        this.supervisorId = iSupervisor.getSupervisorId();
    +        this.assignmentId = iSupervisor.getAssignmentId();
    +
    +        try {
    +            this.hostName = Utils.hostname(conf);
    +        } catch (UnknownHostException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        this.currAssignment = new ConcurrentHashMap<>();
    +
    +        this.heartbeatTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.eventTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.blobUpdateTimer = new StormTimer("blob-update-timer", new DefaultUncaughtExceptionHandler());
    +
    +        this.assignmentVersions = new ConcurrentHashMap<>();
    +        this.syncRetry = new AtomicInteger(0);
    +        this.stormIdToProfileActions = new ConcurrentHashMap<>();
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            try {
    +                this.resourceIsolationManager = (CgroupManager) Utils.newInstance((String) conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN));
    +                this.resourceIsolationManager.prepare(conf);
    +                LOG.info("Using resource isolation plugin {} {}", conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN), resourceIsolationManager);
    +            } catch (IOException e) {
    +                throw Utils.wrapInRuntime(e);
    +            }
    +        } else {
    +            this.resourceIsolationManager = null;
    +        }
    +    }
    +
    +    public ConcurrentHashMap<String, List<ProfileRequest>> getStormIdToProfileActions() {
    +        return stormIdToProfileActions;
    +    }
    +
    +    public void setStormIdToProfileActions(Map<String, List<ProfileRequest>> stormIdToProfileActions) {
    +        this.stormIdToProfileActions.clear();
    +        this.stormIdToProfileActions.putAll(stormIdToProfileActions);
    +    }
    +
    +    public Map getConf() {
    +        return conf;
    +    }
    +
    +    public void setConf(Map conf) {
    +        this.conf = conf;
    +    }
    +
    +    public IContext getSharedContext() {
    +        return sharedContext;
    +    }
    +
    +    public void setSharedContext(IContext sharedContext) {
    +        this.sharedContext = sharedContext;
    +    }
    +
    +    public boolean isActive() {
    +        return active;
    +    }
    +
    +    public void setActive(boolean active) {
    +        this.active = active;
    +    }
    +
    +    public ISupervisor getiSupervisor() {
    +        return iSupervisor;
    +    }
    +
    +    public void setiSupervisor(ISupervisor iSupervisor) {
    +        this.iSupervisor = iSupervisor;
    +    }
    +
    +    public Utils.UptimeComputer getUpTime() {
    +        return upTime;
    +    }
    +
    +    public void setUpTime(Utils.UptimeComputer upTime) {
    +        this.upTime = upTime;
    +    }
    +
    +    public String getStormVersion() {
    +        return stormVersion;
    +    }
    +
    +    public void setStormVersion(String stormVersion) {
    +        this.stormVersion = stormVersion;
    +    }
    +
    +    public ConcurrentHashMap<String, String> getWorkerThreadPidsAtom() {
    +        return workerThreadPidsAtom;
    +    }
    +
    +    public void setWorkerThreadPidsAtom(ConcurrentHashMap<String, String> workerThreadPidsAtom) {
    +        this.workerThreadPidsAtom = workerThreadPidsAtom;
    +    }
    +
    +    public IStormClusterState getStormClusterState() {
    +        return stormClusterState;
    +    }
    +
    +    public void setStormClusterState(IStormClusterState stormClusterState) {
    +        this.stormClusterState = stormClusterState;
    +    }
    +
    +    public LocalState getLocalState() {
    +        return localState;
    +    }
    +
    +    public void setLocalState(LocalState localState) {
    --- End diff --
    
    Not used


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r57182643
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncProcessEvent.java ---
    @@ -0,0 +1,428 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.daemon.supervisor.workermanager.IWorkerManager;
    +import org.apache.storm.generated.ExecutorInfo;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.WorkerResources;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +import org.yaml.snakeyaml.Yaml;
    +
    +import java.io.File;
    +import java.io.FileWriter;
    +import java.io.IOException;
    +import java.util.*;
    +
    +/**
    + * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file - rmr
    + * heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new worker
    + * ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait for workers
    + * launch
    + */
    +public class SyncProcessEvent implements Runnable {
    +
    +    private static Logger LOG = LoggerFactory.getLogger(SyncProcessEvent.class);
    +
    +    private  LocalState localState;
    +    private  SupervisorData supervisorData;
    +    public static final ExecutorInfo SYSTEM_EXECUTOR_INFO = new ExecutorInfo(-1, -1);
    +
    +    private class ProcessExitCallback implements Utils.ExitCodeCallable {
    +        private final String logPrefix;
    +        private final String workerId;
    +
    +        public ProcessExitCallback(String logPrefix, String workerId) {
    +            this.logPrefix = logPrefix;
    +            this.workerId = workerId;
    +        }
    +
    +        @Override
    +        public Object call() throws Exception {
    +            return null;
    +        }
    +
    +        @Override
    +        public Object call(int exitCode) {
    +            LOG.info("{} exited with code: {}", logPrefix, exitCode);
    +            supervisorData.getDeadWorkers().add(workerId);
    +            return null;
    +        }
    +    }
    +
    +    public SyncProcessEvent(){
    +
    +    }
    +    public SyncProcessEvent(SupervisorData supervisorData) {
    +        init(supervisorData);
    +    }
    +
    +    //TODO: initData is intended to local supervisor, so we will remove them after porting worker.clj to java
    +    public void init(SupervisorData supervisorData){
    +        this.supervisorData = supervisorData;
    +        this.localState = supervisorData.getLocalState();
    +    }
    +
    +    @Override
    +    public void run() {
    +        LOG.debug("Syncing processes");
    +        try {
    +            Map conf = supervisorData.getConf();
    +            Map<Integer, LocalAssignment> assignedExecutors = localState.getLocalAssignmentsMap();
    +
    +            if (assignedExecutors == null) {
    +                assignedExecutors = new HashMap<>();
    +            }
    +            int now = Time.currentTimeSecs();
    +
    +            Map<String, StateHeartbeat> localWorkerStats = getLocalWorkerStats(supervisorData, assignedExecutors, now);
    +
    +            Set<String> keeperWorkerIds = new HashSet<>();
    +            Set<Integer> keepPorts = new HashSet<>();
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() == State.VALID) {
    +                    keeperWorkerIds.add(entry.getKey());
    +                    keepPorts.add(stateHeartbeat.getHeartbeat().get_port());
    +                }
    +            }
    +            Map<Integer, LocalAssignment> reassignExecutors = getReassignExecutors(assignedExecutors, keepPorts);
    +            Map<Integer, String> newWorkerIds = new HashMap<>();
    +            for (Integer port : reassignExecutors.keySet()) {
    +                newWorkerIds.put(port, Utils.uuid());
    +            }
    +            LOG.debug("Syncing processes");
    +            LOG.debug("Assigned executors: {}", assignedExecutors);
    +            LOG.debug("Allocated: {}", localWorkerStats);
    +
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() != State.VALID) {
    +                    LOG.info("Shutting down and clearing state for id {}, Current supervisor time: {}, State: {}, Heartbeat: {}", entry.getKey(), now,
    +                            stateHeartbeat.getState(), stateHeartbeat.getHeartbeat());
    +                    shutWorker(supervisorData, supervisorData.getWorkerManager(), entry.getKey());
    +                }
    +            }
    +            // start new workers
    +            Map<String, Integer> newWorkerPortToIds = startNewWorkers(newWorkerIds, reassignExecutors);
    +
    +            Map<String, Integer> allWorkerPortToIds = new HashMap<>();
    +            Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +            for (String keeper : keeperWorkerIds) {
    +                allWorkerPortToIds.put(keeper, approvedWorkers.get(keeper));
    +            }
    +            allWorkerPortToIds.putAll(newWorkerPortToIds);
    +            localState.setApprovedWorkers(allWorkerPortToIds);
    +            waitForWorkersLaunch(conf, newWorkerPortToIds.keySet());
    +
    +        } catch (Exception e) {
    +            LOG.error("Failed Sync Process", e);
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +    }
    +
    +    protected void waitForWorkersLaunch(Map conf, Set<String> workerIds) throws Exception {
    +        int startTime = Time.currentTimeSecs();
    +        int timeOut = (int) conf.get(Config.NIMBUS_SUPERVISOR_TIMEOUT_SECS);
    +        for (String workerId : workerIds) {
    +            LocalState localState = ConfigUtils.workerState(conf, workerId);
    +            while (true) {
    +                LSWorkerHeartbeat hb = localState.getWorkerHeartBeat();
    +                if (hb != null || (Time.currentTimeSecs() - startTime) > timeOut)
    +                    break;
    +                LOG.info("{} still hasn't started", workerId);
    +                Time.sleep(500);
    +            }
    +            if (localState.getWorkerHeartBeat() == null) {
    +                LOG.info("Worker {} failed to start", workerId);
    +            }
    +        }
    +    }
    +
    +    protected Map<Integer, LocalAssignment> getReassignExecutors(Map<Integer, LocalAssignment> assignExecutors, Set<Integer> keepPorts) {
    +        Map<Integer, LocalAssignment> reassignExecutors = new HashMap<>();
    +        reassignExecutors.putAll(assignExecutors);
    +        for (Integer port : keepPorts) {
    +            reassignExecutors.remove(port);
    +        }
    +        return reassignExecutors;
    +    }
    +    
    +    /**
    +     * Returns map from worker id to worker heartbeat. if the heartbeat is nil, then the worker is dead
    +     * 
    +     * @param assignedExecutors
    +     * @return
    +     * @throws Exception
    +     */
    +    public Map<String, StateHeartbeat> getLocalWorkerStats(SupervisorData supervisorData, Map<Integer, LocalAssignment> assignedExecutors, int now) throws Exception {
    +        Map<String, StateHeartbeat> workerIdHbstate = new HashMap<>();
    +        Map conf = supervisorData.getConf();
    +        LocalState localState = supervisorData.getLocalState();
    +        Map<String, LSWorkerHeartbeat> idToHeartbeat = SupervisorUtils.readWorkerHeartbeats(conf);
    +        Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +        Set<String> approvedIds = new HashSet<>();
    +        if (approvedWorkers != null) {
    +            approvedIds.addAll(approvedWorkers.keySet());
    +        }
    +        for (Map.Entry<String, LSWorkerHeartbeat> entry : idToHeartbeat.entrySet()) {
    +            String workerId = entry.getKey();
    +            LSWorkerHeartbeat whb = entry.getValue();
    +            State state;
    +            if (whb == null) {
    +                state = State.NOT_STARTED;
    +            } else if (!approvedIds.contains(workerId) || !matchesAssignment(whb, assignedExecutors)) {
    +                state = State.DISALLOWED;
    +            } else if (supervisorData.getDeadWorkers().contains(workerId)) {
    +                LOG.info("Worker Process {} has died", workerId);
    +                state = State.TIMED_OUT;
    +            } else if (SupervisorUtils.isWorkerHbTimedOut(now, whb, conf)) {
    +                state = State.TIMED_OUT;
    +            } else {
    +                state = State.VALID;
    +            }
    +            LOG.debug("Worker:{} state:{} WorkerHeartbeat:{} at supervisor time-secs {}", workerId, state, whb, now);
    +            workerIdHbstate.put(workerId, new StateHeartbeat(state, whb));
    +        }
    +        return workerIdHbstate;
    +    }
    +
    +    protected boolean matchesAssignment(LSWorkerHeartbeat whb, Map<Integer, LocalAssignment> assignedExecutors) {
    +        LocalAssignment localAssignment = assignedExecutors.get(whb.get_port());
    +        if (localAssignment == null || !localAssignment.get_topology_id().equals(whb.get_topology_id())) {
    +            return false;
    +        }
    +        List<ExecutorInfo> executorInfos = new ArrayList<>();
    +        executorInfos.addAll(whb.get_executors());
    +        // remove SYSTEM_EXECUTOR_ID
    +        executorInfos.remove(SYSTEM_EXECUTOR_INFO);
    +        List<ExecutorInfo> localExecuorInfos = localAssignment.get_executors();
    +
    +        if (localExecuorInfos.size() != executorInfos.size())
    +            return false;
    +
    +        for (ExecutorInfo executorInfo : localExecuorInfos){
    +            if (!localExecuorInfos.contains(executorInfo))
    +                return false;
    +        }
    +        return true;
    +    }
    +
    +    /**
    +     * launch a worker in local mode.
    +     */
    +    protected void launchLocalWorker(SupervisorData supervisorData, String stormId, Long port, String workerId, WorkerResources resources) throws IOException {
    +        // port this function after porting worker to java
    +    }
    +
    +    protected void launchDistributedWorker(IWorkerManager workerManager, Map conf, String supervisorId, String assignmentId, String stormId, Long port, String workerId,
    +                                           WorkerResources resources, ConcurrentHashSet deadWorkers) throws IOException {
    +        Map stormConf = ConfigUtils.readSupervisorStormConf(conf, stormId);
    +        String user = (String) stormConf.get(Config.TOPOLOGY_SUBMITTER_USER);
    +        writeLogMetadata(stormConf, user, workerId, stormId, port, conf);
    +        ConfigUtils.setWorkerUserWSE(conf, workerId, user);
    +        createArtifactsLink(conf, stormId, port, workerId);
    +
    +        String logPrefix = "Worker Process " + workerId;
    +        if (deadWorkers != null)
    +            deadWorkers.remove(workerId);
    +        createBlobstoreLinks(conf, stormId, workerId);
    +        ProcessExitCallback processExitCallback = new ProcessExitCallback(logPrefix, workerId);
    +        workerManager.launchWorker(supervisorId, assignmentId, stormId, port, workerId, resources, processExitCallback);
    +    }
    +
    +    protected Map<String, Integer> startNewWorkers(Map<Integer, String> newWorkerIds, Map<Integer, LocalAssignment> reassignExecutors) throws IOException {
    +
    +        Map<String, Integer> newValidWorkerIds = new HashMap<>();
    +        Map conf = supervisorData.getConf();
    +        String supervisorId = supervisorData.getSupervisorId();
    +        String clusterMode = ConfigUtils.clusterMode(conf);
    +
    +        for (Map.Entry<Integer, LocalAssignment> entry : reassignExecutors.entrySet()) {
    +            Integer port = entry.getKey();
    +            LocalAssignment assignment = entry.getValue();
    +            String workerId = newWorkerIds.get(port);
    +            String stormId = assignment.get_topology_id();
    +            WorkerResources resources = assignment.get_resources();
    +
    +            // This condition checks for required files exist before launching the worker
    +            if (SupervisorUtils.doRequiredTopoFilesExist(conf, stormId)) {
    +                String pidsPath = ConfigUtils.workerPidsRoot(conf, workerId);
    +                String hbPath = ConfigUtils.workerHeartbeatsRoot(conf, workerId);
    +
    +                LOG.info("Launching worker with assignment {} for this supervisor {} on port {} with id {}", assignment, supervisorData.getSupervisorId(), port,
    +                        workerId);
    +
    +                FileUtils.forceMkdir(new File(pidsPath));
    +                FileUtils.forceMkdir(new File(ConfigUtils.workerTmpRoot(conf, workerId)));
    +                FileUtils.forceMkdir(new File(hbPath));
    +
    +                if (clusterMode.endsWith("distributed")) {
    +                    launchDistributedWorker(supervisorData.getWorkerManager(), conf, supervisorId, supervisorData.getAssignmentId(), stormId, port.longValue(), workerId, resources, supervisorData.getDeadWorkers());
    +                } else if (clusterMode.endsWith("local")) {
    +                    launchLocalWorker(supervisorData, stormId, port.longValue(), workerId, resources);
    +                }
    +                newValidWorkerIds.put(workerId, port);
    +
    +            } else {
    +                LOG.info("Missing topology storm code, so can't launch worker with assignment {} for this supervisor {} on port {} with id {}", assignment,
    +                        supervisorData.getSupervisorId(), port, workerId);
    +            }
    +
    +        }
    +        return newValidWorkerIds;
    +    }
    +
    +    public void writeLogMetadata(Map stormconf, String user, String workerId, String stormId, Long port, Map conf) throws IOException {
    +        Map data = new HashMap();
    +        data.put(Config.TOPOLOGY_SUBMITTER_USER, user);
    +        data.put("worker-id", workerId);
    +
    +        Set<String> logsGroups = new HashSet<>();
    +        //for supervisor-test
    +        if (stormconf.get(Config.LOGS_GROUPS) != null) {
    +            List<String> groups = (List<String>) stormconf.get(Config.LOGS_GROUPS);
    +            for (String group : groups){
    +                logsGroups.add(group);
    +            }
    +        }
    +        if (stormconf.get(Config.TOPOLOGY_GROUPS) != null) {
    +            List<String> topGroups = (List<String>) stormconf.get(Config.TOPOLOGY_GROUPS);
    +            logsGroups.addAll(topGroups);
    +        }
    +        data.put(Config.LOGS_GROUPS, logsGroups.toArray());
    +
    +        Set<String> logsUsers = new HashSet<>();
    +        if (stormconf.get(Config.LOGS_USERS) != null) {
    +            List<String> logUsers = (List<String>) stormconf.get(Config.LOGS_USERS);
    +            for (String logUser : logUsers){
    +                logsUsers.add(logUser);
    +            }
    +        }
    +        if (stormconf.get(Config.TOPOLOGY_USERS) != null) {
    +            List<String> topUsers = (List<String>) stormconf.get(Config.TOPOLOGY_USERS);
    +            for (String logUser : topUsers){
    +                logsUsers.add(logUser);
    +            }
    +        }
    +        data.put(Config.LOGS_USERS, logsUsers.toArray());
    +        writeLogMetadataToYamlFile(stormId, port, data, conf);
    +    }
    +
    +    /**
    +     * run worker as user needs the directory to have special permissions or it is insecure
    +     * 
    +     * @param stormId
    +     * @param port
    +     * @param data
    +     * @param conf
    +     * @throws IOException
    +     */
    +    public void writeLogMetadataToYamlFile(String stormId, Long port, Map data, Map conf) throws IOException {
    +        File file = ConfigUtils.getLogMetaDataFile(conf, stormId, port.intValue());
    +
    +        if (!Utils.checkFileExists(file.getParent())) {
    +            if (Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false)) {
    +                FileUtils.forceMkdir(file.getParentFile());
    +                SupervisorUtils.setupStormCodeDir(conf, ConfigUtils.readSupervisorStormConf(conf, stormId), file.getParentFile().getCanonicalPath());
    +            } else {
    +                file.getParentFile().mkdirs();
    +            }
    +        }
    +        FileWriter writer = new FileWriter(file);
    +        Yaml yaml = new Yaml();
    +        try {
    +            yaml.dump(data, writer);
    +        }finally {
    +            writer.close();
    +        }
    +    }
    +
    +    /**
    +     * Create a symlink from workder directory to its port artifacts directory
    +     * 
    +     * @param conf
    +     * @param stormId
    +     * @param port
    +     * @param workerId
    +     */
    +    protected void createArtifactsLink(Map conf, String stormId, Long port, String workerId) throws IOException {
    +        String workerDir = ConfigUtils.workerRoot(conf, workerId);
    +        String topoDir = ConfigUtils.workerArtifactsRoot(conf, stormId);
    +        if (Utils.checkFileExists(workerDir)) {
    +            Utils.createSymlink(workerDir, topoDir, "artifacts", String.valueOf(port));
    +        }
    +    }
    +
    +    /**
    +     * Create symlinks in worker launch directory for all blobs
    +     * 
    +     * @param conf
    +     * @param stormId
    +     * @param workerId
    +     * @throws IOException
    +     */
    +    protected void createBlobstoreLinks(Map conf, String stormId, String workerId) throws IOException {
    +        String stormRoot = ConfigUtils.supervisorStormDistRoot(conf, stormId);
    +        Map stormConf = ConfigUtils.readSupervisorStormConf(conf, stormId);
    +        String workerRoot = ConfigUtils.workerRoot(conf, workerId);
    +        Map<String, Map<String, Object>> blobstoreMap = (Map<String, Map<String, Object>>) stormConf.get(Config.TOPOLOGY_BLOBSTORE_MAP);
    +        List<String> blobFileNames = new ArrayList<>();
    +        if (blobstoreMap != null) {
    +            for (Map.Entry<String, Map<String, Object>> entry : blobstoreMap.entrySet()) {
    +                String key = entry.getKey();
    +                Map<String, Object> blobInfo = entry.getValue();
    +                String ret = null;
    +                if (blobInfo != null && blobInfo.containsKey("localname")) {
    +                    ret = (String) blobInfo.get("localname");
    +                } else {
    +                    ret = key;
    +                }
    +                blobFileNames.add(ret);
    +            }
    +        }
    +        List<String> resourceFileNames = new ArrayList<>();
    +        resourceFileNames.add(ConfigUtils.RESOURCES_SUBDIR);
    +        resourceFileNames.addAll(blobFileNames);
    +        LOG.info("Creating symlinks for worker-id: {} storm-id: {} for files({}): {}", workerId, stormId, resourceFileNames.size(), resourceFileNames);
    +        Utils.createSymlink(workerRoot, stormRoot, ConfigUtils.RESOURCES_SUBDIR);
    +        for (String fileName : blobFileNames) {
    +            Utils.createSymlink(workerRoot, stormRoot, fileName, fileName);
    +        }
    +    }
    +
    +    public void shutWorker(SupervisorData supervisorData, IWorkerManager workerManager, String workerId) throws IOException, InterruptedException{
    --- End diff --
    
    And why do we need this function? Why are we calling the cleanupWorker function in here and not in shutdownWorker?


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55937586
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/timer/SupervisorHeartbeat.java ---
    @@ -0,0 +1,87 @@
    +/**
    + * 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.supervisor.timer;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.supervisor.SupervisorData;
    +import org.apache.storm.generated.SupervisorInfo;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +
    +import java.util.ArrayList;
    +import java.util.HashMap;
    +import java.util.List;
    +import java.util.Map;
    +
    +public class SupervisorHeartbeat implements Runnable {
    --- End diff --
    
    does it need to be Runnable?


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55937648
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/timer/SupervisorHeartbeat.java ---
    @@ -0,0 +1,87 @@
    +/**
    + * 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.supervisor.timer;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.supervisor.SupervisorData;
    +import org.apache.storm.generated.SupervisorInfo;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +
    +import java.util.ArrayList;
    +import java.util.HashMap;
    +import java.util.List;
    +import java.util.Map;
    +
    +public class SupervisorHeartbeat implements Runnable {
    --- End diff --
    
    Please ignore my above comment. I see that it is being scheduled. 


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55584050
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorData.java ---
    @@ -0,0 +1,339 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.cluster.ClusterStateContext;
    +import org.apache.storm.cluster.ClusterUtils;
    +import org.apache.storm.cluster.DaemonType;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.ProfileRequest;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +import java.net.UnknownHostException;
    +import java.util.ArrayList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.concurrent.ConcurrentHashMap;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SupervisorData {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorData.class);
    +
    +    private Map conf;
    +    private IContext sharedContext;
    +    private volatile boolean active;
    +    private ISupervisor iSupervisor;
    +    private Utils.UptimeComputer upTime;
    +    private String stormVersion;
    +
    +    private ConcurrentHashMap<String, String> workerThreadPidsAtom; // for local mode
    +
    +    private IStormClusterState stormClusterState;
    +
    +    private LocalState localState;
    +
    +    private String supervisorId;
    +
    +    private String assignmentId;
    +
    +    private String hostName;
    +
    +    // used for reporting used ports when heartbeating
    +    private ConcurrentHashMap<Long, LocalAssignment> currAssignment;
    +
    +    private StormTimer heartbeatTimer;
    +
    +    private StormTimer eventTimer;
    +
    +    private StormTimer blobUpdateTimer;
    +
    +    private Localizer localizer;
    +
    +    private ConcurrentHashMap<String, Map<String, Object>> assignmentVersions;
    +
    +    private AtomicInteger syncRetry;
    +
    +    private final Object downloadLock = new Object();
    +
    +    private ConcurrentHashMap<String, List<ProfileRequest>> stormIdToProfileActions;
    +
    +    private CgroupManager resourceIsolationManager;
    +
    +    private ConcurrentHashSet<String> deadWorkers;
    +
    +    public SupervisorData(Map conf, IContext sharedContext, ISupervisor iSupervisor) {
    +        this.conf = conf;
    +        this.sharedContext = sharedContext;
    +        this.iSupervisor = iSupervisor;
    +        this.active = true;
    +        this.upTime = Utils.makeUptimeComputer();
    +        this.stormVersion = VersionInfo.getVersion();
    +        this.workerThreadPidsAtom = new ConcurrentHashMap<String, String>();
    +        this.deadWorkers = new ConcurrentHashSet();
    +
    +        List<ACL> acls = null;
    +        if (Utils.isZkAuthenticationConfiguredStormServer(conf)) {
    +            acls = SupervisorUtils.supervisorZkAcls();
    +        }
    +
    +        try {
    +            this.stormClusterState = ClusterUtils.mkStormClusterState(conf, acls, new ClusterStateContext(DaemonType.SUPERVISOR));
    +        } catch (Exception e) {
    +            LOG.error("supervisor can't create stormClusterState");
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        try {
    +            this.localState = ConfigUtils.supervisorState(conf);
    +            this.localizer = Utils.createLocalizer(conf, ConfigUtils.supervisorLocalDir(conf));
    +        } catch (IOException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +        this.supervisorId = iSupervisor.getSupervisorId();
    +        this.assignmentId = iSupervisor.getAssignmentId();
    +
    +        try {
    +            this.hostName = Utils.hostname(conf);
    +        } catch (UnknownHostException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        this.currAssignment = new ConcurrentHashMap<>();
    +
    +        this.heartbeatTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.eventTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.blobUpdateTimer = new StormTimer("blob-update-timer", new DefaultUncaughtExceptionHandler());
    +
    +        this.assignmentVersions = new ConcurrentHashMap<>();
    +        this.syncRetry = new AtomicInteger(0);
    +        this.stormIdToProfileActions = new ConcurrentHashMap<>();
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            try {
    +                this.resourceIsolationManager = (CgroupManager) Utils.newInstance((String) conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN));
    +                this.resourceIsolationManager.prepare(conf);
    +                LOG.info("Using resource isolation plugin {} {}", conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN), resourceIsolationManager);
    +            } catch (IOException e) {
    +                throw Utils.wrapInRuntime(e);
    +            }
    +        } else {
    +            this.resourceIsolationManager = null;
    +        }
    +    }
    +
    +    public ConcurrentHashMap<String, List<ProfileRequest>> getStormIdToProfileActions() {
    +        return stormIdToProfileActions;
    +    }
    +
    +    public void setStormIdToProfileActions(Map<String, List<ProfileRequest>> stormIdToProfileActions) {
    +        this.stormIdToProfileActions.clear();
    +        this.stormIdToProfileActions.putAll(stormIdToProfileActions);
    +    }
    +
    +    public Map getConf() {
    +        return conf;
    +    }
    +
    +    public void setConf(Map conf) {
    --- End diff --
    
    This is not used and I am not sure of a time we would want to do this.  Can we remove setConf and make conf final?


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55937502
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/StandaloneSupervisor.java ---
    @@ -0,0 +1,84 @@
    +/**
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + * http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.storm.daemon.supervisor;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +
    +import java.io.IOException;
    +import java.util.Collection;
    +import java.util.Map;
    +
    +public class StandaloneSupervisor implements ISupervisor {
    +    private String supervisorId;
    +    private Map conf;
    +
    +    @Override
    +    public void prepare(Map stormConf, String schedulerLocalDir) {
    +        try {
    +            LocalState localState = new LocalState(schedulerLocalDir);
    +            String supervisorId = localState.getSupervisorId();
    +            if (supervisorId == null) {
    +                supervisorId = generateSupervisorId();
    +                localState.setSupervisorId(supervisorId);
    +            }
    +            this.conf = stormConf;
    +            this.supervisorId = supervisorId;
    +        } catch (IOException e) {
    +            throw new RuntimeException(e);
    +        }
    +    }
    +
    +    @Override
    +    public String getSupervisorId() {
    +        return supervisorId;
    +    }
    +
    +    @Override
    +    public String getAssignmentId() {
    +        return supervisorId;
    +    }
    +
    +    @Override
    +    // @return is vector which need be converted to be int
    --- End diff --
    
    this comment can be removed


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r57181897
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncProcessEvent.java ---
    @@ -0,0 +1,428 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.daemon.supervisor.workermanager.IWorkerManager;
    +import org.apache.storm.generated.ExecutorInfo;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.WorkerResources;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +import org.yaml.snakeyaml.Yaml;
    +
    +import java.io.File;
    +import java.io.FileWriter;
    +import java.io.IOException;
    +import java.util.*;
    +
    +/**
    + * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file - rmr
    + * heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new worker
    + * ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait for workers
    + * launch
    + */
    +public class SyncProcessEvent implements Runnable {
    +
    +    private static Logger LOG = LoggerFactory.getLogger(SyncProcessEvent.class);
    +
    +    private  LocalState localState;
    +    private  SupervisorData supervisorData;
    +    public static final ExecutorInfo SYSTEM_EXECUTOR_INFO = new ExecutorInfo(-1, -1);
    +
    +    private class ProcessExitCallback implements Utils.ExitCodeCallable {
    +        private final String logPrefix;
    +        private final String workerId;
    +
    +        public ProcessExitCallback(String logPrefix, String workerId) {
    +            this.logPrefix = logPrefix;
    +            this.workerId = workerId;
    +        }
    +
    +        @Override
    +        public Object call() throws Exception {
    +            return null;
    +        }
    +
    +        @Override
    +        public Object call(int exitCode) {
    +            LOG.info("{} exited with code: {}", logPrefix, exitCode);
    +            supervisorData.getDeadWorkers().add(workerId);
    +            return null;
    +        }
    +    }
    +
    +    public SyncProcessEvent(){
    +
    +    }
    +    public SyncProcessEvent(SupervisorData supervisorData) {
    +        init(supervisorData);
    +    }
    +
    +    //TODO: initData is intended to local supervisor, so we will remove them after porting worker.clj to java
    +    public void init(SupervisorData supervisorData){
    +        this.supervisorData = supervisorData;
    +        this.localState = supervisorData.getLocalState();
    +    }
    +
    +    @Override
    +    public void run() {
    +        LOG.debug("Syncing processes");
    +        try {
    +            Map conf = supervisorData.getConf();
    +            Map<Integer, LocalAssignment> assignedExecutors = localState.getLocalAssignmentsMap();
    +
    +            if (assignedExecutors == null) {
    +                assignedExecutors = new HashMap<>();
    +            }
    +            int now = Time.currentTimeSecs();
    +
    +            Map<String, StateHeartbeat> localWorkerStats = getLocalWorkerStats(supervisorData, assignedExecutors, now);
    +
    +            Set<String> keeperWorkerIds = new HashSet<>();
    +            Set<Integer> keepPorts = new HashSet<>();
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() == State.VALID) {
    +                    keeperWorkerIds.add(entry.getKey());
    +                    keepPorts.add(stateHeartbeat.getHeartbeat().get_port());
    +                }
    +            }
    +            Map<Integer, LocalAssignment> reassignExecutors = getReassignExecutors(assignedExecutors, keepPorts);
    +            Map<Integer, String> newWorkerIds = new HashMap<>();
    +            for (Integer port : reassignExecutors.keySet()) {
    +                newWorkerIds.put(port, Utils.uuid());
    +            }
    +            LOG.debug("Syncing processes");
    +            LOG.debug("Assigned executors: {}", assignedExecutors);
    +            LOG.debug("Allocated: {}", localWorkerStats);
    +
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() != State.VALID) {
    +                    LOG.info("Shutting down and clearing state for id {}, Current supervisor time: {}, State: {}, Heartbeat: {}", entry.getKey(), now,
    +                            stateHeartbeat.getState(), stateHeartbeat.getHeartbeat());
    +                    shutWorker(supervisorData, supervisorData.getWorkerManager(), entry.getKey());
    +                }
    +            }
    +            // start new workers
    +            Map<String, Integer> newWorkerPortToIds = startNewWorkers(newWorkerIds, reassignExecutors);
    +
    +            Map<String, Integer> allWorkerPortToIds = new HashMap<>();
    +            Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +            for (String keeper : keeperWorkerIds) {
    +                allWorkerPortToIds.put(keeper, approvedWorkers.get(keeper));
    +            }
    +            allWorkerPortToIds.putAll(newWorkerPortToIds);
    +            localState.setApprovedWorkers(allWorkerPortToIds);
    +            waitForWorkersLaunch(conf, newWorkerPortToIds.keySet());
    +
    +        } catch (Exception e) {
    +            LOG.error("Failed Sync Process", e);
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +    }
    +
    +    protected void waitForWorkersLaunch(Map conf, Set<String> workerIds) throws Exception {
    +        int startTime = Time.currentTimeSecs();
    +        int timeOut = (int) conf.get(Config.NIMBUS_SUPERVISOR_TIMEOUT_SECS);
    +        for (String workerId : workerIds) {
    +            LocalState localState = ConfigUtils.workerState(conf, workerId);
    +            while (true) {
    +                LSWorkerHeartbeat hb = localState.getWorkerHeartBeat();
    +                if (hb != null || (Time.currentTimeSecs() - startTime) > timeOut)
    +                    break;
    +                LOG.info("{} still hasn't started", workerId);
    +                Time.sleep(500);
    +            }
    +            if (localState.getWorkerHeartBeat() == null) {
    +                LOG.info("Worker {} failed to start", workerId);
    +            }
    +        }
    +    }
    +
    +    protected Map<Integer, LocalAssignment> getReassignExecutors(Map<Integer, LocalAssignment> assignExecutors, Set<Integer> keepPorts) {
    +        Map<Integer, LocalAssignment> reassignExecutors = new HashMap<>();
    +        reassignExecutors.putAll(assignExecutors);
    +        for (Integer port : keepPorts) {
    +            reassignExecutors.remove(port);
    +        }
    +        return reassignExecutors;
    +    }
    +    
    +    /**
    +     * Returns map from worker id to worker heartbeat. if the heartbeat is nil, then the worker is dead
    +     * 
    +     * @param assignedExecutors
    +     * @return
    +     * @throws Exception
    +     */
    +    public Map<String, StateHeartbeat> getLocalWorkerStats(SupervisorData supervisorData, Map<Integer, LocalAssignment> assignedExecutors, int now) throws Exception {
    +        Map<String, StateHeartbeat> workerIdHbstate = new HashMap<>();
    +        Map conf = supervisorData.getConf();
    +        LocalState localState = supervisorData.getLocalState();
    +        Map<String, LSWorkerHeartbeat> idToHeartbeat = SupervisorUtils.readWorkerHeartbeats(conf);
    +        Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +        Set<String> approvedIds = new HashSet<>();
    +        if (approvedWorkers != null) {
    +            approvedIds.addAll(approvedWorkers.keySet());
    +        }
    +        for (Map.Entry<String, LSWorkerHeartbeat> entry : idToHeartbeat.entrySet()) {
    +            String workerId = entry.getKey();
    +            LSWorkerHeartbeat whb = entry.getValue();
    +            State state;
    +            if (whb == null) {
    +                state = State.NOT_STARTED;
    +            } else if (!approvedIds.contains(workerId) || !matchesAssignment(whb, assignedExecutors)) {
    +                state = State.DISALLOWED;
    +            } else if (supervisorData.getDeadWorkers().contains(workerId)) {
    +                LOG.info("Worker Process {} has died", workerId);
    +                state = State.TIMED_OUT;
    +            } else if (SupervisorUtils.isWorkerHbTimedOut(now, whb, conf)) {
    +                state = State.TIMED_OUT;
    +            } else {
    +                state = State.VALID;
    +            }
    +            LOG.debug("Worker:{} state:{} WorkerHeartbeat:{} at supervisor time-secs {}", workerId, state, whb, now);
    +            workerIdHbstate.put(workerId, new StateHeartbeat(state, whb));
    +        }
    +        return workerIdHbstate;
    +    }
    +
    +    protected boolean matchesAssignment(LSWorkerHeartbeat whb, Map<Integer, LocalAssignment> assignedExecutors) {
    +        LocalAssignment localAssignment = assignedExecutors.get(whb.get_port());
    +        if (localAssignment == null || !localAssignment.get_topology_id().equals(whb.get_topology_id())) {
    +            return false;
    +        }
    +        List<ExecutorInfo> executorInfos = new ArrayList<>();
    +        executorInfos.addAll(whb.get_executors());
    +        // remove SYSTEM_EXECUTOR_ID
    +        executorInfos.remove(SYSTEM_EXECUTOR_INFO);
    +        List<ExecutorInfo> localExecuorInfos = localAssignment.get_executors();
    +
    +        if (localExecuorInfos.size() != executorInfos.size())
    +            return false;
    +
    +        for (ExecutorInfo executorInfo : localExecuorInfos){
    +            if (!localExecuorInfos.contains(executorInfo))
    +                return false;
    +        }
    +        return true;
    +    }
    +
    +    /**
    +     * launch a worker in local mode.
    +     */
    +    protected void launchLocalWorker(SupervisorData supervisorData, String stormId, Long port, String workerId, WorkerResources resources) throws IOException {
    +        // port this function after porting worker to java
    +    }
    +
    +    protected void launchDistributedWorker(IWorkerManager workerManager, Map conf, String supervisorId, String assignmentId, String stormId, Long port, String workerId,
    +                                           WorkerResources resources, ConcurrentHashSet deadWorkers) throws IOException {
    +        Map stormConf = ConfigUtils.readSupervisorStormConf(conf, stormId);
    +        String user = (String) stormConf.get(Config.TOPOLOGY_SUBMITTER_USER);
    +        writeLogMetadata(stormConf, user, workerId, stormId, port, conf);
    +        ConfigUtils.setWorkerUserWSE(conf, workerId, user);
    +        createArtifactsLink(conf, stormId, port, workerId);
    +
    +        String logPrefix = "Worker Process " + workerId;
    +        if (deadWorkers != null)
    +            deadWorkers.remove(workerId);
    +        createBlobstoreLinks(conf, stormId, workerId);
    +        ProcessExitCallback processExitCallback = new ProcessExitCallback(logPrefix, workerId);
    +        workerManager.launchWorker(supervisorId, assignmentId, stormId, port, workerId, resources, processExitCallback);
    +    }
    +
    +    protected Map<String, Integer> startNewWorkers(Map<Integer, String> newWorkerIds, Map<Integer, LocalAssignment> reassignExecutors) throws IOException {
    +
    +        Map<String, Integer> newValidWorkerIds = new HashMap<>();
    +        Map conf = supervisorData.getConf();
    +        String supervisorId = supervisorData.getSupervisorId();
    +        String clusterMode = ConfigUtils.clusterMode(conf);
    +
    +        for (Map.Entry<Integer, LocalAssignment> entry : reassignExecutors.entrySet()) {
    +            Integer port = entry.getKey();
    +            LocalAssignment assignment = entry.getValue();
    +            String workerId = newWorkerIds.get(port);
    +            String stormId = assignment.get_topology_id();
    +            WorkerResources resources = assignment.get_resources();
    +
    +            // This condition checks for required files exist before launching the worker
    +            if (SupervisorUtils.doRequiredTopoFilesExist(conf, stormId)) {
    +                String pidsPath = ConfigUtils.workerPidsRoot(conf, workerId);
    +                String hbPath = ConfigUtils.workerHeartbeatsRoot(conf, workerId);
    +
    +                LOG.info("Launching worker with assignment {} for this supervisor {} on port {} with id {}", assignment, supervisorData.getSupervisorId(), port,
    +                        workerId);
    +
    +                FileUtils.forceMkdir(new File(pidsPath));
    +                FileUtils.forceMkdir(new File(ConfigUtils.workerTmpRoot(conf, workerId)));
    +                FileUtils.forceMkdir(new File(hbPath));
    +
    +                if (clusterMode.endsWith("distributed")) {
    +                    launchDistributedWorker(supervisorData.getWorkerManager(), conf, supervisorId, supervisorData.getAssignmentId(), stormId, port.longValue(), workerId, resources, supervisorData.getDeadWorkers());
    +                } else if (clusterMode.endsWith("local")) {
    +                    launchLocalWorker(supervisorData, stormId, port.longValue(), workerId, resources);
    +                }
    +                newValidWorkerIds.put(workerId, port);
    +
    +            } else {
    +                LOG.info("Missing topology storm code, so can't launch worker with assignment {} for this supervisor {} on port {} with id {}", assignment,
    +                        supervisorData.getSupervisorId(), port, workerId);
    +            }
    +
    +        }
    +        return newValidWorkerIds;
    +    }
    +
    +    public void writeLogMetadata(Map stormconf, String user, String workerId, String stormId, Long port, Map conf) throws IOException {
    +        Map data = new HashMap();
    +        data.put(Config.TOPOLOGY_SUBMITTER_USER, user);
    +        data.put("worker-id", workerId);
    +
    +        Set<String> logsGroups = new HashSet<>();
    +        //for supervisor-test
    +        if (stormconf.get(Config.LOGS_GROUPS) != null) {
    +            List<String> groups = (List<String>) stormconf.get(Config.LOGS_GROUPS);
    +            for (String group : groups){
    +                logsGroups.add(group);
    +            }
    +        }
    +        if (stormconf.get(Config.TOPOLOGY_GROUPS) != null) {
    +            List<String> topGroups = (List<String>) stormconf.get(Config.TOPOLOGY_GROUPS);
    +            logsGroups.addAll(topGroups);
    +        }
    +        data.put(Config.LOGS_GROUPS, logsGroups.toArray());
    +
    +        Set<String> logsUsers = new HashSet<>();
    +        if (stormconf.get(Config.LOGS_USERS) != null) {
    +            List<String> logUsers = (List<String>) stormconf.get(Config.LOGS_USERS);
    +            for (String logUser : logUsers){
    +                logsUsers.add(logUser);
    +            }
    +        }
    +        if (stormconf.get(Config.TOPOLOGY_USERS) != null) {
    +            List<String> topUsers = (List<String>) stormconf.get(Config.TOPOLOGY_USERS);
    +            for (String logUser : topUsers){
    +                logsUsers.add(logUser);
    +            }
    +        }
    +        data.put(Config.LOGS_USERS, logsUsers.toArray());
    +        writeLogMetadataToYamlFile(stormId, port, data, conf);
    +    }
    +
    +    /**
    +     * run worker as user needs the directory to have special permissions or it is insecure
    +     * 
    +     * @param stormId
    +     * @param port
    +     * @param data
    +     * @param conf
    +     * @throws IOException
    +     */
    +    public void writeLogMetadataToYamlFile(String stormId, Long port, Map data, Map conf) throws IOException {
    +        File file = ConfigUtils.getLogMetaDataFile(conf, stormId, port.intValue());
    +
    +        if (!Utils.checkFileExists(file.getParent())) {
    +            if (Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false)) {
    +                FileUtils.forceMkdir(file.getParentFile());
    +                SupervisorUtils.setupStormCodeDir(conf, ConfigUtils.readSupervisorStormConf(conf, stormId), file.getParentFile().getCanonicalPath());
    +            } else {
    +                file.getParentFile().mkdirs();
    +            }
    +        }
    +        FileWriter writer = new FileWriter(file);
    +        Yaml yaml = new Yaml();
    +        try {
    +            yaml.dump(data, writer);
    +        }finally {
    +            writer.close();
    +        }
    +    }
    +
    +    /**
    +     * Create a symlink from workder directory to its port artifacts directory
    +     * 
    +     * @param conf
    +     * @param stormId
    +     * @param port
    +     * @param workerId
    +     */
    +    protected void createArtifactsLink(Map conf, String stormId, Long port, String workerId) throws IOException {
    +        String workerDir = ConfigUtils.workerRoot(conf, workerId);
    +        String topoDir = ConfigUtils.workerArtifactsRoot(conf, stormId);
    +        if (Utils.checkFileExists(workerDir)) {
    +            Utils.createSymlink(workerDir, topoDir, "artifacts", String.valueOf(port));
    +        }
    +    }
    +
    +    /**
    +     * Create symlinks in worker launch directory for all blobs
    +     * 
    +     * @param conf
    +     * @param stormId
    +     * @param workerId
    +     * @throws IOException
    +     */
    +    protected void createBlobstoreLinks(Map conf, String stormId, String workerId) throws IOException {
    +        String stormRoot = ConfigUtils.supervisorStormDistRoot(conf, stormId);
    +        Map stormConf = ConfigUtils.readSupervisorStormConf(conf, stormId);
    +        String workerRoot = ConfigUtils.workerRoot(conf, workerId);
    +        Map<String, Map<String, Object>> blobstoreMap = (Map<String, Map<String, Object>>) stormConf.get(Config.TOPOLOGY_BLOBSTORE_MAP);
    +        List<String> blobFileNames = new ArrayList<>();
    +        if (blobstoreMap != null) {
    +            for (Map.Entry<String, Map<String, Object>> entry : blobstoreMap.entrySet()) {
    +                String key = entry.getKey();
    +                Map<String, Object> blobInfo = entry.getValue();
    +                String ret = null;
    +                if (blobInfo != null && blobInfo.containsKey("localname")) {
    +                    ret = (String) blobInfo.get("localname");
    +                } else {
    +                    ret = key;
    +                }
    +                blobFileNames.add(ret);
    +            }
    +        }
    +        List<String> resourceFileNames = new ArrayList<>();
    +        resourceFileNames.add(ConfigUtils.RESOURCES_SUBDIR);
    +        resourceFileNames.addAll(blobFileNames);
    +        LOG.info("Creating symlinks for worker-id: {} storm-id: {} for files({}): {}", workerId, stormId, resourceFileNames.size(), resourceFileNames);
    +        Utils.createSymlink(workerRoot, stormRoot, ConfigUtils.RESOURCES_SUBDIR);
    +        for (String fileName : blobFileNames) {
    +            Utils.createSymlink(workerRoot, stormRoot, fileName, fileName);
    +        }
    +    }
    +
    +    public void shutWorker(SupervisorData supervisorData, IWorkerManager workerManager, String workerId) throws IOException, InterruptedException{
    --- End diff --
    
    can we name this function to something other than shutWorker since there is already a shutdownWorker function and the similarities the names may cause confusion


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55942818
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncProcessEvent.java ---
    @@ -0,0 +1,672 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.ExecutorInfo;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.WorkerResources;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +import org.yaml.snakeyaml.Yaml;
    +
    +import java.io.File;
    +import java.io.FileWriter;
    +import java.io.IOException;
    +import java.util.*;
    +
    +/**
    + * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file - rmr
    + * heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new worker
    + * ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait for workers
    + * launch
    + */
    +public class SyncProcessEvent implements Runnable {
    +
    +    private static Logger LOG = LoggerFactory.getLogger(SyncProcessEvent.class);
    +
    +    private  LocalState localState;
    +    private  SupervisorData supervisorData;
    +    public static final ExecutorInfo SYSTEM_EXECUTOR_INFO = new ExecutorInfo(-1, -1);
    +
    +    private class ProcessExitCallback implements Utils.ExitCodeCallable {
    +        private final String logPrefix;
    +        private final String workerId;
    +
    +        public ProcessExitCallback(String logPrefix, String workerId) {
    +            this.logPrefix = logPrefix;
    +            this.workerId = workerId;
    +        }
    +
    +        @Override
    +        public Object call() throws Exception {
    +            return null;
    +        }
    +
    +        @Override
    +        public Object call(int exitCode) {
    +            LOG.info("{} exited with code: {}", logPrefix, exitCode);
    +            supervisorData.getDeadWorkers().add(workerId);
    +            return null;
    +        }
    +    }
    +
    +    public SyncProcessEvent(){
    +
    +    }
    +    public SyncProcessEvent(SupervisorData supervisorData) {
    +        init(supervisorData);
    +    }
    +
    +    //TODO: initData is intended to local supervisor, so we will remove them after porting worker.clj to java
    +    public void init(SupervisorData supervisorData){
    +        this.supervisorData = supervisorData;
    +        this.localState = supervisorData.getLocalState();
    +    }
    +
    +
    +    /**
    +     * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file -
    +     * rmr heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new
    +     * worker ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait
    +     * for workers launch
    +     */
    +    @Override
    +    public void run() {
    +        LOG.debug("Syncing processes");
    +        try {
    +            Map conf = supervisorData.getConf();
    +            Map<Integer, LocalAssignment> assignedExecutors = localState.getLocalAssignmentsMap();
    +
    +            if (assignedExecutors == null) {
    +                assignedExecutors = new HashMap<>();
    +            }
    +            int now = Time.currentTimeSecs();
    +
    +            Map<String, StateHeartbeat> localWorkerStats = getLocalWorkerStats(supervisorData, assignedExecutors, now);
    +
    +            Set<String> keeperWorkerIds = new HashSet<>();
    +            Set<Integer> keepPorts = new HashSet<>();
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() == State.VALID) {
    +                    keeperWorkerIds.add(entry.getKey());
    +                    keepPorts.add(stateHeartbeat.getHeartbeat().get_port());
    +                }
    +            }
    +            Map<Integer, LocalAssignment> reassignExecutors = getReassignExecutors(assignedExecutors, keepPorts);
    +            Map<Integer, String> newWorkerIds = new HashMap<>();
    +            for (Integer port : reassignExecutors.keySet()) {
    +                newWorkerIds.put(port, Utils.uuid());
    +            }
    +            LOG.debug("Syncing processes");
    +            LOG.debug("Assigned executors: {}", assignedExecutors);
    +            LOG.debug("Allocated: {}", localWorkerStats);
    +
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() != State.VALID) {
    +                    LOG.info("Shutting down and clearing state for id {}, Current supervisor time: {}, State: {}, Heartbeat: {}", entry.getKey(), now,
    +                            stateHeartbeat.getState(), stateHeartbeat.getHeartbeat());
    +                    shutWorker(supervisorData, entry.getKey());
    +                }
    +            }
    +            // start new workers
    +            Map<String, Integer> newWorkerPortToIds = startNewWorkers(newWorkerIds, reassignExecutors);
    +
    +            Map<String, Integer> allWorkerPortToIds = new HashMap<>();
    +            Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +            for (String keeper : keeperWorkerIds) {
    +                allWorkerPortToIds.put(keeper, approvedWorkers.get(keeper));
    +            }
    +            allWorkerPortToIds.putAll(newWorkerPortToIds);
    +            localState.setApprovedWorkers(allWorkerPortToIds);
    +            waitForWorkersLaunch(conf, newWorkerPortToIds.keySet());
    +
    +        } catch (Exception e) {
    +            LOG.error("Failed Sync Process", e);
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +    }
    +
    +    protected void waitForWorkersLaunch(Map conf, Set<String> workerIds) throws Exception {
    +        int startTime = Time.currentTimeSecs();
    +        int timeOut = (int) conf.get(Config.NIMBUS_SUPERVISOR_TIMEOUT_SECS);
    +        for (String workerId : workerIds) {
    +            LocalState localState = ConfigUtils.workerState(conf, workerId);
    +            while (true) {
    +                LSWorkerHeartbeat hb = localState.getWorkerHeartBeat();
    +                if (hb != null || (Time.currentTimeSecs() - startTime) > timeOut)
    +                    break;
    +                LOG.info("{} still hasn't started", workerId);
    +                Time.sleep(500);
    +            }
    +            if (localState.getWorkerHeartBeat() == null) {
    +                LOG.info("Worker {} failed to start", workerId);
    +            }
    +        }
    +    }
    +
    +    protected Map<Integer, LocalAssignment> getReassignExecutors(Map<Integer, LocalAssignment> assignExecutors, Set<Integer> keepPorts) {
    +        Map<Integer, LocalAssignment> reassignExecutors = new HashMap<>();
    +        reassignExecutors.putAll(assignExecutors);
    +        for (Integer port : keepPorts) {
    +            reassignExecutors.remove(port);
    +        }
    +        return reassignExecutors;
    +    }
    +    
    +    /**
    +     * Returns map from worker id to worker heartbeat. if the heartbeat is nil, then the worker is dead
    +     * 
    +     * @param assignedExecutors
    +     * @return
    +     * @throws Exception
    +     */
    +    public Map<String, StateHeartbeat> getLocalWorkerStats(SupervisorData supervisorData, Map<Integer, LocalAssignment> assignedExecutors, int now) throws Exception {
    +        Map<String, StateHeartbeat> workerIdHbstate = new HashMap<>();
    +        Map conf = supervisorData.getConf();
    +        LocalState localState = supervisorData.getLocalState();
    +        Map<String, LSWorkerHeartbeat> idToHeartbeat = SupervisorUtils.readWorkerHeartbeats(conf);
    +        Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +        Set<String> approvedIds = new HashSet<>();
    +        if (approvedWorkers != null) {
    +            approvedIds.addAll(approvedWorkers.keySet());
    +        }
    +        for (Map.Entry<String, LSWorkerHeartbeat> entry : idToHeartbeat.entrySet()) {
    +            String workerId = entry.getKey();
    +            LSWorkerHeartbeat whb = entry.getValue();
    +            State state;
    +            if (whb == null) {
    +                state = State.NOT_STARTED;
    +            } else if (!approvedIds.contains(workerId) || !matchesAssignment(whb, assignedExecutors)) {
    +                state = State.DISALLOWED;
    +            } else if (supervisorData.getDeadWorkers().contains(workerId)) {
    +                LOG.info("Worker Process {} has died", workerId);
    +                state = State.TIMED_OUT;
    +            } else if (SupervisorUtils.isWorkerHbTimedOut(now, whb, conf)) {
    +                state = State.TIMED_OUT;
    +            } else {
    +                state = State.VALID;
    +            }
    +            LOG.debug("Worker:{} state:{} WorkerHeartbeat:{} at supervisor time-secs {}", workerId, state, whb, now);
    +            workerIdHbstate.put(workerId, new StateHeartbeat(state, whb));
    +        }
    +        return workerIdHbstate;
    +    }
    +
    +    protected boolean matchesAssignment(LSWorkerHeartbeat whb, Map<Integer, LocalAssignment> assignedExecutors) {
    +        LocalAssignment localAssignment = assignedExecutors.get(whb.get_port());
    +        if (localAssignment == null || !localAssignment.get_topology_id().equals(whb.get_topology_id())) {
    +            return false;
    +        }
    +        List<ExecutorInfo> executorInfos = new ArrayList<>();
    +        executorInfos.addAll(whb.get_executors());
    +        // remove SYSTEM_EXECUTOR_ID
    +        executorInfos.remove(SYSTEM_EXECUTOR_INFO);
    +        List<ExecutorInfo> localExecuorInfos = localAssignment.get_executors();
    +
    +        if (localExecuorInfos.size() != executorInfos.size())
    +            return false;
    +
    +        for (ExecutorInfo executorInfo : localExecuorInfos){
    +            if (!localExecuorInfos.contains(executorInfo))
    +                return false;
    +        }
    +        return true;
    +    }
    +
    +    /**
    +     * launch a worker in local mode.
    +     */
    +    protected void launchWorker(SupervisorData supervisorData, String stormId, Long port, String workerId, WorkerResources resources) throws IOException {
    +        // port this function after porting worker to java
    +    }
    +
    +    protected String getWorkerClassPath(String stormJar, Map stormConf) {
    +        List<String> topoClasspath = new ArrayList<>();
    +        Object object = stormConf.get(Config.TOPOLOGY_CLASSPATH);
    +
    +        if (object instanceof List) {
    +            topoClasspath.addAll((List<String>) object);
    +        } else if (object instanceof String){
    +            topoClasspath.add((String)object);
    +        }else {
    +            //ignore
    +        }
    +        String classPath = Utils.workerClasspath();
    +        String classAddPath = Utils.addToClasspath(classPath, Arrays.asList(stormJar));
    +        return Utils.addToClasspath(classAddPath, topoClasspath);
    +    }
    +
    +    /**
    +     * "Generates runtime childopts by replacing keys with topology-id, worker-id, port, mem-onheap"
    +     * 
    +     * @param value
    +     * @param workerId
    +     * @param stormId
    +     * @param port
    +     * @param memOnheap
    +     */
    +    public List<String> substituteChildopts(Object value, String workerId, String stormId, Long port, int memOnheap) {
    +        List<String> rets = new ArrayList<>();
    +        if (value instanceof String) {
    +            String string = (String) value;
    +            string = string.replace("%ID%", String.valueOf(port));
    +            string = string.replace("%WORKER-ID%", workerId);
    +            string = string.replace("%TOPOLOGY-ID%", stormId);
    +            string = string.replace("%WORKER-PORT%", String.valueOf(port));
    +            string = string.replace("%HEAP-MEM%", String.valueOf(memOnheap));
    +            String[] strings = string.split("\\s+");
    +            rets.addAll(Arrays.asList(strings));
    +        } else if (value instanceof List) {
    --- End diff --
    
    this can be collection instead. 


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55937985
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorManger.java ---
    @@ -0,0 +1,97 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.event.EventManager;
    +import org.apache.storm.utils.Utils;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.Collection;
    +import java.util.Map;
    +
    +public class SupervisorManger implements SupervisorDaemon, DaemonCommon, Runnable {
    --- End diff --
    
    nit. class name should be SupervisorManager. 


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55715681
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/DaemonCommon.java ---
    @@ -0,0 +1,22 @@
    +/**
    + * 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.supervisor;
    +
    +public interface DaemonCommon {
    --- End diff --
    
    is DaemonCommon going to be a interface that needs to be implemented by all Storm daemons? If so we need to move this file one directory up


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55584354
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorData.java ---
    @@ -0,0 +1,339 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.cluster.ClusterStateContext;
    +import org.apache.storm.cluster.ClusterUtils;
    +import org.apache.storm.cluster.DaemonType;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.ProfileRequest;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +import java.net.UnknownHostException;
    +import java.util.ArrayList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.concurrent.ConcurrentHashMap;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SupervisorData {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorData.class);
    +
    +    private Map conf;
    +    private IContext sharedContext;
    +    private volatile boolean active;
    +    private ISupervisor iSupervisor;
    +    private Utils.UptimeComputer upTime;
    +    private String stormVersion;
    +
    +    private ConcurrentHashMap<String, String> workerThreadPidsAtom; // for local mode
    +
    +    private IStormClusterState stormClusterState;
    +
    +    private LocalState localState;
    +
    +    private String supervisorId;
    +
    +    private String assignmentId;
    +
    +    private String hostName;
    +
    +    // used for reporting used ports when heartbeating
    +    private ConcurrentHashMap<Long, LocalAssignment> currAssignment;
    +
    +    private StormTimer heartbeatTimer;
    +
    +    private StormTimer eventTimer;
    +
    +    private StormTimer blobUpdateTimer;
    +
    +    private Localizer localizer;
    +
    +    private ConcurrentHashMap<String, Map<String, Object>> assignmentVersions;
    +
    +    private AtomicInteger syncRetry;
    +
    +    private final Object downloadLock = new Object();
    +
    +    private ConcurrentHashMap<String, List<ProfileRequest>> stormIdToProfileActions;
    +
    +    private CgroupManager resourceIsolationManager;
    +
    +    private ConcurrentHashSet<String> deadWorkers;
    +
    +    public SupervisorData(Map conf, IContext sharedContext, ISupervisor iSupervisor) {
    +        this.conf = conf;
    +        this.sharedContext = sharedContext;
    +        this.iSupervisor = iSupervisor;
    +        this.active = true;
    +        this.upTime = Utils.makeUptimeComputer();
    +        this.stormVersion = VersionInfo.getVersion();
    +        this.workerThreadPidsAtom = new ConcurrentHashMap<String, String>();
    +        this.deadWorkers = new ConcurrentHashSet();
    +
    +        List<ACL> acls = null;
    +        if (Utils.isZkAuthenticationConfiguredStormServer(conf)) {
    +            acls = SupervisorUtils.supervisorZkAcls();
    +        }
    +
    +        try {
    +            this.stormClusterState = ClusterUtils.mkStormClusterState(conf, acls, new ClusterStateContext(DaemonType.SUPERVISOR));
    +        } catch (Exception e) {
    +            LOG.error("supervisor can't create stormClusterState");
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        try {
    +            this.localState = ConfigUtils.supervisorState(conf);
    +            this.localizer = Utils.createLocalizer(conf, ConfigUtils.supervisorLocalDir(conf));
    +        } catch (IOException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +        this.supervisorId = iSupervisor.getSupervisorId();
    +        this.assignmentId = iSupervisor.getAssignmentId();
    +
    +        try {
    +            this.hostName = Utils.hostname(conf);
    +        } catch (UnknownHostException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        this.currAssignment = new ConcurrentHashMap<>();
    +
    +        this.heartbeatTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.eventTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.blobUpdateTimer = new StormTimer("blob-update-timer", new DefaultUncaughtExceptionHandler());
    +
    +        this.assignmentVersions = new ConcurrentHashMap<>();
    +        this.syncRetry = new AtomicInteger(0);
    +        this.stormIdToProfileActions = new ConcurrentHashMap<>();
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            try {
    +                this.resourceIsolationManager = (CgroupManager) Utils.newInstance((String) conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN));
    +                this.resourceIsolationManager.prepare(conf);
    +                LOG.info("Using resource isolation plugin {} {}", conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN), resourceIsolationManager);
    +            } catch (IOException e) {
    +                throw Utils.wrapInRuntime(e);
    +            }
    +        } else {
    +            this.resourceIsolationManager = null;
    +        }
    +    }
    +
    +    public ConcurrentHashMap<String, List<ProfileRequest>> getStormIdToProfileActions() {
    +        return stormIdToProfileActions;
    +    }
    +
    +    public void setStormIdToProfileActions(Map<String, List<ProfileRequest>> stormIdToProfileActions) {
    +        this.stormIdToProfileActions.clear();
    +        this.stormIdToProfileActions.putAll(stormIdToProfileActions);
    +    }
    +
    +    public Map getConf() {
    +        return conf;
    +    }
    +
    +    public void setConf(Map conf) {
    +        this.conf = conf;
    +    }
    +
    +    public IContext getSharedContext() {
    +        return sharedContext;
    +    }
    +
    +    public void setSharedContext(IContext sharedContext) {
    --- End diff --
    
    Here too this is not used so it would probably be best to remove this method and mark sharedContext as final.  At least for the time being.


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55585426
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorData.java ---
    @@ -0,0 +1,339 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.cluster.ClusterStateContext;
    +import org.apache.storm.cluster.ClusterUtils;
    +import org.apache.storm.cluster.DaemonType;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.ProfileRequest;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +import java.net.UnknownHostException;
    +import java.util.ArrayList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.concurrent.ConcurrentHashMap;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SupervisorData {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorData.class);
    +
    +    private Map conf;
    +    private IContext sharedContext;
    +    private volatile boolean active;
    +    private ISupervisor iSupervisor;
    +    private Utils.UptimeComputer upTime;
    +    private String stormVersion;
    +
    +    private ConcurrentHashMap<String, String> workerThreadPidsAtom; // for local mode
    +
    +    private IStormClusterState stormClusterState;
    +
    +    private LocalState localState;
    +
    +    private String supervisorId;
    +
    +    private String assignmentId;
    +
    +    private String hostName;
    +
    +    // used for reporting used ports when heartbeating
    +    private ConcurrentHashMap<Long, LocalAssignment> currAssignment;
    +
    +    private StormTimer heartbeatTimer;
    +
    +    private StormTimer eventTimer;
    +
    +    private StormTimer blobUpdateTimer;
    +
    +    private Localizer localizer;
    +
    +    private ConcurrentHashMap<String, Map<String, Object>> assignmentVersions;
    +
    +    private AtomicInteger syncRetry;
    +
    +    private final Object downloadLock = new Object();
    +
    +    private ConcurrentHashMap<String, List<ProfileRequest>> stormIdToProfileActions;
    +
    +    private CgroupManager resourceIsolationManager;
    +
    +    private ConcurrentHashSet<String> deadWorkers;
    +
    +    public SupervisorData(Map conf, IContext sharedContext, ISupervisor iSupervisor) {
    +        this.conf = conf;
    +        this.sharedContext = sharedContext;
    +        this.iSupervisor = iSupervisor;
    +        this.active = true;
    +        this.upTime = Utils.makeUptimeComputer();
    +        this.stormVersion = VersionInfo.getVersion();
    +        this.workerThreadPidsAtom = new ConcurrentHashMap<String, String>();
    +        this.deadWorkers = new ConcurrentHashSet();
    +
    +        List<ACL> acls = null;
    +        if (Utils.isZkAuthenticationConfiguredStormServer(conf)) {
    +            acls = SupervisorUtils.supervisorZkAcls();
    +        }
    +
    +        try {
    +            this.stormClusterState = ClusterUtils.mkStormClusterState(conf, acls, new ClusterStateContext(DaemonType.SUPERVISOR));
    +        } catch (Exception e) {
    +            LOG.error("supervisor can't create stormClusterState");
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        try {
    +            this.localState = ConfigUtils.supervisorState(conf);
    +            this.localizer = Utils.createLocalizer(conf, ConfigUtils.supervisorLocalDir(conf));
    +        } catch (IOException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +        this.supervisorId = iSupervisor.getSupervisorId();
    +        this.assignmentId = iSupervisor.getAssignmentId();
    +
    +        try {
    +            this.hostName = Utils.hostname(conf);
    +        } catch (UnknownHostException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        this.currAssignment = new ConcurrentHashMap<>();
    +
    +        this.heartbeatTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.eventTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.blobUpdateTimer = new StormTimer("blob-update-timer", new DefaultUncaughtExceptionHandler());
    +
    +        this.assignmentVersions = new ConcurrentHashMap<>();
    +        this.syncRetry = new AtomicInteger(0);
    +        this.stormIdToProfileActions = new ConcurrentHashMap<>();
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            try {
    +                this.resourceIsolationManager = (CgroupManager) Utils.newInstance((String) conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN));
    +                this.resourceIsolationManager.prepare(conf);
    +                LOG.info("Using resource isolation plugin {} {}", conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN), resourceIsolationManager);
    +            } catch (IOException e) {
    +                throw Utils.wrapInRuntime(e);
    +            }
    +        } else {
    +            this.resourceIsolationManager = null;
    +        }
    +    }
    +
    +    public ConcurrentHashMap<String, List<ProfileRequest>> getStormIdToProfileActions() {
    +        return stormIdToProfileActions;
    +    }
    +
    +    public void setStormIdToProfileActions(Map<String, List<ProfileRequest>> stormIdToProfileActions) {
    +        this.stormIdToProfileActions.clear();
    +        this.stormIdToProfileActions.putAll(stormIdToProfileActions);
    +    }
    +
    +    public Map getConf() {
    +        return conf;
    +    }
    +
    +    public void setConf(Map conf) {
    +        this.conf = conf;
    +    }
    +
    +    public IContext getSharedContext() {
    +        return sharedContext;
    +    }
    +
    +    public void setSharedContext(IContext sharedContext) {
    +        this.sharedContext = sharedContext;
    +    }
    +
    +    public boolean isActive() {
    +        return active;
    +    }
    +
    +    public void setActive(boolean active) {
    +        this.active = active;
    +    }
    +
    +    public ISupervisor getiSupervisor() {
    +        return iSupervisor;
    +    }
    +
    +    public void setiSupervisor(ISupervisor iSupervisor) {
    +        this.iSupervisor = iSupervisor;
    +    }
    +
    +    public Utils.UptimeComputer getUpTime() {
    +        return upTime;
    +    }
    +
    +    public void setUpTime(Utils.UptimeComputer upTime) {
    +        this.upTime = upTime;
    +    }
    +
    +    public String getStormVersion() {
    +        return stormVersion;
    +    }
    +
    +    public void setStormVersion(String stormVersion) {
    +        this.stormVersion = stormVersion;
    +    }
    +
    +    public ConcurrentHashMap<String, String> getWorkerThreadPidsAtom() {
    +        return workerThreadPidsAtom;
    +    }
    +
    +    public void setWorkerThreadPidsAtom(ConcurrentHashMap<String, String> workerThreadPidsAtom) {
    +        this.workerThreadPidsAtom = workerThreadPidsAtom;
    +    }
    +
    +    public IStormClusterState getStormClusterState() {
    +        return stormClusterState;
    +    }
    +
    +    public void setStormClusterState(IStormClusterState stormClusterState) {
    +        this.stormClusterState = stormClusterState;
    +    }
    +
    +    public LocalState getLocalState() {
    +        return localState;
    +    }
    +
    +    public void setLocalState(LocalState localState) {
    +        this.localState = localState;
    +    }
    +
    +    public String getSupervisorId() {
    +        return supervisorId;
    +    }
    +
    +    public void setSupervisorId(String supervisorId) {
    +        this.supervisorId = supervisorId;
    +    }
    +
    +    public String getAssignmentId() {
    +        return assignmentId;
    +    }
    +
    +    public void setAssignmentId(String assignmentId) {
    +        this.assignmentId = assignmentId;
    +    }
    +
    +    public String getHostName() {
    +        return hostName;
    +    }
    +
    +    public void setHostName(String hostName) {
    +        this.hostName = hostName;
    +    }
    +
    +    public ConcurrentHashMap<Long, LocalAssignment> getCurrAssignment() {
    +        return currAssignment;
    +    }
    +
    +    public void setCurrAssignment(Map<Long, LocalAssignment> currAssignment) {
    +        this.currAssignment.clear();
    +        this.currAssignment.putAll(currAssignment);
    +    }
    +
    +    public StormTimer getHeartbeatTimer() {
    +        return heartbeatTimer;
    +    }
    +
    +    public void setHeartbeatTimer(StormTimer heartbeatTimer) {
    +        this.heartbeatTimer = heartbeatTimer;
    +    }
    +
    +    public StormTimer getEventTimer() {
    +        return eventTimer;
    +    }
    +
    +    public void setEventTimer(StormTimer eventTimer) {
    +        this.eventTimer = eventTimer;
    +    }
    +
    +    public StormTimer getBlobUpdateTimer() {
    +        return blobUpdateTimer;
    +    }
    +
    +    public void setBlobUpdateTimer(StormTimer blobUpdateTimer) {
    +        this.blobUpdateTimer = blobUpdateTimer;
    +    }
    +
    +    public Localizer getLocalizer() {
    +        return localizer;
    +    }
    +
    +    public void setLocalizer(Localizer localizer) {
    +        this.localizer = localizer;
    +    }
    +
    +    public AtomicInteger getSyncRetry() {
    +        return syncRetry;
    +    }
    +
    +    public void setSyncRetry(AtomicInteger syncRetry) {
    --- End diff --
    
    Not Used.


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55584718
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorData.java ---
    @@ -0,0 +1,339 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.cluster.ClusterStateContext;
    +import org.apache.storm.cluster.ClusterUtils;
    +import org.apache.storm.cluster.DaemonType;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.ProfileRequest;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +import java.net.UnknownHostException;
    +import java.util.ArrayList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.concurrent.ConcurrentHashMap;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SupervisorData {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorData.class);
    +
    +    private Map conf;
    +    private IContext sharedContext;
    +    private volatile boolean active;
    +    private ISupervisor iSupervisor;
    +    private Utils.UptimeComputer upTime;
    +    private String stormVersion;
    +
    +    private ConcurrentHashMap<String, String> workerThreadPidsAtom; // for local mode
    +
    +    private IStormClusterState stormClusterState;
    +
    +    private LocalState localState;
    +
    +    private String supervisorId;
    +
    +    private String assignmentId;
    +
    +    private String hostName;
    +
    +    // used for reporting used ports when heartbeating
    +    private ConcurrentHashMap<Long, LocalAssignment> currAssignment;
    +
    +    private StormTimer heartbeatTimer;
    +
    +    private StormTimer eventTimer;
    +
    +    private StormTimer blobUpdateTimer;
    +
    +    private Localizer localizer;
    +
    +    private ConcurrentHashMap<String, Map<String, Object>> assignmentVersions;
    +
    +    private AtomicInteger syncRetry;
    +
    +    private final Object downloadLock = new Object();
    +
    +    private ConcurrentHashMap<String, List<ProfileRequest>> stormIdToProfileActions;
    +
    +    private CgroupManager resourceIsolationManager;
    +
    +    private ConcurrentHashSet<String> deadWorkers;
    +
    +    public SupervisorData(Map conf, IContext sharedContext, ISupervisor iSupervisor) {
    +        this.conf = conf;
    +        this.sharedContext = sharedContext;
    +        this.iSupervisor = iSupervisor;
    +        this.active = true;
    +        this.upTime = Utils.makeUptimeComputer();
    +        this.stormVersion = VersionInfo.getVersion();
    +        this.workerThreadPidsAtom = new ConcurrentHashMap<String, String>();
    +        this.deadWorkers = new ConcurrentHashSet();
    +
    +        List<ACL> acls = null;
    +        if (Utils.isZkAuthenticationConfiguredStormServer(conf)) {
    +            acls = SupervisorUtils.supervisorZkAcls();
    +        }
    +
    +        try {
    +            this.stormClusterState = ClusterUtils.mkStormClusterState(conf, acls, new ClusterStateContext(DaemonType.SUPERVISOR));
    +        } catch (Exception e) {
    +            LOG.error("supervisor can't create stormClusterState");
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        try {
    +            this.localState = ConfigUtils.supervisorState(conf);
    +            this.localizer = Utils.createLocalizer(conf, ConfigUtils.supervisorLocalDir(conf));
    +        } catch (IOException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +        this.supervisorId = iSupervisor.getSupervisorId();
    +        this.assignmentId = iSupervisor.getAssignmentId();
    +
    +        try {
    +            this.hostName = Utils.hostname(conf);
    +        } catch (UnknownHostException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        this.currAssignment = new ConcurrentHashMap<>();
    +
    +        this.heartbeatTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.eventTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.blobUpdateTimer = new StormTimer("blob-update-timer", new DefaultUncaughtExceptionHandler());
    +
    +        this.assignmentVersions = new ConcurrentHashMap<>();
    +        this.syncRetry = new AtomicInteger(0);
    +        this.stormIdToProfileActions = new ConcurrentHashMap<>();
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            try {
    +                this.resourceIsolationManager = (CgroupManager) Utils.newInstance((String) conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN));
    +                this.resourceIsolationManager.prepare(conf);
    +                LOG.info("Using resource isolation plugin {} {}", conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN), resourceIsolationManager);
    +            } catch (IOException e) {
    +                throw Utils.wrapInRuntime(e);
    +            }
    +        } else {
    +            this.resourceIsolationManager = null;
    +        }
    +    }
    +
    +    public ConcurrentHashMap<String, List<ProfileRequest>> getStormIdToProfileActions() {
    +        return stormIdToProfileActions;
    +    }
    +
    +    public void setStormIdToProfileActions(Map<String, List<ProfileRequest>> stormIdToProfileActions) {
    +        this.stormIdToProfileActions.clear();
    +        this.stormIdToProfileActions.putAll(stormIdToProfileActions);
    +    }
    +
    +    public Map getConf() {
    +        return conf;
    +    }
    +
    +    public void setConf(Map conf) {
    +        this.conf = conf;
    +    }
    +
    +    public IContext getSharedContext() {
    +        return sharedContext;
    +    }
    +
    +    public void setSharedContext(IContext sharedContext) {
    +        this.sharedContext = sharedContext;
    +    }
    +
    +    public boolean isActive() {
    +        return active;
    +    }
    +
    +    public void setActive(boolean active) {
    +        this.active = active;
    +    }
    +
    +    public ISupervisor getiSupervisor() {
    +        return iSupervisor;
    +    }
    +
    +    public void setiSupervisor(ISupervisor iSupervisor) {
    +        this.iSupervisor = iSupervisor;
    +    }
    +
    +    public Utils.UptimeComputer getUpTime() {
    +        return upTime;
    +    }
    +
    +    public void setUpTime(Utils.UptimeComputer upTime) {
    +        this.upTime = upTime;
    +    }
    +
    +    public String getStormVersion() {
    +        return stormVersion;
    +    }
    +
    +    public void setStormVersion(String stormVersion) {
    +        this.stormVersion = stormVersion;
    +    }
    +
    +    public ConcurrentHashMap<String, String> getWorkerThreadPidsAtom() {
    +        return workerThreadPidsAtom;
    +    }
    +
    +    public void setWorkerThreadPidsAtom(ConcurrentHashMap<String, String> workerThreadPidsAtom) {
    +        this.workerThreadPidsAtom = workerThreadPidsAtom;
    +    }
    +
    +    public IStormClusterState getStormClusterState() {
    +        return stormClusterState;
    +    }
    +
    +    public void setStormClusterState(IStormClusterState stormClusterState) {
    --- End diff --
    
    Not used


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55639499
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/ShutdownWork.java ---
    @@ -0,0 +1,125 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.ProcessSimulator;
    +import org.apache.storm.daemon.Shutdownable;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.IOException;
    +import java.util.*;
    +
    +public  class ShutdownWork implements Shutdownable {
    +
    +    private static Logger LOG = LoggerFactory.getLogger(ShutdownWork.class);
    +
    +    public void shutWorker(SupervisorData supervisorData, String workerId) throws IOException, InterruptedException {
    +        LOG.info("Shutting down {}:{}", supervisorData.getSupervisorId(), workerId);
    +        Map conf = supervisorData.getConf();
    +        Collection<String> pids = Utils.readDirContents(ConfigUtils.workerPidsRoot(conf, workerId));
    +        Integer shutdownSleepSecs = Utils.getInt(conf.get(Config.SUPERVISOR_WORKER_SHUTDOWN_SLEEP_SECS));
    +        Boolean asUser = Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false);
    +        String user = ConfigUtils.getWorkerUser(conf, workerId);
    +        String threadPid = supervisorData.getWorkerThreadPidsAtom().get(workerId);
    +        if (StringUtils.isNotBlank(threadPid)) {
    +            ProcessSimulator.killProcess(threadPid);
    +        }
    +
    +        for (String pid : pids) {
    +            if (asUser) {
    +                List<String> commands = new ArrayList<>();
    +                commands.add("signal");
    +                commands.add(pid);
    +                commands.add("15");
    +                String logPrefix = "kill - 15 " + pid;
    --- End diff --
    
    nit. -15 (no space)


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#issuecomment-197155837
  
    @jerrypeng  Of course


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#issuecomment-197042280
  
    I have a bug fix for cgroups that involve a couple lines of modification in supervisor.clj.  
    
    https://github.com/apache/storm/pull/1216
    
    If that pull request gets merged first please remember to also implement that change 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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55939026
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncProcessEvent.java ---
    @@ -0,0 +1,672 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.ExecutorInfo;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.WorkerResources;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +import org.yaml.snakeyaml.Yaml;
    +
    +import java.io.File;
    +import java.io.FileWriter;
    +import java.io.IOException;
    +import java.util.*;
    +
    +/**
    + * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file - rmr
    + * heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new worker
    + * ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait for workers
    + * launch
    + */
    +public class SyncProcessEvent implements Runnable {
    +
    +    private static Logger LOG = LoggerFactory.getLogger(SyncProcessEvent.class);
    +
    +    private  LocalState localState;
    +    private  SupervisorData supervisorData;
    +    public static final ExecutorInfo SYSTEM_EXECUTOR_INFO = new ExecutorInfo(-1, -1);
    +
    +    private class ProcessExitCallback implements Utils.ExitCodeCallable {
    +        private final String logPrefix;
    +        private final String workerId;
    +
    +        public ProcessExitCallback(String logPrefix, String workerId) {
    +            this.logPrefix = logPrefix;
    +            this.workerId = workerId;
    +        }
    +
    +        @Override
    +        public Object call() throws Exception {
    +            return null;
    +        }
    +
    +        @Override
    +        public Object call(int exitCode) {
    +            LOG.info("{} exited with code: {}", logPrefix, exitCode);
    +            supervisorData.getDeadWorkers().add(workerId);
    +            return null;
    +        }
    +    }
    +
    +    public SyncProcessEvent(){
    +
    +    }
    +    public SyncProcessEvent(SupervisorData supervisorData) {
    +        init(supervisorData);
    +    }
    +
    +    //TODO: initData is intended to local supervisor, so we will remove them after porting worker.clj to java
    +    public void init(SupervisorData supervisorData){
    +        this.supervisorData = supervisorData;
    +        this.localState = supervisorData.getLocalState();
    +    }
    +
    +
    +    /**
    +     * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file -
    +     * rmr heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new
    +     * worker ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait
    +     * for workers launch
    +     */
    +    @Override
    +    public void run() {
    +        LOG.debug("Syncing processes");
    +        try {
    +            Map conf = supervisorData.getConf();
    +            Map<Integer, LocalAssignment> assignedExecutors = localState.getLocalAssignmentsMap();
    +
    +            if (assignedExecutors == null) {
    +                assignedExecutors = new HashMap<>();
    +            }
    +            int now = Time.currentTimeSecs();
    +
    +            Map<String, StateHeartbeat> localWorkerStats = getLocalWorkerStats(supervisorData, assignedExecutors, now);
    +
    +            Set<String> keeperWorkerIds = new HashSet<>();
    +            Set<Integer> keepPorts = new HashSet<>();
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() == State.VALID) {
    +                    keeperWorkerIds.add(entry.getKey());
    +                    keepPorts.add(stateHeartbeat.getHeartbeat().get_port());
    +                }
    +            }
    +            Map<Integer, LocalAssignment> reassignExecutors = getReassignExecutors(assignedExecutors, keepPorts);
    +            Map<Integer, String> newWorkerIds = new HashMap<>();
    +            for (Integer port : reassignExecutors.keySet()) {
    +                newWorkerIds.put(port, Utils.uuid());
    +            }
    +            LOG.debug("Syncing processes");
    +            LOG.debug("Assigned executors: {}", assignedExecutors);
    +            LOG.debug("Allocated: {}", localWorkerStats);
    +
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() != State.VALID) {
    +                    LOG.info("Shutting down and clearing state for id {}, Current supervisor time: {}, State: {}, Heartbeat: {}", entry.getKey(), now,
    +                            stateHeartbeat.getState(), stateHeartbeat.getHeartbeat());
    +                    shutWorker(supervisorData, entry.getKey());
    +                }
    +            }
    +            // start new workers
    +            Map<String, Integer> newWorkerPortToIds = startNewWorkers(newWorkerIds, reassignExecutors);
    +
    +            Map<String, Integer> allWorkerPortToIds = new HashMap<>();
    +            Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +            for (String keeper : keeperWorkerIds) {
    +                allWorkerPortToIds.put(keeper, approvedWorkers.get(keeper));
    +            }
    +            allWorkerPortToIds.putAll(newWorkerPortToIds);
    +            localState.setApprovedWorkers(allWorkerPortToIds);
    +            waitForWorkersLaunch(conf, newWorkerPortToIds.keySet());
    +
    +        } catch (Exception e) {
    +            LOG.error("Failed Sync Process", e);
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +    }
    +
    +    protected void waitForWorkersLaunch(Map conf, Set<String> workerIds) throws Exception {
    +        int startTime = Time.currentTimeSecs();
    +        int timeOut = (int) conf.get(Config.NIMBUS_SUPERVISOR_TIMEOUT_SECS);
    +        for (String workerId : workerIds) {
    +            LocalState localState = ConfigUtils.workerState(conf, workerId);
    +            while (true) {
    +                LSWorkerHeartbeat hb = localState.getWorkerHeartBeat();
    +                if (hb != null || (Time.currentTimeSecs() - startTime) > timeOut)
    +                    break;
    +                LOG.info("{} still hasn't started", workerId);
    +                Time.sleep(500);
    +            }
    +            if (localState.getWorkerHeartBeat() == null) {
    +                LOG.info("Worker {} failed to start", workerId);
    +            }
    +        }
    +    }
    +
    +    protected Map<Integer, LocalAssignment> getReassignExecutors(Map<Integer, LocalAssignment> assignExecutors, Set<Integer> keepPorts) {
    +        Map<Integer, LocalAssignment> reassignExecutors = new HashMap<>();
    +        reassignExecutors.putAll(assignExecutors);
    +        for (Integer port : keepPorts) {
    +            reassignExecutors.remove(port);
    +        }
    +        return reassignExecutors;
    +    }
    +    
    +    /**
    +     * Returns map from worker id to worker heartbeat. if the heartbeat is nil, then the worker is dead
    +     * 
    +     * @param assignedExecutors
    +     * @return
    +     * @throws Exception
    +     */
    +    public Map<String, StateHeartbeat> getLocalWorkerStats(SupervisorData supervisorData, Map<Integer, LocalAssignment> assignedExecutors, int now) throws Exception {
    +        Map<String, StateHeartbeat> workerIdHbstate = new HashMap<>();
    +        Map conf = supervisorData.getConf();
    +        LocalState localState = supervisorData.getLocalState();
    +        Map<String, LSWorkerHeartbeat> idToHeartbeat = SupervisorUtils.readWorkerHeartbeats(conf);
    +        Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +        Set<String> approvedIds = new HashSet<>();
    +        if (approvedWorkers != null) {
    +            approvedIds.addAll(approvedWorkers.keySet());
    +        }
    +        for (Map.Entry<String, LSWorkerHeartbeat> entry : idToHeartbeat.entrySet()) {
    +            String workerId = entry.getKey();
    +            LSWorkerHeartbeat whb = entry.getValue();
    +            State state;
    +            if (whb == null) {
    +                state = State.NOT_STARTED;
    +            } else if (!approvedIds.contains(workerId) || !matchesAssignment(whb, assignedExecutors)) {
    +                state = State.DISALLOWED;
    +            } else if (supervisorData.getDeadWorkers().contains(workerId)) {
    +                LOG.info("Worker Process {} has died", workerId);
    +                state = State.TIMED_OUT;
    +            } else if (SupervisorUtils.isWorkerHbTimedOut(now, whb, conf)) {
    +                state = State.TIMED_OUT;
    +            } else {
    +                state = State.VALID;
    +            }
    +            LOG.debug("Worker:{} state:{} WorkerHeartbeat:{} at supervisor time-secs {}", workerId, state, whb, now);
    +            workerIdHbstate.put(workerId, new StateHeartbeat(state, whb));
    +        }
    +        return workerIdHbstate;
    +    }
    +
    +    protected boolean matchesAssignment(LSWorkerHeartbeat whb, Map<Integer, LocalAssignment> assignedExecutors) {
    +        LocalAssignment localAssignment = assignedExecutors.get(whb.get_port());
    +        if (localAssignment == null || !localAssignment.get_topology_id().equals(whb.get_topology_id())) {
    +            return false;
    +        }
    +        List<ExecutorInfo> executorInfos = new ArrayList<>();
    +        executorInfos.addAll(whb.get_executors());
    +        // remove SYSTEM_EXECUTOR_ID
    +        executorInfos.remove(SYSTEM_EXECUTOR_INFO);
    +        List<ExecutorInfo> localExecuorInfos = localAssignment.get_executors();
    +
    +        if (localExecuorInfos.size() != executorInfos.size())
    +            return false;
    +
    +        for (ExecutorInfo executorInfo : localExecuorInfos){
    +            if (!localExecuorInfos.contains(executorInfo))
    +                return false;
    +        }
    +        return true;
    +    }
    +
    +    /**
    +     * launch a worker in local mode.
    +     */
    +    protected void launchWorker(SupervisorData supervisorData, String stormId, Long port, String workerId, WorkerResources resources) throws IOException {
    +        // port this function after porting worker to java
    +    }
    +
    +    protected String getWorkerClassPath(String stormJar, Map stormConf) {
    +        List<String> topoClasspath = new ArrayList<>();
    +        Object object = stormConf.get(Config.TOPOLOGY_CLASSPATH);
    +
    +        if (object instanceof List) {
    +            topoClasspath.addAll((List<String>) object);
    +        } else if (object instanceof String){
    +            topoClasspath.add((String)object);
    +        }else {
    +            //ignore
    +        }
    +        String classPath = Utils.workerClasspath();
    +        String classAddPath = Utils.addToClasspath(classPath, Arrays.asList(stormJar));
    +        return Utils.addToClasspath(classAddPath, topoClasspath);
    +    }
    +
    +    /**
    +     * "Generates runtime childopts by replacing keys with topology-id, worker-id, port, mem-onheap"
    +     * 
    +     * @param value
    +     * @param workerId
    +     * @param stormId
    +     * @param port
    +     * @param memOnheap
    +     */
    +    public List<String> substituteChildopts(Object value, String workerId, String stormId, Long port, int memOnheap) {
    +        List<String> rets = new ArrayList<>();
    +        if (value instanceof String) {
    +            String string = (String) value;
    +            string = string.replace("%ID%", String.valueOf(port));
    +            string = string.replace("%WORKER-ID%", workerId);
    +            string = string.replace("%TOPOLOGY-ID%", stormId);
    +            string = string.replace("%WORKER-PORT%", String.valueOf(port));
    +            string = string.replace("%HEAP-MEM%", String.valueOf(memOnheap));
    +            String[] strings = string.split("\\s+");
    +            rets.addAll(Arrays.asList(strings));
    +        } else if (value instanceof List) {
    +            List<Object> objects = (List<Object>) value;
    +            for (Object object : objects) {
    +                String str = (String)object;
    +                str = str.replace("%ID%", String.valueOf(port));
    +                str = str.replace("%WORKER-ID%", workerId);
    +                str = str.replace("%TOPOLOGY-ID%", stormId);
    +                str = str.replace("%WORKER-PORT%", String.valueOf(port));
    +                str = str.replace("%HEAP-MEM%", String.valueOf(memOnheap));
    +                rets.add(str);
    +            }
    +        }
    +        return rets;
    +    }
    +
    +
    +
    +    /**
    +     * launch a worker in distributed mode
    +     * supervisorId for testing
    +     * @throws IOException
    +     */
    +    protected void launchWorker(Map conf, String supervisorId, String assignmentId, String stormId, Long port, String workerId,
    +            WorkerResources resources, CgroupManager cgroupManager, ConcurrentHashSet deadWorkers) throws IOException {
    +
    +        Boolean runWorkerAsUser = Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false);
    +        String stormHome = ConfigUtils.concatIfNotNull(System.getProperty("storm.home"));
    +        String stormOptions = ConfigUtils.concatIfNotNull(System.getProperty("storm.options"));
    +        String stormConfFile = ConfigUtils.concatIfNotNull(System.getProperty("storm.conf.file"));
    +        String workerTmpDir = ConfigUtils.workerTmpRoot(conf, workerId);
    +
    +        String stormLogDir = ConfigUtils.getLogDir();
    +        String stormLogConfDir = (String) (conf.get(Config.STORM_LOG4J2_CONF_DIR));
    +
    +        String stormLog4j2ConfDir;
    +        if (StringUtils.isNotBlank(stormLogConfDir)) {
    +            if (Utils.isAbsolutePath(stormLogConfDir)) {
    +                stormLog4j2ConfDir = stormLogConfDir;
    +            } else {
    +                stormLog4j2ConfDir = stormHome + Utils.FILE_PATH_SEPARATOR + stormLogConfDir;
    +            }
    +        } else {
    +            stormLog4j2ConfDir = stormHome + Utils.FILE_PATH_SEPARATOR + "log4j2";
    +        }
    +
    +        String stormRoot = ConfigUtils.supervisorStormDistRoot(conf, stormId);
    +
    +        String jlp = jlp(stormRoot, conf);
    +
    +        String stormJar = ConfigUtils.supervisorStormJarPath(stormRoot);
    +
    +        Map stormConf = ConfigUtils.readSupervisorStormConf(conf, stormId);
    +
    +        String workerClassPath = getWorkerClassPath(stormJar, stormConf);
    +
    +        Object topGcOptsObject = stormConf.get(Config.TOPOLOGY_WORKER_GC_CHILDOPTS);
    +        List<String> topGcOpts = new ArrayList<>();
    --- End diff --
    
    This should be done only if topoGcOpts Object is not 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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55585748
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorData.java ---
    @@ -0,0 +1,339 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.cluster.ClusterStateContext;
    +import org.apache.storm.cluster.ClusterUtils;
    +import org.apache.storm.cluster.DaemonType;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.ProfileRequest;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +import java.net.UnknownHostException;
    +import java.util.ArrayList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.concurrent.ConcurrentHashMap;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SupervisorData {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorData.class);
    +
    +    private Map conf;
    +    private IContext sharedContext;
    +    private volatile boolean active;
    +    private ISupervisor iSupervisor;
    +    private Utils.UptimeComputer upTime;
    +    private String stormVersion;
    +
    +    private ConcurrentHashMap<String, String> workerThreadPidsAtom; // for local mode
    +
    +    private IStormClusterState stormClusterState;
    +
    +    private LocalState localState;
    +
    +    private String supervisorId;
    +
    +    private String assignmentId;
    +
    +    private String hostName;
    +
    +    // used for reporting used ports when heartbeating
    +    private ConcurrentHashMap<Long, LocalAssignment> currAssignment;
    +
    +    private StormTimer heartbeatTimer;
    +
    +    private StormTimer eventTimer;
    +
    +    private StormTimer blobUpdateTimer;
    +
    +    private Localizer localizer;
    +
    +    private ConcurrentHashMap<String, Map<String, Object>> assignmentVersions;
    +
    +    private AtomicInteger syncRetry;
    +
    +    private final Object downloadLock = new Object();
    +
    +    private ConcurrentHashMap<String, List<ProfileRequest>> stormIdToProfileActions;
    +
    +    private CgroupManager resourceIsolationManager;
    +
    +    private ConcurrentHashSet<String> deadWorkers;
    +
    +    public SupervisorData(Map conf, IContext sharedContext, ISupervisor iSupervisor) {
    +        this.conf = conf;
    +        this.sharedContext = sharedContext;
    +        this.iSupervisor = iSupervisor;
    +        this.active = true;
    +        this.upTime = Utils.makeUptimeComputer();
    +        this.stormVersion = VersionInfo.getVersion();
    +        this.workerThreadPidsAtom = new ConcurrentHashMap<String, String>();
    +        this.deadWorkers = new ConcurrentHashSet();
    +
    +        List<ACL> acls = null;
    +        if (Utils.isZkAuthenticationConfiguredStormServer(conf)) {
    +            acls = SupervisorUtils.supervisorZkAcls();
    +        }
    +
    +        try {
    +            this.stormClusterState = ClusterUtils.mkStormClusterState(conf, acls, new ClusterStateContext(DaemonType.SUPERVISOR));
    +        } catch (Exception e) {
    +            LOG.error("supervisor can't create stormClusterState");
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        try {
    +            this.localState = ConfigUtils.supervisorState(conf);
    +            this.localizer = Utils.createLocalizer(conf, ConfigUtils.supervisorLocalDir(conf));
    +        } catch (IOException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +        this.supervisorId = iSupervisor.getSupervisorId();
    +        this.assignmentId = iSupervisor.getAssignmentId();
    +
    +        try {
    +            this.hostName = Utils.hostname(conf);
    +        } catch (UnknownHostException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        this.currAssignment = new ConcurrentHashMap<>();
    +
    +        this.heartbeatTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.eventTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.blobUpdateTimer = new StormTimer("blob-update-timer", new DefaultUncaughtExceptionHandler());
    +
    +        this.assignmentVersions = new ConcurrentHashMap<>();
    +        this.syncRetry = new AtomicInteger(0);
    +        this.stormIdToProfileActions = new ConcurrentHashMap<>();
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            try {
    +                this.resourceIsolationManager = (CgroupManager) Utils.newInstance((String) conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN));
    +                this.resourceIsolationManager.prepare(conf);
    +                LOG.info("Using resource isolation plugin {} {}", conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN), resourceIsolationManager);
    +            } catch (IOException e) {
    +                throw Utils.wrapInRuntime(e);
    +            }
    +        } else {
    +            this.resourceIsolationManager = null;
    +        }
    +    }
    +
    +    public ConcurrentHashMap<String, List<ProfileRequest>> getStormIdToProfileActions() {
    +        return stormIdToProfileActions;
    +    }
    +
    +    public void setStormIdToProfileActions(Map<String, List<ProfileRequest>> stormIdToProfileActions) {
    +        this.stormIdToProfileActions.clear();
    +        this.stormIdToProfileActions.putAll(stormIdToProfileActions);
    +    }
    +
    +    public Map getConf() {
    +        return conf;
    +    }
    +
    +    public void setConf(Map conf) {
    +        this.conf = conf;
    +    }
    +
    +    public IContext getSharedContext() {
    +        return sharedContext;
    +    }
    +
    +    public void setSharedContext(IContext sharedContext) {
    +        this.sharedContext = sharedContext;
    +    }
    +
    +    public boolean isActive() {
    +        return active;
    +    }
    +
    +    public void setActive(boolean active) {
    +        this.active = active;
    +    }
    +
    +    public ISupervisor getiSupervisor() {
    +        return iSupervisor;
    +    }
    +
    +    public void setiSupervisor(ISupervisor iSupervisor) {
    +        this.iSupervisor = iSupervisor;
    +    }
    +
    +    public Utils.UptimeComputer getUpTime() {
    +        return upTime;
    +    }
    +
    +    public void setUpTime(Utils.UptimeComputer upTime) {
    +        this.upTime = upTime;
    +    }
    +
    +    public String getStormVersion() {
    +        return stormVersion;
    +    }
    +
    +    public void setStormVersion(String stormVersion) {
    +        this.stormVersion = stormVersion;
    +    }
    +
    +    public ConcurrentHashMap<String, String> getWorkerThreadPidsAtom() {
    +        return workerThreadPidsAtom;
    +    }
    +
    +    public void setWorkerThreadPidsAtom(ConcurrentHashMap<String, String> workerThreadPidsAtom) {
    +        this.workerThreadPidsAtom = workerThreadPidsAtom;
    +    }
    +
    +    public IStormClusterState getStormClusterState() {
    +        return stormClusterState;
    +    }
    +
    +    public void setStormClusterState(IStormClusterState stormClusterState) {
    +        this.stormClusterState = stormClusterState;
    +    }
    +
    +    public LocalState getLocalState() {
    +        return localState;
    +    }
    +
    +    public void setLocalState(LocalState localState) {
    +        this.localState = localState;
    +    }
    +
    +    public String getSupervisorId() {
    +        return supervisorId;
    +    }
    +
    +    public void setSupervisorId(String supervisorId) {
    +        this.supervisorId = supervisorId;
    +    }
    +
    +    public String getAssignmentId() {
    +        return assignmentId;
    +    }
    +
    +    public void setAssignmentId(String assignmentId) {
    +        this.assignmentId = assignmentId;
    +    }
    +
    +    public String getHostName() {
    +        return hostName;
    +    }
    +
    +    public void setHostName(String hostName) {
    +        this.hostName = hostName;
    +    }
    +
    +    public ConcurrentHashMap<Long, LocalAssignment> getCurrAssignment() {
    +        return currAssignment;
    +    }
    +
    +    public void setCurrAssignment(Map<Long, LocalAssignment> currAssignment) {
    +        this.currAssignment.clear();
    +        this.currAssignment.putAll(currAssignment);
    +    }
    +
    +    public StormTimer getHeartbeatTimer() {
    +        return heartbeatTimer;
    +    }
    +
    +    public void setHeartbeatTimer(StormTimer heartbeatTimer) {
    +        this.heartbeatTimer = heartbeatTimer;
    +    }
    +
    +    public StormTimer getEventTimer() {
    +        return eventTimer;
    +    }
    +
    +    public void setEventTimer(StormTimer eventTimer) {
    +        this.eventTimer = eventTimer;
    +    }
    +
    +    public StormTimer getBlobUpdateTimer() {
    +        return blobUpdateTimer;
    +    }
    +
    +    public void setBlobUpdateTimer(StormTimer blobUpdateTimer) {
    +        this.blobUpdateTimer = blobUpdateTimer;
    +    }
    +
    +    public Localizer getLocalizer() {
    +        return localizer;
    +    }
    +
    +    public void setLocalizer(Localizer localizer) {
    +        this.localizer = localizer;
    +    }
    +
    +    public AtomicInteger getSyncRetry() {
    +        return syncRetry;
    +    }
    +
    +    public void setSyncRetry(AtomicInteger syncRetry) {
    +        this.syncRetry = syncRetry;
    +    }
    +
    +    public ConcurrentHashMap<String, Map<String, Object>> getAssignmentVersions() {
    +        return assignmentVersions;
    +    }
    +
    +    public void setAssignmentVersions(Map<String, Map<String, Object>> assignmentVersions) {
    +        this.assignmentVersions.clear();
    +        this.assignmentVersions.putAll(assignmentVersions);
    +    }
    +
    +    public CgroupManager getResourceIsolationManager() {
    +        return resourceIsolationManager;
    +    }
    +
    +    public void setResourceIsolationManager(CgroupManager resourceIsolationManager) {
    +        this.resourceIsolationManager = resourceIsolationManager;
    +    }
    +
    +    public Object getDownloadLock() {
    +        return downloadLock;
    +    }
    +
    +    public ConcurrentHashSet getDeadWorkers() {
    +        return deadWorkers;
    +    }
    +
    +    public void setDeadWorkers(ConcurrentHashSet deadWorkers) {
    --- End diff --
    
    Not used.


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55585266
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorData.java ---
    @@ -0,0 +1,339 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.cluster.ClusterStateContext;
    +import org.apache.storm.cluster.ClusterUtils;
    +import org.apache.storm.cluster.DaemonType;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.ProfileRequest;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +import java.net.UnknownHostException;
    +import java.util.ArrayList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.concurrent.ConcurrentHashMap;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SupervisorData {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorData.class);
    +
    +    private Map conf;
    +    private IContext sharedContext;
    +    private volatile boolean active;
    +    private ISupervisor iSupervisor;
    +    private Utils.UptimeComputer upTime;
    +    private String stormVersion;
    +
    +    private ConcurrentHashMap<String, String> workerThreadPidsAtom; // for local mode
    +
    +    private IStormClusterState stormClusterState;
    +
    +    private LocalState localState;
    +
    +    private String supervisorId;
    +
    +    private String assignmentId;
    +
    +    private String hostName;
    +
    +    // used for reporting used ports when heartbeating
    +    private ConcurrentHashMap<Long, LocalAssignment> currAssignment;
    +
    +    private StormTimer heartbeatTimer;
    +
    +    private StormTimer eventTimer;
    +
    +    private StormTimer blobUpdateTimer;
    +
    +    private Localizer localizer;
    +
    +    private ConcurrentHashMap<String, Map<String, Object>> assignmentVersions;
    +
    +    private AtomicInteger syncRetry;
    +
    +    private final Object downloadLock = new Object();
    +
    +    private ConcurrentHashMap<String, List<ProfileRequest>> stormIdToProfileActions;
    +
    +    private CgroupManager resourceIsolationManager;
    +
    +    private ConcurrentHashSet<String> deadWorkers;
    +
    +    public SupervisorData(Map conf, IContext sharedContext, ISupervisor iSupervisor) {
    +        this.conf = conf;
    +        this.sharedContext = sharedContext;
    +        this.iSupervisor = iSupervisor;
    +        this.active = true;
    +        this.upTime = Utils.makeUptimeComputer();
    +        this.stormVersion = VersionInfo.getVersion();
    +        this.workerThreadPidsAtom = new ConcurrentHashMap<String, String>();
    +        this.deadWorkers = new ConcurrentHashSet();
    +
    +        List<ACL> acls = null;
    +        if (Utils.isZkAuthenticationConfiguredStormServer(conf)) {
    +            acls = SupervisorUtils.supervisorZkAcls();
    +        }
    +
    +        try {
    +            this.stormClusterState = ClusterUtils.mkStormClusterState(conf, acls, new ClusterStateContext(DaemonType.SUPERVISOR));
    +        } catch (Exception e) {
    +            LOG.error("supervisor can't create stormClusterState");
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        try {
    +            this.localState = ConfigUtils.supervisorState(conf);
    +            this.localizer = Utils.createLocalizer(conf, ConfigUtils.supervisorLocalDir(conf));
    +        } catch (IOException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +        this.supervisorId = iSupervisor.getSupervisorId();
    +        this.assignmentId = iSupervisor.getAssignmentId();
    +
    +        try {
    +            this.hostName = Utils.hostname(conf);
    +        } catch (UnknownHostException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        this.currAssignment = new ConcurrentHashMap<>();
    +
    +        this.heartbeatTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.eventTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.blobUpdateTimer = new StormTimer("blob-update-timer", new DefaultUncaughtExceptionHandler());
    +
    +        this.assignmentVersions = new ConcurrentHashMap<>();
    +        this.syncRetry = new AtomicInteger(0);
    +        this.stormIdToProfileActions = new ConcurrentHashMap<>();
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            try {
    +                this.resourceIsolationManager = (CgroupManager) Utils.newInstance((String) conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN));
    +                this.resourceIsolationManager.prepare(conf);
    +                LOG.info("Using resource isolation plugin {} {}", conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN), resourceIsolationManager);
    +            } catch (IOException e) {
    +                throw Utils.wrapInRuntime(e);
    +            }
    +        } else {
    +            this.resourceIsolationManager = null;
    +        }
    +    }
    +
    +    public ConcurrentHashMap<String, List<ProfileRequest>> getStormIdToProfileActions() {
    +        return stormIdToProfileActions;
    +    }
    +
    +    public void setStormIdToProfileActions(Map<String, List<ProfileRequest>> stormIdToProfileActions) {
    +        this.stormIdToProfileActions.clear();
    +        this.stormIdToProfileActions.putAll(stormIdToProfileActions);
    +    }
    +
    +    public Map getConf() {
    +        return conf;
    +    }
    +
    +    public void setConf(Map conf) {
    +        this.conf = conf;
    +    }
    +
    +    public IContext getSharedContext() {
    +        return sharedContext;
    +    }
    +
    +    public void setSharedContext(IContext sharedContext) {
    +        this.sharedContext = sharedContext;
    +    }
    +
    +    public boolean isActive() {
    +        return active;
    +    }
    +
    +    public void setActive(boolean active) {
    +        this.active = active;
    +    }
    +
    +    public ISupervisor getiSupervisor() {
    +        return iSupervisor;
    +    }
    +
    +    public void setiSupervisor(ISupervisor iSupervisor) {
    +        this.iSupervisor = iSupervisor;
    +    }
    +
    +    public Utils.UptimeComputer getUpTime() {
    +        return upTime;
    +    }
    +
    +    public void setUpTime(Utils.UptimeComputer upTime) {
    +        this.upTime = upTime;
    +    }
    +
    +    public String getStormVersion() {
    +        return stormVersion;
    +    }
    +
    +    public void setStormVersion(String stormVersion) {
    +        this.stormVersion = stormVersion;
    +    }
    +
    +    public ConcurrentHashMap<String, String> getWorkerThreadPidsAtom() {
    +        return workerThreadPidsAtom;
    +    }
    +
    +    public void setWorkerThreadPidsAtom(ConcurrentHashMap<String, String> workerThreadPidsAtom) {
    +        this.workerThreadPidsAtom = workerThreadPidsAtom;
    +    }
    +
    +    public IStormClusterState getStormClusterState() {
    +        return stormClusterState;
    +    }
    +
    +    public void setStormClusterState(IStormClusterState stormClusterState) {
    +        this.stormClusterState = stormClusterState;
    +    }
    +
    +    public LocalState getLocalState() {
    +        return localState;
    +    }
    +
    +    public void setLocalState(LocalState localState) {
    +        this.localState = localState;
    +    }
    +
    +    public String getSupervisorId() {
    +        return supervisorId;
    +    }
    +
    +    public void setSupervisorId(String supervisorId) {
    +        this.supervisorId = supervisorId;
    +    }
    +
    +    public String getAssignmentId() {
    +        return assignmentId;
    +    }
    +
    +    public void setAssignmentId(String assignmentId) {
    +        this.assignmentId = assignmentId;
    +    }
    +
    +    public String getHostName() {
    +        return hostName;
    +    }
    +
    +    public void setHostName(String hostName) {
    +        this.hostName = hostName;
    +    }
    +
    +    public ConcurrentHashMap<Long, LocalAssignment> getCurrAssignment() {
    +        return currAssignment;
    +    }
    +
    +    public void setCurrAssignment(Map<Long, LocalAssignment> currAssignment) {
    +        this.currAssignment.clear();
    +        this.currAssignment.putAll(currAssignment);
    --- End diff --
    
    The clear with the add should probably be atomic.  The race is very small, but I would rather see us have an AtomicReference<Map<Long, LocalAssignment>> instead of a ConcurrentHashMap.


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55701258
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorUtils.java ---
    @@ -0,0 +1,273 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.curator.utils.PathUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.localizer.LocalResource;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.IOException;
    +import java.net.URLDecoder;
    +import java.util.*;
    +
    +public class SupervisorUtils {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorUtils.class);
    +
    +    private static final SupervisorUtils INSTANCE = new SupervisorUtils();
    +    private static SupervisorUtils _instance = INSTANCE;
    +
    +    public static void setInstance(SupervisorUtils u) {
    +        _instance = u;
    +    }
    +
    +    public static void resetInstance() {
    +        _instance = INSTANCE;
    +    }
    +
    +    public static Process workerLauncher(Map conf, String user, List<String> args, Map<String, String> environment, final String logPreFix,
    --- End diff --
    
    @revans2  agree. 


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55568307
  
    --- Diff: storm-core/src/clj/org/apache/storm/daemon/local_supervisor.clj ---
    @@ -0,0 +1,61 @@
    +;; 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.
    +(ns org.apache.storm.daemon.local-supervisor
    +  (:import [org.apache.storm.daemon.supervisor SyncProcessEvent SupervisorData ShutdownWork Supervisor]
    +           [org.apache.storm.utils Utils ConfigUtils]
    +           [org.apache.storm ProcessSimulator])
    +  (:use [org.apache.storm.daemon common]
    +        [org.apache.storm log])
    +  (:require [org.apache.storm.daemon [worker :as worker] ])
    +  (:require [clojure.string :as str])
    +  (:gen-class))
    --- End diff --
    
    If we are going to leave this part of the supervisor in clojure for now that is fine, but we need a follow on JIRA to move it to java wonce worker is moved 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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55640204
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/Supervisor.java ---
    @@ -0,0 +1,196 @@
    +/**
    + * 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.supervisor;
    +
    +import com.codahale.metrics.Gauge;
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.commons.io.FileUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.daemon.supervisor.timer.RunProfilerActions;
    +import org.apache.storm.daemon.supervisor.timer.SupervisorHealthCheck;
    +import org.apache.storm.daemon.supervisor.timer.SupervisorHeartbeat;
    +import org.apache.storm.daemon.supervisor.timer.UpdateBlobs;
    +import org.apache.storm.event.EventManagerImp;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.InterruptedIOException;
    +import java.util.Collection;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +
    +public class Supervisor {
    +    private static Logger LOG = LoggerFactory.getLogger(Supervisor.class);
    +
    +    //TODO: to be removed after porting worker.clj. localSyncProcess is intended to start local supervisor
    +    private SyncProcessEvent localSyncProcess;
    +
    +    public void setLocalSyncProcess(SyncProcessEvent localSyncProcess) {
    +        this.localSyncProcess = localSyncProcess;
    +    }
    +
    +
    +    /**
    +     * in local state, supervisor stores who its current assignments are another thread launches events to restart any dead processes if necessary
    +     * 
    +     * @param conf
    +     * @param sharedContext
    +     * @param iSupervisor
    +     * @return
    +     * @throws Exception
    +     */
    +    public SupervisorManger mkSupervisor(final Map conf, IContext sharedContext, ISupervisor iSupervisor) throws Exception {
    +        SupervisorManger supervisorManger = null;
    +        try {
    +            LOG.info("Starting Supervisor with conf {}", conf);
    +            iSupervisor.prepare(conf, ConfigUtils.supervisorIsupervisorDir(conf));
    +            String path = ConfigUtils.supervisorTmpDir(conf);
    +            FileUtils.cleanDirectory(new File(path));
    +
    +            final SupervisorData supervisorData = new SupervisorData(conf, sharedContext, iSupervisor);
    +            Localizer localizer = supervisorData.getLocalizer();
    +
    +            SupervisorHeartbeat hb = new SupervisorHeartbeat(conf, supervisorData);
    +            hb.run();
    +            // should synchronize supervisor so it doesn't launch anything after being down (optimization)
    +            Integer heartbeatFrequency = Utils.getInt(conf.get(Config.SUPERVISOR_HEARTBEAT_FREQUENCY_SECS));
    +            supervisorData.getHeartbeatTimer().scheduleRecurring(0, heartbeatFrequency, hb);
    +
    +            Set<String> downdedStormId = SupervisorUtils.readDownLoadedStormIds(conf);
    +            for (String stormId : downdedStormId) {
    +                SupervisorUtils.addBlobReferences(localizer, stormId, conf);
    +            }
    +            // do this after adding the references so we don't try to clean things being used
    +            localizer.startCleaner();
    +
    +            EventManagerImp syncSupEventManager = new EventManagerImp(false);
    +            EventManagerImp syncProcessManager = new EventManagerImp(false);
    +
    +            SyncProcessEvent syncProcessEvent = null;
    +            if (ConfigUtils.isLocalMode(conf)){
    +                localSyncProcess.init(supervisorData);
    +                syncProcessEvent = localSyncProcess;
    +            }else{
    +                syncProcessEvent = new SyncProcessEvent(supervisorData);
    +            }
    +
    +            SyncSupervisorEvent syncSupervisorEvent = new SyncSupervisorEvent(supervisorData, syncProcessEvent, syncSupEventManager, syncProcessManager);
    +            UpdateBlobs updateBlobsThread = new UpdateBlobs(supervisorData);
    +            RunProfilerActions runProfilerActionThread = new RunProfilerActions(supervisorData);
    +
    +            if ((Boolean) conf.get(Config.SUPERVISOR_ENABLE)) {
    +                StormTimer eventTimer = supervisorData.getEventTimer();
    +                // This isn't strictly necessary, but it doesn't hurt and ensures that the machine stays up
    +                // to date even if callbacks don't all work exactly right
    +                eventTimer.scheduleRecurring(0, 10, new EventManagerPushCallback(syncSupervisorEvent, syncSupEventManager));
    +
    +                eventTimer.scheduleRecurring(0, Utils.getInt(conf.get(Config.SUPERVISOR_MONITOR_FREQUENCY_SECS)),
    +                        new EventManagerPushCallback(syncProcessEvent, syncProcessManager));
    +
    +                // Blob update thread. Starts with 30 seconds delay, every 30 seconds
    +                supervisorData.getBlobUpdateTimer().scheduleRecurring(30, 30, new EventManagerPushCallback(updateBlobsThread, syncSupEventManager));
    +
    +                // supervisor health check
    +                eventTimer.scheduleRecurring(300, 300, new SupervisorHealthCheck(supervisorData));
    +
    +                // Launch a thread that Runs profiler commands . Starts with 30 seconds delay, every 30 seconds
    +                eventTimer.scheduleRecurring(30, 30, new EventManagerPushCallback(runProfilerActionThread, syncSupEventManager));
    +            }
    +            LOG.info("Starting supervisor with id {} at host {}.", supervisorData.getSupervisorId(), supervisorData.getHostName() );
    +            supervisorManger = new SupervisorManger(supervisorData, syncSupEventManager, syncProcessManager);
    +        } catch (Throwable t) {
    +            if (Utils.exceptionCauseIsInstanceOf(InterruptedIOException.class, t)) {
    +                throw t;
    +            } else if (Utils.exceptionCauseIsInstanceOf(InterruptedException.class, t)) {
    +                throw t;
    +            } else {
    +                LOG.error("Error on initialization of server supervisor: {}", t);
    +                Utils.exitProcess(13, "Error on initialization");
    +            }
    +        }
    +        return supervisorManger;
    +    }
    +
    +    /**
    +     * start distribute supervisor
    +     */
    +    private void launch() {
    +        LOG.info("Starting supervisor for storm version '{}'.", VersionInfo.getVersion());
    +        SupervisorManger supervisorManager;
    +        try {
    +            Map<Object, Object> conf = Utils.readStormConfig();
    +            if (ConfigUtils.isLocalMode(conf)) {
    +                throw new IllegalArgumentException("Cannot start server in local mode!");
    +            }
    +            ISupervisor iSupervisor = new StandaloneSupervisor();
    +            supervisorManager = mkSupervisor(conf, null, iSupervisor);
    +            if (supervisorManager != null)
    +                Utils.addShutdownHookWithForceKillIn1Sec(supervisorManager);
    +            registerWorkerNumGauge("drpc:num-execute-http-requests", conf);
    --- End diff --
    
    drpc !!.. name should be corrected


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r57414646
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncSupervisorEvent.java ---
    @@ -0,0 +1,632 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.blobstore.BlobStore;
    +import org.apache.storm.blobstore.ClientBlobStore;
    +import org.apache.storm.cluster.IStateStorage;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.event.EventManager;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.localizer.LocalResource;
    +import org.apache.storm.localizer.LocalizedResource;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.utils.*;
    +import org.apache.thrift.transport.TTransportException;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.FileOutputStream;
    +import java.io.IOException;
    +import java.net.JarURLConnection;
    +import java.net.URL;
    +import java.nio.file.Files;
    +import java.nio.file.StandardCopyOption;
    +import java.util.*;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SyncSupervisorEvent implements Runnable {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SyncSupervisorEvent.class);
    +
    +    private EventManager syncSupEventManager;
    +    private EventManager syncProcessManager;
    +    private IStormClusterState stormClusterState;
    +    private LocalState localState;
    +    private SyncProcessEvent syncProcesses;
    +    private SupervisorData supervisorData;
    +
    +    public SyncSupervisorEvent(SupervisorData supervisorData, SyncProcessEvent syncProcesses, EventManager syncSupEventManager,
    +            EventManager syncProcessManager) {
    +
    +        this.syncProcesses = syncProcesses;
    +        this.syncSupEventManager = syncSupEventManager;
    +        this.syncProcessManager = syncProcessManager;
    +        this.stormClusterState = supervisorData.getStormClusterState();
    +        this.localState = supervisorData.getLocalState();
    +        this.supervisorData = supervisorData;
    +    }
    +
    +    @Override
    +    public void run() {
    +        try {
    +            Map conf = supervisorData.getConf();
    +            Runnable syncCallback = new EventManagerPushCallback(this, syncSupEventManager);
    +            List<String> stormIds = stormClusterState.assignments(syncCallback);
    +            Map<String, Map<String, Object>> assignmentsSnapshot =
    +                    getAssignmentsSnapshot(stormClusterState, stormIds, supervisorData.getAssignmentVersions().get(), syncCallback);
    +            Map<String, List<ProfileRequest>> stormIdToProfilerActions = getProfileActions(stormClusterState, stormIds);
    +
    +            Set<String> allDownloadedTopologyIds = SupervisorUtils.readDownLoadedStormIds(conf);
    +            Map<String, String> stormcodeMap = readStormCodeLocations(assignmentsSnapshot);
    +            Map<Integer, LocalAssignment> existingAssignment = localState.getLocalAssignmentsMap();
    +            if (existingAssignment == null) {
    +                existingAssignment = new HashMap<>();
    +            }
    +
    +            Map<Integer, LocalAssignment> allAssignment =
    +                    readAssignments(assignmentsSnapshot, existingAssignment, supervisorData.getAssignmentId(), supervisorData.getSyncRetry());
    +
    +            Map<Integer, LocalAssignment> newAssignment = new HashMap<>();
    +            Set<String> assignedStormIds = new HashSet<>();
    +
    +            for (Map.Entry<Integer, LocalAssignment> entry : allAssignment.entrySet()) {
    +                if (supervisorData.getiSupervisor().confirmAssigned(entry.getKey())) {
    +                    newAssignment.put(entry.getKey(), entry.getValue());
    +                    assignedStormIds.add(entry.getValue().get_topology_id());
    +                }
    +            }
    +
    +            Set<String> srashStormIds = verifyDownloadedFiles(conf, supervisorData.getLocalizer(), assignedStormIds, allDownloadedTopologyIds);
    +            Set<String> downloadedStormIds = new HashSet<>();
    +            downloadedStormIds.addAll(allDownloadedTopologyIds);
    +            downloadedStormIds.removeAll(srashStormIds);
    +
    +            LOG.debug("Synchronizing supervisor");
    +            LOG.debug("Storm code map: {}", stormcodeMap);
    +            LOG.debug("All assignment: {}", allAssignment);
    +            LOG.debug("New assignment: {}", newAssignment);
    +            LOG.debug("Assigned Storm Ids {}", assignedStormIds);
    +            LOG.debug("All Downloaded Ids {}", allDownloadedTopologyIds);
    +            LOG.debug("Checked Downloaded Ids {}", srashStormIds);
    +            LOG.debug("Downloaded Ids {}", downloadedStormIds);
    +            LOG.debug("Storm Ids Profiler Actions {}", stormIdToProfilerActions);
    +
    +            // download code first
    +            // This might take awhile
    +            // - should this be done separately from usual monitoring?
    +            // should we only download when topology is assigned to this supervisor?
    +            for (Map.Entry<String, String> entry : stormcodeMap.entrySet()) {
    +                String stormId = entry.getKey();
    +                if (!downloadedStormIds.contains(stormId) && assignedStormIds.contains(stormId)) {
    +                    LOG.info("Downloading code for storm id {}.", stormId);
    +                    try {
    +                        downloadStormCode(conf, stormId, entry.getValue(), supervisorData.getLocalizer());
    +                    } catch (Exception e) {
    +                        if (Utils.exceptionCauseIsInstanceOf(NimbusLeaderNotFoundException.class, e)) {
    +                            LOG.warn("Nimbus leader was not available.", e);
    +                        } else if (Utils.exceptionCauseIsInstanceOf(TTransportException.class, e)) {
    +                            LOG.warn("There was a connection problem with nimbus.", e);
    +                        } else {
    +                            throw e;
    +                        }
    +                    }
    +                    LOG.info("Finished downloading code for storm id {}", stormId);
    +                }
    +            }
    +
    +            LOG.debug("Writing new assignment {}", newAssignment);
    +
    +            Set<Integer> killWorkers = new HashSet<>();
    +            killWorkers.addAll(existingAssignment.keySet());
    +            killWorkers.removeAll(newAssignment.keySet());
    +            for (Integer port : killWorkers) {
    +                supervisorData.getiSupervisor().killedWorker(port);
    +            }
    +
    +            killExistingWorkersWithChangeInComponents(supervisorData, existingAssignment, newAssignment);
    +
    +            supervisorData.getiSupervisor().assigned(newAssignment.keySet());
    +            localState.setLocalAssignmentsMap(newAssignment);
    +            supervisorData.setAssignmentVersions(assignmentsSnapshot);
    +            supervisorData.setStormIdToProfileActions(stormIdToProfilerActions);
    +
    +            Map<Long, LocalAssignment> convertNewAssignment = new HashMap<>();
    +            for (Map.Entry<Integer, LocalAssignment> entry : newAssignment.entrySet()) {
    +                convertNewAssignment.put(entry.getKey().longValue(), entry.getValue());
    +            }
    +            supervisorData.setCurrAssignment(convertNewAssignment);
    +            // remove any downloaded code that's no longer assigned or active
    +            // important that this happens after setting the local assignment so that
    +            // synchronize-supervisor doesn't try to launch workers for which the
    +            // resources don't exist
    +            if (Utils.isOnWindows()) {
    +                shutdownDisallowedWorkers();
    +            }
    +            for (String stormId : allDownloadedTopologyIds) {
    +                if (!stormcodeMap.containsKey(stormId)) {
    +                    LOG.info("Removing code for storm id {}.", stormId);
    +                    rmTopoFiles(conf, stormId, supervisorData.getLocalizer(), true);
    +                }
    +            }
    +            syncProcessManager.add(syncProcesses);
    +        } catch (Exception e) {
    +            LOG.error("Failed to Sync Supervisor", e);
    +            throw new RuntimeException(e);
    +        }
    +
    +    }
    +
    +    private void killExistingWorkersWithChangeInComponents(SupervisorData supervisorData, Map<Integer, LocalAssignment> existingAssignment,
    +            Map<Integer, LocalAssignment> newAssignment) throws Exception {
    +        LocalState localState = supervisorData.getLocalState();
    +        Map<Integer, LocalAssignment> assignedExecutors = localState.getLocalAssignmentsMap();
    +        if (assignedExecutors == null) {
    +            assignedExecutors = new HashMap<>();
    +        }
    +        int now = Time.currentTimeSecs();
    +        Map<String, StateHeartbeat> workerIdHbstate = syncProcesses.getLocalWorkerStats(supervisorData, assignedExecutors, now);
    +        Map<Integer, String> vaildPortToWorkerIds = new HashMap<>();
    +        for (Map.Entry<String, StateHeartbeat> entry : workerIdHbstate.entrySet()) {
    +            String workerId = entry.getKey();
    +            StateHeartbeat stateHeartbeat = entry.getValue();
    +            if (stateHeartbeat != null && stateHeartbeat.getState() == State.VALID) {
    +                vaildPortToWorkerIds.put(stateHeartbeat.getHeartbeat().get_port(), workerId);
    +            }
    +        }
    +
    +        Map<Integer, LocalAssignment> intersectAssignment = new HashMap<>();
    +        for (Map.Entry<Integer, LocalAssignment> entry : newAssignment.entrySet()) {
    +            Integer port = entry.getKey();
    +            if (existingAssignment.containsKey(port)) {
    +                intersectAssignment.put(port, entry.getValue());
    +            }
    +        }
    +
    +        for (Integer port : intersectAssignment.keySet()) {
    +            List<ExecutorInfo> existExecutors = existingAssignment.get(port).get_executors();
    +            List<ExecutorInfo> newExecutors = newAssignment.get(port).get_executors();
    +            if (newExecutors.size() != existExecutors.size()) {
    --- End diff --
    
    ok, I will update it. Thank you.


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55938351
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncProcessEvent.java ---
    @@ -0,0 +1,672 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.ExecutorInfo;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.WorkerResources;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +import org.yaml.snakeyaml.Yaml;
    +
    +import java.io.File;
    +import java.io.FileWriter;
    +import java.io.IOException;
    +import java.util.*;
    +
    +/**
    + * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file - rmr
    + * heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new worker
    + * ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait for workers
    + * launch
    + */
    +public class SyncProcessEvent implements Runnable {
    +
    +    private static Logger LOG = LoggerFactory.getLogger(SyncProcessEvent.class);
    +
    +    private  LocalState localState;
    +    private  SupervisorData supervisorData;
    +    public static final ExecutorInfo SYSTEM_EXECUTOR_INFO = new ExecutorInfo(-1, -1);
    +
    +    private class ProcessExitCallback implements Utils.ExitCodeCallable {
    +        private final String logPrefix;
    +        private final String workerId;
    +
    +        public ProcessExitCallback(String logPrefix, String workerId) {
    +            this.logPrefix = logPrefix;
    +            this.workerId = workerId;
    +        }
    +
    +        @Override
    +        public Object call() throws Exception {
    +            return null;
    +        }
    +
    +        @Override
    +        public Object call(int exitCode) {
    +            LOG.info("{} exited with code: {}", logPrefix, exitCode);
    +            supervisorData.getDeadWorkers().add(workerId);
    +            return null;
    +        }
    +    }
    +
    +    public SyncProcessEvent(){
    +
    +    }
    +    public SyncProcessEvent(SupervisorData supervisorData) {
    +        init(supervisorData);
    +    }
    +
    +    //TODO: initData is intended to local supervisor, so we will remove them after porting worker.clj to java
    --- End diff --
    
    is this a valid to-do?


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55584469
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorData.java ---
    @@ -0,0 +1,339 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.cluster.ClusterStateContext;
    +import org.apache.storm.cluster.ClusterUtils;
    +import org.apache.storm.cluster.DaemonType;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.ProfileRequest;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +import java.net.UnknownHostException;
    +import java.util.ArrayList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.concurrent.ConcurrentHashMap;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SupervisorData {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorData.class);
    +
    +    private Map conf;
    +    private IContext sharedContext;
    +    private volatile boolean active;
    +    private ISupervisor iSupervisor;
    +    private Utils.UptimeComputer upTime;
    +    private String stormVersion;
    +
    +    private ConcurrentHashMap<String, String> workerThreadPidsAtom; // for local mode
    +
    +    private IStormClusterState stormClusterState;
    +
    +    private LocalState localState;
    +
    +    private String supervisorId;
    +
    +    private String assignmentId;
    +
    +    private String hostName;
    +
    +    // used for reporting used ports when heartbeating
    +    private ConcurrentHashMap<Long, LocalAssignment> currAssignment;
    +
    +    private StormTimer heartbeatTimer;
    +
    +    private StormTimer eventTimer;
    +
    +    private StormTimer blobUpdateTimer;
    +
    +    private Localizer localizer;
    +
    +    private ConcurrentHashMap<String, Map<String, Object>> assignmentVersions;
    +
    +    private AtomicInteger syncRetry;
    +
    +    private final Object downloadLock = new Object();
    +
    +    private ConcurrentHashMap<String, List<ProfileRequest>> stormIdToProfileActions;
    +
    +    private CgroupManager resourceIsolationManager;
    +
    +    private ConcurrentHashSet<String> deadWorkers;
    +
    +    public SupervisorData(Map conf, IContext sharedContext, ISupervisor iSupervisor) {
    +        this.conf = conf;
    +        this.sharedContext = sharedContext;
    +        this.iSupervisor = iSupervisor;
    +        this.active = true;
    +        this.upTime = Utils.makeUptimeComputer();
    +        this.stormVersion = VersionInfo.getVersion();
    +        this.workerThreadPidsAtom = new ConcurrentHashMap<String, String>();
    +        this.deadWorkers = new ConcurrentHashSet();
    +
    +        List<ACL> acls = null;
    +        if (Utils.isZkAuthenticationConfiguredStormServer(conf)) {
    +            acls = SupervisorUtils.supervisorZkAcls();
    +        }
    +
    +        try {
    +            this.stormClusterState = ClusterUtils.mkStormClusterState(conf, acls, new ClusterStateContext(DaemonType.SUPERVISOR));
    +        } catch (Exception e) {
    +            LOG.error("supervisor can't create stormClusterState");
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        try {
    +            this.localState = ConfigUtils.supervisorState(conf);
    +            this.localizer = Utils.createLocalizer(conf, ConfigUtils.supervisorLocalDir(conf));
    +        } catch (IOException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +        this.supervisorId = iSupervisor.getSupervisorId();
    +        this.assignmentId = iSupervisor.getAssignmentId();
    +
    +        try {
    +            this.hostName = Utils.hostname(conf);
    +        } catch (UnknownHostException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        this.currAssignment = new ConcurrentHashMap<>();
    +
    +        this.heartbeatTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.eventTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.blobUpdateTimer = new StormTimer("blob-update-timer", new DefaultUncaughtExceptionHandler());
    +
    +        this.assignmentVersions = new ConcurrentHashMap<>();
    +        this.syncRetry = new AtomicInteger(0);
    +        this.stormIdToProfileActions = new ConcurrentHashMap<>();
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            try {
    +                this.resourceIsolationManager = (CgroupManager) Utils.newInstance((String) conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN));
    +                this.resourceIsolationManager.prepare(conf);
    +                LOG.info("Using resource isolation plugin {} {}", conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN), resourceIsolationManager);
    +            } catch (IOException e) {
    +                throw Utils.wrapInRuntime(e);
    +            }
    +        } else {
    +            this.resourceIsolationManager = null;
    +        }
    +    }
    +
    +    public ConcurrentHashMap<String, List<ProfileRequest>> getStormIdToProfileActions() {
    +        return stormIdToProfileActions;
    +    }
    +
    +    public void setStormIdToProfileActions(Map<String, List<ProfileRequest>> stormIdToProfileActions) {
    +        this.stormIdToProfileActions.clear();
    +        this.stormIdToProfileActions.putAll(stormIdToProfileActions);
    +    }
    +
    +    public Map getConf() {
    +        return conf;
    +    }
    +
    +    public void setConf(Map conf) {
    +        this.conf = conf;
    +    }
    +
    +    public IContext getSharedContext() {
    +        return sharedContext;
    +    }
    +
    +    public void setSharedContext(IContext sharedContext) {
    +        this.sharedContext = sharedContext;
    +    }
    +
    +    public boolean isActive() {
    +        return active;
    +    }
    +
    +    public void setActive(boolean active) {
    +        this.active = active;
    +    }
    +
    +    public ISupervisor getiSupervisor() {
    +        return iSupervisor;
    +    }
    +
    +    public void setiSupervisor(ISupervisor iSupervisor) {
    +        this.iSupervisor = iSupervisor;
    +    }
    +
    +    public Utils.UptimeComputer getUpTime() {
    +        return upTime;
    +    }
    +
    +    public void setUpTime(Utils.UptimeComputer upTime) {
    +        this.upTime = upTime;
    +    }
    +
    +    public String getStormVersion() {
    +        return stormVersion;
    +    }
    +
    +    public void setStormVersion(String stormVersion) {
    --- End diff --
    
    Not used


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r57228512
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncSupervisorEvent.java ---
    @@ -0,0 +1,632 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.blobstore.BlobStore;
    +import org.apache.storm.blobstore.ClientBlobStore;
    +import org.apache.storm.cluster.IStateStorage;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.event.EventManager;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.localizer.LocalResource;
    +import org.apache.storm.localizer.LocalizedResource;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.utils.*;
    +import org.apache.thrift.transport.TTransportException;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.FileOutputStream;
    +import java.io.IOException;
    +import java.net.JarURLConnection;
    +import java.net.URL;
    +import java.nio.file.Files;
    +import java.nio.file.StandardCopyOption;
    +import java.util.*;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SyncSupervisorEvent implements Runnable {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SyncSupervisorEvent.class);
    +
    +    private EventManager syncSupEventManager;
    +    private EventManager syncProcessManager;
    +    private IStormClusterState stormClusterState;
    +    private LocalState localState;
    +    private SyncProcessEvent syncProcesses;
    +    private SupervisorData supervisorData;
    +
    +    public SyncSupervisorEvent(SupervisorData supervisorData, SyncProcessEvent syncProcesses, EventManager syncSupEventManager,
    +            EventManager syncProcessManager) {
    +
    +        this.syncProcesses = syncProcesses;
    +        this.syncSupEventManager = syncSupEventManager;
    +        this.syncProcessManager = syncProcessManager;
    +        this.stormClusterState = supervisorData.getStormClusterState();
    +        this.localState = supervisorData.getLocalState();
    +        this.supervisorData = supervisorData;
    +    }
    +
    +    @Override
    +    public void run() {
    +        try {
    +            Map conf = supervisorData.getConf();
    +            Runnable syncCallback = new EventManagerPushCallback(this, syncSupEventManager);
    +            List<String> stormIds = stormClusterState.assignments(syncCallback);
    +            Map<String, Map<String, Object>> assignmentsSnapshot =
    +                    getAssignmentsSnapshot(stormClusterState, stormIds, supervisorData.getAssignmentVersions().get(), syncCallback);
    +            Map<String, List<ProfileRequest>> stormIdToProfilerActions = getProfileActions(stormClusterState, stormIds);
    +
    +            Set<String> allDownloadedTopologyIds = SupervisorUtils.readDownLoadedStormIds(conf);
    +            Map<String, String> stormcodeMap = readStormCodeLocations(assignmentsSnapshot);
    +            Map<Integer, LocalAssignment> existingAssignment = localState.getLocalAssignmentsMap();
    +            if (existingAssignment == null) {
    +                existingAssignment = new HashMap<>();
    +            }
    +
    +            Map<Integer, LocalAssignment> allAssignment =
    +                    readAssignments(assignmentsSnapshot, existingAssignment, supervisorData.getAssignmentId(), supervisorData.getSyncRetry());
    +
    +            Map<Integer, LocalAssignment> newAssignment = new HashMap<>();
    +            Set<String> assignedStormIds = new HashSet<>();
    +
    +            for (Map.Entry<Integer, LocalAssignment> entry : allAssignment.entrySet()) {
    +                if (supervisorData.getiSupervisor().confirmAssigned(entry.getKey())) {
    +                    newAssignment.put(entry.getKey(), entry.getValue());
    +                    assignedStormIds.add(entry.getValue().get_topology_id());
    +                }
    +            }
    +
    +            Set<String> srashStormIds = verifyDownloadedFiles(conf, supervisorData.getLocalizer(), assignedStormIds, allDownloadedTopologyIds);
    +            Set<String> downloadedStormIds = new HashSet<>();
    +            downloadedStormIds.addAll(allDownloadedTopologyIds);
    +            downloadedStormIds.removeAll(srashStormIds);
    +
    +            LOG.debug("Synchronizing supervisor");
    +            LOG.debug("Storm code map: {}", stormcodeMap);
    +            LOG.debug("All assignment: {}", allAssignment);
    +            LOG.debug("New assignment: {}", newAssignment);
    +            LOG.debug("Assigned Storm Ids {}", assignedStormIds);
    +            LOG.debug("All Downloaded Ids {}", allDownloadedTopologyIds);
    +            LOG.debug("Checked Downloaded Ids {}", srashStormIds);
    +            LOG.debug("Downloaded Ids {}", downloadedStormIds);
    +            LOG.debug("Storm Ids Profiler Actions {}", stormIdToProfilerActions);
    +
    +            // download code first
    +            // This might take awhile
    +            // - should this be done separately from usual monitoring?
    +            // should we only download when topology is assigned to this supervisor?
    +            for (Map.Entry<String, String> entry : stormcodeMap.entrySet()) {
    +                String stormId = entry.getKey();
    +                if (!downloadedStormIds.contains(stormId) && assignedStormIds.contains(stormId)) {
    +                    LOG.info("Downloading code for storm id {}.", stormId);
    +                    try {
    +                        downloadStormCode(conf, stormId, entry.getValue(), supervisorData.getLocalizer());
    +                    } catch (Exception e) {
    +                        if (Utils.exceptionCauseIsInstanceOf(NimbusLeaderNotFoundException.class, e)) {
    +                            LOG.warn("Nimbus leader was not available.", e);
    +                        } else if (Utils.exceptionCauseIsInstanceOf(TTransportException.class, e)) {
    +                            LOG.warn("There was a connection problem with nimbus.", e);
    +                        } else {
    +                            throw e;
    +                        }
    +                    }
    +                    LOG.info("Finished downloading code for storm id {}", stormId);
    +                }
    +            }
    +
    +            LOG.debug("Writing new assignment {}", newAssignment);
    +
    +            Set<Integer> killWorkers = new HashSet<>();
    +            killWorkers.addAll(existingAssignment.keySet());
    +            killWorkers.removeAll(newAssignment.keySet());
    +            for (Integer port : killWorkers) {
    +                supervisorData.getiSupervisor().killedWorker(port);
    +            }
    +
    +            killExistingWorkersWithChangeInComponents(supervisorData, existingAssignment, newAssignment);
    +
    +            supervisorData.getiSupervisor().assigned(newAssignment.keySet());
    +            localState.setLocalAssignmentsMap(newAssignment);
    +            supervisorData.setAssignmentVersions(assignmentsSnapshot);
    +            supervisorData.setStormIdToProfileActions(stormIdToProfilerActions);
    +
    +            Map<Long, LocalAssignment> convertNewAssignment = new HashMap<>();
    +            for (Map.Entry<Integer, LocalAssignment> entry : newAssignment.entrySet()) {
    +                convertNewAssignment.put(entry.getKey().longValue(), entry.getValue());
    +            }
    +            supervisorData.setCurrAssignment(convertNewAssignment);
    +            // remove any downloaded code that's no longer assigned or active
    +            // important that this happens after setting the local assignment so that
    +            // synchronize-supervisor doesn't try to launch workers for which the
    +            // resources don't exist
    +            if (Utils.isOnWindows()) {
    +                shutdownDisallowedWorkers();
    +            }
    +            for (String stormId : allDownloadedTopologyIds) {
    +                if (!stormcodeMap.containsKey(stormId)) {
    +                    LOG.info("Removing code for storm id {}.", stormId);
    +                    rmTopoFiles(conf, stormId, supervisorData.getLocalizer(), true);
    +                }
    +            }
    +            syncProcessManager.add(syncProcesses);
    +        } catch (Exception e) {
    +            LOG.error("Failed to Sync Supervisor", e);
    +            throw new RuntimeException(e);
    +        }
    +
    +    }
    +
    +    private void killExistingWorkersWithChangeInComponents(SupervisorData supervisorData, Map<Integer, LocalAssignment> existingAssignment,
    +            Map<Integer, LocalAssignment> newAssignment) throws Exception {
    +        LocalState localState = supervisorData.getLocalState();
    +        Map<Integer, LocalAssignment> assignedExecutors = localState.getLocalAssignmentsMap();
    +        if (assignedExecutors == null) {
    +            assignedExecutors = new HashMap<>();
    +        }
    +        int now = Time.currentTimeSecs();
    +        Map<String, StateHeartbeat> workerIdHbstate = syncProcesses.getLocalWorkerStats(supervisorData, assignedExecutors, now);
    +        Map<Integer, String> vaildPortToWorkerIds = new HashMap<>();
    +        for (Map.Entry<String, StateHeartbeat> entry : workerIdHbstate.entrySet()) {
    +            String workerId = entry.getKey();
    +            StateHeartbeat stateHeartbeat = entry.getValue();
    +            if (stateHeartbeat != null && stateHeartbeat.getState() == State.VALID) {
    +                vaildPortToWorkerIds.put(stateHeartbeat.getHeartbeat().get_port(), workerId);
    +            }
    +        }
    +
    +        Map<Integer, LocalAssignment> intersectAssignment = new HashMap<>();
    +        for (Map.Entry<Integer, LocalAssignment> entry : newAssignment.entrySet()) {
    +            Integer port = entry.getKey();
    +            if (existingAssignment.containsKey(port)) {
    +                intersectAssignment.put(port, entry.getValue());
    +            }
    +        }
    +
    +        for (Integer port : intersectAssignment.keySet()) {
    +            List<ExecutorInfo> existExecutors = existingAssignment.get(port).get_executors();
    +            List<ExecutorInfo> newExecutors = newAssignment.get(port).get_executors();
    +            if (newExecutors.size() != existExecutors.size()) {
    --- End diff --
    
    I think this logic will work just wasn't clear 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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55963334
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncProcessEvent.java ---
    @@ -0,0 +1,672 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.ExecutorInfo;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.WorkerResources;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +import org.yaml.snakeyaml.Yaml;
    +
    +import java.io.File;
    +import java.io.FileWriter;
    +import java.io.IOException;
    +import java.util.*;
    +
    +/**
    + * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file - rmr
    + * heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new worker
    + * ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait for workers
    + * launch
    + */
    +public class SyncProcessEvent implements Runnable {
    +
    +    private static Logger LOG = LoggerFactory.getLogger(SyncProcessEvent.class);
    +
    +    private  LocalState localState;
    +    private  SupervisorData supervisorData;
    +    public static final ExecutorInfo SYSTEM_EXECUTOR_INFO = new ExecutorInfo(-1, -1);
    +
    +    private class ProcessExitCallback implements Utils.ExitCodeCallable {
    +        private final String logPrefix;
    +        private final String workerId;
    +
    +        public ProcessExitCallback(String logPrefix, String workerId) {
    +            this.logPrefix = logPrefix;
    +            this.workerId = workerId;
    +        }
    +
    +        @Override
    +        public Object call() throws Exception {
    +            return null;
    +        }
    +
    +        @Override
    +        public Object call(int exitCode) {
    +            LOG.info("{} exited with code: {}", logPrefix, exitCode);
    +            supervisorData.getDeadWorkers().add(workerId);
    +            return null;
    +        }
    +    }
    +
    +    public SyncProcessEvent(){
    +
    +    }
    +    public SyncProcessEvent(SupervisorData supervisorData) {
    +        init(supervisorData);
    +    }
    +
    +    //TODO: initData is intended to local supervisor, so we will remove them after porting worker.clj to java
    +    public void init(SupervisorData supervisorData){
    +        this.supervisorData = supervisorData;
    +        this.localState = supervisorData.getLocalState();
    +    }
    +
    +
    +    /**
    +     * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file -
    +     * rmr heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new
    +     * worker ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait
    +     * for workers launch
    +     */
    +    @Override
    +    public void run() {
    +        LOG.debug("Syncing processes");
    +        try {
    +            Map conf = supervisorData.getConf();
    +            Map<Integer, LocalAssignment> assignedExecutors = localState.getLocalAssignmentsMap();
    +
    +            if (assignedExecutors == null) {
    +                assignedExecutors = new HashMap<>();
    +            }
    +            int now = Time.currentTimeSecs();
    +
    +            Map<String, StateHeartbeat> localWorkerStats = getLocalWorkerStats(supervisorData, assignedExecutors, now);
    +
    +            Set<String> keeperWorkerIds = new HashSet<>();
    +            Set<Integer> keepPorts = new HashSet<>();
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() == State.VALID) {
    +                    keeperWorkerIds.add(entry.getKey());
    +                    keepPorts.add(stateHeartbeat.getHeartbeat().get_port());
    +                }
    +            }
    +            Map<Integer, LocalAssignment> reassignExecutors = getReassignExecutors(assignedExecutors, keepPorts);
    +            Map<Integer, String> newWorkerIds = new HashMap<>();
    +            for (Integer port : reassignExecutors.keySet()) {
    +                newWorkerIds.put(port, Utils.uuid());
    +            }
    +            LOG.debug("Syncing processes");
    +            LOG.debug("Assigned executors: {}", assignedExecutors);
    +            LOG.debug("Allocated: {}", localWorkerStats);
    +
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() != State.VALID) {
    +                    LOG.info("Shutting down and clearing state for id {}, Current supervisor time: {}, State: {}, Heartbeat: {}", entry.getKey(), now,
    +                            stateHeartbeat.getState(), stateHeartbeat.getHeartbeat());
    +                    shutWorker(supervisorData, entry.getKey());
    +                }
    +            }
    +            // start new workers
    +            Map<String, Integer> newWorkerPortToIds = startNewWorkers(newWorkerIds, reassignExecutors);
    +
    +            Map<String, Integer> allWorkerPortToIds = new HashMap<>();
    +            Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +            for (String keeper : keeperWorkerIds) {
    +                allWorkerPortToIds.put(keeper, approvedWorkers.get(keeper));
    +            }
    +            allWorkerPortToIds.putAll(newWorkerPortToIds);
    +            localState.setApprovedWorkers(allWorkerPortToIds);
    +            waitForWorkersLaunch(conf, newWorkerPortToIds.keySet());
    +
    +        } catch (Exception e) {
    +            LOG.error("Failed Sync Process", e);
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +    }
    +
    +    protected void waitForWorkersLaunch(Map conf, Set<String> workerIds) throws Exception {
    +        int startTime = Time.currentTimeSecs();
    +        int timeOut = (int) conf.get(Config.NIMBUS_SUPERVISOR_TIMEOUT_SECS);
    +        for (String workerId : workerIds) {
    +            LocalState localState = ConfigUtils.workerState(conf, workerId);
    +            while (true) {
    +                LSWorkerHeartbeat hb = localState.getWorkerHeartBeat();
    +                if (hb != null || (Time.currentTimeSecs() - startTime) > timeOut)
    +                    break;
    +                LOG.info("{} still hasn't started", workerId);
    +                Time.sleep(500);
    +            }
    +            if (localState.getWorkerHeartBeat() == null) {
    +                LOG.info("Worker {} failed to start", workerId);
    +            }
    +        }
    +    }
    +
    +    protected Map<Integer, LocalAssignment> getReassignExecutors(Map<Integer, LocalAssignment> assignExecutors, Set<Integer> keepPorts) {
    +        Map<Integer, LocalAssignment> reassignExecutors = new HashMap<>();
    +        reassignExecutors.putAll(assignExecutors);
    +        for (Integer port : keepPorts) {
    +            reassignExecutors.remove(port);
    +        }
    +        return reassignExecutors;
    +    }
    +    
    +    /**
    +     * Returns map from worker id to worker heartbeat. if the heartbeat is nil, then the worker is dead
    +     * 
    +     * @param assignedExecutors
    +     * @return
    +     * @throws Exception
    +     */
    +    public Map<String, StateHeartbeat> getLocalWorkerStats(SupervisorData supervisorData, Map<Integer, LocalAssignment> assignedExecutors, int now) throws Exception {
    +        Map<String, StateHeartbeat> workerIdHbstate = new HashMap<>();
    +        Map conf = supervisorData.getConf();
    +        LocalState localState = supervisorData.getLocalState();
    +        Map<String, LSWorkerHeartbeat> idToHeartbeat = SupervisorUtils.readWorkerHeartbeats(conf);
    +        Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +        Set<String> approvedIds = new HashSet<>();
    +        if (approvedWorkers != null) {
    +            approvedIds.addAll(approvedWorkers.keySet());
    +        }
    +        for (Map.Entry<String, LSWorkerHeartbeat> entry : idToHeartbeat.entrySet()) {
    +            String workerId = entry.getKey();
    +            LSWorkerHeartbeat whb = entry.getValue();
    +            State state;
    +            if (whb == null) {
    +                state = State.NOT_STARTED;
    +            } else if (!approvedIds.contains(workerId) || !matchesAssignment(whb, assignedExecutors)) {
    +                state = State.DISALLOWED;
    +            } else if (supervisorData.getDeadWorkers().contains(workerId)) {
    +                LOG.info("Worker Process {} has died", workerId);
    +                state = State.TIMED_OUT;
    +            } else if (SupervisorUtils.isWorkerHbTimedOut(now, whb, conf)) {
    +                state = State.TIMED_OUT;
    +            } else {
    +                state = State.VALID;
    +            }
    +            LOG.debug("Worker:{} state:{} WorkerHeartbeat:{} at supervisor time-secs {}", workerId, state, whb, now);
    +            workerIdHbstate.put(workerId, new StateHeartbeat(state, whb));
    +        }
    +        return workerIdHbstate;
    +    }
    +
    +    protected boolean matchesAssignment(LSWorkerHeartbeat whb, Map<Integer, LocalAssignment> assignedExecutors) {
    +        LocalAssignment localAssignment = assignedExecutors.get(whb.get_port());
    +        if (localAssignment == null || !localAssignment.get_topology_id().equals(whb.get_topology_id())) {
    +            return false;
    +        }
    +        List<ExecutorInfo> executorInfos = new ArrayList<>();
    +        executorInfos.addAll(whb.get_executors());
    +        // remove SYSTEM_EXECUTOR_ID
    +        executorInfos.remove(SYSTEM_EXECUTOR_INFO);
    +        List<ExecutorInfo> localExecuorInfos = localAssignment.get_executors();
    +
    +        if (localExecuorInfos.size() != executorInfos.size())
    +            return false;
    +
    +        for (ExecutorInfo executorInfo : localExecuorInfos){
    +            if (!localExecuorInfos.contains(executorInfo))
    +                return false;
    +        }
    +        return true;
    +    }
    +
    +    /**
    +     * launch a worker in local mode.
    +     */
    +    protected void launchWorker(SupervisorData supervisorData, String stormId, Long port, String workerId, WorkerResources resources) throws IOException {
    +        // port this function after porting worker to java
    +    }
    +
    +    protected String getWorkerClassPath(String stormJar, Map stormConf) {
    +        List<String> topoClasspath = new ArrayList<>();
    +        Object object = stormConf.get(Config.TOPOLOGY_CLASSPATH);
    +
    +        if (object instanceof List) {
    +            topoClasspath.addAll((List<String>) object);
    +        } else if (object instanceof String){
    +            topoClasspath.add((String)object);
    +        }else {
    +            //ignore
    +        }
    +        String classPath = Utils.workerClasspath();
    +        String classAddPath = Utils.addToClasspath(classPath, Arrays.asList(stormJar));
    +        return Utils.addToClasspath(classAddPath, topoClasspath);
    +    }
    +
    +    /**
    +     * "Generates runtime childopts by replacing keys with topology-id, worker-id, port, mem-onheap"
    +     * 
    +     * @param value
    +     * @param workerId
    +     * @param stormId
    +     * @param port
    +     * @param memOnheap
    +     */
    +    public List<String> substituteChildopts(Object value, String workerId, String stormId, Long port, int memOnheap) {
    +        List<String> rets = new ArrayList<>();
    +        if (value instanceof String) {
    +            String string = (String) value;
    +            string = string.replace("%ID%", String.valueOf(port));
    +            string = string.replace("%WORKER-ID%", workerId);
    +            string = string.replace("%TOPOLOGY-ID%", stormId);
    +            string = string.replace("%WORKER-PORT%", String.valueOf(port));
    +            string = string.replace("%HEAP-MEM%", String.valueOf(memOnheap));
    +            String[] strings = string.split("\\s+");
    +            rets.addAll(Arrays.asList(strings));
    +        } else if (value instanceof List) {
    +            List<Object> objects = (List<Object>) value;
    +            for (Object object : objects) {
    +                String str = (String)object;
    +                str = str.replace("%ID%", String.valueOf(port));
    +                str = str.replace("%WORKER-ID%", workerId);
    +                str = str.replace("%TOPOLOGY-ID%", stormId);
    +                str = str.replace("%WORKER-PORT%", String.valueOf(port));
    +                str = str.replace("%HEAP-MEM%", String.valueOf(memOnheap));
    +                rets.add(str);
    +            }
    +        }
    +        return rets;
    +    }
    +
    +
    +
    +    /**
    +     * launch a worker in distributed mode
    +     * supervisorId for testing
    +     * @throws IOException
    +     */
    +    protected void launchWorker(Map conf, String supervisorId, String assignmentId, String stormId, Long port, String workerId,
    +            WorkerResources resources, CgroupManager cgroupManager, ConcurrentHashSet deadWorkers) throws IOException {
    +
    +        Boolean runWorkerAsUser = Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false);
    +        String stormHome = ConfigUtils.concatIfNotNull(System.getProperty("storm.home"));
    +        String stormOptions = ConfigUtils.concatIfNotNull(System.getProperty("storm.options"));
    +        String stormConfFile = ConfigUtils.concatIfNotNull(System.getProperty("storm.conf.file"));
    +        String workerTmpDir = ConfigUtils.workerTmpRoot(conf, workerId);
    +
    +        String stormLogDir = ConfigUtils.getLogDir();
    +        String stormLogConfDir = (String) (conf.get(Config.STORM_LOG4J2_CONF_DIR));
    +
    +        String stormLog4j2ConfDir;
    +        if (StringUtils.isNotBlank(stormLogConfDir)) {
    +            if (Utils.isAbsolutePath(stormLogConfDir)) {
    +                stormLog4j2ConfDir = stormLogConfDir;
    +            } else {
    +                stormLog4j2ConfDir = stormHome + Utils.FILE_PATH_SEPARATOR + stormLogConfDir;
    +            }
    +        } else {
    +            stormLog4j2ConfDir = stormHome + Utils.FILE_PATH_SEPARATOR + "log4j2";
    +        }
    +
    +        String stormRoot = ConfigUtils.supervisorStormDistRoot(conf, stormId);
    +
    +        String jlp = jlp(stormRoot, conf);
    +
    +        String stormJar = ConfigUtils.supervisorStormJarPath(stormRoot);
    +
    +        Map stormConf = ConfigUtils.readSupervisorStormConf(conf, stormId);
    +
    +        String workerClassPath = getWorkerClassPath(stormJar, stormConf);
    +
    +        Object topGcOptsObject = stormConf.get(Config.TOPOLOGY_WORKER_GC_CHILDOPTS);
    +        List<String> topGcOpts = new ArrayList<>();
    +        if (topGcOptsObject instanceof String) {
    +            topGcOpts.add((String) topGcOptsObject);
    +        } else if (topGcOptsObject instanceof List) {
    +            topGcOpts.addAll((List<String>) topGcOptsObject);
    +        }
    +
    +        int memOnheap = 0;
    +        if (resources.get_mem_on_heap() > 0) {
    +            memOnheap = (int) Math.ceil(resources.get_mem_on_heap());
    +        } else {
    +            //set the default heap memory size for supervisor-test
    +            memOnheap = Utils.getInt(stormConf.get(Config.WORKER_HEAP_MEMORY_MB), 768);
    +        }
    +
    +        int memoffheap = (int) Math.ceil(resources.get_mem_off_heap());
    +
    +        int cpu = (int) Math.ceil(resources.get_cpu());
    +
    +        List<String> gcOpts = null;
    +
    +        if (topGcOpts != null) {
    +            gcOpts = substituteChildopts(topGcOpts, workerId, stormId, port, memOnheap);
    +        } else {
    +            gcOpts = substituteChildopts(conf.get(Config.WORKER_GC_CHILDOPTS), workerId, stormId, port, memOnheap);
    +        }
    +
    +        Object topoWorkerLogwriterObject = stormConf.get(Config.TOPOLOGY_WORKER_LOGWRITER_CHILDOPTS);
    +        List<String> topoWorkerLogwriterChildopts = new ArrayList<>();
    +        if (topoWorkerLogwriterObject instanceof String) {
    +            topoWorkerLogwriterChildopts.add((String) topoWorkerLogwriterObject);
    +        } else if (topoWorkerLogwriterObject instanceof List) {
    +            topoWorkerLogwriterChildopts.addAll((List<String>) topoWorkerLogwriterObject);
    +        }
    +
    +        String user = (String) stormConf.get(Config.TOPOLOGY_SUBMITTER_USER);
    +
    +        String logfileName = "worker.log";
    +
    +        String workersArtifacets = ConfigUtils.workerArtifactsRoot(conf);
    +
    +        String loggingSensitivity = (String) stormConf.get(Config.TOPOLOGY_LOGGING_SENSITIVITY);
    +        if (loggingSensitivity == null) {
    +            loggingSensitivity = "S3";
    +        }
    +
    +        List<String> workerChildopts = substituteChildopts(conf.get(Config.WORKER_CHILDOPTS), workerId, stormId, port, memOnheap);
    +
    +        List<String> topWorkerChildopts = substituteChildopts(stormConf.get(Config.TOPOLOGY_WORKER_CHILDOPTS), workerId, stormId, port, memOnheap);
    +
    +        List<String> workerProfilerChildopts = null;
    +        if (Utils.getBoolean(conf.get(Config.WORKER_PROFILER_ENABLED), false)) {
    +            workerProfilerChildopts = substituteChildopts(conf.get(Config.WORKER_PROFILER_CHILDOPTS), workerId, stormId, port, memOnheap);
    +        }else {
    +            workerProfilerChildopts = new ArrayList<>();
    +        }
    +
    +        Map<String, String> topEnvironment = new HashMap<String, String>();
    +        Map<String, String> environment = (Map<String, String>) stormConf.get(Config.TOPOLOGY_ENVIRONMENT);
    +        if (environment != null) {
    +            topEnvironment.putAll(environment);
    +        }
    +        topEnvironment.put("LD_LIBRARY_PATH", jlp);
    +
    +        String log4jConfigurationFile = null;
    +        if (System.getProperty("os.name").startsWith("Windows") && !stormLog4j2ConfDir.startsWith("file:")) {
    +            log4jConfigurationFile = "file:///" + stormLog4j2ConfDir;
    +        } else {
    +            log4jConfigurationFile = stormLog4j2ConfDir;
    +        }
    +        log4jConfigurationFile = log4jConfigurationFile + Utils.FILE_PATH_SEPARATOR + "worker.xml";
    +
    +        List<String> commandList = new ArrayList<>();
    +        commandList.add(SupervisorUtils.javaCmd("java"));
    +        commandList.add("-cp");
    +        commandList.add(workerClassPath);
    +        commandList.addAll(topoWorkerLogwriterChildopts);
    +        commandList.add("-Dlogfile.name=" + logfileName);
    +        commandList.add("-Dstorm.home=" + stormHome);
    +        commandList.add("-Dworkers.artifacts=" + workersArtifacets);
    +        commandList.add("-Dstorm.id=" + stormId);
    +        commandList.add("-Dworker.id=" + workerId);
    +        commandList.add("-Dworker.port=" + port);
    +        commandList.add("-Dstorm.log.dir=" + stormLogDir);
    +        commandList.add("-Dlog4j.configurationFile=" + log4jConfigurationFile);
    +        commandList.add("-DLog4jContextSelector=org.apache.logging.log4j.core.selector.BasicContextSelector");
    +        commandList.add("org.apache.storm.LogWriter");
    +
    +        commandList.add(SupervisorUtils.javaCmd("java"));
    +        commandList.add("-server");
    +        commandList.addAll(workerChildopts);
    +        commandList.addAll(topWorkerChildopts);
    +        commandList.addAll(gcOpts);
    +        commandList.addAll(workerProfilerChildopts);
    +        commandList.add("-Djava.library.path=" + jlp);
    +        commandList.add("-Dlogfile.name=" + logfileName);
    +        commandList.add("-Dstorm.home=" + stormHome);
    +        commandList.add("-Dworkers.artifacts=" + workersArtifacets);
    +        commandList.add("-Dstorm.conf.file=" + stormConfFile);
    +        commandList.add("-Dstorm.options=" + stormOptions);
    +        commandList.add("-Dstorm.log.dir=" + stormLogDir);
    +        commandList.add("-Djava.io.tmpdir=" + workerTmpDir);
    +        commandList.add("-Dlogging.sensitivity=" + loggingSensitivity);
    +        commandList.add("-Dlog4j.configurationFile=" + log4jConfigurationFile);
    +        commandList.add("-DLog4jContextSelector=org.apache.logging.log4j.core.selector.BasicContextSelector");
    +        commandList.add("-Dstorm.id=" + stormId);
    +        commandList.add("-Dworker.id=" + workerId);
    +        commandList.add("-Dworker.port=" + port);
    +        commandList.add("-cp");
    +        commandList.add(workerClassPath);
    +        commandList.add("org.apache.storm.daemon.worker");
    +        commandList.add(stormId);
    +        commandList.add(assignmentId);
    +        commandList.add(String.valueOf(port));
    +        commandList.add(workerId);
    +
    +        // {"cpu" cpu "memory" (+ mem-onheap mem-offheap (int (Math/ceil (conf STORM-CGROUP-MEMORY-LIMIT-TOLERANCE-MARGIN-MB))))
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            int cgRoupMem = (int) (Math.ceil((double) conf.get(Config.STORM_CGROUP_MEMORY_LIMIT_TOLERANCE_MARGIN_MB)));
    --- End diff --
    
    nit. you can rename the variable to cGroupMem


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55584436
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorData.java ---
    @@ -0,0 +1,339 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.cluster.ClusterStateContext;
    +import org.apache.storm.cluster.ClusterUtils;
    +import org.apache.storm.cluster.DaemonType;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.ProfileRequest;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +import java.net.UnknownHostException;
    +import java.util.ArrayList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.concurrent.ConcurrentHashMap;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SupervisorData {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorData.class);
    +
    +    private Map conf;
    +    private IContext sharedContext;
    +    private volatile boolean active;
    +    private ISupervisor iSupervisor;
    +    private Utils.UptimeComputer upTime;
    +    private String stormVersion;
    +
    +    private ConcurrentHashMap<String, String> workerThreadPidsAtom; // for local mode
    +
    +    private IStormClusterState stormClusterState;
    +
    +    private LocalState localState;
    +
    +    private String supervisorId;
    +
    +    private String assignmentId;
    +
    +    private String hostName;
    +
    +    // used for reporting used ports when heartbeating
    +    private ConcurrentHashMap<Long, LocalAssignment> currAssignment;
    +
    +    private StormTimer heartbeatTimer;
    +
    +    private StormTimer eventTimer;
    +
    +    private StormTimer blobUpdateTimer;
    +
    +    private Localizer localizer;
    +
    +    private ConcurrentHashMap<String, Map<String, Object>> assignmentVersions;
    +
    +    private AtomicInteger syncRetry;
    +
    +    private final Object downloadLock = new Object();
    +
    +    private ConcurrentHashMap<String, List<ProfileRequest>> stormIdToProfileActions;
    +
    +    private CgroupManager resourceIsolationManager;
    +
    +    private ConcurrentHashSet<String> deadWorkers;
    +
    +    public SupervisorData(Map conf, IContext sharedContext, ISupervisor iSupervisor) {
    +        this.conf = conf;
    +        this.sharedContext = sharedContext;
    +        this.iSupervisor = iSupervisor;
    +        this.active = true;
    +        this.upTime = Utils.makeUptimeComputer();
    +        this.stormVersion = VersionInfo.getVersion();
    +        this.workerThreadPidsAtom = new ConcurrentHashMap<String, String>();
    +        this.deadWorkers = new ConcurrentHashSet();
    +
    +        List<ACL> acls = null;
    +        if (Utils.isZkAuthenticationConfiguredStormServer(conf)) {
    +            acls = SupervisorUtils.supervisorZkAcls();
    +        }
    +
    +        try {
    +            this.stormClusterState = ClusterUtils.mkStormClusterState(conf, acls, new ClusterStateContext(DaemonType.SUPERVISOR));
    +        } catch (Exception e) {
    +            LOG.error("supervisor can't create stormClusterState");
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        try {
    +            this.localState = ConfigUtils.supervisorState(conf);
    +            this.localizer = Utils.createLocalizer(conf, ConfigUtils.supervisorLocalDir(conf));
    +        } catch (IOException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +        this.supervisorId = iSupervisor.getSupervisorId();
    +        this.assignmentId = iSupervisor.getAssignmentId();
    +
    +        try {
    +            this.hostName = Utils.hostname(conf);
    +        } catch (UnknownHostException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        this.currAssignment = new ConcurrentHashMap<>();
    +
    +        this.heartbeatTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.eventTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.blobUpdateTimer = new StormTimer("blob-update-timer", new DefaultUncaughtExceptionHandler());
    +
    +        this.assignmentVersions = new ConcurrentHashMap<>();
    +        this.syncRetry = new AtomicInteger(0);
    +        this.stormIdToProfileActions = new ConcurrentHashMap<>();
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            try {
    +                this.resourceIsolationManager = (CgroupManager) Utils.newInstance((String) conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN));
    +                this.resourceIsolationManager.prepare(conf);
    +                LOG.info("Using resource isolation plugin {} {}", conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN), resourceIsolationManager);
    +            } catch (IOException e) {
    +                throw Utils.wrapInRuntime(e);
    +            }
    +        } else {
    +            this.resourceIsolationManager = null;
    +        }
    +    }
    +
    +    public ConcurrentHashMap<String, List<ProfileRequest>> getStormIdToProfileActions() {
    +        return stormIdToProfileActions;
    +    }
    +
    +    public void setStormIdToProfileActions(Map<String, List<ProfileRequest>> stormIdToProfileActions) {
    +        this.stormIdToProfileActions.clear();
    +        this.stormIdToProfileActions.putAll(stormIdToProfileActions);
    +    }
    +
    +    public Map getConf() {
    +        return conf;
    +    }
    +
    +    public void setConf(Map conf) {
    +        this.conf = conf;
    +    }
    +
    +    public IContext getSharedContext() {
    +        return sharedContext;
    +    }
    +
    +    public void setSharedContext(IContext sharedContext) {
    +        this.sharedContext = sharedContext;
    +    }
    +
    +    public boolean isActive() {
    +        return active;
    +    }
    +
    +    public void setActive(boolean active) {
    +        this.active = active;
    +    }
    +
    +    public ISupervisor getiSupervisor() {
    +        return iSupervisor;
    +    }
    +
    +    public void setiSupervisor(ISupervisor iSupervisor) {
    +        this.iSupervisor = iSupervisor;
    +    }
    +
    +    public Utils.UptimeComputer getUpTime() {
    +        return upTime;
    +    }
    +
    +    public void setUpTime(Utils.UptimeComputer upTime) {
    --- End diff --
    
    Not used.


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r57171985
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncSupervisorEvent.java ---
    @@ -0,0 +1,632 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.blobstore.BlobStore;
    +import org.apache.storm.blobstore.ClientBlobStore;
    +import org.apache.storm.cluster.IStateStorage;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.event.EventManager;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.localizer.LocalResource;
    +import org.apache.storm.localizer.LocalizedResource;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.utils.*;
    +import org.apache.thrift.transport.TTransportException;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.FileOutputStream;
    +import java.io.IOException;
    +import java.net.JarURLConnection;
    +import java.net.URL;
    +import java.nio.file.Files;
    +import java.nio.file.StandardCopyOption;
    +import java.util.*;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SyncSupervisorEvent implements Runnable {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SyncSupervisorEvent.class);
    +
    +    private EventManager syncSupEventManager;
    +    private EventManager syncProcessManager;
    +    private IStormClusterState stormClusterState;
    +    private LocalState localState;
    +    private SyncProcessEvent syncProcesses;
    +    private SupervisorData supervisorData;
    +
    +    public SyncSupervisorEvent(SupervisorData supervisorData, SyncProcessEvent syncProcesses, EventManager syncSupEventManager,
    +            EventManager syncProcessManager) {
    +
    +        this.syncProcesses = syncProcesses;
    +        this.syncSupEventManager = syncSupEventManager;
    +        this.syncProcessManager = syncProcessManager;
    +        this.stormClusterState = supervisorData.getStormClusterState();
    +        this.localState = supervisorData.getLocalState();
    +        this.supervisorData = supervisorData;
    +    }
    +
    +    @Override
    +    public void run() {
    +        try {
    +            Map conf = supervisorData.getConf();
    +            Runnable syncCallback = new EventManagerPushCallback(this, syncSupEventManager);
    +            List<String> stormIds = stormClusterState.assignments(syncCallback);
    +            Map<String, Map<String, Object>> assignmentsSnapshot =
    +                    getAssignmentsSnapshot(stormClusterState, stormIds, supervisorData.getAssignmentVersions().get(), syncCallback);
    +            Map<String, List<ProfileRequest>> stormIdToProfilerActions = getProfileActions(stormClusterState, stormIds);
    +
    +            Set<String> allDownloadedTopologyIds = SupervisorUtils.readDownLoadedStormIds(conf);
    +            Map<String, String> stormcodeMap = readStormCodeLocations(assignmentsSnapshot);
    +            Map<Integer, LocalAssignment> existingAssignment = localState.getLocalAssignmentsMap();
    +            if (existingAssignment == null) {
    +                existingAssignment = new HashMap<>();
    +            }
    +
    +            Map<Integer, LocalAssignment> allAssignment =
    +                    readAssignments(assignmentsSnapshot, existingAssignment, supervisorData.getAssignmentId(), supervisorData.getSyncRetry());
    +
    +            Map<Integer, LocalAssignment> newAssignment = new HashMap<>();
    +            Set<String> assignedStormIds = new HashSet<>();
    +
    +            for (Map.Entry<Integer, LocalAssignment> entry : allAssignment.entrySet()) {
    +                if (supervisorData.getiSupervisor().confirmAssigned(entry.getKey())) {
    +                    newAssignment.put(entry.getKey(), entry.getValue());
    +                    assignedStormIds.add(entry.getValue().get_topology_id());
    +                }
    +            }
    +
    +            Set<String> srashStormIds = verifyDownloadedFiles(conf, supervisorData.getLocalizer(), assignedStormIds, allDownloadedTopologyIds);
    +            Set<String> downloadedStormIds = new HashSet<>();
    +            downloadedStormIds.addAll(allDownloadedTopologyIds);
    +            downloadedStormIds.removeAll(srashStormIds);
    +
    +            LOG.debug("Synchronizing supervisor");
    +            LOG.debug("Storm code map: {}", stormcodeMap);
    +            LOG.debug("All assignment: {}", allAssignment);
    +            LOG.debug("New assignment: {}", newAssignment);
    +            LOG.debug("Assigned Storm Ids {}", assignedStormIds);
    +            LOG.debug("All Downloaded Ids {}", allDownloadedTopologyIds);
    +            LOG.debug("Checked Downloaded Ids {}", srashStormIds);
    +            LOG.debug("Downloaded Ids {}", downloadedStormIds);
    +            LOG.debug("Storm Ids Profiler Actions {}", stormIdToProfilerActions);
    +
    +            // download code first
    +            // This might take awhile
    +            // - should this be done separately from usual monitoring?
    +            // should we only download when topology is assigned to this supervisor?
    +            for (Map.Entry<String, String> entry : stormcodeMap.entrySet()) {
    +                String stormId = entry.getKey();
    +                if (!downloadedStormIds.contains(stormId) && assignedStormIds.contains(stormId)) {
    +                    LOG.info("Downloading code for storm id {}.", stormId);
    +                    try {
    +                        downloadStormCode(conf, stormId, entry.getValue(), supervisorData.getLocalizer());
    +                    } catch (Exception e) {
    +                        if (Utils.exceptionCauseIsInstanceOf(NimbusLeaderNotFoundException.class, e)) {
    +                            LOG.warn("Nimbus leader was not available.", e);
    +                        } else if (Utils.exceptionCauseIsInstanceOf(TTransportException.class, e)) {
    +                            LOG.warn("There was a connection problem with nimbus.", e);
    +                        } else {
    +                            throw e;
    +                        }
    +                    }
    +                    LOG.info("Finished downloading code for storm id {}", stormId);
    +                }
    +            }
    +
    +            LOG.debug("Writing new assignment {}", newAssignment);
    +
    +            Set<Integer> killWorkers = new HashSet<>();
    +            killWorkers.addAll(existingAssignment.keySet());
    +            killWorkers.removeAll(newAssignment.keySet());
    +            for (Integer port : killWorkers) {
    +                supervisorData.getiSupervisor().killedWorker(port);
    +            }
    +
    +            killExistingWorkersWithChangeInComponents(supervisorData, existingAssignment, newAssignment);
    +
    +            supervisorData.getiSupervisor().assigned(newAssignment.keySet());
    +            localState.setLocalAssignmentsMap(newAssignment);
    +            supervisorData.setAssignmentVersions(assignmentsSnapshot);
    +            supervisorData.setStormIdToProfileActions(stormIdToProfilerActions);
    +
    +            Map<Long, LocalAssignment> convertNewAssignment = new HashMap<>();
    +            for (Map.Entry<Integer, LocalAssignment> entry : newAssignment.entrySet()) {
    +                convertNewAssignment.put(entry.getKey().longValue(), entry.getValue());
    +            }
    +            supervisorData.setCurrAssignment(convertNewAssignment);
    +            // remove any downloaded code that's no longer assigned or active
    +            // important that this happens after setting the local assignment so that
    +            // synchronize-supervisor doesn't try to launch workers for which the
    +            // resources don't exist
    +            if (Utils.isOnWindows()) {
    +                shutdownDisallowedWorkers();
    +            }
    +            for (String stormId : allDownloadedTopologyIds) {
    +                if (!stormcodeMap.containsKey(stormId)) {
    +                    LOG.info("Removing code for storm id {}.", stormId);
    +                    rmTopoFiles(conf, stormId, supervisorData.getLocalizer(), true);
    +                }
    +            }
    +            syncProcessManager.add(syncProcesses);
    +        } catch (Exception e) {
    +            LOG.error("Failed to Sync Supervisor", e);
    +            throw new RuntimeException(e);
    +        }
    +
    +    }
    +
    +    private void killExistingWorkersWithChangeInComponents(SupervisorData supervisorData, Map<Integer, LocalAssignment> existingAssignment,
    +            Map<Integer, LocalAssignment> newAssignment) throws Exception {
    +        LocalState localState = supervisorData.getLocalState();
    +        Map<Integer, LocalAssignment> assignedExecutors = localState.getLocalAssignmentsMap();
    +        if (assignedExecutors == null) {
    +            assignedExecutors = new HashMap<>();
    +        }
    +        int now = Time.currentTimeSecs();
    +        Map<String, StateHeartbeat> workerIdHbstate = syncProcesses.getLocalWorkerStats(supervisorData, assignedExecutors, now);
    +        Map<Integer, String> vaildPortToWorkerIds = new HashMap<>();
    +        for (Map.Entry<String, StateHeartbeat> entry : workerIdHbstate.entrySet()) {
    +            String workerId = entry.getKey();
    +            StateHeartbeat stateHeartbeat = entry.getValue();
    +            if (stateHeartbeat != null && stateHeartbeat.getState() == State.VALID) {
    +                vaildPortToWorkerIds.put(stateHeartbeat.getHeartbeat().get_port(), workerId);
    +            }
    +        }
    +
    +        Map<Integer, LocalAssignment> intersectAssignment = new HashMap<>();
    +        for (Map.Entry<Integer, LocalAssignment> entry : newAssignment.entrySet()) {
    +            Integer port = entry.getKey();
    +            if (existingAssignment.containsKey(port)) {
    +                intersectAssignment.put(port, entry.getValue());
    +            }
    +        }
    +
    +        for (Integer port : intersectAssignment.keySet()) {
    +            List<ExecutorInfo> existExecutors = existingAssignment.get(port).get_executors();
    +            List<ExecutorInfo> newExecutors = newAssignment.get(port).get_executors();
    +            if (newExecutors.size() != existExecutors.size()) {
    --- End diff --
    
    @hustfxj did you also add the bug fix that was merged in STORM-1636?  If it is, the logic the check whether there is a scheduling change in a worker is not correct.  If there is not a scheduling change for a worker than the assignment for that executor will contain the same executors (regardless of ordering) as the "newAssignment".  Thus we are comparing two sets (without considering ordering) if they contain the same elements.


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55604560
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncProcessEvent.java ---
    @@ -0,0 +1,669 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.ExecutorInfo;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.WorkerResources;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +import org.yaml.snakeyaml.Yaml;
    +
    +import java.io.File;
    +import java.io.FileWriter;
    +import java.io.IOException;
    +import java.util.*;
    +
    +/**
    + * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file - rmr
    + * heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new worker
    + * ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait for workers
    + * launch
    + */
    +public class SyncProcessEvent extends ShutdownWork implements Runnable {
    +
    +    private static Logger LOG = LoggerFactory.getLogger(SyncProcessEvent.class);
    +
    +    private  LocalState localState;
    +
    +    private SupervisorData supervisorData;
    +
    +    private class ProcessExitCallback implements Utils.ExitCodeCallable {
    +        private final String logPrefix;
    +        private final String workerId;
    +
    +        public ProcessExitCallback(String logPrefix, String workerId) {
    +            this.logPrefix = logPrefix;
    +            this.workerId = workerId;
    +        }
    +
    +        @Override
    +        public Object call() throws Exception {
    +            return null;
    +        }
    +
    +        @Override
    +        public Object call(int exitCode) {
    +            LOG.info("{} exited with code: {}", logPrefix, exitCode);
    +            supervisorData.getDeadWorkers().add(workerId);
    +            return null;
    +        }
    +    }
    +
    +    public SyncProcessEvent(){
    +
    +    }
    +    public SyncProcessEvent(SupervisorData supervisorData) {
    +        init(supervisorData);
    +    }
    +
    +    //TODO: initData is intended to local supervisor, so we will remove them after porting worker.clj to java
    +    public void init(SupervisorData supervisorData){
    +        this.supervisorData = supervisorData;
    +        this.localState = supervisorData.getLocalState();
    +    }
    +
    +
    +    /**
    +     * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file -
    +     * rmr heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new
    +     * worker ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait
    +     * for workers launch
    +     */
    +    @Override
    +    public void run() {
    +        LOG.debug("Syncing processes");
    +        try {
    +            Map conf = supervisorData.getConf();
    +            Map<Integer, LocalAssignment> assignedExecutors = localState.getLocalAssignmentsMap();
    +
    +            if (assignedExecutors == null) {
    +                assignedExecutors = new HashMap<>();
    +            }
    +            int now = Time.currentTimeSecs();
    +
    +            Map<String, StateHeartbeat> localWorkerStats = getLocalWorkerStats(supervisorData, assignedExecutors, now);
    +
    +            Set<String> keeperWorkerIds = new HashSet<>();
    +            Set<Integer> keepPorts = new HashSet<>();
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() == State.valid) {
    +                    keeperWorkerIds.add(entry.getKey());
    +                    keepPorts.add(stateHeartbeat.getHeartbeat().get_port());
    +                }
    +            }
    +            Map<Integer, LocalAssignment> reassignExecutors = getReassignExecutors(assignedExecutors, keepPorts);
    +            Map<Integer, String> newWorkerIds = new HashMap<>();
    +            for (Integer port : reassignExecutors.keySet()) {
    +                newWorkerIds.put(port, Utils.uuid());
    +            }
    +            LOG.debug("Syncing processes");
    +            LOG.debug("Assigned executors: {}", assignedExecutors);
    +            LOG.debug("Allocated: {}", localWorkerStats);
    +
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() != State.valid) {
    +                    LOG.info("Shutting down and clearing state for id {}, Current supervisor time: {}, State: {}, Heartbeat: {}", entry.getKey(), now,
    +                            stateHeartbeat.getState(), stateHeartbeat.getHeartbeat());
    +                    shutWorker(supervisorData, entry.getKey());
    +                }
    +            }
    +            // start new workers
    +            Map<String, Integer> newWorkerPortToIds = startNewWorkers(newWorkerIds, reassignExecutors);
    +
    +            Map<String, Integer> allWorkerPortToIds = new HashMap<>();
    +            Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +            for (String keeper : keeperWorkerIds) {
    +                allWorkerPortToIds.put(keeper, approvedWorkers.get(keeper));
    +            }
    +            allWorkerPortToIds.putAll(newWorkerPortToIds);
    +            localState.setApprovedWorkers(allWorkerPortToIds);
    +            waitForWorkersLaunch(conf, newWorkerPortToIds.keySet());
    +
    +        } catch (Exception e) {
    +            LOG.error("Failed Sync Process", e);
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +    }
    +
    +    protected void waitForWorkersLaunch(Map conf, Set<String> workerIds) throws Exception {
    +        int startTime = Time.currentTimeSecs();
    +        int timeOut = (int) conf.get(Config.NIMBUS_SUPERVISOR_TIMEOUT_SECS);
    +        for (String workerId : workerIds) {
    +            LocalState localState = ConfigUtils.workerState(conf, workerId);
    +            while (true) {
    +                LSWorkerHeartbeat hb = localState.getWorkerHeartBeat();
    +                if (hb != null || (Time.currentTimeSecs() - startTime) > timeOut)
    +                    break;
    +                LOG.info("{} still hasn't started", workerId);
    +                Time.sleep(500);
    +            }
    +            if (localState.getWorkerHeartBeat() == null) {
    +                LOG.info("Worker {} failed to start", workerId);
    +            }
    +        }
    +    }
    +
    +    protected Map<Integer, LocalAssignment> getReassignExecutors(Map<Integer, LocalAssignment> assignExecutors, Set<Integer> keepPorts) {
    +        Map<Integer, LocalAssignment> reassignExecutors = new HashMap<>();
    +        reassignExecutors.putAll(assignExecutors);
    +        for (Integer port : keepPorts) {
    +            reassignExecutors.remove(port);
    +        }
    +        return reassignExecutors;
    +    }
    +
    +
    +
    +    /**
    +     * Returns map from worker id to worker heartbeat. if the heartbeat is nil, then the worker is dead
    +     * 
    +     * @param assignedExecutors
    +     * @return
    +     * @throws Exception
    +     */
    +    public Map<String, StateHeartbeat> getLocalWorkerStats(SupervisorData supervisorData, Map<Integer, LocalAssignment> assignedExecutors, int now) throws Exception {
    +        Map<String, StateHeartbeat> workerIdHbstate = new HashMap<>();
    +        Map conf = supervisorData.getConf();
    +        LocalState localState = supervisorData.getLocalState();
    +        Map<String, LSWorkerHeartbeat> idToHeartbeat = SupervisorUtils.readWorkerHeartbeats(conf);
    +        Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +        Set<String> approvedIds = new HashSet<>();
    +        if (approvedWorkers != null) {
    +            approvedIds.addAll(approvedWorkers.keySet());
    +        }
    +        for (Map.Entry<String, LSWorkerHeartbeat> entry : idToHeartbeat.entrySet()) {
    +            String workerId = entry.getKey();
    +            LSWorkerHeartbeat whb = entry.getValue();
    +            State state;
    +            if (whb == null) {
    +                state = State.notStarted;
    +            } else if (!approvedIds.contains(workerId) || !matchesAssignment(whb, assignedExecutors)) {
    +                state = State.disallowed;
    +            } else if (supervisorData.getDeadWorkers().contains(workerId)) {
    +                LOG.info("Worker Process {}as died", workerId);
    +                state = State.timedOut;
    +            } else if (SupervisorUtils.isWorkerHbTimedOut(now, whb, conf)) {
    +                state = State.timedOut;
    +            } else {
    +                state = State.valid;
    +            }
    +            LOG.debug("Worker:{} state:{} WorkerHeartbeat:{} at supervisor time-secs {}", workerId, state, whb, now);
    +            workerIdHbstate.put(workerId, new StateHeartbeat(state, whb));
    +        }
    +        return workerIdHbstate;
    +    }
    +
    +    protected boolean matchesAssignment(LSWorkerHeartbeat whb, Map<Integer, LocalAssignment> assignedExecutors) {
    +        LocalAssignment localAssignment = assignedExecutors.get(whb.get_port());
    +        if (localAssignment == null || !localAssignment.get_topology_id().equals(whb.get_topology_id())) {
    +            return false;
    +        }
    +        List<ExecutorInfo> executorInfos = new ArrayList<>();
    +        executorInfos.addAll(whb.get_executors());
    +        // remove SYSTEM_EXECUTOR_ID
    +        executorInfos.remove(new ExecutorInfo(-1, -1));
    --- End diff --
    
    Very minor nit. Can we move this ExecutorInfo to Contants as something like
    ```
    public static final SYSTEM_EXECUTOR_INFO = new ExecutorInfo(-1, -1);
    ```
    
    so when worker.clj goes to java we can drop SYSTEM-EXECUTOR_ID from Constants?


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55938337
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncProcessEvent.java ---
    @@ -0,0 +1,672 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.ExecutorInfo;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.WorkerResources;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +import org.yaml.snakeyaml.Yaml;
    +
    +import java.io.File;
    +import java.io.FileWriter;
    +import java.io.IOException;
    +import java.util.*;
    +
    +/**
    + * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file - rmr
    + * heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new worker
    + * ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait for workers
    + * launch
    + */
    +public class SyncProcessEvent implements Runnable {
    +
    +    private static Logger LOG = LoggerFactory.getLogger(SyncProcessEvent.class);
    +
    +    private  LocalState localState;
    +    private  SupervisorData supervisorData;
    +    public static final ExecutorInfo SYSTEM_EXECUTOR_INFO = new ExecutorInfo(-1, -1);
    +
    +    private class ProcessExitCallback implements Utils.ExitCodeCallable {
    +        private final String logPrefix;
    +        private final String workerId;
    +
    +        public ProcessExitCallback(String logPrefix, String workerId) {
    +            this.logPrefix = logPrefix;
    +            this.workerId = workerId;
    +        }
    +
    +        @Override
    +        public Object call() throws Exception {
    +            return null;
    +        }
    +
    +        @Override
    +        public Object call(int exitCode) {
    +            LOG.info("{} exited with code: {}", logPrefix, exitCode);
    +            supervisorData.getDeadWorkers().add(workerId);
    +            return null;
    +        }
    +    }
    +
    +    public SyncProcessEvent(){
    +
    +    }
    +    public SyncProcessEvent(SupervisorData supervisorData) {
    +        init(supervisorData);
    +    }
    +
    +    //TODO: initData is intended to local supervisor, so we will remove them after porting worker.clj to java
    +    public void init(SupervisorData supervisorData){
    +        this.supervisorData = supervisorData;
    +        this.localState = supervisorData.getLocalState();
    +    }
    +
    +
    +    /**
    --- End diff --
    
    same comment is at the class level also which can be removed.


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55584846
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorData.java ---
    @@ -0,0 +1,339 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.cluster.ClusterStateContext;
    +import org.apache.storm.cluster.ClusterUtils;
    +import org.apache.storm.cluster.DaemonType;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.ProfileRequest;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +import java.net.UnknownHostException;
    +import java.util.ArrayList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.concurrent.ConcurrentHashMap;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SupervisorData {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorData.class);
    +
    +    private Map conf;
    +    private IContext sharedContext;
    +    private volatile boolean active;
    +    private ISupervisor iSupervisor;
    +    private Utils.UptimeComputer upTime;
    +    private String stormVersion;
    +
    +    private ConcurrentHashMap<String, String> workerThreadPidsAtom; // for local mode
    +
    +    private IStormClusterState stormClusterState;
    +
    +    private LocalState localState;
    +
    +    private String supervisorId;
    +
    +    private String assignmentId;
    +
    +    private String hostName;
    +
    +    // used for reporting used ports when heartbeating
    +    private ConcurrentHashMap<Long, LocalAssignment> currAssignment;
    +
    +    private StormTimer heartbeatTimer;
    +
    +    private StormTimer eventTimer;
    +
    +    private StormTimer blobUpdateTimer;
    +
    +    private Localizer localizer;
    +
    +    private ConcurrentHashMap<String, Map<String, Object>> assignmentVersions;
    +
    +    private AtomicInteger syncRetry;
    +
    +    private final Object downloadLock = new Object();
    +
    +    private ConcurrentHashMap<String, List<ProfileRequest>> stormIdToProfileActions;
    +
    +    private CgroupManager resourceIsolationManager;
    +
    +    private ConcurrentHashSet<String> deadWorkers;
    +
    +    public SupervisorData(Map conf, IContext sharedContext, ISupervisor iSupervisor) {
    +        this.conf = conf;
    +        this.sharedContext = sharedContext;
    +        this.iSupervisor = iSupervisor;
    +        this.active = true;
    +        this.upTime = Utils.makeUptimeComputer();
    +        this.stormVersion = VersionInfo.getVersion();
    +        this.workerThreadPidsAtom = new ConcurrentHashMap<String, String>();
    +        this.deadWorkers = new ConcurrentHashSet();
    +
    +        List<ACL> acls = null;
    +        if (Utils.isZkAuthenticationConfiguredStormServer(conf)) {
    +            acls = SupervisorUtils.supervisorZkAcls();
    +        }
    +
    +        try {
    +            this.stormClusterState = ClusterUtils.mkStormClusterState(conf, acls, new ClusterStateContext(DaemonType.SUPERVISOR));
    +        } catch (Exception e) {
    +            LOG.error("supervisor can't create stormClusterState");
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        try {
    +            this.localState = ConfigUtils.supervisorState(conf);
    +            this.localizer = Utils.createLocalizer(conf, ConfigUtils.supervisorLocalDir(conf));
    +        } catch (IOException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +        this.supervisorId = iSupervisor.getSupervisorId();
    +        this.assignmentId = iSupervisor.getAssignmentId();
    +
    +        try {
    +            this.hostName = Utils.hostname(conf);
    +        } catch (UnknownHostException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        this.currAssignment = new ConcurrentHashMap<>();
    +
    +        this.heartbeatTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.eventTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.blobUpdateTimer = new StormTimer("blob-update-timer", new DefaultUncaughtExceptionHandler());
    +
    +        this.assignmentVersions = new ConcurrentHashMap<>();
    +        this.syncRetry = new AtomicInteger(0);
    +        this.stormIdToProfileActions = new ConcurrentHashMap<>();
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            try {
    +                this.resourceIsolationManager = (CgroupManager) Utils.newInstance((String) conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN));
    +                this.resourceIsolationManager.prepare(conf);
    +                LOG.info("Using resource isolation plugin {} {}", conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN), resourceIsolationManager);
    +            } catch (IOException e) {
    +                throw Utils.wrapInRuntime(e);
    +            }
    +        } else {
    +            this.resourceIsolationManager = null;
    +        }
    +    }
    +
    +    public ConcurrentHashMap<String, List<ProfileRequest>> getStormIdToProfileActions() {
    +        return stormIdToProfileActions;
    +    }
    +
    +    public void setStormIdToProfileActions(Map<String, List<ProfileRequest>> stormIdToProfileActions) {
    +        this.stormIdToProfileActions.clear();
    +        this.stormIdToProfileActions.putAll(stormIdToProfileActions);
    +    }
    +
    +    public Map getConf() {
    +        return conf;
    +    }
    +
    +    public void setConf(Map conf) {
    +        this.conf = conf;
    +    }
    +
    +    public IContext getSharedContext() {
    +        return sharedContext;
    +    }
    +
    +    public void setSharedContext(IContext sharedContext) {
    +        this.sharedContext = sharedContext;
    +    }
    +
    +    public boolean isActive() {
    +        return active;
    +    }
    +
    +    public void setActive(boolean active) {
    +        this.active = active;
    +    }
    +
    +    public ISupervisor getiSupervisor() {
    +        return iSupervisor;
    +    }
    +
    +    public void setiSupervisor(ISupervisor iSupervisor) {
    +        this.iSupervisor = iSupervisor;
    +    }
    +
    +    public Utils.UptimeComputer getUpTime() {
    +        return upTime;
    +    }
    +
    +    public void setUpTime(Utils.UptimeComputer upTime) {
    +        this.upTime = upTime;
    +    }
    +
    +    public String getStormVersion() {
    +        return stormVersion;
    +    }
    +
    +    public void setStormVersion(String stormVersion) {
    +        this.stormVersion = stormVersion;
    +    }
    +
    +    public ConcurrentHashMap<String, String> getWorkerThreadPidsAtom() {
    +        return workerThreadPidsAtom;
    +    }
    +
    +    public void setWorkerThreadPidsAtom(ConcurrentHashMap<String, String> workerThreadPidsAtom) {
    +        this.workerThreadPidsAtom = workerThreadPidsAtom;
    +    }
    +
    +    public IStormClusterState getStormClusterState() {
    +        return stormClusterState;
    +    }
    +
    +    public void setStormClusterState(IStormClusterState stormClusterState) {
    +        this.stormClusterState = stormClusterState;
    +    }
    +
    +    public LocalState getLocalState() {
    +        return localState;
    +    }
    +
    +    public void setLocalState(LocalState localState) {
    +        this.localState = localState;
    +    }
    +
    +    public String getSupervisorId() {
    +        return supervisorId;
    +    }
    +
    +    public void setSupervisorId(String supervisorId) {
    +        this.supervisorId = supervisorId;
    +    }
    +
    +    public String getAssignmentId() {
    +        return assignmentId;
    +    }
    +
    +    public void setAssignmentId(String assignmentId) {
    --- End diff --
    
    Not used


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55938152
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorUtils.java ---
    @@ -0,0 +1,353 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.ProcessSimulator;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.localizer.LocalResource;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.IOException;
    +import java.net.URLDecoder;
    +import java.util.*;
    +
    +public class SupervisorUtils {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorUtils.class);
    +
    +    private static final SupervisorUtils INSTANCE = new SupervisorUtils();
    +    private static SupervisorUtils _instance = INSTANCE;
    +    public static void setInstance(SupervisorUtils u) {
    +        _instance = u;
    +    }
    +    public static void resetInstance() {
    +        _instance = INSTANCE;
    +    }
    +
    +    public static Process workerLauncher(Map conf, String user, List<String> args, Map<String, String> environment, final String logPreFix,
    +            final Utils.ExitCodeCallable exitCodeCallback, File dir) throws IOException {
    +        if (StringUtils.isBlank(user)) {
    +            throw new IllegalArgumentException("User cannot be blank when calling workerLauncher.");
    +        }
    +        String wlinitial = (String) (conf.get(Config.SUPERVISOR_WORKER_LAUNCHER));
    +        String stormHome = ConfigUtils.concatIfNotNull(System.getProperty("storm.home"));
    +        String wl;
    +        if (StringUtils.isNotBlank(wlinitial)) {
    +            wl = wlinitial;
    +        } else {
    +            wl = stormHome + "/bin/worker-launcher";
    +        }
    +        List<String> commands = new ArrayList<>();
    +        commands.add(wl);
    +        commands.add(user);
    +        commands.addAll(args);
    +        LOG.info("Running as user: {} command: {}", user, commands);
    +        return Utils.launchProcess(commands, environment, logPreFix, exitCodeCallback, dir);
    +    }
    +
    +    public static int workerLauncherAndWait(Map conf, String user, List<String> args, final Map<String, String> environment, final String logPreFix)
    +            throws IOException {
    +        int ret = 0;
    +        Process process = workerLauncher(conf, user, args, environment, logPreFix, null, null);
    +        if (StringUtils.isNotBlank(logPreFix))
    +            Utils.readAndLogStream(logPreFix, process.getInputStream());
    +        try {
    +            process.waitFor();
    +        } catch (InterruptedException e) {
    +            LOG.info("{} interrupted.", logPreFix);
    +        }
    +        ret = process.exitValue();
    +        return ret;
    +    }
    +
    +    public static void setupStormCodeDir(Map conf, Map stormConf, String dir) throws IOException {
    +        if (Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false)) {
    +            String logPrefix = "setup conf for " + dir;
    +            List<String> commands = new ArrayList<>();
    +            commands.add("code-dir");
    +            commands.add(dir);
    +            workerLauncherAndWait(conf, (String) (stormConf.get(Config.TOPOLOGY_SUBMITTER_USER)), commands, null, logPrefix);
    +        }
    +    }
    +
    +    public static void rmrAsUser(Map conf, String id, String path) throws IOException {
    +        String user = Utils.getFileOwner(path);
    +        String logPreFix = "rmr " + id;
    +        List<String> commands = new ArrayList<>();
    +        commands.add("rmr");
    +        commands.add(path);
    +        SupervisorUtils.workerLauncherAndWait(conf, user, commands, null, logPreFix);
    +        if (Utils.checkFileExists(path)) {
    +            throw new RuntimeException(path + " was not deleted.");
    +        }
    +    }
    +
    +    /**
    +     * Given the blob information returns the value of the uncompress field, handling it either being a string or a boolean value, or if it's not specified then
    +     * returns false
    +     * 
    +     * @param blobInfo
    +     * @return
    +     */
    +    public static Boolean shouldUncompressBlob(Map<String, Object> blobInfo) {
    +        return new Boolean((String) blobInfo.get("uncompress"));
    --- End diff --
    
    It only handles string values and not boolean values. Correct definition would be
    ` return new Boolean(String.valueOf(blobInfo.get("uncompress")))`


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r57193403
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncSupervisorEvent.java ---
    @@ -0,0 +1,632 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.blobstore.BlobStore;
    +import org.apache.storm.blobstore.ClientBlobStore;
    +import org.apache.storm.cluster.IStateStorage;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.event.EventManager;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.localizer.LocalResource;
    +import org.apache.storm.localizer.LocalizedResource;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.utils.*;
    +import org.apache.thrift.transport.TTransportException;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.FileOutputStream;
    +import java.io.IOException;
    +import java.net.JarURLConnection;
    +import java.net.URL;
    +import java.nio.file.Files;
    +import java.nio.file.StandardCopyOption;
    +import java.util.*;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SyncSupervisorEvent implements Runnable {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SyncSupervisorEvent.class);
    +
    +    private EventManager syncSupEventManager;
    +    private EventManager syncProcessManager;
    +    private IStormClusterState stormClusterState;
    +    private LocalState localState;
    +    private SyncProcessEvent syncProcesses;
    +    private SupervisorData supervisorData;
    +
    +    public SyncSupervisorEvent(SupervisorData supervisorData, SyncProcessEvent syncProcesses, EventManager syncSupEventManager,
    +            EventManager syncProcessManager) {
    +
    +        this.syncProcesses = syncProcesses;
    +        this.syncSupEventManager = syncSupEventManager;
    +        this.syncProcessManager = syncProcessManager;
    +        this.stormClusterState = supervisorData.getStormClusterState();
    +        this.localState = supervisorData.getLocalState();
    +        this.supervisorData = supervisorData;
    +    }
    +
    +    @Override
    +    public void run() {
    +        try {
    +            Map conf = supervisorData.getConf();
    +            Runnable syncCallback = new EventManagerPushCallback(this, syncSupEventManager);
    +            List<String> stormIds = stormClusterState.assignments(syncCallback);
    +            Map<String, Map<String, Object>> assignmentsSnapshot =
    +                    getAssignmentsSnapshot(stormClusterState, stormIds, supervisorData.getAssignmentVersions().get(), syncCallback);
    +            Map<String, List<ProfileRequest>> stormIdToProfilerActions = getProfileActions(stormClusterState, stormIds);
    +
    +            Set<String> allDownloadedTopologyIds = SupervisorUtils.readDownLoadedStormIds(conf);
    +            Map<String, String> stormcodeMap = readStormCodeLocations(assignmentsSnapshot);
    +            Map<Integer, LocalAssignment> existingAssignment = localState.getLocalAssignmentsMap();
    +            if (existingAssignment == null) {
    +                existingAssignment = new HashMap<>();
    +            }
    +
    +            Map<Integer, LocalAssignment> allAssignment =
    +                    readAssignments(assignmentsSnapshot, existingAssignment, supervisorData.getAssignmentId(), supervisorData.getSyncRetry());
    +
    +            Map<Integer, LocalAssignment> newAssignment = new HashMap<>();
    +            Set<String> assignedStormIds = new HashSet<>();
    +
    +            for (Map.Entry<Integer, LocalAssignment> entry : allAssignment.entrySet()) {
    +                if (supervisorData.getiSupervisor().confirmAssigned(entry.getKey())) {
    +                    newAssignment.put(entry.getKey(), entry.getValue());
    +                    assignedStormIds.add(entry.getValue().get_topology_id());
    +                }
    +            }
    +
    +            Set<String> srashStormIds = verifyDownloadedFiles(conf, supervisorData.getLocalizer(), assignedStormIds, allDownloadedTopologyIds);
    +            Set<String> downloadedStormIds = new HashSet<>();
    +            downloadedStormIds.addAll(allDownloadedTopologyIds);
    +            downloadedStormIds.removeAll(srashStormIds);
    +
    +            LOG.debug("Synchronizing supervisor");
    +            LOG.debug("Storm code map: {}", stormcodeMap);
    +            LOG.debug("All assignment: {}", allAssignment);
    +            LOG.debug("New assignment: {}", newAssignment);
    +            LOG.debug("Assigned Storm Ids {}", assignedStormIds);
    +            LOG.debug("All Downloaded Ids {}", allDownloadedTopologyIds);
    +            LOG.debug("Checked Downloaded Ids {}", srashStormIds);
    +            LOG.debug("Downloaded Ids {}", downloadedStormIds);
    +            LOG.debug("Storm Ids Profiler Actions {}", stormIdToProfilerActions);
    +
    +            // download code first
    +            // This might take awhile
    +            // - should this be done separately from usual monitoring?
    +            // should we only download when topology is assigned to this supervisor?
    +            for (Map.Entry<String, String> entry : stormcodeMap.entrySet()) {
    +                String stormId = entry.getKey();
    +                if (!downloadedStormIds.contains(stormId) && assignedStormIds.contains(stormId)) {
    +                    LOG.info("Downloading code for storm id {}.", stormId);
    +                    try {
    +                        downloadStormCode(conf, stormId, entry.getValue(), supervisorData.getLocalizer());
    +                    } catch (Exception e) {
    +                        if (Utils.exceptionCauseIsInstanceOf(NimbusLeaderNotFoundException.class, e)) {
    +                            LOG.warn("Nimbus leader was not available.", e);
    +                        } else if (Utils.exceptionCauseIsInstanceOf(TTransportException.class, e)) {
    +                            LOG.warn("There was a connection problem with nimbus.", e);
    +                        } else {
    +                            throw e;
    +                        }
    +                    }
    +                    LOG.info("Finished downloading code for storm id {}", stormId);
    +                }
    +            }
    +
    +            LOG.debug("Writing new assignment {}", newAssignment);
    +
    +            Set<Integer> killWorkers = new HashSet<>();
    +            killWorkers.addAll(existingAssignment.keySet());
    +            killWorkers.removeAll(newAssignment.keySet());
    +            for (Integer port : killWorkers) {
    +                supervisorData.getiSupervisor().killedWorker(port);
    +            }
    +
    +            killExistingWorkersWithChangeInComponents(supervisorData, existingAssignment, newAssignment);
    +
    +            supervisorData.getiSupervisor().assigned(newAssignment.keySet());
    +            localState.setLocalAssignmentsMap(newAssignment);
    +            supervisorData.setAssignmentVersions(assignmentsSnapshot);
    +            supervisorData.setStormIdToProfileActions(stormIdToProfilerActions);
    +
    +            Map<Long, LocalAssignment> convertNewAssignment = new HashMap<>();
    +            for (Map.Entry<Integer, LocalAssignment> entry : newAssignment.entrySet()) {
    +                convertNewAssignment.put(entry.getKey().longValue(), entry.getValue());
    +            }
    +            supervisorData.setCurrAssignment(convertNewAssignment);
    +            // remove any downloaded code that's no longer assigned or active
    +            // important that this happens after setting the local assignment so that
    +            // synchronize-supervisor doesn't try to launch workers for which the
    +            // resources don't exist
    +            if (Utils.isOnWindows()) {
    +                shutdownDisallowedWorkers();
    +            }
    +            for (String stormId : allDownloadedTopologyIds) {
    +                if (!stormcodeMap.containsKey(stormId)) {
    +                    LOG.info("Removing code for storm id {}.", stormId);
    +                    rmTopoFiles(conf, stormId, supervisorData.getLocalizer(), true);
    +                }
    +            }
    +            syncProcessManager.add(syncProcesses);
    +        } catch (Exception e) {
    +            LOG.error("Failed to Sync Supervisor", e);
    +            throw new RuntimeException(e);
    +        }
    +
    +    }
    +
    +    private void killExistingWorkersWithChangeInComponents(SupervisorData supervisorData, Map<Integer, LocalAssignment> existingAssignment,
    +            Map<Integer, LocalAssignment> newAssignment) throws Exception {
    +        LocalState localState = supervisorData.getLocalState();
    +        Map<Integer, LocalAssignment> assignedExecutors = localState.getLocalAssignmentsMap();
    +        if (assignedExecutors == null) {
    +            assignedExecutors = new HashMap<>();
    +        }
    +        int now = Time.currentTimeSecs();
    +        Map<String, StateHeartbeat> workerIdHbstate = syncProcesses.getLocalWorkerStats(supervisorData, assignedExecutors, now);
    +        Map<Integer, String> vaildPortToWorkerIds = new HashMap<>();
    +        for (Map.Entry<String, StateHeartbeat> entry : workerIdHbstate.entrySet()) {
    +            String workerId = entry.getKey();
    +            StateHeartbeat stateHeartbeat = entry.getValue();
    +            if (stateHeartbeat != null && stateHeartbeat.getState() == State.VALID) {
    +                vaildPortToWorkerIds.put(stateHeartbeat.getHeartbeat().get_port(), workerId);
    +            }
    +        }
    +
    +        Map<Integer, LocalAssignment> intersectAssignment = new HashMap<>();
    +        for (Map.Entry<Integer, LocalAssignment> entry : newAssignment.entrySet()) {
    +            Integer port = entry.getKey();
    +            if (existingAssignment.containsKey(port)) {
    +                intersectAssignment.put(port, entry.getValue());
    +            }
    +        }
    +
    +        for (Integer port : intersectAssignment.keySet()) {
    +            List<ExecutorInfo> existExecutors = existingAssignment.get(port).get_executors();
    +            List<ExecutorInfo> newExecutors = newAssignment.get(port).get_executors();
    +            if (newExecutors.size() != existExecutors.size()) {
    --- End diff --
    
    @jerrypeng  I may not follow up your means. If they contain the same elements  (without considering ordering) , it don't  shut down the worker.
    ···
               for (ExecutorInfo executorInfo : newExecutors) {
                    if (!existExecutors.contains(executorInfo)) {
                        syncProcesses.shutWorker(supervisorData, supervisorData.getWorkerManager(), vaildPortToWorkerIds.get(port));
                        break;
                    }
                }
    ···


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55584398
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorData.java ---
    @@ -0,0 +1,339 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.cluster.ClusterStateContext;
    +import org.apache.storm.cluster.ClusterUtils;
    +import org.apache.storm.cluster.DaemonType;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.ProfileRequest;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +import java.net.UnknownHostException;
    +import java.util.ArrayList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.concurrent.ConcurrentHashMap;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SupervisorData {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorData.class);
    +
    +    private Map conf;
    +    private IContext sharedContext;
    +    private volatile boolean active;
    +    private ISupervisor iSupervisor;
    +    private Utils.UptimeComputer upTime;
    +    private String stormVersion;
    +
    +    private ConcurrentHashMap<String, String> workerThreadPidsAtom; // for local mode
    +
    +    private IStormClusterState stormClusterState;
    +
    +    private LocalState localState;
    +
    +    private String supervisorId;
    +
    +    private String assignmentId;
    +
    +    private String hostName;
    +
    +    // used for reporting used ports when heartbeating
    +    private ConcurrentHashMap<Long, LocalAssignment> currAssignment;
    +
    +    private StormTimer heartbeatTimer;
    +
    +    private StormTimer eventTimer;
    +
    +    private StormTimer blobUpdateTimer;
    +
    +    private Localizer localizer;
    +
    +    private ConcurrentHashMap<String, Map<String, Object>> assignmentVersions;
    +
    +    private AtomicInteger syncRetry;
    +
    +    private final Object downloadLock = new Object();
    +
    +    private ConcurrentHashMap<String, List<ProfileRequest>> stormIdToProfileActions;
    +
    +    private CgroupManager resourceIsolationManager;
    +
    +    private ConcurrentHashSet<String> deadWorkers;
    +
    +    public SupervisorData(Map conf, IContext sharedContext, ISupervisor iSupervisor) {
    +        this.conf = conf;
    +        this.sharedContext = sharedContext;
    +        this.iSupervisor = iSupervisor;
    +        this.active = true;
    +        this.upTime = Utils.makeUptimeComputer();
    +        this.stormVersion = VersionInfo.getVersion();
    +        this.workerThreadPidsAtom = new ConcurrentHashMap<String, String>();
    +        this.deadWorkers = new ConcurrentHashSet();
    +
    +        List<ACL> acls = null;
    +        if (Utils.isZkAuthenticationConfiguredStormServer(conf)) {
    +            acls = SupervisorUtils.supervisorZkAcls();
    +        }
    +
    +        try {
    +            this.stormClusterState = ClusterUtils.mkStormClusterState(conf, acls, new ClusterStateContext(DaemonType.SUPERVISOR));
    +        } catch (Exception e) {
    +            LOG.error("supervisor can't create stormClusterState");
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        try {
    +            this.localState = ConfigUtils.supervisorState(conf);
    +            this.localizer = Utils.createLocalizer(conf, ConfigUtils.supervisorLocalDir(conf));
    +        } catch (IOException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +        this.supervisorId = iSupervisor.getSupervisorId();
    +        this.assignmentId = iSupervisor.getAssignmentId();
    +
    +        try {
    +            this.hostName = Utils.hostname(conf);
    +        } catch (UnknownHostException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        this.currAssignment = new ConcurrentHashMap<>();
    +
    +        this.heartbeatTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.eventTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.blobUpdateTimer = new StormTimer("blob-update-timer", new DefaultUncaughtExceptionHandler());
    +
    +        this.assignmentVersions = new ConcurrentHashMap<>();
    +        this.syncRetry = new AtomicInteger(0);
    +        this.stormIdToProfileActions = new ConcurrentHashMap<>();
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            try {
    +                this.resourceIsolationManager = (CgroupManager) Utils.newInstance((String) conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN));
    +                this.resourceIsolationManager.prepare(conf);
    +                LOG.info("Using resource isolation plugin {} {}", conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN), resourceIsolationManager);
    +            } catch (IOException e) {
    +                throw Utils.wrapInRuntime(e);
    +            }
    +        } else {
    +            this.resourceIsolationManager = null;
    +        }
    +    }
    +
    +    public ConcurrentHashMap<String, List<ProfileRequest>> getStormIdToProfileActions() {
    +        return stormIdToProfileActions;
    +    }
    +
    +    public void setStormIdToProfileActions(Map<String, List<ProfileRequest>> stormIdToProfileActions) {
    +        this.stormIdToProfileActions.clear();
    +        this.stormIdToProfileActions.putAll(stormIdToProfileActions);
    +    }
    +
    +    public Map getConf() {
    +        return conf;
    +    }
    +
    +    public void setConf(Map conf) {
    +        this.conf = conf;
    +    }
    +
    +    public IContext getSharedContext() {
    +        return sharedContext;
    +    }
    +
    +    public void setSharedContext(IContext sharedContext) {
    +        this.sharedContext = sharedContext;
    +    }
    +
    +    public boolean isActive() {
    +        return active;
    +    }
    +
    +    public void setActive(boolean active) {
    +        this.active = active;
    +    }
    +
    +    public ISupervisor getiSupervisor() {
    +        return iSupervisor;
    +    }
    +
    +    public void setiSupervisor(ISupervisor iSupervisor) {
    --- End diff --
    
    Not used.


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#issuecomment-193767423
  
    Sure @hustfxj  Makes sense


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55601506
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorUtils.java ---
    @@ -0,0 +1,273 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.curator.utils.PathUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.localizer.LocalResource;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.IOException;
    +import java.net.URLDecoder;
    +import java.util.*;
    +
    +public class SupervisorUtils {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorUtils.class);
    +
    +    private static final SupervisorUtils INSTANCE = new SupervisorUtils();
    +    private static SupervisorUtils _instance = INSTANCE;
    +
    +    public static void setInstance(SupervisorUtils u) {
    +        _instance = u;
    +    }
    +
    +    public static void resetInstance() {
    +        _instance = INSTANCE;
    +    }
    +
    +    public static Process workerLauncher(Map conf, String user, List<String> args, Map<String, String> environment, final String logPreFix,
    +            final Utils.ExitCodeCallable exitCodeCallback, File dir) throws IOException {
    +        if (StringUtils.isBlank(user)) {
    +            throw new IllegalArgumentException("User cannot be blank when calling workerLauncher.");
    +        }
    +        String wlinitial = (String) (conf.get(Config.SUPERVISOR_WORKER_LAUNCHER));
    +        String stormHome = ConfigUtils.concatIfNotNull(System.getProperty("storm.home"));
    +        String wl;
    +        if (StringUtils.isNotBlank(wlinitial)) {
    +            wl = wlinitial;
    +        } else {
    +            wl = stormHome + "/bin/worker-launcher";
    +        }
    +        List<String> commands = new ArrayList<>();
    +        commands.add(wl);
    +        commands.add(user);
    +        commands.addAll(args);
    +        return Utils.launchProcess(commands, environment, logPreFix, exitCodeCallback, dir);
    +    }
    +
    +    public static int workerLauncherAndWait(Map conf, String user, List<String> args, final Map<String, String> environment, final String logPreFix)
    +            throws IOException {
    +        int ret = 0;
    +        Process process = workerLauncher(conf, user, args, environment, logPreFix, null, null);
    +        if (StringUtils.isNotBlank(logPreFix))
    +            Utils.readAndLogStream(logPreFix, process.getInputStream());
    +        try {
    +            process.waitFor();
    +        } catch (InterruptedException e) {
    +            LOG.info("{} interrupted.", logPreFix);
    +        }
    +        ret = process.exitValue();
    +        return ret;
    +    }
    +
    +    public static void setupStormCodeDir(Map conf, Map stormConf, String dir) throws IOException {
    +        if (Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false)) {
    +            String logPrefix = "setup conf for " + dir;
    +            List<String> commands = new ArrayList<>();
    +            commands.add("code-dir");
    +            commands.add(dir);
    +            workerLauncherAndWait(conf, (String) (stormConf.get(Config.TOPOLOGY_SUBMITTER_USER)), commands, null, logPrefix);
    +        }
    +    }
    +
    +    public static void rmrAsUser(Map conf, String id, String path) throws IOException {
    +        String user = Utils.getFileOwner(path);
    +        String logPreFix = "rmr " + id;
    +        List<String> commands = new ArrayList<>();
    +        commands.add("rmr");
    +        commands.add(path);
    +        SupervisorUtils.workerLauncherAndWait(conf, user, commands, null, logPreFix);
    +        if (Utils.checkFileExists(path)) {
    +            throw new RuntimeException(path + " was not deleted.");
    +        }
    +    }
    +
    +    /**
    +     * Given the blob information returns the value of the uncompress field, handling it either being a string or a boolean value, or if it's not specified then
    +     * returns false
    +     * 
    +     * @param blobInfo
    +     * @return
    +     */
    +    public static Boolean isShouldUncompressBlob(Map<String, Object> blobInfo) {
    +        return new Boolean((String) blobInfo.get("uncompress"));
    +    }
    +
    +    /**
    +     * Remove a reference to a blob when its no longer needed
    +     * 
    +     * @param blobstoreMap
    +     * @return
    +     */
    +    public static List<LocalResource> blobstoreMapToLocalresources(Map<String, Map<String, Object>> blobstoreMap) {
    +        List<LocalResource> localResourceList = new ArrayList<>();
    +        if (blobstoreMap != null) {
    +            for (Map.Entry<String, Map<String, Object>> map : blobstoreMap.entrySet()) {
    +                LocalResource localResource = new LocalResource(map.getKey(), isShouldUncompressBlob(map.getValue()));
    +                localResourceList.add(localResource);
    +            }
    +        }
    +        return localResourceList;
    +    }
    +
    +    /**
    +     * For each of the downloaded topologies, adds references to the blobs that the topologies are using. This is used to reconstruct the cache on restart.
    +     * 
    +     * @param localizer
    +     * @param stormId
    +     * @param conf
    +     */
    +    public static void addBlobReferences(Localizer localizer, String stormId, Map conf) throws IOException {
    +        Map stormConf = ConfigUtils.readSupervisorStormConf(conf, stormId);
    +        Map<String, Map<String, Object>> blobstoreMap = (Map<String, Map<String, Object>>) stormConf.get(Config.TOPOLOGY_BLOBSTORE_MAP);
    +        String user = (String) stormConf.get(Config.TOPOLOGY_SUBMITTER_USER);
    +        String topoName = (String) stormConf.get(Config.TOPOLOGY_NAME);
    +        List<LocalResource> localresources = SupervisorUtils.blobstoreMapToLocalresources(blobstoreMap);
    +        if (blobstoreMap != null) {
    +            localizer.addReferences(localresources, user, topoName);
    +        }
    +    }
    +
    +    public static Set<String> readDownLoadedStormIds(Map conf) throws IOException {
    +        Set<String> stormIds = new HashSet<>();
    +        String path = ConfigUtils.supervisorStormDistRoot(conf);
    +        Collection<String> rets = Utils.readDirContents(path);
    +        for (String ret : rets) {
    +            stormIds.add(URLDecoder.decode(ret));
    +        }
    +        return stormIds;
    +    }
    +
    +    public static Collection<String> supervisorWorkerIds(Map conf) {
    +        String workerRoot = ConfigUtils.workerRoot(conf);
    +        return Utils.readDirContents(workerRoot);
    +    }
    +
    +    public static boolean checkTopoFilesExist(Map conf, String stormId) throws IOException {
    +        String stormroot = ConfigUtils.supervisorStormDistRoot(conf, stormId);
    +        String stormjarpath = ConfigUtils.supervisorStormJarPath(stormroot);
    +        String stormcodepath = ConfigUtils.supervisorStormCodePath(stormroot);
    +        String stormconfpath = ConfigUtils.supervisorStormConfPath(stormroot);
    +        if (!Utils.checkFileExists(stormroot))
    +            return false;
    +        if (!Utils.checkFileExists(stormcodepath))
    +            return false;
    +        if (!Utils.checkFileExists(stormconfpath))
    +            return false;
    +        if (ConfigUtils.isLocalMode(conf) || Utils.checkFileExists(stormjarpath))
    +            return true;
    +        return false;
    +    }
    +
    +    public static Collection<String> myWorkerIds(Map conf){
    --- End diff --
    
    This is the same as supervisorWorkerIds.  We should combine the two together.


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55585347
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorData.java ---
    @@ -0,0 +1,339 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.cluster.ClusterStateContext;
    +import org.apache.storm.cluster.ClusterUtils;
    +import org.apache.storm.cluster.DaemonType;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.ProfileRequest;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +import java.net.UnknownHostException;
    +import java.util.ArrayList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.concurrent.ConcurrentHashMap;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SupervisorData {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorData.class);
    +
    +    private Map conf;
    +    private IContext sharedContext;
    +    private volatile boolean active;
    +    private ISupervisor iSupervisor;
    +    private Utils.UptimeComputer upTime;
    +    private String stormVersion;
    +
    +    private ConcurrentHashMap<String, String> workerThreadPidsAtom; // for local mode
    +
    +    private IStormClusterState stormClusterState;
    +
    +    private LocalState localState;
    +
    +    private String supervisorId;
    +
    +    private String assignmentId;
    +
    +    private String hostName;
    +
    +    // used for reporting used ports when heartbeating
    +    private ConcurrentHashMap<Long, LocalAssignment> currAssignment;
    +
    +    private StormTimer heartbeatTimer;
    +
    +    private StormTimer eventTimer;
    +
    +    private StormTimer blobUpdateTimer;
    +
    +    private Localizer localizer;
    +
    +    private ConcurrentHashMap<String, Map<String, Object>> assignmentVersions;
    +
    +    private AtomicInteger syncRetry;
    +
    +    private final Object downloadLock = new Object();
    +
    +    private ConcurrentHashMap<String, List<ProfileRequest>> stormIdToProfileActions;
    +
    +    private CgroupManager resourceIsolationManager;
    +
    +    private ConcurrentHashSet<String> deadWorkers;
    +
    +    public SupervisorData(Map conf, IContext sharedContext, ISupervisor iSupervisor) {
    +        this.conf = conf;
    +        this.sharedContext = sharedContext;
    +        this.iSupervisor = iSupervisor;
    +        this.active = true;
    +        this.upTime = Utils.makeUptimeComputer();
    +        this.stormVersion = VersionInfo.getVersion();
    +        this.workerThreadPidsAtom = new ConcurrentHashMap<String, String>();
    +        this.deadWorkers = new ConcurrentHashSet();
    +
    +        List<ACL> acls = null;
    +        if (Utils.isZkAuthenticationConfiguredStormServer(conf)) {
    +            acls = SupervisorUtils.supervisorZkAcls();
    +        }
    +
    +        try {
    +            this.stormClusterState = ClusterUtils.mkStormClusterState(conf, acls, new ClusterStateContext(DaemonType.SUPERVISOR));
    +        } catch (Exception e) {
    +            LOG.error("supervisor can't create stormClusterState");
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        try {
    +            this.localState = ConfigUtils.supervisorState(conf);
    +            this.localizer = Utils.createLocalizer(conf, ConfigUtils.supervisorLocalDir(conf));
    +        } catch (IOException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +        this.supervisorId = iSupervisor.getSupervisorId();
    +        this.assignmentId = iSupervisor.getAssignmentId();
    +
    +        try {
    +            this.hostName = Utils.hostname(conf);
    +        } catch (UnknownHostException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        this.currAssignment = new ConcurrentHashMap<>();
    +
    +        this.heartbeatTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.eventTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.blobUpdateTimer = new StormTimer("blob-update-timer", new DefaultUncaughtExceptionHandler());
    +
    +        this.assignmentVersions = new ConcurrentHashMap<>();
    +        this.syncRetry = new AtomicInteger(0);
    +        this.stormIdToProfileActions = new ConcurrentHashMap<>();
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            try {
    +                this.resourceIsolationManager = (CgroupManager) Utils.newInstance((String) conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN));
    +                this.resourceIsolationManager.prepare(conf);
    +                LOG.info("Using resource isolation plugin {} {}", conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN), resourceIsolationManager);
    +            } catch (IOException e) {
    +                throw Utils.wrapInRuntime(e);
    +            }
    +        } else {
    +            this.resourceIsolationManager = null;
    +        }
    +    }
    +
    +    public ConcurrentHashMap<String, List<ProfileRequest>> getStormIdToProfileActions() {
    +        return stormIdToProfileActions;
    +    }
    +
    +    public void setStormIdToProfileActions(Map<String, List<ProfileRequest>> stormIdToProfileActions) {
    +        this.stormIdToProfileActions.clear();
    +        this.stormIdToProfileActions.putAll(stormIdToProfileActions);
    +    }
    +
    +    public Map getConf() {
    +        return conf;
    +    }
    +
    +    public void setConf(Map conf) {
    +        this.conf = conf;
    +    }
    +
    +    public IContext getSharedContext() {
    +        return sharedContext;
    +    }
    +
    +    public void setSharedContext(IContext sharedContext) {
    +        this.sharedContext = sharedContext;
    +    }
    +
    +    public boolean isActive() {
    +        return active;
    +    }
    +
    +    public void setActive(boolean active) {
    +        this.active = active;
    +    }
    +
    +    public ISupervisor getiSupervisor() {
    +        return iSupervisor;
    +    }
    +
    +    public void setiSupervisor(ISupervisor iSupervisor) {
    +        this.iSupervisor = iSupervisor;
    +    }
    +
    +    public Utils.UptimeComputer getUpTime() {
    +        return upTime;
    +    }
    +
    +    public void setUpTime(Utils.UptimeComputer upTime) {
    +        this.upTime = upTime;
    +    }
    +
    +    public String getStormVersion() {
    +        return stormVersion;
    +    }
    +
    +    public void setStormVersion(String stormVersion) {
    +        this.stormVersion = stormVersion;
    +    }
    +
    +    public ConcurrentHashMap<String, String> getWorkerThreadPidsAtom() {
    +        return workerThreadPidsAtom;
    +    }
    +
    +    public void setWorkerThreadPidsAtom(ConcurrentHashMap<String, String> workerThreadPidsAtom) {
    +        this.workerThreadPidsAtom = workerThreadPidsAtom;
    +    }
    +
    +    public IStormClusterState getStormClusterState() {
    +        return stormClusterState;
    +    }
    +
    +    public void setStormClusterState(IStormClusterState stormClusterState) {
    +        this.stormClusterState = stormClusterState;
    +    }
    +
    +    public LocalState getLocalState() {
    +        return localState;
    +    }
    +
    +    public void setLocalState(LocalState localState) {
    +        this.localState = localState;
    +    }
    +
    +    public String getSupervisorId() {
    +        return supervisorId;
    +    }
    +
    +    public void setSupervisorId(String supervisorId) {
    +        this.supervisorId = supervisorId;
    +    }
    +
    +    public String getAssignmentId() {
    +        return assignmentId;
    +    }
    +
    +    public void setAssignmentId(String assignmentId) {
    +        this.assignmentId = assignmentId;
    +    }
    +
    +    public String getHostName() {
    +        return hostName;
    +    }
    +
    +    public void setHostName(String hostName) {
    +        this.hostName = hostName;
    +    }
    +
    +    public ConcurrentHashMap<Long, LocalAssignment> getCurrAssignment() {
    +        return currAssignment;
    +    }
    +
    +    public void setCurrAssignment(Map<Long, LocalAssignment> currAssignment) {
    +        this.currAssignment.clear();
    +        this.currAssignment.putAll(currAssignment);
    +    }
    +
    +    public StormTimer getHeartbeatTimer() {
    +        return heartbeatTimer;
    +    }
    +
    +    public void setHeartbeatTimer(StormTimer heartbeatTimer) {
    +        this.heartbeatTimer = heartbeatTimer;
    +    }
    +
    +    public StormTimer getEventTimer() {
    +        return eventTimer;
    +    }
    +
    +    public void setEventTimer(StormTimer eventTimer) {
    +        this.eventTimer = eventTimer;
    +    }
    +
    +    public StormTimer getBlobUpdateTimer() {
    +        return blobUpdateTimer;
    +    }
    +
    +    public void setBlobUpdateTimer(StormTimer blobUpdateTimer) {
    --- End diff --
    
    Not used


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55585292
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorData.java ---
    @@ -0,0 +1,339 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.cluster.ClusterStateContext;
    +import org.apache.storm.cluster.ClusterUtils;
    +import org.apache.storm.cluster.DaemonType;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.ProfileRequest;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +import java.net.UnknownHostException;
    +import java.util.ArrayList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.concurrent.ConcurrentHashMap;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SupervisorData {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorData.class);
    +
    +    private Map conf;
    +    private IContext sharedContext;
    +    private volatile boolean active;
    +    private ISupervisor iSupervisor;
    +    private Utils.UptimeComputer upTime;
    +    private String stormVersion;
    +
    +    private ConcurrentHashMap<String, String> workerThreadPidsAtom; // for local mode
    +
    +    private IStormClusterState stormClusterState;
    +
    +    private LocalState localState;
    +
    +    private String supervisorId;
    +
    +    private String assignmentId;
    +
    +    private String hostName;
    +
    +    // used for reporting used ports when heartbeating
    +    private ConcurrentHashMap<Long, LocalAssignment> currAssignment;
    +
    +    private StormTimer heartbeatTimer;
    +
    +    private StormTimer eventTimer;
    +
    +    private StormTimer blobUpdateTimer;
    +
    +    private Localizer localizer;
    +
    +    private ConcurrentHashMap<String, Map<String, Object>> assignmentVersions;
    +
    +    private AtomicInteger syncRetry;
    +
    +    private final Object downloadLock = new Object();
    +
    +    private ConcurrentHashMap<String, List<ProfileRequest>> stormIdToProfileActions;
    +
    +    private CgroupManager resourceIsolationManager;
    +
    +    private ConcurrentHashSet<String> deadWorkers;
    +
    +    public SupervisorData(Map conf, IContext sharedContext, ISupervisor iSupervisor) {
    +        this.conf = conf;
    +        this.sharedContext = sharedContext;
    +        this.iSupervisor = iSupervisor;
    +        this.active = true;
    +        this.upTime = Utils.makeUptimeComputer();
    +        this.stormVersion = VersionInfo.getVersion();
    +        this.workerThreadPidsAtom = new ConcurrentHashMap<String, String>();
    +        this.deadWorkers = new ConcurrentHashSet();
    +
    +        List<ACL> acls = null;
    +        if (Utils.isZkAuthenticationConfiguredStormServer(conf)) {
    +            acls = SupervisorUtils.supervisorZkAcls();
    +        }
    +
    +        try {
    +            this.stormClusterState = ClusterUtils.mkStormClusterState(conf, acls, new ClusterStateContext(DaemonType.SUPERVISOR));
    +        } catch (Exception e) {
    +            LOG.error("supervisor can't create stormClusterState");
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        try {
    +            this.localState = ConfigUtils.supervisorState(conf);
    +            this.localizer = Utils.createLocalizer(conf, ConfigUtils.supervisorLocalDir(conf));
    +        } catch (IOException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +        this.supervisorId = iSupervisor.getSupervisorId();
    +        this.assignmentId = iSupervisor.getAssignmentId();
    +
    +        try {
    +            this.hostName = Utils.hostname(conf);
    +        } catch (UnknownHostException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        this.currAssignment = new ConcurrentHashMap<>();
    +
    +        this.heartbeatTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.eventTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.blobUpdateTimer = new StormTimer("blob-update-timer", new DefaultUncaughtExceptionHandler());
    +
    +        this.assignmentVersions = new ConcurrentHashMap<>();
    +        this.syncRetry = new AtomicInteger(0);
    +        this.stormIdToProfileActions = new ConcurrentHashMap<>();
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            try {
    +                this.resourceIsolationManager = (CgroupManager) Utils.newInstance((String) conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN));
    +                this.resourceIsolationManager.prepare(conf);
    +                LOG.info("Using resource isolation plugin {} {}", conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN), resourceIsolationManager);
    +            } catch (IOException e) {
    +                throw Utils.wrapInRuntime(e);
    +            }
    +        } else {
    +            this.resourceIsolationManager = null;
    +        }
    +    }
    +
    +    public ConcurrentHashMap<String, List<ProfileRequest>> getStormIdToProfileActions() {
    +        return stormIdToProfileActions;
    +    }
    +
    +    public void setStormIdToProfileActions(Map<String, List<ProfileRequest>> stormIdToProfileActions) {
    +        this.stormIdToProfileActions.clear();
    +        this.stormIdToProfileActions.putAll(stormIdToProfileActions);
    +    }
    +
    +    public Map getConf() {
    +        return conf;
    +    }
    +
    +    public void setConf(Map conf) {
    +        this.conf = conf;
    +    }
    +
    +    public IContext getSharedContext() {
    +        return sharedContext;
    +    }
    +
    +    public void setSharedContext(IContext sharedContext) {
    +        this.sharedContext = sharedContext;
    +    }
    +
    +    public boolean isActive() {
    +        return active;
    +    }
    +
    +    public void setActive(boolean active) {
    +        this.active = active;
    +    }
    +
    +    public ISupervisor getiSupervisor() {
    +        return iSupervisor;
    +    }
    +
    +    public void setiSupervisor(ISupervisor iSupervisor) {
    +        this.iSupervisor = iSupervisor;
    +    }
    +
    +    public Utils.UptimeComputer getUpTime() {
    +        return upTime;
    +    }
    +
    +    public void setUpTime(Utils.UptimeComputer upTime) {
    +        this.upTime = upTime;
    +    }
    +
    +    public String getStormVersion() {
    +        return stormVersion;
    +    }
    +
    +    public void setStormVersion(String stormVersion) {
    +        this.stormVersion = stormVersion;
    +    }
    +
    +    public ConcurrentHashMap<String, String> getWorkerThreadPidsAtom() {
    +        return workerThreadPidsAtom;
    +    }
    +
    +    public void setWorkerThreadPidsAtom(ConcurrentHashMap<String, String> workerThreadPidsAtom) {
    +        this.workerThreadPidsAtom = workerThreadPidsAtom;
    +    }
    +
    +    public IStormClusterState getStormClusterState() {
    +        return stormClusterState;
    +    }
    +
    +    public void setStormClusterState(IStormClusterState stormClusterState) {
    +        this.stormClusterState = stormClusterState;
    +    }
    +
    +    public LocalState getLocalState() {
    +        return localState;
    +    }
    +
    +    public void setLocalState(LocalState localState) {
    +        this.localState = localState;
    +    }
    +
    +    public String getSupervisorId() {
    +        return supervisorId;
    +    }
    +
    +    public void setSupervisorId(String supervisorId) {
    +        this.supervisorId = supervisorId;
    +    }
    +
    +    public String getAssignmentId() {
    +        return assignmentId;
    +    }
    +
    +    public void setAssignmentId(String assignmentId) {
    +        this.assignmentId = assignmentId;
    +    }
    +
    +    public String getHostName() {
    +        return hostName;
    +    }
    +
    +    public void setHostName(String hostName) {
    +        this.hostName = hostName;
    +    }
    +
    +    public ConcurrentHashMap<Long, LocalAssignment> getCurrAssignment() {
    +        return currAssignment;
    +    }
    +
    +    public void setCurrAssignment(Map<Long, LocalAssignment> currAssignment) {
    +        this.currAssignment.clear();
    +        this.currAssignment.putAll(currAssignment);
    +    }
    +
    +    public StormTimer getHeartbeatTimer() {
    +        return heartbeatTimer;
    +    }
    +
    +    public void setHeartbeatTimer(StormTimer heartbeatTimer) {
    --- End diff --
    
    Not used


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55583857
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/Supervisor.java ---
    @@ -0,0 +1,196 @@
    +/**
    + * 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.supervisor;
    +
    +import com.codahale.metrics.Gauge;
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.commons.io.FileUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.daemon.supervisor.timer.RunProfilerActions;
    +import org.apache.storm.daemon.supervisor.timer.SupervisorHealthCheck;
    +import org.apache.storm.daemon.supervisor.timer.SupervisorHeartbeat;
    +import org.apache.storm.daemon.supervisor.timer.UpdateBlobs;
    +import org.apache.storm.event.EventManagerImp;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.InterruptedIOException;
    +import java.util.Collection;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +
    +public class Supervisor {
    +    private static Logger LOG = LoggerFactory.getLogger(Supervisor.class);
    +
    +    //TODO: to be removed after porting worker.clj. localSyncProcess is intended to start local supervisor
    +    private SyncProcessEvent localSyncProcess;
    +
    +    public void setLocalSyncProcess(SyncProcessEvent localSyncProcess) {
    +        this.localSyncProcess = localSyncProcess;
    +    }
    +
    +
    +    /**
    +     * in local state, supervisor stores who its current assignments are another thread launches events to restart any dead processes if necessary
    +     * 
    +     * @param conf
    +     * @param sharedContext
    +     * @param iSupervisor
    +     * @return
    +     * @throws Exception
    +     */
    +    public SupervisorManger mkSupervisor(final Map conf, IContext sharedContext, ISupervisor iSupervisor) throws Exception {
    +        SupervisorManger supervisorManger = null;
    +        try {
    +            LOG.info("Starting Supervisor with conf {}", conf);
    +            iSupervisor.prepare(conf, ConfigUtils.supervisorIsupervisorDir(conf));
    +            String path = ConfigUtils.supervisorTmpDir(conf);
    +            FileUtils.cleanDirectory(new File(path));
    +
    +            final SupervisorData supervisorData = new SupervisorData(conf, sharedContext, iSupervisor);
    +            Localizer localizer = supervisorData.getLocalizer();
    +
    +            SupervisorHeartbeat hb = new SupervisorHeartbeat(conf, supervisorData);
    +            hb.run();
    +            // should synchronize supervisor so it doesn't launch anything after being down (optimization)
    +            Integer heartbeatFrequency = Utils.getInt(conf.get(Config.SUPERVISOR_HEARTBEAT_FREQUENCY_SECS));
    +            supervisorData.getHeartbeatTimer().scheduleRecurring(0, heartbeatFrequency, hb);
    +
    +            Set<String> downdedStormId = SupervisorUtils.readDownLoadedStormIds(conf);
    +            for (String stormId : downdedStormId) {
    +                SupervisorUtils.addBlobReferences(localizer, stormId, conf);
    +            }
    +            // do this after adding the references so we don't try to clean things being used
    +            localizer.startCleaner();
    +
    +            EventManagerImp syncSupEventManager = new EventManagerImp(false);
    +            EventManagerImp syncProcessManager = new EventManagerImp(false);
    +
    +            SyncProcessEvent syncProcessEvent = null;
    +            if (ConfigUtils.isLocalMode(conf)){
    +                localSyncProcess.init(supervisorData);
    +                syncProcessEvent = localSyncProcess;
    +            }else{
    +                syncProcessEvent = new SyncProcessEvent(supervisorData);
    +            }
    +
    +            SyncSupervisorEvent syncSupervisorEvent = new SyncSupervisorEvent(supervisorData, syncProcessEvent, syncSupEventManager, syncProcessManager);
    +            UpdateBlobs updateBlobsThread = new UpdateBlobs(supervisorData);
    +            RunProfilerActions runProfilerActionThread = new RunProfilerActions(supervisorData);
    +
    +            if ((Boolean) conf.get(Config.SUPERVISOR_ENABLE)) {
    +                StormTimer eventTimer = supervisorData.getEventTimer();
    +                // This isn't strictly necessary, but it doesn't hurt and ensures that the machine stays up
    +                // to date even if callbacks don't all work exactly right
    +                eventTimer.scheduleRecurring(0, 10, new EventManagerPushCallback(syncSupervisorEvent, syncSupEventManager));
    +
    +                eventTimer.scheduleRecurring(0, Utils.getInt(conf.get(Config.SUPERVISOR_MONITOR_FREQUENCY_SECS)),
    +                        new EventManagerPushCallback(syncProcessEvent, syncProcessManager));
    +
    +                // Blob update thread. Starts with 30 seconds delay, every 30 seconds
    +                supervisorData.getBlobUpdateTimer().scheduleRecurring(30, 30, new EventManagerPushCallback(updateBlobsThread, syncSupEventManager));
    +
    +                // supervisor health check
    +                eventTimer.scheduleRecurring(300, 300, new SupervisorHealthCheck(supervisorData));
    +
    +                // Launch a thread that Runs profiler commands . Starts with 30 seconds delay, every 30 seconds
    +                eventTimer.scheduleRecurring(30, 30, new EventManagerPushCallback(runProfilerActionThread, syncSupEventManager));
    +            }
    +            LOG.info("Starting supervisor with id {} at host {}.", supervisorData.getSupervisorId(), supervisorData.getHostName() );
    +            supervisorManger = new SupervisorManger(supervisorData, syncSupEventManager, syncProcessManager);
    +        } catch (Throwable t) {
    +            if (Utils.exceptionCauseIsInstanceOf(InterruptedIOException.class, t)) {
    +                throw t;
    +            } else if (Utils.exceptionCauseIsInstanceOf(InterruptedException.class, t)) {
    +                throw t;
    +            } else {
    +                LOG.error("Error on initialization of server supervisor: {}", t);
    +                Utils.exitProcess(13, "Error on initialization");
    +            }
    +        }
    +        return supervisorManger;
    +    }
    +
    +    /**
    +     * start distribute supervisor
    +     */
    +    private void launch() {
    --- End diff --
    
    If we cannot make it static, that is fine, but it still needs to take an ISupervisor instance as a parameter somewhere.


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55639523
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/ShutdownWork.java ---
    @@ -0,0 +1,125 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.ProcessSimulator;
    +import org.apache.storm.daemon.Shutdownable;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.IOException;
    +import java.util.*;
    +
    +public  class ShutdownWork implements Shutdownable {
    +
    +    private static Logger LOG = LoggerFactory.getLogger(ShutdownWork.class);
    +
    +    public void shutWorker(SupervisorData supervisorData, String workerId) throws IOException, InterruptedException {
    +        LOG.info("Shutting down {}:{}", supervisorData.getSupervisorId(), workerId);
    +        Map conf = supervisorData.getConf();
    +        Collection<String> pids = Utils.readDirContents(ConfigUtils.workerPidsRoot(conf, workerId));
    +        Integer shutdownSleepSecs = Utils.getInt(conf.get(Config.SUPERVISOR_WORKER_SHUTDOWN_SLEEP_SECS));
    +        Boolean asUser = Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false);
    +        String user = ConfigUtils.getWorkerUser(conf, workerId);
    +        String threadPid = supervisorData.getWorkerThreadPidsAtom().get(workerId);
    +        if (StringUtils.isNotBlank(threadPid)) {
    +            ProcessSimulator.killProcess(threadPid);
    +        }
    +
    +        for (String pid : pids) {
    +            if (asUser) {
    +                List<String> commands = new ArrayList<>();
    +                commands.add("signal");
    +                commands.add(pid);
    +                commands.add("15");
    +                String logPrefix = "kill - 15 " + pid;
    +                SupervisorUtils.workerLauncherAndWait(conf, user, commands, null, logPrefix);
    +            } else {
    +                Utils.killProcessWithSigTerm(pid);
    +            }
    +        }
    +
    +        if (pids.size() > 0) {
    +            LOG.info("Sleep {} seconds for execution of cleanup threads on worker.", shutdownSleepSecs);
    +            Time.sleepSecs(shutdownSleepSecs);
    +        }
    +
    +        for (String pid : pids) {
    +            if (asUser) {
    +                List<String> commands = new ArrayList<>();
    +                commands.add("signal");
    +                commands.add(pid);
    +                commands.add("9");
    +                String logPrefix = "kill - 9 " + pid;
    --- End diff --
    
    nit. -9


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55583696
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/Supervisor.java ---
    @@ -0,0 +1,196 @@
    +/**
    + * 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.supervisor;
    +
    +import com.codahale.metrics.Gauge;
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.commons.io.FileUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.daemon.supervisor.timer.RunProfilerActions;
    +import org.apache.storm.daemon.supervisor.timer.SupervisorHealthCheck;
    +import org.apache.storm.daemon.supervisor.timer.SupervisorHeartbeat;
    +import org.apache.storm.daemon.supervisor.timer.UpdateBlobs;
    +import org.apache.storm.event.EventManagerImp;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.InterruptedIOException;
    +import java.util.Collection;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +
    +public class Supervisor {
    +    private static Logger LOG = LoggerFactory.getLogger(Supervisor.class);
    +
    +    //TODO: to be removed after porting worker.clj. localSyncProcess is intended to start local supervisor
    +    private SyncProcessEvent localSyncProcess;
    +
    +    public void setLocalSyncProcess(SyncProcessEvent localSyncProcess) {
    +        this.localSyncProcess = localSyncProcess;
    +    }
    +
    +
    +    /**
    +     * in local state, supervisor stores who its current assignments are another thread launches events to restart any dead processes if necessary
    +     * 
    +     * @param conf
    +     * @param sharedContext
    +     * @param iSupervisor
    +     * @return
    +     * @throws Exception
    +     */
    +    public SupervisorManger mkSupervisor(final Map conf, IContext sharedContext, ISupervisor iSupervisor) throws Exception {
    +        SupervisorManger supervisorManger = null;
    +        try {
    +            LOG.info("Starting Supervisor with conf {}", conf);
    +            iSupervisor.prepare(conf, ConfigUtils.supervisorIsupervisorDir(conf));
    +            String path = ConfigUtils.supervisorTmpDir(conf);
    +            FileUtils.cleanDirectory(new File(path));
    +
    +            final SupervisorData supervisorData = new SupervisorData(conf, sharedContext, iSupervisor);
    +            Localizer localizer = supervisorData.getLocalizer();
    +
    +            SupervisorHeartbeat hb = new SupervisorHeartbeat(conf, supervisorData);
    +            hb.run();
    +            // should synchronize supervisor so it doesn't launch anything after being down (optimization)
    +            Integer heartbeatFrequency = Utils.getInt(conf.get(Config.SUPERVISOR_HEARTBEAT_FREQUENCY_SECS));
    +            supervisorData.getHeartbeatTimer().scheduleRecurring(0, heartbeatFrequency, hb);
    +
    +            Set<String> downdedStormId = SupervisorUtils.readDownLoadedStormIds(conf);
    +            for (String stormId : downdedStormId) {
    +                SupervisorUtils.addBlobReferences(localizer, stormId, conf);
    +            }
    +            // do this after adding the references so we don't try to clean things being used
    +            localizer.startCleaner();
    +
    +            EventManagerImp syncSupEventManager = new EventManagerImp(false);
    +            EventManagerImp syncProcessManager = new EventManagerImp(false);
    +
    +            SyncProcessEvent syncProcessEvent = null;
    +            if (ConfigUtils.isLocalMode(conf)){
    +                localSyncProcess.init(supervisorData);
    +                syncProcessEvent = localSyncProcess;
    +            }else{
    +                syncProcessEvent = new SyncProcessEvent(supervisorData);
    +            }
    +
    +            SyncSupervisorEvent syncSupervisorEvent = new SyncSupervisorEvent(supervisorData, syncProcessEvent, syncSupEventManager, syncProcessManager);
    +            UpdateBlobs updateBlobsThread = new UpdateBlobs(supervisorData);
    +            RunProfilerActions runProfilerActionThread = new RunProfilerActions(supervisorData);
    +
    +            if ((Boolean) conf.get(Config.SUPERVISOR_ENABLE)) {
    +                StormTimer eventTimer = supervisorData.getEventTimer();
    +                // This isn't strictly necessary, but it doesn't hurt and ensures that the machine stays up
    +                // to date even if callbacks don't all work exactly right
    +                eventTimer.scheduleRecurring(0, 10, new EventManagerPushCallback(syncSupervisorEvent, syncSupEventManager));
    +
    +                eventTimer.scheduleRecurring(0, Utils.getInt(conf.get(Config.SUPERVISOR_MONITOR_FREQUENCY_SECS)),
    +                        new EventManagerPushCallback(syncProcessEvent, syncProcessManager));
    +
    +                // Blob update thread. Starts with 30 seconds delay, every 30 seconds
    +                supervisorData.getBlobUpdateTimer().scheduleRecurring(30, 30, new EventManagerPushCallback(updateBlobsThread, syncSupEventManager));
    +
    +                // supervisor health check
    +                eventTimer.scheduleRecurring(300, 300, new SupervisorHealthCheck(supervisorData));
    +
    +                // Launch a thread that Runs profiler commands . Starts with 30 seconds delay, every 30 seconds
    +                eventTimer.scheduleRecurring(30, 30, new EventManagerPushCallback(runProfilerActionThread, syncSupEventManager));
    +            }
    +            LOG.info("Starting supervisor with id {} at host {}.", supervisorData.getSupervisorId(), supervisorData.getHostName() );
    +            supervisorManger = new SupervisorManger(supervisorData, syncSupEventManager, syncProcessManager);
    +        } catch (Throwable t) {
    +            if (Utils.exceptionCauseIsInstanceOf(InterruptedIOException.class, t)) {
    +                throw t;
    +            } else if (Utils.exceptionCauseIsInstanceOf(InterruptedException.class, t)) {
    +                throw t;
    +            } else {
    +                LOG.error("Error on initialization of server supervisor: {}", t);
    +                Utils.exitProcess(13, "Error on initialization");
    +            }
    +        }
    +        return supervisorManger;
    +    }
    +
    +    /**
    +     * start distribute supervisor
    +     */
    +    private void launch() {
    +        LOG.info("Starting supervisor for storm version '{}'.", VersionInfo.getVersion());
    +        SupervisorManger supervisorManager;
    +        try {
    +            Map<Object, Object> conf = Utils.readStormConfig();
    +            if (ConfigUtils.isLocalMode(conf)) {
    +                throw new IllegalArgumentException("Cannot start server in local mode!");
    +            }
    +            ISupervisor iSupervisor = new StandaloneSupervisor();
    +            supervisorManager = mkSupervisor(conf, null, iSupervisor);
    +            if (supervisorManager != null)
    +                Utils.addShutdownHookWithForceKillIn1Sec(supervisorManager);
    +            registerWorkerNumGauge("drpc:num-execute-http-requests", conf);
    +            startMetricsReporters(conf);
    +        } catch (Exception e) {
    +            LOG.error("Failed to start supervisor\n", e);
    +            System.exit(1);
    +        }
    +    }
    +
    +    // To be removed
    +    private void registerWorkerNumGauge(String name, final Map conf) {
    +        MetricRegistry metricRegistry = new MetricRegistry();
    --- End diff --
    
    Please use the StormMericsRegistry instead.


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55583753
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/Supervisor.java ---
    @@ -0,0 +1,196 @@
    +/**
    + * 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.supervisor;
    +
    +import com.codahale.metrics.Gauge;
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.commons.io.FileUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.daemon.supervisor.timer.RunProfilerActions;
    +import org.apache.storm.daemon.supervisor.timer.SupervisorHealthCheck;
    +import org.apache.storm.daemon.supervisor.timer.SupervisorHeartbeat;
    +import org.apache.storm.daemon.supervisor.timer.UpdateBlobs;
    +import org.apache.storm.event.EventManagerImp;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.InterruptedIOException;
    +import java.util.Collection;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +
    +public class Supervisor {
    +    private static Logger LOG = LoggerFactory.getLogger(Supervisor.class);
    +
    +    //TODO: to be removed after porting worker.clj. localSyncProcess is intended to start local supervisor
    +    private SyncProcessEvent localSyncProcess;
    +
    +    public void setLocalSyncProcess(SyncProcessEvent localSyncProcess) {
    +        this.localSyncProcess = localSyncProcess;
    +    }
    +
    +
    +    /**
    +     * in local state, supervisor stores who its current assignments are another thread launches events to restart any dead processes if necessary
    +     * 
    +     * @param conf
    +     * @param sharedContext
    +     * @param iSupervisor
    +     * @return
    +     * @throws Exception
    +     */
    +    public SupervisorManger mkSupervisor(final Map conf, IContext sharedContext, ISupervisor iSupervisor) throws Exception {
    +        SupervisorManger supervisorManger = null;
    +        try {
    +            LOG.info("Starting Supervisor with conf {}", conf);
    +            iSupervisor.prepare(conf, ConfigUtils.supervisorIsupervisorDir(conf));
    +            String path = ConfigUtils.supervisorTmpDir(conf);
    +            FileUtils.cleanDirectory(new File(path));
    +
    +            final SupervisorData supervisorData = new SupervisorData(conf, sharedContext, iSupervisor);
    +            Localizer localizer = supervisorData.getLocalizer();
    +
    +            SupervisorHeartbeat hb = new SupervisorHeartbeat(conf, supervisorData);
    +            hb.run();
    +            // should synchronize supervisor so it doesn't launch anything after being down (optimization)
    +            Integer heartbeatFrequency = Utils.getInt(conf.get(Config.SUPERVISOR_HEARTBEAT_FREQUENCY_SECS));
    +            supervisorData.getHeartbeatTimer().scheduleRecurring(0, heartbeatFrequency, hb);
    +
    +            Set<String> downdedStormId = SupervisorUtils.readDownLoadedStormIds(conf);
    +            for (String stormId : downdedStormId) {
    +                SupervisorUtils.addBlobReferences(localizer, stormId, conf);
    +            }
    +            // do this after adding the references so we don't try to clean things being used
    +            localizer.startCleaner();
    +
    +            EventManagerImp syncSupEventManager = new EventManagerImp(false);
    +            EventManagerImp syncProcessManager = new EventManagerImp(false);
    +
    +            SyncProcessEvent syncProcessEvent = null;
    +            if (ConfigUtils.isLocalMode(conf)){
    +                localSyncProcess.init(supervisorData);
    +                syncProcessEvent = localSyncProcess;
    +            }else{
    +                syncProcessEvent = new SyncProcessEvent(supervisorData);
    +            }
    +
    +            SyncSupervisorEvent syncSupervisorEvent = new SyncSupervisorEvent(supervisorData, syncProcessEvent, syncSupEventManager, syncProcessManager);
    +            UpdateBlobs updateBlobsThread = new UpdateBlobs(supervisorData);
    +            RunProfilerActions runProfilerActionThread = new RunProfilerActions(supervisorData);
    +
    +            if ((Boolean) conf.get(Config.SUPERVISOR_ENABLE)) {
    +                StormTimer eventTimer = supervisorData.getEventTimer();
    +                // This isn't strictly necessary, but it doesn't hurt and ensures that the machine stays up
    +                // to date even if callbacks don't all work exactly right
    +                eventTimer.scheduleRecurring(0, 10, new EventManagerPushCallback(syncSupervisorEvent, syncSupEventManager));
    +
    +                eventTimer.scheduleRecurring(0, Utils.getInt(conf.get(Config.SUPERVISOR_MONITOR_FREQUENCY_SECS)),
    +                        new EventManagerPushCallback(syncProcessEvent, syncProcessManager));
    +
    +                // Blob update thread. Starts with 30 seconds delay, every 30 seconds
    +                supervisorData.getBlobUpdateTimer().scheduleRecurring(30, 30, new EventManagerPushCallback(updateBlobsThread, syncSupEventManager));
    +
    +                // supervisor health check
    +                eventTimer.scheduleRecurring(300, 300, new SupervisorHealthCheck(supervisorData));
    +
    +                // Launch a thread that Runs profiler commands . Starts with 30 seconds delay, every 30 seconds
    +                eventTimer.scheduleRecurring(30, 30, new EventManagerPushCallback(runProfilerActionThread, syncSupEventManager));
    +            }
    +            LOG.info("Starting supervisor with id {} at host {}.", supervisorData.getSupervisorId(), supervisorData.getHostName() );
    +            supervisorManger = new SupervisorManger(supervisorData, syncSupEventManager, syncProcessManager);
    +        } catch (Throwable t) {
    +            if (Utils.exceptionCauseIsInstanceOf(InterruptedIOException.class, t)) {
    +                throw t;
    +            } else if (Utils.exceptionCauseIsInstanceOf(InterruptedException.class, t)) {
    +                throw t;
    +            } else {
    +                LOG.error("Error on initialization of server supervisor: {}", t);
    +                Utils.exitProcess(13, "Error on initialization");
    +            }
    +        }
    +        return supervisorManger;
    +    }
    +
    +    /**
    +     * start distribute supervisor
    +     */
    +    private void launch() {
    +        LOG.info("Starting supervisor for storm version '{}'.", VersionInfo.getVersion());
    +        SupervisorManger supervisorManager;
    +        try {
    +            Map<Object, Object> conf = Utils.readStormConfig();
    +            if (ConfigUtils.isLocalMode(conf)) {
    +                throw new IllegalArgumentException("Cannot start server in local mode!");
    +            }
    +            ISupervisor iSupervisor = new StandaloneSupervisor();
    +            supervisorManager = mkSupervisor(conf, null, iSupervisor);
    +            if (supervisorManager != null)
    +                Utils.addShutdownHookWithForceKillIn1Sec(supervisorManager);
    +            registerWorkerNumGauge("drpc:num-execute-http-requests", conf);
    +            startMetricsReporters(conf);
    +        } catch (Exception e) {
    +            LOG.error("Failed to start supervisor\n", e);
    +            System.exit(1);
    +        }
    +    }
    +
    +    // To be removed
    +    private void registerWorkerNumGauge(String name, final Map conf) {
    +        MetricRegistry metricRegistry = new MetricRegistry();
    +        metricRegistry.remove(name);
    +        metricRegistry.register(name, new Gauge<Integer>() {
    +            @Override
    +            public Integer getValue() {
    +                Collection<String> pids = SupervisorUtils.myWorkerIds(conf);
    +                return pids.size();
    +            }
    +        });
    +    }
    +
    +    // To be removed
    +    private void startMetricsReporters(Map conf) {
    +        List<PreparableReporter> preparableReporters = MetricsUtils.getPreparableReporters(conf);
    --- End diff --
    
    Here to please use the code we already merged in.


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#issuecomment-197645649
  
    @revans2  can you look at it again ?


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55938170
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/Supervisor.java ---
    @@ -0,0 +1,178 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.daemon.supervisor.timer.RunProfilerActions;
    +import org.apache.storm.daemon.supervisor.timer.SupervisorHealthCheck;
    +import org.apache.storm.daemon.supervisor.timer.SupervisorHeartbeat;
    +import org.apache.storm.daemon.supervisor.timer.UpdateBlobs;
    +import org.apache.storm.event.EventManagerImp;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.metric.StormMetricsRegistry;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.InterruptedIOException;
    +import java.util.Collection;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.Callable;
    +
    +public class Supervisor {
    +    private static Logger LOG = LoggerFactory.getLogger(Supervisor.class);
    +
    +    // TODO: to be removed after porting worker.clj. localSyncProcess is intended to start local supervisor
    +    private SyncProcessEvent localSyncProcess;
    +
    +    public void setLocalSyncProcess(SyncProcessEvent localSyncProcess) {
    +        this.localSyncProcess = localSyncProcess;
    +    }
    +
    +    /**
    +     * in local state, supervisor stores who its current assignments are another thread launches events to restart any dead processes if necessary
    +     * 
    +     * @param conf
    +     * @param sharedContext
    +     * @param iSupervisor
    +     * @return
    +     * @throws Exception
    +     */
    +    public SupervisorManger mkSupervisor(final Map conf, IContext sharedContext, ISupervisor iSupervisor) throws Exception {
    +        SupervisorManger supervisorManger = null;
    +        try {
    +            LOG.info("Starting Supervisor with conf {}", conf);
    +            iSupervisor.prepare(conf, ConfigUtils.supervisorIsupervisorDir(conf));
    +            String path = ConfigUtils.supervisorTmpDir(conf);
    +            FileUtils.cleanDirectory(new File(path));
    +
    +            final SupervisorData supervisorData = new SupervisorData(conf, sharedContext, iSupervisor);
    +            Localizer localizer = supervisorData.getLocalizer();
    +
    +            SupervisorHeartbeat hb = new SupervisorHeartbeat(conf, supervisorData);
    +            hb.run();
    +            // should synchronize supervisor so it doesn't launch anything after being down (optimization)
    +            Integer heartbeatFrequency = Utils.getInt(conf.get(Config.SUPERVISOR_HEARTBEAT_FREQUENCY_SECS));
    +            supervisorData.getHeartbeatTimer().scheduleRecurring(0, heartbeatFrequency, hb);
    +
    +            Set<String> downdedStormId = SupervisorUtils.readDownLoadedStormIds(conf);
    --- End diff --
    
    nit. downloadedStormIds


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55692930
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorUtils.java ---
    @@ -0,0 +1,273 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.curator.utils.PathUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.localizer.LocalResource;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.IOException;
    +import java.net.URLDecoder;
    +import java.util.*;
    +
    +public class SupervisorUtils {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorUtils.class);
    +
    +    private static final SupervisorUtils INSTANCE = new SupervisorUtils();
    +    private static SupervisorUtils _instance = INSTANCE;
    +
    +    public static void setInstance(SupervisorUtils u) {
    +        _instance = u;
    +    }
    +
    +    public static void resetInstance() {
    +        _instance = INSTANCE;
    +    }
    +
    +    public static Process workerLauncher(Map conf, String user, List<String> args, Map<String, String> environment, final String logPreFix,
    --- End diff --
    
    I never understood why is it called worker launcher. One may think that it launches a worker but it doesn't. I wish if it could be renamed to something else. 


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55694794
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncProcessEvent.java ---
    @@ -0,0 +1,669 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.ExecutorInfo;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.WorkerResources;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +import org.yaml.snakeyaml.Yaml;
    +
    +import java.io.File;
    +import java.io.FileWriter;
    +import java.io.IOException;
    +import java.util.*;
    +
    +/**
    + * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file - rmr
    + * heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new worker
    + * ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait for workers
    + * launch
    + */
    +public class SyncProcessEvent extends ShutdownWork implements Runnable {
    +
    +    private static Logger LOG = LoggerFactory.getLogger(SyncProcessEvent.class);
    +
    +    private  LocalState localState;
    +
    +    private SupervisorData supervisorData;
    +
    +    private class ProcessExitCallback implements Utils.ExitCodeCallable {
    +        private final String logPrefix;
    +        private final String workerId;
    +
    +        public ProcessExitCallback(String logPrefix, String workerId) {
    +            this.logPrefix = logPrefix;
    +            this.workerId = workerId;
    +        }
    +
    +        @Override
    +        public Object call() throws Exception {
    +            return null;
    +        }
    +
    +        @Override
    +        public Object call(int exitCode) {
    +            LOG.info("{} exited with code: {}", logPrefix, exitCode);
    +            supervisorData.getDeadWorkers().add(workerId);
    +            return null;
    +        }
    +    }
    +
    +    public SyncProcessEvent(){
    +
    +    }
    +    public SyncProcessEvent(SupervisorData supervisorData) {
    +        init(supervisorData);
    +    }
    +
    +    //TODO: initData is intended to local supervisor, so we will remove them after porting worker.clj to java
    +    public void init(SupervisorData supervisorData){
    +        this.supervisorData = supervisorData;
    +        this.localState = supervisorData.getLocalState();
    +    }
    +
    +
    +    /**
    +     * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file -
    +     * rmr heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new
    +     * worker ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait
    +     * for workers launch
    +     */
    +    @Override
    +    public void run() {
    +        LOG.debug("Syncing processes");
    +        try {
    +            Map conf = supervisorData.getConf();
    +            Map<Integer, LocalAssignment> assignedExecutors = localState.getLocalAssignmentsMap();
    +
    +            if (assignedExecutors == null) {
    +                assignedExecutors = new HashMap<>();
    +            }
    +            int now = Time.currentTimeSecs();
    +
    +            Map<String, StateHeartbeat> localWorkerStats = getLocalWorkerStats(supervisorData, assignedExecutors, now);
    +
    +            Set<String> keeperWorkerIds = new HashSet<>();
    +            Set<Integer> keepPorts = new HashSet<>();
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() == State.valid) {
    +                    keeperWorkerIds.add(entry.getKey());
    +                    keepPorts.add(stateHeartbeat.getHeartbeat().get_port());
    +                }
    +            }
    +            Map<Integer, LocalAssignment> reassignExecutors = getReassignExecutors(assignedExecutors, keepPorts);
    +            Map<Integer, String> newWorkerIds = new HashMap<>();
    +            for (Integer port : reassignExecutors.keySet()) {
    +                newWorkerIds.put(port, Utils.uuid());
    +            }
    +            LOG.debug("Syncing processes");
    +            LOG.debug("Assigned executors: {}", assignedExecutors);
    +            LOG.debug("Allocated: {}", localWorkerStats);
    +
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() != State.valid) {
    +                    LOG.info("Shutting down and clearing state for id {}, Current supervisor time: {}, State: {}, Heartbeat: {}", entry.getKey(), now,
    +                            stateHeartbeat.getState(), stateHeartbeat.getHeartbeat());
    +                    shutWorker(supervisorData, entry.getKey());
    +                }
    +            }
    +            // start new workers
    +            Map<String, Integer> newWorkerPortToIds = startNewWorkers(newWorkerIds, reassignExecutors);
    +
    +            Map<String, Integer> allWorkerPortToIds = new HashMap<>();
    +            Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +            for (String keeper : keeperWorkerIds) {
    +                allWorkerPortToIds.put(keeper, approvedWorkers.get(keeper));
    +            }
    +            allWorkerPortToIds.putAll(newWorkerPortToIds);
    +            localState.setApprovedWorkers(allWorkerPortToIds);
    +            waitForWorkersLaunch(conf, newWorkerPortToIds.keySet());
    +
    +        } catch (Exception e) {
    +            LOG.error("Failed Sync Process", e);
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +    }
    +
    +    protected void waitForWorkersLaunch(Map conf, Set<String> workerIds) throws Exception {
    +        int startTime = Time.currentTimeSecs();
    +        int timeOut = (int) conf.get(Config.NIMBUS_SUPERVISOR_TIMEOUT_SECS);
    +        for (String workerId : workerIds) {
    +            LocalState localState = ConfigUtils.workerState(conf, workerId);
    +            while (true) {
    +                LSWorkerHeartbeat hb = localState.getWorkerHeartBeat();
    +                if (hb != null || (Time.currentTimeSecs() - startTime) > timeOut)
    +                    break;
    +                LOG.info("{} still hasn't started", workerId);
    +                Time.sleep(500);
    +            }
    +            if (localState.getWorkerHeartBeat() == null) {
    +                LOG.info("Worker {} failed to start", workerId);
    +            }
    +        }
    +    }
    +
    +    protected Map<Integer, LocalAssignment> getReassignExecutors(Map<Integer, LocalAssignment> assignExecutors, Set<Integer> keepPorts) {
    +        Map<Integer, LocalAssignment> reassignExecutors = new HashMap<>();
    +        reassignExecutors.putAll(assignExecutors);
    +        for (Integer port : keepPorts) {
    +            reassignExecutors.remove(port);
    +        }
    +        return reassignExecutors;
    +    }
    +
    +
    +
    +    /**
    +     * Returns map from worker id to worker heartbeat. if the heartbeat is nil, then the worker is dead
    +     * 
    +     * @param assignedExecutors
    +     * @return
    +     * @throws Exception
    +     */
    +    public Map<String, StateHeartbeat> getLocalWorkerStats(SupervisorData supervisorData, Map<Integer, LocalAssignment> assignedExecutors, int now) throws Exception {
    +        Map<String, StateHeartbeat> workerIdHbstate = new HashMap<>();
    +        Map conf = supervisorData.getConf();
    +        LocalState localState = supervisorData.getLocalState();
    +        Map<String, LSWorkerHeartbeat> idToHeartbeat = SupervisorUtils.readWorkerHeartbeats(conf);
    +        Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +        Set<String> approvedIds = new HashSet<>();
    +        if (approvedWorkers != null) {
    +            approvedIds.addAll(approvedWorkers.keySet());
    +        }
    +        for (Map.Entry<String, LSWorkerHeartbeat> entry : idToHeartbeat.entrySet()) {
    +            String workerId = entry.getKey();
    +            LSWorkerHeartbeat whb = entry.getValue();
    +            State state;
    +            if (whb == null) {
    +                state = State.notStarted;
    +            } else if (!approvedIds.contains(workerId) || !matchesAssignment(whb, assignedExecutors)) {
    +                state = State.disallowed;
    +            } else if (supervisorData.getDeadWorkers().contains(workerId)) {
    +                LOG.info("Worker Process {}as died", workerId);
    +                state = State.timedOut;
    +            } else if (SupervisorUtils.isWorkerHbTimedOut(now, whb, conf)) {
    +                state = State.timedOut;
    +            } else {
    +                state = State.valid;
    +            }
    +            LOG.debug("Worker:{} state:{} WorkerHeartbeat:{} at supervisor time-secs {}", workerId, state, whb, now);
    +            workerIdHbstate.put(workerId, new StateHeartbeat(state, whb));
    +        }
    +        return workerIdHbstate;
    +    }
    +
    +    protected boolean matchesAssignment(LSWorkerHeartbeat whb, Map<Integer, LocalAssignment> assignedExecutors) {
    +        LocalAssignment localAssignment = assignedExecutors.get(whb.get_port());
    +        if (localAssignment == null || !localAssignment.get_topology_id().equals(whb.get_topology_id())) {
    +            return false;
    +        }
    +        List<ExecutorInfo> executorInfos = new ArrayList<>();
    +        executorInfos.addAll(whb.get_executors());
    +        // remove SYSTEM_EXECUTOR_ID
    +        executorInfos.remove(new ExecutorInfo(-1, -1));
    +        List<ExecutorInfo> localExecuorInfos = localAssignment.get_executors();
    +
    +        if (localExecuorInfos.size() != executorInfos.size())
    +            return false;
    +
    +        for (ExecutorInfo executorInfo : localExecuorInfos){
    +            if (!localExecuorInfos.contains(executorInfo))
    +                return false;
    +        }
    +        return true;
    +    }
    +
    +    /**
    +     * launch a worker in local mode.
    +     */
    +    protected void launchWorker(SupervisorData supervisorData, String stormId, Long port, String workerId, WorkerResources resources) throws IOException {
    +        // port this function after porting worker to java
    +    }
    +
    +    protected String getWorkerClassPath(String stormJar, Map stormConf) {
    +        List<String> topoClasspath = new ArrayList<>();
    +        Object object = stormConf.get(Config.TOPOLOGY_CLASSPATH);
    +
    +        if (object instanceof List) {
    +            topoClasspath.addAll((List<String>) object);
    +        } else if (object instanceof String){
    +            topoClasspath.add((String)object);
    +        }else {
    +            //ignore
    --- End diff --
    
    @revans2 the exception of topology will kill supervisor if we throw an exception. Do you think it is ok?


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55942812
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncProcessEvent.java ---
    @@ -0,0 +1,672 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.ExecutorInfo;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.WorkerResources;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +import org.yaml.snakeyaml.Yaml;
    +
    +import java.io.File;
    +import java.io.FileWriter;
    +import java.io.IOException;
    +import java.util.*;
    +
    +/**
    + * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file - rmr
    + * heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new worker
    + * ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait for workers
    + * launch
    + */
    +public class SyncProcessEvent implements Runnable {
    +
    +    private static Logger LOG = LoggerFactory.getLogger(SyncProcessEvent.class);
    +
    +    private  LocalState localState;
    +    private  SupervisorData supervisorData;
    +    public static final ExecutorInfo SYSTEM_EXECUTOR_INFO = new ExecutorInfo(-1, -1);
    +
    +    private class ProcessExitCallback implements Utils.ExitCodeCallable {
    +        private final String logPrefix;
    +        private final String workerId;
    +
    +        public ProcessExitCallback(String logPrefix, String workerId) {
    +            this.logPrefix = logPrefix;
    +            this.workerId = workerId;
    +        }
    +
    +        @Override
    +        public Object call() throws Exception {
    +            return null;
    +        }
    +
    +        @Override
    +        public Object call(int exitCode) {
    +            LOG.info("{} exited with code: {}", logPrefix, exitCode);
    +            supervisorData.getDeadWorkers().add(workerId);
    +            return null;
    +        }
    +    }
    +
    +    public SyncProcessEvent(){
    +
    +    }
    +    public SyncProcessEvent(SupervisorData supervisorData) {
    +        init(supervisorData);
    +    }
    +
    +    //TODO: initData is intended to local supervisor, so we will remove them after porting worker.clj to java
    +    public void init(SupervisorData supervisorData){
    +        this.supervisorData = supervisorData;
    +        this.localState = supervisorData.getLocalState();
    +    }
    +
    +
    +    /**
    +     * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file -
    +     * rmr heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new
    +     * worker ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait
    +     * for workers launch
    +     */
    +    @Override
    +    public void run() {
    +        LOG.debug("Syncing processes");
    +        try {
    +            Map conf = supervisorData.getConf();
    +            Map<Integer, LocalAssignment> assignedExecutors = localState.getLocalAssignmentsMap();
    +
    +            if (assignedExecutors == null) {
    +                assignedExecutors = new HashMap<>();
    +            }
    +            int now = Time.currentTimeSecs();
    +
    +            Map<String, StateHeartbeat> localWorkerStats = getLocalWorkerStats(supervisorData, assignedExecutors, now);
    +
    +            Set<String> keeperWorkerIds = new HashSet<>();
    +            Set<Integer> keepPorts = new HashSet<>();
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() == State.VALID) {
    +                    keeperWorkerIds.add(entry.getKey());
    +                    keepPorts.add(stateHeartbeat.getHeartbeat().get_port());
    +                }
    +            }
    +            Map<Integer, LocalAssignment> reassignExecutors = getReassignExecutors(assignedExecutors, keepPorts);
    +            Map<Integer, String> newWorkerIds = new HashMap<>();
    +            for (Integer port : reassignExecutors.keySet()) {
    +                newWorkerIds.put(port, Utils.uuid());
    +            }
    +            LOG.debug("Syncing processes");
    +            LOG.debug("Assigned executors: {}", assignedExecutors);
    +            LOG.debug("Allocated: {}", localWorkerStats);
    +
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() != State.VALID) {
    +                    LOG.info("Shutting down and clearing state for id {}, Current supervisor time: {}, State: {}, Heartbeat: {}", entry.getKey(), now,
    +                            stateHeartbeat.getState(), stateHeartbeat.getHeartbeat());
    +                    shutWorker(supervisorData, entry.getKey());
    +                }
    +            }
    +            // start new workers
    +            Map<String, Integer> newWorkerPortToIds = startNewWorkers(newWorkerIds, reassignExecutors);
    +
    +            Map<String, Integer> allWorkerPortToIds = new HashMap<>();
    +            Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +            for (String keeper : keeperWorkerIds) {
    +                allWorkerPortToIds.put(keeper, approvedWorkers.get(keeper));
    +            }
    +            allWorkerPortToIds.putAll(newWorkerPortToIds);
    +            localState.setApprovedWorkers(allWorkerPortToIds);
    +            waitForWorkersLaunch(conf, newWorkerPortToIds.keySet());
    +
    +        } catch (Exception e) {
    +            LOG.error("Failed Sync Process", e);
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +    }
    +
    +    protected void waitForWorkersLaunch(Map conf, Set<String> workerIds) throws Exception {
    +        int startTime = Time.currentTimeSecs();
    +        int timeOut = (int) conf.get(Config.NIMBUS_SUPERVISOR_TIMEOUT_SECS);
    +        for (String workerId : workerIds) {
    +            LocalState localState = ConfigUtils.workerState(conf, workerId);
    +            while (true) {
    +                LSWorkerHeartbeat hb = localState.getWorkerHeartBeat();
    +                if (hb != null || (Time.currentTimeSecs() - startTime) > timeOut)
    +                    break;
    +                LOG.info("{} still hasn't started", workerId);
    +                Time.sleep(500);
    +            }
    +            if (localState.getWorkerHeartBeat() == null) {
    +                LOG.info("Worker {} failed to start", workerId);
    +            }
    +        }
    +    }
    +
    +    protected Map<Integer, LocalAssignment> getReassignExecutors(Map<Integer, LocalAssignment> assignExecutors, Set<Integer> keepPorts) {
    +        Map<Integer, LocalAssignment> reassignExecutors = new HashMap<>();
    +        reassignExecutors.putAll(assignExecutors);
    +        for (Integer port : keepPorts) {
    +            reassignExecutors.remove(port);
    +        }
    +        return reassignExecutors;
    +    }
    +    
    +    /**
    +     * Returns map from worker id to worker heartbeat. if the heartbeat is nil, then the worker is dead
    +     * 
    +     * @param assignedExecutors
    +     * @return
    +     * @throws Exception
    +     */
    +    public Map<String, StateHeartbeat> getLocalWorkerStats(SupervisorData supervisorData, Map<Integer, LocalAssignment> assignedExecutors, int now) throws Exception {
    +        Map<String, StateHeartbeat> workerIdHbstate = new HashMap<>();
    +        Map conf = supervisorData.getConf();
    +        LocalState localState = supervisorData.getLocalState();
    +        Map<String, LSWorkerHeartbeat> idToHeartbeat = SupervisorUtils.readWorkerHeartbeats(conf);
    +        Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +        Set<String> approvedIds = new HashSet<>();
    +        if (approvedWorkers != null) {
    +            approvedIds.addAll(approvedWorkers.keySet());
    +        }
    +        for (Map.Entry<String, LSWorkerHeartbeat> entry : idToHeartbeat.entrySet()) {
    +            String workerId = entry.getKey();
    +            LSWorkerHeartbeat whb = entry.getValue();
    +            State state;
    +            if (whb == null) {
    +                state = State.NOT_STARTED;
    +            } else if (!approvedIds.contains(workerId) || !matchesAssignment(whb, assignedExecutors)) {
    +                state = State.DISALLOWED;
    +            } else if (supervisorData.getDeadWorkers().contains(workerId)) {
    +                LOG.info("Worker Process {} has died", workerId);
    +                state = State.TIMED_OUT;
    +            } else if (SupervisorUtils.isWorkerHbTimedOut(now, whb, conf)) {
    +                state = State.TIMED_OUT;
    +            } else {
    +                state = State.VALID;
    +            }
    +            LOG.debug("Worker:{} state:{} WorkerHeartbeat:{} at supervisor time-secs {}", workerId, state, whb, now);
    +            workerIdHbstate.put(workerId, new StateHeartbeat(state, whb));
    +        }
    +        return workerIdHbstate;
    +    }
    +
    +    protected boolean matchesAssignment(LSWorkerHeartbeat whb, Map<Integer, LocalAssignment> assignedExecutors) {
    +        LocalAssignment localAssignment = assignedExecutors.get(whb.get_port());
    +        if (localAssignment == null || !localAssignment.get_topology_id().equals(whb.get_topology_id())) {
    +            return false;
    +        }
    +        List<ExecutorInfo> executorInfos = new ArrayList<>();
    +        executorInfos.addAll(whb.get_executors());
    +        // remove SYSTEM_EXECUTOR_ID
    +        executorInfos.remove(SYSTEM_EXECUTOR_INFO);
    +        List<ExecutorInfo> localExecuorInfos = localAssignment.get_executors();
    +
    +        if (localExecuorInfos.size() != executorInfos.size())
    +            return false;
    +
    +        for (ExecutorInfo executorInfo : localExecuorInfos){
    +            if (!localExecuorInfos.contains(executorInfo))
    +                return false;
    +        }
    +        return true;
    +    }
    +
    +    /**
    +     * launch a worker in local mode.
    +     */
    +    protected void launchWorker(SupervisorData supervisorData, String stormId, Long port, String workerId, WorkerResources resources) throws IOException {
    +        // port this function after porting worker to java
    +    }
    +
    +    protected String getWorkerClassPath(String stormJar, Map stormConf) {
    +        List<String> topoClasspath = new ArrayList<>();
    +        Object object = stormConf.get(Config.TOPOLOGY_CLASSPATH);
    +
    +        if (object instanceof List) {
    +            topoClasspath.addAll((List<String>) object);
    +        } else if (object instanceof String){
    +            topoClasspath.add((String)object);
    +        }else {
    +            //ignore
    +        }
    +        String classPath = Utils.workerClasspath();
    +        String classAddPath = Utils.addToClasspath(classPath, Arrays.asList(stormJar));
    +        return Utils.addToClasspath(classAddPath, topoClasspath);
    +    }
    +
    +    /**
    +     * "Generates runtime childopts by replacing keys with topology-id, worker-id, port, mem-onheap"
    +     * 
    +     * @param value
    +     * @param workerId
    +     * @param stormId
    +     * @param port
    +     * @param memOnheap
    +     */
    +    public List<String> substituteChildopts(Object value, String workerId, String stormId, Long port, int memOnheap) {
    +        List<String> rets = new ArrayList<>();
    --- End diff --
    
    clojure code would have returned null if value is null. Also default type was assumed to be 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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#issuecomment-200214770
  
    @jerrypeng  I have merge your bug fix.Thank you.


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55689859
  
    --- Diff: storm-core/src/clj/org/apache/storm/daemon/local_supervisor.clj ---
    @@ -0,0 +1,61 @@
    +;; 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.
    +(ns org.apache.storm.daemon.local-supervisor
    +  (:import [org.apache.storm.daemon.supervisor SyncProcessEvent SupervisorData ShutdownWork Supervisor]
    +           [org.apache.storm.utils Utils ConfigUtils]
    +           [org.apache.storm ProcessSimulator])
    +  (:use [org.apache.storm.daemon common]
    +        [org.apache.storm log])
    +  (:require [org.apache.storm.daemon [worker :as worker] ])
    +  (:require [clojure.string :as str])
    +  (:gen-class))
    --- End diff --
    
    ok! I will follow up the JIRA to move local_supervisor.clj to java after this PR is merged into 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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55965454
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncSupervisorEvent.java ---
    @@ -0,0 +1,631 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.blobstore.BlobStore;
    +import org.apache.storm.blobstore.ClientBlobStore;
    +import org.apache.storm.cluster.IStateStorage;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.event.EventManager;
    +import org.apache.storm.generated.*;
    +import org.apache.storm.localizer.LocalResource;
    +import org.apache.storm.localizer.LocalizedResource;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.utils.*;
    +import org.apache.thrift.transport.TTransportException;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.FileOutputStream;
    +import java.io.IOException;
    +import java.net.JarURLConnection;
    +import java.net.URL;
    +import java.nio.file.Files;
    +import java.nio.file.StandardCopyOption;
    +import java.util.*;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SyncSupervisorEvent implements Runnable {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SyncSupervisorEvent.class);
    +
    +    private EventManager syncSupEventManager;
    +    private EventManager syncProcessManager;
    +    private IStormClusterState stormClusterState;
    +    private LocalState localState;
    +    private SyncProcessEvent syncProcesses;
    +    private SupervisorData supervisorData;
    +
    +    public SyncSupervisorEvent(SupervisorData supervisorData, SyncProcessEvent syncProcesses, EventManager syncSupEventManager,
    +            EventManager syncProcessManager) {
    +
    +        this.syncProcesses = syncProcesses;
    +        this.syncSupEventManager = syncSupEventManager;
    +        this.syncProcessManager = syncProcessManager;
    +        this.stormClusterState = supervisorData.getStormClusterState();
    +        this.localState = supervisorData.getLocalState();
    +        this.supervisorData = supervisorData;
    +    }
    +
    +    @Override
    +    public void run() {
    +        try {
    +            Map conf = supervisorData.getConf();
    +            Runnable syncCallback = new EventManagerPushCallback(this, syncSupEventManager);
    +            List<String> stormIds = stormClusterState.assignments(syncCallback);
    +            Map<String, Map<String, Object>> assignmentsSnapshot =
    +                    getAssignmentsSnapshot(stormClusterState, stormIds, supervisorData.getAssignmentVersions().get(), syncCallback);
    +            Map<String, List<ProfileRequest>> stormIdToProfilerActions = getProfileActions(stormClusterState, stormIds);
    +
    +            Set<String> allDownloadedTopologyIds = SupervisorUtils.readDownLoadedStormIds(conf);
    +            Map<String, String> stormcodeMap = readStormCodeLocations(assignmentsSnapshot);
    +            Map<Integer, LocalAssignment> existingAssignment = localState.getLocalAssignmentsMap();
    +            if (existingAssignment == null) {
    +                existingAssignment = new HashMap<>();
    +            }
    +
    +            Map<Integer, LocalAssignment> allAssignment =
    +                    readAssignments(assignmentsSnapshot, existingAssignment, supervisorData.getAssignmentId(), supervisorData.getSyncRetry());
    +
    +            Map<Integer, LocalAssignment> newAssignment = new HashMap<>();
    +            Set<String> assignedStormIds = new HashSet<>();
    +
    +            for (Map.Entry<Integer, LocalAssignment> entry : allAssignment.entrySet()) {
    +                if (supervisorData.getiSupervisor().confirmAssigned(entry.getKey())) {
    +                    newAssignment.put(entry.getKey(), entry.getValue());
    +                    assignedStormIds.add(entry.getValue().get_topology_id());
    +                }
    +            }
    +
    +            Set<String> srashStormIds = verifyDownloadedFiles(conf, supervisorData.getLocalizer(), assignedStormIds, allDownloadedTopologyIds);
    +            Set<String> downloadedStormIds = new HashSet<>();
    +            downloadedStormIds.addAll(allDownloadedTopologyIds);
    +            downloadedStormIds.removeAll(srashStormIds);
    +
    +            LOG.debug("Synchronizing supervisor");
    +            LOG.debug("Storm code map: {}", stormcodeMap);
    +            LOG.debug("All assignment: {}", allAssignment);
    +            LOG.debug("New assignment: {}", newAssignment);
    +            LOG.debug("Assigned Storm Ids {}", assignedStormIds);
    +            LOG.debug("All Downloaded Ids {}", allDownloadedTopologyIds);
    +            LOG.debug("Checked Downloaded Ids {}", srashStormIds);
    +            LOG.debug("Downloaded Ids {}", downloadedStormIds);
    +            LOG.debug("Storm Ids Profiler Actions {}", stormIdToProfilerActions);
    +            // download code first
    +            // This might take awhile
    +            // - should this be done separately from usual monitoring?
    +            // should we only download when topology is assigned to this supervisor?
    +            for (Map.Entry<String, String> entry : stormcodeMap.entrySet()) {
    +                String stormId = entry.getKey();
    +                if (!downloadedStormIds.contains(stormId) && assignedStormIds.contains(stormId)) {
    +                    LOG.info("Downloading code for storm id {}.", stormId);
    +                    try {
    +                        downloadStormCode(conf, stormId, entry.getValue(), supervisorData.getLocalizer());
    +                    } catch (Exception e) {
    +                        if (Utils.exceptionCauseIsInstanceOf(NimbusLeaderNotFoundException.class, e)) {
    +                            LOG.warn("Nimbus leader was not available.", e);
    +                        } else if (Utils.exceptionCauseIsInstanceOf(TTransportException.class, e)) {
    +                            LOG.warn("There was a connection problem with nimbus.", e);
    +                        } else {
    +                            throw e;
    +                        }
    +                    }
    +                    LOG.info("Finished downloading code for storm id {}", stormId);
    +                }
    +            }
    +
    +            LOG.debug("Writing new assignment {}", newAssignment);
    +
    +            Set<Integer> killWorkers = new HashSet<>();
    +            killWorkers.addAll(existingAssignment.keySet());
    +            killWorkers.removeAll(newAssignment.keySet());
    +            for (Integer port : killWorkers) {
    +                supervisorData.getiSupervisor().killedWorker(port);
    +            }
    +
    +            killExistingWorkersWithChangeInComponents(supervisorData, existingAssignment, newAssignment);
    +
    +            supervisorData.getiSupervisor().assigned(newAssignment.keySet());
    +            localState.setLocalAssignmentsMap(newAssignment);
    +            supervisorData.setAssignmentVersions(assignmentsSnapshot);
    +            supervisorData.setStormIdToProfileActions(stormIdToProfilerActions);
    +
    +            Map<Long, LocalAssignment> convertNewAssignment = new HashMap<>();
    +            for (Map.Entry<Integer, LocalAssignment> entry : newAssignment.entrySet()) {
    +                convertNewAssignment.put(entry.getKey().longValue(), entry.getValue());
    +            }
    +            supervisorData.setCurrAssignment(convertNewAssignment);
    +            // remove any downloaded code that's no longer assigned or active
    +            // important that this happens after setting the local assignment so that
    +            // synchronize-supervisor doesn't try to launch workers for which the
    +            // resources don't exist
    +            if (Utils.isOnWindows()) {
    +                shutdownDisallowedWorkers();
    +            }
    +            for (String stormId : allDownloadedTopologyIds) {
    +                if (!stormcodeMap.containsKey(stormId)) {
    +                    LOG.info("Removing code for storm id {}.", stormId);
    +                    rmTopoFiles(conf, stormId, supervisorData.getLocalizer(), true);
    +                }
    +            }
    +            syncProcessManager.add(syncProcesses);
    +        } catch (Exception e) {
    +            LOG.error("Failed to Sync Supervisor", e);
    +            throw new RuntimeException(e);
    +        }
    +
    +    }
    +
    +    private void killExistingWorkersWithChangeInComponents(SupervisorData supervisorData, Map<Integer, LocalAssignment> existingAssignment,
    +            Map<Integer, LocalAssignment> newAssignment) throws Exception {
    +        LocalState localState = supervisorData.getLocalState();
    +        Map<Integer, LocalAssignment> assignedExecutors = localState.getLocalAssignmentsMap();
    +        if (assignedExecutors == null) {
    +            assignedExecutors = new HashMap<>();
    +        }
    +        int now = Time.currentTimeSecs();
    +        Map<String, StateHeartbeat> workerIdHbstate = syncProcesses.getLocalWorkerStats(supervisorData, assignedExecutors, now);
    +        Map<Integer, String> vaildPortToWorkerIds = new HashMap<>();
    +        for (Map.Entry<String, StateHeartbeat> entry : workerIdHbstate.entrySet()) {
    +            String workerId = entry.getKey();
    +            StateHeartbeat stateHeartbeat = entry.getValue();
    +            if (stateHeartbeat != null && stateHeartbeat.getState() == State.VALID) {
    +                vaildPortToWorkerIds.put(stateHeartbeat.getHeartbeat().get_port(), workerId);
    +            }
    +        }
    +
    +        Map<Integer, LocalAssignment> intersectAssignment = new HashMap<>();
    +        for (Map.Entry<Integer, LocalAssignment> entry : newAssignment.entrySet()) {
    +            Integer port = entry.getKey();
    +            if (existingAssignment.containsKey(port)) {
    +                intersectAssignment.put(port, entry.getValue());
    +            }
    +        }
    +
    +        for (Integer port : intersectAssignment.keySet()) {
    +            List<ExecutorInfo> existExecutors = existingAssignment.get(port).get_executors();
    +            List<ExecutorInfo> newExecutors = newAssignment.get(port).get_executors();
    +            if (newExecutors.size() != existExecutors.size()) {
    +                syncProcesses.shutWorker(supervisorData, vaildPortToWorkerIds.get(port));
    +                continue;
    +            }
    +            for (ExecutorInfo executorInfo : newExecutors) {
    +                if (!existExecutors.contains(executorInfo)) {
    +                    syncProcesses.shutWorker(supervisorData, vaildPortToWorkerIds.get(port));
    +                    break;
    +                }
    +            }
    +
    +        }
    +    }
    +
    +    protected Map<String, Map<String, Object>> getAssignmentsSnapshot(IStormClusterState stormClusterState, List<String> stormIds,
    +            Map<String, Map<String, Object>> localAssignmentVersion, Runnable callback) throws Exception {
    +        Map<String, Map<String, Object>> updateAssignmentVersion = new HashMap<>();
    +        for (String stormId : stormIds) {
    +            Integer recordedVersion = -1;
    +            Integer version = stormClusterState.assignmentVersion(stormId, callback);
    +            if (localAssignmentVersion.containsKey(stormId) && localAssignmentVersion.get(stormId) != null) {
    +                recordedVersion = (Integer) localAssignmentVersion.get(stormId).get(IStateStorage.VERSION);
    +            }
    +            if (version == null) {
    +                // ignore
    +            } else if (version == recordedVersion) {
    +                updateAssignmentVersion.put(stormId, localAssignmentVersion.get(stormId));
    +            } else {
    +                Map<String, Object> assignmentVersion = (Map<String, Object>) stormClusterState.assignmentInfoWithVersion(stormId, callback);
    +                updateAssignmentVersion.put(stormId, assignmentVersion);
    +            }
    +        }
    +        return updateAssignmentVersion;
    +    }
    +
    +    protected Map<String, List<ProfileRequest>> getProfileActions(IStormClusterState stormClusterState, List<String> stormIds) throws Exception {
    +        Map<String, List<ProfileRequest>> ret = new HashMap<String, List<ProfileRequest>>();
    +        for (String stormId : stormIds) {
    +            List<ProfileRequest> profileRequests = stormClusterState.getTopologyProfileRequests(stormId);
    +            ret.put(stormId, profileRequests);
    +        }
    +        return ret;
    +    }
    +
    +    protected Map<String, String> readStormCodeLocations(Map<String, Map<String, Object>> assignmentsSnapshot) {
    +        Map<String, String> stormcodeMap = new HashMap<>();
    +        for (Map.Entry<String, Map<String, Object>> entry : assignmentsSnapshot.entrySet()) {
    +            Assignment assignment = (Assignment) (entry.getValue().get(IStateStorage.DATA));
    +            if (assignment != null) {
    +                stormcodeMap.put(entry.getKey(), assignment.get_master_code_dir());
    +            }
    +        }
    +        return stormcodeMap;
    +    }
    +
    +    /**
    +     * Remove a reference to a blob when its no longer needed.
    +     * 
    +     * @param localizer
    +     * @param stormId
    +     * @param conf
    +     */
    +    protected void removeBlobReferences(Localizer localizer, String stormId, Map conf) throws Exception {
    +        Map stormConf = ConfigUtils.readSupervisorStormConf(conf, stormId);
    +        Map<String, Map<String, Object>> blobstoreMap = (Map<String, Map<String, Object>>) stormConf.get(Config.TOPOLOGY_BLOBSTORE_MAP);
    +        String user = (String) stormConf.get(Config.TOPOLOGY_SUBMITTER_USER);
    +        String topoName = (String) stormConf.get(Config.TOPOLOGY_NAME);
    +        if (blobstoreMap != null) {
    +            for (Map.Entry<String, Map<String, Object>> entry : blobstoreMap.entrySet()) {
    +                String key = entry.getKey();
    +                Map<String, Object> blobInfo = entry.getValue();
    +                localizer.removeBlobReference(key, user, topoName, SupervisorUtils.shouldUncompressBlob(blobInfo));
    +            }
    +        }
    +    }
    +
    +    protected void rmTopoFiles(Map conf, String stormId, Localizer localizer, boolean isrmBlobRefs) throws IOException {
    +        String path = ConfigUtils.supervisorStormDistRoot(conf, stormId);
    +        try {
    +            if (isrmBlobRefs) {
    +                removeBlobReferences(localizer, stormId, conf);
    +            }
    +            if (Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false)) {
    +                SupervisorUtils.rmrAsUser(conf, stormId, path);
    +            } else {
    +                Utils.forceDelete(ConfigUtils.supervisorStormDistRoot(conf, stormId));
    +            }
    +        } catch (Exception e) {
    +            LOG.info("Exception removing: {} ", stormId, e);
    +        }
    +    }
    +
    +    /**
    +     * Check for the files exists to avoid supervisor crashing Also makes sure there is no necessity for locking"
    +     * 
    +     * @param conf
    +     * @param localizer
    +     * @param assignedStormIds
    +     * @param allDownloadedTopologyIds
    +     * @return
    +     */
    +    protected Set<String> verifyDownloadedFiles(Map conf, Localizer localizer, Set<String> assignedStormIds, Set<String> allDownloadedTopologyIds)
    +            throws IOException {
    +        Set<String> srashStormIds = new HashSet<>();
    +        for (String stormId : allDownloadedTopologyIds) {
    +            if (assignedStormIds.contains(stormId)) {
    +                if (!SupervisorUtils.doRequiredTopoFilesExist(conf, stormId)) {
    +                    LOG.debug("Files not present in topology directory");
    +                    rmTopoFiles(conf, stormId, localizer, false);
    +                    srashStormIds.add(stormId);
    +                }
    +            }
    +        }
    +        return srashStormIds;
    +    }
    +
    +    /**
    +     * download code ; two cluster mode: local and distributed
    +     *
    +     * @param conf
    +     * @param stormId
    +     * @param masterCodeDir
    +     * @throws IOException
    +     */
    +    private void downloadStormCode(Map conf, String stormId, String masterCodeDir, Localizer localizer) throws Exception {
    +        String clusterMode = ConfigUtils.clusterMode(conf);
    +
    +        if (clusterMode.endsWith("distributed")) {
    +            downloadDistributeStormCode(conf, stormId, masterCodeDir, localizer);
    +        } else if (clusterMode.endsWith("local")) {
    +            downloadLocalStormCode(conf, stormId, masterCodeDir, localizer);
    +        }
    +    }
    +
    +    private void downloadLocalStormCode(Map conf, String stormId, String masterCodeDir, Localizer localizer) throws Exception {
    +
    +        String tmproot = ConfigUtils.supervisorTmpDir(conf) + Utils.FILE_PATH_SEPARATOR + Utils.uuid();
    +        String stormroot = ConfigUtils.supervisorStormDistRoot(conf, stormId);
    +        BlobStore blobStore = Utils.getNimbusBlobStore(conf, masterCodeDir, null);
    +        try {
    +            FileUtils.forceMkdir(new File(tmproot));
    +            String stormCodeKey = ConfigUtils.masterStormCodeKey(stormId);
    +            String stormConfKey = ConfigUtils.masterStormConfKey(stormId);
    +            String codePath = ConfigUtils.supervisorStormCodePath(tmproot);
    +            String confPath = ConfigUtils.supervisorStormConfPath(tmproot);
    +            blobStore.readBlobTo(stormCodeKey, new FileOutputStream(codePath), null);
    +            blobStore.readBlobTo(stormConfKey, new FileOutputStream(confPath), null);
    +        } finally {
    +            blobStore.shutdown();
    +        }
    +        FileUtils.moveDirectory(new File(tmproot), new File(stormroot));
    +        SupervisorUtils.setupStormCodeDir(conf, ConfigUtils.readSupervisorStormConf(conf, stormId), stormroot);
    +        ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    +
    +        String resourcesJar = resourcesJar();
    +
    +        URL url = classloader.getResource(ConfigUtils.RESOURCES_SUBDIR);
    +
    +        String targetDir = stormroot + Utils.FILE_PATH_SEPARATOR + ConfigUtils.RESOURCES_SUBDIR;
    +
    +        if (resourcesJar != null) {
    +            LOG.info("Extracting resources from jar at {} to {}", resourcesJar, targetDir);
    +            Utils.extractDirFromJar(resourcesJar, ConfigUtils.RESOURCES_SUBDIR, stormroot);
    +        } else if (url != null) {
    +
    +            LOG.info("Copying resources at {} to {} ", url.toString(), targetDir);
    +            if (url.getProtocol() == "jar") {
    +                JarURLConnection urlConnection = (JarURLConnection) url.openConnection();
    +                Utils.extractDirFromJar(urlConnection.getJarFileURL().getFile(), ConfigUtils.RESOURCES_SUBDIR, stormroot);
    +            } else {
    +                FileUtils.copyDirectory(new File(url.getFile()), (new File(targetDir)));
    +            }
    +        }
    +    }
    +
    +    /**
    +     * Downloading to permanent location is atomic
    +     * 
    +     * @param conf
    +     * @param stormId
    +     * @param masterCodeDir
    +     * @param localizer
    +     * @throws Exception
    +     */
    +    private void downloadDistributeStormCode(Map conf, String stormId, String masterCodeDir, Localizer localizer) throws Exception {
    +
    +        String tmproot = ConfigUtils.supervisorTmpDir(conf) + Utils.FILE_PATH_SEPARATOR + Utils.uuid();
    +        String stormroot = ConfigUtils.supervisorStormDistRoot(conf, stormId);
    +        ClientBlobStore blobStore = Utils.getClientBlobStoreForSupervisor(conf);
    +        FileUtils.forceMkdir(new File(tmproot));
    +        if (Utils.isOnWindows()) {
    +            if (Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false)) {
    +                throw new RuntimeException("ERROR: Windows doesn't implement setting the correct permissions");
    +            }
    +        } else {
    +            Utils.restrictPermissions(tmproot);
    +        }
    +        String stormJarKey = ConfigUtils.masterStormJarKey(stormId);
    +        String stormCodeKey = ConfigUtils.masterStormCodeKey(stormId);
    +        String stormConfKey = ConfigUtils.masterStormConfKey(stormId);
    +        String jarPath = ConfigUtils.supervisorStormJarPath(tmproot);
    +        String codePath = ConfigUtils.supervisorStormCodePath(tmproot);
    +        String confPath = ConfigUtils.supervisorStormConfPath(tmproot);
    +        Utils.downloadResourcesAsSupervisor(stormJarKey, jarPath, blobStore);
    +        Utils.downloadResourcesAsSupervisor(stormCodeKey, codePath, blobStore);
    +        Utils.downloadResourcesAsSupervisor(stormConfKey, confPath, blobStore);
    +        blobStore.shutdown();
    +        Utils.extractDirFromJar(jarPath, ConfigUtils.RESOURCES_SUBDIR, tmproot);
    +        downloadBlobsForTopology(conf, confPath, localizer, tmproot);
    +        if (IsDownloadBlobsForTopologySucceed(confPath, tmproot)) {
    +            LOG.info("Successfully downloaded blob resources for storm-id {}", stormId);
    +            FileUtils.forceMkdir(new File(stormroot));
    +            Files.move(new File(tmproot).toPath(), new File(stormroot).toPath(), StandardCopyOption.ATOMIC_MOVE);
    +            SupervisorUtils.setupStormCodeDir(conf, ConfigUtils.readSupervisorStormConf(conf, stormId), stormroot);
    +        } else {
    +            LOG.info("Failed to download blob resources for storm-id ", stormId);
    +            Utils.forceDelete(tmproot);
    +        }
    +    }
    +
    +    /**
    +     * Assert if all blobs are downloaded for the given topology
    +     * 
    +     * @param stormconfPath
    +     * @param targetDir
    +     * @return
    +     */
    +    protected boolean IsDownloadBlobsForTopologySucceed(String stormconfPath, String targetDir) throws IOException {
    +        Map stormConf = Utils.fromCompressedJsonConf(FileUtils.readFileToByteArray(new File(stormconfPath)));
    +        Map<String, Map<String, Object>> blobstoreMap = (Map<String, Map<String, Object>>) stormConf.get(Config.TOPOLOGY_BLOBSTORE_MAP);
    +        List<String> blobFileNames = new ArrayList<>();
    +        if (blobstoreMap != null) {
    +            for (Map.Entry<String, Map<String, Object>> entry : blobstoreMap.entrySet()) {
    +                String key = entry.getKey();
    +                Map<String, Object> blobInfo = entry.getValue();
    +                String ret = null;
    +                if (blobInfo != null && blobInfo.containsKey("localname")) {
    +                    ret = (String) blobInfo.get("localname");
    +                } else {
    +                    ret = key;
    +                }
    +                blobFileNames.add(ret);
    +            }
    +        }
    +        for (String string : blobFileNames) {
    +            if (!Utils.checkFileExists(string))
    +                return false;
    +        }
    +        return true;
    +    }
    +
    +    /**
    +     * Download all blobs listed in the topology configuration for a given topology.
    +     * 
    +     * @param conf
    +     * @param stormconfPath
    +     * @param localizer
    +     * @param tmpRoot
    +     */
    +    protected void downloadBlobsForTopology(Map conf, String stormconfPath, Localizer localizer, String tmpRoot) throws IOException {
    +        Map stormConf = ConfigUtils.readSupervisorStormConfGivenPath(conf, stormconfPath);
    +        Map<String, Map<String, Object>> blobstoreMap = (Map<String, Map<String, Object>>) stormConf.get(Config.TOPOLOGY_BLOBSTORE_MAP);
    +        String user = (String) stormConf.get(Config.TOPOLOGY_SUBMITTER_USER);
    +        String topoName = (String) stormConf.get(Config.TOPOLOGY_NAME);
    +        File userDir = localizer.getLocalUserFileCacheDir(user);
    +        List<LocalResource> localResourceList = SupervisorUtils.blobstoreMapToLocalresources(blobstoreMap);
    +        if (localResourceList.size() > 0) {
    +            if (!userDir.exists()) {
    +                FileUtils.forceMkdir(userDir);
    +            }
    +            try {
    +                List<LocalizedResource> localizedResources = localizer.getBlobs(localResourceList, user, topoName, userDir);
    +                setupBlobPermission(conf, user, userDir.toString());
    +                for (LocalizedResource localizedResource : localizedResources) {
    +                    File rsrcFilePath = new File(localizedResource.getFilePath());
    +                    String keyName = rsrcFilePath.getName();
    +                    String blobSymlinkTargetName = new File(localizedResource.getCurrentSymlinkPath()).getName();
    +
    +                    String symlinkName = null;
    +                    if (blobstoreMap != null) {
    +                        Map<String, Object> blobInfo = blobstoreMap.get(keyName);
    +                        if (blobInfo != null && blobInfo.containsKey("localname")) {
    --- End diff --
    
    this logic was wrapped inside get-blob-localname in clojure. In java, it is duplicated in three places. 


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#issuecomment-193738634
  
    @zhuoliu @abhishekagarwal87  Thank you. I will consider your suggestions, and adjust class hierarchy. Of course, I hope others can help review the supervisor and give me some comments. Then I will revise the codes together in order to avoid to different suggestions and repeat modifications. Thank you again.


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55585316
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorData.java ---
    @@ -0,0 +1,339 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.cluster.ClusterStateContext;
    +import org.apache.storm.cluster.ClusterUtils;
    +import org.apache.storm.cluster.DaemonType;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.ProfileRequest;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +import java.net.UnknownHostException;
    +import java.util.ArrayList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.concurrent.ConcurrentHashMap;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SupervisorData {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorData.class);
    +
    +    private Map conf;
    +    private IContext sharedContext;
    +    private volatile boolean active;
    +    private ISupervisor iSupervisor;
    +    private Utils.UptimeComputer upTime;
    +    private String stormVersion;
    +
    +    private ConcurrentHashMap<String, String> workerThreadPidsAtom; // for local mode
    +
    +    private IStormClusterState stormClusterState;
    +
    +    private LocalState localState;
    +
    +    private String supervisorId;
    +
    +    private String assignmentId;
    +
    +    private String hostName;
    +
    +    // used for reporting used ports when heartbeating
    +    private ConcurrentHashMap<Long, LocalAssignment> currAssignment;
    +
    +    private StormTimer heartbeatTimer;
    +
    +    private StormTimer eventTimer;
    +
    +    private StormTimer blobUpdateTimer;
    +
    +    private Localizer localizer;
    +
    +    private ConcurrentHashMap<String, Map<String, Object>> assignmentVersions;
    +
    +    private AtomicInteger syncRetry;
    +
    +    private final Object downloadLock = new Object();
    +
    +    private ConcurrentHashMap<String, List<ProfileRequest>> stormIdToProfileActions;
    +
    +    private CgroupManager resourceIsolationManager;
    +
    +    private ConcurrentHashSet<String> deadWorkers;
    +
    +    public SupervisorData(Map conf, IContext sharedContext, ISupervisor iSupervisor) {
    +        this.conf = conf;
    +        this.sharedContext = sharedContext;
    +        this.iSupervisor = iSupervisor;
    +        this.active = true;
    +        this.upTime = Utils.makeUptimeComputer();
    +        this.stormVersion = VersionInfo.getVersion();
    +        this.workerThreadPidsAtom = new ConcurrentHashMap<String, String>();
    +        this.deadWorkers = new ConcurrentHashSet();
    +
    +        List<ACL> acls = null;
    +        if (Utils.isZkAuthenticationConfiguredStormServer(conf)) {
    +            acls = SupervisorUtils.supervisorZkAcls();
    +        }
    +
    +        try {
    +            this.stormClusterState = ClusterUtils.mkStormClusterState(conf, acls, new ClusterStateContext(DaemonType.SUPERVISOR));
    +        } catch (Exception e) {
    +            LOG.error("supervisor can't create stormClusterState");
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        try {
    +            this.localState = ConfigUtils.supervisorState(conf);
    +            this.localizer = Utils.createLocalizer(conf, ConfigUtils.supervisorLocalDir(conf));
    +        } catch (IOException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +        this.supervisorId = iSupervisor.getSupervisorId();
    +        this.assignmentId = iSupervisor.getAssignmentId();
    +
    +        try {
    +            this.hostName = Utils.hostname(conf);
    +        } catch (UnknownHostException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        this.currAssignment = new ConcurrentHashMap<>();
    +
    +        this.heartbeatTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.eventTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.blobUpdateTimer = new StormTimer("blob-update-timer", new DefaultUncaughtExceptionHandler());
    +
    +        this.assignmentVersions = new ConcurrentHashMap<>();
    +        this.syncRetry = new AtomicInteger(0);
    +        this.stormIdToProfileActions = new ConcurrentHashMap<>();
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            try {
    +                this.resourceIsolationManager = (CgroupManager) Utils.newInstance((String) conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN));
    +                this.resourceIsolationManager.prepare(conf);
    +                LOG.info("Using resource isolation plugin {} {}", conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN), resourceIsolationManager);
    +            } catch (IOException e) {
    +                throw Utils.wrapInRuntime(e);
    +            }
    +        } else {
    +            this.resourceIsolationManager = null;
    +        }
    +    }
    +
    +    public ConcurrentHashMap<String, List<ProfileRequest>> getStormIdToProfileActions() {
    +        return stormIdToProfileActions;
    +    }
    +
    +    public void setStormIdToProfileActions(Map<String, List<ProfileRequest>> stormIdToProfileActions) {
    +        this.stormIdToProfileActions.clear();
    +        this.stormIdToProfileActions.putAll(stormIdToProfileActions);
    +    }
    +
    +    public Map getConf() {
    +        return conf;
    +    }
    +
    +    public void setConf(Map conf) {
    +        this.conf = conf;
    +    }
    +
    +    public IContext getSharedContext() {
    +        return sharedContext;
    +    }
    +
    +    public void setSharedContext(IContext sharedContext) {
    +        this.sharedContext = sharedContext;
    +    }
    +
    +    public boolean isActive() {
    +        return active;
    +    }
    +
    +    public void setActive(boolean active) {
    +        this.active = active;
    +    }
    +
    +    public ISupervisor getiSupervisor() {
    +        return iSupervisor;
    +    }
    +
    +    public void setiSupervisor(ISupervisor iSupervisor) {
    +        this.iSupervisor = iSupervisor;
    +    }
    +
    +    public Utils.UptimeComputer getUpTime() {
    +        return upTime;
    +    }
    +
    +    public void setUpTime(Utils.UptimeComputer upTime) {
    +        this.upTime = upTime;
    +    }
    +
    +    public String getStormVersion() {
    +        return stormVersion;
    +    }
    +
    +    public void setStormVersion(String stormVersion) {
    +        this.stormVersion = stormVersion;
    +    }
    +
    +    public ConcurrentHashMap<String, String> getWorkerThreadPidsAtom() {
    +        return workerThreadPidsAtom;
    +    }
    +
    +    public void setWorkerThreadPidsAtom(ConcurrentHashMap<String, String> workerThreadPidsAtom) {
    +        this.workerThreadPidsAtom = workerThreadPidsAtom;
    +    }
    +
    +    public IStormClusterState getStormClusterState() {
    +        return stormClusterState;
    +    }
    +
    +    public void setStormClusterState(IStormClusterState stormClusterState) {
    +        this.stormClusterState = stormClusterState;
    +    }
    +
    +    public LocalState getLocalState() {
    +        return localState;
    +    }
    +
    +    public void setLocalState(LocalState localState) {
    +        this.localState = localState;
    +    }
    +
    +    public String getSupervisorId() {
    +        return supervisorId;
    +    }
    +
    +    public void setSupervisorId(String supervisorId) {
    +        this.supervisorId = supervisorId;
    +    }
    +
    +    public String getAssignmentId() {
    +        return assignmentId;
    +    }
    +
    +    public void setAssignmentId(String assignmentId) {
    +        this.assignmentId = assignmentId;
    +    }
    +
    +    public String getHostName() {
    +        return hostName;
    +    }
    +
    +    public void setHostName(String hostName) {
    +        this.hostName = hostName;
    +    }
    +
    +    public ConcurrentHashMap<Long, LocalAssignment> getCurrAssignment() {
    +        return currAssignment;
    +    }
    +
    +    public void setCurrAssignment(Map<Long, LocalAssignment> currAssignment) {
    +        this.currAssignment.clear();
    +        this.currAssignment.putAll(currAssignment);
    +    }
    +
    +    public StormTimer getHeartbeatTimer() {
    +        return heartbeatTimer;
    +    }
    +
    +    public void setHeartbeatTimer(StormTimer heartbeatTimer) {
    +        this.heartbeatTimer = heartbeatTimer;
    +    }
    +
    +    public StormTimer getEventTimer() {
    +        return eventTimer;
    +    }
    +
    +    public void setEventTimer(StormTimer eventTimer) {
    --- End diff --
    
    Not used


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55938008
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorManger.java ---
    @@ -0,0 +1,97 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.event.EventManager;
    +import org.apache.storm.utils.Utils;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.Collection;
    +import java.util.Map;
    +
    +public class SupervisorManger implements SupervisorDaemon, DaemonCommon, Runnable {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorManger.class);
    +    private final EventManager eventManager;
    +    private final EventManager processesEventManager;
    +    private SupervisorData supervisorData;
    +
    +    public SupervisorManger(SupervisorData supervisorData, EventManager eventManager, EventManager processesEventManager) {
    +        this.eventManager = eventManager;
    +        this.supervisorData = supervisorData;
    +        this.processesEventManager = processesEventManager;
    +    }
    +
    +    public void shutdown() {
    +        LOG.info("Shutting down supervisor{}", supervisorData.getSupervisorId());
    +        supervisorData.setActive(false);
    +        try {
    +            supervisorData.getHeartbeatTimer().close();
    +            supervisorData.getEventTimer().close();
    +            supervisorData.getBlobUpdateTimer().close();
    +            eventManager.close();
    +            processesEventManager.close();
    +        } catch (Exception e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +        supervisorData.getStormClusterState().disconnect();
    +    }
    +
    +    @Override
    +    public void shutdownAllWorkers() {
    +
    +        Collection<String> workerIds = SupervisorUtils.supervisorWorkerIds(supervisorData.getConf());
    +        try {
    +            for (String workerId : workerIds) {
    +                SupervisorUtils.shutWorker(supervisorData, workerId);
    +            }
    +        } catch (Exception e) {
    +            LOG.error("shutWorker failed");
    +            throw Utils.wrapInRuntime(e);
    +        }
    +    }
    +
    +    @Override
    +    public Map getConf() {
    +        return supervisorData.getConf();
    +    }
    +
    +    @Override
    +    public String getId() {
    +        return supervisorData.getSupervisorId();
    +    }
    +
    +    @Override
    +    public boolean isWaiting() {
    +        if (!supervisorData.isActive()) {
    +            return true;
    +        }
    +
    +        if (supervisorData.getHeartbeatTimer().isTimerWaiting() && supervisorData.getEventTimer().isTimerWaiting() && eventManager.waiting()
    +                && processesEventManager.waiting()) {
    +            return true;
    +        }
    +        return false;
    +    }
    +
    +    public void run() {
    --- End diff --
    
    it is not very intuitive that SupervisorManager is also a shutdown hook. You can remove this from here and in the use an anonymous shutdown hook


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55938368
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncProcessEvent.java ---
    @@ -0,0 +1,672 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.ExecutorInfo;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.WorkerResources;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +import org.yaml.snakeyaml.Yaml;
    +
    +import java.io.File;
    +import java.io.FileWriter;
    +import java.io.IOException;
    +import java.util.*;
    +
    +/**
    + * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file - rmr
    + * heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new worker
    + * ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait for workers
    + * launch
    + */
    +public class SyncProcessEvent implements Runnable {
    +
    +    private static Logger LOG = LoggerFactory.getLogger(SyncProcessEvent.class);
    +
    +    private  LocalState localState;
    +    private  SupervisorData supervisorData;
    +    public static final ExecutorInfo SYSTEM_EXECUTOR_INFO = new ExecutorInfo(-1, -1);
    +
    +    private class ProcessExitCallback implements Utils.ExitCodeCallable {
    +        private final String logPrefix;
    +        private final String workerId;
    +
    +        public ProcessExitCallback(String logPrefix, String workerId) {
    +            this.logPrefix = logPrefix;
    +            this.workerId = workerId;
    +        }
    +
    +        @Override
    +        public Object call() throws Exception {
    +            return null;
    +        }
    +
    +        @Override
    +        public Object call(int exitCode) {
    +            LOG.info("{} exited with code: {}", logPrefix, exitCode);
    +            supervisorData.getDeadWorkers().add(workerId);
    +            return null;
    +        }
    +    }
    +
    +    public SyncProcessEvent(){
    +
    +    }
    +    public SyncProcessEvent(SupervisorData supervisorData) {
    +        init(supervisorData);
    +    }
    +
    +    //TODO: initData is intended to local supervisor, so we will remove them after porting worker.clj to java
    +    public void init(SupervisorData supervisorData){
    +        this.supervisorData = supervisorData;
    +        this.localState = supervisorData.getLocalState();
    +    }
    +
    +
    +    /**
    +     * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file -
    +     * rmr heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new
    +     * worker ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait
    +     * for workers launch
    +     */
    +    @Override
    +    public void run() {
    +        LOG.debug("Syncing processes");
    --- End diff --
    
    this can be removed. 


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55697815
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorUtils.java ---
    @@ -0,0 +1,273 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.curator.utils.PathUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.localizer.LocalResource;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.IOException;
    +import java.net.URLDecoder;
    +import java.util.*;
    +
    +public class SupervisorUtils {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorUtils.class);
    +
    +    private static final SupervisorUtils INSTANCE = new SupervisorUtils();
    +    private static SupervisorUtils _instance = INSTANCE;
    +
    +    public static void setInstance(SupervisorUtils u) {
    +        _instance = u;
    +    }
    +
    +    public static void resetInstance() {
    +        _instance = INSTANCE;
    +    }
    +
    +    public static Process workerLauncher(Map conf, String user, List<String> args, Map<String, String> environment, final String logPreFix,
    --- End diff --
    
    It does launch the worker when run-as-user is set, that was what it was originally for, but other operations needed privileges too, and as such it has expanded its role.
    
    I am fine with changing it, just thought I would give you some background on it.  FYI we took most of the code from the hadoop `container-launcher`, and they have the same naming problem.
    
    Ideally I would ultimately like to see a  WorkerManager java API that would call into a native linux-worker-manager binary and would look something like the following, NOTE: I have not thought through all of the APIs and I have really not thought about exactly what parameters would need to be passed to it.  This is just a general concept that would allow us to eventually support docker, local-workers, run-as-user, cgroups and possibly other things much more cleanly.
    
    ```
    public interface WorkerManager {
      Future<WorkerPrepareResult> prepareWorker(String workerId, LocalisedResources lr, Resources resources);
      Future<LaunchWorkerResult> launchWorker(String workerId, WorkerExitCallback, ...);
      Future<KillWorkerResult> killWorker(String workerId);
      Future<CleanupWorkerResult> cleanupWorker(String workerId,...);
      List<WorkerInfo> runningWorkers();
      //Possibly in the  future
      //Future<ResizeWorkerResult> resizeWorker(String workerId, Resources newResources);
    }
    ```


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55573977
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/timer/SupervisorHeartbeat.java ---
    @@ -0,0 +1,89 @@
    +/**
    + * 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.supervisor.timer;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.supervisor.SupervisorData;
    +import org.apache.storm.generated.SupervisorInfo;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +
    +import java.util.ArrayList;
    +import java.util.HashMap;
    +import java.util.List;
    +import java.util.Map;
    +
    +public class SupervisorHeartbeat implements Runnable {
    +
    +    private IStormClusterState stormClusterState;
    +    private String supervisorId;
    +    private Map conf;
    --- End diff --
    
    Can we please mark stormClusterState, supervisorId, conf and supervisorData as final?


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55938035
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/Supervisor.java ---
    @@ -0,0 +1,178 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.daemon.supervisor.timer.RunProfilerActions;
    +import org.apache.storm.daemon.supervisor.timer.SupervisorHealthCheck;
    +import org.apache.storm.daemon.supervisor.timer.SupervisorHeartbeat;
    +import org.apache.storm.daemon.supervisor.timer.UpdateBlobs;
    +import org.apache.storm.event.EventManagerImp;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.metric.StormMetricsRegistry;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.InterruptedIOException;
    +import java.util.Collection;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.Callable;
    +
    +public class Supervisor {
    +    private static Logger LOG = LoggerFactory.getLogger(Supervisor.class);
    +
    +    // TODO: to be removed after porting worker.clj. localSyncProcess is intended to start local supervisor
    +    private SyncProcessEvent localSyncProcess;
    +
    +    public void setLocalSyncProcess(SyncProcessEvent localSyncProcess) {
    +        this.localSyncProcess = localSyncProcess;
    +    }
    +
    +    /**
    +     * in local state, supervisor stores who its current assignments are another thread launches events to restart any dead processes if necessary
    +     * 
    +     * @param conf
    +     * @param sharedContext
    +     * @param iSupervisor
    +     * @return
    +     * @throws Exception
    +     */
    +    public SupervisorManger mkSupervisor(final Map conf, IContext sharedContext, ISupervisor iSupervisor) throws Exception {
    +        SupervisorManger supervisorManger = null;
    +        try {
    +            LOG.info("Starting Supervisor with conf {}", conf);
    +            iSupervisor.prepare(conf, ConfigUtils.supervisorIsupervisorDir(conf));
    +            String path = ConfigUtils.supervisorTmpDir(conf);
    +            FileUtils.cleanDirectory(new File(path));
    +
    +            final SupervisorData supervisorData = new SupervisorData(conf, sharedContext, iSupervisor);
    +            Localizer localizer = supervisorData.getLocalizer();
    +
    +            SupervisorHeartbeat hb = new SupervisorHeartbeat(conf, supervisorData);
    +            hb.run();
    +            // should synchronize supervisor so it doesn't launch anything after being down (optimization)
    +            Integer heartbeatFrequency = Utils.getInt(conf.get(Config.SUPERVISOR_HEARTBEAT_FREQUENCY_SECS));
    +            supervisorData.getHeartbeatTimer().scheduleRecurring(0, heartbeatFrequency, hb);
    +
    +            Set<String> downdedStormId = SupervisorUtils.readDownLoadedStormIds(conf);
    +            for (String stormId : downdedStormId) {
    +                SupervisorUtils.addBlobReferences(localizer, stormId, conf);
    +            }
    +            // do this after adding the references so we don't try to clean things being used
    +            localizer.startCleaner();
    +
    +            EventManagerImp syncSupEventManager = new EventManagerImp(false);
    +            EventManagerImp syncProcessManager = new EventManagerImp(false);
    +
    +            SyncProcessEvent syncProcessEvent = null;
    +            if (ConfigUtils.isLocalMode(conf)) {
    +                localSyncProcess.init(supervisorData);
    +                syncProcessEvent = localSyncProcess;
    +            } else {
    +                syncProcessEvent = new SyncProcessEvent(supervisorData);
    +            }
    +
    +            SyncSupervisorEvent syncSupervisorEvent = new SyncSupervisorEvent(supervisorData, syncProcessEvent, syncSupEventManager, syncProcessManager);
    +            UpdateBlobs updateBlobsThread = new UpdateBlobs(supervisorData);
    +            RunProfilerActions runProfilerActionThread = new RunProfilerActions(supervisorData);
    +
    +            if ((Boolean) conf.get(Config.SUPERVISOR_ENABLE)) {
    +                StormTimer eventTimer = supervisorData.getEventTimer();
    +                // This isn't strictly necessary, but it doesn't hurt and ensures that the machine stays up
    +                // to date even if callbacks don't all work exactly right
    +                eventTimer.scheduleRecurring(0, 10, new EventManagerPushCallback(syncSupervisorEvent, syncSupEventManager));
    +
    +                eventTimer.scheduleRecurring(0, Utils.getInt(conf.get(Config.SUPERVISOR_MONITOR_FREQUENCY_SECS)),
    +                        new EventManagerPushCallback(syncProcessEvent, syncProcessManager));
    +
    +                // Blob update thread. Starts with 30 seconds delay, every 30 seconds
    +                supervisorData.getBlobUpdateTimer().scheduleRecurring(30, 30, new EventManagerPushCallback(updateBlobsThread, syncSupEventManager));
    +
    +                // supervisor health check
    +                eventTimer.scheduleRecurring(300, 300, new SupervisorHealthCheck(supervisorData));
    +
    +                // Launch a thread that Runs profiler commands . Starts with 30 seconds delay, every 30 seconds
    +                eventTimer.scheduleRecurring(30, 30, new EventManagerPushCallback(runProfilerActionThread, syncSupEventManager));
    +            }
    +            LOG.info("Starting supervisor with id {} at host {}.", supervisorData.getSupervisorId(), supervisorData.getHostName());
    +            supervisorManger = new SupervisorManger(supervisorData, syncSupEventManager, syncProcessManager);
    +        } catch (Throwable t) {
    +            if (Utils.exceptionCauseIsInstanceOf(InterruptedIOException.class, t)) {
    +                throw t;
    +            } else if (Utils.exceptionCauseIsInstanceOf(InterruptedException.class, t)) {
    +                throw t;
    +            } else {
    +                LOG.error("Error on initialization of server supervisor: {}", t);
    +                Utils.exitProcess(13, "Error on initialization");
    +            }
    +        }
    +        return supervisorManger;
    +    }
    +
    +    /**
    +     * start distribute supervisor
    +     */
    +    private void launch(ISupervisor iSupervisor) {
    +        LOG.info("Starting supervisor for storm version '{}'.", VersionInfo.getVersion());
    +        SupervisorManger supervisorManager;
    +        try {
    +            Map<Object, Object> conf = Utils.readStormConfig();
    +            if (ConfigUtils.isLocalMode(conf)) {
    +                throw new IllegalArgumentException("Cannot start server in local mode!");
    +            }
    +            supervisorManager = mkSupervisor(conf, null, iSupervisor);
    +            if (supervisorManager != null)
    +                Utils.addShutdownHookWithForceKillIn1Sec(supervisorManager);
    --- End diff --
    
    when you remove runnable interface from supervisorManager, this will become 
    ```
    Utils.addShutdownHookWithForceKillIn1Sec(new Runnable() { 
      public void run() {
         supervisorManager.shutdown()
    }
    });
    ```


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55573829
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/timer/SupervisorHeartbeat.java ---
    @@ -0,0 +1,89 @@
    +/**
    + * 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.supervisor.timer;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.daemon.supervisor.SupervisorData;
    +import org.apache.storm.generated.SupervisorInfo;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +
    +import java.util.ArrayList;
    +import java.util.HashMap;
    +import java.util.List;
    +import java.util.Map;
    +
    +public class SupervisorHeartbeat implements Runnable {
    +
    +    private IStormClusterState stormClusterState;
    +    private String supervisorId;
    +    private Map conf;
    +    private SupervisorInfo supervisorInfo;
    --- End diff --
    
    This can be removed.  It is only needed inside `update`.


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55253935
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/ShutdownWork.java ---
    @@ -0,0 +1,125 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.ProcessSimulator;
    +import org.apache.storm.daemon.Shutdownable;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.IOException;
    +import java.util.*;
    +
    +public  class ShutdownWork implements Shutdownable {
    --- End diff --
    
    It is OK to put the shutWorker function in a separate class but we not think it should implement Shutdownable. 
    
    Or we might just go with the original implementation to put these two functions in SupervisorUtils.java as static. Then SupervisorManger and SyncProcessEvent will not need to extend ShutdownWork (they seem not natural subclasses of ShutdownWork.)


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55584589
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorData.java ---
    @@ -0,0 +1,339 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.cluster.ClusterStateContext;
    +import org.apache.storm.cluster.ClusterUtils;
    +import org.apache.storm.cluster.DaemonType;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.ProfileRequest;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +import java.net.UnknownHostException;
    +import java.util.ArrayList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.concurrent.ConcurrentHashMap;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SupervisorData {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorData.class);
    +
    +    private Map conf;
    +    private IContext sharedContext;
    +    private volatile boolean active;
    +    private ISupervisor iSupervisor;
    +    private Utils.UptimeComputer upTime;
    +    private String stormVersion;
    +
    +    private ConcurrentHashMap<String, String> workerThreadPidsAtom; // for local mode
    +
    +    private IStormClusterState stormClusterState;
    +
    +    private LocalState localState;
    +
    +    private String supervisorId;
    +
    +    private String assignmentId;
    +
    +    private String hostName;
    +
    +    // used for reporting used ports when heartbeating
    +    private ConcurrentHashMap<Long, LocalAssignment> currAssignment;
    +
    +    private StormTimer heartbeatTimer;
    +
    +    private StormTimer eventTimer;
    +
    +    private StormTimer blobUpdateTimer;
    +
    +    private Localizer localizer;
    +
    +    private ConcurrentHashMap<String, Map<String, Object>> assignmentVersions;
    +
    +    private AtomicInteger syncRetry;
    +
    +    private final Object downloadLock = new Object();
    +
    +    private ConcurrentHashMap<String, List<ProfileRequest>> stormIdToProfileActions;
    +
    +    private CgroupManager resourceIsolationManager;
    +
    +    private ConcurrentHashSet<String> deadWorkers;
    +
    +    public SupervisorData(Map conf, IContext sharedContext, ISupervisor iSupervisor) {
    +        this.conf = conf;
    +        this.sharedContext = sharedContext;
    +        this.iSupervisor = iSupervisor;
    +        this.active = true;
    +        this.upTime = Utils.makeUptimeComputer();
    +        this.stormVersion = VersionInfo.getVersion();
    +        this.workerThreadPidsAtom = new ConcurrentHashMap<String, String>();
    +        this.deadWorkers = new ConcurrentHashSet();
    +
    +        List<ACL> acls = null;
    +        if (Utils.isZkAuthenticationConfiguredStormServer(conf)) {
    +            acls = SupervisorUtils.supervisorZkAcls();
    +        }
    +
    +        try {
    +            this.stormClusterState = ClusterUtils.mkStormClusterState(conf, acls, new ClusterStateContext(DaemonType.SUPERVISOR));
    +        } catch (Exception e) {
    +            LOG.error("supervisor can't create stormClusterState");
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        try {
    +            this.localState = ConfigUtils.supervisorState(conf);
    +            this.localizer = Utils.createLocalizer(conf, ConfigUtils.supervisorLocalDir(conf));
    +        } catch (IOException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +        this.supervisorId = iSupervisor.getSupervisorId();
    +        this.assignmentId = iSupervisor.getAssignmentId();
    +
    +        try {
    +            this.hostName = Utils.hostname(conf);
    +        } catch (UnknownHostException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        this.currAssignment = new ConcurrentHashMap<>();
    +
    +        this.heartbeatTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.eventTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.blobUpdateTimer = new StormTimer("blob-update-timer", new DefaultUncaughtExceptionHandler());
    +
    +        this.assignmentVersions = new ConcurrentHashMap<>();
    +        this.syncRetry = new AtomicInteger(0);
    +        this.stormIdToProfileActions = new ConcurrentHashMap<>();
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            try {
    +                this.resourceIsolationManager = (CgroupManager) Utils.newInstance((String) conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN));
    +                this.resourceIsolationManager.prepare(conf);
    +                LOG.info("Using resource isolation plugin {} {}", conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN), resourceIsolationManager);
    +            } catch (IOException e) {
    +                throw Utils.wrapInRuntime(e);
    +            }
    +        } else {
    +            this.resourceIsolationManager = null;
    +        }
    +    }
    +
    +    public ConcurrentHashMap<String, List<ProfileRequest>> getStormIdToProfileActions() {
    +        return stormIdToProfileActions;
    +    }
    +
    +    public void setStormIdToProfileActions(Map<String, List<ProfileRequest>> stormIdToProfileActions) {
    +        this.stormIdToProfileActions.clear();
    +        this.stormIdToProfileActions.putAll(stormIdToProfileActions);
    +    }
    +
    +    public Map getConf() {
    +        return conf;
    +    }
    +
    +    public void setConf(Map conf) {
    +        this.conf = conf;
    +    }
    +
    +    public IContext getSharedContext() {
    +        return sharedContext;
    +    }
    +
    +    public void setSharedContext(IContext sharedContext) {
    +        this.sharedContext = sharedContext;
    +    }
    +
    +    public boolean isActive() {
    +        return active;
    +    }
    +
    +    public void setActive(boolean active) {
    +        this.active = active;
    +    }
    +
    +    public ISupervisor getiSupervisor() {
    +        return iSupervisor;
    +    }
    +
    +    public void setiSupervisor(ISupervisor iSupervisor) {
    +        this.iSupervisor = iSupervisor;
    +    }
    +
    +    public Utils.UptimeComputer getUpTime() {
    +        return upTime;
    +    }
    +
    +    public void setUpTime(Utils.UptimeComputer upTime) {
    +        this.upTime = upTime;
    +    }
    +
    +    public String getStormVersion() {
    +        return stormVersion;
    +    }
    +
    +    public void setStormVersion(String stormVersion) {
    +        this.stormVersion = stormVersion;
    +    }
    +
    +    public ConcurrentHashMap<String, String> getWorkerThreadPidsAtom() {
    +        return workerThreadPidsAtom;
    +    }
    +
    +    public void setWorkerThreadPidsAtom(ConcurrentHashMap<String, String> workerThreadPidsAtom) {
    --- End diff --
    
    Not used.


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55938186
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorUtils.java ---
    @@ -0,0 +1,353 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.ProcessSimulator;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.localizer.LocalResource;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.IOException;
    +import java.net.URLDecoder;
    +import java.util.*;
    +
    +public class SupervisorUtils {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorUtils.class);
    +
    +    private static final SupervisorUtils INSTANCE = new SupervisorUtils();
    +    private static SupervisorUtils _instance = INSTANCE;
    +    public static void setInstance(SupervisorUtils u) {
    +        _instance = u;
    +    }
    +    public static void resetInstance() {
    +        _instance = INSTANCE;
    +    }
    +
    +    public static Process workerLauncher(Map conf, String user, List<String> args, Map<String, String> environment, final String logPreFix,
    +            final Utils.ExitCodeCallable exitCodeCallback, File dir) throws IOException {
    +        if (StringUtils.isBlank(user)) {
    +            throw new IllegalArgumentException("User cannot be blank when calling workerLauncher.");
    +        }
    +        String wlinitial = (String) (conf.get(Config.SUPERVISOR_WORKER_LAUNCHER));
    +        String stormHome = ConfigUtils.concatIfNotNull(System.getProperty("storm.home"));
    +        String wl;
    +        if (StringUtils.isNotBlank(wlinitial)) {
    +            wl = wlinitial;
    +        } else {
    +            wl = stormHome + "/bin/worker-launcher";
    +        }
    +        List<String> commands = new ArrayList<>();
    +        commands.add(wl);
    +        commands.add(user);
    +        commands.addAll(args);
    +        LOG.info("Running as user: {} command: {}", user, commands);
    +        return Utils.launchProcess(commands, environment, logPreFix, exitCodeCallback, dir);
    +    }
    +
    +    public static int workerLauncherAndWait(Map conf, String user, List<String> args, final Map<String, String> environment, final String logPreFix)
    +            throws IOException {
    +        int ret = 0;
    +        Process process = workerLauncher(conf, user, args, environment, logPreFix, null, null);
    +        if (StringUtils.isNotBlank(logPreFix))
    +            Utils.readAndLogStream(logPreFix, process.getInputStream());
    +        try {
    +            process.waitFor();
    +        } catch (InterruptedException e) {
    +            LOG.info("{} interrupted.", logPreFix);
    +        }
    +        ret = process.exitValue();
    +        return ret;
    +    }
    +
    +    public static void setupStormCodeDir(Map conf, Map stormConf, String dir) throws IOException {
    +        if (Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false)) {
    +            String logPrefix = "setup conf for " + dir;
    +            List<String> commands = new ArrayList<>();
    +            commands.add("code-dir");
    +            commands.add(dir);
    +            workerLauncherAndWait(conf, (String) (stormConf.get(Config.TOPOLOGY_SUBMITTER_USER)), commands, null, logPrefix);
    +        }
    +    }
    +
    +    public static void rmrAsUser(Map conf, String id, String path) throws IOException {
    +        String user = Utils.getFileOwner(path);
    +        String logPreFix = "rmr " + id;
    +        List<String> commands = new ArrayList<>();
    +        commands.add("rmr");
    +        commands.add(path);
    +        SupervisorUtils.workerLauncherAndWait(conf, user, commands, null, logPreFix);
    +        if (Utils.checkFileExists(path)) {
    +            throw new RuntimeException(path + " was not deleted.");
    +        }
    +    }
    +
    +    /**
    +     * Given the blob information returns the value of the uncompress field, handling it either being a string or a boolean value, or if it's not specified then
    +     * returns false
    +     * 
    +     * @param blobInfo
    +     * @return
    +     */
    +    public static Boolean shouldUncompressBlob(Map<String, Object> blobInfo) {
    +        return new Boolean((String) blobInfo.get("uncompress"));
    +    }
    +
    +    /**
    +     * Remove a reference to a blob when its no longer needed
    --- End diff --
    
    Correct doc comment is 
    `Returns a list of LocalResources based on the blobstore-map passed in.`


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55939032
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncProcessEvent.java ---
    @@ -0,0 +1,672 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.ExecutorInfo;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.WorkerResources;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +import org.yaml.snakeyaml.Yaml;
    +
    +import java.io.File;
    +import java.io.FileWriter;
    +import java.io.IOException;
    +import java.util.*;
    +
    +/**
    + * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file - rmr
    + * heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new worker
    + * ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait for workers
    + * launch
    + */
    +public class SyncProcessEvent implements Runnable {
    +
    +    private static Logger LOG = LoggerFactory.getLogger(SyncProcessEvent.class);
    +
    +    private  LocalState localState;
    +    private  SupervisorData supervisorData;
    +    public static final ExecutorInfo SYSTEM_EXECUTOR_INFO = new ExecutorInfo(-1, -1);
    +
    +    private class ProcessExitCallback implements Utils.ExitCodeCallable {
    +        private final String logPrefix;
    +        private final String workerId;
    +
    +        public ProcessExitCallback(String logPrefix, String workerId) {
    +            this.logPrefix = logPrefix;
    +            this.workerId = workerId;
    +        }
    +
    +        @Override
    +        public Object call() throws Exception {
    +            return null;
    +        }
    +
    +        @Override
    +        public Object call(int exitCode) {
    +            LOG.info("{} exited with code: {}", logPrefix, exitCode);
    +            supervisorData.getDeadWorkers().add(workerId);
    +            return null;
    +        }
    +    }
    +
    +    public SyncProcessEvent(){
    +
    +    }
    +    public SyncProcessEvent(SupervisorData supervisorData) {
    +        init(supervisorData);
    +    }
    +
    +    //TODO: initData is intended to local supervisor, so we will remove them after porting worker.clj to java
    +    public void init(SupervisorData supervisorData){
    +        this.supervisorData = supervisorData;
    +        this.localState = supervisorData.getLocalState();
    +    }
    +
    +
    +    /**
    +     * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file -
    +     * rmr heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new
    +     * worker ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait
    +     * for workers launch
    +     */
    +    @Override
    +    public void run() {
    +        LOG.debug("Syncing processes");
    +        try {
    +            Map conf = supervisorData.getConf();
    +            Map<Integer, LocalAssignment> assignedExecutors = localState.getLocalAssignmentsMap();
    +
    +            if (assignedExecutors == null) {
    +                assignedExecutors = new HashMap<>();
    +            }
    +            int now = Time.currentTimeSecs();
    +
    +            Map<String, StateHeartbeat> localWorkerStats = getLocalWorkerStats(supervisorData, assignedExecutors, now);
    +
    +            Set<String> keeperWorkerIds = new HashSet<>();
    +            Set<Integer> keepPorts = new HashSet<>();
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() == State.VALID) {
    +                    keeperWorkerIds.add(entry.getKey());
    +                    keepPorts.add(stateHeartbeat.getHeartbeat().get_port());
    +                }
    +            }
    +            Map<Integer, LocalAssignment> reassignExecutors = getReassignExecutors(assignedExecutors, keepPorts);
    +            Map<Integer, String> newWorkerIds = new HashMap<>();
    +            for (Integer port : reassignExecutors.keySet()) {
    +                newWorkerIds.put(port, Utils.uuid());
    +            }
    +            LOG.debug("Syncing processes");
    +            LOG.debug("Assigned executors: {}", assignedExecutors);
    +            LOG.debug("Allocated: {}", localWorkerStats);
    +
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() != State.VALID) {
    +                    LOG.info("Shutting down and clearing state for id {}, Current supervisor time: {}, State: {}, Heartbeat: {}", entry.getKey(), now,
    +                            stateHeartbeat.getState(), stateHeartbeat.getHeartbeat());
    +                    shutWorker(supervisorData, entry.getKey());
    +                }
    +            }
    +            // start new workers
    +            Map<String, Integer> newWorkerPortToIds = startNewWorkers(newWorkerIds, reassignExecutors);
    +
    +            Map<String, Integer> allWorkerPortToIds = new HashMap<>();
    +            Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +            for (String keeper : keeperWorkerIds) {
    +                allWorkerPortToIds.put(keeper, approvedWorkers.get(keeper));
    +            }
    +            allWorkerPortToIds.putAll(newWorkerPortToIds);
    +            localState.setApprovedWorkers(allWorkerPortToIds);
    +            waitForWorkersLaunch(conf, newWorkerPortToIds.keySet());
    +
    +        } catch (Exception e) {
    +            LOG.error("Failed Sync Process", e);
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +    }
    +
    +    protected void waitForWorkersLaunch(Map conf, Set<String> workerIds) throws Exception {
    +        int startTime = Time.currentTimeSecs();
    +        int timeOut = (int) conf.get(Config.NIMBUS_SUPERVISOR_TIMEOUT_SECS);
    +        for (String workerId : workerIds) {
    +            LocalState localState = ConfigUtils.workerState(conf, workerId);
    +            while (true) {
    +                LSWorkerHeartbeat hb = localState.getWorkerHeartBeat();
    +                if (hb != null || (Time.currentTimeSecs() - startTime) > timeOut)
    +                    break;
    +                LOG.info("{} still hasn't started", workerId);
    +                Time.sleep(500);
    +            }
    +            if (localState.getWorkerHeartBeat() == null) {
    +                LOG.info("Worker {} failed to start", workerId);
    +            }
    +        }
    +    }
    +
    +    protected Map<Integer, LocalAssignment> getReassignExecutors(Map<Integer, LocalAssignment> assignExecutors, Set<Integer> keepPorts) {
    +        Map<Integer, LocalAssignment> reassignExecutors = new HashMap<>();
    +        reassignExecutors.putAll(assignExecutors);
    +        for (Integer port : keepPorts) {
    +            reassignExecutors.remove(port);
    +        }
    +        return reassignExecutors;
    +    }
    +    
    +    /**
    +     * Returns map from worker id to worker heartbeat. if the heartbeat is nil, then the worker is dead
    +     * 
    +     * @param assignedExecutors
    +     * @return
    +     * @throws Exception
    +     */
    +    public Map<String, StateHeartbeat> getLocalWorkerStats(SupervisorData supervisorData, Map<Integer, LocalAssignment> assignedExecutors, int now) throws Exception {
    +        Map<String, StateHeartbeat> workerIdHbstate = new HashMap<>();
    +        Map conf = supervisorData.getConf();
    +        LocalState localState = supervisorData.getLocalState();
    +        Map<String, LSWorkerHeartbeat> idToHeartbeat = SupervisorUtils.readWorkerHeartbeats(conf);
    +        Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +        Set<String> approvedIds = new HashSet<>();
    +        if (approvedWorkers != null) {
    +            approvedIds.addAll(approvedWorkers.keySet());
    +        }
    +        for (Map.Entry<String, LSWorkerHeartbeat> entry : idToHeartbeat.entrySet()) {
    +            String workerId = entry.getKey();
    +            LSWorkerHeartbeat whb = entry.getValue();
    +            State state;
    +            if (whb == null) {
    +                state = State.NOT_STARTED;
    +            } else if (!approvedIds.contains(workerId) || !matchesAssignment(whb, assignedExecutors)) {
    +                state = State.DISALLOWED;
    +            } else if (supervisorData.getDeadWorkers().contains(workerId)) {
    +                LOG.info("Worker Process {} has died", workerId);
    +                state = State.TIMED_OUT;
    +            } else if (SupervisorUtils.isWorkerHbTimedOut(now, whb, conf)) {
    +                state = State.TIMED_OUT;
    +            } else {
    +                state = State.VALID;
    +            }
    +            LOG.debug("Worker:{} state:{} WorkerHeartbeat:{} at supervisor time-secs {}", workerId, state, whb, now);
    +            workerIdHbstate.put(workerId, new StateHeartbeat(state, whb));
    +        }
    +        return workerIdHbstate;
    +    }
    +
    +    protected boolean matchesAssignment(LSWorkerHeartbeat whb, Map<Integer, LocalAssignment> assignedExecutors) {
    +        LocalAssignment localAssignment = assignedExecutors.get(whb.get_port());
    +        if (localAssignment == null || !localAssignment.get_topology_id().equals(whb.get_topology_id())) {
    +            return false;
    +        }
    +        List<ExecutorInfo> executorInfos = new ArrayList<>();
    +        executorInfos.addAll(whb.get_executors());
    +        // remove SYSTEM_EXECUTOR_ID
    +        executorInfos.remove(SYSTEM_EXECUTOR_INFO);
    +        List<ExecutorInfo> localExecuorInfos = localAssignment.get_executors();
    +
    +        if (localExecuorInfos.size() != executorInfos.size())
    +            return false;
    +
    +        for (ExecutorInfo executorInfo : localExecuorInfos){
    +            if (!localExecuorInfos.contains(executorInfo))
    +                return false;
    +        }
    +        return true;
    +    }
    +
    +    /**
    +     * launch a worker in local mode.
    +     */
    +    protected void launchWorker(SupervisorData supervisorData, String stormId, Long port, String workerId, WorkerResources resources) throws IOException {
    +        // port this function after porting worker to java
    +    }
    +
    +    protected String getWorkerClassPath(String stormJar, Map stormConf) {
    +        List<String> topoClasspath = new ArrayList<>();
    +        Object object = stormConf.get(Config.TOPOLOGY_CLASSPATH);
    +
    +        if (object instanceof List) {
    +            topoClasspath.addAll((List<String>) object);
    +        } else if (object instanceof String){
    +            topoClasspath.add((String)object);
    +        }else {
    +            //ignore
    +        }
    +        String classPath = Utils.workerClasspath();
    +        String classAddPath = Utils.addToClasspath(classPath, Arrays.asList(stormJar));
    +        return Utils.addToClasspath(classAddPath, topoClasspath);
    +    }
    +
    +    /**
    +     * "Generates runtime childopts by replacing keys with topology-id, worker-id, port, mem-onheap"
    +     * 
    +     * @param value
    +     * @param workerId
    +     * @param stormId
    +     * @param port
    +     * @param memOnheap
    +     */
    +    public List<String> substituteChildopts(Object value, String workerId, String stormId, Long port, int memOnheap) {
    +        List<String> rets = new ArrayList<>();
    +        if (value instanceof String) {
    +            String string = (String) value;
    +            string = string.replace("%ID%", String.valueOf(port));
    +            string = string.replace("%WORKER-ID%", workerId);
    +            string = string.replace("%TOPOLOGY-ID%", stormId);
    +            string = string.replace("%WORKER-PORT%", String.valueOf(port));
    +            string = string.replace("%HEAP-MEM%", String.valueOf(memOnheap));
    +            String[] strings = string.split("\\s+");
    +            rets.addAll(Arrays.asList(strings));
    +        } else if (value instanceof List) {
    +            List<Object> objects = (List<Object>) value;
    +            for (Object object : objects) {
    +                String str = (String)object;
    +                str = str.replace("%ID%", String.valueOf(port));
    +                str = str.replace("%WORKER-ID%", workerId);
    +                str = str.replace("%TOPOLOGY-ID%", stormId);
    +                str = str.replace("%WORKER-PORT%", String.valueOf(port));
    +                str = str.replace("%HEAP-MEM%", String.valueOf(memOnheap));
    +                rets.add(str);
    +            }
    +        }
    +        return rets;
    +    }
    +
    +
    +
    +    /**
    +     * launch a worker in distributed mode
    +     * supervisorId for testing
    +     * @throws IOException
    +     */
    +    protected void launchWorker(Map conf, String supervisorId, String assignmentId, String stormId, Long port, String workerId,
    +            WorkerResources resources, CgroupManager cgroupManager, ConcurrentHashSet deadWorkers) throws IOException {
    +
    +        Boolean runWorkerAsUser = Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false);
    +        String stormHome = ConfigUtils.concatIfNotNull(System.getProperty("storm.home"));
    +        String stormOptions = ConfigUtils.concatIfNotNull(System.getProperty("storm.options"));
    +        String stormConfFile = ConfigUtils.concatIfNotNull(System.getProperty("storm.conf.file"));
    +        String workerTmpDir = ConfigUtils.workerTmpRoot(conf, workerId);
    +
    +        String stormLogDir = ConfigUtils.getLogDir();
    +        String stormLogConfDir = (String) (conf.get(Config.STORM_LOG4J2_CONF_DIR));
    +
    +        String stormLog4j2ConfDir;
    +        if (StringUtils.isNotBlank(stormLogConfDir)) {
    +            if (Utils.isAbsolutePath(stormLogConfDir)) {
    +                stormLog4j2ConfDir = stormLogConfDir;
    +            } else {
    +                stormLog4j2ConfDir = stormHome + Utils.FILE_PATH_SEPARATOR + stormLogConfDir;
    +            }
    +        } else {
    +            stormLog4j2ConfDir = stormHome + Utils.FILE_PATH_SEPARATOR + "log4j2";
    +        }
    +
    +        String stormRoot = ConfigUtils.supervisorStormDistRoot(conf, stormId);
    +
    +        String jlp = jlp(stormRoot, conf);
    +
    +        String stormJar = ConfigUtils.supervisorStormJarPath(stormRoot);
    +
    +        Map stormConf = ConfigUtils.readSupervisorStormConf(conf, stormId);
    +
    +        String workerClassPath = getWorkerClassPath(stormJar, stormConf);
    +
    +        Object topGcOptsObject = stormConf.get(Config.TOPOLOGY_WORKER_GC_CHILDOPTS);
    +        List<String> topGcOpts = new ArrayList<>();
    +        if (topGcOptsObject instanceof String) {
    +            topGcOpts.add((String) topGcOptsObject);
    +        } else if (topGcOptsObject instanceof List) {
    +            topGcOpts.addAll((List<String>) topGcOptsObject);
    +        }
    +
    +        int memOnheap = 0;
    +        if (resources.get_mem_on_heap() > 0) {
    +            memOnheap = (int) Math.ceil(resources.get_mem_on_heap());
    +        } else {
    +            //set the default heap memory size for supervisor-test
    +            memOnheap = Utils.getInt(stormConf.get(Config.WORKER_HEAP_MEMORY_MB), 768);
    +        }
    +
    +        int memoffheap = (int) Math.ceil(resources.get_mem_off_heap());
    +
    +        int cpu = (int) Math.ceil(resources.get_cpu());
    +
    +        List<String> gcOpts = null;
    +
    +        if (topGcOpts != null) {
    +            gcOpts = substituteChildopts(topGcOpts, workerId, stormId, port, memOnheap);
    +        } else {
    +            gcOpts = substituteChildopts(conf.get(Config.WORKER_GC_CHILDOPTS), workerId, stormId, port, memOnheap);
    --- End diff --
    
    this will never be called. Please refer to my comment above. 


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55601229
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorUtils.java ---
    @@ -0,0 +1,273 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.curator.utils.PathUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.localizer.LocalResource;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.IOException;
    +import java.net.URLDecoder;
    +import java.util.*;
    +
    +public class SupervisorUtils {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorUtils.class);
    +
    +    private static final SupervisorUtils INSTANCE = new SupervisorUtils();
    +    private static SupervisorUtils _instance = INSTANCE;
    +
    +    public static void setInstance(SupervisorUtils u) {
    +        _instance = u;
    +    }
    +
    +    public static void resetInstance() {
    +        _instance = INSTANCE;
    +    }
    +
    +    public static Process workerLauncher(Map conf, String user, List<String> args, Map<String, String> environment, final String logPreFix,
    +            final Utils.ExitCodeCallable exitCodeCallback, File dir) throws IOException {
    +        if (StringUtils.isBlank(user)) {
    +            throw new IllegalArgumentException("User cannot be blank when calling workerLauncher.");
    +        }
    +        String wlinitial = (String) (conf.get(Config.SUPERVISOR_WORKER_LAUNCHER));
    +        String stormHome = ConfigUtils.concatIfNotNull(System.getProperty("storm.home"));
    +        String wl;
    +        if (StringUtils.isNotBlank(wlinitial)) {
    +            wl = wlinitial;
    +        } else {
    +            wl = stormHome + "/bin/worker-launcher";
    +        }
    +        List<String> commands = new ArrayList<>();
    +        commands.add(wl);
    +        commands.add(user);
    +        commands.addAll(args);
    +        return Utils.launchProcess(commands, environment, logPreFix, exitCodeCallback, dir);
    +    }
    +
    +    public static int workerLauncherAndWait(Map conf, String user, List<String> args, final Map<String, String> environment, final String logPreFix)
    +            throws IOException {
    +        int ret = 0;
    +        Process process = workerLauncher(conf, user, args, environment, logPreFix, null, null);
    +        if (StringUtils.isNotBlank(logPreFix))
    +            Utils.readAndLogStream(logPreFix, process.getInputStream());
    +        try {
    +            process.waitFor();
    +        } catch (InterruptedException e) {
    +            LOG.info("{} interrupted.", logPreFix);
    +        }
    +        ret = process.exitValue();
    +        return ret;
    +    }
    +
    +    public static void setupStormCodeDir(Map conf, Map stormConf, String dir) throws IOException {
    +        if (Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false)) {
    +            String logPrefix = "setup conf for " + dir;
    +            List<String> commands = new ArrayList<>();
    +            commands.add("code-dir");
    +            commands.add(dir);
    +            workerLauncherAndWait(conf, (String) (stormConf.get(Config.TOPOLOGY_SUBMITTER_USER)), commands, null, logPrefix);
    +        }
    +    }
    +
    +    public static void rmrAsUser(Map conf, String id, String path) throws IOException {
    +        String user = Utils.getFileOwner(path);
    +        String logPreFix = "rmr " + id;
    +        List<String> commands = new ArrayList<>();
    +        commands.add("rmr");
    +        commands.add(path);
    +        SupervisorUtils.workerLauncherAndWait(conf, user, commands, null, logPreFix);
    +        if (Utils.checkFileExists(path)) {
    +            throw new RuntimeException(path + " was not deleted.");
    +        }
    +    }
    +
    +    /**
    +     * Given the blob information returns the value of the uncompress field, handling it either being a string or a boolean value, or if it's not specified then
    +     * returns false
    +     * 
    +     * @param blobInfo
    +     * @return
    +     */
    +    public static Boolean isShouldUncompressBlob(Map<String, Object> blobInfo) {
    +        return new Boolean((String) blobInfo.get("uncompress"));
    +    }
    +
    +    /**
    +     * Remove a reference to a blob when its no longer needed
    +     * 
    +     * @param blobstoreMap
    +     * @return
    +     */
    +    public static List<LocalResource> blobstoreMapToLocalresources(Map<String, Map<String, Object>> blobstoreMap) {
    +        List<LocalResource> localResourceList = new ArrayList<>();
    +        if (blobstoreMap != null) {
    +            for (Map.Entry<String, Map<String, Object>> map : blobstoreMap.entrySet()) {
    +                LocalResource localResource = new LocalResource(map.getKey(), isShouldUncompressBlob(map.getValue()));
    +                localResourceList.add(localResource);
    +            }
    +        }
    +        return localResourceList;
    +    }
    +
    +    /**
    +     * For each of the downloaded topologies, adds references to the blobs that the topologies are using. This is used to reconstruct the cache on restart.
    +     * 
    +     * @param localizer
    +     * @param stormId
    +     * @param conf
    +     */
    +    public static void addBlobReferences(Localizer localizer, String stormId, Map conf) throws IOException {
    +        Map stormConf = ConfigUtils.readSupervisorStormConf(conf, stormId);
    +        Map<String, Map<String, Object>> blobstoreMap = (Map<String, Map<String, Object>>) stormConf.get(Config.TOPOLOGY_BLOBSTORE_MAP);
    +        String user = (String) stormConf.get(Config.TOPOLOGY_SUBMITTER_USER);
    +        String topoName = (String) stormConf.get(Config.TOPOLOGY_NAME);
    +        List<LocalResource> localresources = SupervisorUtils.blobstoreMapToLocalresources(blobstoreMap);
    +        if (blobstoreMap != null) {
    +            localizer.addReferences(localresources, user, topoName);
    +        }
    +    }
    +
    +    public static Set<String> readDownLoadedStormIds(Map conf) throws IOException {
    +        Set<String> stormIds = new HashSet<>();
    +        String path = ConfigUtils.supervisorStormDistRoot(conf);
    +        Collection<String> rets = Utils.readDirContents(path);
    +        for (String ret : rets) {
    +            stormIds.add(URLDecoder.decode(ret));
    +        }
    +        return stormIds;
    +    }
    +
    +    public static Collection<String> supervisorWorkerIds(Map conf) {
    +        String workerRoot = ConfigUtils.workerRoot(conf);
    +        return Utils.readDirContents(workerRoot);
    +    }
    +
    +    public static boolean checkTopoFilesExist(Map conf, String stormId) throws IOException {
    --- End diff --
    
    check implies to me that we will do something if they don't exist.  I would prefer to see this be a question like `doTopoFilesExist`, or `doRequiredTopoFilesExist`.


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55584667
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorData.java ---
    @@ -0,0 +1,339 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.cluster.ClusterStateContext;
    +import org.apache.storm.cluster.ClusterUtils;
    +import org.apache.storm.cluster.DaemonType;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.ProfileRequest;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +import java.net.UnknownHostException;
    +import java.util.ArrayList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.concurrent.ConcurrentHashMap;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SupervisorData {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorData.class);
    +
    +    private Map conf;
    +    private IContext sharedContext;
    +    private volatile boolean active;
    +    private ISupervisor iSupervisor;
    +    private Utils.UptimeComputer upTime;
    +    private String stormVersion;
    +
    +    private ConcurrentHashMap<String, String> workerThreadPidsAtom; // for local mode
    +
    +    private IStormClusterState stormClusterState;
    +
    +    private LocalState localState;
    +
    +    private String supervisorId;
    +
    +    private String assignmentId;
    +
    +    private String hostName;
    +
    +    // used for reporting used ports when heartbeating
    +    private ConcurrentHashMap<Long, LocalAssignment> currAssignment;
    +
    +    private StormTimer heartbeatTimer;
    +
    +    private StormTimer eventTimer;
    +
    +    private StormTimer blobUpdateTimer;
    +
    +    private Localizer localizer;
    +
    +    private ConcurrentHashMap<String, Map<String, Object>> assignmentVersions;
    +
    +    private AtomicInteger syncRetry;
    +
    +    private final Object downloadLock = new Object();
    +
    +    private ConcurrentHashMap<String, List<ProfileRequest>> stormIdToProfileActions;
    +
    +    private CgroupManager resourceIsolationManager;
    +
    +    private ConcurrentHashSet<String> deadWorkers;
    +
    +    public SupervisorData(Map conf, IContext sharedContext, ISupervisor iSupervisor) {
    +        this.conf = conf;
    +        this.sharedContext = sharedContext;
    +        this.iSupervisor = iSupervisor;
    +        this.active = true;
    +        this.upTime = Utils.makeUptimeComputer();
    +        this.stormVersion = VersionInfo.getVersion();
    +        this.workerThreadPidsAtom = new ConcurrentHashMap<String, String>();
    +        this.deadWorkers = new ConcurrentHashSet();
    +
    +        List<ACL> acls = null;
    +        if (Utils.isZkAuthenticationConfiguredStormServer(conf)) {
    +            acls = SupervisorUtils.supervisorZkAcls();
    +        }
    +
    +        try {
    +            this.stormClusterState = ClusterUtils.mkStormClusterState(conf, acls, new ClusterStateContext(DaemonType.SUPERVISOR));
    +        } catch (Exception e) {
    +            LOG.error("supervisor can't create stormClusterState");
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        try {
    +            this.localState = ConfigUtils.supervisorState(conf);
    +            this.localizer = Utils.createLocalizer(conf, ConfigUtils.supervisorLocalDir(conf));
    +        } catch (IOException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +        this.supervisorId = iSupervisor.getSupervisorId();
    +        this.assignmentId = iSupervisor.getAssignmentId();
    +
    +        try {
    +            this.hostName = Utils.hostname(conf);
    +        } catch (UnknownHostException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        this.currAssignment = new ConcurrentHashMap<>();
    +
    +        this.heartbeatTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.eventTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.blobUpdateTimer = new StormTimer("blob-update-timer", new DefaultUncaughtExceptionHandler());
    +
    +        this.assignmentVersions = new ConcurrentHashMap<>();
    +        this.syncRetry = new AtomicInteger(0);
    +        this.stormIdToProfileActions = new ConcurrentHashMap<>();
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            try {
    +                this.resourceIsolationManager = (CgroupManager) Utils.newInstance((String) conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN));
    +                this.resourceIsolationManager.prepare(conf);
    +                LOG.info("Using resource isolation plugin {} {}", conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN), resourceIsolationManager);
    +            } catch (IOException e) {
    +                throw Utils.wrapInRuntime(e);
    +            }
    +        } else {
    +            this.resourceIsolationManager = null;
    +        }
    +    }
    +
    +    public ConcurrentHashMap<String, List<ProfileRequest>> getStormIdToProfileActions() {
    +        return stormIdToProfileActions;
    +    }
    +
    +    public void setStormIdToProfileActions(Map<String, List<ProfileRequest>> stormIdToProfileActions) {
    +        this.stormIdToProfileActions.clear();
    +        this.stormIdToProfileActions.putAll(stormIdToProfileActions);
    +    }
    +
    +    public Map getConf() {
    +        return conf;
    +    }
    +
    +    public void setConf(Map conf) {
    +        this.conf = conf;
    +    }
    +
    +    public IContext getSharedContext() {
    +        return sharedContext;
    +    }
    +
    +    public void setSharedContext(IContext sharedContext) {
    +        this.sharedContext = sharedContext;
    +    }
    +
    +    public boolean isActive() {
    +        return active;
    +    }
    +
    +    public void setActive(boolean active) {
    +        this.active = active;
    +    }
    +
    +    public ISupervisor getiSupervisor() {
    +        return iSupervisor;
    +    }
    +
    +    public void setiSupervisor(ISupervisor iSupervisor) {
    +        this.iSupervisor = iSupervisor;
    +    }
    +
    +    public Utils.UptimeComputer getUpTime() {
    +        return upTime;
    +    }
    +
    +    public void setUpTime(Utils.UptimeComputer upTime) {
    +        this.upTime = upTime;
    +    }
    +
    +    public String getStormVersion() {
    +        return stormVersion;
    +    }
    +
    +    public void setStormVersion(String stormVersion) {
    +        this.stormVersion = stormVersion;
    +    }
    +
    +    public ConcurrentHashMap<String, String> getWorkerThreadPidsAtom() {
    --- End diff --
    
    This is not really an atom any more, so lets drop atom from the name.


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55254223
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/StandaloneSupervisor.java ---
    @@ -0,0 +1,87 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +
    +import java.io.IOException;
    +import java.util.Collection;
    +import java.util.Map;
    +import java.util.UUID;
    +
    +public class StandaloneSupervisor implements ISupervisor {
    +
    +    private String supervisorId;
    +
    --- End diff --
    
    extra line


---
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-1279] port backtype.storm.daemon.superv...

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

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


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55584866
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorData.java ---
    @@ -0,0 +1,339 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.cluster.ClusterStateContext;
    +import org.apache.storm.cluster.ClusterUtils;
    +import org.apache.storm.cluster.DaemonType;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.ProfileRequest;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +import java.net.UnknownHostException;
    +import java.util.ArrayList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.concurrent.ConcurrentHashMap;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SupervisorData {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorData.class);
    +
    +    private Map conf;
    +    private IContext sharedContext;
    +    private volatile boolean active;
    +    private ISupervisor iSupervisor;
    +    private Utils.UptimeComputer upTime;
    +    private String stormVersion;
    +
    +    private ConcurrentHashMap<String, String> workerThreadPidsAtom; // for local mode
    +
    +    private IStormClusterState stormClusterState;
    +
    +    private LocalState localState;
    +
    +    private String supervisorId;
    +
    +    private String assignmentId;
    +
    +    private String hostName;
    +
    +    // used for reporting used ports when heartbeating
    +    private ConcurrentHashMap<Long, LocalAssignment> currAssignment;
    +
    +    private StormTimer heartbeatTimer;
    +
    +    private StormTimer eventTimer;
    +
    +    private StormTimer blobUpdateTimer;
    +
    +    private Localizer localizer;
    +
    +    private ConcurrentHashMap<String, Map<String, Object>> assignmentVersions;
    +
    +    private AtomicInteger syncRetry;
    +
    +    private final Object downloadLock = new Object();
    +
    +    private ConcurrentHashMap<String, List<ProfileRequest>> stormIdToProfileActions;
    +
    +    private CgroupManager resourceIsolationManager;
    +
    +    private ConcurrentHashSet<String> deadWorkers;
    +
    +    public SupervisorData(Map conf, IContext sharedContext, ISupervisor iSupervisor) {
    +        this.conf = conf;
    +        this.sharedContext = sharedContext;
    +        this.iSupervisor = iSupervisor;
    +        this.active = true;
    +        this.upTime = Utils.makeUptimeComputer();
    +        this.stormVersion = VersionInfo.getVersion();
    +        this.workerThreadPidsAtom = new ConcurrentHashMap<String, String>();
    +        this.deadWorkers = new ConcurrentHashSet();
    +
    +        List<ACL> acls = null;
    +        if (Utils.isZkAuthenticationConfiguredStormServer(conf)) {
    +            acls = SupervisorUtils.supervisorZkAcls();
    +        }
    +
    +        try {
    +            this.stormClusterState = ClusterUtils.mkStormClusterState(conf, acls, new ClusterStateContext(DaemonType.SUPERVISOR));
    +        } catch (Exception e) {
    +            LOG.error("supervisor can't create stormClusterState");
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        try {
    +            this.localState = ConfigUtils.supervisorState(conf);
    +            this.localizer = Utils.createLocalizer(conf, ConfigUtils.supervisorLocalDir(conf));
    +        } catch (IOException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +        this.supervisorId = iSupervisor.getSupervisorId();
    +        this.assignmentId = iSupervisor.getAssignmentId();
    +
    +        try {
    +            this.hostName = Utils.hostname(conf);
    +        } catch (UnknownHostException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        this.currAssignment = new ConcurrentHashMap<>();
    +
    +        this.heartbeatTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.eventTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.blobUpdateTimer = new StormTimer("blob-update-timer", new DefaultUncaughtExceptionHandler());
    +
    +        this.assignmentVersions = new ConcurrentHashMap<>();
    +        this.syncRetry = new AtomicInteger(0);
    +        this.stormIdToProfileActions = new ConcurrentHashMap<>();
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            try {
    +                this.resourceIsolationManager = (CgroupManager) Utils.newInstance((String) conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN));
    +                this.resourceIsolationManager.prepare(conf);
    +                LOG.info("Using resource isolation plugin {} {}", conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN), resourceIsolationManager);
    +            } catch (IOException e) {
    +                throw Utils.wrapInRuntime(e);
    +            }
    +        } else {
    +            this.resourceIsolationManager = null;
    +        }
    +    }
    +
    +    public ConcurrentHashMap<String, List<ProfileRequest>> getStormIdToProfileActions() {
    +        return stormIdToProfileActions;
    +    }
    +
    +    public void setStormIdToProfileActions(Map<String, List<ProfileRequest>> stormIdToProfileActions) {
    +        this.stormIdToProfileActions.clear();
    +        this.stormIdToProfileActions.putAll(stormIdToProfileActions);
    +    }
    +
    +    public Map getConf() {
    +        return conf;
    +    }
    +
    +    public void setConf(Map conf) {
    +        this.conf = conf;
    +    }
    +
    +    public IContext getSharedContext() {
    +        return sharedContext;
    +    }
    +
    +    public void setSharedContext(IContext sharedContext) {
    +        this.sharedContext = sharedContext;
    +    }
    +
    +    public boolean isActive() {
    +        return active;
    +    }
    +
    +    public void setActive(boolean active) {
    +        this.active = active;
    +    }
    +
    +    public ISupervisor getiSupervisor() {
    +        return iSupervisor;
    +    }
    +
    +    public void setiSupervisor(ISupervisor iSupervisor) {
    +        this.iSupervisor = iSupervisor;
    +    }
    +
    +    public Utils.UptimeComputer getUpTime() {
    +        return upTime;
    +    }
    +
    +    public void setUpTime(Utils.UptimeComputer upTime) {
    +        this.upTime = upTime;
    +    }
    +
    +    public String getStormVersion() {
    +        return stormVersion;
    +    }
    +
    +    public void setStormVersion(String stormVersion) {
    +        this.stormVersion = stormVersion;
    +    }
    +
    +    public ConcurrentHashMap<String, String> getWorkerThreadPidsAtom() {
    +        return workerThreadPidsAtom;
    +    }
    +
    +    public void setWorkerThreadPidsAtom(ConcurrentHashMap<String, String> workerThreadPidsAtom) {
    +        this.workerThreadPidsAtom = workerThreadPidsAtom;
    +    }
    +
    +    public IStormClusterState getStormClusterState() {
    +        return stormClusterState;
    +    }
    +
    +    public void setStormClusterState(IStormClusterState stormClusterState) {
    +        this.stormClusterState = stormClusterState;
    +    }
    +
    +    public LocalState getLocalState() {
    +        return localState;
    +    }
    +
    +    public void setLocalState(LocalState localState) {
    +        this.localState = localState;
    +    }
    +
    +    public String getSupervisorId() {
    +        return supervisorId;
    +    }
    +
    +    public void setSupervisorId(String supervisorId) {
    +        this.supervisorId = supervisorId;
    +    }
    +
    +    public String getAssignmentId() {
    +        return assignmentId;
    +    }
    +
    +    public void setAssignmentId(String assignmentId) {
    +        this.assignmentId = assignmentId;
    +    }
    +
    +    public String getHostName() {
    +        return hostName;
    +    }
    +
    +    public void setHostName(String hostName) {
    --- End diff --
    
    Not Used


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55571026
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/State.java ---
    @@ -0,0 +1,22 @@
    +/**
    + * 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.supervisor;
    +
    +public enum State {
    +    valid, disallowed, notStarted, timedOut;
    --- End diff --
    
    minor nit. Can we name these more like java const Enums values?
    
    ```
    VALID, DISALLOWED, NOT_STARTED, TIMED_OUT;
    ```


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55937791
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/Supervisor.java ---
    @@ -0,0 +1,178 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.daemon.supervisor.timer.RunProfilerActions;
    +import org.apache.storm.daemon.supervisor.timer.SupervisorHealthCheck;
    +import org.apache.storm.daemon.supervisor.timer.SupervisorHeartbeat;
    +import org.apache.storm.daemon.supervisor.timer.UpdateBlobs;
    +import org.apache.storm.event.EventManagerImp;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.metric.StormMetricsRegistry;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.InterruptedIOException;
    +import java.util.Collection;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.Callable;
    +
    +public class Supervisor {
    +    private static Logger LOG = LoggerFactory.getLogger(Supervisor.class);
    +
    +    // TODO: to be removed after porting worker.clj. localSyncProcess is intended to start local supervisor
    +    private SyncProcessEvent localSyncProcess;
    +
    +    public void setLocalSyncProcess(SyncProcessEvent localSyncProcess) {
    +        this.localSyncProcess = localSyncProcess;
    +    }
    +
    +    /**
    +     * in local state, supervisor stores who its current assignments are another thread launches events to restart any dead processes if necessary
    +     * 
    +     * @param conf
    +     * @param sharedContext
    +     * @param iSupervisor
    +     * @return
    +     * @throws Exception
    +     */
    +    public SupervisorManger mkSupervisor(final Map conf, IContext sharedContext, ISupervisor iSupervisor) throws Exception {
    +        SupervisorManger supervisorManger = null;
    +        try {
    +            LOG.info("Starting Supervisor with conf {}", conf);
    +            iSupervisor.prepare(conf, ConfigUtils.supervisorIsupervisorDir(conf));
    +            String path = ConfigUtils.supervisorTmpDir(conf);
    +            FileUtils.cleanDirectory(new File(path));
    +
    +            final SupervisorData supervisorData = new SupervisorData(conf, sharedContext, iSupervisor);
    +            Localizer localizer = supervisorData.getLocalizer();
    +
    +            SupervisorHeartbeat hb = new SupervisorHeartbeat(conf, supervisorData);
    +            hb.run();
    +            // should synchronize supervisor so it doesn't launch anything after being down (optimization)
    +            Integer heartbeatFrequency = Utils.getInt(conf.get(Config.SUPERVISOR_HEARTBEAT_FREQUENCY_SECS));
    +            supervisorData.getHeartbeatTimer().scheduleRecurring(0, heartbeatFrequency, hb);
    +
    +            Set<String> downdedStormId = SupervisorUtils.readDownLoadedStormIds(conf);
    +            for (String stormId : downdedStormId) {
    +                SupervisorUtils.addBlobReferences(localizer, stormId, conf);
    +            }
    +            // do this after adding the references so we don't try to clean things being used
    +            localizer.startCleaner();
    +
    +            EventManagerImp syncSupEventManager = new EventManagerImp(false);
    +            EventManagerImp syncProcessManager = new EventManagerImp(false);
    +
    +            SyncProcessEvent syncProcessEvent = null;
    +            if (ConfigUtils.isLocalMode(conf)) {
    +                localSyncProcess.init(supervisorData);
    +                syncProcessEvent = localSyncProcess;
    +            } else {
    +                syncProcessEvent = new SyncProcessEvent(supervisorData);
    +            }
    +
    +            SyncSupervisorEvent syncSupervisorEvent = new SyncSupervisorEvent(supervisorData, syncProcessEvent, syncSupEventManager, syncProcessManager);
    +            UpdateBlobs updateBlobsThread = new UpdateBlobs(supervisorData);
    +            RunProfilerActions runProfilerActionThread = new RunProfilerActions(supervisorData);
    +
    +            if ((Boolean) conf.get(Config.SUPERVISOR_ENABLE)) {
    +                StormTimer eventTimer = supervisorData.getEventTimer();
    +                // This isn't strictly necessary, but it doesn't hurt and ensures that the machine stays up
    +                // to date even if callbacks don't all work exactly right
    +                eventTimer.scheduleRecurring(0, 10, new EventManagerPushCallback(syncSupervisorEvent, syncSupEventManager));
    +
    +                eventTimer.scheduleRecurring(0, Utils.getInt(conf.get(Config.SUPERVISOR_MONITOR_FREQUENCY_SECS)),
    +                        new EventManagerPushCallback(syncProcessEvent, syncProcessManager));
    +
    +                // Blob update thread. Starts with 30 seconds delay, every 30 seconds
    +                supervisorData.getBlobUpdateTimer().scheduleRecurring(30, 30, new EventManagerPushCallback(updateBlobsThread, syncSupEventManager));
    +
    +                // supervisor health check
    +                eventTimer.scheduleRecurring(300, 300, new SupervisorHealthCheck(supervisorData));
    +
    +                // Launch a thread that Runs profiler commands . Starts with 30 seconds delay, every 30 seconds
    +                eventTimer.scheduleRecurring(30, 30, new EventManagerPushCallback(runProfilerActionThread, syncSupEventManager));
    +            }
    +            LOG.info("Starting supervisor with id {} at host {}.", supervisorData.getSupervisorId(), supervisorData.getHostName());
    +            supervisorManger = new SupervisorManger(supervisorData, syncSupEventManager, syncProcessManager);
    +        } catch (Throwable t) {
    +            if (Utils.exceptionCauseIsInstanceOf(InterruptedIOException.class, t)) {
    +                throw t;
    +            } else if (Utils.exceptionCauseIsInstanceOf(InterruptedException.class, t)) {
    +                throw t;
    +            } else {
    +                LOG.error("Error on initialization of server supervisor: {}", t);
    +                Utils.exitProcess(13, "Error on initialization");
    +            }
    +        }
    +        return supervisorManger;
    +    }
    +
    +    /**
    +     * start distribute supervisor
    +     */
    +    private void launch(ISupervisor iSupervisor) {
    +        LOG.info("Starting supervisor for storm version '{}'.", VersionInfo.getVersion());
    +        SupervisorManger supervisorManager;
    +        try {
    +            Map<Object, Object> conf = Utils.readStormConfig();
    +            if (ConfigUtils.isLocalMode(conf)) {
    +                throw new IllegalArgumentException("Cannot start server in local mode!");
    +            }
    +            supervisorManager = mkSupervisor(conf, null, iSupervisor);
    +            if (supervisorManager != null)
    +                Utils.addShutdownHookWithForceKillIn1Sec(supervisorManager);
    +            registerWorkerNumGauge("supervisor:num-slots-used-gauge", conf);
    +            StormMetricsRegistry.startMetricsReporters(conf);
    +        } catch (Exception e) {
    +            LOG.error("Failed to start supervisor\n", e);
    +            System.exit(1);
    +        }
    +    }
    +
    +    private void registerWorkerNumGauge(String name, final Map conf) {
    +        StormMetricsRegistry.registerGauge("supervisor:num-slots-used-gauge", new Callable<Integer>() {
    --- End diff --
    
    name argument is not used. 


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55942826
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncProcessEvent.java ---
    @@ -0,0 +1,672 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.ExecutorInfo;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.WorkerResources;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +import org.yaml.snakeyaml.Yaml;
    +
    +import java.io.File;
    +import java.io.FileWriter;
    +import java.io.IOException;
    +import java.util.*;
    +
    +/**
    + * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file - rmr
    + * heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new worker
    + * ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait for workers
    + * launch
    + */
    +public class SyncProcessEvent implements Runnable {
    +
    +    private static Logger LOG = LoggerFactory.getLogger(SyncProcessEvent.class);
    +
    +    private  LocalState localState;
    +    private  SupervisorData supervisorData;
    +    public static final ExecutorInfo SYSTEM_EXECUTOR_INFO = new ExecutorInfo(-1, -1);
    +
    +    private class ProcessExitCallback implements Utils.ExitCodeCallable {
    +        private final String logPrefix;
    +        private final String workerId;
    +
    +        public ProcessExitCallback(String logPrefix, String workerId) {
    +            this.logPrefix = logPrefix;
    +            this.workerId = workerId;
    +        }
    +
    +        @Override
    +        public Object call() throws Exception {
    +            return null;
    +        }
    +
    +        @Override
    +        public Object call(int exitCode) {
    +            LOG.info("{} exited with code: {}", logPrefix, exitCode);
    +            supervisorData.getDeadWorkers().add(workerId);
    +            return null;
    +        }
    +    }
    +
    +    public SyncProcessEvent(){
    +
    +    }
    +    public SyncProcessEvent(SupervisorData supervisorData) {
    +        init(supervisorData);
    +    }
    +
    +    //TODO: initData is intended to local supervisor, so we will remove them after porting worker.clj to java
    +    public void init(SupervisorData supervisorData){
    +        this.supervisorData = supervisorData;
    +        this.localState = supervisorData.getLocalState();
    +    }
    +
    +
    +    /**
    +     * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file -
    +     * rmr heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new
    +     * worker ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait
    +     * for workers launch
    +     */
    +    @Override
    +    public void run() {
    +        LOG.debug("Syncing processes");
    +        try {
    +            Map conf = supervisorData.getConf();
    +            Map<Integer, LocalAssignment> assignedExecutors = localState.getLocalAssignmentsMap();
    +
    +            if (assignedExecutors == null) {
    +                assignedExecutors = new HashMap<>();
    +            }
    +            int now = Time.currentTimeSecs();
    +
    +            Map<String, StateHeartbeat> localWorkerStats = getLocalWorkerStats(supervisorData, assignedExecutors, now);
    +
    +            Set<String> keeperWorkerIds = new HashSet<>();
    +            Set<Integer> keepPorts = new HashSet<>();
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() == State.VALID) {
    +                    keeperWorkerIds.add(entry.getKey());
    +                    keepPorts.add(stateHeartbeat.getHeartbeat().get_port());
    +                }
    +            }
    +            Map<Integer, LocalAssignment> reassignExecutors = getReassignExecutors(assignedExecutors, keepPorts);
    +            Map<Integer, String> newWorkerIds = new HashMap<>();
    +            for (Integer port : reassignExecutors.keySet()) {
    +                newWorkerIds.put(port, Utils.uuid());
    +            }
    +            LOG.debug("Syncing processes");
    +            LOG.debug("Assigned executors: {}", assignedExecutors);
    +            LOG.debug("Allocated: {}", localWorkerStats);
    +
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() != State.VALID) {
    +                    LOG.info("Shutting down and clearing state for id {}, Current supervisor time: {}, State: {}, Heartbeat: {}", entry.getKey(), now,
    +                            stateHeartbeat.getState(), stateHeartbeat.getHeartbeat());
    +                    shutWorker(supervisorData, entry.getKey());
    +                }
    +            }
    +            // start new workers
    +            Map<String, Integer> newWorkerPortToIds = startNewWorkers(newWorkerIds, reassignExecutors);
    +
    +            Map<String, Integer> allWorkerPortToIds = new HashMap<>();
    +            Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +            for (String keeper : keeperWorkerIds) {
    +                allWorkerPortToIds.put(keeper, approvedWorkers.get(keeper));
    +            }
    +            allWorkerPortToIds.putAll(newWorkerPortToIds);
    +            localState.setApprovedWorkers(allWorkerPortToIds);
    +            waitForWorkersLaunch(conf, newWorkerPortToIds.keySet());
    +
    +        } catch (Exception e) {
    +            LOG.error("Failed Sync Process", e);
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +    }
    +
    +    protected void waitForWorkersLaunch(Map conf, Set<String> workerIds) throws Exception {
    +        int startTime = Time.currentTimeSecs();
    +        int timeOut = (int) conf.get(Config.NIMBUS_SUPERVISOR_TIMEOUT_SECS);
    +        for (String workerId : workerIds) {
    +            LocalState localState = ConfigUtils.workerState(conf, workerId);
    +            while (true) {
    +                LSWorkerHeartbeat hb = localState.getWorkerHeartBeat();
    +                if (hb != null || (Time.currentTimeSecs() - startTime) > timeOut)
    +                    break;
    +                LOG.info("{} still hasn't started", workerId);
    +                Time.sleep(500);
    +            }
    +            if (localState.getWorkerHeartBeat() == null) {
    +                LOG.info("Worker {} failed to start", workerId);
    +            }
    +        }
    +    }
    +
    +    protected Map<Integer, LocalAssignment> getReassignExecutors(Map<Integer, LocalAssignment> assignExecutors, Set<Integer> keepPorts) {
    +        Map<Integer, LocalAssignment> reassignExecutors = new HashMap<>();
    +        reassignExecutors.putAll(assignExecutors);
    +        for (Integer port : keepPorts) {
    +            reassignExecutors.remove(port);
    +        }
    +        return reassignExecutors;
    +    }
    +    
    +    /**
    +     * Returns map from worker id to worker heartbeat. if the heartbeat is nil, then the worker is dead
    +     * 
    +     * @param assignedExecutors
    +     * @return
    +     * @throws Exception
    +     */
    +    public Map<String, StateHeartbeat> getLocalWorkerStats(SupervisorData supervisorData, Map<Integer, LocalAssignment> assignedExecutors, int now) throws Exception {
    +        Map<String, StateHeartbeat> workerIdHbstate = new HashMap<>();
    +        Map conf = supervisorData.getConf();
    +        LocalState localState = supervisorData.getLocalState();
    +        Map<String, LSWorkerHeartbeat> idToHeartbeat = SupervisorUtils.readWorkerHeartbeats(conf);
    +        Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +        Set<String> approvedIds = new HashSet<>();
    +        if (approvedWorkers != null) {
    +            approvedIds.addAll(approvedWorkers.keySet());
    +        }
    +        for (Map.Entry<String, LSWorkerHeartbeat> entry : idToHeartbeat.entrySet()) {
    +            String workerId = entry.getKey();
    +            LSWorkerHeartbeat whb = entry.getValue();
    +            State state;
    +            if (whb == null) {
    +                state = State.NOT_STARTED;
    +            } else if (!approvedIds.contains(workerId) || !matchesAssignment(whb, assignedExecutors)) {
    +                state = State.DISALLOWED;
    +            } else if (supervisorData.getDeadWorkers().contains(workerId)) {
    +                LOG.info("Worker Process {} has died", workerId);
    +                state = State.TIMED_OUT;
    +            } else if (SupervisorUtils.isWorkerHbTimedOut(now, whb, conf)) {
    +                state = State.TIMED_OUT;
    +            } else {
    +                state = State.VALID;
    +            }
    +            LOG.debug("Worker:{} state:{} WorkerHeartbeat:{} at supervisor time-secs {}", workerId, state, whb, now);
    +            workerIdHbstate.put(workerId, new StateHeartbeat(state, whb));
    +        }
    +        return workerIdHbstate;
    +    }
    +
    +    protected boolean matchesAssignment(LSWorkerHeartbeat whb, Map<Integer, LocalAssignment> assignedExecutors) {
    +        LocalAssignment localAssignment = assignedExecutors.get(whb.get_port());
    +        if (localAssignment == null || !localAssignment.get_topology_id().equals(whb.get_topology_id())) {
    +            return false;
    +        }
    +        List<ExecutorInfo> executorInfos = new ArrayList<>();
    +        executorInfos.addAll(whb.get_executors());
    +        // remove SYSTEM_EXECUTOR_ID
    +        executorInfos.remove(SYSTEM_EXECUTOR_INFO);
    +        List<ExecutorInfo> localExecuorInfos = localAssignment.get_executors();
    +
    +        if (localExecuorInfos.size() != executorInfos.size())
    +            return false;
    +
    +        for (ExecutorInfo executorInfo : localExecuorInfos){
    +            if (!localExecuorInfos.contains(executorInfo))
    +                return false;
    +        }
    +        return true;
    +    }
    +
    +    /**
    +     * launch a worker in local mode.
    +     */
    +    protected void launchWorker(SupervisorData supervisorData, String stormId, Long port, String workerId, WorkerResources resources) throws IOException {
    +        // port this function after porting worker to java
    +    }
    +
    +    protected String getWorkerClassPath(String stormJar, Map stormConf) {
    +        List<String> topoClasspath = new ArrayList<>();
    +        Object object = stormConf.get(Config.TOPOLOGY_CLASSPATH);
    +
    +        if (object instanceof List) {
    +            topoClasspath.addAll((List<String>) object);
    +        } else if (object instanceof String){
    +            topoClasspath.add((String)object);
    +        }else {
    +            //ignore
    +        }
    +        String classPath = Utils.workerClasspath();
    +        String classAddPath = Utils.addToClasspath(classPath, Arrays.asList(stormJar));
    +        return Utils.addToClasspath(classAddPath, topoClasspath);
    +    }
    +
    +    /**
    +     * "Generates runtime childopts by replacing keys with topology-id, worker-id, port, mem-onheap"
    +     * 
    +     * @param value
    +     * @param workerId
    +     * @param stormId
    +     * @param port
    +     * @param memOnheap
    +     */
    +    public List<String> substituteChildopts(Object value, String workerId, String stormId, Long port, int memOnheap) {
    +        List<String> rets = new ArrayList<>();
    +        if (value instanceof String) {
    +            String string = (String) value;
    +            string = string.replace("%ID%", String.valueOf(port));
    +            string = string.replace("%WORKER-ID%", workerId);
    +            string = string.replace("%TOPOLOGY-ID%", stormId);
    +            string = string.replace("%WORKER-PORT%", String.valueOf(port));
    +            string = string.replace("%HEAP-MEM%", String.valueOf(memOnheap));
    +            String[] strings = string.split("\\s+");
    +            rets.addAll(Arrays.asList(strings));
    +        } else if (value instanceof List) {
    +            List<Object> objects = (List<Object>) value;
    +            for (Object object : objects) {
    +                String str = (String)object;
    --- End diff --
    
    nit. space before object


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55942961
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorUtils.java ---
    @@ -0,0 +1,353 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.ProcessSimulator;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.localizer.LocalResource;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.IOException;
    +import java.net.URLDecoder;
    +import java.util.*;
    +
    +public class SupervisorUtils {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorUtils.class);
    +
    +    private static final SupervisorUtils INSTANCE = new SupervisorUtils();
    +    private static SupervisorUtils _instance = INSTANCE;
    +    public static void setInstance(SupervisorUtils u) {
    +        _instance = u;
    +    }
    +    public static void resetInstance() {
    +        _instance = INSTANCE;
    +    }
    +
    +    public static Process workerLauncher(Map conf, String user, List<String> args, Map<String, String> environment, final String logPreFix,
    +            final Utils.ExitCodeCallable exitCodeCallback, File dir) throws IOException {
    +        if (StringUtils.isBlank(user)) {
    +            throw new IllegalArgumentException("User cannot be blank when calling workerLauncher.");
    +        }
    +        String wlinitial = (String) (conf.get(Config.SUPERVISOR_WORKER_LAUNCHER));
    +        String stormHome = ConfigUtils.concatIfNotNull(System.getProperty("storm.home"));
    +        String wl;
    +        if (StringUtils.isNotBlank(wlinitial)) {
    +            wl = wlinitial;
    +        } else {
    +            wl = stormHome + "/bin/worker-launcher";
    +        }
    +        List<String> commands = new ArrayList<>();
    +        commands.add(wl);
    +        commands.add(user);
    +        commands.addAll(args);
    +        LOG.info("Running as user: {} command: {}", user, commands);
    +        return Utils.launchProcess(commands, environment, logPreFix, exitCodeCallback, dir);
    +    }
    +
    +    public static int workerLauncherAndWait(Map conf, String user, List<String> args, final Map<String, String> environment, final String logPreFix)
    +            throws IOException {
    +        int ret = 0;
    +        Process process = workerLauncher(conf, user, args, environment, logPreFix, null, null);
    +        if (StringUtils.isNotBlank(logPreFix))
    +            Utils.readAndLogStream(logPreFix, process.getInputStream());
    +        try {
    +            process.waitFor();
    +        } catch (InterruptedException e) {
    +            LOG.info("{} interrupted.", logPreFix);
    +        }
    +        ret = process.exitValue();
    +        return ret;
    +    }
    +
    +    public static void setupStormCodeDir(Map conf, Map stormConf, String dir) throws IOException {
    +        if (Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false)) {
    +            String logPrefix = "setup conf for " + dir;
    +            List<String> commands = new ArrayList<>();
    +            commands.add("code-dir");
    +            commands.add(dir);
    +            workerLauncherAndWait(conf, (String) (stormConf.get(Config.TOPOLOGY_SUBMITTER_USER)), commands, null, logPrefix);
    +        }
    +    }
    +
    +    public static void rmrAsUser(Map conf, String id, String path) throws IOException {
    +        String user = Utils.getFileOwner(path);
    +        String logPreFix = "rmr " + id;
    +        List<String> commands = new ArrayList<>();
    +        commands.add("rmr");
    +        commands.add(path);
    +        SupervisorUtils.workerLauncherAndWait(conf, user, commands, null, logPreFix);
    +        if (Utils.checkFileExists(path)) {
    +            throw new RuntimeException(path + " was not deleted.");
    +        }
    +    }
    +
    +    /**
    +     * Given the blob information returns the value of the uncompress field, handling it either being a string or a boolean value, or if it's not specified then
    +     * returns false
    +     * 
    +     * @param blobInfo
    +     * @return
    +     */
    +    public static Boolean shouldUncompressBlob(Map<String, Object> blobInfo) {
    +        return new Boolean((String) blobInfo.get("uncompress"));
    +    }
    +
    +    /**
    +     * Remove a reference to a blob when its no longer needed
    +     * 
    +     * @param blobstoreMap
    +     * @return
    +     */
    +    public static List<LocalResource> blobstoreMapToLocalresources(Map<String, Map<String, Object>> blobstoreMap) {
    +        List<LocalResource> localResourceList = new ArrayList<>();
    +        if (blobstoreMap != null) {
    +            for (Map.Entry<String, Map<String, Object>> map : blobstoreMap.entrySet()) {
    +                LocalResource localResource = new LocalResource(map.getKey(), shouldUncompressBlob(map.getValue()));
    +                localResourceList.add(localResource);
    +            }
    +        }
    +        return localResourceList;
    +    }
    +
    +    /**
    +     * For each of the downloaded topologies, adds references to the blobs that the topologies are using. This is used to reconstruct the cache on restart.
    +     * 
    +     * @param localizer
    +     * @param stormId
    +     * @param conf
    +     */
    +    public static void addBlobReferences(Localizer localizer, String stormId, Map conf) throws IOException {
    +        Map stormConf = ConfigUtils.readSupervisorStormConf(conf, stormId);
    +        Map<String, Map<String, Object>> blobstoreMap = (Map<String, Map<String, Object>>) stormConf.get(Config.TOPOLOGY_BLOBSTORE_MAP);
    +        String user = (String) stormConf.get(Config.TOPOLOGY_SUBMITTER_USER);
    +        String topoName = (String) stormConf.get(Config.TOPOLOGY_NAME);
    +        List<LocalResource> localresources = SupervisorUtils.blobstoreMapToLocalresources(blobstoreMap);
    +        if (blobstoreMap != null) {
    +            localizer.addReferences(localresources, user, topoName);
    +        }
    +    }
    +
    +    public static Set<String> readDownLoadedStormIds(Map conf) throws IOException {
    +        Set<String> stormIds = new HashSet<>();
    +        String path = ConfigUtils.supervisorStormDistRoot(conf);
    +        Collection<String> rets = Utils.readDirContents(path);
    +        for (String ret : rets) {
    +            stormIds.add(URLDecoder.decode(ret));
    +        }
    +        return stormIds;
    +    }
    +
    +    public static Collection<String> supervisorWorkerIds(Map conf) {
    +        String workerRoot = ConfigUtils.workerRoot(conf);
    +        return Utils.readDirContents(workerRoot);
    +    }
    +
    +    public static boolean doRequiredTopoFilesExist(Map conf, String stormId) throws IOException {
    +        String stormroot = ConfigUtils.supervisorStormDistRoot(conf, stormId);
    +        String stormjarpath = ConfigUtils.supervisorStormJarPath(stormroot);
    +        String stormcodepath = ConfigUtils.supervisorStormCodePath(stormroot);
    +        String stormconfpath = ConfigUtils.supervisorStormConfPath(stormroot);
    +        if (!Utils.checkFileExists(stormroot))
    +            return false;
    +        if (!Utils.checkFileExists(stormcodepath))
    +            return false;
    +        if (!Utils.checkFileExists(stormconfpath))
    +            return false;
    +        if (ConfigUtils.isLocalMode(conf) || Utils.checkFileExists(stormjarpath))
    +            return true;
    +        return false;
    +    }
    +
    +    /**
    +     * Returns map from worr id to heartbeat
    +     *
    +     * @param conf
    +     * @return
    +     * @throws Exception
    +     */
    +    public static Map<String, LSWorkerHeartbeat> readWorkerHeartbeats(Map conf) throws Exception {
    +        return _instance.readWorkerHeartbeatsImpl(conf);
    +    }
    +
    +    public  Map<String, LSWorkerHeartbeat> readWorkerHeartbeatsImpl(Map conf) throws Exception {
    +        Map<String, LSWorkerHeartbeat> workerHeartbeats = new HashMap<>();
    +
    +        Collection<String> workerIds = SupervisorUtils.supervisorWorkerIds(conf);
    +
    +        for (String workerId : workerIds) {
    +            LSWorkerHeartbeat whb = readWorkerHeartbeat(conf, workerId);
    +            // ATTENTION: whb can be null
    +            workerHeartbeats.put(workerId, whb);
    +        }
    +        return workerHeartbeats;
    +    }
    +
    +
    +    /**
    +     * get worker heartbeat by workerId
    +     *
    +     * @param conf
    +     * @param workerId
    +     * @return
    +     * @throws IOException
    +     */
    +    public static LSWorkerHeartbeat readWorkerHeartbeat(Map conf, String workerId) {
    +        return _instance.readWorkerHeartbeatImpl(conf, workerId);
    +    }
    +
    +    public  LSWorkerHeartbeat readWorkerHeartbeatImpl(Map conf, String workerId) {
    +        try {
    +            LocalState localState = ConfigUtils.workerState(conf, workerId);
    +            return localState.getWorkerHeartBeat();
    +        } catch (Exception e) {
    +            LOG.warn("Failed to read local heartbeat for workerId : {},Ignoring exception.", workerId, e);
    +            return null;
    +        }
    +    }
    +
    +    public static boolean  isWorkerHbTimedOut(int now, LSWorkerHeartbeat whb, Map conf) {
    +        return _instance.isWorkerHbTimedOutImpl(now, whb, conf);
    +    }
    +
    +    public  boolean  isWorkerHbTimedOutImpl(int now, LSWorkerHeartbeat whb, Map conf) {
    +        boolean result = false;
    +        if ((now - whb.get_time_secs()) > Utils.getInt(conf.get(Config.SUPERVISOR_WORKER_TIMEOUT_SECS))) {
    +            result = true;
    +        }
    +        return result;
    +    }
    +
    +    public static String javaCmd(String cmd) {
    --- End diff --
    
    since cmd is always going to be "java", can the parameter be removed?


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55963987
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncProcessEvent.java ---
    @@ -0,0 +1,672 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.ExecutorInfo;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.WorkerResources;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +import org.yaml.snakeyaml.Yaml;
    +
    +import java.io.File;
    +import java.io.FileWriter;
    +import java.io.IOException;
    +import java.util.*;
    +
    +/**
    + * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file - rmr
    + * heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new worker
    + * ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait for workers
    + * launch
    + */
    +public class SyncProcessEvent implements Runnable {
    +
    +    private static Logger LOG = LoggerFactory.getLogger(SyncProcessEvent.class);
    +
    +    private  LocalState localState;
    +    private  SupervisorData supervisorData;
    +    public static final ExecutorInfo SYSTEM_EXECUTOR_INFO = new ExecutorInfo(-1, -1);
    +
    +    private class ProcessExitCallback implements Utils.ExitCodeCallable {
    +        private final String logPrefix;
    +        private final String workerId;
    +
    +        public ProcessExitCallback(String logPrefix, String workerId) {
    +            this.logPrefix = logPrefix;
    +            this.workerId = workerId;
    +        }
    +
    +        @Override
    +        public Object call() throws Exception {
    +            return null;
    +        }
    +
    +        @Override
    +        public Object call(int exitCode) {
    +            LOG.info("{} exited with code: {}", logPrefix, exitCode);
    +            supervisorData.getDeadWorkers().add(workerId);
    +            return null;
    +        }
    +    }
    +
    +    public SyncProcessEvent(){
    +
    +    }
    +    public SyncProcessEvent(SupervisorData supervisorData) {
    +        init(supervisorData);
    +    }
    +
    +    //TODO: initData is intended to local supervisor, so we will remove them after porting worker.clj to java
    +    public void init(SupervisorData supervisorData){
    +        this.supervisorData = supervisorData;
    +        this.localState = supervisorData.getLocalState();
    +    }
    +
    +
    +    /**
    +     * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file -
    +     * rmr heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new
    +     * worker ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait
    +     * for workers launch
    +     */
    +    @Override
    +    public void run() {
    +        LOG.debug("Syncing processes");
    +        try {
    +            Map conf = supervisorData.getConf();
    +            Map<Integer, LocalAssignment> assignedExecutors = localState.getLocalAssignmentsMap();
    +
    +            if (assignedExecutors == null) {
    +                assignedExecutors = new HashMap<>();
    +            }
    +            int now = Time.currentTimeSecs();
    +
    +            Map<String, StateHeartbeat> localWorkerStats = getLocalWorkerStats(supervisorData, assignedExecutors, now);
    +
    +            Set<String> keeperWorkerIds = new HashSet<>();
    +            Set<Integer> keepPorts = new HashSet<>();
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() == State.VALID) {
    +                    keeperWorkerIds.add(entry.getKey());
    +                    keepPorts.add(stateHeartbeat.getHeartbeat().get_port());
    +                }
    +            }
    +            Map<Integer, LocalAssignment> reassignExecutors = getReassignExecutors(assignedExecutors, keepPorts);
    +            Map<Integer, String> newWorkerIds = new HashMap<>();
    +            for (Integer port : reassignExecutors.keySet()) {
    +                newWorkerIds.put(port, Utils.uuid());
    +            }
    +            LOG.debug("Syncing processes");
    +            LOG.debug("Assigned executors: {}", assignedExecutors);
    +            LOG.debug("Allocated: {}", localWorkerStats);
    +
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() != State.VALID) {
    +                    LOG.info("Shutting down and clearing state for id {}, Current supervisor time: {}, State: {}, Heartbeat: {}", entry.getKey(), now,
    +                            stateHeartbeat.getState(), stateHeartbeat.getHeartbeat());
    +                    shutWorker(supervisorData, entry.getKey());
    +                }
    +            }
    +            // start new workers
    +            Map<String, Integer> newWorkerPortToIds = startNewWorkers(newWorkerIds, reassignExecutors);
    +
    +            Map<String, Integer> allWorkerPortToIds = new HashMap<>();
    +            Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +            for (String keeper : keeperWorkerIds) {
    +                allWorkerPortToIds.put(keeper, approvedWorkers.get(keeper));
    +            }
    +            allWorkerPortToIds.putAll(newWorkerPortToIds);
    +            localState.setApprovedWorkers(allWorkerPortToIds);
    +            waitForWorkersLaunch(conf, newWorkerPortToIds.keySet());
    +
    +        } catch (Exception e) {
    +            LOG.error("Failed Sync Process", e);
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +    }
    +
    +    protected void waitForWorkersLaunch(Map conf, Set<String> workerIds) throws Exception {
    +        int startTime = Time.currentTimeSecs();
    +        int timeOut = (int) conf.get(Config.NIMBUS_SUPERVISOR_TIMEOUT_SECS);
    +        for (String workerId : workerIds) {
    +            LocalState localState = ConfigUtils.workerState(conf, workerId);
    +            while (true) {
    +                LSWorkerHeartbeat hb = localState.getWorkerHeartBeat();
    +                if (hb != null || (Time.currentTimeSecs() - startTime) > timeOut)
    +                    break;
    +                LOG.info("{} still hasn't started", workerId);
    +                Time.sleep(500);
    +            }
    +            if (localState.getWorkerHeartBeat() == null) {
    +                LOG.info("Worker {} failed to start", workerId);
    +            }
    +        }
    +    }
    +
    +    protected Map<Integer, LocalAssignment> getReassignExecutors(Map<Integer, LocalAssignment> assignExecutors, Set<Integer> keepPorts) {
    +        Map<Integer, LocalAssignment> reassignExecutors = new HashMap<>();
    +        reassignExecutors.putAll(assignExecutors);
    +        for (Integer port : keepPorts) {
    +            reassignExecutors.remove(port);
    +        }
    +        return reassignExecutors;
    +    }
    +    
    +    /**
    +     * Returns map from worker id to worker heartbeat. if the heartbeat is nil, then the worker is dead
    +     * 
    +     * @param assignedExecutors
    +     * @return
    +     * @throws Exception
    +     */
    +    public Map<String, StateHeartbeat> getLocalWorkerStats(SupervisorData supervisorData, Map<Integer, LocalAssignment> assignedExecutors, int now) throws Exception {
    +        Map<String, StateHeartbeat> workerIdHbstate = new HashMap<>();
    +        Map conf = supervisorData.getConf();
    +        LocalState localState = supervisorData.getLocalState();
    +        Map<String, LSWorkerHeartbeat> idToHeartbeat = SupervisorUtils.readWorkerHeartbeats(conf);
    +        Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +        Set<String> approvedIds = new HashSet<>();
    +        if (approvedWorkers != null) {
    +            approvedIds.addAll(approvedWorkers.keySet());
    +        }
    +        for (Map.Entry<String, LSWorkerHeartbeat> entry : idToHeartbeat.entrySet()) {
    +            String workerId = entry.getKey();
    +            LSWorkerHeartbeat whb = entry.getValue();
    +            State state;
    +            if (whb == null) {
    +                state = State.NOT_STARTED;
    +            } else if (!approvedIds.contains(workerId) || !matchesAssignment(whb, assignedExecutors)) {
    +                state = State.DISALLOWED;
    +            } else if (supervisorData.getDeadWorkers().contains(workerId)) {
    +                LOG.info("Worker Process {} has died", workerId);
    +                state = State.TIMED_OUT;
    +            } else if (SupervisorUtils.isWorkerHbTimedOut(now, whb, conf)) {
    +                state = State.TIMED_OUT;
    +            } else {
    +                state = State.VALID;
    +            }
    +            LOG.debug("Worker:{} state:{} WorkerHeartbeat:{} at supervisor time-secs {}", workerId, state, whb, now);
    +            workerIdHbstate.put(workerId, new StateHeartbeat(state, whb));
    +        }
    +        return workerIdHbstate;
    +    }
    +
    +    protected boolean matchesAssignment(LSWorkerHeartbeat whb, Map<Integer, LocalAssignment> assignedExecutors) {
    +        LocalAssignment localAssignment = assignedExecutors.get(whb.get_port());
    +        if (localAssignment == null || !localAssignment.get_topology_id().equals(whb.get_topology_id())) {
    +            return false;
    +        }
    +        List<ExecutorInfo> executorInfos = new ArrayList<>();
    +        executorInfos.addAll(whb.get_executors());
    +        // remove SYSTEM_EXECUTOR_ID
    +        executorInfos.remove(SYSTEM_EXECUTOR_INFO);
    +        List<ExecutorInfo> localExecuorInfos = localAssignment.get_executors();
    +
    +        if (localExecuorInfos.size() != executorInfos.size())
    +            return false;
    +
    +        for (ExecutorInfo executorInfo : localExecuorInfos){
    +            if (!localExecuorInfos.contains(executorInfo))
    +                return false;
    +        }
    +        return true;
    +    }
    +
    +    /**
    +     * launch a worker in local mode.
    +     */
    +    protected void launchWorker(SupervisorData supervisorData, String stormId, Long port, String workerId, WorkerResources resources) throws IOException {
    +        // port this function after porting worker to java
    +    }
    +
    +    protected String getWorkerClassPath(String stormJar, Map stormConf) {
    +        List<String> topoClasspath = new ArrayList<>();
    +        Object object = stormConf.get(Config.TOPOLOGY_CLASSPATH);
    +
    +        if (object instanceof List) {
    +            topoClasspath.addAll((List<String>) object);
    +        } else if (object instanceof String){
    +            topoClasspath.add((String)object);
    +        }else {
    +            //ignore
    +        }
    +        String classPath = Utils.workerClasspath();
    +        String classAddPath = Utils.addToClasspath(classPath, Arrays.asList(stormJar));
    +        return Utils.addToClasspath(classAddPath, topoClasspath);
    +    }
    +
    +    /**
    +     * "Generates runtime childopts by replacing keys with topology-id, worker-id, port, mem-onheap"
    +     * 
    +     * @param value
    +     * @param workerId
    +     * @param stormId
    +     * @param port
    +     * @param memOnheap
    +     */
    +    public List<String> substituteChildopts(Object value, String workerId, String stormId, Long port, int memOnheap) {
    +        List<String> rets = new ArrayList<>();
    +        if (value instanceof String) {
    +            String string = (String) value;
    +            string = string.replace("%ID%", String.valueOf(port));
    +            string = string.replace("%WORKER-ID%", workerId);
    +            string = string.replace("%TOPOLOGY-ID%", stormId);
    +            string = string.replace("%WORKER-PORT%", String.valueOf(port));
    +            string = string.replace("%HEAP-MEM%", String.valueOf(memOnheap));
    +            String[] strings = string.split("\\s+");
    +            rets.addAll(Arrays.asList(strings));
    +        } else if (value instanceof List) {
    +            List<Object> objects = (List<Object>) value;
    +            for (Object object : objects) {
    +                String str = (String)object;
    +                str = str.replace("%ID%", String.valueOf(port));
    +                str = str.replace("%WORKER-ID%", workerId);
    +                str = str.replace("%TOPOLOGY-ID%", stormId);
    +                str = str.replace("%WORKER-PORT%", String.valueOf(port));
    +                str = str.replace("%HEAP-MEM%", String.valueOf(memOnheap));
    +                rets.add(str);
    +            }
    +        }
    +        return rets;
    +    }
    +
    +
    +
    +    /**
    +     * launch a worker in distributed mode
    +     * supervisorId for testing
    +     * @throws IOException
    +     */
    +    protected void launchWorker(Map conf, String supervisorId, String assignmentId, String stormId, Long port, String workerId,
    +            WorkerResources resources, CgroupManager cgroupManager, ConcurrentHashSet deadWorkers) throws IOException {
    +
    +        Boolean runWorkerAsUser = Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false);
    +        String stormHome = ConfigUtils.concatIfNotNull(System.getProperty("storm.home"));
    +        String stormOptions = ConfigUtils.concatIfNotNull(System.getProperty("storm.options"));
    +        String stormConfFile = ConfigUtils.concatIfNotNull(System.getProperty("storm.conf.file"));
    +        String workerTmpDir = ConfigUtils.workerTmpRoot(conf, workerId);
    +
    +        String stormLogDir = ConfigUtils.getLogDir();
    +        String stormLogConfDir = (String) (conf.get(Config.STORM_LOG4J2_CONF_DIR));
    +
    +        String stormLog4j2ConfDir;
    +        if (StringUtils.isNotBlank(stormLogConfDir)) {
    +            if (Utils.isAbsolutePath(stormLogConfDir)) {
    +                stormLog4j2ConfDir = stormLogConfDir;
    +            } else {
    +                stormLog4j2ConfDir = stormHome + Utils.FILE_PATH_SEPARATOR + stormLogConfDir;
    +            }
    +        } else {
    +            stormLog4j2ConfDir = stormHome + Utils.FILE_PATH_SEPARATOR + "log4j2";
    +        }
    +
    +        String stormRoot = ConfigUtils.supervisorStormDistRoot(conf, stormId);
    +
    +        String jlp = jlp(stormRoot, conf);
    +
    +        String stormJar = ConfigUtils.supervisorStormJarPath(stormRoot);
    +
    +        Map stormConf = ConfigUtils.readSupervisorStormConf(conf, stormId);
    +
    +        String workerClassPath = getWorkerClassPath(stormJar, stormConf);
    +
    +        Object topGcOptsObject = stormConf.get(Config.TOPOLOGY_WORKER_GC_CHILDOPTS);
    +        List<String> topGcOpts = new ArrayList<>();
    +        if (topGcOptsObject instanceof String) {
    +            topGcOpts.add((String) topGcOptsObject);
    +        } else if (topGcOptsObject instanceof List) {
    +            topGcOpts.addAll((List<String>) topGcOptsObject);
    +        }
    +
    +        int memOnheap = 0;
    +        if (resources.get_mem_on_heap() > 0) {
    +            memOnheap = (int) Math.ceil(resources.get_mem_on_heap());
    +        } else {
    +            //set the default heap memory size for supervisor-test
    +            memOnheap = Utils.getInt(stormConf.get(Config.WORKER_HEAP_MEMORY_MB), 768);
    +        }
    +
    +        int memoffheap = (int) Math.ceil(resources.get_mem_off_heap());
    +
    +        int cpu = (int) Math.ceil(resources.get_cpu());
    +
    +        List<String> gcOpts = null;
    +
    +        if (topGcOpts != null) {
    +            gcOpts = substituteChildopts(topGcOpts, workerId, stormId, port, memOnheap);
    +        } else {
    +            gcOpts = substituteChildopts(conf.get(Config.WORKER_GC_CHILDOPTS), workerId, stormId, port, memOnheap);
    +        }
    +
    +        Object topoWorkerLogwriterObject = stormConf.get(Config.TOPOLOGY_WORKER_LOGWRITER_CHILDOPTS);
    +        List<String> topoWorkerLogwriterChildopts = new ArrayList<>();
    +        if (topoWorkerLogwriterObject instanceof String) {
    +            topoWorkerLogwriterChildopts.add((String) topoWorkerLogwriterObject);
    +        } else if (topoWorkerLogwriterObject instanceof List) {
    +            topoWorkerLogwriterChildopts.addAll((List<String>) topoWorkerLogwriterObject);
    +        }
    +
    +        String user = (String) stormConf.get(Config.TOPOLOGY_SUBMITTER_USER);
    +
    +        String logfileName = "worker.log";
    +
    +        String workersArtifacets = ConfigUtils.workerArtifactsRoot(conf);
    +
    +        String loggingSensitivity = (String) stormConf.get(Config.TOPOLOGY_LOGGING_SENSITIVITY);
    +        if (loggingSensitivity == null) {
    +            loggingSensitivity = "S3";
    +        }
    +
    +        List<String> workerChildopts = substituteChildopts(conf.get(Config.WORKER_CHILDOPTS), workerId, stormId, port, memOnheap);
    +
    +        List<String> topWorkerChildopts = substituteChildopts(stormConf.get(Config.TOPOLOGY_WORKER_CHILDOPTS), workerId, stormId, port, memOnheap);
    +
    +        List<String> workerProfilerChildopts = null;
    +        if (Utils.getBoolean(conf.get(Config.WORKER_PROFILER_ENABLED), false)) {
    +            workerProfilerChildopts = substituteChildopts(conf.get(Config.WORKER_PROFILER_CHILDOPTS), workerId, stormId, port, memOnheap);
    +        }else {
    +            workerProfilerChildopts = new ArrayList<>();
    +        }
    +
    +        Map<String, String> topEnvironment = new HashMap<String, String>();
    +        Map<String, String> environment = (Map<String, String>) stormConf.get(Config.TOPOLOGY_ENVIRONMENT);
    +        if (environment != null) {
    +            topEnvironment.putAll(environment);
    +        }
    +        topEnvironment.put("LD_LIBRARY_PATH", jlp);
    +
    +        String log4jConfigurationFile = null;
    +        if (System.getProperty("os.name").startsWith("Windows") && !stormLog4j2ConfDir.startsWith("file:")) {
    +            log4jConfigurationFile = "file:///" + stormLog4j2ConfDir;
    +        } else {
    +            log4jConfigurationFile = stormLog4j2ConfDir;
    +        }
    +        log4jConfigurationFile = log4jConfigurationFile + Utils.FILE_PATH_SEPARATOR + "worker.xml";
    +
    +        List<String> commandList = new ArrayList<>();
    +        commandList.add(SupervisorUtils.javaCmd("java"));
    +        commandList.add("-cp");
    +        commandList.add(workerClassPath);
    +        commandList.addAll(topoWorkerLogwriterChildopts);
    +        commandList.add("-Dlogfile.name=" + logfileName);
    +        commandList.add("-Dstorm.home=" + stormHome);
    +        commandList.add("-Dworkers.artifacts=" + workersArtifacets);
    +        commandList.add("-Dstorm.id=" + stormId);
    +        commandList.add("-Dworker.id=" + workerId);
    +        commandList.add("-Dworker.port=" + port);
    +        commandList.add("-Dstorm.log.dir=" + stormLogDir);
    +        commandList.add("-Dlog4j.configurationFile=" + log4jConfigurationFile);
    +        commandList.add("-DLog4jContextSelector=org.apache.logging.log4j.core.selector.BasicContextSelector");
    +        commandList.add("org.apache.storm.LogWriter");
    +
    +        commandList.add(SupervisorUtils.javaCmd("java"));
    +        commandList.add("-server");
    +        commandList.addAll(workerChildopts);
    +        commandList.addAll(topWorkerChildopts);
    +        commandList.addAll(gcOpts);
    +        commandList.addAll(workerProfilerChildopts);
    +        commandList.add("-Djava.library.path=" + jlp);
    +        commandList.add("-Dlogfile.name=" + logfileName);
    +        commandList.add("-Dstorm.home=" + stormHome);
    +        commandList.add("-Dworkers.artifacts=" + workersArtifacets);
    +        commandList.add("-Dstorm.conf.file=" + stormConfFile);
    +        commandList.add("-Dstorm.options=" + stormOptions);
    +        commandList.add("-Dstorm.log.dir=" + stormLogDir);
    +        commandList.add("-Djava.io.tmpdir=" + workerTmpDir);
    +        commandList.add("-Dlogging.sensitivity=" + loggingSensitivity);
    +        commandList.add("-Dlog4j.configurationFile=" + log4jConfigurationFile);
    +        commandList.add("-DLog4jContextSelector=org.apache.logging.log4j.core.selector.BasicContextSelector");
    +        commandList.add("-Dstorm.id=" + stormId);
    +        commandList.add("-Dworker.id=" + workerId);
    +        commandList.add("-Dworker.port=" + port);
    +        commandList.add("-cp");
    +        commandList.add(workerClassPath);
    +        commandList.add("org.apache.storm.daemon.worker");
    +        commandList.add(stormId);
    +        commandList.add(assignmentId);
    +        commandList.add(String.valueOf(port));
    +        commandList.add(workerId);
    +
    +        // {"cpu" cpu "memory" (+ mem-onheap mem-offheap (int (Math/ceil (conf STORM-CGROUP-MEMORY-LIMIT-TOLERANCE-MARGIN-MB))))
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            int cgRoupMem = (int) (Math.ceil((double) conf.get(Config.STORM_CGROUP_MEMORY_LIMIT_TOLERANCE_MARGIN_MB)));
    +            int memoryValue = memoffheap + memOnheap + cgRoupMem;
    +            int cpuValue = cpu;
    +            Map<String, Number> map = new HashMap<>();
    +            map.put("cpu", cpuValue);
    +            map.put("memory", memoryValue);
    +            cgroupManager.reserveResourcesForWorker(workerId, map);
    +            commandList = cgroupManager.getLaunchCommand(workerId, commandList);
    +        }
    +
    +        LOG.info("Launching worker with command: {}. ", Utils.shellCmd(commandList));
    +        writeLogMetadata(stormConf, user, workerId, stormId, port, conf);
    +        ConfigUtils.setWorkerUserWSE(conf, workerId, user);
    +        createArtifactsLink(conf, stormId, port, workerId);
    +
    +        String logPrefix = "Worker Process " + workerId;
    +        String workerDir = ConfigUtils.workerRoot(conf, workerId);
    +
    +        if (deadWorkers != null)
    +            deadWorkers.remove(workerId);
    +        createBlobstoreLinks(conf, stormId, workerId);
    +
    +        ProcessExitCallback processExitCallback = new ProcessExitCallback(logPrefix, workerId);
    +        if (runWorkerAsUser) {
    +            List<String> args = new ArrayList<>();
    +            args.add("worker");
    +            args.add(workerDir);
    +            args.add(Utils.writeScript(workerDir, commandList, topEnvironment));
    +            SupervisorUtils.workerLauncher(conf, user, args, null, logPrefix, processExitCallback, new File(workerDir));
    +        } else {
    +            Utils.launchProcess(commandList, topEnvironment, logPrefix, processExitCallback, new File(workerDir));
    +        }
    +    }
    +
    +    protected String jlp(String stormRoot, Map conf) {
    +        String resourceRoot = stormRoot + Utils.FILE_PATH_SEPARATOR + ConfigUtils.RESOURCES_SUBDIR;
    +        String os = System.getProperty("os.name").replaceAll("\\s+", "_");
    +        String arch = System.getProperty("os.arch");
    +        String archResourceRoot = resourceRoot + Utils.FILE_PATH_SEPARATOR + os + "-" + arch;
    +        String ret = archResourceRoot + Utils.FILE_PATH_SEPARATOR + resourceRoot + Utils.FILE_PATH_SEPARATOR + conf.get(Config.JAVA_LIBRARY_PATH);
    +        return ret;
    +    }
    +
    +    protected Map<String, Integer> startNewWorkers(Map<Integer, String> newWorkerIds, Map<Integer, LocalAssignment> reassignExecutors) throws IOException {
    +
    +        Map<String, Integer> newValidWorkerIds = new HashMap<>();
    +        Map conf = supervisorData.getConf();
    +        String supervisorId = supervisorData.getSupervisorId();
    +        String clusterMode = ConfigUtils.clusterMode(conf);
    +
    +        for (Map.Entry<Integer, LocalAssignment> entry : reassignExecutors.entrySet()) {
    +            Integer port = entry.getKey();
    +            LocalAssignment assignment = entry.getValue();
    +            String workerId = newWorkerIds.get(port);
    +            String stormId = assignment.get_topology_id();
    +            WorkerResources resources = assignment.get_resources();
    +
    +            // This condition checks for required files exist before launching the worker
    +            if (SupervisorUtils.doRequiredTopoFilesExist(conf, stormId)) {
    +                String pidsPath = ConfigUtils.workerPidsRoot(conf, workerId);
    +                String hbPath = ConfigUtils.workerHeartbeatsRoot(conf, workerId);
    +
    +                LOG.info("Launching worker with assignment {} for this supervisor {} on port {} with id {}", assignment, supervisorData.getSupervisorId(), port,
    +                        workerId);
    +
    +                FileUtils.forceMkdir(new File(pidsPath));
    +                FileUtils.forceMkdir(new File(ConfigUtils.workerTmpRoot(conf, workerId)));
    +                FileUtils.forceMkdir(new File(hbPath));
    +
    +                if (clusterMode.endsWith("distributed")) {
    +                    launchWorker(conf, supervisorId, supervisorData.getAssignmentId(), stormId, port.longValue(), workerId, resources,
    +                            supervisorData.getResourceIsolationManager(), supervisorData.getDeadWorkers());
    +                } else if (clusterMode.endsWith("local")) {
    +                    launchWorker(supervisorData, stormId, port.longValue(), workerId, resources);
    +                }
    +                newValidWorkerIds.put(workerId, port);
    +
    +            } else {
    +                LOG.info("Missing topology storm code, so can't launch worker with assignment {} for this supervisor {} on port {} with id {}", assignment,
    +                        supervisorData.getSupervisorId(), port, workerId);
    +            }
    +
    +        }
    +        return newValidWorkerIds;
    +    }
    +
    +    public void writeLogMetadata(Map stormconf, String user, String workerId, String stormId, Long port, Map conf) throws IOException {
    +        Map data = new HashMap();
    +        data.put(Config.TOPOLOGY_SUBMITTER_USER, user);
    +        data.put("worker-id", workerId);
    +
    +        Set<String> logsGroups = new HashSet<>();
    +        //for supervisor-test
    +        if (stormconf.get(Config.LOGS_GROUPS) != null) {
    +            List<String> groups = (List<String>) stormconf.get(Config.LOGS_GROUPS);
    +            for (String group : groups){
    +                logsGroups.add(group);
    +            }
    +        }
    +        if (stormconf.get(Config.TOPOLOGY_GROUPS) != null) {
    +            List<String> topGroups = (List<String>) stormconf.get(Config.TOPOLOGY_GROUPS);
    +            for (String group : topGroups){
    --- End diff --
    
    you can use logsGroups.addAll 


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55585655
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorData.java ---
    @@ -0,0 +1,339 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.cluster.ClusterStateContext;
    +import org.apache.storm.cluster.ClusterUtils;
    +import org.apache.storm.cluster.DaemonType;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.ProfileRequest;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +import java.net.UnknownHostException;
    +import java.util.ArrayList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.concurrent.ConcurrentHashMap;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SupervisorData {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorData.class);
    +
    +    private Map conf;
    +    private IContext sharedContext;
    +    private volatile boolean active;
    +    private ISupervisor iSupervisor;
    +    private Utils.UptimeComputer upTime;
    +    private String stormVersion;
    +
    +    private ConcurrentHashMap<String, String> workerThreadPidsAtom; // for local mode
    +
    +    private IStormClusterState stormClusterState;
    +
    +    private LocalState localState;
    +
    +    private String supervisorId;
    +
    +    private String assignmentId;
    +
    +    private String hostName;
    +
    +    // used for reporting used ports when heartbeating
    +    private ConcurrentHashMap<Long, LocalAssignment> currAssignment;
    +
    +    private StormTimer heartbeatTimer;
    +
    +    private StormTimer eventTimer;
    +
    +    private StormTimer blobUpdateTimer;
    +
    +    private Localizer localizer;
    +
    +    private ConcurrentHashMap<String, Map<String, Object>> assignmentVersions;
    +
    +    private AtomicInteger syncRetry;
    +
    +    private final Object downloadLock = new Object();
    +
    +    private ConcurrentHashMap<String, List<ProfileRequest>> stormIdToProfileActions;
    +
    +    private CgroupManager resourceIsolationManager;
    +
    +    private ConcurrentHashSet<String> deadWorkers;
    +
    +    public SupervisorData(Map conf, IContext sharedContext, ISupervisor iSupervisor) {
    +        this.conf = conf;
    +        this.sharedContext = sharedContext;
    +        this.iSupervisor = iSupervisor;
    +        this.active = true;
    +        this.upTime = Utils.makeUptimeComputer();
    +        this.stormVersion = VersionInfo.getVersion();
    +        this.workerThreadPidsAtom = new ConcurrentHashMap<String, String>();
    +        this.deadWorkers = new ConcurrentHashSet();
    +
    +        List<ACL> acls = null;
    +        if (Utils.isZkAuthenticationConfiguredStormServer(conf)) {
    +            acls = SupervisorUtils.supervisorZkAcls();
    +        }
    +
    +        try {
    +            this.stormClusterState = ClusterUtils.mkStormClusterState(conf, acls, new ClusterStateContext(DaemonType.SUPERVISOR));
    +        } catch (Exception e) {
    +            LOG.error("supervisor can't create stormClusterState");
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        try {
    +            this.localState = ConfigUtils.supervisorState(conf);
    +            this.localizer = Utils.createLocalizer(conf, ConfigUtils.supervisorLocalDir(conf));
    +        } catch (IOException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +        this.supervisorId = iSupervisor.getSupervisorId();
    +        this.assignmentId = iSupervisor.getAssignmentId();
    +
    +        try {
    +            this.hostName = Utils.hostname(conf);
    +        } catch (UnknownHostException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        this.currAssignment = new ConcurrentHashMap<>();
    +
    +        this.heartbeatTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.eventTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.blobUpdateTimer = new StormTimer("blob-update-timer", new DefaultUncaughtExceptionHandler());
    +
    +        this.assignmentVersions = new ConcurrentHashMap<>();
    +        this.syncRetry = new AtomicInteger(0);
    +        this.stormIdToProfileActions = new ConcurrentHashMap<>();
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            try {
    +                this.resourceIsolationManager = (CgroupManager) Utils.newInstance((String) conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN));
    +                this.resourceIsolationManager.prepare(conf);
    +                LOG.info("Using resource isolation plugin {} {}", conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN), resourceIsolationManager);
    +            } catch (IOException e) {
    +                throw Utils.wrapInRuntime(e);
    +            }
    +        } else {
    +            this.resourceIsolationManager = null;
    +        }
    +    }
    +
    +    public ConcurrentHashMap<String, List<ProfileRequest>> getStormIdToProfileActions() {
    +        return stormIdToProfileActions;
    +    }
    +
    +    public void setStormIdToProfileActions(Map<String, List<ProfileRequest>> stormIdToProfileActions) {
    +        this.stormIdToProfileActions.clear();
    +        this.stormIdToProfileActions.putAll(stormIdToProfileActions);
    +    }
    +
    +    public Map getConf() {
    +        return conf;
    +    }
    +
    +    public void setConf(Map conf) {
    +        this.conf = conf;
    +    }
    +
    +    public IContext getSharedContext() {
    +        return sharedContext;
    +    }
    +
    +    public void setSharedContext(IContext sharedContext) {
    +        this.sharedContext = sharedContext;
    +    }
    +
    +    public boolean isActive() {
    +        return active;
    +    }
    +
    +    public void setActive(boolean active) {
    +        this.active = active;
    +    }
    +
    +    public ISupervisor getiSupervisor() {
    +        return iSupervisor;
    +    }
    +
    +    public void setiSupervisor(ISupervisor iSupervisor) {
    +        this.iSupervisor = iSupervisor;
    +    }
    +
    +    public Utils.UptimeComputer getUpTime() {
    +        return upTime;
    +    }
    +
    +    public void setUpTime(Utils.UptimeComputer upTime) {
    +        this.upTime = upTime;
    +    }
    +
    +    public String getStormVersion() {
    +        return stormVersion;
    +    }
    +
    +    public void setStormVersion(String stormVersion) {
    +        this.stormVersion = stormVersion;
    +    }
    +
    +    public ConcurrentHashMap<String, String> getWorkerThreadPidsAtom() {
    +        return workerThreadPidsAtom;
    +    }
    +
    +    public void setWorkerThreadPidsAtom(ConcurrentHashMap<String, String> workerThreadPidsAtom) {
    +        this.workerThreadPidsAtom = workerThreadPidsAtom;
    +    }
    +
    +    public IStormClusterState getStormClusterState() {
    +        return stormClusterState;
    +    }
    +
    +    public void setStormClusterState(IStormClusterState stormClusterState) {
    +        this.stormClusterState = stormClusterState;
    +    }
    +
    +    public LocalState getLocalState() {
    +        return localState;
    +    }
    +
    +    public void setLocalState(LocalState localState) {
    +        this.localState = localState;
    +    }
    +
    +    public String getSupervisorId() {
    +        return supervisorId;
    +    }
    +
    +    public void setSupervisorId(String supervisorId) {
    +        this.supervisorId = supervisorId;
    +    }
    +
    +    public String getAssignmentId() {
    +        return assignmentId;
    +    }
    +
    +    public void setAssignmentId(String assignmentId) {
    +        this.assignmentId = assignmentId;
    +    }
    +
    +    public String getHostName() {
    +        return hostName;
    +    }
    +
    +    public void setHostName(String hostName) {
    +        this.hostName = hostName;
    +    }
    +
    +    public ConcurrentHashMap<Long, LocalAssignment> getCurrAssignment() {
    +        return currAssignment;
    +    }
    +
    +    public void setCurrAssignment(Map<Long, LocalAssignment> currAssignment) {
    +        this.currAssignment.clear();
    +        this.currAssignment.putAll(currAssignment);
    +    }
    +
    +    public StormTimer getHeartbeatTimer() {
    +        return heartbeatTimer;
    +    }
    +
    +    public void setHeartbeatTimer(StormTimer heartbeatTimer) {
    +        this.heartbeatTimer = heartbeatTimer;
    +    }
    +
    +    public StormTimer getEventTimer() {
    +        return eventTimer;
    +    }
    +
    +    public void setEventTimer(StormTimer eventTimer) {
    +        this.eventTimer = eventTimer;
    +    }
    +
    +    public StormTimer getBlobUpdateTimer() {
    +        return blobUpdateTimer;
    +    }
    +
    +    public void setBlobUpdateTimer(StormTimer blobUpdateTimer) {
    +        this.blobUpdateTimer = blobUpdateTimer;
    +    }
    +
    +    public Localizer getLocalizer() {
    +        return localizer;
    +    }
    +
    +    public void setLocalizer(Localizer localizer) {
    +        this.localizer = localizer;
    +    }
    +
    +    public AtomicInteger getSyncRetry() {
    +        return syncRetry;
    +    }
    +
    +    public void setSyncRetry(AtomicInteger syncRetry) {
    +        this.syncRetry = syncRetry;
    +    }
    +
    +    public ConcurrentHashMap<String, Map<String, Object>> getAssignmentVersions() {
    +        return assignmentVersions;
    +    }
    +
    +    public void setAssignmentVersions(Map<String, Map<String, Object>> assignmentVersions) {
    +        this.assignmentVersions.clear();
    +        this.assignmentVersions.putAll(assignmentVersions);
    --- End diff --
    
    Here too this operation should be atomic and I would rather see assignmentVersions be an `AtomicReference<Map<String, Map<String, Object>>>`


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#issuecomment-193287754
  
    WorkerManager - shutting down worker, launching worker, cleanup worker, reading worker heartbeat (basically the pieces of code which deals with individual worker) can go here. 
    Code which calls the WorkerManager for each worker e.g. shutdownAllWorkers can go to SupervisorManager as you have 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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55712301
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncProcessEvent.java ---
    @@ -0,0 +1,669 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.ExecutorInfo;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.WorkerResources;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +import org.yaml.snakeyaml.Yaml;
    +
    +import java.io.File;
    +import java.io.FileWriter;
    +import java.io.IOException;
    +import java.util.*;
    +
    +/**
    + * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file - rmr
    + * heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new worker
    + * ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait for workers
    + * launch
    + */
    +public class SyncProcessEvent extends ShutdownWork implements Runnable {
    +
    +    private static Logger LOG = LoggerFactory.getLogger(SyncProcessEvent.class);
    +
    +    private  LocalState localState;
    +
    +    private SupervisorData supervisorData;
    +
    +    private class ProcessExitCallback implements Utils.ExitCodeCallable {
    +        private final String logPrefix;
    +        private final String workerId;
    +
    +        public ProcessExitCallback(String logPrefix, String workerId) {
    +            this.logPrefix = logPrefix;
    +            this.workerId = workerId;
    +        }
    +
    +        @Override
    +        public Object call() throws Exception {
    +            return null;
    +        }
    +
    +        @Override
    +        public Object call(int exitCode) {
    +            LOG.info("{} exited with code: {}", logPrefix, exitCode);
    +            supervisorData.getDeadWorkers().add(workerId);
    +            return null;
    +        }
    +    }
    +
    +    public SyncProcessEvent(){
    +
    +    }
    +    public SyncProcessEvent(SupervisorData supervisorData) {
    +        init(supervisorData);
    +    }
    +
    +    //TODO: initData is intended to local supervisor, so we will remove them after porting worker.clj to java
    +    public void init(SupervisorData supervisorData){
    +        this.supervisorData = supervisorData;
    +        this.localState = supervisorData.getLocalState();
    +    }
    +
    +
    +    /**
    +     * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file -
    +     * rmr heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new
    +     * worker ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait
    +     * for workers launch
    +     */
    +    @Override
    +    public void run() {
    +        LOG.debug("Syncing processes");
    +        try {
    +            Map conf = supervisorData.getConf();
    +            Map<Integer, LocalAssignment> assignedExecutors = localState.getLocalAssignmentsMap();
    +
    +            if (assignedExecutors == null) {
    +                assignedExecutors = new HashMap<>();
    +            }
    +            int now = Time.currentTimeSecs();
    +
    +            Map<String, StateHeartbeat> localWorkerStats = getLocalWorkerStats(supervisorData, assignedExecutors, now);
    +
    +            Set<String> keeperWorkerIds = new HashSet<>();
    +            Set<Integer> keepPorts = new HashSet<>();
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() == State.valid) {
    +                    keeperWorkerIds.add(entry.getKey());
    +                    keepPorts.add(stateHeartbeat.getHeartbeat().get_port());
    +                }
    +            }
    +            Map<Integer, LocalAssignment> reassignExecutors = getReassignExecutors(assignedExecutors, keepPorts);
    +            Map<Integer, String> newWorkerIds = new HashMap<>();
    +            for (Integer port : reassignExecutors.keySet()) {
    +                newWorkerIds.put(port, Utils.uuid());
    +            }
    +            LOG.debug("Syncing processes");
    +            LOG.debug("Assigned executors: {}", assignedExecutors);
    +            LOG.debug("Allocated: {}", localWorkerStats);
    +
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() != State.valid) {
    +                    LOG.info("Shutting down and clearing state for id {}, Current supervisor time: {}, State: {}, Heartbeat: {}", entry.getKey(), now,
    +                            stateHeartbeat.getState(), stateHeartbeat.getHeartbeat());
    +                    shutWorker(supervisorData, entry.getKey());
    +                }
    +            }
    +            // start new workers
    +            Map<String, Integer> newWorkerPortToIds = startNewWorkers(newWorkerIds, reassignExecutors);
    +
    +            Map<String, Integer> allWorkerPortToIds = new HashMap<>();
    +            Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +            for (String keeper : keeperWorkerIds) {
    +                allWorkerPortToIds.put(keeper, approvedWorkers.get(keeper));
    +            }
    +            allWorkerPortToIds.putAll(newWorkerPortToIds);
    +            localState.setApprovedWorkers(allWorkerPortToIds);
    +            waitForWorkersLaunch(conf, newWorkerPortToIds.keySet());
    +
    +        } catch (Exception e) {
    +            LOG.error("Failed Sync Process", e);
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +    }
    +
    +    protected void waitForWorkersLaunch(Map conf, Set<String> workerIds) throws Exception {
    +        int startTime = Time.currentTimeSecs();
    +        int timeOut = (int) conf.get(Config.NIMBUS_SUPERVISOR_TIMEOUT_SECS);
    +        for (String workerId : workerIds) {
    +            LocalState localState = ConfigUtils.workerState(conf, workerId);
    +            while (true) {
    +                LSWorkerHeartbeat hb = localState.getWorkerHeartBeat();
    +                if (hb != null || (Time.currentTimeSecs() - startTime) > timeOut)
    +                    break;
    +                LOG.info("{} still hasn't started", workerId);
    +                Time.sleep(500);
    +            }
    +            if (localState.getWorkerHeartBeat() == null) {
    +                LOG.info("Worker {} failed to start", workerId);
    +            }
    +        }
    +    }
    +
    +    protected Map<Integer, LocalAssignment> getReassignExecutors(Map<Integer, LocalAssignment> assignExecutors, Set<Integer> keepPorts) {
    +        Map<Integer, LocalAssignment> reassignExecutors = new HashMap<>();
    +        reassignExecutors.putAll(assignExecutors);
    +        for (Integer port : keepPorts) {
    +            reassignExecutors.remove(port);
    +        }
    +        return reassignExecutors;
    +    }
    +
    +
    +
    +    /**
    +     * Returns map from worker id to worker heartbeat. if the heartbeat is nil, then the worker is dead
    +     * 
    +     * @param assignedExecutors
    +     * @return
    +     * @throws Exception
    +     */
    +    public Map<String, StateHeartbeat> getLocalWorkerStats(SupervisorData supervisorData, Map<Integer, LocalAssignment> assignedExecutors, int now) throws Exception {
    +        Map<String, StateHeartbeat> workerIdHbstate = new HashMap<>();
    +        Map conf = supervisorData.getConf();
    +        LocalState localState = supervisorData.getLocalState();
    +        Map<String, LSWorkerHeartbeat> idToHeartbeat = SupervisorUtils.readWorkerHeartbeats(conf);
    +        Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +        Set<String> approvedIds = new HashSet<>();
    +        if (approvedWorkers != null) {
    +            approvedIds.addAll(approvedWorkers.keySet());
    +        }
    +        for (Map.Entry<String, LSWorkerHeartbeat> entry : idToHeartbeat.entrySet()) {
    +            String workerId = entry.getKey();
    +            LSWorkerHeartbeat whb = entry.getValue();
    +            State state;
    +            if (whb == null) {
    +                state = State.notStarted;
    +            } else if (!approvedIds.contains(workerId) || !matchesAssignment(whb, assignedExecutors)) {
    +                state = State.disallowed;
    +            } else if (supervisorData.getDeadWorkers().contains(workerId)) {
    +                LOG.info("Worker Process {}as died", workerId);
    +                state = State.timedOut;
    +            } else if (SupervisorUtils.isWorkerHbTimedOut(now, whb, conf)) {
    +                state = State.timedOut;
    +            } else {
    +                state = State.valid;
    +            }
    +            LOG.debug("Worker:{} state:{} WorkerHeartbeat:{} at supervisor time-secs {}", workerId, state, whb, now);
    +            workerIdHbstate.put(workerId, new StateHeartbeat(state, whb));
    +        }
    +        return workerIdHbstate;
    +    }
    +
    +    protected boolean matchesAssignment(LSWorkerHeartbeat whb, Map<Integer, LocalAssignment> assignedExecutors) {
    +        LocalAssignment localAssignment = assignedExecutors.get(whb.get_port());
    +        if (localAssignment == null || !localAssignment.get_topology_id().equals(whb.get_topology_id())) {
    +            return false;
    +        }
    +        List<ExecutorInfo> executorInfos = new ArrayList<>();
    +        executorInfos.addAll(whb.get_executors());
    +        // remove SYSTEM_EXECUTOR_ID
    +        executorInfos.remove(new ExecutorInfo(-1, -1));
    +        List<ExecutorInfo> localExecuorInfos = localAssignment.get_executors();
    +
    +        if (localExecuorInfos.size() != executorInfos.size())
    +            return false;
    +
    +        for (ExecutorInfo executorInfo : localExecuorInfos){
    +            if (!localExecuorInfos.contains(executorInfo))
    +                return false;
    +        }
    +        return true;
    +    }
    +
    +    /**
    +     * launch a worker in local mode.
    +     */
    +    protected void launchWorker(SupervisorData supervisorData, String stormId, Long port, String workerId, WorkerResources resources) throws IOException {
    +        // port this function after porting worker to java
    +    }
    +
    +    protected String getWorkerClassPath(String stormJar, Map stormConf) {
    +        List<String> topoClasspath = new ArrayList<>();
    +        Object object = stormConf.get(Config.TOPOLOGY_CLASSPATH);
    +
    +        if (object instanceof List) {
    +            topoClasspath.addAll((List<String>) object);
    +        } else if (object instanceof String){
    +            topoClasspath.add((String)object);
    +        }else {
    +            //ignore
    --- End diff --
    
    The original code was
    
    ```
    (let [...
              topo-classpath (if-let [cp (storm-conf TOPOLOGY-CLASSPATH)]
                               [cp]
                               [])
              ... (Utils/addToClasspath something topo-classpath) ...
    ```
    
    The Signature for Utils.addToClasspath is
    
    ```
    public static String addToClasspath(String classpath, Collection<String> paths);
    ```
    
    if `cp` was anything but a `String` in that code we would get a `ClassCastException` that would bring down the supervisor.  This code is even more lenient and supports both `String` and `List<String>`.  Which fixes a bug in our translation of the Utils code.
    
    You are right that we don't want a bad user config to bring down a supervisor, but if nimbus is doing the right thing and validating the config before it goes to the supervisor we should never see this happen.  `TOPOLOGY_CLASSPATH` is annotated with ` @isStringOrStringList`.  So if we ever see `object` as something that is not a `String`, `List<String>`, or `null` it means we have a bug in our code somewhere, and silently ignoring it feels wrong to me.
    
    I would be fine with us logging an error if it is something different, but not totally ignoring 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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55937914
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorManger.java ---
    @@ -0,0 +1,97 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.event.EventManager;
    +import org.apache.storm.utils.Utils;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.util.Collection;
    +import java.util.Map;
    +
    +public class SupervisorManger implements SupervisorDaemon, DaemonCommon, Runnable {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorManger.class);
    +    private final EventManager eventManager;
    +    private final EventManager processesEventManager;
    +    private SupervisorData supervisorData;
    +
    +    public SupervisorManger(SupervisorData supervisorData, EventManager eventManager, EventManager processesEventManager) {
    +        this.eventManager = eventManager;
    +        this.supervisorData = supervisorData;
    +        this.processesEventManager = processesEventManager;
    +    }
    +
    +    public void shutdown() {
    +        LOG.info("Shutting down supervisor{}", supervisorData.getSupervisorId());
    --- End diff --
    
    minor. space after supervisor. 


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55584817
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorData.java ---
    @@ -0,0 +1,339 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.cluster.ClusterStateContext;
    +import org.apache.storm.cluster.ClusterUtils;
    +import org.apache.storm.cluster.DaemonType;
    +import org.apache.storm.cluster.IStormClusterState;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.ProfileRequest;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +import java.net.UnknownHostException;
    +import java.util.ArrayList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.concurrent.ConcurrentHashMap;
    +import java.util.concurrent.atomic.AtomicInteger;
    +
    +public class SupervisorData {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorData.class);
    +
    +    private Map conf;
    +    private IContext sharedContext;
    +    private volatile boolean active;
    +    private ISupervisor iSupervisor;
    +    private Utils.UptimeComputer upTime;
    +    private String stormVersion;
    +
    +    private ConcurrentHashMap<String, String> workerThreadPidsAtom; // for local mode
    +
    +    private IStormClusterState stormClusterState;
    +
    +    private LocalState localState;
    +
    +    private String supervisorId;
    +
    +    private String assignmentId;
    +
    +    private String hostName;
    +
    +    // used for reporting used ports when heartbeating
    +    private ConcurrentHashMap<Long, LocalAssignment> currAssignment;
    +
    +    private StormTimer heartbeatTimer;
    +
    +    private StormTimer eventTimer;
    +
    +    private StormTimer blobUpdateTimer;
    +
    +    private Localizer localizer;
    +
    +    private ConcurrentHashMap<String, Map<String, Object>> assignmentVersions;
    +
    +    private AtomicInteger syncRetry;
    +
    +    private final Object downloadLock = new Object();
    +
    +    private ConcurrentHashMap<String, List<ProfileRequest>> stormIdToProfileActions;
    +
    +    private CgroupManager resourceIsolationManager;
    +
    +    private ConcurrentHashSet<String> deadWorkers;
    +
    +    public SupervisorData(Map conf, IContext sharedContext, ISupervisor iSupervisor) {
    +        this.conf = conf;
    +        this.sharedContext = sharedContext;
    +        this.iSupervisor = iSupervisor;
    +        this.active = true;
    +        this.upTime = Utils.makeUptimeComputer();
    +        this.stormVersion = VersionInfo.getVersion();
    +        this.workerThreadPidsAtom = new ConcurrentHashMap<String, String>();
    +        this.deadWorkers = new ConcurrentHashSet();
    +
    +        List<ACL> acls = null;
    +        if (Utils.isZkAuthenticationConfiguredStormServer(conf)) {
    +            acls = SupervisorUtils.supervisorZkAcls();
    +        }
    +
    +        try {
    +            this.stormClusterState = ClusterUtils.mkStormClusterState(conf, acls, new ClusterStateContext(DaemonType.SUPERVISOR));
    +        } catch (Exception e) {
    +            LOG.error("supervisor can't create stormClusterState");
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        try {
    +            this.localState = ConfigUtils.supervisorState(conf);
    +            this.localizer = Utils.createLocalizer(conf, ConfigUtils.supervisorLocalDir(conf));
    +        } catch (IOException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +        this.supervisorId = iSupervisor.getSupervisorId();
    +        this.assignmentId = iSupervisor.getAssignmentId();
    +
    +        try {
    +            this.hostName = Utils.hostname(conf);
    +        } catch (UnknownHostException e) {
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +        this.currAssignment = new ConcurrentHashMap<>();
    +
    +        this.heartbeatTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.eventTimer = new StormTimer(null, new DefaultUncaughtExceptionHandler());
    +
    +        this.blobUpdateTimer = new StormTimer("blob-update-timer", new DefaultUncaughtExceptionHandler());
    +
    +        this.assignmentVersions = new ConcurrentHashMap<>();
    +        this.syncRetry = new AtomicInteger(0);
    +        this.stormIdToProfileActions = new ConcurrentHashMap<>();
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            try {
    +                this.resourceIsolationManager = (CgroupManager) Utils.newInstance((String) conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN));
    +                this.resourceIsolationManager.prepare(conf);
    +                LOG.info("Using resource isolation plugin {} {}", conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN), resourceIsolationManager);
    +            } catch (IOException e) {
    +                throw Utils.wrapInRuntime(e);
    +            }
    +        } else {
    +            this.resourceIsolationManager = null;
    +        }
    +    }
    +
    +    public ConcurrentHashMap<String, List<ProfileRequest>> getStormIdToProfileActions() {
    +        return stormIdToProfileActions;
    +    }
    +
    +    public void setStormIdToProfileActions(Map<String, List<ProfileRequest>> stormIdToProfileActions) {
    +        this.stormIdToProfileActions.clear();
    +        this.stormIdToProfileActions.putAll(stormIdToProfileActions);
    +    }
    +
    +    public Map getConf() {
    +        return conf;
    +    }
    +
    +    public void setConf(Map conf) {
    +        this.conf = conf;
    +    }
    +
    +    public IContext getSharedContext() {
    +        return sharedContext;
    +    }
    +
    +    public void setSharedContext(IContext sharedContext) {
    +        this.sharedContext = sharedContext;
    +    }
    +
    +    public boolean isActive() {
    +        return active;
    +    }
    +
    +    public void setActive(boolean active) {
    +        this.active = active;
    +    }
    +
    +    public ISupervisor getiSupervisor() {
    +        return iSupervisor;
    +    }
    +
    +    public void setiSupervisor(ISupervisor iSupervisor) {
    +        this.iSupervisor = iSupervisor;
    +    }
    +
    +    public Utils.UptimeComputer getUpTime() {
    +        return upTime;
    +    }
    +
    +    public void setUpTime(Utils.UptimeComputer upTime) {
    +        this.upTime = upTime;
    +    }
    +
    +    public String getStormVersion() {
    +        return stormVersion;
    +    }
    +
    +    public void setStormVersion(String stormVersion) {
    +        this.stormVersion = stormVersion;
    +    }
    +
    +    public ConcurrentHashMap<String, String> getWorkerThreadPidsAtom() {
    +        return workerThreadPidsAtom;
    +    }
    +
    +    public void setWorkerThreadPidsAtom(ConcurrentHashMap<String, String> workerThreadPidsAtom) {
    +        this.workerThreadPidsAtom = workerThreadPidsAtom;
    +    }
    +
    +    public IStormClusterState getStormClusterState() {
    +        return stormClusterState;
    +    }
    +
    +    public void setStormClusterState(IStormClusterState stormClusterState) {
    +        this.stormClusterState = stormClusterState;
    +    }
    +
    +    public LocalState getLocalState() {
    +        return localState;
    +    }
    +
    +    public void setLocalState(LocalState localState) {
    +        this.localState = localState;
    +    }
    +
    +    public String getSupervisorId() {
    +        return supervisorId;
    +    }
    +
    +    public void setSupervisorId(String supervisorId) {
    --- End diff --
    
    Not used.


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55939157
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncProcessEvent.java ---
    @@ -0,0 +1,672 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.ExecutorInfo;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.WorkerResources;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +import org.yaml.snakeyaml.Yaml;
    +
    +import java.io.File;
    +import java.io.FileWriter;
    +import java.io.IOException;
    +import java.util.*;
    +
    +/**
    + * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file - rmr
    + * heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new worker
    + * ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait for workers
    + * launch
    + */
    +public class SyncProcessEvent implements Runnable {
    +
    +    private static Logger LOG = LoggerFactory.getLogger(SyncProcessEvent.class);
    +
    +    private  LocalState localState;
    +    private  SupervisorData supervisorData;
    +    public static final ExecutorInfo SYSTEM_EXECUTOR_INFO = new ExecutorInfo(-1, -1);
    +
    +    private class ProcessExitCallback implements Utils.ExitCodeCallable {
    +        private final String logPrefix;
    +        private final String workerId;
    +
    +        public ProcessExitCallback(String logPrefix, String workerId) {
    +            this.logPrefix = logPrefix;
    +            this.workerId = workerId;
    +        }
    +
    +        @Override
    +        public Object call() throws Exception {
    +            return null;
    +        }
    +
    +        @Override
    +        public Object call(int exitCode) {
    +            LOG.info("{} exited with code: {}", logPrefix, exitCode);
    +            supervisorData.getDeadWorkers().add(workerId);
    +            return null;
    +        }
    +    }
    +
    +    public SyncProcessEvent(){
    +
    +    }
    +    public SyncProcessEvent(SupervisorData supervisorData) {
    +        init(supervisorData);
    +    }
    +
    +    //TODO: initData is intended to local supervisor, so we will remove them after porting worker.clj to java
    +    public void init(SupervisorData supervisorData){
    +        this.supervisorData = supervisorData;
    +        this.localState = supervisorData.getLocalState();
    +    }
    +
    +
    +    /**
    +     * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file -
    +     * rmr heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new
    +     * worker ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait
    +     * for workers launch
    +     */
    +    @Override
    +    public void run() {
    +        LOG.debug("Syncing processes");
    +        try {
    +            Map conf = supervisorData.getConf();
    +            Map<Integer, LocalAssignment> assignedExecutors = localState.getLocalAssignmentsMap();
    +
    +            if (assignedExecutors == null) {
    +                assignedExecutors = new HashMap<>();
    +            }
    +            int now = Time.currentTimeSecs();
    +
    +            Map<String, StateHeartbeat> localWorkerStats = getLocalWorkerStats(supervisorData, assignedExecutors, now);
    +
    +            Set<String> keeperWorkerIds = new HashSet<>();
    +            Set<Integer> keepPorts = new HashSet<>();
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() == State.VALID) {
    +                    keeperWorkerIds.add(entry.getKey());
    +                    keepPorts.add(stateHeartbeat.getHeartbeat().get_port());
    +                }
    +            }
    +            Map<Integer, LocalAssignment> reassignExecutors = getReassignExecutors(assignedExecutors, keepPorts);
    +            Map<Integer, String> newWorkerIds = new HashMap<>();
    +            for (Integer port : reassignExecutors.keySet()) {
    +                newWorkerIds.put(port, Utils.uuid());
    +            }
    +            LOG.debug("Syncing processes");
    +            LOG.debug("Assigned executors: {}", assignedExecutors);
    +            LOG.debug("Allocated: {}", localWorkerStats);
    +
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() != State.VALID) {
    +                    LOG.info("Shutting down and clearing state for id {}, Current supervisor time: {}, State: {}, Heartbeat: {}", entry.getKey(), now,
    +                            stateHeartbeat.getState(), stateHeartbeat.getHeartbeat());
    +                    shutWorker(supervisorData, entry.getKey());
    +                }
    +            }
    +            // start new workers
    +            Map<String, Integer> newWorkerPortToIds = startNewWorkers(newWorkerIds, reassignExecutors);
    +
    +            Map<String, Integer> allWorkerPortToIds = new HashMap<>();
    +            Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +            for (String keeper : keeperWorkerIds) {
    +                allWorkerPortToIds.put(keeper, approvedWorkers.get(keeper));
    +            }
    +            allWorkerPortToIds.putAll(newWorkerPortToIds);
    +            localState.setApprovedWorkers(allWorkerPortToIds);
    +            waitForWorkersLaunch(conf, newWorkerPortToIds.keySet());
    +
    +        } catch (Exception e) {
    +            LOG.error("Failed Sync Process", e);
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +    }
    +
    +    protected void waitForWorkersLaunch(Map conf, Set<String> workerIds) throws Exception {
    +        int startTime = Time.currentTimeSecs();
    +        int timeOut = (int) conf.get(Config.NIMBUS_SUPERVISOR_TIMEOUT_SECS);
    +        for (String workerId : workerIds) {
    +            LocalState localState = ConfigUtils.workerState(conf, workerId);
    +            while (true) {
    +                LSWorkerHeartbeat hb = localState.getWorkerHeartBeat();
    +                if (hb != null || (Time.currentTimeSecs() - startTime) > timeOut)
    +                    break;
    +                LOG.info("{} still hasn't started", workerId);
    +                Time.sleep(500);
    +            }
    +            if (localState.getWorkerHeartBeat() == null) {
    +                LOG.info("Worker {} failed to start", workerId);
    +            }
    +        }
    +    }
    +
    +    protected Map<Integer, LocalAssignment> getReassignExecutors(Map<Integer, LocalAssignment> assignExecutors, Set<Integer> keepPorts) {
    +        Map<Integer, LocalAssignment> reassignExecutors = new HashMap<>();
    +        reassignExecutors.putAll(assignExecutors);
    +        for (Integer port : keepPorts) {
    +            reassignExecutors.remove(port);
    +        }
    +        return reassignExecutors;
    +    }
    +    
    +    /**
    +     * Returns map from worker id to worker heartbeat. if the heartbeat is nil, then the worker is dead
    +     * 
    +     * @param assignedExecutors
    +     * @return
    +     * @throws Exception
    +     */
    +    public Map<String, StateHeartbeat> getLocalWorkerStats(SupervisorData supervisorData, Map<Integer, LocalAssignment> assignedExecutors, int now) throws Exception {
    +        Map<String, StateHeartbeat> workerIdHbstate = new HashMap<>();
    +        Map conf = supervisorData.getConf();
    +        LocalState localState = supervisorData.getLocalState();
    +        Map<String, LSWorkerHeartbeat> idToHeartbeat = SupervisorUtils.readWorkerHeartbeats(conf);
    +        Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +        Set<String> approvedIds = new HashSet<>();
    +        if (approvedWorkers != null) {
    +            approvedIds.addAll(approvedWorkers.keySet());
    +        }
    +        for (Map.Entry<String, LSWorkerHeartbeat> entry : idToHeartbeat.entrySet()) {
    +            String workerId = entry.getKey();
    +            LSWorkerHeartbeat whb = entry.getValue();
    +            State state;
    +            if (whb == null) {
    +                state = State.NOT_STARTED;
    +            } else if (!approvedIds.contains(workerId) || !matchesAssignment(whb, assignedExecutors)) {
    +                state = State.DISALLOWED;
    +            } else if (supervisorData.getDeadWorkers().contains(workerId)) {
    +                LOG.info("Worker Process {} has died", workerId);
    +                state = State.TIMED_OUT;
    +            } else if (SupervisorUtils.isWorkerHbTimedOut(now, whb, conf)) {
    +                state = State.TIMED_OUT;
    +            } else {
    +                state = State.VALID;
    +            }
    +            LOG.debug("Worker:{} state:{} WorkerHeartbeat:{} at supervisor time-secs {}", workerId, state, whb, now);
    +            workerIdHbstate.put(workerId, new StateHeartbeat(state, whb));
    +        }
    +        return workerIdHbstate;
    +    }
    +
    +    protected boolean matchesAssignment(LSWorkerHeartbeat whb, Map<Integer, LocalAssignment> assignedExecutors) {
    +        LocalAssignment localAssignment = assignedExecutors.get(whb.get_port());
    +        if (localAssignment == null || !localAssignment.get_topology_id().equals(whb.get_topology_id())) {
    +            return false;
    +        }
    +        List<ExecutorInfo> executorInfos = new ArrayList<>();
    +        executorInfos.addAll(whb.get_executors());
    +        // remove SYSTEM_EXECUTOR_ID
    +        executorInfos.remove(SYSTEM_EXECUTOR_INFO);
    +        List<ExecutorInfo> localExecuorInfos = localAssignment.get_executors();
    +
    +        if (localExecuorInfos.size() != executorInfos.size())
    +            return false;
    +
    +        for (ExecutorInfo executorInfo : localExecuorInfos){
    +            if (!localExecuorInfos.contains(executorInfo))
    +                return false;
    +        }
    +        return true;
    +    }
    +
    +    /**
    +     * launch a worker in local mode.
    +     */
    +    protected void launchWorker(SupervisorData supervisorData, String stormId, Long port, String workerId, WorkerResources resources) throws IOException {
    +        // port this function after porting worker to java
    +    }
    +
    +    protected String getWorkerClassPath(String stormJar, Map stormConf) {
    +        List<String> topoClasspath = new ArrayList<>();
    +        Object object = stormConf.get(Config.TOPOLOGY_CLASSPATH);
    +
    +        if (object instanceof List) {
    +            topoClasspath.addAll((List<String>) object);
    +        } else if (object instanceof String){
    +            topoClasspath.add((String)object);
    +        }else {
    +            //ignore
    +        }
    +        String classPath = Utils.workerClasspath();
    +        String classAddPath = Utils.addToClasspath(classPath, Arrays.asList(stormJar));
    +        return Utils.addToClasspath(classAddPath, topoClasspath);
    +    }
    +
    +    /**
    +     * "Generates runtime childopts by replacing keys with topology-id, worker-id, port, mem-onheap"
    +     * 
    +     * @param value
    +     * @param workerId
    +     * @param stormId
    +     * @param port
    +     * @param memOnheap
    +     */
    +    public List<String> substituteChildopts(Object value, String workerId, String stormId, Long port, int memOnheap) {
    +        List<String> rets = new ArrayList<>();
    +        if (value instanceof String) {
    +            String string = (String) value;
    +            string = string.replace("%ID%", String.valueOf(port));
    +            string = string.replace("%WORKER-ID%", workerId);
    +            string = string.replace("%TOPOLOGY-ID%", stormId);
    +            string = string.replace("%WORKER-PORT%", String.valueOf(port));
    +            string = string.replace("%HEAP-MEM%", String.valueOf(memOnheap));
    +            String[] strings = string.split("\\s+");
    +            rets.addAll(Arrays.asList(strings));
    +        } else if (value instanceof List) {
    +            List<Object> objects = (List<Object>) value;
    +            for (Object object : objects) {
    +                String str = (String)object;
    +                str = str.replace("%ID%", String.valueOf(port));
    +                str = str.replace("%WORKER-ID%", workerId);
    +                str = str.replace("%TOPOLOGY-ID%", stormId);
    +                str = str.replace("%WORKER-PORT%", String.valueOf(port));
    +                str = str.replace("%HEAP-MEM%", String.valueOf(memOnheap));
    +                rets.add(str);
    +            }
    +        }
    +        return rets;
    +    }
    +
    +
    +
    +    /**
    +     * launch a worker in distributed mode
    +     * supervisorId for testing
    +     * @throws IOException
    +     */
    +    protected void launchWorker(Map conf, String supervisorId, String assignmentId, String stormId, Long port, String workerId,
    +            WorkerResources resources, CgroupManager cgroupManager, ConcurrentHashSet deadWorkers) throws IOException {
    +
    +        Boolean runWorkerAsUser = Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false);
    +        String stormHome = ConfigUtils.concatIfNotNull(System.getProperty("storm.home"));
    +        String stormOptions = ConfigUtils.concatIfNotNull(System.getProperty("storm.options"));
    +        String stormConfFile = ConfigUtils.concatIfNotNull(System.getProperty("storm.conf.file"));
    +        String workerTmpDir = ConfigUtils.workerTmpRoot(conf, workerId);
    +
    +        String stormLogDir = ConfigUtils.getLogDir();
    +        String stormLogConfDir = (String) (conf.get(Config.STORM_LOG4J2_CONF_DIR));
    +
    +        String stormLog4j2ConfDir;
    +        if (StringUtils.isNotBlank(stormLogConfDir)) {
    +            if (Utils.isAbsolutePath(stormLogConfDir)) {
    +                stormLog4j2ConfDir = stormLogConfDir;
    +            } else {
    +                stormLog4j2ConfDir = stormHome + Utils.FILE_PATH_SEPARATOR + stormLogConfDir;
    +            }
    +        } else {
    +            stormLog4j2ConfDir = stormHome + Utils.FILE_PATH_SEPARATOR + "log4j2";
    +        }
    +
    +        String stormRoot = ConfigUtils.supervisorStormDistRoot(conf, stormId);
    +
    +        String jlp = jlp(stormRoot, conf);
    +
    +        String stormJar = ConfigUtils.supervisorStormJarPath(stormRoot);
    +
    +        Map stormConf = ConfigUtils.readSupervisorStormConf(conf, stormId);
    +
    +        String workerClassPath = getWorkerClassPath(stormJar, stormConf);
    +
    +        Object topGcOptsObject = stormConf.get(Config.TOPOLOGY_WORKER_GC_CHILDOPTS);
    +        List<String> topGcOpts = new ArrayList<>();
    +        if (topGcOptsObject instanceof String) {
    +            topGcOpts.add((String) topGcOptsObject);
    +        } else if (topGcOptsObject instanceof List) {
    +            topGcOpts.addAll((List<String>) topGcOptsObject);
    +        }
    +
    +        int memOnheap = 0;
    +        if (resources.get_mem_on_heap() > 0) {
    +            memOnheap = (int) Math.ceil(resources.get_mem_on_heap());
    +        } else {
    +            //set the default heap memory size for supervisor-test
    +            memOnheap = Utils.getInt(stormConf.get(Config.WORKER_HEAP_MEMORY_MB), 768);
    +        }
    +
    +        int memoffheap = (int) Math.ceil(resources.get_mem_off_heap());
    +
    +        int cpu = (int) Math.ceil(resources.get_cpu());
    +
    +        List<String> gcOpts = null;
    +
    +        if (topGcOpts != null) {
    +            gcOpts = substituteChildopts(topGcOpts, workerId, stormId, port, memOnheap);
    +        } else {
    +            gcOpts = substituteChildopts(conf.get(Config.WORKER_GC_CHILDOPTS), workerId, stormId, port, memOnheap);
    +        }
    +
    +        Object topoWorkerLogwriterObject = stormConf.get(Config.TOPOLOGY_WORKER_LOGWRITER_CHILDOPTS);
    +        List<String> topoWorkerLogwriterChildopts = new ArrayList<>();
    +        if (topoWorkerLogwriterObject instanceof String) {
    +            topoWorkerLogwriterChildopts.add((String) topoWorkerLogwriterObject);
    +        } else if (topoWorkerLogwriterObject instanceof List) {
    --- End diff --
    
    checking instanceof List is not sufficient here as any collection is acceptable. You can do `instanceof Collection` and cast it to `Collection<String>` instead. Same can be done in other places as well. 


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55605034
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncProcessEvent.java ---
    @@ -0,0 +1,669 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.ExecutorInfo;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.WorkerResources;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +import org.yaml.snakeyaml.Yaml;
    +
    +import java.io.File;
    +import java.io.FileWriter;
    +import java.io.IOException;
    +import java.util.*;
    +
    +/**
    + * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file - rmr
    + * heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new worker
    + * ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait for workers
    + * launch
    + */
    +public class SyncProcessEvent extends ShutdownWork implements Runnable {
    +
    +    private static Logger LOG = LoggerFactory.getLogger(SyncProcessEvent.class);
    +
    +    private  LocalState localState;
    +
    +    private SupervisorData supervisorData;
    +
    +    private class ProcessExitCallback implements Utils.ExitCodeCallable {
    +        private final String logPrefix;
    +        private final String workerId;
    +
    +        public ProcessExitCallback(String logPrefix, String workerId) {
    +            this.logPrefix = logPrefix;
    +            this.workerId = workerId;
    +        }
    +
    +        @Override
    +        public Object call() throws Exception {
    +            return null;
    +        }
    +
    +        @Override
    +        public Object call(int exitCode) {
    +            LOG.info("{} exited with code: {}", logPrefix, exitCode);
    +            supervisorData.getDeadWorkers().add(workerId);
    +            return null;
    +        }
    +    }
    +
    +    public SyncProcessEvent(){
    +
    +    }
    +    public SyncProcessEvent(SupervisorData supervisorData) {
    +        init(supervisorData);
    +    }
    +
    +    //TODO: initData is intended to local supervisor, so we will remove them after porting worker.clj to java
    +    public void init(SupervisorData supervisorData){
    +        this.supervisorData = supervisorData;
    +        this.localState = supervisorData.getLocalState();
    +    }
    +
    +
    +    /**
    +     * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file -
    +     * rmr heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new
    +     * worker ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait
    +     * for workers launch
    +     */
    +    @Override
    +    public void run() {
    +        LOG.debug("Syncing processes");
    +        try {
    +            Map conf = supervisorData.getConf();
    +            Map<Integer, LocalAssignment> assignedExecutors = localState.getLocalAssignmentsMap();
    +
    +            if (assignedExecutors == null) {
    +                assignedExecutors = new HashMap<>();
    +            }
    +            int now = Time.currentTimeSecs();
    +
    +            Map<String, StateHeartbeat> localWorkerStats = getLocalWorkerStats(supervisorData, assignedExecutors, now);
    +
    +            Set<String> keeperWorkerIds = new HashSet<>();
    +            Set<Integer> keepPorts = new HashSet<>();
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() == State.valid) {
    +                    keeperWorkerIds.add(entry.getKey());
    +                    keepPorts.add(stateHeartbeat.getHeartbeat().get_port());
    +                }
    +            }
    +            Map<Integer, LocalAssignment> reassignExecutors = getReassignExecutors(assignedExecutors, keepPorts);
    +            Map<Integer, String> newWorkerIds = new HashMap<>();
    +            for (Integer port : reassignExecutors.keySet()) {
    +                newWorkerIds.put(port, Utils.uuid());
    +            }
    +            LOG.debug("Syncing processes");
    +            LOG.debug("Assigned executors: {}", assignedExecutors);
    +            LOG.debug("Allocated: {}", localWorkerStats);
    +
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() != State.valid) {
    +                    LOG.info("Shutting down and clearing state for id {}, Current supervisor time: {}, State: {}, Heartbeat: {}", entry.getKey(), now,
    +                            stateHeartbeat.getState(), stateHeartbeat.getHeartbeat());
    +                    shutWorker(supervisorData, entry.getKey());
    +                }
    +            }
    +            // start new workers
    +            Map<String, Integer> newWorkerPortToIds = startNewWorkers(newWorkerIds, reassignExecutors);
    +
    +            Map<String, Integer> allWorkerPortToIds = new HashMap<>();
    +            Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +            for (String keeper : keeperWorkerIds) {
    +                allWorkerPortToIds.put(keeper, approvedWorkers.get(keeper));
    +            }
    +            allWorkerPortToIds.putAll(newWorkerPortToIds);
    +            localState.setApprovedWorkers(allWorkerPortToIds);
    +            waitForWorkersLaunch(conf, newWorkerPortToIds.keySet());
    +
    +        } catch (Exception e) {
    +            LOG.error("Failed Sync Process", e);
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +    }
    +
    +    protected void waitForWorkersLaunch(Map conf, Set<String> workerIds) throws Exception {
    +        int startTime = Time.currentTimeSecs();
    +        int timeOut = (int) conf.get(Config.NIMBUS_SUPERVISOR_TIMEOUT_SECS);
    +        for (String workerId : workerIds) {
    +            LocalState localState = ConfigUtils.workerState(conf, workerId);
    +            while (true) {
    +                LSWorkerHeartbeat hb = localState.getWorkerHeartBeat();
    +                if (hb != null || (Time.currentTimeSecs() - startTime) > timeOut)
    +                    break;
    +                LOG.info("{} still hasn't started", workerId);
    +                Time.sleep(500);
    +            }
    +            if (localState.getWorkerHeartBeat() == null) {
    +                LOG.info("Worker {} failed to start", workerId);
    +            }
    +        }
    +    }
    +
    +    protected Map<Integer, LocalAssignment> getReassignExecutors(Map<Integer, LocalAssignment> assignExecutors, Set<Integer> keepPorts) {
    +        Map<Integer, LocalAssignment> reassignExecutors = new HashMap<>();
    +        reassignExecutors.putAll(assignExecutors);
    +        for (Integer port : keepPorts) {
    +            reassignExecutors.remove(port);
    +        }
    +        return reassignExecutors;
    +    }
    +
    +
    +
    +    /**
    +     * Returns map from worker id to worker heartbeat. if the heartbeat is nil, then the worker is dead
    +     * 
    +     * @param assignedExecutors
    +     * @return
    +     * @throws Exception
    +     */
    +    public Map<String, StateHeartbeat> getLocalWorkerStats(SupervisorData supervisorData, Map<Integer, LocalAssignment> assignedExecutors, int now) throws Exception {
    +        Map<String, StateHeartbeat> workerIdHbstate = new HashMap<>();
    +        Map conf = supervisorData.getConf();
    +        LocalState localState = supervisorData.getLocalState();
    +        Map<String, LSWorkerHeartbeat> idToHeartbeat = SupervisorUtils.readWorkerHeartbeats(conf);
    +        Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +        Set<String> approvedIds = new HashSet<>();
    +        if (approvedWorkers != null) {
    +            approvedIds.addAll(approvedWorkers.keySet());
    +        }
    +        for (Map.Entry<String, LSWorkerHeartbeat> entry : idToHeartbeat.entrySet()) {
    +            String workerId = entry.getKey();
    +            LSWorkerHeartbeat whb = entry.getValue();
    +            State state;
    +            if (whb == null) {
    +                state = State.notStarted;
    +            } else if (!approvedIds.contains(workerId) || !matchesAssignment(whb, assignedExecutors)) {
    +                state = State.disallowed;
    +            } else if (supervisorData.getDeadWorkers().contains(workerId)) {
    +                LOG.info("Worker Process {}as died", workerId);
    +                state = State.timedOut;
    +            } else if (SupervisorUtils.isWorkerHbTimedOut(now, whb, conf)) {
    +                state = State.timedOut;
    +            } else {
    +                state = State.valid;
    +            }
    +            LOG.debug("Worker:{} state:{} WorkerHeartbeat:{} at supervisor time-secs {}", workerId, state, whb, now);
    +            workerIdHbstate.put(workerId, new StateHeartbeat(state, whb));
    +        }
    +        return workerIdHbstate;
    +    }
    +
    +    protected boolean matchesAssignment(LSWorkerHeartbeat whb, Map<Integer, LocalAssignment> assignedExecutors) {
    +        LocalAssignment localAssignment = assignedExecutors.get(whb.get_port());
    +        if (localAssignment == null || !localAssignment.get_topology_id().equals(whb.get_topology_id())) {
    +            return false;
    +        }
    +        List<ExecutorInfo> executorInfos = new ArrayList<>();
    +        executorInfos.addAll(whb.get_executors());
    +        // remove SYSTEM_EXECUTOR_ID
    +        executorInfos.remove(new ExecutorInfo(-1, -1));
    +        List<ExecutorInfo> localExecuorInfos = localAssignment.get_executors();
    +
    +        if (localExecuorInfos.size() != executorInfos.size())
    +            return false;
    +
    +        for (ExecutorInfo executorInfo : localExecuorInfos){
    +            if (!localExecuorInfos.contains(executorInfo))
    +                return false;
    +        }
    +        return true;
    +    }
    +
    +    /**
    +     * launch a worker in local mode.
    +     */
    +    protected void launchWorker(SupervisorData supervisorData, String stormId, Long port, String workerId, WorkerResources resources) throws IOException {
    +        // port this function after porting worker to java
    +    }
    +
    +    protected String getWorkerClassPath(String stormJar, Map stormConf) {
    +        List<String> topoClasspath = new ArrayList<>();
    +        Object object = stormConf.get(Config.TOPOLOGY_CLASSPATH);
    +
    +        if (object instanceof List) {
    +            topoClasspath.addAll((List<String>) object);
    +        } else if (object instanceof String){
    +            topoClasspath.add((String)object);
    +        }else {
    +            //ignore
    --- End diff --
    
    Can we throw an exception here if object is not null?  If TOPOLOGY_CLASSPATH is something else we have an error in our code somewhere.


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55694293
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorUtils.java ---
    @@ -0,0 +1,273 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.curator.utils.PathUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.localizer.LocalResource;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.IOException;
    +import java.net.URLDecoder;
    +import java.util.*;
    +
    +public class SupervisorUtils {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorUtils.class);
    +
    +    private static final SupervisorUtils INSTANCE = new SupervisorUtils();
    +    private static SupervisorUtils _instance = INSTANCE;
    +
    +    public static void setInstance(SupervisorUtils u) {
    +        _instance = u;
    +    }
    +
    +    public static void resetInstance() {
    +        _instance = INSTANCE;
    +    }
    +
    +    public static Process workerLauncher(Map conf, String user, List<String> args, Map<String, String> environment, final String logPreFix,
    --- End diff --
    
    Yes. I am confused with the name in fact.


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55938211
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorUtils.java ---
    @@ -0,0 +1,353 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.ProcessSimulator;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.localizer.LocalResource;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.IOException;
    +import java.net.URLDecoder;
    +import java.util.*;
    +
    +public class SupervisorUtils {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorUtils.class);
    +
    +    private static final SupervisorUtils INSTANCE = new SupervisorUtils();
    +    private static SupervisorUtils _instance = INSTANCE;
    +    public static void setInstance(SupervisorUtils u) {
    +        _instance = u;
    +    }
    +    public static void resetInstance() {
    +        _instance = INSTANCE;
    +    }
    +
    +    public static Process workerLauncher(Map conf, String user, List<String> args, Map<String, String> environment, final String logPreFix,
    +            final Utils.ExitCodeCallable exitCodeCallback, File dir) throws IOException {
    +        if (StringUtils.isBlank(user)) {
    +            throw new IllegalArgumentException("User cannot be blank when calling workerLauncher.");
    +        }
    +        String wlinitial = (String) (conf.get(Config.SUPERVISOR_WORKER_LAUNCHER));
    +        String stormHome = ConfigUtils.concatIfNotNull(System.getProperty("storm.home"));
    +        String wl;
    +        if (StringUtils.isNotBlank(wlinitial)) {
    +            wl = wlinitial;
    +        } else {
    +            wl = stormHome + "/bin/worker-launcher";
    +        }
    +        List<String> commands = new ArrayList<>();
    +        commands.add(wl);
    +        commands.add(user);
    +        commands.addAll(args);
    +        LOG.info("Running as user: {} command: {}", user, commands);
    +        return Utils.launchProcess(commands, environment, logPreFix, exitCodeCallback, dir);
    +    }
    +
    +    public static int workerLauncherAndWait(Map conf, String user, List<String> args, final Map<String, String> environment, final String logPreFix)
    +            throws IOException {
    +        int ret = 0;
    +        Process process = workerLauncher(conf, user, args, environment, logPreFix, null, null);
    +        if (StringUtils.isNotBlank(logPreFix))
    +            Utils.readAndLogStream(logPreFix, process.getInputStream());
    +        try {
    +            process.waitFor();
    +        } catch (InterruptedException e) {
    +            LOG.info("{} interrupted.", logPreFix);
    +        }
    +        ret = process.exitValue();
    +        return ret;
    +    }
    +
    +    public static void setupStormCodeDir(Map conf, Map stormConf, String dir) throws IOException {
    +        if (Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false)) {
    +            String logPrefix = "setup conf for " + dir;
    +            List<String> commands = new ArrayList<>();
    +            commands.add("code-dir");
    +            commands.add(dir);
    +            workerLauncherAndWait(conf, (String) (stormConf.get(Config.TOPOLOGY_SUBMITTER_USER)), commands, null, logPrefix);
    +        }
    +    }
    +
    +    public static void rmrAsUser(Map conf, String id, String path) throws IOException {
    +        String user = Utils.getFileOwner(path);
    +        String logPreFix = "rmr " + id;
    +        List<String> commands = new ArrayList<>();
    +        commands.add("rmr");
    +        commands.add(path);
    +        SupervisorUtils.workerLauncherAndWait(conf, user, commands, null, logPreFix);
    +        if (Utils.checkFileExists(path)) {
    +            throw new RuntimeException(path + " was not deleted.");
    +        }
    +    }
    +
    +    /**
    +     * Given the blob information returns the value of the uncompress field, handling it either being a string or a boolean value, or if it's not specified then
    +     * returns false
    +     * 
    +     * @param blobInfo
    +     * @return
    +     */
    +    public static Boolean shouldUncompressBlob(Map<String, Object> blobInfo) {
    +        return new Boolean((String) blobInfo.get("uncompress"));
    +    }
    +
    +    /**
    +     * Remove a reference to a blob when its no longer needed
    +     * 
    +     * @param blobstoreMap
    +     * @return
    +     */
    +    public static List<LocalResource> blobstoreMapToLocalresources(Map<String, Map<String, Object>> blobstoreMap) {
    +        List<LocalResource> localResourceList = new ArrayList<>();
    +        if (blobstoreMap != null) {
    +            for (Map.Entry<String, Map<String, Object>> map : blobstoreMap.entrySet()) {
    +                LocalResource localResource = new LocalResource(map.getKey(), shouldUncompressBlob(map.getValue()));
    +                localResourceList.add(localResource);
    +            }
    +        }
    +        return localResourceList;
    +    }
    +
    +    /**
    +     * For each of the downloaded topologies, adds references to the blobs that the topologies are using. This is used to reconstruct the cache on restart.
    +     * 
    +     * @param localizer
    +     * @param stormId
    +     * @param conf
    +     */
    +    public static void addBlobReferences(Localizer localizer, String stormId, Map conf) throws IOException {
    +        Map stormConf = ConfigUtils.readSupervisorStormConf(conf, stormId);
    +        Map<String, Map<String, Object>> blobstoreMap = (Map<String, Map<String, Object>>) stormConf.get(Config.TOPOLOGY_BLOBSTORE_MAP);
    +        String user = (String) stormConf.get(Config.TOPOLOGY_SUBMITTER_USER);
    +        String topoName = (String) stormConf.get(Config.TOPOLOGY_NAME);
    +        List<LocalResource> localresources = SupervisorUtils.blobstoreMapToLocalresources(blobstoreMap);
    +        if (blobstoreMap != null) {
    +            localizer.addReferences(localresources, user, topoName);
    +        }
    +    }
    +
    +    public static Set<String> readDownLoadedStormIds(Map conf) throws IOException {
    +        Set<String> stormIds = new HashSet<>();
    +        String path = ConfigUtils.supervisorStormDistRoot(conf);
    +        Collection<String> rets = Utils.readDirContents(path);
    +        for (String ret : rets) {
    +            stormIds.add(URLDecoder.decode(ret));
    +        }
    +        return stormIds;
    +    }
    +
    +    public static Collection<String> supervisorWorkerIds(Map conf) {
    +        String workerRoot = ConfigUtils.workerRoot(conf);
    +        return Utils.readDirContents(workerRoot);
    +    }
    +
    +    public static boolean doRequiredTopoFilesExist(Map conf, String stormId) throws IOException {
    +        String stormroot = ConfigUtils.supervisorStormDistRoot(conf, stormId);
    +        String stormjarpath = ConfigUtils.supervisorStormJarPath(stormroot);
    +        String stormcodepath = ConfigUtils.supervisorStormCodePath(stormroot);
    +        String stormconfpath = ConfigUtils.supervisorStormConfPath(stormroot);
    +        if (!Utils.checkFileExists(stormroot))
    +            return false;
    +        if (!Utils.checkFileExists(stormcodepath))
    +            return false;
    +        if (!Utils.checkFileExists(stormconfpath))
    +            return false;
    +        if (ConfigUtils.isLocalMode(conf) || Utils.checkFileExists(stormjarpath))
    +            return true;
    +        return false;
    +    }
    +
    +    /**
    +     * Returns map from worr id to heartbeat
    --- End diff --
    
    nit. map from worker id to heartbeat


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55216918
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorUtils.java ---
    @@ -0,0 +1,273 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.curator.utils.PathUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.localizer.LocalResource;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.IOException;
    +import java.net.URLDecoder;
    +import java.util.*;
    +
    +public class SupervisorUtils {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorUtils.class);
    +
    +    private static final SupervisorUtils INSTANCE = new SupervisorUtils();
    +    private static SupervisorUtils _instance = INSTANCE;
    +
    +    public static void setInstance(SupervisorUtils u) {
    +        _instance = u;
    +    }
    +
    +    public static void resetInstance() {
    +        _instance = INSTANCE;
    +    }
    +
    +    public static Process workerLauncher(Map conf, String user, List<String> args, Map<String, String> environment, final String logPreFix,
    +            final Utils.ExitCodeCallable exitCodeCallback, File dir) throws IOException {
    +        if (StringUtils.isBlank(user)) {
    +            throw new IllegalArgumentException("User cannot be blank when calling workerLauncher.");
    +        }
    +        String wlinitial = (String) (conf.get(Config.SUPERVISOR_WORKER_LAUNCHER));
    +        String stormHome = ConfigUtils.concatIfNotNull(System.getProperty("storm.home"));
    +        String wl;
    +        if (StringUtils.isNotBlank(wlinitial)) {
    +            wl = wlinitial;
    +        } else {
    +            wl = stormHome + "/bin/worker-launcher";
    +        }
    +        List<String> commands = new ArrayList<>();
    +        commands.add(wl);
    +        commands.add(user);
    +        commands.addAll(args);
    +        return Utils.launchProcess(commands, environment, logPreFix, exitCodeCallback, dir);
    +    }
    +
    +    public static int workerLauncherAndWait(Map conf, String user, List<String> args, final Map<String, String> environment, final String logPreFix)
    +            throws IOException {
    +        int ret = 0;
    +        Process process = workerLauncher(conf, user, args, environment, logPreFix, null, null);
    +        if (StringUtils.isNotBlank(logPreFix))
    +            Utils.readAndLogStream(logPreFix, process.getInputStream());
    +        try {
    +            process.waitFor();
    +        } catch (InterruptedException e) {
    +            LOG.info("{} interrupted.", logPreFix);
    +        }
    +        ret = process.exitValue();
    +        return ret;
    +    }
    +
    +    public static void setupStormCodeDir(Map conf, Map stormConf, String dir) throws IOException {
    +        if (Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false)) {
    +            String logPrefix = "setup conf for " + dir;
    +            List<String> commands = new ArrayList<>();
    +            commands.add("code-dir");
    +            commands.add(dir);
    +            workerLauncherAndWait(conf, (String) (stormConf.get(Config.TOPOLOGY_SUBMITTER_USER)), commands, null, logPrefix);
    +        }
    +    }
    +
    +    public static void rmrAsUser(Map conf, String id, String path) throws IOException {
    +        String user = Utils.getFileOwner(path);
    +        String logPreFix = "rmr " + id;
    +        List<String> commands = new ArrayList<>();
    +        commands.add("rmr");
    +        commands.add(path);
    +        SupervisorUtils.workerLauncherAndWait(conf, user, commands, null, logPreFix);
    +        if (Utils.checkFileExists(path)) {
    +            throw new RuntimeException(path + " was not deleted.");
    +        }
    +    }
    +
    +    /**
    +     * Given the blob information returns the value of the uncompress field, handling it either being a string or a boolean value, or if it's not specified then
    +     * returns false
    +     * 
    +     * @param blobInfo
    +     * @return
    +     */
    +    public static Boolean isShouldUncompressBlob(Map<String, Object> blobInfo) {
    --- End diff --
    
    can be renamed to shouldUncompressBlob


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55599650
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorUtils.java ---
    @@ -0,0 +1,273 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.curator.utils.PathUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.localizer.LocalResource;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.IOException;
    +import java.net.URLDecoder;
    +import java.util.*;
    +
    +public class SupervisorUtils {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorUtils.class);
    +
    +    private static final SupervisorUtils INSTANCE = new SupervisorUtils();
    +    private static SupervisorUtils _instance = INSTANCE;
    +
    +    public static void setInstance(SupervisorUtils u) {
    +        _instance = u;
    +    }
    +
    +    public static void resetInstance() {
    +        _instance = INSTANCE;
    +    }
    +
    +    public static Process workerLauncher(Map conf, String user, List<String> args, Map<String, String> environment, final String logPreFix,
    +            final Utils.ExitCodeCallable exitCodeCallback, File dir) throws IOException {
    +        if (StringUtils.isBlank(user)) {
    +            throw new IllegalArgumentException("User cannot be blank when calling workerLauncher.");
    +        }
    +        String wlinitial = (String) (conf.get(Config.SUPERVISOR_WORKER_LAUNCHER));
    +        String stormHome = ConfigUtils.concatIfNotNull(System.getProperty("storm.home"));
    +        String wl;
    +        if (StringUtils.isNotBlank(wlinitial)) {
    +            wl = wlinitial;
    +        } else {
    +            wl = stormHome + "/bin/worker-launcher";
    +        }
    +        List<String> commands = new ArrayList<>();
    +        commands.add(wl);
    +        commands.add(user);
    +        commands.addAll(args);
    +        return Utils.launchProcess(commands, environment, logPreFix, exitCodeCallback, dir);
    --- End diff --
    
    We are missing a log message just before this.
    ```
    (log-message "Running as user:" user " command:" (pr-str command))
    ```
    
    it can be very helpful for debugging
    
    ```
    LOG.info("Running as user: {} command: {}", user, command);
    ```


---
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-1279] port backtype.storm.daemon.superv...

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

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


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55964084
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncProcessEvent.java ---
    @@ -0,0 +1,672 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.generated.ExecutorInfo;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.WorkerResources;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +import org.yaml.snakeyaml.Yaml;
    +
    +import java.io.File;
    +import java.io.FileWriter;
    +import java.io.IOException;
    +import java.util.*;
    +
    +/**
    + * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file - rmr
    + * heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new worker
    + * ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait for workers
    + * launch
    + */
    +public class SyncProcessEvent implements Runnable {
    +
    +    private static Logger LOG = LoggerFactory.getLogger(SyncProcessEvent.class);
    +
    +    private  LocalState localState;
    +    private  SupervisorData supervisorData;
    +    public static final ExecutorInfo SYSTEM_EXECUTOR_INFO = new ExecutorInfo(-1, -1);
    +
    +    private class ProcessExitCallback implements Utils.ExitCodeCallable {
    +        private final String logPrefix;
    +        private final String workerId;
    +
    +        public ProcessExitCallback(String logPrefix, String workerId) {
    +            this.logPrefix = logPrefix;
    +            this.workerId = workerId;
    +        }
    +
    +        @Override
    +        public Object call() throws Exception {
    +            return null;
    +        }
    +
    +        @Override
    +        public Object call(int exitCode) {
    +            LOG.info("{} exited with code: {}", logPrefix, exitCode);
    +            supervisorData.getDeadWorkers().add(workerId);
    +            return null;
    +        }
    +    }
    +
    +    public SyncProcessEvent(){
    +
    +    }
    +    public SyncProcessEvent(SupervisorData supervisorData) {
    +        init(supervisorData);
    +    }
    +
    +    //TODO: initData is intended to local supervisor, so we will remove them after porting worker.clj to java
    +    public void init(SupervisorData supervisorData){
    +        this.supervisorData = supervisorData;
    +        this.localState = supervisorData.getLocalState();
    +    }
    +
    +
    +    /**
    +     * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file -
    +     * rmr heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new
    +     * worker ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait
    +     * for workers launch
    +     */
    +    @Override
    +    public void run() {
    +        LOG.debug("Syncing processes");
    +        try {
    +            Map conf = supervisorData.getConf();
    +            Map<Integer, LocalAssignment> assignedExecutors = localState.getLocalAssignmentsMap();
    +
    +            if (assignedExecutors == null) {
    +                assignedExecutors = new HashMap<>();
    +            }
    +            int now = Time.currentTimeSecs();
    +
    +            Map<String, StateHeartbeat> localWorkerStats = getLocalWorkerStats(supervisorData, assignedExecutors, now);
    +
    +            Set<String> keeperWorkerIds = new HashSet<>();
    +            Set<Integer> keepPorts = new HashSet<>();
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() == State.VALID) {
    +                    keeperWorkerIds.add(entry.getKey());
    +                    keepPorts.add(stateHeartbeat.getHeartbeat().get_port());
    +                }
    +            }
    +            Map<Integer, LocalAssignment> reassignExecutors = getReassignExecutors(assignedExecutors, keepPorts);
    +            Map<Integer, String> newWorkerIds = new HashMap<>();
    +            for (Integer port : reassignExecutors.keySet()) {
    +                newWorkerIds.put(port, Utils.uuid());
    +            }
    +            LOG.debug("Syncing processes");
    +            LOG.debug("Assigned executors: {}", assignedExecutors);
    +            LOG.debug("Allocated: {}", localWorkerStats);
    +
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() != State.VALID) {
    +                    LOG.info("Shutting down and clearing state for id {}, Current supervisor time: {}, State: {}, Heartbeat: {}", entry.getKey(), now,
    +                            stateHeartbeat.getState(), stateHeartbeat.getHeartbeat());
    +                    shutWorker(supervisorData, entry.getKey());
    +                }
    +            }
    +            // start new workers
    +            Map<String, Integer> newWorkerPortToIds = startNewWorkers(newWorkerIds, reassignExecutors);
    +
    +            Map<String, Integer> allWorkerPortToIds = new HashMap<>();
    +            Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +            for (String keeper : keeperWorkerIds) {
    +                allWorkerPortToIds.put(keeper, approvedWorkers.get(keeper));
    +            }
    +            allWorkerPortToIds.putAll(newWorkerPortToIds);
    +            localState.setApprovedWorkers(allWorkerPortToIds);
    +            waitForWorkersLaunch(conf, newWorkerPortToIds.keySet());
    +
    +        } catch (Exception e) {
    +            LOG.error("Failed Sync Process", e);
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +    }
    +
    +    protected void waitForWorkersLaunch(Map conf, Set<String> workerIds) throws Exception {
    +        int startTime = Time.currentTimeSecs();
    +        int timeOut = (int) conf.get(Config.NIMBUS_SUPERVISOR_TIMEOUT_SECS);
    +        for (String workerId : workerIds) {
    +            LocalState localState = ConfigUtils.workerState(conf, workerId);
    +            while (true) {
    +                LSWorkerHeartbeat hb = localState.getWorkerHeartBeat();
    +                if (hb != null || (Time.currentTimeSecs() - startTime) > timeOut)
    +                    break;
    +                LOG.info("{} still hasn't started", workerId);
    +                Time.sleep(500);
    +            }
    +            if (localState.getWorkerHeartBeat() == null) {
    +                LOG.info("Worker {} failed to start", workerId);
    +            }
    +        }
    +    }
    +
    +    protected Map<Integer, LocalAssignment> getReassignExecutors(Map<Integer, LocalAssignment> assignExecutors, Set<Integer> keepPorts) {
    +        Map<Integer, LocalAssignment> reassignExecutors = new HashMap<>();
    +        reassignExecutors.putAll(assignExecutors);
    +        for (Integer port : keepPorts) {
    +            reassignExecutors.remove(port);
    +        }
    +        return reassignExecutors;
    +    }
    +    
    +    /**
    +     * Returns map from worker id to worker heartbeat. if the heartbeat is nil, then the worker is dead
    +     * 
    +     * @param assignedExecutors
    +     * @return
    +     * @throws Exception
    +     */
    +    public Map<String, StateHeartbeat> getLocalWorkerStats(SupervisorData supervisorData, Map<Integer, LocalAssignment> assignedExecutors, int now) throws Exception {
    +        Map<String, StateHeartbeat> workerIdHbstate = new HashMap<>();
    +        Map conf = supervisorData.getConf();
    +        LocalState localState = supervisorData.getLocalState();
    +        Map<String, LSWorkerHeartbeat> idToHeartbeat = SupervisorUtils.readWorkerHeartbeats(conf);
    +        Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +        Set<String> approvedIds = new HashSet<>();
    +        if (approvedWorkers != null) {
    +            approvedIds.addAll(approvedWorkers.keySet());
    +        }
    +        for (Map.Entry<String, LSWorkerHeartbeat> entry : idToHeartbeat.entrySet()) {
    +            String workerId = entry.getKey();
    +            LSWorkerHeartbeat whb = entry.getValue();
    +            State state;
    +            if (whb == null) {
    +                state = State.NOT_STARTED;
    +            } else if (!approvedIds.contains(workerId) || !matchesAssignment(whb, assignedExecutors)) {
    +                state = State.DISALLOWED;
    +            } else if (supervisorData.getDeadWorkers().contains(workerId)) {
    +                LOG.info("Worker Process {} has died", workerId);
    +                state = State.TIMED_OUT;
    +            } else if (SupervisorUtils.isWorkerHbTimedOut(now, whb, conf)) {
    +                state = State.TIMED_OUT;
    +            } else {
    +                state = State.VALID;
    +            }
    +            LOG.debug("Worker:{} state:{} WorkerHeartbeat:{} at supervisor time-secs {}", workerId, state, whb, now);
    +            workerIdHbstate.put(workerId, new StateHeartbeat(state, whb));
    +        }
    +        return workerIdHbstate;
    +    }
    +
    +    protected boolean matchesAssignment(LSWorkerHeartbeat whb, Map<Integer, LocalAssignment> assignedExecutors) {
    +        LocalAssignment localAssignment = assignedExecutors.get(whb.get_port());
    +        if (localAssignment == null || !localAssignment.get_topology_id().equals(whb.get_topology_id())) {
    +            return false;
    +        }
    +        List<ExecutorInfo> executorInfos = new ArrayList<>();
    +        executorInfos.addAll(whb.get_executors());
    +        // remove SYSTEM_EXECUTOR_ID
    +        executorInfos.remove(SYSTEM_EXECUTOR_INFO);
    +        List<ExecutorInfo> localExecuorInfos = localAssignment.get_executors();
    +
    +        if (localExecuorInfos.size() != executorInfos.size())
    +            return false;
    +
    +        for (ExecutorInfo executorInfo : localExecuorInfos){
    +            if (!localExecuorInfos.contains(executorInfo))
    +                return false;
    +        }
    +        return true;
    +    }
    +
    +    /**
    +     * launch a worker in local mode.
    +     */
    +    protected void launchWorker(SupervisorData supervisorData, String stormId, Long port, String workerId, WorkerResources resources) throws IOException {
    +        // port this function after porting worker to java
    +    }
    +
    +    protected String getWorkerClassPath(String stormJar, Map stormConf) {
    +        List<String> topoClasspath = new ArrayList<>();
    +        Object object = stormConf.get(Config.TOPOLOGY_CLASSPATH);
    +
    +        if (object instanceof List) {
    +            topoClasspath.addAll((List<String>) object);
    +        } else if (object instanceof String){
    +            topoClasspath.add((String)object);
    +        }else {
    +            //ignore
    +        }
    +        String classPath = Utils.workerClasspath();
    +        String classAddPath = Utils.addToClasspath(classPath, Arrays.asList(stormJar));
    +        return Utils.addToClasspath(classAddPath, topoClasspath);
    +    }
    +
    +    /**
    +     * "Generates runtime childopts by replacing keys with topology-id, worker-id, port, mem-onheap"
    +     * 
    +     * @param value
    +     * @param workerId
    +     * @param stormId
    +     * @param port
    +     * @param memOnheap
    +     */
    +    public List<String> substituteChildopts(Object value, String workerId, String stormId, Long port, int memOnheap) {
    +        List<String> rets = new ArrayList<>();
    +        if (value instanceof String) {
    +            String string = (String) value;
    +            string = string.replace("%ID%", String.valueOf(port));
    +            string = string.replace("%WORKER-ID%", workerId);
    +            string = string.replace("%TOPOLOGY-ID%", stormId);
    +            string = string.replace("%WORKER-PORT%", String.valueOf(port));
    +            string = string.replace("%HEAP-MEM%", String.valueOf(memOnheap));
    +            String[] strings = string.split("\\s+");
    +            rets.addAll(Arrays.asList(strings));
    +        } else if (value instanceof List) {
    +            List<Object> objects = (List<Object>) value;
    +            for (Object object : objects) {
    +                String str = (String)object;
    +                str = str.replace("%ID%", String.valueOf(port));
    +                str = str.replace("%WORKER-ID%", workerId);
    +                str = str.replace("%TOPOLOGY-ID%", stormId);
    +                str = str.replace("%WORKER-PORT%", String.valueOf(port));
    +                str = str.replace("%HEAP-MEM%", String.valueOf(memOnheap));
    +                rets.add(str);
    +            }
    +        }
    +        return rets;
    +    }
    +
    +
    +
    +    /**
    +     * launch a worker in distributed mode
    +     * supervisorId for testing
    +     * @throws IOException
    +     */
    +    protected void launchWorker(Map conf, String supervisorId, String assignmentId, String stormId, Long port, String workerId,
    +            WorkerResources resources, CgroupManager cgroupManager, ConcurrentHashSet deadWorkers) throws IOException {
    +
    +        Boolean runWorkerAsUser = Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false);
    +        String stormHome = ConfigUtils.concatIfNotNull(System.getProperty("storm.home"));
    +        String stormOptions = ConfigUtils.concatIfNotNull(System.getProperty("storm.options"));
    +        String stormConfFile = ConfigUtils.concatIfNotNull(System.getProperty("storm.conf.file"));
    +        String workerTmpDir = ConfigUtils.workerTmpRoot(conf, workerId);
    +
    +        String stormLogDir = ConfigUtils.getLogDir();
    +        String stormLogConfDir = (String) (conf.get(Config.STORM_LOG4J2_CONF_DIR));
    +
    +        String stormLog4j2ConfDir;
    +        if (StringUtils.isNotBlank(stormLogConfDir)) {
    +            if (Utils.isAbsolutePath(stormLogConfDir)) {
    +                stormLog4j2ConfDir = stormLogConfDir;
    +            } else {
    +                stormLog4j2ConfDir = stormHome + Utils.FILE_PATH_SEPARATOR + stormLogConfDir;
    +            }
    +        } else {
    +            stormLog4j2ConfDir = stormHome + Utils.FILE_PATH_SEPARATOR + "log4j2";
    +        }
    +
    +        String stormRoot = ConfigUtils.supervisorStormDistRoot(conf, stormId);
    +
    +        String jlp = jlp(stormRoot, conf);
    +
    +        String stormJar = ConfigUtils.supervisorStormJarPath(stormRoot);
    +
    +        Map stormConf = ConfigUtils.readSupervisorStormConf(conf, stormId);
    +
    +        String workerClassPath = getWorkerClassPath(stormJar, stormConf);
    +
    +        Object topGcOptsObject = stormConf.get(Config.TOPOLOGY_WORKER_GC_CHILDOPTS);
    +        List<String> topGcOpts = new ArrayList<>();
    +        if (topGcOptsObject instanceof String) {
    +            topGcOpts.add((String) topGcOptsObject);
    +        } else if (topGcOptsObject instanceof List) {
    +            topGcOpts.addAll((List<String>) topGcOptsObject);
    +        }
    +
    +        int memOnheap = 0;
    +        if (resources.get_mem_on_heap() > 0) {
    +            memOnheap = (int) Math.ceil(resources.get_mem_on_heap());
    +        } else {
    +            //set the default heap memory size for supervisor-test
    +            memOnheap = Utils.getInt(stormConf.get(Config.WORKER_HEAP_MEMORY_MB), 768);
    +        }
    +
    +        int memoffheap = (int) Math.ceil(resources.get_mem_off_heap());
    +
    +        int cpu = (int) Math.ceil(resources.get_cpu());
    +
    +        List<String> gcOpts = null;
    +
    +        if (topGcOpts != null) {
    +            gcOpts = substituteChildopts(topGcOpts, workerId, stormId, port, memOnheap);
    +        } else {
    +            gcOpts = substituteChildopts(conf.get(Config.WORKER_GC_CHILDOPTS), workerId, stormId, port, memOnheap);
    +        }
    +
    +        Object topoWorkerLogwriterObject = stormConf.get(Config.TOPOLOGY_WORKER_LOGWRITER_CHILDOPTS);
    +        List<String> topoWorkerLogwriterChildopts = new ArrayList<>();
    +        if (topoWorkerLogwriterObject instanceof String) {
    +            topoWorkerLogwriterChildopts.add((String) topoWorkerLogwriterObject);
    +        } else if (topoWorkerLogwriterObject instanceof List) {
    +            topoWorkerLogwriterChildopts.addAll((List<String>) topoWorkerLogwriterObject);
    +        }
    +
    +        String user = (String) stormConf.get(Config.TOPOLOGY_SUBMITTER_USER);
    +
    +        String logfileName = "worker.log";
    +
    +        String workersArtifacets = ConfigUtils.workerArtifactsRoot(conf);
    +
    +        String loggingSensitivity = (String) stormConf.get(Config.TOPOLOGY_LOGGING_SENSITIVITY);
    +        if (loggingSensitivity == null) {
    +            loggingSensitivity = "S3";
    +        }
    +
    +        List<String> workerChildopts = substituteChildopts(conf.get(Config.WORKER_CHILDOPTS), workerId, stormId, port, memOnheap);
    +
    +        List<String> topWorkerChildopts = substituteChildopts(stormConf.get(Config.TOPOLOGY_WORKER_CHILDOPTS), workerId, stormId, port, memOnheap);
    +
    +        List<String> workerProfilerChildopts = null;
    +        if (Utils.getBoolean(conf.get(Config.WORKER_PROFILER_ENABLED), false)) {
    +            workerProfilerChildopts = substituteChildopts(conf.get(Config.WORKER_PROFILER_CHILDOPTS), workerId, stormId, port, memOnheap);
    +        }else {
    +            workerProfilerChildopts = new ArrayList<>();
    +        }
    +
    +        Map<String, String> topEnvironment = new HashMap<String, String>();
    +        Map<String, String> environment = (Map<String, String>) stormConf.get(Config.TOPOLOGY_ENVIRONMENT);
    +        if (environment != null) {
    +            topEnvironment.putAll(environment);
    +        }
    +        topEnvironment.put("LD_LIBRARY_PATH", jlp);
    +
    +        String log4jConfigurationFile = null;
    +        if (System.getProperty("os.name").startsWith("Windows") && !stormLog4j2ConfDir.startsWith("file:")) {
    +            log4jConfigurationFile = "file:///" + stormLog4j2ConfDir;
    +        } else {
    +            log4jConfigurationFile = stormLog4j2ConfDir;
    +        }
    +        log4jConfigurationFile = log4jConfigurationFile + Utils.FILE_PATH_SEPARATOR + "worker.xml";
    +
    +        List<String> commandList = new ArrayList<>();
    +        commandList.add(SupervisorUtils.javaCmd("java"));
    +        commandList.add("-cp");
    +        commandList.add(workerClassPath);
    +        commandList.addAll(topoWorkerLogwriterChildopts);
    +        commandList.add("-Dlogfile.name=" + logfileName);
    +        commandList.add("-Dstorm.home=" + stormHome);
    +        commandList.add("-Dworkers.artifacts=" + workersArtifacets);
    +        commandList.add("-Dstorm.id=" + stormId);
    +        commandList.add("-Dworker.id=" + workerId);
    +        commandList.add("-Dworker.port=" + port);
    +        commandList.add("-Dstorm.log.dir=" + stormLogDir);
    +        commandList.add("-Dlog4j.configurationFile=" + log4jConfigurationFile);
    +        commandList.add("-DLog4jContextSelector=org.apache.logging.log4j.core.selector.BasicContextSelector");
    +        commandList.add("org.apache.storm.LogWriter");
    +
    +        commandList.add(SupervisorUtils.javaCmd("java"));
    +        commandList.add("-server");
    +        commandList.addAll(workerChildopts);
    +        commandList.addAll(topWorkerChildopts);
    +        commandList.addAll(gcOpts);
    +        commandList.addAll(workerProfilerChildopts);
    +        commandList.add("-Djava.library.path=" + jlp);
    +        commandList.add("-Dlogfile.name=" + logfileName);
    +        commandList.add("-Dstorm.home=" + stormHome);
    +        commandList.add("-Dworkers.artifacts=" + workersArtifacets);
    +        commandList.add("-Dstorm.conf.file=" + stormConfFile);
    +        commandList.add("-Dstorm.options=" + stormOptions);
    +        commandList.add("-Dstorm.log.dir=" + stormLogDir);
    +        commandList.add("-Djava.io.tmpdir=" + workerTmpDir);
    +        commandList.add("-Dlogging.sensitivity=" + loggingSensitivity);
    +        commandList.add("-Dlog4j.configurationFile=" + log4jConfigurationFile);
    +        commandList.add("-DLog4jContextSelector=org.apache.logging.log4j.core.selector.BasicContextSelector");
    +        commandList.add("-Dstorm.id=" + stormId);
    +        commandList.add("-Dworker.id=" + workerId);
    +        commandList.add("-Dworker.port=" + port);
    +        commandList.add("-cp");
    +        commandList.add(workerClassPath);
    +        commandList.add("org.apache.storm.daemon.worker");
    +        commandList.add(stormId);
    +        commandList.add(assignmentId);
    +        commandList.add(String.valueOf(port));
    +        commandList.add(workerId);
    +
    +        // {"cpu" cpu "memory" (+ mem-onheap mem-offheap (int (Math/ceil (conf STORM-CGROUP-MEMORY-LIMIT-TOLERANCE-MARGIN-MB))))
    +        if (Utils.getBoolean(conf.get(Config.STORM_RESOURCE_ISOLATION_PLUGIN_ENABLE), false)) {
    +            int cgRoupMem = (int) (Math.ceil((double) conf.get(Config.STORM_CGROUP_MEMORY_LIMIT_TOLERANCE_MARGIN_MB)));
    +            int memoryValue = memoffheap + memOnheap + cgRoupMem;
    +            int cpuValue = cpu;
    +            Map<String, Number> map = new HashMap<>();
    +            map.put("cpu", cpuValue);
    +            map.put("memory", memoryValue);
    +            cgroupManager.reserveResourcesForWorker(workerId, map);
    +            commandList = cgroupManager.getLaunchCommand(workerId, commandList);
    +        }
    +
    +        LOG.info("Launching worker with command: {}. ", Utils.shellCmd(commandList));
    +        writeLogMetadata(stormConf, user, workerId, stormId, port, conf);
    +        ConfigUtils.setWorkerUserWSE(conf, workerId, user);
    +        createArtifactsLink(conf, stormId, port, workerId);
    +
    +        String logPrefix = "Worker Process " + workerId;
    +        String workerDir = ConfigUtils.workerRoot(conf, workerId);
    +
    +        if (deadWorkers != null)
    +            deadWorkers.remove(workerId);
    +        createBlobstoreLinks(conf, stormId, workerId);
    +
    +        ProcessExitCallback processExitCallback = new ProcessExitCallback(logPrefix, workerId);
    +        if (runWorkerAsUser) {
    +            List<String> args = new ArrayList<>();
    +            args.add("worker");
    +            args.add(workerDir);
    +            args.add(Utils.writeScript(workerDir, commandList, topEnvironment));
    +            SupervisorUtils.workerLauncher(conf, user, args, null, logPrefix, processExitCallback, new File(workerDir));
    +        } else {
    +            Utils.launchProcess(commandList, topEnvironment, logPrefix, processExitCallback, new File(workerDir));
    +        }
    +    }
    +
    +    protected String jlp(String stormRoot, Map conf) {
    +        String resourceRoot = stormRoot + Utils.FILE_PATH_SEPARATOR + ConfigUtils.RESOURCES_SUBDIR;
    +        String os = System.getProperty("os.name").replaceAll("\\s+", "_");
    +        String arch = System.getProperty("os.arch");
    +        String archResourceRoot = resourceRoot + Utils.FILE_PATH_SEPARATOR + os + "-" + arch;
    +        String ret = archResourceRoot + Utils.FILE_PATH_SEPARATOR + resourceRoot + Utils.FILE_PATH_SEPARATOR + conf.get(Config.JAVA_LIBRARY_PATH);
    +        return ret;
    +    }
    +
    +    protected Map<String, Integer> startNewWorkers(Map<Integer, String> newWorkerIds, Map<Integer, LocalAssignment> reassignExecutors) throws IOException {
    +
    +        Map<String, Integer> newValidWorkerIds = new HashMap<>();
    +        Map conf = supervisorData.getConf();
    +        String supervisorId = supervisorData.getSupervisorId();
    +        String clusterMode = ConfigUtils.clusterMode(conf);
    +
    +        for (Map.Entry<Integer, LocalAssignment> entry : reassignExecutors.entrySet()) {
    +            Integer port = entry.getKey();
    +            LocalAssignment assignment = entry.getValue();
    +            String workerId = newWorkerIds.get(port);
    +            String stormId = assignment.get_topology_id();
    +            WorkerResources resources = assignment.get_resources();
    +
    +            // This condition checks for required files exist before launching the worker
    +            if (SupervisorUtils.doRequiredTopoFilesExist(conf, stormId)) {
    +                String pidsPath = ConfigUtils.workerPidsRoot(conf, workerId);
    +                String hbPath = ConfigUtils.workerHeartbeatsRoot(conf, workerId);
    +
    +                LOG.info("Launching worker with assignment {} for this supervisor {} on port {} with id {}", assignment, supervisorData.getSupervisorId(), port,
    +                        workerId);
    +
    +                FileUtils.forceMkdir(new File(pidsPath));
    +                FileUtils.forceMkdir(new File(ConfigUtils.workerTmpRoot(conf, workerId)));
    +                FileUtils.forceMkdir(new File(hbPath));
    +
    +                if (clusterMode.endsWith("distributed")) {
    +                    launchWorker(conf, supervisorId, supervisorData.getAssignmentId(), stormId, port.longValue(), workerId, resources,
    +                            supervisorData.getResourceIsolationManager(), supervisorData.getDeadWorkers());
    +                } else if (clusterMode.endsWith("local")) {
    +                    launchWorker(supervisorData, stormId, port.longValue(), workerId, resources);
    +                }
    +                newValidWorkerIds.put(workerId, port);
    +
    +            } else {
    +                LOG.info("Missing topology storm code, so can't launch worker with assignment {} for this supervisor {} on port {} with id {}", assignment,
    +                        supervisorData.getSupervisorId(), port, workerId);
    +            }
    +
    +        }
    +        return newValidWorkerIds;
    +    }
    +
    +    public void writeLogMetadata(Map stormconf, String user, String workerId, String stormId, Long port, Map conf) throws IOException {
    +        Map data = new HashMap();
    +        data.put(Config.TOPOLOGY_SUBMITTER_USER, user);
    +        data.put("worker-id", workerId);
    +
    +        Set<String> logsGroups = new HashSet<>();
    +        //for supervisor-test
    +        if (stormconf.get(Config.LOGS_GROUPS) != null) {
    +            List<String> groups = (List<String>) stormconf.get(Config.LOGS_GROUPS);
    +            for (String group : groups){
    +                logsGroups.add(group);
    +            }
    +        }
    +        if (stormconf.get(Config.TOPOLOGY_GROUPS) != null) {
    +            List<String> topGroups = (List<String>) stormconf.get(Config.TOPOLOGY_GROUPS);
    +            for (String group : topGroups){
    +                logsGroups.add(group);
    +            }
    +        }
    +        data.put(Config.LOGS_GROUPS, logsGroups.toArray());
    +
    +        Set<String> logsUsers = new HashSet<>();
    +        if (stormconf.get(Config.LOGS_USERS) != null) {
    +            List<String> logUsers = (List<String>) stormconf.get(Config.LOGS_USERS);
    +            for (String logUser : logUsers){
    +                logsUsers.add(logUser);
    +            }
    +        }
    +        if (stormconf.get(Config.TOPOLOGY_USERS) != null) {
    +            List<String> topUsers = (List<String>) stormconf.get(Config.TOPOLOGY_USERS);
    +            for (String logUser : topUsers){
    +                logsUsers.add(logUser);
    +            }
    +        }
    +        data.put(Config.LOGS_USERS, logsUsers.toArray());
    +        writeLogMetadataToYamlFile(stormId, port, data, conf);
    +    }
    +
    +    /**
    +     * run worker as user needs the directory to have special permissions or it is insecure
    +     * 
    +     * @param stormId
    +     * @param port
    +     * @param data
    +     * @param conf
    +     * @throws IOException
    +     */
    +    public void writeLogMetadataToYamlFile(String stormId, Long port, Map data, Map conf) throws IOException {
    +        File file = ConfigUtils.getLogMetaDataFile(conf, stormId, port.intValue());
    +
    +        if (!Utils.checkFileExists(file.getParent())) {
    +            if (Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false)) {
    +                FileUtils.forceMkdir(file.getParentFile());
    +                SupervisorUtils.setupStormCodeDir(conf, ConfigUtils.readSupervisorStormConf(conf, stormId), file.getParentFile().getCanonicalPath());
    +            } else {
    +                file.getParentFile().mkdirs();
    +            }
    +        }
    +        FileWriter writer = new FileWriter(file);
    +        Yaml yaml = new Yaml();
    +        try {
    +            yaml.dump(data, writer);
    +        }finally {
    --- End diff --
    
    nit. space after } 


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#issuecomment-192118347
  
    success on supervisor test in my computer of  windows, but CI have 2 failures about supervisor-test.clj. I can't see the supervisor-test.xml. So I don't kown where failures come ? I didi some manual testing and things look good. I hope everyone can review it and give me some suggests. With my pressure!


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55583591
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/Supervisor.java ---
    @@ -0,0 +1,196 @@
    +/**
    + * 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.supervisor;
    +
    +import com.codahale.metrics.Gauge;
    +import com.codahale.metrics.MetricRegistry;
    +import org.apache.commons.io.FileUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.StormTimer;
    +import org.apache.storm.daemon.metrics.MetricsUtils;
    +import org.apache.storm.daemon.metrics.reporters.PreparableReporter;
    +import org.apache.storm.daemon.supervisor.timer.RunProfilerActions;
    +import org.apache.storm.daemon.supervisor.timer.SupervisorHealthCheck;
    +import org.apache.storm.daemon.supervisor.timer.SupervisorHeartbeat;
    +import org.apache.storm.daemon.supervisor.timer.UpdateBlobs;
    +import org.apache.storm.event.EventManagerImp;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.messaging.IContext;
    +import org.apache.storm.scheduler.ISupervisor;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.Utils;
    +import org.apache.storm.utils.VersionInfo;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.InterruptedIOException;
    +import java.util.Collection;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +
    +public class Supervisor {
    +    private static Logger LOG = LoggerFactory.getLogger(Supervisor.class);
    +
    +    //TODO: to be removed after porting worker.clj. localSyncProcess is intended to start local supervisor
    +    private SyncProcessEvent localSyncProcess;
    +
    +    public void setLocalSyncProcess(SyncProcessEvent localSyncProcess) {
    +        this.localSyncProcess = localSyncProcess;
    +    }
    +
    +
    +    /**
    +     * in local state, supervisor stores who its current assignments are another thread launches events to restart any dead processes if necessary
    +     * 
    +     * @param conf
    +     * @param sharedContext
    +     * @param iSupervisor
    +     * @return
    +     * @throws Exception
    +     */
    +    public SupervisorManger mkSupervisor(final Map conf, IContext sharedContext, ISupervisor iSupervisor) throws Exception {
    +        SupervisorManger supervisorManger = null;
    +        try {
    +            LOG.info("Starting Supervisor with conf {}", conf);
    +            iSupervisor.prepare(conf, ConfigUtils.supervisorIsupervisorDir(conf));
    +            String path = ConfigUtils.supervisorTmpDir(conf);
    +            FileUtils.cleanDirectory(new File(path));
    +
    +            final SupervisorData supervisorData = new SupervisorData(conf, sharedContext, iSupervisor);
    +            Localizer localizer = supervisorData.getLocalizer();
    +
    +            SupervisorHeartbeat hb = new SupervisorHeartbeat(conf, supervisorData);
    +            hb.run();
    +            // should synchronize supervisor so it doesn't launch anything after being down (optimization)
    +            Integer heartbeatFrequency = Utils.getInt(conf.get(Config.SUPERVISOR_HEARTBEAT_FREQUENCY_SECS));
    +            supervisorData.getHeartbeatTimer().scheduleRecurring(0, heartbeatFrequency, hb);
    +
    +            Set<String> downdedStormId = SupervisorUtils.readDownLoadedStormIds(conf);
    +            for (String stormId : downdedStormId) {
    +                SupervisorUtils.addBlobReferences(localizer, stormId, conf);
    +            }
    +            // do this after adding the references so we don't try to clean things being used
    +            localizer.startCleaner();
    +
    +            EventManagerImp syncSupEventManager = new EventManagerImp(false);
    +            EventManagerImp syncProcessManager = new EventManagerImp(false);
    +
    +            SyncProcessEvent syncProcessEvent = null;
    +            if (ConfigUtils.isLocalMode(conf)){
    +                localSyncProcess.init(supervisorData);
    +                syncProcessEvent = localSyncProcess;
    +            }else{
    +                syncProcessEvent = new SyncProcessEvent(supervisorData);
    +            }
    +
    +            SyncSupervisorEvent syncSupervisorEvent = new SyncSupervisorEvent(supervisorData, syncProcessEvent, syncSupEventManager, syncProcessManager);
    +            UpdateBlobs updateBlobsThread = new UpdateBlobs(supervisorData);
    +            RunProfilerActions runProfilerActionThread = new RunProfilerActions(supervisorData);
    +
    +            if ((Boolean) conf.get(Config.SUPERVISOR_ENABLE)) {
    +                StormTimer eventTimer = supervisorData.getEventTimer();
    +                // This isn't strictly necessary, but it doesn't hurt and ensures that the machine stays up
    +                // to date even if callbacks don't all work exactly right
    +                eventTimer.scheduleRecurring(0, 10, new EventManagerPushCallback(syncSupervisorEvent, syncSupEventManager));
    +
    +                eventTimer.scheduleRecurring(0, Utils.getInt(conf.get(Config.SUPERVISOR_MONITOR_FREQUENCY_SECS)),
    +                        new EventManagerPushCallback(syncProcessEvent, syncProcessManager));
    +
    +                // Blob update thread. Starts with 30 seconds delay, every 30 seconds
    +                supervisorData.getBlobUpdateTimer().scheduleRecurring(30, 30, new EventManagerPushCallback(updateBlobsThread, syncSupEventManager));
    +
    +                // supervisor health check
    +                eventTimer.scheduleRecurring(300, 300, new SupervisorHealthCheck(supervisorData));
    +
    +                // Launch a thread that Runs profiler commands . Starts with 30 seconds delay, every 30 seconds
    +                eventTimer.scheduleRecurring(30, 30, new EventManagerPushCallback(runProfilerActionThread, syncSupEventManager));
    +            }
    +            LOG.info("Starting supervisor with id {} at host {}.", supervisorData.getSupervisorId(), supervisorData.getHostName() );
    +            supervisorManger = new SupervisorManger(supervisorData, syncSupEventManager, syncProcessManager);
    +        } catch (Throwable t) {
    +            if (Utils.exceptionCauseIsInstanceOf(InterruptedIOException.class, t)) {
    +                throw t;
    +            } else if (Utils.exceptionCauseIsInstanceOf(InterruptedException.class, t)) {
    +                throw t;
    +            } else {
    +                LOG.error("Error on initialization of server supervisor: {}", t);
    +                Utils.exitProcess(13, "Error on initialization");
    +            }
    +        }
    +        return supervisorManger;
    +    }
    +
    +    /**
    +     * start distribute supervisor
    +     */
    +    private void launch() {
    --- End diff --
    
    In the short term `launch` should be static and take an instance of ISupervisor as a parameter.  This is required to continue to support some projects like storm on mesos.
    
    https://github.com/mesos/storm/blob/master/storm/src/main/storm/mesos/MesosSupervisor.java#L58 


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r55732854
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SupervisorUtils.java ---
    @@ -0,0 +1,273 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.curator.utils.PathUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.localizer.LocalResource;
    +import org.apache.storm.localizer.Localizer;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Utils;
    +import org.apache.zookeeper.ZooDefs;
    +import org.apache.zookeeper.data.ACL;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.File;
    +import java.io.IOException;
    +import java.net.URLDecoder;
    +import java.util.*;
    +
    +public class SupervisorUtils {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(SupervisorUtils.class);
    +
    +    private static final SupervisorUtils INSTANCE = new SupervisorUtils();
    +    private static SupervisorUtils _instance = INSTANCE;
    +
    +    public static void setInstance(SupervisorUtils u) {
    +        _instance = u;
    +    }
    +
    +    public static void resetInstance() {
    +        _instance = INSTANCE;
    +    }
    +
    +    public static Process workerLauncher(Map conf, String user, List<String> args, Map<String, String> environment, final String logPreFix,
    --- End diff --
    
    Thank you for the clarification. runAsUser sounds like a good name for this API. It is also possible to always pass user in the API signatures. If SUPERVISOR_WORKER_LAUNCHER is not enabled, the user argument will be local user and ignored in the implementation. Otherwise, commands will be launched with that user's permission. The implementation can be prepared when supervisor starts up. 


---
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-1279] port backtype.storm.daemon.superv...

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

    https://github.com/apache/storm/pull/1184#discussion_r57185550
  
    --- Diff: storm-core/src/jvm/org/apache/storm/daemon/supervisor/SyncProcessEvent.java ---
    @@ -0,0 +1,428 @@
    +/**
    + * 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.supervisor;
    +
    +import org.apache.commons.io.FileUtils;
    +import org.apache.commons.lang.StringUtils;
    +import org.apache.storm.Config;
    +import org.apache.storm.container.cgroup.CgroupManager;
    +import org.apache.storm.daemon.supervisor.workermanager.IWorkerManager;
    +import org.apache.storm.generated.ExecutorInfo;
    +import org.apache.storm.generated.LSWorkerHeartbeat;
    +import org.apache.storm.generated.LocalAssignment;
    +import org.apache.storm.generated.WorkerResources;
    +import org.apache.storm.utils.ConfigUtils;
    +import org.apache.storm.utils.LocalState;
    +import org.apache.storm.utils.Time;
    +import org.apache.storm.utils.Utils;
    +import org.eclipse.jetty.util.ConcurrentHashSet;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +import org.yaml.snakeyaml.Yaml;
    +
    +import java.io.File;
    +import java.io.FileWriter;
    +import java.io.IOException;
    +import java.util.*;
    +
    +/**
    + * 1. to kill are those in allocated that are dead or disallowed 2. kill the ones that should be dead - read pids, kill -9 and individually remove file - rmr
    + * heartbeat dir, rmdir pid dir, rmdir id dir (catch exception and log) 3. of the rest, figure out what assignments aren't yet satisfied 4. generate new worker
    + * ids, write new "approved workers" to LS 5. create local dir for worker id 5. launch new workers (give worker-id, port, and supervisor-id) 6. wait for workers
    + * launch
    + */
    +public class SyncProcessEvent implements Runnable {
    +
    +    private static Logger LOG = LoggerFactory.getLogger(SyncProcessEvent.class);
    +
    +    private  LocalState localState;
    +    private  SupervisorData supervisorData;
    +    public static final ExecutorInfo SYSTEM_EXECUTOR_INFO = new ExecutorInfo(-1, -1);
    +
    +    private class ProcessExitCallback implements Utils.ExitCodeCallable {
    +        private final String logPrefix;
    +        private final String workerId;
    +
    +        public ProcessExitCallback(String logPrefix, String workerId) {
    +            this.logPrefix = logPrefix;
    +            this.workerId = workerId;
    +        }
    +
    +        @Override
    +        public Object call() throws Exception {
    +            return null;
    +        }
    +
    +        @Override
    +        public Object call(int exitCode) {
    +            LOG.info("{} exited with code: {}", logPrefix, exitCode);
    +            supervisorData.getDeadWorkers().add(workerId);
    +            return null;
    +        }
    +    }
    +
    +    public SyncProcessEvent(){
    +
    +    }
    +    public SyncProcessEvent(SupervisorData supervisorData) {
    +        init(supervisorData);
    +    }
    +
    +    //TODO: initData is intended to local supervisor, so we will remove them after porting worker.clj to java
    +    public void init(SupervisorData supervisorData){
    +        this.supervisorData = supervisorData;
    +        this.localState = supervisorData.getLocalState();
    +    }
    +
    +    @Override
    +    public void run() {
    +        LOG.debug("Syncing processes");
    +        try {
    +            Map conf = supervisorData.getConf();
    +            Map<Integer, LocalAssignment> assignedExecutors = localState.getLocalAssignmentsMap();
    +
    +            if (assignedExecutors == null) {
    +                assignedExecutors = new HashMap<>();
    +            }
    +            int now = Time.currentTimeSecs();
    +
    +            Map<String, StateHeartbeat> localWorkerStats = getLocalWorkerStats(supervisorData, assignedExecutors, now);
    +
    +            Set<String> keeperWorkerIds = new HashSet<>();
    +            Set<Integer> keepPorts = new HashSet<>();
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() == State.VALID) {
    +                    keeperWorkerIds.add(entry.getKey());
    +                    keepPorts.add(stateHeartbeat.getHeartbeat().get_port());
    +                }
    +            }
    +            Map<Integer, LocalAssignment> reassignExecutors = getReassignExecutors(assignedExecutors, keepPorts);
    +            Map<Integer, String> newWorkerIds = new HashMap<>();
    +            for (Integer port : reassignExecutors.keySet()) {
    +                newWorkerIds.put(port, Utils.uuid());
    +            }
    +            LOG.debug("Syncing processes");
    +            LOG.debug("Assigned executors: {}", assignedExecutors);
    +            LOG.debug("Allocated: {}", localWorkerStats);
    +
    +            for (Map.Entry<String, StateHeartbeat> entry : localWorkerStats.entrySet()) {
    +                StateHeartbeat stateHeartbeat = entry.getValue();
    +                if (stateHeartbeat.getState() != State.VALID) {
    +                    LOG.info("Shutting down and clearing state for id {}, Current supervisor time: {}, State: {}, Heartbeat: {}", entry.getKey(), now,
    +                            stateHeartbeat.getState(), stateHeartbeat.getHeartbeat());
    +                    shutWorker(supervisorData, supervisorData.getWorkerManager(), entry.getKey());
    +                }
    +            }
    +            // start new workers
    +            Map<String, Integer> newWorkerPortToIds = startNewWorkers(newWorkerIds, reassignExecutors);
    +
    +            Map<String, Integer> allWorkerPortToIds = new HashMap<>();
    +            Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +            for (String keeper : keeperWorkerIds) {
    +                allWorkerPortToIds.put(keeper, approvedWorkers.get(keeper));
    +            }
    +            allWorkerPortToIds.putAll(newWorkerPortToIds);
    +            localState.setApprovedWorkers(allWorkerPortToIds);
    +            waitForWorkersLaunch(conf, newWorkerPortToIds.keySet());
    +
    +        } catch (Exception e) {
    +            LOG.error("Failed Sync Process", e);
    +            throw Utils.wrapInRuntime(e);
    +        }
    +
    +    }
    +
    +    protected void waitForWorkersLaunch(Map conf, Set<String> workerIds) throws Exception {
    +        int startTime = Time.currentTimeSecs();
    +        int timeOut = (int) conf.get(Config.NIMBUS_SUPERVISOR_TIMEOUT_SECS);
    +        for (String workerId : workerIds) {
    +            LocalState localState = ConfigUtils.workerState(conf, workerId);
    +            while (true) {
    +                LSWorkerHeartbeat hb = localState.getWorkerHeartBeat();
    +                if (hb != null || (Time.currentTimeSecs() - startTime) > timeOut)
    +                    break;
    +                LOG.info("{} still hasn't started", workerId);
    +                Time.sleep(500);
    +            }
    +            if (localState.getWorkerHeartBeat() == null) {
    +                LOG.info("Worker {} failed to start", workerId);
    +            }
    +        }
    +    }
    +
    +    protected Map<Integer, LocalAssignment> getReassignExecutors(Map<Integer, LocalAssignment> assignExecutors, Set<Integer> keepPorts) {
    +        Map<Integer, LocalAssignment> reassignExecutors = new HashMap<>();
    +        reassignExecutors.putAll(assignExecutors);
    +        for (Integer port : keepPorts) {
    +            reassignExecutors.remove(port);
    +        }
    +        return reassignExecutors;
    +    }
    +    
    +    /**
    +     * Returns map from worker id to worker heartbeat. if the heartbeat is nil, then the worker is dead
    +     * 
    +     * @param assignedExecutors
    +     * @return
    +     * @throws Exception
    +     */
    +    public Map<String, StateHeartbeat> getLocalWorkerStats(SupervisorData supervisorData, Map<Integer, LocalAssignment> assignedExecutors, int now) throws Exception {
    +        Map<String, StateHeartbeat> workerIdHbstate = new HashMap<>();
    +        Map conf = supervisorData.getConf();
    +        LocalState localState = supervisorData.getLocalState();
    +        Map<String, LSWorkerHeartbeat> idToHeartbeat = SupervisorUtils.readWorkerHeartbeats(conf);
    +        Map<String, Integer> approvedWorkers = localState.getApprovedWorkers();
    +        Set<String> approvedIds = new HashSet<>();
    +        if (approvedWorkers != null) {
    +            approvedIds.addAll(approvedWorkers.keySet());
    +        }
    +        for (Map.Entry<String, LSWorkerHeartbeat> entry : idToHeartbeat.entrySet()) {
    +            String workerId = entry.getKey();
    +            LSWorkerHeartbeat whb = entry.getValue();
    +            State state;
    +            if (whb == null) {
    +                state = State.NOT_STARTED;
    +            } else if (!approvedIds.contains(workerId) || !matchesAssignment(whb, assignedExecutors)) {
    +                state = State.DISALLOWED;
    +            } else if (supervisorData.getDeadWorkers().contains(workerId)) {
    +                LOG.info("Worker Process {} has died", workerId);
    +                state = State.TIMED_OUT;
    +            } else if (SupervisorUtils.isWorkerHbTimedOut(now, whb, conf)) {
    +                state = State.TIMED_OUT;
    +            } else {
    +                state = State.VALID;
    +            }
    +            LOG.debug("Worker:{} state:{} WorkerHeartbeat:{} at supervisor time-secs {}", workerId, state, whb, now);
    +            workerIdHbstate.put(workerId, new StateHeartbeat(state, whb));
    +        }
    +        return workerIdHbstate;
    +    }
    +
    +    protected boolean matchesAssignment(LSWorkerHeartbeat whb, Map<Integer, LocalAssignment> assignedExecutors) {
    +        LocalAssignment localAssignment = assignedExecutors.get(whb.get_port());
    +        if (localAssignment == null || !localAssignment.get_topology_id().equals(whb.get_topology_id())) {
    +            return false;
    +        }
    +        List<ExecutorInfo> executorInfos = new ArrayList<>();
    +        executorInfos.addAll(whb.get_executors());
    +        // remove SYSTEM_EXECUTOR_ID
    +        executorInfos.remove(SYSTEM_EXECUTOR_INFO);
    +        List<ExecutorInfo> localExecuorInfos = localAssignment.get_executors();
    +
    +        if (localExecuorInfos.size() != executorInfos.size())
    +            return false;
    +
    +        for (ExecutorInfo executorInfo : localExecuorInfos){
    +            if (!localExecuorInfos.contains(executorInfo))
    +                return false;
    +        }
    +        return true;
    +    }
    +
    +    /**
    +     * launch a worker in local mode.
    +     */
    +    protected void launchLocalWorker(SupervisorData supervisorData, String stormId, Long port, String workerId, WorkerResources resources) throws IOException {
    +        // port this function after porting worker to java
    +    }
    +
    +    protected void launchDistributedWorker(IWorkerManager workerManager, Map conf, String supervisorId, String assignmentId, String stormId, Long port, String workerId,
    +                                           WorkerResources resources, ConcurrentHashSet deadWorkers) throws IOException {
    +        Map stormConf = ConfigUtils.readSupervisorStormConf(conf, stormId);
    +        String user = (String) stormConf.get(Config.TOPOLOGY_SUBMITTER_USER);
    +        writeLogMetadata(stormConf, user, workerId, stormId, port, conf);
    +        ConfigUtils.setWorkerUserWSE(conf, workerId, user);
    +        createArtifactsLink(conf, stormId, port, workerId);
    +
    +        String logPrefix = "Worker Process " + workerId;
    +        if (deadWorkers != null)
    +            deadWorkers.remove(workerId);
    +        createBlobstoreLinks(conf, stormId, workerId);
    +        ProcessExitCallback processExitCallback = new ProcessExitCallback(logPrefix, workerId);
    +        workerManager.launchWorker(supervisorId, assignmentId, stormId, port, workerId, resources, processExitCallback);
    +    }
    +
    +    protected Map<String, Integer> startNewWorkers(Map<Integer, String> newWorkerIds, Map<Integer, LocalAssignment> reassignExecutors) throws IOException {
    +
    +        Map<String, Integer> newValidWorkerIds = new HashMap<>();
    +        Map conf = supervisorData.getConf();
    +        String supervisorId = supervisorData.getSupervisorId();
    +        String clusterMode = ConfigUtils.clusterMode(conf);
    +
    +        for (Map.Entry<Integer, LocalAssignment> entry : reassignExecutors.entrySet()) {
    +            Integer port = entry.getKey();
    +            LocalAssignment assignment = entry.getValue();
    +            String workerId = newWorkerIds.get(port);
    +            String stormId = assignment.get_topology_id();
    +            WorkerResources resources = assignment.get_resources();
    +
    +            // This condition checks for required files exist before launching the worker
    +            if (SupervisorUtils.doRequiredTopoFilesExist(conf, stormId)) {
    +                String pidsPath = ConfigUtils.workerPidsRoot(conf, workerId);
    +                String hbPath = ConfigUtils.workerHeartbeatsRoot(conf, workerId);
    +
    +                LOG.info("Launching worker with assignment {} for this supervisor {} on port {} with id {}", assignment, supervisorData.getSupervisorId(), port,
    +                        workerId);
    +
    +                FileUtils.forceMkdir(new File(pidsPath));
    +                FileUtils.forceMkdir(new File(ConfigUtils.workerTmpRoot(conf, workerId)));
    +                FileUtils.forceMkdir(new File(hbPath));
    +
    +                if (clusterMode.endsWith("distributed")) {
    +                    launchDistributedWorker(supervisorData.getWorkerManager(), conf, supervisorId, supervisorData.getAssignmentId(), stormId, port.longValue(), workerId, resources, supervisorData.getDeadWorkers());
    +                } else if (clusterMode.endsWith("local")) {
    +                    launchLocalWorker(supervisorData, stormId, port.longValue(), workerId, resources);
    +                }
    +                newValidWorkerIds.put(workerId, port);
    +
    +            } else {
    +                LOG.info("Missing topology storm code, so can't launch worker with assignment {} for this supervisor {} on port {} with id {}", assignment,
    +                        supervisorData.getSupervisorId(), port, workerId);
    +            }
    +
    +        }
    +        return newValidWorkerIds;
    +    }
    +
    +    public void writeLogMetadata(Map stormconf, String user, String workerId, String stormId, Long port, Map conf) throws IOException {
    +        Map data = new HashMap();
    +        data.put(Config.TOPOLOGY_SUBMITTER_USER, user);
    +        data.put("worker-id", workerId);
    +
    +        Set<String> logsGroups = new HashSet<>();
    +        //for supervisor-test
    +        if (stormconf.get(Config.LOGS_GROUPS) != null) {
    +            List<String> groups = (List<String>) stormconf.get(Config.LOGS_GROUPS);
    +            for (String group : groups){
    +                logsGroups.add(group);
    +            }
    +        }
    +        if (stormconf.get(Config.TOPOLOGY_GROUPS) != null) {
    +            List<String> topGroups = (List<String>) stormconf.get(Config.TOPOLOGY_GROUPS);
    +            logsGroups.addAll(topGroups);
    +        }
    +        data.put(Config.LOGS_GROUPS, logsGroups.toArray());
    +
    +        Set<String> logsUsers = new HashSet<>();
    +        if (stormconf.get(Config.LOGS_USERS) != null) {
    +            List<String> logUsers = (List<String>) stormconf.get(Config.LOGS_USERS);
    +            for (String logUser : logUsers){
    +                logsUsers.add(logUser);
    +            }
    +        }
    +        if (stormconf.get(Config.TOPOLOGY_USERS) != null) {
    +            List<String> topUsers = (List<String>) stormconf.get(Config.TOPOLOGY_USERS);
    +            for (String logUser : topUsers){
    +                logsUsers.add(logUser);
    +            }
    +        }
    +        data.put(Config.LOGS_USERS, logsUsers.toArray());
    +        writeLogMetadataToYamlFile(stormId, port, data, conf);
    +    }
    +
    +    /**
    +     * run worker as user needs the directory to have special permissions or it is insecure
    +     * 
    +     * @param stormId
    +     * @param port
    +     * @param data
    +     * @param conf
    +     * @throws IOException
    +     */
    +    public void writeLogMetadataToYamlFile(String stormId, Long port, Map data, Map conf) throws IOException {
    +        File file = ConfigUtils.getLogMetaDataFile(conf, stormId, port.intValue());
    +
    +        if (!Utils.checkFileExists(file.getParent())) {
    +            if (Utils.getBoolean(conf.get(Config.SUPERVISOR_RUN_WORKER_AS_USER), false)) {
    +                FileUtils.forceMkdir(file.getParentFile());
    +                SupervisorUtils.setupStormCodeDir(conf, ConfigUtils.readSupervisorStormConf(conf, stormId), file.getParentFile().getCanonicalPath());
    +            } else {
    +                file.getParentFile().mkdirs();
    +            }
    +        }
    +        FileWriter writer = new FileWriter(file);
    +        Yaml yaml = new Yaml();
    +        try {
    +            yaml.dump(data, writer);
    +        }finally {
    +            writer.close();
    +        }
    +    }
    +
    +    /**
    +     * Create a symlink from workder directory to its port artifacts directory
    +     * 
    +     * @param conf
    +     * @param stormId
    +     * @param port
    +     * @param workerId
    +     */
    +    protected void createArtifactsLink(Map conf, String stormId, Long port, String workerId) throws IOException {
    +        String workerDir = ConfigUtils.workerRoot(conf, workerId);
    +        String topoDir = ConfigUtils.workerArtifactsRoot(conf, stormId);
    +        if (Utils.checkFileExists(workerDir)) {
    +            Utils.createSymlink(workerDir, topoDir, "artifacts", String.valueOf(port));
    +        }
    +    }
    +
    +    /**
    +     * Create symlinks in worker launch directory for all blobs
    +     * 
    +     * @param conf
    +     * @param stormId
    +     * @param workerId
    +     * @throws IOException
    +     */
    +    protected void createBlobstoreLinks(Map conf, String stormId, String workerId) throws IOException {
    +        String stormRoot = ConfigUtils.supervisorStormDistRoot(conf, stormId);
    +        Map stormConf = ConfigUtils.readSupervisorStormConf(conf, stormId);
    +        String workerRoot = ConfigUtils.workerRoot(conf, workerId);
    +        Map<String, Map<String, Object>> blobstoreMap = (Map<String, Map<String, Object>>) stormConf.get(Config.TOPOLOGY_BLOBSTORE_MAP);
    +        List<String> blobFileNames = new ArrayList<>();
    +        if (blobstoreMap != null) {
    +            for (Map.Entry<String, Map<String, Object>> entry : blobstoreMap.entrySet()) {
    +                String key = entry.getKey();
    +                Map<String, Object> blobInfo = entry.getValue();
    +                String ret = null;
    +                if (blobInfo != null && blobInfo.containsKey("localname")) {
    +                    ret = (String) blobInfo.get("localname");
    +                } else {
    +                    ret = key;
    +                }
    +                blobFileNames.add(ret);
    +            }
    +        }
    +        List<String> resourceFileNames = new ArrayList<>();
    +        resourceFileNames.add(ConfigUtils.RESOURCES_SUBDIR);
    +        resourceFileNames.addAll(blobFileNames);
    +        LOG.info("Creating symlinks for worker-id: {} storm-id: {} for files({}): {}", workerId, stormId, resourceFileNames.size(), resourceFileNames);
    +        Utils.createSymlink(workerRoot, stormRoot, ConfigUtils.RESOURCES_SUBDIR);
    +        for (String fileName : blobFileNames) {
    +            Utils.createSymlink(workerRoot, stormRoot, fileName, fileName);
    +        }
    +    }
    +
    +    public void shutWorker(SupervisorData supervisorData, IWorkerManager workerManager, String workerId) throws IOException, InterruptedException{
    --- End diff --
    
    @jerrypeng  for integration test, I can not explain it clearly. You can refer to the code as follows 
    ```
    (defmacro capture-changed-workers
      [& body]
      `(let [launch-captured# (atom {})
             shutdown-captured# (atom {})]
         (with-var-roots [local-supervisor/launch-local-worker (mk-capture-launch-fn launch-captured#)
                          local-supervisor/shutdown-local-worker (mk-capture-shutdown-fn shutdown-captured#)]
                         ~@body
                         {:launched @launch-captured#
                          :shutdown @shutdown-captured#})))
    ```
    ```
    (defn local-process []
      "Create a local process event"
      (proxy [SyncProcessEvent] []
        (launchLocalWorker [supervisorData stormId port workerId resources]
          (launch-local-worker supervisorData stormId port workerId resources))
        (shutWorker [supervisorData worker-manager workerId] (shutdown-local-worker supervisorData worker-manager workerId))))
    ```


---
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.
---