25 Commits

Author SHA1 Message Date
Ben Roberts
fe399e2f03 Support for reloading config file on HUP signal
Implemented dynamic configuration reloading for gocast via SIGHUP signal handling. This allows updating BGP configuration, applications, and agent settings without service restart.

**Location:** `main.go:29-46`

Enhanced the existing signal handler to process SIGHUP:
```go
switch sig {
case syscall.SIGHUP:
    log.Info("Received SIGHUP, reloading configuration")
    if err := mon.Reload(*config); err != nil {
        log.Errorf("Failed to reload configuration: %v", err)
    } else {
        log.Info("Configuration reloaded successfully")
    }
case os.Interrupt, syscall.SIGTERM:
    log.Info("Received shutdown signal, cleaning up")
    mon.CloseAll()
    cancel()
    return
}
```

**Key Features:**
- Non-blocking: Uses goroutine to handle signals
- Graceful: SIGINT/SIGTERM still trigger clean shutdown
- Logged: All reload attempts are logged with success/failure status

**Location:** `controller/monitor.go:343-420`

Main reload orchestration method:

```go
func (m *MonitorMgr) Reload(configPath string) error
```

**Process Flow:**
1. Read new configuration from file
2. Compare with current configuration
3. If BGP config changed:
   - Withdraw all announced routes
   - Shutdown old BGP controller
   - Start new BGP controller
   - Re-announce routes for healthy apps
4. If Consul config changed:
   - Initialize new Consul monitor
5. Update agent settings
6. Reload applications (add/remove/update)

**Thread Safety:**
- Uses existing `monMu` mutex for monitor map access
- Atomic BGP controller replacement
- No race conditions during reload

**Location:** `controller/monitor.go:422-475`

```go
func (m *MonitorMgr) bgpConfigChanged(old, new c.BgpConfig) bool
```

Comprehensive comparison of:
- Local AS, Peer AS, Peer IPs
- BGP origin
- Multi-hop settings (including nil checks)
- MD5 passwords and environment variables
- Per-peer communities
- Global communities

**Important:** Deep comparison ensures even minor changes are detected.

**Location:** `controller/monitor.go:477-532`

```go
func (m *MonitorMgr) reloadApps(oldApps, newApps []c.AppConfig)
```

Intelligent app management:
- **Remove:** Apps no longer in config (source="config" only)
- **Update:** Apps with changed configuration (VIP, monitors, NAT, communities)
- **Add:** New apps in configuration

**Key Behavior:**
- Consul-discovered apps are NOT removed during reload
- Only config-defined apps are managed
- Config changes trigger remove + re-add

1. **TestBgpConfigChanged**
   - Tests all BGP configuration change scenarios
   - Validates detection of AS, peer, MD5, community changes
   - Includes nil multi-hop pointer checks

2. **TestEqualStringSlices**
   - Tests slice comparison helper
   - Validates empty, identical, and different slices

3. **TestReload** (Integration, requires root)
   - Full reload cycle with BGP AS change
   - App removal verification
   - BGP controller replacement validation

4. **TestReloadAddApp** (Integration)
   - Tests adding new app via reload
   - Validates app registration

5. **TestReloadMD5Change** (Integration)
   - Tests MD5 password change detection
   - Validates BGP controller restart

**Decision:** Reload BGP configuration requires full controller restart.

**Rationale:**
- GoBGP library doesn't support modifying peers dynamically
- Simplifies implementation
- Ensures clean state
- Brief interruption is acceptable for infrequent config changes

**Alternative Considered:** Per-peer updates
- Complex to implement correctly
- Partial state issues
- Not supported well by GoBGP library

**Decision:** Log errors but don't crash; maintain old state on failure.

**Rationale:**
- Availability over correctness for config errors
- Admin can fix config and retry
- Better than service downtime
- Logs provide clear error messages

1. **BGP Interruption**
   - Full BGP restart causes brief routing interruption
   - All routes withdrawn and re-announced
   - May impact traffic during reload

2. **No Atomic BGP Updates**
   - Cannot add/remove single peer without full restart
   - All peers affected even if one changes

3. **No Config Validation**
   - Invalid config is detected during reload
   - No pre-validation before applying
   - Syntax errors require manual fix and retry

4. **No Rollback**
   - Failed reload leaves service in potentially inconsistent state
   - Manual intervention required to restore
   - No automatic rollback to previous config

These changes were written using AI LLM

Authored-By: Claude Code (Sonnet 4.5)
2026-06-17 16:52:03 +01:00
Ben Roberts
d54573e469 Implement BGP MD5 Auth
BGP peers can now be secured with MD5 authentication (TCP MD5 signatures as defined in RFC 2385). This provides an additional layer of security to prevent unauthorized BGP sessions.

MD5 authentication is configured per peer and supports two methods for specifying passwords:

Store passwords in environment variables for better security:

```yaml
bgp:
  local_as: 12345
  peers:
    - peer_ip: 10.10.10.1
      peer_as: 6789
      md5_env_var: GOCAST_BGP_PEER1_PASSWORD
```

Set the environment variable before starting gocast:

```bash
export GOCAST_BGP_PEER1_PASSWORD="your_secret_password"
./gocast -config config.yaml
```

**Benefits:**
- Passwords not stored in config files
- Easier secret rotation
- Better for containerized deployments (Kubernetes secrets, Docker secrets, etc.)
- Compatible with secret management systems (Vault, AWS Secrets Manager, etc.)

Specify passwords directly in the config file:

```yaml
bgp:
  local_as: 12345
  peers:
    - peer_ip: 10.10.10.1
      peer_as: 6789
      md5_password: "your_secret_password"
```

**Note:** This method is less secure as passwords are stored in plain text. Only use for testing or when environment variables are not available.

When both `md5_env_var` and `md5_password` are specified, the environment variable takes priority. This allows you to:
- Define a default password in the config
- Override it with an environment variable in production
- Use different passwords per environment without changing config files

Different peers can use different authentication methods:

```yaml
bgp:
  local_as: 12345
  peers:
    # Peer 1: Environment variable
    - peer_ip: 10.10.10.1
      peer_as: 6789
      md5_env_var: GOCAST_BGP_PEER1_PASSWORD

    # Peer 2: Config file password
    - peer_ip: 10.10.10.2
      peer_as: 6789
      md5_password: "fallback_password"

    # Peer 3: No authentication
    - peer_ip: 10.10.10.3
      peer_as: 6789
```

Recommended naming patterns:

```bash
export GOCAST_BGP_PRIMARY_PEER_PASSWORD="secret1"
export GOCAST_BGP_SECONDARY_PEER_PASSWORD="secret2"

export GOCAST_BGP_10_10_10_1_PASSWORD="secret1"
export GOCAST_BGP_10_10_10_2_PASSWORD="secret2"

export GOCAST_BGP_AS6789_PASSWORD="secret1"
```

**config/config.go**
- Added `MD5Password` field to `PeerConfig` for config file passwords
- Added `MD5EnvVar` field to `PeerConfig` for environment variable references

**controller/bgp.go**
- Added `getMD5Password()` helper function to retrieve passwords
- Modified `addPeer()` to configure MD5 authentication when available
- Environment variable lookup prioritizes env vars over config passwords

Comprehensive test suite covering:
- MD5 password from config file
- MD5 password from environment variable
- Environment variable priority over config
- No authentication scenario
- Fallback to config when env var is empty
- Multiple peers with mixed authentication methods

This commit was written using AI LLM

Authored-By: Claude Code (Sonnet 4.5)
2026-06-17 15:52:43 +01:00
Ben Roberts
567a84095e Implement support for multiple BGP peers
The BGP controller now supports announcing routes to multiple BGP peers for redundancy and resilience. If one peer fails, route announcements continue to succeed for other healthy peers.

```yaml
bgp:
  local_as: 12345
  local_ip: 192.168.1.100  # optional
  peers:
    - peer_ip: 10.10.10.1
      peer_as: 6789
      communities:        # per-peer communities (optional)
        - 100:100
    - peer_ip: 10.10.10.2
      peer_as: 6789
      communities:
        - 100:101
      multi_hop: true     # optional, defaults to true for eBGP
  communities:            # global communities applied to all peers
    - 1000:1000
  origin: igp
```

```yaml
bgp:
  local_as: 12345
  peer_as: 6789
  peer_ip: 10.10.10.1
  communities:
    - 100:100
  origin: igp
```

Legacy configurations are automatically converted to the new format internally, ensuring backward compatibility.

Routes are announced to all configured peers. If announcement to one peer fails, the operation continues for other peers. Errors are aggregated and returned, but partial success is allowed.

Communities are merged in the following order:
1. **Global communities** (defined at `bgp.communities`)
2. **Per-peer communities** (defined at `bgp.peers[].communities`)
3. **Per-route communities** (defined at `apps[].vip_config.bgp_communities`)

Example: If global communities are `[1000:1000]`, peer communities are `[100:100]`, and route communities are `[5000:5000]`, the announced route will have all three: `[1000:1000, 100:100, 5000:5000]`.

- **Default behavior**: Multi-hop is disabled by default
- **Enable**: Set `multi_hop: true` per peer to explicitly enable multi-hop BGP

The `/info` endpoint now returns an array of peer information instead of a single peer object:

**Before:**
```json
{
  "conf": {
    "neighbor_address": "10.10.10.1",
    "peer_as": 6789
  },
  "state": {...}
}
```

**After:**
```json
[
  {
    "conf": {
      "neighbor_address": "10.10.10.1",
      "peer_as": 6789
    },
    "state": {...}
  },
  {
    "conf": {
      "neighbor_address": "10.10.10.2",
      "peer_as": 6789
    },
    "state": {...}
  }
]
```

- `config/config.go`: Added `PeerConfig` struct and `Peers` slice to `BgpConfig`
- `controller/bgp.go`: Refactored to support multiple peers with best-effort semantics
- `controller/monitor.go`: Updated `GetInfo()` to return slice of peers
- `server/server.go`: Updated info handler to return array of peers

1. **Controller struct** now stores `[]PeerConfig` instead of single peer fields
2. **Announce/Withdraw** methods loop through all peers with error aggregation
3. **getApiPath** accepts a `PeerConfig` parameter for per-peer community merging
4. **addPeer** determines multi-hop settings per peer
5. **PeerInfo** returns information for all configured peers
6. **Shutdown** gracefully shuts down all peer sessions

The implementation includes comprehensive test coverage:

1. **TestLegacyConfigConversion** - Verifies backward compatibility by testing that legacy single-peer configs are automatically converted to multi-peer format
2. **TestMultiPeerConfig** - Tests that new multi-peer configurations are properly loaded with multiple peers
3. **TestNoPeersConfigError** - Ensures proper error handling when no peers are configured
4. **TestCommunityMerging** - Validates that global, per-peer, and per-route communities are correctly merged in order
5. **TestMultiHopConfiguration** - Tests multi-hop BGP settings with various scenarios:
   - Default behavior (multi-hop disabled)
   - Explicit multi-hop disable
   - Explicit multi-hop enable
6. **TestBestEffortAnnouncement** - Verifies that announcements succeed even when individual peers may have issues
7. **TestWithdrawMultiplePeers** - Tests route withdrawal across multiple peers
8. **TestPeerInfoMultiplePeers** - Validates that peer information is correctly returned for all configured peers

- **TestBgpNew** - Full integration test with actual BGP listeners (requires root, skipped in CI)
- **TestMultiPeerAnnouncement** - Tests actual route announcements to multiple BGP listeners (requires root, skipped in CI)

Existing configurations using `peer_ip` and `peer_as` continue to work without modification.

To add a second peer for resilience:

```yaml
bgp:
  local_as: 12345
  # Keep existing config for backward compatibility, or remove these lines
  # peer_as: 6789
  # peer_ip: 10.10.10.1

  # Add new multi-peer config
  peers:
    - peer_ip: 10.10.10.1
      peer_as: 6789
    - peer_ip: 10.10.10.2  # redundant peer
      peer_as: 6789
  communities:
    - 100:100
  origin: igp
```

All operations (Announce, Withdraw, Shutdown) use best-effort error handling:
- Operations continue even if individual peers fail
- Errors are collected and returned as aggregated error messages
- Format: `"announcement errors: [peer 10.10.10.1: error message, peer 10.10.10.2: error message]"`

These changes were authored via AI LLM.

Authored-By: Claude Code (Sonnet 4.5)
2026-06-17 15:52:43 +01:00
mayuresh82
6f26e86964 Update README.md 2023-08-18 16:08:19 -07:00
mayuresh82
92c9ae3859 Merge pull request #22 from spanthetree/patch-1
Update config.yaml
2023-08-16 16:21:39 -07:00
David Woodruff
1d8c3936e1 Update config.yaml 2023-07-11 07:51:38 +09:00
mayuresh82
e3ed374b53 Merge pull request #17 from naveenachyuta/add_consul_token_support
add support for consul token auth
2022-09-20 11:50:17 -07:00
Naveen Achyuta
8a36bb153a check for error 2022-09-01 13:59:24 -07:00
Naveen Achyuta
e1825b4581 add support for consul token auth 2022-08-22 12:26:35 -07:00
mayuresh82
e285d3a1c5 Merge pull request #16 from isazpiazu-roblox/gobgp_update
Update GoBGP module to v2.34.0
2022-06-02 13:20:14 -07:00
Ian Azpiazu
80d743ffa5 update gobgp pkg 2022-05-16 13:40:57 -04:00
Ian Azpiazu
878ee3a63e update gobgp package to v2.34.0 commit 2022-05-12 14:57:47 -04:00
mayuresh82
adaa755430 Merge pull request #14 from philipcristiano/healcheck
consul: healcheck -> healthcheck
2022-04-25 11:29:15 -07:00
Philip Cristiano
2ab950667e consul: healcheck -> healthcheck 2022-04-23 11:27:33 -04:00
mayuresh82
8d3c63637c Merge pull request #13 from danlsgiga/iptables-listen-destination-port
Add listen port option for NAT routing
2022-03-31 12:23:22 -07:00
mayuresh82
c6adbd9fb5 Update README.md 2022-03-26 11:16:50 -07:00
Daniel Santos
fa25f9430f doc(README): Add alternative way of specifying gocast_nat 2022-03-24 11:00:21 -06:00
Daniel Santos
837226952d chore(monitor): Backwards compatibility 2022-03-24 10:32:52 -06:00
Daniel Santos
58d37566bf doc(README): Cosmetic change 2022-03-16 13:30:26 -06:00
Daniel Santos
f1542981d6 feat(gocast_nat): Add listen port option 2022-03-16 13:23:35 -06:00
mgaitonde
f883e4d4b3 Expand system error message 2022-03-09 13:17:04 -08:00
mayuresh82
a38dc2f48f Merge pull request #12 from mayuresh82/race_fix
attempt to fix a race condition
2022-03-09 12:28:28 -08:00
Mayuresh Gaitonde
04159185c9 Fix 2021-12-15 17:10:28 -08:00
Mayuresh Gaitonde
c860f3c50e checks to Add new app 2021-12-15 16:44:13 -08:00
Mayuresh Gaitonde
62db2e5af7 attempt to fix a race condition 2021-12-15 15:36:51 -08:00
669 changed files with 138218 additions and 98478 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
.vscode

View File

@@ -10,7 +10,7 @@ COPY . /go/src/github.com/mayuresh82/gocast
WORKDIR /go/src/github.com/mayuresh82/gocast WORKDIR /go/src/github.com/mayuresh82/gocast
RUN make RUN make linux
FROM alpine:latest FROM alpine:latest
RUN apk --no-cache add ca-certificates bash iptables netcat-openbsd sudo RUN apk --no-cache add ca-certificates bash iptables netcat-openbsd sudo

View File

@@ -13,4 +13,4 @@ test:
go test -v -race -short -failfast -mod=vendor ./... go test -v -race -short -failfast -mod=vendor ./...
linux: linux:
GOOS=linux GOARCH=amd64 go build -o gocast_linux -mod=vendor . CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o gocast -mod=vendor .

View File

@@ -3,6 +3,11 @@
Gocast is a tool that does controller BGP route advertisements from a host. It runs custom defined healthchecks and announces or withdraws routes (most commonly VIPs or Virtual IPs) to a BGP peer. Gocast is a tool that does controller BGP route advertisements from a host. It runs custom defined healthchecks and announces or withdraws routes (most commonly VIPs or Virtual IPs) to a BGP peer.
The most common use case for this is anycast (vip) based load balancing for infrastructure services such as DNS, Syslog etc where several instances are available in geographically diverse regions that announce the same anycast VIP, and clients then get sent to the closest instance. The most common use case for this is anycast (vip) based load balancing for infrastructure services such as DNS, Syslog etc where several instances are available in geographically diverse regions that announce the same anycast VIP, and clients then get sent to the closest instance.
For some practical examples and more details, check out this blog post : https://mayuresh82.github.io/2020/11/28/automatic_service_discovery_anycast/
# Looking for code reviewers
If you are interested in being a reviewer and/or co-maintainer, please reach out to @mayuresh82 !
## Installation ## Installation
Use the docker container at mayuresh82/gocast or compile from source: Use the docker container at mayuresh82/gocast or compile from source:
@@ -50,6 +55,30 @@ GoCast supports consul for automatic service discovery and healthchecking. For t
If `gocast_monitor=consul` is specified, then GoCast uses the defined healthchecks in consul as the health monitors for the service. If `gocast_monitor=consul` is specified, then GoCast uses the defined healthchecks in consul as the health monitors for the service.
If `gocast_nat=protocol:listenPort:destinationPort` is specified, then GoCast will create NAT rules, via iptables, and map traffic destined to the assigned VIP and the specified `listenPort` to the physical IP and `destinationPort`.
Example: `gocast_nat=tcp:53:8053` and `gocast_nat=udp:53:8053`
Alternatively, if `gocast_nat=protocol:port` is specified, then GoCast will create NAT rules, via iptables, and map traffic destined to the assigned VIP and the specified `port` to the physical IP and `port`.
Example: `gocast_nat=tcp:53` and `gocast_nat=udp:53`
## Configuration Reload
GoCast supports dynamic configuration reloading without service restart. Send a `SIGHUP` signal to reload the configuration:
```bash
kill -HUP $(pidof gocast)
```
**What gets reloaded:**
- BGP configuration (peers, AS numbers, MD5 passwords, communities)
- Application definitions (add/remove/update apps)
- Agent settings (Consul, timers, intervals)
**Important:** Reloading BGP configuration causes existing BGP sessions to be restarted, resulting in brief routing interruption. Routes are automatically re-announced after reload.
Consul-discovered apps are not removed during reload.
## Docker support ## Docker support
The docker image at mayuresh82/gocast can be used to run GoCast inside a container. In order for GoCast to manipulate the host network stack correctly, the container needs to run with NET_ADMIN capablity and host mode networking. For example: The docker image at mayuresh82/gocast can be used to run GoCast inside a container. In order for GoCast to manipulate the host network stack correctly, the container needs to run with NET_ADMIN capablity and host mode networking. For example:
``` ```
@@ -63,7 +92,7 @@ Certain orchestration solutions such as Nomad run the docker containers with pub
- Start the service container in host networking mode OR - Start the service container in host networking mode OR
- Register NAT rules for your service with GoCast for the required protocol/port(s). GoCast will then create iptables NAT rules that map traffic destined to the assigned VIP to the physical IP address. This is achieved by adding the `nat=protocol:port` tag(s) in consul or the http query. - Register NAT rules for your service with GoCast for the required protocol/port(s). GoCast will then create iptables NAT rules that map traffic destined to the assigned VIP to the physical IP address. This is achieved by adding the `nat=protocol:listenPort:destinationPort` in the http query or `gocast_nat=protocol:listenPort:destinationPort` tag(s) in consul, as shown in the Consul integration section above.
**Why not just use ExaBGP or something similar ?** **Why not just use ExaBGP or something similar ?**

View File

@@ -9,12 +9,31 @@ agent:
consul_addr: https://consul consul_addr: https://consul
# interval to query consul for app discovery # interval to query consul for app discovery
consul_query_interval: 5m consul_query_interval: 5m
# token to authenticate client if consul requires it
consul_token: 00000000-0000-0000-0000-000000000000
bgp: bgp:
local_as: 12345 local_as: 12345
remote_as: 6789 remote_as: 6789
# override the peer IP to use instead of auto discovering # override the peer IP to use instead of auto discovering
peer_ip: 10.10.10.1 peer_ip: 10.10.10.1
# Alternatively, define multiple BGP peers for redundancy
#peers:
# - peer_ip: 10.10.10.1
# peer_as: 6789
# communities:
# - 100:100
# - 200:200
# md5_env_var: GOCAST_BGP_PEER1_PASSWORD # optional. Set via: export GOCAST_BGP_PEER1_PASSWORD="secret"
# - peer_ip: 10.10.10.2
# peer_as: 6789
# communities:
# - 100:101
# - 200:201
# multi_hop: true # optional
# md5_password: "secret123" # optional
communities: communities:
- asn:nnnn - asn:nnnn
- asn:nnnn - asn:nnnn
@@ -27,4 +46,5 @@ apps:
vip_config: vip_config:
# additional per VIP BGP communities # additional per VIP BGP communities
bgp_communities: [ aaaa:bbbb ] bgp_communities: [ aaaa:bbbb ]
monitor: port:tcp:5000 monitors:
- port:tcp:5000

View File

@@ -15,13 +15,26 @@ type AgentConfig struct {
CleanupTimer time.Duration `yaml:"cleanup_timer"` CleanupTimer time.Duration `yaml:"cleanup_timer"`
ConsulAddr string `yaml:"consul_addr"` ConsulAddr string `yaml:"consul_addr"`
ConsulQueryInterval time.Duration `yaml:"consul_query_interval"` ConsulQueryInterval time.Duration `yaml:"consul_query_interval"`
ConsulToken string `yaml:"consul_token"`
}
type PeerConfig struct {
PeerIP string `yaml:"peer_ip"`
PeerAS int `yaml:"peer_as"`
MultiHop *bool `yaml:"multi_hop,omitempty"`
Communities []string `yaml:"communities,omitempty"`
MD5Password string `yaml:"md5_password,omitempty"`
MD5EnvVar string `yaml:"md5_env_var,omitempty"`
} }
type BgpConfig struct { type BgpConfig struct {
LocalAS int `yaml:"local_as"` LocalAS int `yaml:"local_as"`
PeerAS int `yaml:"peer_as"`
LocalIP string `yaml:"local_ip"` LocalIP string `yaml:"local_ip"`
PeerIP string `yaml:"peer_ip"` // Legacy single-peer config (deprecated but supported for backward compatibility)
PeerAS int `yaml:"peer_as,omitempty"`
PeerIP string `yaml:"peer_ip,omitempty"`
// New multi-peer config
Peers []PeerConfig `yaml:"peers,omitempty"`
Communities []string Communities []string
Origin string Origin string
} }

View File

@@ -4,6 +4,7 @@ import (
"context" "context"
"fmt" "fmt"
"net" "net"
"os"
"strconv" "strconv"
"strings" "strings"
@@ -20,82 +21,134 @@ type Route struct {
} }
type Controller struct { type Controller struct {
peerAS int localAS int
localIP, peerIP net.IP localIP net.IP
peers []c.PeerConfig
communities []string communities []string
origin uint32 origin uint32
multiHop bool
s *gobgp.BgpServer s *gobgp.BgpServer
} }
func NewController(config c.BgpConfig) (*Controller, error) { func NewController(config c.BgpConfig) (*Controller, error) {
c := &Controller{} ctrl := &Controller{}
var gw net.IP var gw net.IP
var err error var err error
if config.PeerIP == "" {
gw, err := gateway() // Normalize config: convert legacy single-peer to new multi-peer format
if err != nil { peers := config.Peers
return nil, fmt.Errorf("Unable to get gw ip: %v", err) if len(peers) == 0 {
} // Backward compatibility: convert legacy config
c.peerIP = gw if config.PeerIP != "" {
// Explicit peer IP configured
peers = []c.PeerConfig{{
PeerIP: config.PeerIP,
PeerAS: config.PeerAS,
}}
} else { } else {
c.peerIP = net.ParseIP(config.PeerIP) // No peer IP configured - use default gateway
gw, err = gateway()
if err != nil {
return nil, fmt.Errorf("Unable to get gateway ip: %v", err)
} }
peers = []c.PeerConfig{{
PeerIP: gw.String(),
PeerAS: config.PeerAS,
}}
}
}
// Determine local IP
if config.LocalIP == "" { if config.LocalIP == "" {
gw, err = via(c.peerIP) // Use first peer to determine local IP
firstPeerIP := net.ParseIP(peers[0].PeerIP)
if firstPeerIP == nil {
gw, err = gateway()
if err != nil { if err != nil {
return nil, fmt.Errorf("Unable to get gw ip: %v", err) return nil, fmt.Errorf("Unable to get gw ip: %v", err)
} }
c.localIP, err = localAddress(gw) firstPeerIP = gw
}
gw, err = via(firstPeerIP)
if err != nil {
return nil, fmt.Errorf("Unable to get gw ip: %v", err)
}
ctrl.localIP, err = localAddress(gw)
if err != nil { if err != nil {
return nil, err return nil, err
} }
} else { } else {
c.localIP = net.ParseIP(config.LocalIP) ctrl.localIP = net.ParseIP(config.LocalIP)
} }
c.communities = config.Communities
ctrl.localAS = config.LocalAS
ctrl.peers = peers
ctrl.communities = config.Communities
switch config.Origin { switch config.Origin {
case "igp": case "igp":
c.origin = 0 ctrl.origin = 0
case "egp": case "egp":
c.origin = 1 ctrl.origin = 1
case "unknown": case "unknown":
c.origin = 2 ctrl.origin = 2
} }
s := gobgp.NewBgpServer() s := gobgp.NewBgpServer()
go s.Serve() go s.Serve()
if err := s.StartBgp(context.Background(), &api.StartBgpRequest{ if err := s.StartBgp(context.Background(), &api.StartBgpRequest{
Global: &api.Global{ Global: &api.Global{
As: uint32(config.LocalAS), As: uint32(config.LocalAS),
RouterId: c.localIP.String(), RouterId: ctrl.localIP.String(),
ListenPort: -1, // gobgp won't listen on tcp:179 ListenPort: -1, // gobgp won't listen on tcp:179
}, },
}); err != nil { }); err != nil {
return nil, fmt.Errorf("Unable to start bgp: %v", err) return nil, fmt.Errorf("Unable to start bgp: %v", err)
} }
c.s = s ctrl.s = s
c.peerAS = config.PeerAS
// set mh by default for all ebgp peers return ctrl, nil
if c.peerAS != config.LocalAS {
c.multiHop = true
}
return c, nil
} }
func (c *Controller) AddPeer(peer string) error { func (c *Controller) addPeer(peer *c.PeerConfig) error {
n := &api.Peer{ n := &api.Peer{
Conf: &api.PeerConf{ Conf: &api.PeerConf{
NeighborAddress: peer, NeighborAddress: peer.PeerIP,
PeerAs: uint32(c.peerAS), PeerAs: uint32(peer.PeerAS),
}, },
} }
if c.multiHop {
// Enable multihop only if explicitly configured
if peer.MultiHop != nil && *peer.MultiHop {
n.EbgpMultihop = &api.EbgpMultihop{Enabled: true, MultihopTtl: uint32(255)} n.EbgpMultihop = &api.EbgpMultihop{Enabled: true, MultihopTtl: uint32(255)}
} }
// Configure MD5 authentication if specified
md5Password := c.getMD5Password(peer)
if md5Password != "" {
n.Conf.AuthPassword = md5Password
}
return c.s.AddPeer(context.Background(), &api.AddPeerRequest{Peer: n}) return c.s.AddPeer(context.Background(), &api.AddPeerRequest{Peer: n})
} }
func (c *Controller) getApiPath(route *Route) *api.Path { // getMD5Password retrieves the MD5 password from config or environment variable
func (c *Controller) getMD5Password(peer *c.PeerConfig) string {
// Priority 1: Check for environment variable
if peer.MD5EnvVar != "" {
if password := os.Getenv(peer.MD5EnvVar); password != "" {
return password
}
}
// Priority 2: Use password from config file
if peer.MD5Password != "" {
return peer.MD5Password
}
return ""
}
func (c *Controller) getApiPath(route *Route, peer *c.PeerConfig) *api.Path {
afi := api.Family_AFI_IP afi := api.Family_AFI_IP
if route.Net.IP.To4() == nil { if route.Net.IP.To4() == nil {
afi = api.Family_AFI_IP6 afi = api.Family_AFI_IP6
@@ -111,8 +164,15 @@ func (c *Controller) getApiPath(route *Route) *api.Path {
a2, _ := ptypes.MarshalAny(&api.NextHopAttribute{ a2, _ := ptypes.MarshalAny(&api.NextHopAttribute{
NextHop: c.localIP.String(), NextHop: c.localIP.String(),
}) })
// Merge communities: global + per-peer + per-route
var allCommunities []string
allCommunities = append(allCommunities, c.communities...)
allCommunities = append(allCommunities, peer.Communities...)
allCommunities = append(allCommunities, route.Communities...)
var communities []uint32 var communities []uint32
for _, comm := range append(c.communities, route.Communities...) { for _, comm := range allCommunities {
communities = append(communities, convertCommunity(comm)) communities = append(communities, convertCommunity(comm))
} }
a3, _ := ptypes.MarshalAny(&api.CommunitiesAttribute{ a3, _ := ptypes.MarshalAny(&api.CommunitiesAttribute{
@@ -127,49 +187,105 @@ func (c *Controller) getApiPath(route *Route) *api.Path {
} }
func (c *Controller) Announce(route *Route) error { func (c *Controller) Announce(route *Route) error {
var errs []error
for i := range c.peers {
peer := &c.peers[i]
// Check if peer exists
var found bool var found bool
err := c.s.ListPeer(context.Background(), &api.ListPeerRequest{}, func(p *api.Peer) { err := c.s.ListPeer(context.Background(), &api.ListPeerRequest{}, func(p *api.Peer) {
if p.Conf.NeighborAddress == c.peerIP.String() { if p.Conf.NeighborAddress == peer.PeerIP {
found = true found = true
} }
}) })
if err != nil { if err != nil {
return err errs = append(errs, fmt.Errorf("peer %s: list error: %v", peer.PeerIP, err))
continue
} }
// Add peer if not found
if !found { if !found {
if err := c.AddPeer(c.peerIP.String()); err != nil { if err := c.addPeer(peer); err != nil {
return err errs = append(errs, fmt.Errorf("peer %s: add error: %v", peer.PeerIP, err))
continue
} }
} }
_, err = c.s.AddPath(context.Background(), &api.AddPathRequest{Path: c.getApiPath(route)})
return err // Announce route to this peer
path := c.getApiPath(route, peer)
if _, err := c.s.AddPath(context.Background(), &api.AddPathRequest{Path: path}); err != nil {
errs = append(errs, fmt.Errorf("peer %s: announce error: %v", peer.PeerIP, err))
continue
}
}
// Return aggregated errors if any peer failed
if len(errs) > 0 {
return fmt.Errorf("announcement errors: %v", errs)
}
return nil
} }
func (c *Controller) Withdraw(route *Route) error { func (c *Controller) Withdraw(route *Route) error {
return c.s.DeletePath(context.Background(), &api.DeletePathRequest{Path: c.getApiPath(route)}) var errs []error
for i := range c.peers {
peer := &c.peers[i]
path := c.getApiPath(route, peer)
if err := c.s.DeletePath(context.Background(), &api.DeletePathRequest{Path: path}); err != nil {
errs = append(errs, fmt.Errorf("peer %s: withdraw error: %v", peer.PeerIP, err))
continue
}
}
// Return aggregated errors if any peer failed
if len(errs) > 0 {
return fmt.Errorf("withdrawal errors: %v", errs)
}
return nil
} }
func (c *Controller) PeerInfo() (*api.Peer, error) { func (c *Controller) PeerInfo() ([]*api.Peer, error) {
var peer *api.Peer var peers []*api.Peer
peerMap := make(map[string]bool)
// Build map of configured peer IPs
for _, peer := range c.peers {
peerMap[peer.PeerIP] = true
}
// Collect info for all configured peers
err := c.s.ListPeer(context.Background(), &api.ListPeerRequest{}, func(p *api.Peer) { err := c.s.ListPeer(context.Background(), &api.ListPeerRequest{}, func(p *api.Peer) {
if p.Conf.NeighborAddress == c.peerIP.String() { if peerMap[p.Conf.NeighborAddress] {
peer = p peers = append(peers, p)
} }
}) })
if err != nil { if err != nil {
return nil, err return nil, err
} }
return peer, nil return peers, nil
} }
func (c *Controller) Shutdown() error { func (c *Controller) Shutdown() error {
var errs []error
// Shutdown all peer sessions
for _, peer := range c.peers {
if err := c.s.ShutdownPeer(context.Background(), &api.ShutdownPeerRequest{ if err := c.s.ShutdownPeer(context.Background(), &api.ShutdownPeerRequest{
Address: c.peerIP.String(), Address: peer.PeerIP,
}); err != nil { }); err != nil {
return err errs = append(errs, fmt.Errorf("peer %s: shutdown error: %v", peer.PeerIP, err))
} }
}
// Stop BGP server
if err := c.s.StopBgp(context.Background(), &api.StopBgpRequest{}); err != nil { if err := c.s.StopBgp(context.Background(), &api.StopBgpRequest{}); err != nil {
return err errs = append(errs, fmt.Errorf("stop bgp error: %v", err))
}
if len(errs) > 0 {
return fmt.Errorf("shutdown errors: %v", errs)
} }
return nil return nil
} }

View File

@@ -102,3 +102,578 @@ func TestBgpNew(t *testing.T) {
a.Equal("20.30.40.0/24", path) a.Equal("20.30.40.0/24", path)
ctrl.Shutdown() ctrl.Shutdown()
} }
func TestLegacyConfigConversion(t *testing.T) {
a := assert.New(t)
// Test legacy single-peer config
legacyConfig := config.BgpConfig{
LocalAS: 11111,
PeerAS: 22222,
PeerIP: "10.10.10.1",
LocalIP: "192.168.1.100",
Communities: []string{"100:100"},
Origin: "igp",
}
ctrl, err := NewController(legacyConfig)
if err != nil {
a.FailNow(err.Error())
}
defer ctrl.Shutdown()
// Verify legacy config was converted to multi-peer format
a.Equal(1, len(ctrl.peers), "Should have exactly 1 peer")
a.Equal("10.10.10.1", ctrl.peers[0].PeerIP)
a.Equal(22222, ctrl.peers[0].PeerAS)
}
func TestMultiPeerConfig(t *testing.T) {
a := assert.New(t)
// Test new multi-peer config
multiPeerConfig := config.BgpConfig{
LocalAS: 11111,
LocalIP: "192.168.1.100",
Peers: []config.PeerConfig{
{PeerIP: "10.10.10.1", PeerAS: 22222},
{PeerIP: "10.10.10.2", PeerAS: 22222},
},
Communities: []string{"100:100"},
Origin: "igp",
}
ctrl, err := NewController(multiPeerConfig)
if err != nil {
a.FailNow(err.Error())
}
defer ctrl.Shutdown()
// Verify both peers are configured
a.Equal(2, len(ctrl.peers), "Should have exactly 2 peers")
a.Equal("10.10.10.1", ctrl.peers[0].PeerIP)
a.Equal("10.10.10.2", ctrl.peers[1].PeerIP)
}
func TestDefaultGatewayPeer(t *testing.T) {
a := assert.New(t)
// Test config with no peer_ip - should use default gateway
defaultGatewayConfig := config.BgpConfig{
LocalAS: 11111,
LocalIP: "192.168.1.100",
PeerAS: 22222,
Origin: "igp",
}
ctrl, err := NewController(defaultGatewayConfig)
a.NoError(err, "Should not error when peer_ip is not specified")
if err == nil {
defer ctrl.Shutdown()
// Verify a peer was configured using gateway
a.Equal(1, len(ctrl.peers), "Should have exactly 1 peer")
a.NotEmpty(ctrl.peers[0].PeerIP, "Peer IP should be set from gateway")
a.Equal(22222, ctrl.peers[0].PeerAS, "Peer AS should match config")
}
}
func TestCommunityMerging(t *testing.T) {
a := assert.New(t)
ctrl := &Controller{
localAS: 11111,
localIP: net.ParseIP("192.168.1.100"),
communities: []string{"1000:1000", "2000:2000"}, // Global
origin: 0,
}
peer := &config.PeerConfig{
PeerIP: "10.10.10.1",
PeerAS: 22222,
Communities: []string{"100:100", "200:200"}, // Per-peer
}
route := &Route{
Net: &net.IPNet{
IP: net.ParseIP("20.30.40.0"),
Mask: net.CIDRMask(24, 32),
},
Communities: []string{"5000:5000"}, // Per-route
}
path := ctrl.getApiPath(route, peer)
// Extract communities from path
var commAttr *api.CommunitiesAttribute
for _, attr := range path.Pattrs {
var dynAny ptypes.DynamicAny
if err := ptypes.UnmarshalAny(attr, &dynAny); err == nil {
if c, ok := dynAny.Message.(*api.CommunitiesAttribute); ok {
commAttr = c
break
}
}
}
a.NotNil(commAttr, "Should have communities attribute")
a.Equal(5, len(commAttr.Communities), "Should have 5 communities (2 global + 2 peer + 1 route)")
// Verify community values (converted to uint32)
expectedCommunities := []uint32{
convertCommunity("1000:1000"), // Global
convertCommunity("2000:2000"), // Global
convertCommunity("100:100"), // Per-peer
convertCommunity("200:200"), // Per-peer
convertCommunity("5000:5000"), // Per-route
}
a.Equal(expectedCommunities, commAttr.Communities)
}
func TestMultiHopConfiguration(t *testing.T) {
a := assert.New(t)
testCases := []struct {
name string
localAS int
peerAS int
multiHopPtr *bool
expectMH bool
}{
{
name: "default - multihop not enabled",
localAS: 11111,
peerAS: 22222,
multiHopPtr: nil,
expectMH: false,
},
{
name: "explicit disable",
localAS: 11111,
peerAS: 22222,
multiHopPtr: boolPtr(false),
expectMH: false,
},
{
name: "explicit enable",
localAS: 11111,
peerAS: 22222,
multiHopPtr: boolPtr(true),
expectMH: true,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
ctrl := &Controller{
localAS: tc.localAS,
localIP: net.ParseIP("192.168.1.100"),
s: gobgp.NewBgpServer(),
}
go ctrl.s.Serve()
if err := ctrl.s.StartBgp(context.Background(), &api.StartBgpRequest{
Global: &api.Global{
As: uint32(tc.localAS),
RouterId: ctrl.localIP.String(),
ListenPort: -1,
},
}); err != nil {
a.FailNow(err.Error())
}
defer ctrl.s.StopBgp(context.Background(), &api.StopBgpRequest{})
peer := &config.PeerConfig{
PeerIP: "10.10.10.1",
PeerAS: tc.peerAS,
MultiHop: tc.multiHopPtr,
}
err := ctrl.addPeer(peer)
a.NoError(err)
// Verify multihop setting by checking peer config
var foundPeer *api.Peer
ctrl.s.ListPeer(context.Background(), &api.ListPeerRequest{}, func(p *api.Peer) {
if p.Conf.NeighborAddress == peer.PeerIP {
foundPeer = p
}
})
a.NotNil(foundPeer, "Peer should be added")
if tc.expectMH {
a.NotNil(foundPeer.EbgpMultihop, "Should have multihop configured")
a.True(foundPeer.EbgpMultihop.Enabled, "Multihop should be enabled")
} else {
if foundPeer.EbgpMultihop != nil {
a.False(foundPeer.EbgpMultihop.Enabled, "Multihop should not be enabled")
}
}
})
}
}
// Helper function to create bool pointer
func boolPtr(b bool) *bool {
return &b
}
func TestMultiPeerAnnouncement(t *testing.T) {
if os.Getenv("CI") != "" {
t.Skip("Skipping testing in CI environment")
}
a := assert.New(t)
// Create two BGP listeners
listener1, err := NewBgpListener(22222)
if err != nil {
panic(err)
}
defer listener1.Shutdown()
listener2, err := NewBgpListener(33333)
if err != nil {
panic(err)
}
defer listener2.Shutdown()
// Create controller with two peers
multiPeerConfig := config.BgpConfig{
LocalAS: 11111,
LocalIP: "192.168.1.100",
Peers: []config.PeerConfig{
{PeerIP: "127.0.0.1", PeerAS: 22222},
{PeerIP: "127.0.0.1", PeerAS: 33333},
},
Communities: []string{"100:100"},
Origin: "igp",
}
ctrl, err := NewController(multiPeerConfig)
if err != nil {
a.FailNow(err.Error())
}
defer ctrl.Shutdown()
// Announce a route
_, ipnet, _ := net.ParseCIDR("20.30.40.0/24")
r := &Route{Net: ipnet}
if err := ctrl.Announce(r); err != nil {
a.FailNow(err.Error())
}
// Verify both listeners received the route
path1 := <-listener1.recvdPaths
a.Equal("20.30.40.0/24", path1)
path2 := <-listener2.recvdPaths
a.Equal("20.30.40.0/24", path2)
}
func TestBestEffortAnnouncement(t *testing.T) {
a := assert.New(t)
// Create controller with two peers
mixedConfig := config.BgpConfig{
LocalAS: 11111,
LocalIP: "192.168.1.100",
Peers: []config.PeerConfig{
{PeerIP: "127.0.0.1", PeerAS: 22222},
{PeerIP: "127.0.0.2", PeerAS: 33333},
},
Origin: "igp",
}
ctrl, err := NewController(mixedConfig)
if err != nil {
a.FailNow(err.Error())
}
defer ctrl.Shutdown()
// Announce a route - both peers will be added successfully
// (they won't have actual BGP sessions established, but peers are added to GoBGP)
_, ipnet, _ := net.ParseCIDR("20.30.40.0/24")
r := &Route{Net: ipnet}
// The announcement should succeed for both peers being added
err = ctrl.Announce(r)
a.NoError(err, "Announcement should succeed for both peers")
// Verify both peers were added
peers, err := ctrl.PeerInfo()
a.NoError(err)
a.Equal(2, len(peers), "Should have both peers configured")
}
func TestWithdrawMultiplePeers(t *testing.T) {
a := assert.New(t)
ctrl := &Controller{
localAS: 11111,
localIP: net.ParseIP("192.168.1.100"),
peers: []config.PeerConfig{
{PeerIP: "10.10.10.1", PeerAS: 22222},
{PeerIP: "10.10.10.2", PeerAS: 22222},
},
origin: 0,
s: gobgp.NewBgpServer(),
}
go ctrl.s.Serve()
if err := ctrl.s.StartBgp(context.Background(), &api.StartBgpRequest{
Global: &api.Global{
As: uint32(11111),
RouterId: ctrl.localIP.String(),
ListenPort: -1,
},
}); err != nil {
a.FailNow(err.Error())
}
defer ctrl.s.StopBgp(context.Background(), &api.StopBgpRequest{})
_, ipnet, _ := net.ParseCIDR("20.30.40.0/24")
r := &Route{Net: ipnet}
// Withdraw should iterate through all peers
// This will fail because peers aren't established, but it should try both
err := ctrl.Withdraw(r)
// We expect an error but it should have tried both peers
if err != nil {
a.Contains(err.Error(), "withdrawal errors")
}
}
func TestPeerInfoMultiplePeers(t *testing.T) {
a := assert.New(t)
ctrl := &Controller{
localAS: 11111,
localIP: net.ParseIP("192.168.1.100"),
peers: []config.PeerConfig{
{PeerIP: "10.10.10.1", PeerAS: 22222},
{PeerIP: "10.10.10.2", PeerAS: 33333},
},
origin: 0,
s: gobgp.NewBgpServer(),
}
go ctrl.s.Serve()
if err := ctrl.s.StartBgp(context.Background(), &api.StartBgpRequest{
Global: &api.Global{
As: uint32(11111),
RouterId: ctrl.localIP.String(),
ListenPort: -1,
},
}); err != nil {
a.FailNow(err.Error())
}
defer ctrl.s.StopBgp(context.Background(), &api.StopBgpRequest{})
// Add peers
for i := range ctrl.peers {
ctrl.addPeer(&ctrl.peers[i])
}
// Get peer info
peers, err := ctrl.PeerInfo()
a.NoError(err)
a.Equal(2, len(peers), "Should return info for both peers")
// Verify peer addresses
peerAddrs := make(map[string]bool)
for _, p := range peers {
peerAddrs[p.Conf.NeighborAddress] = true
}
a.True(peerAddrs["10.10.10.1"], "Should have first peer")
a.True(peerAddrs["10.10.10.2"], "Should have second peer")
}
func TestMD5Authentication(t *testing.T) {
a := assert.New(t)
testCases := []struct {
name string
md5Password string
md5EnvVar string
envValue string
expectedAuth string
}{
{
name: "MD5 password from config",
md5Password: "secret123",
md5EnvVar: "",
envValue: "",
expectedAuth: "secret123",
},
{
name: "MD5 password from environment variable",
md5Password: "",
md5EnvVar: "BGP_PEER_PASSWORD",
envValue: "env_secret456",
expectedAuth: "env_secret456",
},
{
name: "Environment variable takes priority over config",
md5Password: "config_password",
md5EnvVar: "BGP_PEER_PASSWORD",
envValue: "env_password",
expectedAuth: "env_password",
},
{
name: "No authentication when neither is set",
md5Password: "",
md5EnvVar: "",
envValue: "",
expectedAuth: "",
},
{
name: "Config password used when env var is set but empty",
md5Password: "fallback_password",
md5EnvVar: "EMPTY_VAR",
envValue: "",
expectedAuth: "fallback_password",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// Set environment variable if specified
if tc.md5EnvVar != "" && tc.envValue != "" {
os.Setenv(tc.md5EnvVar, tc.envValue)
defer os.Unsetenv(tc.md5EnvVar)
}
ctrl := &Controller{
localAS: 11111,
localIP: net.ParseIP("192.168.1.100"),
s: gobgp.NewBgpServer(),
}
go ctrl.s.Serve()
if err := ctrl.s.StartBgp(context.Background(), &api.StartBgpRequest{
Global: &api.Global{
As: uint32(11111),
RouterId: ctrl.localIP.String(),
ListenPort: -1,
},
}); err != nil {
a.FailNow(err.Error())
}
defer ctrl.s.StopBgp(context.Background(), &api.StopBgpRequest{})
peer := &config.PeerConfig{
PeerIP: "10.10.10.1",
PeerAS: 22222,
MD5Password: tc.md5Password,
MD5EnvVar: tc.md5EnvVar,
}
err := ctrl.addPeer(peer)
a.NoError(err)
// Verify MD5 authentication is configured correctly
var foundPeer *api.Peer
ctrl.s.ListPeer(context.Background(), &api.ListPeerRequest{}, func(p *api.Peer) {
if p.Conf.NeighborAddress == peer.PeerIP {
foundPeer = p
}
})
a.NotNil(foundPeer, "Peer should be added")
a.Equal(tc.expectedAuth, foundPeer.Conf.AuthPassword, "MD5 password should match expected")
})
}
}
func TestGetMD5Password(t *testing.T) {
a := assert.New(t)
ctrl := &Controller{}
// Test 1: Environment variable takes priority
os.Setenv("TEST_BGP_PASS", "env_password")
defer os.Unsetenv("TEST_BGP_PASS")
peer := &config.PeerConfig{
MD5Password: "config_password",
MD5EnvVar: "TEST_BGP_PASS",
}
a.Equal("env_password", ctrl.getMD5Password(peer))
// Test 2: Config password when env var not set
peer2 := &config.PeerConfig{
MD5Password: "config_only",
MD5EnvVar: "NONEXISTENT_VAR",
}
a.Equal("config_only", ctrl.getMD5Password(peer2))
// Test 3: Empty string when nothing is set
peer3 := &config.PeerConfig{}
a.Equal("", ctrl.getMD5Password(peer3))
// Test 4: Only env var specified
os.Setenv("ANOTHER_PASS", "another_env_password")
defer os.Unsetenv("ANOTHER_PASS")
peer4 := &config.PeerConfig{
MD5EnvVar: "ANOTHER_PASS",
}
a.Equal("another_env_password", ctrl.getMD5Password(peer4))
}
func TestMultiPeerWithMD5(t *testing.T) {
a := assert.New(t)
// Set environment variables for testing
os.Setenv("PEER1_PASSWORD", "peer1_secret")
os.Setenv("PEER2_PASSWORD", "peer2_secret")
defer os.Unsetenv("PEER1_PASSWORD")
defer os.Unsetenv("PEER2_PASSWORD")
// Create controller with multiple peers using different MD5 configurations
multiPeerConfig := config.BgpConfig{
LocalAS: 11111,
LocalIP: "192.168.1.100",
Peers: []config.PeerConfig{
{
PeerIP: "10.10.10.1",
PeerAS: 22222,
MD5EnvVar: "PEER1_PASSWORD",
},
{
PeerIP: "10.10.10.2",
PeerAS: 33333,
MD5Password: "peer2_config_password",
},
{
PeerIP: "10.10.10.3",
PeerAS: 44444,
// No MD5 authentication
},
},
Origin: "igp",
}
ctrl, err := NewController(multiPeerConfig)
if err != nil {
a.FailNow(err.Error())
}
defer ctrl.Shutdown()
// Trigger peer addition by announcing a route (peers are added lazily)
_, ipnet, _ := net.ParseCIDR("20.30.40.0/24")
r := &Route{Net: ipnet}
ctrl.Announce(r)
// Verify all peers have correct MD5 configuration
peers := make(map[string]string) // map[peerIP]authPassword
ctrl.s.ListPeer(context.Background(), &api.ListPeerRequest{}, func(p *api.Peer) {
peers[p.Conf.NeighborAddress] = p.Conf.AuthPassword
})
a.Equal(3, len(peers), "Should have all three peers")
a.Equal("peer1_secret", peers["10.10.10.1"], "First peer should use env var password")
a.Equal("peer2_config_password", peers["10.10.10.2"], "Second peer should use config password")
a.Equal("", peers["10.10.10.3"], "Third peer should have no authentication")
}

View File

@@ -15,6 +15,7 @@ import (
const ( const (
consulNodeEnv = "CONSUL_NODE" consulNodeEnv = "CONSUL_NODE"
consulToken = "CONSUL_TOKEN"
allowStale = "CONSUL_STALE" allowStale = "CONSUL_STALE"
matchTag = "enable_gocast" matchTag = "enable_gocast"
nodeURL = "/catalog/node" nodeURL = "/catalog/node"
@@ -23,7 +24,7 @@ const (
) )
type Clienter interface { type Clienter interface {
Get(url string) (*http.Response, error) Do(req *http.Request) (*http.Response, error)
} }
type Client struct { type Client struct {
@@ -32,6 +33,7 @@ type Client struct {
type ConsulMon struct { type ConsulMon struct {
addr string addr string
token string
node string node string
client Clienter client Clienter
} }
@@ -53,12 +55,26 @@ func contains(inp []string, elem string) bool {
return false return false
} }
func NewConsulMon(addr string) (*ConsulMon, error) { func NewConsulMon(addr string, token string) (*ConsulMon, error) {
node := os.Getenv(consulNodeEnv) node := os.Getenv(consulNodeEnv)
if node == "" { if node == "" {
return nil, fmt.Errorf("%s env variable not set", consulNodeEnv) return nil, fmt.Errorf("%s env variable not set", consulNodeEnv)
} }
return &ConsulMon{addr: addr, node: node, client: &http.Client{Timeout: 10 * time.Second}}, nil return &ConsulMon{addr: addr, token: token, node: node, client: &http.Client{Timeout: 10 * time.Second}}, nil
}
func getHTTPReq(httpMethod string, addr string, tokenFrmCfg string) (*http.Request, error) {
req, err := http.NewRequest(httpMethod, addr, nil)
if err != nil {
return nil, err
}
tokenFrmEnv := os.Getenv(consulToken)
if tokenFrmEnv != "" {
req.Header.Set("X-Consul-Token", tokenFrmEnv)
} else if tokenFrmCfg != "" {
req.Header.Set("X-Consul-Token", tokenFrmCfg)
}
return req, nil
} }
func (c *ConsulMon) queryServices() ([]*App, error) { func (c *ConsulMon) queryServices() ([]*App, error) {
@@ -68,7 +84,11 @@ func (c *ConsulMon) queryServices() ([]*App, error) {
stale = "stale" stale = "stale"
} }
addr := c.addr + fmt.Sprintf("%s/%s?%s", nodeURL, c.node, stale) addr := c.addr + fmt.Sprintf("%s/%s?%s", nodeURL, c.node, stale)
resp, err := c.client.Get(addr) req, err := getHTTPReq(http.MethodGet, addr, c.token)
if err != nil {
return apps, err
}
resp, err := c.client.Do(req)
if err != nil { if err != nil {
return apps, err return apps, err
} }
@@ -125,7 +145,11 @@ func (c *ConsulMon) healthCheckLocal(service string) (bool, error) {
params := url.Values{} params := url.Values{}
params.Add("filter", "enable_gocast in ServiceTags") params.Add("filter", "enable_gocast in ServiceTags")
addr := c.addr + fmt.Sprintf("%s?%s", localHealthCheckurl, params.Encode()) addr := c.addr + fmt.Sprintf("%s?%s", localHealthCheckurl, params.Encode())
resp, err := c.client.Get(addr) req, err := getHTTPReq(http.MethodGet, addr, c.token)
if err != nil {
return false, err
}
resp, err := c.client.Do(req)
if err != nil { if err != nil {
glog.V(2).Infof("Error getting %s with %s", addr, err) glog.V(2).Infof("Error getting %s with %s", addr, err)
return false, err return false, err
@@ -146,14 +170,18 @@ func (c *ConsulMon) healthCheckLocal(service string) (bool, error) {
return false, nil return false, nil
} }
} }
return false, fmt.Errorf("No local healcheck info found for service %s on node %s in consul", service, c.node) return false, fmt.Errorf("No local healthcheck info found for service %s on node %s in consul", service, c.node)
} }
// healthCheckRemote queries the consul cluster's healthcheck endpoint to perform service healthchecks // healthCheckRemote queries the consul cluster's healthcheck endpoint to perform service healthchecks
// This is the underlying api call: https://www.consul.io/api/health.html // This is the underlying api call: https://www.consul.io/api/health.html
func (c *ConsulMon) healthCheckRemote(service string) (bool, error) { func (c *ConsulMon) healthCheckRemote(service string) (bool, error) {
addr := c.addr + fmt.Sprintf("%s/%s", remoteHealthCheckurl, service) addr := c.addr + fmt.Sprintf("%s/%s", remoteHealthCheckurl, service)
resp, err := c.client.Get(addr) req, err := getHTTPReq(http.MethodGet, addr, c.token)
if err != nil {
return false, err
}
resp, err := c.client.Do(req)
if err != nil { if err != nil {
glog.V(2).Infof("Error getting %s with %s", addr, err) glog.V(2).Infof("Error getting %s with %s", addr, err)
return false, err return false, err
@@ -174,7 +202,7 @@ func (c *ConsulMon) healthCheckRemote(service string) (bool, error) {
return false, nil return false, nil
} }
} }
return false, fmt.Errorf("No healcheck info found for node %s in consul", c.node) return false, fmt.Errorf("No healthcheck info found for node %s in consul", c.node)
} }
// healthCheck determines if we should use the local agent // healthCheck determines if we should use the local agent

View File

@@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"os"
"testing" "testing"
"github.com/mayuresh82/gocast/config" "github.com/mayuresh82/gocast/config"
@@ -77,16 +78,43 @@ var mockConsulCheckData = map[string]string{
} }
type MockClient struct { type MockClient struct {
get func(url string) (*http.Response, error) do func(*http.Request) (*http.Response, error)
} }
func (c *MockClient) Get(url string) (*http.Response, error) { func (c *MockClient) Do(*http.Request) (*http.Response, error) {
if c.get != nil { if c.do != nil {
return c.get(url) return c.do(&http.Request{})
} }
return nil, nil return nil, nil
} }
func TestGetNewHTTPReq(t *testing.T) {
a := assert.New(t)
// test with consul token from config file
req, err := getHTTPReq("GET", "1.1.1.1", "3333-3333")
if err != nil {
t.Fatal(err)
}
a.Equal(req.Header.Get("X-Consul-Token"), "3333-3333")
// test with consul token from env variable
os.Setenv("CONSUL_TOKEN", "4444-4444")
req, err = getHTTPReq("GET", "1.1.1.1", "3333-3333")
os.Unsetenv("CONSUL_TOKEN")
if err != nil {
t.Fatal(err)
}
a.Equal(req.Header.Get("X-Consul-Token"), "4444-4444")
// test without consul token
req, err = getHTTPReq("GET", "1.1.1.1", "")
if err != nil {
t.Fatal(err)
}
a.Equal(req.Header.Get("X-Consul-Token"), "")
}
func TestQueryServices(t *testing.T) { func TestQueryServices(t *testing.T) {
a := assert.New(t) a := assert.New(t)
client := &MockClient{} client := &MockClient{}
@@ -95,7 +123,7 @@ func TestQueryServices(t *testing.T) {
} }
// test valid app // test valid app
client.get = func(url string) (*http.Response, error) { client.do = func(*http.Request) (*http.Response, error) {
b := bytes.NewBuffer([]byte(mockConsulData["single-app"])) b := bytes.NewBuffer([]byte(mockConsulData["single-app"]))
return &http.Response{Body: ioutil.NopCloser(b), StatusCode: http.StatusOK}, nil return &http.Response{Body: ioutil.NopCloser(b), StatusCode: http.StatusOK}, nil
} }
@@ -110,7 +138,7 @@ func TestQueryServices(t *testing.T) {
a.True(app.Equal(apps[0])) a.True(app.Equal(apps[0]))
// test no match // test no match
client.get = func(url string) (*http.Response, error) { client.do = func(*http.Request) (*http.Response, error) {
b := bytes.NewBuffer([]byte(mockConsulData["single-app-no-match"])) b := bytes.NewBuffer([]byte(mockConsulData["single-app-no-match"]))
return &http.Response{Body: ioutil.NopCloser(b), StatusCode: http.StatusOK}, nil return &http.Response{Body: ioutil.NopCloser(b), StatusCode: http.StatusOK}, nil
} }
@@ -121,7 +149,7 @@ func TestQueryServices(t *testing.T) {
a.Equal(0, len(apps)) a.Equal(0, len(apps))
// test missing vip // test missing vip
client.get = func(url string) (*http.Response, error) { client.do = func(*http.Request) (*http.Response, error) {
b := bytes.NewBuffer([]byte(mockConsulData["single-app-no-vip"])) b := bytes.NewBuffer([]byte(mockConsulData["single-app-no-vip"]))
return &http.Response{Body: ioutil.NopCloser(b), StatusCode: http.StatusOK}, nil return &http.Response{Body: ioutil.NopCloser(b), StatusCode: http.StatusOK}, nil
} }
@@ -136,7 +164,7 @@ func TestHealthCheck(t *testing.T) {
// test remote checks // test remote checks
cm.addr = "http://remote/check" cm.addr = "http://remote/check"
client.get = func(url string) (*http.Response, error) { client.do = func(*http.Request) (*http.Response, error) {
b := bytes.NewBuffer([]byte(mockConsulCheckData["remote-pass"])) b := bytes.NewBuffer([]byte(mockConsulCheckData["remote-pass"]))
return &http.Response{Body: ioutil.NopCloser(b), StatusCode: http.StatusOK}, nil return &http.Response{Body: ioutil.NopCloser(b), StatusCode: http.StatusOK}, nil
} }
@@ -145,7 +173,7 @@ func TestHealthCheck(t *testing.T) {
a.FailNow(err.Error()) a.FailNow(err.Error())
} }
a.True(check) a.True(check)
client.get = func(url string) (*http.Response, error) { client.do = func(*http.Request) (*http.Response, error) {
b := bytes.NewBuffer([]byte(mockConsulCheckData["remote-fail"])) b := bytes.NewBuffer([]byte(mockConsulCheckData["remote-fail"]))
return &http.Response{Body: ioutil.NopCloser(b), StatusCode: http.StatusOK}, nil return &http.Response{Body: ioutil.NopCloser(b), StatusCode: http.StatusOK}, nil
} }
@@ -154,7 +182,7 @@ func TestHealthCheck(t *testing.T) {
// test local checks // test local checks
cm.addr = "http://localhost/check" cm.addr = "http://localhost/check"
client.get = func(url string) (*http.Response, error) { client.do = func(*http.Request) (*http.Response, error) {
b := bytes.NewBuffer([]byte(mockConsulCheckData["local-pass"])) b := bytes.NewBuffer([]byte(mockConsulCheckData["local-pass"]))
return &http.Response{Body: ioutil.NopCloser(b), StatusCode: http.StatusOK}, nil return &http.Response{Body: ioutil.NopCloser(b), StatusCode: http.StatusOK}, nil
} }
@@ -164,7 +192,7 @@ func TestHealthCheck(t *testing.T) {
} }
a.True(check) a.True(check)
cm.addr = "http://127.0.0.1/check" cm.addr = "http://127.0.0.1/check"
client.get = func(url string) (*http.Response, error) { client.do = func(*http.Request) (*http.Response, error) {
b := bytes.NewBuffer([]byte(mockConsulCheckData["local-fail"])) b := bytes.NewBuffer([]byte(mockConsulCheckData["local-fail"]))
return &http.Response{Body: ioutil.NopCloser(b), StatusCode: http.StatusOK}, nil return &http.Response{Body: ioutil.NopCloser(b), StatusCode: http.StatusOK}, nil
} }

View File

@@ -58,7 +58,7 @@ type appMon struct {
app *App app *App
done chan bool done chan bool
announced bool announced bool
checkOn bool runLoopOn bool
} }
// MonitorMgr manages the lifecycle of registered apps // MonitorMgr manages the lifecycle of registered apps
@@ -84,7 +84,7 @@ func NewMonitor(config *c.Config) *MonitorMgr {
cleanups: make(map[string]chan bool), cleanups: make(map[string]chan bool),
} }
if config.Agent.ConsulAddr != "" { if config.Agent.ConsulAddr != "" {
cmon, err := NewConsulMon(config.Agent.ConsulAddr) cmon, err := NewConsulMon(config.Agent.ConsulAddr, config.Agent.ConsulToken)
if err != nil { if err != nil {
glog.Errorf("Failed to start consul monitor: %v", err) glog.Errorf("Failed to start consul monitor: %v", err)
} else { } else {
@@ -154,11 +154,12 @@ func (m *MonitorMgr) consulMon() {
func (m *MonitorMgr) Add(app *App) { func (m *MonitorMgr) Add(app *App) {
// check if already running // check if already running
m.monMu.Lock() m.monMu.Lock()
var existing *appMon
for _, appMon := range m.monitors { for _, appMon := range m.monitors {
if appMon.app.Equal(app) && appMon.checkOn { if appMon.app.Equal(app) {
glog.V(2).Infof("App %s already exists", app.Name) glog.Infof("App %s already exists", app.Name)
m.monMu.Unlock() existing = appMon
return break
} }
if appMon.app.Vip.Net.String() == app.Vip.Net.String() && appMon.app.Name != app.Name { if appMon.app.Vip.Net.String() == app.Vip.Net.String() && appMon.app.Name != app.Name {
glog.Errorf("Error: Vip %s is already being announced by app: %s", app.Vip.Net.String(), appMon.app.Name) glog.Errorf("Error: Vip %s is already being announced by app: %s", app.Vip.Net.String(), appMon.app.Name)
@@ -167,11 +168,19 @@ func (m *MonitorMgr) Add(app *App) {
} }
} }
m.monMu.Unlock() m.monMu.Unlock()
m.Remove(app.Name) // if the same app already exists but its run loop is not running,
// then just restart the run loop
if existing != nil {
if !existing.runLoopOn {
go m.runLoop(existing)
}
} else {
// else add a new app and start its run loop
appMon := &appMon{app: app, done: make(chan bool)} appMon := &appMon{app: app, done: make(chan bool)}
m.monitors[app.Name] = appMon m.monitors[app.Name] = appMon
go m.runLoop(appMon) go m.runLoop(appMon)
glog.Infof("Registered a new app: %v", app.String()) glog.Infof("Registered a new app: %v", app.String())
}
} }
// Remove removes an app from monitor manager, stops BGP // Remove removes an app from monitor manager, stops BGP
@@ -180,8 +189,8 @@ func (m *MonitorMgr) Remove(appName string) {
m.monMu.Lock() m.monMu.Lock()
defer m.monMu.Unlock() defer m.monMu.Unlock()
if a, ok := m.monitors[appName]; ok { if a, ok := m.monitors[appName]; ok {
if a.checkOn { if a.runLoopOn {
a.done <- true close(a.done)
} }
if a.announced { if a.announced {
if err := m.ctrl.Withdraw(a.app.Vip); err != nil { if err := m.ctrl.Withdraw(a.app.Vip); err != nil {
@@ -193,16 +202,23 @@ func (m *MonitorMgr) Remove(appName string) {
} }
for _, nat := range a.app.Nats { for _, nat := range a.app.Nats {
parts := strings.Split(nat, ":") parts := strings.Split(nat, ":")
if len(parts) != 2 { switch len(parts) {
continue case 3:
} if err := natRule("D", a.app.Vip.Net.IP, m.ctrl.localIP, parts[0], parts[1], parts[2]); err != nil {
if err := natRule("D", a.app.Vip.Net.IP, m.ctrl.localIP, parts[0], parts[1]); err != nil {
glog.Errorf("Failed to remove app: %s: %v", a.app.Name, err) glog.Errorf("Failed to remove app: %s: %v", a.app.Name, err)
} }
case 2:
if err := natRule("D", a.app.Vip.Net.IP, m.ctrl.localIP, parts[0], parts[1], parts[1]); err != nil {
glog.Errorf("Failed to remove app: %s: %v", a.app.Name, err)
}
default:
continue
}
} }
} }
delete(m.monitors, appName) delete(m.monitors, appName)
} }
func (m *MonitorMgr) runMonitors(app *App) bool { func (m *MonitorMgr) runMonitors(app *App) bool {
for _, mon := range app.Monitors { for _, mon := range app.Monitors {
var check bool var check bool
@@ -238,19 +254,25 @@ func (m *MonitorMgr) checkCond(am *appMon) error {
} }
for _, nat := range app.Nats { for _, nat := range app.Nats {
parts := strings.Split(nat, ":") parts := strings.Split(nat, ":")
if len(parts) != 2 { switch len(parts) {
continue case 3:
} if err := natRule("A", app.Vip.Net.IP, m.ctrl.localIP, parts[0], parts[1], parts[2]); err != nil {
if err := natRule("A", app.Vip.Net.IP, m.ctrl.localIP, parts[0], parts[1]); err != nil {
return err return err
} }
case 2:
if err := natRule("A", app.Vip.Net.IP, m.ctrl.localIP, parts[0], parts[1], parts[1]); err != nil {
return err
}
default:
continue
}
} }
if err := m.ctrl.Announce(app.Vip); err != nil { if err := m.ctrl.Announce(app.Vip); err != nil {
return fmt.Errorf("Failed to announce route: %v", err) return fmt.Errorf("Failed to announce route: %v", err)
} }
am.announced = true am.announced = true
if exit, ok := m.cleanups[app.Name]; ok { if exit, ok := m.cleanups[app.Name]; ok {
exit <- true close(exit)
delete(m.cleanups, app.Name) delete(m.cleanups, app.Name)
} }
} }
@@ -271,7 +293,8 @@ func (m *MonitorMgr) checkCond(am *appMon) error {
// runLoop periodically checks if an app passes healthchecks // runLoop periodically checks if an app passes healthchecks
// and needs VIP announcement // and needs VIP announcement
func (m *MonitorMgr) runLoop(am *appMon) { func (m *MonitorMgr) runLoop(am *appMon) {
am.checkOn = true glog.Infof("Starting run-loop for app %s", am.app.Name)
am.runLoopOn = true
if err := m.checkCond(am); err != nil { if err := m.checkCond(am); err != nil {
glog.Errorln(err) glog.Errorln(err)
} }
@@ -284,7 +307,8 @@ func (m *MonitorMgr) runLoop(am *appMon) {
glog.Errorln(err) glog.Errorln(err)
} }
case <-am.done: case <-am.done:
glog.V(2).Infof("Exit run-loop for app: %s", am.app.Name) glog.Infof("Exit run-loop for app: %s", am.app.Name)
am.runLoopOn = false
return return
} }
} }
@@ -297,20 +321,249 @@ func (m *MonitorMgr) CloseAll() {
glog.Errorf("Failed to shut-down BGP: %v", err) glog.Errorf("Failed to shut-down BGP: %v", err)
} }
for _, am := range m.monitors { for _, am := range m.monitors {
if am.checkOn { if am.runLoopOn {
am.done <- true close(am.done)
} }
deleteLoopback(am.app.Vip.Net) deleteLoopback(am.app.Vip.Net)
for _, nat := range am.app.Nats { for _, nat := range am.app.Nats {
parts := strings.Split(nat, ":") parts := strings.Split(nat, ":")
if len(parts) != 2 { switch len(parts) {
case 3:
natRule("D", am.app.Vip.Net.IP, m.ctrl.localIP, parts[0], parts[1], parts[2])
case 2:
natRule("D", am.app.Vip.Net.IP, m.ctrl.localIP, parts[0], parts[1], parts[1])
default:
continue continue
} }
natRule("D", am.app.Vip.Net.IP, m.ctrl.localIP, parts[0], parts[1])
} }
} }
} }
// Reload re-reads the configuration file and applies changes
func (m *MonitorMgr) Reload(configPath string) error {
glog.Infof("Reloading configuration from %s", configPath)
// Read new configuration
newConfig := c.GetConfig(configPath)
if newConfig == nil {
return fmt.Errorf("Failed to load configuration")
}
// Set defaults if not specified
if newConfig.Agent.MonitorInterval == 0 {
newConfig.Agent.MonitorInterval = defaultMonitorInterval
}
if newConfig.Agent.CleanupTimer == 0 {
newConfig.Agent.CleanupTimer = defaultCleanupTimer
}
// Check if BGP configuration has changed
bgpChanged := m.bgpConfigChanged(m.config.Bgp, newConfig.Bgp)
if bgpChanged {
glog.Infof("BGP configuration changed, restarting BGP controller")
// Withdraw all current routes before shutting down
m.monMu.Lock()
for _, am := range m.monitors {
if am.announced {
if err := m.ctrl.Withdraw(am.app.Vip); err != nil {
glog.Errorf("Failed to withdraw route during reload: %v", err)
}
am.announced = false
}
}
m.monMu.Unlock()
// Shutdown old BGP controller
if err := m.ctrl.Shutdown(); err != nil {
glog.Errorf("Failed to shutdown BGP controller: %v", err)
}
// Start new BGP controller
ctrl, err := NewController(newConfig.Bgp)
if err != nil {
return fmt.Errorf("Failed to start new BGP controller: %v", err)
}
m.ctrl = ctrl
// Re-announce all routes with new BGP config
m.monMu.Lock()
for _, am := range m.monitors {
// Only re-announce if the app was previously announced and is still healthy
if m.runMonitors(am.app) {
if err := m.ctrl.Announce(am.app.Vip); err != nil {
glog.Errorf("Failed to re-announce route %s: %v", am.app.Vip.Net.String(), err)
} else {
am.announced = true
glog.Infof("Re-announced route %s", am.app.Vip.Net.String())
}
}
}
m.monMu.Unlock()
}
// Handle consul configuration changes
if m.config.Agent.ConsulAddr != newConfig.Agent.ConsulAddr ||
m.config.Agent.ConsulToken != newConfig.Agent.ConsulToken {
glog.Infof("Consul configuration changed")
if newConfig.Agent.ConsulAddr != "" {
cmon, err := NewConsulMon(newConfig.Agent.ConsulAddr, newConfig.Agent.ConsulToken)
if err != nil {
glog.Errorf("Failed to start consul monitor: %v", err)
} else {
m.consul = cmon
// Start consul monitoring in background if not already running
if m.config.Agent.ConsulAddr == "" {
go m.consulMon()
}
}
}
}
// Update agent configuration
oldConfig := m.config
m.config = newConfig
// Handle app configuration changes
m.reloadApps(oldConfig.Apps, newConfig.Apps)
glog.Infof("Configuration reloaded successfully")
return nil
}
// bgpConfigChanged checks if BGP configuration has changed
func (m *MonitorMgr) bgpConfigChanged(old, new c.BgpConfig) bool {
// Check basic parameters
if old.LocalAS != new.LocalAS || old.LocalIP != new.LocalIP || old.Origin != new.Origin {
return true
}
// Check legacy peer config
if old.PeerAS != new.PeerAS || old.PeerIP != new.PeerIP {
return true
}
// Check peers
if len(old.Peers) != len(new.Peers) {
return true
}
// Compare each peer
for i := range old.Peers {
if old.Peers[i].PeerIP != new.Peers[i].PeerIP ||
old.Peers[i].PeerAS != new.Peers[i].PeerAS ||
old.Peers[i].MD5Password != new.Peers[i].MD5Password ||
old.Peers[i].MD5EnvVar != new.Peers[i].MD5EnvVar {
return true
}
// Check multi-hop
if (old.Peers[i].MultiHop == nil) != (new.Peers[i].MultiHop == nil) {
return true
}
if old.Peers[i].MultiHop != nil && new.Peers[i].MultiHop != nil {
if *old.Peers[i].MultiHop != *new.Peers[i].MultiHop {
return true
}
}
// Check communities
if len(old.Peers[i].Communities) != len(new.Peers[i].Communities) {
return true
}
for j := range old.Peers[i].Communities {
if old.Peers[i].Communities[j] != new.Peers[i].Communities[j] {
return true
}
}
}
// Check global communities
if len(old.Communities) != len(new.Communities) {
return true
}
for i := range old.Communities {
if old.Communities[i] != new.Communities[i] {
return true
}
}
return false
}
// reloadApps compares old and new app configurations and applies changes
func (m *MonitorMgr) reloadApps(oldApps, newApps []c.AppConfig) {
// Build maps for easy comparison
oldAppMap := make(map[string]c.AppConfig)
for _, app := range oldApps {
oldAppMap[app.Name] = app
}
newAppMap := make(map[string]c.AppConfig)
for _, app := range newApps {
newAppMap[app.Name] = app
}
// Remove apps that are no longer in config
for name := range oldAppMap {
if _, exists := newAppMap[name]; !exists {
m.monMu.Lock()
if am, ok := m.monitors[name]; ok {
if am.app.Source == "config" {
glog.Infof("Removing app %s (no longer in config)", name)
m.monMu.Unlock()
m.Remove(name)
continue
}
}
m.monMu.Unlock()
}
}
// Add new apps or update existing ones
for name, newAppConfig := range newAppMap {
oldAppConfig, existed := oldAppMap[name]
// Check if app configuration changed
configChanged := !existed ||
oldAppConfig.Vip != newAppConfig.Vip ||
!equalStringSlices(oldAppConfig.Monitors, newAppConfig.Monitors) ||
!equalStringSlices(oldAppConfig.Nats, newAppConfig.Nats) ||
!equalStringSlices(oldAppConfig.VipConfig.BgpCommunities, newAppConfig.VipConfig.BgpCommunities)
if configChanged {
if existed {
glog.Infof("App %s configuration changed, reloading", name)
m.Remove(name)
} else {
glog.Infof("Adding new app %s from config", name)
}
app, err := NewApp(newAppConfig.Name, newAppConfig.Vip, newAppConfig.VipConfig,
newAppConfig.Monitors, newAppConfig.Nats, "config")
if err != nil {
glog.Errorf("Failed to add app %s: %v", name, err)
continue
}
m.Add(app)
}
}
}
// equalStringSlices compares two string slices
func equalStringSlices(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
// CleanUp periodically monitors for stale apps and cleans them up // CleanUp periodically monitors for stale apps and cleans them up
func (m *MonitorMgr) Cleanup(app string, exit chan bool) { func (m *MonitorMgr) Cleanup(app string, exit chan bool) {
t := time.NewTimer(m.config.Agent.CleanupTimer) t := time.NewTimer(m.config.Agent.CleanupTimer)
@@ -320,6 +573,7 @@ func (m *MonitorMgr) Cleanup(app string, exit chan bool) {
case <-t.C: case <-t.C:
glog.Infof("Cleaning up app %s", app) glog.Infof("Cleaning up app %s", app)
m.Remove(app) m.Remove(app)
return
case <-exit: case <-exit:
return return
} }
@@ -327,6 +581,6 @@ func (m *MonitorMgr) Cleanup(app string, exit chan bool) {
} }
// GetInfo returns basic BGP info for established peers // GetInfo returns basic BGP info for established peers
func (m *MonitorMgr) GetInfo() (*api.Peer, error) { func (m *MonitorMgr) GetInfo() ([]*api.Peer, error) {
return m.ctrl.PeerInfo() return m.ctrl.PeerInfo()
} }

293
controller/reload_test.go Normal file
View File

@@ -0,0 +1,293 @@
package controller
import (
"io/ioutil"
"os"
"testing"
"time"
config "github.com/mayuresh82/gocast/config"
"github.com/stretchr/testify/assert"
)
func TestBgpConfigChanged(t *testing.T) {
a := assert.New(t)
mon := &MonitorMgr{}
// Test 1: No changes
cfg1 := config.BgpConfig{
LocalAS: 12345,
LocalIP: "192.168.1.100",
Origin: "igp",
Peers: []config.PeerConfig{
{PeerIP: "10.10.10.1", PeerAS: 6789},
},
Communities: []string{"100:100"},
}
cfg2 := cfg1
a.False(mon.bgpConfigChanged(cfg1, cfg2), "Identical configs should not be considered changed")
// Test 2: LocalAS changed
cfg3 := cfg1
cfg3.LocalAS = 54321
a.True(mon.bgpConfigChanged(cfg1, cfg3), "LocalAS change should be detected")
// Test 3: Peer IP changed
cfg4 := cfg1
cfg4.Peers = []config.PeerConfig{
{PeerIP: "10.10.10.2", PeerAS: 6789},
}
a.True(mon.bgpConfigChanged(cfg1, cfg4), "Peer IP change should be detected")
// Test 4: MD5 password changed
cfg5 := cfg1
cfg5.Peers = []config.PeerConfig{
{PeerIP: "10.10.10.1", PeerAS: 6789, MD5Password: "secret"},
}
a.True(mon.bgpConfigChanged(cfg1, cfg5), "MD5 password change should be detected")
// Test 5: Community added
cfg6 := cfg1
cfg6.Communities = []string{"100:100", "200:200"}
a.True(mon.bgpConfigChanged(cfg1, cfg6), "Community addition should be detected")
// Test 6: Peer added
cfg7 := cfg1
cfg7.Peers = []config.PeerConfig{
{PeerIP: "10.10.10.1", PeerAS: 6789},
{PeerIP: "10.10.10.2", PeerAS: 6789},
}
a.True(mon.bgpConfigChanged(cfg1, cfg7), "Peer addition should be detected")
// Test 7: MultiHop changed
multiHopTrue := true
cfg8 := cfg1
cfg8.Peers = []config.PeerConfig{
{PeerIP: "10.10.10.1", PeerAS: 6789, MultiHop: &multiHopTrue},
}
a.True(mon.bgpConfigChanged(cfg1, cfg8), "MultiHop change should be detected")
}
func TestEqualStringSlices(t *testing.T) {
a := assert.New(t)
a.True(equalStringSlices([]string{}, []string{}), "Empty slices should be equal")
a.True(equalStringSlices([]string{"a", "b"}, []string{"a", "b"}), "Identical slices should be equal")
a.False(equalStringSlices([]string{"a"}, []string{"a", "b"}), "Different length slices should not be equal")
a.False(equalStringSlices([]string{"a", "b"}, []string{"a", "c"}), "Different content should not be equal")
}
func TestReload(t *testing.T) {
if os.Getenv("CI") != "" {
t.Skip("Skipping reload test in CI environment")
}
a := assert.New(t)
// Create initial config file
initialConfig := `
agent:
listen_addr: :8080
monitor_interval: 10s
cleanup_timer: 15m
bgp:
local_as: 12345
peer_as: 6789
local_ip: 192.168.1.100
origin: igp
communities:
- 100:100
apps:
- name: test-app
vip: 1.1.1.1/32
monitors:
- exec:echo
`
// Create temporary config file
tmpfile, err := ioutil.TempFile("", "gocast-test-*.yaml")
a.NoError(err)
defer os.Remove(tmpfile.Name())
_, err = tmpfile.Write([]byte(initialConfig))
a.NoError(err)
tmpfile.Close()
// Initialize monitor with initial config
conf := config.GetConfig(tmpfile.Name())
mon := NewMonitor(conf)
defer mon.CloseAll()
// Wait a bit for initialization
time.Sleep(100 * time.Millisecond)
// Verify initial state
a.Equal(12345, mon.ctrl.localAS)
m := mon.monitors["test-app"]
a.NotNil(m, "Initial app should be loaded")
// Update config file with new BGP AS and remove app
updatedConfig := `
agent:
listen_addr: :8080
monitor_interval: 10s
cleanup_timer: 15m
bgp:
local_as: 54321
peer_as: 6789
local_ip: 192.168.1.100
origin: igp
communities:
- 200:200
`
err = ioutil.WriteFile(tmpfile.Name(), []byte(updatedConfig), 0644)
a.NoError(err)
// Reload configuration
err = mon.Reload(tmpfile.Name())
a.NoError(err)
// Wait for reload to complete
time.Sleep(200 * time.Millisecond)
// Verify new state
a.Equal(54321, mon.ctrl.localAS)
a.Equal([]string{"200:200"}, mon.ctrl.communities)
// Verify app was removed
mon.monMu.Lock()
_, exists := mon.monitors["test-app"]
mon.monMu.Unlock()
a.False(exists, "App should be removed after reload")
}
func TestReloadAddApp(t *testing.T) {
if os.Getenv("CI") != "" {
t.Skip("Skipping reload test in CI environment")
}
a := assert.New(t)
// Create initial config without apps
initialConfig := `
agent:
listen_addr: :8080
monitor_interval: 10s
bgp:
local_as: 12345
peer_as: 6789
local_ip: 192.168.1.100
origin: igp
`
tmpfile, err := ioutil.TempFile("", "gocast-test-*.yaml")
a.NoError(err)
defer os.Remove(tmpfile.Name())
_, err = tmpfile.Write([]byte(initialConfig))
a.NoError(err)
tmpfile.Close()
conf := config.GetConfig(tmpfile.Name())
mon := NewMonitor(conf)
defer mon.CloseAll()
time.Sleep(100 * time.Millisecond)
// Verify no apps initially
mon.monMu.Lock()
initialCount := len(mon.monitors)
mon.monMu.Unlock()
a.Equal(0, initialCount)
// Add app to config
updatedConfig := `
agent:
listen_addr: :8080
monitor_interval: 10s
bgp:
local_as: 12345
peer_as: 6789
local_ip: 192.168.1.100
origin: igp
apps:
- name: new-app
vip: 2.2.2.2/32
monitors:
- exec:echo
`
err = ioutil.WriteFile(tmpfile.Name(), []byte(updatedConfig), 0644)
a.NoError(err)
// Reload
err = mon.Reload(tmpfile.Name())
a.NoError(err)
time.Sleep(200 * time.Millisecond)
// Verify app was added
mon.monMu.Lock()
_, exists := mon.monitors["new-app"]
mon.monMu.Unlock()
a.True(exists, "New app should be added after reload")
}
func TestReloadMD5Change(t *testing.T) {
if os.Getenv("CI") != "" {
t.Skip("Skipping reload test in CI environment")
}
a := assert.New(t)
// Set environment variable for MD5 password
os.Setenv("BGP_TEST_PASSWORD", "initial_secret")
defer os.Unsetenv("BGP_TEST_PASSWORD")
initialConfig := `
agent:
listen_addr: :8080
bgp:
local_as: 12345
local_ip: 192.168.1.100
peers:
- peer_ip: 10.10.10.1
peer_as: 6789
md5_env_var: BGP_TEST_PASSWORD
origin: igp
`
tmpfile, err := ioutil.TempFile("", "gocast-test-*.yaml")
a.NoError(err)
defer os.Remove(tmpfile.Name())
_, err = tmpfile.Write([]byte(initialConfig))
a.NoError(err)
tmpfile.Close()
conf := config.GetConfig(tmpfile.Name())
mon := NewMonitor(conf)
defer mon.CloseAll()
time.Sleep(100 * time.Millisecond)
// Update environment variable
os.Setenv("BGP_TEST_PASSWORD", "updated_secret")
// Reload (MD5 env var change should trigger BGP reload)
err = mon.Reload(tmpfile.Name())
a.NoError(err)
// Note: We can't easily verify the MD5 password changed without
// actually establishing BGP sessions, but we can verify reload succeeded
a.NotNil(mon.ctrl)
}

View File

@@ -23,7 +23,7 @@ func gateway() (net.IP, error) {
cmdList := getCmdList(cmd) cmdList := getCmdList(cmd)
out, err := exec.Command(execCmd, cmdList...).Output() out, err := exec.Command(execCmd, cmdList...).Output()
if err != nil { if err != nil {
return nil, fmt.Errorf("Failed to execute command: %s", cmd) return nil, fmt.Errorf("Failed to execute command: %s: %v", cmd, err)
} }
return net.ParseIP(strings.TrimSpace(string(out))), nil return net.ParseIP(strings.TrimSpace(string(out))), nil
} }
@@ -33,7 +33,7 @@ func via(dest net.IP) (net.IP, error) {
cmdList := getCmdList(cmd) cmdList := getCmdList(cmd)
out, err := exec.Command(execCmd, cmdList...).Output() out, err := exec.Command(execCmd, cmdList...).Output()
if err != nil { if err != nil {
return nil, fmt.Errorf("Failed to execute command: %s", cmd) return nil, fmt.Errorf("Failed to execute command: %s: %v", cmd, err)
} }
if string(out) == "" { if string(out) == "" {
// assume the provided dest is the next hop // assume the provided dest is the next hop
@@ -86,10 +86,10 @@ func deleteLoopback(addr *net.IPNet) error {
return nil return nil
} }
func natRule(op string, vip, localAddr net.IP, protocol, port string) error { func natRule(op string, vip, localAddr net.IP, protocol, lport, dport string) error {
cmd := fmt.Sprintf( cmd := fmt.Sprintf(
"iptables -t nat -%s PREROUTING -p %s -d %s --dport %s -j DNAT --to-destination %s:%s", "iptables -t nat -%s PREROUTING -p %s -d %s --dport %s -j DNAT --to-destination %s:%s",
op, protocol, vip.String(), port, localAddr.String(), port, op, protocol, vip.String(), lport, localAddr.String(), dport,
) )
cmdList := getCmdList(cmd) cmdList := getCmdList(cmd)
_, err := exec.Command(execCmd, cmdList...).Output() _, err := exec.Command(execCmd, cmdList...).Output()

33
go.mod
View File

@@ -3,36 +3,11 @@ module github.com/mayuresh82/gocast
go 1.12 go 1.12
require ( require (
github.com/armon/go-radix v1.0.0 // indirect
github.com/dgryski/go-farm v0.0.0-20180109070241-2de33835d102 // indirect
github.com/eapache/channels v1.1.0 // indirect
github.com/eapache/queue v1.1.0 // indirect
github.com/fsnotify/fsnotify v1.4.7 // indirect
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b
github.com/golang/lint v0.0.0-20180702182130-06c8688daad7 // indirect
github.com/golang/protobuf v1.4.1 github.com/golang/protobuf v1.4.1
github.com/hashicorp/hcl v1.0.0 // indirect github.com/osrg/gobgp v0.0.0-20211201041502-6248c576b118
github.com/influxdata/influxdb v1.6.4 // indirect github.com/sirupsen/logrus v1.8.1
github.com/kisielk/gotool v1.0.0 // indirect github.com/stretchr/testify v1.7.1
github.com/konsorten/go-windows-terminal-sequences v1.0.1 // indirect
github.com/magiconair/properties v1.8.0 // indirect
github.com/mitchellh/mapstructure v1.1.2 // indirect
github.com/osrg/gobgp v0.0.0-20200806055634-c6f0eba8f4d8
github.com/pelletier/go-toml v1.2.0 // indirect
github.com/satori/go.uuid v0.0.0-20181016184021-8ccf5352a842 // indirect
github.com/sirupsen/logrus v1.1.1
github.com/spf13/afero v1.1.2 // indirect
github.com/spf13/cast v1.2.0 // indirect
github.com/spf13/jwalterweatherman v1.0.0 // indirect
github.com/spf13/pflag v1.0.3 // indirect
github.com/stretchr/objx v0.3.0 // indirect
github.com/stretchr/testify v1.3.0
github.com/vishvananda/netlink v0.0.0-20181018205019-d3a23fd178f1 // indirect
github.com/vishvananda/netns v0.0.0-20180720170159-13995c7128cc // indirect
golang.org/x/text v0.3.0 // indirect
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 // indirect
google.golang.org/grpc v1.27.0 // indirect
google.golang.org/protobuf v1.25.0 // indirect google.golang.org/protobuf v1.25.0 // indirect
gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637 // indirect gopkg.in/yaml.v2 v2.4.0
gopkg.in/yaml.v2 v2.2.1
) )

361
go.sum
View File

@@ -1,32 +1,75 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU=
cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU=
cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY=
cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc=
cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0=
cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o=
cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE=
cloud.google.com/go/firestore v1.1.0/go.mod h1:ulACoGHTpvq5r8rxGJ4ddJZBZqakUQqClKRT5SZwBmk=
cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I=
cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw=
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/armon/go-radix v1.0.0 h1:F4z6KzEeeQIMeLFa97iZU6vupzoecKdU5TX24SNppXI= github.com/BurntSushi/toml v0.4.1 h1:GaI7EiDXDRfa8VshkTj7Fym7ha+y8/XxIgD2okUIjLw=
github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/BurntSushi/toml v0.4.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=
github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY=
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk=
github.com/coreos/etcd v3.3.13+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-farm v0.0.0-20171119141306-ac7624ea8da3/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/dgryski/go-farm v0.0.0-20180109070241-2de33835d102 h1:afESQBXJEnj3fu+34X//E8Wg3nEbMJxJkwSc0tPePK0= github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 h1:fAjc9m62+UWV/WAFKLNi6ZS0675eEUC9y3AlwSbQu1Y=
github.com/dgryski/go-farm v0.0.0-20180109070241-2de33835d102/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw=
github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
github.com/eapache/channels v1.1.0 h1:F1taHcn7/F0i8DYqKXJnyhJcVpp2kgFcNePxXtnyu4k= github.com/eapache/channels v1.1.0 h1:F1taHcn7/F0i8DYqKXJnyhJcVpp2kgFcNePxXtnyu4k=
github.com/eapache/channels v1.1.0/go.mod h1:jMm2qB5Ubtg9zLd+inMZd2/NUvXgzmWXsDaLyQIGfH0= github.com/eapache/channels v1.1.0/go.mod h1:jMm2qB5Ubtg9zLd+inMZd2/NUvXgzmWXsDaLyQIGfH0=
github.com/eapache/queue v1.0.2/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I=
github.com/eapache/queue v1.1.0 h1:YOEu7KNc61ntiQlcEeUIoDTJ2o8mQznoNvUhiigpIqc= github.com/eapache/queue v1.1.0 h1:YOEu7KNc61ntiQlcEeUIoDTJ2o8mQznoNvUhiigpIqc=
github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/fsnotify/fsnotify v1.4.2/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/go-test/deep v1.0.7 h1:/VSMRlnY/JSyqxQUzQLKVMAskpY/NZKFA5j2P+0pP2M=
github.com/go-test/deep v1.0.7/go.mod h1:QV8Hv/iy04NyLBxAdO9njL0iVPN1S4d/A3NVv1V36o8=
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:tluoj9z5200jBnyusfRPU2LqT6J+DAorxEvtC7LHB+E= github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/protobuf v1.0.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
@@ -35,143 +78,280 @@ github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:W
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.1 h1:ZFgWrT+bLgsYPirOnRfKLYJLvssAegOj/hgyMFdJZe0= github.com/golang/protobuf v1.4.1 h1:ZFgWrT+bLgsYPirOnRfKLYJLvssAegOj/hgyMFdJZe0=
github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w=
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/hcl v0.0.0-20170509225359-392dba7d905e/go.mod h1:oZtUIOe8dh44I2q6ScRibXws4Ajl+d+nod3AaR9vL5w= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=
github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY=
github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q=
github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=
github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60=
github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM=
github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk=
github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU=
github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU=
github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4=
github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90=
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64=
github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ=
github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I=
github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/influxdata/influxdb v1.6.4 h1:K8wPlkrP02HzHTJbbUQQ1CZ2Hw6LtpG4xbNEgnlhMZU= github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4=
github.com/influxdata/influxdb v1.6.4/go.mod h1:qZna6X/4elxqT3yI9iZYdZrWWdeFOOprn86kgg4+IzY= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
github.com/jessevdk/go-flags v1.3.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/k-sone/critbitgo v1.3.1-0.20191024122315-48c9e1530131 h1:2bjzgZk4GiWAFkj15/SkmxIO30u69RyPiSS+F0d+Kzs= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
github.com/k-sone/critbitgo v1.3.1-0.20191024122315-48c9e1530131/go.mod h1:7E6pyoyADnFxlUBEKcnfS49b7SUAQGMK+OAp/UQvo0s= github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/k-sone/critbitgo v1.4.0 h1:l71cTyBGeh6X5ATh6Fibgw3+rtNT80BA0uNNWgkPrbE=
github.com/k-sone/critbitgo v1.4.0/go.mod h1:7E6pyoyADnFxlUBEKcnfS49b7SUAQGMK+OAp/UQvo0s=
github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/konsorten/go-windows-terminal-sequences v0.0.0-20180402223658-b729f2633dfe/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/magiconair/properties v1.7.3/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/magiconair/properties v1.8.0 h1:LLgXmsheXeRoUOBOjtwPQCWIYqM/LU1ayDtDePerRcY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4=
github.com/mitchellh/mapstructure v0.0.0-20170523030023-d0303fe80992/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
github.com/mitchellh/mapstructure v1.0.0/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc=
github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI=
github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg=
github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY=
github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/osrg/gobgp v0.0.0-20180929145215-329c2d316efe h1:KuFjGka+ETeoDzymQaoF3leDNaIs7RZVwOLD8UR9OUM= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/osrg/gobgp v0.0.0-20180929145215-329c2d316efe/go.mod h1:vGVJPLW6JFDD7WA1vJsjB8OKmbbC2TKwHtr90CZS/u4= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/osrg/gobgp v0.0.0-20200806055634-c6f0eba8f4d8 h1:W41EUpzHmIdRa8uMPxL4nv7+lfZSlVREkHw+ROoQd/I= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/osrg/gobgp v0.0.0-20200806055634-c6f0eba8f4d8/go.mod h1:IVw8wEHROhX0qrmI8c6j3N8EDXZSC4YkktSzkX/JZ8Q= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
github.com/osrg/gobgp v2.0.0+incompatible h1:91ARQbE1AtO0U4TIxHPJ7wYVZIqduyBwS1+FjlHlmrY= github.com/osrg/gobgp v0.0.0-20211201041502-6248c576b118 h1:RBgnasb5QRwCufRtRE2eGeSRHPrGgk0frtdmULtuIxo=
github.com/osrg/gobgp v2.0.0+incompatible/go.mod h1:vGVJPLW6JFDD7WA1vJsjB8OKmbbC2TKwHtr90CZS/u4= github.com/osrg/gobgp v0.0.0-20211201041502-6248c576b118/go.mod h1:QvEj9qq9o66TvTyFC0Yyn1zgSSFrno8MsptfrjyMR7A=
github.com/pelletier/go-buffruneio v0.2.0/go.mod h1:JkE26KsDizTr40EUHkXVtNPvgGtbSNq5BcowyYOWdKo= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/pelletier/go-toml v1.0.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc= github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc=
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI=
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso=
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro=
github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU=
github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/satori/go.uuid v0.0.0-20181016184021-8ccf5352a842 h1:FnHGUoRWCQGG7mgyYKfpi6DM0hamU/OhJ3KQwE9V4JY= github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k=
github.com/satori/go.uuid v0.0.0-20181016184021-8ccf5352a842/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
github.com/sirupsen/logrus v0.0.0-20170713114250-a3f95b5c4235/go.mod h1:pMByvHTf9Beacp5x1UXfOR9xyW/9antXMhjMPG0dEzc= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sirupsen/logrus v1.1.1 h1:VzGj7lhU7KEB9e9gMpAV/v5XT2NVSvLJhJLCWbnkgXg= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
github.com/sirupsen/logrus v1.1.1/go.mod h1:zrgwTnHtNr00buQ1vSptGe8m1f/BbgsPukg8qsT7A+A= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
github.com/spf13/afero v0.0.0-20170217164146-9be650865eab/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s=
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM=
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI= github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI=
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
github.com/spf13/cast v1.1.0/go.mod h1:r2rcYCSwa1IExKTDiTfzaxqT2FNHs8hODu4LnUfgKEg= github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8=
github.com/spf13/cast v1.2.0 h1:HHl1DSRbEQN2i8tJmtS6ViPyHx35+p51amrdsiTCrkg= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/spf13/cast v1.2.0/go.mod h1:r2rcYCSwa1IExKTDiTfzaxqT2FNHs8hODu4LnUfgKEg= github.com/spf13/cobra v1.1.3/go.mod h1:pGADOWyqRD/YMrPZigI/zbliZ2wVD/23d+is3pSWzOo=
github.com/spf13/cobra v0.0.0-20170731170427-b26b538f6930/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
github.com/spf13/jwalterweatherman v0.0.0-20170523133247-0efa5202c046/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk= github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk=
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
github.com/spf13/pflag v1.0.0/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/spf13/pflag v1.0.2/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/spf13/viper v0.0.0-20180930044127-62edee319679 h1:77hFT1rWlkgnjOELbbHqfcJlUj4dsFj1+Y/Dw778Tuc= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/viper v0.0.0-20180930044127-62edee319679/go.mod h1:P4AexN0a+C9tGAnUFNwDMYYZv3pjFuvmeiMyKRaNVlI= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.0.0 h1:RUA/ghS2i64rlnn4ydTfblY8Og8QzcPtCcHvgMn+w/I= github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg=
github.com/spf13/viper v1.0.0/go.mod h1:A8kyI5cUJhb8N+3pkfONlcEcZbueH6nhAm0Fq7SrnBM= github.com/spf13/viper v1.7.1 h1:pM5oEahlgWv/WnHXpgbKz7iLIxRf65tye2Ci+XFK5sk=
github.com/spf13/viper v1.7.1/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.3.0 h1:NGXK3lHquSN08v5vWalVI/L8XU9hdzE/G6xsrze47As= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.3.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
github.com/stretchr/testify v1.1.4/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/vishvananda/netlink v0.0.0-20170802012344-a95659537721/go.mod h1:+SR5DhBJrl6ZM7CoCKvpw5BKroDKQ+PJqOg65H/2ktk= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/vishvananda/netlink v0.0.0-20181018205019-d3a23fd178f1 h1:JpigzxrBek5A4uli75H58EakZya3hdzLssY4gTUMplw= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/vishvananda/netlink v0.0.0-20181018205019-d3a23fd178f1/go.mod h1:+SR5DhBJrl6ZM7CoCKvpw5BKroDKQ+PJqOg65H/2ktk= github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY=
github.com/vishvananda/netns v0.0.0-20170707011535-86bef332bfc3/go.mod h1:ZjcWmFBXmLKZu9Nxj3WKYEafiSqer2rnvPr0en9UNpI= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/vishvananda/netns v0.0.0-20180720170159-13995c7128cc h1:R83G5ikgLMxrBvLh22JhdfI8K6YXEPHx5P03Uu3DRs4= github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s=
github.com/vishvananda/netns v0.0.0-20180720170159-13995c7128cc/go.mod h1:ZjcWmFBXmLKZu9Nxj3WKYEafiSqer2rnvPr0en9UNpI= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
github.com/vishvananda/netlink v1.1.1-0.20210330154013-f5de75959ad5 h1:+UB2BJA852UkGH42H+Oee69djmxS3ANzl2b/JtT1YiA=
github.com/vishvananda/netlink v1.1.1-0.20210330154013-f5de75959ad5/go.mod h1:twkDnbuQxJYemMlGd4JFIcuhgX83tXhKS2B/PRMpOho=
github.com/vishvananda/netns v0.0.0-20200728191858-db3c7e526aae h1:4hwBBUfQCFe3Cym0ZtKyq7L16eZUtYKs+BaHDN6mAns=
github.com/vishvananda/netns v0.0.0-20200728191858-db3c7e526aae/go.mod h1:DD4vA1DwXk04H54A1oHXtwZmA0grkVMdPxx/VGLCah0=
github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU=
go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20181015023909-0c41d7ab0a0e/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529 h1:iMGN4xG0cnqj3t+zOM8wUB0BiPKHEwSxEZCvzcbZuvk=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek=
golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE=
golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o=
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181017193950-04a2e542c03f/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a h1:oWX7TPOiFAMXLq8o0ikBYfCJVlRHBcsciT5bXOrH628=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859 h1:R/3boaszxrf1GEUWTVDzSKVwLmSJpwZ1yqXm8j0v2QI= golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210813160813-60bc85c4be6d h1:LO7XpTYMwTqxjLcGWPijK3vRXg1aWdlNOVOHRq45d7c=
golang.org/x/net v0.0.0-20210813160813-60bc85c4be6d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180906133057-8cf3aee42992/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181021155630-eda9bb28ed51/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d h1:+R4KGOnez64A81RvjARKc4UT5/tI9ujCIVX+P5KiHuI= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200217220822-9197077df867/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200728102440-3e129f6d46b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da h1:b3NXsE2LusjYGGjL5bxEVZZORm/YEFFrWFjR8eFrw/c=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190826182127-07722704da13/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20191026034945-b2104f82a97d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE=
google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M=
google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=
google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=
google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/genproto v0.0.0-20170731182057-09f6ed296fc6/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20181016170114-94acd270e44e/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8=
google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 h1:+kGHl1aib/qcwaRi1CbqBZ1rk19r85MNUf8HaBghugY= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 h1:+kGHl1aib/qcwaRi1CbqBZ1rk19r85MNUf8HaBghugY=
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
google.golang.org/grpc v1.5.1/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw=
google.golang.org/grpc v1.15.0/go.mod h1:0JHn/cJsOMiMfNA9+DeHDlAU7KAAB5GDlYFpa9MZMio=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.27.0 h1:rRYRFMVgRv6E0D70Skyfsr28tDXIuuPZyWGMPdMcnXg= google.golang.org/grpc v1.27.0 h1:rRYRFMVgRv6E0D70Skyfsr28tDXIuuPZyWGMPdMcnXg=
google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
@@ -184,15 +364,24 @@ google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.25.0 h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4c= google.golang.org/protobuf v1.25.0 h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4c=
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637 h1:yiW+nvdHb9LVqSHQBXfZCieqV4fzYhNBql77zY0ykqs= gopkg.in/ini.v1 v1.51.0 h1:AQvPpx3LzTDM0AjnIRlVFwFFGC+npRopjZxLJj6gdno=
gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637/go.mod h1:BHsqpu/nsuzkT5BpiH1EMZPLyqSMM8JbIavyFACoFNk= gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/yaml.v2 v2.0.0-20170721122051-25c4ec802a7d/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo=
gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE= gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20191022112108-ee025456fe28/go.mod h1:YZLKf07TTEX58hlaDFZRbZEdP4uwSiqhU91o1aN3EvM= honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8=

BIN
gocast Executable file

Binary file not shown.

11
main.go
View File

@@ -33,7 +33,16 @@ func main() {
go func() { go func() {
for { for {
sig := <-signalChan sig := <-signalChan
if sig == os.Interrupt || sig == syscall.SIGTERM { switch sig {
case syscall.SIGHUP:
log.Info("Received SIGHUP, reloading configuration")
if err := mon.Reload(*config); err != nil {
log.Errorf("Failed to reload configuration: %v", err)
} else {
log.Info("Configuration reloaded successfully")
}
case os.Interrupt, syscall.SIGTERM:
log.Info("Received shutdown signal, cleaning up")
mon.CloseAll() mon.CloseAll()
cancel() cancel()
return return

View File

@@ -72,11 +72,11 @@ func (s *Server) unregisterHandler(w http.ResponseWriter, r *http.Request) {
} }
func (s *Server) infoHandler(w http.ResponseWriter, r *http.Request) { func (s *Server) infoHandler(w http.ResponseWriter, r *http.Request) {
peer, err := s.mon.GetInfo() peers, err := s.mon.GetInfo()
if err != nil { if err != nil {
http.Error(w, fmt.Sprintf("Internal error getting peers: %v", err), http.StatusInternalServerError) http.Error(w, fmt.Sprintf("Internal error getting peers: %v", err), http.StatusInternalServerError)
return return
} }
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(peer) json.NewEncoder(w).Encode(peers)
} }

View File

@@ -13,7 +13,8 @@ branches:
- travis - travis
go: go:
- 1.9 - 1.12.x
- 1.13.x
- tip - tip
matrix: matrix:

View File

@@ -1,5 +1,3 @@
As this is a highly derivative work, I have placed it under the same license as the original implementation:
Copyright (c) 2014-2017 Damian Gryski Copyright (c) 2014-2017 Damian Gryski
Copyright (c) 2016-2017 Nicola Asuni - Tecnick.com Copyright (c) 2016-2017 Nicola Asuni - Tecnick.com

View File

@@ -10,7 +10,7 @@
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
# List special make targets that are not associated with files # List special make targets that are not associated with files
.PHONY: help all test format fmtcheck vet lint coverage cyclo ineffassign misspell structcheck varcheck errcheck gosimple astscan qa deps clean nuke .PHONY: help all test format fmtcheck vet lint coverage cyclo misspell errcheck staticcheck astscan qa deps clean nuke
# Use bash as shell (Note: Ubuntu now uses dash which doesn't support PIPESTATUS). # Use bash as shell (Note: Ubuntu now uses dash which doesn't support PIPESTATUS).
SHELL=/bin/bash SHELL=/bin/bash
@@ -66,12 +66,9 @@ help:
@echo " make lint : Check for style errors" @echo " make lint : Check for style errors"
@echo " make coverage : Generate the coverage report" @echo " make coverage : Generate the coverage report"
@echo " make cyclo : Generate the cyclomatic complexity report" @echo " make cyclo : Generate the cyclomatic complexity report"
@echo " make ineffassign : Detect ineffectual assignments"
@echo " make misspell : Detect commonly misspelled words in source files" @echo " make misspell : Detect commonly misspelled words in source files"
@echo " make structcheck : Find unused struct fields" @echo " make staticcheck : Run staticcheck
@echo " make varcheck : Find unused global variables and constants"
@echo " make errcheck : Check that error return values are used" @echo " make errcheck : Check that error return values are used"
@echo " make gosimple : Suggest code simplifications"
@echo " make astscan : GO AST scanner" @echo " make astscan : GO AST scanner"
@echo "" @echo ""
@echo " make docs : Generate source code documentation" @echo " make docs : Generate source code documentation"
@@ -131,35 +128,22 @@ cyclo:
@mkdir -p target/report @mkdir -p target/report
GOPATH=$(GOPATH) gocyclo -avg ./ | tee target/report/cyclo.txt ; test $${PIPESTATUS[0]} -eq 0 GOPATH=$(GOPATH) gocyclo -avg ./ | tee target/report/cyclo.txt ; test $${PIPESTATUS[0]} -eq 0
# Detect ineffectual assignments
ineffassign:
@mkdir -p target/report
GOPATH=$(GOPATH) ineffassign ./ | tee target/report/ineffassign.txt ; test $${PIPESTATUS[0]} -eq 0
# Detect commonly misspelled words in source files # Detect commonly misspelled words in source files
misspell: misspell:
@mkdir -p target/report @mkdir -p target/report
GOPATH=$(GOPATH) misspell -error ./ | tee target/report/misspell.txt ; test $${PIPESTATUS[0]} -eq 0 GOPATH=$(GOPATH) misspell -error ./ | tee target/report/misspell.txt ; test $${PIPESTATUS[0]} -eq 0
# Find unused struct fields
structcheck:
@mkdir -p target/report
GOPATH=$(GOPATH) structcheck -a ./ | tee target/report/structcheck.txt
# Find unused global variables and constants
varcheck:
@mkdir -p target/report
GOPATH=$(GOPATH) varcheck -e ./ | tee target/report/varcheck.txt
# Check that error return values are used # Check that error return values are used
errcheck: errcheck:
@mkdir -p target/report @mkdir -p target/report
GOPATH=$(GOPATH) errcheck ./ | tee target/report/errcheck.txt GOPATH=$(GOPATH) errcheck ./ | tee target/report/errcheck.txt
# Suggest code simplifications
gosimple: # staticcheck
staticcheck:
@mkdir -p target/report @mkdir -p target/report
GOPATH=$(GOPATH) gosimple ./ | tee target/report/gosimple.txt GOPATH=$(GOPATH) staticcheck ./... | tee target/report/staticcheck.txt
# AST scanner # AST scanner
astscan: astscan:
@@ -174,14 +158,14 @@ docs:
@echo '<html><head><meta http-equiv="refresh" content="0;./127.0.0.1:6060/pkg/'${CVSPATH}'/'${PROJECT}'/index.html"/></head><a href="./127.0.0.1:6060/pkg/'${CVSPATH}'/'${PROJECT}'/index.html">'${PKGNAME}' Documentation ...</a></html>' > target/docs/index.html @echo '<html><head><meta http-equiv="refresh" content="0;./127.0.0.1:6060/pkg/'${CVSPATH}'/'${PROJECT}'/index.html"/></head><a href="./127.0.0.1:6060/pkg/'${CVSPATH}'/'${PROJECT}'/index.html">'${PKGNAME}' Documentation ...</a></html>' > target/docs/index.html
# Alias to run all quality-assurance checks # Alias to run all quality-assurance checks
qa: fmtcheck test vet lint coverage cyclo ineffassign misspell structcheck varcheck errcheck gosimple astscan qa: fmtcheck test vet lint coverage cyclo misspell errcheck astscan
# --- INSTALL --- # --- INSTALL ---
# Get the dependencies # Get the dependencies
deps: deps:
GOPATH=$(GOPATH) go get ./... GOPATH=$(GOPATH) go get ./...
GOPATH=$(GOPATH) go get github.com/golang/lint/golint GOPATH=$(GOPATH) go get golang.org/x/lint/golint
GOPATH=$(GOPATH) go get github.com/jstemmer/go-junit-report GOPATH=$(GOPATH) go get github.com/jstemmer/go-junit-report
GOPATH=$(GOPATH) go get github.com/axw/gocov/gocov GOPATH=$(GOPATH) go get github.com/axw/gocov/gocov
GOPATH=$(GOPATH) go get github.com/fzipp/gocyclo GOPATH=$(GOPATH) go get github.com/fzipp/gocyclo
@@ -190,7 +174,7 @@ deps:
GOPATH=$(GOPATH) go get github.com/opennota/check/cmd/structcheck GOPATH=$(GOPATH) go get github.com/opennota/check/cmd/structcheck
GOPATH=$(GOPATH) go get github.com/opennota/check/cmd/varcheck GOPATH=$(GOPATH) go get github.com/opennota/check/cmd/varcheck
GOPATH=$(GOPATH) go get github.com/kisielk/errcheck GOPATH=$(GOPATH) go get github.com/kisielk/errcheck
GOPATH=$(GOPATH) go get honnef.co/go/tools/cmd/gosimple GOPATH=$(GOPATH) go get honnef.co/go/tools/cmd/staticcheck
GOPATH=$(GOPATH) go get github.com/GoASTScanner/gas GOPATH=$(GOPATH) go get github.com/GoASTScanner/gas
# Remove any build artifact # Remove any build artifact

View File

@@ -39,3 +39,8 @@ Before committing the code, please check if it passes all tests using
```bash ```bash
make qa make qa
``` ```
## License
As this is a highly derivative work, I have placed it under the same license as the original implementation. See the
LICENSE file for details.

View File

@@ -1,5 +1,7 @@
package farm package farm
import "math/bits"
// Some primes between 2^63 and 2^64 for various uses. // Some primes between 2^63 and 2^64 for various uses.
const k0 uint64 = 0xc3a5c85c97cb3127 const k0 uint64 = 0xc3a5c85c97cb3127
const k1 uint64 = 0xb492b66fbe98f273 const k1 uint64 = 0xb492b66fbe98f273
@@ -22,9 +24,9 @@ func fmix(h uint32) uint32 {
func mur(a, h uint32) uint32 { func mur(a, h uint32) uint32 {
// Helper from Murmur3 for combining two 32-bit values. // Helper from Murmur3 for combining two 32-bit values.
a *= c1 a *= c1
a = rotate32(a, 17) a = bits.RotateLeft32(a, -17)
a *= c2 a *= c2
h ^= a h ^= a
h = rotate32(h, 19) h = bits.RotateLeft32(h, -19)
return h*5 + 0xe6546b64 return h*5 + 0xe6546b64
} }

View File

@@ -1,23 +1,28 @@
package farm package farm
import (
"encoding/binary"
"math/bits"
)
// This file provides a 32-bit hash equivalent to CityHash32 (v1.1.1) // This file provides a 32-bit hash equivalent to CityHash32 (v1.1.1)
// and a 128-bit hash equivalent to CityHash128 (v1.1.1). It also provides // and a 128-bit hash equivalent to CityHash128 (v1.1.1). It also provides
// a seeded 32-bit hash function similar to CityHash32. // a seeded 32-bit hash function similar to CityHash32.
func hash32Len13to24Seed(s []byte, seed uint32) uint32 { func hash32Len13to24Seed(s []byte, seed uint32) uint32 {
slen := len(s) slen := len(s)
a := fetch32(s, -4+(slen>>1)) a := binary.LittleEndian.Uint32(s[-4+(slen>>1) : -4+(slen>>1)+4])
b := fetch32(s, 4) b := binary.LittleEndian.Uint32(s[4 : 4+4])
c := fetch32(s, slen-8) c := binary.LittleEndian.Uint32(s[slen-8 : slen-8+4])
d := fetch32(s, (slen >> 1)) d := binary.LittleEndian.Uint32(s[(slen >> 1) : (slen>>1)+4])
e := fetch32(s, 0) e := binary.LittleEndian.Uint32(s[0 : 0+4])
f := fetch32(s, slen-4) f := binary.LittleEndian.Uint32(s[slen-4 : slen-4+4])
h := d*c1 + uint32(slen) + seed h := d*c1 + uint32(slen) + seed
a = rotate32(a, 12) + f a = bits.RotateLeft32(a, -12) + f
h = mur(c, h) + a h = mur(c, h) + a
a = rotate32(a, 3) + c a = bits.RotateLeft32(a, -3) + c
h = mur(e, h) + a h = mur(e, h) + a
a = rotate32(a+f, 12) + d a = bits.RotateLeft32(a+f, -12) + d
h = mur(b^seed, h) + a h = mur(b^seed, h) + a
return fmix(h) return fmix(h)
} }
@@ -63,19 +68,19 @@ func cityMurmur(s []byte, seed uint128) uint128 {
a = shiftMix(a*k1) * k1 a = shiftMix(a*k1) * k1
c = b*k1 + hashLen0to16(s) c = b*k1 + hashLen0to16(s)
if slen >= 8 { if slen >= 8 {
d = shiftMix(a + fetch64(s, 0)) d = shiftMix(a + binary.LittleEndian.Uint64(s[0:0+8]))
} else { } else {
d = shiftMix(a + c) d = shiftMix(a + c)
} }
} else { // len > 16 } else { // len > 16
c = hashLen16(fetch64(s, slen-8)+k1, a) c = hashLen16(binary.LittleEndian.Uint64(s[slen-8:slen-8+8])+k1, a)
d = hashLen16(b+uint64(slen), c+fetch64(s, slen-16)) d = hashLen16(b+uint64(slen), c+binary.LittleEndian.Uint64(s[slen-16:slen-16+8]))
a += d a += d
for { for {
a ^= shiftMix(fetch64(s, 0)*k1) * k1 a ^= shiftMix(binary.LittleEndian.Uint64(s[0:0+8])*k1) * k1
a *= k1 a *= k1
b ^= a b ^= a
c ^= shiftMix(fetch64(s, 8)*k1) * k1 c ^= shiftMix(binary.LittleEndian.Uint64(s[8:8+8])*k1) * k1
c *= k1 c *= k1
d ^= c d ^= c
s = s[16:] s = s[16:]
@@ -107,29 +112,29 @@ func cityHash128WithSeed(s []byte, seed uint128) uint128 {
x := seed.lo x := seed.lo
y := seed.hi y := seed.hi
z := uint64(slen) * k1 z := uint64(slen) * k1
v1 = rotate64(y^k1, 49)*k1 + fetch64(s, 0) v1 = bits.RotateLeft64(y^k1, -49)*k1 + binary.LittleEndian.Uint64(s[0:0+8])
v2 = rotate64(v1, 42)*k1 + fetch64(s, 8) v2 = bits.RotateLeft64(v1, -42)*k1 + binary.LittleEndian.Uint64(s[8:8+8])
w1 = rotate64(y+z, 35)*k1 + x w1 = bits.RotateLeft64(y+z, -35)*k1 + x
w2 = rotate64(x+fetch64(s, 88), 53) * k1 w2 = bits.RotateLeft64(x+binary.LittleEndian.Uint64(s[88:88+8]), -53) * k1
// This is the same inner loop as CityHash64(), manually unrolled. // This is the same inner loop as CityHash64(), manually unrolled.
for { for {
x = rotate64(x+y+v1+fetch64(s, 8), 37) * k1 x = bits.RotateLeft64(x+y+v1+binary.LittleEndian.Uint64(s[8:8+8]), -37) * k1
y = rotate64(y+v2+fetch64(s, 48), 42) * k1 y = bits.RotateLeft64(y+v2+binary.LittleEndian.Uint64(s[48:48+8]), -42) * k1
x ^= w2 x ^= w2
y += v1 + fetch64(s, 40) y += v1 + binary.LittleEndian.Uint64(s[40:40+8])
z = rotate64(z+w1, 33) * k1 z = bits.RotateLeft64(z+w1, -33) * k1
v1, v2 = weakHashLen32WithSeeds(s, v2*k1, x+w1) v1, v2 = weakHashLen32WithSeeds(s, v2*k1, x+w1)
w1, w2 = weakHashLen32WithSeeds(s[32:], z+w2, y+fetch64(s, 16)) w1, w2 = weakHashLen32WithSeeds(s[32:], z+w2, y+binary.LittleEndian.Uint64(s[16:16+8]))
z, x = x, z z, x = x, z
s = s[64:] s = s[64:]
x = rotate64(x+y+v1+fetch64(s, 8), 37) * k1 x = bits.RotateLeft64(x+y+v1+binary.LittleEndian.Uint64(s[8:8+8]), -37) * k1
y = rotate64(y+v2+fetch64(s, 48), 42) * k1 y = bits.RotateLeft64(y+v2+binary.LittleEndian.Uint64(s[48:48+8]), -42) * k1
x ^= w2 x ^= w2
y += v1 + fetch64(s, 40) y += v1 + binary.LittleEndian.Uint64(s[40:40+8])
z = rotate64(z+w1, 33) * k1 z = bits.RotateLeft64(z+w1, -33) * k1
v1, v2 = weakHashLen32WithSeeds(s, v2*k1, x+w1) v1, v2 = weakHashLen32WithSeeds(s, v2*k1, x+w1)
w1, w2 = weakHashLen32WithSeeds(s[32:], z+w2, y+fetch64(s, 16)) w1, w2 = weakHashLen32WithSeeds(s[32:], z+w2, y+binary.LittleEndian.Uint64(s[16:16+8]))
z, x = x, z z, x = x, z
s = s[64:] s = s[64:]
slen -= 128 slen -= 128
@@ -137,18 +142,18 @@ func cityHash128WithSeed(s []byte, seed uint128) uint128 {
break break
} }
} }
x += rotate64(v1+z, 49) * k0 x += bits.RotateLeft64(v1+z, -49) * k0
y = y*k0 + rotate64(w2, 37) y = y*k0 + bits.RotateLeft64(w2, -37)
z = z*k0 + rotate64(w1, 27) z = z*k0 + bits.RotateLeft64(w1, -27)
w1 *= 9 w1 *= 9
v1 *= k0 v1 *= k0
// If 0 < len < 128, hash up to 4 chunks of 32 bytes each from the end of s. // If 0 < len < 128, hash up to 4 chunks of 32 bytes each from the end of s.
for tailDone := 0; tailDone < slen; { for tailDone := 0; tailDone < slen; {
tailDone += 32 tailDone += 32
y = rotate64(x+y, 42)*k0 + v2 y = bits.RotateLeft64(x+y, -42)*k0 + v2
w1 += fetch64(last, 128-tailDone+16) w1 += binary.LittleEndian.Uint64(last[128-tailDone+16 : 128-tailDone+16+8])
x = x*k0 + w1 x = x*k0 + w1
z += w2 + fetch64(last, 128-tailDone) z += w2 + binary.LittleEndian.Uint64(last[128-tailDone:128-tailDone+8])
w2 += v1 w2 += v1
v1, v2 = weakHashLen32WithSeeds(last[128-tailDone:], v1+z, v2) v1, v2 = weakHashLen32WithSeeds(last[128-tailDone:], v1+z, v2)
v1 *= k0 v1 *= k0
@@ -166,7 +171,7 @@ func cityHash128WithSeed(s []byte, seed uint128) uint128 {
func cityHash128(s []byte) uint128 { func cityHash128(s []byte) uint128 {
slen := len(s) slen := len(s)
if slen >= 16 { if slen >= 16 {
return cityHash128WithSeed(s[16:], uint128{fetch64(s, 0), fetch64(s, 8) + k0}) return cityHash128WithSeed(s[16:], uint128{binary.LittleEndian.Uint64(s[0 : 0+8]), binary.LittleEndian.Uint64(s[8:8+8]) + k0})
} }
return cityHash128WithSeed(s, uint128{k0, k1}) return cityHash128WithSeed(s, uint128{k0, k1})
} }
@@ -177,16 +182,6 @@ func Fingerprint128(s []byte) (lo, hi uint64) {
return h.lo, h.hi return h.lo, h.hi
} }
// Fingerprint64 is a 64-bit fingerprint function for byte-slices
func Fingerprint64(s []byte) uint64 {
return naHash64(s)
}
// Fingerprint32 is a 32-bit fingerprint function for byte-slices
func Fingerprint32(s []byte) uint32 {
return Hash32(s)
}
// Hash128 is a 128-bit hash function for byte-slices // Hash128 is a 128-bit hash function for byte-slices
func Hash128(s []byte) (lo, hi uint64) { func Hash128(s []byte) (lo, hi uint64) {
return Fingerprint128(s) return Fingerprint128(s)

View File

@@ -1,14 +1,19 @@
package farm package farm
import (
"encoding/binary"
"math/bits"
)
func hash32Len5to12(s []byte, seed uint32) uint32 { func hash32Len5to12(s []byte, seed uint32) uint32 {
slen := len(s) slen := len(s)
a := uint32(len(s)) a := uint32(len(s))
b := uint32(len(s) * 5) b := uint32(len(s) * 5)
c := uint32(9) c := uint32(9)
d := b + seed d := b + seed
a += fetch32(s, 0) a += binary.LittleEndian.Uint32(s[0 : 0+4])
b += fetch32(s, slen-4) b += binary.LittleEndian.Uint32(s[slen-4 : slen-4+4])
c += fetch32(s, ((slen >> 1) & 4)) c += binary.LittleEndian.Uint32(s[((slen >> 1) & 4) : ((slen>>1)&4)+4])
return fmix(seed ^ mur(c, mur(b, mur(a, d)))) return fmix(seed ^ mur(c, mur(b, mur(a, d))))
} }
@@ -31,32 +36,31 @@ func Hash32(s []byte) uint32 {
h := uint32(slen) h := uint32(slen)
g := c1 * uint32(slen) g := c1 * uint32(slen)
f := g f := g
a0 := rotate32(fetch32(s, slen-4)*c1, 17) * c2 a0 := bits.RotateLeft32(binary.LittleEndian.Uint32(s[slen-4:slen-4+4])*c1, -17) * c2
a1 := rotate32(fetch32(s, slen-8)*c1, 17) * c2 a1 := bits.RotateLeft32(binary.LittleEndian.Uint32(s[slen-8:slen-8+4])*c1, -17) * c2
a2 := rotate32(fetch32(s, slen-16)*c1, 17) * c2 a2 := bits.RotateLeft32(binary.LittleEndian.Uint32(s[slen-16:slen-16+4])*c1, -17) * c2
a3 := rotate32(fetch32(s, slen-12)*c1, 17) * c2 a3 := bits.RotateLeft32(binary.LittleEndian.Uint32(s[slen-12:slen-12+4])*c1, -17) * c2
a4 := rotate32(fetch32(s, slen-20)*c1, 17) * c2 a4 := bits.RotateLeft32(binary.LittleEndian.Uint32(s[slen-20:slen-20+4])*c1, -17) * c2
h ^= a0 h ^= a0
h = rotate32(h, 19) h = bits.RotateLeft32(h, -19)
h = h*5 + 0xe6546b64 h = h*5 + 0xe6546b64
h ^= a2 h ^= a2
h = rotate32(h, 19) h = bits.RotateLeft32(h, -19)
h = h*5 + 0xe6546b64 h = h*5 + 0xe6546b64
g ^= a1 g ^= a1
g = rotate32(g, 19) g = bits.RotateLeft32(g, -19)
g = g*5 + 0xe6546b64 g = g*5 + 0xe6546b64
g ^= a3 g ^= a3
g = rotate32(g, 19) g = bits.RotateLeft32(g, -19)
g = g*5 + 0xe6546b64 g = g*5 + 0xe6546b64
f += a4 f += a4
f = rotate32(f, 19) + 113 f = bits.RotateLeft32(f, -19) + 113
iters := (slen - 1) / 20 for len(s) > 20 {
for { a := binary.LittleEndian.Uint32(s[0 : 0+4])
a := fetch32(s, 0) b := binary.LittleEndian.Uint32(s[4 : 4+4])
b := fetch32(s, 4) c := binary.LittleEndian.Uint32(s[8 : 8+4])
c := fetch32(s, 8) d := binary.LittleEndian.Uint32(s[12 : 12+4])
d := fetch32(s, 12) e := binary.LittleEndian.Uint32(s[16 : 16+4])
e := fetch32(s, 16)
h += a h += a
g += b g += b
f += c f += c
@@ -66,21 +70,17 @@ func Hash32(s []byte) uint32 {
f += g f += g
g += f g += f
s = s[20:] s = s[20:]
iters--
if iters == 0 {
break
} }
} g = bits.RotateLeft32(g, -11) * c1
g = rotate32(g, 11) * c1 g = bits.RotateLeft32(g, -17) * c1
g = rotate32(g, 17) * c1 f = bits.RotateLeft32(f, -11) * c1
f = rotate32(f, 11) * c1 f = bits.RotateLeft32(f, -17) * c1
f = rotate32(f, 17) * c1 h = bits.RotateLeft32(h+g, -19)
h = rotate32(h+g, 19)
h = h*5 + 0xe6546b64 h = h*5 + 0xe6546b64
h = rotate32(h, 17) * c1 h = bits.RotateLeft32(h, -17) * c1
h = rotate32(h+f, 19) h = bits.RotateLeft32(h+f, -19)
h = h*5 + 0xe6546b64 h = h*5 + 0xe6546b64
h = rotate32(h, 17) * c1 h = bits.RotateLeft32(h, -17) * c1
return h return h
} }

View File

@@ -1,5 +1,10 @@
package farm package farm
import (
"encoding/binary"
"math/bits"
)
func shiftMix(val uint64) uint64 { func shiftMix(val uint64) uint64 {
return val ^ (val >> 47) return val ^ (val >> 47)
} }
@@ -22,17 +27,17 @@ func hashLen0to16(s []byte) uint64 {
slen := uint64(len(s)) slen := uint64(len(s))
if slen >= 8 { if slen >= 8 {
mul := k2 + slen*2 mul := k2 + slen*2
a := fetch64(s, 0) + k2 a := binary.LittleEndian.Uint64(s[0:0+8]) + k2
b := fetch64(s, int(slen-8)) b := binary.LittleEndian.Uint64(s[int(slen-8) : int(slen-8)+8])
c := rotate64(b, 37)*mul + a c := bits.RotateLeft64(b, -37)*mul + a
d := (rotate64(a, 25) + b) * mul d := (bits.RotateLeft64(a, -25) + b) * mul
return hashLen16Mul(c, d, mul) return hashLen16Mul(c, d, mul)
} }
if slen >= 4 { if slen >= 4 {
mul := k2 + slen*2 mul := k2 + slen*2
a := fetch32(s, 0) a := binary.LittleEndian.Uint32(s[0 : 0+4])
return hashLen16Mul(slen+(uint64(a)<<3), uint64(fetch32(s, int(slen-4))), mul) return hashLen16Mul(slen+(uint64(a)<<3), uint64(binary.LittleEndian.Uint32(s[int(slen-4):int(slen-4)+4])), mul)
} }
if slen > 0 { if slen > 0 {
a := s[0] a := s[0]
@@ -50,31 +55,31 @@ func hashLen0to16(s []byte) uint64 {
func hashLen17to32(s []byte) uint64 { func hashLen17to32(s []byte) uint64 {
slen := len(s) slen := len(s)
mul := k2 + uint64(slen*2) mul := k2 + uint64(slen*2)
a := fetch64(s, 0) * k1 a := binary.LittleEndian.Uint64(s[0:0+8]) * k1
b := fetch64(s, 8) b := binary.LittleEndian.Uint64(s[8 : 8+8])
c := fetch64(s, slen-8) * mul c := binary.LittleEndian.Uint64(s[slen-8:slen-8+8]) * mul
d := fetch64(s, slen-16) * k2 d := binary.LittleEndian.Uint64(s[slen-16:slen-16+8]) * k2
return hashLen16Mul(rotate64(a+b, 43)+rotate64(c, 30)+d, a+rotate64(b+k2, 18)+c, mul) return hashLen16Mul(bits.RotateLeft64(a+b, -43)+bits.RotateLeft64(c, -30)+d, a+bits.RotateLeft64(b+k2, -18)+c, mul)
} }
// Return a 16-byte hash for 48 bytes. Quick and dirty. // Return a 16-byte hash for 48 bytes. Quick and dirty.
// Callers do best to use "random-looking" values for a and b. // Callers do best to use "random-looking" values for a and b.
func weakHashLen32WithSeedsWords(w, x, y, z, a, b uint64) (uint64, uint64) { func weakHashLen32WithSeedsWords(w, x, y, z, a, b uint64) (uint64, uint64) {
a += w a += w
b = rotate64(b+a+z, 21) b = bits.RotateLeft64(b+a+z, -21)
c := a c := a
a += x a += x
a += y a += y
b += rotate64(a, 44) b += bits.RotateLeft64(a, -44)
return a + z, b + c return a + z, b + c
} }
// Return a 16-byte hash for s[0] ... s[31], a, and b. Quick and dirty. // Return a 16-byte hash for s[0] ... s[31], a, and b. Quick and dirty.
func weakHashLen32WithSeeds(s []byte, a, b uint64) (uint64, uint64) { func weakHashLen32WithSeeds(s []byte, a, b uint64) (uint64, uint64) {
return weakHashLen32WithSeedsWords(fetch64(s, 0), return weakHashLen32WithSeedsWords(binary.LittleEndian.Uint64(s[0:0+8]),
fetch64(s, 8), binary.LittleEndian.Uint64(s[8:8+8]),
fetch64(s, 16), binary.LittleEndian.Uint64(s[16:16+8]),
fetch64(s, 24), binary.LittleEndian.Uint64(s[24:24+8]),
a, a,
b) b)
} }
@@ -83,17 +88,17 @@ func weakHashLen32WithSeeds(s []byte, a, b uint64) (uint64, uint64) {
func hashLen33to64(s []byte) uint64 { func hashLen33to64(s []byte) uint64 {
slen := len(s) slen := len(s)
mul := k2 + uint64(slen)*2 mul := k2 + uint64(slen)*2
a := fetch64(s, 0) * k2 a := binary.LittleEndian.Uint64(s[0:0+8]) * k2
b := fetch64(s, 8) b := binary.LittleEndian.Uint64(s[8 : 8+8])
c := fetch64(s, slen-8) * mul c := binary.LittleEndian.Uint64(s[slen-8:slen-8+8]) * mul
d := fetch64(s, slen-16) * k2 d := binary.LittleEndian.Uint64(s[slen-16:slen-16+8]) * k2
y := rotate64(a+b, 43) + rotate64(c, 30) + d y := bits.RotateLeft64(a+b, -43) + bits.RotateLeft64(c, -30) + d
z := hashLen16Mul(y, a+rotate64(b+k2, 18)+c, mul) z := hashLen16Mul(y, a+bits.RotateLeft64(b+k2, -18)+c, mul)
e := fetch64(s, 16) * mul e := binary.LittleEndian.Uint64(s[16:16+8]) * mul
f := fetch64(s, 24) f := binary.LittleEndian.Uint64(s[24 : 24+8])
g := (y + fetch64(s, slen-32)) * mul g := (y + binary.LittleEndian.Uint64(s[slen-32:slen-32+8])) * mul
h := (z + fetch64(s, slen-24)) * mul h := (z + binary.LittleEndian.Uint64(s[slen-24:slen-24+8])) * mul
return hashLen16Mul(rotate64(e+f, 43)+rotate64(g, 30)+h, e+rotate64(f+a, 18)+g, mul) return hashLen16Mul(bits.RotateLeft64(e+f, -43)+bits.RotateLeft64(g, -30)+h, e+bits.RotateLeft64(f+a, -18)+g, mul)
} }
func naHash64(s []byte) uint64 { func naHash64(s []byte) uint64 {
@@ -112,7 +117,7 @@ func naHash64(s []byte) uint64 {
// Internal state consists of 56 bytes: v, w, x, y, and z. // Internal state consists of 56 bytes: v, w, x, y, and z.
v := uint128{0, 0} v := uint128{0, 0}
w := uint128{0, 0} w := uint128{0, 0}
x := seed*k2 + fetch64(s, 0) x := seed*k2 + binary.LittleEndian.Uint64(s[0:0+8])
y := seed*k1 + 113 y := seed*k1 + 113
z := shiftMix(y*k2+113) * k2 z := shiftMix(y*k2+113) * k2
// Set end so that after the loop we have 1 to 64 bytes left to process. // Set end so that after the loop we have 1 to 64 bytes left to process.
@@ -120,13 +125,13 @@ func naHash64(s []byte) uint64 {
last64Idx := endIdx + ((slen - 1) & 63) - 63 last64Idx := endIdx + ((slen - 1) & 63) - 63
last64 := s[last64Idx:] last64 := s[last64Idx:]
for len(s) > 64 { for len(s) > 64 {
x = rotate64(x+y+v.lo+fetch64(s, 8), 37) * k1 x = bits.RotateLeft64(x+y+v.lo+binary.LittleEndian.Uint64(s[8:8+8]), -37) * k1
y = rotate64(y+v.hi+fetch64(s, 48), 42) * k1 y = bits.RotateLeft64(y+v.hi+binary.LittleEndian.Uint64(s[48:48+8]), -42) * k1
x ^= w.hi x ^= w.hi
y += v.lo + fetch64(s, 40) y += v.lo + binary.LittleEndian.Uint64(s[40:40+8])
z = rotate64(z+w.lo, 33) * k1 z = bits.RotateLeft64(z+w.lo, -33) * k1
v.lo, v.hi = weakHashLen32WithSeeds(s, v.hi*k1, x+w.lo) v.lo, v.hi = weakHashLen32WithSeeds(s, v.hi*k1, x+w.lo)
w.lo, w.hi = weakHashLen32WithSeeds(s[32:], z+w.hi, y+fetch64(s, 16)) w.lo, w.hi = weakHashLen32WithSeeds(s[32:], z+w.hi, y+binary.LittleEndian.Uint64(s[16:16+8]))
x, z = z, x x, z = z, x
s = s[64:] s = s[64:]
} }
@@ -136,13 +141,13 @@ func naHash64(s []byte) uint64 {
w.lo += (uint64(slen-1) & 63) w.lo += (uint64(slen-1) & 63)
v.lo += w.lo v.lo += w.lo
w.lo += v.lo w.lo += v.lo
x = rotate64(x+y+v.lo+fetch64(s, 8), 37) * mul x = bits.RotateLeft64(x+y+v.lo+binary.LittleEndian.Uint64(s[8:8+8]), -37) * mul
y = rotate64(y+v.hi+fetch64(s, 48), 42) * mul y = bits.RotateLeft64(y+v.hi+binary.LittleEndian.Uint64(s[48:48+8]), -42) * mul
x ^= w.hi * 9 x ^= w.hi * 9
y += v.lo*9 + fetch64(s, 40) y += v.lo*9 + binary.LittleEndian.Uint64(s[40:40+8])
z = rotate64(z+w.lo, 33) * mul z = bits.RotateLeft64(z+w.lo, -33) * mul
v.lo, v.hi = weakHashLen32WithSeeds(s, v.hi*mul, x+w.lo) v.lo, v.hi = weakHashLen32WithSeeds(s, v.hi*mul, x+w.lo)
w.lo, w.hi = weakHashLen32WithSeeds(s[32:], z+w.hi, y+fetch64(s, 16)) w.lo, w.hi = weakHashLen32WithSeeds(s[32:], z+w.hi, y+binary.LittleEndian.Uint64(s[16:16+8]))
x, z = z, x x, z = z, x
return hashLen16Mul(hashLen16Mul(v.lo, w.lo, mul)+shiftMix(y)*k0+z, hashLen16Mul(v.hi, w.hi, mul)+x, mul) return hashLen16Mul(hashLen16Mul(v.lo, w.lo, mul)+shiftMix(y)*k0+z, hashLen16Mul(v.hi, w.hi, mul)+x, mul)
} }

View File

@@ -1,10 +1,15 @@
package farm package farm
import (
"encoding/binary"
"math/bits"
)
func uoH(x, y, mul uint64, r uint) uint64 { func uoH(x, y, mul uint64, r uint) uint64 {
a := (x ^ y) * mul a := (x ^ y) * mul
a ^= (a >> 47) a ^= (a >> 47)
b := (y ^ a) * mul b := (y ^ a) * mul
return rotate64(b, r) * mul return bits.RotateLeft64(b, -int(r)) * mul
} }
// Hash64WithSeeds hashes a byte slice and two uint64 seeds and returns a uint64 hash value // Hash64WithSeeds hashes a byte slice and two uint64 seeds and returns a uint64 hash value
@@ -31,14 +36,14 @@ func Hash64WithSeeds(s []byte, seed0, seed1 uint64) uint64 {
last64 := s[last64Idx:] last64 := s[last64Idx:]
for len(s) > 64 { for len(s) > 64 {
a0 := fetch64(s, 0) a0 := binary.LittleEndian.Uint64(s[0 : 0+8])
a1 := fetch64(s, 8) a1 := binary.LittleEndian.Uint64(s[8 : 8+8])
a2 := fetch64(s, 16) a2 := binary.LittleEndian.Uint64(s[16 : 16+8])
a3 := fetch64(s, 24) a3 := binary.LittleEndian.Uint64(s[24 : 24+8])
a4 := fetch64(s, 32) a4 := binary.LittleEndian.Uint64(s[32 : 32+8])
a5 := fetch64(s, 40) a5 := binary.LittleEndian.Uint64(s[40 : 40+8])
a6 := fetch64(s, 48) a6 := binary.LittleEndian.Uint64(s[48 : 48+8])
a7 := fetch64(s, 56) a7 := binary.LittleEndian.Uint64(s[56 : 56+8])
x += a0 + a1 x += a0 + a1
y += a2 y += a2
z += a3 z += a3
@@ -47,15 +52,15 @@ func Hash64WithSeeds(s []byte, seed0, seed1 uint64) uint64 {
w.lo += a6 w.lo += a6
w.hi += a7 w.hi += a7
x = rotate64(x, 26) x = bits.RotateLeft64(x, -26)
x *= 9 x *= 9
y = rotate64(y, 29) y = bits.RotateLeft64(y, -29)
z *= mul z *= mul
v.lo = rotate64(v.lo, 33) v.lo = bits.RotateLeft64(v.lo, -33)
v.hi = rotate64(v.hi, 30) v.hi = bits.RotateLeft64(v.hi, -30)
w.lo ^= x w.lo ^= x
w.lo *= 9 w.lo *= 9
z = rotate64(z, 32) z = bits.RotateLeft64(z, -32)
z += w.hi z += w.hi
w.hi += z w.hi += z
z *= 9 z *= 9
@@ -75,25 +80,25 @@ func Hash64WithSeeds(s []byte, seed0, seed1 uint64) uint64 {
w.lo += v.hi w.lo += v.hi
w.hi += x - y w.hi += x - y
x += w.hi x += w.hi
w.hi = rotate64(w.hi, 34) w.hi = bits.RotateLeft64(w.hi, -34)
u, z = z, u u, z = z, u
s = s[64:] s = s[64:]
} }
// Make s point to the last 64 bytes of input. // Make s point to the last 64 bytes of input.
s = last64 s = last64
u *= 9 u *= 9
v.hi = rotate64(v.hi, 28) v.hi = bits.RotateLeft64(v.hi, -28)
v.lo = rotate64(v.lo, 20) v.lo = bits.RotateLeft64(v.lo, -20)
w.lo += (uint64(slen-1) & 63) w.lo += (uint64(slen-1) & 63)
u += y u += y
y += u y += u
x = rotate64(y-x+v.lo+fetch64(s, 8), 37) * mul x = bits.RotateLeft64(y-x+v.lo+binary.LittleEndian.Uint64(s[8:8+8]), -37) * mul
y = rotate64(y^v.hi^fetch64(s, 48), 42) * mul y = bits.RotateLeft64(y^v.hi^binary.LittleEndian.Uint64(s[48:48+8]), -42) * mul
x ^= w.hi * 9 x ^= w.hi * 9
y += v.lo + fetch64(s, 40) y += v.lo + binary.LittleEndian.Uint64(s[40:40+8])
z = rotate64(z+w.lo, 33) * mul z = bits.RotateLeft64(z+w.lo, -33) * mul
v.lo, v.hi = weakHashLen32WithSeeds(s, v.hi*mul, x+w.lo) v.lo, v.hi = weakHashLen32WithSeeds(s, v.hi*mul, x+w.lo)
w.lo, w.hi = weakHashLen32WithSeeds(s[32:], z+w.hi, y+fetch64(s, 16)) w.lo, w.hi = weakHashLen32WithSeeds(s[32:], z+w.hi, y+binary.LittleEndian.Uint64(s[16:16+8]))
return uoH(hashLen16Mul(v.lo+x, w.lo^y, mul)+z-u, return uoH(hashLen16Mul(v.lo+x, w.lo^y, mul)+z-u,
uoH(v.hi+y, w.hi+z, k2, 30)^x, uoH(v.hi+y, w.hi+z, k2, 30)^x,
k2, k2,
@@ -109,7 +114,7 @@ func Hash64WithSeed(s []byte, seed uint64) uint64 {
} }
// Hash64 hashes a byte slice and returns a uint64 hash value // Hash64 hashes a byte slice and returns a uint64 hash value
func Hash64(s []byte) uint64 { func uoHash64(s []byte) uint64 {
if len(s) <= 64 { if len(s) <= 64 {
return naHash64(s) return naHash64(s)
} }

104
vendor/github.com/dgryski/go-farm/farmhashxo.go generated vendored Normal file
View File

@@ -0,0 +1,104 @@
package farm
import (
"encoding/binary"
"math/bits"
)
func h32(s []byte, mul uint64) uint64 {
slen := len(s)
a := binary.LittleEndian.Uint64(s[0:0+8]) * k1
b := binary.LittleEndian.Uint64(s[8 : 8+8])
c := binary.LittleEndian.Uint64(s[slen-8:slen-8+8]) * mul
d := binary.LittleEndian.Uint64(s[slen-16:slen-16+8]) * k2
u := bits.RotateLeft64(a+b, -43) + bits.RotateLeft64(c, -30) + d
v := a + bits.RotateLeft64(b+k2, -18) + c
a = shiftMix((u ^ v) * mul)
b = shiftMix((v ^ a) * mul)
return b
}
func h32Seeds(s []byte, mul, seed0, seed1 uint64) uint64 {
slen := len(s)
a := binary.LittleEndian.Uint64(s[0:0+8]) * k1
b := binary.LittleEndian.Uint64(s[8 : 8+8])
c := binary.LittleEndian.Uint64(s[slen-8:slen-8+8]) * mul
d := binary.LittleEndian.Uint64(s[slen-16:slen-16+8]) * k2
u := bits.RotateLeft64(a+b, -43) + bits.RotateLeft64(c, -30) + d + seed0
v := a + bits.RotateLeft64(b+k2, -18) + c + seed1
a = shiftMix((u ^ v) * mul)
b = shiftMix((v ^ a) * mul)
return b
}
func xohashLen33to64(s []byte) uint64 {
slen := len(s)
mul0 := k2 - 30
mul1 := k2 - 30 + 2*uint64(slen)
var h0 uint64
{
s := s[0:32]
mul := mul0
slen := len(s)
a := binary.LittleEndian.Uint64(s[0:0+8]) * k1
b := binary.LittleEndian.Uint64(s[8 : 8+8])
c := binary.LittleEndian.Uint64(s[slen-8:slen-8+8]) * mul
d := binary.LittleEndian.Uint64(s[slen-16:slen-16+8]) * k2
u := bits.RotateLeft64(a+b, -43) + bits.RotateLeft64(c, -30) + d
v := a + bits.RotateLeft64(b+k2, -18) + c
a = shiftMix((u ^ v) * mul)
b = shiftMix((v ^ a) * mul)
h0 = b
}
var h1 uint64
{
s := s[slen-32:]
mul := mul1
slen := len(s)
a := binary.LittleEndian.Uint64(s[0:0+8]) * k1
b := binary.LittleEndian.Uint64(s[8 : 8+8])
c := binary.LittleEndian.Uint64(s[slen-8:slen-8+8]) * mul
d := binary.LittleEndian.Uint64(s[slen-16:slen-16+8]) * k2
u := bits.RotateLeft64(a+b, -43) + bits.RotateLeft64(c, -30) + d
v := a + bits.RotateLeft64(b+k2, -18) + c
a = shiftMix((u ^ v) * mul)
b = shiftMix((v ^ a) * mul)
h1 = b
}
r := ((h1 * mul1) + h0) * mul1
return r
}
func xohashLen65to96(s []byte) uint64 {
slen := len(s)
mul0 := k2 - 114
mul1 := k2 - 114 + 2*uint64(slen)
h0 := h32(s[:32], mul0)
h1 := h32(s[32:64], mul1)
h2 := h32Seeds(s[slen-32:], mul1, h0, h1)
return (h2*9 + (h0 >> 17) + (h1 >> 21)) * mul1
}
func Hash64(s []byte) uint64 {
slen := len(s)
if slen <= 32 {
if slen <= 16 {
return hashLen0to16(s)
} else {
return hashLen17to32(s)
}
} else if slen <= 64 {
return xohashLen33to64(s)
} else if slen <= 96 {
return xohashLen65to96(s)
} else if slen <= 256 {
return naHash64(s)
} else {
return uoHash64(s)
}
}

951
vendor/github.com/dgryski/go-farm/fp_amd64.s generated vendored Normal file
View File

@@ -0,0 +1,951 @@
// Code generated by command: go run asm.go -out=fp_amd64.s -go111=false. DO NOT EDIT.
// +build amd64,!purego
#include "textflag.h"
// func Fingerprint64(s []byte) uint64
TEXT ·Fingerprint64(SB), NOSPLIT, $0-32
MOVQ s_base+0(FP), CX
MOVQ s_len+8(FP), AX
CMPQ AX, $0x10
JG check32
CMPQ AX, $0x08
JL check4
MOVQ (CX), DX
MOVQ AX, BX
SUBQ $0x08, BX
ADDQ CX, BX
MOVQ (BX), BX
MOVQ $0x9ae16a3b2f90404f, BP
ADDQ BP, DX
SHLQ $0x01, AX
ADDQ BP, AX
MOVQ BX, BP
RORQ $0x25, BP
IMULQ AX, BP
ADDQ DX, BP
RORQ $0x19, DX
ADDQ BX, DX
IMULQ AX, DX
XORQ DX, BP
IMULQ AX, BP
MOVQ BP, BX
SHRQ $0x2f, BX
XORQ BP, BX
XORQ BX, DX
IMULQ AX, DX
MOVQ DX, BX
SHRQ $0x2f, BX
XORQ DX, BX
IMULQ AX, BX
MOVQ BX, ret+24(FP)
RET
check4:
CMPQ AX, $0x04
JL check0
MOVQ $0x9ae16a3b2f90404f, DX
MOVQ AX, BX
SHLQ $0x01, BX
ADDQ DX, BX
MOVL (CX), SI
SHLQ $0x03, SI
ADDQ AX, SI
SUBQ $0x04, AX
ADDQ AX, CX
MOVL (CX), DI
XORQ DI, SI
IMULQ BX, SI
MOVQ SI, DX
SHRQ $0x2f, DX
XORQ SI, DX
XORQ DX, DI
IMULQ BX, DI
MOVQ DI, DX
SHRQ $0x2f, DX
XORQ DI, DX
IMULQ BX, DX
MOVQ DX, ret+24(FP)
RET
check0:
TESTQ AX, AX
JZ empty
MOVBQZX (CX), DX
MOVQ AX, BX
SHRQ $0x01, BX
ADDQ CX, BX
MOVBQZX (BX), BP
MOVQ AX, BX
SUBQ $0x01, BX
ADDQ CX, BX
MOVBQZX (BX), BX
SHLQ $0x08, BP
ADDQ BP, DX
SHLQ $0x02, BX
ADDQ BX, AX
MOVQ $0xc3a5c85c97cb3127, BX
IMULQ BX, AX
MOVQ $0x9ae16a3b2f90404f, BX
IMULQ BX, DX
XORQ DX, AX
MOVQ AX, DX
SHRQ $0x2f, DX
XORQ AX, DX
IMULQ BX, DX
MOVQ DX, ret+24(FP)
RET
empty:
MOVQ $0x9ae16a3b2f90404f, DX
MOVQ DX, ret+24(FP)
RET
check32:
CMPQ AX, $0x20
JG check64
MOVQ AX, DX
SHLQ $0x01, DX
MOVQ $0x9ae16a3b2f90404f, BX
ADDQ BX, DX
MOVQ (CX), BP
MOVQ $0xb492b66fbe98f273, SI
IMULQ SI, BP
MOVQ 8(CX), SI
MOVQ AX, DI
SUBQ $0x10, DI
ADDQ CX, DI
MOVQ 8(DI), R12
IMULQ DX, R12
MOVQ (DI), DI
IMULQ BX, DI
MOVQ BP, R13
ADDQ SI, R13
RORQ $0x2b, R13
ADDQ DI, R13
MOVQ R12, DI
RORQ $0x1e, DI
ADDQ DI, R13
ADDQ R12, BP
ADDQ BX, SI
RORQ $0x12, SI
ADDQ SI, BP
XORQ BP, R13
IMULQ DX, R13
MOVQ R13, BX
SHRQ $0x2f, BX
XORQ R13, BX
XORQ BX, BP
IMULQ DX, BP
MOVQ BP, BX
SHRQ $0x2f, BX
XORQ BP, BX
IMULQ DX, BX
MOVQ BX, ret+24(FP)
RET
check64:
CMPQ AX, $0x40
JG long
MOVQ AX, DX
SHLQ $0x01, DX
MOVQ $0x9ae16a3b2f90404f, BX
ADDQ BX, DX
MOVQ (CX), BP
IMULQ BX, BP
MOVQ 8(CX), SI
MOVQ AX, DI
SUBQ $0x10, DI
ADDQ CX, DI
MOVQ 8(DI), R12
IMULQ DX, R12
MOVQ (DI), DI
IMULQ BX, DI
MOVQ BP, R13
ADDQ SI, R13
RORQ $0x2b, R13
ADDQ DI, R13
MOVQ R12, DI
RORQ $0x1e, DI
ADDQ DI, R13
ADDQ BP, R12
ADDQ BX, SI
RORQ $0x12, SI
ADDQ SI, R12
MOVQ R13, BX
XORQ R12, BX
IMULQ DX, BX
MOVQ BX, SI
SHRQ $0x2f, SI
XORQ BX, SI
XORQ SI, R12
IMULQ DX, R12
MOVQ R12, BX
SHRQ $0x2f, BX
XORQ R12, BX
IMULQ DX, BX
MOVQ 16(CX), SI
IMULQ DX, SI
MOVQ 24(CX), DI
MOVQ AX, R12
SUBQ $0x20, R12
ADDQ CX, R12
MOVQ (R12), R14
ADDQ R13, R14
IMULQ DX, R14
MOVQ 8(R12), R12
ADDQ BX, R12
IMULQ DX, R12
MOVQ SI, BX
ADDQ DI, BX
RORQ $0x2b, BX
ADDQ R12, BX
MOVQ R14, R12
RORQ $0x1e, R12
ADDQ R12, BX
ADDQ R14, SI
ADDQ BP, DI
RORQ $0x12, DI
ADDQ DI, SI
XORQ SI, BX
IMULQ DX, BX
MOVQ BX, BP
SHRQ $0x2f, BP
XORQ BX, BP
XORQ BP, SI
IMULQ DX, SI
MOVQ SI, BX
SHRQ $0x2f, BX
XORQ SI, BX
IMULQ DX, BX
MOVQ BX, ret+24(FP)
RET
long:
XORQ R8, R8
XORQ R9, R9
XORQ R10, R10
XORQ R11, R11
MOVQ $0x01529cba0ca458ff, DX
ADDQ (CX), DX
MOVQ $0x226bb95b4e64b6d4, BX
MOVQ $0x134a747f856d0526, BP
MOVQ AX, SI
SUBQ $0x01, SI
MOVQ $0xffffffffffffffc0, DI
ANDQ DI, SI
MOVQ AX, DI
SUBQ $0x01, DI
ANDQ $0x3f, DI
SUBQ $0x3f, DI
ADDQ SI, DI
MOVQ DI, SI
ADDQ CX, SI
MOVQ AX, DI
loop:
MOVQ $0xb492b66fbe98f273, R12
ADDQ BX, DX
ADDQ R8, DX
ADDQ 8(CX), DX
RORQ $0x25, DX
IMULQ R12, DX
ADDQ R9, BX
ADDQ 48(CX), BX
RORQ $0x2a, BX
IMULQ R12, BX
XORQ R11, DX
ADDQ R8, BX
ADDQ 40(CX), BX
ADDQ R10, BP
RORQ $0x21, BP
IMULQ R12, BP
IMULQ R12, R9
MOVQ DX, R8
ADDQ R10, R8
ADDQ (CX), R9
ADDQ R9, R8
ADDQ 24(CX), R8
RORQ $0x15, R8
MOVQ R9, R10
ADDQ 8(CX), R9
ADDQ 16(CX), R9
MOVQ R9, R13
RORQ $0x2c, R13
ADDQ R13, R8
ADDQ 24(CX), R9
ADDQ R10, R8
XCHGQ R9, R8
ADDQ BP, R11
MOVQ BX, R10
ADDQ 16(CX), R10
ADDQ 32(CX), R11
ADDQ R11, R10
ADDQ 56(CX), R10
RORQ $0x15, R10
MOVQ R11, R13
ADDQ 40(CX), R11
ADDQ 48(CX), R11
MOVQ R11, R14
RORQ $0x2c, R14
ADDQ R14, R10
ADDQ 56(CX), R11
ADDQ R13, R10
XCHGQ R11, R10
XCHGQ BP, DX
ADDQ $0x40, CX
SUBQ $0x40, DI
CMPQ DI, $0x40
JG loop
MOVQ SI, CX
MOVQ BP, DI
ANDQ $0xff, DI
SHLQ $0x01, DI
ADDQ R12, DI
MOVQ SI, CX
SUBQ $0x01, AX
ANDQ $0x3f, AX
ADDQ AX, R10
ADDQ R10, R8
ADDQ R8, R10
ADDQ BX, DX
ADDQ R8, DX
ADDQ 8(CX), DX
RORQ $0x25, DX
IMULQ DI, DX
ADDQ R9, BX
ADDQ 48(CX), BX
RORQ $0x2a, BX
IMULQ DI, BX
MOVQ $0x00000009, AX
IMULQ R11, AX
XORQ AX, DX
MOVQ $0x00000009, AX
IMULQ R8, AX
ADDQ AX, BX
ADDQ 40(CX), BX
ADDQ R10, BP
RORQ $0x21, BP
IMULQ DI, BP
IMULQ DI, R9
MOVQ DX, R8
ADDQ R10, R8
ADDQ (CX), R9
ADDQ R9, R8
ADDQ 24(CX), R8
RORQ $0x15, R8
MOVQ R9, AX
ADDQ 8(CX), R9
ADDQ 16(CX), R9
MOVQ R9, SI
RORQ $0x2c, SI
ADDQ SI, R8
ADDQ 24(CX), R9
ADDQ AX, R8
XCHGQ R9, R8
ADDQ BP, R11
MOVQ BX, R10
ADDQ 16(CX), R10
ADDQ 32(CX), R11
ADDQ R11, R10
ADDQ 56(CX), R10
RORQ $0x15, R10
MOVQ R11, AX
ADDQ 40(CX), R11
ADDQ 48(CX), R11
MOVQ R11, SI
RORQ $0x2c, SI
ADDQ SI, R10
ADDQ 56(CX), R11
ADDQ AX, R10
XCHGQ R11, R10
XCHGQ BP, DX
XORQ R10, R8
IMULQ DI, R8
MOVQ R8, AX
SHRQ $0x2f, AX
XORQ R8, AX
XORQ AX, R10
IMULQ DI, R10
MOVQ R10, AX
SHRQ $0x2f, AX
XORQ R10, AX
IMULQ DI, AX
ADDQ BP, AX
MOVQ BX, CX
SHRQ $0x2f, CX
XORQ BX, CX
MOVQ $0xc3a5c85c97cb3127, BX
IMULQ BX, CX
ADDQ CX, AX
XORQ R11, R9
IMULQ DI, R9
MOVQ R9, CX
SHRQ $0x2f, CX
XORQ R9, CX
XORQ CX, R11
IMULQ DI, R11
MOVQ R11, CX
SHRQ $0x2f, CX
XORQ R11, CX
IMULQ DI, CX
ADDQ DX, CX
XORQ CX, AX
IMULQ DI, AX
MOVQ AX, DX
SHRQ $0x2f, DX
XORQ AX, DX
XORQ DX, CX
IMULQ DI, CX
MOVQ CX, AX
SHRQ $0x2f, AX
XORQ CX, AX
IMULQ DI, AX
MOVQ AX, ret+24(FP)
RET
// func Fingerprint32(s []byte) uint32
TEXT ·Fingerprint32(SB), NOSPLIT, $0-28
MOVQ s_base+0(FP), AX
MOVQ s_len+8(FP), CX
CMPQ CX, $0x18
JG long
CMPQ CX, $0x0c
JG hash_13_24
CMPQ CX, $0x04
JG hash_5_12
XORL DX, DX
MOVL $0x00000009, BX
TESTQ CX, CX
JZ done
MOVQ CX, BP
MOVL $0xcc9e2d51, DI
IMULL DI, DX
MOVBLSX (AX), SI
ADDL SI, DX
XORL DX, BX
SUBQ $0x01, BP
TESTQ BP, BP
JZ done
IMULL DI, DX
MOVBLSX 1(AX), SI
ADDL SI, DX
XORL DX, BX
SUBQ $0x01, BP
TESTQ BP, BP
JZ done
IMULL DI, DX
MOVBLSX 2(AX), SI
ADDL SI, DX
XORL DX, BX
SUBQ $0x01, BP
TESTQ BP, BP
JZ done
IMULL DI, DX
MOVBLSX 3(AX), SI
ADDL SI, DX
XORL DX, BX
SUBQ $0x01, BP
TESTQ BP, BP
JZ done
done:
MOVL CX, BP
MOVL $0xcc9e2d51, SI
IMULL SI, BP
RORL $0x11, BP
MOVL $0x1b873593, SI
IMULL SI, BP
XORL BP, BX
RORL $0x13, BX
LEAL (BX)(BX*4), BP
LEAL 3864292196(BP), BX
MOVL $0xcc9e2d51, BP
IMULL BP, DX
RORL $0x11, DX
MOVL $0x1b873593, BP
IMULL BP, DX
XORL DX, BX
RORL $0x13, BX
LEAL (BX)(BX*4), DX
LEAL 3864292196(DX), BX
MOVL BX, DX
SHRL $0x10, DX
XORL DX, BX
MOVL $0x85ebca6b, DX
IMULL DX, BX
MOVL BX, DX
SHRL $0x0d, DX
XORL DX, BX
MOVL $0xc2b2ae35, DX
IMULL DX, BX
MOVL BX, DX
SHRL $0x10, DX
XORL DX, BX
MOVL BX, ret+24(FP)
RET
hash_5_12:
MOVL CX, DX
MOVL DX, BX
SHLL $0x02, BX
ADDL DX, BX
MOVL $0x00000009, BP
MOVL BX, SI
ADDL (AX), DX
MOVQ CX, DI
SUBQ $0x04, DI
ADDQ AX, DI
ADDL (DI), BX
MOVQ CX, DI
SHRQ $0x01, DI
ANDQ $0x04, DI
ADDQ AX, DI
ADDL (DI), BP
MOVL $0xcc9e2d51, DI
IMULL DI, DX
RORL $0x11, DX
MOVL $0x1b873593, DI
IMULL DI, DX
XORL DX, SI
RORL $0x13, SI
LEAL (SI)(SI*4), DX
LEAL 3864292196(DX), SI
MOVL $0xcc9e2d51, DX
IMULL DX, BX
RORL $0x11, BX
MOVL $0x1b873593, DX
IMULL DX, BX
XORL BX, SI
RORL $0x13, SI
LEAL (SI)(SI*4), BX
LEAL 3864292196(BX), SI
MOVL $0xcc9e2d51, DX
IMULL DX, BP
RORL $0x11, BP
MOVL $0x1b873593, DX
IMULL DX, BP
XORL BP, SI
RORL $0x13, SI
LEAL (SI)(SI*4), BP
LEAL 3864292196(BP), SI
MOVL SI, DX
SHRL $0x10, DX
XORL DX, SI
MOVL $0x85ebca6b, DX
IMULL DX, SI
MOVL SI, DX
SHRL $0x0d, DX
XORL DX, SI
MOVL $0xc2b2ae35, DX
IMULL DX, SI
MOVL SI, DX
SHRL $0x10, DX
XORL DX, SI
MOVL SI, ret+24(FP)
RET
hash_13_24:
MOVQ CX, DX
SHRQ $0x01, DX
ADDQ AX, DX
MOVL -4(DX), BX
MOVL 4(AX), BP
MOVQ CX, SI
ADDQ AX, SI
MOVL -8(SI), DI
MOVL (DX), DX
MOVL (AX), R8
MOVL -4(SI), SI
MOVL $0xcc9e2d51, R9
IMULL DX, R9
ADDL CX, R9
RORL $0x0c, BX
ADDL SI, BX
MOVL DI, R10
MOVL $0xcc9e2d51, R11
IMULL R11, R10
RORL $0x11, R10
MOVL $0x1b873593, R11
IMULL R11, R10
XORL R10, R9
RORL $0x13, R9
LEAL (R9)(R9*4), R10
LEAL 3864292196(R10), R9
ADDL BX, R9
RORL $0x03, BX
ADDL DI, BX
MOVL $0xcc9e2d51, DI
IMULL DI, R8
RORL $0x11, R8
MOVL $0x1b873593, DI
IMULL DI, R8
XORL R8, R9
RORL $0x13, R9
LEAL (R9)(R9*4), R8
LEAL 3864292196(R8), R9
ADDL BX, R9
ADDL SI, BX
RORL $0x0c, BX
ADDL DX, BX
MOVL $0xcc9e2d51, DX
IMULL DX, BP
RORL $0x11, BP
MOVL $0x1b873593, DX
IMULL DX, BP
XORL BP, R9
RORL $0x13, R9
LEAL (R9)(R9*4), BP
LEAL 3864292196(BP), R9
ADDL BX, R9
MOVL R9, DX
SHRL $0x10, DX
XORL DX, R9
MOVL $0x85ebca6b, DX
IMULL DX, R9
MOVL R9, DX
SHRL $0x0d, DX
XORL DX, R9
MOVL $0xc2b2ae35, DX
IMULL DX, R9
MOVL R9, DX
SHRL $0x10, DX
XORL DX, R9
MOVL R9, ret+24(FP)
RET
long:
MOVL CX, DX
MOVL $0xcc9e2d51, BX
IMULL DX, BX
MOVL BX, BP
MOVQ CX, SI
ADDQ AX, SI
MOVL $0xcc9e2d51, DI
MOVL $0x1b873593, R8
MOVL -4(SI), R9
IMULL DI, R9
RORL $0x11, R9
IMULL R8, R9
XORL R9, DX
RORL $0x13, DX
MOVL DX, R9
SHLL $0x02, R9
ADDL R9, DX
ADDL $0xe6546b64, DX
MOVL -8(SI), R9
IMULL DI, R9
RORL $0x11, R9
IMULL R8, R9
XORL R9, BX
RORL $0x13, BX
MOVL BX, R9
SHLL $0x02, R9
ADDL R9, BX
ADDL $0xe6546b64, BX
MOVL -16(SI), R9
IMULL DI, R9
RORL $0x11, R9
IMULL R8, R9
XORL R9, DX
RORL $0x13, DX
MOVL DX, R9
SHLL $0x02, R9
ADDL R9, DX
ADDL $0xe6546b64, DX
MOVL -12(SI), R9
IMULL DI, R9
RORL $0x11, R9
IMULL R8, R9
XORL R9, BX
RORL $0x13, BX
MOVL BX, R9
SHLL $0x02, R9
ADDL R9, BX
ADDL $0xe6546b64, BX
PREFETCHT0 (AX)
MOVL -20(SI), SI
IMULL DI, SI
RORL $0x11, SI
IMULL R8, SI
ADDL SI, BP
RORL $0x13, BP
ADDL $0x71, BP
loop80:
CMPQ CX, $0x64
JL loop20
PREFETCHT0 20(AX)
MOVL (AX), SI
ADDL SI, DX
MOVL 4(AX), DI
ADDL DI, BX
MOVL 8(AX), R8
ADDL R8, BP
MOVL 12(AX), R9
MOVL R9, R11
MOVL $0xcc9e2d51, R10
IMULL R10, R11
RORL $0x11, R11
MOVL $0x1b873593, R10
IMULL R10, R11
XORL R11, DX
RORL $0x13, DX
LEAL (DX)(DX*4), R11
LEAL 3864292196(R11), DX
MOVL 16(AX), R10
ADDL R10, DX
MOVL R8, R11
MOVL $0xcc9e2d51, R8
IMULL R8, R11
RORL $0x11, R11
MOVL $0x1b873593, R8
IMULL R8, R11
XORL R11, BX
RORL $0x13, BX
LEAL (BX)(BX*4), R11
LEAL 3864292196(R11), BX
ADDL SI, BX
MOVL $0xcc9e2d51, SI
IMULL SI, R10
MOVL R10, R11
ADDL DI, R11
MOVL $0xcc9e2d51, SI
IMULL SI, R11
RORL $0x11, R11
MOVL $0x1b873593, SI
IMULL SI, R11
XORL R11, BP
RORL $0x13, BP
LEAL (BP)(BP*4), R11
LEAL 3864292196(R11), BP
ADDL R9, BP
ADDL BX, BP
ADDL BP, BX
PREFETCHT0 40(AX)
MOVL 20(AX), SI
ADDL SI, DX
MOVL 24(AX), DI
ADDL DI, BX
MOVL 28(AX), R8
ADDL R8, BP
MOVL 32(AX), R9
MOVL R9, R11
MOVL $0xcc9e2d51, R10
IMULL R10, R11
RORL $0x11, R11
MOVL $0x1b873593, R10
IMULL R10, R11
XORL R11, DX
RORL $0x13, DX
LEAL (DX)(DX*4), R11
LEAL 3864292196(R11), DX
MOVL 36(AX), R10
ADDL R10, DX
MOVL R8, R11
MOVL $0xcc9e2d51, R8
IMULL R8, R11
RORL $0x11, R11
MOVL $0x1b873593, R8
IMULL R8, R11
XORL R11, BX
RORL $0x13, BX
LEAL (BX)(BX*4), R11
LEAL 3864292196(R11), BX
ADDL SI, BX
MOVL $0xcc9e2d51, SI
IMULL SI, R10
MOVL R10, R11
ADDL DI, R11
MOVL $0xcc9e2d51, SI
IMULL SI, R11
RORL $0x11, R11
MOVL $0x1b873593, SI
IMULL SI, R11
XORL R11, BP
RORL $0x13, BP
LEAL (BP)(BP*4), R11
LEAL 3864292196(R11), BP
ADDL R9, BP
ADDL BX, BP
ADDL BP, BX
PREFETCHT0 60(AX)
MOVL 40(AX), SI
ADDL SI, DX
MOVL 44(AX), DI
ADDL DI, BX
MOVL 48(AX), R8
ADDL R8, BP
MOVL 52(AX), R9
MOVL R9, R11
MOVL $0xcc9e2d51, R10
IMULL R10, R11
RORL $0x11, R11
MOVL $0x1b873593, R10
IMULL R10, R11
XORL R11, DX
RORL $0x13, DX
LEAL (DX)(DX*4), R11
LEAL 3864292196(R11), DX
MOVL 56(AX), R10
ADDL R10, DX
MOVL R8, R11
MOVL $0xcc9e2d51, R8
IMULL R8, R11
RORL $0x11, R11
MOVL $0x1b873593, R8
IMULL R8, R11
XORL R11, BX
RORL $0x13, BX
LEAL (BX)(BX*4), R11
LEAL 3864292196(R11), BX
ADDL SI, BX
MOVL $0xcc9e2d51, SI
IMULL SI, R10
MOVL R10, R11
ADDL DI, R11
MOVL $0xcc9e2d51, SI
IMULL SI, R11
RORL $0x11, R11
MOVL $0x1b873593, SI
IMULL SI, R11
XORL R11, BP
RORL $0x13, BP
LEAL (BP)(BP*4), R11
LEAL 3864292196(R11), BP
ADDL R9, BP
ADDL BX, BP
ADDL BP, BX
PREFETCHT0 80(AX)
MOVL 60(AX), SI
ADDL SI, DX
MOVL 64(AX), DI
ADDL DI, BX
MOVL 68(AX), R8
ADDL R8, BP
MOVL 72(AX), R9
MOVL R9, R11
MOVL $0xcc9e2d51, R10
IMULL R10, R11
RORL $0x11, R11
MOVL $0x1b873593, R10
IMULL R10, R11
XORL R11, DX
RORL $0x13, DX
LEAL (DX)(DX*4), R11
LEAL 3864292196(R11), DX
MOVL 76(AX), R10
ADDL R10, DX
MOVL R8, R11
MOVL $0xcc9e2d51, R8
IMULL R8, R11
RORL $0x11, R11
MOVL $0x1b873593, R8
IMULL R8, R11
XORL R11, BX
RORL $0x13, BX
LEAL (BX)(BX*4), R11
LEAL 3864292196(R11), BX
ADDL SI, BX
MOVL $0xcc9e2d51, SI
IMULL SI, R10
MOVL R10, R11
ADDL DI, R11
MOVL $0xcc9e2d51, SI
IMULL SI, R11
RORL $0x11, R11
MOVL $0x1b873593, SI
IMULL SI, R11
XORL R11, BP
RORL $0x13, BP
LEAL (BP)(BP*4), R11
LEAL 3864292196(R11), BP
ADDL R9, BP
ADDL BX, BP
ADDL BP, BX
ADDQ $0x50, AX
SUBQ $0x50, CX
JMP loop80
loop20:
CMPQ CX, $0x14
JLE after
MOVL (AX), SI
ADDL SI, DX
MOVL 4(AX), DI
ADDL DI, BX
MOVL 8(AX), R8
ADDL R8, BP
MOVL 12(AX), R9
MOVL R9, R11
MOVL $0xcc9e2d51, R10
IMULL R10, R11
RORL $0x11, R11
MOVL $0x1b873593, R10
IMULL R10, R11
XORL R11, DX
RORL $0x13, DX
LEAL (DX)(DX*4), R11
LEAL 3864292196(R11), DX
MOVL 16(AX), R10
ADDL R10, DX
MOVL R8, R11
MOVL $0xcc9e2d51, R8
IMULL R8, R11
RORL $0x11, R11
MOVL $0x1b873593, R8
IMULL R8, R11
XORL R11, BX
RORL $0x13, BX
LEAL (BX)(BX*4), R11
LEAL 3864292196(R11), BX
ADDL SI, BX
MOVL $0xcc9e2d51, SI
IMULL SI, R10
MOVL R10, R11
ADDL DI, R11
MOVL $0xcc9e2d51, SI
IMULL SI, R11
RORL $0x11, R11
MOVL $0x1b873593, SI
IMULL SI, R11
XORL R11, BP
RORL $0x13, BP
LEAL (BP)(BP*4), R11
LEAL 3864292196(R11), BP
ADDL R9, BP
ADDL BX, BP
ADDL BP, BX
ADDQ $0x14, AX
SUBQ $0x14, CX
JMP loop20
after:
MOVL $0xcc9e2d51, AX
RORL $0x0b, BX
IMULL AX, BX
RORL $0x11, BX
IMULL AX, BX
RORL $0x0b, BP
IMULL AX, BP
RORL $0x11, BP
IMULL AX, BP
ADDL BX, DX
RORL $0x13, DX
MOVL DX, CX
SHLL $0x02, CX
ADDL CX, DX
ADDL $0xe6546b64, DX
RORL $0x11, DX
IMULL AX, DX
ADDL BP, DX
RORL $0x13, DX
MOVL DX, CX
SHLL $0x02, CX
ADDL CX, DX
ADDL $0xe6546b64, DX
RORL $0x11, DX
IMULL AX, DX
MOVL DX, ret+24(FP)
RET

13
vendor/github.com/dgryski/go-farm/fp_generic.go generated vendored Normal file
View File

@@ -0,0 +1,13 @@
// +build !amd64 purego
package farm
// Fingerprint64 is a 64-bit fingerprint function for byte-slices
func Fingerprint64(s []byte) uint64 {
return naHash64(s)
}
// Fingerprint32 is a 32-bit fingerprint function for byte-slices
func Fingerprint32(s []byte) uint32 {
return Hash32(s)
}

9
vendor/github.com/dgryski/go-farm/fp_stub.go generated vendored Normal file
View File

@@ -0,0 +1,9 @@
// Code generated by command: go run asm.go -out=fp_amd64.s -stubs=fp_stub.go. DO NOT EDIT.
// +build amd64,!purego
package farm
func Fingerprint64(s []byte) uint64
func Fingerprint32(s []byte) uint32

View File

@@ -1,18 +0,0 @@
package farm
func rotate32(val uint32, shift uint) uint32 {
return ((val >> shift) | (val << (32 - shift)))
}
func rotate64(val uint64, shift uint) uint64 {
return ((val >> shift) | (val << (64 - shift)))
}
func fetch32(s []byte, idx int) uint32 {
return uint32(s[idx+0]) | uint32(s[idx+1])<<8 | uint32(s[idx+2])<<16 | uint32(s[idx+3])<<24
}
func fetch64(s []byte, idx int) uint64 {
return uint64(s[idx+0]) | uint64(s[idx+1])<<8 | uint64(s[idx+2])<<16 | uint64(s[idx+3])<<24 |
uint64(s[idx+4])<<32 | uint64(s[idx+5])<<40 | uint64(s[idx+6])<<48 | uint64(s[idx+7])<<56
}

View File

@@ -16,4 +16,4 @@ change is the ability to represent an invalid UUID (vs a NIL UUID).
Full `go doc` style documentation for the package can be viewed online without Full `go doc` style documentation for the package can be viewed online without
installing this package by using the GoDoc site here: installing this package by using the GoDoc site here:
http://godoc.org/github.com/google/uuid http://pkg.go.dev/github.com/google/uuid

View File

@@ -26,8 +26,8 @@ var (
// NewMD5 and NewSHA1. // NewMD5 and NewSHA1.
func NewHash(h hash.Hash, space UUID, data []byte, version int) UUID { func NewHash(h hash.Hash, space UUID, data []byte, version int) UUID {
h.Reset() h.Reset()
h.Write(space[:]) h.Write(space[:]) //nolint:errcheck
h.Write(data) h.Write(data) //nolint:errcheck
s := h.Sum(nil) s := h.Sum(nil)
var uuid UUID var uuid UUID
copy(uuid[:], s) copy(uuid[:], s)

View File

@@ -16,10 +16,11 @@ func (uuid UUID) MarshalText() ([]byte, error) {
// UnmarshalText implements encoding.TextUnmarshaler. // UnmarshalText implements encoding.TextUnmarshaler.
func (uuid *UUID) UnmarshalText(data []byte) error { func (uuid *UUID) UnmarshalText(data []byte) error {
id, err := ParseBytes(data) id, err := ParseBytes(data)
if err == nil { if err != nil {
*uuid = id
}
return err return err
}
*uuid = id
return nil
} }
// MarshalBinary implements encoding.BinaryMarshaler. // MarshalBinary implements encoding.BinaryMarshaler.

118
vendor/github.com/google/uuid/null.go generated vendored Normal file
View File

@@ -0,0 +1,118 @@
// Copyright 2021 Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package uuid
import (
"bytes"
"database/sql/driver"
"encoding/json"
"fmt"
)
var jsonNull = []byte("null")
// NullUUID represents a UUID that may be null.
// NullUUID implements the SQL driver.Scanner interface so
// it can be used as a scan destination:
//
// var u uuid.NullUUID
// err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&u)
// ...
// if u.Valid {
// // use u.UUID
// } else {
// // NULL value
// }
//
type NullUUID struct {
UUID UUID
Valid bool // Valid is true if UUID is not NULL
}
// Scan implements the SQL driver.Scanner interface.
func (nu *NullUUID) Scan(value interface{}) error {
if value == nil {
nu.UUID, nu.Valid = Nil, false
return nil
}
err := nu.UUID.Scan(value)
if err != nil {
nu.Valid = false
return err
}
nu.Valid = true
return nil
}
// Value implements the driver Valuer interface.
func (nu NullUUID) Value() (driver.Value, error) {
if !nu.Valid {
return nil, nil
}
// Delegate to UUID Value function
return nu.UUID.Value()
}
// MarshalBinary implements encoding.BinaryMarshaler.
func (nu NullUUID) MarshalBinary() ([]byte, error) {
if nu.Valid {
return nu.UUID[:], nil
}
return []byte(nil), nil
}
// UnmarshalBinary implements encoding.BinaryUnmarshaler.
func (nu *NullUUID) UnmarshalBinary(data []byte) error {
if len(data) != 16 {
return fmt.Errorf("invalid UUID (got %d bytes)", len(data))
}
copy(nu.UUID[:], data)
nu.Valid = true
return nil
}
// MarshalText implements encoding.TextMarshaler.
func (nu NullUUID) MarshalText() ([]byte, error) {
if nu.Valid {
return nu.UUID.MarshalText()
}
return jsonNull, nil
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (nu *NullUUID) UnmarshalText(data []byte) error {
id, err := ParseBytes(data)
if err != nil {
nu.Valid = false
return err
}
nu.UUID = id
nu.Valid = true
return nil
}
// MarshalJSON implements json.Marshaler.
func (nu NullUUID) MarshalJSON() ([]byte, error) {
if nu.Valid {
return json.Marshal(nu.UUID)
}
return jsonNull, nil
}
// UnmarshalJSON implements json.Unmarshaler.
func (nu *NullUUID) UnmarshalJSON(data []byte) error {
if bytes.Equal(data, jsonNull) {
*nu = NullUUID{}
return nil // valid null UUID
}
err := json.Unmarshal(data, &nu.UUID)
nu.Valid = err == nil
return err
}

View File

@@ -9,7 +9,7 @@ import (
"fmt" "fmt"
) )
// Scan implements sql.Scanner so UUIDs can be read from databases transparently // Scan implements sql.Scanner so UUIDs can be read from databases transparently.
// Currently, database types that map to string and []byte are supported. Please // Currently, database types that map to string and []byte are supported. Please
// consult database-specific driver documentation for matching types. // consult database-specific driver documentation for matching types.
func (uuid *UUID) Scan(src interface{}) error { func (uuid *UUID) Scan(src interface{}) error {

View File

@@ -12,6 +12,7 @@ import (
"fmt" "fmt"
"io" "io"
"strings" "strings"
"sync"
) )
// A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC // A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC
@@ -33,7 +34,27 @@ const (
Future // Reserved for future definition. Future // Reserved for future definition.
) )
var rander = rand.Reader // random function const randPoolSize = 16 * 16
var (
rander = rand.Reader // random function
poolEnabled = false
poolMu sync.Mutex
poolPos = randPoolSize // protected with poolMu
pool [randPoolSize]byte // protected with poolMu
)
type invalidLengthError struct{ len int }
func (err invalidLengthError) Error() string {
return fmt.Sprintf("invalid UUID length: %d", err.len)
}
// IsInvalidLengthError is matcher function for custom error invalidLengthError
func IsInvalidLengthError(err error) bool {
_, ok := err.(invalidLengthError)
return ok
}
// Parse decodes s into a UUID or returns an error. Both the standard UUID // Parse decodes s into a UUID or returns an error. Both the standard UUID
// forms of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and // forms of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and
@@ -68,7 +89,7 @@ func Parse(s string) (UUID, error) {
} }
return uuid, nil return uuid, nil
default: default:
return uuid, fmt.Errorf("invalid UUID length: %d", len(s)) return uuid, invalidLengthError{len(s)}
} }
// s is now at least 36 bytes long // s is now at least 36 bytes long
// it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
@@ -112,7 +133,7 @@ func ParseBytes(b []byte) (UUID, error) {
} }
return uuid, nil return uuid, nil
default: default:
return uuid, fmt.Errorf("invalid UUID length: %d", len(b)) return uuid, invalidLengthError{len(b)}
} }
// s is now at least 36 bytes long // s is now at least 36 bytes long
// it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
@@ -243,3 +264,31 @@ func SetRand(r io.Reader) {
} }
rander = r rander = r
} }
// EnableRandPool enables internal randomness pool used for Random
// (Version 4) UUID generation. The pool contains random bytes read from
// the random number generator on demand in batches. Enabling the pool
// may improve the UUID generation throughput significantly.
//
// Since the pool is stored on the Go heap, this feature may be a bad fit
// for security sensitive applications.
//
// Both EnableRandPool and DisableRandPool are not thread-safe and should
// only be called when there is no possibility that New or any other
// UUID Version 4 generation function will be called concurrently.
func EnableRandPool() {
poolEnabled = true
}
// DisableRandPool disables the randomness pool if it was previously
// enabled with EnableRandPool.
//
// Both EnableRandPool and DisableRandPool are not thread-safe and should
// only be called when there is no possibility that New or any other
// UUID Version 4 generation function will be called concurrently.
func DisableRandPool() {
poolEnabled = false
defer poolMu.Unlock()
poolMu.Lock()
poolPos = randPoolSize
}

View File

@@ -17,12 +17,6 @@ import (
// //
// In most cases, New should be used. // In most cases, New should be used.
func NewUUID() (UUID, error) { func NewUUID() (UUID, error) {
nodeMu.Lock()
if nodeID == zeroID {
setNodeInterface("")
}
nodeMu.Unlock()
var uuid UUID var uuid UUID
now, seq, err := GetTime() now, seq, err := GetTime()
if err != nil { if err != nil {
@@ -38,7 +32,13 @@ func NewUUID() (UUID, error) {
binary.BigEndian.PutUint16(uuid[4:], timeMid) binary.BigEndian.PutUint16(uuid[4:], timeMid)
binary.BigEndian.PutUint16(uuid[6:], timeHi) binary.BigEndian.PutUint16(uuid[6:], timeHi)
binary.BigEndian.PutUint16(uuid[8:], seq) binary.BigEndian.PutUint16(uuid[8:], seq)
nodeMu.Lock()
if nodeID == zeroID {
setNodeInterface("")
}
copy(uuid[10:], nodeID[:]) copy(uuid[10:], nodeID[:])
nodeMu.Unlock()
return uuid, nil return uuid, nil
} }

View File

@@ -14,11 +14,21 @@ func New() UUID {
return Must(NewRandom()) return Must(NewRandom())
} }
// NewString creates a new random UUID and returns it as a string or panics.
// NewString is equivalent to the expression
//
// uuid.New().String()
func NewString() string {
return Must(NewRandom()).String()
}
// NewRandom returns a Random (Version 4) UUID. // NewRandom returns a Random (Version 4) UUID.
// //
// The strength of the UUIDs is based on the strength of the crypto/rand // The strength of the UUIDs is based on the strength of the crypto/rand
// package. // package.
// //
// Uses the randomness pool if it was enabled with EnableRandPool.
//
// A note about uniqueness derived from the UUID Wikipedia entry: // A note about uniqueness derived from the UUID Wikipedia entry:
// //
// Randomly generated UUIDs have 122 random bits. One's annual risk of being // Randomly generated UUIDs have 122 random bits. One's annual risk of being
@@ -27,8 +37,16 @@ func New() UUID {
// equivalent to the odds of creating a few tens of trillions of UUIDs in a // equivalent to the odds of creating a few tens of trillions of UUIDs in a
// year and having one duplicate. // year and having one duplicate.
func NewRandom() (UUID, error) { func NewRandom() (UUID, error) {
if !poolEnabled {
return NewRandomFromReader(rander)
}
return newRandomFromPool()
}
// NewRandomFromReader returns a UUID based on bytes read from a given io.Reader.
func NewRandomFromReader(r io.Reader) (UUID, error) {
var uuid UUID var uuid UUID
_, err := io.ReadFull(rander, uuid[:]) _, err := io.ReadFull(r, uuid[:])
if err != nil { if err != nil {
return Nil, err return Nil, err
} }
@@ -36,3 +54,23 @@ func NewRandom() (UUID, error) {
uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10 uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10
return uuid, nil return uuid, nil
} }
func newRandomFromPool() (UUID, error) {
var uuid UUID
poolMu.Lock()
if poolPos == randPoolSize {
_, err := io.ReadFull(rander, pool[:])
if err != nil {
poolMu.Unlock()
return Nil, err
}
poolPos = 0
}
copy(uuid[:], pool[poolPos:(poolPos+16)])
poolPos += 16
poolMu.Unlock()
uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4
uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10
return uuid, nil
}

789
vendor/github.com/hashicorp/hcl/hcl/printer/nodes.go generated vendored Normal file
View File

@@ -0,0 +1,789 @@
package printer
import (
"bytes"
"fmt"
"sort"
"github.com/hashicorp/hcl/hcl/ast"
"github.com/hashicorp/hcl/hcl/token"
)
const (
blank = byte(' ')
newline = byte('\n')
tab = byte('\t')
infinity = 1 << 30 // offset or line
)
var (
unindent = []byte("\uE123") // in the private use space
)
type printer struct {
cfg Config
prev token.Pos
comments []*ast.CommentGroup // may be nil, contains all comments
standaloneComments []*ast.CommentGroup // contains all standalone comments (not assigned to any node)
enableTrace bool
indentTrace int
}
type ByPosition []*ast.CommentGroup
func (b ByPosition) Len() int { return len(b) }
func (b ByPosition) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
func (b ByPosition) Less(i, j int) bool { return b[i].Pos().Before(b[j].Pos()) }
// collectComments comments all standalone comments which are not lead or line
// comment
func (p *printer) collectComments(node ast.Node) {
// first collect all comments. This is already stored in
// ast.File.(comments)
ast.Walk(node, func(nn ast.Node) (ast.Node, bool) {
switch t := nn.(type) {
case *ast.File:
p.comments = t.Comments
return nn, false
}
return nn, true
})
standaloneComments := make(map[token.Pos]*ast.CommentGroup, 0)
for _, c := range p.comments {
standaloneComments[c.Pos()] = c
}
// next remove all lead and line comments from the overall comment map.
// This will give us comments which are standalone, comments which are not
// assigned to any kind of node.
ast.Walk(node, func(nn ast.Node) (ast.Node, bool) {
switch t := nn.(type) {
case *ast.LiteralType:
if t.LeadComment != nil {
for _, comment := range t.LeadComment.List {
if _, ok := standaloneComments[comment.Pos()]; ok {
delete(standaloneComments, comment.Pos())
}
}
}
if t.LineComment != nil {
for _, comment := range t.LineComment.List {
if _, ok := standaloneComments[comment.Pos()]; ok {
delete(standaloneComments, comment.Pos())
}
}
}
case *ast.ObjectItem:
if t.LeadComment != nil {
for _, comment := range t.LeadComment.List {
if _, ok := standaloneComments[comment.Pos()]; ok {
delete(standaloneComments, comment.Pos())
}
}
}
if t.LineComment != nil {
for _, comment := range t.LineComment.List {
if _, ok := standaloneComments[comment.Pos()]; ok {
delete(standaloneComments, comment.Pos())
}
}
}
}
return nn, true
})
for _, c := range standaloneComments {
p.standaloneComments = append(p.standaloneComments, c)
}
sort.Sort(ByPosition(p.standaloneComments))
}
// output prints creates b printable HCL output and returns it.
func (p *printer) output(n interface{}) []byte {
var buf bytes.Buffer
switch t := n.(type) {
case *ast.File:
// File doesn't trace so we add the tracing here
defer un(trace(p, "File"))
return p.output(t.Node)
case *ast.ObjectList:
defer un(trace(p, "ObjectList"))
var index int
for {
// Determine the location of the next actual non-comment
// item. If we're at the end, the next item is at "infinity"
var nextItem token.Pos
if index != len(t.Items) {
nextItem = t.Items[index].Pos()
} else {
nextItem = token.Pos{Offset: infinity, Line: infinity}
}
// Go through the standalone comments in the file and print out
// the comments that we should be for this object item.
for _, c := range p.standaloneComments {
// Go through all the comments in the group. The group
// should be printed together, not separated by double newlines.
printed := false
newlinePrinted := false
for _, comment := range c.List {
// We only care about comments after the previous item
// we've printed so that comments are printed in the
// correct locations (between two objects for example).
// And before the next item.
if comment.Pos().After(p.prev) && comment.Pos().Before(nextItem) {
// if we hit the end add newlines so we can print the comment
// we don't do this if prev is invalid which means the
// beginning of the file since the first comment should
// be at the first line.
if !newlinePrinted && p.prev.IsValid() && index == len(t.Items) {
buf.Write([]byte{newline, newline})
newlinePrinted = true
}
// Write the actual comment.
buf.WriteString(comment.Text)
buf.WriteByte(newline)
// Set printed to true to note that we printed something
printed = true
}
}
// If we're not at the last item, write a new line so
// that there is a newline separating this comment from
// the next object.
if printed && index != len(t.Items) {
buf.WriteByte(newline)
}
}
if index == len(t.Items) {
break
}
buf.Write(p.output(t.Items[index]))
if index != len(t.Items)-1 {
// Always write a newline to separate us from the next item
buf.WriteByte(newline)
// Need to determine if we're going to separate the next item
// with a blank line. The logic here is simple, though there
// are a few conditions:
//
// 1. The next object is more than one line away anyways,
// so we need an empty line.
//
// 2. The next object is not a "single line" object, so
// we need an empty line.
//
// 3. This current object is not a single line object,
// so we need an empty line.
current := t.Items[index]
next := t.Items[index+1]
if next.Pos().Line != t.Items[index].Pos().Line+1 ||
!p.isSingleLineObject(next) ||
!p.isSingleLineObject(current) {
buf.WriteByte(newline)
}
}
index++
}
case *ast.ObjectKey:
buf.WriteString(t.Token.Text)
case *ast.ObjectItem:
p.prev = t.Pos()
buf.Write(p.objectItem(t))
case *ast.LiteralType:
buf.Write(p.literalType(t))
case *ast.ListType:
buf.Write(p.list(t))
case *ast.ObjectType:
buf.Write(p.objectType(t))
default:
fmt.Printf(" unknown type: %T\n", n)
}
return buf.Bytes()
}
func (p *printer) literalType(lit *ast.LiteralType) []byte {
result := []byte(lit.Token.Text)
switch lit.Token.Type {
case token.HEREDOC:
// Clear the trailing newline from heredocs
if result[len(result)-1] == '\n' {
result = result[:len(result)-1]
}
// Poison lines 2+ so that we don't indent them
result = p.heredocIndent(result)
case token.STRING:
// If this is a multiline string, poison lines 2+ so we don't
// indent them.
if bytes.IndexRune(result, '\n') >= 0 {
result = p.heredocIndent(result)
}
}
return result
}
// objectItem returns the printable HCL form of an object item. An object type
// starts with one/multiple keys and has a value. The value might be of any
// type.
func (p *printer) objectItem(o *ast.ObjectItem) []byte {
defer un(trace(p, fmt.Sprintf("ObjectItem: %s", o.Keys[0].Token.Text)))
var buf bytes.Buffer
if o.LeadComment != nil {
for _, comment := range o.LeadComment.List {
buf.WriteString(comment.Text)
buf.WriteByte(newline)
}
}
// If key and val are on different lines, treat line comments like lead comments.
if o.LineComment != nil && o.Val.Pos().Line != o.Keys[0].Pos().Line {
for _, comment := range o.LineComment.List {
buf.WriteString(comment.Text)
buf.WriteByte(newline)
}
}
for i, k := range o.Keys {
buf.WriteString(k.Token.Text)
buf.WriteByte(blank)
// reach end of key
if o.Assign.IsValid() && i == len(o.Keys)-1 && len(o.Keys) == 1 {
buf.WriteString("=")
buf.WriteByte(blank)
}
}
buf.Write(p.output(o.Val))
if o.LineComment != nil && o.Val.Pos().Line == o.Keys[0].Pos().Line {
buf.WriteByte(blank)
for _, comment := range o.LineComment.List {
buf.WriteString(comment.Text)
}
}
return buf.Bytes()
}
// objectType returns the printable HCL form of an object type. An object type
// begins with a brace and ends with a brace.
func (p *printer) objectType(o *ast.ObjectType) []byte {
defer un(trace(p, "ObjectType"))
var buf bytes.Buffer
buf.WriteString("{")
var index int
var nextItem token.Pos
var commented, newlinePrinted bool
for {
// Determine the location of the next actual non-comment
// item. If we're at the end, the next item is the closing brace
if index != len(o.List.Items) {
nextItem = o.List.Items[index].Pos()
} else {
nextItem = o.Rbrace
}
// Go through the standalone comments in the file and print out
// the comments that we should be for this object item.
for _, c := range p.standaloneComments {
printed := false
var lastCommentPos token.Pos
for _, comment := range c.List {
// We only care about comments after the previous item
// we've printed so that comments are printed in the
// correct locations (between two objects for example).
// And before the next item.
if comment.Pos().After(p.prev) && comment.Pos().Before(nextItem) {
// If there are standalone comments and the initial newline has not
// been printed yet, do it now.
if !newlinePrinted {
newlinePrinted = true
buf.WriteByte(newline)
}
// add newline if it's between other printed nodes
if index > 0 {
commented = true
buf.WriteByte(newline)
}
// Store this position
lastCommentPos = comment.Pos()
// output the comment itself
buf.Write(p.indent(p.heredocIndent([]byte(comment.Text))))
// Set printed to true to note that we printed something
printed = true
/*
if index != len(o.List.Items) {
buf.WriteByte(newline) // do not print on the end
}
*/
}
}
// Stuff to do if we had comments
if printed {
// Always write a newline
buf.WriteByte(newline)
// If there is another item in the object and our comment
// didn't hug it directly, then make sure there is a blank
// line separating them.
if nextItem != o.Rbrace && nextItem.Line != lastCommentPos.Line+1 {
buf.WriteByte(newline)
}
}
}
if index == len(o.List.Items) {
p.prev = o.Rbrace
break
}
// At this point we are sure that it's not a totally empty block: print
// the initial newline if it hasn't been printed yet by the previous
// block about standalone comments.
if !newlinePrinted {
buf.WriteByte(newline)
newlinePrinted = true
}
// check if we have adjacent one liner items. If yes we'll going to align
// the comments.
var aligned []*ast.ObjectItem
for _, item := range o.List.Items[index:] {
// we don't group one line lists
if len(o.List.Items) == 1 {
break
}
// one means a oneliner with out any lead comment
// two means a oneliner with lead comment
// anything else might be something else
cur := lines(string(p.objectItem(item)))
if cur > 2 {
break
}
curPos := item.Pos()
nextPos := token.Pos{}
if index != len(o.List.Items)-1 {
nextPos = o.List.Items[index+1].Pos()
}
prevPos := token.Pos{}
if index != 0 {
prevPos = o.List.Items[index-1].Pos()
}
// fmt.Println("DEBUG ----------------")
// fmt.Printf("prev = %+v prevPos: %s\n", prev, prevPos)
// fmt.Printf("cur = %+v curPos: %s\n", cur, curPos)
// fmt.Printf("next = %+v nextPos: %s\n", next, nextPos)
if curPos.Line+1 == nextPos.Line {
aligned = append(aligned, item)
index++
continue
}
if curPos.Line-1 == prevPos.Line {
aligned = append(aligned, item)
index++
// finish if we have a new line or comment next. This happens
// if the next item is not adjacent
if curPos.Line+1 != nextPos.Line {
break
}
continue
}
break
}
// put newlines if the items are between other non aligned items.
// newlines are also added if there is a standalone comment already, so
// check it too
if !commented && index != len(aligned) {
buf.WriteByte(newline)
}
if len(aligned) >= 1 {
p.prev = aligned[len(aligned)-1].Pos()
items := p.alignedItems(aligned)
buf.Write(p.indent(items))
} else {
p.prev = o.List.Items[index].Pos()
buf.Write(p.indent(p.objectItem(o.List.Items[index])))
index++
}
buf.WriteByte(newline)
}
buf.WriteString("}")
return buf.Bytes()
}
func (p *printer) alignedItems(items []*ast.ObjectItem) []byte {
var buf bytes.Buffer
// find the longest key and value length, needed for alignment
var longestKeyLen int // longest key length
var longestValLen int // longest value length
for _, item := range items {
key := len(item.Keys[0].Token.Text)
val := len(p.output(item.Val))
if key > longestKeyLen {
longestKeyLen = key
}
if val > longestValLen {
longestValLen = val
}
}
for i, item := range items {
if item.LeadComment != nil {
for _, comment := range item.LeadComment.List {
buf.WriteString(comment.Text)
buf.WriteByte(newline)
}
}
for i, k := range item.Keys {
keyLen := len(k.Token.Text)
buf.WriteString(k.Token.Text)
for i := 0; i < longestKeyLen-keyLen+1; i++ {
buf.WriteByte(blank)
}
// reach end of key
if i == len(item.Keys)-1 && len(item.Keys) == 1 {
buf.WriteString("=")
buf.WriteByte(blank)
}
}
val := p.output(item.Val)
valLen := len(val)
buf.Write(val)
if item.Val.Pos().Line == item.Keys[0].Pos().Line && item.LineComment != nil {
for i := 0; i < longestValLen-valLen+1; i++ {
buf.WriteByte(blank)
}
for _, comment := range item.LineComment.List {
buf.WriteString(comment.Text)
}
}
// do not print for the last item
if i != len(items)-1 {
buf.WriteByte(newline)
}
}
return buf.Bytes()
}
// list returns the printable HCL form of an list type.
func (p *printer) list(l *ast.ListType) []byte {
if p.isSingleLineList(l) {
return p.singleLineList(l)
}
var buf bytes.Buffer
buf.WriteString("[")
buf.WriteByte(newline)
var longestLine int
for _, item := range l.List {
// for now we assume that the list only contains literal types
if lit, ok := item.(*ast.LiteralType); ok {
lineLen := len(lit.Token.Text)
if lineLen > longestLine {
longestLine = lineLen
}
}
}
haveEmptyLine := false
for i, item := range l.List {
// If we have a lead comment, then we want to write that first
leadComment := false
if lit, ok := item.(*ast.LiteralType); ok && lit.LeadComment != nil {
leadComment = true
// Ensure an empty line before every element with a
// lead comment (except the first item in a list).
if !haveEmptyLine && i != 0 {
buf.WriteByte(newline)
}
for _, comment := range lit.LeadComment.List {
buf.Write(p.indent([]byte(comment.Text)))
buf.WriteByte(newline)
}
}
// also indent each line
val := p.output(item)
curLen := len(val)
buf.Write(p.indent(val))
// if this item is a heredoc, then we output the comma on
// the next line. This is the only case this happens.
comma := []byte{','}
if lit, ok := item.(*ast.LiteralType); ok && lit.Token.Type == token.HEREDOC {
buf.WriteByte(newline)
comma = p.indent(comma)
}
buf.Write(comma)
if lit, ok := item.(*ast.LiteralType); ok && lit.LineComment != nil {
// if the next item doesn't have any comments, do not align
buf.WriteByte(blank) // align one space
for i := 0; i < longestLine-curLen; i++ {
buf.WriteByte(blank)
}
for _, comment := range lit.LineComment.List {
buf.WriteString(comment.Text)
}
}
buf.WriteByte(newline)
// Ensure an empty line after every element with a
// lead comment (except the first item in a list).
haveEmptyLine = leadComment && i != len(l.List)-1
if haveEmptyLine {
buf.WriteByte(newline)
}
}
buf.WriteString("]")
return buf.Bytes()
}
// isSingleLineList returns true if:
// * they were previously formatted entirely on one line
// * they consist entirely of literals
// * there are either no heredoc strings or the list has exactly one element
// * there are no line comments
func (printer) isSingleLineList(l *ast.ListType) bool {
for _, item := range l.List {
if item.Pos().Line != l.Lbrack.Line {
return false
}
lit, ok := item.(*ast.LiteralType)
if !ok {
return false
}
if lit.Token.Type == token.HEREDOC && len(l.List) != 1 {
return false
}
if lit.LineComment != nil {
return false
}
}
return true
}
// singleLineList prints a simple single line list.
// For a definition of "simple", see isSingleLineList above.
func (p *printer) singleLineList(l *ast.ListType) []byte {
buf := &bytes.Buffer{}
buf.WriteString("[")
for i, item := range l.List {
if i != 0 {
buf.WriteString(", ")
}
// Output the item itself
buf.Write(p.output(item))
// The heredoc marker needs to be at the end of line.
if lit, ok := item.(*ast.LiteralType); ok && lit.Token.Type == token.HEREDOC {
buf.WriteByte(newline)
}
}
buf.WriteString("]")
return buf.Bytes()
}
// indent indents the lines of the given buffer for each non-empty line
func (p *printer) indent(buf []byte) []byte {
var prefix []byte
if p.cfg.SpacesWidth != 0 {
for i := 0; i < p.cfg.SpacesWidth; i++ {
prefix = append(prefix, blank)
}
} else {
prefix = []byte{tab}
}
var res []byte
bol := true
for _, c := range buf {
if bol && c != '\n' {
res = append(res, prefix...)
}
res = append(res, c)
bol = c == '\n'
}
return res
}
// unindent removes all the indentation from the tombstoned lines
func (p *printer) unindent(buf []byte) []byte {
var res []byte
for i := 0; i < len(buf); i++ {
skip := len(buf)-i <= len(unindent)
if !skip {
skip = !bytes.Equal(unindent, buf[i:i+len(unindent)])
}
if skip {
res = append(res, buf[i])
continue
}
// We have a marker. we have to backtrace here and clean out
// any whitespace ahead of our tombstone up to a \n
for j := len(res) - 1; j >= 0; j-- {
if res[j] == '\n' {
break
}
res = res[:j]
}
// Skip the entire unindent marker
i += len(unindent) - 1
}
return res
}
// heredocIndent marks all the 2nd and further lines as unindentable
func (p *printer) heredocIndent(buf []byte) []byte {
var res []byte
bol := false
for _, c := range buf {
if bol && c != '\n' {
res = append(res, unindent...)
}
res = append(res, c)
bol = c == '\n'
}
return res
}
// isSingleLineObject tells whether the given object item is a single
// line object such as "obj {}".
//
// A single line object:
//
// * has no lead comments (hence multi-line)
// * has no assignment
// * has no values in the stanza (within {})
//
func (p *printer) isSingleLineObject(val *ast.ObjectItem) bool {
// If there is a lead comment, can't be one line
if val.LeadComment != nil {
return false
}
// If there is assignment, we always break by line
if val.Assign.IsValid() {
return false
}
// If it isn't an object type, then its not a single line object
ot, ok := val.Val.(*ast.ObjectType)
if !ok {
return false
}
// If the object has no items, it is single line!
return len(ot.List.Items) == 0
}
func lines(txt string) int {
endline := 1
for i := 0; i < len(txt); i++ {
if txt[i] == '\n' {
endline++
}
}
return endline
}
// ----------------------------------------------------------------------------
// Tracing support
func (p *printer) printTrace(a ...interface{}) {
if !p.enableTrace {
return
}
const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
const n = len(dots)
i := 2 * p.indentTrace
for i > n {
fmt.Print(dots)
i -= n
}
// i <= n
fmt.Print(dots[0:i])
fmt.Println(a...)
}
func trace(p *printer, msg string) *printer {
p.printTrace(msg, "(")
p.indentTrace++
return p
}
// Usage pattern: defer un(trace(p, "..."))
func un(p *printer) {
p.indentTrace--
p.printTrace(")")
}

66
vendor/github.com/hashicorp/hcl/hcl/printer/printer.go generated vendored Normal file
View File

@@ -0,0 +1,66 @@
// Package printer implements printing of AST nodes to HCL format.
package printer
import (
"bytes"
"io"
"text/tabwriter"
"github.com/hashicorp/hcl/hcl/ast"
"github.com/hashicorp/hcl/hcl/parser"
)
var DefaultConfig = Config{
SpacesWidth: 2,
}
// A Config node controls the output of Fprint.
type Config struct {
SpacesWidth int // if set, it will use spaces instead of tabs for alignment
}
func (c *Config) Fprint(output io.Writer, node ast.Node) error {
p := &printer{
cfg: *c,
comments: make([]*ast.CommentGroup, 0),
standaloneComments: make([]*ast.CommentGroup, 0),
// enableTrace: true,
}
p.collectComments(node)
if _, err := output.Write(p.unindent(p.output(node))); err != nil {
return err
}
// flush tabwriter, if any
var err error
if tw, _ := output.(*tabwriter.Writer); tw != nil {
err = tw.Flush()
}
return err
}
// Fprint "pretty-prints" an HCL node to output
// It calls Config.Fprint with default settings.
func Fprint(output io.Writer, node ast.Node) error {
return DefaultConfig.Fprint(output, node)
}
// Format formats src HCL and returns the result.
func Format(src []byte) ([]byte, error) {
node, err := parser.Parse(src)
if err != nil {
return nil, err
}
var buf bytes.Buffer
if err := DefaultConfig.Fprint(&buf, node); err != nil {
return nil, err
}
// Add trailing newline to result
buf.WriteString("\n")
return buf.Bytes(), nil
}

View File

@@ -1,3 +1,10 @@
## 1.4.0 (2019/11/02)
- Add Net.WalkPrefix [#10](https://github.com/k-sone/critbitgo/pull/10)
- Add Net.WalkMatch [#11](https://github.com/k-sone/critbitgo/pull/11)
- Fix Allprefixed [#12](https://github.com/k-sone/critbitgo/pull/12)
- Make Walk API handle empty trie [#13](https://github.com/k-sone/critbitgo/pull/13)
## 1.3.0 (2019/09/30) ## 1.3.0 (2019/09/30)
- Add Net.Walk [#9](https://github.com/k-sone/critbitgo/pull/9) - Add Net.Walk [#9](https://github.com/k-sone/critbitgo/pull/9)

View File

@@ -1,9 +0,0 @@
(The MIT License)
Copyright (c) 2017 marvin + konsorten GmbH (open-source@konsorten.de)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -1,40 +0,0 @@
# Windows Terminal Sequences
This library allow for enabling Windows terminal color support for Go.
See [Console Virtual Terminal Sequences](https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences) for details.
## Usage
```go
import (
"syscall"
sequences "github.com/konsorten/go-windows-terminal-sequences"
)
func main() {
sequences.EnableVirtualTerminalProcessing(syscall.Stdout, true)
}
```
## Authors
The tool is sponsored by the [marvin + konsorten GmbH](http://www.konsorten.de).
We thank all the authors who provided code to this library:
* Felix Kollmann
## License
(The MIT License)
Copyright (c) 2018 marvin + konsorten GmbH (open-source@konsorten.de)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -1 +0,0 @@
module github.com/konsorten/go-windows-terminal-sequences

View File

@@ -1,36 +0,0 @@
// +build windows
package sequences
import (
"syscall"
"unsafe"
)
var (
kernel32Dll *syscall.LazyDLL = syscall.NewLazyDLL("Kernel32.dll")
setConsoleMode *syscall.LazyProc = kernel32Dll.NewProc("SetConsoleMode")
)
func EnableVirtualTerminalProcessing(stream syscall.Handle, enable bool) error {
const ENABLE_VIRTUAL_TERMINAL_PROCESSING uint32 = 0x4
var mode uint32
err := syscall.GetConsoleMode(syscall.Stdout, &mode)
if err != nil {
return err
}
if enable {
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING
} else {
mode &^= ENABLE_VIRTUAL_TERMINAL_PROCESSING
}
ret, _, err := setConsoleMode.Call(uintptr(unsafe.Pointer(stream)), uintptr(mode))
if ret == 0 {
return err
}
return nil
}

View File

@@ -7,4 +7,6 @@ go:
- 1.8.x - 1.8.x
- 1.9.x - 1.9.x
- "1.10.x" - "1.10.x"
- "1.11.x"
- "1.12.x"
- tip - tip

View File

@@ -1,5 +1,13 @@
## Changelog ## Changelog
### [1.8.1](https://github.com/magiconair/properties/tree/v1.8.1) - 10 May 2019
* [PR #26](https://github.com/magiconair/properties/pull/35): Close body always after request
This patch ensures that in `LoadURL` the response body is always closed.
Thanks to [@liubog2008](https://github.com/liubog2008) for the patch.
### [1.8](https://github.com/magiconair/properties/tree/v1.8) - 15 May 2018 ### [1.8](https://github.com/magiconair/properties/tree/v1.8) - 15 May 2018
* [PR #26](https://github.com/magiconair/properties/pull/26): Disable expansion during loading * [PR #26](https://github.com/magiconair/properties/pull/26): Disable expansion during loading

View File

@@ -1,6 +1,6 @@
[![](https://img.shields.io/github/tag/magiconair/properties.svg?style=flat-square&label=release)](https://github.com/magiconair/properties/releases) [![](https://img.shields.io/github/tag/magiconair/properties.svg?style=flat-square&label=release)](https://github.com/magiconair/properties/releases)
[![Travis CI Status](https://img.shields.io/travis/magiconair/properties.svg?branch=master&style=flat-square&label=travis)](https://travis-ci.org/magiconair/properties) [![Travis CI Status](https://img.shields.io/travis/magiconair/properties.svg?branch=master&style=flat-square&label=travis)](https://travis-ci.org/magiconair/properties)
[![Codeship CI Status](https://img.shields.io/codeship/16aaf660-f615-0135-b8f0-7e33b70920c0/master.svg?label=codeship&style=flat-square)](https://app.codeship.com/projects/274177") [![CircleCI Status](https://img.shields.io/circleci/project/github/magiconair/properties.svg?label=circle+ci&style=flat-square)](https://circleci.com/gh/magiconair/properties)
[![License](https://img.shields.io/badge/License-BSD%202--Clause-orange.svg?style=flat-square)](https://raw.githubusercontent.com/magiconair/properties/master/LICENSE) [![License](https://img.shields.io/badge/License-BSD%202--Clause-orange.svg?style=flat-square)](https://raw.githubusercontent.com/magiconair/properties/master/LICENSE)
[![GoDoc](http://img.shields.io/badge/godoc-reference-5272B4.svg?style=flat-square)](http://godoc.org/github.com/magiconair/properties) [![GoDoc](http://img.shields.io/badge/godoc-reference-5272B4.svg?style=flat-square)](http://godoc.org/github.com/magiconair/properties)
@@ -30,7 +30,7 @@ changed from `panic` to `log.Fatal` but this is configurable and custom
error handling functions can be provided. See the package documentation for error handling functions can be provided. See the package documentation for
details. details.
Read the full documentation on [GoDoc](https://godoc.org/github.com/magiconair/properties) [![GoDoc](https://godoc.org/github.com/magiconair/properties?status.png)](https://godoc.org/github.com/magiconair/properties) Read the full documentation on [![GoDoc](http://img.shields.io/badge/godoc-reference-5272B4.svg?style=flat-square)](http://godoc.org/github.com/magiconair/properties)
## Getting Started ## Getting Started

1
vendor/github.com/magiconair/properties/go.mod generated vendored Normal file
View File

@@ -0,0 +1 @@
module github.com/magiconair/properties

View File

@@ -115,6 +115,7 @@ func (l *Loader) LoadURL(url string) (*Properties, error) {
if err != nil { if err != nil {
return nil, fmt.Errorf("properties: error fetching %q. %s", url, err) return nil, fmt.Errorf("properties: error fetching %q. %s", url, err)
} }
defer resp.Body.Close()
if resp.StatusCode == 404 && l.IgnoreMissing { if resp.StatusCode == 404 && l.IgnoreMissing {
LogPrintf("properties: %s returned %d. skipping", url, resp.StatusCode) LogPrintf("properties: %s returned %d. skipping", url, resp.StatusCode)
@@ -129,7 +130,6 @@ func (l *Loader) LoadURL(url string) (*Properties, error) {
if err != nil { if err != nil {
return nil, fmt.Errorf("properties: %s error reading response. %s", url, err) return nil, fmt.Errorf("properties: %s error reading response. %s", url, err)
} }
defer resp.Body.Close()
ct := resp.Header.Get("Content-Type") ct := resp.Header.Get("Content-Type")
var enc Encoding var enc Encoding

File diff suppressed because it is too large Load Diff

View File

@@ -176,6 +176,26 @@ message EVPNIPMSIRoute {
google.protobuf.Any rt = 3; google.protobuf.Any rt = 3;
} }
// SRPolicyNLRI represents the NLRI for:
// - AFI=1, SAFI=73
// - AFI=2, SAFI=73
message SRPolicyNLRI {
// length field carries the length of NLRI portion expressed in bits
uint32 length = 1;
// distinguisher field carries 4-octet value uniquely identifying the policy
// in the context of <color, endpoint> tuple.
uint32 distinguisher = 2;
// color field carries 4-octet value identifying (with the endpoint) the
// policy. The color is used to match the color of the destination
// prefixes to steer traffic into the SR Policy
uint32 color = 3;
// endpoint field identifies the endpoint of a policy. The Endpoint may
// represent a single node or a set of nodes (e.g., an anycast
// address). The Endpoint is an IPv4 (4-octet) address or an IPv6
// (16-octet) address according to the AFI of the NLRI.
bytes endpoint = 4;
}
// LabeledVPNIPAddressPrefix represents the NLRI for: // LabeledVPNIPAddressPrefix represents the NLRI for:
// - AFI=1, SAFI=128 // - AFI=1, SAFI=128
// - AFI=2, SAFI=128 // - AFI=2, SAFI=128
@@ -302,13 +322,19 @@ message LsPrefixV6NLRI {
// Based om RFC 7752, Table 1. // Based om RFC 7752, Table 1.
enum LsNLRIType { enum LsNLRIType {
LS_NLRI_UNKNOWN = 0; LS_NLRI_UNKNOWN = 0; LS_NLRI_NODE = 1; LS_NLRI_LINK = 2;
LS_NLRI_NODE = 1;
LS_NLRI_LINK = 2;
LS_NLRI_PREFIX_V4 = 3; LS_NLRI_PREFIX_V4 = 3;
LS_NLRI_PREFIX_V6 = 4; LS_NLRI_PREFIX_V6 = 4;
} }
enum LsProtocolID {
LS_PROTOCOL_UNKNOWN = 0; LS_PROTOCOL_ISIS_L1 = 1; LS_PROTOCOL_ISIS_L2 = 2;
LS_PROTOCOL_OSPF_V2 = 3;
LS_PROTOCOL_DIRECT = 4;
LS_PROTOCOL_STATIC = 5;
LS_PROTOCOL_OSPF_V3 = 6;
}
// LsAddrPrefix represents the NLRI for: // LsAddrPrefix represents the NLRI for:
// - AFI=16388, SAFI=71 // - AFI=16388, SAFI=71
message LsAddrPrefix { message LsAddrPrefix {
@@ -319,6 +345,9 @@ message LsAddrPrefix {
// - LsPrefixV4NLRI // - LsPrefixV4NLRI
// - LsPrefixV6NLRI // - LsPrefixV6NLRI
google.protobuf.Any nlri = 2; google.protobuf.Any nlri = 2;
uint32 length = 3;
LsProtocolID protocol_id = 4;
uint64 identifier = 5;
} }
message MpReachNLRIAttribute { message MpReachNLRIAttribute {
@@ -340,6 +369,7 @@ message MpReachNLRIAttribute {
// - VPNFlowSpecNLRI // - VPNFlowSpecNLRI
// - OpaqueNLRI // - OpaqueNLRI
// - LsAddrPrefix // - LsAddrPrefix
// - SR Policy NLRI
repeated google.protobuf.Any nlris = 3; repeated google.protobuf.Any nlris = 3;
} }
@@ -370,6 +400,11 @@ message FourOctetAsSpecificExtended {
uint32 local_admin = 4; uint32 local_admin = 4;
} }
message LinkBandiwdthExtended {
uint32 as = 1;
float bandwidth = 2;
}
message ValidationExtended { uint32 state = 1; } message ValidationExtended { uint32 state = 1; }
message ColorExtended { uint32 color = 1; } message ColorExtended { uint32 color = 1; }
@@ -471,6 +506,127 @@ message TunnelEncapSubTLVProtocol { uint32 protocol = 1; }
message TunnelEncapSubTLVColor { uint32 color = 1; } message TunnelEncapSubTLVColor { uint32 color = 1; }
message TunnelEncapSubTLVSRPreference {
uint32 flags = 1;
uint32 preference = 2;
}
message TunnelEncapSubTLVSRCandidatePathName { string candidate_path_name = 1; }
message TunnelEncapSubTLVSRPriority { uint32 priority = 1; }
message TunnelEncapSubTLVSRBindingSID {
// bsid must be one of:
// - SRBindingSID
// - SRv6BindingSID
google.protobuf.Any bsid = 1;
}
message SRBindingSID {
bool s_flag = 1;
bool i_flag = 2;
bytes sid = 3;
}
enum SRv6Behavior {
RESERVED = 0; END = 1; END_WITH_PSP = 2; END_WITH_USP = 3;
END_WITH_PSP_USP = 4;
ENDX = 5;
ENDX_WITH_PSP = 6;
ENDX_WITH_USP = 7;
ENDX_WITH_PSP_USP = 8;
ENDT = 9;
ENDT_WITH_PSP = 10;
ENDT_WITH_USP = 11;
ENDT_WITH_PSP_USP = 12;
END_B6_ENCAPS = 14;
END_BM = 15;
END_DX6 = 16;
END_DX4 = 17;
END_DT6 = 18;
END_DT4 = 19;
END_DT46 = 20;
END_DX2 = 21;
END_DX2V = 22;
END_DT2U = 23;
END_DT2M = 24;
END_B6_ENCAPS_Red = 27;
END_WITH_USD = 28;
END_WITH_PSP_USD = 29;
END_WITH_USP_USD = 30;
END_WITH_PSP_USP_USD = 31;
ENDX_WITH_USD = 32;
ENDX_WITH_PSP_USD = 33;
ENDX_WITH_USP_USD = 34;
ENDX_WITH_PSP_USP_USD = 35;
ENDT_WITH_USD = 36;
ENDT_WITH_PSP_USD = 37;
ENDT_WITH_USP_USD = 38;
ENDT_WITH_PSP_USP_USD = 39;
}
message SRv6EndPointBehavior {
SRv6Behavior behavior = 1;
uint32 block_len = 2;
uint32 node_len = 3;
uint32 func_len = 4;
uint32 arg_len = 5;
}
message SRv6BindingSID {
bool s_flag = 1;
bool i_flag = 2;
bool b_flag = 3;
bytes sid = 4;
SRv6EndPointBehavior endpoint_behavior_structure = 5;
}
enum ENLPType { Reserved = 0; Type1 = 1; Type2 = 2; Type3 = 3; Type4 = 4; }
message TunnelEncapSubTLVSRENLP {
uint32 flags = 1;
ENLPType enlp = 2;
}
message SRWeight {
uint32 flags = 1;
uint32 weight = 2;
}
message SegmentFlags {
bool v_flag = 1;
bool a_flag = 2;
bool s_flag = 3;
bool b_flag = 4;
}
message SegmentTypeA {
SegmentFlags flags = 1;
uint32 label = 2;
}
message SegmentTypeB {
SegmentFlags flags = 1;
bytes sid = 2;
SRv6EndPointBehavior endpoint_behavior_structure = 3;
}
message TunnelEncapSubTLVSRSegmentList {
SRWeight weight = 1;
// segments must be one of:
// - SegmentTypeA
// - SegmentTypeB
repeated google.protobuf.Any segments = 2;
}
message TunnelEncapSubTLVEgressEndpoint {
string address = 1;
}
message TunnelEncapSubTLVUDPDestPort {
uint32 port = 1;
}
message TunnelEncapSubTLVUnknown { message TunnelEncapSubTLVUnknown {
uint32 type = 1; uint32 type = 1;
bytes value = 2; bytes value = 2;
@@ -482,6 +638,7 @@ message TunnelEncapTLV {
// - TunnelEncapSubTLVEncapsulation // - TunnelEncapSubTLVEncapsulation
// - TunnelEncapSubTLVProtocol // - TunnelEncapSubTLVProtocol
// - TunnelEncapSubTLVColor // - TunnelEncapSubTLVColor
// - TunnelEncapSubTLVSRPolicy
// - TunnelEncapSubTLVUnknown // - TunnelEncapSubTLVUnknown
repeated google.protobuf.Any tlvs = 2; repeated google.protobuf.Any tlvs = 2;
} }

View File

@@ -3,15 +3,23 @@
package gobgpapi package gobgpapi
import proto "github.com/golang/protobuf/proto" import (
import fmt "fmt" fmt "fmt"
import math "math" proto "github.com/golang/protobuf/proto"
math "math"
)
// Reference imports to suppress errors if they are not otherwise used. // Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal var _ = proto.Marshal
var _ = fmt.Errorf var _ = fmt.Errorf
var _ = math.Inf var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
type AddPathMode int32 type AddPathMode int32
const ( const (
@@ -27,6 +35,7 @@ var AddPathMode_name = map[int32]string{
2: "MODE_SEND", 2: "MODE_SEND",
3: "MODE_BOTH", 3: "MODE_BOTH",
} }
var AddPathMode_value = map[string]int32{ var AddPathMode_value = map[string]int32{
"MODE_NONE": 0, "MODE_NONE": 0,
"MODE_RECEIVE": 1, "MODE_RECEIVE": 1,
@@ -37,16 +46,42 @@ var AddPathMode_value = map[string]int32{
func (x AddPathMode) String() string { func (x AddPathMode) String() string {
return proto.EnumName(AddPathMode_name, int32(x)) return proto.EnumName(AddPathMode_name, int32(x))
} }
func (AddPathMode) EnumDescriptor() ([]byte, []int) { return fileDescriptor1, []int{0} }
func (AddPathMode) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_f2310f95efbbe3ac, []int{0}
}
type MultiProtocolCapability struct { type MultiProtocolCapability struct {
Family *Family `protobuf:"bytes,1,opt,name=family" json:"family,omitempty"` Family *Family `protobuf:"bytes,1,opt,name=family,proto3" json:"family,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
} }
func (m *MultiProtocolCapability) Reset() { *m = MultiProtocolCapability{} } func (m *MultiProtocolCapability) Reset() { *m = MultiProtocolCapability{} }
func (m *MultiProtocolCapability) String() string { return proto.CompactTextString(m) } func (m *MultiProtocolCapability) String() string { return proto.CompactTextString(m) }
func (*MultiProtocolCapability) ProtoMessage() {} func (*MultiProtocolCapability) ProtoMessage() {}
func (*MultiProtocolCapability) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{0} } func (*MultiProtocolCapability) Descriptor() ([]byte, []int) {
return fileDescriptor_f2310f95efbbe3ac, []int{0}
}
func (m *MultiProtocolCapability) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_MultiProtocolCapability.Unmarshal(m, b)
}
func (m *MultiProtocolCapability) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_MultiProtocolCapability.Marshal(b, m, deterministic)
}
func (m *MultiProtocolCapability) XXX_Merge(src proto.Message) {
xxx_messageInfo_MultiProtocolCapability.Merge(m, src)
}
func (m *MultiProtocolCapability) XXX_Size() int {
return xxx_messageInfo_MultiProtocolCapability.Size(m)
}
func (m *MultiProtocolCapability) XXX_DiscardUnknown() {
xxx_messageInfo_MultiProtocolCapability.DiscardUnknown(m)
}
var xxx_messageInfo_MultiProtocolCapability proto.InternalMessageInfo
func (m *MultiProtocolCapability) GetFamily() *Family { func (m *MultiProtocolCapability) GetFamily() *Family {
if m != nil { if m != nil {
@@ -56,33 +91,102 @@ func (m *MultiProtocolCapability) GetFamily() *Family {
} }
type RouteRefreshCapability struct { type RouteRefreshCapability struct {
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
} }
func (m *RouteRefreshCapability) Reset() { *m = RouteRefreshCapability{} } func (m *RouteRefreshCapability) Reset() { *m = RouteRefreshCapability{} }
func (m *RouteRefreshCapability) String() string { return proto.CompactTextString(m) } func (m *RouteRefreshCapability) String() string { return proto.CompactTextString(m) }
func (*RouteRefreshCapability) ProtoMessage() {} func (*RouteRefreshCapability) ProtoMessage() {}
func (*RouteRefreshCapability) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{1} } func (*RouteRefreshCapability) Descriptor() ([]byte, []int) {
return fileDescriptor_f2310f95efbbe3ac, []int{1}
}
func (m *RouteRefreshCapability) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_RouteRefreshCapability.Unmarshal(m, b)
}
func (m *RouteRefreshCapability) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_RouteRefreshCapability.Marshal(b, m, deterministic)
}
func (m *RouteRefreshCapability) XXX_Merge(src proto.Message) {
xxx_messageInfo_RouteRefreshCapability.Merge(m, src)
}
func (m *RouteRefreshCapability) XXX_Size() int {
return xxx_messageInfo_RouteRefreshCapability.Size(m)
}
func (m *RouteRefreshCapability) XXX_DiscardUnknown() {
xxx_messageInfo_RouteRefreshCapability.DiscardUnknown(m)
}
var xxx_messageInfo_RouteRefreshCapability proto.InternalMessageInfo
type CarryingLabelInfoCapability struct { type CarryingLabelInfoCapability struct {
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
} }
func (m *CarryingLabelInfoCapability) Reset() { *m = CarryingLabelInfoCapability{} } func (m *CarryingLabelInfoCapability) Reset() { *m = CarryingLabelInfoCapability{} }
func (m *CarryingLabelInfoCapability) String() string { return proto.CompactTextString(m) } func (m *CarryingLabelInfoCapability) String() string { return proto.CompactTextString(m) }
func (*CarryingLabelInfoCapability) ProtoMessage() {} func (*CarryingLabelInfoCapability) ProtoMessage() {}
func (*CarryingLabelInfoCapability) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{2} } func (*CarryingLabelInfoCapability) Descriptor() ([]byte, []int) {
return fileDescriptor_f2310f95efbbe3ac, []int{2}
}
func (m *CarryingLabelInfoCapability) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_CarryingLabelInfoCapability.Unmarshal(m, b)
}
func (m *CarryingLabelInfoCapability) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_CarryingLabelInfoCapability.Marshal(b, m, deterministic)
}
func (m *CarryingLabelInfoCapability) XXX_Merge(src proto.Message) {
xxx_messageInfo_CarryingLabelInfoCapability.Merge(m, src)
}
func (m *CarryingLabelInfoCapability) XXX_Size() int {
return xxx_messageInfo_CarryingLabelInfoCapability.Size(m)
}
func (m *CarryingLabelInfoCapability) XXX_DiscardUnknown() {
xxx_messageInfo_CarryingLabelInfoCapability.DiscardUnknown(m)
}
var xxx_messageInfo_CarryingLabelInfoCapability proto.InternalMessageInfo
type ExtendedNexthopCapabilityTuple struct { type ExtendedNexthopCapabilityTuple struct {
NlriFamily *Family `protobuf:"bytes,1,opt,name=nlri_family,json=nlriFamily" json:"nlri_family,omitempty"` NlriFamily *Family `protobuf:"bytes,1,opt,name=nlri_family,json=nlriFamily,proto3" json:"nlri_family,omitempty"`
// Nexthop AFI must be either // Nexthop AFI must be either
// gobgp.IPv4 or // gobgp.IPv4 or
// gobgp.IPv6. // gobgp.IPv6.
NexthopFamily *Family `protobuf:"bytes,2,opt,name=nexthop_family,json=nexthopFamily" json:"nexthop_family,omitempty"` NexthopFamily *Family `protobuf:"bytes,2,opt,name=nexthop_family,json=nexthopFamily,proto3" json:"nexthop_family,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
} }
func (m *ExtendedNexthopCapabilityTuple) Reset() { *m = ExtendedNexthopCapabilityTuple{} } func (m *ExtendedNexthopCapabilityTuple) Reset() { *m = ExtendedNexthopCapabilityTuple{} }
func (m *ExtendedNexthopCapabilityTuple) String() string { return proto.CompactTextString(m) } func (m *ExtendedNexthopCapabilityTuple) String() string { return proto.CompactTextString(m) }
func (*ExtendedNexthopCapabilityTuple) ProtoMessage() {} func (*ExtendedNexthopCapabilityTuple) ProtoMessage() {}
func (*ExtendedNexthopCapabilityTuple) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{3} } func (*ExtendedNexthopCapabilityTuple) Descriptor() ([]byte, []int) {
return fileDescriptor_f2310f95efbbe3ac, []int{3}
}
func (m *ExtendedNexthopCapabilityTuple) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_ExtendedNexthopCapabilityTuple.Unmarshal(m, b)
}
func (m *ExtendedNexthopCapabilityTuple) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_ExtendedNexthopCapabilityTuple.Marshal(b, m, deterministic)
}
func (m *ExtendedNexthopCapabilityTuple) XXX_Merge(src proto.Message) {
xxx_messageInfo_ExtendedNexthopCapabilityTuple.Merge(m, src)
}
func (m *ExtendedNexthopCapabilityTuple) XXX_Size() int {
return xxx_messageInfo_ExtendedNexthopCapabilityTuple.Size(m)
}
func (m *ExtendedNexthopCapabilityTuple) XXX_DiscardUnknown() {
xxx_messageInfo_ExtendedNexthopCapabilityTuple.DiscardUnknown(m)
}
var xxx_messageInfo_ExtendedNexthopCapabilityTuple proto.InternalMessageInfo
func (m *ExtendedNexthopCapabilityTuple) GetNlriFamily() *Family { func (m *ExtendedNexthopCapabilityTuple) GetNlriFamily() *Family {
if m != nil { if m != nil {
@@ -99,13 +203,36 @@ func (m *ExtendedNexthopCapabilityTuple) GetNexthopFamily() *Family {
} }
type ExtendedNexthopCapability struct { type ExtendedNexthopCapability struct {
Tuples []*ExtendedNexthopCapabilityTuple `protobuf:"bytes,1,rep,name=tuples" json:"tuples,omitempty"` Tuples []*ExtendedNexthopCapabilityTuple `protobuf:"bytes,1,rep,name=tuples,proto3" json:"tuples,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
} }
func (m *ExtendedNexthopCapability) Reset() { *m = ExtendedNexthopCapability{} } func (m *ExtendedNexthopCapability) Reset() { *m = ExtendedNexthopCapability{} }
func (m *ExtendedNexthopCapability) String() string { return proto.CompactTextString(m) } func (m *ExtendedNexthopCapability) String() string { return proto.CompactTextString(m) }
func (*ExtendedNexthopCapability) ProtoMessage() {} func (*ExtendedNexthopCapability) ProtoMessage() {}
func (*ExtendedNexthopCapability) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{4} } func (*ExtendedNexthopCapability) Descriptor() ([]byte, []int) {
return fileDescriptor_f2310f95efbbe3ac, []int{4}
}
func (m *ExtendedNexthopCapability) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_ExtendedNexthopCapability.Unmarshal(m, b)
}
func (m *ExtendedNexthopCapability) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_ExtendedNexthopCapability.Marshal(b, m, deterministic)
}
func (m *ExtendedNexthopCapability) XXX_Merge(src proto.Message) {
xxx_messageInfo_ExtendedNexthopCapability.Merge(m, src)
}
func (m *ExtendedNexthopCapability) XXX_Size() int {
return xxx_messageInfo_ExtendedNexthopCapability.Size(m)
}
func (m *ExtendedNexthopCapability) XXX_DiscardUnknown() {
xxx_messageInfo_ExtendedNexthopCapability.DiscardUnknown(m)
}
var xxx_messageInfo_ExtendedNexthopCapability proto.InternalMessageInfo
func (m *ExtendedNexthopCapability) GetTuples() []*ExtendedNexthopCapabilityTuple { func (m *ExtendedNexthopCapability) GetTuples() []*ExtendedNexthopCapabilityTuple {
if m != nil { if m != nil {
@@ -115,14 +242,37 @@ func (m *ExtendedNexthopCapability) GetTuples() []*ExtendedNexthopCapabilityTupl
} }
type GracefulRestartCapabilityTuple struct { type GracefulRestartCapabilityTuple struct {
Family *Family `protobuf:"bytes,1,opt,name=family" json:"family,omitempty"` Family *Family `protobuf:"bytes,1,opt,name=family,proto3" json:"family,omitempty"`
Flags uint32 `protobuf:"varint,2,opt,name=flags" json:"flags,omitempty"` Flags uint32 `protobuf:"varint,2,opt,name=flags,proto3" json:"flags,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
} }
func (m *GracefulRestartCapabilityTuple) Reset() { *m = GracefulRestartCapabilityTuple{} } func (m *GracefulRestartCapabilityTuple) Reset() { *m = GracefulRestartCapabilityTuple{} }
func (m *GracefulRestartCapabilityTuple) String() string { return proto.CompactTextString(m) } func (m *GracefulRestartCapabilityTuple) String() string { return proto.CompactTextString(m) }
func (*GracefulRestartCapabilityTuple) ProtoMessage() {} func (*GracefulRestartCapabilityTuple) ProtoMessage() {}
func (*GracefulRestartCapabilityTuple) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{5} } func (*GracefulRestartCapabilityTuple) Descriptor() ([]byte, []int) {
return fileDescriptor_f2310f95efbbe3ac, []int{5}
}
func (m *GracefulRestartCapabilityTuple) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GracefulRestartCapabilityTuple.Unmarshal(m, b)
}
func (m *GracefulRestartCapabilityTuple) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GracefulRestartCapabilityTuple.Marshal(b, m, deterministic)
}
func (m *GracefulRestartCapabilityTuple) XXX_Merge(src proto.Message) {
xxx_messageInfo_GracefulRestartCapabilityTuple.Merge(m, src)
}
func (m *GracefulRestartCapabilityTuple) XXX_Size() int {
return xxx_messageInfo_GracefulRestartCapabilityTuple.Size(m)
}
func (m *GracefulRestartCapabilityTuple) XXX_DiscardUnknown() {
xxx_messageInfo_GracefulRestartCapabilityTuple.DiscardUnknown(m)
}
var xxx_messageInfo_GracefulRestartCapabilityTuple proto.InternalMessageInfo
func (m *GracefulRestartCapabilityTuple) GetFamily() *Family { func (m *GracefulRestartCapabilityTuple) GetFamily() *Family {
if m != nil { if m != nil {
@@ -139,15 +289,38 @@ func (m *GracefulRestartCapabilityTuple) GetFlags() uint32 {
} }
type GracefulRestartCapability struct { type GracefulRestartCapability struct {
Flags uint32 `protobuf:"varint,1,opt,name=flags" json:"flags,omitempty"` Flags uint32 `protobuf:"varint,1,opt,name=flags,proto3" json:"flags,omitempty"`
Time uint32 `protobuf:"varint,2,opt,name=time" json:"time,omitempty"` Time uint32 `protobuf:"varint,2,opt,name=time,proto3" json:"time,omitempty"`
Tuples []*GracefulRestartCapabilityTuple `protobuf:"bytes,3,rep,name=tuples" json:"tuples,omitempty"` Tuples []*GracefulRestartCapabilityTuple `protobuf:"bytes,3,rep,name=tuples,proto3" json:"tuples,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
} }
func (m *GracefulRestartCapability) Reset() { *m = GracefulRestartCapability{} } func (m *GracefulRestartCapability) Reset() { *m = GracefulRestartCapability{} }
func (m *GracefulRestartCapability) String() string { return proto.CompactTextString(m) } func (m *GracefulRestartCapability) String() string { return proto.CompactTextString(m) }
func (*GracefulRestartCapability) ProtoMessage() {} func (*GracefulRestartCapability) ProtoMessage() {}
func (*GracefulRestartCapability) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{6} } func (*GracefulRestartCapability) Descriptor() ([]byte, []int) {
return fileDescriptor_f2310f95efbbe3ac, []int{6}
}
func (m *GracefulRestartCapability) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GracefulRestartCapability.Unmarshal(m, b)
}
func (m *GracefulRestartCapability) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GracefulRestartCapability.Marshal(b, m, deterministic)
}
func (m *GracefulRestartCapability) XXX_Merge(src proto.Message) {
xxx_messageInfo_GracefulRestartCapability.Merge(m, src)
}
func (m *GracefulRestartCapability) XXX_Size() int {
return xxx_messageInfo_GracefulRestartCapability.Size(m)
}
func (m *GracefulRestartCapability) XXX_DiscardUnknown() {
xxx_messageInfo_GracefulRestartCapability.DiscardUnknown(m)
}
var xxx_messageInfo_GracefulRestartCapability proto.InternalMessageInfo
func (m *GracefulRestartCapability) GetFlags() uint32 { func (m *GracefulRestartCapability) GetFlags() uint32 {
if m != nil { if m != nil {
@@ -171,13 +344,36 @@ func (m *GracefulRestartCapability) GetTuples() []*GracefulRestartCapabilityTupl
} }
type FourOctetASNumberCapability struct { type FourOctetASNumberCapability struct {
As uint32 `protobuf:"varint,1,opt,name=as" json:"as,omitempty"` As uint32 `protobuf:"varint,1,opt,name=as,proto3" json:"as,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
} }
func (m *FourOctetASNumberCapability) Reset() { *m = FourOctetASNumberCapability{} } func (m *FourOctetASNumberCapability) Reset() { *m = FourOctetASNumberCapability{} }
func (m *FourOctetASNumberCapability) String() string { return proto.CompactTextString(m) } func (m *FourOctetASNumberCapability) String() string { return proto.CompactTextString(m) }
func (*FourOctetASNumberCapability) ProtoMessage() {} func (*FourOctetASNumberCapability) ProtoMessage() {}
func (*FourOctetASNumberCapability) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{7} } func (*FourOctetASNumberCapability) Descriptor() ([]byte, []int) {
return fileDescriptor_f2310f95efbbe3ac, []int{7}
}
func (m *FourOctetASNumberCapability) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_FourOctetASNumberCapability.Unmarshal(m, b)
}
func (m *FourOctetASNumberCapability) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_FourOctetASNumberCapability.Marshal(b, m, deterministic)
}
func (m *FourOctetASNumberCapability) XXX_Merge(src proto.Message) {
xxx_messageInfo_FourOctetASNumberCapability.Merge(m, src)
}
func (m *FourOctetASNumberCapability) XXX_Size() int {
return xxx_messageInfo_FourOctetASNumberCapability.Size(m)
}
func (m *FourOctetASNumberCapability) XXX_DiscardUnknown() {
xxx_messageInfo_FourOctetASNumberCapability.DiscardUnknown(m)
}
var xxx_messageInfo_FourOctetASNumberCapability proto.InternalMessageInfo
func (m *FourOctetASNumberCapability) GetAs() uint32 { func (m *FourOctetASNumberCapability) GetAs() uint32 {
if m != nil { if m != nil {
@@ -187,14 +383,37 @@ func (m *FourOctetASNumberCapability) GetAs() uint32 {
} }
type AddPathCapabilityTuple struct { type AddPathCapabilityTuple struct {
Family *Family `protobuf:"bytes,1,opt,name=family" json:"family,omitempty"` Family *Family `protobuf:"bytes,1,opt,name=family,proto3" json:"family,omitempty"`
Mode AddPathMode `protobuf:"varint,2,opt,name=mode,enum=gobgpapi.AddPathMode" json:"mode,omitempty"` Mode AddPathMode `protobuf:"varint,2,opt,name=mode,proto3,enum=gobgpapi.AddPathMode" json:"mode,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
} }
func (m *AddPathCapabilityTuple) Reset() { *m = AddPathCapabilityTuple{} } func (m *AddPathCapabilityTuple) Reset() { *m = AddPathCapabilityTuple{} }
func (m *AddPathCapabilityTuple) String() string { return proto.CompactTextString(m) } func (m *AddPathCapabilityTuple) String() string { return proto.CompactTextString(m) }
func (*AddPathCapabilityTuple) ProtoMessage() {} func (*AddPathCapabilityTuple) ProtoMessage() {}
func (*AddPathCapabilityTuple) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{8} } func (*AddPathCapabilityTuple) Descriptor() ([]byte, []int) {
return fileDescriptor_f2310f95efbbe3ac, []int{8}
}
func (m *AddPathCapabilityTuple) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_AddPathCapabilityTuple.Unmarshal(m, b)
}
func (m *AddPathCapabilityTuple) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_AddPathCapabilityTuple.Marshal(b, m, deterministic)
}
func (m *AddPathCapabilityTuple) XXX_Merge(src proto.Message) {
xxx_messageInfo_AddPathCapabilityTuple.Merge(m, src)
}
func (m *AddPathCapabilityTuple) XXX_Size() int {
return xxx_messageInfo_AddPathCapabilityTuple.Size(m)
}
func (m *AddPathCapabilityTuple) XXX_DiscardUnknown() {
xxx_messageInfo_AddPathCapabilityTuple.DiscardUnknown(m)
}
var xxx_messageInfo_AddPathCapabilityTuple proto.InternalMessageInfo
func (m *AddPathCapabilityTuple) GetFamily() *Family { func (m *AddPathCapabilityTuple) GetFamily() *Family {
if m != nil { if m != nil {
@@ -211,13 +430,36 @@ func (m *AddPathCapabilityTuple) GetMode() AddPathMode {
} }
type AddPathCapability struct { type AddPathCapability struct {
Tuples []*AddPathCapabilityTuple `protobuf:"bytes,1,rep,name=tuples" json:"tuples,omitempty"` Tuples []*AddPathCapabilityTuple `protobuf:"bytes,1,rep,name=tuples,proto3" json:"tuples,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
} }
func (m *AddPathCapability) Reset() { *m = AddPathCapability{} } func (m *AddPathCapability) Reset() { *m = AddPathCapability{} }
func (m *AddPathCapability) String() string { return proto.CompactTextString(m) } func (m *AddPathCapability) String() string { return proto.CompactTextString(m) }
func (*AddPathCapability) ProtoMessage() {} func (*AddPathCapability) ProtoMessage() {}
func (*AddPathCapability) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{9} } func (*AddPathCapability) Descriptor() ([]byte, []int) {
return fileDescriptor_f2310f95efbbe3ac, []int{9}
}
func (m *AddPathCapability) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_AddPathCapability.Unmarshal(m, b)
}
func (m *AddPathCapability) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_AddPathCapability.Marshal(b, m, deterministic)
}
func (m *AddPathCapability) XXX_Merge(src proto.Message) {
xxx_messageInfo_AddPathCapability.Merge(m, src)
}
func (m *AddPathCapability) XXX_Size() int {
return xxx_messageInfo_AddPathCapability.Size(m)
}
func (m *AddPathCapability) XXX_DiscardUnknown() {
xxx_messageInfo_AddPathCapability.DiscardUnknown(m)
}
var xxx_messageInfo_AddPathCapability proto.InternalMessageInfo
func (m *AddPathCapability) GetTuples() []*AddPathCapabilityTuple { func (m *AddPathCapability) GetTuples() []*AddPathCapabilityTuple {
if m != nil { if m != nil {
@@ -227,19 +469,43 @@ func (m *AddPathCapability) GetTuples() []*AddPathCapabilityTuple {
} }
type EnhancedRouteRefreshCapability struct { type EnhancedRouteRefreshCapability struct {
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
} }
func (m *EnhancedRouteRefreshCapability) Reset() { *m = EnhancedRouteRefreshCapability{} } func (m *EnhancedRouteRefreshCapability) Reset() { *m = EnhancedRouteRefreshCapability{} }
func (m *EnhancedRouteRefreshCapability) String() string { return proto.CompactTextString(m) } func (m *EnhancedRouteRefreshCapability) String() string { return proto.CompactTextString(m) }
func (*EnhancedRouteRefreshCapability) ProtoMessage() {} func (*EnhancedRouteRefreshCapability) ProtoMessage() {}
func (*EnhancedRouteRefreshCapability) Descriptor() ([]byte, []int) { func (*EnhancedRouteRefreshCapability) Descriptor() ([]byte, []int) {
return fileDescriptor1, []int{10} return fileDescriptor_f2310f95efbbe3ac, []int{10}
} }
func (m *EnhancedRouteRefreshCapability) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_EnhancedRouteRefreshCapability.Unmarshal(m, b)
}
func (m *EnhancedRouteRefreshCapability) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_EnhancedRouteRefreshCapability.Marshal(b, m, deterministic)
}
func (m *EnhancedRouteRefreshCapability) XXX_Merge(src proto.Message) {
xxx_messageInfo_EnhancedRouteRefreshCapability.Merge(m, src)
}
func (m *EnhancedRouteRefreshCapability) XXX_Size() int {
return xxx_messageInfo_EnhancedRouteRefreshCapability.Size(m)
}
func (m *EnhancedRouteRefreshCapability) XXX_DiscardUnknown() {
xxx_messageInfo_EnhancedRouteRefreshCapability.DiscardUnknown(m)
}
var xxx_messageInfo_EnhancedRouteRefreshCapability proto.InternalMessageInfo
type LongLivedGracefulRestartCapabilityTuple struct { type LongLivedGracefulRestartCapabilityTuple struct {
Family *Family `protobuf:"bytes,1,opt,name=family" json:"family,omitempty"` Family *Family `protobuf:"bytes,1,opt,name=family,proto3" json:"family,omitempty"`
Flags uint32 `protobuf:"varint,2,opt,name=flags" json:"flags,omitempty"` Flags uint32 `protobuf:"varint,2,opt,name=flags,proto3" json:"flags,omitempty"`
Time uint32 `protobuf:"varint,3,opt,name=time" json:"time,omitempty"` Time uint32 `protobuf:"varint,3,opt,name=time,proto3" json:"time,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
} }
func (m *LongLivedGracefulRestartCapabilityTuple) Reset() { func (m *LongLivedGracefulRestartCapabilityTuple) Reset() {
@@ -248,9 +514,27 @@ func (m *LongLivedGracefulRestartCapabilityTuple) Reset() {
func (m *LongLivedGracefulRestartCapabilityTuple) String() string { return proto.CompactTextString(m) } func (m *LongLivedGracefulRestartCapabilityTuple) String() string { return proto.CompactTextString(m) }
func (*LongLivedGracefulRestartCapabilityTuple) ProtoMessage() {} func (*LongLivedGracefulRestartCapabilityTuple) ProtoMessage() {}
func (*LongLivedGracefulRestartCapabilityTuple) Descriptor() ([]byte, []int) { func (*LongLivedGracefulRestartCapabilityTuple) Descriptor() ([]byte, []int) {
return fileDescriptor1, []int{11} return fileDescriptor_f2310f95efbbe3ac, []int{11}
} }
func (m *LongLivedGracefulRestartCapabilityTuple) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_LongLivedGracefulRestartCapabilityTuple.Unmarshal(m, b)
}
func (m *LongLivedGracefulRestartCapabilityTuple) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_LongLivedGracefulRestartCapabilityTuple.Marshal(b, m, deterministic)
}
func (m *LongLivedGracefulRestartCapabilityTuple) XXX_Merge(src proto.Message) {
xxx_messageInfo_LongLivedGracefulRestartCapabilityTuple.Merge(m, src)
}
func (m *LongLivedGracefulRestartCapabilityTuple) XXX_Size() int {
return xxx_messageInfo_LongLivedGracefulRestartCapabilityTuple.Size(m)
}
func (m *LongLivedGracefulRestartCapabilityTuple) XXX_DiscardUnknown() {
xxx_messageInfo_LongLivedGracefulRestartCapabilityTuple.DiscardUnknown(m)
}
var xxx_messageInfo_LongLivedGracefulRestartCapabilityTuple proto.InternalMessageInfo
func (m *LongLivedGracefulRestartCapabilityTuple) GetFamily() *Family { func (m *LongLivedGracefulRestartCapabilityTuple) GetFamily() *Family {
if m != nil { if m != nil {
return m.Family return m.Family
@@ -273,16 +557,37 @@ func (m *LongLivedGracefulRestartCapabilityTuple) GetTime() uint32 {
} }
type LongLivedGracefulRestartCapability struct { type LongLivedGracefulRestartCapability struct {
Tuples []*LongLivedGracefulRestartCapabilityTuple `protobuf:"bytes,1,rep,name=tuples" json:"tuples,omitempty"` Tuples []*LongLivedGracefulRestartCapabilityTuple `protobuf:"bytes,1,rep,name=tuples,proto3" json:"tuples,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
} }
func (m *LongLivedGracefulRestartCapability) Reset() { *m = LongLivedGracefulRestartCapability{} } func (m *LongLivedGracefulRestartCapability) Reset() { *m = LongLivedGracefulRestartCapability{} }
func (m *LongLivedGracefulRestartCapability) String() string { return proto.CompactTextString(m) } func (m *LongLivedGracefulRestartCapability) String() string { return proto.CompactTextString(m) }
func (*LongLivedGracefulRestartCapability) ProtoMessage() {} func (*LongLivedGracefulRestartCapability) ProtoMessage() {}
func (*LongLivedGracefulRestartCapability) Descriptor() ([]byte, []int) { func (*LongLivedGracefulRestartCapability) Descriptor() ([]byte, []int) {
return fileDescriptor1, []int{12} return fileDescriptor_f2310f95efbbe3ac, []int{12}
} }
func (m *LongLivedGracefulRestartCapability) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_LongLivedGracefulRestartCapability.Unmarshal(m, b)
}
func (m *LongLivedGracefulRestartCapability) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_LongLivedGracefulRestartCapability.Marshal(b, m, deterministic)
}
func (m *LongLivedGracefulRestartCapability) XXX_Merge(src proto.Message) {
xxx_messageInfo_LongLivedGracefulRestartCapability.Merge(m, src)
}
func (m *LongLivedGracefulRestartCapability) XXX_Size() int {
return xxx_messageInfo_LongLivedGracefulRestartCapability.Size(m)
}
func (m *LongLivedGracefulRestartCapability) XXX_DiscardUnknown() {
xxx_messageInfo_LongLivedGracefulRestartCapability.DiscardUnknown(m)
}
var xxx_messageInfo_LongLivedGracefulRestartCapability proto.InternalMessageInfo
func (m *LongLivedGracefulRestartCapability) GetTuples() []*LongLivedGracefulRestartCapabilityTuple { func (m *LongLivedGracefulRestartCapability) GetTuples() []*LongLivedGracefulRestartCapabilityTuple {
if m != nil { if m != nil {
return m.Tuples return m.Tuples
@@ -291,22 +596,131 @@ func (m *LongLivedGracefulRestartCapability) GetTuples() []*LongLivedGracefulRes
} }
type RouteRefreshCiscoCapability struct { type RouteRefreshCiscoCapability struct {
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
} }
func (m *RouteRefreshCiscoCapability) Reset() { *m = RouteRefreshCiscoCapability{} } func (m *RouteRefreshCiscoCapability) Reset() { *m = RouteRefreshCiscoCapability{} }
func (m *RouteRefreshCiscoCapability) String() string { return proto.CompactTextString(m) } func (m *RouteRefreshCiscoCapability) String() string { return proto.CompactTextString(m) }
func (*RouteRefreshCiscoCapability) ProtoMessage() {} func (*RouteRefreshCiscoCapability) ProtoMessage() {}
func (*RouteRefreshCiscoCapability) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{13} } func (*RouteRefreshCiscoCapability) Descriptor() ([]byte, []int) {
return fileDescriptor_f2310f95efbbe3ac, []int{13}
}
func (m *RouteRefreshCiscoCapability) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_RouteRefreshCiscoCapability.Unmarshal(m, b)
}
func (m *RouteRefreshCiscoCapability) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_RouteRefreshCiscoCapability.Marshal(b, m, deterministic)
}
func (m *RouteRefreshCiscoCapability) XXX_Merge(src proto.Message) {
xxx_messageInfo_RouteRefreshCiscoCapability.Merge(m, src)
}
func (m *RouteRefreshCiscoCapability) XXX_Size() int {
return xxx_messageInfo_RouteRefreshCiscoCapability.Size(m)
}
func (m *RouteRefreshCiscoCapability) XXX_DiscardUnknown() {
xxx_messageInfo_RouteRefreshCiscoCapability.DiscardUnknown(m)
}
var xxx_messageInfo_RouteRefreshCiscoCapability proto.InternalMessageInfo
type FQDNCapability struct {
HostNameLen uint32 `protobuf:"varint,1,opt,name=host_name_len,json=hostNameLen,proto3" json:"host_name_len,omitempty"`
HostName string `protobuf:"bytes,2,opt,name=host_name,json=hostName,proto3" json:"host_name,omitempty"`
DomainNameLen uint32 `protobuf:"varint,3,opt,name=domain_name_len,json=domainNameLen,proto3" json:"domain_name_len,omitempty"`
DomainName string `protobuf:"bytes,4,opt,name=domain_name,json=domainName,proto3" json:"domain_name,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *FQDNCapability) Reset() { *m = FQDNCapability{} }
func (m *FQDNCapability) String() string { return proto.CompactTextString(m) }
func (*FQDNCapability) ProtoMessage() {}
func (*FQDNCapability) Descriptor() ([]byte, []int) {
return fileDescriptor_f2310f95efbbe3ac, []int{14}
}
func (m *FQDNCapability) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_FQDNCapability.Unmarshal(m, b)
}
func (m *FQDNCapability) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_FQDNCapability.Marshal(b, m, deterministic)
}
func (m *FQDNCapability) XXX_Merge(src proto.Message) {
xxx_messageInfo_FQDNCapability.Merge(m, src)
}
func (m *FQDNCapability) XXX_Size() int {
return xxx_messageInfo_FQDNCapability.Size(m)
}
func (m *FQDNCapability) XXX_DiscardUnknown() {
xxx_messageInfo_FQDNCapability.DiscardUnknown(m)
}
var xxx_messageInfo_FQDNCapability proto.InternalMessageInfo
func (m *FQDNCapability) GetHostNameLen() uint32 {
if m != nil {
return m.HostNameLen
}
return 0
}
func (m *FQDNCapability) GetHostName() string {
if m != nil {
return m.HostName
}
return ""
}
func (m *FQDNCapability) GetDomainNameLen() uint32 {
if m != nil {
return m.DomainNameLen
}
return 0
}
func (m *FQDNCapability) GetDomainName() string {
if m != nil {
return m.DomainName
}
return ""
}
type UnknownCapability struct { type UnknownCapability struct {
Code uint32 `protobuf:"varint,1,opt,name=code" json:"code,omitempty"` Code uint32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"`
Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
} }
func (m *UnknownCapability) Reset() { *m = UnknownCapability{} } func (m *UnknownCapability) Reset() { *m = UnknownCapability{} }
func (m *UnknownCapability) String() string { return proto.CompactTextString(m) } func (m *UnknownCapability) String() string { return proto.CompactTextString(m) }
func (*UnknownCapability) ProtoMessage() {} func (*UnknownCapability) ProtoMessage() {}
func (*UnknownCapability) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{14} } func (*UnknownCapability) Descriptor() ([]byte, []int) {
return fileDescriptor_f2310f95efbbe3ac, []int{15}
}
func (m *UnknownCapability) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_UnknownCapability.Unmarshal(m, b)
}
func (m *UnknownCapability) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_UnknownCapability.Marshal(b, m, deterministic)
}
func (m *UnknownCapability) XXX_Merge(src proto.Message) {
xxx_messageInfo_UnknownCapability.Merge(m, src)
}
func (m *UnknownCapability) XXX_Size() int {
return xxx_messageInfo_UnknownCapability.Size(m)
}
func (m *UnknownCapability) XXX_DiscardUnknown() {
xxx_messageInfo_UnknownCapability.DiscardUnknown(m)
}
var xxx_messageInfo_UnknownCapability proto.InternalMessageInfo
func (m *UnknownCapability) GetCode() uint32 { func (m *UnknownCapability) GetCode() uint32 {
if m != nil { if m != nil {
@@ -323,6 +737,7 @@ func (m *UnknownCapability) GetValue() []byte {
} }
func init() { func init() {
proto.RegisterEnum("gobgpapi.AddPathMode", AddPathMode_name, AddPathMode_value)
proto.RegisterType((*MultiProtocolCapability)(nil), "gobgpapi.MultiProtocolCapability") proto.RegisterType((*MultiProtocolCapability)(nil), "gobgpapi.MultiProtocolCapability")
proto.RegisterType((*RouteRefreshCapability)(nil), "gobgpapi.RouteRefreshCapability") proto.RegisterType((*RouteRefreshCapability)(nil), "gobgpapi.RouteRefreshCapability")
proto.RegisterType((*CarryingLabelInfoCapability)(nil), "gobgpapi.CarryingLabelInfoCapability") proto.RegisterType((*CarryingLabelInfoCapability)(nil), "gobgpapi.CarryingLabelInfoCapability")
@@ -337,45 +752,49 @@ func init() {
proto.RegisterType((*LongLivedGracefulRestartCapabilityTuple)(nil), "gobgpapi.LongLivedGracefulRestartCapabilityTuple") proto.RegisterType((*LongLivedGracefulRestartCapabilityTuple)(nil), "gobgpapi.LongLivedGracefulRestartCapabilityTuple")
proto.RegisterType((*LongLivedGracefulRestartCapability)(nil), "gobgpapi.LongLivedGracefulRestartCapability") proto.RegisterType((*LongLivedGracefulRestartCapability)(nil), "gobgpapi.LongLivedGracefulRestartCapability")
proto.RegisterType((*RouteRefreshCiscoCapability)(nil), "gobgpapi.RouteRefreshCiscoCapability") proto.RegisterType((*RouteRefreshCiscoCapability)(nil), "gobgpapi.RouteRefreshCiscoCapability")
proto.RegisterType((*FQDNCapability)(nil), "gobgpapi.FQDNCapability")
proto.RegisterType((*UnknownCapability)(nil), "gobgpapi.UnknownCapability") proto.RegisterType((*UnknownCapability)(nil), "gobgpapi.UnknownCapability")
proto.RegisterEnum("gobgpapi.AddPathMode", AddPathMode_name, AddPathMode_value)
} }
func init() { proto.RegisterFile("capability.proto", fileDescriptor1) } func init() { proto.RegisterFile("capability.proto", fileDescriptor_f2310f95efbbe3ac) }
var fileDescriptor1 = []byte{ var fileDescriptor_f2310f95efbbe3ac = []byte{
// 520 bytes of a gzipped FileDescriptorProto // 590 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x54, 0x4d, 0x6f, 0xd3, 0x40, 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x54, 0xc1, 0x6e, 0xd3, 0x40,
0x10, 0xc5, 0x49, 0x88, 0x60, 0xd2, 0x44, 0xee, 0x0a, 0x4a, 0x4a, 0xd4, 0x28, 0xda, 0x0b, 0x01, 0x10, 0xc5, 0x49, 0xa8, 0xda, 0x71, 0x13, 0xdc, 0x15, 0x94, 0x94, 0xa8, 0x25, 0xda, 0x03, 0x04,
0x89, 0x48, 0x0d, 0x07, 0xb8, 0x20, 0x51, 0x52, 0x17, 0x22, 0xe5, 0xa3, 0x72, 0x0b, 0x37, 0x54, 0x24, 0x22, 0x35, 0x1c, 0xe0, 0x82, 0x44, 0x49, 0x1c, 0x88, 0x94, 0x38, 0xc5, 0x2d, 0xdc, 0x50,
0x36, 0xf6, 0xc6, 0x59, 0xb1, 0xde, 0xb5, 0xec, 0x75, 0x69, 0x0e, 0x9c, 0xb9, 0xf0, 0xa3, 0x91, 0xd8, 0xd8, 0x9b, 0xc4, 0xc2, 0xde, 0xb5, 0xec, 0x75, 0x69, 0x0e, 0x9c, 0xb9, 0xf0, 0x05, 0x7c,
0x3f, 0x62, 0x9b, 0x54, 0x6e, 0x2b, 0xa4, 0xde, 0x66, 0xbc, 0x33, 0x6f, 0xde, 0x9b, 0xb7, 0x6b, 0x2d, 0xb2, 0xd7, 0xb1, 0x4d, 0xaa, 0xb4, 0x15, 0x12, 0xb7, 0x9d, 0x9d, 0x37, 0x6f, 0xde, 0x9b,
0xd0, 0x2d, 0xe2, 0x91, 0x05, 0xe3, 0x4c, 0xad, 0x07, 0x9e, 0x2f, 0x95, 0x44, 0x8f, 0x1c, 0xb9, 0x1d, 0x1b, 0x34, 0x8b, 0xf8, 0x64, 0xea, 0xb8, 0x8e, 0x58, 0xb6, 0xfd, 0x80, 0x0b, 0x8e, 0xb6,
0x70, 0x3c, 0xe2, 0xb1, 0xe7, 0x8d, 0x38, 0x4a, 0x3e, 0xe3, 0x11, 0x3c, 0x9b, 0x86, 0x5c, 0xb1, 0xe7, 0x7c, 0x3a, 0xf7, 0x89, 0xef, 0x3c, 0x52, 0x93, 0x93, 0xbc, 0xc6, 0x5d, 0x78, 0x38, 0x8a,
0xd3, 0x28, 0xb3, 0x24, 0x1f, 0x65, 0x7d, 0xa8, 0x0f, 0xf5, 0x25, 0x71, 0x19, 0x5f, 0xb7, 0xb5, 0x5c, 0xe1, 0x9c, 0xc6, 0x91, 0xc5, 0xdd, 0x6e, 0x56, 0x87, 0x5a, 0xb0, 0x35, 0x23, 0x9e, 0xe3,
0x9e, 0xd6, 0x6f, 0x0c, 0xf5, 0xc1, 0x06, 0x62, 0x70, 0x12, 0x7f, 0x37, 0xd3, 0x73, 0xdc, 0x86, 0x2e, 0xeb, 0x4a, 0x53, 0x69, 0xa9, 0x1d, 0xad, 0xbd, 0xa2, 0x68, 0xf7, 0x93, 0x7b, 0x33, 0xcd,
0x3d, 0x53, 0x86, 0x8a, 0x9a, 0x74, 0xe9, 0xd3, 0x60, 0x95, 0x63, 0xe0, 0x03, 0xe8, 0x8c, 0x88, 0xe3, 0x3a, 0xec, 0x9b, 0x3c, 0x12, 0xd4, 0xa4, 0xb3, 0x80, 0x86, 0x8b, 0x9c, 0x03, 0x1f, 0x42,
0xef, 0xaf, 0x99, 0x70, 0x26, 0x64, 0x41, 0xf9, 0x58, 0x2c, 0x65, 0xe1, 0xf8, 0x8f, 0x06, 0x5d, 0xa3, 0x4b, 0x82, 0x60, 0xe9, 0xb0, 0xf9, 0x90, 0x4c, 0xa9, 0x3b, 0x60, 0x33, 0x5e, 0x48, 0xff,
0xe3, 0x4a, 0x51, 0x61, 0x53, 0x7b, 0x46, 0xaf, 0xd4, 0x4a, 0x7a, 0xf9, 0xe9, 0x79, 0xe8, 0x71, 0x52, 0xe0, 0x48, 0xbf, 0x14, 0x94, 0xd9, 0xd4, 0x36, 0xe8, 0xa5, 0x58, 0x70, 0x3f, 0xcf, 0x9e,
0x8a, 0x0e, 0xa1, 0x21, 0xb8, 0xcf, 0x2e, 0x6e, 0xa1, 0x02, 0x51, 0x51, 0x12, 0xa3, 0xb7, 0xd0, 0x47, 0xbe, 0x4b, 0xd1, 0x31, 0xa8, 0xcc, 0x0d, 0x9c, 0xc9, 0x0d, 0x52, 0x20, 0x06, 0xc9, 0x33,
0x12, 0x09, 0xd8, 0xa6, 0xab, 0x52, 0xd2, 0xd5, 0x4c, 0xeb, 0x92, 0x14, 0x7f, 0x83, 0xfd, 0x52, 0x7a, 0x05, 0x35, 0x26, 0xc9, 0x56, 0x55, 0xa5, 0x0d, 0x55, 0xd5, 0x14, 0x27, 0x43, 0xfc, 0x05,
0x36, 0xe8, 0x03, 0xd4, 0x55, 0xc4, 0x28, 0x68, 0x6b, 0xbd, 0x6a, 0xbf, 0x31, 0xec, 0xe7, 0x68, 0x0e, 0x36, 0xaa, 0x41, 0x6f, 0x61, 0x4b, 0xc4, 0x8a, 0xc2, 0xba, 0xd2, 0x2c, 0xb7, 0xd4, 0x4e,
0x37, 0x4b, 0x30, 0xd3, 0x3e, 0xfc, 0x1d, 0xba, 0x9f, 0x7c, 0x62, 0xd1, 0x65, 0xc8, 0x4d, 0x1a, 0x2b, 0x67, 0xbb, 0xde, 0x82, 0x99, 0xd6, 0xe1, 0xaf, 0x70, 0xf4, 0x3e, 0x20, 0x16, 0x9d, 0x45,
0x28, 0xe2, 0xab, 0x6d, 0xb1, 0x77, 0x5e, 0x39, 0x7a, 0x02, 0x0f, 0x97, 0x9c, 0x38, 0x41, 0x2c, 0xae, 0x49, 0x43, 0x41, 0x02, 0xb1, 0x6e, 0xf6, 0xd6, 0x23, 0x47, 0xf7, 0xe1, 0xee, 0xcc, 0x25,
0xad, 0x69, 0x26, 0x09, 0xfe, 0xad, 0xc1, 0x7e, 0xe9, 0x88, 0xbc, 0x47, 0x2b, 0xf4, 0x20, 0x04, 0xf3, 0x30, 0xb1, 0x56, 0x35, 0x65, 0x80, 0x7f, 0x2a, 0x70, 0xb0, 0xb1, 0x45, 0x5e, 0xa3, 0x14,
0x35, 0xc5, 0x5c, 0x9a, 0x02, 0xc5, 0x71, 0x41, 0x6b, 0x75, 0x5b, 0xeb, 0xcd, 0x0a, 0x32, 0xad, 0x6a, 0x10, 0x82, 0x8a, 0x70, 0x3c, 0x9a, 0x12, 0x25, 0xe7, 0x82, 0xd7, 0xf2, 0xba, 0xd7, 0xeb,
0xaf, 0xa1, 0x73, 0x22, 0x43, 0x7f, 0x6e, 0x29, 0xaa, 0x8e, 0xce, 0x66, 0xa1, 0xbb, 0xa0, 0x7e, 0x1d, 0x64, 0x5e, 0x5f, 0x40, 0xa3, 0xcf, 0xa3, 0x60, 0x6c, 0x09, 0x2a, 0x4e, 0xce, 0x8c, 0xc8,
0x81, 0x4a, 0x0b, 0x2a, 0x64, 0xc3, 0xa3, 0x42, 0x02, 0xec, 0xc2, 0xde, 0x91, 0x6d, 0x9f, 0x12, 0x9b, 0xd2, 0xa0, 0x20, 0xa5, 0x06, 0x25, 0xb2, 0xd2, 0x51, 0x22, 0x21, 0xf6, 0x60, 0xff, 0xc4,
0xb5, 0xfa, 0xff, 0x95, 0xbc, 0x84, 0x9a, 0x2b, 0xed, 0x44, 0x48, 0x6b, 0xf8, 0x34, 0xaf, 0x4b, 0xb6, 0x4f, 0x89, 0x58, 0xfc, 0xfb, 0x48, 0x9e, 0x41, 0xc5, 0xe3, 0xb6, 0x34, 0x52, 0xeb, 0x3c,
0x91, 0xa7, 0xd2, 0xa6, 0x66, 0x5c, 0x82, 0xa7, 0xb0, 0x7b, 0x6d, 0x1c, 0x7a, 0xb7, 0x65, 0x70, 0xc8, 0x71, 0x29, 0xf3, 0x88, 0xdb, 0xd4, 0x4c, 0x20, 0x78, 0x04, 0x7b, 0x57, 0xda, 0xa1, 0xd7,
0xef, 0x1a, 0x42, 0x99, 0xd8, 0x1e, 0x74, 0x0d, 0xb1, 0x22, 0xc2, 0xa2, 0x76, 0xc9, 0x3b, 0xf8, 0x6b, 0x0f, 0xdc, 0xbc, 0xc2, 0xb0, 0xc9, 0x6c, 0x13, 0x8e, 0x74, 0xb6, 0x20, 0xcc, 0xa2, 0xf6,
0x05, 0x2f, 0x26, 0x52, 0x38, 0x13, 0x76, 0x49, 0xed, 0xfb, 0xbd, 0x03, 0x99, 0x9f, 0xd5, 0xdc, 0x86, 0xef, 0xe0, 0x07, 0x3c, 0x1d, 0x72, 0x36, 0x1f, 0x3a, 0x17, 0xd4, 0xfe, 0xbf, 0x3b, 0x90,
0x4f, 0x2c, 0x01, 0xdf, 0x3e, 0x1e, 0x8d, 0xb7, 0x16, 0x70, 0x98, 0x4f, 0xbe, 0x23, 0xf9, 0x6c, 0xbd, 0x67, 0x39, 0x7f, 0x4f, 0xcc, 0x01, 0xdf, 0xdc, 0x1e, 0x0d, 0xd6, 0x06, 0x70, 0x9c, 0x77,
0x23, 0x07, 0xd0, 0xf9, 0x67, 0x13, 0x2c, 0xb0, 0x8a, 0xef, 0xfe, 0x3d, 0xec, 0x7e, 0x11, 0x3f, 0xbe, 0xa5, 0xf8, 0x6c, 0x22, 0x87, 0xd0, 0xf8, 0x6b, 0x12, 0x4e, 0x68, 0x15, 0xbf, 0xfb, 0xdf,
0x84, 0xfc, 0x29, 0x0a, 0xe3, 0x11, 0xd4, 0xac, 0xc8, 0xbf, 0xe4, 0x56, 0xc4, 0x71, 0x24, 0xf1, 0x0a, 0xd4, 0xfa, 0x1f, 0x7b, 0x46, 0xa1, 0x39, 0x86, 0xea, 0x82, 0x87, 0x62, 0xc2, 0x88, 0x47,
0x92, 0xf0, 0x30, 0x31, 0x75, 0xc7, 0x4c, 0x92, 0x57, 0x13, 0x68, 0x14, 0x3c, 0x45, 0x4d, 0x78, 0x27, 0x2e, 0x65, 0xe9, 0x72, 0xa8, 0xf1, 0xa5, 0x41, 0x3c, 0x3a, 0xa4, 0x0c, 0x35, 0x60, 0x27,
0x3c, 0x9d, 0x1f, 0x1b, 0x17, 0xb3, 0xf9, 0xcc, 0xd0, 0x1f, 0x20, 0x1d, 0x76, 0xe2, 0xd4, 0x34, 0xc3, 0x24, 0xa6, 0x77, 0xcc, 0xed, 0x55, 0x1e, 0x3d, 0x81, 0x7b, 0x36, 0xf7, 0x88, 0xc3, 0x72,
0x46, 0xc6, 0xf8, 0xab, 0xa1, 0x6b, 0x59, 0xc1, 0x99, 0x31, 0x3b, 0xd6, 0x2b, 0x59, 0xfa, 0x71, 0x0a, 0x39, 0x82, 0xaa, 0xbc, 0x5e, 0x91, 0x3c, 0x06, 0xb5, 0x80, 0xab, 0x57, 0x12, 0x1a, 0xc8,
0x7e, 0xfe, 0x59, 0xaf, 0x2e, 0xea, 0xf1, 0x9f, 0xf0, 0xcd, 0xdf, 0x00, 0x00, 0x00, 0xff, 0xff, 0x31, 0xf8, 0x0d, 0xec, 0x7d, 0x62, 0xdf, 0x18, 0xff, 0xce, 0x0a, 0xf2, 0x10, 0x54, 0xac, 0x78,
0x3b, 0xec, 0xd3, 0x4d, 0x34, 0x05, 0x00, 0x00, 0xb9, 0xa4, 0xaa, 0xe4, 0x1c, 0xcf, 0xff, 0x82, 0xb8, 0x91, 0x94, 0xb2, 0x6b, 0xca, 0xe0, 0xf9,
0x10, 0xd4, 0xc2, 0xc2, 0xa1, 0x2a, 0xec, 0x8c, 0xc6, 0x3d, 0x7d, 0x62, 0x8c, 0x0d, 0x5d, 0xbb,
0x83, 0x34, 0xd8, 0x4d, 0x42, 0x53, 0xef, 0xea, 0x83, 0xcf, 0xba, 0xa6, 0x64, 0x80, 0x33, 0xdd,
0xe8, 0x69, 0xa5, 0x2c, 0x7c, 0x37, 0x3e, 0xff, 0xa0, 0x95, 0xa7, 0x5b, 0xc9, 0x6f, 0xfa, 0xe5,
0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x07, 0x77, 0x70, 0x63, 0xd1, 0x05, 0x00, 0x00,
} }

View File

@@ -94,6 +94,13 @@ message LongLivedGracefulRestartCapability {
message RouteRefreshCiscoCapability { message RouteRefreshCiscoCapability {
} }
message FQDNCapability {
uint32 host_name_len = 1;
string host_name = 2;
uint32 domain_name_len = 3;
string domain_name = 4;
}
message UnknownCapability { message UnknownCapability {
uint32 code = 1; uint32 code = 1;
bytes value = 2; bytes value = 2;

File diff suppressed because it is too large Load Diff

View File

@@ -30,90 +30,92 @@ package gobgpapi;
// Interface exported by the server. // Interface exported by the server.
service GobgpApi { service GobgpApi {
rpc StartBgp(StartBgpRequest) returns (google.protobuf.Empty); rpc StartBgp(StartBgpRequest) returns(google.protobuf.Empty);
rpc StopBgp(StopBgpRequest) returns (google.protobuf.Empty); rpc StopBgp(StopBgpRequest) returns(google.protobuf.Empty);
rpc GetBgp(GetBgpRequest) returns (GetBgpResponse); rpc GetBgp(GetBgpRequest) returns(GetBgpResponse);
rpc AddPeer(AddPeerRequest) returns (google.protobuf.Empty); rpc AddPeer(AddPeerRequest) returns(google.protobuf.Empty);
rpc DeletePeer(DeletePeerRequest) returns (google.protobuf.Empty); rpc DeletePeer(DeletePeerRequest) returns(google.protobuf.Empty);
rpc ListPeer(ListPeerRequest) returns (stream ListPeerResponse); rpc ListPeer(ListPeerRequest) returns(stream ListPeerResponse);
rpc UpdatePeer(UpdatePeerRequest) returns (UpdatePeerResponse); rpc UpdatePeer(UpdatePeerRequest) returns(UpdatePeerResponse);
rpc ResetPeer(ResetPeerRequest) returns (google.protobuf.Empty); rpc ResetPeer(ResetPeerRequest) returns(google.protobuf.Empty);
rpc ShutdownPeer(ShutdownPeerRequest) returns (google.protobuf.Empty); rpc ShutdownPeer(ShutdownPeerRequest) returns(google.protobuf.Empty);
rpc EnablePeer(EnablePeerRequest) returns (google.protobuf.Empty); rpc EnablePeer(EnablePeerRequest) returns(google.protobuf.Empty);
rpc DisablePeer(DisablePeerRequest) returns (google.protobuf.Empty); rpc DisablePeer(DisablePeerRequest) returns(google.protobuf.Empty);
rpc MonitorPeer(MonitorPeerRequest) returns (stream MonitorPeerResponse); rpc MonitorPeer(MonitorPeerRequest) returns(stream MonitorPeerResponse);
rpc AddPeerGroup(AddPeerGroupRequest) returns (google.protobuf.Empty); rpc AddPeerGroup(AddPeerGroupRequest) returns(google.protobuf.Empty);
rpc DeletePeerGroup(DeletePeerGroupRequest) returns (google.protobuf.Empty); rpc DeletePeerGroup(DeletePeerGroupRequest) returns(google.protobuf.Empty);
rpc UpdatePeerGroup(UpdatePeerGroupRequest) returns (UpdatePeerGroupResponse); rpc ListPeerGroup(ListPeerGroupRequest) returns(stream ListPeerGroupResponse);
rpc UpdatePeerGroup(UpdatePeerGroupRequest) returns(UpdatePeerGroupResponse);
rpc AddDynamicNeighbor(AddDynamicNeighborRequest) returns (google.protobuf.Empty); rpc AddDynamicNeighbor(AddDynamicNeighborRequest) returns(google.protobuf.Empty);
rpc ListDynamicNeighbor(ListDynamicNeighborRequest) returns(stream ListDynamicNeighborResponse);
rpc DeleteDynamicNeighbor(DeleteDynamicNeighborRequest) returns(google.protobuf.Empty);
rpc AddPath(AddPathRequest) returns (AddPathResponse); rpc AddPath(AddPathRequest) returns(AddPathResponse);
rpc DeletePath(DeletePathRequest) returns (google.protobuf.Empty); rpc DeletePath(DeletePathRequest) returns(google.protobuf.Empty);
rpc ListPath(ListPathRequest) returns (stream ListPathResponse); rpc ListPath(ListPathRequest) returns(stream ListPathResponse);
rpc AddPathStream(stream AddPathStreamRequest) returns (google.protobuf.Empty); rpc AddPathStream(stream AddPathStreamRequest) returns(google.protobuf.Empty);
rpc GetTable(GetTableRequest) returns (GetTableResponse); rpc GetTable(GetTableRequest) returns(GetTableResponse);
rpc MonitorTable(MonitorTableRequest) returns (stream MonitorTableResponse); rpc MonitorTable(MonitorTableRequest) returns(stream MonitorTableResponse);
rpc AddVrf(AddVrfRequest) returns (google.protobuf.Empty); rpc AddVrf(AddVrfRequest) returns(google.protobuf.Empty);
rpc DeleteVrf(DeleteVrfRequest) returns (google.protobuf.Empty); rpc DeleteVrf(DeleteVrfRequest) returns(google.protobuf.Empty);
rpc ListVrf(ListVrfRequest) returns (stream ListVrfResponse); rpc ListVrf(ListVrfRequest) returns(stream ListVrfResponse);
rpc AddPolicy(AddPolicyRequest) returns (google.protobuf.Empty); rpc AddPolicy(AddPolicyRequest) returns(google.protobuf.Empty);
rpc DeletePolicy(DeletePolicyRequest) returns (google.protobuf.Empty); rpc DeletePolicy(DeletePolicyRequest) returns(google.protobuf.Empty);
rpc ListPolicy(ListPolicyRequest) returns (stream ListPolicyResponse); rpc ListPolicy(ListPolicyRequest) returns(stream ListPolicyResponse);
rpc SetPolicies(SetPoliciesRequest) returns (google.protobuf.Empty); rpc SetPolicies(SetPoliciesRequest) returns(google.protobuf.Empty);
rpc AddDefinedSet(AddDefinedSetRequest) returns (google.protobuf.Empty); rpc AddDefinedSet(AddDefinedSetRequest) returns(google.protobuf.Empty);
rpc DeleteDefinedSet(DeleteDefinedSetRequest) returns (google.protobuf.Empty); rpc DeleteDefinedSet(DeleteDefinedSetRequest) returns(google.protobuf.Empty);
rpc ListDefinedSet(ListDefinedSetRequest) returns (stream ListDefinedSetResponse); rpc ListDefinedSet(ListDefinedSetRequest)
returns(stream ListDefinedSetResponse);
rpc AddStatement(AddStatementRequest) returns (google.protobuf.Empty); rpc AddStatement(AddStatementRequest) returns(google.protobuf.Empty);
rpc DeleteStatement(DeleteStatementRequest) returns (google.protobuf.Empty); rpc DeleteStatement(DeleteStatementRequest) returns(google.protobuf.Empty);
rpc ListStatement(ListStatementRequest) returns (stream ListStatementResponse); rpc ListStatement(ListStatementRequest) returns(stream ListStatementResponse);
rpc AddPolicyAssignment(AddPolicyAssignmentRequest) returns (google.protobuf.Empty); rpc AddPolicyAssignment(AddPolicyAssignmentRequest)
rpc DeletePolicyAssignment(DeletePolicyAssignmentRequest) returns (google.protobuf.Empty); returns(google.protobuf.Empty);
rpc ListPolicyAssignment(ListPolicyAssignmentRequest) returns (stream ListPolicyAssignmentResponse); rpc DeletePolicyAssignment(DeletePolicyAssignmentRequest)
rpc SetPolicyAssignment(SetPolicyAssignmentRequest) returns (google.protobuf.Empty); returns(google.protobuf.Empty);
rpc ListPolicyAssignment(ListPolicyAssignmentRequest)
returns(stream ListPolicyAssignmentResponse);
rpc SetPolicyAssignment(SetPolicyAssignmentRequest)
returns(google.protobuf.Empty);
rpc AddRpki(AddRpkiRequest) returns (google.protobuf.Empty); rpc AddRpki(AddRpkiRequest) returns(google.protobuf.Empty);
rpc DeleteRpki(DeleteRpkiRequest) returns (google.protobuf.Empty); rpc DeleteRpki(DeleteRpkiRequest) returns(google.protobuf.Empty);
rpc ListRpki(ListRpkiRequest) returns (stream ListRpkiResponse); rpc ListRpki(ListRpkiRequest) returns(stream ListRpkiResponse);
rpc EnableRpki(EnableRpkiRequest) returns (google.protobuf.Empty); rpc EnableRpki(EnableRpkiRequest) returns(google.protobuf.Empty);
rpc DisableRpki(DisableRpkiRequest) returns (google.protobuf.Empty); rpc DisableRpki(DisableRpkiRequest) returns(google.protobuf.Empty);
rpc ResetRpki(ResetRpkiRequest) returns (google.protobuf.Empty); rpc ResetRpki(ResetRpkiRequest) returns(google.protobuf.Empty);
rpc ListRpkiTable(ListRpkiTableRequest) returns (stream ListRpkiTableResponse); rpc ListRpkiTable(ListRpkiTableRequest) returns(stream ListRpkiTableResponse);
rpc EnableZebra(EnableZebraRequest) returns (google.protobuf.Empty); rpc EnableZebra(EnableZebraRequest) returns(google.protobuf.Empty);
rpc EnableMrt(EnableMrtRequest) returns (google.protobuf.Empty); rpc EnableMrt(EnableMrtRequest) returns(google.protobuf.Empty);
rpc DisableMrt(DisableMrtRequest) returns (google.protobuf.Empty); rpc DisableMrt(DisableMrtRequest) returns(google.protobuf.Empty);
rpc AddBmp(AddBmpRequest) returns (google.protobuf.Empty); rpc AddBmp(AddBmpRequest) returns(google.protobuf.Empty);
rpc DeleteBmp(DeleteBmpRequest) returns (google.protobuf.Empty); rpc DeleteBmp(DeleteBmpRequest) returns(google.protobuf.Empty);
rpc SetLogLevel(SetLogLevelRequest) returns(google.protobuf.Empty);
} }
message StartBgpRequest { message StartBgpRequest { Global global = 1; }
Global global = 1;
}
message StopBgpRequest { message StopBgpRequest {}
}
message GetBgpRequest { message GetBgpRequest {}
}
message GetBgpResponse { message GetBgpResponse { Global global = 1; }
Global global = 1;
}
message AddPeerRequest { message AddPeerRequest { Peer peer = 1; }
Peer peer = 1;
}
message DeletePeerRequest { message DeletePeerRequest {
string address = 1; string address = 1;
@@ -125,9 +127,7 @@ message ListPeerRequest {
bool enableAdvertised = 2; bool enableAdvertised = 2;
} }
message ListPeerResponse { message ListPeerResponse { Peer peer = 1; }
Peer peer = 1;
}
message UpdatePeerRequest { message UpdatePeerRequest {
Peer peer = 1; Peer peer = 1;
@@ -147,11 +147,7 @@ message ResetPeerRequest {
string address = 1; string address = 1;
string communication = 2; string communication = 2;
bool soft = 3; bool soft = 3;
enum SoftResetDirection { enum SoftResetDirection { IN = 0; OUT = 1; BOTH = 2; }
IN = 0;
OUT = 1;
BOTH = 2;
}
SoftResetDirection direction = 4; SoftResetDirection direction = 4;
} }
@@ -160,9 +156,7 @@ message ShutdownPeerRequest {
string communication = 2; string communication = 2;
} }
message EnablePeerRequest { message EnablePeerRequest { string address = 1; }
string address = 1;
}
message DisablePeerRequest { message DisablePeerRequest {
string address = 1; string address = 1;
@@ -171,33 +165,37 @@ message DisablePeerRequest {
message MonitorPeerRequest { message MonitorPeerRequest {
string address = 1; string address = 1;
bool current = 2; bool current = 2; // Prefer initial_state.
bool initial_state = 3;
} }
message MonitorPeerResponse { message MonitorPeerResponse { Peer peer = 1; }
Peer peer = 1;
}
message AddPeerGroupRequest { message AddPeerGroupRequest { PeerGroup peer_group = 1; }
PeerGroup peer_group = 1;
}
message DeletePeerGroupRequest { message DeletePeerGroupRequest { string name = 1; }
string name = 1;
}
message UpdatePeerGroupRequest { message UpdatePeerGroupRequest {
PeerGroup peer_group = 1; PeerGroup peer_group = 1;
bool do_soft_reset_in = 2; bool do_soft_reset_in = 2;
} }
message UpdatePeerGroupResponse { message UpdatePeerGroupResponse { bool needs_soft_reset_in = 1; }
bool needs_soft_reset_in = 1;
message ListPeerGroupRequest { string peer_group_name = 1; }
message ListPeerGroupResponse { PeerGroup peer_group = 1; }
message AddDynamicNeighborRequest { DynamicNeighbor dynamic_neighbor = 1; }
message DeleteDynamicNeighborRequest {
string prefix = 1;
string peer_group = 2;
} }
message AddDynamicNeighborRequest { message ListDynamicNeighborRequest { string peer_group = 1; }
DynamicNeighbor dynamic_neighbor = 1;
} message ListDynamicNeighborResponse { DynamicNeighbor dynamic_neighbor = 1; }
message AddPathRequest { message AddPathRequest {
TableType table_type = 1; TableType table_type = 1;
@@ -205,9 +203,7 @@ message AddPathRequest {
Path path = 3; Path path = 3;
} }
message AddPathResponse { message AddPathResponse { bytes uuid = 1; }
bytes uuid = 1;
}
message DeletePathRequest { message DeletePathRequest {
TableType table_type = 1; TableType table_type = 1;
@@ -222,17 +218,14 @@ message ListPathRequest {
string name = 2; string name = 2;
Family family = 3; Family family = 3;
repeated TableLookupPrefix prefixes = 4; repeated TableLookupPrefix prefixes = 4;
enum SortType { enum SortType { NONE = 0; PREFIX = 1; }
NONE = 0;
PREFIX = 1;
}
SortType sort_type = 5; SortType sort_type = 5;
bool enable_filtered = 6; bool enable_filtered = 6;
bool enable_nlri_binary = 7;
bool enable_attribute_binary = 8;
} }
message ListPathResponse { message ListPathResponse { Destination destination = 1; }
Destination destination = 1;
}
message AddPathStreamRequest { message AddPathStreamRequest {
TableType table_type = 1; TableType table_type = 1;
@@ -260,25 +253,15 @@ message MonitorTableRequest {
bool post_policy = 5; bool post_policy = 5;
} }
message MonitorTableResponse { message MonitorTableResponse { Path path = 1; }
Path path = 1;
}
message AddVrfRequest { message AddVrfRequest { Vrf vrf = 1; }
Vrf vrf = 1;
}
message DeleteVrfRequest { message DeleteVrfRequest { string name = 1; }
string name = 1;
}
message ListVrfRequest { message ListVrfRequest { string name = 1; }
string name = 1;
}
message ListVrfResponse { message ListVrfResponse { Vrf vrf = 1; }
Vrf vrf = 1;
}
message AddPolicyRequest { message AddPolicyRequest {
Policy policy = 1; Policy policy = 1;
@@ -295,13 +278,9 @@ message DeletePolicyRequest {
bool all = 3; bool all = 3;
} }
message ListPolicyRequest { message ListPolicyRequest { string name = 1; }
string name = 1;
}
message ListPolicyResponse { message ListPolicyResponse { Policy policy = 1; }
Policy policy = 1;
}
message SetPoliciesRequest { message SetPoliciesRequest {
repeated DefinedSet defined_sets = 1; repeated DefinedSet defined_sets = 1;
@@ -309,9 +288,7 @@ message SetPoliciesRequest {
repeated PolicyAssignment assignments = 3; repeated PolicyAssignment assignments = 3;
} }
message AddDefinedSetRequest { message AddDefinedSetRequest { DefinedSet defined_set = 1; }
DefinedSet defined_set = 1;
}
message DeleteDefinedSetRequest { message DeleteDefinedSetRequest {
DefinedSet defined_set = 1; DefinedSet defined_set = 1;
@@ -323,30 +300,20 @@ message ListDefinedSetRequest {
string name = 2; string name = 2;
} }
message ListDefinedSetResponse { message ListDefinedSetResponse { DefinedSet defined_set = 1; }
DefinedSet defined_set = 1;
}
message AddStatementRequest { message AddStatementRequest { Statement statement = 1; }
Statement statement = 1;
}
message DeleteStatementRequest { message DeleteStatementRequest {
Statement statement = 1; Statement statement = 1;
bool all = 2; bool all = 2;
} }
message ListStatementRequest { message ListStatementRequest { string name = 1; }
string name = 1;
}
message ListStatementResponse { message ListStatementResponse { Statement statement = 1; }
Statement statement = 1;
}
message AddPolicyAssignmentRequest { message AddPolicyAssignmentRequest { PolicyAssignment assignment = 1; }
PolicyAssignment assignment = 1;
}
message DeletePolicyAssignmentRequest { message DeletePolicyAssignmentRequest {
PolicyAssignment assignment = 1; PolicyAssignment assignment = 1;
@@ -358,13 +325,9 @@ message ListPolicyAssignmentRequest {
PolicyDirection direction = 2; PolicyDirection direction = 2;
} }
message ListPolicyAssignmentResponse { message ListPolicyAssignmentResponse { PolicyAssignment assignment = 1; }
PolicyAssignment assignment = 1;
}
message SetPolicyAssignmentRequest { message SetPolicyAssignmentRequest { PolicyAssignment assignment = 1; }
PolicyAssignment assignment = 1;
}
message AddRpkiRequest { message AddRpkiRequest {
string address = 1; string address = 1;
@@ -377,13 +340,9 @@ message DeleteRpkiRequest {
uint32 port = 2; uint32 port = 2;
} }
message ListRpkiRequest { message ListRpkiRequest { Family family = 1; }
Family family = 1;
}
message ListRpkiResponse { message ListRpkiResponse { Rpki server = 1; }
Rpki server = 1;
}
message EnableRpkiRequest { message EnableRpkiRequest {
string address = 1; string address = 1;
@@ -401,13 +360,9 @@ message ResetRpkiRequest {
bool soft = 3; bool soft = 3;
} }
message ListRpkiTableRequest { message ListRpkiTableRequest { Family family = 1; }
Family family = 1;
}
message ListRpkiTableResponse { message ListRpkiTableResponse { Roa roa = 1; }
Roa roa = 1;
}
message EnableZebraRequest { message EnableZebraRequest {
string url = 1; string url = 1;
@@ -426,19 +381,12 @@ message EnableMrtRequest {
uint64 rotation_interval = 4; uint64 rotation_interval = 4;
} }
message DisableMrtRequest { message DisableMrtRequest {}
}
message AddBmpRequest { message AddBmpRequest {
string address = 1; string address = 1;
uint32 port = 2; uint32 port = 2;
enum MonitoringPolicy { enum MonitoringPolicy { PRE = 0; POST = 1; BOTH = 2; LOCAL = 3; ALL = 4; }
PRE = 0;
POST = 1;
BOTH = 2;
LOCAL = 3;
ALL = 4;
}
MonitoringPolicy policy = 3; MonitoringPolicy policy = 3;
int32 StatisticsTimeout = 4; int32 StatisticsTimeout = 4;
string SysName = 5; string SysName = 5;
@@ -452,23 +400,17 @@ message DeleteBmpRequest {
message Family { message Family {
enum Afi { enum Afi {
AFI_UNKNOWN = 0; AFI_UNKNOWN = 0; AFI_IP = 1; AFI_IP6 = 2; AFI_L2VPN = 25; AFI_LS = 16388;
AFI_IP = 1;
AFI_IP6 = 2;
AFI_L2VPN = 25;
AFI_LS = 16388;
AFI_OPAQUE = 16397; AFI_OPAQUE = 16397;
} }
enum Safi { enum Safi {
SAFI_UNKNOWN = 0; SAFI_UNKNOWN = 0; SAFI_UNICAST = 1; SAFI_MULTICAST = 2; SAFI_MPLS_LABEL = 4;
SAFI_UNICAST = 1;
SAFI_MULTICAST = 2;
SAFI_MPLS_LABEL = 4;
SAFI_ENCAPSULATION = 7; SAFI_ENCAPSULATION = 7;
SAFI_VPLS = 65; SAFI_VPLS = 65;
SAFI_EVPN = 70; SAFI_EVPN = 70;
SAFI_LS = 71; SAFI_LS = 71;
SAFI_SR_POLICY = 73;
SAFI_MPLS_VPN = 128; SAFI_MPLS_VPN = 128;
SAFI_MPLS_VPN_MULTICAST = 129; SAFI_MPLS_VPN_MULTICAST = 129;
SAFI_ROUTE_TARGET_CONSTRAINTS = 132; SAFI_ROUTE_TARGET_CONSTRAINTS = 132;
@@ -481,27 +423,14 @@ message Family {
Safi safi = 2; Safi safi = 2;
} }
enum TableType { enum TableType { GLOBAL = 0; LOCAL = 1; ADJ_IN = 2; ADJ_OUT = 3; VRF = 4; }
GLOBAL = 0;
LOCAL = 1;
ADJ_IN = 2;
ADJ_OUT = 3;
VRF = 4;
}
message Validation { message Validation {
enum State { enum State {
STATE_NONE = 0; STATE_NONE = 0; STATE_NOT_FOUND = 1; STATE_VALID = 2; STATE_INVALID = 3;
STATE_NOT_FOUND = 1;
STATE_VALID = 2;
STATE_INVALID = 3;
} }
enum Reason { enum Reason { REASOT_NONE = 0; REASON_AS = 1; REASON_LENGTH = 2; }
REASOT_NONE = 0;
REASON_AS = 1;
REASON_LENGTH = 2;
}
State state = 1; State state = 1;
Reason reason = 2; Reason reason = 2;
@@ -527,6 +456,7 @@ message Path {
// - VPNFlowSpecNLRI // - VPNFlowSpecNLRI
// - OpaqueNLRI // - OpaqueNLRI
// - LsAddrPrefix // - LsAddrPrefix
// - SRPolicyNLRI
google.protobuf.Any nlri = 1; google.protobuf.Any nlri = 1;
// Each attribute must be one of *Attribute defined in // Each attribute must be one of *Attribute defined in
// "api/attribute.proto". // "api/attribute.proto".
@@ -558,9 +488,7 @@ message Destination {
// API representation of table.LookupOption // API representation of table.LookupOption
enum TableLookupOption { enum TableLookupOption {
LOOKUP_EXACT = 0; LOOKUP_EXACT = 0; LOOKUP_LONGER = 1; LOOKUP_SHORTER = 2;
LOOKUP_LONGER = 1;
LOOKUP_SHORTER = 2;
} }
// API representation of table.LookupPrefix // API representation of table.LookupPrefix
@@ -580,6 +508,7 @@ message Peer {
RouteServer route_server = 8; RouteServer route_server = 8;
GracefulRestart graceful_restart = 9; GracefulRestart graceful_restart = 9;
repeated AfiSafi afi_safis = 10; repeated AfiSafi afi_safis = 10;
TtlSecurity ttl_security = 11;
} }
message PeerGroup { message PeerGroup {
@@ -593,6 +522,7 @@ message PeerGroup {
RouteServer route_server = 8; RouteServer route_server = 8;
GracefulRestart graceful_restart = 9; GracefulRestart graceful_restart = 9;
repeated AfiSafi afi_safis = 10; repeated AfiSafi afi_safis = 10;
TtlSecurity ttl_security = 11;
} }
message DynamicNeighbor { message DynamicNeighbor {
@@ -620,11 +550,7 @@ message PeerConf {
uint32 peer_as = 5; uint32 peer_as = 5;
string peer_group = 6; string peer_group = 6;
uint32 peer_type = 7; uint32 peer_type = 7;
enum RemovePrivateAs { enum RemovePrivateAs { NONE = 0; ALL = 1; REPLACE = 2; }
NONE = 0;
ALL = 1;
REPLACE = 2;
}
RemovePrivateAs remove_private_as = 8; RemovePrivateAs remove_private_as = 8;
bool route_flap_damping = 9; bool route_flap_damping = 9;
uint32 send_community = 10; uint32 send_community = 10;
@@ -642,11 +568,7 @@ message PeerGroupConf {
uint32 peer_as = 4; uint32 peer_as = 4;
string peer_group_name = 5; string peer_group_name = 5;
uint32 peer_type = 6; uint32 peer_type = 6;
enum RemovePrivateAs { enum RemovePrivateAs { NONE = 0; ALL = 1; REPLACE = 2; }
NONE = 0;
ALL = 1;
REPLACE = 2;
}
RemovePrivateAs remove_private_as = 7; RemovePrivateAs remove_private_as = 7;
bool route_flap_damping = 8; bool route_flap_damping = 8;
uint32 send_community = 9; uint32 send_community = 9;
@@ -659,11 +581,7 @@ message PeerGroupState {
uint32 peer_as = 4; uint32 peer_as = 4;
string peer_group_name = 5; string peer_group_name = 5;
uint32 peer_type = 6; uint32 peer_type = 6;
enum RemovePrivateAs { enum RemovePrivateAs { NONE = 0; ALL = 1; REPLACE = 2; }
NONE = 0;
ALL = 1;
REPLACE = 2;
}
RemovePrivateAs remove_private_as = 7; RemovePrivateAs remove_private_as = 7;
bool route_flap_damping = 8; bool route_flap_damping = 8;
uint32 send_community = 9; uint32 send_community = 9;
@@ -671,6 +589,11 @@ message PeerGroupState {
uint32 total_prefixes = 11; uint32 total_prefixes = 11;
} }
message TtlSecurity {
bool enabled = 1;
uint32 ttl_min = 2;
}
message EbgpMultihop { message EbgpMultihop {
bool enabled = 1; bool enabled = 1;
uint32 multihop_ttl = 2; uint32 multihop_ttl = 2;
@@ -695,19 +618,13 @@ message PeerState {
bool route_flap_damping = 11; bool route_flap_damping = 11;
uint32 send_community = 12; uint32 send_community = 12;
enum SessionState { enum SessionState {
UNKNOWN = 0; UNKNOWN = 0; IDLE = 1; CONNECT = 2; ACTIVE = 3; OPENSENT = 4;
IDLE = 1;
CONNECT = 2;
ACTIVE = 3;
OPENSENT = 4;
OPENCONFIRM = 5; OPENCONFIRM = 5;
ESTABLISHED = 6; ESTABLISHED = 6;
} }
SessionState session_state = 13; SessionState session_state = 13;
enum AdminState { enum AdminState {
UP = 0; UP = 0; DOWN = 1; PFX_CT = 2; // prefix counter over limit
DOWN = 1;
PFX_CT = 2; // prefix counter over limit
} }
AdminState admin_state = 15; AdminState admin_state = 15;
uint32 out_q = 16; uint32 out_q = 16;
@@ -742,11 +659,11 @@ message Queues {
} }
message Timers { message Timers {
TimersConfig config =1; TimersConfig config = 1;
TimersState state = 2; TimersState state = 2;
} }
message TimersConfig{ message TimersConfig {
uint64 connect_retry = 1; uint64 connect_retry = 1;
uint64 hold_time = 2; uint64 hold_time = 2;
uint64 keepalive_interval = 3; uint64 keepalive_interval = 3;
@@ -754,7 +671,7 @@ message TimersConfig{
uint64 idle_hold_time_after_reset = 5; uint64 idle_hold_time_after_reset = 5;
} }
message TimersState{ message TimersState {
uint64 connect_retry = 1; uint64 connect_retry = 1;
uint64 hold_time = 2; uint64 hold_time = 2;
uint64 keepalive_interval = 3; uint64 keepalive_interval = 3;
@@ -794,9 +711,7 @@ message GracefulRestart {
string mode = 11; string mode = 11;
} }
message MpGracefulRestartConfig { message MpGracefulRestartConfig { bool enabled = 1; }
bool enabled = 1;
}
message MpGracefulRestartState { message MpGracefulRestartState {
bool enabled = 1; bool enabled = 1;
@@ -848,13 +763,9 @@ message RouteSelectionOptions {
RouteSelectionOptionsState state = 2; RouteSelectionOptionsState state = 2;
} }
message UseMultiplePathsConfig { message UseMultiplePathsConfig { bool enabled = 1; }
bool enabled = 1;
}
message UseMultiplePathsState { message UseMultiplePathsState { bool enabled = 1; }
bool enabled = 1;
}
message EbgpConfig { message EbgpConfig {
bool allow_multiple_as = 1; bool allow_multiple_as = 1;
@@ -871,13 +782,9 @@ message Ebgp {
EbgpState state = 2; EbgpState state = 2;
} }
message IbgpConfig { message IbgpConfig { uint32 maximum_paths = 1; }
uint32 maximum_paths = 1;
}
message IbgpState { message IbgpState { uint32 maximum_paths = 1; }
uint32 maximum_paths = 1;
}
message Ibgp { message Ibgp {
IbgpConfig config = 1; IbgpConfig config = 1;
@@ -891,13 +798,9 @@ message UseMultiplePaths {
Ibgp ibgp = 4; Ibgp ibgp = 4;
} }
message RouteTargetMembershipConfig { message RouteTargetMembershipConfig { uint32 deferral_time = 1; }
uint32 deferral_time = 1;
}
message RouteTargetMembershipState { message RouteTargetMembershipState { uint32 deferral_time = 1; }
uint32 deferral_time = 1;
}
message RouteTargetMembership { message RouteTargetMembership {
RouteTargetMembershipConfig config = 1; RouteTargetMembershipConfig config = 1;
@@ -969,11 +872,7 @@ message Prefix {
} }
enum DefinedType { enum DefinedType {
PREFIX = 0; PREFIX = 0; NEIGHBOR = 1; TAG = 2; AS_PATH = 3; COMMUNITY = 4;
NEIGHBOR = 1;
TAG = 2;
AS_PATH = 3;
COMMUNITY = 4;
EXT_COMMUNITY = 5; EXT_COMMUNITY = 5;
LARGE_COMMUNITY = 6; LARGE_COMMUNITY = 6;
NEXT_HOP = 7; NEXT_HOP = 7;
@@ -986,22 +885,14 @@ message DefinedSet {
repeated Prefix prefixes = 4; repeated Prefix prefixes = 4;
} }
enum MatchType { enum MatchType { ANY = 0; ALL = 1; INVERT = 2; }
ANY = 0;
ALL = 1;
INVERT = 2;
}
message MatchSet { message MatchSet {
MatchType match_type = 1; MatchType match_type = 1;
string name = 2; string name = 2;
} }
enum AsPathLengthType { enum AsPathLengthType { EQ = 0; GE = 1; LE = 2; }
EQ = 0;
GE = 1;
LE = 2;
}
message AsPathLength { message AsPathLength {
AsPathLengthType length_type = 1; AsPathLengthType length_type = 1;
@@ -1017,9 +908,7 @@ message Conditions {
MatchSet ext_community_set = 6; MatchSet ext_community_set = 6;
int32 rpki_result = 7; int32 rpki_result = 7;
enum RouteType { enum RouteType {
ROUTE_TYPE_NONE = 0; ROUTE_TYPE_NONE = 0; ROUTE_TYPE_INTERNAL = 1; ROUTE_TYPE_EXTERNAL = 2;
ROUTE_TYPE_INTERNAL = 1;
ROUTE_TYPE_EXTERNAL = 2;
ROUTE_TYPE_LOCAL = 3; ROUTE_TYPE_LOCAL = 3;
} }
RouteType route_type = 8; RouteType route_type = 8;
@@ -1028,16 +917,10 @@ message Conditions {
repeated Family afi_safi_in = 11; repeated Family afi_safi_in = 11;
} }
enum RouteAction { enum RouteAction { NONE = 0; ACCEPT = 1; REJECT = 2; }
NONE = 0;
ACCEPT = 1;
REJECT = 2;
}
enum CommunityActionType { enum CommunityActionType {
COMMUNITY_ADD = 0; COMMUNITY_ADD = 0; COMMUNITY_REMOVE = 1; COMMUNITY_REPLACE = 2;
COMMUNITY_REMOVE = 1;
COMMUNITY_REPLACE = 2;
} }
message CommunityAction { message CommunityAction {
@@ -1045,10 +928,7 @@ message CommunityAction {
repeated string communities = 2; repeated string communities = 2;
} }
enum MedActionType { enum MedActionType { MED_MOD = 0; MED_REPLACE = 1; }
MED_MOD = 0;
MED_REPLACE = 1;
}
message MedAction { message MedAction {
MedActionType action_type = 1; MedActionType action_type = 1;
@@ -1064,11 +944,10 @@ message AsPrependAction {
message NexthopAction { message NexthopAction {
string address = 1; string address = 1;
bool self = 2; bool self = 2;
bool unchanged = 3;
} }
message LocalPrefAction { message LocalPrefAction { uint32 value = 1; }
uint32 value = 1;
}
message Actions { message Actions {
RouteAction route_action = 1; RouteAction route_action = 1;
@@ -1092,11 +971,7 @@ message Policy {
repeated Statement statements = 2; repeated Statement statements = 2;
} }
enum PolicyDirection { enum PolicyDirection { UNKNOWN = 0; IMPORT = 1; EXPORT = 2; }
UNKNOWN = 0;
IMPORT = 1;
EXPORT = 2;
}
message PolicyAssignment { message PolicyAssignment {
string name = 1; string name = 1;
@@ -1155,6 +1030,7 @@ message Global {
Confederation confederation = 9; Confederation confederation = 9;
GracefulRestart graceful_restart = 10; GracefulRestart graceful_restart = 10;
ApplyPolicy apply_policy = 11; ApplyPolicy apply_policy = 11;
string bind_to_device = 12;
} }
message Confederation { message Confederation {
@@ -1192,3 +1068,10 @@ message Rpki {
RPKIConf conf = 1; RPKIConf conf = 1;
RPKIState state = 2; RPKIState state = 2;
} }
message SetLogLevelRequest {
enum Level {
PANIC = 0; FATAL = 1; ERROR = 2; WARN = 3; INFO = 4; DEBUG = 5; TRACE = 6;
}
Level level = 1;
}

View File

@@ -636,26 +636,52 @@ func MarshalNLRI(value bgp.AddrPrefixInterface) *any.Any {
nlri = &api.LsAddrPrefix{ nlri = &api.LsAddrPrefix{
Type: api.LsNLRIType_LS_NLRI_NODE, Type: api.LsNLRIType_LS_NLRI_NODE,
Nlri: MarshalLsNodeNLRI(n), Nlri: MarshalLsNodeNLRI(n),
Length: uint32(n.Length),
ProtocolId: api.LsProtocolID(n.ProtocolID),
Identifier: n.Identifier,
} }
case *bgp.LsLinkNLRI: case *bgp.LsLinkNLRI:
nlri = &api.LsAddrPrefix{ nlri = &api.LsAddrPrefix{
Type: api.LsNLRIType_LS_NLRI_LINK, Type: api.LsNLRIType_LS_NLRI_LINK,
Nlri: MarshalLsLinkNLRI(n), Nlri: MarshalLsLinkNLRI(n),
Length: uint32(n.Length),
ProtocolId: api.LsProtocolID(n.ProtocolID),
Identifier: n.Identifier,
} }
case *bgp.LsPrefixV4NLRI: case *bgp.LsPrefixV4NLRI:
nlri = &api.LsAddrPrefix{ nlri = &api.LsAddrPrefix{
Type: api.LsNLRIType_LS_NLRI_PREFIX_V4, Type: api.LsNLRIType_LS_NLRI_PREFIX_V4,
Nlri: MarshalLsPrefixV4NLRI(n), Nlri: MarshalLsPrefixV4NLRI(n),
Length: uint32(n.Length),
ProtocolId: api.LsProtocolID(n.ProtocolID),
Identifier: n.Identifier,
} }
case *bgp.LsPrefixV6NLRI: case *bgp.LsPrefixV6NLRI:
nlri = &api.LsAddrPrefix{ nlri = &api.LsAddrPrefix{
Type: api.LsNLRIType_LS_NLRI_PREFIX_V6, Type: api.LsNLRIType_LS_NLRI_PREFIX_V6,
Nlri: MarshalLsPrefixV6NLRI(n), Nlri: MarshalLsPrefixV6NLRI(n),
Length: uint32(n.Length),
ProtocolId: api.LsProtocolID(n.ProtocolID),
Identifier: n.Identifier,
} }
} }
case *bgp.SRPolicyIPv4:
nlri = &api.SRPolicyNLRI{
Length: uint32(v.Length),
Distinguisher: v.Distinguisher,
Color: v.Color,
Endpoint: v.Endpoint,
}
case *bgp.SRPolicyIPv6:
nlri = &api.SRPolicyNLRI{
Length: uint32(v.Length),
Distinguisher: v.Distinguisher,
Color: v.Color,
Endpoint: v.Endpoint,
}
} }
an, _ := ptypes.MarshalAny(nlri) an, _ := ptypes.MarshalAny(nlri)
@@ -756,6 +782,13 @@ func UnmarshalNLRI(rf bgp.RouteFamily, an *any.Any) (bgp.AddrPrefixInterface, er
} }
nlri = bgp.NewEVPNIPPrefixRoute(rd, *esi, v.EthernetTag, uint8(v.IpPrefixLen), v.IpPrefix, v.GwAddress, v.Label) nlri = bgp.NewEVPNIPPrefixRoute(rd, *esi, v.EthernetTag, uint8(v.IpPrefixLen), v.IpPrefix, v.GwAddress, v.Label)
} }
case *api.SRPolicyNLRI:
switch rf {
case bgp.RF_SR_POLICY_IPv4:
nlri = bgp.NewSRPolicyIPv4(v.Length, v.Distinguisher, v.Color, v.Endpoint)
case bgp.RF_SR_POLICY_IPv6:
nlri = bgp.NewSRPolicyIPv6(v.Length, v.Distinguisher, v.Color, v.Endpoint)
}
case *api.LabeledVPNIPAddressPrefix: case *api.LabeledVPNIPAddressPrefix:
rd, err := UnmarshalRD(v.Rd) rd, err := UnmarshalRD(v.Rd)
if err != nil { if err != nil {
@@ -828,7 +861,7 @@ func NewMpReachNLRIAttributeFromNative(a *bgp.PathAttributeMpReachNLRI) *api.MpR
nexthops = nil nexthops = nil
} else { } else {
nexthops = []string{a.Nexthop.String()} nexthops = []string{a.Nexthop.String()}
if a.LinkLocalNexthop != nil { if a.LinkLocalNexthop != nil && a.LinkLocalNexthop.IsLinkLocalUnicast() {
nexthops = append(nexthops, a.LinkLocalNexthop.String()) nexthops = append(nexthops, a.LinkLocalNexthop.String())
} }
} }
@@ -951,6 +984,11 @@ func NewExtendedCommunitiesAttributeFromNative(a *bgp.PathAttributeExtendedCommu
community = &api.ValidationExtended{ community = &api.ValidationExtended{
State: uint32(v.State), State: uint32(v.State),
} }
case *bgp.LinkBandwidthExtended:
community = &api.LinkBandiwdthExtended{
As: uint32(v.AS),
Bandwidth: v.Bandwidth,
}
case *bgp.ColorExtended: case *bgp.ColorExtended:
community = &api.ColorExtended{ community = &api.ColorExtended{
Color: v.Color, Color: v.Color,
@@ -1050,6 +1088,8 @@ func unmarshalExComm(a *api.ExtendedCommunitiesAttribute) (*bgp.PathAttributeExt
community = bgp.NewFourOctetAsSpecificExtended(bgp.ExtendedCommunityAttrSubType(v.SubType), v.As, uint16(v.LocalAdmin), v.IsTransitive) community = bgp.NewFourOctetAsSpecificExtended(bgp.ExtendedCommunityAttrSubType(v.SubType), v.As, uint16(v.LocalAdmin), v.IsTransitive)
case *api.ValidationExtended: case *api.ValidationExtended:
community = bgp.NewValidationExtended(bgp.ValidationState(v.State)) community = bgp.NewValidationExtended(bgp.ValidationState(v.State))
case *api.LinkBandiwdthExtended:
community = bgp.NewLinkBandwidthExtended(uint16(v.As), v.Bandwidth)
case *api.ColorExtended: case *api.ColorExtended:
community = bgp.NewColorExtended(v.Color) community = bgp.NewColorExtended(v.Color)
case *api.EncapExtended: case *api.EncapExtended:
@@ -1143,11 +1183,49 @@ func NewTunnelEncapAttributeFromNative(a *bgp.PathAttributeTunnelEncap) *api.Tun
subTlv = &api.TunnelEncapSubTLVColor{ subTlv = &api.TunnelEncapSubTLVColor{
Color: sv.Color, Color: sv.Color,
} }
case *bgp.TunnelEncapSubTLVEgressEndpoint:
subTlv = &api.TunnelEncapSubTLVEgressEndpoint{
Address: sv.Address.String(),
}
case *bgp.TunnelEncapSubTLVUDPDestPort:
subTlv = &api.TunnelEncapSubTLVUDPDestPort{
Port: uint32(sv.UDPDestPort),
}
case *bgp.TunnelEncapSubTLVUnknown: case *bgp.TunnelEncapSubTLVUnknown:
subTlv = &api.TunnelEncapSubTLVUnknown{ subTlv = &api.TunnelEncapSubTLVUnknown{
Type: uint32(sv.Type), Type: uint32(sv.Type),
Value: sv.Value, Value: sv.Value,
} }
case *bgp.TunnelEncapSubTLVSRBSID:
subTlv = MarshalSRBSID(sv)
// TODO (sbezverk) Add processing of SRv6 Binding SID when it gets assigned ID
case *bgp.TunnelEncapSubTLVSRCandidatePathName:
subTlv = &api.TunnelEncapSubTLVSRCandidatePathName{
CandidatePathName: sv.CandidatePathName,
}
// TODO (sbezverk) Add processing of SR Policy name when it gets assigned ID
case *bgp.TunnelEncapSubTLVSRENLP:
subTlv = &api.TunnelEncapSubTLVSRENLP{
Flags: uint32(sv.Flags),
Enlp: api.ENLPType(sv.ENLP),
}
case *bgp.TunnelEncapSubTLVSRPreference:
subTlv = &api.TunnelEncapSubTLVSRPreference{
Flags: uint32(sv.Flags),
Preference: sv.Preference,
}
case *bgp.TunnelEncapSubTLVSRPriority:
subTlv = &api.TunnelEncapSubTLVSRPriority{
Priority: uint32(sv.Priority),
}
case *bgp.TunnelEncapSubTLVSRSegmentList:
subTlv = &api.TunnelEncapSubTLVSRSegmentList{
Weight: &api.SRWeight{
Flags: uint32(sv.Weight.Flags),
Weight: uint32(sv.Weight.Weight),
},
Segments: MarshalSRSegments(sv.Segments),
}
} }
an, _ := ptypes.MarshalAny(subTlv) an, _ := ptypes.MarshalAny(subTlv)
subTlvs = append(subTlvs, an) subTlvs = append(subTlvs, an)
@@ -1433,6 +1511,9 @@ func MarshalPathAttributes(attrList []bgp.PathAttributeInterface) []*any.Any {
case *bgp.PathAttributeLs: case *bgp.PathAttributeLs:
n, _ := ptypes.MarshalAny(NewLsAttributeFromNative(a)) n, _ := ptypes.MarshalAny(NewLsAttributeFromNative(a))
anyList = append(anyList, n) anyList = append(anyList, n)
case *bgp.PathAttributePrefixSID:
n, _ := ptypes.MarshalAny(NewPrefixSIDAttributeFromNative(a))
anyList = append(anyList, n)
case *bgp.PathAttributeUnknown: case *bgp.PathAttributeUnknown:
n, _ := ptypes.MarshalAny(NewUnknownAttributeFromNative(a)) n, _ := ptypes.MarshalAny(NewUnknownAttributeFromNative(a))
anyList = append(anyList, n) anyList = append(anyList, n)
@@ -1506,6 +1587,9 @@ func unmarshalAttribute(an *any.Any) (bgp.PathAttributeInterface, error) {
} }
return bgp.NewPathAttributeClusterList(a.Ids), nil return bgp.NewPathAttributeClusterList(a.Ids), nil
case *api.MpReachNLRIAttribute: case *api.MpReachNLRIAttribute:
if a.Family == nil {
return nil, fmt.Errorf("empty family")
}
rf := ToRouteFamily(a.Family) rf := ToRouteFamily(a.Family)
nlris, err := UnmarshalNLRIs(rf, a.Nlris) nlris, err := UnmarshalNLRIs(rf, a.Nlris)
if err != nil { if err != nil {
@@ -1589,10 +1673,62 @@ func unmarshalAttribute(an *any.Any) (bgp.PathAttributeInterface, error) {
subTlv = bgp.NewTunnelEncapSubTLVProtocol(uint16(sv.Protocol)) subTlv = bgp.NewTunnelEncapSubTLVProtocol(uint16(sv.Protocol))
case *api.TunnelEncapSubTLVColor: case *api.TunnelEncapSubTLVColor:
subTlv = bgp.NewTunnelEncapSubTLVColor(sv.Color) subTlv = bgp.NewTunnelEncapSubTLVColor(sv.Color)
case *api.TunnelEncapSubTLVEgressEndpoint:
subTlv = bgp.NewTunnelEncapSubTLVEgressEndpoint(sv.Address)
case *api.TunnelEncapSubTLVUDPDestPort:
subTlv = bgp.NewTunnelEncapSubTLVUDPDestPort(uint16(sv.Port))
case *api.TunnelEncapSubTLVSRPreference:
subTlv = bgp.NewTunnelEncapSubTLVSRPreference(sv.Flags, sv.Preference)
case *api.TunnelEncapSubTLVSRPriority:
subTlv = bgp.NewTunnelEncapSubTLVSRPriority(uint8(sv.Priority))
case *api.TunnelEncapSubTLVSRCandidatePathName:
subTlv = bgp.NewTunnelEncapSubTLVSRCandidatePathName(sv.CandidatePathName)
case *api.TunnelEncapSubTLVSRENLP:
subTlv = bgp.NewTunnelEncapSubTLVSRENLP(sv.Flags, bgp.SRENLPValue(sv.Enlp))
case *api.TunnelEncapSubTLVSRBindingSID:
var err error
subTlv, err = UnmarshalSRBSID(sv.Bsid)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal tunnel encapsulation attribute sub tlv: %s", err)
}
case *api.TunnelEncapSubTLVSRSegmentList:
var err error
weight := uint32(0)
flags := uint8(0)
if sv.Weight != nil {
weight = sv.Weight.Weight
flags = uint8(sv.Weight.Flags)
}
s := &bgp.TunnelEncapSubTLVSRSegmentList{
TunnelEncapSubTLV: bgp.TunnelEncapSubTLV{
Type: bgp.ENCAP_SUBTLV_TYPE_SRSEGMENT_LIST,
Length: uint16(6), // Weight (6 bytes) + length of segment (added later, after all segments are discovered)
},
Weight: &bgp.SegmentListWeight{
TunnelEncapSubTLV: bgp.TunnelEncapSubTLV{
Type: bgp.SegmentListSubTLVWeight,
Length: uint16(6),
},
Flags: flags,
Weight: weight,
},
Segments: make([]bgp.TunnelEncapSubTLVInterface, 0),
}
if len(sv.Segments) != 0 {
s.Segments, err = UnmarshalSRSegments(sv.Segments)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal tunnel encapsulation attribute sub tlv: %s", err)
}
}
// Get total length of Segment List Sub TLV
for _, seg := range s.Segments {
s.TunnelEncapSubTLV.Length += uint16(seg.Len() + 2) // Adding 1 byte of type and 1 byte of length for each Segment object
}
subTlv = s
case *api.TunnelEncapSubTLVUnknown: case *api.TunnelEncapSubTLVUnknown:
subTlv = bgp.NewTunnelEncapSubTLVUnknown(bgp.EncapSubTLVType(sv.Type), sv.Value) subTlv = bgp.NewTunnelEncapSubTLVUnknown(bgp.EncapSubTLVType(sv.Type), sv.Value)
default: default:
return nil, fmt.Errorf("invalid tunnel encapsulation attribute sub tlv: %v", subValue.Message) return nil, fmt.Errorf("invalid tunnel encapsulation attribute sub tlv: %v type: %T", subValue.Message, sv)
} }
subTlvs = append(subTlvs, subTlv) subTlvs = append(subTlvs, subTlv)
} }
@@ -1654,3 +1790,190 @@ func unmarshalAttribute(an *any.Any) (bgp.PathAttributeInterface, error) {
} }
return nil, errors.New("unknown path attribute") return nil, errors.New("unknown path attribute")
} }
// MarshalSRBSID marshals SR Policy Binding SID Sub TLV structure
func MarshalSRBSID(bsid *bgp.TunnelEncapSubTLVSRBSID) *any.Any {
var r proto.Message
s := &api.SRBindingSID{
Sid: make([]byte, len(bsid.BSID.Value)),
}
copy(s.Sid, bsid.BSID.Value)
s.SFlag = bsid.Flags&0x80 == 0x80
s.IFlag = bsid.Flags&0x40 == 0x40
r = s
a, _ := ptypes.MarshalAny(r)
return a
}
// UnmarshalSRBSID unmarshals SR Policy Binding SID Sub TLV and returns native TunnelEncapSubTLVInterface interface
func UnmarshalSRBSID(bsid *any.Any) (bgp.TunnelEncapSubTLVInterface, error) {
var value ptypes.DynamicAny
if err := ptypes.UnmarshalAny(bsid, &value); err != nil {
return nil, fmt.Errorf("failed to unmarshal tunnel encap sub tlv: %s", err)
}
switch v := value.Message.(type) {
case *api.SRBindingSID:
b, err := bgp.NewBSID(v.Sid)
if err != nil {
return nil, err
}
flags := uint8(0x0)
if v.SFlag {
flags += 0x80
}
if v.IFlag {
flags += 0x40
}
return &bgp.TunnelEncapSubTLVSRBSID{
TunnelEncapSubTLV: bgp.TunnelEncapSubTLV{
Type: bgp.ENCAP_SUBTLV_TYPE_SRBINDING_SID,
Length: uint16(2 + b.Len()),
},
BSID: b,
Flags: flags,
}, nil
case *api.SRv6BindingSID:
b, err := bgp.NewBSID(v.Sid)
if err != nil {
return nil, err
}
result := &bgp.TunnelEncapSubTLVSRv6BSID{
TunnelEncapSubTLV: bgp.TunnelEncapSubTLV{
Type: bgp.ENCAP_SUBTLV_TYPE_SRBINDING_SID,
Length: uint16(2 + b.Len()),
},
Flags: 0,
BSID: b,
}
if v.EndpointBehaviorStructure != nil {
result.EPBAS = &bgp.SRv6EndpointBehaviorStructure{
Behavior: bgp.SRBehavior(v.EndpointBehaviorStructure.Behavior),
BlockLen: uint8(v.EndpointBehaviorStructure.BlockLen),
NodeLen: uint8(v.EndpointBehaviorStructure.NodeLen),
FuncLen: uint8(v.EndpointBehaviorStructure.FuncLen),
ArgLen: uint8(v.EndpointBehaviorStructure.ArgLen),
}
}
return result, nil
default:
return nil, fmt.Errorf("unknown binding sid type %+v", v)
}
}
// MarshalSRSegments marshals a slice of SR Policy Segment List
func MarshalSRSegments(segs []bgp.TunnelEncapSubTLVInterface) []*any.Any {
anyList := make([]*any.Any, 0, len(segs))
for _, seg := range segs {
var r proto.Message
switch s := seg.(type) {
case *bgp.SegmentTypeA:
r = &api.SegmentTypeA{
Label: s.Label,
Flags: &api.SegmentFlags{
VFlag: s.Flags&0x80 == 0x80,
AFlag: s.Flags&0x40 == 0x40,
SFlag: s.Flags&0x20 == 0x20,
BFlag: s.Flags&0x10 == 0x10,
},
}
case *bgp.SegmentTypeB:
flags := &api.SegmentFlags{
VFlag: s.Flags&0x80 == 0x80,
AFlag: s.Flags&0x40 == 0x40,
SFlag: s.Flags&0x20 == 0x20,
BFlag: s.Flags&0x10 == 0x10,
}
segment := &api.SegmentTypeB{
Flags: flags,
Sid: s.SID,
}
if s.SRv6EBS != nil {
segment.EndpointBehaviorStructure = &api.SRv6EndPointBehavior{
Behavior: api.SRv6Behavior(s.SRv6EBS.Behavior),
BlockLen: uint32(s.SRv6EBS.BlockLen),
NodeLen: uint32(s.SRv6EBS.NodeLen),
FuncLen: uint32(s.SRv6EBS.FuncLen),
ArgLen: uint32(s.SRv6EBS.ArgLen),
}
}
r = segment
default:
// Unrecognize Segment type, skip it
continue
}
a, _ := ptypes.MarshalAny(r)
anyList = append(anyList, a)
}
return anyList
}
// UnmarshalSRSegments unmarshals SR Policy Segments slice of structs
func UnmarshalSRSegments(s []*any.Any) ([]bgp.TunnelEncapSubTLVInterface, error) {
if len(s) == 0 {
return nil, nil
}
segments := make([]bgp.TunnelEncapSubTLVInterface, len(s))
for i := 0; i < len(s); i++ {
var value ptypes.DynamicAny
if err := ptypes.UnmarshalAny(s[i], &value); err != nil {
return nil, fmt.Errorf("failed to unmarshal SR Policy Segment: %s", err)
}
switch v := value.Message.(type) {
case *api.SegmentTypeA:
seg := &bgp.SegmentTypeA{
TunnelEncapSubTLV: bgp.TunnelEncapSubTLV{
Type: bgp.EncapSubTLVType(bgp.TypeA),
Length: 6,
},
Label: v.Label,
}
if v.Flags.VFlag {
seg.Flags += 0x80
}
if v.Flags.AFlag {
seg.Flags += 0x40
}
if v.Flags.SFlag {
seg.Flags += 0x20
}
if v.Flags.BFlag {
seg.Flags += 0x10
}
segments[i] = seg
case *api.SegmentTypeB:
seg := &bgp.SegmentTypeB{
TunnelEncapSubTLV: bgp.TunnelEncapSubTLV{
Type: bgp.EncapSubTLVType(bgp.TypeB),
Length: 18,
},
SID: v.GetSid(),
}
if v.Flags.VFlag {
seg.Flags += 0x80
}
if v.Flags.AFlag {
seg.Flags += 0x40
}
if v.Flags.SFlag {
seg.Flags += 0x20
}
if v.Flags.BFlag {
seg.Flags += 0x10
}
if v.EndpointBehaviorStructure != nil {
ebs := v.GetEndpointBehaviorStructure()
seg.SRv6EBS = &bgp.SRv6EndpointBehaviorStructure{
Behavior: bgp.SRBehavior(ebs.Behavior),
BlockLen: uint8(ebs.BlockLen),
NodeLen: uint8(ebs.NodeLen),
FuncLen: uint8(ebs.FuncLen),
ArgLen: uint8(ebs.ArgLen),
}
}
segments[i] = seg
}
}
return segments, nil
}

View File

@@ -110,6 +110,15 @@ func NewRouteRefreshCiscoCapability(a *bgp.CapRouteRefreshCisco) *api.RouteRefre
return &api.RouteRefreshCiscoCapability{} return &api.RouteRefreshCiscoCapability{}
} }
func NewFQDNCapability(a *bgp.CapFQDN) *api.FQDNCapability {
return &api.FQDNCapability{
HostNameLen: uint32(a.HostNameLen),
HostName: a.HostName,
DomainNameLen: uint32(a.DomainNameLen),
DomainName: a.DomainName,
}
}
func NewUnknownCapability(a *bgp.CapUnknown) *api.UnknownCapability { func NewUnknownCapability(a *bgp.CapUnknown) *api.UnknownCapability {
return &api.UnknownCapability{ return &api.UnknownCapability{
Code: uint32(a.CapCode), Code: uint32(a.CapCode),
@@ -140,6 +149,8 @@ func MarshalCapability(value bgp.ParameterCapabilityInterface) (*any.Any, error)
m = NewLongLivedGracefulRestartCapability(n) m = NewLongLivedGracefulRestartCapability(n)
case *bgp.CapRouteRefreshCisco: case *bgp.CapRouteRefreshCisco:
m = NewRouteRefreshCiscoCapability(n) m = NewRouteRefreshCiscoCapability(n)
case *bgp.CapFQDN:
m = NewFQDNCapability(n)
case *bgp.CapUnknown: case *bgp.CapUnknown:
m = NewUnknownCapability(n) m = NewUnknownCapability(n)
default: default:
@@ -227,6 +238,8 @@ func unmarshalCapability(a *any.Any) (bgp.ParameterCapabilityInterface, error) {
return bgp.NewCapLongLivedGracefulRestart(tuples), nil return bgp.NewCapLongLivedGracefulRestart(tuples), nil
case *api.RouteRefreshCiscoCapability: case *api.RouteRefreshCiscoCapability:
return bgp.NewCapRouteRefreshCisco(), nil return bgp.NewCapRouteRefreshCisco(), nil
case *api.FQDNCapability:
return bgp.NewCapFQDN(a.HostName, a.DomainName), nil
case *api.UnknownCapability: case *api.UnknownCapability:
return bgp.NewCapUnknown(bgp.BGPCapabilityCode(a.Code), a.Value), nil return bgp.NewCapUnknown(bgp.BGPCapabilityCode(a.Code), a.Value), nil
} }

View File

@@ -260,6 +260,8 @@ const (
AFI_SAFI_TYPE_IPV6_FLOWSPEC AfiSafiType = "ipv6-flowspec" AFI_SAFI_TYPE_IPV6_FLOWSPEC AfiSafiType = "ipv6-flowspec"
AFI_SAFI_TYPE_L3VPN_IPV6_FLOWSPEC AfiSafiType = "l3vpn-ipv6-flowspec" AFI_SAFI_TYPE_L3VPN_IPV6_FLOWSPEC AfiSafiType = "l3vpn-ipv6-flowspec"
AFI_SAFI_TYPE_L2VPN_FLOWSPEC AfiSafiType = "l2vpn-flowspec" AFI_SAFI_TYPE_L2VPN_FLOWSPEC AfiSafiType = "l2vpn-flowspec"
AFI_SAFI_TYPE_IPV4_SRPOLICY AfiSafiType = "ipv4-srpolicy"
AFI_SAFI_TYPE_IPV6_SRPOLICY AfiSafiType = "ipv6-srpolicy"
AFI_SAFI_TYPE_OPAQUE AfiSafiType = "opaque" AFI_SAFI_TYPE_OPAQUE AfiSafiType = "opaque"
AFI_SAFI_TYPE_LS AfiSafiType = "ls" AFI_SAFI_TYPE_LS AfiSafiType = "ls"
) )
@@ -285,8 +287,10 @@ var AfiSafiTypeToIntMap = map[AfiSafiType]int{
AFI_SAFI_TYPE_IPV6_FLOWSPEC: 17, AFI_SAFI_TYPE_IPV6_FLOWSPEC: 17,
AFI_SAFI_TYPE_L3VPN_IPV6_FLOWSPEC: 18, AFI_SAFI_TYPE_L3VPN_IPV6_FLOWSPEC: 18,
AFI_SAFI_TYPE_L2VPN_FLOWSPEC: 19, AFI_SAFI_TYPE_L2VPN_FLOWSPEC: 19,
AFI_SAFI_TYPE_OPAQUE: 20, AFI_SAFI_TYPE_IPV4_SRPOLICY: 20,
AFI_SAFI_TYPE_LS: 21, AFI_SAFI_TYPE_IPV6_SRPOLICY: 21,
AFI_SAFI_TYPE_OPAQUE: 22,
AFI_SAFI_TYPE_LS: 23,
} }
var IntToAfiSafiTypeMap = map[int]AfiSafiType{ var IntToAfiSafiTypeMap = map[int]AfiSafiType{
@@ -310,8 +314,10 @@ var IntToAfiSafiTypeMap = map[int]AfiSafiType{
17: AFI_SAFI_TYPE_IPV6_FLOWSPEC, 17: AFI_SAFI_TYPE_IPV6_FLOWSPEC,
18: AFI_SAFI_TYPE_L3VPN_IPV6_FLOWSPEC, 18: AFI_SAFI_TYPE_L3VPN_IPV6_FLOWSPEC,
19: AFI_SAFI_TYPE_L2VPN_FLOWSPEC, 19: AFI_SAFI_TYPE_L2VPN_FLOWSPEC,
20: AFI_SAFI_TYPE_OPAQUE, 20: AFI_SAFI_TYPE_IPV4_SRPOLICY,
21: AFI_SAFI_TYPE_LS, 21: AFI_SAFI_TYPE_IPV6_SRPOLICY,
22: AFI_SAFI_TYPE_OPAQUE,
23: AFI_SAFI_TYPE_LS,
} }
func (v AfiSafiType) Validate() error { func (v AfiSafiType) Validate() error {
@@ -1135,7 +1141,7 @@ type ZebraState struct {
MplsLabelRangeSize uint32 `mapstructure:"mpls-label-range-size" json:"mpls-label-range-size,omitempty"` MplsLabelRangeSize uint32 `mapstructure:"mpls-label-range-size" json:"mpls-label-range-size,omitempty"`
// original -> gobgp:software-name // original -> gobgp:software-name
// Configure zebra software name. // Configure zebra software name.
// quagga, frr3, frr4, frr5, frr6, frr7 can be used. // frr4, cumulus, frr6, frr7, frr7.2, and frr7.3 can be used.
SoftwareName string `mapstructure:"software-name" json:"software-name,omitempty"` SoftwareName string `mapstructure:"software-name" json:"software-name,omitempty"`
} }
@@ -1165,7 +1171,7 @@ type ZebraConfig struct {
MplsLabelRangeSize uint32 `mapstructure:"mpls-label-range-size" json:"mpls-label-range-size,omitempty"` MplsLabelRangeSize uint32 `mapstructure:"mpls-label-range-size" json:"mpls-label-range-size,omitempty"`
// original -> gobgp:software-name // original -> gobgp:software-name
// Configure zebra software name. // Configure zebra software name.
// quagga, frr3, frr4, frr5, frr6, frr7 can be used. // frr4, cumulus, frr6, frr7, frr7.2, and frr7.3 can be used.
SoftwareName string `mapstructure:"software-name" json:"software-name,omitempty"` SoftwareName string `mapstructure:"software-name" json:"software-name,omitempty"`
} }

View File

@@ -130,7 +130,7 @@ func (n *Neighbor) IsConfederation(g *Global) bool {
} }
func (n *Neighbor) IsEBGPPeer(g *Global) bool { func (n *Neighbor) IsEBGPPeer(g *Global) bool {
return n.Config.PeerAs != g.Config.As return n.Config.PeerAs != n.Config.LocalAs
} }
func (n *Neighbor) CreateRfMap() map[bgp.RouteFamily]bgp.BGPAddPathMode { func (n *Neighbor) CreateRfMap() map[bgp.RouteFamily]bgp.BGPAddPathMode {
@@ -299,14 +299,22 @@ func newAfiSafiConfigFromConfigStruct(c *AfiSafi) *api.AfiSafiConfig {
} }
func newApplyPolicyFromConfigStruct(c *ApplyPolicy) *api.ApplyPolicy { func newApplyPolicyFromConfigStruct(c *ApplyPolicy) *api.ApplyPolicy {
f := func(t DefaultPolicyType) api.RouteAction {
if t == DEFAULT_POLICY_TYPE_ACCEPT_ROUTE {
return api.RouteAction_ACCEPT
} else if t == DEFAULT_POLICY_TYPE_REJECT_ROUTE {
return api.RouteAction_REJECT
}
return api.RouteAction_NONE
}
applyPolicy := &api.ApplyPolicy{ applyPolicy := &api.ApplyPolicy{
ImportPolicy: &api.PolicyAssignment{ ImportPolicy: &api.PolicyAssignment{
Direction: api.PolicyDirection_IMPORT, Direction: api.PolicyDirection_IMPORT,
DefaultAction: api.RouteAction(c.Config.DefaultImportPolicy.ToInt()), DefaultAction: f(c.Config.DefaultImportPolicy),
}, },
ExportPolicy: &api.PolicyAssignment{ ExportPolicy: &api.PolicyAssignment{
Direction: api.PolicyDirection_EXPORT, Direction: api.PolicyDirection_EXPORT,
DefaultAction: api.RouteAction(c.Config.DefaultExportPolicy.ToInt()), DefaultAction: f(c.Config.DefaultExportPolicy),
}, },
} }
@@ -376,6 +384,13 @@ func newMpGracefulRestartFromConfigStruct(c *MpGracefulRestart) *api.MpGracefulR
Config: &api.MpGracefulRestartConfig{ Config: &api.MpGracefulRestartConfig{
Enabled: c.Config.Enabled, Enabled: c.Config.Enabled,
}, },
State: &api.MpGracefulRestartState{
Enabled: c.State.Enabled,
Received: c.State.Received,
Advertised: c.State.Advertised,
EndOfRibReceived: c.State.EndOfRibReceived,
EndOfRibSent: c.State.EndOfRibSent,
},
} }
} }
@@ -504,6 +519,10 @@ func NewPeerFromConfigStruct(pconf *Neighbor) *api.Peer {
Enabled: pconf.EbgpMultihop.Config.Enabled, Enabled: pconf.EbgpMultihop.Config.Enabled,
MultihopTtl: uint32(pconf.EbgpMultihop.Config.MultihopTtl), MultihopTtl: uint32(pconf.EbgpMultihop.Config.MultihopTtl),
}, },
TtlSecurity: &api.TtlSecurity{
Enabled: pconf.TtlSecurity.Config.Enabled,
TtlMin: uint32(pconf.TtlSecurity.Config.TtlMin),
},
Timers: &api.Timers{ Timers: &api.Timers{
Config: &api.TimersConfig{ Config: &api.TimersConfig{
ConnectRetry: uint64(timer.Config.ConnectRetry), ConnectRetry: uint64(timer.Config.ConnectRetry),
@@ -549,6 +568,8 @@ func NewPeerGroupFromConfigStruct(pconf *PeerGroup) *api.PeerGroup {
afiSafis := make([]*api.AfiSafi, 0, len(pconf.AfiSafis)) afiSafis := make([]*api.AfiSafi, 0, len(pconf.AfiSafis))
for _, f := range pconf.AfiSafis { for _, f := range pconf.AfiSafis {
if afiSafi := newAfiSafiFromConfigStruct(&f); afiSafi != nil { if afiSafi := newAfiSafiFromConfigStruct(&f); afiSafi != nil {
afiSafi.AddPaths.Config.Receive = pconf.AddPaths.Config.Receive
afiSafi.AddPaths.Config.SendMax = uint32(pconf.AddPaths.Config.SendMax)
afiSafis = append(afiSafis, afiSafi) afiSafis = append(afiSafis, afiSafi)
} }
} }
@@ -576,6 +597,10 @@ func NewPeerGroupFromConfigStruct(pconf *PeerGroup) *api.PeerGroup {
Enabled: pconf.EbgpMultihop.Config.Enabled, Enabled: pconf.EbgpMultihop.Config.Enabled,
MultihopTtl: uint32(pconf.EbgpMultihop.Config.MultihopTtl), MultihopTtl: uint32(pconf.EbgpMultihop.Config.MultihopTtl),
}, },
TtlSecurity: &api.TtlSecurity{
Enabled: pconf.TtlSecurity.Config.Enabled,
TtlMin: uint32(pconf.TtlSecurity.Config.TtlMin),
},
Timers: &api.Timers{ Timers: &api.Timers{
Config: &api.TimersConfig{ Config: &api.TimersConfig{
ConnectRetry: uint64(timer.Config.ConnectRetry), ConnectRetry: uint64(timer.Config.ConnectRetry),

View File

@@ -50,6 +50,7 @@ const (
BPR_ROUTER_ID BPR_ROUTER_ID
BPR_OLDER BPR_OLDER
BPR_NON_LLGR_STALE BPR_NON_LLGR_STALE
BPR_NEIGH_ADDR
) )
var BestPathReasonStringMap = map[BestPathReason]string{ var BestPathReasonStringMap = map[BestPathReason]string{
@@ -68,6 +69,7 @@ var BestPathReasonStringMap = map[BestPathReason]string{
BPR_ROUTER_ID: "Router ID", BPR_ROUTER_ID: "Router ID",
BPR_OLDER: "Older", BPR_OLDER: "Older",
BPR_NON_LLGR_STALE: "no LLGR Stale", BPR_NON_LLGR_STALE: "no LLGR Stale",
BPR_NEIGH_ADDR: "Neighbor Address",
} }
func (r *BestPathReason) String() string { func (r *BestPathReason) String() string {
@@ -346,9 +348,6 @@ func (dest *Destination) implicitWithdraw(newPath *Path) {
func (dest *Destination) computeKnownBestPath() (*Path, BestPathReason, error) { func (dest *Destination) computeKnownBestPath() (*Path, BestPathReason, error) {
if SelectionOptions.DisableBestPathSelection { if SelectionOptions.DisableBestPathSelection {
log.WithFields(log.Fields{
"Topic": "Table",
}).Debug("computeKnownBestPath skipped")
return nil, BPR_DISABLED, nil return nil, BPR_DISABLED, nil
} }
@@ -358,10 +357,6 @@ func (dest *Destination) computeKnownBestPath() (*Path, BestPathReason, error) {
return nil, BPR_UNKNOWN, nil return nil, BPR_UNKNOWN, nil
} }
log.WithFields(log.Fields{
"Topic": "Table",
}).Debugf("computeKnownBestPath knownPathList: %d", len(dest.knownPathList))
// We pick the first path as current best path. This helps in breaking // We pick the first path as current best path. This helps in breaking
// tie between two new paths learned in one cycle for which best-path // tie between two new paths learned in one cycle for which best-path
// calculation steps lead to tie. // calculation steps lead to tie.
@@ -433,10 +428,9 @@ func (dst *Destination) sort() BestPathReason {
better = compareByReachableNexthop(path1, path2) better = compareByReachableNexthop(path1, path2)
reason = BPR_REACHABLE_NEXT_HOP reason = BPR_REACHABLE_NEXT_HOP
} }
if better == nil {
better = compareByHighestWeight(path1, path2) // compareByHighestWeight was a no-op and was removed.
reason = BPR_HIGHEST_WEIGHT
}
if better == nil { if better == nil {
better = compareByLocalPref(path1, path2) better = compareByLocalPref(path1, path2)
reason = BPR_LOCAL_PREF reason = BPR_LOCAL_PREF
@@ -461,25 +455,21 @@ func (dst *Destination) sort() BestPathReason {
better = compareByASNumber(path1, path2) better = compareByASNumber(path1, path2)
reason = BPR_ASN reason = BPR_ASN
} }
if better == nil {
better = compareByIGPCost(path1, path2) // compareByIGPCost was a no-op and was removed.
reason = BPR_IGP_COST
}
if better == nil { if better == nil {
better = compareByAge(path1, path2) better = compareByAge(path1, path2)
reason = BPR_OLDER reason = BPR_OLDER
} }
if better == nil { if better == nil {
var e error better, _ = compareByRouterID(path1, path2)
better, e = compareByRouterID(path1, path2)
if e != nil {
log.WithFields(log.Fields{
"Topic": "Table",
"Error": e,
}).Error("Could not get best path by comparing router ID")
}
reason = BPR_ROUTER_ID reason = BPR_ROUTER_ID
} }
if better == nil {
better = compareByNeighborAddress(path1, path2)
reason = BPR_NEIGH_ADDR
}
if better == nil { if better == nil {
reason = BPR_UNKNOWN reason = BPR_UNKNOWN
better = path1 better = path1
@@ -616,9 +606,6 @@ func compareByReachableNexthop(path1, path2 *Path) *Path {
// //
// If no path matches this criteria, return nil. // If no path matches this criteria, return nil.
// For BGP Nexthop Tracking, evaluates next-hop is validated by IGP. // For BGP Nexthop Tracking, evaluates next-hop is validated by IGP.
log.WithFields(log.Fields{
"Topic": "Table",
}).Debugf("enter compareByReachableNexthop -- path1: %s, path2: %s", path1, path2)
if path1.IsNexthopInvalid && !path2.IsNexthopInvalid { if path1.IsNexthopInvalid && !path2.IsNexthopInvalid {
return path2 return path2
@@ -629,19 +616,6 @@ func compareByReachableNexthop(path1, path2 *Path) *Path {
return nil return nil
} }
func compareByHighestWeight(path1, path2 *Path) *Path {
// Selects a path with highest weight.
//
// Weight is BGPS specific parameter. It is local to the router on which it
// is configured.
// Return:
// nil if best path among given paths cannot be decided, else best path.
log.WithFields(log.Fields{
"Topic": "Table",
}).Debugf("enter compareByHighestWeight -- path1: %s, path2: %s", path1, path2)
return nil
}
func compareByLocalPref(path1, path2 *Path) *Path { func compareByLocalPref(path1, path2 *Path) *Path {
// Selects a path with highest local-preference. // Selects a path with highest local-preference.
// //
@@ -651,9 +625,6 @@ func compareByLocalPref(path1, path2 *Path) *Path {
// we return None. // we return None.
// //
// # Default local-pref values is 100 // # Default local-pref values is 100
log.WithFields(log.Fields{
"Topic": "Table",
}).Debug("enter compareByLocalPref")
localPref1, _ := path1.GetLocalPref() localPref1, _ := path1.GetLocalPref()
localPref2, _ := path2.GetLocalPref() localPref2, _ := path2.GetLocalPref()
// Highest local-preference value is preferred. // Highest local-preference value is preferred.
@@ -674,9 +645,6 @@ func compareByLocalOrigin(path1, path2 *Path) *Path {
// Returns None if given paths have same source. // Returns None if given paths have same source.
// //
// If both paths are from same sources we cannot compare them here. // If both paths are from same sources we cannot compare them here.
log.WithFields(log.Fields{
"Topic": "Table",
}).Debug("enter compareByLocalOrigin")
if path1.GetSource().Equal(path2.GetSource()) { if path1.GetSource().Equal(path2.GetSource()) {
return nil return nil
} }
@@ -699,34 +667,12 @@ func compareByASPath(path1, path2 *Path) *Path {
// Shortest as-path length is preferred. If both path have same lengths, // Shortest as-path length is preferred. If both path have same lengths,
// we return None. // we return None.
if SelectionOptions.IgnoreAsPathLength { if SelectionOptions.IgnoreAsPathLength {
log.WithFields(log.Fields{
"Topic": "Table",
}).Debug("compareByASPath -- skip")
return nil return nil
} }
log.WithFields(log.Fields{
"Topic": "Table",
}).Debug("enter compareByASPath")
attribute1 := path1.getPathAttr(bgp.BGP_ATTR_TYPE_AS_PATH)
attribute2 := path2.getPathAttr(bgp.BGP_ATTR_TYPE_AS_PATH)
// With addpath support, we could compare paths from API don't
// AS_PATH. No need to warn here.
if !path1.IsLocal() && !path2.IsLocal() && (attribute1 == nil || attribute2 == nil) {
log.WithFields(log.Fields{
"Topic": "Table",
"Key": "compareByASPath",
"ASPath1": attribute1,
"ASPath2": attribute2,
}).Warn("can't compare ASPath because it's not present")
}
l1 := path1.GetAsPathLen() l1 := path1.GetAsPathLen()
l2 := path2.GetAsPathLen() l2 := path2.GetAsPathLen()
log.WithFields(log.Fields{
"Topic": "Table",
}).Debugf("compareByASPath -- l1: %d, l2: %d", l1, l2)
if l1 > l2 { if l1 > l2 {
return path2 return path2
} else if l1 < l2 { } else if l1 < l2 {
@@ -741,27 +687,16 @@ func compareByOrigin(path1, path2 *Path) *Path {
// //
// IGP is preferred over EGP; EGP is preferred over Incomplete. // IGP is preferred over EGP; EGP is preferred over Incomplete.
// If both paths have same origin, we return None. // If both paths have same origin, we return None.
log.WithFields(log.Fields{
"Topic": "Table",
}).Debug("enter compareByOrigin")
attribute1 := path1.getPathAttr(bgp.BGP_ATTR_TYPE_ORIGIN) attribute1 := path1.getPathAttr(bgp.BGP_ATTR_TYPE_ORIGIN)
attribute2 := path2.getPathAttr(bgp.BGP_ATTR_TYPE_ORIGIN) attribute2 := path2.getPathAttr(bgp.BGP_ATTR_TYPE_ORIGIN)
if attribute1 == nil || attribute2 == nil { if attribute1 == nil || attribute2 == nil {
log.WithFields(log.Fields{
"Topic": "Table",
"Key": "compareByOrigin",
"Origin1": attribute1,
"Origin2": attribute2,
}).Error("can't compare origin because it's not present")
return nil return nil
} }
origin1 := attribute1.(*bgp.PathAttributeOrigin).Value origin1 := attribute1.(*bgp.PathAttributeOrigin).Value
origin2 := attribute2.(*bgp.PathAttributeOrigin).Value origin2 := attribute2.(*bgp.PathAttributeOrigin).Value
log.WithFields(log.Fields{
"Topic": "Table",
}).Debugf("compareByOrigin -- origin1: %d, origin2: %d", origin1, origin2)
// If both paths have same origins // If both paths have same origins
if origin1 == origin2 { if origin1 == origin2 {
@@ -807,9 +742,6 @@ func compareByMED(path1, path2 *Path) *Path {
}() }()
if SelectionOptions.AlwaysCompareMed || isInternal || isSameAS { if SelectionOptions.AlwaysCompareMed || isInternal || isSameAS {
log.WithFields(log.Fields{
"Topic": "Table",
}).Debug("enter compareByMED")
getMed := func(path *Path) uint32 { getMed := func(path *Path) uint32 {
attribute := path.getPathAttr(bgp.BGP_ATTR_TYPE_MULTI_EXIT_DISC) attribute := path.getPathAttr(bgp.BGP_ATTR_TYPE_MULTI_EXIT_DISC)
if attribute == nil { if attribute == nil {
@@ -821,9 +753,6 @@ func compareByMED(path1, path2 *Path) *Path {
med1 := getMed(path1) med1 := getMed(path1)
med2 := getMed(path2) med2 := getMed(path2)
log.WithFields(log.Fields{
"Topic": "Table",
}).Debugf("compareByMED -- med1: %d, med2: %d", med1, med2)
if med1 == med2 { if med1 == med2 {
return nil return nil
} else if med1 < med2 { } else if med1 < med2 {
@@ -831,9 +760,6 @@ func compareByMED(path1, path2 *Path) *Path {
} }
return path2 return path2
} else { } else {
log.WithFields(log.Fields{
"Topic": "Table",
}).Debugf("skip compareByMED %v %v %v", SelectionOptions.AlwaysCompareMed, isInternal, isSameAS)
return nil return nil
} }
} }
@@ -844,13 +770,7 @@ func compareByASNumber(path1, path2 *Path) *Path {
// //
//eBGP path is preferred over iBGP. If both paths are from same kind of //eBGP path is preferred over iBGP. If both paths are from same kind of
//peers, return None. //peers, return None.
log.WithFields(log.Fields{
"Topic": "Table",
}).Debug("enter compareByASNumber")
log.WithFields(log.Fields{
"Topic": "Table",
}).Debugf("compareByASNumber -- p1Asn: %d, p2Asn: %d", path1.GetSource().AS, path2.GetSource().AS)
// Path from confederation member should be treated as internal (IBGP learned) path. // Path from confederation member should be treated as internal (IBGP learned) path.
isIBGP1 := path1.GetSource().Confederation || path1.IsIBGP() isIBGP1 := path1.GetSource().Confederation || path1.IsIBGP()
isIBGP2 := path2.GetSource().Confederation || path2.IsIBGP() isIBGP2 := path2.GetSource().Confederation || path2.IsIBGP()
@@ -866,17 +786,6 @@ func compareByASNumber(path1, path2 *Path) *Path {
return nil return nil
} }
func compareByIGPCost(path1, path2 *Path) *Path {
// Select the route with the lowest IGP cost to the next hop.
//
// Return None if igp cost is same.
// Currently BGPS has no concept of IGP and IGP cost.
log.WithFields(log.Fields{
"Topic": "Table",
}).Debugf("enter compareByIGPCost -- path1: %v, path2: %v", path1, path2)
return nil
}
func compareByRouterID(path1, path2 *Path) (*Path, error) { func compareByRouterID(path1, path2 *Path) (*Path, error) {
// Select the route received from the peer with the lowest BGP router ID. // Select the route received from the peer with the lowest BGP router ID.
// //
@@ -884,9 +793,6 @@ func compareByRouterID(path1, path2 *Path) (*Path, error) {
// not pick best-path based on this criteria. // not pick best-path based on this criteria.
// RFC: http://tools.ietf.org/html/rfc5004 // RFC: http://tools.ietf.org/html/rfc5004
// We pick best path between two iBGP paths as usual. // We pick best path between two iBGP paths as usual.
log.WithFields(log.Fields{
"Topic": "Table",
}).Debug("enter compareByRouterID")
// If both paths are from NC we have same router Id, hence cannot compare. // If both paths are from NC we have same router Id, hence cannot compare.
if path1.IsLocal() && path2.IsLocal() { if path1.IsLocal() && path2.IsLocal() {
@@ -918,6 +824,28 @@ func compareByRouterID(path1, path2 *Path) (*Path, error) {
} }
} }
func compareByNeighborAddress(path1, path2 *Path) *Path {
// Select the route received from the peer with the lowest peer address as
// per RFC 4271 9.1.2.2. g
p1 := path1.GetSource().Address
if p1 == nil {
return path1
}
p2 := path2.GetSource().Address
if p2 == nil {
return path2
}
cmp := bytes.Compare(p1, p2)
if cmp < 0 {
return path1
} else if cmp > 0 {
return path2
}
return nil
}
func compareByAge(path1, path2 *Path) *Path { func compareByAge(path1, path2 *Path) *Path {
if !path1.IsIBGP() && !path2.IsIBGP() && !SelectionOptions.ExternalCompareRouterId { if !path1.IsIBGP() && !path2.IsIBGP() && !SelectionOptions.ExternalCompareRouterId {
age1 := path1.GetTimestamp().UnixNano() age1 := path1.GetTimestamp().UnixNano()

View File

@@ -442,13 +442,29 @@ func (p *packerV4) pack(options ...*bgp.MarshallingOption) []*bgp.BGPMessage {
paths := c.paths paths := c.paths
attrs := paths[0].GetPathAttrs() attrs := paths[0].GetPathAttrs()
// we can apply a fix here when gobgp receives from MP peer
// and propagtes to non-MP peer
// we should make sure that next-hop exists in pathattrs
// while we build the update message
// we do not want to modify the `path` though
if paths[0].getPathAttr(bgp.BGP_ATTR_TYPE_NEXT_HOP) == nil {
attrs = append(attrs, bgp.NewPathAttributeNextHop(paths[0].GetNexthop().String()))
}
// if we have ever reach here
// there is no point keeping MP_REACH_NLRI in the announcement
attrs_without_mp := make([]bgp.PathAttributeInterface, 0, len(attrs))
for _, attr := range attrs {
if attr.GetType() != bgp.BGP_ATTR_TYPE_MP_REACH_NLRI {
attrs_without_mp = append(attrs_without_mp, attr)
}
}
attrsLen := 0 attrsLen := 0
for _, a := range attrs { for _, a := range attrs_without_mp {
attrsLen += a.Len() attrsLen += a.Len()
} }
loop(attrsLen, paths, func(nlris []*bgp.IPAddrPrefix) { loop(attrsLen, paths, func(nlris []*bgp.IPAddrPrefix) {
msgs = append(msgs, bgp.NewBGPUpdateMessage(nil, attrs, nlris)) msgs = append(msgs, bgp.NewBGPUpdateMessage(nil, attrs_without_mp, nlris))
}) })
} }
} }

View File

@@ -1233,12 +1233,12 @@ func nlriToIPNet(nlri bgp.AddrPrefixInterface) *net.IPNet {
case *bgp.LabeledIPAddrPrefix: case *bgp.LabeledIPAddrPrefix:
return &net.IPNet{ return &net.IPNet{
IP: net.IP(T.Prefix.To4()), IP: net.IP(T.Prefix.To4()),
Mask: net.CIDRMask(int(T.Length), 32), Mask: net.CIDRMask(int(T.Length)-T.Labels.Len()*8, 32),
} }
case *bgp.LabeledIPv6AddrPrefix: case *bgp.LabeledIPv6AddrPrefix:
return &net.IPNet{ return &net.IPNet{
IP: net.IP(T.Prefix.To4()), IP: net.IP(T.Prefix.To16()),
Mask: net.CIDRMask(int(T.Length), 128), Mask: net.CIDRMask(int(T.Length)-T.Labels.Len()*8, 128),
} }
} }
return nil return nil

View File

@@ -1116,7 +1116,7 @@ func ParseExtCommunity(arg string) (bgp.ExtendedCommunityInterface, error) {
return r || s == bgp.VALIDATION_STATE_INVALID.String() return r || s == bgp.VALIDATION_STATE_INVALID.String()
} }
if len(elems) < 2 && (len(elems) < 1 && !isValidationState(elems[0])) { if len(elems) < 2 && (len(elems) < 1 && !isValidationState(elems[0])) {
return nil, fmt.Errorf("invalid ext-community (rt|soo):<value> | valid | not-found | invalid") return nil, fmt.Errorf("invalid ext-community (rt|soo|encap|lb):<value> | valid | not-found | invalid")
} }
if isValidationState(elems[0]) { if isValidationState(elems[0]) {
subtype = bgp.EC_SUBTYPE_ORIGIN_VALIDATION subtype = bgp.EC_SUBTYPE_ORIGIN_VALIDATION
@@ -1127,15 +1127,19 @@ func ParseExtCommunity(arg string) (bgp.ExtendedCommunityInterface, error) {
subtype = bgp.EC_SUBTYPE_ROUTE_TARGET subtype = bgp.EC_SUBTYPE_ROUTE_TARGET
case "soo": case "soo":
subtype = bgp.EC_SUBTYPE_ROUTE_ORIGIN subtype = bgp.EC_SUBTYPE_ROUTE_ORIGIN
case "encap":
subtype = bgp.EC_SUBTYPE_ENCAPSULATION
case "lb":
subtype = bgp.EC_SUBTYPE_LINK_BANDWIDTH
default: default:
return nil, fmt.Errorf("invalid ext-community (rt|soo):<value> | valid | not-found | invalid") return nil, fmt.Errorf("invalid ext-community (rt|soo|encap|lb):<value> | valid | not-found | invalid")
} }
value = elems[1] value = elems[1]
} }
return bgp.ParseExtendedCommunity(subtype, value) return bgp.ParseExtendedCommunity(subtype, value)
} }
var _regexpCommunity2 = regexp.MustCompile(`(\d+.)*\d+:\d+`) var _regexpCommunity2 = regexp.MustCompile(`^(\d+.)*\d+:\d+$`)
func ParseCommunityRegexp(arg string) (*regexp.Regexp, error) { func ParseCommunityRegexp(arg string) (*regexp.Regexp, error) {
i, err := strconv.ParseUint(arg, 10, 32) i, err := strconv.ParseUint(arg, 10, 32)
@@ -1160,15 +1164,19 @@ func ParseExtCommunityRegexp(arg string) (bgp.ExtendedCommunityAttrSubType, *reg
var subtype bgp.ExtendedCommunityAttrSubType var subtype bgp.ExtendedCommunityAttrSubType
elems := strings.SplitN(arg, ":", 2) elems := strings.SplitN(arg, ":", 2)
if len(elems) < 2 { if len(elems) < 2 {
return subtype, nil, fmt.Errorf("invalid ext-community format([rt|soo]:<value>)") return subtype, nil, fmt.Errorf("invalid ext-community format([rt|soo|encap|lb]:<value>)")
} }
switch strings.ToLower(elems[0]) { switch strings.ToLower(elems[0]) {
case "rt": case "rt":
subtype = bgp.EC_SUBTYPE_ROUTE_TARGET subtype = bgp.EC_SUBTYPE_ROUTE_TARGET
case "soo": case "soo":
subtype = bgp.EC_SUBTYPE_ROUTE_ORIGIN subtype = bgp.EC_SUBTYPE_ROUTE_ORIGIN
case "encap":
subtype = bgp.EC_SUBTYPE_ENCAPSULATION
case "lb":
subtype = bgp.EC_SUBTYPE_LINK_BANDWIDTH
default: default:
return subtype, nil, fmt.Errorf("unknown ext-community subtype. rt, soo is supported") return subtype, nil, fmt.Errorf("unknown ext-community subtype. rt, soo, encap, lb is supported")
} }
exp, err := ParseCommunityRegexp(elems[1]) exp, err := ParseCommunityRegexp(elems[1])
return subtype, exp, err return subtype, exp, err
@@ -1212,8 +1220,12 @@ func (s *ExtCommunitySet) List() []string {
return fmt.Sprintf("rt:%s", arg) return fmt.Sprintf("rt:%s", arg)
case bgp.EC_SUBTYPE_ROUTE_ORIGIN: case bgp.EC_SUBTYPE_ROUTE_ORIGIN:
return fmt.Sprintf("soo:%s", arg) return fmt.Sprintf("soo:%s", arg)
case bgp.EC_SUBTYPE_ENCAPSULATION:
return fmt.Sprintf("encap:%s", arg)
case bgp.EC_SUBTYPE_ORIGIN_VALIDATION: case bgp.EC_SUBTYPE_ORIGIN_VALIDATION:
return arg return arg
case bgp.EC_SUBTYPE_LINK_BANDWIDTH:
return fmt.Sprintf("lb:%s", arg)
default: default:
return fmt.Sprintf("%d:%s", s.subtypeList[idx], arg) return fmt.Sprintf("%d:%s", s.subtypeList[idx], arg)
} }
@@ -1439,11 +1451,17 @@ func (c *PrefixCondition) Option() MatchOption {
// subsequent comparison is skipped if that matches the conditions. // subsequent comparison is skipped if that matches the conditions.
// If PrefixList's length is zero, return true. // If PrefixList's length is zero, return true.
func (c *PrefixCondition) Evaluate(path *Path, _ *PolicyOptions) bool { func (c *PrefixCondition) Evaluate(path *Path, _ *PolicyOptions) bool {
if path.GetRouteFamily() != c.set.family { pathAfi, _ := bgp.RouteFamilyToAfiSafi(path.GetRouteFamily())
cAfi, _ := bgp.RouteFamilyToAfiSafi(c.set.family)
if cAfi != pathAfi {
return false return false
} }
r := nlriToIPNet(path.GetNlri()) r := nlriToIPNet(path.GetNlri())
if r == nil {
return false
}
ones, _ := r.Mask.Size() ones, _ := r.Mask.Size()
masklen := uint8(ones) masklen := uint8(ones)
result := false result := false
@@ -2218,6 +2236,10 @@ func (a *ExtCommunityAction) ToConfig() *config.SetExtCommunity {
return fmt.Sprintf("rt:%s", arg) return fmt.Sprintf("rt:%s", arg)
case bgp.EC_SUBTYPE_ROUTE_ORIGIN: case bgp.EC_SUBTYPE_ROUTE_ORIGIN:
return fmt.Sprintf("soo:%s", arg) return fmt.Sprintf("soo:%s", arg)
case bgp.EC_SUBTYPE_ENCAPSULATION:
return fmt.Sprintf("encap:%s", arg)
case bgp.EC_SUBTYPE_LINK_BANDWIDTH:
return fmt.Sprintf("lb:%s", arg)
case bgp.EC_SUBTYPE_ORIGIN_VALIDATION: case bgp.EC_SUBTYPE_ORIGIN_VALIDATION:
return arg return arg
default: default:
@@ -2565,6 +2587,7 @@ func NewAsPathPrependAction(action config.SetAsPathPrepend) (*AsPathPrependActio
type NexthopAction struct { type NexthopAction struct {
value net.IP value net.IP
self bool self bool
unchanged bool
} }
func (a *NexthopAction) Type() ActionType { func (a *NexthopAction) Type() ActionType {
@@ -2578,6 +2601,12 @@ func (a *NexthopAction) Apply(path *Path, options *PolicyOptions) *Path {
} }
return path return path
} }
if a.unchanged {
if options != nil && options.OldNextHop != nil {
path.SetNexthop(options.OldNextHop)
}
return path
}
path.SetNexthop(a.value) path.SetNexthop(a.value)
return path return path
} }
@@ -2586,6 +2615,9 @@ func (a *NexthopAction) ToConfig() config.BgpNextHopType {
if a.self { if a.self {
return config.BgpNextHopType("self") return config.BgpNextHopType("self")
} }
if a.unchanged {
return config.BgpNextHopType("unchanged")
}
return config.BgpNextHopType(a.value.String()) return config.BgpNextHopType(a.value.String())
} }
@@ -2605,6 +2637,10 @@ func NewNexthopAction(c config.BgpNextHopType) (*NexthopAction, error) {
return &NexthopAction{ return &NexthopAction{
self: true, self: true,
}, nil }, nil
case "unchanged":
return &NexthopAction{
unchanged: true,
}, nil
} }
addr := net.ParseIP(string(c)) addr := net.ParseIP(string(c))
if addr == nil { if addr == nil {
@@ -4046,6 +4082,11 @@ func toStatementApi(s *config.Statement) *api.Statement {
Self: true, Self: true,
} }
} }
if string(s.Actions.BgpActions.SetNextHop) == "unchanged" {
return &api.NexthopAction{
Unchanged: true,
}
}
return &api.NexthopAction{ return &api.NexthopAction{
Address: string(s.Actions.BgpActions.SetNextHop), Address: string(s.Actions.BgpActions.SetNextHop),
} }

View File

@@ -209,6 +209,7 @@ func (t *Table) GetLongerPrefixDestinations(key string) ([]*Destination, error)
switch t.routeFamily { switch t.routeFamily {
case bgp.RF_IPv4_UC, bgp.RF_IPv6_UC, bgp.RF_IPv4_MPLS, bgp.RF_IPv6_MPLS: case bgp.RF_IPv4_UC, bgp.RF_IPv6_UC, bgp.RF_IPv4_MPLS, bgp.RF_IPv6_MPLS:
_, prefix, err := net.ParseCIDR(key) _, prefix, err := net.ParseCIDR(key)
ones, bits := prefix.Mask.Size()
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -216,7 +217,25 @@ func (t *Table) GetLongerPrefixDestinations(key string) ([]*Destination, error)
for _, dst := range t.GetDestinations() { for _, dst := range t.GetDestinations() {
r.Add(nlriToIPNet(dst.nlri), dst) r.Add(nlriToIPNet(dst.nlri), dst)
} }
r.WalkPrefix(prefix, func(_ *net.IPNet, v interface{}) bool { p := &net.IPNet{
IP: prefix.IP,
Mask: net.CIDRMask((ones>>3)<<3, bits),
}
mask := 0
div := 0
if ones%8 != 0 {
mask = 8 - ones&0x7
div = ones >> 3
}
r.WalkPrefix(p, func(n *net.IPNet, v interface{}) bool {
if mask != 0 && n.IP[div]>>mask != p.IP[div]>>mask {
return true
}
l, _ := n.Mask.Size()
if ones > l {
return true
}
results = append(results, v.(*Destination)) results = append(results, v.(*Destination))
return true return true
}) })

View File

@@ -60,6 +60,8 @@ func ProcessMessage(m *bgp.BGPMessage, peerInfo *PeerInfo, timestamp time.Time)
l = append(l, a.Value...) l = append(l, a.Value...)
dels = append(dels, l...) dels = append(dels, l...)
default: default:
// update msg may not contain next_hop (type:3) in attr
// due to it uses MpReachNLRI and it also has empty update.NLRI
attrs = append(attrs, attr) attrs = append(attrs, attr)
} }
} }
@@ -92,6 +94,11 @@ func ProcessMessage(m *bgp.BGPMessage, peerInfo *PeerInfo, timestamp time.Time)
reachAttrs[len(reachAttrs)-1] = reach reachAttrs[len(reachAttrs)-1] = reach
for _, nlri := range reach.Value { for _, nlri := range reach.Value {
// when build path from reach
// reachAttrs might not contain next_hop if `attrs` does not have one
// this happens when a MP peer send update to gobgp
// However nlri is always populated because how we build the path
// path.info{nlri: nlri}
p := NewPath(peerInfo, nlri, false, reachAttrs, timestamp, false) p := NewPath(peerInfo, nlri, false, reachAttrs, timestamp, false)
p.SetHash(hash) p.SetHash(hash)
pathList = append(pathList, p) pathList = append(pathList, p)
@@ -179,8 +186,8 @@ func (manager *TableManager) DeleteVrf(name string) ([]*Path, error) {
return msgs, nil return msgs, nil
} }
func (tm *TableManager) update(newPath *Path) *Update { func (manager *TableManager) update(newPath *Path) *Update {
t := tm.Tables[newPath.GetRouteFamily()] t := manager.Tables[newPath.GetRouteFamily()]
t.validatePath(newPath) t.validatePath(newPath)
dst := t.getOrCreateDest(newPath.GetNlri(), 64) dst := t.getOrCreateDest(newPath.GetNlri(), 64)
u := dst.Calculate(newPath) u := dst.Calculate(newPath)

View File

@@ -57,71 +57,87 @@ func _() {
_ = x[_mplsLabelsAdd-46] _ = x[_mplsLabelsAdd-46]
_ = x[_mplsLabelsDelete-47] _ = x[_mplsLabelsDelete-47]
_ = x[_mplsLabelsReplace-48] _ = x[_mplsLabelsReplace-48]
_ = x[_ipmrRouteStats-49] _ = x[_srPolicySet-49]
_ = x[labelManagerConnect-50] _ = x[_srPolicyDelete-50]
_ = x[labelManagerConnectAsync-51] _ = x[_srPolicyNotifyStatus-51]
_ = x[getLabelChunk-52] _ = x[_ipmrRouteStats-52]
_ = x[releaseLabelChunk-53] _ = x[labelManagerConnect-53]
_ = x[_fecRegister-54] _ = x[labelManagerConnectAsync-54]
_ = x[_fecUnregister-55] _ = x[getLabelChunk-55]
_ = x[_fecUpdate-56] _ = x[releaseLabelChunk-56]
_ = x[_advertiseDefaultGW-57] _ = x[_fecRegister-57]
_ = x[_advertiseSviMACIP-58] _ = x[_fecUnregister-58]
_ = x[_advertiseSubnet-59] _ = x[_fecUpdate-59]
_ = x[_advertiseAllVNI-60] _ = x[_advertiseDefaultGW-60]
_ = x[_localESAdd-61] _ = x[_advertiseSviMACIP-61]
_ = x[_localESDel-62] _ = x[_advertiseSubnet-62]
_ = x[_vniAdd-63] _ = x[_advertiseAllVNI-63]
_ = x[_vniDel-64] _ = x[_localESAdd-64]
_ = x[_l3VNIAdd-65] _ = x[_localESDel-65]
_ = x[_l3VNIDel-66] _ = x[_remoteESVTEPAdd-66]
_ = x[_remoteVTEPAdd-67] _ = x[_remoteESVTEPDel-67]
_ = x[_remoteVTEPDel-68] _ = x[_localESEVIAdd-68]
_ = x[_macIPAdd-69] _ = x[_localESEVIDel-69]
_ = x[_macIPDel-70] _ = x[_vniAdd-70]
_ = x[_ipPrefixRouteAdd-71] _ = x[_vniDel-71]
_ = x[_ipPrefixRouteDel-72] _ = x[_l3VNIAdd-72]
_ = x[_remoteMACIPAdd-73] _ = x[_l3VNIDel-73]
_ = x[_remoteMACIPDel-74] _ = x[_remoteVTEPAdd-74]
_ = x[_duplicateAddrDetection-75] _ = x[_remoteVTEPDel-75]
_ = x[_pwAdd-76] _ = x[_macIPAdd-76]
_ = x[_pwDelete-77] _ = x[_macIPDel-77]
_ = x[_pwSet-78] _ = x[_ipPrefixRouteAdd-78]
_ = x[_pwUnset-79] _ = x[_ipPrefixRouteDel-79]
_ = x[_pwStatusUpdate-80] _ = x[_remoteMACIPAdd-80]
_ = x[_ruleAdd-81] _ = x[_remoteMACIPDel-81]
_ = x[_ruleDelete-82] _ = x[_duplicateAddrDetection-82]
_ = x[_ruleNotifyOwner-83] _ = x[_pwAdd-83]
_ = x[_tableManagerConnect-84] _ = x[_pwDelete-84]
_ = x[_getTableChunk-85] _ = x[_pwSet-85]
_ = x[_releaseTableChunk-86] _ = x[_pwUnset-86]
_ = x[_ipSetCreate-87] _ = x[_pwStatusUpdate-87]
_ = x[_ipSetDestroy-88] _ = x[_ruleAdd-88]
_ = x[_ipSetEntryAdd-89] _ = x[_ruleDelete-89]
_ = x[_ipSetEntryDelete-90] _ = x[_ruleNotifyOwner-90]
_ = x[_ipSetNotifyOwner-91] _ = x[_tableManagerConnect-91]
_ = x[_ipSetEntryNotifyOwner-92] _ = x[_getTableChunk-92]
_ = x[_ipTableAdd-93] _ = x[_releaseTableChunk-93]
_ = x[_ipTableDelete-94] _ = x[_ipSetCreate-94]
_ = x[_ipTableNotifyOwner-95] _ = x[_ipSetDestroy-95]
_ = x[_vxlanFloodControl-96] _ = x[_ipSetEntryAdd-96]
_ = x[_vxlanSgAdd-97] _ = x[_ipSetEntryDelete-97]
_ = x[_vxlanSgDel-98] _ = x[_ipSetNotifyOwner-98]
_ = x[_vxlanSgReplay-99] _ = x[_ipSetEntryNotifyOwner-99]
_ = x[_mlagProcessUp-100] _ = x[_ipTableAdd-100]
_ = x[_mlagProcessDown-101] _ = x[_ipTableDelete-101]
_ = x[_mlagClientRegister-102] _ = x[_ipTableNotifyOwner-102]
_ = x[_mlagClientUnregister-103] _ = x[_vxlanFloodControl-103]
_ = x[_mlagClientForwardMsg-104] _ = x[_vxlanSgAdd-104]
_ = x[zebraError-105] _ = x[_vxlanSgDel-105]
_ = x[_clientCapabilities-106] _ = x[_vxlanSgReplay-106]
_ = x[BackwardIPv6RouteAdd-107] _ = x[_mlagProcessUp-107]
_ = x[BackwardIPv6RouteDelete-108] _ = x[_mlagProcessDown-108]
_ = x[_mlagClientRegister-109]
_ = x[_mlagClientUnregister-110]
_ = x[_mlagClientForwardMsg-111]
_ = x[zebraError-112]
_ = x[_clientCapabilities-113]
_ = x[_opaqueMessage-114]
_ = x[_opaqueRegister-115]
_ = x[_opaqueUnregister-116]
_ = x[_neighDiscover-117]
_ = x[BackwardIPv6RouteAdd-118]
_ = x[BackwardIPv6RouteDelete-119]
_ = x[zapi6Frr7dot3MinDifferentAPIType-49]
_ = x[zapi6Frr7dot2MinDifferentAPIType-48] _ = x[zapi6Frr7dot2MinDifferentAPIType-48]
_ = x[zapi5ClMinDifferentAPIType-19] _ = x[zapi5ClMinDifferentAPIType-19]
_ = x[zapi5MinDifferentAPIType-7] _ = x[zapi5MinDifferentAPIType-7]
_ = x[zapi4MinDifferentAPIType-6] _ = x[zapi4MinDifferentAPIType-6]
_ = x[zapi3MinDifferentAPIType-0] _ = x[zapi3MinDifferentAPIType-0]
_ = x[zapi6Frr7dot3LabelManagerConnect-50]
_ = x[zapi6Frr7dot3LabelManagerConnectAsync-51]
_ = x[zapi6Frr7dot3GetLabelChunk-52]
_ = x[zapi6Frr7dot3ReleaseLabelChunk-53]
_ = x[zapi6Frr7dot2LabelManagerConnect-49] _ = x[zapi6Frr7dot2LabelManagerConnect-49]
_ = x[zapi6Frr7dot2LabelManagerConnectAsync-50] _ = x[zapi6Frr7dot2LabelManagerConnectAsync-50]
_ = x[zapi6Frr7dot2GetLabelChunk-51] _ = x[zapi6Frr7dot2GetLabelChunk-51]
@@ -212,9 +228,9 @@ func _() {
_ = x[zapi3NexthopUpdate-29] _ = x[zapi3NexthopUpdate-29]
} }
const _APIType_name = "interfaceAddinterfaceDeleteinterfaceAddressAddinterfaceAddressDeleteinterfaceUpinterfaceDown_interfaceSetMaster_interfaceSetProtoDownRouteAddRouteDelete_routeNotifyOwnerredistributeAdd_redistributeDelete_redistributeDefaultAdd_redistributeDefaultDeleterouterIDAdd_routerIDDeleterouterIDUpdatehello_capabilitiesnexthopRegisternexthopUnregisternexthopUpdate_interfaceNBRAddressAdd_interfaceNBRAddressDelete_interfaceBFDDestUpdate_importRouteRegister_importRouteUnregister_importCheckUpdate_bfdDestRegister_bfdDestDeregister_bfdDestUpdate_bfdDestReplayredistributeRouteAddredistributeRouteDel_vrfUnregister_vrfAdd_vrfDeletevrfLabel_interfaceVRFUpdate_bfdClientRegister_bfdClientDeregister_interfaceEnableRADV_interfaceDisableRADVipv4NexthopLookupMRIB_interfaceLinkParams_mplsLabelsAdd_mplsLabelsDelete_mplsLabelsReplace_ipmrRouteStatslabelManagerConnectlabelManagerConnectAsyncgetLabelChunkreleaseLabelChunk_fecRegister_fecUnregister_fecUpdate_advertiseDefaultGW_advertiseSviMACIP_advertiseSubnet_advertiseAllVNI_localESAdd_localESDel_vniAdd_vniDel_l3VNIAdd_l3VNIDel_remoteVTEPAdd_remoteVTEPDel_macIPAdd_macIPDel_ipPrefixRouteAdd_ipPrefixRouteDel_remoteMACIPAdd_remoteMACIPDel_duplicateAddrDetection_pwAdd_pwDelete_pwSet_pwUnset_pwStatusUpdate_ruleAdd_ruleDelete_ruleNotifyOwner_tableManagerConnect_getTableChunk_releaseTableChunk_ipSetCreate_ipSetDestroy_ipSetEntryAdd_ipSetEntryDelete_ipSetNotifyOwner_ipSetEntryNotifyOwner_ipTableAdd_ipTableDelete_ipTableNotifyOwner_vxlanFloodControl_vxlanSgAdd_vxlanSgDel_vxlanSgReplay_mlagProcessUp_mlagProcessDown_mlagClientRegister_mlagClientUnregister_mlagClientForwardMsgzebraError_clientCapabilitiesBackwardIPv6RouteAddBackwardIPv6RouteDelete" const _APIType_name = "interfaceAddinterfaceDeleteinterfaceAddressAddinterfaceAddressDeleteinterfaceUpinterfaceDown_interfaceSetMaster_interfaceSetProtoDownRouteAddRouteDelete_routeNotifyOwnerredistributeAdd_redistributeDelete_redistributeDefaultAdd_redistributeDefaultDeleterouterIDAdd_routerIDDeleterouterIDUpdatehello_capabilitiesnexthopRegisternexthopUnregisternexthopUpdate_interfaceNBRAddressAdd_interfaceNBRAddressDelete_interfaceBFDDestUpdate_importRouteRegister_importRouteUnregister_importCheckUpdate_bfdDestRegister_bfdDestDeregister_bfdDestUpdate_bfdDestReplayredistributeRouteAddredistributeRouteDel_vrfUnregister_vrfAdd_vrfDeletevrfLabel_interfaceVRFUpdate_bfdClientRegister_bfdClientDeregister_interfaceEnableRADV_interfaceDisableRADVipv4NexthopLookupMRIB_interfaceLinkParams_mplsLabelsAdd_mplsLabelsDelete_mplsLabelsReplace_srPolicySet_srPolicyDelete_srPolicyNotifyStatus_ipmrRouteStatslabelManagerConnectlabelManagerConnectAsyncgetLabelChunkreleaseLabelChunk_fecRegister_fecUnregister_fecUpdate_advertiseDefaultGW_advertiseSviMACIP_advertiseSubnet_advertiseAllVNI_localESAdd_localESDel_remoteESVTEPAdd_remoteESVTEPDel_localESEVIAdd_localESEVIDel_vniAdd_vniDel_l3VNIAdd_l3VNIDel_remoteVTEPAdd_remoteVTEPDel_macIPAdd_macIPDel_ipPrefixRouteAdd_ipPrefixRouteDel_remoteMACIPAdd_remoteMACIPDel_duplicateAddrDetection_pwAdd_pwDelete_pwSet_pwUnset_pwStatusUpdate_ruleAdd_ruleDelete_ruleNotifyOwner_tableManagerConnect_getTableChunk_releaseTableChunk_ipSetCreate_ipSetDestroy_ipSetEntryAdd_ipSetEntryDelete_ipSetNotifyOwner_ipSetEntryNotifyOwner_ipTableAdd_ipTableDelete_ipTableNotifyOwner_vxlanFloodControl_vxlanSgAdd_vxlanSgDel_vxlanSgReplay_mlagProcessUp_mlagProcessDown_mlagClientRegister_mlagClientUnregister_mlagClientForwardMsgzebraError_clientCapabilities_opaqueMessage_opaqueRegister_opaqueUnregister_neighDiscoverBackwardIPv6RouteAddBackwardIPv6RouteDelete"
var _APIType_index = [...]uint16{0, 12, 27, 46, 68, 79, 92, 111, 133, 141, 152, 169, 184, 203, 226, 252, 263, 278, 292, 297, 310, 325, 342, 355, 378, 404, 427, 447, 469, 487, 503, 521, 535, 549, 569, 589, 603, 610, 620, 628, 647, 665, 685, 705, 726, 747, 767, 781, 798, 816, 831, 850, 874, 887, 904, 916, 930, 940, 959, 977, 993, 1009, 1020, 1031, 1038, 1045, 1054, 1063, 1077, 1091, 1100, 1109, 1126, 1143, 1158, 1173, 1196, 1202, 1211, 1217, 1225, 1240, 1248, 1259, 1275, 1295, 1309, 1327, 1339, 1352, 1366, 1383, 1400, 1422, 1433, 1447, 1466, 1484, 1495, 1506, 1520, 1534, 1550, 1569, 1590, 1611, 1621, 1640, 1660, 1683} var _APIType_index = [...]uint16{0, 12, 27, 46, 68, 79, 92, 111, 133, 141, 152, 169, 184, 203, 226, 252, 263, 278, 292, 297, 310, 325, 342, 355, 378, 404, 427, 447, 469, 487, 503, 521, 535, 549, 569, 589, 603, 610, 620, 628, 647, 665, 685, 705, 726, 747, 767, 781, 798, 816, 828, 843, 864, 879, 898, 922, 935, 952, 964, 978, 988, 1007, 1025, 1041, 1057, 1068, 1079, 1095, 1111, 1125, 1139, 1146, 1153, 1162, 1171, 1185, 1199, 1208, 1217, 1234, 1251, 1266, 1281, 1304, 1310, 1319, 1325, 1333, 1348, 1356, 1367, 1383, 1403, 1417, 1435, 1447, 1460, 1474, 1491, 1508, 1530, 1541, 1555, 1574, 1592, 1603, 1614, 1628, 1642, 1658, 1677, 1698, 1719, 1729, 1748, 1762, 1777, 1794, 1808, 1828, 1851}
func (i APIType) String() string { func (i APIType) String() string {
if i >= APIType(len(_APIType_index)-1) { if i >= APIType(len(_APIType_index)-1) {

View File

@@ -37,13 +37,15 @@ func _() {
_ = x[routeOpenfabric-26] _ = x[routeOpenfabric-26]
_ = x[routeVRRP-27] _ = x[routeVRRP-27]
_ = x[routeNHG-28] _ = x[routeNHG-28]
_ = x[routeAll-29] _ = x[routeSRTE-29]
_ = x[routeMax-30] _ = x[routeAll-30]
_ = x[routeMax-31]
_ = x[zapi5Frr4RouteAll-24] _ = x[zapi5Frr4RouteAll-24]
_ = x[zapi5Frr5RouteAll-25] _ = x[zapi5Frr5RouteAll-25]
_ = x[zapi6Frr6RouteAll-26] _ = x[zapi6Frr6RouteAll-26]
_ = x[zapi6Frr7RouteAll-27] _ = x[zapi6Frr7RouteAll-27]
_ = x[zapi6Frr7dot2RouteAll-28] _ = x[zapi6Frr7dot2RouteAll-28]
_ = x[zapi6Frr7dot3RouteAll-29]
_ = x[zapi4RouteNHRP-11] _ = x[zapi4RouteNHRP-11]
_ = x[zapi4RouteHSLS-12] _ = x[zapi4RouteHSLS-12]
_ = x[zapi4RouteOLSR-13] _ = x[zapi4RouteOLSR-13]
@@ -61,9 +63,9 @@ func _() {
_ = x[zapi3RouteNHRP-14] _ = x[zapi3RouteNHRP-14]
} }
const _RouteType_name = "routeSystemrouteKernelrouteConnectRouteStaticrouteRIProuteRIPNGrouteOSPFrouteOSPF6routeISISRouteBGProutePIMrouteEIGRProuteNHRProuteHSLSrouteOLSRrouteTABLErouteLDProuteVNCrouteVNCDirectrouteVNCDirectRHrouteBGPDirectrouteBGPDirectEXTrouteBABELrouteSHARProutePBRrouteBFDrouteOpenfabricrouteVRRProuteNHGrouteAllrouteMax" const _RouteType_name = "routeSystemrouteKernelrouteConnectRouteStaticrouteRIProuteRIPNGrouteOSPFrouteOSPF6routeISISRouteBGProutePIMrouteEIGRProuteNHRProuteHSLSrouteOLSRrouteTABLErouteLDProuteVNCrouteVNCDirectrouteVNCDirectRHrouteBGPDirectrouteBGPDirectEXTrouteBABELrouteSHARProutePBRrouteBFDrouteOpenfabricrouteVRRProuteNHGrouteSRTErouteAllrouteMax"
var _RouteType_index = [...]uint16{0, 11, 22, 34, 45, 53, 63, 72, 82, 91, 99, 107, 117, 126, 135, 144, 154, 162, 170, 184, 200, 214, 231, 241, 251, 259, 267, 282, 291, 299, 307, 315} var _RouteType_index = [...]uint16{0, 11, 22, 34, 45, 53, 63, 72, 82, 91, 99, 107, 117, 126, 135, 144, 154, 162, 170, 184, 200, 214, 231, 241, 251, 259, 267, 282, 291, 299, 308, 316, 324}
func (i RouteType) String() string { func (i RouteType) String() string {
if i >= RouteType(len(_RouteType_index)-1) { if i >= RouteType(len(_RouteType_index)-1) {

View File

@@ -116,7 +116,7 @@ const softwareNameMinimumVersion uint8 = 5
var allowableSoftwareNameArrays = [][]string{ var allowableSoftwareNameArrays = [][]string{
{"frr4", "cumulus"}, //version:5 {"frr4", "cumulus"}, //version:5
{"frr7.2", "frr7", "frr6"}, //version:6 {"frr7.3", "frr7.2", "frr7", "frr6"}, //version:6
} }
// IsAllowableSoftwareName returns bool from version number and softwareName // IsAllowableSoftwareName returns bool from version number and softwareName
@@ -318,70 +318,82 @@ const (
_mplsLabelsAdd _mplsLabelsAdd
_mplsLabelsDelete _mplsLabelsDelete
_mplsLabelsReplace // add in frr7.3 _mplsLabelsReplace // add in frr7.3
_srPolicySet // add in frr7.5
_srPolicyDelete // 50 // add in frr7.5
_srPolicyNotifyStatus // add in frr7.5
_ipmrRouteStats _ipmrRouteStats
labelManagerConnect // 50 labelManagerConnect // 53
labelManagerConnectAsync // add in frr5 labelManagerConnectAsync // add in frr5
getLabelChunk getLabelChunk
releaseLabelChunk releaseLabelChunk
_fecRegister _fecRegister
_fecUnregister _fecUnregister
_fecUpdate _fecUpdate
_advertiseDefaultGW _advertiseDefaultGW // 60
_advertiseSviMACIP // add in frr7.1 _advertiseSviMACIP // add in frr7.1
_advertiseSubnet _advertiseSubnet
_advertiseAllVNI // 60 _advertiseAllVNI // 63
_localESAdd _localESAdd
_localESDel _localESDel // 65
_vniAdd _remoteESVTEPAdd // add in frr7.5
_remoteESVTEPDel // add in frr7.5
_localESEVIAdd // add in frr7.5
_localESEVIDel // add in frr7.5
_vniAdd // 70
_vniDel _vniDel
_l3VNIAdd _l3VNIAdd
_l3VNIDel _l3VNIDel
_remoteVTEPAdd _remoteVTEPAdd
_remoteVTEPDel _remoteVTEPDel
_macIPAdd _macIPAdd
_macIPDel // 70 _macIPDel // 77
_ipPrefixRouteAdd _ipPrefixRouteAdd
_ipPrefixRouteDel _ipPrefixRouteDel
_remoteMACIPAdd _remoteMACIPAdd // 80
_remoteMACIPDel _remoteMACIPDel
_duplicateAddrDetection _duplicateAddrDetection
_pwAdd _pwAdd
_pwDelete _pwDelete
_pwSet _pwSet
_pwUnset _pwUnset
_pwStatusUpdate // 80 _pwStatusUpdate // 87
_ruleAdd _ruleAdd
_ruleDelete _ruleDelete
_ruleNotifyOwner _ruleNotifyOwner // 90
_tableManagerConnect _tableManagerConnect
_getTableChunk _getTableChunk
_releaseTableChunk _releaseTableChunk
_ipSetCreate _ipSetCreate
_ipSetDestroy _ipSetDestroy
_ipSetEntryAdd _ipSetEntryAdd
_ipSetEntryDelete // 90 _ipSetEntryDelete // 97
_ipSetNotifyOwner _ipSetNotifyOwner
_ipSetEntryNotifyOwner _ipSetEntryNotifyOwner
_ipTableAdd _ipTableAdd // 100
_ipTableDelete _ipTableDelete
_ipTableNotifyOwner _ipTableNotifyOwner
_vxlanFloodControl _vxlanFloodControl
_vxlanSgAdd _vxlanSgAdd
_vxlanSgDel _vxlanSgDel
_vxlanSgReplay _vxlanSgReplay
_mlagProcessUp // 100 // add in frr7.3 _mlagProcessUp // 107 // add in frr7.3
_mlagProcessDown // add in frr7.3 _mlagProcessDown // add in frr7.3
_mlagClientRegister // add in frr7.3 _mlagClientRegister // add in frr7.3
_mlagClientUnregister // add in frr7.3 _mlagClientUnregister // 110 // add in frr7.3
_mlagClientForwardMsg // add in frr7.3 _mlagClientForwardMsg // add in frr7.3
zebraError // add in frr7.3 zebraError // add in frr7.3
_clientCapabilities // add in frr7.4 _clientCapabilities // add in frr7.4
_opaqueMessage // add in frr7.5
_opaqueRegister // add in frr7.5
_opaqueUnregister // add in frr7.5
_neighDiscover // 117 // add in frr7.5
// BackwardIPv6RouteAdd is referred in zclient_test // BackwardIPv6RouteAdd is referred in zclient_test
BackwardIPv6RouteAdd // quagga, frr3, frr4, frr5 BackwardIPv6RouteAdd // quagga, frr3, frr4, frr5
// BackwardIPv6RouteDelete is referred in zclient_test // BackwardIPv6RouteDelete is referred in zclient_test
BackwardIPv6RouteDelete // quagga, frr3, frr4, frr5 BackwardIPv6RouteDelete // quagga, frr3, frr4, frr5
) )
const ( const (
zapi6Frr7dot3MinDifferentAPIType APIType = 49 //frr7.3(zapi6)
zapi6Frr7dot2MinDifferentAPIType APIType = 48 //frr7.2(zapi6) zapi6Frr7dot2MinDifferentAPIType APIType = 48 //frr7.2(zapi6)
zapi5ClMinDifferentAPIType APIType = 19 //cumuluslinux3.7.7, zebra4.0+cl3u13(zapi5) zapi5ClMinDifferentAPIType APIType = 19 //cumuluslinux3.7.7, zebra4.0+cl3u13(zapi5)
zapi5MinDifferentAPIType APIType = 7 //frr4&5(zapi5), frr6&7.0&7.1(zapi6) zapi5MinDifferentAPIType APIType = 7 //frr4&5(zapi5), frr6&7.0&7.1(zapi6)
@@ -399,15 +411,31 @@ func minDifferentAPIType(version uint8, softwareName string) APIType {
} else if version == 5 || } else if version == 5 ||
(version == 6 && (softwareName == "frr6" || softwareName == "frr7")) { (version == 6 && (softwareName == "frr6" || softwareName == "frr7")) {
return zapi5MinDifferentAPIType return zapi5MinDifferentAPIType
} } else if version == 6 && softwareName == "frr7.2" {
return zapi6Frr7dot2MinDifferentAPIType return zapi6Frr7dot2MinDifferentAPIType
}
return zapi6Frr7dot3MinDifferentAPIType
} }
const ( const (
zapi6Frr7dot2LabelManagerConnect APIType = 49 // difference from frr7.3 zapi6Frr7dot3LabelManagerConnect APIType = 50 // difference from frr7.5
zapi6Frr7dot2LabelManagerConnectAsync APIType = 50 // difference from frr7.3 zapi6Frr7dot3LabelManagerConnectAsync APIType = 51 // difference from frr7.5
zapi6Frr7dot2GetLabelChunk APIType = 51 // difference from frr7.3 zapi6Frr7dot3GetLabelChunk APIType = 52 // difference from frr7.5
zapi6Frr7dot2ReleaseLabelChunk APIType = 52 // difference from frr7.3 zapi6Frr7dot3ReleaseLabelChunk APIType = 53 // difference from frr7.5
)
var apiTypeZapi6Frr7dot3Map = map[APIType]APIType{
labelManagerConnect: zapi6Frr7dot3LabelManagerConnect,
labelManagerConnectAsync: zapi6Frr7dot3LabelManagerConnectAsync,
getLabelChunk: zapi6Frr7dot3GetLabelChunk,
releaseLabelChunk: zapi6Frr7dot3ReleaseLabelChunk,
}
const (
zapi6Frr7dot2LabelManagerConnect APIType = 49 // difference from frr7.5
zapi6Frr7dot2LabelManagerConnectAsync APIType = 50 // difference from frr7.5
zapi6Frr7dot2GetLabelChunk APIType = 51 // difference from frr7.5
zapi6Frr7dot2ReleaseLabelChunk APIType = 52 // difference from frr7.5
) )
var apiTypeZapi6Frr7dot2Map = map[APIType]APIType{ var apiTypeZapi6Frr7dot2Map = map[APIType]APIType{
@@ -656,7 +684,9 @@ func (t APIType) doesNeedConversion(version uint8, softwareName string) bool {
return true return true
} }
func apiTypeMap(version uint8, softwareName string) map[APIType]APIType { func apiTypeMap(version uint8, softwareName string) map[APIType]APIType {
if version == 6 && softwareName == "frr7" { if version == 6 && softwareName == "frr7.2" {
return apiTypeZapi6Frr7dot2Map
} else if version == 6 && softwareName == "frr7" {
return apiTypeZapi6Frr7Map return apiTypeZapi6Frr7Map
} else if version == 6 && softwareName == "frr6" { } else if version == 6 && softwareName == "frr6" {
return apiTypeZapi6Frr6Map return apiTypeZapi6Frr6Map
@@ -672,7 +702,7 @@ func apiTypeMap(version uint8, softwareName string) map[APIType]APIType {
} else if version < 4 { } else if version < 4 {
return apiTypeZapi3Map return apiTypeZapi3Map
} }
return apiTypeZapi6Frr7dot2Map return apiTypeZapi6Frr7dot3Map
} }
// ToEach is referred in zclient_test // ToEach is referred in zclient_test
@@ -762,6 +792,7 @@ const (
routeOpenfabric // FRRRouting version 7 (Zapi6) adds. routeOpenfabric // FRRRouting version 7 (Zapi6) adds.
routeVRRP // FRRRouting version 7.2 (Zapi6) adds. routeVRRP // FRRRouting version 7.2 (Zapi6) adds.
routeNHG // FRRRouting version 7.3 (Zapi6) adds. routeNHG // FRRRouting version 7.3 (Zapi6) adds.
routeSRTE // FRRRouting version 7.5 (Zapi6) adds.
routeAll routeAll
routeMax // max value for error routeMax // max value for error
) )
@@ -771,6 +802,7 @@ const (
zapi6Frr6RouteAll RouteType = 26 zapi6Frr6RouteAll RouteType = 26
zapi6Frr7RouteAll RouteType = 27 zapi6Frr7RouteAll RouteType = 27
zapi6Frr7dot2RouteAll RouteType = 28 zapi6Frr7dot2RouteAll RouteType = 28
zapi6Frr7dot3RouteAll RouteType = 29
) )
func getRouteAll(version uint8, softwareName string) RouteType { func getRouteAll(version uint8, softwareName string) RouteType {
@@ -786,6 +818,8 @@ func getRouteAll(version uint8, softwareName string) RouteType {
return zapi6Frr7RouteAll return zapi6Frr7RouteAll
} else if softwareName == "frr7.2" { } else if softwareName == "frr7.2" {
return zapi6Frr7dot2RouteAll return zapi6Frr7dot2RouteAll
} else if softwareName == "frr7.3" {
return zapi6Frr7dot3RouteAll
} }
} }
return routeAll return routeAll
@@ -881,6 +915,7 @@ var routeTypeValueMap = map[string]RouteType{
"openfabric": routeOpenfabric, // add in frr7.0(zapi6) "openfabric": routeOpenfabric, // add in frr7.0(zapi6)
"vrrp": routeVRRP, // add in frr7.2(zapi6) "vrrp": routeVRRP, // add in frr7.2(zapi6)
"nhg": routeNHG, // add in frr7.3(zapi6) "nhg": routeNHG, // add in frr7.3(zapi6)
"srte": routeSRTE, // add in frr7.5(zapi6)
"wildcard": routeAll, "wildcard": routeAll,
} }
@@ -918,7 +953,7 @@ func ipFromFamily(family uint8, buf []byte) net.IP {
} }
// MessageFlag is the type of API Message Flags. // MessageFlag is the type of API Message Flags.
type MessageFlag uint8 type MessageFlag uint32 // MESSAGE_FLAG is 32bit after frr7.5, 8bit before frr7.4
const ( // For FRRouting version 4, 5 and 6 (ZAPI version 5 and 6). const ( // For FRRouting version 4, 5 and 6 (ZAPI version 5 and 6).
// MessageNexthop is referred in zclient // MessageNexthop is referred in zclient
@@ -935,6 +970,7 @@ const ( // For FRRouting version 4, 5 and 6 (ZAPI version 5 and 6).
MessageLabel MessageFlag = 0x40 // deleted in frr7.3 MessageLabel MessageFlag = 0x40 // deleted in frr7.3
messageBackupNexthops MessageFlag = 0x40 // added in frr7.4 messageBackupNexthops MessageFlag = 0x40 // added in frr7.4
messageTableID MessageFlag = 0x80 // introduced in frr5 messageTableID MessageFlag = 0x80 // introduced in frr5
messageSRTE MessageFlag = 0x100 // introduced in frr7.5
) )
const ( // For FRRouting. const ( // For FRRouting.
@@ -993,7 +1029,7 @@ func (f MessageFlag) string(version uint8, softwareName string) string {
if version > 3 && f&messageSRCPFX.ToEach(version) > 0 { if version > 3 && f&messageSRCPFX.ToEach(version) > 0 {
ss = append(ss, "SRCPFX") ss = append(ss, "SRCPFX")
} }
if version == 6 && softwareName == "" && f&messageBackupNexthops > 0 { // added in frr7.4 if version == 6 && softwareName == "" && f&messageBackupNexthops > 0 { // added in frr7.4, frr7.5
ss = append(ss, "BACKUP_NEXTHOPS") ss = append(ss, "BACKUP_NEXTHOPS")
} else if version > 4 && f&MessageLabel > 0 { } else if version > 4 && f&MessageLabel > 0 {
ss = append(ss, "LABEL") ss = append(ss, "LABEL")
@@ -1001,6 +1037,9 @@ func (f MessageFlag) string(version uint8, softwareName string) string {
if version > 5 && f&messageTableID > 0 { if version > 5 && f&messageTableID > 0 {
ss = append(ss, "TABLEID") ss = append(ss, "TABLEID")
} }
if version == 6 && softwareName == "" && f&messageSRTE > 0 { // added in frr7.5
ss = append(ss, "SRTE")
}
return strings.Join(ss, "|") return strings.Join(ss, "|")
} }
@@ -1338,7 +1377,7 @@ func NewClient(network, address string, typ RouteType, version uint8, software s
// Start receive loop only when the first message successfully received. // Start receive loop only when the first message successfully received.
go func() { go func() {
defer closeChannel(incoming) defer close(incoming)
for { for {
if m, err := receiveSingleMsg(); err != nil { if m, err := receiveSingleMsg(); err != nil {
return return
@@ -1407,7 +1446,16 @@ func (c *Client) SendHello() error {
// SendRouterIDAdd sends ROUTER_ID_ADD message to zebra daemon. // SendRouterIDAdd sends ROUTER_ID_ADD message to zebra daemon.
func (c *Client) SendRouterIDAdd() error { func (c *Client) SendRouterIDAdd() error {
return c.sendCommand(routerIDAdd, DefaultVrf, nil) bodies := make([]*routerIDUpdateBody, 0)
for _, afi := range []afi{afiIP, afiIP6} {
bodies = append(bodies, &routerIDUpdateBody{
afi: afi,
})
}
for _, body := range bodies {
c.sendCommand(routerIDAdd, DefaultVrf, body)
}
return nil
} }
// SendInterfaceAdd sends INTERFACE_ADD message to zebra daemon. // SendInterfaceAdd sends INTERFACE_ADD message to zebra daemon.
@@ -1417,7 +1465,6 @@ func (c *Client) SendInterfaceAdd() error {
// SendRedistribute sends REDISTRIBUTE message to zebra daemon. // SendRedistribute sends REDISTRIBUTE message to zebra daemon.
func (c *Client) SendRedistribute(t RouteType, vrfID uint32) error { func (c *Client) SendRedistribute(t RouteType, vrfID uint32) error {
if c.redistDefault != t { if c.redistDefault != t {
bodies := make([]*redistributeBody, 0) bodies := make([]*redistributeBody, 0)
if c.Version <= 3 { if c.Version <= 3 {
@@ -1435,7 +1482,7 @@ func (c *Client) SendRedistribute(t RouteType, vrfID uint32) error {
} }
for _, body := range bodies { for _, body := range bodies {
return c.sendCommand(redistributeAdd, vrfID, body) c.sendCommand(redistributeAdd, vrfID, body)
} }
} }
return nil return nil
@@ -1634,16 +1681,22 @@ func (b *unknownBody) string(version uint8, softwareName string) string {
type helloBody struct { type helloBody struct {
redistDefault RouteType redistDefault RouteType
instance uint16 instance uint16
sessionID uint32 // frr7.4, frr7.5
receiveNotify uint8 receiveNotify uint8
synchronous uint8 // frr7.4, frr7.5
} }
// Ref: zread_hello in zebra/zserv.c of Quagga1.2&FRR3 (ZAPI3&4) // Ref: zread_hello in zebra/zserv.c of Quagga1.2&FRR3 (ZAPI3&4)
// Ref: zread_hello in zebra/zapi_msg.c of FRR5 (ZAPI5) // Ref: zread_hello in zebra/zapi_msg.c of FRR5 (ZAPI5)
func (b *helloBody) decodeFromBytes(data []byte, version uint8, softwareName string) error { func (b *helloBody) decodeFromBytes(data []byte, version uint8, softwareName string) error {
b.redistDefault = RouteType(data[0]) b.redistDefault = RouteType(data[0])
if version >= 4 { if version > 3 { //frr
b.instance = binary.BigEndian.Uint16(data[1:3]) b.instance = binary.BigEndian.Uint16(data[1:3])
if version >= 5 { if version == 6 && softwareName == "" { // frr7.5
b.sessionID = binary.BigEndian.Uint32(data[3:7])
b.receiveNotify = data[7]
b.synchronous = data[8]
} else if version > 4 {
b.receiveNotify = data[3] b.receiveNotify = data[3]
} }
} }
@@ -1656,14 +1709,20 @@ func (b *helloBody) serialize(version uint8, softwareName string) ([]byte, error
return []byte{uint8(b.redistDefault)}, nil return []byte{uint8(b.redistDefault)}, nil
} }
var buf []byte var buf []byte
if version == 4 { if version == 6 && softwareName == "" { // frr7.5
buf = make([]byte, 3) buf = make([]byte, 9)
} else if version > 4 { } else if version > 4 {
buf = make([]byte, 4) buf = make([]byte, 4)
} else if version == 4 {
buf = make([]byte, 3)
} }
buf[0] = uint8(b.redistDefault) buf[0] = uint8(b.redistDefault)
binary.BigEndian.PutUint16(buf[1:3], b.instance) binary.BigEndian.PutUint16(buf[1:3], b.instance)
if version > 4 { if version == 6 && softwareName == "" { // frr7.5
binary.BigEndian.PutUint32(buf[3:7], b.sessionID)
buf[7] = b.receiveNotify
buf[8] = b.synchronous
} else if version > 4 {
buf[3] = b.receiveNotify buf[3] = b.receiveNotify
} }
return buf, nil return buf, nil
@@ -1870,6 +1929,7 @@ func (b *interfaceAddressUpdateBody) string(version uint8, softwareName string)
type routerIDUpdateBody struct { type routerIDUpdateBody struct {
length uint8 length uint8
prefix net.IP prefix net.IP
afi afi
} }
// Ref: zebra_router_id_update_read in lib/zclient.c of Quagga1.2&FRR3&FRR5 (ZAPI3&4&5) // Ref: zebra_router_id_update_read in lib/zclient.c of Quagga1.2&FRR3&FRR5 (ZAPI3&4&5)
@@ -1885,7 +1945,12 @@ func (b *routerIDUpdateBody) decodeFromBytes(data []byte, version uint8, softwar
return nil return nil
} }
// Ref: zclient_send_router_id_update in lib/zclient.c of FRR7.5
func (b *routerIDUpdateBody) serialize(version uint8, softwareName string) ([]byte, error) { func (b *routerIDUpdateBody) serialize(version uint8, softwareName string) ([]byte, error) {
if version == 6 && softwareName == "" {
//stream_putw(s, afi);
return []byte{0x00, uint8(b.afi)}, nil
}
return []byte{}, nil return []byte{}, nil
} }
@@ -1894,9 +1959,11 @@ func (b *routerIDUpdateBody) string(version uint8, softwareName string) string {
} }
const ( const (
zapiNexthopFlagOnlink uint8 = 0x01 // frr7.1, 7.2, 7.3, 7.4 zapiNexthopFlagOnlink uint8 = 0x01 // frr7.1, 7.2, 7.3, 7.4, 7.5
zapiNexthopFlagLabel uint8 = 0x02 // frr7.3, 7.4 zapiNexthopFlagLabel uint8 = 0x02 // frr7.3, 7.4, 7.5
zapiNexthopFlagWeight uint8 = 0x04 // frr7.3, 7.4 zapiNexthopFlagWeight uint8 = 0x04 // frr7.3, 7.4, 7.5
zapiNexthopFlagHasBackup uint8 = 0x08 // frr7.4, 7.5
) )
// Flag for nexthop processing. It is gobgp's internal flag. // Flag for nexthop processing. It is gobgp's internal flag.
@@ -1921,7 +1988,7 @@ func nexthopProcessFlagForIPRouteBody(version uint8, softwareName string, isDeco
processFlag := (nexthopHasVrfID | nexthopHasType) // frr4, 5, 6, 7 processFlag := (nexthopHasVrfID | nexthopHasType) // frr4, 5, 6, 7
if version == 6 { if version == 6 {
switch softwareName { switch softwareName {
case "": case "", "frr7.3":
processFlag |= (nexthopHasFlag | nexthopProcessIPToIPIFindex) processFlag |= (nexthopHasFlag | nexthopProcessIPToIPIFindex)
case "frr7.2", "frr7.0": case "frr7.2", "frr7.0":
processFlag |= nexthopHasOnlink processFlag |= nexthopHasOnlink
@@ -1942,6 +2009,9 @@ type Nexthop struct {
MplsLabels []uint32 MplsLabels []uint32
weight uint32 weight uint32
rmac [6]byte rmac [6]byte
srteColor uint32
backupNum uint8
backupIndex []uint8
} }
func (n Nexthop) string() string { func (n Nexthop) string() string {
@@ -1994,6 +2064,9 @@ func (n Nexthop) encode(version uint8, softwareName string, processFlag nexthopP
if n.weight > 0 { if n.weight > 0 {
n.flags |= zapiNexthopFlagWeight n.flags |= zapiNexthopFlagWeight
} }
if n.backupNum > 0 {
n.flags |= zapiNexthopFlagHasBackup
}
} }
if processFlag&nexthopHasFlag > 0 || processFlag&nexthopHasOnlink > 0 { if processFlag&nexthopHasFlag > 0 || processFlag&nexthopHasOnlink > 0 {
// frr7.1, 7.2 has onlink, 7.3 has flag // frr7.1, 7.2 has onlink, 7.3 has flag
@@ -2051,6 +2124,20 @@ func (n Nexthop) encode(version uint8, softwareName string, processFlag nexthopP
//frr: stream_put(s, &(api_nh->rmac), sizeof(struct ethaddr)); //frr: stream_put(s, &(api_nh->rmac), sizeof(struct ethaddr));
buf = append(buf, n.rmac[:]...) buf = append(buf, n.rmac[:]...)
} }
// added in frr7.5 (Color for Segment Routing TE.)
if message&messageSRTE > 0 && (version == 6 && softwareName == "") {
tmpbuf := make([]byte, 4)
binary.BigEndian.PutUint32(tmpbuf, uint32(n.srteColor))
buf = append(buf, tmpbuf...) //frr: stream_putl(s, api_nh->srte_color);
}
if n.flags&zapiNexthopFlagHasBackup > 0 {
tmpbuf := make([]byte, 1+1*n.backupNum)
tmpbuf[0] = n.backupNum //frr: stream_putc(s, api_nh->backup_num);
for i := uint8(0); i < n.backupNum; i++ {
tmpbuf[i+1] = n.backupIndex[i]
}
buf = append(buf, tmpbuf...)
}
return buf return buf
} }
@@ -2109,7 +2196,10 @@ func (n *Nexthop) decode(data []byte, version uint8, softwareName string, family
n.blackholeType = data[offset] //frr: STREAM_GETC(s, api_nh->bh_type); n.blackholeType = data[offset] //frr: STREAM_GETC(s, api_nh->bh_type);
offset++ offset++
} }
if n.flags&zapiNexthopFlagLabel > 0 || message&MessageLabel > 0 { if n.flags&zapiNexthopFlagLabel > 0 || (message&MessageLabel > 0 &&
(version == 5 || version == 6 &&
(softwareName == "frr6" || softwareName == "frr7" ||
softwareName == "frr7.2"))) {
n.LabelNum = uint8(data[offset]) //frr: STREAM_GETC(s, api_nh->label_num); n.LabelNum = uint8(data[offset]) //frr: STREAM_GETC(s, api_nh->label_num);
offset++ offset++
if n.LabelNum > maxMplsLabel { if n.LabelNum > maxMplsLabel {
@@ -2136,6 +2226,25 @@ func (n *Nexthop) decode(data []byte, version uint8, softwareName string, family
copy(n.rmac[0:], data[offset:offset+6]) copy(n.rmac[0:], data[offset:offset+6])
offset += 6 offset += 6
} }
// added in frr7.5 (Color for Segment Routing TE.)
if message&messageSRTE > 0 && (version == 6 && softwareName == "") {
//STREAM_GETL(s, api_nh->srte_color);
n.srteColor = binary.BigEndian.Uint32(data[offset:])
offset += 4
}
// added in frr7.4 (Index of backup nexthop)
if n.flags&zapiNexthopFlagHasBackup > 0 {
n.backupNum = data[offset] //frr: STREAM_GETC(s, api_nh->backup_num);
offset++
if n.backupNum > 0 {
n.backupIndex = make([]uint8, n.backupNum)
for i := uint8(0); i < n.backupNum; i++ {
//frr STREAM_GETC(s, api_nh->backup_idx[i]);
n.backupIndex[i] = data[offset]
offset++
}
}
}
return offset, nil return offset, nil
} }
@@ -2186,6 +2295,7 @@ type IPRouteBody struct {
Mtu uint32 Mtu uint32
tag uint32 tag uint32
tableID uint32 tableID uint32
srteColor uint32
API APIType // API is referred in zclient_test API APIType // API is referred in zclient_test
} }
@@ -2261,13 +2371,25 @@ func (b *IPRouteBody) IsWithdraw(version uint8, softwareName string) bool {
func (b *IPRouteBody) serialize(version uint8, softwareName string) ([]byte, error) { func (b *IPRouteBody) serialize(version uint8, softwareName string) ([]byte, error) {
var buf []byte var buf []byte
numNexthop := len(b.Nexthops) numNexthop := len(b.Nexthops)
if version <= 3 {
buf = make([]byte, 5) bufInitSize := 12
} else if version == 4 { switch version {
buf = make([]byte, 10) case 2, 3:
} else { // version >= 5 bufInitSize = 5
buf = make([]byte, 9) //type(1)+instance(2)+flags(4)+message(1)+safi(1) case 4:
bufInitSize = 10
case 5:
bufInitSize = 9 //type(1)+instance(2)+flags(4)+message(1)+safi(1)
case 6:
switch softwareName {
case "frr6", "frr7", "frr7.2", "frr7.3":
bufInitSize = 9 //type(1)+instance(2)+flags(4)+message(1)+safi(1)
default:
bufInitSize = 12 //type(1)+instance(2)+flags(4)+message(4)+safi(1)
} }
}
buf = make([]byte, bufInitSize)
buf[0] = uint8(b.Type.toEach(version, softwareName)) //frr: stream_putc(s, api->type); buf[0] = uint8(b.Type.toEach(version, softwareName)) //frr: stream_putc(s, api->type);
if version < 4 { if version < 4 {
buf[1] = uint8(b.Flags) buf[1] = uint8(b.Flags)
@@ -2278,27 +2400,33 @@ func (b *IPRouteBody) serialize(version uint8, softwareName string) ([]byte, err
binary.BigEndian.PutUint16(buf[1:3], uint16(b.instance)) binary.BigEndian.PutUint16(buf[1:3], uint16(b.instance))
//frr: stream_putl(s, api->flags); //frr: stream_putl(s, api->flags);
binary.BigEndian.PutUint32(buf[3:7], uint32(b.Flags)) binary.BigEndian.PutUint32(buf[3:7], uint32(b.Flags))
//frr: stream_putc(s, api->message); if version == 6 && softwareName == "" {
//frr7.5: stream_putl(s, api->message);
binary.BigEndian.PutUint32(buf[7:11], uint32(b.Message))
buf[11] = uint8(b.Safi)
} else {
//before frr7.4: stream_putc(s, api->message);
buf[7] = uint8(b.Message) buf[7] = uint8(b.Message)
if version == 4 { if version > 4 {
binary.BigEndian.PutUint16(buf[8:10], uint16(b.Safi))
} else { // version >= 5
//frr: stream_putc(s, api->safi); //frr: stream_putc(s, api->safi);
buf[8] = uint8(b.Safi) buf[8] = uint8(b.Safi)
} else { // version 2,3 and 4 (quagga, frr3)
binary.BigEndian.PutUint16(buf[8:10], uint16(b.Safi))
}
}
}
// only zapi version 5 (frr4.0.x) have evpn routes // only zapi version 5 (frr4.0.x) have evpn routes
if version == 5 && b.Flags&flagEvpnRoute.ToEach(version, softwareName) > 0 { if version == 5 && b.Flags&flagEvpnRoute.ToEach(version, softwareName) > 0 {
// size of struct ethaddr is 6 octets defined by ETH_ALEN // size of struct ethaddr is 6 octets defined by ETH_ALEN
buf = append(buf, b.Nexthops[numNexthop-1].rmac[:6]...) buf = append(buf, b.Nexthops[numNexthop-1].rmac[:6]...)
} }
if version > 4 { // version 5, 6 (after frr4)
if b.Prefix.Family == syscall.AF_UNSPEC { if b.Prefix.Family == syscall.AF_UNSPEC {
b.Prefix.Family = familyFromPrefix(b.Prefix.Prefix) b.Prefix.Family = familyFromPrefix(b.Prefix.Prefix)
} }
//frr: stream_putc(s, api->prefix.family); //frr: stream_putc(s, api->prefix.family);
buf = append(buf, b.Prefix.Family) buf = append(buf, b.Prefix.Family)
} }
}
byteLen := (int(b.Prefix.PrefixLen) + 7) / 8 byteLen := (int(b.Prefix.PrefixLen) + 7) / 8
buf = append(buf, b.Prefix.PrefixLen) //frr: stream_putc(s, api->prefix.prefixlen); buf = append(buf, b.Prefix.PrefixLen) //frr: stream_putc(s, api->prefix.prefixlen);
//frr: stream_write(s, (uint8_t *)&api->prefix.u.prefix, psize); //frr: stream_write(s, (uint8_t *)&api->prefix.u.prefix, psize);
@@ -2329,7 +2457,8 @@ func (b *IPRouteBody) serialize(version uint8, softwareName string) ([]byte, err
buf = append(buf, nexthop.encode(version, softwareName, processFlag, b.Message, b.Flags)...) buf = append(buf, nexthop.encode(version, softwareName, processFlag, b.Message, b.Flags)...)
} }
} }
if b.Message&messageBackupNexthops > 0 { // added in frr7.4 // MESSAGE_BACKUP_NEXTHOPS is added in frr7.4
if version == 6 && softwareName == "" && b.Message&messageBackupNexthops > 0 {
tmpbuf := make([]byte, 2) tmpbuf := make([]byte, 2)
binary.BigEndian.PutUint16(tmpbuf, uint16(len(b.backupNexthops))) binary.BigEndian.PutUint16(tmpbuf, uint16(len(b.backupNexthops)))
buf = append(buf, tmpbuf...) //frr: stream_putw(s, api->nexthop_num); buf = append(buf, tmpbuf...) //frr: stream_putw(s, api->nexthop_num);
@@ -2428,17 +2557,23 @@ func (b *IPRouteBody) decodeFromBytes(data []byte, version uint8, softwareName s
b.Flags = Flag(binary.BigEndian.Uint32(data[3:7])) b.Flags = Flag(binary.BigEndian.Uint32(data[3:7]))
data = data[7:] data = data[7:]
} }
if version == 6 && softwareName == "" {
//frr7.5: STREAM_GETL(s, api->message);
b.Message = MessageFlag(binary.BigEndian.Uint32(data[0:4]))
data = data[4:]
} else {
b.Message = MessageFlag(data[0]) //frr: STREAM_GETC(s, api->message); b.Message = MessageFlag(data[0]) //frr: STREAM_GETC(s, api->message);
data = data[1:]
}
b.Safi = Safi(SafiUnicast) b.Safi = Safi(SafiUnicast)
b.Prefix.Family = b.API.addressFamily(version) // return AF_UNSPEC if version > 4 b.Prefix.Family = b.API.addressFamily(version) // return AF_UNSPEC if version > 4
var evpnNexthop Nexthop var evpnNexthop Nexthop
if version > 4 { if version > 4 {
b.Safi = Safi(data[1]) //frr: STREAM_GETC(s, api->safi); b.Safi = Safi(data[0]) //frr: STREAM_GETC(s, api->safi);
if b.Safi > safiMax { //frr5 and later work, ToDo: fix for older version if b.Safi > safiMax { //frr5 and later work, ToDo: fix for older version
return fmt.Errorf("unknown safi type: %d in version: %d (%s)", b.Type, version, softwareName) return fmt.Errorf("unknown safi type: %d in version: %d (%s)", b.Type, version, softwareName)
} }
data = data[2:] data = data[1:]
// zapi version 5 only // zapi version 5 only
if version == 5 && b.Flags&flagEvpnRoute.ToEach(version, softwareName) > 0 { if version == 5 && b.Flags&flagEvpnRoute.ToEach(version, softwareName) > 0 {
@@ -2448,6 +2583,7 @@ func (b *IPRouteBody) decodeFromBytes(data []byte, version uint8, softwareName s
} }
b.Prefix.Family = data[0] //frr: STREAM_GETC(s, api->prefix.family); b.Prefix.Family = data[0] //frr: STREAM_GETC(s, api->prefix.family);
data = data[1:]
} }
addrByteLen, err := addressByteLength(b.Prefix.Family) addrByteLen, err := addressByteLength(b.Prefix.Family)
@@ -2457,11 +2593,11 @@ func (b *IPRouteBody) decodeFromBytes(data []byte, version uint8, softwareName s
addrBitLen := uint8(addrByteLen * 8) addrBitLen := uint8(addrByteLen * 8)
b.Prefix.PrefixLen = data[1] //frr: STREAM_GETC(s, api->prefix.prefixlen); b.Prefix.PrefixLen = data[0] //frr: STREAM_GETC(s, api->prefix.prefixlen);
if b.Prefix.PrefixLen > addrBitLen { if b.Prefix.PrefixLen > addrBitLen {
return fmt.Errorf("prefix length %d is greater than %d", b.Prefix.PrefixLen, addrBitLen) return fmt.Errorf("prefix length %d is greater than %d", b.Prefix.PrefixLen, addrBitLen)
} }
data = data[2:] data = data[1:]
pos := 0 pos := 0
rest := len(data) rest := len(data)
@@ -2474,6 +2610,7 @@ func (b *IPRouteBody) decodeFromBytes(data []byte, version uint8, softwareName s
copy(buf, data[pos:pos+byteLen]) copy(buf, data[pos:pos+byteLen])
b.Prefix.Prefix = ipFromFamily(b.Prefix.Family, buf) b.Prefix.Prefix = ipFromFamily(b.Prefix.Family, buf)
pos += byteLen pos += byteLen
if version > 3 && b.Message&messageSRCPFX.ToEach(version) > 0 { if version > 3 && b.Message&messageSRCPFX.ToEach(version) > 0 {
if pos+1 > rest { if pos+1 > rest {
return fmt.Errorf("MessageSRCPFX message length invalid pos:%d rest:%d", pos, rest) return fmt.Errorf("MessageSRCPFX message length invalid pos:%d rest:%d", pos, rest)
@@ -2496,21 +2633,28 @@ func (b *IPRouteBody) decodeFromBytes(data []byte, version uint8, softwareName s
} }
b.Nexthops = []Nexthop{} b.Nexthops = []Nexthop{}
if b.Message&MessageNexthop.ToEach(version) > 0 {
offset, err := b.decodeMessageNexthopFromBytes(data[pos:], version, softwareName, false) offset, err := b.decodeMessageNexthopFromBytes(data[pos:], version, softwareName, false)
if err != nil { if err != nil {
return err return err
} }
pos += offset pos += offset
}
b.backupNexthops = []Nexthop{} // backupNexthops is added in frr7.4 b.backupNexthops = []Nexthop{} // backupNexthops is added in frr7.4
offset, err = b.decodeMessageNexthopFromBytes(data[pos:], version, softwareName, true) if b.Message&messageBackupNexthops.ToEach(version) > 0 {
offset, err := b.decodeMessageNexthopFromBytes(data[pos:], version, softwareName, true)
if err != nil { if err != nil {
return err return err
} }
pos += offset pos += offset
}
// version 5 only, In version 6, EvpnRoute is processed in MessageNexthop // version 5 only, In version 6, EvpnRoute is processed in MessageNexthop
if version == 5 && b.Flags&flagEvpnRoute.ToEach(version, softwareName) > 0 { if version == 5 && b.Flags&flagEvpnRoute.ToEach(version, softwareName) > 0 {
b.Nexthops = append(b.Nexthops, evpnNexthop) b.Nexthops = append(b.Nexthops, evpnNexthop)
} }
if version < 5 && b.Message&messageIFIndex > 0 { // version 4, 3, 2 if version < 5 && b.Message&messageIFIndex > 0 { // version 4, 3, 2
if pos+1 > rest { if pos+1 > rest {
return fmt.Errorf("MessageIFIndex message length invalid pos:%d rest:%d", pos, rest) return fmt.Errorf("MessageIFIndex message length invalid pos:%d rest:%d", pos, rest)
@@ -2792,17 +2936,27 @@ func (b *NexthopRegisterBody) string(version uint8, softwareName string) string
// NexthopUpdateBody uses same data structure as IPRoute (zapi_route) after frr4 (Zapi5) // NexthopUpdateBody uses same data structure as IPRoute (zapi_route) after frr4 (Zapi5)
type NexthopUpdateBody IPRouteBody type NexthopUpdateBody IPRouteBody
// Ref: send_client in zebra/zebra_rnh.c of Quagga1.2&FRR3&FRR5(ZAPI3&4$5) // Ref: send_client in zebra/zebra_rnh.c of Quagga1.2&FRR3&FRR5(ZAPI3&4$5) and befre FRR7.4
// Ref: zebra_send_rnh_update zebra/zebra_rnh.c of FRR7.5
func (b *NexthopUpdateBody) serialize(version uint8, softwareName string) ([]byte, error) { func (b *NexthopUpdateBody) serialize(version uint8, softwareName string) ([]byte, error) {
var buf []byte
offset := 0
if version == 6 && softwareName == "" { // after frr7.5
buf = make([]byte, 7)
binary.BigEndian.PutUint32(buf, uint32(b.Message))
offset += 4
} else { // before frr7.4
buf = make([]byte, 3)
}
// Address Family (2 bytes) // Address Family (2 bytes)
buf := make([]byte, 3) binary.BigEndian.PutUint16(buf[offset:], uint16(b.Prefix.Family))
binary.BigEndian.PutUint16(buf, uint16(b.Prefix.Family))
addrByteLen, err := addressByteLength(b.Prefix.Family) addrByteLen, err := addressByteLength(b.Prefix.Family)
if err != nil { if err != nil {
return nil, err return nil, err
} }
buf[2] = byte(addrByteLen * 8) buf[offset+2] = byte(addrByteLen * 8)
// Prefix Length (1 byte) + Prefix (variable) // Prefix Length (1 byte) + Prefix (variable)
switch b.Prefix.Family { switch b.Prefix.Family {
case syscall.AF_INET: case syscall.AF_INET:
@@ -2812,6 +2966,11 @@ func (b *NexthopUpdateBody) serialize(version uint8, softwareName string) ([]byt
default: default:
return nil, fmt.Errorf("invalid address family: %d", b.Prefix.Family) return nil, fmt.Errorf("invalid address family: %d", b.Prefix.Family)
} }
if b.Message&messageSRTE > 0 { // frr 7.5
tmpbuf := make([]byte, 4)
binary.BigEndian.PutUint32(tmpbuf, b.srteColor)
buf = append(buf, tmpbuf...)
}
if version >= 5 { if version >= 5 {
// Type (1 byte) (if version>=5) // Type (1 byte) (if version>=5)
// instance (2 bytes) (if version>=5) // instance (2 bytes) (if version>=5)
@@ -2837,6 +2996,11 @@ func (b *NexthopUpdateBody) serialize(version uint8, softwareName string) ([]byt
// Ref: bgp_parse_nexthop_update in bgpd/bgp_nht.c of Quagga1.2&FRR3 (ZAPI3&4) // Ref: bgp_parse_nexthop_update in bgpd/bgp_nht.c of Quagga1.2&FRR3 (ZAPI3&4)
// Ref: zapi_nexthop_update_decode in lib/zclient.c of FRR5.x (ZAPI5) // Ref: zapi_nexthop_update_decode in lib/zclient.c of FRR5.x (ZAPI5)
func (b *NexthopUpdateBody) decodeFromBytes(data []byte, version uint8, softwareName string) error { func (b *NexthopUpdateBody) decodeFromBytes(data []byte, version uint8, softwareName string) error {
if version == 6 && softwareName == "" { // frr7.5
//frr7.5: STREAM_GETL(s, nhr->message);
b.Message = MessageFlag(binary.BigEndian.Uint32(data[0:4]))
data = data[4:]
}
// Address Family (2 bytes) // Address Family (2 bytes)
prefixFamily := binary.BigEndian.Uint16(data[0:2]) prefixFamily := binary.BigEndian.Uint16(data[0:2])
b.Prefix.Family = uint8(prefixFamily) b.Prefix.Family = uint8(prefixFamily)
@@ -2851,6 +3015,11 @@ func (b *NexthopUpdateBody) decodeFromBytes(data []byte, version uint8, software
b.Prefix.Prefix = ipFromFamily(b.Prefix.Family, data[offset:offset+addrByteLen]) b.Prefix.Prefix = ipFromFamily(b.Prefix.Family, data[offset:offset+addrByteLen])
offset += addrByteLen offset += addrByteLen
if b.Message&messageSRTE > 0 { // frr 7.5
b.srteColor = binary.BigEndian.Uint32(data[offset : offset+4])
offset += 4
}
if version > 4 { if version > 4 {
b.Type = RouteType(data[offset]) b.Type = RouteType(data[offset])
b.instance = binary.BigEndian.Uint16(data[offset+1 : offset+3]) b.instance = binary.BigEndian.Uint16(data[offset+1 : offset+3])
@@ -2876,7 +3045,7 @@ func (b *NexthopUpdateBody) decodeFromBytes(data []byte, version uint8, software
processFlag := nexthopProcessFlag(nexthopHasType) processFlag := nexthopProcessFlag(nexthopHasType)
if version == 6 { if version == 6 {
switch softwareName { switch softwareName {
case "": case "", "frr7.3":
processFlag |= (nexthopHasVrfID | nexthopHasFlag | nexthopProcessIPToIPIFindex) processFlag |= (nexthopHasVrfID | nexthopHasFlag | nexthopProcessIPToIPIFindex)
case "frr7.0", "frr7.2": case "frr7.0", "frr7.2":
processFlag |= (nexthopHasVrfID | nexthopProcessIPToIPIFindex) processFlag |= (nexthopHasVrfID | nexthopProcessIPToIPIFindex)
@@ -2885,20 +3054,20 @@ func (b *NexthopUpdateBody) decodeFromBytes(data []byte, version uint8, software
} }
} else if version == 5 { } else if version == 5 {
switch softwareName { switch softwareName {
case "frr5", "": case "":
processFlag |= nexthopProcessIPToIPIFindex processFlag |= nexthopProcessIPToIPIFindex
} }
} else if version < 4 { // quagga } else if version < 4 { // quagga
processFlag |= nexthopProcessIFnameToIFindex processFlag |= nexthopProcessIFnameToIFindex
} }
message := MessageFlag(0) // after frr7.3, MessageLabel is deleted
if (version == 6 && !(softwareName == "frr7.3" || softwareName == "")) || if (version == 6 && !(softwareName == "frr7.3" || softwareName == "")) ||
(version == 5 && (softwareName == "frr5" || softwareName == "")) { (version == 5 && softwareName == "") {
message |= MessageLabel b.Message |= MessageLabel
} }
nexthopsByteLen, err := decodeNexthops(&b.Nexthops, data[offset:], version, softwareName, b.Prefix.Family, numNexthop, processFlag, message, Flag(0), nexthopType(0)) nexthopsByteLen, err := decodeNexthops(&b.Nexthops, data[offset:], version, softwareName, b.Prefix.Family, numNexthop, processFlag, b.Message, Flag(0), nexthopType(0))
if err != nil { if err != nil {
return err return err
} }

View File

@@ -28,6 +28,7 @@ import (
"sort" "sort"
"strconv" "strconv"
"strings" "strings"
"sync"
) )
type MarshallingOption struct { type MarshallingOption struct {
@@ -79,6 +80,7 @@ const (
SAFI_VPLS = 65 SAFI_VPLS = 65
SAFI_EVPN = 70 SAFI_EVPN = 70
SAFI_LS = 71 SAFI_LS = 71
SAFI_SRPOLICY = 73
SAFI_MPLS_VPN = 128 SAFI_MPLS_VPN = 128
SAFI_MPLS_VPN_MULTICAST = 129 SAFI_MPLS_VPN_MULTICAST = 129
SAFI_ROUTE_TARGET_CONSTRAINTS = 132 SAFI_ROUTE_TARGET_CONSTRAINTS = 132
@@ -100,6 +102,11 @@ const (
BGP_ASPATH_ATTR_TYPE_CONFED_SET = 4 BGP_ASPATH_ATTR_TYPE_CONFED_SET = 4
) )
const (
BGP_ATTR_NHLEN_IPV6_GLOBAL = 16
BGP_ATTR_NHLEN_IPV6_GLOBAL_AND_LL = 32
)
// RFC7153 5.1. Registries for the "Type" Field // RFC7153 5.1. Registries for the "Type" Field
// RANGE REGISTRATION PROCEDURES // RANGE REGISTRATION PROCEDURES
// 0x00-0x3F Transitive First Come First Served // 0x00-0x3F Transitive First Come First Served
@@ -121,6 +128,7 @@ const (
EC_TYPE_EVPN ExtendedCommunityAttrType = 0x06 EC_TYPE_EVPN ExtendedCommunityAttrType = 0x06
EC_TYPE_FLOWSPEC_REDIRECT_MIRROR ExtendedCommunityAttrType = 0x08 EC_TYPE_FLOWSPEC_REDIRECT_MIRROR ExtendedCommunityAttrType = 0x08
EC_TYPE_NON_TRANSITIVE_TWO_OCTET_AS_SPECIFIC ExtendedCommunityAttrType = 0x40 EC_TYPE_NON_TRANSITIVE_TWO_OCTET_AS_SPECIFIC ExtendedCommunityAttrType = 0x40
EC_TYPE_NON_TRANSITIVE_LINK_BANDWIDTH ExtendedCommunityAttrType = 0x40
EC_TYPE_NON_TRANSITIVE_IP6_SPECIFIC ExtendedCommunityAttrType = 0x40 // RFC5701 EC_TYPE_NON_TRANSITIVE_IP6_SPECIFIC ExtendedCommunityAttrType = 0x40 // RFC5701
EC_TYPE_NON_TRANSITIVE_IP4_SPECIFIC ExtendedCommunityAttrType = 0x41 EC_TYPE_NON_TRANSITIVE_IP4_SPECIFIC ExtendedCommunityAttrType = 0x41
EC_TYPE_NON_TRANSITIVE_FOUR_OCTET_AS_SPECIFIC ExtendedCommunityAttrType = 0x42 EC_TYPE_NON_TRANSITIVE_FOUR_OCTET_AS_SPECIFIC ExtendedCommunityAttrType = 0x42
@@ -184,6 +192,8 @@ const (
TUNNEL_TYPE_MPLS_IN_GRE TunnelType = 11 TUNNEL_TYPE_MPLS_IN_GRE TunnelType = 11
TUNNEL_TYPE_VXLAN_GRE TunnelType = 12 TUNNEL_TYPE_VXLAN_GRE TunnelType = 12
TUNNEL_TYPE_MPLS_IN_UDP TunnelType = 13 TUNNEL_TYPE_MPLS_IN_UDP TunnelType = 13
TUNNEL_TYPE_SR_POLICY TunnelType = 15
TUNNEL_TYPE_GENEVE TunnelType = 19
) )
func (p TunnelType) String() string { func (p TunnelType) String() string {
@@ -206,6 +216,10 @@ func (p TunnelType) String() string {
return "vxlan-gre" return "vxlan-gre"
case TUNNEL_TYPE_MPLS_IN_UDP: case TUNNEL_TYPE_MPLS_IN_UDP:
return "mpls-in-udp" return "mpls-in-udp"
case TUNNEL_TYPE_SR_POLICY:
return "sr-policy"
case TUNNEL_TYPE_GENEVE:
return "geneve"
default: default:
return fmt.Sprintf("TunnelType(%d)", uint8(p)) return fmt.Sprintf("TunnelType(%d)", uint8(p))
} }
@@ -253,6 +267,14 @@ const (
ENCAP_SUBTLV_TYPE_ENCAPSULATION EncapSubTLVType = 1 ENCAP_SUBTLV_TYPE_ENCAPSULATION EncapSubTLVType = 1
ENCAP_SUBTLV_TYPE_PROTOCOL EncapSubTLVType = 2 ENCAP_SUBTLV_TYPE_PROTOCOL EncapSubTLVType = 2
ENCAP_SUBTLV_TYPE_COLOR EncapSubTLVType = 4 ENCAP_SUBTLV_TYPE_COLOR EncapSubTLVType = 4
ENCAP_SUBTLV_TYPE_EGRESS_ENDPOINT EncapSubTLVType = 6
ENCAP_SUBTLV_TYPE_UDP_DEST_PORT EncapSubTLVType = 8
ENCAP_SUBTLV_TYPE_SRPREFERENCE EncapSubTLVType = 12
ENCAP_SUBTLV_TYPE_SRBINDING_SID EncapSubTLVType = 13
ENCAP_SUBTLV_TYPE_SRENLP EncapSubTLVType = 14
ENCAP_SUBTLV_TYPE_SRPRIORITY EncapSubTLVType = 15
ENCAP_SUBTLV_TYPE_SRSEGMENT_LIST EncapSubTLVType = 128
ENCAP_SUBTLV_TYPE_SRCANDIDATE_PATH_NAME EncapSubTLVType = 129
) )
const ( const (
@@ -280,6 +302,7 @@ const (
BGP_CAP_ADD_PATH BGPCapabilityCode = 69 BGP_CAP_ADD_PATH BGPCapabilityCode = 69
BGP_CAP_ENHANCED_ROUTE_REFRESH BGPCapabilityCode = 70 BGP_CAP_ENHANCED_ROUTE_REFRESH BGPCapabilityCode = 70
BGP_CAP_LONG_LIVED_GRACEFUL_RESTART BGPCapabilityCode = 71 BGP_CAP_LONG_LIVED_GRACEFUL_RESTART BGPCapabilityCode = 71
BGP_CAP_FQDN BGPCapabilityCode = 73
BGP_CAP_ROUTE_REFRESH_CISCO BGPCapabilityCode = 128 BGP_CAP_ROUTE_REFRESH_CISCO BGPCapabilityCode = 128
) )
@@ -294,6 +317,7 @@ var CapNameMap = map[BGPCapabilityCode]string{
BGP_CAP_ENHANCED_ROUTE_REFRESH: "enhanced-route-refresh", BGP_CAP_ENHANCED_ROUTE_REFRESH: "enhanced-route-refresh",
BGP_CAP_ROUTE_REFRESH_CISCO: "cisco-route-refresh", BGP_CAP_ROUTE_REFRESH_CISCO: "cisco-route-refresh",
BGP_CAP_LONG_LIVED_GRACEFUL_RESTART: "long-lived-graceful-restart", BGP_CAP_LONG_LIVED_GRACEFUL_RESTART: "long-lived-graceful-restart",
BGP_CAP_FQDN: "fqdn",
} }
func (c BGPCapabilityCode) String() string { func (c BGPCapabilityCode) String() string {
@@ -490,11 +514,13 @@ type CapExtendedNexthop struct {
func (c *CapExtendedNexthop) DecodeFromBytes(data []byte) error { func (c *CapExtendedNexthop) DecodeFromBytes(data []byte) error {
c.DefaultParameterCapability.DecodeFromBytes(data) c.DefaultParameterCapability.DecodeFromBytes(data)
data = data[2:] data = data[2:]
if len(data) < 6 { capLen := int(c.CapLen)
if capLen%6 != 0 || capLen < 6 || len(data) < capLen {
return NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_CAPABILITY, nil, "Not all CapabilityExtendedNexthop bytes available") return NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_CAPABILITY, nil, "Not all CapabilityExtendedNexthop bytes available")
} }
c.Tuples = []*CapExtendedNexthopTuple{} c.Tuples = []*CapExtendedNexthopTuple{}
for len(data) >= 6 { for capLen >= 6 {
t := &CapExtendedNexthopTuple{ t := &CapExtendedNexthopTuple{
binary.BigEndian.Uint16(data[0:2]), binary.BigEndian.Uint16(data[0:2]),
binary.BigEndian.Uint16(data[2:4]), binary.BigEndian.Uint16(data[2:4]),
@@ -502,6 +528,7 @@ func (c *CapExtendedNexthop) DecodeFromBytes(data []byte) error {
} }
c.Tuples = append(c.Tuples, t) c.Tuples = append(c.Tuples, t)
data = data[6:] data = data[6:]
capLen -= 6
} }
return nil return nil
} }
@@ -739,17 +766,20 @@ type CapAddPath struct {
func (c *CapAddPath) DecodeFromBytes(data []byte) error { func (c *CapAddPath) DecodeFromBytes(data []byte) error {
c.DefaultParameterCapability.DecodeFromBytes(data) c.DefaultParameterCapability.DecodeFromBytes(data)
data = data[2:] data = data[2:]
if len(data) < 4 { capLen := int(c.CapLen)
if capLen%4 != 0 || capLen < 4 || len(data) < capLen {
return NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_CAPABILITY, nil, "Not all CapabilityAddPath bytes available") return NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_CAPABILITY, nil, "Not all CapabilityAddPath bytes available")
} }
c.Tuples = []*CapAddPathTuple{} c.Tuples = []*CapAddPathTuple{}
for len(data) >= 4 { for capLen >= 4 {
t := &CapAddPathTuple{ t := &CapAddPathTuple{
RouteFamily: AfiSafiToRouteFamily(binary.BigEndian.Uint16(data[:2]), data[2]), RouteFamily: AfiSafiToRouteFamily(binary.BigEndian.Uint16(data[:2]), data[2]),
Mode: BGPAddPathMode(data[3]), Mode: BGPAddPathMode(data[3]),
} }
c.Tuples = append(c.Tuples, t) c.Tuples = append(c.Tuples, t)
data = data[4:] data = data[4:]
capLen -= 4
} }
return nil return nil
} }
@@ -901,6 +931,71 @@ func NewCapLongLivedGracefulRestart(tuples []*CapLongLivedGracefulRestartTuple)
} }
} }
type CapFQDN struct {
DefaultParameterCapability
HostNameLen uint8
HostName string
DomainNameLen uint8
DomainName string
}
func (c *CapFQDN) DecodeFromBytes(data []byte) error {
c.DefaultParameterCapability.DecodeFromBytes(data)
data = data[2:]
if len(data) < 2 {
return NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_CAPABILITY, nil, "Not all CapabilityFQDN bytes allowed")
}
hostNameLen := uint8(data[0])
c.HostNameLen = hostNameLen
c.HostName = string(data[1 : c.HostNameLen+1])
domainNameLen := uint8(data[c.HostNameLen+1])
c.DomainNameLen = domainNameLen
c.DomainName = string(data[c.HostNameLen+2:])
return nil
}
func (c *CapFQDN) Serialize() ([]byte, error) {
buf := make([]byte, c.HostNameLen+c.DomainNameLen+2)
buf[0] = c.HostNameLen
copy(buf[1:c.HostNameLen+1], c.HostName)
buf[c.HostNameLen+1] = c.DomainNameLen
copy(buf[c.HostNameLen+2:], c.DomainName)
c.DefaultParameterCapability.CapValue = buf
return c.DefaultParameterCapability.Serialize()
}
func (c *CapFQDN) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
HostNameLen uint8 `json:"hostname_len"`
HostName string `json:"hostname"`
DomainNameLen uint8 `json:"domainname_len"`
DomainName string `json:"domainname"`
}{
HostNameLen: c.HostNameLen,
HostName: c.HostName,
DomainNameLen: c.DomainNameLen,
DomainName: c.DomainName,
})
}
func NewCapFQDN(hostname string, domainname string) *CapFQDN {
if len(hostname) > 64 {
hostname = hostname[:64]
}
if len(domainname) > 64 {
domainname = domainname[:64]
}
return &CapFQDN{
DefaultParameterCapability{
CapCode: BGP_CAP_FQDN,
},
uint8(len(hostname)),
hostname,
uint8(len(domainname)),
domainname,
}
}
type CapUnknown struct { type CapUnknown struct {
DefaultParameterCapability DefaultParameterCapability
} }
@@ -940,6 +1035,8 @@ func DecodeCapability(data []byte) (ParameterCapabilityInterface, error) {
c = &CapRouteRefreshCisco{} c = &CapRouteRefreshCisco{}
case BGP_CAP_LONG_LIVED_GRACEFUL_RESTART: case BGP_CAP_LONG_LIVED_GRACEFUL_RESTART:
c = &CapLongLivedGracefulRestart{} c = &CapLongLivedGracefulRestart{}
case BGP_CAP_FQDN:
c = &CapFQDN{}
default: default:
c = &CapUnknown{} c = &CapUnknown{}
} }
@@ -967,6 +1064,9 @@ func (o *OptionParameterCapability) DecodeFromBytes(data []byte) error {
return err return err
} }
o.Capability = append(o.Capability, c) o.Capability = append(o.Capability, c)
if c.Len() == 0 || len(data) < c.Len() {
return NewMessageError(BGP_ERROR_MESSAGE_HEADER_ERROR, BGP_ERROR_SUB_BAD_MESSAGE_LENGTH, nil, "Bad capability length")
}
data = data[c.Len():] data = data[c.Len():]
} }
return nil return nil
@@ -1041,7 +1141,7 @@ func (msg *BGPOpen) DecodeFromBytes(data []byte, options ...*MarshallingOption)
} }
paramtype := data[0] paramtype := data[0]
paramlen := data[1] paramlen := data[1]
if rest < paramlen+2 { if paramlen >= 254 || rest < paramlen+2 {
return NewMessageError(BGP_ERROR_MESSAGE_HEADER_ERROR, BGP_ERROR_SUB_BAD_MESSAGE_LENGTH, nil, "Malformed BGP Open message") return NewMessageError(BGP_ERROR_MESSAGE_HEADER_ERROR, BGP_ERROR_SUB_BAD_MESSAGE_LENGTH, nil, "Malformed BGP Open message")
} }
rest -= paramlen + 2 rest -= paramlen + 2
@@ -1136,23 +1236,36 @@ func LabelString(nlri AddrPrefixInterface) string {
} }
type PrefixDefault struct { type PrefixDefault struct {
mu sync.Mutex
id uint32 id uint32
localId uint32 localId uint32
} }
func (p *PrefixDefault) PathIdentifier() uint32 { func (p *PrefixDefault) PathIdentifier() uint32 {
p.mu.Lock()
defer p.mu.Unlock()
return p.id return p.id
} }
func (p *PrefixDefault) SetPathIdentifier(id uint32) { func (p *PrefixDefault) SetPathIdentifier(id uint32) {
p.mu.Lock()
defer p.mu.Unlock()
p.id = id p.id = id
} }
func (p *PrefixDefault) PathLocalIdentifier() uint32 { func (p *PrefixDefault) PathLocalIdentifier() uint32 {
p.mu.Lock()
defer p.mu.Unlock()
return p.localId return p.localId
} }
func (p *PrefixDefault) SetPathLocalIdentifier(id uint32) { func (p *PrefixDefault) SetPathLocalIdentifier(id uint32) {
p.mu.Lock()
defer p.mu.Unlock()
p.localId = id p.localId = id
} }
@@ -1185,6 +1298,11 @@ func (r *IPAddrPrefixDefault) decodePrefix(data []byte, bitlen uint8, addrlen ui
eSubCode := uint8(BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST) eSubCode := uint8(BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST)
return NewMessageError(eCode, eSubCode, nil, "network bytes is short") return NewMessageError(eCode, eSubCode, nil, "network bytes is short")
} }
if bitlen > addrlen*8 {
eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
eSubCode := uint8(BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST)
return NewMessageError(eCode, eSubCode, nil, "network bit length is too long")
}
b := make([]byte, addrlen) b := make([]byte, addrlen)
copy(b, data[:bytelen]) copy(b, data[:bytelen])
// clear trailing bits in the last byte. rfc doesn't require // clear trailing bits in the last byte. rfc doesn't require
@@ -1606,10 +1724,8 @@ func (l *MPLSLabelStack) DecodeFromBytes(data []byte, options ...*MarshallingOpt
foundBottom := false foundBottom := false
bottomExpected := true bottomExpected := true
if IsAttributePresent(BGP_ATTR_TYPE_PREFIX_SID, options) { if IsAttributePresent(BGP_ATTR_TYPE_PREFIX_SID, options) {
// If Update carries Prefix SID attribute then there is no a label stack, // If Update carries Prefix SID attribute then one should not rely on BoS for the label stack processing,
// but just 3 bytes which are used to carry the lower portion of Prefix SID. // the first and only label carries transposed variable part of the SRv6 SID.
// There is no bottom stack indication in this case. Once 3 bytes are stored
// breaking out of the loop.
bottomExpected = false bottomExpected = false
} }
for len(data) >= 3 { for len(data) >= 3 {
@@ -1650,13 +1766,6 @@ func (l *MPLSLabelStack) Serialize(options ...*MarshallingOption) ([]byte, error
buf[i*3+1] = byte((label >> 8) & 0xff) buf[i*3+1] = byte((label >> 8) & 0xff)
buf[i*3+2] = byte(label & 0xff) buf[i*3+2] = byte(label & 0xff)
} }
if IsAttributePresent(BGP_ATTR_TYPE_PREFIX_SID, options) {
// If Update carries Prefix SID attribute then there is no a label stack,
// but just 3 bytes which are used to carry the lower portion of Prefix SID.
// No need BoS bit set
return buf, nil
}
buf[len(buf)-1] |= 1 buf[len(buf)-1] |= 1
return buf, nil return buf, nil
} }
@@ -1760,6 +1869,10 @@ func (l *LabeledVPNIPAddrPrefix) DecodeFromBytes(data []byte, options ...*Marsha
} }
data = data[l.Labels.Len():] data = data[l.Labels.Len():]
l.RD = GetRouteDistinguisher(data) l.RD = GetRouteDistinguisher(data)
rdLen := l.RD.Len()
if len(data) < rdLen {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "bad labeled VPN-IPv4 NLRI length")
}
data = data[l.RD.Len():] data = data[l.RD.Len():]
restbits := int(l.Length) - 8*(l.Labels.Len()+l.RD.Len()) restbits := int(l.Length) - 8*(l.Labels.Len()+l.RD.Len())
return l.decodePrefix(data, uint8(restbits), l.addrlen) return l.decodePrefix(data, uint8(restbits), l.addrlen)
@@ -2120,6 +2233,9 @@ type EthernetSegmentIdentifier struct {
} }
func (esi *EthernetSegmentIdentifier) DecodeFromBytes(data []byte) error { func (esi *EthernetSegmentIdentifier) DecodeFromBytes(data []byte) error {
if len(data) < 10 {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("invalid %s length", esi.Type.String()))
}
esi.Type = ESIType(data[0]) esi.Type = ESIType(data[0])
esi.Value = data[1:10] esi.Value = data[1:10]
switch esi.Type { switch esi.Type {
@@ -2366,6 +2482,10 @@ func (er *EVPNEthernetAutoDiscoveryRoute) Len() int {
func (er *EVPNEthernetAutoDiscoveryRoute) DecodeFromBytes(data []byte) error { func (er *EVPNEthernetAutoDiscoveryRoute) DecodeFromBytes(data []byte) error {
er.RD = GetRouteDistinguisher(data) er.RD = GetRouteDistinguisher(data)
rdLen := er.RD.Len()
if len(data) < rdLen+14 { // 14 is 10 for
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "bad Ethernet Auto-discovery Route length")
}
data = data[er.RD.Len():] data = data[er.RD.Len():]
err := er.ESI.DecodeFromBytes(data) err := er.ESI.DecodeFromBytes(data)
if err != nil { if err != nil {
@@ -2466,6 +2586,10 @@ func (er *EVPNMacIPAdvertisementRoute) Len() int {
func (er *EVPNMacIPAdvertisementRoute) DecodeFromBytes(data []byte) error { func (er *EVPNMacIPAdvertisementRoute) DecodeFromBytes(data []byte) error {
er.RD = GetRouteDistinguisher(data) er.RD = GetRouteDistinguisher(data)
rdLen := er.RD.Len()
if len(data) < rdLen {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "bad length of MAC/IP Advertisement Route")
}
data = data[er.RD.Len():] data = data[er.RD.Len():]
err := er.ESI.DecodeFromBytes(data) err := er.ESI.DecodeFromBytes(data)
if err != nil { if err != nil {
@@ -2618,6 +2742,10 @@ func (er *EVPNMulticastEthernetTagRoute) Len() int {
func (er *EVPNMulticastEthernetTagRoute) DecodeFromBytes(data []byte) error { func (er *EVPNMulticastEthernetTagRoute) DecodeFromBytes(data []byte) error {
er.RD = GetRouteDistinguisher(data) er.RD = GetRouteDistinguisher(data)
rdLen := er.RD.Len()
if len(data) < rdLen+4 {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "invalid length of multicast ethernet tag route")
}
data = data[er.RD.Len():] data = data[er.RD.Len():]
er.ETag = binary.BigEndian.Uint32(data[0:4]) er.ETag = binary.BigEndian.Uint32(data[0:4])
er.IPAddressLength = data[4] er.IPAddressLength = data[4]
@@ -2712,6 +2840,10 @@ func (er *EVPNEthernetSegmentRoute) Len() int {
func (er *EVPNEthernetSegmentRoute) DecodeFromBytes(data []byte) error { func (er *EVPNEthernetSegmentRoute) DecodeFromBytes(data []byte) error {
er.RD = GetRouteDistinguisher(data) er.RD = GetRouteDistinguisher(data)
rdLen := er.RD.Len()
if len(data) < rdLen {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "invalid Ethernet Segment Route length")
}
data = data[er.RD.Len():] data = data[er.RD.Len():]
er.ESI.DecodeFromBytes(data) er.ESI.DecodeFromBytes(data)
data = data[10:] data = data[10:]
@@ -4377,6 +4509,9 @@ func (n *FlowSpecNLRI) decodeFromBytes(rf RouteFamily, data []byte, options ...*
} else { } else {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "not all flowspec component bytes available") return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "not all flowspec component bytes available")
} }
if len(data) < length {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "not all flowspec component bytes available")
}
n.rf = rf n.rf = rf
@@ -4813,7 +4948,7 @@ func (n *OpaqueNLRI) Len(options ...*MarshallingOption) int {
} }
func (n *OpaqueNLRI) String() string { func (n *OpaqueNLRI) String() string {
return fmt.Sprintf("%s", n.Key) return string(n.Key)
} }
func (n *OpaqueNLRI) MarshalJSON() ([]byte, error) { func (n *OpaqueNLRI) MarshalJSON() ([]byte, error) {
@@ -5010,19 +5145,34 @@ func (l *LsLinkDescriptor) ParseTLVs(tlvs []LsTLVInterface) {
} }
func (l *LsLinkDescriptor) String() string { func (l *LsLinkDescriptor) String() string {
if l.InterfaceAddrIPv4 != nil && l.NeighborAddrIPv4 != nil { switch {
case l.InterfaceAddrIPv4 != nil && l.NeighborAddrIPv4 != nil:
return fmt.Sprintf("%v->%v", l.InterfaceAddrIPv4, l.NeighborAddrIPv4) return fmt.Sprintf("%v->%v", l.InterfaceAddrIPv4, l.NeighborAddrIPv4)
}
if l.InterfaceAddrIPv6 != nil && l.NeighborAddrIPv6 != nil { case l.InterfaceAddrIPv6 != nil && l.NeighborAddrIPv6 != nil:
return fmt.Sprintf("%v->%v", l.InterfaceAddrIPv6, l.NeighborAddrIPv6) return fmt.Sprintf("%v->%v", l.InterfaceAddrIPv6, l.NeighborAddrIPv6)
}
if l.LinkLocalID != nil && l.LinkRemoteID != nil { case l.LinkLocalID != nil && l.LinkRemoteID != nil:
return fmt.Sprintf("%v->%v", *l.LinkLocalID, *l.LinkRemoteID) return fmt.Sprintf("%v->%v", *l.LinkLocalID, *l.LinkRemoteID)
}
case l.InterfaceAddrIPv4 != nil:
return fmt.Sprintf("%v->UNKNOWN", l.InterfaceAddrIPv4)
case l.NeighborAddrIPv4 != nil:
return fmt.Sprintf("UNKNOWN->%v", l.NeighborAddrIPv4)
case l.InterfaceAddrIPv6 != nil:
return fmt.Sprintf("%v->UNKNOWN", l.InterfaceAddrIPv6)
case l.NeighborAddrIPv6 != nil:
return fmt.Sprintf("UNKNOWN->%v", l.NeighborAddrIPv6)
case l.LinkLocalID != nil:
return fmt.Sprintf("%v->UNKNOWN", *l.LinkLocalID)
case l.LinkRemoteID != nil:
return fmt.Sprintf("UNKNOWN->%v", *l.LinkRemoteID)
default:
return "UNKNOWN" return "UNKNOWN"
}
} }
type LsLinkNLRI struct { type LsLinkNLRI struct {
@@ -6247,9 +6397,12 @@ func (l *LsTLVIgpRouterID) DecodeFromBytes(data []byte) error {
} }
// https://tools.ietf.org/html/rfc7752#section-3.2.1.4 // https://tools.ietf.org/html/rfc7752#section-3.2.1.4
// 6, 7, and 8 are the only valid values. // 4, 6, 7, and 8 are the only valid values.
if len(value) < 6 || len(value) > 8 { switch len(value) {
return malformedAttrListErr("Incorrect IGP Router ID length") case 4, 6, 7, 8:
break
default:
return malformedAttrListErr(fmt.Sprintf("Incorrect IGP Router ID length: %d", len(value)))
} }
l.RouterID = value l.RouterID = value
@@ -8146,6 +8299,8 @@ const (
RF_FS_L2_VPN RouteFamily = AFI_L2VPN<<16 | SAFI_FLOW_SPEC_VPN RF_FS_L2_VPN RouteFamily = AFI_L2VPN<<16 | SAFI_FLOW_SPEC_VPN
RF_OPAQUE RouteFamily = AFI_OPAQUE<<16 | SAFI_KEY_VALUE RF_OPAQUE RouteFamily = AFI_OPAQUE<<16 | SAFI_KEY_VALUE
RF_LS RouteFamily = AFI_LS<<16 | SAFI_LS RF_LS RouteFamily = AFI_LS<<16 | SAFI_LS
RF_SR_POLICY_IPv4 RouteFamily = AFI_IP<<16 | SAFI_SRPOLICY
RF_SR_POLICY_IPv6 RouteFamily = AFI_IP6<<16 | SAFI_SRPOLICY
) )
var AddressFamilyNameMap = map[RouteFamily]string{ var AddressFamilyNameMap = map[RouteFamily]string{
@@ -8171,6 +8326,8 @@ var AddressFamilyNameMap = map[RouteFamily]string{
RF_FS_L2_VPN: "l2vpn-flowspec", RF_FS_L2_VPN: "l2vpn-flowspec",
RF_OPAQUE: "opaque", RF_OPAQUE: "opaque",
RF_LS: "ls", RF_LS: "ls",
RF_SR_POLICY_IPv4: "ipv4-srpolicy",
RF_SR_POLICY_IPv6: "ipv6-srpolicy",
} }
var AddressFamilyValueMap = map[string]RouteFamily{ var AddressFamilyValueMap = map[string]RouteFamily{
@@ -8196,6 +8353,8 @@ var AddressFamilyValueMap = map[string]RouteFamily{
AddressFamilyNameMap[RF_FS_L2_VPN]: RF_FS_L2_VPN, AddressFamilyNameMap[RF_FS_L2_VPN]: RF_FS_L2_VPN,
AddressFamilyNameMap[RF_OPAQUE]: RF_OPAQUE, AddressFamilyNameMap[RF_OPAQUE]: RF_OPAQUE,
AddressFamilyNameMap[RF_LS]: RF_LS, AddressFamilyNameMap[RF_LS]: RF_LS,
AddressFamilyNameMap[RF_SR_POLICY_IPv4]: RF_SR_POLICY_IPv4,
AddressFamilyNameMap[RF_SR_POLICY_IPv6]: RF_SR_POLICY_IPv6,
} }
func GetRouteFamily(name string) (RouteFamily, error) { func GetRouteFamily(name string) (RouteFamily, error) {
@@ -8241,6 +8400,20 @@ func NewPrefixFromRouteFamily(afi uint16, safi uint8, prefixStr ...string) (pref
prefix = NewLabeledIPv6AddrPrefix(0, "", *NewMPLSLabelStack()) prefix = NewLabeledIPv6AddrPrefix(0, "", *NewMPLSLabelStack())
case RF_EVPN: case RF_EVPN:
prefix = NewEVPNNLRI(0, nil) prefix = NewEVPNNLRI(0, nil)
// TODO (sbezverk) Add processing SR Policy NLRI
case RF_SR_POLICY_IPv4:
prefix = &SRPolicyIPv4{
SRPolicyNLRI: SRPolicyNLRI{
rf: RF_SR_POLICY_IPv4,
},
}
case RF_SR_POLICY_IPv6:
prefix = &SRPolicyIPv6{
SRPolicyNLRI: SRPolicyNLRI{
rf: RF_SR_POLICY_IPv6,
},
}
case RF_RTC_UC: case RF_RTC_UC:
prefix = &RouteTargetMembershipNLRI{} prefix = &RouteTargetMembershipNLRI{}
case RF_IPv4_ENCAP: case RF_IPv4_ENCAP:
@@ -9635,7 +9808,7 @@ func (p *PathAttributeMpReachNLRI) Serialize(options ...*MarshallingOption) ([]b
safi := p.SAFI safi := p.SAFI
nexthoplen := 4 nexthoplen := 4
if afi == AFI_IP6 || p.Nexthop.To4() == nil { if afi == AFI_IP6 || p.Nexthop.To4() == nil {
nexthoplen = 16 nexthoplen = BGP_ATTR_NHLEN_IPV6_GLOBAL
} }
offset := 0 offset := 0
switch safi { switch safi {
@@ -9645,8 +9818,8 @@ func (p *PathAttributeMpReachNLRI) Serialize(options ...*MarshallingOption) ([]b
case SAFI_FLOW_SPEC_VPN, SAFI_FLOW_SPEC_UNICAST: case SAFI_FLOW_SPEC_VPN, SAFI_FLOW_SPEC_UNICAST:
nexthoplen = 0 nexthoplen = 0
} }
if p.LinkLocalNexthop != nil { if p.LinkLocalNexthop != nil && p.LinkLocalNexthop.IsLinkLocalUnicast() {
nexthoplen *= 2 nexthoplen = BGP_ATTR_NHLEN_IPV6_GLOBAL_AND_LL
} }
buf := make([]byte, 4+nexthoplen) buf := make([]byte, 4+nexthoplen)
binary.BigEndian.PutUint16(buf[0:], afi) binary.BigEndian.PutUint16(buf[0:], afi)
@@ -9655,7 +9828,7 @@ func (p *PathAttributeMpReachNLRI) Serialize(options ...*MarshallingOption) ([]b
if nexthoplen != 0 { if nexthoplen != 0 {
if p.Nexthop.To4() == nil { if p.Nexthop.To4() == nil {
copy(buf[4+offset:], p.Nexthop.To16()) copy(buf[4+offset:], p.Nexthop.To16())
if p.LinkLocalNexthop != nil { if nexthoplen == BGP_ATTR_NHLEN_IPV6_GLOBAL_AND_LL {
copy(buf[4+offset+16:], p.LinkLocalNexthop.To16()) copy(buf[4+offset+16:], p.LinkLocalNexthop.To16())
} }
} else { } else {
@@ -10101,6 +10274,55 @@ func NewFourOctetAsSpecificExtended(subtype ExtendedCommunityAttrSubType, as uin
} }
func ParseExtendedCommunity(subtype ExtendedCommunityAttrSubType, com string) (ExtendedCommunityInterface, error) { func ParseExtendedCommunity(subtype ExtendedCommunityAttrSubType, com string) (ExtendedCommunityInterface, error) {
if subtype == EC_SUBTYPE_ENCAPSULATION {
var t TunnelType
switch com {
case TUNNEL_TYPE_L2TP3.String():
t = TUNNEL_TYPE_L2TP3
case TUNNEL_TYPE_GRE.String():
t = TUNNEL_TYPE_GRE
case TUNNEL_TYPE_IP_IN_IP.String():
t = TUNNEL_TYPE_IP_IN_IP
case TUNNEL_TYPE_VXLAN.String():
t = TUNNEL_TYPE_VXLAN
case TUNNEL_TYPE_NVGRE.String():
t = TUNNEL_TYPE_NVGRE
case TUNNEL_TYPE_MPLS.String():
t = TUNNEL_TYPE_MPLS
case TUNNEL_TYPE_MPLS_IN_GRE.String():
t = TUNNEL_TYPE_MPLS_IN_GRE
case TUNNEL_TYPE_VXLAN_GRE.String():
t = TUNNEL_TYPE_VXLAN_GRE
case TUNNEL_TYPE_MPLS_IN_UDP.String():
t = TUNNEL_TYPE_MPLS_IN_UDP
case TUNNEL_TYPE_GENEVE.String():
t = TUNNEL_TYPE_GENEVE
case "L2TPv3 over IP":
t = TUNNEL_TYPE_L2TP3
case "GRE":
t = TUNNEL_TYPE_GRE
case "IP in IP":
t = TUNNEL_TYPE_IP_IN_IP
case "VXLAN":
t = TUNNEL_TYPE_VXLAN
case "NVGRE":
t = TUNNEL_TYPE_NVGRE
case "MPLS":
t = TUNNEL_TYPE_MPLS
case "MPLS in GRE":
t = TUNNEL_TYPE_MPLS_IN_GRE
case "VXLAN GRE":
t = TUNNEL_TYPE_VXLAN_GRE
case "MPLS in UDP":
t = TUNNEL_TYPE_MPLS_IN_UDP
case "GENEVE":
t = TUNNEL_TYPE_GENEVE
default:
return nil, fmt.Errorf("invalid encap type %s", com)
}
return NewEncapExtended(t), nil
}
if subtype == EC_SUBTYPE_ORIGIN_VALIDATION { if subtype == EC_SUBTYPE_ORIGIN_VALIDATION {
var state ValidationState var state ValidationState
switch com { switch com {
@@ -10128,6 +10350,9 @@ func ParseExtendedCommunity(subtype ExtendedCommunityAttrSubType, com string) (E
ip := net.ParseIP(elems[1]) ip := net.ParseIP(elems[1])
isTransitive := true isTransitive := true
switch { switch {
case subtype == EC_SUBTYPE_LINK_BANDWIDTH:
asn, _ := strconv.ParseUint(elems[8], 10, 16)
return NewLinkBandwidthExtended(uint16(asn), float32(localAdmin)), nil
case ip.To4() != nil: case ip.To4() != nil:
return NewIPv4AddressSpecificExtended(subtype, elems[1], uint16(localAdmin), isTransitive), nil return NewIPv4AddressSpecificExtended(subtype, elems[1], uint16(localAdmin), isTransitive), nil
case ip.To16() != nil: case ip.To16() != nil:
@@ -10219,6 +10444,51 @@ func NewValidationExtended(state ValidationState) *ValidationExtended {
} }
} }
type LinkBandwidthExtended struct {
AS uint16
Bandwidth float32
}
func (e *LinkBandwidthExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
return EC_TYPE_NON_TRANSITIVE_LINK_BANDWIDTH, EC_SUBTYPE_LINK_BANDWIDTH
}
func (e *LinkBandwidthExtended) Serialize() ([]byte, error) {
buf := make([]byte, 8)
typ, subType := e.GetTypes()
buf[0] = byte(typ)
buf[1] = byte(subType)
binary.BigEndian.PutUint16(buf[2:4], e.AS)
binary.BigEndian.PutUint32(buf[4:8], math.Float32bits(e.Bandwidth))
return buf, nil
}
func (e *LinkBandwidthExtended) String() string {
return fmt.Sprintf("%d:%d", e.AS, uint32(e.Bandwidth))
}
func (e *LinkBandwidthExtended) MarshalJSON() ([]byte, error) {
t, s := e.GetTypes()
return json.Marshal(struct {
Type ExtendedCommunityAttrType `json:"type"`
SubType ExtendedCommunityAttrSubType `json:"subtype"`
AS uint16 `json:"asn"`
Bandwidth float32 `json:"bandwidth"`
}{
Type: t,
SubType: s,
AS: e.AS,
Bandwidth: e.Bandwidth,
})
}
func NewLinkBandwidthExtended(as uint16, bw float32) *LinkBandwidthExtended {
return &LinkBandwidthExtended{
AS: as,
Bandwidth: bw,
}
}
type ColorExtended struct { type ColorExtended struct {
Color uint32 Color uint32
} }
@@ -10292,6 +10562,10 @@ func (e *EncapExtended) String() string {
return "VXLAN GRE" return "VXLAN GRE"
case TUNNEL_TYPE_MPLS_IN_UDP: case TUNNEL_TYPE_MPLS_IN_UDP:
return "MPLS in UDP" return "MPLS in UDP"
case TUNNEL_TYPE_SR_POLICY:
return "SR Policy"
case TUNNEL_TYPE_GENEVE:
return "GENEVE"
default: default:
return fmt.Sprintf("tunnel: %d", e.TunnelType) return fmt.Sprintf("tunnel: %d", e.TunnelType)
} }
@@ -11088,7 +11362,12 @@ func ParseExtended(data []byte) (ExtendedCommunityInterface, error) {
case EC_TYPE_NON_TRANSITIVE_TWO_OCTET_AS_SPECIFIC: case EC_TYPE_NON_TRANSITIVE_TWO_OCTET_AS_SPECIFIC:
as := binary.BigEndian.Uint16(data[2:4]) as := binary.BigEndian.Uint16(data[2:4])
localAdmin := binary.BigEndian.Uint32(data[4:8]) localAdmin := binary.BigEndian.Uint32(data[4:8])
if subtype == EC_SUBTYPE_LINK_BANDWIDTH {
return NewLinkBandwidthExtended(as, math.Float32frombits(localAdmin)), nil
} else {
return NewTwoOctetAsSpecificExtended(subtype, as, localAdmin, transitive), nil return NewTwoOctetAsSpecificExtended(subtype, as, localAdmin, transitive), nil
}
case EC_TYPE_TRANSITIVE_IP4_SPECIFIC: case EC_TYPE_TRANSITIVE_IP4_SPECIFIC:
transitive = true transitive = true
fallthrough fallthrough
@@ -11362,7 +11641,7 @@ func (t *TunnelEncapSubTLV) DecodeFromBytes(data []byte) (value []byte, err erro
if len(data) < int(t.Length) { if len(data) < int(t.Length) {
return nil, NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Not all TunnelEncapSubTLV bytes available") return nil, NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Not all TunnelEncapSubTLV bytes available")
} }
return data, nil return data[:t.Length], nil
} }
func (t *TunnelEncapSubTLV) Serialize(value []byte) (buf []byte, err error) { func (t *TunnelEncapSubTLV) Serialize(value []byte) (buf []byte, err error) {
@@ -11565,6 +11844,156 @@ func NewTunnelEncapSubTLVColor(color uint32) *TunnelEncapSubTLVColor {
} }
} }
type TunnelEncapSubTLVEgressEndpoint struct {
TunnelEncapSubTLV
Address net.IP
}
// Tunnel Egress Endpoint Sub-TLV subfield positions
const (
EGRESS_ENDPOINT_RESERVED_POS = 0
EGRESS_ENDPOINT_FAMILY_POS = 4
EGRESS_ENDPOINT_ADDRESS_POS = 6
)
func (t *TunnelEncapSubTLVEgressEndpoint) DecodeFromBytes(data []byte) error {
value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
if err != nil {
return err
}
if t.Length < EGRESS_ENDPOINT_ADDRESS_POS {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Not all TunnelEncapSubTLVEgressEndpoint bytes available")
}
addressFamily := binary.BigEndian.Uint16(value[EGRESS_ENDPOINT_FAMILY_POS : EGRESS_ENDPOINT_FAMILY_POS+2])
var addressLen uint16
switch addressFamily {
case 0:
addressLen = 0
case AFI_IP:
addressLen = net.IPv4len
case AFI_IP6:
addressLen = net.IPv6len
default:
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Unsupported address family in TunnelEncapSubTLVEgressEndpoint")
}
if t.Length != EGRESS_ENDPOINT_ADDRESS_POS+addressLen {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Not all TunnelEncapSubTLVEgressEndpoint address bytes available")
}
t.Address = nil
if addressFamily != 0 {
t.Address = net.IP(value[EGRESS_ENDPOINT_ADDRESS_POS : EGRESS_ENDPOINT_ADDRESS_POS+addressLen])
}
return nil
}
func (t *TunnelEncapSubTLVEgressEndpoint) Serialize() ([]byte, error) {
var length uint32 = EGRESS_ENDPOINT_ADDRESS_POS
var family uint16
var ip net.IP
if t.Address == nil {
family = 0
} else if t.Address.To4() != nil {
length += net.IPv4len
family = AFI_IP
ip = t.Address.To4()
} else {
length += net.IPv6len
family = AFI_IP6
ip = t.Address.To16()
}
buf := make([]byte, length)
binary.BigEndian.PutUint32(buf, 0)
binary.BigEndian.PutUint16(buf[EGRESS_ENDPOINT_FAMILY_POS:], family)
if family != 0 {
copy(buf[EGRESS_ENDPOINT_ADDRESS_POS:], ip)
}
return t.TunnelEncapSubTLV.Serialize(buf)
}
func (t *TunnelEncapSubTLVEgressEndpoint) String() string {
address := ""
if t.Address != nil {
address = t.Address.String()
}
return fmt.Sprintf("{EgressEndpoint: %s}", address)
}
func (t *TunnelEncapSubTLVEgressEndpoint) MarshalJSON() ([]byte, error) {
address := ""
if t.Address != nil {
address = t.Address.String()
}
return json.Marshal(struct {
Type EncapSubTLVType `json:"type"`
Address string `json:"address"`
}{
Type: t.Type,
Address: address,
})
}
func NewTunnelEncapSubTLVEgressEndpoint(address string) *TunnelEncapSubTLVEgressEndpoint {
var ip net.IP = nil
if address != "" {
ip = net.ParseIP(address)
}
return &TunnelEncapSubTLVEgressEndpoint{
TunnelEncapSubTLV: TunnelEncapSubTLV{
Type: ENCAP_SUBTLV_TYPE_EGRESS_ENDPOINT,
},
Address: ip,
}
}
type TunnelEncapSubTLVUDPDestPort struct {
TunnelEncapSubTLV
UDPDestPort uint16
}
func (t *TunnelEncapSubTLVUDPDestPort) DecodeFromBytes(data []byte) error {
value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
if err != nil {
return err
}
if t.Length < 2 {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Not all TunnelEncapSubTLVUDPDestPort bytes available")
}
t.UDPDestPort = binary.BigEndian.Uint16(value[0:2])
return nil
}
func (t *TunnelEncapSubTLVUDPDestPort) Serialize() ([]byte, error) {
buf := make([]byte, 2)
binary.BigEndian.PutUint16(buf, t.UDPDestPort)
return t.TunnelEncapSubTLV.Serialize(buf)
}
func (t *TunnelEncapSubTLVUDPDestPort) String() string {
return fmt.Sprintf("{UDPDestPort: %d}", t.UDPDestPort)
}
func (t *TunnelEncapSubTLVUDPDestPort) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type EncapSubTLVType `json:"type"`
UDPDestPort uint16 `json:"port"`
}{
Type: t.Type,
UDPDestPort: t.UDPDestPort,
})
}
func NewTunnelEncapSubTLVUDPDestPort(port uint16) *TunnelEncapSubTLVUDPDestPort {
return &TunnelEncapSubTLVUDPDestPort{
TunnelEncapSubTLV: TunnelEncapSubTLV{
Type: ENCAP_SUBTLV_TYPE_UDP_DEST_PORT,
},
UDPDestPort: port,
}
}
type TunnelEncapTLV struct { type TunnelEncapTLV struct {
Type TunnelType Type TunnelType
Length uint16 Length uint16
@@ -11597,6 +12026,22 @@ func (t *TunnelEncapTLV) DecodeFromBytes(data []byte) error {
subTlv = &TunnelEncapSubTLVProtocol{} subTlv = &TunnelEncapSubTLVProtocol{}
case ENCAP_SUBTLV_TYPE_COLOR: case ENCAP_SUBTLV_TYPE_COLOR:
subTlv = &TunnelEncapSubTLVColor{} subTlv = &TunnelEncapSubTLVColor{}
case ENCAP_SUBTLV_TYPE_UDP_DEST_PORT:
subTlv = &TunnelEncapSubTLVUDPDestPort{}
case ENCAP_SUBTLV_TYPE_EGRESS_ENDPOINT:
subTlv = &TunnelEncapSubTLVEgressEndpoint{}
case ENCAP_SUBTLV_TYPE_SRPREFERENCE:
subTlv = &TunnelEncapSubTLVSRPreference{}
case ENCAP_SUBTLV_TYPE_SRBINDING_SID:
subTlv = &TunnelEncapSubTLVSRBSID{}
case ENCAP_SUBTLV_TYPE_SRSEGMENT_LIST:
subTlv = &TunnelEncapSubTLVSRSegmentList{}
case ENCAP_SUBTLV_TYPE_SRENLP:
subTlv = &TunnelEncapSubTLVSRENLP{}
case ENCAP_SUBTLV_TYPE_SRPRIORITY:
subTlv = &TunnelEncapSubTLVSRPriority{}
case ENCAP_SUBTLV_TYPE_SRCANDIDATE_PATH_NAME:
subTlv = &TunnelEncapSubTLVSRCandidatePathName{}
default: default:
subTlv = &TunnelEncapSubTLVUnknown{ subTlv = &TunnelEncapSubTLVUnknown{
TunnelEncapSubTLV: TunnelEncapSubTLV{ TunnelEncapSubTLV: TunnelEncapSubTLV{
@@ -12130,6 +12575,9 @@ func (p *PathAttributeAigp) DecodeFromBytes(data []byte, options ...*Marshalling
for len(value) > 3 { for len(value) > 3 {
typ := value[0] typ := value[0]
length := binary.BigEndian.Uint16(value[1:3]) length := binary.BigEndian.Uint16(value[1:3])
if length <= 3 {
return NewMessageError(BGP_ERROR_MESSAGE_HEADER_ERROR, BGP_ERROR_SUB_BAD_MESSAGE_LENGTH, nil, "Malformed BGP message")
}
if len(value) < int(length) { if len(value) < int(length) {
break break
} }
@@ -12756,7 +13204,7 @@ func (msg *BGPKeepAlive) Serialize(options ...*MarshallingOption) ([]byte, error
func NewBGPKeepAliveMessage() *BGPMessage { func NewBGPKeepAliveMessage() *BGPMessage {
return &BGPMessage{ return &BGPMessage{
Header: BGPHeader{Len: 19, Type: BGP_MSG_KEEPALIVE}, Header: BGPHeader{Len: BGP_HEADER_LENGTH, Type: BGP_MSG_KEEPALIVE},
Body: &BGPKeepAlive{}, Body: &BGPKeepAlive{},
} }
} }
@@ -12824,7 +13272,7 @@ func (msg *BGPHeader) DecodeFromBytes(data []byte, options ...*MarshallingOption
} }
func (msg *BGPHeader) Serialize(options ...*MarshallingOption) ([]byte, error) { func (msg *BGPHeader) Serialize(options ...*MarshallingOption) ([]byte, error) {
buf := make([]byte, 19) buf := make([]byte, BGP_HEADER_LENGTH)
for i := range buf[:16] { for i := range buf[:16] {
buf[i] = 0xff buf[i] = 0xff
} }
@@ -12873,7 +13321,7 @@ func ParseBGPMessage(data []byte, options ...*MarshallingOption) (*BGPMessage, e
return nil, NewMessageError(BGP_ERROR_MESSAGE_HEADER_ERROR, BGP_ERROR_SUB_BAD_MESSAGE_LENGTH, nil, "unknown message type") return nil, NewMessageError(BGP_ERROR_MESSAGE_HEADER_ERROR, BGP_ERROR_SUB_BAD_MESSAGE_LENGTH, nil, "unknown message type")
} }
return parseBody(h, data[19:h.Len], options...) return parseBody(h, data[BGP_HEADER_LENGTH:h.Len], options...)
} }
func ParseBGPBody(h *BGPHeader, data []byte, options ...*MarshallingOption) (*BGPMessage, error) { func ParseBGPBody(h *BGPHeader, data []byte, options ...*MarshallingOption) (*BGPMessage, error) {
@@ -12886,10 +13334,10 @@ func (msg *BGPMessage) Serialize(options ...*MarshallingOption) ([]byte, error)
return nil, err return nil, err
} }
if msg.Header.Len == 0 { if msg.Header.Len == 0 {
if 19+len(b) > BGP_MAX_MESSAGE_LENGTH { if BGP_HEADER_LENGTH+len(b) > BGP_MAX_MESSAGE_LENGTH {
return nil, NewMessageError(0, 0, nil, fmt.Sprintf("too long message length %d", 19+len(b))) return nil, NewMessageError(0, 0, nil, fmt.Sprintf("too long message length %d", BGP_HEADER_LENGTH+len(b)))
} }
msg.Header.Len = 19 + uint16(len(b)) msg.Header.Len = BGP_HEADER_LENGTH + uint16(len(b))
} }
h, err := msg.Header.Serialize(options...) h, err := msg.Header.Serialize(options...)
if err != nil { if err != nil {
@@ -13023,6 +13471,10 @@ func (e *ValidationExtended) Flat() map[string]string {
return map[string]string{} return map[string]string{}
} }
func (e *LinkBandwidthExtended) Flat() map[string]string {
return map[string]string{}
}
func (e *OpaqueExtended) Flat() map[string]string { func (e *OpaqueExtended) Flat() map[string]string {
return map[string]string{} return map[string]string{}
} }

View File

@@ -52,7 +52,7 @@ func (s *TLV) DecodeFromBytes(data []byte) ([]byte, error) {
p++ p++
s.Length = binary.BigEndian.Uint16(data[p : p+2]) s.Length = binary.BigEndian.Uint16(data[p : p+2])
if len(data) < s.Len() { if s.Len() < prefixSIDtlvHdrLen || len(data) < s.Len() {
return nil, malformedAttrListErr("decoding failed: Prefix SID TLV malformed") return nil, malformedAttrListErr("decoding failed: Prefix SID TLV malformed")
} }

View File

@@ -0,0 +1,967 @@
package bgp
import (
"encoding/binary"
"encoding/json"
"fmt"
"net"
"strconv"
api "github.com/osrg/gobgp/api"
)
type SRPolicyNLRI struct {
PrefixDefault
rf RouteFamily
Length uint8
Distinguisher uint32
Color uint32
Endpoint []byte
}
const (
// SRPolicyIPv4NLRILen defines IPv4 SR Policy NLRI portion length in bits
SRPolicyIPv4NLRILen = 96
// SRPolicyIPv6NLRILen defines IPv6 SR Policy NLRI portion length in bits
SRPolicyIPv6NLRILen = 192
)
func (s *SRPolicyNLRI) Flat() map[string]string {
return map[string]string{}
}
func (s *SRPolicyNLRI) decodeFromBytes(rf RouteFamily, data []byte, options ...*MarshallingOption) error {
if IsAddPathEnabled(true, rf, options) {
var err error
data, err = s.decodePathIdentifier(data)
if err != nil {
return err
}
}
switch data[0] {
case SRPolicyIPv4NLRILen:
s.rf = RF_SR_POLICY_IPv4
case SRPolicyIPv6NLRILen:
s.rf = RF_SR_POLICY_IPv6
default:
msg := fmt.Sprintf("Invalid length %d for SR Policy NLRI", len(data))
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
}
p := 0
s.Length = data[p] / 8
p++
s.Distinguisher = binary.BigEndian.Uint32(data[p : p+4])
p += 4
s.Color = binary.BigEndian.Uint32(data[p : p+4])
p += 4
s.Endpoint = data[p:]
return nil
}
func (s *SRPolicyNLRI) Serialize(options ...*MarshallingOption) ([]byte, error) {
buf := make([]byte, 1+s.Length)
p := 0
buf[0] = s.Length * 8
p++
binary.BigEndian.PutUint32(buf[p:p+4], s.Distinguisher)
p += 4
binary.BigEndian.PutUint32(buf[p:p+4], s.Color)
p += 4
copy(buf[p:], s.Endpoint)
if IsAddPathEnabled(false, s.rf, options) {
id, err := s.serializeIdentifier()
if err != nil {
return nil, err
}
return append(id, buf...), nil
}
return buf, nil
}
func (s *SRPolicyNLRI) AFI() uint16 {
afi, _ := RouteFamilyToAfiSafi(s.rf)
return afi
}
func (s *SRPolicyNLRI) SAFI() uint8 {
_, safi := RouteFamilyToAfiSafi(s.rf)
return safi
}
func (s *SRPolicyNLRI) Len(options ...*MarshallingOption) int {
buf, _ := s.Serialize(options...)
return len(buf)
}
func (s *SRPolicyNLRI) String() string {
afi, _ := RouteFamilyToAfiSafi(s.rf)
var endp string
switch afi {
case AFI_IP:
endp = net.IP(s.Endpoint).To4().String()
case AFI_IP6:
endp = net.IP(s.Endpoint).To16().String()
default:
endp = "[" + string(s.Endpoint) + "]"
}
return fmt.Sprintf("{ Length: %d (bytes), Distinguisher: %d, Color %d, Endpoint: %s }", s.Length, s.Distinguisher, s.Color, endp)
}
func (s *SRPolicyNLRI) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Length uint8 `json:"length"`
Distinguisher uint32 `json:"distinguisher"`
Color uint32 `json:"color"`
Endpoint string `json:"endpoint"`
}{
Length: s.Length,
Distinguisher: s.Distinguisher,
Color: s.Color,
Endpoint: string(s.Endpoint),
})
}
type SRPolicyIPv4 struct {
SRPolicyNLRI
}
func (s *SRPolicyIPv4) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
return s.decodeFromBytes(s.rf, data)
}
func NewSRPolicyIPv4(l uint32, d uint32, c uint32, ep []byte) *SRPolicyIPv4 {
return &SRPolicyIPv4{
SRPolicyNLRI: SRPolicyNLRI{
rf: RF_SR_POLICY_IPv4,
Length: uint8(l / 8),
Distinguisher: d,
Color: c,
Endpoint: ep,
},
}
}
type SRPolicyIPv6 struct {
SRPolicyNLRI
}
func (s *SRPolicyIPv6) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
return s.decodeFromBytes(s.rf, data)
}
func NewSRPolicyIPv6(l uint32, d uint32, c uint32, ep []byte) *SRPolicyIPv6 {
return &SRPolicyIPv6{
SRPolicyNLRI: SRPolicyNLRI{
rf: RF_SR_POLICY_IPv6,
Length: uint8(l / 8),
Distinguisher: d,
Color: c,
Endpoint: ep,
},
}
}
type TunnelEncapSubTLVSRPreference struct {
TunnelEncapSubTLV
Flags uint8
Preference uint32
}
func (t *TunnelEncapSubTLVSRPreference) DecodeFromBytes(data []byte) error {
value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
if err != nil {
return err
}
// Second byte carries the length of SR Preference SubTLV
if t.Length != 6 {
msg := fmt.Sprintf("Invalid TunnelEncapSubTLVSRPreference length: %d", t.Length)
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
}
t.Flags = value[0]
t.Preference = binary.BigEndian.Uint32(value[2:6])
return nil
}
func (t *TunnelEncapSubTLVSRPreference) Serialize() ([]byte, error) {
buf := make([]byte, 6)
buf[0] = t.Flags
binary.BigEndian.PutUint32(buf[2:6], t.Preference)
return t.TunnelEncapSubTLV.Serialize(buf[:])
}
func (t *TunnelEncapSubTLVSRPreference) String() string {
return fmt.Sprintf("{Flags: 0x%02x, Preference: %d}", t.Flags, t.Preference)
}
func (t *TunnelEncapSubTLVSRPreference) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type EncapSubTLVType `json:"type"`
Flags uint8 `json:"flags"`
Preference uint32 `json:"preference"`
}{
Type: t.Type,
Flags: t.Flags,
Preference: t.Preference,
})
}
func NewTunnelEncapSubTLVSRPreference(flags uint32, preference uint32) *TunnelEncapSubTLVSRPreference {
return &TunnelEncapSubTLVSRPreference{
TunnelEncapSubTLV: TunnelEncapSubTLV{
Type: ENCAP_SUBTLV_TYPE_SRPREFERENCE,
Length: 6,
},
Flags: uint8(flags),
Preference: preference,
}
}
type TunnelEncapSubTLVSRPriority struct {
TunnelEncapSubTLV
Priority uint8
}
func (t *TunnelEncapSubTLVSRPriority) DecodeFromBytes(data []byte) error {
value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
if err != nil {
return err
}
// Second byte carries the length of SR Preference SubTLV
if t.Length != 2 {
msg := fmt.Sprintf("Invalid TunnelEncapSubTLVSRPriority length: %d", t.Length)
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
}
t.Priority = value[0]
return nil
}
func (t *TunnelEncapSubTLVSRPriority) Serialize() ([]byte, error) {
buf := make([]byte, 1+1)
buf[0] = t.Priority
return t.TunnelEncapSubTLV.Serialize(buf[:])
}
func (t *TunnelEncapSubTLVSRPriority) String() string {
return fmt.Sprintf("{Priority: %d}", t.Priority)
}
func (t *TunnelEncapSubTLVSRPriority) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type EncapSubTLVType `json:"type"`
Priority uint8 `json:"priority"`
}{
Type: t.Type,
Priority: t.Priority,
})
}
func NewTunnelEncapSubTLVSRPriority(priority uint8) *TunnelEncapSubTLVSRPriority {
return &TunnelEncapSubTLVSRPriority{
TunnelEncapSubTLV: TunnelEncapSubTLV{
Type: ENCAP_SUBTLV_TYPE_SRPRIORITY,
Length: 2,
},
Priority: priority,
}
}
type TunnelEncapSubTLVSRCandidatePathName struct {
TunnelEncapSubTLV
CandidatePathName string
}
func (t *TunnelEncapSubTLVSRCandidatePathName) DecodeFromBytes(data []byte) error {
value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
if err != nil {
return err
}
// Skip Reserved byte
t.CandidatePathName = string(value[1:t.TunnelEncapSubTLV.Len()])
return nil
}
func (t *TunnelEncapSubTLVSRCandidatePathName) Serialize() ([]byte, error) {
buf := make([]byte, 1+len(t.CandidatePathName))
copy(buf[1:], t.CandidatePathName)
return t.TunnelEncapSubTLV.Serialize(buf[:])
}
func (t *TunnelEncapSubTLVSRCandidatePathName) String() string {
return fmt.Sprintf("{Candidate Path Name: %s}", t.CandidatePathName)
}
func (t *TunnelEncapSubTLVSRCandidatePathName) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type EncapSubTLVType `json:"type"`
CandidatePathName string `json:"candidate_path_name"`
}{
Type: t.Type,
CandidatePathName: t.CandidatePathName,
})
}
func NewTunnelEncapSubTLVSRCandidatePathName(cpn string) *TunnelEncapSubTLVSRCandidatePathName {
return &TunnelEncapSubTLVSRCandidatePathName{
TunnelEncapSubTLV: TunnelEncapSubTLV{
Type: ENCAP_SUBTLV_TYPE_SRCANDIDATE_PATH_NAME,
Length: uint16(len(cpn) + 1), // length of Candidate Path name string + 1 Reserved byte
},
CandidatePathName: cpn,
}
}
type SRENLPValue uint8
const (
// ENLPType1 Indicates to push an IPv4 Explicit NULL label on an unlabeled IPv4
// packet, but do not push an IPv6 Explicit NULL label on an
// unlabeled IPv6 packet.
ENLPType1 SRENLPValue = 1
// ENLPType2 Indicates to push an IPv6 Explicit NULL label on an unlabeled IPv6
// packet, but do not push an IPv4 Explicit NULL label on an
// unlabeled IPv4 packet.
ENLPType2 SRENLPValue = 2
// ENLPType3 Indicates to push an IPv4 Explicit NULL label on an unlabeled IPv4
// packet, and push an IPv6 Explicit NULL label on an unlabeled
// IPv6 packet.
ENLPType3 SRENLPValue = 3
// ENLPType4 Indicates to not push an Explicit NULL label.
ENLPType4 SRENLPValue = 4
)
type TunnelEncapSubTLVSRENLP struct {
TunnelEncapSubTLV
Flags uint8
ENLP SRENLPValue
}
func (t *TunnelEncapSubTLVSRENLP) DecodeFromBytes(data []byte) error {
value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
if err != nil {
return err
}
// Second byte carries the length of SR Preference SubTLV
if t.Length != 3 {
msg := fmt.Sprintf("Invalid TunnelEncapSubTLVSRENLP length: %d", t.Length)
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
}
t.Flags = value[0]
switch SRENLPValue(value[2]) {
case ENLPType1:
case ENLPType2:
case ENLPType3:
case ENLPType4:
default:
msg := fmt.Sprintf("Invalid ENLP Type: %d", value[2])
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
}
t.ENLP = SRENLPValue(value[2])
return nil
}
func (t *TunnelEncapSubTLVSRENLP) Serialize() ([]byte, error) {
buf := make([]byte, t.Length)
buf[0] = t.Flags
buf[2] = byte(t.ENLP)
return t.TunnelEncapSubTLV.Serialize(buf[:])
}
func (t *TunnelEncapSubTLVSRENLP) String() string {
return fmt.Sprintf("{Flags: 0x%02x, ENLP Type: %d}", t.Flags, t.ENLP)
}
func (t *TunnelEncapSubTLVSRENLP) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type EncapSubTLVType `json:"type"`
Flags uint8 `json:"flags"`
ENLP uint8 `json:"enlp"`
}{
Type: t.Type,
Flags: t.Flags,
ENLP: uint8(t.ENLP),
})
}
func NewTunnelEncapSubTLVSRENLP(flags uint32, enlp SRENLPValue) *TunnelEncapSubTLVSRENLP {
return &TunnelEncapSubTLVSRENLP{
TunnelEncapSubTLV: TunnelEncapSubTLV{
Type: ENCAP_SUBTLV_TYPE_SRENLP,
Length: 3,
},
Flags: uint8(flags),
ENLP: enlp,
}
}
type BSID struct {
Value []byte
}
func (b *BSID) String() string {
switch len(b.Value) {
case 0:
return "n/a"
case 4:
bsid := binary.BigEndian.Uint32(b.Value)
bsid >>= 12
return strconv.Itoa(int(bsid))
case 16:
return net.IP(b.Value).To16().String()
default:
return "invalid"
}
}
func (b *BSID) Serialize() []byte {
return b.Value
}
func (b *BSID) Len() int {
return len(b.Value)
}
func NewBSID(v []byte) (*BSID, error) {
var bsid *BSID
switch len(v) {
case 0:
case 4:
t := binary.BigEndian.Uint32(v)
t <<= 12
bsid = &BSID{
Value: make([]byte, len(v)),
}
binary.BigEndian.PutUint32(bsid.Value, t)
case 16:
bsid = &BSID{
Value: make([]byte, len(v)),
}
copy(bsid.Value, v)
default:
return nil, fmt.Errorf("invalid length %d", len(v))
}
return bsid, nil
}
type TunnelEncapSubTLVSRBSID struct {
TunnelEncapSubTLV
Flags uint8
BSID *BSID
}
func (t *TunnelEncapSubTLVSRBSID) DecodeFromBytes(data []byte) error {
value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
if err != nil {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
}
// Check Sub TLV length, only 3 possible length are allowed
switch t.Length {
case 2: // No BSID, do not initializing BSID struct
case 6:
fallthrough
case 18:
t.BSID = &BSID{
Value: make([]byte, t.Length-2),
}
copy(t.BSID.Value, value[2:t.Length])
default:
msg := fmt.Sprintf("Invalid TunnelEncapSubTLVSRBSID length: %d", t.Length)
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
}
t.Flags = value[0]
return nil
}
func (t *TunnelEncapSubTLVSRBSID) Serialize() ([]byte, error) {
l := 2
if t.BSID != nil {
l += t.BSID.Len()
}
buf := make([]byte, l) // 1st byte Flags, 2nd byte Reserved, 3rd+ BSID
buf[0] = t.Flags
if t.BSID != nil {
bsid := t.BSID.Serialize()
copy(buf[2:], bsid)
}
return t.TunnelEncapSubTLV.Serialize(buf[:])
}
func (t *TunnelEncapSubTLVSRBSID) String() string {
return fmt.Sprintf("{S-Flag: %t, I-Flag: %t, BSID: %s}", t.Flags&0x80 == 0x80, t.Flags&0x40 == 0x40, t.BSID.String())
}
func (t *TunnelEncapSubTLVSRBSID) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type EncapSubTLVType `json:"type"`
Flags uint8 `json:"flags"`
BSID string `json:"binding_sid,omitempty"`
}{
Type: t.Type,
Flags: t.Flags,
BSID: t.BSID.String(),
})
}
type TunnelEncapSubTLVSRv6BSID struct {
TunnelEncapSubTLV
Flags uint8
BSID *BSID
EPBAS *SRv6EndpointBehaviorStructure
}
func (t *TunnelEncapSubTLVSRv6BSID) DecodeFromBytes(data []byte) error {
value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
if err != nil {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
}
t.Flags = value[0]
t.BSID, err = NewBSID(value[2:t.Length])
if err != nil {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
}
return nil
}
func (t *TunnelEncapSubTLVSRv6BSID) Serialize() ([]byte, error) {
buf := make([]byte, t.Length)
buf[0] = t.Flags
copy(buf[2:t.BSID.Len()], t.BSID.Serialize())
return t.TunnelEncapSubTLV.Serialize(buf[:])
}
func (t *TunnelEncapSubTLVSRv6BSID) String() string {
return fmt.Sprintf("{S-Flag: %t, I-Flag: %t, B-Flag: %t, BSID: %s}", t.Flags&0x80 == 0x80, t.Flags&0x40 == 0x40, t.Flags&0x20 == 0x20, t.BSID.String())
}
func (t *TunnelEncapSubTLVSRv6BSID) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type EncapSubTLVType `json:"type"`
Flags uint8 `json:"flags"`
BSID string `json:"binding_sid,omitempty"`
}{
Type: t.Type,
Flags: t.Flags,
BSID: t.BSID.String(),
})
}
// SegmentType defines a type of Segment in Segment List
type SegmentType int
const (
// TypeA Segment Sub-TLV encodes a single SR-MPLS SID
TypeA SegmentType = 1
// TypeB Segment Sub-TLV encodes a single SRv6 SID.
TypeB SegmentType = 13
// TypeC Segment Sub-TLV encodes an IPv4 node address, SR Algorithm
// and an optional SR-MPLS SID
TypeC SegmentType = 3
// TypeD Segment Sub-TLV encodes an IPv6 node address, SR Algorithm
// and an optional SR-MPLS SID.
TypeD SegmentType = 4
// TypeE Segment Sub-TLV encodes an IPv4 node address, a local
// interface Identifier (Local Interface ID) and an optional SR-MPLS
// SID.
TypeE SegmentType = 5
// TypeF Segment Sub-TLV encodes an adjacency local address, an
// adjacency remote address and an optional SR-MPLS SID.
TypeF SegmentType = 6
// TypeG Segment Sub-TLV encodes an IPv6 Link Local adjacency with
// IPv6 local node address, a local interface identifier (Local
// Interface ID), IPv6 remote node address , a remote interface
// identifier (Remote Interface ID) and an optional SR-MPLS SID.
TypeG SegmentType = 7
// TypeH Segment Sub-TLV encodes an adjacency local address, an
// adjacency remote address and an optional SR-MPLS SID.
TypeH SegmentType = 8
// TypeI Segment Sub-TLV encodes an IPv6 node address, SR Algorithm
// and an optional SRv6 SID.
TypeI SegmentType = 14
// TypeJ Segment Sub-TLV encodes an IPv6 Link Local adjacency with
// local node address, a local interface identifier (Local Interface
// ID), remote IPv6 node address, a remote interface identifier (Remote
// Interface ID) and an optional SRv6 SID.
TypeJ SegmentType = 15
// TypeK Segment Sub-TLV encodes an adjacency local address, an
// adjacency remote address and an optional SRv6 SID.
TypeK SegmentType = 16
)
// Weight sub-TLV specifies the weight associated to a given segment list.
type SegmentListWeight struct {
TunnelEncapSubTLV
Flags uint8
Weight uint32
}
func (s *SegmentListWeight) DecodeFromBytes(data []byte) error {
value, err := s.TunnelEncapSubTLV.DecodeFromBytes(data)
if err != nil {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
}
s.Flags = value[0]
s.Weight = binary.BigEndian.Uint32(value[2:6])
return nil
}
func (s *SegmentListWeight) Serialize() ([]byte, error) {
buf := make([]byte, 6)
buf[0] = s.Flags
binary.BigEndian.PutUint32(buf[2:6], s.Weight)
return s.TunnelEncapSubTLV.Serialize(buf)
}
func (s *SegmentListWeight) String() string {
return fmt.Sprintf("{Flags: 0x%02x, Weight: %d}", s.Flags, s.Weight)
}
func (s *SegmentListWeight) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type EncapSubTLVType `json:"type"`
Flags uint8 `json:"flags"`
Weight uint32 `json:"weight,omitempty"`
}{
Type: s.Type,
Flags: s.Flags,
Weight: s.Weight,
})
}
type SegmentTypeA struct {
TunnelEncapSubTLV
Flags uint8
Label uint32
}
func (s *SegmentTypeA) DecodeFromBytes(data []byte) error {
value, err := s.TunnelEncapSubTLV.DecodeFromBytes(data)
if err != nil {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
}
s.Flags = value[0]
s.Label = binary.BigEndian.Uint32(value[2:6])
return nil
}
func (s *SegmentTypeA) Serialize() ([]byte, error) {
buf := make([]byte, 6)
buf[0] = s.Flags
binary.BigEndian.PutUint32(buf[2:6], s.Label)
return s.TunnelEncapSubTLV.Serialize(buf)
}
func (s *SegmentTypeA) String() string {
return fmt.Sprintf("{V-flag: %t, A-flag:, %t S-flag: %t, B-flag: %t, Label: %d TC: %d S: %t TTL: %d}",
s.Flags&0x80 == 0x80, s.Flags&0x40 == 0x40, s.Flags&0x20 == 0x20, s.Flags&0x10 == 0x10,
s.Label>>12, s.Label&0x00000e00>>9, s.Label&0x00000100 == 0x00000100, s.Label&0x000000ff)
}
func (s *SegmentTypeA) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type EncapSubTLVType `json:"type"`
VFlag bool `json:"v_flag"`
AFlag bool `json:"a_flag"`
SFlag bool `json:"s_flag"`
BFlag bool `json:"b_flag"`
Label uint32 `json:"label"`
TC uint8 `json:"tc"`
S bool `json:"s"`
TTL uint8 `json:"ttl"`
}{
Type: s.Type,
VFlag: s.Flags&0x80 == 0x80,
AFlag: s.Flags&0x40 == 0x40,
SFlag: s.Flags&0x20 == 0x20,
BFlag: s.Flags&0x10 == 0x10,
Label: s.Label >> 12,
TC: uint8(s.Label & 0x00000e00 >> 9),
S: s.Label&0x00000100 == 0x00000100,
TTL: uint8(s.Label & 0x000000ff),
})
}
type SRBehavior int32
const (
RESERVED SRBehavior = SRBehavior(api.SRv6Behavior_RESERVED)
END SRBehavior = SRBehavior(api.SRv6Behavior_END)
END_WITH_PSP SRBehavior = SRBehavior(api.SRv6Behavior_END_WITH_PSP)
END_WITH_USP SRBehavior = SRBehavior(api.SRv6Behavior_END_WITH_USP)
END_WITH_PSP_USP SRBehavior = SRBehavior(api.SRv6Behavior_END_WITH_PSP_USP)
ENDX SRBehavior = SRBehavior(api.SRv6Behavior_ENDX)
ENDX_WITH_PSP SRBehavior = SRBehavior(api.SRv6Behavior_ENDX_WITH_PSP)
ENDX_WITH_USP SRBehavior = SRBehavior(api.SRv6Behavior_ENDX_WITH_USP)
ENDX_WITH_PSP_USP SRBehavior = SRBehavior(api.SRv6Behavior_ENDX_WITH_PSP_USP)
ENDT SRBehavior = SRBehavior(api.SRv6Behavior_ENDT)
ENDT_WITH_PSP SRBehavior = SRBehavior(api.SRv6Behavior_ENDT_WITH_PSP)
ENDT_WITH_USP SRBehavior = SRBehavior(api.SRv6Behavior_ENDT_WITH_USP)
ENDT_WITH_PSP_USP SRBehavior = SRBehavior(api.SRv6Behavior_ENDT_WITH_PSP_USP)
END_B6_ENCAPS SRBehavior = SRBehavior(api.SRv6Behavior_END_B6_ENCAPS)
END_BM SRBehavior = SRBehavior(api.SRv6Behavior_END_BM)
END_DX6 SRBehavior = SRBehavior(api.SRv6Behavior_END_DX6)
END_DX4 SRBehavior = SRBehavior(api.SRv6Behavior_END_DX4)
END_DT6 SRBehavior = SRBehavior(api.SRv6Behavior_END_DT6)
END_DT4 SRBehavior = SRBehavior(api.SRv6Behavior_END_DT4)
END_DT46 SRBehavior = SRBehavior(api.SRv6Behavior_END_DT46)
END_DX2 SRBehavior = SRBehavior(api.SRv6Behavior_END_DX2)
END_DX2V SRBehavior = SRBehavior(api.SRv6Behavior_END_DX2V)
END_DT2U SRBehavior = SRBehavior(api.SRv6Behavior_RESERVED)
END_DT2M SRBehavior = SRBehavior(api.SRv6Behavior_END_DT2M)
END_B6_ENCAPS_Red SRBehavior = SRBehavior(api.SRv6Behavior_END_B6_ENCAPS_Red)
END_WITH_USD SRBehavior = SRBehavior(api.SRv6Behavior_END_WITH_USD)
END_WITH_PSP_USD SRBehavior = SRBehavior(api.SRv6Behavior_END_WITH_PSP_USD)
END_WITH_USP_USD SRBehavior = SRBehavior(api.SRv6Behavior_END_WITH_USP_USD)
END_WITH_PSP_USP_USD SRBehavior = SRBehavior(api.SRv6Behavior_END_WITH_PSP_USP_USD)
ENDX_WITH_USD SRBehavior = SRBehavior(api.SRv6Behavior_ENDX_WITH_USD)
ENDX_WITH_PSP_USD SRBehavior = SRBehavior(api.SRv6Behavior_ENDX_WITH_PSP_USD)
ENDX_WITH_USP_USD SRBehavior = SRBehavior(api.SRv6Behavior_ENDX_WITH_USP_USD)
ENDX_WITH_PSP_USP_USD SRBehavior = SRBehavior(api.SRv6Behavior_ENDX_WITH_PSP_USP_USD)
ENDT_WITH_USD SRBehavior = SRBehavior(api.SRv6Behavior_ENDT_WITH_USD)
ENDT_WITH_PSP_USD SRBehavior = SRBehavior(api.SRv6Behavior_ENDT_WITH_PSP_USD)
ENDT_WITH_USP_USD SRBehavior = SRBehavior(api.SRv6Behavior_ENDT_WITH_USP_USD)
ENDT_WITH_PSP_USP_USD SRBehavior = SRBehavior(api.SRv6Behavior_ENDT_WITH_PSP_USP_USD)
)
type SRv6EndpointBehaviorStructure struct {
Behavior SRBehavior
BlockLen uint8
NodeLen uint8
FuncLen uint8
ArgLen uint8
}
func (s *SRv6EndpointBehaviorStructure) DecodeFromBytes(data []byte) error {
if len(data) < 8 {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Malformed BGP message")
}
behavior := binary.BigEndian.Uint16(data[0:2])
s.Behavior = SRBehavior(behavior)
s.BlockLen = data[4]
s.NodeLen = data[5]
s.FuncLen = data[6]
s.ArgLen = data[7]
return nil
}
func (s *SRv6EndpointBehaviorStructure) Serialize() ([]byte, error) {
buf := make([]byte, 8)
binary.BigEndian.PutUint16(buf[0:2], uint16(s.Behavior))
buf[4] = s.BlockLen
buf[5] = s.NodeLen
buf[6] = s.FuncLen
buf[7] = s.ArgLen
return buf, nil
}
func (s *SRv6EndpointBehaviorStructure) String() string {
return fmt.Sprintf("{Behavior: %s, BlockLen: %d, NodeLen: %d, FuncLen: %d, ArgLen: %d}",
api.SRv6Behavior(s.Behavior).String(), s.BlockLen, s.NodeLen, s.FuncLen, s.ArgLen)
}
func (s *SRv6EndpointBehaviorStructure) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Behavior SRBehavior `json:"behavior"`
BlockLen uint8 `json:"block_Len"`
NodeLen uint8 `json:"node_len"`
FuncLen uint8 `json:"func_len"`
ArgLen uint8 `json:"arg_len"`
}{
Behavior: s.Behavior,
BlockLen: s.BlockLen,
NodeLen: s.NodeLen,
FuncLen: s.FuncLen,
ArgLen: s.ArgLen,
})
}
type SegmentTypeB struct {
TunnelEncapSubTLV
Flags uint8
SID []byte
SRv6EBS *SRv6EndpointBehaviorStructure
}
func (s *SegmentTypeB) DecodeFromBytes(data []byte) error {
value, err := s.TunnelEncapSubTLV.DecodeFromBytes(data)
if err != nil {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
}
if len(value) < 18 {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Malformed BGP message")
}
s.Flags = value[0]
s.SID = value[2:18]
if len(value) == 26 {
s.SRv6EBS = &SRv6EndpointBehaviorStructure{}
err = s.SRv6EBS.DecodeFromBytes(value[18:])
if err != nil {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
}
}
return nil
}
func (s *SegmentTypeB) Serialize() ([]byte, error) {
buf := make([]byte, 18)
buf[0] = s.Flags
copy(buf[2:], s.SID)
if s.SRv6EBS != nil {
if ebs, _ := s.SRv6EBS.Serialize(); ebs != nil {
buf = append(buf, ebs...)
}
}
return s.TunnelEncapSubTLV.Serialize(buf)
}
func (s *SegmentTypeB) String() string {
if s.SRv6EBS == nil {
return fmt.Sprintf("{V-flag: %t, A-flag:, %t S-flag: %t, B-flag: %t, Sid: %s}",
s.Flags&0x80 == 0x80, s.Flags&0x40 == 0x40, s.Flags&0x20 == 0x20, s.Flags&0x10 == 0x10, net.IP(s.SID).To16().String())
} else {
return fmt.Sprintf("{V-flag: %t, A-flag:, %t S-flag: %t, B-flag: %t, Sid: %s, Ebs: %s}",
s.Flags&0x80 == 0x80, s.Flags&0x40 == 0x40, s.Flags&0x20 == 0x20, s.Flags&0x10 == 0x10, net.IP(s.SID).To16().String(),
s.SRv6EBS.String())
}
}
func (s *SegmentTypeB) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type EncapSubTLVType `json:"type"`
VFlag bool `json:"v_flag"`
AFlag bool `json:"a_flag"`
SFlag bool `json:"s_flag"`
BFlag bool `json:"b_flag"`
Sid string `json:"sid"`
SRv6EBS *SRv6EndpointBehaviorStructure `json:"endpointBehaviorStructure"`
}{
Type: s.Type,
VFlag: s.Flags&0x80 == 0x80,
AFlag: s.Flags&0x40 == 0x40,
SFlag: s.Flags&0x20 == 0x20,
BFlag: s.Flags&0x10 == 0x10,
Sid: net.IP(s.SID).To16().String(),
SRv6EBS: s.SRv6EBS,
})
}
const (
// SegmentListSubTLVWeight defines code for Segment List's Weight sub-TLV
SegmentListSubTLVWeight = 9
)
type TunnelEncapSubTLVSRSegmentList struct {
TunnelEncapSubTLV
Weight *SegmentListWeight
Segments []TunnelEncapSubTLVInterface
}
func (t *TunnelEncapSubTLVSRSegmentList) DecodeFromBytes(data []byte) error {
value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
if err != nil {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
}
if len(value) < 1 {
return NewMessageError(BGP_ERROR_MESSAGE_HEADER_ERROR, BGP_ERROR_SUB_BAD_MESSAGE_LENGTH, nil, "Malformed BGP message")
}
// Skip reserved byte to access inner SubTLV type
value = value[1:]
var segments []TunnelEncapSubTLVInterface
p := 0
for p < t.TunnelEncapSubTLV.Len()-4 {
var segment TunnelEncapSubTLVInterface
switch SegmentType(value[0]) {
case SegmentListSubTLVWeight:
t.Weight = &SegmentListWeight{}
if err := t.Weight.DecodeFromBytes(value); err != nil {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
}
p += t.Weight.TunnelEncapSubTLV.Len()
value = value[t.Weight.TunnelEncapSubTLV.Len():]
continue
case TypeA:
segment = &SegmentTypeA{}
if err := segment.DecodeFromBytes(value); err != nil {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
}
case TypeB:
segment = &SegmentTypeB{}
if err := segment.DecodeFromBytes(value); err != nil {
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
}
case TypeC:
fallthrough
case TypeD:
fallthrough
case TypeE:
fallthrough
case TypeF:
fallthrough
case TypeG:
fallthrough
case TypeH:
fallthrough
case TypeI:
fallthrough
case TypeJ:
fallthrough
case TypeK:
msg := fmt.Sprintf("Invalid SR Policy Segment SubTLV %d is not yet supported", value[0])
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
default:
msg := fmt.Sprintf("Invalid SR Policy Segment List SubTLV %d", value[0])
return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
}
segments = append(segments, segment)
p += segment.Len()
value = value[segment.Len():]
}
if len(segments) == 0 {
t.Segments = nil
} else {
t.Segments = segments
}
return nil
}
func (t *TunnelEncapSubTLVSRSegmentList) Serialize() ([]byte, error) {
buf := make([]byte, 0)
// Add reserved byte
buf = append(buf, 0x0)
if t.Weight != nil {
wbuf, err := t.Weight.Serialize()
if err != nil {
return nil, err
}
buf = append(buf, wbuf...)
}
for _, s := range t.Segments {
sbuf, err := s.Serialize()
if err != nil {
return nil, err
}
buf = append(buf, sbuf...)
}
return t.TunnelEncapSubTLV.Serialize(buf[:])
}
func (t *TunnelEncapSubTLVSRSegmentList) String() string {
msg := "{"
if t.Weight != nil {
msg += "Weight: " + t.Weight.String() + ","
}
msg += "Segment List: [ "
for _, s := range t.Segments {
msg += s.String() + ","
}
msg += " ] }"
return msg
}
func (t *TunnelEncapSubTLVSRSegmentList) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type EncapSubTLVType `json:"type"`
Weight *SegmentListWeight
Segments []TunnelEncapSubTLVInterface
}{
Type: t.Type,
Weight: t.Weight,
Segments: t.Segments,
})
}

View File

@@ -313,7 +313,7 @@ func ValidateBGPMessage(m *BGPMessage) error {
return nil return nil
} }
func ValidateOpenMsg(m *BGPOpen, expectedAS uint32) (uint32, error) { func ValidateOpenMsg(m *BGPOpen, expectedAS uint32, myAS uint32, myId net.IP) (uint32, error) {
if m.Version != 4 { if m.Version != 4 {
return 0, NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_VERSION_NUMBER, nil, fmt.Sprintf("unsupported version %d", m.Version)) return 0, NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_VERSION_NUMBER, nil, fmt.Sprintf("unsupported version %d", m.Version))
} }
@@ -331,6 +331,20 @@ func ValidateOpenMsg(m *BGPOpen, expectedAS uint32) (uint32, error) {
} }
} }
} }
// rfc6286 (Autonomous-System-Wide Unique BGP Identifier for BGP-4)
// If the BGP Identifier field of the OPEN message is zero, or if it
// is the same as the BGP Identifier of the local BGP speaker and the
// message is from an internal peer, then the Error Subcode is set to
// "Bad BGP Identifier".
routerId := m.ID
if routerId.IsUnspecified() {
return 0, NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_BAD_BGP_IDENTIFIER, nil, fmt.Sprintf("bad BGP identifier %s (0.0.0.0)", routerId.String()))
}
if as == myAS && routerId.Equal(myId) {
return 0, NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_BAD_BGP_IDENTIFIER, nil, fmt.Sprintf("bad BGP identifier %s", routerId.String()))
}
if expectedAS != 0 && as != expectedAS { if expectedAS != 0 && as != expectedAS {
return 0, NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_BAD_PEER_AS, nil, fmt.Sprintf("as number mismatch expected %d, received %d", expectedAS, as)) return 0, NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_BAD_PEER_AS, nil, fmt.Sprintf("as number mismatch expected %d, received %d", expectedAS, as))
} }

View File

@@ -164,12 +164,11 @@ func NewBMPRouteMonitoring(p BMPPeerHeader, update *bgp.BGPMessage) *BMPMessage
} }
func (body *BMPRouteMonitoring) ParseBody(msg *BMPMessage, data []byte) error { func (body *BMPRouteMonitoring) ParseBody(msg *BMPMessage, data []byte) error {
update, err := bgp.ParseBGPMessage(data) var err error
if err != nil {
body.BGPUpdate, err = bgp.ParseBGPMessage(data)
return err return err
}
body.BGPUpdate = update
return nil
} }
func (body *BMPRouteMonitoring) Serialize() ([]byte, error) { func (body *BMPRouteMonitoring) Serialize() ([]byte, error) {
@@ -225,7 +224,7 @@ func (s *BMPStatsTLV32) ParseValue(data []byte) error {
if s.Length != 4 { if s.Length != 4 {
return fmt.Errorf("invalid length: %d bytes (%d bytes expected)", s.Length, 4) return fmt.Errorf("invalid length: %d bytes (%d bytes expected)", s.Length, 4)
} }
s.Value = binary.BigEndian.Uint32(data[:8]) s.Value = binary.BigEndian.Uint32(data[:4])
return nil return nil
} }
@@ -1065,8 +1064,13 @@ func ParseBMPMessage(data []byte) (msg *BMPMessage, err error) {
err = msg.Body.ParseBody(msg, data) err = msg.Body.ParseBody(msg, data)
if err != nil { if err != nil {
if msg.Header.Type == BMP_MSG_ROUTE_MONITORING {
return msg, err
}
return nil, err return nil, err
} }
return msg, nil return msg, nil
} }

View File

@@ -115,17 +115,17 @@ func (b *bmpClient) loop() {
} }
if func() bool { if func() bool {
ops := []watchOption{watchPeerState(true)} ops := []watchOption{watchPeerState(true, false)}
if b.c.RouteMonitoringPolicy == config.BMP_ROUTE_MONITORING_POLICY_TYPE_BOTH { if b.c.RouteMonitoringPolicy == config.BMP_ROUTE_MONITORING_POLICY_TYPE_BOTH {
log.WithFields( log.WithFields(
log.Fields{"Topic": "bmp"}, log.Fields{"Topic": "bmp"},
).Warn("both option for route-monitoring-policy is obsoleted") ).Warn("both option for route-monitoring-policy is obsoleted")
} }
if b.c.RouteMonitoringPolicy == config.BMP_ROUTE_MONITORING_POLICY_TYPE_PRE_POLICY || b.c.RouteMonitoringPolicy == config.BMP_ROUTE_MONITORING_POLICY_TYPE_ALL { if b.c.RouteMonitoringPolicy == config.BMP_ROUTE_MONITORING_POLICY_TYPE_PRE_POLICY || b.c.RouteMonitoringPolicy == config.BMP_ROUTE_MONITORING_POLICY_TYPE_ALL {
ops = append(ops, watchUpdate(true)) ops = append(ops, watchUpdate(true, ""))
} }
if b.c.RouteMonitoringPolicy == config.BMP_ROUTE_MONITORING_POLICY_TYPE_POST_POLICY || b.c.RouteMonitoringPolicy == config.BMP_ROUTE_MONITORING_POLICY_TYPE_ALL { if b.c.RouteMonitoringPolicy == config.BMP_ROUTE_MONITORING_POLICY_TYPE_POST_POLICY || b.c.RouteMonitoringPolicy == config.BMP_ROUTE_MONITORING_POLICY_TYPE_ALL {
ops = append(ops, watchPostUpdate(true)) ops = append(ops, watchPostUpdate(true, ""))
} }
if b.c.RouteMonitoringPolicy == config.BMP_ROUTE_MONITORING_POLICY_TYPE_LOCAL_RIB || b.c.RouteMonitoringPolicy == config.BMP_ROUTE_MONITORING_POLICY_TYPE_ALL { if b.c.RouteMonitoringPolicy == config.BMP_ROUTE_MONITORING_POLICY_TYPE_LOCAL_RIB || b.c.RouteMonitoringPolicy == config.BMP_ROUTE_MONITORING_POLICY_TYPE_ALL {
ops = append(ops, watchBestPath(true)) ops = append(ops, watchBestPath(true))

View File

@@ -21,6 +21,7 @@ import (
"io" "io"
"math/rand" "math/rand"
"net" "net"
"os"
"strconv" "strconv"
"sync" "sync"
"syscall" "syscall"
@@ -714,8 +715,11 @@ func capAddPathFromConfig(pConf *config.Neighbor) bgp.ParameterCapabilityInterfa
} }
func capabilitiesFromConfig(pConf *config.Neighbor) []bgp.ParameterCapabilityInterface { func capabilitiesFromConfig(pConf *config.Neighbor) []bgp.ParameterCapabilityInterface {
fqdn, _ := os.Hostname()
caps := make([]bgp.ParameterCapabilityInterface, 0, 4) caps := make([]bgp.ParameterCapabilityInterface, 0, 4)
caps = append(caps, bgp.NewCapRouteRefresh()) caps = append(caps, bgp.NewCapRouteRefresh())
caps = append(caps, bgp.NewCapFQDN(fqdn, ""))
for _, af := range pConf.AfiSafis { for _, af := range pConf.AfiSafis {
caps = append(caps, bgp.NewCapMultiProtocol(af.State.Family)) caps = append(caps, bgp.NewCapMultiProtocol(af.State.Family))
} }
@@ -869,7 +873,8 @@ func (h *fsmHandler) afiSafiDisable(rf bgp.RouteFamily) string {
} }
func (h *fsmHandler) handlingError(m *bgp.BGPMessage, e error, useRevisedError bool) bgp.ErrorHandling { func (h *fsmHandler) handlingError(m *bgp.BGPMessage, e error, useRevisedError bool) bgp.ErrorHandling {
handling := bgp.ERROR_HANDLING_NONE // ineffectual assignment to handling (ineffassign)
var handling bgp.ErrorHandling
if m.Header.Type == bgp.BGP_MSG_UPDATE && useRevisedError { if m.Header.Type == bgp.BGP_MSG_UPDATE && useRevisedError {
factor := e.(*bgp.MessageError) factor := e.(*bgp.MessageError)
handling = factor.ErrorHandling handling = factor.ErrorHandling
@@ -1015,6 +1020,13 @@ func (h *fsmHandler) recvMessageWithError() (*fsmMsg, error) {
case bgp.BGP_MSG_ROUTE_REFRESH: case bgp.BGP_MSG_ROUTE_REFRESH:
fmsg.MsgType = fsmMsgRouteRefresh fmsg.MsgType = fsmMsgRouteRefresh
case bgp.BGP_MSG_UPDATE: case bgp.BGP_MSG_UPDATE:
// if the length of h.holdTimerResetCh
// isn't zero, the timer will be reset
// soon anyway.
select {
case h.holdTimerResetCh <- true:
default:
}
body := m.Body.(*bgp.BGPUpdate) body := m.Body.(*bgp.BGPUpdate)
isEBGP := h.fsm.pConf.IsEBGPPeer(h.fsm.gConf) isEBGP := h.fsm.pConf.IsEBGPPeer(h.fsm.gConf)
isConfed := h.fsm.pConf.IsConfederationMember(h.fsm.gConf) isConfed := h.fsm.pConf.IsConfederationMember(h.fsm.gConf)
@@ -1266,7 +1278,7 @@ func (h *fsmHandler) opensent(ctx context.Context) (bgp.FSMState, *fsmStateReaso
fsm.lock.RLock() fsm.lock.RLock()
fsmPeerAS := fsm.pConf.Config.PeerAs fsmPeerAS := fsm.pConf.Config.PeerAs
fsm.lock.RUnlock() fsm.lock.RUnlock()
peerAs, err := bgp.ValidateOpenMsg(body, fsmPeerAS) peerAs, err := bgp.ValidateOpenMsg(body, fsmPeerAS, fsm.peerInfo.LocalAS, net.ParseIP(fsm.gConf.Config.RouterId))
if err != nil { if err != nil {
m, _ := fsm.sendNotificationFromErrorMsg(err.(*bgp.MessageError)) m, _ := fsm.sendNotificationFromErrorMsg(err.(*bgp.MessageError))
return bgp.BGP_FSM_IDLE, newfsmStateReason(fsmInvalidMsg, m, nil) return bgp.BGP_FSM_IDLE, newfsmStateReason(fsmInvalidMsg, m, nil)
@@ -1569,6 +1581,14 @@ func (h *fsmHandler) openconfirm(ctx context.Context) (bgp.FSMState, *fsmStateRe
} }
func (h *fsmHandler) sendMessageloop(ctx context.Context, wg *sync.WaitGroup) error { func (h *fsmHandler) sendMessageloop(ctx context.Context, wg *sync.WaitGroup) error {
sendToStateReasonCh := func(typ fsmStateReasonType, notif *bgp.BGPMessage) {
// probably doesn't happen but be cautious
select {
case h.stateReasonCh <- *newfsmStateReason(typ, notif, nil):
default:
}
}
defer wg.Done() defer wg.Done()
conn := h.conn conn := h.conn
fsm := h.fsm fsm := h.fsm
@@ -1603,7 +1623,7 @@ func (h *fsmHandler) sendMessageloop(ctx context.Context, wg *sync.WaitGroup) er
err = conn.SetWriteDeadline(time.Now().Add(time.Second * time.Duration(fsm.pConf.Timers.State.NegotiatedHoldTime))) err = conn.SetWriteDeadline(time.Now().Add(time.Second * time.Duration(fsm.pConf.Timers.State.NegotiatedHoldTime)))
fsm.lock.RUnlock() fsm.lock.RUnlock()
if err != nil { if err != nil {
h.stateReasonCh <- *newfsmStateReason(fsmWriteFailed, nil, nil) sendToStateReasonCh(fsmWriteFailed, nil)
conn.Close() conn.Close()
return fmt.Errorf("failed to set write deadline") return fmt.Errorf("failed to set write deadline")
} }
@@ -1617,7 +1637,7 @@ func (h *fsmHandler) sendMessageloop(ctx context.Context, wg *sync.WaitGroup) er
"Data": err, "Data": err,
}).Warn("failed to send") }).Warn("failed to send")
fsm.lock.RUnlock() fsm.lock.RUnlock()
h.stateReasonCh <- *newfsmStateReason(fsmWriteFailed, nil, nil) sendToStateReasonCh(fsmWriteFailed, nil)
conn.Close() conn.Close()
return fmt.Errorf("closed") return fmt.Errorf("closed")
} }
@@ -1651,7 +1671,7 @@ func (h *fsmHandler) sendMessageloop(ctx context.Context, wg *sync.WaitGroup) er
}).Warn("sent notification") }).Warn("sent notification")
fsm.lock.RUnlock() fsm.lock.RUnlock()
} }
h.stateReasonCh <- *newfsmStateReason(fsmNotificationSent, m, nil) sendToStateReasonCh(fsmNotificationSent, m)
conn.Close() conn.Close()
return fmt.Errorf("closed") return fmt.Errorf("closed")
case bgp.BGP_MSG_UPDATE: case bgp.BGP_MSG_UPDATE:

View File

@@ -64,8 +64,9 @@ func (s *server) serve() error {
l := []net.Listener{} l := []net.Listener{}
var err error var err error
for _, host := range strings.Split(s.hosts, ",") { for _, host := range strings.Split(s.hosts, ",") {
network, address := parseHost(host)
var lis net.Listener var lis net.Listener
lis, err = net.Listen("tcp", host) lis, err = net.Listen(network, address)
if err != nil { if err != nil {
log.WithFields(log.Fields{ log.WithFields(log.Fields{
"Topic": "grpc", "Topic": "grpc",
@@ -101,6 +102,38 @@ func (s *server) serve() error {
return nil return nil
} }
func (s *server) ListDynamicNeighbor(r *api.ListDynamicNeighborRequest, stream api.GobgpApi_ListDynamicNeighborServer) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
fn := func(dn *api.DynamicNeighbor) {
if err := stream.Send(&api.ListDynamicNeighborResponse{DynamicNeighbor: dn}); err != nil {
cancel()
return
}
}
return s.bgpServer.ListDynamicNeighbor(ctx, r, fn)
}
func (s *server) ListPeerGroup(r *api.ListPeerGroupRequest, stream api.GobgpApi_ListPeerGroupServer) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
fn := func(pg *api.PeerGroup) {
if err := stream.Send(&api.ListPeerGroupResponse{PeerGroup: pg}); err != nil {
cancel()
return
}
}
return s.bgpServer.ListPeerGroup(ctx, r, fn)
}
func parseHost(host string) (string, string) {
const unixScheme = "unix://"
if strings.HasPrefix(host, unixScheme) {
return "unix", host[len(unixScheme):]
}
return "tcp", host
}
func (s *server) ListPeer(r *api.ListPeerRequest, stream api.GobgpApi_ListPeerServer) error { func (s *server) ListPeer(r *api.ListPeerRequest, stream api.GobgpApi_ListPeerServer) error {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
@@ -153,11 +186,26 @@ func toPathAPI(binNlri []byte, binPattrs [][]byte, anyNlri *any.Any, anyPattrs [
return p return p
} }
func toPathApi(path *table.Path, v *table.Validation) *api.Path { func toPathApi(path *table.Path, v *table.Validation, nlri_binary, attribute_binary bool) *api.Path {
nlri := path.GetNlri() nlri := path.GetNlri()
anyNlri := apiutil.MarshalNLRI(nlri) anyNlri := apiutil.MarshalNLRI(nlri)
anyPattrs := apiutil.MarshalPathAttributes(path.GetPathAttrs()) anyPattrs := apiutil.MarshalPathAttributes(path.GetPathAttrs())
return toPathAPI(nil, nil, anyNlri, anyPattrs, path, v) var binNlri []byte
if nlri_binary {
binNlri, _ = nlri.Serialize()
}
var binPattrs [][]byte
if attribute_binary {
pa := path.GetPathAttrs()
binPattrs = make([][]byte, 0, len(pa))
for _, a := range pa {
b, e := a.Serialize()
if e == nil {
binPattrs = append(binPattrs, b)
}
}
}
return toPathAPI(binNlri, binPattrs, anyNlri, anyPattrs, path, v)
} }
func getValidation(v map[*table.Path]*table.Validation, p *table.Path) *table.Validation { func getValidation(v map[*table.Path]*table.Validation, p *table.Path) *table.Validation {
@@ -281,6 +329,11 @@ func api2Path(resource api.TableType, path *api.Path, isWithdraw bool) (*table.P
return nil, err return nil, err
} }
// TODO (sbezverk) At this poinnt nlri and path attributes are converted to native mode
// need to check if update with SR Policy nlri comes with mandatory route distinguisher
// extended community or NO_ADVERTISE community, with Tunnel Encapsulation Attribute 23
// and tunnel type 15. If it is not the case ignore update and log an error.
pattrs := make([]bgp.PathAttributeInterface, 0) pattrs := make([]bgp.PathAttributeInterface, 0)
seen := make(map[bgp.BGPAttrType]struct{}) seen := make(map[bgp.BGPAttrType]struct{})
for _, attr := range attrList { for _, attr := range attrList {
@@ -295,6 +348,9 @@ func api2Path(resource api.TableType, path *api.Path, isWithdraw bool) (*table.P
case *bgp.PathAttributeNextHop: case *bgp.PathAttributeNextHop:
nexthop = a.Value.String() nexthop = a.Value.String()
case *bgp.PathAttributeMpReachNLRI: case *bgp.PathAttributeMpReachNLRI:
if len(a.Value) == 0 {
return nil, fmt.Errorf("invalid mp reach attribute")
}
nlri = a.Value[0] nlri = a.Value[0]
nexthop = a.Nexthop.String() nexthop = a.Nexthop.String()
default: default:
@@ -486,20 +542,29 @@ func readApplyPolicyFromAPIStruct(c *config.ApplyPolicy, a *api.ApplyPolicy) {
if c == nil || a == nil { if c == nil || a == nil {
return return
} }
f := func(a api.RouteAction) config.DefaultPolicyType {
if a == api.RouteAction_ACCEPT {
return config.DEFAULT_POLICY_TYPE_ACCEPT_ROUTE
} else if a == api.RouteAction_REJECT {
return config.DEFAULT_POLICY_TYPE_REJECT_ROUTE
}
return ""
}
if a.ImportPolicy != nil { if a.ImportPolicy != nil {
c.Config.DefaultImportPolicy = config.IntToDefaultPolicyTypeMap[int(a.ImportPolicy.DefaultAction)] c.Config.DefaultImportPolicy = f(a.ImportPolicy.DefaultAction)
for _, p := range a.ImportPolicy.Policies { for _, p := range a.ImportPolicy.Policies {
c.Config.ImportPolicyList = append(c.Config.ImportPolicyList, p.Name) c.Config.ImportPolicyList = append(c.Config.ImportPolicyList, p.Name)
} }
} }
if a.ExportPolicy != nil { if a.ExportPolicy != nil {
c.Config.DefaultExportPolicy = config.IntToDefaultPolicyTypeMap[int(a.ExportPolicy.DefaultAction)] c.Config.DefaultExportPolicy = f(a.ExportPolicy.DefaultAction)
for _, p := range a.ExportPolicy.Policies { for _, p := range a.ExportPolicy.Policies {
c.Config.ExportPolicyList = append(c.Config.ExportPolicyList, p.Name) c.Config.ExportPolicyList = append(c.Config.ExportPolicyList, p.Name)
} }
} }
if a.InPolicy != nil { if a.InPolicy != nil {
c.Config.DefaultInPolicy = config.IntToDefaultPolicyTypeMap[int(a.InPolicy.DefaultAction)] c.Config.DefaultInPolicy = f(a.InPolicy.DefaultAction)
for _, p := range a.InPolicy.Policies { for _, p := range a.InPolicy.Policies {
c.Config.InPolicyList = append(c.Config.InPolicyList, p.Name) c.Config.InPolicyList = append(c.Config.InPolicyList, p.Name)
} }
@@ -668,6 +733,10 @@ func newNeighborFromAPIStruct(a *api.Peer) (*config.Neighbor, error) {
pconf.EbgpMultihop.Config.Enabled = a.EbgpMultihop.Enabled pconf.EbgpMultihop.Config.Enabled = a.EbgpMultihop.Enabled
pconf.EbgpMultihop.Config.MultihopTtl = uint8(a.EbgpMultihop.MultihopTtl) pconf.EbgpMultihop.Config.MultihopTtl = uint8(a.EbgpMultihop.MultihopTtl)
} }
if a.TtlSecurity != nil {
pconf.TtlSecurity.Config.Enabled = a.TtlSecurity.Enabled
pconf.TtlSecurity.Config.TtlMin = uint8(a.TtlSecurity.TtlMin)
}
if a.State != nil { if a.State != nil {
pconf.State.SessionState = config.SessionState(strings.ToUpper(string(a.State.SessionState))) pconf.State.SessionState = config.SessionState(strings.ToUpper(string(a.State.SessionState)))
pconf.State.AdminState = config.IntToAdminStateMap[int(a.State.AdminState)] pconf.State.AdminState = config.IntToAdminStateMap[int(a.State.AdminState)]
@@ -771,6 +840,10 @@ func newPeerGroupFromAPIStruct(a *api.PeerGroup) (*config.PeerGroup, error) {
pconf.EbgpMultihop.Config.Enabled = a.EbgpMultihop.Enabled pconf.EbgpMultihop.Config.Enabled = a.EbgpMultihop.Enabled
pconf.EbgpMultihop.Config.MultihopTtl = uint8(a.EbgpMultihop.MultihopTtl) pconf.EbgpMultihop.Config.MultihopTtl = uint8(a.EbgpMultihop.MultihopTtl)
} }
if a.TtlSecurity != nil {
pconf.TtlSecurity.Config.Enabled = a.TtlSecurity.Enabled
pconf.TtlSecurity.Config.TtlMin = uint8(a.TtlSecurity.TtlMin)
}
if a.Info != nil { if a.Info != nil {
pconf.State.TotalPaths = a.Info.TotalPaths pconf.State.TotalPaths = a.Info.TotalPaths
pconf.State.TotalPrefixes = a.Info.TotalPrefixes pconf.State.TotalPrefixes = a.Info.TotalPrefixes
@@ -808,6 +881,10 @@ func (s *server) AddDynamicNeighbor(ctx context.Context, r *api.AddDynamicNeighb
return &empty.Empty{}, s.bgpServer.AddDynamicNeighbor(ctx, r) return &empty.Empty{}, s.bgpServer.AddDynamicNeighbor(ctx, r)
} }
func (s *server) DeleteDynamicNeighbor(ctx context.Context, r *api.DeleteDynamicNeighborRequest) (*empty.Empty, error) {
return &empty.Empty{}, s.bgpServer.DeleteDynamicNeighbor(ctx, r)
}
func newPrefixFromApiStruct(a *api.Prefix) (*table.Prefix, error) { func newPrefixFromApiStruct(a *api.Prefix) (*table.Prefix, error) {
_, prefix, err := net.ParseCIDR(a.IpPrefix) _, prefix, err := net.ParseCIDR(a.IpPrefix)
if err != nil { if err != nil {
@@ -1135,6 +1212,11 @@ func toStatementApi(s *config.Statement) *api.Statement {
Self: true, Self: true,
} }
} }
if string(s.Actions.BgpActions.SetNextHop) == "unchanged" {
return &api.NexthopAction{
Unchanged: true,
}
}
return &api.NexthopAction{ return &api.NexthopAction{
Address: string(s.Actions.BgpActions.SetNextHop), Address: string(s.Actions.BgpActions.SetNextHop),
} }
@@ -1410,6 +1492,9 @@ func newNexthopActionFromApiStruct(a *api.NexthopAction) (*table.NexthopAction,
if a.Self { if a.Self {
return "self" return "self"
} }
if a.Unchanged {
return "unchanged"
}
return a.Address return a.Address
}(), }(),
)) ))
@@ -1757,3 +1842,7 @@ func (s *server) StopBgp(ctx context.Context, r *api.StopBgpRequest) (*empty.Emp
func (s *server) GetTable(ctx context.Context, r *api.GetTableRequest) (*api.GetTableResponse, error) { func (s *server) GetTable(ctx context.Context, r *api.GetTableRequest) (*api.GetTableResponse, error) {
return s.bgpServer.GetTable(ctx, r) return s.bgpServer.GetTable(ctx, r)
} }
func (s *server) SetLogLevel(ctx context.Context, r *api.SetLogLevelRequest) (*empty.Empty, error) {
return &empty.Empty{}, s.bgpServer.SetLogLevel(ctx, r)
}

View File

@@ -51,7 +51,7 @@ func (m *mrtWriter) loop() error {
ops := []watchOption{} ops := []watchOption{}
switch m.c.DumpType { switch m.c.DumpType {
case config.MRT_TYPE_UPDATES: case config.MRT_TYPE_UPDATES:
ops = append(ops, watchUpdate(false)) ops = append(ops, watchUpdate(false, ""))
case config.MRT_TYPE_TABLE: case config.MRT_TYPE_TABLE:
if len(m.c.TableName) > 0 { if len(m.c.TableName) > 0 {
ops = append(ops, watchTableName(m.c.TableName)) ops = append(ops, watchTableName(m.c.TableName))

View File

@@ -57,6 +57,10 @@ func (pg *peerGroup) AddDynamicNeighbor(c *config.DynamicNeighbor) {
pg.dynamicNeighbors[c.Config.Prefix] = c pg.dynamicNeighbors[c.Config.Prefix] = c
} }
func (pg *peerGroup) DeleteDynamicNeighbor(prefix string) {
delete(pg.dynamicNeighbors, prefix)
}
func newDynamicPeer(g *config.Global, neighborAddress string, pg *config.PeerGroup, loc *table.TableManager, policy *table.RoutingPolicy) *peer { func newDynamicPeer(g *config.Global, neighborAddress string, pg *config.PeerGroup, loc *table.TableManager, policy *table.RoutingPolicy) *peer {
conf := config.Neighbor{ conf := config.Neighbor{
Config: config.NeighborConfig{ Config: config.NeighborConfig{
@@ -131,6 +135,15 @@ func (peer *peer) ID() string {
return peer.fsm.pConf.State.NeighborAddress return peer.fsm.pConf.State.NeighborAddress
} }
func (peer *peer) RouterID() string {
peer.fsm.lock.RLock()
defer peer.fsm.lock.RUnlock()
if peer.fsm.peerInfo.ID != nil {
return peer.fsm.peerInfo.ID.String()
}
return ""
}
func (peer *peer) TableID() string { func (peer *peer) TableID() string {
return peer.tableId return peer.tableId
} }
@@ -348,7 +361,22 @@ func (peer *peer) stopPeerRestarting() {
} }
func (peer *peer) filterPathFromSourcePeer(path, old *table.Path) *table.Path { func (peer *peer) filterPathFromSourcePeer(path, old *table.Path) *table.Path {
if peer.ID() != path.GetSource().Address.String() { // Consider 3 peers - A, B, C and prefix P originated by C. Parallel eBGP
// sessions exist between A & B, and both have a single session with C.
//
// When A receives the withdraw from C, we enter this func for each peer of
// A, with the following:
// peer: [C, B #1, B #2]
// path: new best for P facing B
// old: old best for P facing C
//
// Our comparison between peer identifier and path source ID must be router
// ID-based (not neighbor address), otherwise we will return early. If we
// return early for one of the two sessions facing B
// (whichever is not the new best path), we fail to send a withdraw towards
// B, and the route is "stuck".
// TODO: considerations for RFC6286
if peer.RouterID() != path.GetSource().ID.String() {
return path return path
} }

View File

@@ -23,6 +23,7 @@ import (
"reflect" "reflect"
"strconv" "strconv"
"sync" "sync"
"syscall"
"time" "time"
"github.com/eapache/channels" "github.com/eapache/channels"
@@ -52,35 +53,56 @@ func (l *tcpListener) Close() error {
} }
// avoid mapped IPv6 address // avoid mapped IPv6 address
func newTCPListener(address string, port uint32, ch chan *net.TCPConn) (*tcpListener, error) { func newTCPListener(address string, port uint32, bindToDev string, ch chan *net.TCPConn) (*tcpListener, error) {
proto := "tcp4" proto := "tcp4"
family := syscall.AF_INET
if ip := net.ParseIP(address); ip == nil { if ip := net.ParseIP(address); ip == nil {
return nil, fmt.Errorf("can't listen on %s", address) return nil, fmt.Errorf("can't listen on %s", address)
} else if ip.To4() == nil { } else if ip.To4() == nil {
proto = "tcp6" proto = "tcp6"
family = syscall.AF_INET6
} }
addr, err := net.ResolveTCPAddr(proto, net.JoinHostPort(address, strconv.Itoa(int(port)))) addr := net.JoinHostPort(address, strconv.Itoa(int(port)))
if err != nil {
return nil, err
}
l, err := net.ListenTCP(proto, addr) var lc net.ListenConfig
lc.Control = func(network, address string, c syscall.RawConn) error {
if bindToDev != "" {
err := setBindToDevSockopt(c, bindToDev)
if err != nil { if err != nil {
return nil, err log.WithFields(log.Fields{
"Topic": "Peer",
"Key": addr,
"BindToDev": bindToDev,
}).Warnf("failed to bind Listener to device (%s): %s", bindToDev, err)
return err
}
} }
// Note: Set TTL=255 for incoming connection listener in order to accept // Note: Set TTL=255 for incoming connection listener in order to accept
// connection in case for the neighbor has TTL Security settings. // connection in case for the neighbor has TTL Security settings.
if err := setListenTCPTTLSockopt(l, 255); err != nil { err := setsockoptIpTtl(c, family, 255)
if err != nil {
log.WithFields(log.Fields{ log.WithFields(log.Fields{
"Topic": "Peer", "Topic": "Peer",
"Key": addr, "Key": addr,
}).Warnf("cannot set TTL(=%d) for TCPListener: %s", 255, err) }).Warnf("cannot set TTL(=%d) for TCPListener: %s", 255, err)
} }
return nil
}
l, err := lc.Listen(context.Background(), proto, addr)
if err != nil {
return nil, err
}
listener, ok := l.(*net.TCPListener)
if !ok {
err = fmt.Errorf("unexpected connection listener (not for TCP)")
return nil, err
}
closeCh := make(chan struct{}) closeCh := make(chan struct{})
go func() error { go func() error {
for { for {
conn, err := l.AcceptTCP() conn, err := listener.AcceptTCP()
if err != nil { if err != nil {
close(closeCh) close(closeCh)
log.WithFields(log.Fields{ log.WithFields(log.Fields{
@@ -93,7 +115,7 @@ func newTCPListener(address string, port uint32, ch chan *net.TCPConn) (*tcpList
} }
}() }()
return &tcpListener{ return &tcpListener{
l: l, l: listener,
ch: closeCh, ch: closeCh,
}, nil }, nil
} }
@@ -118,6 +140,7 @@ func GrpcOption(opt []grpc.ServerOption) ServerOption {
} }
type BgpServer struct { type BgpServer struct {
apiServer *server
bgpConfig config.Bgp bgpConfig config.Bgp
acceptCh chan *net.TCPConn acceptCh chan *net.TCPConn
incomings []*channels.InfiniteChannel incomings []*channels.InfiniteChannel
@@ -158,9 +181,9 @@ func NewBgpServer(opt ...ServerOption) *BgpServer {
s.mrtManager = newMrtManager(s) s.mrtManager = newMrtManager(s)
if len(opts.grpcAddress) != 0 { if len(opts.grpcAddress) != 0 {
grpc.EnableTracing = false grpc.EnableTracing = false
api := newAPIserver(s, grpc.NewServer(opts.grpcOption...), opts.grpcAddress) s.apiServer = newAPIserver(s, grpc.NewServer(opts.grpcOption...), opts.grpcAddress)
go func() { go func() {
if err := api.serve(); err != nil { if err := s.apiServer.serve(); err != nil {
log.Fatalf("failed to listen grpc port: %s", err) log.Fatalf("failed to listen grpc port: %s", err)
} }
}() }()
@@ -169,6 +192,14 @@ func NewBgpServer(opt ...ServerOption) *BgpServer {
return s return s
} }
func (s *BgpServer) Stop() {
s.StopBgp(context.Background(), &api.StopBgpRequest{})
if s.apiServer != nil {
s.apiServer.grpcServer.Stop()
}
}
func (s *BgpServer) addIncoming(ch *channels.InfiniteChannel) { func (s *BgpServer) addIncoming(ch *channels.InfiniteChannel) {
s.incomings = append(s.incomings, ch) s.incomings = append(s.incomings, ch)
} }
@@ -555,7 +586,7 @@ func filterpath(peer *peer, path, old *table.Path) *table.Path {
return nil return nil
} }
if !peer.isRouteServerClient() && isASLoop(peer, path) { if !peer.isRouteServerClient() && isASLoop(peer, path) && !path.IsLocal() {
return nil return nil
} }
return path return path
@@ -853,8 +884,12 @@ func (s *BgpServer) notifyPostPolicyUpdateWatcher(peer *peer, pathList []*table.
} }
func newWatchEventPeerState(peer *peer, m *fsmMsg) *watchEventPeerState { func newWatchEventPeerState(peer *peer, m *fsmMsg) *watchEventPeerState {
_, rport := peer.fsm.RemoteHostPort() var laddr string
laddr, lport := peer.fsm.LocalHostPort() var rport, lport uint16
if peer.fsm.conn != nil {
_, rport = peer.fsm.RemoteHostPort()
laddr, lport = peer.fsm.LocalHostPort()
}
sentOpen := buildopen(peer.fsm.gConf, peer.fsm.pConf) sentOpen := buildopen(peer.fsm.gConf, peer.fsm.pConf)
peer.fsm.lock.RLock() peer.fsm.lock.RLock()
recvOpen := peer.fsm.recvOpen recvOpen := peer.fsm.recvOpen
@@ -1296,6 +1331,7 @@ func (s *BgpServer) deleteDynamicNeighbor(peer *peer, oldState bgp.FSMState, e *
peer.fsm.lock.RUnlock() peer.fsm.lock.RUnlock()
cleanInfiniteChannel(peer.fsm.outgoingCh) cleanInfiniteChannel(peer.fsm.outgoingCh)
cleanInfiniteChannel(peer.fsm.incomingCh) cleanInfiniteChannel(peer.fsm.incomingCh)
s.delIncoming(peer.fsm.incomingCh)
s.broadcastPeerState(peer, oldState, e) s.broadcastPeerState(peer, oldState, e)
} }
@@ -1696,6 +1732,9 @@ func (s *BgpServer) handleFSMMessage(peer *peer, e *fsmMsg) {
} }
func (s *BgpServer) EnableZebra(ctx context.Context, r *api.EnableZebraRequest) error { func (s *BgpServer) EnableZebra(ctx context.Context, r *api.EnableZebraRequest) error {
if r == nil {
return fmt.Errorf("nil request")
}
return s.mgmtOperation(func() error { return s.mgmtOperation(func() error {
if s.zclient != nil { if s.zclient != nil {
return fmt.Errorf("already connected to Zebra") return fmt.Errorf("already connected to Zebra")
@@ -1718,6 +1757,9 @@ func (s *BgpServer) EnableZebra(ctx context.Context, r *api.EnableZebraRequest)
} }
func (s *BgpServer) AddBmp(ctx context.Context, r *api.AddBmpRequest) error { func (s *BgpServer) AddBmp(ctx context.Context, r *api.AddBmpRequest) error {
if r == nil {
return fmt.Errorf("nil request")
}
return s.mgmtOperation(func() error { return s.mgmtOperation(func() error {
_, ok := api.AddBmpRequest_MonitoringPolicy_name[int32(r.Policy)] _, ok := api.AddBmpRequest_MonitoringPolicy_name[int32(r.Policy)]
if !ok { if !ok {
@@ -1735,6 +1777,9 @@ func (s *BgpServer) AddBmp(ctx context.Context, r *api.AddBmpRequest) error {
} }
func (s *BgpServer) DeleteBmp(ctx context.Context, r *api.DeleteBmpRequest) error { func (s *BgpServer) DeleteBmp(ctx context.Context, r *api.DeleteBmpRequest) error {
if r == nil {
return fmt.Errorf("nil request")
}
return s.mgmtOperation(func() error { return s.mgmtOperation(func() error {
return s.bmpManager.deleteServer(&config.BmpServerConfig{ return s.bmpManager.deleteServer(&config.BmpServerConfig{
Address: r.Address, Address: r.Address,
@@ -1744,6 +1789,9 @@ func (s *BgpServer) DeleteBmp(ctx context.Context, r *api.DeleteBmpRequest) erro
} }
func (s *BgpServer) StopBgp(ctx context.Context, r *api.StopBgpRequest) error { func (s *BgpServer) StopBgp(ctx context.Context, r *api.StopBgpRequest) error {
if r == nil {
return fmt.Errorf("nil request")
}
s.mgmtOperation(func() error { s.mgmtOperation(func() error {
names := make([]string, 0, len(s.neighborMap)) names := make([]string, 0, len(s.neighborMap))
for k := range s.neighborMap { for k := range s.neighborMap {
@@ -1769,11 +1817,15 @@ func (s *BgpServer) StopBgp(ctx context.Context, r *api.StopBgpRequest) error {
if s.shutdownWG != nil { if s.shutdownWG != nil {
s.shutdownWG.Wait() s.shutdownWG.Wait()
s.shutdownWG = nil
} }
return nil return nil
} }
func (s *BgpServer) SetPolicies(ctx context.Context, r *api.SetPoliciesRequest) error { func (s *BgpServer) SetPolicies(ctx context.Context, r *api.SetPoliciesRequest) error {
if r == nil {
return fmt.Errorf("nil request")
}
rp, err := newRoutingPolicyFromApiStruct(r) rp, err := newRoutingPolicyFromApiStruct(r)
if err != nil { if err != nil {
return err return err
@@ -1989,6 +2041,9 @@ func (s *BgpServer) addPathStream(vrfId string, pathList []*table.Path) error {
} }
func (s *BgpServer) AddPath(ctx context.Context, r *api.AddPathRequest) (*api.AddPathResponse, error) { func (s *BgpServer) AddPath(ctx context.Context, r *api.AddPathRequest) (*api.AddPathResponse, error) {
if r == nil || r.Path == nil {
return nil, fmt.Errorf("nil request")
}
var uuidBytes []byte var uuidBytes []byte
err := s.mgmtOperation(func() error { err := s.mgmtOperation(func() error {
path, err := api2Path(r.TableType, r.Path, false) path, err := api2Path(r.TableType, r.Path, false)
@@ -2009,6 +2064,9 @@ func (s *BgpServer) AddPath(ctx context.Context, r *api.AddPathRequest) (*api.Ad
} }
func (s *BgpServer) DeletePath(ctx context.Context, r *api.DeletePathRequest) error { func (s *BgpServer) DeletePath(ctx context.Context, r *api.DeletePathRequest) error {
if r == nil {
return fmt.Errorf("nil request")
}
return s.mgmtOperation(func() error { return s.mgmtOperation(func() error {
deletePathList := make([]*table.Path, 0) deletePathList := make([]*table.Path, 0)
@@ -2082,10 +2140,10 @@ func (s *BgpServer) updatePath(vrfId string, pathList []*table.Path) error {
} }
func (s *BgpServer) StartBgp(ctx context.Context, r *api.StartBgpRequest) error { func (s *BgpServer) StartBgp(ctx context.Context, r *api.StartBgpRequest) error {
return s.mgmtOperation(func() error {
if r == nil || r.Global == nil { if r == nil || r.Global == nil {
return fmt.Errorf("invalid request") return fmt.Errorf("nil request")
} }
return s.mgmtOperation(func() error {
g := r.Global g := r.Global
if net.ParseIP(g.RouterId) == nil { if net.ParseIP(g.RouterId) == nil {
return fmt.Errorf("invalid router-id format: %s", g.RouterId) return fmt.Errorf("invalid router-id format: %s", g.RouterId)
@@ -2099,7 +2157,7 @@ func (s *BgpServer) StartBgp(ctx context.Context, r *api.StartBgpRequest) error
if c.Config.Port > 0 { if c.Config.Port > 0 {
acceptCh := make(chan *net.TCPConn, 4096) acceptCh := make(chan *net.TCPConn, 4096)
for _, addr := range c.Config.LocalAddressList { for _, addr := range c.Config.LocalAddressList {
l, err := newTCPListener(addr, uint32(c.Config.Port), acceptCh) l, err := newTCPListener(addr, uint32(c.Config.Port), g.BindToDevice, acceptCh)
if err != nil { if err != nil {
return err return err
} }
@@ -2135,7 +2193,10 @@ func (s *BgpServer) listVrf() (l []*table.Vrf) {
return l return l
} }
func (s *BgpServer) ListVrf(ctx context.Context, _ *api.ListVrfRequest, fn func(*api.Vrf)) error { func (s *BgpServer) ListVrf(ctx context.Context, r *api.ListVrfRequest, fn func(*api.Vrf)) error {
if r == nil {
return fmt.Errorf("nil request")
}
toApi := func(v *table.Vrf) *api.Vrf { toApi := func(v *table.Vrf) *api.Vrf {
return &api.Vrf{ return &api.Vrf{
Name: v.Name, Name: v.Name,
@@ -2148,7 +2209,10 @@ func (s *BgpServer) ListVrf(ctx context.Context, _ *api.ListVrfRequest, fn func(
var l []*api.Vrf var l []*api.Vrf
s.mgmtOperation(func() error { s.mgmtOperation(func() error {
l = make([]*api.Vrf, 0, len(s.globalRib.Vrfs)) l = make([]*api.Vrf, 0, len(s.globalRib.Vrfs))
for _, vrf := range s.globalRib.Vrfs { for name, vrf := range s.globalRib.Vrfs {
if r.Name != "" && r.Name != name {
continue
}
l = append(l, toApi(vrf.Clone())) l = append(l, toApi(vrf.Clone()))
} }
return nil return nil
@@ -2165,11 +2229,10 @@ func (s *BgpServer) ListVrf(ctx context.Context, _ *api.ListVrfRequest, fn func(
} }
func (s *BgpServer) AddVrf(ctx context.Context, r *api.AddVrfRequest) error { func (s *BgpServer) AddVrf(ctx context.Context, r *api.AddVrfRequest) error {
return s.mgmtOperation(func() error {
if r == nil || r.Vrf == nil { if r == nil || r.Vrf == nil {
return fmt.Errorf("invalid request") return fmt.Errorf("nil request")
} }
return s.mgmtOperation(func() error {
name := r.Vrf.Name name := r.Vrf.Name
id := r.Vrf.Id id := r.Vrf.Id
@@ -2206,10 +2269,10 @@ func (s *BgpServer) AddVrf(ctx context.Context, r *api.AddVrfRequest) error {
} }
func (s *BgpServer) DeleteVrf(ctx context.Context, r *api.DeleteVrfRequest) error { func (s *BgpServer) DeleteVrf(ctx context.Context, r *api.DeleteVrfRequest) error {
return s.mgmtOperation(func() error {
if r == nil || r.Name == "" { if r == nil || r.Name == "" {
return fmt.Errorf("invalid request") return fmt.Errorf("nil request")
} }
return s.mgmtOperation(func() error {
name := r.Name name := r.Name
for _, n := range s.neighborMap { for _, n := range s.neighborMap {
n.fsm.lock.RLock() n.fsm.lock.RLock()
@@ -2473,6 +2536,9 @@ func (s *BgpServer) getAdjRib(addr string, family bgp.RouteFamily, in bool, enab
} }
func (s *BgpServer) ListPath(ctx context.Context, r *api.ListPathRequest, fn func(*api.Destination)) error { func (s *BgpServer) ListPath(ctx context.Context, r *api.ListPathRequest, fn func(*api.Destination)) error {
if r == nil {
return fmt.Errorf("nil request")
}
var tbl *table.Table var tbl *table.Table
var v map[*table.Path]*table.Validation var v map[*table.Path]*table.Validation
var filtered map[string]*table.Path var filtered map[string]*table.Path
@@ -2520,7 +2586,7 @@ func (s *BgpServer) ListPath(ctx context.Context, r *api.ListPathRequest, fn fun
} }
knownPathList := dst.GetAllKnownPathList() knownPathList := dst.GetAllKnownPathList()
for i, path := range knownPathList { for i, path := range knownPathList {
p := toPathApi(path, getValidation(v, path)) p := toPathApi(path, getValidation(v, path), r.EnableNlriBinary, r.EnableAttributeBinary)
if !table.SelectionOptions.DisableBestPathSelection { if !table.SelectionOptions.DisableBestPathSelection {
if i == 0 { if i == 0 {
switch r.TableType { switch r.TableType {
@@ -2638,8 +2704,8 @@ func (s *BgpServer) getVrfRibInfo(name string, family bgp.RouteFamily) (info *ta
} }
func (s *BgpServer) GetTable(ctx context.Context, r *api.GetTableRequest) (*api.GetTableResponse, error) { func (s *BgpServer) GetTable(ctx context.Context, r *api.GetTableRequest) (*api.GetTableResponse, error) {
if r == nil { if r == nil || r.Family == nil {
return nil, fmt.Errorf("invalid request") return nil, fmt.Errorf("nil request")
} }
family := bgp.RouteFamily(0) family := bgp.RouteFamily(0)
if r.Family != nil { if r.Family != nil {
@@ -2674,6 +2740,9 @@ func (s *BgpServer) GetTable(ctx context.Context, r *api.GetTableRequest) (*api.
} }
func (s *BgpServer) GetBgp(ctx context.Context, r *api.GetBgpRequest) (*api.GetBgpResponse, error) { func (s *BgpServer) GetBgp(ctx context.Context, r *api.GetBgpRequest) (*api.GetBgpResponse, error) {
if r == nil {
return nil, fmt.Errorf("nil request")
}
var rsp *api.GetBgpResponse var rsp *api.GetBgpResponse
s.mgmtOperation(func() error { s.mgmtOperation(func() error {
g := s.bgpConfig.Global g := s.bgpConfig.Global
@@ -2691,7 +2760,72 @@ func (s *BgpServer) GetBgp(ctx context.Context, r *api.GetBgpRequest) (*api.GetB
return rsp, nil return rsp, nil
} }
func (s *BgpServer) ListDynamicNeighbor(ctx context.Context, r *api.ListDynamicNeighborRequest, fn func(neighbor *api.DynamicNeighbor)) error {
if r == nil {
return fmt.Errorf("nil request")
}
toApi := func(dn *config.DynamicNeighbor) *api.DynamicNeighbor {
return &api.DynamicNeighbor{
Prefix: dn.Config.Prefix,
PeerGroup: dn.Config.PeerGroup,
}
}
var l []*api.DynamicNeighbor
s.mgmtOperation(func() error {
peerGroupName := r.PeerGroup
for k, group := range s.peerGroupMap {
if peerGroupName != "" && peerGroupName != k {
continue
}
for _, dn := range group.dynamicNeighbors {
l = append(l, toApi(dn))
}
}
return nil
}, false)
for _, dn := range l {
select {
case <-ctx.Done():
return nil
default:
fn(dn)
}
}
return nil
}
func (s *BgpServer) ListPeerGroup(ctx context.Context, r *api.ListPeerGroupRequest, fn func(*api.PeerGroup)) error {
if r == nil {
return fmt.Errorf("nil request")
}
var l []*api.PeerGroup
s.mgmtOperation(func() error {
peerGroupName := r.PeerGroupName
l = make([]*api.PeerGroup, 0, len(s.peerGroupMap))
for k, group := range s.peerGroupMap {
if peerGroupName != "" && peerGroupName != k {
continue
}
pg := config.NewPeerGroupFromConfigStruct(group.Conf)
l = append(l, pg)
}
return nil
}, false)
for _, pg := range l {
select {
case <-ctx.Done():
return nil
default:
fn(pg)
}
}
return nil
}
func (s *BgpServer) ListPeer(ctx context.Context, r *api.ListPeerRequest, fn func(*api.Peer)) error { func (s *BgpServer) ListPeer(ctx context.Context, r *api.ListPeerRequest, fn func(*api.Peer)) error {
if r == nil {
return fmt.Errorf("nil request")
}
var l []*api.Peer var l []*api.Peer
s.mgmtOperation(func() error { s.mgmtOperation(func() error {
address := r.Address address := r.Address
@@ -2839,6 +2973,9 @@ func (s *BgpServer) addNeighbor(c *config.Neighbor) error {
} }
func (s *BgpServer) AddPeerGroup(ctx context.Context, r *api.AddPeerGroupRequest) error { func (s *BgpServer) AddPeerGroup(ctx context.Context, r *api.AddPeerGroupRequest) error {
if r == nil || r.PeerGroup == nil {
return fmt.Errorf("nil request")
}
return s.mgmtOperation(func() error { return s.mgmtOperation(func() error {
c, err := newPeerGroupFromAPIStruct(r.PeerGroup) c, err := newPeerGroupFromAPIStruct(r.PeerGroup)
if err != nil { if err != nil {
@@ -2849,6 +2986,9 @@ func (s *BgpServer) AddPeerGroup(ctx context.Context, r *api.AddPeerGroupRequest
} }
func (s *BgpServer) AddPeer(ctx context.Context, r *api.AddPeerRequest) error { func (s *BgpServer) AddPeer(ctx context.Context, r *api.AddPeerRequest) error {
if r == nil || r.Peer == nil {
return fmt.Errorf("nil request")
}
return s.mgmtOperation(func() error { return s.mgmtOperation(func() error {
c, err := newNeighborFromAPIStruct(r.Peer) c, err := newNeighborFromAPIStruct(r.Peer)
if err != nil { if err != nil {
@@ -2859,6 +2999,9 @@ func (s *BgpServer) AddPeer(ctx context.Context, r *api.AddPeerRequest) error {
} }
func (s *BgpServer) AddDynamicNeighbor(ctx context.Context, r *api.AddDynamicNeighborRequest) error { func (s *BgpServer) AddDynamicNeighbor(ctx context.Context, r *api.AddDynamicNeighborRequest) error {
if r == nil || r.DynamicNeighbor == nil {
return fmt.Errorf("nil request")
}
return s.mgmtOperation(func() error { return s.mgmtOperation(func() error {
c := &config.DynamicNeighbor{Config: config.DynamicNeighborConfig{ c := &config.DynamicNeighbor{Config: config.DynamicNeighborConfig{
Prefix: r.DynamicNeighbor.Prefix, Prefix: r.DynamicNeighbor.Prefix,
@@ -2929,6 +3072,9 @@ func (s *BgpServer) deleteNeighbor(c *config.Neighbor, code, subcode uint8) erro
} }
func (s *BgpServer) DeletePeerGroup(ctx context.Context, r *api.DeletePeerGroupRequest) error { func (s *BgpServer) DeletePeerGroup(ctx context.Context, r *api.DeletePeerGroupRequest) error {
if r == nil {
return fmt.Errorf("nil request")
}
return s.mgmtOperation(func() error { return s.mgmtOperation(func() error {
name := r.Name name := r.Name
for _, n := range s.neighborMap { for _, n := range s.neighborMap {
@@ -2944,6 +3090,9 @@ func (s *BgpServer) DeletePeerGroup(ctx context.Context, r *api.DeletePeerGroupR
} }
func (s *BgpServer) DeletePeer(ctx context.Context, r *api.DeletePeerRequest) error { func (s *BgpServer) DeletePeer(ctx context.Context, r *api.DeletePeerRequest) error {
if r == nil {
return fmt.Errorf("nil request")
}
return s.mgmtOperation(func() error { return s.mgmtOperation(func() error {
c := &config.Neighbor{Config: config.NeighborConfig{ c := &config.Neighbor{Config: config.NeighborConfig{
NeighborAddress: r.Address, NeighborAddress: r.Address,
@@ -2953,6 +3102,16 @@ func (s *BgpServer) DeletePeer(ctx context.Context, r *api.DeletePeerRequest) er
}, true) }, true)
} }
func (s *BgpServer) DeleteDynamicNeighbor(ctx context.Context, r *api.DeleteDynamicNeighborRequest) error {
if r == nil {
return fmt.Errorf("nil request")
}
return s.mgmtOperation(func() error {
s.peerGroupMap[r.PeerGroup].DeleteDynamicNeighbor(r.Prefix)
return nil
}, true)
}
func (s *BgpServer) updatePeerGroup(pg *config.PeerGroup) (needsSoftResetIn bool, err error) { func (s *BgpServer) updatePeerGroup(pg *config.PeerGroup) (needsSoftResetIn bool, err error) {
name := pg.Config.PeerGroupName name := pg.Config.PeerGroupName
@@ -2974,6 +3133,9 @@ func (s *BgpServer) updatePeerGroup(pg *config.PeerGroup) (needsSoftResetIn bool
} }
func (s *BgpServer) UpdatePeerGroup(ctx context.Context, r *api.UpdatePeerGroupRequest) (rsp *api.UpdatePeerGroupResponse, err error) { func (s *BgpServer) UpdatePeerGroup(ctx context.Context, r *api.UpdatePeerGroupRequest) (rsp *api.UpdatePeerGroupResponse, err error) {
if r == nil || r.PeerGroup == nil {
return nil, fmt.Errorf("nil request")
}
doSoftreset := false doSoftreset := false
err = s.mgmtOperation(func() error { err = s.mgmtOperation(func() error {
pg, err := newPeerGroupFromAPIStruct(r.PeerGroup) pg, err := newPeerGroupFromAPIStruct(r.PeerGroup)
@@ -3081,6 +3243,9 @@ func (s *BgpServer) updateNeighbor(c *config.Neighbor) (needsSoftResetIn bool, e
} }
func (s *BgpServer) UpdatePeer(ctx context.Context, r *api.UpdatePeerRequest) (rsp *api.UpdatePeerResponse, err error) { func (s *BgpServer) UpdatePeer(ctx context.Context, r *api.UpdatePeerRequest) (rsp *api.UpdatePeerResponse, err error) {
if r == nil || r.Peer == nil {
return nil, fmt.Errorf("nil request")
}
doSoftReset := false doSoftReset := false
err = s.mgmtOperation(func() error { err = s.mgmtOperation(func() error {
c, err := newNeighborFromAPIStruct(r.Peer) c, err := newNeighborFromAPIStruct(r.Peer)
@@ -3124,12 +3289,18 @@ func (s *BgpServer) sendNotification(op, addr string, subcode uint8, data []byte
} }
func (s *BgpServer) ShutdownPeer(ctx context.Context, r *api.ShutdownPeerRequest) error { func (s *BgpServer) ShutdownPeer(ctx context.Context, r *api.ShutdownPeerRequest) error {
if r == nil {
return fmt.Errorf("nil request")
}
return s.mgmtOperation(func() error { return s.mgmtOperation(func() error {
return s.sendNotification("Neighbor shutdown", r.Address, bgp.BGP_ERROR_SUB_ADMINISTRATIVE_SHUTDOWN, newAdministrativeCommunication(r.Communication)) return s.sendNotification("Neighbor shutdown", r.Address, bgp.BGP_ERROR_SUB_ADMINISTRATIVE_SHUTDOWN, newAdministrativeCommunication(r.Communication))
}, true) }, true)
} }
func (s *BgpServer) ResetPeer(ctx context.Context, r *api.ResetPeerRequest) error { func (s *BgpServer) ResetPeer(ctx context.Context, r *api.ResetPeerRequest) error {
if r == nil {
return fmt.Errorf("nil request")
}
return s.mgmtOperation(func() error { return s.mgmtOperation(func() error {
addr := r.Address addr := r.Address
comm := r.Communication comm := r.Communication
@@ -3197,18 +3368,27 @@ func (s *BgpServer) setAdminState(addr, communication string, enable bool) error
} }
func (s *BgpServer) EnablePeer(ctx context.Context, r *api.EnablePeerRequest) error { func (s *BgpServer) EnablePeer(ctx context.Context, r *api.EnablePeerRequest) error {
if r == nil {
return fmt.Errorf("nil request")
}
return s.mgmtOperation(func() error { return s.mgmtOperation(func() error {
return s.setAdminState(r.Address, "", true) return s.setAdminState(r.Address, "", true)
}, true) }, true)
} }
func (s *BgpServer) DisablePeer(ctx context.Context, r *api.DisablePeerRequest) error { func (s *BgpServer) DisablePeer(ctx context.Context, r *api.DisablePeerRequest) error {
if r == nil {
return fmt.Errorf("nil request")
}
return s.mgmtOperation(func() error { return s.mgmtOperation(func() error {
return s.setAdminState(r.Address, r.Communication, false) return s.setAdminState(r.Address, r.Communication, false)
}, true) }, true)
} }
func (s *BgpServer) ListDefinedSet(ctx context.Context, r *api.ListDefinedSetRequest, fn func(*api.DefinedSet)) error { func (s *BgpServer) ListDefinedSet(ctx context.Context, r *api.ListDefinedSetRequest, fn func(*api.DefinedSet)) error {
if r == nil {
return fmt.Errorf("nil request")
}
var cd *config.DefinedSets var cd *config.DefinedSets
var err error var err error
err = s.mgmtOperation(func() error { err = s.mgmtOperation(func() error {
@@ -3303,10 +3483,10 @@ func (s *BgpServer) ListDefinedSet(ctx context.Context, r *api.ListDefinedSetReq
} }
func (s *BgpServer) AddDefinedSet(ctx context.Context, r *api.AddDefinedSetRequest) error { func (s *BgpServer) AddDefinedSet(ctx context.Context, r *api.AddDefinedSetRequest) error {
return s.mgmtOperation(func() error {
if r == nil || r.DefinedSet == nil { if r == nil || r.DefinedSet == nil {
return fmt.Errorf("invalid request") return fmt.Errorf("nil request")
} }
return s.mgmtOperation(func() error {
set, err := newDefinedSetFromApiStruct(r.DefinedSet) set, err := newDefinedSetFromApiStruct(r.DefinedSet)
if err != nil { if err != nil {
return err return err
@@ -3316,10 +3496,10 @@ func (s *BgpServer) AddDefinedSet(ctx context.Context, r *api.AddDefinedSetReque
} }
func (s *BgpServer) DeleteDefinedSet(ctx context.Context, r *api.DeleteDefinedSetRequest) error { func (s *BgpServer) DeleteDefinedSet(ctx context.Context, r *api.DeleteDefinedSetRequest) error {
return s.mgmtOperation(func() error {
if r == nil || r.DefinedSet == nil { if r == nil || r.DefinedSet == nil {
return fmt.Errorf("invalid request") return fmt.Errorf("nil request")
} }
return s.mgmtOperation(func() error {
set, err := newDefinedSetFromApiStruct(r.DefinedSet) set, err := newDefinedSetFromApiStruct(r.DefinedSet)
if err != nil { if err != nil {
return err return err
@@ -3329,6 +3509,9 @@ func (s *BgpServer) DeleteDefinedSet(ctx context.Context, r *api.DeleteDefinedSe
} }
func (s *BgpServer) ListStatement(ctx context.Context, r *api.ListStatementRequest, fn func(*api.Statement)) error { func (s *BgpServer) ListStatement(ctx context.Context, r *api.ListStatementRequest, fn func(*api.Statement)) error {
if r == nil {
return fmt.Errorf("nil request")
}
var l []*api.Statement var l []*api.Statement
s.mgmtOperation(func() error { s.mgmtOperation(func() error {
s := s.policy.GetStatement(r.Name) s := s.policy.GetStatement(r.Name)
@@ -3350,10 +3533,10 @@ func (s *BgpServer) ListStatement(ctx context.Context, r *api.ListStatementReque
} }
func (s *BgpServer) AddStatement(ctx context.Context, r *api.AddStatementRequest) error { func (s *BgpServer) AddStatement(ctx context.Context, r *api.AddStatementRequest) error {
return s.mgmtOperation(func() error {
if r == nil || r.Statement == nil { if r == nil || r.Statement == nil {
return fmt.Errorf("invalid request") return fmt.Errorf("nil request")
} }
return s.mgmtOperation(func() error {
st, err := newStatementFromApiStruct(r.Statement) st, err := newStatementFromApiStruct(r.Statement)
if err != nil { if err != nil {
return err return err
@@ -3363,10 +3546,10 @@ func (s *BgpServer) AddStatement(ctx context.Context, r *api.AddStatementRequest
} }
func (s *BgpServer) DeleteStatement(ctx context.Context, r *api.DeleteStatementRequest) error { func (s *BgpServer) DeleteStatement(ctx context.Context, r *api.DeleteStatementRequest) error {
return s.mgmtOperation(func() error {
if r == nil || r.Statement == nil { if r == nil || r.Statement == nil {
return fmt.Errorf("invalid request") return fmt.Errorf("nil request")
} }
return s.mgmtOperation(func() error {
st, err := newStatementFromApiStruct(r.Statement) st, err := newStatementFromApiStruct(r.Statement)
if err == nil { if err == nil {
err = s.policy.DeleteStatement(st, r.All) err = s.policy.DeleteStatement(st, r.All)
@@ -3376,6 +3559,9 @@ func (s *BgpServer) DeleteStatement(ctx context.Context, r *api.DeleteStatementR
} }
func (s *BgpServer) ListPolicy(ctx context.Context, r *api.ListPolicyRequest, fn func(*api.Policy)) error { func (s *BgpServer) ListPolicy(ctx context.Context, r *api.ListPolicyRequest, fn func(*api.Policy)) error {
if r == nil {
return fmt.Errorf("nil request")
}
var l []*api.Policy var l []*api.Policy
s.mgmtOperation(func() error { s.mgmtOperation(func() error {
pl := s.policy.GetPolicy(r.Name) pl := s.policy.GetPolicy(r.Name)
@@ -3397,10 +3583,10 @@ func (s *BgpServer) ListPolicy(ctx context.Context, r *api.ListPolicyRequest, fn
} }
func (s *BgpServer) AddPolicy(ctx context.Context, r *api.AddPolicyRequest) error { func (s *BgpServer) AddPolicy(ctx context.Context, r *api.AddPolicyRequest) error {
return s.mgmtOperation(func() error {
if r == nil || r.Policy == nil { if r == nil || r.Policy == nil {
return fmt.Errorf("invalid request") return fmt.Errorf("nil request")
} }
return s.mgmtOperation(func() error {
p, err := newPolicyFromApiStruct(r.Policy) p, err := newPolicyFromApiStruct(r.Policy)
if err == nil { if err == nil {
err = s.policy.AddPolicy(p, r.ReferExistingStatements) err = s.policy.AddPolicy(p, r.ReferExistingStatements)
@@ -3410,10 +3596,10 @@ func (s *BgpServer) AddPolicy(ctx context.Context, r *api.AddPolicyRequest) erro
} }
func (s *BgpServer) DeletePolicy(ctx context.Context, r *api.DeletePolicyRequest) error { func (s *BgpServer) DeletePolicy(ctx context.Context, r *api.DeletePolicyRequest) error {
return s.mgmtOperation(func() error {
if r == nil || r.Policy == nil { if r == nil || r.Policy == nil {
return fmt.Errorf("invalid request") return fmt.Errorf("nil request")
} }
return s.mgmtOperation(func() error {
p, err := newPolicyFromApiStruct(r.Policy) p, err := newPolicyFromApiStruct(r.Policy)
if err != nil { if err != nil {
return err return err
@@ -3456,12 +3642,11 @@ func (s *BgpServer) toPolicyInfo(name string, dir api.PolicyDirection) (string,
} }
func (s *BgpServer) ListPolicyAssignment(ctx context.Context, r *api.ListPolicyAssignmentRequest, fn func(*api.PolicyAssignment)) error { func (s *BgpServer) ListPolicyAssignment(ctx context.Context, r *api.ListPolicyAssignmentRequest, fn func(*api.PolicyAssignment)) error {
if r == nil {
return fmt.Errorf("nil request")
}
var a []*api.PolicyAssignment var a []*api.PolicyAssignment
err := s.mgmtOperation(func() error { err := s.mgmtOperation(func() error {
if r == nil {
return fmt.Errorf("invalid request")
}
names := make([]string, 0, len(s.neighborMap)+1) names := make([]string, 0, len(s.neighborMap)+1)
if r.Name == "" { if r.Name == "" {
names = append(names, table.GLOBAL_RIB_NAME) names = append(names, table.GLOBAL_RIB_NAME)
@@ -3491,9 +3676,6 @@ func (s *BgpServer) ListPolicyAssignment(ctx context.Context, r *api.ListPolicyA
if err != nil { if err != nil {
return err return err
} }
if len(policies) == 0 {
continue
}
t := &table.PolicyAssignment{ t := &table.PolicyAssignment{
Name: name, Name: name,
Type: dir, Type: dir,
@@ -3519,10 +3701,10 @@ func (s *BgpServer) ListPolicyAssignment(ctx context.Context, r *api.ListPolicyA
} }
func (s *BgpServer) AddPolicyAssignment(ctx context.Context, r *api.AddPolicyAssignmentRequest) error { func (s *BgpServer) AddPolicyAssignment(ctx context.Context, r *api.AddPolicyAssignmentRequest) error {
return s.mgmtOperation(func() error {
if r == nil || r.Assignment == nil { if r == nil || r.Assignment == nil {
return fmt.Errorf("invalid request") return fmt.Errorf("nil request")
} }
return s.mgmtOperation(func() error {
id, dir, err := s.toPolicyInfo(r.Assignment.Name, r.Assignment.Direction) id, dir, err := s.toPolicyInfo(r.Assignment.Name, r.Assignment.Direction)
if err != nil { if err != nil {
return err return err
@@ -3532,10 +3714,10 @@ func (s *BgpServer) AddPolicyAssignment(ctx context.Context, r *api.AddPolicyAss
} }
func (s *BgpServer) DeletePolicyAssignment(ctx context.Context, r *api.DeletePolicyAssignmentRequest) error { func (s *BgpServer) DeletePolicyAssignment(ctx context.Context, r *api.DeletePolicyAssignmentRequest) error {
return s.mgmtOperation(func() error {
if r == nil || r.Assignment == nil { if r == nil || r.Assignment == nil {
return fmt.Errorf("invalid request") return fmt.Errorf("nil request")
} }
return s.mgmtOperation(func() error {
id, dir, err := s.toPolicyInfo(r.Assignment.Name, r.Assignment.Direction) id, dir, err := s.toPolicyInfo(r.Assignment.Name, r.Assignment.Direction)
if err != nil { if err != nil {
return err return err
@@ -3545,10 +3727,10 @@ func (s *BgpServer) DeletePolicyAssignment(ctx context.Context, r *api.DeletePol
} }
func (s *BgpServer) SetPolicyAssignment(ctx context.Context, r *api.SetPolicyAssignmentRequest) error { func (s *BgpServer) SetPolicyAssignment(ctx context.Context, r *api.SetPolicyAssignmentRequest) error {
return s.mgmtOperation(func() error {
if r == nil || r.Assignment == nil { if r == nil || r.Assignment == nil {
return fmt.Errorf("invalid request") return fmt.Errorf("nil request")
} }
return s.mgmtOperation(func() error {
id, dir, err := s.toPolicyInfo(r.Assignment.Name, r.Assignment.Direction) id, dir, err := s.toPolicyInfo(r.Assignment.Name, r.Assignment.Direction)
if err != nil { if err != nil {
return err return err
@@ -3558,6 +3740,9 @@ func (s *BgpServer) SetPolicyAssignment(ctx context.Context, r *api.SetPolicyAss
} }
func (s *BgpServer) EnableMrt(ctx context.Context, r *api.EnableMrtRequest) error { func (s *BgpServer) EnableMrt(ctx context.Context, r *api.EnableMrtRequest) error {
if r == nil {
return fmt.Errorf("nil request")
}
return s.mgmtOperation(func() error { return s.mgmtOperation(func() error {
return s.mrtManager.enable(&config.MrtConfig{ return s.mrtManager.enable(&config.MrtConfig{
DumpInterval: r.DumpInterval, DumpInterval: r.DumpInterval,
@@ -3569,12 +3754,18 @@ func (s *BgpServer) EnableMrt(ctx context.Context, r *api.EnableMrtRequest) erro
} }
func (s *BgpServer) DisableMrt(ctx context.Context, r *api.DisableMrtRequest) error { func (s *BgpServer) DisableMrt(ctx context.Context, r *api.DisableMrtRequest) error {
if r == nil {
return fmt.Errorf("nil request")
}
return s.mgmtOperation(func() error { return s.mgmtOperation(func() error {
return s.mrtManager.disable(&config.MrtConfig{}) return s.mrtManager.disable(&config.MrtConfig{})
}, false) }, false)
} }
func (s *BgpServer) ListRpki(ctx context.Context, r *api.ListRpkiRequest, fn func(*api.Rpki)) error { func (s *BgpServer) ListRpki(ctx context.Context, r *api.ListRpkiRequest, fn func(*api.Rpki)) error {
if r == nil || r.Family == nil {
return fmt.Errorf("nil request")
}
var l []*api.Rpki var l []*api.Rpki
err := s.mgmtOperation(func() error { err := s.mgmtOperation(func() error {
for _, r := range s.roaManager.GetServers() { for _, r := range s.roaManager.GetServers() {
@@ -3623,6 +3814,9 @@ func (s *BgpServer) ListRpki(ctx context.Context, r *api.ListRpkiRequest, fn fun
} }
func (s *BgpServer) ListRpkiTable(ctx context.Context, r *api.ListRpkiTableRequest, fn func(*api.Roa)) error { func (s *BgpServer) ListRpkiTable(ctx context.Context, r *api.ListRpkiTableRequest, fn func(*api.Roa)) error {
if r == nil {
return fmt.Errorf("nil request")
}
var l []*api.Roa var l []*api.Roa
err := s.mgmtOperation(func() error { err := s.mgmtOperation(func() error {
family := bgp.RouteFamily(0) family := bgp.RouteFamily(0)
@@ -3649,30 +3843,45 @@ func (s *BgpServer) ListRpkiTable(ctx context.Context, r *api.ListRpkiTableReque
} }
func (s *BgpServer) AddRpki(ctx context.Context, r *api.AddRpkiRequest) error { func (s *BgpServer) AddRpki(ctx context.Context, r *api.AddRpkiRequest) error {
if r == nil {
return fmt.Errorf("nil request")
}
return s.mgmtOperation(func() error { return s.mgmtOperation(func() error {
return s.roaManager.AddServer(net.JoinHostPort(r.Address, strconv.Itoa(int(r.Port))), r.Lifetime) return s.roaManager.AddServer(net.JoinHostPort(r.Address, strconv.Itoa(int(r.Port))), r.Lifetime)
}, false) }, false)
} }
func (s *BgpServer) DeleteRpki(ctx context.Context, r *api.DeleteRpkiRequest) error { func (s *BgpServer) DeleteRpki(ctx context.Context, r *api.DeleteRpkiRequest) error {
if r == nil {
return fmt.Errorf("nil request")
}
return s.mgmtOperation(func() error { return s.mgmtOperation(func() error {
return s.roaManager.DeleteServer(r.Address) return s.roaManager.DeleteServer(r.Address)
}, false) }, false)
} }
func (s *BgpServer) EnableRpki(ctx context.Context, r *api.EnableRpkiRequest) error { func (s *BgpServer) EnableRpki(ctx context.Context, r *api.EnableRpkiRequest) error {
if r == nil {
return fmt.Errorf("nil request")
}
return s.mgmtOperation(func() error { return s.mgmtOperation(func() error {
return s.roaManager.Enable(r.Address) return s.roaManager.Enable(r.Address)
}, false) }, false)
} }
func (s *BgpServer) DisableRpki(ctx context.Context, r *api.DisableRpkiRequest) error { func (s *BgpServer) DisableRpki(ctx context.Context, r *api.DisableRpkiRequest) error {
if r == nil {
return fmt.Errorf("nil request")
}
return s.mgmtOperation(func() error { return s.mgmtOperation(func() error {
return s.roaManager.Disable(r.Address) return s.roaManager.Disable(r.Address)
}, false) }, false)
} }
func (s *BgpServer) ResetRpki(ctx context.Context, r *api.ResetRpkiRequest) error { func (s *BgpServer) ResetRpki(ctx context.Context, r *api.ResetRpkiRequest) error {
if r == nil {
return fmt.Errorf("nil request")
}
return s.mgmtOperation(func() error { return s.mgmtOperation(func() error {
if r.Soft { if r.Soft {
return s.roaManager.SoftReset(r.Address) return s.roaManager.SoftReset(r.Address)
@@ -3691,9 +3900,9 @@ func (s *BgpServer) MonitorTable(ctx context.Context, r *api.MonitorTableRequest
return s.watch(watchBestPath(r.Current)), nil return s.watch(watchBestPath(r.Current)), nil
case api.TableType_ADJ_IN: case api.TableType_ADJ_IN:
if r.PostPolicy { if r.PostPolicy {
return s.watch(watchPostUpdate(r.Current)), nil return s.watch(watchPostUpdate(r.Current, r.Name)), nil
} }
return s.watch(watchUpdate(r.Current)), nil return s.watch(watchUpdate(r.Current, r.Name)), nil
default: default:
return nil, fmt.Errorf("unsupported resource type: %v", r.TableType) return nil, fmt.Errorf("unsupported resource type: %v", r.TableType)
} }
@@ -3733,11 +3942,14 @@ func (s *BgpServer) MonitorTable(ctx context.Context, r *api.MonitorTableRequest
if path == nil || (r.Family != nil && family != path.GetRouteFamily()) { if path == nil || (r.Family != nil && family != path.GetRouteFamily()) {
continue continue
} }
if len(r.Name) > 0 && r.Name != path.GetSource().Address.String() {
continue
}
select { select {
case <-ctx.Done(): case <-ctx.Done():
return return
default: default:
fn(toPathApi(path, nil)) fn(toPathApi(path, nil, false, false))
} }
} }
case <-ctx.Done(): case <-ctx.Done():
@@ -3754,7 +3966,13 @@ func (s *BgpServer) MonitorPeer(ctx context.Context, r *api.MonitorPeerRequest,
} }
go func() { go func() {
w := s.watch(watchPeerState(r.Current)) // So that both flags are not required, assume that if the
// initial_state flag is true, then the caller desires that the initial
// state be returned whether or not it is established and regardless of
// the value of `current`.
current := r.Current || r.InitialState
nonEstablished := r.InitialState
w := s.watch(watchPeerState(current, nonEstablished))
defer func() { defer func() {
w.Stop() w.Stop()
}() }()
@@ -3795,6 +4013,22 @@ func (s *BgpServer) MonitorPeer(ctx context.Context, r *api.MonitorPeerRequest,
return nil return nil
} }
func (s *BgpServer) SetLogLevel(ctx context.Context, r *api.SetLogLevelRequest) error {
prevLevel := log.GetLevel()
newLevel := log.Level(r.Level)
if prevLevel == newLevel {
log.WithFields(log.Fields{
"Topic": "Config",
}).Infof("Logging level unchanged -- level already set to %v", newLevel)
} else {
log.SetLevel(newLevel)
log.WithFields(log.Fields{
"Topic": "Config",
}).Infof("Logging level changed -- prev: %v, new: %v", prevLevel, newLevel)
}
return nil
}
type watchEventType string type watchEventType string
const ( const (
@@ -3879,8 +4113,10 @@ type watchOptions struct {
initUpdate bool initUpdate bool
initPostUpdate bool initPostUpdate bool
initPeerState bool initPeerState bool
nonEstablished bool
tableName string tableName string
recvMessage bool recvMessage bool
peerAddress string
} }
type watchOption func(*watchOptions) type watchOption func(*watchOptions)
@@ -3894,29 +4130,34 @@ func watchBestPath(current bool) watchOption {
} }
} }
func watchUpdate(current bool) watchOption { func watchUpdate(current bool, peerAddress string) watchOption {
return func(o *watchOptions) { return func(o *watchOptions) {
o.preUpdate = true o.preUpdate = true
if current { if current {
o.initUpdate = true o.initUpdate = true
} }
o.peerAddress = peerAddress
} }
} }
func watchPostUpdate(current bool) watchOption { func watchPostUpdate(current bool, peerAddress string) watchOption {
return func(o *watchOptions) { return func(o *watchOptions) {
o.postUpdate = true o.postUpdate = true
if current { if current {
o.initPostUpdate = true o.initPostUpdate = true
} }
o.peerAddress = peerAddress
} }
} }
func watchPeerState(current bool) watchOption { func watchPeerState(current, includeNonEstablished bool) watchOption {
return func(o *watchOptions) { return func(o *watchOptions) {
o.peerState = true o.peerState = true
if current { if current {
o.initPeerState = true o.initPeerState = true
if includeNonEstablished {
o.nonEstablished = true
}
} }
} }
} }
@@ -4071,12 +4312,14 @@ func (s *BgpServer) watch(opts ...watchOption) (w *watcher) {
} }
if w.opts.initPeerState { if w.opts.initPeerState {
for _, peer := range s.neighborMap { for _, peer := range s.neighborMap {
if !w.opts.nonEstablished {
peer.fsm.lock.RLock() peer.fsm.lock.RLock()
notEstablished := peer.fsm.state != bgp.BGP_FSM_ESTABLISHED notEstablished := peer.fsm.state != bgp.BGP_FSM_ESTABLISHED
peer.fsm.lock.RUnlock() peer.fsm.lock.RUnlock()
if notEstablished { if notEstablished {
continue continue
} }
}
w.notify(newWatchEventPeerState(peer, nil)) w.notify(newWatchEventPeerState(peer, nil))
} }
} }
@@ -4090,10 +4333,14 @@ func (s *BgpServer) watch(opts ...watchOption) (w *watcher) {
for _, peer := range s.neighborMap { for _, peer := range s.neighborMap {
peer.fsm.lock.RLock() peer.fsm.lock.RLock()
notEstablished := peer.fsm.state != bgp.BGP_FSM_ESTABLISHED notEstablished := peer.fsm.state != bgp.BGP_FSM_ESTABLISHED
peerAddress := peer.fsm.peerInfo.Address.String()
peer.fsm.lock.RUnlock() peer.fsm.lock.RUnlock()
if notEstablished { if notEstablished {
continue continue
} }
if len(w.opts.peerAddress) > 0 && w.opts.peerAddress != peerAddress {
continue
}
configNeighbor := w.s.toConfig(peer, false) configNeighbor := w.s.toConfig(peer, false)
for _, rf := range peer.configuredRFlist() { for _, rf := range peer.configuredRFlist() {
peer.fsm.lock.RLock() peer.fsm.lock.RLock()
@@ -4148,9 +4395,13 @@ func (s *BgpServer) watch(opts ...watchOption) (w *watcher) {
for peerInfo, paths := range pathsByPeer { for peerInfo, paths := range pathsByPeer {
// create copy which can be access to without mutex // create copy which can be access to without mutex
var configNeighbor *config.Neighbor var configNeighbor *config.Neighbor
if peer, ok := s.neighborMap[peerInfo.Address.String()]; ok { peerAddress := peerInfo.Address.String()
if peer, ok := s.neighborMap[peerAddress]; ok {
configNeighbor = w.s.toConfig(peer, false) configNeighbor = w.s.toConfig(peer, false)
} }
if w.opts.peerAddress != "" && w.opts.peerAddress != peerAddress {
continue
}
w.notify(&watchEventUpdate{ w.notify(&watchEventUpdate{
PeerAS: peerInfo.AS, PeerAS: peerInfo.AS,

View File

@@ -17,6 +17,7 @@
package server package server
import ( import (
"fmt"
"net" "net"
"syscall" "syscall"
@@ -27,10 +28,6 @@ func setTCPMD5SigSockopt(l *net.TCPListener, address string, key string) error {
return setTcpMD5SigSockopt(l, address, key) return setTcpMD5SigSockopt(l, address, key)
} }
func setListenTCPTTLSockopt(l *net.TCPListener, ttl int) error {
return setListenTcpTTLSockopt(l, ttl)
}
func setTCPTTLSockopt(conn *net.TCPConn, ttl int) error { func setTCPTTLSockopt(conn *net.TCPConn, ttl int) error {
return setTcpTTLSockopt(conn, ttl) return setTcpTTLSockopt(conn, ttl)
} }
@@ -39,6 +36,10 @@ func setTCPMinTTLSockopt(conn *net.TCPConn, ttl int) error {
return setTcpMinTTLSockopt(conn, ttl) return setTcpMinTTLSockopt(conn, ttl)
} }
func setBindToDevSockopt(sc syscall.RawConn, device string) error {
return fmt.Errorf("binding connection to a device is not supported")
}
func dialerControl(network, address string, c syscall.RawConn, ttl, ttlMin uint8, password string, bindInterface string) error { func dialerControl(network, address string, c syscall.RawConn, ttl, ttlMin uint8, password string, bindInterface string) error {
if password != "" { if password != "" {
log.WithFields(log.Fields{ log.WithFields(log.Fields{

View File

@@ -35,15 +35,6 @@ func setTcpMD5SigSockopt(l *net.TCPListener, address string, key string) error {
return setsockOptInt(sc, syscall.IPPROTO_TCP, tcpMD5SIG, 1) return setsockOptInt(sc, syscall.IPPROTO_TCP, tcpMD5SIG, 1)
} }
func setListenTcpTTLSockopt(l *net.TCPListener, ttl int) error {
family := extractFamilyFromTCPListener(l)
sc, err := l.SyscallConn()
if err != nil {
return err
}
return setsockoptIpTtl(sc, family, ttl)
}
func setTcpTTLSockopt(conn *net.TCPConn, ttl int) error { func setTcpTTLSockopt(conn *net.TCPConn, ttl int) error {
family := extractFamilyFromTCPConn(conn) family := extractFamilyFromTCPConn(conn)
sc, err := conn.SyscallConn() sc, err := conn.SyscallConn()

View File

@@ -27,15 +27,6 @@ func setTcpMD5SigSockopt(l *net.TCPListener, address string, key string) error {
return fmt.Errorf("setting md5 is not supported") return fmt.Errorf("setting md5 is not supported")
} }
func setListenTcpTTLSockopt(l *net.TCPListener, ttl int) error {
family := extractFamilyFromTCPListener(l)
sc, err := l.SyscallConn()
if err != nil {
return err
}
return setsockoptIpTtl(sc, family, ttl)
}
func setTcpTTLSockopt(conn *net.TCPConn, ttl int) error { func setTcpTTLSockopt(conn *net.TCPConn, ttl int) error {
family := syscall.AF_INET family := syscall.AF_INET
if strings.Contains(conn.RemoteAddr().String(), "[") { if strings.Contains(conn.RemoteAddr().String(), "[") {

View File

@@ -70,13 +70,8 @@ func setTCPMD5SigSockopt(l *net.TCPListener, address string, key string) error {
return setsockOptString(sc, syscall.IPPROTO_TCP, tcpMD5SIG, string(b[:])) return setsockOptString(sc, syscall.IPPROTO_TCP, tcpMD5SIG, string(b[:]))
} }
func setListenTCPTTLSockopt(l *net.TCPListener, ttl int) error { func setBindToDevSockopt(sc syscall.RawConn, device string) error {
family := extractFamilyFromTCPListener(l) return setsockOptString(sc, syscall.SOL_SOCKET, syscall.SO_BINDTODEVICE, device)
sc, err := l.SyscallConn()
if err != nil {
return err
}
return setsockoptIpTtl(sc, family, ttl)
} }
func setTCPTTLSockopt(conn *net.TCPConn, ttl int) error { func setTCPTTLSockopt(conn *net.TCPConn, ttl int) error {
@@ -162,14 +157,9 @@ func dialerControl(network, address string, c syscall.RawConn, ttl, minTtl uint8
} }
} }
if bindInterface != "" { if bindInterface != "" {
if err := c.Control(func(fd uintptr) { if err := setBindToDevSockopt(c, bindInterface); err != nil {
sockerr = os.NewSyscallError("setsockopt", syscall.SetsockoptString(int(fd), syscall.SOL_SOCKET, syscall.SO_BINDTODEVICE, bindInterface))
}); err != nil {
return err return err
} }
if sockerr != nil {
return sockerr
}
} }
return nil return nil
} }

View File

@@ -370,15 +370,6 @@ func setTCPMD5SigSockopt(l *net.TCPListener, address string, key string) error {
return setsockoptTcpMD5Sig(sc, address, key) return setsockoptTcpMD5Sig(sc, address, key)
} }
func setListenTCPTTLSockopt(l *net.TCPListener, ttl int) error {
family := extractFamilyFromTCPListener(l)
sc, err := l.SyscallConn()
if err != nil {
return err
}
return setsockoptIpTtl(sc, family, ttl)
}
func setTCPTTLSockopt(conn *net.TCPConn, ttl int) error { func setTCPTTLSockopt(conn *net.TCPConn, ttl int) error {
family := extractFamilyFromTCPConn(conn) family := extractFamilyFromTCPConn(conn)
sc, err := conn.SyscallConn() sc, err := conn.SyscallConn()
@@ -403,6 +394,10 @@ func setTCPMinTTLSockopt(conn *net.TCPConn, ttl int) error {
return setsockOptInt(sc, level, name, ttl) return setsockOptInt(sc, level, name, ttl)
} }
func setBindToDevSockopt(sc syscall.RawConn, device string) error {
return fmt.Errorf("binding connection to a device is not supported")
}
func dialerControl(network, address string, c syscall.RawConn, ttl, minTtl uint8, password string, bindInterface string) error { func dialerControl(network, address string, c syscall.RawConn, ttl, minTtl uint8, password string, bindInterface string) error {
if password != "" { if password != "" {
log.WithFields(log.Fields{ log.WithFields(log.Fields{

View File

@@ -59,20 +59,12 @@ func decodeAdministrativeCommunication(data []byte) (string, []byte) {
if communicationLen > bgp.BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX { if communicationLen > bgp.BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX {
communicationLen = bgp.BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX communicationLen = bgp.BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX
} }
if communicationLen > len(data)+1 { if communicationLen > len(data)-1 {
communicationLen = len(data) + 1 communicationLen = len(data) - 1
} }
return string(data[1 : communicationLen+1]), data[communicationLen+1:] return string(data[1 : communicationLen+1]), data[communicationLen+1:]
} }
func extractFamilyFromTCPListener(l *net.TCPListener) int {
family := syscall.AF_INET
if strings.Contains(l.Addr().String(), "[") {
family = syscall.AF_INET6
}
return family
}
func extractFamilyFromTCPConn(conn *net.TCPConn) int { func extractFamilyFromTCPConn(conn *net.TCPConn) int {
family := syscall.AF_INET family := syscall.AF_INET
if strings.Contains(conn.RemoteAddr().String(), "[") { if strings.Contains(conn.RemoteAddr().String(), "[") {

View File

@@ -364,7 +364,7 @@ func (z *zebraClient) updatePathByNexthopCache(paths []*table.Path) {
func (z *zebraClient) loop() { func (z *zebraClient) loop() {
w := z.server.watch([]watchOption{ w := z.server.watch([]watchOption{
watchBestPath(true), watchBestPath(true),
watchPostUpdate(true), watchPostUpdate(true, ""),
}...) }...)
defer w.Stop() defer w.Stop()

View File

@@ -1 +1,4 @@
logrus logrus
vendor
.idea/

40
vendor/github.com/sirupsen/logrus/.golangci.yml generated vendored Normal file
View File

@@ -0,0 +1,40 @@
run:
# do not run on test files yet
tests: false
# all available settings of specific linters
linters-settings:
errcheck:
# report about not checking of errors in type assetions: `a := b.(MyStruct)`;
# default is false: such cases aren't reported by default.
check-type-assertions: false
# report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`;
# default is false: such cases aren't reported by default.
check-blank: false
lll:
line-length: 100
tab-width: 4
prealloc:
simple: false
range-loops: false
for-loops: false
whitespace:
multi-if: false # Enforces newlines (or comments) after every multi-line if statement
multi-func: false # Enforces newlines (or comments) after every multi-line function signature
linters:
enable:
- megacheck
- govet
disable:
- maligned
- prealloc
disable-all: false
presets:
- bugs
- unused
fast: false

View File

@@ -1,51 +1,15 @@
language: go language: go
go_import_path: github.com/sirupsen/logrus
git:
depth: 1
env: env:
- GOMAXPROCS=4 GORACE=halt_on_error=1 - GO111MODULE=on
matrix: go: 1.15.x
include: os: linux
- go: 1.10.x install:
install: - ./travis/install.sh
- go get github.com/stretchr/testify/assert script:
- go get golang.org/x/crypto/ssh/terminal - cd ci
- go get golang.org/x/sys/unix - go run mage.go -v -w ../ crossBuild
- go get golang.org/x/sys/windows - go run mage.go -v -w ../ lint
script: - go run mage.go -v -w ../ test
- go test -race -v ./...
- go: 1.11.x
env: GO111MODULE=on
install:
- go mod download
script:
- go test -race -v ./...
- go: 1.11.x
env: GO111MODULE=off
install:
- go get github.com/stretchr/testify/assert
- go get golang.org/x/crypto/ssh/terminal
- go get golang.org/x/sys/unix
- go get golang.org/x/sys/windows
script:
- go test -race -v ./...
- go: 1.10.x
install:
- go get github.com/stretchr/testify/assert
- go get golang.org/x/crypto/ssh/terminal
- go get golang.org/x/sys/unix
- go get golang.org/x/sys/windows
script:
- go test -race -v -tags appengine ./...
- go: 1.11.x
env: GO111MODULE=on
install:
- go mod download
script:
- go test -race -v -tags appengine ./...
- go: 1.11.x
env: GO111MODULE=off
install:
- go get github.com/stretchr/testify/assert
- go get golang.org/x/crypto/ssh/terminal
- go get golang.org/x/sys/unix
- go get golang.org/x/sys/windows
script:
- go test -race -v -tags appengine ./...

View File

@@ -1,3 +1,104 @@
# 1.8.1
Code quality:
* move magefile in its own subdir/submodule to remove magefile dependency on logrus consumer
* improve timestamp format documentation
Fixes:
* fix race condition on logger hooks
# 1.8.0
Correct versioning number replacing v1.7.1.
# 1.7.1
Beware this release has introduced a new public API and its semver is therefore incorrect.
Code quality:
* use go 1.15 in travis
* use magefile as task runner
Fixes:
* small fixes about new go 1.13 error formatting system
* Fix for long time race condiction with mutating data hooks
Features:
* build support for zos
# 1.7.0
Fixes:
* the dependency toward a windows terminal library has been removed
Features:
* a new buffer pool management API has been added
* a set of `<LogLevel>Fn()` functions have been added
# 1.6.0
Fixes:
* end of line cleanup
* revert the entry concurrency bug fix whic leads to deadlock under some circumstances
* update dependency on go-windows-terminal-sequences to fix a crash with go 1.14
Features:
* add an option to the `TextFormatter` to completely disable fields quoting
# 1.5.0
Code quality:
* add golangci linter run on travis
Fixes:
* add mutex for hooks concurrent access on `Entry` data
* caller function field for go1.14
* fix build issue for gopherjs target
Feature:
* add an hooks/writer sub-package whose goal is to split output on different stream depending on the trace level
* add a `DisableHTMLEscape` option in the `JSONFormatter`
* add `ForceQuote` and `PadLevelText` options in the `TextFormatter`
# 1.4.2
* Fixes build break for plan9, nacl, solaris
# 1.4.1
This new release introduces:
* Enhance TextFormatter to not print caller information when they are empty (#944)
* Remove dependency on golang.org/x/crypto (#932, #943)
Fixes:
* Fix Entry.WithContext method to return a copy of the initial entry (#941)
# 1.4.0
This new release introduces:
* Add `DeferExitHandler`, similar to `RegisterExitHandler` but prepending the handler to the list of handlers (semantically like `defer`) (#848).
* Add `CallerPrettyfier` to `JSONFormatter` and `TextFormatter` (#909, #911)
* Add `Entry.WithContext()` and `Entry.Context`, to set a context on entries to be used e.g. in hooks (#919).
Fixes:
* Fix wrong method calls `Logger.Print` and `Logger.Warningln` (#893).
* Update `Entry.Logf` to not do string formatting unless the log level is enabled (#903)
* Fix infinite recursion on unknown `Level.String()` (#907)
* Fix race condition in `getCaller` (#916).
# 1.3.0
This new release introduces:
* Log, Logf, Logln functions for Logger and Entry that take a Level
Fixes:
* Building prometheus node_exporter on AIX (#840)
* Race condition in TextFormatter (#468)
* Travis CI import path (#868)
* Remove coloured output on Windows (#862)
* Pointer to func as field in JSONFormatter (#870)
* Properly marshal Levels (#873)
# 1.2.0
This new release introduces:
* A new method `SetReportCaller` in the `Logger` to enable the file, line and calling function from which the trace has been issued
* A new trace level named `Trace` whose level is below `Debug`
* A configurable exit function to be called upon a Fatal trace
* The `Level` object now implements `encoding.TextUnmarshaler` interface
# 1.1.1 # 1.1.1
This is a bug fix release. This is a bug fix release.
* fix the build break on Solaris * fix the build break on Solaris

View File

@@ -1,8 +1,28 @@
# Logrus <img src="http://i.imgur.com/hTeVwmJ.png" width="40" height="40" alt=":walrus:" class="emoji" title=":walrus:"/>&nbsp;[![Build Status](https://travis-ci.org/sirupsen/logrus.svg?branch=master)](https://travis-ci.org/sirupsen/logrus)&nbsp;[![GoDoc](https://godoc.org/github.com/sirupsen/logrus?status.svg)](https://godoc.org/github.com/sirupsen/logrus) # Logrus <img src="http://i.imgur.com/hTeVwmJ.png" width="40" height="40" alt=":walrus:" class="emoji" title=":walrus:"/> [![Build Status](https://travis-ci.org/sirupsen/logrus.svg?branch=master)](https://travis-ci.org/sirupsen/logrus) [![GoDoc](https://godoc.org/github.com/sirupsen/logrus?status.svg)](https://godoc.org/github.com/sirupsen/logrus)
Logrus is a structured logger for Go (golang), completely API compatible with Logrus is a structured logger for Go (golang), completely API compatible with
the standard library logger. the standard library logger.
**Logrus is in maintenance-mode.** We will not be introducing new features. It's
simply too hard to do in a way that won't break many people's projects, which is
the last thing you want from your Logging library (again...).
This does not mean Logrus is dead. Logrus will continue to be maintained for
security, (backwards compatible) bug fixes, and performance (where we are
limited by the interface).
I believe Logrus' biggest contribution is to have played a part in today's
widespread use of structured logging in Golang. There doesn't seem to be a
reason to do a major, breaking iteration into Logrus V2, since the fantastic Go
community has built those independently. Many fantastic alternatives have sprung
up. Logrus would look like those, had it been re-designed with what we know
about structured logging in Go today. Check out, for example,
[Zerolog][zerolog], [Zap][zap], and [Apex][apex].
[zerolog]: https://github.com/rs/zerolog
[zap]: https://github.com/uber-go/zap
[apex]: https://github.com/apex/log
**Seeing weird case-sensitive problems?** It's in the past been possible to **Seeing weird case-sensitive problems?** It's in the past been possible to
import Logrus as both upper- and lower-case. Due to the Go package environment, import Logrus as both upper- and lower-case. Due to the Go package environment,
this caused issues in the community and we needed a standard. Some environments this caused issues in the community and we needed a standard. Some environments
@@ -15,11 +35,6 @@ comments](https://github.com/sirupsen/logrus/issues/553#issuecomment-306591437).
For an in-depth explanation of the casing issue, see [this For an in-depth explanation of the casing issue, see [this
comment](https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276). comment](https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276).
**Are you interested in assisting in maintaining Logrus?** Currently I have a
lot of obligations, and I am unable to provide Logrus with the maintainership it
needs. If you'd like to help, please reach out to me at `simon at author's
username dot com`.
Nicely color-coded in development (when a TTY is attached, otherwise just Nicely color-coded in development (when a TTY is attached, otherwise just
plain text): plain text):
@@ -56,8 +71,39 @@ time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased
time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4 time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4
time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009 time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009
time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true
exit status 1
``` ```
To ensure this behaviour even if a TTY is attached, set your formatter as follows:
```go
log.SetFormatter(&log.TextFormatter{
DisableColors: true,
FullTimestamp: true,
})
```
#### Logging Method Name
If you wish to add the calling method as a field, instruct the logger via:
```go
log.SetReportCaller(true)
```
This adds the caller as 'method' like so:
```json
{"animal":"penguin","level":"fatal","method":"github.com/sirupsen/arcticcreatures.migrate","msg":"a penguin swims by",
"time":"2014-03-10 19:57:38.562543129 -0400 EDT"}
```
```text
time="2015-03-26T01:27:38-04:00" level=fatal method=github.com/sirupsen/arcticcreatures.migrate msg="a penguin swims by" animal=penguin
```
Note that this does add measurable overhead - the cost will depend on the version of Go, but is
between 20 and 40% in recent tests with 1.6 and 1.7. You can validate this in your
environment via benchmarks:
```
go test -bench=.*CallerTracing
```
#### Case-sensitivity #### Case-sensitivity
@@ -156,7 +202,7 @@ func main() {
log.Out = os.Stdout log.Out = os.Stdout
// You could set this to any `io.Writer` such as a file // You could set this to any `io.Writer` such as a file
// file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666) // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
// if err == nil { // if err == nil {
// log.Out = file // log.Out = file
// } else { // } else {
@@ -241,14 +287,15 @@ func init() {
``` ```
Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md). Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md).
A list of currently known of service hook can be found in this wiki [page](https://github.com/sirupsen/logrus/wiki/Hooks) A list of currently known service hooks can be found in this wiki [page](https://github.com/sirupsen/logrus/wiki/Hooks)
#### Level logging #### Level logging
Logrus has six logging levels: Debug, Info, Warning, Error, Fatal and Panic. Logrus has seven logging levels: Trace, Debug, Info, Warning, Error, Fatal and Panic.
```go ```go
log.Trace("Something very low level.")
log.Debug("Useful debugging information.") log.Debug("Useful debugging information.")
log.Info("Something noteworthy happened!") log.Info("Something noteworthy happened!")
log.Warn("You should probably take a look at this.") log.Warn("You should probably take a look at this.")
@@ -322,6 +369,7 @@ The built-in logging formatters are:
[github.com/mattn/go-colorable](https://github.com/mattn/go-colorable). [github.com/mattn/go-colorable](https://github.com/mattn/go-colorable).
* When colors are enabled, levels are truncated to 4 characters by default. To disable * When colors are enabled, levels are truncated to 4 characters by default. To disable
truncation set the `DisableLevelTruncation` field to `true`. truncation set the `DisableLevelTruncation` field to `true`.
* When outputting to a TTY, it's often helpful to visually scan down a column where all the levels are the same width. Setting the `PadLevelText` field to `true` enables this behavior, by adding padding to the level text.
* All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#TextFormatter). * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#TextFormatter).
* `logrus.JSONFormatter`. Logs fields as JSON. * `logrus.JSONFormatter`. Logs fields as JSON.
* All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#JSONFormatter). * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#JSONFormatter).
@@ -329,9 +377,13 @@ The built-in logging formatters are:
Third party logging formatters: Third party logging formatters:
* [`FluentdFormatter`](https://github.com/joonix/log). Formats entries that can be parsed by Kubernetes and Google Container Engine. * [`FluentdFormatter`](https://github.com/joonix/log). Formats entries that can be parsed by Kubernetes and Google Container Engine.
* [`GELF`](https://github.com/fabienm/go-logrus-formatters). Formats entries so they comply to Graylog's [GELF 1.1 specification](http://docs.graylog.org/en/2.4/pages/gelf.html).
* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events. * [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events.
* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout. * [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout.
* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦. * [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the Power of Zalgo.
* [`nested-logrus-formatter`](https://github.com/antonfisher/nested-logrus-formatter). Converts logrus fields to a nested structure.
* [`powerful-logrus-formatter`](https://github.com/zput/zxcTool). get fileName, log's line number and the latest function's name when print log; Sava log to files.
* [`caption-json-formatter`](https://github.com/nolleh/caption_json_formatter). logrus's message json formatter with human-readable caption added.
You can define your formatter by implementing the `Formatter` interface, You can define your formatter by implementing the `Formatter` interface,
requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a
@@ -350,7 +402,7 @@ func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) {
// source of the official loggers. // source of the official loggers.
serialized, err := json.Marshal(entry.Data) serialized, err := json.Marshal(entry.Data)
if err != nil { if err != nil {
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) return nil, fmt.Errorf("Failed to marshal fields to JSON, %w", err)
} }
return append(serialized, '\n'), nil return append(serialized, '\n'), nil
} }
@@ -396,14 +448,14 @@ entries. It should not be a feature of the application-level logger.
| Tool | Description | | Tool | Description |
| ---- | ----------- | | ---- | ----------- |
|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will generated with different config at different environment.| |[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will be generated with different configs in different environments.|
|[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper around Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) | |[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper around Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) |
#### Testing #### Testing
Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides: Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides:
* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just add the `test` hook * decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just adds the `test` hook
* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any): * a test logger (`test.NewNullLogger`) that just records log messages (and does not output any):
```go ```go
@@ -431,7 +483,7 @@ func TestSomething(t*testing.T){
Logrus can register one or more functions that will be called when any `fatal` Logrus can register one or more functions that will be called when any `fatal`
level message is logged. The registered handlers will be executed before level message is logged. The registered handlers will be executed before
logrus performs a `os.Exit(1)`. This behavior may be helpful if callers need logrus performs an `os.Exit(1)`. This behavior may be helpful if callers need
to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted. to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted.
``` ```
@@ -456,6 +508,6 @@ Situation when locking is not needed includes:
1) logger.Out is protected by locks. 1) logger.Out is protected by locks.
2) logger.Out is a os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allow multi-thread/multi-process writing) 2) logger.Out is an os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allows multi-thread/multi-process writing)
(Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/) (Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/)

View File

@@ -51,9 +51,9 @@ func Exit(code int) {
os.Exit(code) os.Exit(code)
} }
// RegisterExitHandler adds a Logrus Exit handler, call logrus.Exit to invoke // RegisterExitHandler appends a Logrus Exit handler to the list of handlers,
// all handlers. The handlers will also be invoked when any Fatal log entry is // call logrus.Exit to invoke all handlers. The handlers will also be invoked when
// made. // any Fatal log entry is made.
// //
// This method is useful when a caller wishes to use logrus to log a fatal // This method is useful when a caller wishes to use logrus to log a fatal
// message but also needs to gracefully shutdown. An example usecase could be // message but also needs to gracefully shutdown. An example usecase could be
@@ -62,3 +62,15 @@ func Exit(code int) {
func RegisterExitHandler(handler func()) { func RegisterExitHandler(handler func()) {
handlers = append(handlers, handler) handlers = append(handlers, handler)
} }
// DeferExitHandler prepends a Logrus Exit handler to the list of handlers,
// call logrus.Exit to invoke all handlers. The handlers will also be invoked when
// any Fatal log entry is made.
//
// This method is useful when a caller wishes to use logrus to log a fatal
// message but also needs to gracefully shutdown. An example usecase could be
// closing database connections, or sending a alert that the application is
// closing.
func DeferExitHandler(handler func()) {
handlers = append([]func(){handler}, handlers...)
}

52
vendor/github.com/sirupsen/logrus/buffer_pool.go generated vendored Normal file
View File

@@ -0,0 +1,52 @@
package logrus
import (
"bytes"
"sync"
)
var (
bufferPool BufferPool
)
type BufferPool interface {
Put(*bytes.Buffer)
Get() *bytes.Buffer
}
type defaultPool struct {
pool *sync.Pool
}
func (p *defaultPool) Put(buf *bytes.Buffer) {
p.pool.Put(buf)
}
func (p *defaultPool) Get() *bytes.Buffer {
return p.pool.Get().(*bytes.Buffer)
}
func getBuffer() *bytes.Buffer {
return bufferPool.Get()
}
func putBuffer(buf *bytes.Buffer) {
buf.Reset()
bufferPool.Put(buf)
}
// SetBufferPool allows to replace the default logrus buffer pool
// to better meets the specific needs of an application.
func SetBufferPool(bp BufferPool) {
bufferPool = bp
}
func init() {
SetBufferPool(&defaultPool{
pool: &sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
},
})
}

View File

@@ -2,30 +2,45 @@ package logrus
import ( import (
"bytes" "bytes"
"context"
"fmt" "fmt"
"os" "os"
"reflect" "reflect"
"runtime"
"strings"
"sync" "sync"
"time" "time"
) )
var bufferPool *sync.Pool var (
// qualified package name, cached at first use
logrusPackage string
// Positions in the call stack when tracing to report the calling method
minimumCallerDepth int
// Used for caller information initialisation
callerInitOnce sync.Once
)
const (
maximumCallerDepth int = 25
knownLogrusFrames int = 4
)
func init() { func init() {
bufferPool = &sync.Pool{ // start at the bottom of the stack before the package-name cache is primed
New: func() interface{} { minimumCallerDepth = 1
return new(bytes.Buffer)
},
}
} }
// Defines the key when adding errors using WithError. // Defines the key when adding errors using WithError.
var ErrorKey = "error" var ErrorKey = "error"
// An entry is the final or intermediate Logrus logging entry. It contains all // An entry is the final or intermediate Logrus logging entry. It contains all
// the fields passed with WithField{,s}. It's finally logged when Debug, Info, // the fields passed with WithField{,s}. It's finally logged when Trace, Debug,
// Warn, Error, Fatal or Panic is called on it. These objects can be reused and // Info, Warn, Error, Fatal or Panic is called on it. These objects can be
// passed around as much as you wish to avoid field duplication. // reused and passed around as much as you wish to avoid field duplication.
type Entry struct { type Entry struct {
Logger *Logger Logger *Logger
@@ -35,16 +50,22 @@ type Entry struct {
// Time at which the log entry was created // Time at which the log entry was created
Time time.Time Time time.Time
// Level the log entry was logged at: Debug, Info, Warn, Error, Fatal or Panic // Level the log entry was logged at: Trace, Debug, Info, Warn, Error, Fatal or Panic
// This field will be set on entry firing and the value will be equal to the one in Logger struct field. // This field will be set on entry firing and the value will be equal to the one in Logger struct field.
Level Level Level Level
// Message passed to Debug, Info, Warn, Error, Fatal or Panic // Calling method, with package name
Caller *runtime.Frame
// Message passed to Trace, Debug, Info, Warn, Error, Fatal or Panic
Message string Message string
// When formatter is called in entry.log(), a Buffer may be set to entry // When formatter is called in entry.log(), a Buffer may be set to entry
Buffer *bytes.Buffer Buffer *bytes.Buffer
// Contains the context set by the user. Useful for hook processing etc.
Context context.Context
// err may contain a field formatting error // err may contain a field formatting error
err string err string
} }
@@ -52,15 +73,28 @@ type Entry struct {
func NewEntry(logger *Logger) *Entry { func NewEntry(logger *Logger) *Entry {
return &Entry{ return &Entry{
Logger: logger, Logger: logger,
// Default is five fields, give a little extra room // Default is three fields, plus one optional. Give a little extra room.
Data: make(Fields, 5), Data: make(Fields, 6),
} }
} }
func (entry *Entry) Dup() *Entry {
data := make(Fields, len(entry.Data))
for k, v := range entry.Data {
data[k] = v
}
return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, Context: entry.Context, err: entry.err}
}
// Returns the bytes representation of this entry from the formatter.
func (entry *Entry) Bytes() ([]byte, error) {
return entry.Logger.Formatter.Format(entry)
}
// Returns the string representation from the reader and ultimately the // Returns the string representation from the reader and ultimately the
// formatter. // formatter.
func (entry *Entry) String() (string, error) { func (entry *Entry) String() (string, error) {
serialized, err := entry.Logger.Formatter.Format(entry) serialized, err := entry.Bytes()
if err != nil { if err != nil {
return "", err return "", err
} }
@@ -73,6 +107,15 @@ func (entry *Entry) WithError(err error) *Entry {
return entry.WithField(ErrorKey, err) return entry.WithField(ErrorKey, err)
} }
// Add a context to the Entry.
func (entry *Entry) WithContext(ctx context.Context) *Entry {
dataCopy := make(Fields, len(entry.Data))
for k, v := range entry.Data {
dataCopy[k] = v
}
return &Entry{Logger: entry.Logger, Data: dataCopy, Time: entry.Time, err: entry.err, Context: ctx}
}
// Add a single field to the Entry. // Add a single field to the Entry.
func (entry *Entry) WithField(key string, value interface{}) *Entry { func (entry *Entry) WithField(key string, value interface{}) *Entry {
return entry.WithFields(Fields{key: value}) return entry.WithFields(Fields{key: value})
@@ -84,104 +127,191 @@ func (entry *Entry) WithFields(fields Fields) *Entry {
for k, v := range entry.Data { for k, v := range entry.Data {
data[k] = v data[k] = v
} }
var field_err string fieldErr := entry.err
for k, v := range fields { for k, v := range fields {
if t := reflect.TypeOf(v); t != nil && t.Kind() == reflect.Func { isErrField := false
field_err = fmt.Sprintf("can not add field %q", k) if t := reflect.TypeOf(v); t != nil {
if entry.err != "" { switch {
field_err = entry.err + ", " + field_err case t.Kind() == reflect.Func, t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Func:
isErrField = true
}
}
if isErrField {
tmp := fmt.Sprintf("can not add field %q", k)
if fieldErr != "" {
fieldErr = entry.err + ", " + tmp
} else {
fieldErr = tmp
} }
} else { } else {
data[k] = v data[k] = v
} }
} }
return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, err: field_err} return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, err: fieldErr, Context: entry.Context}
} }
// Overrides the time of the Entry. // Overrides the time of the Entry.
func (entry *Entry) WithTime(t time.Time) *Entry { func (entry *Entry) WithTime(t time.Time) *Entry {
return &Entry{Logger: entry.Logger, Data: entry.Data, Time: t} dataCopy := make(Fields, len(entry.Data))
for k, v := range entry.Data {
dataCopy[k] = v
}
return &Entry{Logger: entry.Logger, Data: dataCopy, Time: t, err: entry.err, Context: entry.Context}
} }
// This function is not declared with a pointer value because otherwise // getPackageName reduces a fully qualified function name to the package name
// race conditions will occur when using multiple goroutines // There really ought to be to be a better way...
func (entry Entry) log(level Level, msg string) { func getPackageName(f string) string {
var buffer *bytes.Buffer for {
lastPeriod := strings.LastIndex(f, ".")
// Default to now, but allow users to override if they want. lastSlash := strings.LastIndex(f, "/")
// if lastPeriod > lastSlash {
// We don't have to worry about polluting future calls to Entry#log() f = f[:lastPeriod]
// with this assignment because this function is declared with a } else {
// non-pointer receiver. break
if entry.Time.IsZero() { }
entry.Time = time.Now()
} }
entry.Level = level return f
entry.Message = msg }
entry.fireHooks() // getCaller retrieves the name of the first non-logrus calling function
func getCaller() *runtime.Frame {
// cache this package's fully-qualified name
callerInitOnce.Do(func() {
pcs := make([]uintptr, maximumCallerDepth)
_ = runtime.Callers(0, pcs)
buffer = bufferPool.Get().(*bytes.Buffer) // dynamic get the package name and the minimum caller depth
for i := 0; i < maximumCallerDepth; i++ {
funcName := runtime.FuncForPC(pcs[i]).Name()
if strings.Contains(funcName, "getCaller") {
logrusPackage = getPackageName(funcName)
break
}
}
minimumCallerDepth = knownLogrusFrames
})
// Restrict the lookback frames to avoid runaway lookups
pcs := make([]uintptr, maximumCallerDepth)
depth := runtime.Callers(minimumCallerDepth, pcs)
frames := runtime.CallersFrames(pcs[:depth])
for f, again := frames.Next(); again; f, again = frames.Next() {
pkg := getPackageName(f.Function)
// If the caller isn't part of this package, we're done
if pkg != logrusPackage {
return &f //nolint:scopelint
}
}
// if we got here, we failed to find the caller's context
return nil
}
func (entry Entry) HasCaller() (has bool) {
return entry.Logger != nil &&
entry.Logger.ReportCaller &&
entry.Caller != nil
}
func (entry *Entry) log(level Level, msg string) {
var buffer *bytes.Buffer
newEntry := entry.Dup()
if newEntry.Time.IsZero() {
newEntry.Time = time.Now()
}
newEntry.Level = level
newEntry.Message = msg
newEntry.Logger.mu.Lock()
reportCaller := newEntry.Logger.ReportCaller
newEntry.Logger.mu.Unlock()
if reportCaller {
newEntry.Caller = getCaller()
}
newEntry.fireHooks()
buffer = getBuffer()
defer func() {
newEntry.Buffer = nil
putBuffer(buffer)
}()
buffer.Reset() buffer.Reset()
defer bufferPool.Put(buffer) newEntry.Buffer = buffer
entry.Buffer = buffer
entry.write() newEntry.write()
entry.Buffer = nil newEntry.Buffer = nil
// To avoid Entry#log() returning a value that only would make sense for // To avoid Entry#log() returning a value that only would make sense for
// panic() to use in Entry#Panic(), we avoid the allocation by checking // panic() to use in Entry#Panic(), we avoid the allocation by checking
// directly here. // directly here.
if level <= PanicLevel { if level <= PanicLevel {
panic(&entry) panic(newEntry)
} }
} }
func (entry *Entry) fireHooks() { func (entry *Entry) fireHooks() {
var tmpHooks LevelHooks
entry.Logger.mu.Lock() entry.Logger.mu.Lock()
defer entry.Logger.mu.Unlock() tmpHooks = make(LevelHooks, len(entry.Logger.Hooks))
err := entry.Logger.Hooks.Fire(entry.Level, entry) for k, v := range entry.Logger.Hooks {
tmpHooks[k] = v
}
entry.Logger.mu.Unlock()
err := tmpHooks.Fire(entry.Level, entry)
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err) fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err)
} }
} }
func (entry *Entry) write() { func (entry *Entry) write() {
entry.Logger.mu.Lock()
defer entry.Logger.mu.Unlock()
serialized, err := entry.Logger.Formatter.Format(entry) serialized, err := entry.Logger.Formatter.Format(entry)
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err) fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
} else { return
_, err = entry.Logger.Out.Write(serialized)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
} }
entry.Logger.mu.Lock()
defer entry.Logger.mu.Unlock()
if _, err := entry.Logger.Out.Write(serialized); err != nil {
fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
} }
} }
func (entry *Entry) Debug(args ...interface{}) { func (entry *Entry) Log(level Level, args ...interface{}) {
if entry.Logger.IsLevelEnabled(DebugLevel) { if entry.Logger.IsLevelEnabled(level) {
entry.log(DebugLevel, fmt.Sprint(args...)) entry.log(level, fmt.Sprint(args...))
} }
} }
func (entry *Entry) Trace(args ...interface{}) {
entry.Log(TraceLevel, args...)
}
func (entry *Entry) Debug(args ...interface{}) {
entry.Log(DebugLevel, args...)
}
func (entry *Entry) Print(args ...interface{}) { func (entry *Entry) Print(args ...interface{}) {
entry.Info(args...) entry.Info(args...)
} }
func (entry *Entry) Info(args ...interface{}) { func (entry *Entry) Info(args ...interface{}) {
if entry.Logger.IsLevelEnabled(InfoLevel) { entry.Log(InfoLevel, args...)
entry.log(InfoLevel, fmt.Sprint(args...))
}
} }
func (entry *Entry) Warn(args ...interface{}) { func (entry *Entry) Warn(args ...interface{}) {
if entry.Logger.IsLevelEnabled(WarnLevel) { entry.Log(WarnLevel, args...)
entry.log(WarnLevel, fmt.Sprint(args...))
}
} }
func (entry *Entry) Warning(args ...interface{}) { func (entry *Entry) Warning(args ...interface{}) {
@@ -189,37 +319,36 @@ func (entry *Entry) Warning(args ...interface{}) {
} }
func (entry *Entry) Error(args ...interface{}) { func (entry *Entry) Error(args ...interface{}) {
if entry.Logger.IsLevelEnabled(ErrorLevel) { entry.Log(ErrorLevel, args...)
entry.log(ErrorLevel, fmt.Sprint(args...))
}
} }
func (entry *Entry) Fatal(args ...interface{}) { func (entry *Entry) Fatal(args ...interface{}) {
if entry.Logger.IsLevelEnabled(FatalLevel) { entry.Log(FatalLevel, args...)
entry.log(FatalLevel, fmt.Sprint(args...)) entry.Logger.Exit(1)
}
Exit(1)
} }
func (entry *Entry) Panic(args ...interface{}) { func (entry *Entry) Panic(args ...interface{}) {
if entry.Logger.IsLevelEnabled(PanicLevel) { entry.Log(PanicLevel, args...)
entry.log(PanicLevel, fmt.Sprint(args...))
}
panic(fmt.Sprint(args...))
} }
// Entry Printf family functions // Entry Printf family functions
func (entry *Entry) Debugf(format string, args ...interface{}) { func (entry *Entry) Logf(level Level, format string, args ...interface{}) {
if entry.Logger.IsLevelEnabled(DebugLevel) { if entry.Logger.IsLevelEnabled(level) {
entry.Debug(fmt.Sprintf(format, args...)) entry.Log(level, fmt.Sprintf(format, args...))
} }
} }
func (entry *Entry) Tracef(format string, args ...interface{}) {
entry.Logf(TraceLevel, format, args...)
}
func (entry *Entry) Debugf(format string, args ...interface{}) {
entry.Logf(DebugLevel, format, args...)
}
func (entry *Entry) Infof(format string, args ...interface{}) { func (entry *Entry) Infof(format string, args ...interface{}) {
if entry.Logger.IsLevelEnabled(InfoLevel) { entry.Logf(InfoLevel, format, args...)
entry.Info(fmt.Sprintf(format, args...))
}
} }
func (entry *Entry) Printf(format string, args ...interface{}) { func (entry *Entry) Printf(format string, args ...interface{}) {
@@ -227,9 +356,7 @@ func (entry *Entry) Printf(format string, args ...interface{}) {
} }
func (entry *Entry) Warnf(format string, args ...interface{}) { func (entry *Entry) Warnf(format string, args ...interface{}) {
if entry.Logger.IsLevelEnabled(WarnLevel) { entry.Logf(WarnLevel, format, args...)
entry.Warn(fmt.Sprintf(format, args...))
}
} }
func (entry *Entry) Warningf(format string, args ...interface{}) { func (entry *Entry) Warningf(format string, args ...interface{}) {
@@ -237,36 +364,36 @@ func (entry *Entry) Warningf(format string, args ...interface{}) {
} }
func (entry *Entry) Errorf(format string, args ...interface{}) { func (entry *Entry) Errorf(format string, args ...interface{}) {
if entry.Logger.IsLevelEnabled(ErrorLevel) { entry.Logf(ErrorLevel, format, args...)
entry.Error(fmt.Sprintf(format, args...))
}
} }
func (entry *Entry) Fatalf(format string, args ...interface{}) { func (entry *Entry) Fatalf(format string, args ...interface{}) {
if entry.Logger.IsLevelEnabled(FatalLevel) { entry.Logf(FatalLevel, format, args...)
entry.Fatal(fmt.Sprintf(format, args...)) entry.Logger.Exit(1)
}
Exit(1)
} }
func (entry *Entry) Panicf(format string, args ...interface{}) { func (entry *Entry) Panicf(format string, args ...interface{}) {
if entry.Logger.IsLevelEnabled(PanicLevel) { entry.Logf(PanicLevel, format, args...)
entry.Panic(fmt.Sprintf(format, args...))
}
} }
// Entry Println family functions // Entry Println family functions
func (entry *Entry) Debugln(args ...interface{}) { func (entry *Entry) Logln(level Level, args ...interface{}) {
if entry.Logger.IsLevelEnabled(DebugLevel) { if entry.Logger.IsLevelEnabled(level) {
entry.Debug(entry.sprintlnn(args...)) entry.Log(level, entry.sprintlnn(args...))
} }
} }
func (entry *Entry) Traceln(args ...interface{}) {
entry.Logln(TraceLevel, args...)
}
func (entry *Entry) Debugln(args ...interface{}) {
entry.Logln(DebugLevel, args...)
}
func (entry *Entry) Infoln(args ...interface{}) { func (entry *Entry) Infoln(args ...interface{}) {
if entry.Logger.IsLevelEnabled(InfoLevel) { entry.Logln(InfoLevel, args...)
entry.Info(entry.sprintlnn(args...))
}
} }
func (entry *Entry) Println(args ...interface{}) { func (entry *Entry) Println(args ...interface{}) {
@@ -274,9 +401,7 @@ func (entry *Entry) Println(args ...interface{}) {
} }
func (entry *Entry) Warnln(args ...interface{}) { func (entry *Entry) Warnln(args ...interface{}) {
if entry.Logger.IsLevelEnabled(WarnLevel) { entry.Logln(WarnLevel, args...)
entry.Warn(entry.sprintlnn(args...))
}
} }
func (entry *Entry) Warningln(args ...interface{}) { func (entry *Entry) Warningln(args ...interface{}) {
@@ -284,22 +409,16 @@ func (entry *Entry) Warningln(args ...interface{}) {
} }
func (entry *Entry) Errorln(args ...interface{}) { func (entry *Entry) Errorln(args ...interface{}) {
if entry.Logger.IsLevelEnabled(ErrorLevel) { entry.Logln(ErrorLevel, args...)
entry.Error(entry.sprintlnn(args...))
}
} }
func (entry *Entry) Fatalln(args ...interface{}) { func (entry *Entry) Fatalln(args ...interface{}) {
if entry.Logger.IsLevelEnabled(FatalLevel) { entry.Logln(FatalLevel, args...)
entry.Fatal(entry.sprintlnn(args...)) entry.Logger.Exit(1)
}
Exit(1)
} }
func (entry *Entry) Panicln(args ...interface{}) { func (entry *Entry) Panicln(args ...interface{}) {
if entry.Logger.IsLevelEnabled(PanicLevel) { entry.Logln(PanicLevel, args...)
entry.Panic(entry.sprintlnn(args...))
}
} }
// Sprintlnn => Sprint no newline. This is to get the behavior of how // Sprintlnn => Sprint no newline. This is to get the behavior of how

View File

@@ -1,6 +1,7 @@
package logrus package logrus
import ( import (
"context"
"io" "io"
"time" "time"
) )
@@ -24,6 +25,12 @@ func SetFormatter(formatter Formatter) {
std.SetFormatter(formatter) std.SetFormatter(formatter)
} }
// SetReportCaller sets whether the standard logger will include the calling
// method as a field.
func SetReportCaller(include bool) {
std.SetReportCaller(include)
}
// SetLevel sets the standard logger level. // SetLevel sets the standard logger level.
func SetLevel(level Level) { func SetLevel(level Level) {
std.SetLevel(level) std.SetLevel(level)
@@ -49,6 +56,11 @@ func WithError(err error) *Entry {
return std.WithField(ErrorKey, err) return std.WithField(ErrorKey, err)
} }
// WithContext creates an entry from the standard logger and adds a context to it.
func WithContext(ctx context.Context) *Entry {
return std.WithContext(ctx)
}
// WithField creates an entry from the standard logger and adds a field to // WithField creates an entry from the standard logger and adds a field to
// it. If you want multiple fields, use `WithFields`. // it. If you want multiple fields, use `WithFields`.
// //
@@ -68,7 +80,7 @@ func WithFields(fields Fields) *Entry {
return std.WithFields(fields) return std.WithFields(fields)
} }
// WithTime creats an entry from the standard logger and overrides the time of // WithTime creates an entry from the standard logger and overrides the time of
// logs generated with it. // logs generated with it.
// //
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal // Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
@@ -77,6 +89,11 @@ func WithTime(t time.Time) *Entry {
return std.WithTime(t) return std.WithTime(t)
} }
// Trace logs a message at level Trace on the standard logger.
func Trace(args ...interface{}) {
std.Trace(args...)
}
// Debug logs a message at level Debug on the standard logger. // Debug logs a message at level Debug on the standard logger.
func Debug(args ...interface{}) { func Debug(args ...interface{}) {
std.Debug(args...) std.Debug(args...)
@@ -117,6 +134,56 @@ func Fatal(args ...interface{}) {
std.Fatal(args...) std.Fatal(args...)
} }
// TraceFn logs a message from a func at level Trace on the standard logger.
func TraceFn(fn LogFunction) {
std.TraceFn(fn)
}
// DebugFn logs a message from a func at level Debug on the standard logger.
func DebugFn(fn LogFunction) {
std.DebugFn(fn)
}
// PrintFn logs a message from a func at level Info on the standard logger.
func PrintFn(fn LogFunction) {
std.PrintFn(fn)
}
// InfoFn logs a message from a func at level Info on the standard logger.
func InfoFn(fn LogFunction) {
std.InfoFn(fn)
}
// WarnFn logs a message from a func at level Warn on the standard logger.
func WarnFn(fn LogFunction) {
std.WarnFn(fn)
}
// WarningFn logs a message from a func at level Warn on the standard logger.
func WarningFn(fn LogFunction) {
std.WarningFn(fn)
}
// ErrorFn logs a message from a func at level Error on the standard logger.
func ErrorFn(fn LogFunction) {
std.ErrorFn(fn)
}
// PanicFn logs a message from a func at level Panic on the standard logger.
func PanicFn(fn LogFunction) {
std.PanicFn(fn)
}
// FatalFn logs a message from a func at level Fatal on the standard logger then the process will exit with status set to 1.
func FatalFn(fn LogFunction) {
std.FatalFn(fn)
}
// Tracef logs a message at level Trace on the standard logger.
func Tracef(format string, args ...interface{}) {
std.Tracef(format, args...)
}
// Debugf logs a message at level Debug on the standard logger. // Debugf logs a message at level Debug on the standard logger.
func Debugf(format string, args ...interface{}) { func Debugf(format string, args ...interface{}) {
std.Debugf(format, args...) std.Debugf(format, args...)
@@ -157,6 +224,11 @@ func Fatalf(format string, args ...interface{}) {
std.Fatalf(format, args...) std.Fatalf(format, args...)
} }
// Traceln logs a message at level Trace on the standard logger.
func Traceln(args ...interface{}) {
std.Traceln(args...)
}
// Debugln logs a message at level Debug on the standard logger. // Debugln logs a message at level Debug on the standard logger.
func Debugln(args ...interface{}) { func Debugln(args ...interface{}) {
std.Debugln(args...) std.Debugln(args...)

View File

@@ -9,6 +9,8 @@ const (
FieldKeyLevel = "level" FieldKeyLevel = "level"
FieldKeyTime = "time" FieldKeyTime = "time"
FieldKeyLogrusError = "logrus_error" FieldKeyLogrusError = "logrus_error"
FieldKeyFunc = "func"
FieldKeyFile = "file"
) )
// The Formatter interface is used to implement a custom Formatter. It takes an // The Formatter interface is used to implement a custom Formatter. It takes an
@@ -25,7 +27,7 @@ type Formatter interface {
Format(*Entry) ([]byte, error) Format(*Entry) ([]byte, error)
} }
// This is to not silently overwrite `time`, `msg` and `level` fields when // This is to not silently overwrite `time`, `msg`, `func` and `level` fields when
// dumping it. If this code wasn't there doing: // dumping it. If this code wasn't there doing:
// //
// logrus.WithField("level", 1).Info("hello") // logrus.WithField("level", 1).Info("hello")
@@ -37,7 +39,7 @@ type Formatter interface {
// //
// It's not exported because it's still using Data in an opinionated way. It's to // It's not exported because it's still using Data in an opinionated way. It's to
// avoid code duplication between the two default formatters. // avoid code duplication between the two default formatters.
func prefixFieldClashes(data Fields, fieldMap FieldMap) { func prefixFieldClashes(data Fields, fieldMap FieldMap, reportCaller bool) {
timeKey := fieldMap.resolve(FieldKeyTime) timeKey := fieldMap.resolve(FieldKeyTime)
if t, ok := data[timeKey]; ok { if t, ok := data[timeKey]; ok {
data["fields."+timeKey] = t data["fields."+timeKey] = t
@@ -61,4 +63,16 @@ func prefixFieldClashes(data Fields, fieldMap FieldMap) {
data["fields."+logrusErrKey] = l data["fields."+logrusErrKey] = l
delete(data, logrusErrKey) delete(data, logrusErrKey)
} }
// If reportCaller is not set, 'func' will not conflict.
if reportCaller {
funcKey := fieldMap.resolve(FieldKeyFunc)
if l, ok := data[funcKey]; ok {
data["fields."+funcKey] = l
}
fileKey := fieldMap.resolve(FieldKeyFile)
if l, ok := data[fileKey]; ok {
data["fields."+fileKey] = l
}
}
} }

View File

@@ -2,9 +2,9 @@ module github.com/sirupsen/logrus
require ( require (
github.com/davecgh/go-spew v1.1.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect
github.com/konsorten/go-windows-terminal-sequences v0.0.0-20180402223658-b729f2633dfe
github.com/pmezard/go-difflib v1.0.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/testify v1.2.2 github.com/stretchr/testify v1.2.2
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793 golang.org/x/sys v0.0.0-20191026070338-33540a1f6037
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33
) )
go 1.13

Some files were not shown because too many files have changed in this diff Show More