clientsmap.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright (C) 2019-2023 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package common
  15. import (
  16. "sync"
  17. "sync/atomic"
  18. "github.com/drakkan/sftpgo/v2/internal/logger"
  19. )
  20. // clienstMap is a struct containing the map of the connected clients
  21. type clientsMap struct {
  22. totalConnections atomic.Int32
  23. mu sync.RWMutex
  24. clients map[string]int
  25. }
  26. func (c *clientsMap) add(source string) {
  27. c.totalConnections.Add(1)
  28. c.mu.Lock()
  29. defer c.mu.Unlock()
  30. c.clients[source]++
  31. }
  32. func (c *clientsMap) remove(source string) {
  33. c.mu.Lock()
  34. defer c.mu.Unlock()
  35. if val, ok := c.clients[source]; ok {
  36. c.totalConnections.Add(-1)
  37. c.clients[source]--
  38. if val > 1 {
  39. return
  40. }
  41. delete(c.clients, source)
  42. } else {
  43. logger.Warn(logSender, "", "cannot remove client %v it is not mapped", source)
  44. }
  45. }
  46. func (c *clientsMap) getTotal() int32 {
  47. return c.totalConnections.Load()
  48. }
  49. func (c *clientsMap) getTotalFrom(source string) int {
  50. c.mu.RLock()
  51. defer c.mu.RUnlock()
  52. return c.clients[source]
  53. }