You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

159 lines
7.4 KiB

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const core = require("@actions/core");
const WebClient_1 = require("./WebClient");
class ApiResult {
constructor(error, result, request, response) {
this.error = error;
this.result = result;
this.request = request;
this.response = response;
}
}
exports.ApiResult = ApiResult;
class AzureError {
}
exports.AzureError = AzureError;
function ToError(response) {
let error = new AzureError();
error.statusCode = response.statusCode;
error.message = response.body;
if (response.body && response.body.error) {
error.code = response.body.error.code;
error.message = response.body.error.message;
error.details = response.body.error.details;
core.error(error.message);
}
return error;
}
exports.ToError = ToError;
class ServiceClient {
constructor(authorizer, timeout) {
this._webClient = new WebClient_1.WebClient();
this._authorizer = authorizer;
this.subscriptionId = this._authorizer.subscriptionID;
this.baseUrl = this._authorizer.baseUrl;
this.longRunningOperationRetryTimeout = !!timeout ? timeout : 0; // In minutes
}
getRequestUri(uriFormat, parameters, queryParameters, apiVersion) {
return this.getRequestUriForbaseUrl(this.baseUrl, uriFormat, parameters, queryParameters, apiVersion);
}
getRequestUriForbaseUrl(baseUrl, uriFormat, parameters, queryParameters, apiVersion) {
let requestUri = baseUrl + uriFormat;
requestUri = requestUri.replace('{subscriptionId}', encodeURIComponent(this.subscriptionId));
for (let key in parameters) {
requestUri = requestUri.replace(key, encodeURIComponent(parameters[key]));
}
// trim all duplicate forward slashes in the url
let regex = /([^:]\/)\/+/gi;
requestUri = requestUri.replace(regex, '$1');
// process query paramerters
queryParameters = queryParameters || [];
if (!!apiVersion) {
queryParameters.push('api-version=' + encodeURIComponent(apiVersion));
}
if (queryParameters.length > 0) {
requestUri += '?' + queryParameters.join('&');
}
return requestUri;
}
beginRequest(request, tokenArgs) {
return __awaiter(this, void 0, void 0, function* () {
let token = yield this._authorizer.getToken(false, tokenArgs);
request.headers = request.headers || {};
request.headers['Authorization'] = `Bearer ${token}`;
request.headers['Content-Type'] = 'application/json; charset=utf-8';
let httpResponse = null;
try {
httpResponse = yield this._webClient.sendRequest(request);
if (httpResponse.statusCode === 401 && httpResponse.body && httpResponse.body.error && httpResponse.body.error.code === "ExpiredAuthenticationToken") {
// The access token might have expire. Re-issue the request after refreshing the token.
token = yield this._authorizer.getToken(true, tokenArgs);
request.headers['Authorization'] = `Bearer ${token}`;
httpResponse = yield this._webClient.sendRequest(request);
}
}
catch (exception) {
let exceptionString = exception.toString();
if (exceptionString.indexOf("Hostname/IP doesn't match certificates's altnames") != -1
|| exceptionString.indexOf("unable to verify the first certificate") != -1
|| exceptionString.indexOf("unable to get local issuer certificate") != -1) {
core.warning("You're probably using a self-signed certificate in the SSL certificate validation chain. To resolve them you need to export a variable named ACTIONS_AZURE_REST_IGNORE_SSL_ERRORS to the value true.");
throw exception;
}
}
return httpResponse;
});
}
accumulateResultFromPagedResult(nextLinkUrl) {
return __awaiter(this, void 0, void 0, function* () {
let result = [];
while (!!nextLinkUrl) {
let nextRequest = {
method: 'GET',
uri: nextLinkUrl
};
let response = yield this.beginRequest(nextRequest);
if (response.statusCode == 200 && response.body) {
if (response.body.value) {
result = result.concat(response.body.value);
}
nextLinkUrl = response.body.nextLink;
}
else {
return new ApiResult(ToError(response));
}
}
return new ApiResult(null, result);
});
}
getLongRunningOperationResult(response) {
return __awaiter(this, void 0, void 0, function* () {
let timeoutInMinutes = 2;
let timeout = new Date().getTime() + timeoutInMinutes * 60 * 1000;
let request = {
method: 'GET',
uri: response.headers['azure-asyncoperation'] || response.headers['location']
};
if (!request.uri) {
throw new Error('Unable to find the Azure-Async operation polling URI.');
}
while (true) {
response = yield this.beginRequest(request);
core.debug(`POLL URL RESULT: ${JSON.stringify(response)}`);
if (response.statusCode === 202 || (response.body && (response.body.status == 'Accepted' || response.body.status == 'Running' || response.body.status == 'InProgress'))) {
if (timeout < new Date().getTime()) {
throw new Error(`Async polling request timed out. URI: ${request.uri}`);
}
let retryAfterInterval = response.headers['retry-after'] && parseInt(response.headers['retry-after']) || 15;
yield this._sleep(retryAfterInterval);
}
else if (response.statusCode === 200) {
break;
}
else {
throw ToError(response);
}
}
return response;
});
}
getAccessToken() {
return this._authorizer.getToken();
}
_sleep(sleepDurationInSeconds) {
return new Promise((resolve) => {
setTimeout(resolve, sleepDurationInSeconds * 1000);
});
}
}
exports.ServiceClient = ServiceClient;