1 /* 2 * Copyright (C) 2018 The Android Open Source Project 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 package com.android.tradefed.device.cloud; 17 18 import com.android.tradefed.log.LogUtil.CLog; 19 import com.android.tradefed.util.FileUtil; 20 21 import java.io.File; 22 import java.io.IOException; 23 import java.util.HashMap; 24 import java.util.Map; 25 26 /** Helper class that parse an Acloud config (used to start a Cloud device instance). */ 27 public class AcloudConfigParser { 28 29 /** Sets of key that can be searched from the configuration. */ 30 public enum AcloudKeys { 31 SERVICE_ACCOUNT_NAME("service_account_name"), 32 SERVICE_ACCOUNT_PRIVATE_KEY("service_account_private_key_path"), 33 ZONE("zone"), 34 PROJECT("project"), 35 MACHINE_TYPE("machine_type"), 36 SERVICE_ACCOUNT_JSON_PRIVATE_KEY("service_account_json_private_key_path"), 37 STABLE_HOST_IMAGE_NAME("stable_host_image_name"), 38 STABLE_HOST_IMAGE_PROJECT("stable_host_image_project"); 39 40 private String mName; 41 AcloudKeys(String name)42 private AcloudKeys(String name) { 43 mName = name; 44 } 45 46 @Override toString()47 public String toString() { 48 return mName; 49 } 50 } 51 52 private Map<String, String> mConfigValues; 53 AcloudConfigParser()54 private AcloudConfigParser() { 55 mConfigValues = new HashMap<>(); 56 } 57 58 /** 59 * Parse an acloud configuration file and returns a populated {@link AcloudConfigParser} that 60 * can be queried for values. Returns null in case of errors. 61 */ parseConfig(File configFile)62 public static AcloudConfigParser parseConfig(File configFile) { 63 if (configFile == null || !configFile.exists()) { 64 CLog.e("Could not read acloud config file: %s.", configFile); 65 return null; 66 } 67 AcloudConfigParser config = new AcloudConfigParser(); 68 try { 69 String content = FileUtil.readStringFromFile(configFile); 70 String[] lines = content.split("\n"); 71 for (String line : lines) { 72 if (line.contains(": ")) { 73 String key = line.split(": ")[0]; 74 String value = line.split(": ")[1].replace("\"", ""); 75 config.mConfigValues.put(key, value); 76 } 77 } 78 } catch (IOException e) { 79 CLog.e(e); 80 return null; 81 } 82 return config; 83 } 84 85 /** Returns the value associated with the Acloud key, null if no value. */ getValueForKey(AcloudKeys key)86 public String getValueForKey(AcloudKeys key) { 87 return mConfigValues.get(key.toString()); 88 } 89 } 90