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.logging; 16 : 17 : import com.google.common.base.Enums; 18 : import com.google.common.hash.Hasher; 19 : import com.google.common.hash.Hashing; 20 : import com.google.gerrit.common.Nullable; 21 : import com.google.gerrit.server.util.time.TimeUtil; 22 : import java.net.InetAddress; 23 : import java.net.UnknownHostException; 24 : 25 : /** Unique identifier for an end-user request, used in logs and similar. */ 26 : public class RequestId { 27 : private static final String MACHINE_ID; 28 : 29 : static { 30 : String id; 31 : try { 32 110 : id = InetAddress.getLocalHost().getHostAddress(); 33 0 : } catch (UnknownHostException e) { 34 0 : id = "unknown"; 35 110 : } 36 110 : MACHINE_ID = id; 37 110 : } 38 : 39 104 : public enum Type { 40 104 : RECEIVE_ID, 41 104 : SUBMISSION_ID, 42 104 : TRACE_ID; 43 : 44 : static boolean isId(String id) { 45 102 : return id != null && Enums.getIfPresent(Type.class, id).isPresent(); 46 : } 47 : } 48 : 49 : public static boolean isSet() { 50 110 : return LoggingContext.getInstance().getTagsAsMap().keySet().stream().anyMatch(Type::isId); 51 : } 52 : 53 : private final String str; 54 : 55 : public RequestId() { 56 3 : this(null); 57 3 : } 58 : 59 102 : public RequestId(@Nullable String resourceId) { 60 102 : Hasher h = Hashing.murmur3_128().newHasher(); 61 102 : h.putLong(Thread.currentThread().getId()).putUnencodedChars(MACHINE_ID); 62 102 : str = 63 102 : (resourceId != null ? resourceId + "-" : "") 64 102 : + TimeUtil.now().toEpochMilli() 65 : + "-" 66 102 : + h.hash().toString().substring(0, 8); 67 102 : } 68 : 69 : @Override 70 : public String toString() { 71 102 : return str; 72 : } 73 : 74 : public String toStringForStorage() { 75 0 : return str; 76 : } 77 : }