import "google/protobuf/empty.proto"; // A simple Bookstore API. // // The API manages shelves and books resources. Shelves contain books. service Bookstore { // Returns a list of all shelves in the bookstore. rpc CreateShelf(CreateShelfRequest) returns (Shelf) {} // Returns a specific bookstore shelf. rpc GetShelf(GetShelfRequest) returns (Shelf) {} } // A shelf resource. message Shelf { // A unique shelf id. int64 id = 1; // A theme of the shelf (fiction, poetry, etc). string theme = 2; } // Request message for CreateShelf method. message CreateShelfRequest { // The shelf resource to create. Shelf shelf = 1; } // Request message for GetShelf method. message GetShelfRequest { // The ID of the shelf resource to retrieve. int64 shelf = 1; }
type: google.api.Service config_version: 3 name: bookstore.endpoints..cloud.goog title: Bookstore gRPC API apis: - name: endpoints.examples.bookstore.Bookstore Http: rules: # 'CreateShelf' can be called using the POST HTTP verb and the '/shelves' URL # path. The posted HTTP body is the JSON respresentation of the 'shelf' field # of 'CreateShelfRequest' protobuf message. # # Client example: # curl -d '{"theme":"Music"}' http://DOMAIN_NAME/v1/shelves # - selector: endpoints.examples.bookstore.Bookstore.CreateShelf post: /v1/shelves body: shelf # # 'GetShelf' is available via the GET HTTP verb and '/shelves/{shelf}' URL # path, where {shelf} is the value of the 'shelf' field of 'GetShelfRequest' # protobuf message. # # Client example - returns the first shelf: # curl http://DOMAIN_NAME/v1/shelves/1 # - selector: endpoints.examples.bookstore.Bookstore.GetShelf get: /v1/shelves/{shelf}
# # Request authentication. # authentication: providers: - id: google_service_account # Replace SERVICE-ACCOUNT-ID with your service account's email address. issuer: SERVICE-ACCOUNT-ID jwks_uri: https://www.googleapis.com/robot/v1/metadata/x509/SERVICE-ACCOUNT-ID rules: # This auth rule will apply to all methods. - selector: "*" requirements: - provider_id: google_service_account
blogs/endpointslambda/aeflex-endpoints/
@app.route('/processmessage', methods=['POST']) def process(): """Process messages with information about S3 objects""" message = request.get_json().get('inputMessage', '') # add other processing as needed # for example, add event to PubSub or # download object using presigned URL, save in Cloud Storage, invoke ML APIs return jsonify({'In app code for endpoint, received message': message})
host: "echo-api.endpoints.aeflex-endpoints.cloud.goog"
inputMessage
# This section configures the processmessage endpoint. "/processmessage": post: description: "Process the given message." operationId: "processmessage" produces: - "application/json" responses: 200: description: "Return a success response" schema: $ref: "#/definitions/successMessage" parameters: - description: "Message to process" in: body name: inputMessage required: true schema: $ref: "#/definitions/inputMessage" security: - api_key: [] definitions: successMessage: properties: message: type: string inputMessage: # This section contains information about the S3 bucket and object to be processed. properties: Bucket: type: string ObjectKey: type: string ContentType: type: string ContentLength: type: integer ETag: type: string PresignedUrl: type: string
gcloud service-management deploy openapi.yaml
Service Configuration [2017-03-05r2] uploaded for service "echo-api.endpoints.aeflex-endpoints.cloud.goog"
endpoints_api_service: # The following values are to be replaced by information from the output of # 'gcloud service-management deploy openapi.yaml' command. name: echo-api.endpoints.aeflex-endpoints.cloud.goog config_id: 2017-03-05r2
gcloud app deploy
blogs/endpointslambda/lambdafunctioninline.py.
from __future__ import print_function import boto3 import json import os import urllib import urllib2 print('Loading function') s3 = boto3.client('s3') endpoint_api_key = os.environ['ENDPOINT_API_KEY'] endpoint_url = "https://aeflex-endpoints.appspot.com/processmessage" def lambda_handler(event, context): # Get the object information from the event bucket = event['Records'][0]['s3']['bucket']['name'] object_key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8')) try: # Retrieve object metadata response = s3.head_object(Bucket=bucket, Key=object_key) # Generate pre-signed URL for object presigned_url = s3.generate_presigned_url('get_object', Params = {'Bucket': bucket, 'Key': object_key}, ExpiresIn = 3600) data = {"inputMessage": { "Bucket": bucket, "ObjectKey": object_key, "ContentType": response['ContentType'], "ContentLength": response['ContentLength'], "ETag": response['ETag'], "PresignedUrl": presigned_url } } headers = {"Content-Type": "application/json", "x-api-key": endpoint_api_key } # Invoke Cloud Endpoints API request = urllib2.Request(endpoint_url, data = json.dumps(data), headers = headers) response = urllib2.urlopen(request) print('Response text: {} \nResponse status: {}'.format(response.read(), response.getcode())) return response.getcode() except Exception as e: print(e) print('Error integrating lambda function with endpoint for the object {} in bucket {}'.format(object_key, bucket)) raise e
GCP_IAAP_AUTH_TOKEN
Authorization: bearer
GCP_IAAP_XSRF_NONCE
aud: https://www.googleapis.com/oauth2/v4/token
exp
iat
iss
target_audience
roles/iap.httpsResourceAccessor
import "cloud.google.com/go/trace"
traceClient, err = trace.NewClient(ctx, "project-id") if err != nil { log.Fatal(err) }
func fetchUsers() ([]*User, error) { span := traceClient.NewSpan("/users") defer span.Finish() // Create the outgoing request, a GET to the users endpoint. req, _ := http.NewRequest("GET", "https://userservice.corp/users", nil) // Create a new child span to identify the outgoing request, // and attach tracing information to the request. rspan := span.NewRemoteChild(req) defer rspan.Finish() res, err := http.DefaultClient.Do(req) if err != nil { return nil, err } // Read the body, unmarshal, and return a slice of users. // ... }
func usersHandler(w http.ResponseWriter, r *http.Request) { span := traceClient.SpanFromRequest(r) defer span.Finish() req, _ := http.NewRequest("GET", "https://meta.service/info", nil) child := span.NewRemoteChild(req) defer child.Finish() // Make the request… }
var tc *trace.Client // initiate the client req, _ := http.NewRequest("GET", "https://userservice.corp/users", nil) res, err := tc.NewHTTPClient(nil).Do(req) if err != nil { // TODO: Handle error. }
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { span := trace.FromContext(r.Context()) // TODO: Use the span. }) http.Handle("/foo", tc.HTTPHandler(handler))
deploy-to-kubernetes-staging: image: codefreshio/kubernetes-deployer:master tag: latest working-directory: ${{initial-clone}} commands: - /deploy/bin/deploy.sh ./root environment: - ENVIRONMENT=${{ENVIRONMENT}} - KUBERNETES_USER=${{KUBERNETES_USER}} - KUBERNETES_PASSWORD=${{KUBERNETES_PASSWORD}} - KUBERNETES_SERVER=${{KUBERNETES_SERVER}} - DOCKER_IMAGE_TAG=${{CF_REVISION}}
“Google Cloud Speech API performs highly accurate speech-to-text transcription in near-real-time. The higher accuracy rates mean we can help dealers get the most out of phone interactions with their customers and increase sales.” — Gary Graves, CTO and Co-Founder, InterActiveTel
resource "google_compute_instance" "blog" { name = "default" machine_type = "n1-standard-1" zone = "us-central1-a" disk { image = "debian-cloud/debian-8" } disk { type = "local-ssd" scratch = true } network_interface { network = "default" } }
$ terraform plan + google_compute_instance.default can_ip_forward: "false" create_timeout: "4" disk.#: "2" disk.0.auto_delete: "true" disk.0.disk_encryption_key_sha256: "" disk.0.image: "debian-cloud/debian-8" disk.1.auto_delete: "true" disk.1.disk_encryption_key_sha256: "" disk.1.scratch: "true" disk.1.type: "local-ssd" machine_type: "n1-standard-1" metadata_fingerprint: "" name: "default" self_link: "" tags_fingerprint: "" zone: "us-central1-a" $ terraform apply google_compute_instance.default: Creating... can_ip_forward: "" => "false" create_timeout: "" => "4" disk.#: "" => "2" disk.0.auto_delete: "" => "true" disk.0.disk_encryption_key_sha256: "" => "" disk.0.image: "" => "debian-cloud/debian-8" disk.1.auto_delete: "" => "true" disk.1.disk_encryption_key_sha256: "" => "" disk.1.scratch: "" => "true" disk.1.type: "" => "local-ssd" machine_type: "" => "n1-standard-1" metadata_fingerprint: "" => "" name: "" => "default" network_interface.#: "" => "1" network_interface.0.address: "" => "" network_interface.0.name: "" => "" network_interface.0.network: "" => "default" self_link: "" => "" tags_fingerprint: "" => "" zone: "" => "us-central1-a" google_compute_instance.default: Still creating... (10s elapsed) google_compute_instance.default: Still creating... (20s elapsed) google_compute_instance.default: Creation complete (ID: default) Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
resource "google_project" "blog" { name = "blog-demo" project_id = "blog-demo-491834" billing_account = "${var.billing_id}" org_id = "${var.org_id}" } resource "google_project_services" "blog" { project = "${google_project.blog.project_id}" services = [ "iam.googleapis.com", "cloudresourcemanager.googleapis.com", "cloudapis.googleapis.com", "compute-component.googleapis.com", ] } resource "google_compute_instance" "blog" { # ... project = "${google_project.blog.project_id}" # <-- ...="" code="" new="" option="">-->
$ terraform apply google_compute_instance.default: Refreshing state... (ID: default) google_project.my_project: Creating... name: "" => "blog-demo" number: "" => "" org_id: "" => "1012963984278" policy_data: "" => "" policy_etag: "" => "" project_id: "" => "blog-demo-491834" skip_delete: "" => "" google_project.my_project: Still creating... (10s elapsed) google_project.my_project: Creation complete (ID: blog-demo-491835) Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
project_creation
git clone
examples/v2/project_creation
gcloud deployment-manager deployments create <newproject_deployment> --config config.yaml --project <Project Creation project>
require "google/cloud/logging" logging = Google::Cloud::Logging.new logger = logging.logger "my_app_log", resource, env: :production logger.info "Job started" logger.info { "Job started" } logger.debug?
$> gsutil notification create -f json -t your-topic gs://your-bucket
$> gcloud beta functions deploy helloWorld --stage-bucket cloud-functions --trigger-bucket your-bucket
Demonstrate your proficiency to design, build and manage solutions on Google Cloud Platform.