Line data Source code
1 : // Copyright (C) 2016 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.server.config; 16 : 17 : import static java.nio.charset.StandardCharsets.UTF_8; 18 : 19 : import com.google.common.base.Strings; 20 : import com.google.inject.Inject; 21 : import com.google.inject.Provider; 22 : import java.io.IOException; 23 : import java.nio.file.Files; 24 : import java.util.UUID; 25 : import org.eclipse.jgit.errors.ConfigInvalidException; 26 : import org.eclipse.jgit.lib.Config; 27 : import org.eclipse.jgit.storage.file.FileBasedConfig; 28 : import org.eclipse.jgit.util.FS; 29 : 30 : public class GerritServerIdProvider implements Provider<String> { 31 : public static final String SECTION = "gerrit"; 32 : public static final String KEY = "serverId"; 33 : 34 : public static String generate() { 35 138 : return UUID.randomUUID().toString(); 36 : } 37 : 38 : private final String id; 39 : 40 : @Inject 41 : public GerritServerIdProvider(@GerritServerConfig Config cfg, SitePaths sitePaths) 42 138 : throws IOException, ConfigInvalidException { 43 138 : String origId = cfg.getString(SECTION, null, KEY); 44 138 : if (!Strings.isNullOrEmpty(origId)) { 45 15 : id = origId; 46 15 : return; 47 : } 48 : 49 : // We're not generally supposed to do work in provider constructors, but this is a bit of a 50 : // special case because we really need to have the ID available by the time the dbInjector 51 : // is created. Fortunately, it's not much work, and it happens once. 52 138 : id = generate(); 53 138 : Config newCfg = readGerritConfig(sitePaths); 54 138 : newCfg.setString(SECTION, null, KEY, id); 55 138 : Files.write(sitePaths.gerrit_config, newCfg.toText().getBytes(UTF_8)); 56 138 : } 57 : 58 : @Override 59 : public String get() { 60 138 : return id; 61 : } 62 : 63 : private static Config readGerritConfig(SitePaths sitePaths) 64 : throws IOException, ConfigInvalidException { 65 : // Reread gerrit.config from disk before writing. We can't just use 66 : // cfg.toText(), as the @GerritServerConfig only has gerrit.config as a 67 : // fallback. 68 138 : FileBasedConfig cfg = new FileBasedConfig(sitePaths.gerrit_config.toFile(), FS.DETECTED); 69 138 : if (!cfg.getFile().exists()) { 70 132 : return new Config(); 71 : } 72 17 : cfg.load(); 73 17 : return cfg; 74 : } 75 : }