1 /* 2 * Copyright 2018, OpenCensus Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package io.opencensus.contrib.resource.util; 18 19 import static com.google.common.base.MoreObjects.firstNonNull; 20 21 import io.opencensus.resource.Resource; 22 import java.util.ArrayList; 23 import java.util.Collections; 24 import java.util.List; 25 26 /** 27 * Utilities for auto detecting resource based on the environment where the application is running. 28 * 29 * @since 0.20 30 */ 31 public final class ResourceUtils { 32 static final Resource EMPTY_RESOURCE = 33 Resource.create(null, Collections.<String, String>emptyMap()); 34 35 /** 36 * Returns a {@code Resource}. Detector sequentially runs resource detection from environment 37 * variables, K8S, GCE and AWS. 38 * 39 * @return a {@code Resource}. 40 * @since 0.20 41 */ detectResource()42 public static Resource detectResource() { 43 List<Resource> resourceList = new ArrayList<Resource>(); 44 resourceList.add(Resource.createFromEnvironmentVariables()); 45 if (System.getenv("KUBERNETES_SERVICE_HOST") != null) { 46 resourceList.add(ContainerResource.detect()); 47 resourceList.add(K8sResource.detect()); 48 } 49 resourceList.add(HostResource.detect()); 50 resourceList.add(CloudResource.detect()); 51 return firstNonNull(Resource.mergeResources(resourceList), EMPTY_RESOURCE); 52 } 53 ResourceUtils()54 private ResourceUtils() {} 55 } 56