【问题标题】:stop multiple service controller queries inside NodeJs promise while loop在 NodeJs Promise while 循环中停止多个服务控制器查询
【发布时间】:2018-06-26 09:03:42
【问题描述】:

我正在尝试从节点脚本启动 Windows 服务。该服务有挂起的坏习惯,有时需要重试才能成功启动。我有一个承诺,而循环设置(请随时提出更好的方法)。我遇到的问题是,每个循环sc.pollInterval 输出都会在控制台中写入重复的结果。下面是我在控制台中看到的重复内容的示例,这是在循环的第二次迭代之后,我希望它只显示该内容一次。

sc \\abnf34873 start ColdFusion 10 Application Server

sc \\abnf34873 queryex ColdFusion 10 Application Server

SERVICE_NAME: ColdFusion 10 Application Server
        TYPE               : 10  WIN32_OWN_PROCESS
        STATE              : 2  START_PENDING
                                (NOT_STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)
        WIN32_EXIT_CODE    : 0  (0x0)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x7d0
        PID                : 0
        FLAGS              :

SERVICE_NAME: ColdFusion 10 Application Server
        TYPE               : 10  WIN32_OWN_PROCESS
        STATE              : 2  START_PENDING
                                (NOT_STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)
        WIN32_EXIT_CODE    : 0  (0x0)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x7d0
        PID                : 13772
        FLAGS              :

这是我的代码。基本上,我将尝试启动服务 3 次。如果没有,那么我会抛出错误。需要注意的一件事是,当我尝试启动服务但它停留在“Start_pending”状态时,我终止了该进程,然后尝试再次启动它。

var retryCount = 0;

// Start the colfusion service
gulp.task('start-coldfusion-service', function(done) {
    var serviceStarted = false;
    console.log("Starting coldfusion service..");
    // This says we're going to ask where it's at every 30 seconds until it's in the desired state.
    sc.pollInterval(30);
    sc.timeout(60);
    retryCount = 0;

    tryServiceStart().then(function(result) {
          // process final result here
        done();
    }).catch(function(err) {
        // process error here
    });
});


function tryServiceStart() {
    return startService().then(function(serviceStarted) {
        if (serviceStarted == false) {
            console.log("Retry Count: " + retryCount);
            // Try again..
            return tryServiceStart();
        } else {
             return result;
        }
    });
}

function startService() {
    return new Promise(function(resolve, reject) {
        var started = true;
        // Make sure the coldfusion service exists on the target server
        sc.query(targetServer, { name: 'ColdFusion 10 Application Server'}).done(function(services) {
            // if the service exists and it is currentl stopped, then we're going to start it.
            if (services.length == 1) {
                var pid = services[0].pid;
                if (services[0].state.name == 'STOPPED') {
                    sc.start(targetServer, 'ColdFusion 10 Application Server')
                        .catch(function(error) {
                            started = false;
                            console.log("Problem starting Coldfusion service! error message: " + error.message);
                            console.log("retrying...");
                            retryCount++;
                            if (parseInt(retryCount) > 2) {
                                throw Error(error.message);
                            }
                       })
                       .done(function(displayName) {
                            if (started) {
                                console.log('Coldfusion service started successfully!');
                            }
                            resolve(started);
                       });
                } else if (services[0].state.name == 'START_PENDING') {
                    kill(pid, {force: true}).catch(function (err) {
                        console.log('Problem killing process..');
                    }).then(function() {
                        console.log('Killed hanging process..');
                        resolve(false);
                    });
                }
            } else {
                console.log("Could not find the service in a stopped state.");
                resolve(false);
            }
        });
   });
}

【问题讨论】:

  • service-control-manager 包声称“所有命令都返回一个承诺”,但是文档(您的代码正确遵守)告诉我们这些所谓的承诺具有 .done().catch() 方法。尚不清楚.done() 是否具有正确的.then() 的全部功能,或者.done() 是否只是像jQuery 的.done() 那样的蹩脚的东西。这些例子表明后者,我没有在网上找到任何告诉我的东西。
  • 感谢@Roamer-1888 提供的信息。我相信你是对的,因为它类似于 JQuery 的 .done() 方法,因为它内部的任何内容每次都会执行,无论承诺被拒绝还是解决。无论如何,我找到了一个我很高兴使用 Promise-retry 包的解决方案。我会尽快发布新代码作为答案。
  • Jmh2013,我今天早些时候玩了一些想法。当我回到我的桌面时,我会将它们作为答案发布。

标签: javascript node.js promise gulp service-control-manager


【解决方案1】:

不太清楚为什么会在控制台中得到重复的结果,但是下面是一些关于如何更好地编写代码的想法,主要是通过在最低级别进行承诺。

非常接近最初的概念,我最终得到了这个......

Promisify sc 命令

  • sc 命令返回类似于 Promise 的内容,但使用 .done() 方法,该方法很可能不具备真正的 .then() 的全部功能
  • 承诺每个命令为.xxxAsync()
  • 通过采用每个命令的.done.then,Promise.resolve() 应该能够同化命令返回的类似promise 的东西。
;(function() {
    commands.forEach(command => {
        sc[command].then = sc[command].done;
        sc[command + 'Async'] = function() {
            return Promise.resolve(sc[command](...arguments)); 
        };
    }).
}(['start', 'query'])); // add other commands as required

gulp.task()

  • 如果服务打开,promise 链遵循成功路径,否则遵循错误路径
  • 无需测试result 即可检测成功路径中的错误情况。
gulp.task('start-coldfusion-service', function(done) {
    console.log('Starting coldfusion service..');
    // This says we're going to ask where it's at every 30 seconds until it's in the desired state.
    sc.pollInterval(30);
    sc.timeout(60);
    tryServiceStart(2) // tryServiceStart(maxRetries)
    .then(done) // success! The service was started.
    .catch(function(err) {
        // the only error to end up here should be 'Maximum tries reached'.
        console.err(err);
        // process error here if necessary
    });
});

tryServiceStart()

  • 在此处重试编排
function tryServiceStart(maxRetries) {
    return startService()
    // .then(() => {}) // success! No action required here, just stay on the success path.
    .catch((error) => {
        // all throws from startService() end up here
        console.error(error); // log intermediate/final error
        if(--maxRetries > 0) {
            return tryServiceStart();
        } else {
            throw new Error('Maximum tries reached');
        }
    });
}

startService()

  • 通过调用sc.query()sc.start()的promisified版本形成一个功能齐全的promise链
  • console.log() 被清除以支持投掷。
  • 抛出的错误将被捕获并记录回tryServiceStart()
function startService() {
    // Make sure the coldfusion service exists on the target server
    return sc.queryAsync(targetServer, { name: 'ColdFusion 10 Application Server'})
    .then((services) => {
        // if the service exists and it is currently stopped, then start it.
        if (services.length == 1) {
            switch(services[0].state.name) {
                case 'STOPPED':
                    return sc.startAsync(targetServer, 'ColdFusion 10 Application Server')
                    .catch((error) => {
                        throw new Error("Problem starting Coldfusion service! error message: " + error.message);
                    });
                break;
                case 'START_PENDING':
                    return kill(services[0].pid, { 'force': true })
                    .then(() => {
                        throw new Error('Killed hanging process..'); // successful kill but still an error as far as startService() is concerned.
                    })
                    .catch((err) => {
                        throw new Error('Problem killing process..');
                    });
                break;
                default:
                    throw new Error("Service not in a stopped state.");
            }
        } else {
            throw new Error('Could not find the service.');
        }
    });
}

仅检查语法错误,因此可能需要调试。

提供 FWIW。酌情随意采用/突袭。

【讨论】:

  • 抱歉回复晚了,我刚刚放假了。我真的很喜欢你在这里所做的。不过,我仍然在控制台中得到重复的结果。 promise-retry 包为我解决了这个问题。所以我删除了tryServiceStart() 函数并使用Promise-retry 包在“start-coldfusion-service”任务中编排重试。我采用了我的代码来密切匹配您在此处的代码。我特别喜欢错误会像现在这样冒出来。
  • 我不确定是什么导致了重复的结果,或者为什么 Promise-retry 应该修复它们。我的代码行为和 Promise-retry 之间一定有一些细微的区别,但对于我的生活,我想不出它可能是什么。无论如何,重要的是你有一个解决方案。祝你好运。
【解决方案2】:

我发现了另一个名为 promise-retry 的 npm 包,它似乎解决了我遇到的问题。同时,我相信它使我的代码更清楚地知道它在做什么。

gulp.task('start-coldfusion-service', function(done) {
    var serviceStarted = false;
    console.log("Starting coldfusion service..");
    // Since starting a service on another server isn't exactly fast, we have to poll the status of it.
    // This says we're going to ask where it's at every 30 seconds until it's in the desired state.
    sc.pollInterval(30);
    sc.timeout(60);     

    promiseRetry({retries: 3}, function (retry, number) {
        console.log('attempt number', number);

        return startService()
        .catch(function (err) {
            console.log(err);
            if (err.code === 'ETIMEDOUT') {
                retry(err);
            } else if (err === 'killedProcess') {
                retry(err);
            }

            throw Error(err);
        });
    })
    .then(function (value) {
        done();
    }, function (err) {
        console.log("Unable to start the service after 3 tries!");
        process.exit();
    });

});

function startService() {
    var errorMsg = "";
    return new Promise(function(resolve, reject) {
        var started = true;
        // Make sure the coldfusion service exists on the target server
        sc.query(targetServer, { name: 'ColdFusion 10 Application Server'}).done(function(services) {
            // if the service exists and it is currentl stopped, then we're going to start it.
            if (services.length == 1) {
                var pid = services[0].pid;
                if (services[0].state.name == 'STOPPED') {
                    sc.start(targetServer, 'ColdFusion 10 Application Server')
                        .catch(function(error) {
                            started = false;
                            errorMsg = error;
                            console.log("Problem starting Coldfusion service! error message: " + error.message);
                            console.log("retrying...");
                       })
                       .done(function(displayName) {
                            if (started) {
                                console.log('Coldfusion service started successfully!');
                                resolve(started);
                            } else {
                                reject(errorMsg);
                            }
                       });
                } else if (services[0].state.name == 'START_PENDING') {
                    kill(pid, {force: true}).catch(function (err) {
                        console.log('Problem killing process..');
                    }).then(function() {
                        console.log('Killed hanging process..');
                        reject("killedProcess");
                    });
                } else {
                    // Must already be started..
                    resolve(true);
                }
            } else {
                console.log("Could not find the service in a stopped state.");
                resolve(false);
            }
        });

   });

}

【讨论】:

  • 小心kill(),它返回(我们假设)一个Promise。如果是这样,那么使用kill(...).catch(...).then(...);,除非catch 回调抛出/重新执行,否则执行将下降到then 回调。您将在我的解决方案中看到我将阅读顺序颠倒为kill(...).then(...).catch(...);。即使有这种逆转,也要确保 catch 回调调用reject();日志记录是不够的。
  • 另外,为了统一,总是拒绝(或抛出)正确的Error,而不是String。这样一来,所有下游捕获都可以写入始终接收Error,无论它是如何/在何处出现的。
  • 感谢您的提示。我已经更新了我的代码以类似于您在答案中的内容。因此,我相信现在已经解决了这个问题。这是我第一次使用 Node 并使用 Promise,非常感谢您的帮助!我的脚本的这一部分现在运行良好!
猜你喜欢
  • 1970-01-01
  • 2017-10-01
  • 2022-10-31
  • 1970-01-01
  • 2016-10-16
  • 1970-01-01
  • 1970-01-01
  • 2013-03-11
  • 1970-01-01
相关资源
最近更新 更多