728x90

두번째 람다 함수를 생성 (P65)

트랜스 코딩된 파일을 외부에서 공개적으로 접근할 수 있도록 설정하는 함수

 

#1 람다 함수를 생성

 



#2 람다 함수 소스 코드를 작성

#2-1 프로젝트 생성 및 모듈 설치

PS C:\Users\i> cd C:\serverless\

PS C:\serverless> mkdir set-permissions

PS C:\serverless> cd .\set-permissions\

PS C:\serverless\set-permissions> npm init -y

Wrote to C:\serverless\set-permissions\package.json:

 

{

  "name": "set-permissions",

  "version": "1.0.0",

  "description": "",

  "main": "index.js",

  "scripts": {

    "test": "echo \"Error: no test specified\" && exit 1"

  },

  "keywords": [],

  "author": "",

  "license": "ISC"

}

PS C:\serverless\set-permissions> npm install aws-sdk





#2-2 predeploy, deploy 스크립트를 추가

c:\serverless\set-permissions\package.json

{

  "name": "set-permissions",

  "version": "1.0.0",

  "description": "",

  "main": "index.js",

  "scripts": {

    "predeploy": "del Lambda-Deployment.zip & zip -r Lambda-Deployment.zip * -x *.zip *.log node_modules/aws-sdk/*", 

    "deploy": "aws lambda update-function-code --function-name 앞에서생성한람다함수의ARN --zip-file fileb://Lambda-Deployment.zip"

  },

  "keywords": [],

  "author": "",

  "license": "ISC",

  "dependencies": {

    "aws-sdk": "^2.862.0"

  }

}

 

#2-3 index.js 파일을 생성하고 코드를 작성

c:\serverless\set-permissions\index.js

// P66

'use stric';


var AWS = require('aws-sdk');

var s3 = new AWS.S3();


exports.handler = function(event, context, callback) {

    // SNS 서비스가 전달한 이벤트 객체에서 동영상이 저장된 버킷과 이름(키)을 추출

    var message = JSON.parse(event.Records[0].Sns.Message); // 참조1의 붉은색 부분을 가져와서 JSON 형식으로 변환

    var sourceBucket = message.Records[0].s3.bucket.name;

    var sourceKey = message.Records[0].s3.object.key;

    sourceKey = decodeURIComponent(sourceKey.replace(/\+/g, ' '));


    // 동영상의 접근제어목록(ACL) 속성을 public-read로 설정 -> 외부에서 접근 가능

    var params = {

        Bucket: sourceBucket,

        Key: sourceKey,

        ACL: 'public-read'

    };

    s3.putObjectAcl(params, function(err, data) {

        if (err) {

            callback(err);

        }

    });    

};



참조1: 람다 함수로 전달되는 이벤트 객체는 다음과 같은 구조를 가진다.

{

  "Records": [

    {

      "EventSource": "aws:sns",

      "EventVersion": "1.0",

      "EventSubscriptionArn": "arn:aws:sns:us-east-1:{{{accountId}}}:ExampleTopic",

      "Sns": {

        "Type": "Notification",

        "MessageId": "95df01b4-ee98-5cb9-9903-4c221d41eb5e",

        "TopicArn": "arn:aws:sns:us-east-1:123456789012:ExampleTopic",

        "Subject": "example subject",

        "Message": '{

  "Records": [

    {

      "eventVersion": "2.0",

      "eventSource": "aws:s3",

      "awsRegion": "us-east-1",

      "eventTime": "1970-01-01T00:00:00.000Z",

      "eventName": "ObjectCreated:Put",

      "userIdentity": {

"principalId": "EXAMPLE"

      },

      "requestParameters": {

"sourceIPAddress": "127.0.0.1"

      },

      "responseElements": {

"x-amz-request-id": "EXAMPLE123456789",

"x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH"

      },

      "s3": {

"s3SchemaVersion": "1.0",

"configurationId": "testConfigRule",

"bucket": {

  "name": "example-bucket",

  "ownerIdentity": {

    "principalId": "EXAMPLE"

  },

  "arn": "arn:aws:s3:::example-bucket"

},

"object": {

  "key": "test/key",

  "size": 1024,

  "eTag": "0123456789abcdef0123456789abcdef",

  "sequencer": "0A1B2C3D4E5F678901"

}

      }

    }

  ]

}',

        "Timestamp": "1970-01-01T00:00:00.000Z",

        "SignatureVersion": "1",

        "Signature": "EXAMPLE",

        "SigningCertUrl": "EXAMPLE",

        "UnsubscribeUrl": "EXAMPLE",

        "MessageAttributes": {

          "Test": {

            "Type": "String",

            "Value": "TestString"

          },

          "TestBinary": {

            "Type": "Binary",

            "Value": "TestBinary"

          }

        }

      }

    }

  ]

}

 

참조2: S3.putObjectAcl()

https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putObjectAcl-property



#3 람다 함수 소스 코드를 배포

PS C:\serverless\set-permissions> npm run deploy



#4 SNS에 람다 함수를 구독으로 추가

 

 



#5 람다 함수가 객체의 ACL을 변경할 수 있는 권한을 추가

 

#5 테스트

#5-1 트랜스 코딩된 파일이 저장되는 버킷의 파일 권한을 확인

 

#5-2 업로드 버킷에 파일명을 변경

 



#5-3 첫번째 람다 함수의 로그를 확인



#5-4 트랜스 코딩된 결과가 저장되는 버킷을 확인



#5-5 이메일 구독이 실행되었는지 확인



#5-6 두번째 람다의 로그 파일을 확인

⇒ 파일이 저장된 버킷에 접근 권한이 없어서 파일의 ACL을 변경할 수 없음 



#5-7 해당 버킷을 접근할 수 있도록 퍼블릭 액세스 차단을 해제

 



#5-8 업로드 버킷의 파일명을 변경

 

#5-9 두번째 람다 함수의 로그를 확인

 

#5-10 트랜스 코딩된 파일의 ACL을 확인



#5-11 객체 URL로 외부에서 호출










실습: set-permissions 람다 함수를 파이썬으로 구현

함수 이름: set-permissions-python

런타임: Python 3.7

 



 

 

테스트

  1. SNS 구독을 추가 

  2. 트랜스 코딩된 결과를 저장하는 버킷의 파일 중 하나의 이름을 변경

  3. 이메일 구독 수신 확인

  4. 로그 확인

  5. 파일의 ACL 변경 확인

 

참고

https://docs.aws.amazon.com/ko_kr/lambda/latest/dg/python-handler.html

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.put_object_acl

 

 

import boto3

 

def lambda_handler(event, context):

# event 구조를 출력

print(event)

 

s3 = boto3.client('s3')

 

# Messages 추출

message = event['Records'][0]['Sns']['Message']

print(message)

 

# 추출한 Messages를 JSON 형식으로 변형

message = json.loads(message)

print(message)

 

# 버킷 이름과 객체 이름을 출력

bucket = message['Records'][0]['s3']['bucket']['name']

print(bucket)

key = message['Records'][0]['s3']['object']['key']

print(key)

 

# 객체의 ACL 변경

# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.put_object_acl

response = s3.put_object_acl(ACL='public-read', Bucket=bucket, Key=key)

print(response)

 

return response





########################## event 구조

{

   "Records":[

      {

         "EventSource":"aws:sns",

         "EventVersion":"1.0",

         "EventSubscriptionArn":"arn:aws:sns:us-east-1:199503606661:transcoded-video-notifications:7d6fe943-417f-4104-b8a1-33a40f64f1d2",

         "Sns":{

            "Type":"Notification",

            "MessageId":"01f0cbfa-dea5-595f-94bc-933e0e2bc7ba",

            "TopicArn":"arn:aws:sns:us-east-1:199503606661:transcoded-video-notifications",

            "Subject":"Amazon S3 Notification",

            "Message":"{\"Records\":[{\"eventVersion\":\"2.1\",\"eventSource\":\"aws:s3\",\"awsRegion\":\"us-east-1\",\"eventTime\":\"2021-03-12T02:13:24.863Z\",\"eventName\":\"ObjectCreated:Copy\",\"userIdentity\":{\"principalId\":\"A357J5TEV9LLY5\"},\"requestParameters\":{\"sourceIPAddress\":\"211.33.180.73\"},\"responseElements\":{\"x-amz-request-id\":\"5RM6ZHKZZ14DMZP5\",\"x-amz-id-2\":\"me++pK16BL4UKGnkm67PcTgbdSP9TdoWJRG8uQ8HrEeBGFfHg5yTjD+R5LAGbZH1fp2ERN2V5NZLc/PGYFKUvM4sylRxpbzz\"},\"s3\":{\"s3SchemaVersion\":\"1.0\",\"configurationId\":\"Transcoded Video\",\"bucket\":{\"name\":\"serverless-videotranscoded-myanjini\",\"ownerIdentity\":{\"principalId\":\"A357J5TEV9LLY5\"},\"arn\":\"arn:aws:s3:::serverless-videotranscoded-myanjini\"},\"object\":{\"key\":\"my_video_v4/my_video_v4-1080p.mp4\",\"size\":14044196,\"eTag\":\"3c111f7192177b6f371fab15825edf4a\",\"sequencer\":\"00604ACE4C53A62126\"}}}]}",

            "Timestamp":"2021-03-12T02:13:34.747Z",

            "SignatureVersion":"1",

            "Signature":"lQeXkSTSUvF/avT9x43HWXMpMYP8QNte20MRgEHrbILotiGoioN3Y5WAoeFFosnl+US3NqBHK67DgVnXC4JZZttXsLQnK2u4ceBl0F66KXuJQMKS9a5XHKY0hoSa3YHwOObG4ppxSB8+zjXN/QjL1Xv6wDIfVikc/PCEp6aF/Ly/P5CrjGA1wiv7rc3EWqju33l9cBFz/jClHeZLSFfsPtR1NGcqvd0jG7ovYT2NM2qQAdCSSweUMVAxahCc2hSHV+zV9DVMlklTxEoCAZ7YwtDo3IVEGgrXjxUOgq/Dho/e8SgvGiwaNjmOot302lsb4gm4a4nfNVD4opzwPAsONQ==",

            "SigningCertUrl":"https://sns.us-east-1.amazonaws.com/SimpleNotificationService-010a507c1833636cd94bdb98bd93083a.pem",

            "UnsubscribeUrl":"https://sns.us-east-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-1:199503606661:transcoded-video-notifications:7d6fe943-417f-4104-b8a1-33a40f64f1d2",

            "MessageAttributes":{

               

            }

         }

      }

   ]

}




########################## Messages 추출

{"Records":[{"eventVersion":"2.1","eventSource":"aws:s3","awsRegion":"us-east-1","eventTime":"2021-03-12T02:13:24.863Z","eventName":"ObjectCreated:Copy","userIdentity":{"principalId":"A357J5TEV9LLY5"},"requestParameters":{"sourceIPAddress":"211.33.180.73"},"responseElements":{"x-amz-request-id":"5RM6ZHKZZ14DMZP5","x-amz-id-2":"me++pK16BL4UKGnkm67PcTgbdSP9TdoWJRG8uQ8HrEeBGFfHg5yTjD+R5LAGbZH1fp2ERN2V5NZLc/PGYFKUvM4sylRxpbzz"},"s3":{"s3SchemaVersion":"1.0","configurationId":"Transcoded Video","bucket":{"name":"serverless-videotranscoded-myanjini","ownerIdentity":{"principalId":"A357J5TEV9LLY5"},"arn":"arn:aws:s3:::serverless-videotranscoded-myanjini"},"object":{"key":"my_video_v4/my_video_v4-1080p.mp4","size":14044196,"eTag":"3c111f7192177b6f371fab15825edf4a","sequencer":"00604ACE4C53A62126"}}}]}





########################## 추출한 Messages를 JSON 형식으로 변형

{

   "Records":[

      {

         "eventVersion":"2.1",

         "eventSource":"aws:s3",

         "awsRegion":"us-east-1",

         "eventTime":"2021-03-12T02:13:24.863Z",

         "eventName":"ObjectCreated:Copy",

         "userIdentity":{

            "principalId":"A357J5TEV9LLY5"

         },

         "requestParameters":{

            "sourceIPAddress":"211.33.180.73"

         },

         "responseElements":{

            "x-amz-request-id":"5RM6ZHKZZ14DMZP5",

            "x-amz-id-2":"me++pK16BL4UKGnkm67PcTgbdSP9TdoWJRG8uQ8HrEeBGFfHg5yTjD+R5LAGbZH1fp2ERN2V5NZLc/PGYFKUvM4sylRxpbzz"

         },

         "s3":{

            "s3SchemaVersion":"1.0",

            "configurationId":"Transcoded Video",

            "bucket":{

               "name":"serverless-videotranscoded-myanjini",

               "ownerIdentity":{

                  "principalId":"A357J5TEV9LLY5"

               },

               "arn":"arn:aws:s3:::serverless-videotranscoded-myanjini"

            },

            "object":{

               "key":"my_video_v4/my_video_v4-1080p.mp4",

               "size":14044196,

               "eTag":"3c111f7192177b6f371fab15825edf4a",

               "sequencer":"00604ACE4C53A62126"

            }

         }

      }

   ]

}



 





메타데이터 생성 (P68)

ffprobe 프로그램을 사용해서 동영상 파일의 정보를 추출

~~~~~~~~~~~~~~~~

윈도우 환경에서는 실행 속성 설정 문제가 있어서, Amazon Linux EC2 인스턴스를 생성해서 해당 인스턴스 내에서 실행



https://docs.aws.amazon.com/ko_kr/lambda/latest/dg/lambda-runtimes.html



#1 Amazon Linux EC2 인스턴스를 생성

 



#2 인스턴스에 SSH 접속 후 node.js를 설치

참고 ⇒ https://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/setting-up-node-on-ec2-instance.html



[ec2-user@ip-172-31-62-117 ~]$ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current

                                 Dload  Upload   Total   Spent    Left  Speed

100 13226  100 13226    0     0   111k      0 --:--:-- --:--:-- --:--:--  111k

=> Downloading nvm as script to '/home/ec2-user/.nvm'

 

=> Appending nvm source string to /home/ec2-user/.bashrc

=> Appending bash_completion source string to /home/ec2-user/.bashrc

=> Close and reopen your terminal to start using nvm or run the following to use it now:

 

export NVM_DIR="$HOME/.nvm"

[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm

[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

[ec2-user@ip-172-31-62-117 ~]$ . ~/.nvm/nvm.sh

[ec2-user@ip-172-31-62-117 ~]$ nvm install node

Downloading and installing node v15.11.0...

Downloading https://nodejs.org/dist/v15.11.0/node-v15.11.0-linux-x64.tar.xz...

############################################################################################# 100.0%

Computing checksum with sha256sum

Checksums matched!

npm notice

npm notice New patch version of npm available! 7.6.0 -> 7.6.3

npm notice Changelog: https://github.com/npm/cli/releases/tag/v7.6.3

npm notice Run npm install -g npm@7.6.3 to update!

npm notice

Now using node v15.11.0 (npm v7.6.0)

Creating default alias: default -> node (-> v15.11.0)

[ec2-user@ip-172-31-62-117 ~]$ node -e "console.log('Running Node.js ' + process.version)"

Running Node.js v15.11.0

 

[ec2-user@ip-172-31-62-117 ~]$ nvm install v12.19.0

Downloading and installing node v12.19.0...

Downloading https://nodejs.org/dist/v12.19.0/node-v12.19.0-linux-x64.tar.xz...

############################################################################################# 100.0%

Computing checksum with sha256sum

Checksums matched!

Now using node v12.19.0 (npm v6.14.8)

 

#3 인스턴스의 ffmpeg 정적 빌드 다운로드 및 설치

https://www.johnvansickle.com/ffmpeg/old-releases/

 

[ec2-user@ip-172-31-62-117 ~]$ wget https://www.johnvansickle.com/ffmpeg/old-releases/ffmpeg-4.2.2-amd64-static.tar.xz

--2021-03-12 04:50:45--  https://www.johnvansickle.com/ffmpeg/old-releases/ffmpeg-4.2.2-amd64-static.tar.xz

Resolving www.johnvansickle.com (www.johnvansickle.com)... 107.180.57.212

Connecting to www.johnvansickle.com (www.johnvansickle.com)|107.180.57.212|:443... connected.

HTTP request sent, awaiting response... 200 OK

Length: 37907552 (36M) [application/x-xz]

Saving to: ‘ffmpeg-4.2.2-amd64-static.tar.xz’

 

100%[==========================================================>] 37,907,552  49.9MB/s   in 0.7s

 

2021-03-12 04:50:46 (49.9 MB/s) - ‘ffmpeg-4.2.2-amd64-static.tar.xz’ saved [37907552/37907552]

 

[ec2-user@ip-172-31-62-117 ~]$ ls ffmpeg-4.2.2-amd64-static.tar.xz

ffmpeg-4.2.2-amd64-static.tar.xz



[ec2-user@ip-172-31-62-117 ~]$ xz -d ffmpeg-4.2.2-amd64-static.tar.xz

[ec2-user@ip-172-31-62-117 ~]$ tar xvf ffmpeg-4.2.2-amd64-static.tar

[ec2-user@ip-172-31-62-117 ~]$ cd ffmpeg-4.2.2-amd64-static/

[ec2-user@ip-172-31-62-117 ffmpeg-4.2.2-amd64-static]$ ll

total 145312

-rwxr-xr-x 1 ec2-user ec2-user 74074472 Mar  2  2020 ffmpeg

-rwxr-xr-x 1 ec2-user ec2-user 73988648 Mar  2  2020 ffprobe ⇐ 미디어 정보를 추출

-rw-r--r-- 1 ec2-user ec2-user    35147 Mar  2  2020 GPLv3.txt

drwxr-xr-x 2 ec2-user ec2-user      309 Mar  2  2020 manpages

drwxr-xr-x 7 ec2-user ec2-user      255 Mar  2  2020 model

-rwxr-xr-x 1 ec2-user ec2-user   690888 Mar  2  2020 qt-faststart

-rw-r--r-- 1 ec2-user ec2-user     2140 Mar  2  2020 readme.txt



#4 세번째 람다 함수 생성

동영상 파일(트랜스 코딩된 동영상 파일, 3개가 생성)의 메타 정보를 추출해서 S3 버킷(트랜스 코딩된 파일이 저장되는 버킷)에 저장하는 람다 함수

 

 

 

 



#5 세번째 람다 함수 소스 코드를 작성 

EC2 인스턴스에서 작업 ⇒ ffprobe를 람다에 포함해서 배포해야 하므로

 

#5-1 프로젝트 생성 - 작업 디렉터리 생성 및 npm init

[ec2-user@ip-172-31-62-117 ffmpeg-4.2.2-amd64-static]$ cd

[ec2-user@ip-172-31-62-117 ~]$ mkdir extract-metadata

[ec2-user@ip-172-31-62-117 ~]$ cd extract-metadata/

[ec2-user@ip-172-31-62-117 extract-metadata]$ mkdir bin

[ec2-user@ip-172-31-62-117 extract-metadata]$ mkdir tmp

[ec2-user@ip-172-31-62-117 extract-metadata]$ npm init -y

Wrote to /home/ec2-user/extract-metadata/package.json:

 

{

  "name": "extract-metadata",

  "version": "1.0.0",

  "description": "",

  "main": "index.js",

  "scripts": {

    "test": "echo \"Error: no test specified\" && exit 1"

  },

  "keywords": [],

  "author": "",

  "license": "ISC"

}



#5-2 aws-sdk 모듈 설치

[ec2-user@ip-172-31-62-117 extract-metadata]$ npm install aws-sdk

npm notice created a lockfile as package-lock.json. You should commit this file.

npm WARN extract-metadata@1.0.0 No description

npm WARN extract-metadata@1.0.0 No repository field.

 

+ aws-sdk@2.862.0

added 14 packages from 66 contributors and audited 14 packages in 2.729s

 

1 package is looking for funding

  run `npm fund` for details

 

found 0 vulnerabilities

 

 

#5-3 package.json 파일에 predeploy, deploy 스크립트를 추가

[ec2-user@ip-172-31-62-117 extract-metadata]$ vi package.json

{

  "name": "extract-metadata",

  "version": "1.0.0",

  "description": "",

  "main": "index.js",

  "scripts": {

    "predeploy": "zip -r Lambda-Deployment.zip * -x *.zip *.log node_modules/aws-sdk/*",

    "deploy": "aws lambda update-function-code --function-name extract-metadata람다함수의ARN --zip-file fileb://Lambda-Deployment.zip"

  },

  "keywords": [],

  "author": "",

  "license": "ISC",

  "dependencies": {

    "aws-sdk": "^2.862.0"

  }

}




#5-4 index.js 파일을 생성 및 작성

[ec2-user@ip-172-31-62-117 extract-metadata]$ vi index.js

'use strict';

var AWS = require('aws-sdk');

// 어플리케이션이 실행되는 호스트의 쉘에서 명령어를 실행

var exec = require('child_process').exec;    

var fs = require('fs');


// PATH 환경 변수에 LAMBDA_TASK_ROOT 환경 변수를 추가

process.env['PATH'] = process.env['PATH'] + ':' + process.env['LAMBDA_TASK_ROOT'];



var s3 = new AWS.S3();


// 메타데이터를 S3 버킷에 파일(객체)로 저장

// body: 메타데이터 내용

function saveMetadataToS3(body, bucket, key, callback) {

    console.log('Saving metadata to S3');

    s3.putObject({

        Bucket: bucket, 

        Key: key, 

        Body: body     // key(파일)의 내용

    }, function(error, data) {

        if (error) {

            callback(error);

        }

    });

}


// 동영상의 메타데이터를 추출 (ffprobe 프로그램을 이용해서)

function extractMetadata(sourceBucket, sourceKey, localFilename, callback) {

    console.log('Extracting metadata');


    var cmd = 'bin/ffprobe -v quiet -print_format json -show_format "/tmp/' + localFilename + '"';

    //                     ~~~~~~~~ ~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    //                     로그생략 출력형식           메타데이터   동영상경로

    // 명령어 실행에 성공하면 JSON 형식의 메타데이터가 stdout으로 전달

    // 프로젝트 디렉터리(extract-metatdata) 아래에 bin/ffprobe가 존재해야 함

    exec(cmd, function(error, stdout, stderr) {

        if (error === null) {

            // 원본 파일명의 확장자를 json으로 변경

            var metadataKey = sourceKey.split('.')[0] + '.json';

            saveMetadataToS3(stdout, sourceBucket, metadataKey, callback);

        } else {

            console.log(stderr);

            callback(error);

        }

    });

}


// S3 버킷에 있는 동영상을 작업 디렉터리(tmp)로 가져오는 함수

function saveFileToFilesystem(sourceBucket, sourceKey, callback) {

    console.log('Saving to filesystem');


    // 파일명(확장자 포함)만 추출해서 tmp 아래에 파일을 생성

    var localFilename = sourceKey.split('/').pop();

    var file = fs.createWriteStream('/tmp/' + localFilename);


    // S3 버킷의 파일을 읽어와서 tmp 아래에 있는 파일에 저장

    var stream = s3.getObject({

        Bucket: sourceBucket, 

        Key: sourceKey

    }).createReadStream().pipe(file);


    stream.on('error', function(error) {

        callback(error);

    });


    // 파일을 다 가져오면 메타 데이터 추출 함수를 호출

    stream.on('close', function() {

        extractMetadata(sourceBucket, sourceKey, localFilename, callback);

    });

}


exports.handler = function (event, context, callback) {

    // 버킷 이름과 경로 및 확장자를 포함한 파일명을 이벤트에서 추출

    var message = JSON.parse(event.Records[0].Sns.Message);

    var sourceBucket = message.Records[0].s3.bucket.name;

    var sourceKey = decodeURIComponent(message.Records[0].s3.object.key.replace(/\+/g, ' '));


    saveFileToFilesystem(sourceBucket, sourceKey, callback);

};




exec() 함수의 실행을 테스트

[ec2-user@ip-172-31-62-117 ffmpeg-4.2.2-amd64-static]$ pwd

/home/ec2-user/ffmpeg-4.2.2-amd64-static

[ec2-user@ip-172-31-62-117 ffmpeg-4.2.2-amd64-static]$ cd /home/ec2-user/ffmpeg-4.2.2-amd64-static

[ec2-user@ip-172-31-62-117 ffmpeg-4.2.2-amd64-static]$ wget https://file-examples-com.github.io/uploads/2018/04/file_example_AVI_480_750kB.avi

--2021-03-12 05:41:28--  https://file-examples-com.github.io/uploads/2018/04/file_example_AVI_480_750kB.avi

Resolving file-examples-com.github.io (file-examples-com.github.io)... 185.199.109.153, 185.199.110.153, 185.199.111.153, ...

Connecting to file-examples-com.github.io (file-examples-com.github.io)|185.199.109.153|:443... connected.

HTTP request sent, awaiting response... 200 OK

Length: 742478 (725K) [video/x-msvideo]

Saving to: ‘file_example_AVI_480_750kB.avi’


100%[=================================================================================>] 742,478     --.-K/s   in 0.01s


2021-03-12 05:41:28 (47.6 MB/s) - ‘file_example_AVI_480_750kB.avi’ saved [742478/742478]


[ec2-user@ip-172-31-62-117 ffmpeg-4.2.2-amd64-static]$ ll

total 146040

-rwxr-xr-x 1 ec2-user ec2-user 74074472 Mar  2  2020 ffmpeg

-rwxr-xr-x 1 ec2-user ec2-user 73988648 Mar  2  2020 ffprobe

-rw-rw-r-- 1 ec2-user ec2-user   742478 Jul  9  2020 file_example_AVI_480_750kB.avi

-rw-r--r-- 1 ec2-user ec2-user    35147 Mar  2  2020 GPLv3.txt

drwxr-xr-x 2 ec2-user ec2-user      309 Mar  2  2020 manpages

drwxr-xr-x 7 ec2-user ec2-user      255 Mar  2  2020 model

-rwxr-xr-x 1 ec2-user ec2-user   690888 Mar  2  2020 qt-faststart

-rw-r--r-- 1 ec2-user ec2-user     2140 Mar  2  2020 readme.txt

[ec2-user@ip-172-31-62-117 ffmpeg-4.2.2-amd64-static]$ ./ffprobe -v quiet -print_format json -show_format ./file_example_AVI_480_750kB.avi

{

    "format": {

        "filename": "./file_example_AVI_480_750kB.avi",

        "nb_streams": 2,

        "nb_programs": 0,

        "format_name": "avi",

        "format_long_name": "AVI (Audio Video Interleaved)",

        "start_time": "0.000000",

        "duration": "30.613333",

        "size": "742478",

        "bit_rate": "194027",

        "probe_score": 100,

        "tags": {

            "encoder": "Lavf57.19.100"

        }

    }

}



#5-5 ffprobe 파일을 extract-metadata/bin 아래로 복사

[ec2-user@ip-172-31-62-117 ffmpeg-4.2.2-amd64-static]$ cd /home/ec2-user/ffmpeg-4.2.2-amd64-static

[ec2-user@ip-172-31-62-117 ffmpeg-4.2.2-amd64-static]$ mv ./ffprobe /home/ec2-user/extract-metadata/bin/

[ec2-user@ip-172-31-62-117 ffmpeg-4.2.2-amd64-static]$ cd /home/ec2-user/extract-metadata/bin/

[ec2-user@ip-172-31-62-117 bin]$ ll

total 72256

-rwxr-xr-x 1 ec2-user ec2-user 73988648 Mar  2  2020 ffprobe



#6 람다 함수를 배포

#6-1 aws configure 

[ec2-user@ip-172-31-62-117 extract-metadata]$ aws configure

AWS Access Key ID [None]: AKIAS*****CWZS64OWB

AWS Secret Access Key [None]: d91uKyd********************I8zSPBXaZtVx2

Default region name [None]: us-east-1

Default output format [None]:



#6-2 배포

[ec2-user@ip-172-31-62-117 extract-metadata]$ npm run deploy



#7 SNS 주제에 연결 = 구독을 생성



#8 테스트

#8-1 트랜스 코딩된 파일이 저장되는 버킷의 파일명(객체명)을 변경



#8-2 동일 버킷에 동일 객체명의 JSON 파일이 생성되는 것을 확인



#8-3 JSON 파일을 다운로드 후 내용 확인

 



#9 파일 종류와 무관하게 이벤트가 트리거되는 문제점을 수정



 

 




실습1. 

아래 URL에 본 이름의 시트를 만들고 다음 각 단계의 결과 화면을 스크린 샷으로 찍어서 올리세요.

https://docs.google.com/spreadsheets/d/1RtDeiPSWj_SJDROoa-6Zwg1uxahktgZT9_yUOi0Zkmw/edit#gid=0

#1 업로드 버킷의 모든 오브젝트 삭제

#2 트랜스 코딩 버킷의 모든 오브젝트 삭제

#3 SNS 구독 중 이메일 구독과 PYTHON 구독 삭제

#4 업로드 버킷에 이미지 등록 (주의: 크기가 작은 이미지를 사용할 것)

#5 트랜스 코딩 버킷에 이미지 3종과 메타데이터 3종이 생성된 것을 확인

#6 트랜스 코딩 버킷의 이미지의 객체 URL로 접근 가능 여부 확인 

 

조별 실습2. (실습1과 병행)

조별 활동으로 첫번째 람다 함수(transcode-video)와 세번째 람다 함수(extract-metadata)를 파이썬 기반으로 작성해서 조별로 업로드하시오. 

https://docs.google.com/spreadsheets/d/1K9Gthlb3h4ryZWvrsrw3zj5jhNTa18BYNyCNVuc4SJQ/edit?usp=sharing

 

  • transcode-video.py 파일

  • extract-metadata.py 파일

 

728x90

'CLOUD > AWS' 카테고리의 다른 글

3/16 - AWS 13차시  (0) 2021.03.16
3/15 - AWS 12차시  (0) 2021.03.15
3/11 - AWS 10차시  (0) 2021.03.11
3/10 - AWS 9차시  (0) 2021.03.10
3/9 - AWS 8차시  (0) 2021.03.09

+ Recent posts