aboutsummaryrefslogtreecommitdiff
path: root/core/src/main/java/io/grpc/InternalChannelz.java
blob: fee7136bbc17e64ea1aa3849d2bebbb57b6143e3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
/*
 * Copyright 2018 The gRPC Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.grpc;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import java.net.SocketAddress;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;

/**
 * This is an internal API. Do NOT use.
 */
@Internal
public final class InternalChannelz {
  private static final Logger log = Logger.getLogger(InternalChannelz.class.getName());
  private static final InternalChannelz INSTANCE = new InternalChannelz();

  private final ConcurrentNavigableMap<Long, InternalInstrumented<ServerStats>> servers
      = new ConcurrentSkipListMap<Long, InternalInstrumented<ServerStats>>();
  private final ConcurrentNavigableMap<Long, InternalInstrumented<ChannelStats>> rootChannels
      = new ConcurrentSkipListMap<Long, InternalInstrumented<ChannelStats>>();
  private final ConcurrentMap<Long, InternalInstrumented<ChannelStats>> subchannels
      = new ConcurrentHashMap<Long, InternalInstrumented<ChannelStats>>();
  // An InProcessTransport can appear in both otherSockets and perServerSockets simultaneously
  private final ConcurrentMap<Long, InternalInstrumented<SocketStats>> otherSockets
      = new ConcurrentHashMap<Long, InternalInstrumented<SocketStats>>();
  private final ConcurrentMap<Long, ServerSocketMap> perServerSockets
      = new ConcurrentHashMap<Long, ServerSocketMap>();

  // A convenience class to avoid deeply nested types.
  private static final class ServerSocketMap
      extends ConcurrentSkipListMap<Long, InternalInstrumented<SocketStats>> {
    private static final long serialVersionUID = -7883772124944661414L;
  }

  @VisibleForTesting
  public InternalChannelz() {
  }

  public static InternalChannelz instance() {
    return INSTANCE;
  }

  /** Adds a server. */
  public void addServer(InternalInstrumented<ServerStats> server) {
    ServerSocketMap prev = perServerSockets.put(id(server), new ServerSocketMap());
    assert prev == null;
    add(servers, server);
  }

  /** Adds a subchannel. */
  public void addSubchannel(InternalInstrumented<ChannelStats> subchannel) {
    add(subchannels, subchannel);
  }

  /** Adds a root channel. */
  public void addRootChannel(InternalInstrumented<ChannelStats> rootChannel) {
    add(rootChannels, rootChannel);
  }

  /** Adds a socket. */
  public void addClientSocket(InternalInstrumented<SocketStats> socket) {
    add(otherSockets, socket);
  }

  public void addListenSocket(InternalInstrumented<SocketStats> socket) {
    add(otherSockets, socket);
  }

  /** Adds a server socket. */
  public void addServerSocket(
      InternalInstrumented<ServerStats> server, InternalInstrumented<SocketStats> socket) {
    ServerSocketMap serverSockets = perServerSockets.get(id(server));
    assert serverSockets != null;
    add(serverSockets, socket);
  }

  /** Removes a server. */
  public void removeServer(InternalInstrumented<ServerStats> server) {
    remove(servers, server);
    ServerSocketMap prev = perServerSockets.remove(id(server));
    assert prev != null;
    assert prev.isEmpty();
  }

  public void removeSubchannel(InternalInstrumented<ChannelStats> subchannel) {
    remove(subchannels, subchannel);
  }

  public void removeRootChannel(InternalInstrumented<ChannelStats> channel) {
    remove(rootChannels, channel);
  }

  public void removeClientSocket(InternalInstrumented<SocketStats> socket) {
    remove(otherSockets, socket);
  }

  public void removeListenSocket(InternalInstrumented<SocketStats> socket) {
    remove(otherSockets, socket);
  }

  /** Removes a server socket. */
  public void removeServerSocket(
      InternalInstrumented<ServerStats> server, InternalInstrumented<SocketStats> socket) {
    ServerSocketMap socketsOfServer = perServerSockets.get(id(server));
    assert socketsOfServer != null;
    remove(socketsOfServer, socket);
  }

  /** Returns a {@link RootChannelList}. */
  public RootChannelList getRootChannels(long fromId, int maxPageSize) {
    List<InternalInstrumented<ChannelStats>> channelList
        = new ArrayList<InternalInstrumented<ChannelStats>>();
    Iterator<InternalInstrumented<ChannelStats>> iterator
        = rootChannels.tailMap(fromId).values().iterator();

    while (iterator.hasNext() && channelList.size() < maxPageSize) {
      channelList.add(iterator.next());
    }
    return new RootChannelList(channelList, !iterator.hasNext());
  }

  /** Returns a channel. */
  @Nullable
  public InternalInstrumented<ChannelStats> getChannel(long id) {
    return rootChannels.get(id);
  }

  /** Returns a subchannel. */
  @Nullable
  public InternalInstrumented<ChannelStats> getSubchannel(long id) {
    return subchannels.get(id);
  }

  /** Returns a server list. */
  public ServerList getServers(long fromId, int maxPageSize) {
    List<InternalInstrumented<ServerStats>> serverList
        = new ArrayList<InternalInstrumented<ServerStats>>(maxPageSize);
    Iterator<InternalInstrumented<ServerStats>> iterator
        = servers.tailMap(fromId).values().iterator();

    while (iterator.hasNext() && serverList.size() < maxPageSize) {
      serverList.add(iterator.next());
    }
    return new ServerList(serverList, !iterator.hasNext());
  }

  /** Returns socket refs for a server. */
  @Nullable
  public ServerSocketsList getServerSockets(long serverId, long fromId, int maxPageSize) {
    ServerSocketMap serverSockets = perServerSockets.get(serverId);
    if (serverSockets == null) {
      return null;
    }
    List<InternalWithLogId> socketList = new ArrayList<InternalWithLogId>(maxPageSize);
    Iterator<InternalInstrumented<SocketStats>> iterator
        = serverSockets.tailMap(fromId).values().iterator();
    while (socketList.size() < maxPageSize && iterator.hasNext()) {
      socketList.add(iterator.next());
    }
    return new ServerSocketsList(socketList, !iterator.hasNext());
  }

  /** Returns a socket. */
  @Nullable
  public InternalInstrumented<SocketStats> getSocket(long id) {
    InternalInstrumented<SocketStats> clientSocket = otherSockets.get(id);
    if (clientSocket != null) {
      return clientSocket;
    }
    return getServerSocket(id);
  }

  private InternalInstrumented<SocketStats> getServerSocket(long id) {
    for (ServerSocketMap perServerSockets : perServerSockets.values()) {
      InternalInstrumented<SocketStats> serverSocket = perServerSockets.get(id);
      if (serverSocket != null) {
        return serverSocket;
      }
    }
    return null;
  }

  @VisibleForTesting
  public boolean containsServer(InternalLogId serverRef) {
    return contains(servers, serverRef);
  }

  @VisibleForTesting
  public boolean containsSubchannel(InternalLogId subchannelRef) {
    return contains(subchannels, subchannelRef);
  }

  public InternalInstrumented<ChannelStats> getRootChannel(long id) {
    return rootChannels.get(id);
  }

  @VisibleForTesting
  public boolean containsClientSocket(InternalLogId transportRef) {
    return contains(otherSockets, transportRef);
  }

  private static <T extends InternalInstrumented<?>> void add(Map<Long, T> map, T object) {
    T prev = map.put(object.getLogId().getId(), object);
    assert prev == null;
  }

  private static <T extends InternalInstrumented<?>> void remove(Map<Long, T> map, T object) {
    T prev = map.remove(id(object));
    assert prev != null;
  }

  private static <T extends InternalInstrumented<?>> boolean contains(
      Map<Long, T> map, InternalLogId id) {
    return map.containsKey(id.getId());
  }

  public static final class RootChannelList {
    public final List<InternalInstrumented<ChannelStats>> channels;
    public final boolean end;

    /** Creates an instance. */
    public RootChannelList(List<InternalInstrumented<ChannelStats>> channels, boolean end) {
      this.channels = checkNotNull(channels);
      this.end = end;
    }
  }

  public static final class ServerList {
    public final List<InternalInstrumented<ServerStats>> servers;
    public final boolean end;

    /** Creates an instance. */
    public ServerList(List<InternalInstrumented<ServerStats>> servers, boolean end) {
      this.servers = checkNotNull(servers);
      this.end = end;
    }
  }

  public static final class ServerSocketsList {
    public final List<InternalWithLogId> sockets;
    public final boolean end;

    /** Creates an instance. */
    public ServerSocketsList(List<InternalWithLogId> sockets, boolean end) {
      this.sockets = sockets;
      this.end = end;
    }
  }

  @Immutable
  public static final class ServerStats {
    public final long callsStarted;
    public final long callsSucceeded;
    public final long callsFailed;
    public final long lastCallStartedNanos;
    public final List<InternalInstrumented<SocketStats>> listenSockets;

    /**
     * Creates an instance.
     */
    public ServerStats(
        long callsStarted,
        long callsSucceeded,
        long callsFailed,
        long lastCallStartedNanos,
        List<InternalInstrumented<SocketStats>> listenSockets) {
      this.callsStarted = callsStarted;
      this.callsSucceeded = callsSucceeded;
      this.callsFailed = callsFailed;
      this.lastCallStartedNanos = lastCallStartedNanos;
      this.listenSockets = checkNotNull(listenSockets);
    }

    public static final class Builder {
      private long callsStarted;
      private long callsSucceeded;
      private long callsFailed;
      private long lastCallStartedNanos;
      public List<InternalInstrumented<SocketStats>> listenSockets = Collections.emptyList();

      public Builder setCallsStarted(long callsStarted) {
        this.callsStarted = callsStarted;
        return this;
      }

      public Builder setCallsSucceeded(long callsSucceeded) {
        this.callsSucceeded = callsSucceeded;
        return this;
      }

      public Builder setCallsFailed(long callsFailed) {
        this.callsFailed = callsFailed;
        return this;
      }

      public Builder setLastCallStartedNanos(long lastCallStartedNanos) {
        this.lastCallStartedNanos = lastCallStartedNanos;
        return this;
      }

      /** Sets the listen sockets. */
      public Builder setListenSockets(List<InternalInstrumented<SocketStats>> listenSockets) {
        checkNotNull(listenSockets);
        this.listenSockets = Collections.unmodifiableList(
            new ArrayList<InternalInstrumented<SocketStats>>(listenSockets));
        return this;
      }

      /**
       * Builds an instance.
       */
      public ServerStats build() {
        return new ServerStats(
            callsStarted,
            callsSucceeded,
            callsFailed,
            lastCallStartedNanos,
            listenSockets);
      }
    }
  }

  /**
   * A data class to represent a channel's stats.
   */
  @Immutable
  public static final class ChannelStats {
    public final String target;
    public final ConnectivityState state;
    @Nullable public final ChannelTrace channelTrace;
    public final long callsStarted;
    public final long callsSucceeded;
    public final long callsFailed;
    public final long lastCallStartedNanos;
    public final List<InternalWithLogId> subchannels;
    public final List<InternalWithLogId> sockets;

    /**
     * Creates an instance.
     */
    private ChannelStats(
        String target,
        ConnectivityState state,
        @Nullable ChannelTrace channelTrace,
        long callsStarted,
        long callsSucceeded,
        long callsFailed,
        long lastCallStartedNanos,
        List<InternalWithLogId> subchannels,
        List<InternalWithLogId> sockets) {
      checkState(
          subchannels.isEmpty() || sockets.isEmpty(),
          "channels can have subchannels only, subchannels can have either sockets OR subchannels, "
              + "neither can have both");
      this.target = target;
      this.state = state;
      this.channelTrace = channelTrace;
      this.callsStarted = callsStarted;
      this.callsSucceeded = callsSucceeded;
      this.callsFailed = callsFailed;
      this.lastCallStartedNanos = lastCallStartedNanos;
      this.subchannels = checkNotNull(subchannels);
      this.sockets = checkNotNull(sockets);
    }

    public static final class Builder {
      private String target;
      private ConnectivityState state;
      private ChannelTrace channelTrace;
      private long callsStarted;
      private long callsSucceeded;
      private long callsFailed;
      private long lastCallStartedNanos;
      private List<InternalWithLogId> subchannels = Collections.emptyList();
      private List<InternalWithLogId> sockets = Collections.emptyList();

      public Builder setTarget(String target) {
        this.target = target;
        return this;
      }

      public Builder setState(ConnectivityState state) {
        this.state = state;
        return this;
      }

      public Builder setChannelTrace(ChannelTrace channelTrace) {
        this.channelTrace = channelTrace;
        return this;
      }

      public Builder setCallsStarted(long callsStarted) {
        this.callsStarted = callsStarted;
        return this;
      }

      public Builder setCallsSucceeded(long callsSucceeded) {
        this.callsSucceeded = callsSucceeded;
        return this;
      }

      public Builder setCallsFailed(long callsFailed) {
        this.callsFailed = callsFailed;
        return this;
      }

      public Builder setLastCallStartedNanos(long lastCallStartedNanos) {
        this.lastCallStartedNanos = lastCallStartedNanos;
        return this;
      }

      /** Sets the subchannels. */
      public Builder setSubchannels(List<InternalWithLogId> subchannels) {
        checkState(sockets.isEmpty());
        this.subchannels = Collections.unmodifiableList(checkNotNull(subchannels));
        return this;
      }

      /** Sets the sockets. */
      public Builder setSockets(List<InternalWithLogId> sockets) {
        checkState(subchannels.isEmpty());
        this.sockets = Collections.unmodifiableList(checkNotNull(sockets));
        return this;
      }

      /**
       * Builds an instance.
       */
      public ChannelStats build() {
        return new ChannelStats(
            target,
            state,
            channelTrace,
            callsStarted,
            callsSucceeded,
            callsFailed,
            lastCallStartedNanos,
            subchannels,
            sockets);
      }
    }
  }

  @Immutable
  public static final class ChannelTrace {
    public final long numEventsLogged;
    public final long creationTimeNanos;
    public final List<Event> events;

    private ChannelTrace(long numEventsLogged, long creationTimeNanos, List<Event> events) {
      this.numEventsLogged = numEventsLogged;
      this.creationTimeNanos = creationTimeNanos;
      this.events = events;
    }

    public static final class Builder {
      private Long numEventsLogged;
      private Long creationTimeNanos;
      private List<Event> events = Collections.emptyList();

      public Builder setNumEventsLogged(long numEventsLogged) {
        this.numEventsLogged = numEventsLogged;
        return this;
      }

      public Builder setCreationTimeNanos(long creationTimeNanos) {
        this.creationTimeNanos = creationTimeNanos;
        return this;
      }

      public Builder setEvents(List<Event> events) {
        this.events = Collections.unmodifiableList(new ArrayList<Event>(events));
        return this;
      }

      /** Builds a new ChannelTrace instance. */
      public ChannelTrace build() {
        checkNotNull(numEventsLogged, "numEventsLogged");
        checkNotNull(creationTimeNanos, "creationTimeNanos");
        return new ChannelTrace(numEventsLogged, creationTimeNanos, events);
      }
    }

    @Immutable
    public static final class Event {
      public final String description;
      public final Severity severity;
      public final long timestampNanos;

      // the oneof child_ref field in proto: one of channelRef and channelRef
      @Nullable public final InternalWithLogId channelRef;
      @Nullable public final InternalWithLogId subchannelRef;

      public enum Severity {
        CT_UNKNOWN, CT_INFO, CT_WARNING, CT_ERROR
      }

      private Event(
          String description, Severity severity, long timestampNanos,
          @Nullable InternalWithLogId channelRef, @Nullable InternalWithLogId subchannelRef) {
        this.description = description;
        this.severity = checkNotNull(severity, "severity");
        this.timestampNanos = timestampNanos;
        this.channelRef = channelRef;
        this.subchannelRef = subchannelRef;
      }

      @Override
      public int hashCode() {
        return Objects.hashCode(description, severity, timestampNanos, channelRef, subchannelRef);
      }

      @Override
      public boolean equals(Object o) {
        if (o instanceof Event) {
          Event that = (Event) o;
          return Objects.equal(description, that.description)
              && Objects.equal(severity, that.severity)
              && timestampNanos == that.timestampNanos
              && Objects.equal(channelRef, that.channelRef)
              && Objects.equal(subchannelRef, that.subchannelRef);
        }
        return false;
      }

      @Override
      public String toString() {
        return MoreObjects.toStringHelper(this)
            .add("description", description)
            .add("severity", severity)
            .add("timestampNanos", timestampNanos)
            .add("channelRef", channelRef)
            .add("subchannelRef", subchannelRef)
            .toString();
      }

      public static final class Builder {
        private String description;
        private Severity severity;
        private Long timestampNanos;
        private InternalWithLogId channelRef;
        private InternalWithLogId subchannelRef;

        public Builder setDescription(String description) {
          this.description = description;
          return this;
        }

        public Builder setTimestampNanos(long timestampNanos) {
          this.timestampNanos = timestampNanos;
          return this;
        }

        public Builder setSeverity(Severity severity) {
          this.severity = severity;
          return this;
        }

        public Builder setChannelRef(InternalWithLogId channelRef) {
          this.channelRef = channelRef;
          return this;
        }

        public Builder setSubchannelRef(InternalWithLogId subchannelRef) {
          this.subchannelRef = subchannelRef;
          return this;
        }

        /** Builds a new Event instance. */
        public Event build() {
          checkNotNull(description, "description");
          checkNotNull(severity, "severity");
          checkNotNull(timestampNanos, "timestampNanos");
          checkState(
              channelRef == null || subchannelRef == null,
              "at least one of channelRef and subchannelRef must be null");
          return new Event(description, severity, timestampNanos, channelRef, subchannelRef);
        }
      }
    }
  }

  public static final class Security {
    @Nullable
    public final Tls tls;
    @Nullable
    public final OtherSecurity other;

    public Security(Tls tls) {
      this.tls = checkNotNull(tls);
      this.other = null;
    }

    public Security(OtherSecurity other) {
      this.tls = null;
      this.other = checkNotNull(other);
    }
  }

  public static final class OtherSecurity {
    public final String name;
    @Nullable
    public final Object any;

    /**
     * Creates an instance.
     * @param name the name.
     * @param any a com.google.protobuf.Any object
     */
    public OtherSecurity(String name, @Nullable Object any) {
      this.name = checkNotNull(name);
      checkState(
          any == null || any.getClass().getName().endsWith("com.google.protobuf.Any"),
          "the 'any' object must be of type com.google.protobuf.Any");
      this.any = any;
    }
  }

  @Immutable
  public static final class Tls {
    public final String cipherSuiteStandardName;
    @Nullable public final Certificate localCert;
    @Nullable public final Certificate remoteCert;

    /**
     * A constructor only for testing.
     */
    public Tls(String cipherSuiteName, Certificate localCert, Certificate remoteCert) {
      this.cipherSuiteStandardName = cipherSuiteName;
      this.localCert = localCert;
      this.remoteCert = remoteCert;
    }

    /**
     * Creates an instance.
     */
    public Tls(SSLSession session) {
      String cipherSuiteStandardName = session.getCipherSuite();
      Certificate localCert = null;
      Certificate remoteCert = null;
      Certificate[] localCerts = session.getLocalCertificates();
      if (localCerts != null) {
        localCert = localCerts[0];
      }
      try {
        Certificate[] peerCerts = session.getPeerCertificates();
        if (peerCerts != null) {
          // The javadoc of getPeerCertificate states that the peer's own certificate is the first
          // element of the list.
          remoteCert = peerCerts[0];
        }
      } catch (SSLPeerUnverifiedException e) {
        // peer cert is not available
        log.log(
            Level.FINE,
            String.format("Peer cert not available for peerHost=%s", session.getPeerHost()),
            e);
      }
      this.cipherSuiteStandardName = cipherSuiteStandardName;
      this.localCert = localCert;
      this.remoteCert = remoteCert;
    }
  }

  public static final class SocketStats {
    @Nullable public final TransportStats data;
    @Nullable public final SocketAddress local;
    @Nullable public final SocketAddress remote;
    public final SocketOptions socketOptions;
    // Can be null if plaintext
    @Nullable public final Security security;

    /** Creates an instance. */
    public SocketStats(
        TransportStats data,
        @Nullable SocketAddress local,
        @Nullable SocketAddress remote,
        SocketOptions socketOptions,
        Security security) {
      this.data = data;
      this.local = checkNotNull(local, "local socket");
      this.remote = remote;
      this.socketOptions = checkNotNull(socketOptions);
      this.security = security;
    }
  }

  public static final class TcpInfo {
    public final int state;
    public final int caState;
    public final int retransmits;
    public final int probes;
    public final int backoff;
    public final int options;
    public final int sndWscale;
    public final int rcvWscale;
    public final int rto;
    public final int ato;
    public final int sndMss;
    public final int rcvMss;
    public final int unacked;
    public final int sacked;
    public final int lost;
    public final int retrans;
    public final int fackets;
    public final int lastDataSent;
    public final int lastAckSent;
    public final int lastDataRecv;
    public final int lastAckRecv;
    public final int pmtu;
    public final int rcvSsthresh;
    public final int rtt;
    public final int rttvar;
    public final int sndSsthresh;
    public final int sndCwnd;
    public final int advmss;
    public final int reordering;

    TcpInfo(int state, int caState, int retransmits, int probes, int backoff, int options,
        int sndWscale, int rcvWscale, int rto, int ato, int sndMss, int rcvMss, int unacked,
        int sacked, int lost, int retrans, int fackets, int lastDataSent, int lastAckSent,
        int lastDataRecv, int lastAckRecv, int pmtu, int rcvSsthresh, int rtt, int rttvar,
        int sndSsthresh, int sndCwnd, int advmss, int reordering) {
      this.state = state;
      this.caState = caState;
      this.retransmits = retransmits;
      this.probes = probes;
      this.backoff = backoff;
      this.options = options;
      this.sndWscale = sndWscale;
      this.rcvWscale = rcvWscale;
      this.rto = rto;
      this.ato = ato;
      this.sndMss = sndMss;
      this.rcvMss = rcvMss;
      this.unacked = unacked;
      this.sacked = sacked;
      this.lost = lost;
      this.retrans = retrans;
      this.fackets = fackets;
      this.lastDataSent = lastDataSent;
      this.lastAckSent = lastAckSent;
      this.lastDataRecv = lastDataRecv;
      this.lastAckRecv = lastAckRecv;
      this.pmtu = pmtu;
      this.rcvSsthresh = rcvSsthresh;
      this.rtt = rtt;
      this.rttvar = rttvar;
      this.sndSsthresh = sndSsthresh;
      this.sndCwnd = sndCwnd;
      this.advmss = advmss;
      this.reordering = reordering;
    }

    public static final class Builder {
      private int state;
      private int caState;
      private int retransmits;
      private int probes;
      private int backoff;
      private int options;
      private int sndWscale;
      private int rcvWscale;
      private int rto;
      private int ato;
      private int sndMss;
      private int rcvMss;
      private int unacked;
      private int sacked;
      private int lost;
      private int retrans;
      private int fackets;
      private int lastDataSent;
      private int lastAckSent;
      private int lastDataRecv;
      private int lastAckRecv;
      private int pmtu;
      private int rcvSsthresh;
      private int rtt;
      private int rttvar;
      private int sndSsthresh;
      private int sndCwnd;
      private int advmss;
      private int reordering;

      public Builder setState(int state) {
        this.state = state;
        return this;
      }

      public Builder setCaState(int caState) {
        this.caState = caState;
        return this;
      }

      public Builder setRetransmits(int retransmits) {
        this.retransmits = retransmits;
        return this;
      }

      public Builder setProbes(int probes) {
        this.probes = probes;
        return this;
      }

      public Builder setBackoff(int backoff) {
        this.backoff = backoff;
        return this;
      }

      public Builder setOptions(int options) {
        this.options = options;
        return this;
      }

      public Builder setSndWscale(int sndWscale) {
        this.sndWscale = sndWscale;
        return this;
      }

      public Builder setRcvWscale(int rcvWscale) {
        this.rcvWscale = rcvWscale;
        return this;
      }

      public Builder setRto(int rto) {
        this.rto = rto;
        return this;
      }

      public Builder setAto(int ato) {
        this.ato = ato;
        return this;
      }

      public Builder setSndMss(int sndMss) {
        this.sndMss = sndMss;
        return this;
      }

      public Builder setRcvMss(int rcvMss) {
        this.rcvMss = rcvMss;
        return this;
      }

      public Builder setUnacked(int unacked) {
        this.unacked = unacked;
        return this;
      }

      public Builder setSacked(int sacked) {
        this.sacked = sacked;
        return this;
      }

      public Builder setLost(int lost) {
        this.lost = lost;
        return this;
      }

      public Builder setRetrans(int retrans) {
        this.retrans = retrans;
        return this;
      }

      public Builder setFackets(int fackets) {
        this.fackets = fackets;
        return this;
      }

      public Builder setLastDataSent(int lastDataSent) {
        this.lastDataSent = lastDataSent;
        return this;
      }

      public Builder setLastAckSent(int lastAckSent) {
        this.lastAckSent = lastAckSent;
        return this;
      }

      public Builder setLastDataRecv(int lastDataRecv) {
        this.lastDataRecv = lastDataRecv;
        return this;
      }

      public Builder setLastAckRecv(int lastAckRecv) {
        this.lastAckRecv = lastAckRecv;
        return this;
      }

      public Builder setPmtu(int pmtu) {
        this.pmtu = pmtu;
        return this;
      }

      public Builder setRcvSsthresh(int rcvSsthresh) {
        this.rcvSsthresh = rcvSsthresh;
        return this;
      }

      public Builder setRtt(int rtt) {
        this.rtt = rtt;
        return this;
      }

      public Builder setRttvar(int rttvar) {
        this.rttvar = rttvar;
        return this;
      }

      public Builder setSndSsthresh(int sndSsthresh) {
        this.sndSsthresh = sndSsthresh;
        return this;
      }

      public Builder setSndCwnd(int sndCwnd) {
        this.sndCwnd = sndCwnd;
        return this;
      }

      public Builder setAdvmss(int advmss) {
        this.advmss = advmss;
        return this;
      }

      public Builder setReordering(int reordering) {
        this.reordering = reordering;
        return this;
      }

      /** Builds an instance. */
      public TcpInfo build() {
        return new TcpInfo(
            state, caState, retransmits, probes, backoff, options, sndWscale, rcvWscale,
            rto, ato, sndMss, rcvMss, unacked, sacked, lost, retrans, fackets, lastDataSent,
            lastAckSent, lastDataRecv, lastAckRecv, pmtu, rcvSsthresh, rtt, rttvar, sndSsthresh,
            sndCwnd, advmss, reordering);
      }
    }
  }

  public static final class SocketOptions {
    public final Map<String, String> others;
    // In netty, the value of a channel option may be null.
    @Nullable public final Integer soTimeoutMillis;
    @Nullable public final Integer lingerSeconds;
    @Nullable public final TcpInfo tcpInfo;

    /** Creates an instance. */
    public SocketOptions(
        @Nullable Integer timeoutMillis,
        @Nullable Integer lingerSeconds,
        @Nullable TcpInfo tcpInfo,
        Map<String, String> others) {
      checkNotNull(others);
      this.soTimeoutMillis = timeoutMillis;
      this.lingerSeconds = lingerSeconds;
      this.tcpInfo = tcpInfo;
      this.others = Collections.unmodifiableMap(new HashMap<String, String>(others));
    }

    public static final class Builder {
      private final Map<String, String> others = new HashMap<String, String>();

      private TcpInfo tcpInfo;
      private Integer timeoutMillis;
      private Integer lingerSeconds;

      /** The value of {@link java.net.Socket#getSoTimeout()}. */
      public Builder setSocketOptionTimeoutMillis(Integer timeoutMillis) {
        this.timeoutMillis = timeoutMillis;
        return this;
      }

      /** The value of {@link java.net.Socket#getSoLinger()}.
       * Note: SO_LINGER is typically expressed in seconds.
       */
      public Builder setSocketOptionLingerSeconds(Integer lingerSeconds) {
        this.lingerSeconds = lingerSeconds;
        return this;
      }

      public Builder setTcpInfo(TcpInfo tcpInfo) {
        this.tcpInfo = tcpInfo;
        return this;
      }

      public Builder addOption(String name, String value) {
        others.put(name, checkNotNull(value));
        return this;
      }

      public Builder addOption(String name, int value) {
        others.put(name, Integer.toString(value));
        return this;
      }

      public Builder addOption(String name, boolean value) {
        others.put(name, Boolean.toString(value));
        return this;
      }

      public SocketOptions build() {
        return new SocketOptions(timeoutMillis, lingerSeconds, tcpInfo, others);
      }
    }
  }

  /**
   * A data class to represent transport stats.
   */
  @Immutable
  public static final class TransportStats {
    public final long streamsStarted;
    public final long lastLocalStreamCreatedTimeNanos;
    public final long lastRemoteStreamCreatedTimeNanos;
    public final long streamsSucceeded;
    public final long streamsFailed;
    public final long messagesSent;
    public final long messagesReceived;
    public final long keepAlivesSent;
    public final long lastMessageSentTimeNanos;
    public final long lastMessageReceivedTimeNanos;
    public final long localFlowControlWindow;
    public final long remoteFlowControlWindow;
    // TODO(zpencer): report socket flags and other info

    /**
     * Creates an instance.
     */
    public TransportStats(
        long streamsStarted,
        long lastLocalStreamCreatedTimeNanos,
        long lastRemoteStreamCreatedTimeNanos,
        long streamsSucceeded,
        long streamsFailed,
        long messagesSent,
        long messagesReceived,
        long keepAlivesSent,
        long lastMessageSentTimeNanos,
        long lastMessageReceivedTimeNanos,
        long localFlowControlWindow,
        long remoteFlowControlWindow) {
      this.streamsStarted = streamsStarted;
      this.lastLocalStreamCreatedTimeNanos = lastLocalStreamCreatedTimeNanos;
      this.lastRemoteStreamCreatedTimeNanos = lastRemoteStreamCreatedTimeNanos;
      this.streamsSucceeded = streamsSucceeded;
      this.streamsFailed = streamsFailed;
      this.messagesSent = messagesSent;
      this.messagesReceived = messagesReceived;
      this.keepAlivesSent = keepAlivesSent;
      this.lastMessageSentTimeNanos = lastMessageSentTimeNanos;
      this.lastMessageReceivedTimeNanos = lastMessageReceivedTimeNanos;
      this.localFlowControlWindow = localFlowControlWindow;
      this.remoteFlowControlWindow = remoteFlowControlWindow;
    }
  }

  /** Unwraps a {@link InternalLogId} to return a {@code long}. */
  public static long id(InternalWithLogId withLogId) {
    return withLogId.getLogId().getId();
  }
}