| 1 | + | package tencent |
| 2 | + | |
| 3 | + | import ( |
| 4 | + | "encoding/json" |
| 5 | + | "errors" |
| 6 | + | "strconv" |
| 7 | + | "strings" |
| 8 | + | "time" |
| 9 | + | |
| 10 | + | billing "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/billing/v20180709" |
| 11 | + | cam "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cam/v20190116" |
| 12 | + | "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common" |
| 13 | + | fcError "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors" |
| 14 | + | "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile" |
| 15 | + | scf "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/scf/v20180416" |
| 16 | + | |
| 17 | + | "github.com/DVKunion/SeaMoon/cmd/client/api/models" |
| 18 | + | "github.com/DVKunion/SeaMoon/cmd/client/api/types" |
| 19 | + | "github.com/DVKunion/SeaMoon/pkg/consts" |
| 20 | + | "github.com/DVKunion/SeaMoon/pkg/xlog" |
| 21 | + | ) |
| 22 | + | |
| 23 | + | const ( |
| 24 | + | BillEndPoint = "billing.tencentcloudapi.com" |
| 25 | + | SCFEndPoint = "scf.tencentcloudapi.com" |
| 26 | + | CAMEndPoint = "cam.tencentcloudapi.com" |
| 27 | + | ) |
| 28 | + | |
| 29 | + | type triggerDesc struct { |
| 30 | + | Api triggerDescApi `json:"api"` |
| 31 | + | Service triggerDescService `json:"service"` |
| 32 | + | Release struct { |
| 33 | + | EnvironmentName string `json:"environmentName"` |
| 34 | + | } `json:"release"` |
| 35 | + | } |
| 36 | + | |
| 37 | + | type triggerDescApi struct { |
| 38 | + | AuthRequired string `json:"authRequired"` |
| 39 | + | AuthType string `json:"authType"` |
| 40 | + | RequestConfig struct { |
| 41 | + | Method string `json:"method"` |
| 42 | + | Path string `json:"path"` |
| 43 | + | } `json:"requestConfig"` |
| 44 | + | IsIntegratedResponse string `json:"isIntegratedResponse"` |
| 45 | + | IsBase64Encoded string `json:"isBase64Encoded"` |
| 46 | + | } |
| 47 | + | |
| 48 | + | type triggerDescService struct { |
| 49 | + | ServiceName string `json:"serviceName"` |
| 50 | + | ServiceType string `json:"serviceType"` |
| 51 | + | SubDomain string `json:"subDomain"` |
| 52 | + | Tags []string `json:"tags"` |
| 53 | + | } |
| 54 | + | |
| 55 | + | type triggerResp struct { |
| 56 | + | Service struct { |
| 57 | + | SubDomain string `json:"subDomain"` |
| 58 | + | } `json:"service"` |
| 59 | + | } |
| 60 | + | |
| 61 | + | type fcInfo struct { |
| 62 | + | detail *scf.GetFunctionResponseParams |
| 63 | + | addr string |
| 64 | + | auth string |
| 65 | + | } |
| 66 | + | |
| 67 | + | func (t *SDK) auth(provider *models.CloudProvider) error { |
| 68 | + | credential := common.NewCredential( |
| 69 | + | provider.CloudAuth.AccessKey, |
| 70 | + | provider.CloudAuth.AccessSecret, |
| 71 | + | ) |
| 72 | + | |
| 73 | + | cpf := profile.NewClientProfile() |
| 74 | + | // 需要授权: SCF、 API GateWay |
| 75 | + | cpf.HttpProfile.Endpoint = "cam.tencentcloudapi.com" |
| 76 | + | roleClient, _ := cam.NewClient(credential, "ap-guangzhou", cpf) |
| 77 | + | |
| 78 | + | apiGateWayPolicy := "{\"version\":\"2.0\",\"statement\":[{\"action\":\"name/sts:AssumeRole\",\"effect\":\"allow\",\"principal\":{\"service\":\"apigateway.qcloud.com\"}}]}" |
| 79 | + | fcPolicy := "{\"version\":\"2.0\",\"statement\":[{\"action\":\"name/sts:AssumeRole\",\"effect\":\"allow\",\"principal\":{\"service\":\"scf.qcloud.com\"}}]}" |
| 80 | + | |
| 81 | + | roleRequest := cam.NewCreateRoleRequest() |
| 82 | + | roleRequest.RoleName = common.StringPtr("ApiGateWay_QCSRole") |
| 83 | + | roleRequest.PolicyDocument = common.StringPtr(apiGateWayPolicy) |
| 84 | + | roleRequest.Description = common.StringPtr("API 网关(API Gateway)对您的腾讯云资源进行访问操作,含上传日志、获取日志游标、下载日志、获取日志主题信息等。") |
| 85 | + | |
| 86 | + | _, err := roleClient.CreateRole(roleRequest) |
| 87 | + | if err != nil { |
| 88 | + | if err, ok := err.(*fcError.TencentCloudSDKError); !ok || err.Code != "InvalidParameter.RoleNameInUse" || |
| 89 | + | err.Message != "role name in use" { |
| 90 | + | return err |
| 91 | + | } |
| 92 | + | } |
| 93 | + | |
| 94 | + | attachRolePolicyRequest := cam.NewAttachRolePolicyRequest() |
| 95 | + | attachRolePolicyRequest.PolicyName = common.StringPtr("QcloudAccessForAPIGatewayRoleInSCFTrigger") |
| 96 | + | attachRolePolicyRequest.AttachRoleName = roleRequest.RoleName |
| 97 | + | |
| 98 | + | _, err = roleClient.AttachRolePolicy(attachRolePolicyRequest) |
| 99 | + | if err != nil { |
| 100 | + | return err |
| 101 | + | } |
| 102 | + | |
| 103 | + | roleRequest = cam.NewCreateRoleRequest() |
| 104 | + | roleRequest.RoleName = common.StringPtr("SCF_QcsRole") |
| 105 | + | roleRequest.PolicyDocument = common.StringPtr(fcPolicy) |
| 106 | + | roleRequest.Description = common.StringPtr("云函数(SCF)操作权限含创建对象存储(COS)触发器,拉取代码包等;含创建API网关(API Gateway)触发器等;含消创建息队列(CMQ)触发器等;含投递日志服务(CLS)日志等。") |
| 107 | + | |
| 108 | + | _, err = roleClient.CreateRole(roleRequest) |
| 109 | + | if err != nil { |
| 110 | + | if err, ok := err.(*fcError.TencentCloudSDKError); !ok || err.Code != "InvalidParameter.RoleNameInUse" || |
| 111 | + | err.Message != "role name in use" { |
| 112 | + | return err |
| 113 | + | } |
| 114 | + | } |
| 115 | + | |
| 116 | + | attachRolePolicyRequest = cam.NewAttachRolePolicyRequest() |
| 117 | + | attachRolePolicyRequest.PolicyName = common.StringPtr("QcloudAccessForScfRole") |
| 118 | + | attachRolePolicyRequest.AttachRoleName = roleRequest.RoleName |
| 119 | + | |
| 120 | + | _, err = roleClient.AttachRolePolicy(attachRolePolicyRequest) |
| 121 | + | if err != nil { |
| 122 | + | return err |
| 123 | + | } |
| 124 | + | |
| 125 | + | return nil |
| 126 | + | } |
| 127 | + | |
| 128 | + | func (t *SDK) billing(provider *models.CloudProvider) (float64, error) { |
| 129 | + | credential := common.NewCredential( |
| 130 | + | provider.CloudAuth.AccessKey, |
| 131 | + | provider.CloudAuth.AccessSecret, |
| 132 | + | ) |
| 133 | + | |
| 134 | + | cpf := profile.NewClientProfile() |
| 135 | + | cpf.HttpProfile.Endpoint = BillEndPoint |
| 136 | + | |
| 137 | + | client, err := billing.NewClient(credential, "", cpf) |
| 138 | + | |
| 139 | + | if err != nil { |
| 140 | + | return 0, err |
| 141 | + | } |
| 142 | + | |
| 143 | + | // 构造请求 |
| 144 | + | request := billing.NewDescribeAccountBalanceRequest() |
| 145 | + | |
| 146 | + | // 发送请求 |
| 147 | + | response, err := client.DescribeAccountBalance(request) |
| 148 | + | |
| 149 | + | if err != nil { |
| 150 | + | return 0, err |
| 151 | + | } |
| 152 | + | |
| 153 | + | balance := *response.Response.Balance |
| 154 | + | |
| 155 | + | return float64(balance) / 100, nil |
| 156 | + | } |
| 157 | + | |
| 158 | + | func (t *SDK) deploy(provider *models.CloudProvider, tun *models.Tunnel) (string, error) { |
| 159 | + | credential := common.NewCredential( |
| 160 | + | provider.CloudAuth.AccessKey, |
| 161 | + | provider.CloudAuth.AccessSecret, |
| 162 | + | ) |
| 163 | + | |
| 164 | + | cpf := profile.NewClientProfile() |
| 165 | + | cpf.HttpProfile.Endpoint = SCFEndPoint |
| 166 | + | |
| 167 | + | // 创建 SFC 客户端 |
| 168 | + | client, err := scf.NewClient(credential, *provider.Region, cpf) |
| 169 | + | |
| 170 | + | if err != nil { |
| 171 | + | return "", err |
| 172 | + | } |
| 173 | + | |
| 174 | + | // SCF 需要一个 namespace |
| 175 | + | // 同阿里云一样,这里硬编码一个 code |
| 176 | + | nsRequest := scf.NewCreateNamespaceRequest() |
| 177 | + | |
| 178 | + | nsRequest.Namespace = common.StringPtr(serviceName) |
| 179 | + | nsRequest.Description = common.StringPtr(serviceDesc) |
| 180 | + | _, err = client.CreateNamespace(nsRequest) |
| 181 | + | if err != nil { |
| 182 | + | // 如果错误是 ns 存在,则忽略。 |
| 183 | + | if err, ok := err.(*fcError.TencentCloudSDKError); !ok || err.Code != scf.RESOURCEINUSE_NAMESPACE { |
| 184 | + | return "", err |
| 185 | + | } |
| 186 | + | } |
| 187 | + | |
| 188 | + | // 创建函数 |
| 189 | + | request := scf.NewCreateFunctionRequest() |
| 190 | + | |
| 191 | + | // 查询的时候只能用模糊匹配,sb, 得用个不会模糊的前缀区分 |
| 192 | + | fcName := "a" + strconv.Itoa(int(tun.CreatedAt.Unix())) + "-" + *tun.Name |
| 193 | + | |
| 194 | + | request.Namespace = common.StringPtr(serviceName) |
| 195 | + | request.FunctionName = common.StringPtr(fcName) |
| 196 | + | request.Description = common.StringPtr(string(*tun.Type)) |
| 197 | + | request.Type = common.StringPtr("HTTP") |
| 198 | + | // 腾讯云没有 cpu 大小设置选项 |
| 199 | + | request.MemorySize = common.Int64Ptr(int64(tun.TunnelConfig.Memory)) |
| 200 | + | // 需要记得打开 ws 支持 |
| 201 | + | request.ProtocolType = common.StringPtr("WS") |
| 202 | + | request.ProtocolParams = &scf.ProtocolParams{ |
| 203 | + | WSParams: &scf.WSParams{ |
| 204 | + | IdleTimeOut: common.Uint64Ptr(60), |
| 205 | + | }, |
| 206 | + | } |
| 207 | + | request.Timeout = common.Int64Ptr(600) |
| 208 | + | |
| 209 | + | port, err := strconv.Atoi(*tun.Port) |
| 210 | + | if err != nil { |
| 211 | + | return "", err |
| 212 | + | } |
| 213 | + | |
| 214 | + | request.AutoCreateClsTopic = common.StringPtr("FALSE") |
| 215 | + | |
| 216 | + | request.Code = &scf.Code{ |
| 217 | + | ImageConfig: &scf.ImageConfig{ |
| 218 | + | ImageType: common.StringPtr("personal"), |
| 219 | + | ImageUri: common.StringPtr("hkccr.ccs.tencentyun.com/seamoon/seamoon:" + consts.Version), |
| 220 | + | Command: common.StringPtr("/app/seamoon"), |
| 221 | + | Args: common.StringPtr("server -p " + *tun.Port + " -t " + string(*tun.Type)), |
| 222 | + | ImagePort: common.Int64Ptr(int64(port)), |
| 223 | + | }, |
| 224 | + | } |
| 225 | + | |
| 226 | + | if tun.TunnelConfig.Tor { |
| 227 | + | request.Environment = &scf.Environment{ |
| 228 | + | Variables: []*scf.Variable{ |
| 229 | + | { |
| 230 | + | Key: common.StringPtr("SEAMOON_TOR"), |
| 231 | + | Value: common.StringPtr("true"), |
| 232 | + | }, |
| 233 | + | }, |
| 234 | + | } |
| 235 | + | } |
| 236 | + | |
| 237 | + | request.PublicNetConfig = &scf.PublicNetConfigIn{ |
| 238 | + | PublicNetStatus: common.StringPtr("ENABLE"), |
| 239 | + | EipConfig: &scf.EipConfigIn{ |
| 240 | + | EipStatus: common.StringPtr("DISABLE"), |
| 241 | + | }, |
| 242 | + | } |
| 243 | + | |
| 244 | + | request.InstanceConcurrencyConfig = &scf.InstanceConcurrencyConfig{ |
| 245 | + | DynamicEnabled: common.StringPtr("FALSE"), |
| 246 | + | MaxConcurrency: common.Uint64Ptr(uint64(tun.TunnelConfig.Instance)), |
| 247 | + | } |
| 248 | + | |
| 249 | + | _, err = client.CreateFunction(request) |
| 250 | + | if err != nil { |
| 251 | + | if err, ok := err.(*fcError.TencentCloudSDKError); !ok || err.Code != scf.RESOURCEINUSE_FUNCTION { |
| 252 | + | return "", err |
| 253 | + | } |
| 254 | + | } |
| 255 | + | |
| 256 | + | // 查询等待状态正常 |
| 257 | + | // 尝试查询20次,每次等待1秒 |
| 258 | + | cnt := 0 |
| 259 | + | for cnt < 20 { |
| 260 | + | eRequest := scf.NewListFunctionsRequest() |
| 261 | + | eRequest.Namespace = common.StringPtr(serviceName) |
| 262 | + | eRequest.SearchKey = common.StringPtr(fcName) |
| 263 | + | |
| 264 | + | fc, err := client.ListFunctions(eRequest) |
| 265 | + | if err != nil { |
| 266 | + | return "", err |
| 267 | + | } |
| 268 | + | if *fc.Response.TotalCount != 1 { |
| 269 | + | return "", errors.New("查询到多余的函数") |
| 270 | + | } |
| 271 | + | xlog.Info("SDK", "正在等待函数创建成功...", "status", *fc.Response.Functions[0].Status, "cnt", cnt) |
| 272 | + | switch *fc.Response.Functions[0].Status { |
| 273 | + | case "Active": |
| 274 | + | cnt = 21 |
| 275 | + | case "Creating": |
| 276 | + | time.Sleep(1 * time.Second) |
| 277 | + | cnt++ |
| 278 | + | continue |
| 279 | + | default: |
| 280 | + | return "", errors.New(*fc.Response.Functions[0].StatusDesc) |
| 281 | + | } |
| 282 | + | } |
| 283 | + | |
| 284 | + | // 尝试创建触发器 |
| 285 | + | r := scf.NewCreateTriggerRequest() |
| 286 | + | r.TriggerName = common.StringPtr("apigw") |
| 287 | + | r.FunctionName = common.StringPtr(fcName) |
| 288 | + | r.Type = common.StringPtr("apigw") |
| 289 | + | |
| 290 | + | config, err := json.Marshal(&triggerDesc{ |
| 291 | + | Api: triggerDescApi{ |
| 292 | + | AuthRequired: func() string { |
| 293 | + | if tun.TunnelConfig.TunnelAuthType == types.Paris { |
| 294 | + | return "TRUE" |
| 295 | + | } |
| 296 | + | return "FALSE" |
| 297 | + | }(), |
| 298 | + | RequestConfig: struct { |
| 299 | + | Method string `json:"method"` |
| 300 | + | Path string `json:"path"` |
| 301 | + | }{Method: "GET", Path: "/"}, |
| 302 | + | IsIntegratedResponse: "FALSE", |
| 303 | + | IsBase64Encoded: "FALSE", |
| 304 | + | }, |
| 305 | + | Service: triggerDescService{ |
| 306 | + | ServiceName: "SCF_API_SERVICE", |
| 307 | + | ServiceType: "BASIC", |
| 308 | + | }, |
| 309 | + | Release: struct { |
| 310 | + | EnvironmentName string `json:"environmentName"` |
| 311 | + | }{EnvironmentName: "release"}, |
| 312 | + | }) |
| 313 | + | |
| 314 | + | // 触发器配置参数叫做 desc... |
| 315 | + | r.TriggerDesc = common.StringPtr(string(config)) |
| 316 | + | r.Namespace = common.StringPtr(serviceName) |
| 317 | + | |
| 318 | + | response, err := client.CreateTrigger(r) |
| 319 | + | if err != nil { |
| 320 | + | return "", err |
| 321 | + | } |
| 322 | + | |
| 323 | + | extractor := &triggerResp{} |
| 324 | + | desc := *response.Response.TriggerInfo.TriggerDesc |
| 325 | + | if err := json.Unmarshal([]byte(desc), extractor); err != nil { |
| 326 | + | return "", err |
| 327 | + | } |
| 328 | + | |
| 329 | + | return extractor.Service.SubDomain, nil |
| 330 | + | } |
| 331 | + | |
| 332 | + | func (t *SDK) sync(provider *models.CloudProvider) ([]fcInfo, error) { |
| 333 | + | credential := common.NewCredential( |
| 334 | + | provider.CloudAuth.AccessKey, |
| 335 | + | provider.CloudAuth.AccessSecret, |
| 336 | + | ) |
| 337 | + | |
| 338 | + | cpf := profile.NewClientProfile() |
| 339 | + | cpf.HttpProfile.Endpoint = SCFEndPoint |
| 340 | + | |
| 341 | + | // 创建 SFC 客户端 |
| 342 | + | client, err := scf.NewClient(credential, *provider.Region, cpf) |
| 343 | + | |
| 344 | + | if err != nil { |
| 345 | + | return nil, err |
| 346 | + | } |
| 347 | + | |
| 348 | + | request := scf.NewListFunctionsRequest() |
| 349 | + | request.Namespace = common.StringPtr(serviceName) |
| 350 | + | request.Limit = common.Int64Ptr(999999) |
| 351 | + | fcList, err := client.ListFunctions(request) |
| 352 | + | if err != nil { |
| 353 | + | return nil, err |
| 354 | + | } |
| 355 | + | var res = make([]fcInfo, 0) |
| 356 | + | // list 不够详细,需要继续处理 |
| 357 | + | for _, fc := range fcList.Response.Functions { |
| 358 | + | target := fcInfo{} |
| 359 | + | req := scf.NewGetFunctionRequest() |
| 360 | + | req.FunctionName = fc.FunctionName |
| 361 | + | req.Namespace = fc.Namespace |
| 362 | + | fcd, err := client.GetFunction(req) |
| 363 | + | if err != nil { |
| 364 | + | xlog.Error("SDK", "get function detail error", "name", *fc.FunctionName, "err", err) |
| 365 | + | continue |
| 366 | + | } else { |
| 367 | + | target.detail = fcd.Response |
| 368 | + | // 解析触发器 |
| 369 | + | trigger := fcd.Response.Triggers |
| 370 | + | if len(trigger) < 1 { |
| 371 | + | xlog.Error("SDK", "get function triggers error", "name", *fc.FunctionName, "err", err) |
| 372 | + | } else { |
| 373 | + | var tri triggerDesc |
| 374 | + | err := json.Unmarshal([]byte(*trigger[0].TriggerDesc), &tri) |
| 375 | + | if err != nil { |
| 376 | + | xlog.Error("SDK", "get function triggers json error", "name", *fc.FunctionName, "err", err) |
| 377 | + | } |
| 378 | + | target.addr = strings.Replace(tri.Service.SubDomain, "https://", "", -1) |
| 379 | + | target.auth = tri.Api.AuthType |
| 380 | + | } |
| 381 | + | } |
| 382 | + | |
| 383 | + | res = append(res, target) |
| 384 | + | } |
| 385 | + | return res, nil |
| 386 | + | } |
| 387 | + | |