首页 \ 问答 \ NodeJS Lambda问题与操作顺序(NodeJS Lambda issue with order of operations)

NodeJS Lambda问题与操作顺序(NodeJS Lambda issue with order of operations)

主要问题是代码执行CodePipeline时,它会下载一个输入工件,将下载的工件和grep template.yml解压缩为一个名为Function name的字符串。 它大部分时间都有效,但会失败,说偶尔找不到template.yml文件。 如果我再次运行它,它将毫无错误地工作。 任何帮助表示感谢。 谢谢!

'严格使用'

// dependencies
const child_process = require('child_process')
const fs = require('fs')
const path = require('path')
const stripDirs = require('strip-dirs')
const AWS = require('aws-sdk')
const unzip = require('unzip')
const shell = require('shelljs')

// global process variable is still accessible
process.env['PATH'] = process.env['PATH'] + ':' + process.env['/tmp']

// get reference to S3 client
const s3 = new AWS.S3({maxRetries: 1, "signatureVersion":"v4"})

exports.handler = function(event, context) {

  const codepipeline = new AWS.CodePipeline()
  let jobId

  // Notify AWS CodePipeline of a successful job
  function putJobSuccess(message) {
    console.log(message)
    codepipeline.putJobSuccessResult({ jobId },
      (err, data) => {
        if (err)
          context.fail(err)
        else
          context.succeed(message)
       })
  }

  // Notify AWS CodePipeline of a failed job
  function putJobFailure(message) {
    console.error('job failure: ', message)
    codepipeline.putJobFailureResult({
      jobId,
      failureDetails: {
      message: JSON.stringify(message),
       type: 'JobFailed',
       externalExecutionId: context.invokeid
      }
    }, (err, data) => context.fail(message))
  }


  try {
const jobEvent = event['CodePipeline.job']
jobId = jobEvent.id
const jobData = jobEvent.data
console.log(jobData)

// Retrieve the value of UserParameters from the Lambda action configuration in AWS CodePipeline, in this case a URL which will be
// health checked by this function.
const userParams = jobData.actionConfiguration.configuration.UserParameters
const userParamsSplit = userParams && userParams.split(' ')
if (!userParams || !userParamsSplit || userParamsSplit.length !== 1)
  throw new Error('The User Parameters field must contain three items separated by spaces: the input artifact name, the location of the lambda function code within the input artifact, and the destination lambda function name')

const artifactName = userParamsSplit[0]
const artifact = jobData.inputArtifacts.find(a => a.name === artifactName && a.location.type === 'S3')
if (!artifact) throw new Error('artifact not found: ', artifactName)
console.log('Artifact:', artifact)

const tmpDir = '/tmp'

const artifactZipFilePath = path.join(tmpDir, stripDirs(artifact.location.s3Location.objectKey, 2))
console.log('ZipFilePath:', artifactZipFilePath)

s3.getObject({
  Bucket: artifact.location.s3Location.bucketName,
  Key: artifact.location.s3Location.objectKey
}, (err, data) => {
  if (err) return putJobFailure(`could not download artifact from S3: ${err.stack || err}`)
  console.log()
  fs.writeFileSync(artifactZipFilePath, data.Body)

const zipFileContents = fs.readFileSync(artifactZipFilePath)
const zipFileDir = stripDirs(artifact.location.s3Location.objectKey, 2).slice(0, -4)
console.log('zipFileDir:', zipFileDir)

const newZipArtifact = path.join('/tmp', stripDirs(artifact.location.s3Location.objectKey, 2))
fs.createReadStream(newZipArtifact).pipe(unzip.Extract({ path: '/tmp' }))
const prependFunctionName = shell.grep('FunctionName', '/tmp/template.yml')
const destLambdaFunctionName = prependFunctionName.replace(/^.+:/,'').replace(/\s/g,'')
const command = require('child_process').exec

command(`echo ${destLambdaFunctionName}`, (error, stdout, stderr) => {
  if (error) {
    console.log("Error occurs");
    console.error(error);
    return;
  }
  console.log(stdout);
  console.log(stderr);
})

lambda.updateFunctionCode({
    FunctionName: destLambdaFunctionName,
    Publish: true,
    ZipFile: zipFileContents
  }, function(err, data) {
    if (err) console.log(err, err.stack) // an error occurred
    else     console.log(data)           // successful response
    const sqsMsg = (data)
    putJobSuccess('lambda code updated')
  })
})
} catch (err) {
putJobFailure(err.stack)
 }
}

The main issue is when the code executes using CodePipeline it will download an input artifact, unzip the downloaded artifact and grep template.yml for a string called Function name. It works most of the time but will fail saying template.yml file not found occasionally. If I rerun it again it will work without errors. Any help is appreciate. Thanks!

'use strict'

// dependencies
const child_process = require('child_process')
const fs = require('fs')
const path = require('path')
const stripDirs = require('strip-dirs')
const AWS = require('aws-sdk')
const unzip = require('unzip')
const shell = require('shelljs')

// global process variable is still accessible
process.env['PATH'] = process.env['PATH'] + ':' + process.env['/tmp']

// get reference to S3 client
const s3 = new AWS.S3({maxRetries: 1, "signatureVersion":"v4"})

exports.handler = function(event, context) {

  const codepipeline = new AWS.CodePipeline()
  let jobId

  // Notify AWS CodePipeline of a successful job
  function putJobSuccess(message) {
    console.log(message)
    codepipeline.putJobSuccessResult({ jobId },
      (err, data) => {
        if (err)
          context.fail(err)
        else
          context.succeed(message)
       })
  }

  // Notify AWS CodePipeline of a failed job
  function putJobFailure(message) {
    console.error('job failure: ', message)
    codepipeline.putJobFailureResult({
      jobId,
      failureDetails: {
      message: JSON.stringify(message),
       type: 'JobFailed',
       externalExecutionId: context.invokeid
      }
    }, (err, data) => context.fail(message))
  }


  try {
const jobEvent = event['CodePipeline.job']
jobId = jobEvent.id
const jobData = jobEvent.data
console.log(jobData)

// Retrieve the value of UserParameters from the Lambda action configuration in AWS CodePipeline, in this case a URL which will be
// health checked by this function.
const userParams = jobData.actionConfiguration.configuration.UserParameters
const userParamsSplit = userParams && userParams.split(' ')
if (!userParams || !userParamsSplit || userParamsSplit.length !== 1)
  throw new Error('The User Parameters field must contain three items separated by spaces: the input artifact name, the location of the lambda function code within the input artifact, and the destination lambda function name')

const artifactName = userParamsSplit[0]
const artifact = jobData.inputArtifacts.find(a => a.name === artifactName && a.location.type === 'S3')
if (!artifact) throw new Error('artifact not found: ', artifactName)
console.log('Artifact:', artifact)

const tmpDir = '/tmp'

const artifactZipFilePath = path.join(tmpDir, stripDirs(artifact.location.s3Location.objectKey, 2))
console.log('ZipFilePath:', artifactZipFilePath)

s3.getObject({
  Bucket: artifact.location.s3Location.bucketName,
  Key: artifact.location.s3Location.objectKey
}, (err, data) => {
  if (err) return putJobFailure(`could not download artifact from S3: ${err.stack || err}`)
  console.log()
  fs.writeFileSync(artifactZipFilePath, data.Body)

const zipFileContents = fs.readFileSync(artifactZipFilePath)
const zipFileDir = stripDirs(artifact.location.s3Location.objectKey, 2).slice(0, -4)
console.log('zipFileDir:', zipFileDir)

const newZipArtifact = path.join('/tmp', stripDirs(artifact.location.s3Location.objectKey, 2))
fs.createReadStream(newZipArtifact).pipe(unzip.Extract({ path: '/tmp' }))
const prependFunctionName = shell.grep('FunctionName', '/tmp/template.yml')
const destLambdaFunctionName = prependFunctionName.replace(/^.+:/,'').replace(/\s/g,'')
const command = require('child_process').exec

command(`echo ${destLambdaFunctionName}`, (error, stdout, stderr) => {
  if (error) {
    console.log("Error occurs");
    console.error(error);
    return;
  }
  console.log(stdout);
  console.log(stderr);
})

lambda.updateFunctionCode({
    FunctionName: destLambdaFunctionName,
    Publish: true,
    ZipFile: zipFileContents
  }, function(err, data) {
    if (err) console.log(err, err.stack) // an error occurred
    else     console.log(data)           // successful response
    const sqsMsg = (data)
    putJobSuccess('lambda code updated')
  })
})
} catch (err) {
putJobFailure(err.stack)
 }
}

原文:https://stackoverflow.com/questions/43546191
更新时间:2024-01-24 06:01

最满意答案

这将返回一个带有类名称的数组(即字符串):

ActiveRecord::Base.descendants.map(&:to_s).select {|x| x.match('::')}

而这将返回实际的类对象:

ActiveRecord::Base.descendants.select {|x| x.name.match('::')}

This will return an array with the class names (ie. strings):

ActiveRecord::Base.descendants.map(&:to_s).select {|x| x.match('::')}

while this will return the actual class objects:

ActiveRecord::Base.descendants.select {|x| x.name.match('::')}

相关问答

更多

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。