subnet.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. // Copyright 2015 CoreOS, Inc.
  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. package subnet
  15. import (
  16. "encoding/json"
  17. "errors"
  18. "time"
  19. "github.com/coreos/flannel/Godeps/_workspace/src/golang.org/x/net/context"
  20. "github.com/coreos/flannel/pkg/ip"
  21. )
  22. type LeaseAttrs struct {
  23. PublicIP ip.IP4
  24. BackendType string `json:",omitempty"`
  25. BackendData json.RawMessage `json:",omitempty"`
  26. }
  27. type Lease struct {
  28. Subnet ip.IP4Net
  29. Attrs *LeaseAttrs
  30. Expiration time.Time
  31. }
  32. func (l *Lease) Key() string {
  33. return l.Subnet.StringSep(".", "-")
  34. }
  35. type (
  36. EventType int
  37. Event struct {
  38. Type EventType `json:"type"`
  39. Lease Lease `json:"lease"`
  40. }
  41. )
  42. const (
  43. SubnetAdded EventType = iota
  44. SubnetRemoved
  45. )
  46. type WatchResult struct {
  47. // Either Events or Leases should be set.
  48. // If Leases are not empty, it means the cursor
  49. // was out of range and Snapshot contains the current
  50. // list of leases
  51. Events []Event `json:"events"`
  52. Snapshot []Lease `json:"snapshot"`
  53. Cursor interface{} `json:"cursor"`
  54. }
  55. func (et EventType) MarshalJSON() ([]byte, error) {
  56. s := ""
  57. switch et {
  58. case SubnetAdded:
  59. s = "added"
  60. case SubnetRemoved:
  61. s = "removed"
  62. default:
  63. return nil, errors.New("bad event type")
  64. }
  65. return json.Marshal(s)
  66. }
  67. func (et *EventType) UnmarshalJSON(data []byte) error {
  68. switch string(data) {
  69. case "added":
  70. *et = SubnetAdded
  71. case "removed":
  72. *et = SubnetRemoved
  73. default:
  74. return errors.New("bad event type")
  75. }
  76. return nil
  77. }
  78. type Manager interface {
  79. GetNetworkConfig(ctx context.Context, network string) (*Config, error)
  80. AcquireLease(ctx context.Context, network string, attrs *LeaseAttrs) (*Lease, error)
  81. RenewLease(ctx context.Context, network string, lease *Lease) error
  82. WatchLeases(ctx context.Context, network string, cursor interface{}) (WatchResult, error)
  83. }