All files / lib/backend-operations ops-cloud-api.js

14.75% Statements 18/122
0% Branches 0/47
0% Functions 0/22
14.75% Lines 18/122
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253                          6x 6x 6x 6x 6x 6x 6x   6x 6x 6x 6x 6x 6x 6x 6x   6x 6x                                                                                                                                                                                                                                                                                                                                                                                                                           6x                              
/* 
 * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
 * the License. A copy of the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file 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.
*/
"use strict";
const fs = require('fs-extra')
const ora = require('ora')
const chalk = require('chalk')
const moment = require('moment')
const extract =  require('extract-zip')
const path = require('path')
const https = require('https')
 
const backendSpecManager = require('./backend-spec-manager.js')
const lambdaBuilder = require('./cloud-api-lambda-builder.js')
const lambdaUploader = require('./cloud-api-lambda-uploader.js')
const dfops = require('../utils/directory-file-ops.js')
const pathManager = require('../utils/awsmobilejs-path-manager.js')
const awsmobileJSConstant = require('../utils/awsmobilejs-constant.js')
const cloudFormationCodes = require('../aws-operations/cloud-formation-codes.js')
const awsClient = require('../aws-operations/aws-client.js')
 
const _featureName = 'cloud-api'
const _featureCommands ={
    'invoke': 'awsmobile cloud-api invoke <apiname> <method> <path> [init]'
}
 
function specify(projectInfo) {
    try{
        const featureDirPath = pathManager.getBackendFeatureDirPath(projectInfo.ProjectPath, _featureName)
        fs.ensureDirSync(featureDirPath)
        const projectFeatureOps = require(pathManager.getProjectFeatureOpsFilePath(projectInfo.ProjectPath, _featureName))
        projectFeatureOps.specify(projectInfo)
    }catch(e){
        console.log(chalk.red(_featureName + ' feature specification error:'))
        console.log(e)
    }
}
 
function hasCommand(command){
    return _featureCommands.hasOwnProperty(command)
}
 
function runCommand(command, projectInfo, args){
    switch(command){
        case 'invoke': 
            commandInvoke(projectInfo, args)
        break
        default: 
            console.log(chalk.red('awsmobile ' + _featureName + ' does NOT recognize the command: ' + command))
        break
    }
}
 
function commandInvoke(projectInfo, args) {
    try{
        const projectFeatureOps = require(pathManager.getProjectFeatureOpsFilePath(projectInfo.ProjectPath, _featureName))
        projectFeatureOps.invoke(projectInfo, args)
    }catch(e){
        console.log(chalk.red(_featureName + ' invoke error:'))
        console.log(e)
    }
}
 
function onFeatureTurnOn(projectInfo, backendProjectSpec){
    try{
        const featureDirPath = pathManager.getBackendFeatureDirPath(projectInfo.ProjectPath, _featureName)
        fs.ensureDirSync(featureDirPath)
        
        const featureBuildDirPath = pathManager.getBackendBuildFeatureDirPath(projectInfo.ProjectPath, _featureName)
        if(fs.existsSync(featureBuildDirPath)){
            fs.removeSync(featureBuildDirPath)
        }
 
        const projectFeatureOps = require(pathManager.getProjectFeatureOpsFilePath(projectInfo.ProjectPath, _featureName))
        projectFeatureOps.onFeatureTurnOn(projectInfo)
    }catch(e){
        console.log(chalk.red(_featureName + ' onFeatureTurnOn error:'))
        console.log(e)
    }
}
 
function onFeatureTurnOff(projectInfo, backendProjectSpec){
    try{
        const featureBuildDirPath = pathManager.getBackendBuildFeatureDirPath(projectInfo.ProjectPath, _featureName)
        if(fs.existsSync(featureBuildDirPath)){
            fs.removeSync(featureBuildDirPath)
        }
        const projectFeatureOps = require(pathManager.getProjectFeatureOpsFilePath(projectInfo.ProjectPath, _featureName))
        projectFeatureOps.onFeatureTurnOff(projectInfo)
    }catch(e){
        console.log(chalk.red(_featureName + ' onFeatureTurnOff error:'))
        console.log(e)
    }
}
 
function build(projectInfo, backendProject, callback){
    lambdaBuilder.build(projectInfo, backendProject, _featureName, function(isNewBuildExecuted){
        if(callback){
            callback(isNewBuildExecuted)
        }
    })
}
 
function preBackendUpdate(projectInfo, awsDetails, backendProjectDetails, callback) {
    lambdaUploader.uploadLambdaZipFiles(projectInfo, awsDetails, backendProjectDetails, _featureName, callback)
}
 
//////////////////// sync backend project ////////////////////
function syncCurrentBackendInfo(projectInfo, backendDetails, awsDetails, callback){
    let lambdaFunctions = backendDetails.resources.filter(isCompleteLamdbaFunction)
    if(lambdaFunctions && lambdaFunctions.length > 0){
        let count = 0
        let spinner = new ora('downloading cloud-api lambda function codebases')
        spinner.start()
        lambdaFunctions.forEach(function(lambdaFunction){
            downloadLambdaFunction(projectInfo, awsDetails, lambdaFunction, function(){
                count ++
                if(count == lambdaFunctions.length){
                    spinner.stop()
                    if(callback){
                        callback()
                    }
                }
            })
        })
    }else{ 
        if(callback){
            callback()
        }
    }
}
 
function downloadLambdaFunction(projectInfo, awsDetails, lambdaFunction, callback){
    const getParams = { FunctionName: lambdaFunction.name }
    const lambdaClient = awsClient.Lambda(awsDetails, lambdaFunction.attributes.region)
    lambdaClient.getFunction(getParams, (err, data) => {
        if(err){
            console.log(err)
        }else if(data && data.Code && data.Code.Location){ 
            const downloadUrl = data.Code.Location
            const featureCurrentInfoDirPath = pathManager.getCurrentBackendFeatureDirPath(projectInfo.ProjectPath, _featureName)
            fs.ensureDirSync(featureCurrentInfoDirPath)
            const functionDestDirPath = path.join(featureCurrentInfoDirPath, lambdaFunction.attributes.configHandlerName)
            fs.emptyDirSync(functionDestDirPath)
 
            const tempZipFileName = lambdaFunction.attributes.configHandlerName +'.zip'
            const tempZipFilePath = path.join(featureCurrentInfoDirPath, tempZipFileName)
            const tempZipFileStream = fs.createWriteStream(tempZipFilePath)
 
            var request = https.get(downloadUrl, function(response) {
                response.pipe(tempZipFileStream)
                .on('close',()=>{
                    extract(tempZipFilePath, {dir: functionDestDirPath}, function (err) {
                        if(err){
                            console.log(chalk.red('error extracting ' + tempZipFileName))
                            console.log(err)
                            console.log('you can try to manually extract the lambda function code base')
                            fs.removeSync(functionDestDirPath)
                        }else{
                            fs.removeSync(tempZipFilePath)
                        }
                        if(callback){
                            callback()
                        }
                    })
                })
            })
        }
    })
}
 
function syncToDevBackend(projectInfo, backendProject, enabledFeatures){
    let featureCurrentInfoDirPath = pathManager.getCurrentBackendFeatureDirPath(projectInfo.ProjectPath, _featureName)
    if(fs.existsSync(featureCurrentInfoDirPath)){
        let featureBackendDirPath = pathManager.getBackendFeatureDirPath(projectInfo.ProjectPath, _featureName)
        fs.emptyDirSync(featureBackendDirPath)
        fs.copySync(featureCurrentInfoDirPath, featureBackendDirPath)
    }
}
 
function isCompleteLamdbaFunction(resource){
    return (resource.type == "AWS::Lambda::Function" &&
                            resource.feature == _featureName &&
                            resource.attributes.status.includes('COMPLETE'))
}
 
/////////////////Cloud Formation Logic/////////////////
function getStateGroup(stateSummary){
    //-2: unrecognized
    //-1: not-yet-deployed
    // 0: in-progress
    // 1: terminal_complate
    // 2: terminal_failed
    let result = -2 
    if(cloudFormationCodes.stackStatusCodes.includes(stateSummary)){
        result = 0
        if(cloudFormationCodes.terminalState_NotDeployed.includes(stateSummary)){
            result = -1
        }else if(cloudFormationCodes.terminalState_Complete.includes(stateSummary)){
            result = 1
        }else if(cloudFormationCodes.terminalState_Failed.includes(stateSummary)){
            result = 2
        }
    }
    return result
}
 
function getFormationStateSummary(backendDetails){
    let result
    let cloudFormataion = backendDetails.resources.find(isCloudApiFormation)
    if(cloudFormataion){
        result = cloudFormataion.attributes.stateSummary
    }
    return result
}
 
function isCloudApiFormation(resource){
    let result = false
    try{
        result = (resource.type == "AWS::CloudFormation::Stack" &&
                                resource.name == 'Development' &&
                                resource.feature == _featureName)
    }catch(e){
        result = false
    }
    return result
}
 
module.exports = {
    featureName: _featureName,
    featureCommands: _featureCommands,
    specify,
    hasCommand,
    runCommand,
    onFeatureTurnOn,
    onFeatureTurnOff,
    build,
    preBackendUpdate,
    syncCurrentBackendInfo,
    syncToDevBackend,
    getStateGroup,
    getFormationStateSummary
}