How Cloud Storage delivers 11 nines of durability—and how you can help

One of the most fundamental aspects of any storage solution is durability—how well is your data protected from loss or corruption? And that can feel especially important for a cloud environment. Cloud Storage has been designed for at least 99.999999999% annual durability, or 11 nines. That means that even with one billion objects, you would likely go a hundred years without losing a single one! We take achieving our durability targets very seriously. In this post, we’ll explore the top ways we protect Cloud Storage data. At the same time, data protection is ultimately a shared responsibility (the most common cause of data loss is accidental deletion by a user or storage administrator), so we’ll provide best practices to help protect your data against risks like natural disasters and user errors.Physical durabilityMost people think about durability in the context of protecting against network, server, and storage hardware failures.At Google, our philosophy is that software is ultimately the best way to protect against hardware failures. This allows us to attain higher reliability at an attractive cost, instead of depending on exotic hardware solutions. We assume hardware will fail all the time—because it does! But that doesn’t mean durability has to suffer.To store an object in Cloud Storage, we break it up into a number of ‘data chunks’, which we place on different servers with different power sources. We also create a number of ‘code chunks’ for redundancy. In the event of a hardware failure (e.g., server, disk), we use data and code chunks to reconstruct the entire object. This technique is called erasure coding. In addition, we store several copies of the metadata needed to find and read the object, so that if one or more metadata servers fails, we can continue to access the object.The key requirement here is that we always store data redundantly across multiple availability zones before a write is acknowledged as successful. The encodings we use provide sufficient redundancy to support a target of more than 11 nines of durability against a hardware failure. Once stored, we regularly verify checksums to guard data at rest from certain types of data errors. In the case of a checksum mismatch, data is automatically repaired using the redundancy present in our encodings.Best practice: use dual-region or multi-region locationsThese layers of protection against physical durability risks are well and good, but they may not protect against substantial physical destruction of a region—think acts of war, an asteroid hit, or other large-scale disasters.Cloud Storage’s 11 nines durability target applies to a single region. To go further and protect against natural disasters that could wipe out an entire region, consider storing your most important data in dual-region or multi-region buckets. These buckets automatically ensure redundancy of your data across geographic regions. Using these buckets requires no additional configuration or API changes to your applications, while providing added durability against very rare, but potentially catastrophic, events. As an added benefit, these location types also come with significantly higher availability SLAs, because we can transparently serve your objects from more than one location if a region is temporarily inaccessible.Durability in transitAnother class of durability risks concerns corruption to data in transit. This could be data transferred across networks within the Cloud Storage service itself or when uploading or downloading objects to/from Cloud Storage.To protect against this source of corruption, data in transit within Cloud Storage is designed to be always checksum-protected, without exception. In the case of a checksum-validation error, the request is automatically retried, or an error is returned, depending on the circumstances.Best practice: use checksums for uploads and downloadsWhile Google Cloud checksums all Cloud Storage objects that travel within our service, to achieve end-to-end protection, we recommend that you provide checksums when you upload your data to Cloud Storage, and validate these checksums on the client when you download an object.Human-induced durability risksArguably the biggest risk of data loss is due to human error—not only errors made by us as developers and operators of the service, but also errors made by Cloud Storage users!Software bugs are potentially the single biggest risk to data durability. To avoid durability loss from software bugs, we take steps to avoid introducing data-corrupting or data-erasing bugs in the first place. We then maintain safeguards to detect these types of bugs quickly, with the aim of catching them before durability degradation turns into durability loss.To catch bugs up front, we only release a new version of Cloud Storage to production after it passes a large set of integration tests. These include exercising a variety of edge-case failure scenarios such as an availability zone going down, and comparing the behaviors of data encoding and placement APIs to previous versions to screen for regressions.Once a new software release is approved, we roll out upgrades in stages by availability zone, starting with a very limited initial area of impact and slowly ramping up until it is in widespread use. This allows us to catch issues before they have a large impact and while there are still additional copies of data (or a sufficient number of erasure code chunks) from which to recover, if needed. These software rollouts are monitored closely with plans in place for quick rollbacks, if necessary.There’s a lot you can do, too, to protect your data from being lost.Best practice: turn on object versioningOne of the most common sources of data loss is accidental deletion of data by a storage administrator or end-user. When you turn on object versioning, Cloud Storage preserves deleted objects in case you need to restore them at a later time. By configuring Object Lifecycle Management policies, you can limit how long you keep versioned objects before they are permanently deleted in order to better control your storage costs.Best practice: back up your dataCloud Storage’s 11-nines durability target does not obviate the need to back up your data. For example, consider what a malicious hacker might do if they obtained access to your Cloud Storage account. Depending on your goals, a backup may be a second data copy in another region or cloud, on-premises, or even physically isolated with an air gap on tape or disk.Best practice: use data access retention policies and audit logsFor long-term data retention, use the Cloud Storage bucket lock feature to set data retention policies and ensure data is locked for specific periods of time. Doing so prevents accidental modification/deletion, and when combined with data access audit logging, can satisfyregulatory and compliance requirements such as FINRA, SEC, and CFTC and certain health care industry retention regulationsBest practice: use role-based access control policiesYou can limit the blast radius of malicious hackers and accidental deletions by ensuring that IAM data access control policies follow the principles of separation of duties and least privilege. For example, separate those with the ability to create buckets from those who can delete projects.Encryption keys and durabilityAll Cloud Storage data is designed to always be encrypted at rest and in transit within the cloud. Because objects are unreadable without their encryption keys, the loss of encryption keys is a significant risk to durability—after all, what use is highly durable data if you can’t read it? With Cloud Storage, you have three choices for key management: 1) trust Google to manage the encryption keys for you, 2) use Customer Managed Encryption Keys (CMEK) with Cloud KMS, or 3) use Customer Supplied Encryption Keys (CSEK) with an external key server.Google takes similar steps as described earlier (including erasure coding and consistency checking) to protect the durability of the encryption keys under its control.Best practice: safeguard your encryption keysBy choosing either CMEK or CSEK to manage your keys, you take direct control of managing your own keys. It is vital in these cases that you also protect your keys in a manner that also provides at least 11 nines of durability. For CSEK, this means maintaining off-site backups of your keys so that you have a path to recovery even if your keys are lost or corrupted in some way. If such precautions are not taken, the durability of the encryption keys will determine the durability of the data.Going beyond 11 ninesGoogle Cloud takes the responsibility of protecting your data extremely seriously. In practice, the numerous techniques outlined here have allowed Cloud Storage to exceed 11 nines of annual durability to date. Add to that the best practices we shared in this guide, and you’ll help to ensure that your data is here when you need it—whether that be later today or decades in the future. To get started, check out this comprehensive collection of Cloud Storage how-to guides.Thanks to Dean Hildebrand, Technical Director, Office of the CTO, who is a coauthor of the document on which this post is based.
Quelle: Google Cloud Platform

Introducing Sqlcommenter: An open source ORM auto-instrumentation library

Object-relational mapping(ORM) helps developers to write queries using an object-oriented paradigm, which integrates naturally with application code in their preferred programming language. Many full-stack developers rely on ORM tools to write database code in their applications,  but since the SQL statements are generated by the ORM libraries, it can be harder for application developers to understand the application code resulting in slow query. The following example shows a snippet of code where 2 lines of Django application code are translated by an ORM library to a single SQL statement.Introducing SqlcommenterToday, we are introducing Sqlcommenter, an open source library that addresses the gap between the ORM libraries and understanding database performance. Sqlcommenter gives application developers visibility into which application code is generating slow queries and maps application traces to database query plans.Sqlcommenter is an open source library that enables ORMs to augment SQL statements before execution, with comments containing information about the code that caused its execution. This helps in easily correlating slow queries with source code and giving insights into backend database performance. In short, it provides observability into the state of client-side applications and their impact on database performance. Application developers need to do very little application code change to enable Sqlcommenter for their applications using ORMs. Observability information from Sqlcommenter can be used by application developers directly using slow query logs, or it can be integrated into other products or tools, such as Cloud SQL Insights, to provide application-centric monitoring.Getting started with SqlcommenterSqlcommenter is available for Python, Java, Node.js and Ruby languages and supports Django, Sqlalchemy, Hibernate, Knex, Sequelize and Rails ORMs. Let’s go over an example of how to enable Sqlcommenter for Django and look at how it helps to analyze Django application performance. Python InstallationSqlcommenter middleware for Django can be installed using the pip3 command.pip3 install –user google-cloud-sqlcommenterEnabling Sqlcommenter for DjangoTo enable Sqlcommenter in a Django application, you can edit your settings.py file to include google.cloud.sqlcommenter.django.middleware.SqlCommenter in the MIDDLEWARE section:Augment slow query logs with ORM informationSlow query logs provided by databases like PostgreSQL and MySQL help in finding and troubleshooting slow running queries. For example, in PostgreSQL, you can set the log_min_duration_statement database flag, and PostgreSQL will log the queries where the  duration is equal or greater than the value specified in log_min_duration_statement.  By augmenting slow query logs with application tags from the ORM, Sqlcommenter helps developers determine what application code is associated with a slow query. Here is an example of a query log from a PostgreSQL database that is used by a Django application with Sqlcommenter for Django enabled.In the above log, you can see an UPDATE statement being executed. At the end of the SQL statement, SQL style comments have been added in the form of key=value pairs, and we call the keys application tags.This comment is added by Sqlcommenter to the SQL query that was generated by the Django ORM.As you can see from the comments, it provides information about the controller, which in this example is “assign_order.” This is the controller method that sent the query. In the case of Django, the Controller in an MVC pattern maps to the View in a Django application. It also provides information about the Route through which this View in Django was called. Using this information, application developers can immediately relate which View method created this query. Since this query has taken 400 msec, an application developer can reason why this query created by the “assign_order” View method is expensive.Trace ORMs with OpenTelemetry integrationSqlcommenter allows OpenCensus and OpenTelemetry trace context information to be propagated to the database, enabling correlation between application traces and database query plans.The following example shows a query log with SQL comments added by Sqlcommenter for the Sequelize ORM.From the example query log above, you can see traceparent tags as part of the comment. The traceparent application tag is based on W3C Trace Context, which defines the standard for trace context propagation with trace id and span id. The traceparent application tag is created by Sqlcommenter using the context. Using the query log and traces from applications, application developers can relate their traces to a specific query. For more information on Context and Trace propagation, please see the OpenTelemetry specification. Application-centric monitoring with Cloud SQL Insights with the help of SqlcommenterLet us look at how the recently launched Cloud SQL Insights integrated with Sqlcommenter to help developers quickly understand and resolve query performance issues on Cloud SQL. Cloud SQL Insights helps you detect and diagnose query performance problems for Cloud SQL databases. It provides self-service, intuitive monitoring, and diagnostic information that goes beyond detection to help you to identify the root cause of performance problems. You can monitor performance at an application level and trace the source of problematic queries across the application stack by model, view, controller, route, user, and host. Cloud SQL Insights uses the information sent by Sqlcommenter to identify the top application tags (controller, route, etc.) that are sent by the application. The following example is an Insights dashboard for the Cloud SQL instance connected to the Django application we saw earlier. As you can see from the table in the screenshot below, top controller and route application tags are provided along with the other metrics for the application tags. These application tags are generated by the Sqlcommenter enabled in the Django application and Cloud SQL PostgreSQL uses these tags to identify the top application tags. This information is shown in the Cloud SQL Insights dashboard and also exported to Cloud Monitoring.The “assign_order” controller, which we saw earlier, is shown along with the route “demo/assign_order” as one of the top tags that is contributing to the database load.  For more details on you can use Insights, see the Cloud SQL Insights documentation.Using end-to-end traces in Cloud SQL InsightsOne issue with using query logs with traceparent is that it’s hard to visualize the query plan and application traces. With Cloud SQL Insights, query plans are generated as Cloud Traces with the traceparent context information from the SQL comments. Since the trace id is created by the application, and the parent span id is sent to the database as SQL comments, end-to-end tracing from application to database is now possible. You can visualize the end-to-end trace with a query plan as spans in the Cloud Trace dashboard. The example below shows application trace spans from OpenTelemetry along with query plan trace spans from the NodeJS Express Sqlcommenter library .Using this information, application developers can not only know the queries created by their application code, they can relate the query plan with application traces to diagnose their application performance issues.You can access these traces in Cloud SQL Insights by selecting an item in the Top Tags table. SummarySqlcommenter provides application developers using ORM tools the ability to diagnose performance issues in their application code impacting databases. With Cloud SQL Insights’ integration with Sqlcommenter, application developers can visualize the top application tags contributing to database load as well as trace end to end application performance problems. For more information on languages and ORM support for Sqlcommenter, or if you would like to contribute to the project, please visit the Sqlcommenter github repo.
Quelle: Google Cloud Platform

At Docker, we are committed to making developer’s lives easier, and maintaining and extending our commitment to the Open Source community and open standards for many of our projects. We believe building new capabilities into the Docker Platform in partnership with our developer community and in full transparency leads to much better software.

Last December, we announced the release of a new experimental Docker Hub CLI tool, also known as hub-tool. This new CLI lets you explore, inspect and manage your content on Docker Hub as well as work with your teams and manage your account. We demonstrated it during the last Docker Community All Hands in December 2020.

This tool is already available with Docker Desktop, so if you are a Windows or Mac user you can try it now. For Linux users, we are pleased to announce that we open sourced the hub-tool code, and it can be found at https://github.com/docker/hub-tool. You can download the binary directly on the release page.

With the open sourcing of hub-tool we have also cut a new v0.3.0 release which includes the following new features:

Added an optional argument to the account info command to check the status of an organization

Added a –platform flag to the tag inspect command to inspect a specific platform if the image is a multi-arch image

Give us feedback!

This tool is still experimental, but it needs feedback from you to improve. Please let us know on the hub-tool issue tracker.

The post 🧪 Open Sourcing the Docker Hub CLI Tool appeared first on Docker Blog.
Quelle: https://blog.docker.com/feed/

OpenStack Project Update 2020

Despite being a very different year than most, the Open Infrastructure community, which has over 110,000 community members, made it a productive and successful year. One of the biggest milestones that happened in the global community last year was that OpenStack, one of the top three most active open source projects with 15 million cores… Read more »
Quelle: openstack.org

Spoiled for choice: Deploying to 3 serverless platforms

I made a webapp called Hot Maze and tried to deploy it to App Engine, to Cloud Functions, and to Cloud Run. This is what I learned in the process.What is Hot MazeHot Maze is a web page that lets you share a photo or a document from your computer to your phone, using a QR code.It’s a fast, frictionless and secure way to transfer a resource, which doesn’t require any account creation or any password.Let’s see it in action. Here, sending a blue gopher:Conceptually, this is what happens within seconds when you drop a file (e.g. a kangaroo) to the Hot Maze web page:Your browser uploads it to a Cloud locationThe web page displays a QR code containing a URL to the Cloud locationYour phone scans and decodes the QR code, and downloads the resource.The exact request sequence would depend on the Cloud components we choose to orchestrate the file transfer. Here is a first sensible workflow using Google Cloud:You drop a file FThe web page asks the Cloud server for 2 unique one-time use URLs: one URL U to upload a file to a temporary location L in Cloud Storage, and another URL D to download the file from L.The web page now uses Uto uploadF to L.The web page encodes D into a QR codeQ and displays it.You scan Qwith a QR code scanner mobile app.The mobile decodes D.The mobile uses D to download Ffrom L.A few minutes later, F is permanently deleted from L.In this scenario, the mobile phone uses a standard QR code reader app (many choices available in the Play store and in the App Store) and then lets its default browser download the file without any extra logic on the phone side.This scenario is secure because no one else knows the secret URLs U and D, thus no one can see your file F or tamper with it. U and D use the HTTPS protocol. The Cloud location L is not publicly accessible.This article shows how to design the application Hot Maze and deploy it to different serverless products of Google Cloud. We’ll explore 3 alternatives: App Engine, Cloud Functions, and Cloud Run.A word about ServerlessThe three design choices discussed below have something in common: they are stateless. This means that the specific server instance that processes a given request does not hold data and is not regarded as a source of truth. This is a fundamental property of autoscaled serverless architectures. The user data (if any) lives in distinct stateful components: a database, a file storage, or a distributed memory cache.Design for App EngineApp Engine Standard is great if your stateless application meets these criteria:Handles HTTP(S) requestsIs statelessIs written in Go, Java, Python, Node.js, PHP, or RubyDoes not need to use the local filesystem or to install binary dependenciesCommunicates with other Google Cloud componentsHot Maze fits this description very well. It is written in Go, and we use Google Cloud Storage (GCS) as a temporary repository of user files. Hot Maze consists of 2 components:The Frontend (static assets): HTML, JS, CSS, images;The Backend: handlers that process the upload and download logic.The source code is available on GitHub. In the repo, this implementation (App Engine + Cloud Storage) is calledB1.Project structureGood news, it is simple and idiomatic to have the Go webapp serve both the Frontend and the Backend.The webapp code is not adherent to App Engine (GAE), it is a standard Go app that can be developed and tested locally. Only app.yaml is specific to App Engine: It specifies which App Engine runtime to use, and how to route the incoming requests.The webapp does not need to worry about HTTPS. The HTTPS termination happens upstream in the “Google Front End Service” (GFE), so the Go code doesn’t need to deal with certificates and encryption.It is a good practice to code the server logic in its own package at the root of the Go module, and have a “main” package executable program inside “cmd” that instantiates the server and listens to a specific port. For example, in my first App Engine implementation of Hot Maze, “github.com/Deleplace/hot-maze/B1″ is both the name of the module and the path of the server package.StorageI chose Cloud Storage to take care of temporary data storage, so I have a dependency to the GCS library cloud.google.com/go/storage. For security reasons (privacy), I don’t grant read and write access to a GCS bucket to anonymous internet users. Instead I’ll have my server generate Signed URLs to let an anonymous user upload and download a given file.FlowWhen a computer user drops a file to the Hot Maze web page, the first request is asking the backend to generate and return 2 URLs: one to let the browser upload the user file to GCS, and one to let the mobile phone download the file from GCS.This is all the information needed to proceed:Upload the file F to the “secure upload URL” UThen encode and display the secure download URL D in a QR codeThe download URL is sufficient to retrieve the file directly from GCS. Ideally, the mobile phone (with a QR code scanner app) would not need to communicate with the App Engine backend at all. See the section Shorter URLs below to discover why we will in fact have the mobile device hit the App Engine service.Serving static assetsThe Frontend part of the app consists of an HTML file, a JS file, a CSS file, and a few images. It may be served by the same server instances as the Backend part, or by different servers, possibly under a different domain name.Go serverThe straightforward path is to have our Go server handle all the requests to the (static) Frontend and to the (dynamic) Backend. This is how we serve all of the contents of a given folder:This approach works exactly the same in local development and in production. Each incoming request to a static file is handled by the Go code of the server instance.Static file handlers in app.yamlIt is also possible to declare the static assets in app.yaml.This has some advantages:The requests for static assets will be handled by a CDN-like file server, not from your App Engine instances;The static assets may be served slightly faster;The static assets don’t experience cold starts. They are fast even when zero instances are running.The request logs still show up in the Cloud Logging console.This may decrease the pressure on my App Engine instances, improve their throughput of dynamic requests, and decrease the total number of occurrences of cold starts (loading latency) for scaling up.  If you use this optimization, I suggest that you keep the Go handler for static files (with http.FileServer), which continues to work for local development. This is now a component that works differently in development and in production, so you will have to keep this fact in mind during QA testing, and be careful not to introduce discrepancies between the app.yaml and the Go code (e.g. the exact set of files and folders, the cache response headers, etc.).The built-in CDN is such a nice and useful feature of App Engine that we should keep it in mind when considering the serverless options for a new project.Shorter URLsThere’s a gotcha: Signed URLs have lengthy crypto parameters, thus are pretty long: 500+ characters.Long URLs are fine for computers, however they’re not great for humans (if one ever needs to type it) and for QR codes. The full-length Signed URL above technically can fit in a standard QR code, but the resulting picture is so complex and full of tiny patterns that your mobile QR code scanner app will have troubles to properly read it.The Upload URL U is used as-is in its full-length form: your browser receives it inside a JSON response, and uses it immediately in JS to upload your resource.However, the Download URL D in full-length is not really appropriate to encode in a QR code. To fix this, we create an extra indirection: a Shortened Download URL containing only the UUID of the resource file. When the mobile device scans the QR code and extracts the short URL, it asks App Engine for the matching full-length URL to the resource in Cloud Storage.This URL shortening process adds a small delay of 1 roundtrip to the App Engine service. It also adds some (moderate) server logic, as the service needs to somehow remember the mapping between the Short D URL and the Long Signed D URL. It has the great benefit of leveraging a QR code that’s actually usable in practice.CleanupWe don’t need and don’t want to keep the user data more than a few minutes in the Cloud servers.Let’s schedule its automatic deletion after 9mn with Cloud Tasks. This is done in three parts:Creation of a new task queue$ gcloud tasks queues create b1-file-expiryA /forget handler that deletes a resource immediately: sourceA Task object that will hit /forget?uuid=<id> 9mn after the signed URLs generation: sourceA request header check ensures that the file deletion is not a public-facing service: It may only be triggered by the task queue.The Signed URLs themselves are short-lived, so the clients may upload and download only for 5mn after URL generation. The cleanup serves other purposes:Reduce storage costs, by deleting obsolete data;Foster privacy by making sure the cloud service doesn’t hold any copy of the user data longer than necessary.PrivacyThe service doesn’t require any account creation, authentication, or password.It is secure because user data can’t be intercepted by third parties:Transport encryption: upload and download use HTTPS,Data encryption at rest in Cloud Storage,Use of a nonce UUID to identify a resource, generated by the package github.com/google/uuid, which uses crypto/rand.Generation of secure Signed URLs that can’t be forged,Signed URLs expire after 5 minutes,User data is deleted after 9 minutes.However, this is different from what we call “end-to-end encryption” (E2EE). The Hot Maze service owner (me) could access the GCS bucket and see the user files before they are deleted. Implementing E2EE would be an interesting project… maybe the material for a future article.Cloud Storage bucket configurationEven with proper Signed URLs, the web browser must still be allowed to access the specific Cloud Storage bucket. If not configured, the browser may refuse and throwAccess to XMLHttpRequest from origin has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.I need to explicitly configure CORS to allow all domain names that may need legit write access (PUT) to the bucket. For this I create a bucket_cors.json file:Then I apply it with:$ gsutil cors set bucket_cors.json gs://hot-maze.appspot.com “hot-maze.appspot.com” looks like a domain name but here it is the name of the bucket that I use to store the temporary files.Cloud Storage access for local development environmentNote that the JSON above includes a localhost domain. This is necessary for the development phase. It is fine to keep this configuration even after the app has been deployed to production. It does not constitute an extra security risk.Service AccountsIt turns out that generating a GCS Signed URL with the Go client library requires a service account private key, having proper permissions. So I visited IAM, created an account ephemeral-storage@hot-maze.iam.gserviceaccount.com and gave it the role “Storage Admin”.Now I can download and use its private key, but there’s no way I’d check in such a sensitive secret in my code repo! Instead I stored the private key in Secret Manager. Then I made sure to grant the role “Secret Manager Secret Accessor” to the App Engine default service account. That’s quite a lot of indirections! The rationale is:To perform a sensitive operation, the backend must be authenticated somehow, but it is not sufficient;Additionally it requires a private key, which is a secret;It is then able to generate an upload URL to be used by an anonymous user of the service;The App Engine backend is automatically authenticated in production;Now the local development environment needs to deal with an explicit service account, in order to read the secret from Secret Manager.Local developmentFrom folder B1:$ export GOOGLE_APPLICATION_CREDENTIALS=/local/path/to/sa.json$ go run github.com/Deleplace/hot-maze/B1/cmd/backendNote that even if the main program is in cmd/backend, we run it from the root directory of the Go module, so that it correctly finds the static folder.The service account key sa.json was downloaded from the IAM web console and stored somewhere in my local file system. It is not intended to be checked in with the source code.DeploymentPrerequisite: I’m already authenticated in the command line tool gcloud, and my active project is hot-maze. From folder B1:$ gcloud app deployThis takes 2 minutes to complete. A new version is deployed as we can see in the web console. It is now accessible at two equivalent URLs:https://hot-maze.uc.r.appspot.comhttps://b1-dot-hot-maze.uc.r.appspot.comIt’s live!Design for Cloud FunctionsUsing Cloud Functions (GCF) to process the incoming events is a lightweight option with fine granularity. GCF is appropriate to process events asynchronously or synchronously. See the source code of the B2 implementation using GCF, GCS and Firebase Hosting.Frontend structure (static assets)The main difference with the first option is that Cloud Functions is not a “web backend” designed to serve HTML pages and resources. For this, we’ll use Firebase Hosting. Let’s:run firebase init in a frontend project folder, and follow the instructions.store index.html and the static folders inside the new firebase public folder.deploy the Frontend with$ firebase deployNote: by default the assets served by Firebase have a header cache-control: max-age=3600 (one hour).Firebase Hosting serves requests from a global CDN.Backend structureAnother difference is that Cloud Functions written in Go are not “standard” Go web servers. To develop and test them locally, we need the Functions framework.In the case of my app:It is still a good idea to have my server business logic in its “hotmaze” package at the root of the Go moduleWe don’t register handlers with http.HandleFunc anymoreFor local dev, we have a main package that calls funcframework.RegisterHTTPFunctionContext for each exposed Function.Note that some configuration values are now provided inside the package “hotmaze” instead of the package “main”. That’s because the executable cmd/backend/main.go will not be used in production. We don’t deploy executables or full servers to GCF. Instead, we deploy each Function separately:$ gcloud functions deploy B2_SecureURLs   –runtime go113 –trigger-http –allow-unauthenticated$ gcloud functions deploy B2_Get   –runtime go113 –trigger-http –allow-unauthenticated$ gcloud functions deploy B2_Forget   –runtime go113 –trigger-http –allow-unauthenticatedThere are 3 deploy commands, because we have 3 dynamic handlers in the backend: one to generate secure URLs, one to redirect from a Short URL to a full-length GCS Signed URL, and one to delete a resource from GCS.The total number of commands to deploy the full application is 4. It is possible to redeploy the Frontend only, or to redeploy only a single Function.It’s live!Local developmentThe Frontend and the Backend are running at a different port.Let’s be explicit in firebase.json and host the Fronted at port 8081:Then, in a first terminal:$ cd B2/frontend$ firebase emulators:startFinally, I run the Backend in the default port 8080 in a second terminal:$ cd B2/backend$ go run cmd/backend/main.goCloud Functions for FirebaseFirebase has a nice built-in integration with Cloud Functions for Javascript functions.My backend is written in Go, which is why I’m using the “traditional” Cloud Functions.Design for Cloud RunCloud Run lets me package the Frontend and the Backend in a Docker image, and deploy this image to production. In the source repo, this implementation (Cloud Run + Cloud Storage) is called B3.With Cloud Run come all the benefits of working with containers, and a few more:I can code in any language I want,using arbitrary binary dependencies (that can work in Linux),same container for local dev, QA, and production,one single container to host the static assets and the dynamic handlers,autoscaling from zero up to many,fast cold starts,and no complex cluster to manage (this is done by the cloud vendor).Project structureThe idiomatic Go webapp serves both the Frontend and the Backend. The structure is similar to the B1 (App Engine)implementation.Using a DockerfileTo package the server (Frontend + Backend) into a Docker image, we first compile the server for the target platform linux amd64. $ go build -o server github.com/Deleplace/hot-maze/B3/cmd/backendThen we ship the executable binary, as well as the folder of static assets. We don’t need to ship the Go source code. The Quickstart sample helps us write a Dockerfile to produce an image with proper CA certificates:Note:Go 1.16 will make it possible to bundle all resources inside the server executable file, thus not copy the static folder in the Dockerfile.Service accountsA deployed Cloud Run service comes with a default Service account enabled.I had to take a minute in IAM to grant it the role “Secret Manager Secret Accessor”As explained in the B1 section, accessing secrets lets us retrieve the service account ephemeral-storage@hot-maze.iam.gserviceaccount.com, which is allowed to generate Signed URLs to our GCS bucket.Local developmentWhen we “just start” our Docker container locally though, there’s no Service account automagically injected. And I would certainly not recommend copying a Service account private key in the Dockerfile, at the risk of checking it in the source repo of container registry.Following the Cloud Run documentation for local testing, I pass my service account JSON key file as arguments to the docker run command:$ export GOOGLE_APPLICATION_CREDENTIALS=/local/path/to/sa.json$ docker build -t hotmaze-b3 . $ docker run -p 8080:8080    -e GOOGLE_APPLICATION_CREDENTIALS=/tmp/keys/sa.json -v    $GOOGLE_APPLICATION_CREDENTIALS:/tmp/keys/sa.json:ro    hotmaze-b3The server is started and available at http://localhost:8080 .The service account key sa.json was downloaded from the IAM web console and stored somewhere in my local file system. It is not intended to be checked in with the source code.DeploymentThese commands compile the Go web server, build an Docker image, push it to Container Registry, and deploy it to Cloud Run:$ go build -o server github.com/Deleplace/hot-maze/B3/cmd/backend$ docker build -t hotmaze-b3 .$ gcloud builds submit –tag gcr.io/hot-maze/hot-maze-b3$ gcloud run deploy hot-maze    –image gcr.io/hot-maze/hot-maze-b3    –platform managed –allow-unauthenticatedThis overwrites the tag latest every time I deploy. For proper versioning, I may want to use more specific tag names such as release-1.0.0.Caveat:if the –allow-unauthenticated flag fails for some reason (“Setting IAM policy failed…”), then one may have to run an extra gcloud command provided in the error message, or in the web console go to Cloud Run > Service > Permissions > Add member “allUsers” and grant it the role “Cloud Run Invoker”.It’s live!Using BuildpacksWriting a correct Dockerfile and deploying a container is more complex than “just deploying the code” to e.g. App Engine.However, Buildpacks are a Cloud Native way to seamlessly containerize and deploy an app from its source code. The main difference with the previous section is that I don’t need a Dockerfile.Following these instructions, here is how I can deploy Hot Maze to Cloud Run:$ pack set-default-builder gcr.io/buildpacks/builder:v1$ pack build –publish gcr.io/hot-maze/hot-maze$ gcloud run deploy –image gcr.io/hot-maze/hot-maze –platform managed –allow-unauthenticatedIts live as well!Static filesFor aforementioned strategic reasons, one may want to have a CDN serve the static assets, e.g. Google Cloud CDN. This part is optional and most useful when the app serves a lot of traffic.Further workWe’ve already seen two performance optimizations:Using a CDN for static assets,Reducing the complexity of the QR code, with URL shortening.I can think of a lot more possible improvements of UX, simplicity and performance. I keep those for potential future articles!ConclusionIn this article we’ve seen how we can structure an app of moderate complexity in order to deploy it to three different serverless platforms in Google Cloud.All of them are valid choices: App Engine + Cloud StorageCloud Functions + Firebase hosting + Cloud StorageCloud Run + Cloud Storage.You may choose the one that best fits your needs depending on the details of your own workflow, or on unique features of one of them. For example if your app is already packaged as a Docker container, then Cloud Run is the best choice.If you wish to learn more about the services mentioned above, please check out these resources:App Engine Standard Environment for GoCloud Functions for GoCloud RunFirebase HostingCloud StorageCloud Storage Signed URLsServing Static Files with App EngineService accountsSecret ManagerCloud LoggingContainer RegistryBuildpacksCloud CDNFree things in Google Cloud90-day $300 Free Trial of Google Cloud
Quelle: Google Cloud Platform