subnet.go 2.3 KB

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