1 // Copyright 2022 Google LLC 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 //////////////////////////////////////////////////////////////////////////////// 16 17 package com.google.crypto.tink.internal; 18 19 import com.google.crypto.tink.monitoring.MonitoringClient; 20 import com.google.crypto.tink.monitoring.MonitoringKeysetInfo; 21 import java.util.concurrent.atomic.AtomicReference; 22 23 /** 24 * A Registry for MonitoringClient. 25 */ 26 public final class MutableMonitoringRegistry { 27 private static final MutableMonitoringRegistry GLOBAL_INSTANCE = 28 new MutableMonitoringRegistry(); 29 globalInstance()30 public static MutableMonitoringRegistry globalInstance() { 31 return GLOBAL_INSTANCE; 32 } 33 34 private static class DoNothingClient implements MonitoringClient { 35 @Override createLogger( MonitoringKeysetInfo keysetInfo, String primitive, String api)36 public MonitoringClient.Logger createLogger( 37 MonitoringKeysetInfo keysetInfo, String primitive, String api) { 38 return MonitoringUtil.DO_NOTHING_LOGGER; 39 } 40 } 41 private static final DoNothingClient DO_NOTHING_CLIENT = new DoNothingClient(); 42 43 private final AtomicReference<MonitoringClient> monitoringClient = new AtomicReference<>(); 44 clear()45 public synchronized void clear() { 46 monitoringClient.set(null); 47 } 48 registerMonitoringClient(MonitoringClient client)49 public synchronized void registerMonitoringClient(MonitoringClient client) { 50 if (monitoringClient.get() != null) { 51 throw new IllegalStateException("a monitoring client has already been registered"); 52 } 53 monitoringClient.set(client); 54 } 55 getMonitoringClient()56 public MonitoringClient getMonitoringClient() { 57 MonitoringClient client = monitoringClient.get(); 58 if (client == null) { 59 return DO_NOTHING_CLIENT; 60 } 61 return client; 62 } 63 MutableMonitoringRegistry()64 public MutableMonitoringRegistry() {} 65 } 66