【问题标题】:Schedule to stop and start instance on Google Cloud Platform - Cloud Scheduler it's the Cloud Function安排在 Google Cloud Platform 上停止和启动实例 - Cloud Scheduler 它是 Cloud Function
【发布时间】:2020-11-17 19:26:28
【问题描述】:

我有以下需求。我希望每天早上 5:00 重新启动我的实例,所以我阅读了自动化它的最佳方法是使用 Cloud Scheduler 和 Cloud Function,但我不知道这两个 GCP 功能。

我在 Cloud Scheduler 中创建了两个计划,其中我的 VM 实例在早上 5:00 STOP 和另一个在早上 5:10 START,但我没有不知道如何在 Cloud Function 中进行以结束我的进程。

有人可以帮我解决这个问题吗?拥抱大家!

在尝试实施时查看我的项目错误日志

错误

{ "jobName": "projects/my-project/locations/us-central1/jobs/Stop", "@type": "type.googleapis.com/google.cloud.scheduler.logging.AttemptFinished", "status": "INTERNAL", "url": "https://us-central1-my-project.cloudfunctions.net/power/stop?zone=us-central1-a&instance=my-instance", "targetType": "HTTP" }

###############

    {
insertId: "1klx7n3g18eq5zs"
jsonPayload: {
jobName: "projects/my-project/locations/us-central1/jobs/Stop"
@type: "type.googleapis.com/google.cloud.scheduler.logging.AttemptFinished"
status: "INTERNAL"
url: "https://us-central1-my-project.cloudfunctions.net/power/stop?zone=us-central1-a&instance=my-instance"
targetType: "HTTP"
}
httpRequest: {
status: 500
}
resource: {
type: "cloud_scheduler_job"
labels: {
location: "us-central1"
project_id: "my-project"
job_id: "Stop"
}
}
timestamp: "2020-08-07T08:00:06.896367090Z"
severity: "ERROR"
logName: "projects/my-project/logs/cloudscheduler.googleapis.com%2Fexecutions"
receiveTimestamp: "2020-08-07T08:00:06.896367090Z"
}

【问题讨论】:

    标签: google-cloud-platform google-cloud-functions google-cloud-scheduler


    【解决方案1】:

    我的项目有相同的用例,我使用这个 python 函数来启动和停止虚拟机,我的函数可以处理路径 startstop

    from flask import Flask, request, abort
    import os
    import logging
    
    app = Flask(__name__)
    
    
    @app.route('/')
    @app.route('/<path:path>')
    def power(path=None):
        #this libraries are mandatory to reach compute engine api
        from googleapiclient import discovery
        from oauth2client.client import GoogleCredentials
    
    
        #the function will take the service account of your function
        credentials = GoogleCredentials.get_application_default()
    
        #this line is to specify the api that we gonna use, in this case compute engine    
        service = discovery.build('compute', 'v1', credentials=credentials, cache_discovery=False)
        logging.getLogger('googleapiclient.discovery_cache').setLevel(logging.ERROR)
    
        # Project ID for this request.
        project = yourprojectID  # Update placeholder value.
        zone = request.args.get('zone', None)
        instance = request.args.get('instance', None)
    
        #call the method to start or stop the instance
        if (request.path == "/stop"):
            req = service.instances().stop(project=project, zone=zone, instance=instance)
    
        elif (request.path == "/start"):
            req = service.instances().start(project=project, zone=zone, instance=instance)
        else:
            abort(418)
        #execute the command
        response = req.execute()
    
        print(response)
        return ("OK")
    
    
    if __name__ == '__main__':
        app.run(port=3000, debug=True)
    
    

    requirements.txt 文件

    google-api-python-client
    oauth2client
    flask
    

    调度器配置

    1. Create a service accountfunctions.invoker permission 在你的函数中
    2. Create new Cloud scheduler job
    3. 以 cron 格式指定频率。
    4. 将 HTTP 指定为目标类型。
    5. 一如既往地添加您的云函数和方法的 URL。
    6. 从 Auth 标头下拉列表中选择令牌 OIDC
    7. 在服务帐户文本框中添加服务帐户电子邮件。
    8. audience field中只需要写函数的URL,不需要任何附加参数

    在云调度程序上,我使用这些 URL 来实现我的功能

    https://us-central1-yourprojectID.cloudfunctions.net/power/stop?zone=us-central1-a&amp;instance=instance-1

    https://us-central1-yourprojectID.cloudfunctions.net/power/stop?zone=us-central1-a&amp;instance=instance-1

    我使用了这些观众

    https://us-central1-yourprojectID.cloudfunctions.net/power

    请在代码和网址中替换yourprojectID

    us-central1是我的函数所在的区域,power是我的函数的名称,us-central1-a是我的实例所在的区域,instance-1是我的实例的名称

    Java 更新

    Cloud 函数支持 java11 和 maven,但这是测试版

    首先你需要这个依赖,请将以下几行添加到你的 pom.xml 文件中:

        <dependency>
          <groupId>com.google.apis</groupId>
          <artifactId>google-api-services-compute</artifactId>
          <version>beta-rev20200629-1.30.10</version>
        </dependency>
        <dependency>
          <groupId>com.google.api-client</groupId>
          <artifactId>google-api-client</artifactId>
          <version>1.30.10</version>
        </dependency>
    

    启动虚拟机的云功能

    package com.example;
    
    import com.google.cloud.functions.HttpFunction;
    import com.google.cloud.functions.HttpRequest;
    import com.google.cloud.functions.HttpResponse;
    import java.io.BufferedWriter;
    import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
    import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.json.jackson2.JacksonFactory;
    import com.google.api.services.compute.Compute;
    import com.google.api.services.compute.model.Operation;
    import java.io.IOException;
    import java.security.GeneralSecurityException;
    import java.util.Arrays;
    
    public class Example implements HttpFunction {
      @Override
      public void service(HttpRequest request, HttpResponse response) throws Exception, IOException, GeneralSecurityException {
        
        
        // Project ID for this request.
        String project = "my-project"; // TODO: Update placeholder value.
    
        // The name of the zone for this request.
        String zone = "my-zone"; // TODO: Update placeholder value.
    
        // Name of the instance resource to start.
        String instance = "my-instance"; // TODO: Update placeholder value.
    
        Compute computeService = createComputeService();
    
        // you can change the method start to stop 
        Compute.Instances.Start request = computeService.instances().start(project, zone, instance);
        
        Operation xresponse = xrequest.execute();
    
        // TODO: Change code below to process the `response` object:
        System.out.println(xresponse);
    
        BufferedWriter writer = response.getWriter();
        writer.write("Done");
    
    
      }
    
      public static Compute createComputeService() throws IOException, GeneralSecurityException {
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    
        GoogleCredential credential = GoogleCredential.getApplicationDefault();
        if (credential.createScopedRequired()) {
          credential =
              credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));
        }
    
        return new Compute.Builder(httpTransport, jsonFactory, credential)
            .setApplicationName("Google-ComputeSample/0.1")
            .build();
      }
    
    }
    

    有关更多信息,您可以查看此文档中的 document 是不同编程语言的一些示例

    【讨论】:

    • JAHernández 感谢您的提示,我将分析您的回复,有人有 java 的东西吗?
    • 在本文档中你可以找到如何使用java调用应用引擎api cloud.google.com/compute/docs/reference/rest/beta/instances/…
    • @JAHernández 谢谢你很快的祝贺,我会尽力解决任何疑问。
    • @JAHernández 我用日志和文件更新了我的问题
    • @Jarciano,如您的错误日志中所示,有必要在service 中重命名变量requestresponse,请检查我的答案中的更新代码,现在这个变量被称为xrequest & xresponse
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    • 2017-09-21
    • 2021-03-25
    • 2021-01-15
    相关资源
    最近更新 更多