How to differentiate whether the code is running in an emulator or in GKE when working with GCP's Datastore

5/29/2018

I am not sure whether I am missing any, after following the instructions given in https://cloud.google.com/datastore/docs/tools/datastore-emulator

I was not able to connect to local emulator unless I create Datastore explicitly using DataStoreClient.

DatastoreDb db = DatastoreDb.Create(projectId, string.Empty, new DatastoreClientImpl(
                new Datastore.DatastoreClient(
                    new Channel("localhost", 8081, ChannelCredentials.Insecure)), new DatastoreSettings()));

instead of just DatastoreDb.Create(projectId);

If we are working in GKE for production, we need to connect to actual Datastore not an emulator, how do we differentiate between the two versions with same code base.

Is there a way to check if code is running GKE, or is this something that should be done via by an environment variable for best results.

-- skjagini
c#
google-cloud-datastore
google-cloud-platform
google-kubernetes-engine

1 Answer

5/29/2018

You can use the Platform class in the Google.Api.Gax namespace (in the Google.Api.Gax package):

Platform platform = Platform.Instance();
switch (platform.Type)
{
    case PlatformType.Gae:
        // Code for AppEngine
        break;
    case PlatformType.Gce:
        // Code for Compute Engine
        break;        
    case PlatformType.Gke:
        // Code for Google Kubernetes Engine
        break;
    default:
        // Code for other contexts
        break;
}
-- Jon Skeet
Source: StackOverflow