funcs.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. /*
  2. *
  3. * Copyright 2018 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. // Package channelz defines APIs for enabling channelz service, entry
  19. // registration/deletion, and accessing channelz data. It also defines channelz
  20. // metric struct formats.
  21. //
  22. // All APIs in this package are experimental.
  23. package channelz
  24. import (
  25. "fmt"
  26. "sort"
  27. "sync"
  28. "sync/atomic"
  29. "time"
  30. "google.golang.org/grpc/grpclog"
  31. )
  32. const (
  33. defaultMaxTraceEntry int32 = 30
  34. )
  35. var (
  36. db dbWrapper
  37. idGen idGenerator
  38. // EntryPerPage defines the number of channelz entries to be shown on a web page.
  39. EntryPerPage = int64(50)
  40. curState int32
  41. maxTraceEntry = defaultMaxTraceEntry
  42. )
  43. // TurnOn turns on channelz data collection.
  44. func TurnOn() {
  45. if !IsOn() {
  46. NewChannelzStorage()
  47. atomic.StoreInt32(&curState, 1)
  48. }
  49. }
  50. // IsOn returns whether channelz data collection is on.
  51. func IsOn() bool {
  52. return atomic.CompareAndSwapInt32(&curState, 1, 1)
  53. }
  54. // SetMaxTraceEntry sets maximum number of trace entry per entity (i.e. channel/subchannel).
  55. // Setting it to 0 will disable channel tracing.
  56. func SetMaxTraceEntry(i int32) {
  57. atomic.StoreInt32(&maxTraceEntry, i)
  58. }
  59. // ResetMaxTraceEntryToDefault resets the maximum number of trace entry per entity to default.
  60. func ResetMaxTraceEntryToDefault() {
  61. atomic.StoreInt32(&maxTraceEntry, defaultMaxTraceEntry)
  62. }
  63. func getMaxTraceEntry() int {
  64. i := atomic.LoadInt32(&maxTraceEntry)
  65. return int(i)
  66. }
  67. // dbWarpper wraps around a reference to internal channelz data storage, and
  68. // provide synchronized functionality to set and get the reference.
  69. type dbWrapper struct {
  70. mu sync.RWMutex
  71. DB *channelMap
  72. }
  73. func (d *dbWrapper) set(db *channelMap) {
  74. d.mu.Lock()
  75. d.DB = db
  76. d.mu.Unlock()
  77. }
  78. func (d *dbWrapper) get() *channelMap {
  79. d.mu.RLock()
  80. defer d.mu.RUnlock()
  81. return d.DB
  82. }
  83. // NewChannelzStorage initializes channelz data storage and id generator.
  84. //
  85. // This function returns a cleanup function to wait for all channelz state to be reset by the
  86. // grpc goroutines when those entities get closed. By using this cleanup function, we make sure tests
  87. // don't mess up each other, i.e. lingering goroutine from previous test doing entity removal happen
  88. // to remove some entity just register by the new test, since the id space is the same.
  89. //
  90. // Note: This function is exported for testing purpose only. User should not call
  91. // it in most cases.
  92. func NewChannelzStorage() (cleanup func() error) {
  93. db.set(&channelMap{
  94. topLevelChannels: make(map[int64]struct{}),
  95. channels: make(map[int64]*channel),
  96. listenSockets: make(map[int64]*listenSocket),
  97. normalSockets: make(map[int64]*normalSocket),
  98. servers: make(map[int64]*server),
  99. subChannels: make(map[int64]*subChannel),
  100. })
  101. idGen.reset()
  102. return func() error {
  103. var err error
  104. cm := db.get()
  105. if cm == nil {
  106. return nil
  107. }
  108. for i := 0; i < 1000; i++ {
  109. cm.mu.Lock()
  110. if len(cm.topLevelChannels) == 0 && len(cm.servers) == 0 && len(cm.channels) == 0 && len(cm.subChannels) == 0 && len(cm.listenSockets) == 0 && len(cm.normalSockets) == 0 {
  111. cm.mu.Unlock()
  112. // all things stored in the channelz map have been cleared.
  113. return nil
  114. }
  115. cm.mu.Unlock()
  116. time.Sleep(10 * time.Millisecond)
  117. }
  118. cm.mu.Lock()
  119. err = fmt.Errorf("after 10s the channelz map has not been cleaned up yet, topchannels: %d, servers: %d, channels: %d, subchannels: %d, listen sockets: %d, normal sockets: %d", len(cm.topLevelChannels), len(cm.servers), len(cm.channels), len(cm.subChannels), len(cm.listenSockets), len(cm.normalSockets))
  120. cm.mu.Unlock()
  121. return err
  122. }
  123. }
  124. // GetTopChannels returns a slice of top channel's ChannelMetric, along with a
  125. // boolean indicating whether there's more top channels to be queried for.
  126. //
  127. // The arg id specifies that only top channel with id at or above it will be included
  128. // in the result. The returned slice is up to a length of the arg maxResults or
  129. // EntryPerPage if maxResults is zero, and is sorted in ascending id order.
  130. func GetTopChannels(id int64, maxResults int64) ([]*ChannelMetric, bool) {
  131. return db.get().GetTopChannels(id, maxResults)
  132. }
  133. // GetServers returns a slice of server's ServerMetric, along with a
  134. // boolean indicating whether there's more servers to be queried for.
  135. //
  136. // The arg id specifies that only server with id at or above it will be included
  137. // in the result. The returned slice is up to a length of the arg maxResults or
  138. // EntryPerPage if maxResults is zero, and is sorted in ascending id order.
  139. func GetServers(id int64, maxResults int64) ([]*ServerMetric, bool) {
  140. return db.get().GetServers(id, maxResults)
  141. }
  142. // GetServerSockets returns a slice of server's (identified by id) normal socket's
  143. // SocketMetric, along with a boolean indicating whether there's more sockets to
  144. // be queried for.
  145. //
  146. // The arg startID specifies that only sockets with id at or above it will be
  147. // included in the result. The returned slice is up to a length of the arg maxResults
  148. // or EntryPerPage if maxResults is zero, and is sorted in ascending id order.
  149. func GetServerSockets(id int64, startID int64, maxResults int64) ([]*SocketMetric, bool) {
  150. return db.get().GetServerSockets(id, startID, maxResults)
  151. }
  152. // GetChannel returns the ChannelMetric for the channel (identified by id).
  153. func GetChannel(id int64) *ChannelMetric {
  154. return db.get().GetChannel(id)
  155. }
  156. // GetSubChannel returns the SubChannelMetric for the subchannel (identified by id).
  157. func GetSubChannel(id int64) *SubChannelMetric {
  158. return db.get().GetSubChannel(id)
  159. }
  160. // GetSocket returns the SocketInternalMetric for the socket (identified by id).
  161. func GetSocket(id int64) *SocketMetric {
  162. return db.get().GetSocket(id)
  163. }
  164. // GetServer returns the ServerMetric for the server (identified by id).
  165. func GetServer(id int64) *ServerMetric {
  166. return db.get().GetServer(id)
  167. }
  168. // RegisterChannel registers the given channel c in channelz database with ref
  169. // as its reference name, and add it to the child list of its parent (identified
  170. // by pid). pid = 0 means no parent. It returns the unique channelz tracking id
  171. // assigned to this channel.
  172. func RegisterChannel(c Channel, pid int64, ref string) int64 {
  173. id := idGen.genID()
  174. cn := &channel{
  175. refName: ref,
  176. c: c,
  177. subChans: make(map[int64]string),
  178. nestedChans: make(map[int64]string),
  179. id: id,
  180. pid: pid,
  181. trace: &channelTrace{createdTime: time.Now(), events: make([]*TraceEvent, 0, getMaxTraceEntry())},
  182. }
  183. if pid == 0 {
  184. db.get().addChannel(id, cn, true, pid, ref)
  185. } else {
  186. db.get().addChannel(id, cn, false, pid, ref)
  187. }
  188. return id
  189. }
  190. // RegisterSubChannel registers the given channel c in channelz database with ref
  191. // as its reference name, and add it to the child list of its parent (identified
  192. // by pid). It returns the unique channelz tracking id assigned to this subchannel.
  193. func RegisterSubChannel(c Channel, pid int64, ref string) int64 {
  194. if pid == 0 {
  195. grpclog.Error("a SubChannel's parent id cannot be 0")
  196. return 0
  197. }
  198. id := idGen.genID()
  199. sc := &subChannel{
  200. refName: ref,
  201. c: c,
  202. sockets: make(map[int64]string),
  203. id: id,
  204. pid: pid,
  205. trace: &channelTrace{createdTime: time.Now(), events: make([]*TraceEvent, 0, getMaxTraceEntry())},
  206. }
  207. db.get().addSubChannel(id, sc, pid, ref)
  208. return id
  209. }
  210. // RegisterServer registers the given server s in channelz database. It returns
  211. // the unique channelz tracking id assigned to this server.
  212. func RegisterServer(s Server, ref string) int64 {
  213. id := idGen.genID()
  214. svr := &server{
  215. refName: ref,
  216. s: s,
  217. sockets: make(map[int64]string),
  218. listenSockets: make(map[int64]string),
  219. id: id,
  220. }
  221. db.get().addServer(id, svr)
  222. return id
  223. }
  224. // RegisterListenSocket registers the given listen socket s in channelz database
  225. // with ref as its reference name, and add it to the child list of its parent
  226. // (identified by pid). It returns the unique channelz tracking id assigned to
  227. // this listen socket.
  228. func RegisterListenSocket(s Socket, pid int64, ref string) int64 {
  229. if pid == 0 {
  230. grpclog.Error("a ListenSocket's parent id cannot be 0")
  231. return 0
  232. }
  233. id := idGen.genID()
  234. ls := &listenSocket{refName: ref, s: s, id: id, pid: pid}
  235. db.get().addListenSocket(id, ls, pid, ref)
  236. return id
  237. }
  238. // RegisterNormalSocket registers the given normal socket s in channelz database
  239. // with ref as its reference name, and add it to the child list of its parent
  240. // (identified by pid). It returns the unique channelz tracking id assigned to
  241. // this normal socket.
  242. func RegisterNormalSocket(s Socket, pid int64, ref string) int64 {
  243. if pid == 0 {
  244. grpclog.Error("a NormalSocket's parent id cannot be 0")
  245. return 0
  246. }
  247. id := idGen.genID()
  248. ns := &normalSocket{refName: ref, s: s, id: id, pid: pid}
  249. db.get().addNormalSocket(id, ns, pid, ref)
  250. return id
  251. }
  252. // RemoveEntry removes an entry with unique channelz trakcing id to be id from
  253. // channelz database.
  254. func RemoveEntry(id int64) {
  255. db.get().removeEntry(id)
  256. }
  257. // TraceEventDesc is what the caller of AddTraceEvent should provide to describe the event to be added
  258. // to the channel trace.
  259. // The Parent field is optional. It is used for event that will be recorded in the entity's parent
  260. // trace also.
  261. type TraceEventDesc struct {
  262. Desc string
  263. Severity Severity
  264. Parent *TraceEventDesc
  265. }
  266. // AddTraceEvent adds trace related to the entity with specified id, using the provided TraceEventDesc.
  267. func AddTraceEvent(id int64, desc *TraceEventDesc) {
  268. if getMaxTraceEntry() == 0 {
  269. return
  270. }
  271. db.get().traceEvent(id, desc)
  272. }
  273. // channelMap is the storage data structure for channelz.
  274. // Methods of channelMap can be divided in two two categories with respect to locking.
  275. // 1. Methods acquire the global lock.
  276. // 2. Methods that can only be called when global lock is held.
  277. // A second type of method need always to be called inside a first type of method.
  278. type channelMap struct {
  279. mu sync.RWMutex
  280. topLevelChannels map[int64]struct{}
  281. servers map[int64]*server
  282. channels map[int64]*channel
  283. subChannels map[int64]*subChannel
  284. listenSockets map[int64]*listenSocket
  285. normalSockets map[int64]*normalSocket
  286. }
  287. func (c *channelMap) addServer(id int64, s *server) {
  288. c.mu.Lock()
  289. s.cm = c
  290. c.servers[id] = s
  291. c.mu.Unlock()
  292. }
  293. func (c *channelMap) addChannel(id int64, cn *channel, isTopChannel bool, pid int64, ref string) {
  294. c.mu.Lock()
  295. cn.cm = c
  296. cn.trace.cm = c
  297. c.channels[id] = cn
  298. if isTopChannel {
  299. c.topLevelChannels[id] = struct{}{}
  300. } else {
  301. c.findEntry(pid).addChild(id, cn)
  302. }
  303. c.mu.Unlock()
  304. }
  305. func (c *channelMap) addSubChannel(id int64, sc *subChannel, pid int64, ref string) {
  306. c.mu.Lock()
  307. sc.cm = c
  308. sc.trace.cm = c
  309. c.subChannels[id] = sc
  310. c.findEntry(pid).addChild(id, sc)
  311. c.mu.Unlock()
  312. }
  313. func (c *channelMap) addListenSocket(id int64, ls *listenSocket, pid int64, ref string) {
  314. c.mu.Lock()
  315. ls.cm = c
  316. c.listenSockets[id] = ls
  317. c.findEntry(pid).addChild(id, ls)
  318. c.mu.Unlock()
  319. }
  320. func (c *channelMap) addNormalSocket(id int64, ns *normalSocket, pid int64, ref string) {
  321. c.mu.Lock()
  322. ns.cm = c
  323. c.normalSockets[id] = ns
  324. c.findEntry(pid).addChild(id, ns)
  325. c.mu.Unlock()
  326. }
  327. // removeEntry triggers the removal of an entry, which may not indeed delete the entry, if it has to
  328. // wait on the deletion of its children and until no other entity's channel trace references it.
  329. // It may lead to a chain of entry deletion. For example, deleting the last socket of a gracefully
  330. // shutting down server will lead to the server being also deleted.
  331. func (c *channelMap) removeEntry(id int64) {
  332. c.mu.Lock()
  333. c.findEntry(id).triggerDelete()
  334. c.mu.Unlock()
  335. }
  336. // c.mu must be held by the caller
  337. func (c *channelMap) decrTraceRefCount(id int64) {
  338. e := c.findEntry(id)
  339. if v, ok := e.(tracedChannel); ok {
  340. v.decrTraceRefCount()
  341. e.deleteSelfIfReady()
  342. }
  343. }
  344. // c.mu must be held by the caller.
  345. func (c *channelMap) findEntry(id int64) entry {
  346. var v entry
  347. var ok bool
  348. if v, ok = c.channels[id]; ok {
  349. return v
  350. }
  351. if v, ok = c.subChannels[id]; ok {
  352. return v
  353. }
  354. if v, ok = c.servers[id]; ok {
  355. return v
  356. }
  357. if v, ok = c.listenSockets[id]; ok {
  358. return v
  359. }
  360. if v, ok = c.normalSockets[id]; ok {
  361. return v
  362. }
  363. return &dummyEntry{idNotFound: id}
  364. }
  365. // c.mu must be held by the caller
  366. // deleteEntry simply deletes an entry from the channelMap. Before calling this
  367. // method, caller must check this entry is ready to be deleted, i.e removeEntry()
  368. // has been called on it, and no children still exist.
  369. // Conditionals are ordered by the expected frequency of deletion of each entity
  370. // type, in order to optimize performance.
  371. func (c *channelMap) deleteEntry(id int64) {
  372. var ok bool
  373. if _, ok = c.normalSockets[id]; ok {
  374. delete(c.normalSockets, id)
  375. return
  376. }
  377. if _, ok = c.subChannels[id]; ok {
  378. delete(c.subChannels, id)
  379. return
  380. }
  381. if _, ok = c.channels[id]; ok {
  382. delete(c.channels, id)
  383. delete(c.topLevelChannels, id)
  384. return
  385. }
  386. if _, ok = c.listenSockets[id]; ok {
  387. delete(c.listenSockets, id)
  388. return
  389. }
  390. if _, ok = c.servers[id]; ok {
  391. delete(c.servers, id)
  392. return
  393. }
  394. }
  395. func (c *channelMap) traceEvent(id int64, desc *TraceEventDesc) {
  396. c.mu.Lock()
  397. child := c.findEntry(id)
  398. childTC, ok := child.(tracedChannel)
  399. if !ok {
  400. c.mu.Unlock()
  401. return
  402. }
  403. childTC.getChannelTrace().append(&TraceEvent{Desc: desc.Desc, Severity: desc.Severity, Timestamp: time.Now()})
  404. if desc.Parent != nil {
  405. parent := c.findEntry(child.getParentID())
  406. var chanType RefChannelType
  407. switch child.(type) {
  408. case *channel:
  409. chanType = RefChannel
  410. case *subChannel:
  411. chanType = RefSubChannel
  412. }
  413. if parentTC, ok := parent.(tracedChannel); ok {
  414. parentTC.getChannelTrace().append(&TraceEvent{
  415. Desc: desc.Parent.Desc,
  416. Severity: desc.Parent.Severity,
  417. Timestamp: time.Now(),
  418. RefID: id,
  419. RefName: childTC.getRefName(),
  420. RefType: chanType,
  421. })
  422. childTC.incrTraceRefCount()
  423. }
  424. }
  425. c.mu.Unlock()
  426. }
  427. type int64Slice []int64
  428. func (s int64Slice) Len() int { return len(s) }
  429. func (s int64Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  430. func (s int64Slice) Less(i, j int) bool { return s[i] < s[j] }
  431. func copyMap(m map[int64]string) map[int64]string {
  432. n := make(map[int64]string)
  433. for k, v := range m {
  434. n[k] = v
  435. }
  436. return n
  437. }
  438. func min(a, b int64) int64 {
  439. if a < b {
  440. return a
  441. }
  442. return b
  443. }
  444. func (c *channelMap) GetTopChannels(id int64, maxResults int64) ([]*ChannelMetric, bool) {
  445. if maxResults <= 0 {
  446. maxResults = EntryPerPage
  447. }
  448. c.mu.RLock()
  449. l := int64(len(c.topLevelChannels))
  450. ids := make([]int64, 0, l)
  451. cns := make([]*channel, 0, min(l, maxResults))
  452. for k := range c.topLevelChannels {
  453. ids = append(ids, k)
  454. }
  455. sort.Sort(int64Slice(ids))
  456. idx := sort.Search(len(ids), func(i int) bool { return ids[i] >= id })
  457. count := int64(0)
  458. var end bool
  459. var t []*ChannelMetric
  460. for i, v := range ids[idx:] {
  461. if count == maxResults {
  462. break
  463. }
  464. if cn, ok := c.channels[v]; ok {
  465. cns = append(cns, cn)
  466. t = append(t, &ChannelMetric{
  467. NestedChans: copyMap(cn.nestedChans),
  468. SubChans: copyMap(cn.subChans),
  469. })
  470. count++
  471. }
  472. if i == len(ids[idx:])-1 {
  473. end = true
  474. break
  475. }
  476. }
  477. c.mu.RUnlock()
  478. if count == 0 {
  479. end = true
  480. }
  481. for i, cn := range cns {
  482. t[i].ChannelData = cn.c.ChannelzMetric()
  483. t[i].ID = cn.id
  484. t[i].RefName = cn.refName
  485. t[i].Trace = cn.trace.dumpData()
  486. }
  487. return t, end
  488. }
  489. func (c *channelMap) GetServers(id, maxResults int64) ([]*ServerMetric, bool) {
  490. if maxResults <= 0 {
  491. maxResults = EntryPerPage
  492. }
  493. c.mu.RLock()
  494. l := int64(len(c.servers))
  495. ids := make([]int64, 0, l)
  496. ss := make([]*server, 0, min(l, maxResults))
  497. for k := range c.servers {
  498. ids = append(ids, k)
  499. }
  500. sort.Sort(int64Slice(ids))
  501. idx := sort.Search(len(ids), func(i int) bool { return ids[i] >= id })
  502. count := int64(0)
  503. var end bool
  504. var s []*ServerMetric
  505. for i, v := range ids[idx:] {
  506. if count == maxResults {
  507. break
  508. }
  509. if svr, ok := c.servers[v]; ok {
  510. ss = append(ss, svr)
  511. s = append(s, &ServerMetric{
  512. ListenSockets: copyMap(svr.listenSockets),
  513. })
  514. count++
  515. }
  516. if i == len(ids[idx:])-1 {
  517. end = true
  518. break
  519. }
  520. }
  521. c.mu.RUnlock()
  522. if count == 0 {
  523. end = true
  524. }
  525. for i, svr := range ss {
  526. s[i].ServerData = svr.s.ChannelzMetric()
  527. s[i].ID = svr.id
  528. s[i].RefName = svr.refName
  529. }
  530. return s, end
  531. }
  532. func (c *channelMap) GetServerSockets(id int64, startID int64, maxResults int64) ([]*SocketMetric, bool) {
  533. if maxResults <= 0 {
  534. maxResults = EntryPerPage
  535. }
  536. var svr *server
  537. var ok bool
  538. c.mu.RLock()
  539. if svr, ok = c.servers[id]; !ok {
  540. // server with id doesn't exist.
  541. c.mu.RUnlock()
  542. return nil, true
  543. }
  544. svrskts := svr.sockets
  545. l := int64(len(svrskts))
  546. ids := make([]int64, 0, l)
  547. sks := make([]*normalSocket, 0, min(l, maxResults))
  548. for k := range svrskts {
  549. ids = append(ids, k)
  550. }
  551. sort.Sort(int64Slice(ids))
  552. idx := sort.Search(len(ids), func(i int) bool { return ids[i] >= startID })
  553. count := int64(0)
  554. var end bool
  555. for i, v := range ids[idx:] {
  556. if count == maxResults {
  557. break
  558. }
  559. if ns, ok := c.normalSockets[v]; ok {
  560. sks = append(sks, ns)
  561. count++
  562. }
  563. if i == len(ids[idx:])-1 {
  564. end = true
  565. break
  566. }
  567. }
  568. c.mu.RUnlock()
  569. if count == 0 {
  570. end = true
  571. }
  572. var s []*SocketMetric
  573. for _, ns := range sks {
  574. sm := &SocketMetric{}
  575. sm.SocketData = ns.s.ChannelzMetric()
  576. sm.ID = ns.id
  577. sm.RefName = ns.refName
  578. s = append(s, sm)
  579. }
  580. return s, end
  581. }
  582. func (c *channelMap) GetChannel(id int64) *ChannelMetric {
  583. cm := &ChannelMetric{}
  584. var cn *channel
  585. var ok bool
  586. c.mu.RLock()
  587. if cn, ok = c.channels[id]; !ok {
  588. // channel with id doesn't exist.
  589. c.mu.RUnlock()
  590. return nil
  591. }
  592. cm.NestedChans = copyMap(cn.nestedChans)
  593. cm.SubChans = copyMap(cn.subChans)
  594. // cn.c can be set to &dummyChannel{} when deleteSelfFromMap is called. Save a copy of cn.c when
  595. // holding the lock to prevent potential data race.
  596. chanCopy := cn.c
  597. c.mu.RUnlock()
  598. cm.ChannelData = chanCopy.ChannelzMetric()
  599. cm.ID = cn.id
  600. cm.RefName = cn.refName
  601. cm.Trace = cn.trace.dumpData()
  602. return cm
  603. }
  604. func (c *channelMap) GetSubChannel(id int64) *SubChannelMetric {
  605. cm := &SubChannelMetric{}
  606. var sc *subChannel
  607. var ok bool
  608. c.mu.RLock()
  609. if sc, ok = c.subChannels[id]; !ok {
  610. // subchannel with id doesn't exist.
  611. c.mu.RUnlock()
  612. return nil
  613. }
  614. cm.Sockets = copyMap(sc.sockets)
  615. // sc.c can be set to &dummyChannel{} when deleteSelfFromMap is called. Save a copy of sc.c when
  616. // holding the lock to prevent potential data race.
  617. chanCopy := sc.c
  618. c.mu.RUnlock()
  619. cm.ChannelData = chanCopy.ChannelzMetric()
  620. cm.ID = sc.id
  621. cm.RefName = sc.refName
  622. cm.Trace = sc.trace.dumpData()
  623. return cm
  624. }
  625. func (c *channelMap) GetSocket(id int64) *SocketMetric {
  626. sm := &SocketMetric{}
  627. c.mu.RLock()
  628. if ls, ok := c.listenSockets[id]; ok {
  629. c.mu.RUnlock()
  630. sm.SocketData = ls.s.ChannelzMetric()
  631. sm.ID = ls.id
  632. sm.RefName = ls.refName
  633. return sm
  634. }
  635. if ns, ok := c.normalSockets[id]; ok {
  636. c.mu.RUnlock()
  637. sm.SocketData = ns.s.ChannelzMetric()
  638. sm.ID = ns.id
  639. sm.RefName = ns.refName
  640. return sm
  641. }
  642. c.mu.RUnlock()
  643. return nil
  644. }
  645. func (c *channelMap) GetServer(id int64) *ServerMetric {
  646. sm := &ServerMetric{}
  647. var svr *server
  648. var ok bool
  649. c.mu.RLock()
  650. if svr, ok = c.servers[id]; !ok {
  651. c.mu.RUnlock()
  652. return nil
  653. }
  654. sm.ListenSockets = copyMap(svr.listenSockets)
  655. c.mu.RUnlock()
  656. sm.ID = svr.id
  657. sm.RefName = svr.refName
  658. sm.ServerData = svr.s.ChannelzMetric()
  659. return sm
  660. }
  661. type idGenerator struct {
  662. id int64
  663. }
  664. func (i *idGenerator) reset() {
  665. atomic.StoreInt64(&i.id, 0)
  666. }
  667. func (i *idGenerator) genID() int64 {
  668. return atomic.AddInt64(&i.id, 1)
  669. }