2
0

resources.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. Copyright © 2021-2022 Ettore Di Giacinto <[email protected]>
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package node
  14. import (
  15. "fmt"
  16. "strings"
  17. "github.com/libp2p/go-libp2p/core/network"
  18. "github.com/libp2p/go-libp2p/core/peer"
  19. libp2pprotocol "github.com/libp2p/go-libp2p/core/protocol"
  20. rcmgr "github.com/libp2p/go-libp2p/p2p/host/resource-manager"
  21. )
  22. func NetSetLimit(mgr network.ResourceManager, scope string, limit rcmgr.Limit) error {
  23. setLimit := func(s network.ResourceScope) error {
  24. limiter, ok := s.(rcmgr.ResourceScopeLimiter)
  25. if !ok {
  26. return fmt.Errorf("resource scope doesn't implement ResourceScopeLimiter interface")
  27. }
  28. limiter.SetLimit(limit)
  29. return nil
  30. }
  31. switch {
  32. case scope == "system":
  33. err := mgr.ViewSystem(func(s network.ResourceScope) error {
  34. return setLimit(s)
  35. })
  36. return err
  37. case scope == "transient":
  38. err := mgr.ViewTransient(func(s network.ResourceScope) error {
  39. return setLimit(s)
  40. })
  41. return err
  42. case strings.HasPrefix(scope, "svc:"):
  43. svc := scope[4:]
  44. err := mgr.ViewService(svc, func(s network.ServiceScope) error {
  45. return setLimit(s)
  46. })
  47. return err
  48. case strings.HasPrefix(scope, "proto:"):
  49. proto := scope[6:]
  50. err := mgr.ViewProtocol(libp2pprotocol.ID(proto), func(s network.ProtocolScope) error {
  51. return setLimit(s)
  52. })
  53. return err
  54. case strings.HasPrefix(scope, "peer:"):
  55. p := scope[5:]
  56. pid, err := peer.Decode(p)
  57. if err != nil {
  58. return fmt.Errorf("invalid peer ID: %s: %w", p, err)
  59. }
  60. err = mgr.ViewPeer(pid, func(s network.PeerScope) error {
  61. return setLimit(s)
  62. })
  63. return err
  64. default:
  65. return fmt.Errorf("invalid scope %s", scope)
  66. }
  67. }