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
| 'use strict'; const zlib = require("zlib"), readLine = require('readline'), COS = require('cos-nodejs-sdk-v5'), cos = new COS({ SecretId: process.env.SECRET_ID, SecretKey: process.env.SECRET_KEY, KeepAlive: false }), tencentcloud = require("/opt/node_modules/tencentcloud-sdk-nodejs"), ClsClient = tencentcloud.cls.v20201016.Client, clientConfig = { credential: { secretId: process.env.SECRET_ID, secretKey: process.env.SECRET_KEY, }, region: process.env.TENCENTCLOUD_REGION, profile: { httpProfile: { endpoint: "cls.tencentcloudapi.com", }, }, }, downloadCycle = 60000, request = require('request'); exports.main_handler = (event, context, callback) => { let gunzip = zlib.createGunzip(); let jsonCount = 0, invalidLines = 0; let rl = readLine.createInterface(gunzip); rl.on('line', function(line) { if (/^\s*\{.*\}\s*$/.test(line)) { jsonCount++; } else { invalidLines++; } }) rl.on('close', () => { callback(null, "有效行数: " + jsonCount + " ,无效行数:" + invalidLines) }) if ("Type" in event && event.Type == "Timer") { let client = new ClsClient(clientConfig); let params = { "TopicId": process.env.TopicId, "Query": "SCF_Namespace:\"" + process.env.SCF_NAMESPACE + "\"", "Count": 10000000, "From": (Math.floor(Date.now() / downloadCycle - 1) * downloadCycle), "To": (Math.floor(Date.now() / downloadCycle) * downloadCycle) }; client.CreateExport(params).then(res => { if ("ExportId" in res) { console.log("导出任务发起成功,生成的文件等待定时器下次触发的时候处理"); client.DescribeExports({ "TopicId": process.env.TopicId }).then(res => { if ("Exports" in res && res.Exports instanceof Array) { for (let i = 0; i < res.Exports.length; i++) { let e = res.Exports[i]; if (e.Status == "Completed") { request(e.CosPath).pipe(gunzip); client.DeleteExport({"ExportId": e.ExportId}); } } } }) } else { console.log("导出任务发起失败,需要告警并走重试逻辑"); } }) } else if ("Records" in event && event.Records instanceof Array) { let records = event.Records; for (let i = 0; i < records.length; i++) { let c = records[i].cos; console.log("下载并分析日志文件 " + c.cosObject.key) cos.getObject({ Bucket: c.cosBucket.name + "-" + c.cosBucket.appid, Region: c.cosBucket.cosRegion, Key: "/" + c.cosObject.key.split("/").slice(3).join("/"), Output: gunzip }, function(err, data) { if (err) console.log("err:" + JSON.stringify(err)) }); } } else { return "未知触发器" } };
|