paiJobInfoCollector.ts 7.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
 * Copyright (c) Microsoft Corporation
 * All rights reserved.
 *
 * MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
 * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

'use strict';

22
// tslint:disable-next-line:no-implicit-dependencies
23
24
25
import * as request from 'request';
import { Deferred } from 'ts-deferred';
import { NNIError, NNIErrorNames } from '../../common/errors';
26
import { getLogger, Logger } from '../../common/log';
27
import { TrialJobStatus } from '../../common/trainingService';
28
29
import { PAIClusterConfig } from './paiConfig';
import { PAITrialJobDetail } from './paiData';
30
31
32
33
34
35
36
37
38
39
40
41
42

/**
 * Collector PAI jobs info from PAI cluster, and update pai job status locally
 */
export class PAIJobInfoCollector {
    private readonly trialJobsMap : Map<string, PAITrialJobDetail>;
    private readonly log: Logger = getLogger();
    private readonly statusesNeedToCheck : TrialJobStatus[];
    private readonly finalStatuses : TrialJobStatus[];

    constructor(jobMap: Map<string, PAITrialJobDetail>) {
        this.trialJobsMap = jobMap;
        this.statusesNeedToCheck = ['RUNNING', 'UNKNOWN', 'WAITING'];
QuanluZhang's avatar
QuanluZhang committed
43
        this.finalStatuses = ['SUCCEEDED', 'FAILED', 'USER_CANCELED', 'SYS_CANCELED', 'EARLY_STOPPED'];
44
45
    }

46
    public async retrieveTrialStatus(paiToken? : string, paiClusterConfig?: PAIClusterConfig) : Promise<void> {
47
        if (paiClusterConfig === undefined || paiToken === undefined) {
48
            return Promise.resolve();
49
50
51
        }

        const updatePaiTrialJobs : Promise<void>[] = [];
52
53
        for (const [trialJobId, paiTrialJob] of this.trialJobsMap) {
            if (paiTrialJob === undefined) {
54
55
                throw new NNIError(NNIErrorNames.NOT_FOUND, `trial job id ${trialJobId} not found`);
            }
56
            updatePaiTrialJobs.push(this.getSinglePAITrialJobInfo(paiTrialJob, paiToken, paiClusterConfig));
57
58
59
60
61
        }

        await Promise.all(updatePaiTrialJobs);
    }

62
63
    private getSinglePAITrialJobInfo(paiTrialJob : PAITrialJobDetail, paiToken : string, paiClusterConfig: PAIClusterConfig)
     : Promise<void> {
64
65
66
        const deferred : Deferred<void> = new Deferred<void>();
        if (!this.statusesNeedToCheck.includes(paiTrialJob.status)) {
            deferred.resolve();
67

68
69
70
71
72
73
            return deferred.promise;
        }

        // Rest call to get PAI job info and update status
        // Refer https://github.com/Microsoft/pai/blob/master/docs/rest-server/API.md for more detail about PAI Rest API
        const getJobInfoRequest: request.Options = {
74
            // tslint:disable-next-line:no-http-string
75
            uri: `http://${paiClusterConfig.host}/rest-server/api/v1/user/${paiClusterConfig.userName}/jobs/${paiTrialJob.paiJobName}`,
76
77
78
            method: 'GET',
            json: true,
            headers: {
79
80
                'Content-Type': 'application/json',
                Authorization: `Bearer ${paiToken}`
81
82
            }
        };
83
84

        // tslint:disable: no-unsafe-any no-any cyclomatic-complexity
85
        //TODO : pass in request timeout param?
86
        request(getJobInfoRequest, (error: Error, response: request.Response, body: any) => {
87
            if ((error !== undefined && error !== null) || response.statusCode >= 500) {
88
89
                this.log.error(`PAI Training service: get job info for trial ${paiTrialJob.id} from PAI Cluster failed!`);
                // Queried PAI job info failed, set job status to UNKNOWN
90
                if (paiTrialJob.status === 'WAITING' || paiTrialJob.status === 'RUNNING') {
91
92
93
                    paiTrialJob.status = 'UNKNOWN';
                }
            } else {
94
95
                if (response.body.jobStatus && response.body.jobStatus.state) {
                    switch (response.body.jobStatus.state) {
96
                        case 'WAITING':
97
98
99
100
                            paiTrialJob.status = 'WAITING';
                            break;
                        case 'RUNNING':
                            paiTrialJob.status = 'RUNNING';
101
                            if (paiTrialJob.startTime === undefined) {
102
103
                                paiTrialJob.startTime = response.body.jobStatus.appLaunchedTime;
                            }
104
                            if (paiTrialJob.url === undefined) {
105
                                paiTrialJob.url = response.body.jobStatus.appTrackingUrl;
106
107
108
109
110
111
                            }
                            break;
                        case 'SUCCEEDED':
                            paiTrialJob.status = 'SUCCEEDED';
                            break;
                        case 'STOPPED':
112
                            if (paiTrialJob.isEarlyStopped !== undefined) {
113
                                paiTrialJob.status = paiTrialJob.isEarlyStopped === true ?
114
115
                                        'EARLY_STOPPED' : 'USER_CANCELED';
                            } else {
116
117
118
                                /* if paiTrialJob's isEarlyStopped is undefined, that mean we didn't stop it via cancellation,
                                 * mark it as SYS_CANCELLED by PAI
                                 */
119
                                paiTrialJob.status = 'SYS_CANCELED';
QuanluZhang's avatar
QuanluZhang committed
120
                            }
121
122
                            break;
                        case 'FAILED':
123
                            paiTrialJob.status = 'FAILED';
124
125
126
127
128
                            break;
                        default:
                            paiTrialJob.status = 'UNKNOWN';
                    }
                    // For final job statues, update startTime, endTime and url
129
130
                    if (this.finalStatuses.includes(paiTrialJob.status)) {
                        if (paiTrialJob.startTime === undefined) {
131
132
                            paiTrialJob.startTime = response.body.jobStatus.appLaunchedTime;
                        }
133
                        if (paiTrialJob.endTime === undefined) {
134
135
136
                            paiTrialJob.endTime = response.body.jobStatus.completedTime;
                        }
                        // Set pai trial job's url to WebHDFS output path
137
                        if (paiTrialJob.hdfsLogPath !== undefined) {
138
                            paiTrialJob.url += `,${paiTrialJob.hdfsLogPath}`;
139
140
141
142
143
144
145
146
147
                        }
                    }
                }
            }
            deferred.resolve();
        });

        return deferred.promise;
    }
148
    // tslint:enable: no-unsafe-any no-any
QuanluZhang's avatar
QuanluZhang committed
149
}