From 9afaa7fef0af6a612be45cfc7ae614a7959c4b7f Mon Sep 17 00:00:00 2001 From: Abhinandan Prativadi Date: Thu, 12 Oct 2017 10:26:25 -0700 Subject: [PATCH] Refactor and Restore changes Signed-off-by: Abhinandan Prativadi --- Makefile | 4 +- api/api.go | 2 +- api/types.go | 28 +- client/network.go | 4 +- client/types.go | 8 +- .../cni_.go => cni_server/cni_server.go} | 2 +- cmd/{cni_/flags_.go => cni_server/flags.go} | 8 +- cmd/dnet/cmd.go | 8 +- cmd/dnet/dnet.go | 80 +- cmd/dnet/flags.go | 8 +- {cni => cmd/dnet_cni}/main.go | 3 +- config/config.go | 5 +- controller.go | 3 - driverapi/driverapi.go | 1 + drivers/overlay/joinleave.go | 7 +- drivers/overlay/ov_serf.go | 2 +- install/Dockerfile.cniserver | 1 - install/cniserver.sh | 4 +- install/config_working.toml | 17 - install/dnet.sh | 2 +- install/net.conf | 5 - libnetwork_internal_test.go | 2 +- netutils/httputils.go | 10 +- pkg/cniapi/api.go | 158 --- pkg/server/cniserver/cni_server.go | 66 -- provider/cni/cniapi/api.go | 240 +++++ .../cni/server}/add_pod.go | 100 +- provider/cni/server/cni_server.go | 117 +++ .../cni/server}/cni_utils.go | 44 - .../cni/server}/del_pod.go | 63 +- provider/cni/store/cni_store.go | 113 +++ provider/provider.go | 10 + sandbox.go | 11 + sandbox_store.go | 18 +- vendor.conf | 1 + .../Microsoft/hcsshim/mksyscall_windows.go | 934 ------------------ vendor/github.com/miekg/dns/types_generate.go | 266 ----- vendor/golang.org/x/sys/unix/mkpost.go | 62 -- vendor/golang.org/x/sys/unix/types_darwin.go | 250 ----- .../golang.org/x/sys/unix/types_dragonfly.go | 242 ----- vendor/golang.org/x/sys/unix/types_freebsd.go | 353 ------- vendor/golang.org/x/sys/unix/types_linux.go | 450 --------- vendor/golang.org/x/sys/unix/types_netbsd.go | 232 ----- vendor/golang.org/x/sys/unix/types_openbsd.go | 244 ----- vendor/golang.org/x/sys/unix/types_solaris.go | 262 ----- 45 files changed, 722 insertions(+), 3728 deletions(-) rename cmd/{cni_/cni_.go => cni_server/cni_server.go} (87%) rename cmd/{cni_/flags_.go => cni_server/flags.go} (82%) rename {cni => cmd/dnet_cni}/main.go (93%) delete mode 100644 install/config_working.toml delete mode 100644 install/net.conf delete mode 100644 pkg/cniapi/api.go delete mode 100644 pkg/server/cniserver/cni_server.go create mode 100644 provider/cni/cniapi/api.go rename {pkg/server/cniserver => provider/cni/server}/add_pod.go (57%) create mode 100644 provider/cni/server/cni_server.go rename {pkg/server/cniserver => provider/cni/server}/cni_utils.go (53%) rename {pkg/server/cniserver => provider/cni/server}/del_pod.go (51%) create mode 100644 provider/cni/store/cni_store.go create mode 100644 provider/provider.go delete mode 100644 vendor/github.com/Microsoft/hcsshim/mksyscall_windows.go delete mode 100644 vendor/github.com/miekg/dns/types_generate.go delete mode 100644 vendor/golang.org/x/sys/unix/mkpost.go delete mode 100644 vendor/golang.org/x/sys/unix/types_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/types_dragonfly.go delete mode 100644 vendor/golang.org/x/sys/unix/types_freebsd.go delete mode 100644 vendor/golang.org/x/sys/unix/types_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/types_netbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/types_openbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/types_solaris.go diff --git a/Makefile b/Makefile index 54f1a5433d..6c668f85f3 100644 --- a/Makefile +++ b/Makefile @@ -36,8 +36,8 @@ build-local: @mkdir -p "bin" go build -tags experimental -o "bin/dnet" ./cmd/dnet go build -o "bin/docker-proxy" ./cmd/proxy - go build -o "bin/cniserver" ./cmd/cni_ - go build -o "bin/cnictl" ./cni/ + go build -o "bin/cniserver" ./cmd/cni_server + go build -o "bin/cnictl" ./cmd/dnet_cni/ clean: @echo "🐳 $@" @if [ -d bin ]; then \ diff --git a/api/api.go b/api/api.go index 0896d2ceb3..d4c2467dd5 100644 --- a/api/api.go +++ b/api/api.go @@ -712,6 +712,7 @@ func procAttachBackend(c libnetwork.NetworkController, vars map[string]string, b if err != nil { return nil, convertNetworkError(err) } + if bk.SandboxKey != "" { err = sb.SetKey(bk.SandboxKey) if err != nil { @@ -738,7 +739,6 @@ func procDetachBackend(c libnetwork.NetworkController, vars map[string]string, b if err != nil { return nil, convertNetworkError(err) } - return nil, &successResponse } diff --git a/api/types.go b/api/types.go index 834acc8b8d..2cccc1e5c5 100644 --- a/api/types.go +++ b/api/types.go @@ -96,12 +96,6 @@ type serviceDelete struct { Force bool `json:"force"` } -// extraHost represents the extra host object -type extraHost struct { - Name string `json:"name"` - Address string `json:"address"` -} - // endpointInfo contants the endpoint info for https response message on endpoint creation type endpointInfo struct { ID string `json:"id"` @@ -112,6 +106,28 @@ type endpointInfo struct { GatewayIPv6 net.IP `json:"gateway_ipv6"` } +// extraHost represents the extra host object +type extraHost struct { + Name string `json:"name"` + Address string `json:"address"` +} + +// SandboxMetadata holds the metadata related to sandox (config) +type SandboxMetadata struct { + ContainerID string `json:"container_id"` + HostName string `json:"host_name"` + DomainName string `json:"domain_name"` + HostsPath string `json:"hosts_path"` + ResolvConfPath string `json:"resolv_conf_path"` + DNS []string `json:"dns"` + ExtraHosts []extraHost `json:"extra_hosts"` + UseExternalKey bool `json:"use_external_key"` + UseDefaultSandbox bool `json:"use_default_sandbox"` + ExposedPorts []types.TransportPort `json:"exposed_ports"` + PortMapping []types.PortBinding `json:"port_mapping"` + ExternalKey string `json:"external_key"` +} + func getEndpointInfo(ep libnetwork.Endpoint) endpointInfo { epInfo := endpointInfo{ID: ep.ID()} diff --git a/client/network.go b/client/network.go index 808d19831a..27ea1bd52c 100644 --- a/client/network.go +++ b/client/network.go @@ -71,9 +71,9 @@ func (cli *NetworkCli) CmdNetworkCreate(chain string, args ...string) error { } } - var icList []ipamConf + var icList []IPAMConf if *flSubnet != "" { - ic := ipamConf{ + ic := IPAMConf{ PreferredPool: *flSubnet, } diff --git a/client/types.go b/client/types.go index 9421b93f12..1b5c238b67 100644 --- a/client/types.go +++ b/client/types.go @@ -35,7 +35,9 @@ type SandboxResource struct { /*********** Body types ************/ -type ipamConf struct { + +// IPAMConf is the ipam configution used during network create +type IPAMConf struct { PreferredPool string SubPool string Gateway string @@ -47,7 +49,7 @@ type NetworkCreate struct { Name string `json:"name"` ID string `json:"id"` NetworkType string `json:"network_type"` - IPv4Conf []ipamConf `json:"ipv4_configuration"` + IPv4Conf []IPAMConf `json:"ipv4_configuration"` DriverOpts map[string]string `json:"driver_opts"` NetworkOpts map[string]string `json:"network_opts"` } @@ -102,7 +104,7 @@ type sandboxParentUpdate struct { Address string `json:"address"` } -// endpointInfo contants the endpoint info for http response message on endpoint creation +// EndpointInfo contants the endpoint info for http response message on endpoint creation type EndpointInfo struct { ID string `json:"id"` Address net.IPNet `json:"address"` diff --git a/cmd/cni_/cni_.go b/cmd/cni_server/cni_server.go similarity index 87% rename from cmd/cni_/cni_.go rename to cmd/cni_server/cni_server.go index 00207b3d83..56272ec7d2 100644 --- a/cmd/cni_/cni_.go +++ b/cmd/cni_server/cni_server.go @@ -29,7 +29,7 @@ func cniApp(stdout, stderr io.Writer) error { app.Usage = "A cni side car for libnetwork daemon." app.Flags = cniserverFlags app.Before = processFlags - //app.Commands = cniCommands + //app.Commands = cniCommands // TODO: Add cni commands to improve debuggability app.Run(os.Args) return nil diff --git a/cmd/cni_/flags_.go b/cmd/cni_server/flags.go similarity index 82% rename from cmd/cni_/flags_.go rename to cmd/cni_server/flags.go index 5960490442..2f6b716f0c 100644 --- a/cmd/cni_/flags_.go +++ b/cmd/cni_server/flags.go @@ -5,8 +5,9 @@ import ( "os" "github.com/codegangsta/cli" - cniserver "github.com/docker/libnetwork/pkg/server/cniserver" "github.com/sirupsen/logrus" + + cniserver "github.com/docker/libnetwork/provider/cni/server" ) var ( @@ -42,13 +43,14 @@ func processFlags(c *cli.Context) error { cniService, err := cniserver.NewCniService(c.String("sock"), c.String("dnet-address"), c.String("dnet-port")) if err != nil { - return fmt.Errorf("faile to create cni service: %v", err) + return fmt.Errorf("failed to create cni service: %v", err) } serverCloseChan := make(chan struct{}) if err := cniService.InitCniService(serverCloseChan); err != nil { - fmt.Printf("Failed to initialize CNI server: \n", err) + logrus.Errorf("Failed to initialize CNI server: %v", err) os.Exit(1) } + // Wait on till the server closes <-serverCloseChan return nil } diff --git a/cmd/dnet/cmd.go b/cmd/dnet/cmd.go index 3727cf82fc..1c85cb788a 100644 --- a/cmd/dnet/cmd.go +++ b/cmd/dnet/cmd.go @@ -47,7 +47,7 @@ func runContainerCreate(c *cli.Context) { } sc := client.SandboxCreate{ContainerID: c.Args()[0]} - obj, _, err := netutils.ReadBody(epConn.conn.HttpCall("POST", "/sandboxes", sc, nil)) + obj, _, err := netutils.ReadBody(epConn.conn.HTTPCall("POST", "/sandboxes", sc, nil)) if err != nil { fmt.Printf("POST failed during create container: %v\n", err) os.Exit(1) @@ -72,7 +72,7 @@ func runContainerRm(c *cli.Context) { os.Exit(1) } - obj, _, err := netutils.ReadBody(epConn.conn.HttpCall("GET", "/sandboxes?partial-container-id="+c.Args()[0], nil, nil)) + obj, _, err := netutils.ReadBody(epConn.conn.HTTPCall("GET", "/sandboxes?partial-container-id="+c.Args()[0], nil, nil)) if err != nil { fmt.Printf("GET failed during container id lookup: %v\n", err) os.Exit(1) @@ -89,7 +89,7 @@ func runContainerRm(c *cli.Context) { os.Exit(1) } - _, _, err = netutils.ReadBody(epConn.conn.HttpCall("DELETE", "/sandboxes/"+sbList[0].ID, nil, nil)) + _, _, err = netutils.ReadBody(epConn.conn.HTTPCall("DELETE", "/sandboxes/"+sbList[0].ID, nil, nil)) if err != nil { fmt.Printf("DELETE of sandbox id %s failed: %v", sbList[0].ID, err) os.Exit(1) @@ -98,7 +98,7 @@ func runContainerRm(c *cli.Context) { func runDockerCommand(c *cli.Context, cmd string) { _, stdout, stderr := term.StdStreams() - oldcli := client.NewNetworkCli(stdout, stderr, epConn.conn.HttpCall) + oldcli := client.NewNetworkCli(stdout, stderr, epConn.conn.HTTPCall) var args []string args = append(args, cmd) if c.Bool("h") { diff --git a/cmd/dnet/dnet.go b/cmd/dnet/dnet.go index bb0a64dace..17524d613e 100644 --- a/cmd/dnet/dnet.go +++ b/cmd/dnet/dnet.go @@ -16,12 +16,15 @@ import ( "github.com/BurntSushi/toml" "github.com/codegangsta/cli" + "github.com/docker/docker/api/types/network" "github.com/docker/docker/opts" "github.com/docker/docker/pkg/discovery" "github.com/docker/docker/pkg/reexec" - - "github.com/docker/docker/api/types/network" "github.com/docker/docker/pkg/term" + "github.com/gorilla/mux" + "github.com/sirupsen/logrus" + "golang.org/x/net/context" + "github.com/docker/libnetwork" "github.com/docker/libnetwork/api" "github.com/docker/libnetwork/cluster" @@ -31,10 +34,9 @@ import ( "github.com/docker/libnetwork/netlabel" "github.com/docker/libnetwork/netutils" "github.com/docker/libnetwork/options" + "github.com/docker/libnetwork/provider" + "github.com/docker/libnetwork/provider/cni/cniapi" "github.com/docker/libnetwork/types" - "github.com/gorilla/mux" - "github.com/sirupsen/logrus" - "golang.org/x/net/context" ) const ( @@ -43,11 +45,12 @@ const ( // DefaultHTTPPort is the default http port used by dnet DefaultHTTPPort = 2389 // DefaultUnixSocket exported - DefaultUnixSocket = "/var/run/dnet.sock" - cfgFileEnv = "LIBNETWORK_CFG" - defaultCfgFile = "/etc/default/libnetwork.toml" - defaultHeartbeat = time.Duration(10) * time.Second - ttlFactor = 2 + DefaultUnixSocket = "/var/run/dnet.sock" + cfgFileEnv = "LIBNETWORK_CFG" + defaultCfgFile = "/etc/default/libnetwork.toml" + defaultHeartbeat = time.Duration(10) * time.Second + ttlFactor = 2 + defaultProviderTimeout = 120 // default time to fetch state from provider ) var epConn *dnetConnection @@ -241,7 +244,7 @@ func createDefaultNetwork(c libnetwork.NetworkController) { } type dnetConnection struct { - conn *netutils.HttpConnection + conn *netutils.HTTPConnection Orchestration *NetworkOrchestration configEvent chan cluster.ConfigEventType } @@ -254,7 +257,7 @@ type NetworkOrchestration struct { Peer string } -func (d *dnetConnection) dnetDaemon(cfgFile string) error { +func (d *dnetConnection) dnetDaemon(cfgFile string, provider string) error { if err := startTestDriver(); err != nil { return fmt.Errorf("failed to start test driver: %v", err) } @@ -264,10 +267,14 @@ func (d *dnetConnection) dnetDaemon(cfgFile string) error { if err == nil { cOptions, err = processConfig(cfg) if err != nil { - fmt.Errorf("failed to process config: %v", err) + return fmt.Errorf("failed to process config: %v", err) } } else { - logrus.Errorf("failed to parse config: %v", err) + return fmt.Errorf("failed to parse config: %v", err) + } + + if provider != "" { + cfg.Daemon.Provider = attachDnetProvider(provider) } bridgeConfig := options.Generic{ @@ -279,9 +286,19 @@ func (d *dnetConnection) dnetDaemon(cfgFile string) error { cOptions = append(cOptions, config.OptionDriverConfig("bridge", bridgeOption)) + // If this is a restore ,then fetch active sandboxes from api server. + if cfg.Daemon.Provider != nil { + sbOptions, err := fetchActiveSandboxes(cfg.Daemon.Provider) + if err != nil { + return err + } + if sbOptions != nil { + cOptions = append(cOptions, sbOptions) + } + } controller, err := libnetwork.New(cOptions...) if err != nil { - fmt.Println("Error starting dnetDaemon :", err) + fmt.Println("Error starting DnetDaemon :", err) return err } controller.SetClusterProvider(d) @@ -440,7 +457,7 @@ func newDnetConnection(val string) (*dnetConnection, error) { } return &dnetConnection{ - &netutils.HttpConnection{ + &netutils.HTTPConnection{ Proto: protoAddrParts[0], Addr: protoAddrParts[1], }, @@ -460,3 +477,34 @@ func ipamOption(bridgeName string) libnetwork.NetworkOption { } return nil } + +func attachDnetProvider(provider string) provider.DnetProvider { + switch provider { + case "cni": + return cniapi.NewDnetCniClient() + default: + return nil + } +} + +func fetchActiveSandboxes(provider provider.DnetProvider) (config.Option, error) { + x := time.Duration(2 * time.Second) + var err error + var sbOptions map[string]interface{} + for x < defaultProviderTimeout { + sbOptions, err = provider.FetchActiveSandboxes() + if err == nil { + goto success + } + logrus.Errorf("Retry:failed to fetch active sandbox: %b", err) + time.Sleep(x * time.Second) + x = x * 2 + } + return nil, fmt.Errorf("failed to fetch active sandbox: %b", err) +success: + logrus.Infof("Active sandboxes are: {%+v}", sbOptions) + if len(sbOptions) != 0 { + return config.OptionActiveSandboxes(sbOptions), nil + } + return nil, nil +} diff --git a/cmd/dnet/flags.go b/cmd/dnet/flags.go index a59bd9d1fd..dfb35806a3 100644 --- a/cmd/dnet/flags.go +++ b/cmd/dnet/flags.go @@ -33,6 +33,10 @@ var ( Value: "/etc/default/libnetwork.toml", Usage: "Configuration file", }, + cli.StringFlag{ + Name: "p, -provider-interface", + Usage: "Provider for Dnet. Accepted values cni", + }, } ) @@ -75,7 +79,9 @@ func processFlags(c *cli.Context) error { } if c.Bool("d") { - err = epConn.dnetDaemon(c.String("c")) + cfgFile := c.String("c") + provider := c.String("p") + err = epConn.dnetDaemon(cfgFile, provider) if err != nil { logrus.Errorf("dnet Daemon exited with an error : %v", err) os.Exit(1) diff --git a/cni/main.go b/cmd/dnet_cni/main.go similarity index 93% rename from cni/main.go rename to cmd/dnet_cni/main.go index 0ea758eaac..518532e59d 100644 --- a/cni/main.go +++ b/cmd/dnet_cni/main.go @@ -6,8 +6,9 @@ import ( "github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/version" - "github.com/docker/libnetwork/pkg/cniapi" log "github.com/sirupsen/logrus" + + "github.com/docker/libnetwork/provider/cni/cniapi" ) func cmdAdd(args *skel.CmdArgs) error { diff --git a/config/config.go b/config/config.go index 010e479a9b..96b394cff4 100644 --- a/config/config.go +++ b/config/config.go @@ -9,11 +9,13 @@ import ( "github.com/docker/docker/pkg/plugingetter" "github.com/docker/go-connections/tlsconfig" "github.com/docker/libkv/store" + "github.com/sirupsen/logrus" + "github.com/docker/libnetwork/cluster" "github.com/docker/libnetwork/datastore" "github.com/docker/libnetwork/netlabel" "github.com/docker/libnetwork/osl" - "github.com/sirupsen/logrus" + "github.com/docker/libnetwork/provider" ) const ( @@ -34,6 +36,7 @@ type Config struct { type DaemonCfg struct { Debug bool Experimental bool + Provider provider.DnetProvider DataDir string DefaultNetwork string DefaultGwNetwork string diff --git a/controller.go b/controller.go index c13c0f13e9..74002abcff 100644 --- a/controller.go +++ b/controller.go @@ -190,13 +190,11 @@ func New(cfgOptions ...config.Option) (NetworkController, error) { if err := c.initStores(); err != nil { return nil, err } - c.initDefaultGwNetwork() drvRegistry, err := drvregistry.New(c.getStore(datastore.LocalScope), c.getStore(datastore.GlobalScope), c.RegisterDriver, nil, c.cfg.PluginGetter) if err != nil { return nil, err } - for _, i := range getInitializers(c.cfg.Daemon.Experimental) { var dcfg map[string]interface{} @@ -236,7 +234,6 @@ func New(cfgOptions ...config.Option) (NetworkController, error) { c.sandboxCleanup(c.cfg.ActiveSandboxes) c.cleanupLocalEndpoints() c.networkCleanup() - if err := c.startExternalKeyListener(); err != nil { return nil, err } diff --git a/driverapi/driverapi.go b/driverapi/driverapi.go index 1acff58c14..22a19f9427 100644 --- a/driverapi/driverapi.go +++ b/driverapi/driverapi.go @@ -154,6 +154,7 @@ type JoinInfo interface { AddTableEntry(tableName string, key string, value []byte) error } +// LeaveInfo interface for object release during sandbox detach type LeaveInfo interface { // ReleaseAddress frees up allocated IP ReleaseAddress(net.IP) error diff --git a/drivers/overlay/joinleave.go b/drivers/overlay/joinleave.go index 7cf0a47710..3a1384f843 100644 --- a/drivers/overlay/joinleave.go +++ b/drivers/overlay/joinleave.go @@ -44,7 +44,7 @@ func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, return fmt.Errorf("could not find subnet for endpoint %s", eid) } - if n.hostAccess && s.gwIP == nil { + if s.gwIP == nil { gwIP, err := jinfo.RequestAddress(s.subnetIP) if err != nil { logrus.Errorf("RequestAddress failed %s %v", s.subnetIP.String(), err) @@ -245,13 +245,8 @@ func (d *driver) Leave(nid, eid string, linfo driverapi.LeaveInfo) error { } } -<<<<<<< 0cea43c346ddc660804aa04ad19eac5811d704e5 d.peerDelete(nid, eid, ep.addr.IP, ep.addr.Mask, ep.mac, net.ParseIP(d.advertiseAddress), true) -======= n.leaveSandbox(linfo) ->>>>>>> Make use of the RequestAddress feature for hostAccess overlay network - - n.leaveSandbox() return nil } diff --git a/drivers/overlay/ov_serf.go b/drivers/overlay/ov_serf.go index 64654b2b6e..b54ce09bdb 100644 --- a/drivers/overlay/ov_serf.go +++ b/drivers/overlay/ov_serf.go @@ -102,7 +102,7 @@ func (d *driver) notifyEvent(event ovNotify) { if !nw.hostAccess { return } - var snet *subnet = nil + var snet *subnet for _, s := range nw.subnets { if s.subnetIP.Contains(ep.addr.IP) { snet = s diff --git a/install/Dockerfile.cniserver b/install/Dockerfile.cniserver index 88d57776b0..87f07fb2c4 100644 --- a/install/Dockerfile.cniserver +++ b/install/Dockerfile.cniserver @@ -9,6 +9,5 @@ RUN apt-get update \ COPY bin/cniserver /var/libnetwork/bin/ COPY cniserver.sh /var/libnetwork/ COPY bin/cnictl /var/libnetwork/bin/ -COPY net.conf /var/libnetwork/config/ ENTRYPOINT ["/var/libnetwork/cniserver.sh"] diff --git a/install/cniserver.sh b/install/cniserver.sh index 35521f6f4f..59f4447b25 100755 --- a/install/cniserver.sh +++ b/install/cniserver.sh @@ -1,6 +1,6 @@ #!/bin/bash set -euo pipefail -cp /var/libnetwork/bin/cnictl /opt/cni/bin/libnetwork-cni -cp /var/libnetwork/config/net.conf /etc/cni/net.d/00-libnetwork-cni.conf +cp /var/libnetwork/bin/cnictl /opt/cni/bin/dnet-cni +echo ${DNET_CNI_CONF} > /etc/cni/net.d/00-dnet-cni.conf /var/libnetwork/bin/cniserver &> /home/libnetwork/cniserver.log diff --git a/install/config_working.toml b/install/config_working.toml deleted file mode 100644 index 9132939dac..0000000000 --- a/install/config_working.toml +++ /dev/null @@ -1,17 +0,0 @@ -title = "LibNetwork Configuration file" - -[daemon] - debug = true - labels = ["com.docker.network.driver.overlay.hostmode=true"] -[cluster] - discovery = "etcd://localhost:2379" -[datastore] - embedded = false -[datastore.client] - provider = "etcd" - Address = "localhost:2379" -[scopes] - [scopes.global] - [scopes.global.client] - provider = "etcd" - address = "localhost:2379" diff --git a/install/dnet.sh b/install/dnet.sh index f8832ef88b..b69d68d1a7 100755 --- a/install/dnet.sh +++ b/install/dnet.sh @@ -1,3 +1,3 @@ #!/bin/bash set -euo pipefail -/var/libnetwork/bin/dnet -d -c /var/libnetwork/config/config.toml &> /home/libnetwork/dnet.log +/var/libnetwork/bin/dnet -d -p cni -c /var/libnetwork/config/config.toml &> /home/libnetwork/dnet.log diff --git a/install/net.conf b/install/net.conf deleted file mode 100644 index a0d75136e2..0000000000 --- a/install/net.conf +++ /dev/null @@ -1,5 +0,0 @@ -{ - "cniVersion": "0.2.0", - "name": "orange", - "type": "libnetwork-cni" -} diff --git a/libnetwork_internal_test.go b/libnetwork_internal_test.go index 58742cf5e1..fb61e4fd5b 100644 --- a/libnetwork_internal_test.go +++ b/libnetwork_internal_test.go @@ -653,7 +653,7 @@ func (b *badDriver) EndpointOperInfo(nid, eid string) (map[string]interface{}, e func (b *badDriver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error { return fmt.Errorf("I will not allow any join") } -func (b *badDriver) Leave(nid, eid string) error { +func (b *badDriver) Leave(nid, eid string, linfo driverapi.LeaveInfo) error { return nil } func (b *badDriver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error { diff --git a/netutils/httputils.go b/netutils/httputils.go index efea888935..0243430ca4 100644 --- a/netutils/httputils.go +++ b/netutils/httputils.go @@ -9,16 +9,16 @@ import ( "net/http" ) -// HttpConnection holds the protocol and address info for http connection -type HttpConnection struct { +// HTTPConnection holds the protocol and address info for http connection +type HTTPConnection struct { // Proto holds the client protocol i.e. unix. Proto string // Addr holds the client address. Addr string } -// HttpCall is used to make a http call using httpconnection information -func (h *HttpConnection) HttpCall(method, path string, data interface{}, headers map[string][]string) (io.ReadCloser, http.Header, int, error) { +// HTTPCall is used to make a http call using httpconnection information +func (h *HTTPConnection) HTTPCall(method, path string, data interface{}, headers map[string][]string) (io.ReadCloser, http.Header, int, error) { var in io.Reader in, err := encodeData(data) if err != nil { @@ -34,7 +34,6 @@ func (h *HttpConnection) HttpCall(method, path string, data interface{}, headers req.URL.Host = h.Addr req.URL.Scheme = "http" - fmt.Printf("Requesting http: %+v", req) httpClient := &http.Client{} resp, err := httpClient.Do(req) statusCode := -1 @@ -87,6 +86,7 @@ func encodeData(data interface{}) (*bytes.Buffer, error) { return params, nil } +// ReadBody reads http body from stream func ReadBody(stream io.ReadCloser, hdr http.Header, statusCode int, err error) ([]byte, int, error) { if stream != nil { defer stream.Close() diff --git a/pkg/cniapi/api.go b/pkg/cniapi/api.go deleted file mode 100644 index f54c08b207..0000000000 --- a/pkg/cniapi/api.go +++ /dev/null @@ -1,158 +0,0 @@ -package cniapi - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net" - "net/http" - - "github.com/containernetworking/cni/pkg/skel" - "github.com/containernetworking/cni/pkg/types" - "github.com/containernetworking/cni/pkg/types/current" - "github.com/containernetworking/plugins/pkg/ns" - log "github.com/sirupsen/logrus" -) - -const ( - AddPodUrl = "/AddPod" - DelPodUrl = "/DelPod" - DnetCNISock = "/var/run/cniserver.sock" - PluginPath = "/run/libnetwork" -) - -type DnetCniClient struct { - url string - httpClient *http.Client -} - -type CniInfo struct { - ContainerID string - NetNS string - IfName string - NetConf types.NetConf -} - -func unixDial(proto, addr string) (conn net.Conn, err error) { - sock := DnetCNISock - return net.Dial("unix", sock) -} - -func NewDnetCniClient() *DnetCniClient { - c := new(DnetCniClient) - c.url = "http://localhost" - c.httpClient = &http.Client{ - Transport: &http.Transport{ - Dial: unixDial, - }, - } - return c -} - -// SetupPod setups up the sandbox and endpoint for the infra container in a pod -func (l *DnetCniClient) SetupPod(args *skel.CmdArgs) (*current.Result, error) { - var data current.Result - log.Infof("Received Setup Pod %+v", args) - podNetInfo, err := validatePodNetworkInfo(args) - if err != nil { - return nil, fmt.Errorf("failed to valid cni arguments, error: %v", err) - } - buf, err := json.Marshal(podNetInfo) - if err != nil { - return nil, err - } - body := bytes.NewBuffer(buf) - url := l.url + AddPodUrl - r, err := l.httpClient.Post(url, "application/json", body) - if err != nil { - return nil, err - } - defer r.Body.Close() - switch { - case r.StatusCode == int(404): - return nil, fmt.Errorf("page not found") - - case r.StatusCode == int(403): - return nil, fmt.Errorf("access denied") - - case r.StatusCode == int(500): - info, err := ioutil.ReadAll(r.Body) - if err != nil { - return nil, err - } - err = json.Unmarshal(info, &data) - if err != nil { - return nil, err - } - return &data, fmt.Errorf("Internal Server Error") - - case r.StatusCode != int(200): - log.Errorf("POST Status '%s' status code %d \n", r.Status, r.StatusCode) - return nil, fmt.Errorf("%s", r.Status) - } - - response, err := ioutil.ReadAll(r.Body) - if err != nil { - return nil, err - } - - err = json.Unmarshal(response, &data) - if err != nil { - return nil, err - } - return &data, nil -} - -// TearDownPod tears the sandbox and endpoint created for the infra -// container in the pod. -func (l *DnetCniClient) TearDownPod(args *skel.CmdArgs) error { - log.Infof("Received Teardown Pod request %+v", args) - podNetInfo, err := validatePodNetworkInfo(args) - if err != nil { - return fmt.Errorf("failed to valid cni arguments, error: %v", err) - } - buf, err := json.Marshal(podNetInfo) - if err != nil { - return err - } - body := bytes.NewBuffer(buf) - url := l.url + DelPodUrl - r, err := l.httpClient.Post(url, "application/json", body) - defer r.Body.Close() - if err != nil { - fmt.Printf("%v \n", err) - return err - } - - return nil -} - -func validatePodNetworkInfo(args *skel.CmdArgs) (*CniInfo, error) { - rt := new(CniInfo) - if args.ContainerID == "" { - return nil, fmt.Errorf("containerID empty") - } - rt.ContainerID = args.ContainerID - if args.Netns == "" { - return nil, fmt.Errorf("network namespace not present") - } - _, err := ns.GetNS(args.Netns) - if err != nil { - return nil, err - } - rt.NetNS = args.Netns - if args.IfName == "" { - rt.IfName = "eth1" - } else { - rt.IfName = args.IfName - } - var netConf struct { - types.NetConf - } - if err := json.Unmarshal(args.StdinData, &netConf); err != nil { - return nil, fmt.Errorf("failed to unmarshal network configuration :%v", err) - } - rt.NetConf = netConf.NetConf - return rt, nil -} diff --git a/pkg/server/cniserver/cni_server.go b/pkg/server/cniserver/cni_server.go deleted file mode 100644 index 3b887c456e..0000000000 --- a/pkg/server/cniserver/cni_server.go +++ /dev/null @@ -1,66 +0,0 @@ -package server - -import ( - "net" - "net/http" - "os" - "syscall" - - "github.com/docker/libnetwork/netutils" - "github.com/docker/libnetwork/pkg/cniapi" - "github.com/gorilla/mux" - log "github.com/sirupsen/logrus" -) - -const ( - CniServicePort = 9005 -) - -type CniService struct { - //TODO k8sClient *APIClient - - listenPath string - dnetConn *netutils.HttpConnection - sandboxIDStore map[string]string // containerID to sandboxID mapping - endpointIDStore map[string]string // containerID to endpointID mapping -} - -func NewCniService(sock string, dnetIP string, dnetPort string) (*CniService, error) { - dnetUrl := dnetIP + ":" + dnetPort - c := new(CniService) - c.dnetConn = &netutils.HttpConnection{Addr: dnetUrl, Proto: "tcp"} - c.listenPath = sock - c.sandboxIDStore = make(map[string]string) - c.endpointIDStore = make(map[string]string) - return c, nil -} - -// InitCniService initializes the cni server -func (c *CniService) InitCniService(serverCloseChan chan struct{}) error { - log.Infof("Starting CNI server") - // Create http handlers for add and delete pod - router := mux.NewRouter() - t := router.Headers("Content-Type", "application/json").Methods("POST").Subrouter() - t.HandleFunc(cniapi.AddPodUrl, MakeHTTPHandler(c, addPod)) - t.HandleFunc(cniapi.DelPodUrl, MakeHTTPHandler(c, deletePod)) - syscall.Unlink(c.listenPath) - os.MkdirAll(cniapi.PluginPath, 0700) - go func() { - l, err := net.ListenUnix("unix", &net.UnixAddr{Name: c.listenPath, Net: "unix"}) - if err != nil { - panic(err) - } - log.Infof("Libnetwork CNI plugin listening on on %s", c.listenPath) - http.Serve(l, router) - l.Close() - close(serverCloseChan) - }() - return nil -} - -func newCniService() *CniService { - c := new(CniService) - c.sandboxIDStore = make(map[string]string) - c.endpointIDStore = make(map[string]string) - return c -} diff --git a/provider/cni/cniapi/api.go b/provider/cni/cniapi/api.go new file mode 100644 index 0000000000..ec364e8c2a --- /dev/null +++ b/provider/cni/cniapi/api.go @@ -0,0 +1,240 @@ +package cniapi + +import ( + "bytes" + "encoding/json" + "fmt" + "io/ioutil" + "net" + "net/http" + "strings" + + "github.com/containernetworking/cni/pkg/skel" + "github.com/containernetworking/cni/pkg/types" + "github.com/containernetworking/cni/pkg/types/current" + "github.com/containernetworking/plugins/pkg/ns" + log "github.com/sirupsen/logrus" + + "github.com/docker/libnetwork" + "github.com/docker/libnetwork/api" +) + +const ( + // AddPodURL url endpoint to add pod + AddPodURL = "/AddPod" + // DelPodURL url endpoint to delete pod + DelPodURL = "/DelPod" + // GetActivePods url endpoint to fetch active pod sandboxes + GetActivePods = "/ActivePods" + // DnetCNISock is dnet cni sidecar sock file + DnetCNISock = "/var/run/cniserver.sock" +) + +// DnetCniClient is the cni client connection information +type DnetCniClient struct { + url string + httpClient *http.Client +} + +// NetworkConf is the cni network configuration information +type NetworkConf struct { + CNIVersion string `json:"cniVersion,omitempty"` + Name string `json:"name,omitempty"` + Type string `json:"type,omitempty"` + Capabilities map[string]bool `json:"capabilities,omitempty"` + IPAM *IPAMConf `json:"ipam,omitempty"` + DNS types.DNS `json:"dns"` +} + +// IPAMConf is the cni network IPAM configuration information +type IPAMConf struct { + Type string `json:"type,omitempty"` + PreferredPool string `json:"preferred-pool,omitempty"` + SubPool string `json:"sub-pool,omitempty"` + Gateway string `json:"gateway,omitempty"` +} + +// CniInfo represents the cni information for a cni transaction +type CniInfo struct { + ContainerID string + NetNS string + IfName string + NetConf NetworkConf + Metadata map[string]string +} + +func unixDial(proto, addr string) (conn net.Conn, err error) { + sock := DnetCNISock + return net.Dial("unix", sock) +} + +// NewDnetCniClient returns a well formed cni client +func NewDnetCniClient() *DnetCniClient { + c := new(DnetCniClient) + c.url = "http://localhost" + c.httpClient = &http.Client{ + Transport: &http.Transport{ + Dial: unixDial, + }, + } + return c +} + +// SetupPod setups up the sandbox and endpoint for the infra container in a pod +func (l *DnetCniClient) SetupPod(args *skel.CmdArgs) (*current.Result, error) { + var data current.Result + log.Infof("Sending Setup Pod request %+v", args) + podNetInfo, err := validatePodNetworkInfo(args, true) + if err != nil { + return nil, fmt.Errorf("failed to valid cni arguments, error: %v", err) + } + buf, err := json.Marshal(podNetInfo) + if err != nil { + return nil, err + } + body := bytes.NewBuffer(buf) + url := l.url + AddPodURL + r, err := l.httpClient.Post(url, "application/json", body) + if err != nil { + return nil, err + } + defer r.Body.Close() + switch { + case r.StatusCode == int(404): + return nil, fmt.Errorf("page not found") + + case r.StatusCode == int(403): + return nil, fmt.Errorf("access denied") + + case r.StatusCode == int(500): + info, err := ioutil.ReadAll(r.Body) + if err != nil { + return nil, err + } + err = json.Unmarshal(info, &data) + if err != nil { + return nil, err + } + return &data, fmt.Errorf("Internal Server Error") + + case r.StatusCode != int(200): + log.Errorf("POST Status '%s' status code %d \n", r.Status, r.StatusCode) + return nil, fmt.Errorf("%s", r.Status) + } + + response, err := ioutil.ReadAll(r.Body) + if err != nil { + return nil, err + } + + err = json.Unmarshal(response, &data) + if err != nil { + return nil, err + } + return &data, nil +} + +// TearDownPod tears the sandbox and endpoint created for the infra +// container in the pod. +func (l *DnetCniClient) TearDownPod(args *skel.CmdArgs) error { + log.Infof("Sending Teardown Pod request %+v", args) + podNetInfo, err := validatePodNetworkInfo(args, false) + if err != nil { + return fmt.Errorf("failed to validate cni arguments, error: %v", err) + } + buf, err := json.Marshal(podNetInfo) + if err != nil { + return err + } + body := bytes.NewBuffer(buf) + url := l.url + DelPodURL + r, err := l.httpClient.Post(url, "application/json", body) + if err != nil { + return err + } + defer r.Body.Close() + return nil +} + +// FetchActiveSandboxes returns a list of active pods and their sandboxIDs +func (l *DnetCniClient) FetchActiveSandboxes() (map[string]interface{}, error) { + log.Infof("Requesting for for active sandboxes") + var sandboxes map[string]api.SandboxMetadata + url := l.url + GetActivePods + r, err := l.httpClient.Get(url) + if err != nil { + return nil, fmt.Errorf("failed during http get :%v", err) + } + defer r.Body.Close() + response, err := ioutil.ReadAll(r.Body) + if err != nil { + return nil, err + } + err = json.Unmarshal(response, &sandboxes) + if err != nil { + return nil, fmt.Errorf("failed to decode http response: %v", err) + } + result := make(map[string]interface{}) + for sb, meta := range sandboxes { + result[sb] = parseConfigOptions(meta) + } + return result, nil +} + +func parseConfigOptions(meta api.SandboxMetadata) []libnetwork.SandboxOption { + var sbOptions []libnetwork.SandboxOption + if meta.UseExternalKey { + sbOptions = append(sbOptions, libnetwork.OptionUseExternalKey()) + } + if meta.ExternalKey != "" { + sbOptions = append(sbOptions, libnetwork.OptionExternalKey(meta.ExternalKey)) + } + return sbOptions +} + +func validatePodNetworkInfo(args *skel.CmdArgs, add bool) (*CniInfo, error) { + rt := new(CniInfo) + if args.ContainerID == "" { + return nil, fmt.Errorf("containerID empty") + } + rt.ContainerID = args.ContainerID + if add { + if args.Netns == "" { + return nil, fmt.Errorf("network namespace not present") + } + _, err := ns.GetNS(args.Netns) + if err != nil { + return nil, err + } + rt.NetNS = args.Netns + } + if args.IfName == "" { + rt.IfName = "eth1" + } else { + rt.IfName = args.IfName + } + var netConf struct { + NetworkConf + } + if err := json.Unmarshal(args.StdinData, &netConf); err != nil { + return nil, fmt.Errorf("failed to unmarshal network configuration :%v", err) + } + rt.NetConf = netConf.NetworkConf + if args.Args != "" { + rt.Metadata = getMetadataFromArgs(args.Args) + } + return rt, nil +} + +func getMetadataFromArgs(args string) map[string]string { + m := make(map[string]string) + for _, a := range strings.Split(args, ";") { + if strings.Contains(a, "=") { + kvPair := strings.Split(a, "=") + m[strings.TrimSpace(kvPair[0])] = strings.TrimSpace(kvPair[1]) + } else { + m[a] = "" + } + } + return m +} diff --git a/pkg/server/cniserver/add_pod.go b/provider/cni/server/add_pod.go similarity index 57% rename from pkg/server/cniserver/add_pod.go rename to provider/cni/server/add_pod.go index 2a79165a13..981cdba121 100644 --- a/pkg/server/cniserver/add_pod.go +++ b/provider/cni/server/add_pod.go @@ -8,12 +8,13 @@ import ( "net" "net/http" "reflect" + "strings" - "github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types/current" "github.com/docker/libnetwork/client" "github.com/docker/libnetwork/netutils" - "github.com/docker/libnetwork/pkg/cniapi" + "github.com/docker/libnetwork/provider/cni/cniapi" + cnistore "github.com/docker/libnetwork/provider/cni/store" ) func addPod(w http.ResponseWriter, r *http.Request, c *CniService, vars map[string]string) (_ interface{}, retErr error) { @@ -23,18 +24,18 @@ func addPod(w http.ResponseWriter, r *http.Request, c *CniService, vars map[stri content, err := ioutil.ReadAll(r.Body) if err != nil { log.Errorf("Failed to read request: %v", err) - return nil, err + return cniInfo, err } if err := json.Unmarshal(content, &cniInfo); err != nil { - return nil, err + return cniInfo, err } log.Infof("Received add pod request %+v", cniInfo) // Create a Sandbox - sbID, err := c.createSandbox(cniInfo.ContainerID, cniInfo.NetNS) + sbConfig, sbID, err := c.createSandbox(cniInfo.ContainerID) if err != nil { - return nil, fmt.Errorf("failed to create sandbox for %q: %v", cniInfo.ContainerID, err) + return cniInfo, fmt.Errorf("failed to create sandbox for %q: %v", cniInfo.ContainerID, err) } defer func() { if retErr != nil { @@ -66,10 +67,17 @@ func addPod(w http.ResponseWriter, r *http.Request, c *CniService, vars map[stri } } }() - - c.endpointIDStore[cniInfo.ContainerID] = ep.ID - c.sandboxIDStore[cniInfo.ContainerID] = sbID - + cs := &cnistore.CniMetadata{ + PodName: cniInfo.Metadata["K8S_POD_NAME"], + PodNamespace: cniInfo.Metadata["K8S_POD_NAMESPACE"], + InfraContainerID: cniInfo.Metadata["K8S_POD_INFRA_CONTAINER_ID"], + SandboxID: sbID, + EndpointID: ep.ID, + SandboxMeta: cnistore.CopySandboxMetadata(sbConfig, cniInfo.NetNS), + } + if err := c.writeToStore(cs); err != nil { + return nil, fmt.Errorf("failed to write cni metadata to store: %v", err) + } result.Interfaces = append(result.Interfaces, ¤t.Interface{Name: "eth1", Mac: ep.MacAddress.String()}) if !reflect.DeepEqual(ep.Address, (net.IPNet{})) { result.IPs = append(result.IPs, ¤t.IPConfig{ @@ -85,61 +93,60 @@ func addPod(w http.ResponseWriter, r *http.Request, c *CniService, vars map[stri Gateway: ep.GatewayIPv6, }) } - //TODO (Abhi): Point IPs to the interface index + //TODO : Point IPs to the interface index return result, err } -func (c *CniService) createSandbox(ContainerID, netns string) (string, error) { +func (c *CniService) createSandbox(ContainerID string) (client.SandboxCreate, string, error) { sc := client.SandboxCreate{ContainerID: ContainerID, UseExternalKey: true} - obj, _, err := netutils.ReadBody(c.dnetConn.HttpCall("POST", "/sandboxes", sc, nil)) + obj, _, err := netutils.ReadBody(c.dnetConn.HTTPCall("POST", "/sandboxes", sc, nil)) if err != nil { - return "", err + return client.SandboxCreate{}, "", err } var replyID string err = json.Unmarshal(obj, &replyID) if err != nil { - return "", err + return client.SandboxCreate{}, "", err } - return replyID, nil + return sc, replyID, nil } -func (c *CniService) createEndpoint(ContainerID string, netConfig types.NetConf) (client.EndpointInfo, error) { +func (c *CniService) createEndpoint(ContainerID string, netConfig cniapi.NetworkConf) (client.EndpointInfo, error) { var ep client.EndpointInfo // Create network if it doesnt exist. Need to handle refcount to delete - // network on last pod delete. Also handle different network types and option + // network on last pod delete. if !c.networkExists(netConfig.Name) { - if err := c.createNetwork(netConfig.Name, "overlay"); err != nil { + if err := c.createNetwork(netConfig); err != nil && !strings.Contains(err.Error(), "already exists") { return ep, err } } sc := client.ServiceCreate{Name: ContainerID, Network: netConfig.Name, DisableResolution: true} - obj, _, err := netutils.ReadBody(c.dnetConn.HttpCall("POST", "/services", sc, nil)) + obj, _, err := netutils.ReadBody(c.dnetConn.HTTPCall("POST", "/services", sc, nil)) if err != nil { return ep, err } - log.Errorf("createEndpoint result:%+v\n", ep) err = json.Unmarshal(obj, &ep) return ep, err } func (c *CniService) endpointJoin(sandboxID, endpointID, netns string) (retErr error) { nc := client.ServiceAttach{SandboxID: sandboxID, SandboxKey: netns} - _, _, err := netutils.ReadBody(c.dnetConn.HttpCall("POST", "/services/"+endpointID+"/backend", nc, nil)) + _, _, err := netutils.ReadBody(c.dnetConn.HTTPCall("POST", "/services/"+endpointID+"/backend", nc, nil)) return err } -func (c *CniService) networkExists(networkName string) bool { - obj, statusCode, err := netutils.ReadBody(c.dnetConn.HttpCall("GET", "/networks?name="+networkName, nil, nil)) +func (c *CniService) networkExists(networkID string) bool { + obj, statusCode, err := netutils.ReadBody(c.dnetConn.HTTPCall("GET", "/networks?partial-id="+networkID, nil, nil)) if err != nil { - fmt.Printf("%s network does not exists \n", networkName) + log.Debugf("%s network does not exist:%v \n", networkID, err) return false } if statusCode != http.StatusOK { - fmt.Printf("%s network does not exists \n", networkName) + log.Debugf("%s network does not exist \n", networkID) return false } var list []*client.NetworkResource @@ -147,19 +154,32 @@ func (c *CniService) networkExists(networkName string) bool { if err != nil { return false } - fmt.Printf("%s network exists \n", networkName) return (len(list) != 0) } // createNetwork is a very simple utility to create a default network -// if not present. This needs to be expanded into a more full utility function -func (c *CniService) createNetwork(networkName string, driver string) error { - fmt.Printf("Creating a network %s driver: %s \n", networkName, driver) +// if not present. +//TODO: Need to watch out for parallel createnetwork calls on multiple nodes +func (c *CniService) createNetwork(netConf cniapi.NetworkConf) error { + log.Infof("Creating network %+v \n", netConf) driverOpts := make(map[string]string) driverOpts["hostaccess"] = "" - nc := client.NetworkCreate{Name: networkName, NetworkType: driver, + nc := client.NetworkCreate{Name: netConf.Name, ID: netConf.Name, NetworkType: getNetworkType(netConf.Type), DriverOpts: driverOpts} - obj, _, err := netutils.ReadBody(c.dnetConn.HttpCall("POST", "/networks", nc, nil)) + if ipam := netConf.IPAM; ipam != nil { + cfg := client.IPAMConf{} + if ipam.PreferredPool != "" { + cfg.PreferredPool = ipam.PreferredPool + } + if ipam.SubPool != "" { + cfg.SubPool = ipam.SubPool + } + if ipam.Gateway != "" { + cfg.Gateway = ipam.Gateway + } + nc.IPv4Conf = []client.IPAMConf{cfg} + } + obj, _, err := netutils.ReadBody(c.dnetConn.HTTPCall("POST", "/networks", nc, nil)) if err != nil { return err } @@ -168,5 +188,21 @@ func (c *CniService) createNetwork(networkName string, driver string) error { if err != nil { return err } + fmt.Printf("Network creation succeeded: %v", replyID) return nil } + +func getNetworkType(networkType string) string { + switch networkType { + case "dnet-overlay": + return "overlay" + case "dnet-bridge": + return "bridge" + case "dnet-ipvlan": + return "ipvlan" + case "dnet-macvlan": + return "macvlan" + default: + return "overlay" + } +} diff --git a/provider/cni/server/cni_server.go b/provider/cni/server/cni_server.go new file mode 100644 index 0000000000..418972613c --- /dev/null +++ b/provider/cni/server/cni_server.go @@ -0,0 +1,117 @@ +package server + +import ( + "fmt" + "net" + "net/http" + "syscall" + "time" + + "github.com/docker/libkv/store" + "github.com/docker/libkv/store/boltdb" + "github.com/gorilla/mux" + log "github.com/sirupsen/logrus" + + "github.com/docker/libnetwork/datastore" + "github.com/docker/libnetwork/netutils" + "github.com/docker/libnetwork/provider/cni/cniapi" + cnistore "github.com/docker/libnetwork/provider/cni/store" + "github.com/docker/libnetwork/types" +) + +// CniService hold the cni service information +type CniService struct { + listenPath string + dnetConn *netutils.HTTPConnection + store datastore.DataStore +} + +// NewCniService returns a new cni service instance +func NewCniService(sock string, dnetIP string, dnetPort string) (*CniService, error) { + dnetURL := dnetIP + ":" + dnetPort + c := new(CniService) + c.dnetConn = &netutils.HTTPConnection{Addr: dnetURL, Proto: "tcp"} + c.listenPath = sock + return c, nil +} + +// InitCniService initializes the cni server +func (c *CniService) InitCniService(serverCloseChan chan struct{}) error { + log.Infof("Starting CNI server") + router := mux.NewRouter() + t := router.Methods("POST").Subrouter() + t.HandleFunc(cniapi.AddPodURL, MakeHTTPHandler(c, addPod)) + t.HandleFunc(cniapi.DelPodURL, MakeHTTPHandler(c, deletePod)) + syscall.Unlink(c.listenPath) + boltdb.Register() + store, err := localStore() + if err != nil { + return fmt.Errorf("failed to initialize local store: %v", err) + } + c.store = store + go func() { + l, err := net.ListenUnix("unix", &net.UnixAddr{Name: c.listenPath, Net: "unix"}) + if err != nil { + panic(err) + } + log.Infof("Dnet CNI plugin listening on on %s", c.listenPath) + http.Serve(l, router) + l.Close() + close(serverCloseChan) + }() + return nil +} + +func localStore() (datastore.DataStore, error) { + return datastore.NewDataStore(datastore.LocalScope, &datastore.ScopeCfg{ + Client: datastore.ScopeClientCfg{ + Provider: string(store.BOLTDB), + Address: "/var/run/libnetwork/cnidb.db", + Config: &store.Config{ + Bucket: "cni-dnet", + ConnectionTimeout: 5 * time.Second, + }, + }, + }) +} + +// GetStore returns store instance +func (c *CniService) GetStore() datastore.DataStore { + return c.store +} + +func (c *CniService) getCniMetadataFromStore(podName, podNamespace string) (*cnistore.CniMetadata, error) { + store := c.GetStore() + if store == nil { + return nil, nil + } + cs := &cnistore.CniMetadata{PodName: podName, PodNamespace: podNamespace} + if err := store.GetObject(datastore.Key(cs.Key()...), cs); err != nil { + if err == datastore.ErrKeyNotFound { + return nil, fmt.Errorf("failed to find cni metadata from store for %s pod %s namespace: %v", + podName, podNamespace, err) + } + return nil, types.InternalErrorf("could not get pools config from store: %v", err) + } + return cs, nil +} + +func (c *CniService) writeToStore(cs *cnistore.CniMetadata) error { + store := c.GetStore() + if store == nil { + return nil + } + err := store.PutObjectAtomic(cs) + if err == datastore.ErrKeyModified { + return types.RetryErrorf("failed to perform atomic write (%v). retry might fix the error", err) + } + return err +} + +func (c *CniService) deleteFromStore(cs *cnistore.CniMetadata) error { + store := c.GetStore() + if store == nil { + return nil + } + return store.DeleteObjectAtomic(cs) +} diff --git a/pkg/server/cniserver/cni_utils.go b/provider/cni/server/cni_utils.go similarity index 53% rename from pkg/server/cniserver/cni_utils.go rename to provider/cni/server/cni_utils.go index 08d32a4d0b..62ffa86254 100644 --- a/pkg/server/cniserver/cni_utils.go +++ b/provider/cni/server/cni_utils.go @@ -1,9 +1,7 @@ package server import ( - "bytes" "encoding/json" - "io/ioutil" "net/http" "github.com/gorilla/mux" @@ -25,7 +23,6 @@ func MakeHTTPHandler(c *CniService, handlerFunc httpAPIFunc) http.HandlerFunc { if err != nil { // Log error log.Errorf("Handler for %s %s returned error: %s", r.Method, r.URL, err) - if resp == nil { // Send HTTP response http.Error(w, err.Error(), http.StatusInternalServerError) @@ -36,7 +33,6 @@ func MakeHTTPHandler(c *CniService, handlerFunc httpAPIFunc) http.HandlerFunc { http.Error(w, err.Error(), http.StatusInternalServerError) return } - w.WriteHeader(http.StatusInternalServerError) w.Write(content) } @@ -51,48 +47,8 @@ func MakeHTTPHandler(c *CniService, handlerFunc httpAPIFunc) http.HandlerFunc { } } -// writeJSON: writes the value v to the http response stream as json with standard -// json encoding. func writeJSON(w http.ResponseWriter, code int, v interface{}) error { - // Set content type as json w.Header().Set("Content-Type", "application/json") - // write the HTTP status code w.WriteHeader(code) - // Write the Json output return json.NewEncoder(w).Encode(v) } - -// UnknownAction is a catchall handler for additional driver functions -func UnknownAction(w http.ResponseWriter, r *http.Request) { - log.Infof("Unknown action at %q", r.URL.Path) - content, _ := ioutil.ReadAll(r.Body) - log.Infof("Body content: %s", string(content)) - http.NotFound(w, r) -} - -func encodeData(data interface{}) (*bytes.Buffer, error) { - params := bytes.NewBuffer(nil) - if data != nil { - if err := json.NewEncoder(params).Encode(data); err != nil { - return nil, err - } - } - return params, nil -} -func setupRequestHeaders(method string, data interface{}, req *http.Request, headers map[string][]string) { - if data != nil { - if headers == nil { - headers = make(map[string][]string) - } - headers["Content-Type"] = []string{"application/json"} - } - expectedPayload := (method == "POST" || method == "PUT") - if expectedPayload && req.Header.Get("Content-Type") == "" { - req.Header.Set("Content-Type", "text/plain") - } - if headers != nil { - for k, v := range headers { - req.Header[k] = v - } - } -} diff --git a/pkg/server/cniserver/del_pod.go b/provider/cni/server/del_pod.go similarity index 51% rename from pkg/server/cniserver/del_pod.go rename to provider/cni/server/del_pod.go index 2fde508d44..37a9cd0ba7 100644 --- a/pkg/server/cniserver/del_pod.go +++ b/provider/cni/server/del_pod.go @@ -6,9 +6,11 @@ import ( "io/ioutil" "net/http" + "github.com/sirupsen/logrus" + "github.com/docker/libnetwork/client" "github.com/docker/libnetwork/netutils" - "github.com/docker/libnetwork/pkg/cniapi" + "github.com/docker/libnetwork/provider/cni/cniapi" ) func deletePod(w http.ResponseWriter, r *http.Request, c *CniService, vars map[string]string) (interface{}, error) { @@ -24,16 +26,16 @@ func deletePod(w http.ResponseWriter, r *http.Request, c *CniService, vars map[s return nil, err } fmt.Printf("Received delete pod request %+v", cniInfo) - - //Gather sandboxID and the endpointID - sbID, err := c.lookupSandboxID(cniInfo.ContainerID) + cniMetadata, err := c.getCniMetadataFromStore(cniInfo.Metadata["K8S_POD_NAME"], cniInfo.Metadata["K8S_POD_NAMESPACE"]) if err != nil { - return nil, fmt.Errorf("sandbox lookup failed for containerID %q , error:%v", cniInfo.ContainerID, err) - } - epID, err := c.lookupEndpointID(cniInfo.ContainerID) - if err != nil { - return nil, fmt.Errorf("endpoint lookup failed for containerID %q, error:%v", cniInfo.ContainerID, err) + logrus.Errorf("cni pod data not found in plugin store: %v", err) + // If its not found in store we do not have information regarding this pod. + // We just return nil. TODO : figure out an alternative if this causes unwanted + // issues + return nil, nil } + sbID := cniMetadata.SandboxID + epID := cniMetadata.EndpointID if err = c.endpointLeave(sbID, epID); err != nil { return nil, fmt.Errorf("failed to leave endpoint from sandbox for container:%q,sandbox:%q,endpoint:%q, error:%v", cniInfo.ContainerID, sbID, epID, err) @@ -47,54 +49,25 @@ func deletePod(w http.ResponseWriter, r *http.Request, c *CniService, vars map[s if err = c.deleteSandbox(sbID); err != nil { return nil, fmt.Errorf("failed to delete sandbox %q for container %q, error:%v", sbID, cniInfo.ContainerID, err) } - delete(c.endpointIDStore, epID) - delete(c.sandboxIDStore, sbID) + c.deleteFromStore(cniMetadata) return nil, nil } func (c *CniService) endpointLeave(sandboxID, endpointID string) error { - _, _, err := netutils.ReadBody(c.dnetConn.HttpCall("DELETE", "/services/"+endpointID+"/backend/"+sandboxID, nil, nil)) + fmt.Printf("Sending EndpointLeave for endpoint %s , sandbox:%s \n", endpointID, sandboxID) + _, _, err := netutils.ReadBody(c.dnetConn.HTTPCall("DELETE", "/services/"+endpointID+"/backend/"+sandboxID, nil, nil)) return err } func (c *CniService) deleteSandbox(sandboxID string) error { - _, _, err := netutils.ReadBody(c.dnetConn.HttpCall("DELETE", "/sandboxes/"+sandboxID, nil, nil)) + fmt.Printf("Sending deleteSandbox sandbox:%s \n", sandboxID) + _, _, err := netutils.ReadBody(c.dnetConn.HTTPCall("DELETE", "/sandboxes/"+sandboxID, nil, nil)) return err } func (c *CniService) deleteEndpoint(endpointID string) error { + fmt.Printf("Sending deleteEndpoint for endpoint %s \n", endpointID) sd := client.ServiceDelete{Name: endpointID, Force: true} - _, _, err := netutils.ReadBody(c.dnetConn.HttpCall("DELETE", "/services/"+endpointID, sd, nil)) + _, _, err := netutils.ReadBody(c.dnetConn.HTTPCall("DELETE", "/services/"+endpointID, sd, nil)) return err } - -func (c *CniService) lookupSandboxID(containerID string) (string, error) { - if id, ok := c.sandboxIDStore[containerID]; ok { - return id, nil - } - obj, _, err := netutils.ReadBody(c.dnetConn.HttpCall("GET", fmt.Sprintf("/sandboxes?partial-container-id=%s", containerID), nil, nil)) - if err != nil { - return "", err - } - - var sandboxList []client.SandboxResource - err = json.Unmarshal(obj, &sandboxList) - if err != nil { - return "", err - } - - if len(sandboxList) == 0 { - return "", fmt.Errorf("sandbox not found") - } - - c.sandboxIDStore[containerID] = sandboxList[0].ID - return sandboxList[0].ID, nil -} - -func (c *CniService) lookupEndpointID(containerID string) (string, error) { - if id, ok := c.endpointIDStore[containerID]; ok { - return id, nil - } - return "", fmt.Errorf("endpoint not found") - //TODO: query libnetwork core if the cache doesnt have it. -} diff --git a/provider/cni/store/cni_store.go b/provider/cni/store/cni_store.go new file mode 100644 index 0000000000..e3827ffd8a --- /dev/null +++ b/provider/cni/store/cni_store.go @@ -0,0 +1,113 @@ +package store + +import ( + "encoding/json" + + "github.com/docker/libnetwork/api" + "github.com/docker/libnetwork/datastore" + "github.com/sirupsen/logrus" + + "github.com/docker/libnetwork/client" +) + +const ( + cniPrefix = "cni" +) + +// CniMetadata holds the cni metadata information for a pod +type CniMetadata struct { + PodName string + PodNamespace string + InfraContainerID string + SandboxID string + EndpointID string + SandboxMeta api.SandboxMetadata + dbIndex uint64 + dbExists bool +} + +// Key provides the Key to be used in KV Store +func (cs *CniMetadata) Key() []string { + return []string{cniPrefix, cs.PodName, cs.PodNamespace} +} + +// KeyPrefix returns the immediate parent key that can be used for tree walk +func (cs *CniMetadata) KeyPrefix() []string { + return []string{cniPrefix} +} + +// Value marshals the data to be stored in the KV store +func (cs *CniMetadata) Value() []byte { + b, err := json.Marshal(cs) + if err != nil { + logrus.Warnf("failed to marshal cni store: %v", err) + return nil + } + return b +} + +// SetValue unmarshalls the data from the KV store. +func (cs *CniMetadata) SetValue(value []byte) error { + return json.Unmarshal(value, cs) +} + +// Index returns the latest DB Index as seen by this object +func (cs *CniMetadata) Index() uint64 { + return cs.dbIndex +} + +// SetIndex method allows the datastore to store the latest DB Index into this object +func (cs *CniMetadata) SetIndex(index uint64) { + cs.dbIndex = index + cs.dbExists = true +} + +// Exists method is true if this object has been stored in the DB. +func (cs *CniMetadata) Exists() bool { + return cs.dbExists +} + +// Skip provides a way for a KV Object to avoid persisting it in the KV Store +func (cs *CniMetadata) Skip() bool { + return false +} + +// New returns a new cnimetada KVObjects +func (cs *CniMetadata) New() datastore.KVObject { + return &CniMetadata{} +} + +// CopyTo copy from source to destination KBObject +func (cs *CniMetadata) CopyTo(o datastore.KVObject) error { + dstCs := o.(*CniMetadata) + dstCs.PodName = cs.PodName + dstCs.PodNamespace = cs.PodNamespace + dstCs.InfraContainerID = cs.InfraContainerID + dstCs.SandboxID = cs.SandboxID + dstCs.EndpointID = cs.EndpointID + dstCs.SandboxMeta = cs.SandboxMeta + return nil +} + +// DataScope method returns the storage scope of the datastore +func (cs *CniMetadata) DataScope() string { + return datastore.LocalScope +} + +// CopySandboxMetadata creates a sandbox metadata +func CopySandboxMetadata(sbConfig client.SandboxCreate, externalKey string) api.SandboxMetadata { + var meta api.SandboxMetadata + meta.ContainerID = sbConfig.ContainerID + meta.HostName = sbConfig.HostName + meta.DomainName = sbConfig.DomainName + meta.HostsPath = sbConfig.HostsPath + meta.ResolvConfPath = sbConfig.ResolvConfPath + meta.DNS = sbConfig.DNS + meta.UseExternalKey = sbConfig.UseExternalKey + meta.UseDefaultSandbox = sbConfig.UseDefaultSandbox + meta.ExposedPorts = sbConfig.ExposedPorts + meta.PortMapping = sbConfig.PortMapping + meta.ExternalKey = externalKey + //TODO: skipped extrahosts + return meta +} diff --git a/provider/provider.go b/provider/provider.go new file mode 100644 index 0000000000..8bf7f2291b --- /dev/null +++ b/provider/provider.go @@ -0,0 +1,10 @@ +package provider + +// DnetProvider is entity that runs on top of dnet. For eg cni +// TODO: This interface may be removed/expanded depending on the push/pull +// model we might adopt. +type DnetProvider interface { + // FetchActiveSandboxes fetches the active sandboxes as map + // of sandbox IDs and sandbox options + FetchActiveSandboxes() (map[string]interface{}, error) +} diff --git a/sandbox.go b/sandbox.go index 315195ebb8..f301baac43 100644 --- a/sandbox.go +++ b/sandbox.go @@ -128,6 +128,7 @@ type containerConfig struct { generic map[string]interface{} useDefaultSandBox bool useExternalKey bool + externalKey string prio int // higher the value, more the priority exposedPorts []types.TransportPort } @@ -619,6 +620,7 @@ func (sb *sandbox) resolveName(req string, networkName string, epList []*endpoin } func (sb *sandbox) SetKey(basePath string) error { + fmt.Printf("SetKey: %s \n", basePath) start := time.Now() defer func() { logrus.Debugf("sandbox set key processing took %s for container %s", time.Since(start), sb.ContainerID()) @@ -650,6 +652,7 @@ func (sb *sandbox) SetKey(basePath string) error { sb.Lock() sb.osSbox = osSbox + sb.config.externalKey = basePath sb.Unlock() // If the resolver was setup before stop it and set it up in the @@ -1096,6 +1099,14 @@ func OptionUseExternalKey() SandboxOption { } } +// OptionExternalKey function returns an option setter for using external key namespace +// instead of creating one. +func OptionExternalKey(key string) SandboxOption { + return func(sb *sandbox) { + sb.config.externalKey = key + } +} + // OptionGeneric function returns an option setter for Generic configuration // that is not managed by libNetwork but can be used by the Drivers during the call to // net container creation method. Container Labels are a good example. diff --git a/sandbox_store.go b/sandbox_store.go index a083644598..bf3b01d9f1 100644 --- a/sandbox_store.go +++ b/sandbox_store.go @@ -210,7 +210,6 @@ func (c *controller) sandboxCleanup(activeSandboxes map[string]interface{}) { for _, kvo := range kvol { sbs := kvo.(*sbState) - sb := &sandbox{ id: sbs.ID, controller: sbs.c, @@ -244,10 +243,19 @@ func (c *controller) sandboxCleanup(activeSandboxes map[string]interface{}) { create = !sb.config.useDefaultSandBox heap.Init(&sb.endpoints) } - sb.osSbox, err = osl.NewSandbox(sb.Key(), create, isRestore) - if err != nil { - logrus.Errorf("failed to create osl sandbox while trying to restore sandbox %s%s: %v", sb.ID()[0:7], msg, err) - continue + logrus.Debugf("Sandbox restore isRestore:%+v Key:%v,create:%v", isRestore, sb.Key(), create) + if sb.config.useExternalKey { + sb.osSbox, err = osl.GetSandboxForExternalKey(sb.config.externalKey, sb.Key()) + if err != nil { + logrus.Errorf("failed to get sandbox for external key: %v", err) + } + } else { + osSbox, err := osl.NewSandbox(sb.Key(), create, isRestore) + if err != nil { + logrus.Errorf("failed to create osl sandbox while trying to restore sandbox %s%s: %v", sb.ID()[0:7], msg, err) + continue + } + sb.osSbox = osSbox } c.Lock() diff --git a/vendor.conf b/vendor.conf index da120d842e..d531359cd4 100644 --- a/vendor.conf +++ b/vendor.conf @@ -43,3 +43,4 @@ github.com/vishvananda/netns 604eaf189ee867d8c147fafc28def2394e878d25 golang.org/x/net c427ad74c6d7a814201695e9ffde0c5d400a7674 golang.org/x/sys 8f0908ab3b2457e2e15403d3697c9ef5cb4b57a9 github.com/pkg/errors 839d9e913e063e28dfd0e6c7b7512793e0a48be9 +github.com/davecgh/go-spew dce690a33ebe33040a7a2ffeb96dd200060f3fca diff --git a/vendor/github.com/Microsoft/hcsshim/mksyscall_windows.go b/vendor/github.com/Microsoft/hcsshim/mksyscall_windows.go deleted file mode 100644 index 82393ca367..0000000000 --- a/vendor/github.com/Microsoft/hcsshim/mksyscall_windows.go +++ /dev/null @@ -1,934 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -mksyscall_windows generates windows system call bodies - -It parses all files specified on command line containing function -prototypes (like syscall_windows.go) and prints system call bodies -to standard output. - -The prototypes are marked by lines beginning with "//sys" and read -like func declarations if //sys is replaced by func, but: - -* The parameter lists must give a name for each argument. This - includes return parameters. - -* The parameter lists must give a type for each argument: - the (x, y, z int) shorthand is not allowed. - -* If the return parameter is an error number, it must be named err. - -* If go func name needs to be different from it's winapi dll name, - the winapi name could be specified at the end, after "=" sign, like - //sys LoadLibrary(libname string) (handle uint32, err error) = LoadLibraryA - -* Each function that returns err needs to supply a condition, that - return value of winapi will be tested against to detect failure. - This would set err to windows "last-error", otherwise it will be nil. - The value can be provided at end of //sys declaration, like - //sys LoadLibrary(libname string) (handle uint32, err error) [failretval==-1] = LoadLibraryA - and is [failretval==0] by default. - -Usage: - mksyscall_windows [flags] [path ...] - -The flags are: - -output - Specify output file name (outputs to console if blank). - -trace - Generate print statement after every syscall. -*/ -package main - -import ( - "bufio" - "bytes" - "errors" - "flag" - "fmt" - "go/format" - "go/parser" - "go/token" - "io" - "io/ioutil" - "log" - "os" - "path/filepath" - "runtime" - "sort" - "strconv" - "strings" - "text/template" -) - -var ( - filename = flag.String("output", "", "output file name (standard output if omitted)") - printTraceFlag = flag.Bool("trace", false, "generate print statement after every syscall") - systemDLL = flag.Bool("systemdll", true, "whether all DLLs should be loaded from the Windows system directory") -) - -func trim(s string) string { - return strings.Trim(s, " \t") -} - -var packageName string - -func packagename() string { - return packageName -} - -func syscalldot() string { - if packageName == "syscall" { - return "" - } - return "syscall." -} - -// Param is function parameter -type Param struct { - Name string - Type string - fn *Fn - tmpVarIdx int -} - -// tmpVar returns temp variable name that will be used to represent p during syscall. -func (p *Param) tmpVar() string { - if p.tmpVarIdx < 0 { - p.tmpVarIdx = p.fn.curTmpVarIdx - p.fn.curTmpVarIdx++ - } - return fmt.Sprintf("_p%d", p.tmpVarIdx) -} - -// BoolTmpVarCode returns source code for bool temp variable. -func (p *Param) BoolTmpVarCode() string { - const code = `var %s uint32 - if %s { - %s = 1 - } else { - %s = 0 - }` - tmp := p.tmpVar() - return fmt.Sprintf(code, tmp, p.Name, tmp, tmp) -} - -// SliceTmpVarCode returns source code for slice temp variable. -func (p *Param) SliceTmpVarCode() string { - const code = `var %s *%s - if len(%s) > 0 { - %s = &%s[0] - }` - tmp := p.tmpVar() - return fmt.Sprintf(code, tmp, p.Type[2:], p.Name, tmp, p.Name) -} - -// StringTmpVarCode returns source code for string temp variable. -func (p *Param) StringTmpVarCode() string { - errvar := p.fn.Rets.ErrorVarName() - if errvar == "" { - errvar = "_" - } - tmp := p.tmpVar() - const code = `var %s %s - %s, %s = %s(%s)` - s := fmt.Sprintf(code, tmp, p.fn.StrconvType(), tmp, errvar, p.fn.StrconvFunc(), p.Name) - if errvar == "-" { - return s - } - const morecode = ` - if %s != nil { - return - }` - return s + fmt.Sprintf(morecode, errvar) -} - -// TmpVarCode returns source code for temp variable. -func (p *Param) TmpVarCode() string { - switch { - case p.Type == "bool": - return p.BoolTmpVarCode() - case strings.HasPrefix(p.Type, "[]"): - return p.SliceTmpVarCode() - default: - return "" - } -} - -// TmpVarHelperCode returns source code for helper's temp variable. -func (p *Param) TmpVarHelperCode() string { - if p.Type != "string" { - return "" - } - return p.StringTmpVarCode() -} - -// SyscallArgList returns source code fragments representing p parameter -// in syscall. Slices are translated into 2 syscall parameters: pointer to -// the first element and length. -func (p *Param) SyscallArgList() []string { - t := p.HelperType() - var s string - switch { - case t[0] == '*': - s = fmt.Sprintf("unsafe.Pointer(%s)", p.Name) - case t == "bool": - s = p.tmpVar() - case strings.HasPrefix(t, "[]"): - return []string{ - fmt.Sprintf("uintptr(unsafe.Pointer(%s))", p.tmpVar()), - fmt.Sprintf("uintptr(len(%s))", p.Name), - } - default: - s = p.Name - } - return []string{fmt.Sprintf("uintptr(%s)", s)} -} - -// IsError determines if p parameter is used to return error. -func (p *Param) IsError() bool { - return p.Name == "err" && p.Type == "error" -} - -// HelperType returns type of parameter p used in helper function. -func (p *Param) HelperType() string { - if p.Type == "string" { - return p.fn.StrconvType() - } - return p.Type -} - -// join concatenates parameters ps into a string with sep separator. -// Each parameter is converted into string by applying fn to it -// before conversion. -func join(ps []*Param, fn func(*Param) string, sep string) string { - if len(ps) == 0 { - return "" - } - a := make([]string, 0) - for _, p := range ps { - a = append(a, fn(p)) - } - return strings.Join(a, sep) -} - -// Rets describes function return parameters. -type Rets struct { - Name string - Type string - ReturnsError bool - FailCond string -} - -// ErrorVarName returns error variable name for r. -func (r *Rets) ErrorVarName() string { - if r.ReturnsError { - return "err" - } - if r.Type == "error" { - return r.Name - } - return "" -} - -// ToParams converts r into slice of *Param. -func (r *Rets) ToParams() []*Param { - ps := make([]*Param, 0) - if len(r.Name) > 0 { - ps = append(ps, &Param{Name: r.Name, Type: r.Type}) - } - if r.ReturnsError { - ps = append(ps, &Param{Name: "err", Type: "error"}) - } - return ps -} - -// List returns source code of syscall return parameters. -func (r *Rets) List() string { - s := join(r.ToParams(), func(p *Param) string { return p.Name + " " + p.Type }, ", ") - if len(s) > 0 { - s = "(" + s + ")" - } - return s -} - -// PrintList returns source code of trace printing part correspondent -// to syscall return values. -func (r *Rets) PrintList() string { - return join(r.ToParams(), func(p *Param) string { return fmt.Sprintf(`"%s=", %s, `, p.Name, p.Name) }, `", ", `) -} - -// SetReturnValuesCode returns source code that accepts syscall return values. -func (r *Rets) SetReturnValuesCode() string { - if r.Name == "" && !r.ReturnsError { - return "" - } - retvar := "r0" - if r.Name == "" { - retvar = "r1" - } - errvar := "_" - if r.ReturnsError { - errvar = "e1" - } - return fmt.Sprintf("%s, _, %s := ", retvar, errvar) -} - -func (r *Rets) useLongHandleErrorCode(retvar string) string { - const code = `if %s { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = %sEINVAL - } - }` - cond := retvar + " == 0" - if r.FailCond != "" { - cond = strings.Replace(r.FailCond, "failretval", retvar, 1) - } - return fmt.Sprintf(code, cond, syscalldot()) -} - -// SetErrorCode returns source code that sets return parameters. -func (r *Rets) SetErrorCode() string { - const code = `if r0 != 0 { - %s = %sErrno(r0) - }` - const hrCode = `if int32(r0) < 0 { - %s = %sErrno(win32FromHresult(r0)) - }` - if r.Name == "" && !r.ReturnsError { - return "" - } - if r.Name == "" { - return r.useLongHandleErrorCode("r1") - } - if r.Type == "error" { - if r.Name == "hr" { - return fmt.Sprintf(hrCode, r.Name, syscalldot()) - } else { - return fmt.Sprintf(code, r.Name, syscalldot()) - } - } - s := "" - switch { - case r.Type[0] == '*': - s = fmt.Sprintf("%s = (%s)(unsafe.Pointer(r0))", r.Name, r.Type) - case r.Type == "bool": - s = fmt.Sprintf("%s = r0 != 0", r.Name) - default: - s = fmt.Sprintf("%s = %s(r0)", r.Name, r.Type) - } - if !r.ReturnsError { - return s - } - return s + "\n\t" + r.useLongHandleErrorCode(r.Name) -} - -// Fn describes syscall function. -type Fn struct { - Name string - Params []*Param - Rets *Rets - PrintTrace bool - confirmproc bool - dllname string - dllfuncname string - src string - // TODO: get rid of this field and just use parameter index instead - curTmpVarIdx int // insure tmp variables have uniq names -} - -// extractParams parses s to extract function parameters. -func extractParams(s string, f *Fn) ([]*Param, error) { - s = trim(s) - if s == "" { - return nil, nil - } - a := strings.Split(s, ",") - ps := make([]*Param, len(a)) - for i := range ps { - s2 := trim(a[i]) - b := strings.Split(s2, " ") - if len(b) != 2 { - b = strings.Split(s2, "\t") - if len(b) != 2 { - return nil, errors.New("Could not extract function parameter from \"" + s2 + "\"") - } - } - ps[i] = &Param{ - Name: trim(b[0]), - Type: trim(b[1]), - fn: f, - tmpVarIdx: -1, - } - } - return ps, nil -} - -// extractSection extracts text out of string s starting after start -// and ending just before end. found return value will indicate success, -// and prefix, body and suffix will contain correspondent parts of string s. -func extractSection(s string, start, end rune) (prefix, body, suffix string, found bool) { - s = trim(s) - if strings.HasPrefix(s, string(start)) { - // no prefix - body = s[1:] - } else { - a := strings.SplitN(s, string(start), 2) - if len(a) != 2 { - return "", "", s, false - } - prefix = a[0] - body = a[1] - } - a := strings.SplitN(body, string(end), 2) - if len(a) != 2 { - return "", "", "", false - } - return prefix, a[0], a[1], true -} - -// newFn parses string s and return created function Fn. -func newFn(s string) (*Fn, error) { - s = trim(s) - f := &Fn{ - Rets: &Rets{}, - src: s, - PrintTrace: *printTraceFlag, - } - // function name and args - prefix, body, s, found := extractSection(s, '(', ')') - if !found || prefix == "" { - return nil, errors.New("Could not extract function name and parameters from \"" + f.src + "\"") - } - f.Name = prefix - var err error - f.Params, err = extractParams(body, f) - if err != nil { - return nil, err - } - // return values - _, body, s, found = extractSection(s, '(', ')') - if found { - r, err := extractParams(body, f) - if err != nil { - return nil, err - } - switch len(r) { - case 0: - case 1: - if r[0].IsError() { - f.Rets.ReturnsError = true - } else { - f.Rets.Name = r[0].Name - f.Rets.Type = r[0].Type - } - case 2: - if !r[1].IsError() { - return nil, errors.New("Only last windows error is allowed as second return value in \"" + f.src + "\"") - } - f.Rets.ReturnsError = true - f.Rets.Name = r[0].Name - f.Rets.Type = r[0].Type - default: - return nil, errors.New("Too many return values in \"" + f.src + "\"") - } - } - // fail condition - _, body, s, found = extractSection(s, '[', ']') - if found { - f.Rets.FailCond = body - } - // dll and dll function names - s = trim(s) - if s == "" { - return f, nil - } - if !strings.HasPrefix(s, "=") { - return nil, errors.New("Could not extract dll name from \"" + f.src + "\"") - } - s = trim(s[1:]) - a := strings.Split(s, ".") - switch len(a) { - case 1: - f.dllfuncname = a[0] - case 2: - f.dllname = a[0] - f.dllfuncname = a[1] - default: - return nil, errors.New("Could not extract dll name from \"" + f.src + "\"") - } - if f.dllfuncname[len(f.dllfuncname)-1] == '?' { - f.confirmproc = true - f.dllfuncname = f.dllfuncname[0 : len(f.dllfuncname)-1] - } - return f, nil -} - -// DLLName returns DLL name for function f. -func (f *Fn) DLLName() string { - if f.dllname == "" { - return "kernel32" - } - return f.dllname -} - -// DLLName returns DLL function name for function f. -func (f *Fn) DLLFuncName() string { - if f.dllfuncname == "" { - return f.Name - } - return f.dllfuncname -} - -func (f *Fn) ConfirmProc() bool { - return f.confirmproc -} - -// ParamList returns source code for function f parameters. -func (f *Fn) ParamList() string { - return join(f.Params, func(p *Param) string { return p.Name + " " + p.Type }, ", ") -} - -// HelperParamList returns source code for helper function f parameters. -func (f *Fn) HelperParamList() string { - return join(f.Params, func(p *Param) string { return p.Name + " " + p.HelperType() }, ", ") -} - -// ParamPrintList returns source code of trace printing part correspondent -// to syscall input parameters. -func (f *Fn) ParamPrintList() string { - return join(f.Params, func(p *Param) string { return fmt.Sprintf(`"%s=", %s, `, p.Name, p.Name) }, `", ", `) -} - -// ParamCount return number of syscall parameters for function f. -func (f *Fn) ParamCount() int { - n := 0 - for _, p := range f.Params { - n += len(p.SyscallArgList()) - } - return n -} - -// SyscallParamCount determines which version of Syscall/Syscall6/Syscall9/... -// to use. It returns parameter count for correspondent SyscallX function. -func (f *Fn) SyscallParamCount() int { - n := f.ParamCount() - switch { - case n <= 3: - return 3 - case n <= 6: - return 6 - case n <= 9: - return 9 - case n <= 12: - return 12 - case n <= 15: - return 15 - default: - panic("too many arguments to system call") - } -} - -// Syscall determines which SyscallX function to use for function f. -func (f *Fn) Syscall() string { - c := f.SyscallParamCount() - if c == 3 { - return syscalldot() + "Syscall" - } - return syscalldot() + "Syscall" + strconv.Itoa(c) -} - -// SyscallParamList returns source code for SyscallX parameters for function f. -func (f *Fn) SyscallParamList() string { - a := make([]string, 0) - for _, p := range f.Params { - a = append(a, p.SyscallArgList()...) - } - for len(a) < f.SyscallParamCount() { - a = append(a, "0") - } - return strings.Join(a, ", ") -} - -// HelperCallParamList returns source code of call into function f helper. -func (f *Fn) HelperCallParamList() string { - a := make([]string, 0, len(f.Params)) - for _, p := range f.Params { - s := p.Name - if p.Type == "string" { - s = p.tmpVar() - } - a = append(a, s) - } - return strings.Join(a, ", ") -} - -// IsUTF16 is true, if f is W (utf16) function. It is false -// for all A (ascii) functions. -func (_ *Fn) IsUTF16() bool { - return true -} - -// StrconvFunc returns name of Go string to OS string function for f. -func (f *Fn) StrconvFunc() string { - if f.IsUTF16() { - return syscalldot() + "UTF16PtrFromString" - } - return syscalldot() + "BytePtrFromString" -} - -// StrconvType returns Go type name used for OS string for f. -func (f *Fn) StrconvType() string { - if f.IsUTF16() { - return "*uint16" - } - return "*byte" -} - -// HasStringParam is true, if f has at least one string parameter. -// Otherwise it is false. -func (f *Fn) HasStringParam() bool { - for _, p := range f.Params { - if p.Type == "string" { - return true - } - } - return false -} - -var uniqDllFuncName = make(map[string]bool) - -// IsNotDuplicate is true if f is not a duplicated function -func (f *Fn) IsNotDuplicate() bool { - funcName := f.DLLFuncName() - if uniqDllFuncName[funcName] == false { - uniqDllFuncName[funcName] = true - return true - } - return false -} - -// HelperName returns name of function f helper. -func (f *Fn) HelperName() string { - if !f.HasStringParam() { - return f.Name - } - return "_" + f.Name -} - -// Source files and functions. -type Source struct { - Funcs []*Fn - Files []string - StdLibImports []string - ExternalImports []string -} - -func (src *Source) Import(pkg string) { - src.StdLibImports = append(src.StdLibImports, pkg) - sort.Strings(src.StdLibImports) -} - -func (src *Source) ExternalImport(pkg string) { - src.ExternalImports = append(src.ExternalImports, pkg) - sort.Strings(src.ExternalImports) -} - -// ParseFiles parses files listed in fs and extracts all syscall -// functions listed in sys comments. It returns source files -// and functions collection *Source if successful. -func ParseFiles(fs []string) (*Source, error) { - src := &Source{ - Funcs: make([]*Fn, 0), - Files: make([]string, 0), - StdLibImports: []string{ - "unsafe", - }, - ExternalImports: make([]string, 0), - } - for _, file := range fs { - if err := src.ParseFile(file); err != nil { - return nil, err - } - } - return src, nil -} - -// DLLs return dll names for a source set src. -func (src *Source) DLLs() []string { - uniq := make(map[string]bool) - r := make([]string, 0) - for _, f := range src.Funcs { - name := f.DLLName() - if _, found := uniq[name]; !found { - uniq[name] = true - r = append(r, name) - } - } - return r -} - -// ParseFile adds additional file path to a source set src. -func (src *Source) ParseFile(path string) error { - file, err := os.Open(path) - if err != nil { - return err - } - defer file.Close() - - s := bufio.NewScanner(file) - for s.Scan() { - t := trim(s.Text()) - if len(t) < 7 { - continue - } - if !strings.HasPrefix(t, "//sys") { - continue - } - t = t[5:] - if !(t[0] == ' ' || t[0] == '\t') { - continue - } - f, err := newFn(t[1:]) - if err != nil { - return err - } - src.Funcs = append(src.Funcs, f) - } - if err := s.Err(); err != nil { - return err - } - src.Files = append(src.Files, path) - - // get package name - fset := token.NewFileSet() - _, err = file.Seek(0, 0) - if err != nil { - return err - } - pkg, err := parser.ParseFile(fset, "", file, parser.PackageClauseOnly) - if err != nil { - return err - } - packageName = pkg.Name.Name - - return nil -} - -// IsStdRepo returns true if src is part of standard library. -func (src *Source) IsStdRepo() (bool, error) { - if len(src.Files) == 0 { - return false, errors.New("no input files provided") - } - abspath, err := filepath.Abs(src.Files[0]) - if err != nil { - return false, err - } - goroot := runtime.GOROOT() - if runtime.GOOS == "windows" { - abspath = strings.ToLower(abspath) - goroot = strings.ToLower(goroot) - } - sep := string(os.PathSeparator) - if !strings.HasSuffix(goroot, sep) { - goroot += sep - } - return strings.HasPrefix(abspath, goroot), nil -} - -// Generate output source file from a source set src. -func (src *Source) Generate(w io.Writer) error { - const ( - pkgStd = iota // any package in std library - pkgXSysWindows // x/sys/windows package - pkgOther - ) - isStdRepo, err := src.IsStdRepo() - if err != nil { - return err - } - var pkgtype int - switch { - case isStdRepo: - pkgtype = pkgStd - case packageName == "windows": - // TODO: this needs better logic than just using package name - pkgtype = pkgXSysWindows - default: - pkgtype = pkgOther - } - if *systemDLL { - switch pkgtype { - case pkgStd: - src.Import("internal/syscall/windows/sysdll") - case pkgXSysWindows: - default: - src.ExternalImport("golang.org/x/sys/windows") - } - } - src.ExternalImport("github.com/Microsoft/go-winio") - if packageName != "syscall" { - src.Import("syscall") - } - funcMap := template.FuncMap{ - "packagename": packagename, - "syscalldot": syscalldot, - "newlazydll": func(dll string) string { - arg := "\"" + dll + ".dll\"" - if !*systemDLL { - return syscalldot() + "NewLazyDLL(" + arg + ")" - } - switch pkgtype { - case pkgStd: - return syscalldot() + "NewLazyDLL(sysdll.Add(" + arg + "))" - case pkgXSysWindows: - return "NewLazySystemDLL(" + arg + ")" - default: - return "windows.NewLazySystemDLL(" + arg + ")" - } - }, - } - t := template.Must(template.New("main").Funcs(funcMap).Parse(srcTemplate)) - err = t.Execute(w, src) - if err != nil { - return errors.New("Failed to execute template: " + err.Error()) - } - return nil -} - -func usage() { - fmt.Fprintf(os.Stderr, "usage: mksyscall_windows [flags] [path ...]\n") - flag.PrintDefaults() - os.Exit(1) -} - -func main() { - flag.Usage = usage - flag.Parse() - if len(flag.Args()) <= 0 { - fmt.Fprintf(os.Stderr, "no files to parse provided\n") - usage() - } - - src, err := ParseFiles(flag.Args()) - if err != nil { - log.Fatal(err) - } - - var buf bytes.Buffer - if err := src.Generate(&buf); err != nil { - log.Fatal(err) - } - - data, err := format.Source(buf.Bytes()) - if err != nil { - log.Fatal(err) - } - if *filename == "" { - _, err = os.Stdout.Write(data) - } else { - err = ioutil.WriteFile(*filename, data, 0644) - } - if err != nil { - log.Fatal(err) - } -} - -// TODO: use println instead to print in the following template -const srcTemplate = ` - -{{define "main"}}// MACHINE GENERATED BY 'go generate' COMMAND; DO NOT EDIT - -package {{packagename}} - -import ( -{{range .StdLibImports}}"{{.}}" -{{end}} - -{{range .ExternalImports}}"{{.}}" -{{end}} -) - -var _ unsafe.Pointer - -// Do the interface allocations only once for common -// Errno values. -const ( - errnoERROR_IO_PENDING = 997 -) - -var ( - errERROR_IO_PENDING error = {{syscalldot}}Errno(errnoERROR_IO_PENDING) -) - -// errnoErr returns common boxed Errno values, to prevent -// allocations at runtime. -func errnoErr(e {{syscalldot}}Errno) error { - switch e { - case 0: - return nil - case errnoERROR_IO_PENDING: - return errERROR_IO_PENDING - } - // TODO: add more here, after collecting data on the common - // error values see on Windows. (perhaps when running - // all.bat?) - return e -} - -var ( -{{template "dlls" .}} -{{template "funcnames" .}}) -{{range .Funcs}}{{if .HasStringParam}}{{template "helperbody" .}}{{end}}{{template "funcbody" .}}{{end}} -{{end}} - -{{/* help functions */}} - -{{define "dlls"}}{{range .DLLs}} mod{{.}} = {{newlazydll .}} -{{end}}{{end}} - -{{define "funcnames"}}{{range .Funcs}}{{if .IsNotDuplicate}} proc{{.DLLFuncName}} = mod{{.DLLName}}.NewProc("{{.DLLFuncName}}"){{end}} -{{end}}{{end}} - -{{define "helperbody"}} -func {{.Name}}({{.ParamList}}) {{template "results" .}}{ -{{template "helpertmpvars" .}} return {{.HelperName}}({{.HelperCallParamList}}) -} -{{end}} - -{{define "funcbody"}} -func {{.HelperName}}({{.HelperParamList}}) {{template "results" .}}{ -{{template "tmpvars" .}} {{template "syscallcheck" .}}{{template "syscall" .}} -{{template "seterror" .}}{{template "printtrace" .}} return -} -{{end}} - -{{define "helpertmpvars"}}{{range .Params}}{{if .TmpVarHelperCode}} {{.TmpVarHelperCode}} -{{end}}{{end}}{{end}} - -{{define "tmpvars"}}{{range .Params}}{{if .TmpVarCode}} {{.TmpVarCode}} -{{end}}{{end}}{{end}} - -{{define "results"}}{{if .Rets.List}}{{.Rets.List}} {{end}}{{end}} - -{{define "syscall"}}{{.Rets.SetReturnValuesCode}}{{.Syscall}}(proc{{.DLLFuncName}}.Addr(), {{.ParamCount}}, {{.SyscallParamList}}){{end}} - -{{define "syscallcheck"}}{{if .ConfirmProc}}if {{.Rets.ErrorVarName}} = proc{{.DLLFuncName}}.Find(); {{.Rets.ErrorVarName}} != nil { - return -} -{{end}}{{end}} - - -{{define "seterror"}}{{if .Rets.SetErrorCode}} {{.Rets.SetErrorCode}} -{{end}}{{end}} - -{{define "printtrace"}}{{if .PrintTrace}} print("SYSCALL: {{.Name}}(", {{.ParamPrintList}}") (", {{.Rets.PrintList}}")\n") -{{end}}{{end}} - -` diff --git a/vendor/github.com/miekg/dns/types_generate.go b/vendor/github.com/miekg/dns/types_generate.go deleted file mode 100644 index 53690141a1..0000000000 --- a/vendor/github.com/miekg/dns/types_generate.go +++ /dev/null @@ -1,266 +0,0 @@ -//+build ignore - -// types_generate.go is meant to run with go generate. It will use -// go/{importer,types} to track down all the RR struct types. Then for each type -// it will generate conversion tables (TypeToRR and TypeToString) and banal -// methods (len, Header, copy) based on the struct tags. The generated source is -// written to ztypes.go, and is meant to be checked into git. -package main - -import ( - "bytes" - "fmt" - "go/format" - "go/importer" - "go/types" - "log" - "os" - "strings" - "text/template" -) - -var skipLen = map[string]struct{}{ - "NSEC": struct{}{}, - "NSEC3": struct{}{}, - "OPT": struct{}{}, - "WKS": struct{}{}, - "IPSECKEY": struct{}{}, -} - -var packageHdr = ` -// *** DO NOT MODIFY *** -// AUTOGENERATED BY go generate - -package dns - -import ( - "encoding/base64" - "net" -) - -` - -var TypeToRR = template.Must(template.New("TypeToRR").Parse(` -// TypeToRR is a map of constructors for each RR type. -var TypeToRR = map[uint16]func() RR{ -{{range .}}{{if ne . "RFC3597"}} Type{{.}}: func() RR { return new({{.}}) }, -{{end}}{{end}} } - -`)) - -var typeToString = template.Must(template.New("typeToString").Parse(` -// TypeToString is a map of strings for each RR type. -var TypeToString = map[uint16]string{ -{{range .}}{{if ne . "NSAPPTR"}} Type{{.}}: "{{.}}", -{{end}}{{end}} TypeNSAPPTR: "NSAP-PTR", -} - -`)) - -var headerFunc = template.Must(template.New("headerFunc").Parse(` -// Header() functions -{{range .}} func (rr *{{.}}) Header() *RR_Header { return &rr.Hdr } -{{end}} - -`)) - -// getTypeStruct will take a type and the package scope, and return the -// (innermost) struct if the type is considered a RR type (currently defined as -// those structs beginning with a RR_Header, could be redefined as implementing -// the RR interface). The bool return value indicates if embedded structs were -// resolved. -func getTypeStruct(t types.Type, scope *types.Scope) (*types.Struct, bool) { - st, ok := t.Underlying().(*types.Struct) - if !ok { - return nil, false - } - if st.Field(0).Type() == scope.Lookup("RR_Header").Type() { - return st, false - } - if st.Field(0).Anonymous() { - st, _ := getTypeStruct(st.Field(0).Type(), scope) - return st, true - } - return nil, false -} - -func main() { - // Import and type-check the package - pkg, err := importer.Default().Import("github.com/miekg/dns") - fatalIfErr(err) - scope := pkg.Scope() - - // Collect constants like TypeX - var numberedTypes []string - for _, name := range scope.Names() { - o := scope.Lookup(name) - if o == nil || !o.Exported() { - continue - } - b, ok := o.Type().(*types.Basic) - if !ok || b.Kind() != types.Uint16 { - continue - } - if !strings.HasPrefix(o.Name(), "Type") { - continue - } - name := strings.TrimPrefix(o.Name(), "Type") - if name == "PrivateRR" { - continue - } - numberedTypes = append(numberedTypes, name) - } - - // Collect actual types (*X) - var namedTypes []string - for _, name := range scope.Names() { - o := scope.Lookup(name) - if o == nil || !o.Exported() { - continue - } - if st, _ := getTypeStruct(o.Type(), scope); st == nil { - continue - } - if name == "PrivateRR" { - continue - } - - // Check if corresponding TypeX exists - if scope.Lookup("Type"+o.Name()) == nil && o.Name() != "RFC3597" { - log.Fatalf("Constant Type%s does not exist.", o.Name()) - } - - namedTypes = append(namedTypes, o.Name()) - } - - b := &bytes.Buffer{} - b.WriteString(packageHdr) - - // Generate TypeToRR - fatalIfErr(TypeToRR.Execute(b, namedTypes)) - - // Generate typeToString - fatalIfErr(typeToString.Execute(b, numberedTypes)) - - // Generate headerFunc - fatalIfErr(headerFunc.Execute(b, namedTypes)) - - // Generate len() - fmt.Fprint(b, "// len() functions\n") - for _, name := range namedTypes { - if _, ok := skipLen[name]; ok { - continue - } - o := scope.Lookup(name) - st, isEmbedded := getTypeStruct(o.Type(), scope) - if isEmbedded { - continue - } - fmt.Fprintf(b, "func (rr *%s) len() int {\n", name) - fmt.Fprintf(b, "l := rr.Hdr.len()\n") - for i := 1; i < st.NumFields(); i++ { - o := func(s string) { fmt.Fprintf(b, s, st.Field(i).Name()) } - - if _, ok := st.Field(i).Type().(*types.Slice); ok { - switch st.Tag(i) { - case `dns:"-"`: - // ignored - case `dns:"cdomain-name"`, `dns:"domain-name"`, `dns:"txt"`: - o("for _, x := range rr.%s { l += len(x) + 1 }\n") - default: - log.Fatalln(name, st.Field(i).Name(), st.Tag(i)) - } - continue - } - - switch st.Tag(i) { - case `dns:"-"`: - // ignored - case `dns:"cdomain-name"`, `dns:"domain-name"`: - o("l += len(rr.%s) + 1\n") - case `dns:"octet"`: - o("l += len(rr.%s)\n") - case `dns:"base64"`: - o("l += base64.StdEncoding.DecodedLen(len(rr.%s))\n") - case `dns:"size-hex"`, `dns:"hex"`: - o("l += len(rr.%s)/2 + 1\n") - case `dns:"a"`: - o("l += net.IPv4len // %s\n") - case `dns:"aaaa"`: - o("l += net.IPv6len // %s\n") - case `dns:"txt"`: - o("for _, t := range rr.%s { l += len(t) + 1 }\n") - case `dns:"uint48"`: - o("l += 6 // %s\n") - case "": - switch st.Field(i).Type().(*types.Basic).Kind() { - case types.Uint8: - o("l += 1 // %s\n") - case types.Uint16: - o("l += 2 // %s\n") - case types.Uint32: - o("l += 4 // %s\n") - case types.Uint64: - o("l += 8 // %s\n") - case types.String: - o("l += len(rr.%s) + 1\n") - default: - log.Fatalln(name, st.Field(i).Name()) - } - default: - log.Fatalln(name, st.Field(i).Name(), st.Tag(i)) - } - } - fmt.Fprintf(b, "return l }\n") - } - - // Generate copy() - fmt.Fprint(b, "// copy() functions\n") - for _, name := range namedTypes { - o := scope.Lookup(name) - st, isEmbedded := getTypeStruct(o.Type(), scope) - if isEmbedded { - continue - } - fmt.Fprintf(b, "func (rr *%s) copy() RR {\n", name) - fields := []string{"*rr.Hdr.copyHeader()"} - for i := 1; i < st.NumFields(); i++ { - f := st.Field(i).Name() - if sl, ok := st.Field(i).Type().(*types.Slice); ok { - t := sl.Underlying().String() - t = strings.TrimPrefix(t, "[]") - t = strings.TrimPrefix(t, "github.com/miekg/dns.") - fmt.Fprintf(b, "%s := make([]%s, len(rr.%s)); copy(%s, rr.%s)\n", - f, t, f, f, f) - fields = append(fields, f) - continue - } - if st.Field(i).Type().String() == "net.IP" { - fields = append(fields, "copyIP(rr."+f+")") - continue - } - fields = append(fields, "rr."+f) - } - fmt.Fprintf(b, "return &%s{%s}\n", name, strings.Join(fields, ",")) - fmt.Fprintf(b, "}\n") - } - - // gofmt - res, err := format.Source(b.Bytes()) - if err != nil { - b.WriteTo(os.Stderr) - log.Fatal(err) - } - - // write result - f, err := os.Create("ztypes.go") - fatalIfErr(err) - defer f.Close() - f.Write(res) -} - -func fatalIfErr(err error) { - if err != nil { - log.Fatal(err) - } -} diff --git a/vendor/golang.org/x/sys/unix/mkpost.go b/vendor/golang.org/x/sys/unix/mkpost.go deleted file mode 100644 index ed50d902af..0000000000 --- a/vendor/golang.org/x/sys/unix/mkpost.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// mkpost processes the output of cgo -godefs to -// modify the generated types. It is used to clean up -// the sys API in an architecture specific manner. -// -// mkpost is run after cgo -godefs by mkall.sh. -package main - -import ( - "fmt" - "go/format" - "io/ioutil" - "log" - "os" - "regexp" -) - -func main() { - b, err := ioutil.ReadAll(os.Stdin) - if err != nil { - log.Fatal(err) - } - s := string(b) - - goarch := os.Getenv("GOARCH") - goos := os.Getenv("GOOS") - if goarch == "s390x" && goos == "linux" { - // Export the types of PtraceRegs fields. - re := regexp.MustCompile("ptrace(Psw|Fpregs|Per)") - s = re.ReplaceAllString(s, "Ptrace$1") - - // Replace padding fields inserted by cgo with blank identifiers. - re = regexp.MustCompile("Pad_cgo[A-Za-z0-9_]*") - s = re.ReplaceAllString(s, "_") - - // Replace other unwanted fields with blank identifiers. - re = regexp.MustCompile("X_[A-Za-z0-9_]*") - s = re.ReplaceAllString(s, "_") - - // Replace the control_regs union with a blank identifier for now. - re = regexp.MustCompile("(Control_regs)\\s+\\[0\\]uint64") - s = re.ReplaceAllString(s, "_ [0]uint64") - } - - // gofmt - b, err = format.Source([]byte(s)) - if err != nil { - log.Fatal(err) - } - - // Append this command to the header to show where the new file - // came from. - re := regexp.MustCompile("(cgo -godefs [a-zA-Z0-9_]+\\.go.*)") - b = re.ReplaceAll(b, []byte("$1 | go run mkpost.go")) - - fmt.Printf("%s", b) -} diff --git a/vendor/golang.org/x/sys/unix/types_darwin.go b/vendor/golang.org/x/sys/unix/types_darwin.go deleted file mode 100644 index 1153261822..0000000000 --- a/vendor/golang.org/x/sys/unix/types_darwin.go +++ /dev/null @@ -1,250 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -Input to cgo -godefs. See also mkerrors.sh and mkall.sh -*/ - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package unix - -/* -#define __DARWIN_UNIX03 0 -#define KERNEL -#define _DARWIN_USE_64_BIT_INODE -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -enum { - sizeofPtr = sizeof(void*), -}; - -union sockaddr_all { - struct sockaddr s1; // this one gets used for fields - struct sockaddr_in s2; // these pad it out - struct sockaddr_in6 s3; - struct sockaddr_un s4; - struct sockaddr_dl s5; -}; - -struct sockaddr_any { - struct sockaddr addr; - char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; -}; - -*/ -import "C" - -// Machine characteristics; for internal use. - -const ( - sizeofPtr = C.sizeofPtr - sizeofShort = C.sizeof_short - sizeofInt = C.sizeof_int - sizeofLong = C.sizeof_long - sizeofLongLong = C.sizeof_longlong -) - -// Basic types - -type ( - _C_short C.short - _C_int C.int - _C_long C.long - _C_long_long C.longlong -) - -// Time - -type Timespec C.struct_timespec - -type Timeval C.struct_timeval - -type Timeval32 C.struct_timeval32 - -// Processes - -type Rusage C.struct_rusage - -type Rlimit C.struct_rlimit - -type _Gid_t C.gid_t - -// Files - -type Stat_t C.struct_stat64 - -type Statfs_t C.struct_statfs64 - -type Flock_t C.struct_flock - -type Fstore_t C.struct_fstore - -type Radvisory_t C.struct_radvisory - -type Fbootstraptransfer_t C.struct_fbootstraptransfer - -type Log2phys_t C.struct_log2phys - -type Fsid C.struct_fsid - -type Dirent C.struct_dirent - -// Sockets - -type RawSockaddrInet4 C.struct_sockaddr_in - -type RawSockaddrInet6 C.struct_sockaddr_in6 - -type RawSockaddrUnix C.struct_sockaddr_un - -type RawSockaddrDatalink C.struct_sockaddr_dl - -type RawSockaddr C.struct_sockaddr - -type RawSockaddrAny C.struct_sockaddr_any - -type _Socklen C.socklen_t - -type Linger C.struct_linger - -type Iovec C.struct_iovec - -type IPMreq C.struct_ip_mreq - -type IPv6Mreq C.struct_ipv6_mreq - -type Msghdr C.struct_msghdr - -type Cmsghdr C.struct_cmsghdr - -type Inet4Pktinfo C.struct_in_pktinfo - -type Inet6Pktinfo C.struct_in6_pktinfo - -type IPv6MTUInfo C.struct_ip6_mtuinfo - -type ICMPv6Filter C.struct_icmp6_filter - -const ( - SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in - SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - SizeofSockaddrAny = C.sizeof_struct_sockaddr_any - SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un - SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl - SizeofLinger = C.sizeof_struct_linger - SizeofIPMreq = C.sizeof_struct_ip_mreq - SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - SizeofMsghdr = C.sizeof_struct_msghdr - SizeofCmsghdr = C.sizeof_struct_cmsghdr - SizeofInet4Pktinfo = C.sizeof_struct_in_pktinfo - SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo - SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -// Ptrace requests - -const ( - PTRACE_TRACEME = C.PT_TRACE_ME - PTRACE_CONT = C.PT_CONTINUE - PTRACE_KILL = C.PT_KILL -) - -// Events (kqueue, kevent) - -type Kevent_t C.struct_kevent - -// Select - -type FdSet C.fd_set - -// Routing and interface messages - -const ( - SizeofIfMsghdr = C.sizeof_struct_if_msghdr - SizeofIfData = C.sizeof_struct_if_data - SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr - SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr - SizeofIfmaMsghdr2 = C.sizeof_struct_ifma_msghdr2 - SizeofRtMsghdr = C.sizeof_struct_rt_msghdr - SizeofRtMetrics = C.sizeof_struct_rt_metrics -) - -type IfMsghdr C.struct_if_msghdr - -type IfData C.struct_if_data - -type IfaMsghdr C.struct_ifa_msghdr - -type IfmaMsghdr C.struct_ifma_msghdr - -type IfmaMsghdr2 C.struct_ifma_msghdr2 - -type RtMsghdr C.struct_rt_msghdr - -type RtMetrics C.struct_rt_metrics - -// Berkeley packet filter - -const ( - SizeofBpfVersion = C.sizeof_struct_bpf_version - SizeofBpfStat = C.sizeof_struct_bpf_stat - SizeofBpfProgram = C.sizeof_struct_bpf_program - SizeofBpfInsn = C.sizeof_struct_bpf_insn - SizeofBpfHdr = C.sizeof_struct_bpf_hdr -) - -type BpfVersion C.struct_bpf_version - -type BpfStat C.struct_bpf_stat - -type BpfProgram C.struct_bpf_program - -type BpfInsn C.struct_bpf_insn - -type BpfHdr C.struct_bpf_hdr - -// Terminal handling - -type Termios C.struct_termios - -// fchmodat-like syscalls. - -const ( - AT_FDCWD = C.AT_FDCWD - AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW -) diff --git a/vendor/golang.org/x/sys/unix/types_dragonfly.go b/vendor/golang.org/x/sys/unix/types_dragonfly.go deleted file mode 100644 index f3c971dffd..0000000000 --- a/vendor/golang.org/x/sys/unix/types_dragonfly.go +++ /dev/null @@ -1,242 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -Input to cgo -godefs. See also mkerrors.sh and mkall.sh -*/ - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package unix - -/* -#define KERNEL -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -enum { - sizeofPtr = sizeof(void*), -}; - -union sockaddr_all { - struct sockaddr s1; // this one gets used for fields - struct sockaddr_in s2; // these pad it out - struct sockaddr_in6 s3; - struct sockaddr_un s4; - struct sockaddr_dl s5; -}; - -struct sockaddr_any { - struct sockaddr addr; - char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; -}; - -*/ -import "C" - -// Machine characteristics; for internal use. - -const ( - sizeofPtr = C.sizeofPtr - sizeofShort = C.sizeof_short - sizeofInt = C.sizeof_int - sizeofLong = C.sizeof_long - sizeofLongLong = C.sizeof_longlong -) - -// Basic types - -type ( - _C_short C.short - _C_int C.int - _C_long C.long - _C_long_long C.longlong -) - -// Time - -type Timespec C.struct_timespec - -type Timeval C.struct_timeval - -// Processes - -type Rusage C.struct_rusage - -type Rlimit C.struct_rlimit - -type _Gid_t C.gid_t - -// Files - -const ( // Directory mode bits - S_IFMT = C.S_IFMT - S_IFIFO = C.S_IFIFO - S_IFCHR = C.S_IFCHR - S_IFDIR = C.S_IFDIR - S_IFBLK = C.S_IFBLK - S_IFREG = C.S_IFREG - S_IFLNK = C.S_IFLNK - S_IFSOCK = C.S_IFSOCK - S_ISUID = C.S_ISUID - S_ISGID = C.S_ISGID - S_ISVTX = C.S_ISVTX - S_IRUSR = C.S_IRUSR - S_IWUSR = C.S_IWUSR - S_IXUSR = C.S_IXUSR -) - -type Stat_t C.struct_stat - -type Statfs_t C.struct_statfs - -type Flock_t C.struct_flock - -type Dirent C.struct_dirent - -type Fsid C.struct_fsid - -// Sockets - -type RawSockaddrInet4 C.struct_sockaddr_in - -type RawSockaddrInet6 C.struct_sockaddr_in6 - -type RawSockaddrUnix C.struct_sockaddr_un - -type RawSockaddrDatalink C.struct_sockaddr_dl - -type RawSockaddr C.struct_sockaddr - -type RawSockaddrAny C.struct_sockaddr_any - -type _Socklen C.socklen_t - -type Linger C.struct_linger - -type Iovec C.struct_iovec - -type IPMreq C.struct_ip_mreq - -type IPv6Mreq C.struct_ipv6_mreq - -type Msghdr C.struct_msghdr - -type Cmsghdr C.struct_cmsghdr - -type Inet6Pktinfo C.struct_in6_pktinfo - -type IPv6MTUInfo C.struct_ip6_mtuinfo - -type ICMPv6Filter C.struct_icmp6_filter - -const ( - SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in - SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - SizeofSockaddrAny = C.sizeof_struct_sockaddr_any - SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un - SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl - SizeofLinger = C.sizeof_struct_linger - SizeofIPMreq = C.sizeof_struct_ip_mreq - SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - SizeofMsghdr = C.sizeof_struct_msghdr - SizeofCmsghdr = C.sizeof_struct_cmsghdr - SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo - SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -// Ptrace requests - -const ( - PTRACE_TRACEME = C.PT_TRACE_ME - PTRACE_CONT = C.PT_CONTINUE - PTRACE_KILL = C.PT_KILL -) - -// Events (kqueue, kevent) - -type Kevent_t C.struct_kevent - -// Select - -type FdSet C.fd_set - -// Routing and interface messages - -const ( - SizeofIfMsghdr = C.sizeof_struct_if_msghdr - SizeofIfData = C.sizeof_struct_if_data - SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr - SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr - SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr - SizeofRtMsghdr = C.sizeof_struct_rt_msghdr - SizeofRtMetrics = C.sizeof_struct_rt_metrics -) - -type IfMsghdr C.struct_if_msghdr - -type IfData C.struct_if_data - -type IfaMsghdr C.struct_ifa_msghdr - -type IfmaMsghdr C.struct_ifma_msghdr - -type IfAnnounceMsghdr C.struct_if_announcemsghdr - -type RtMsghdr C.struct_rt_msghdr - -type RtMetrics C.struct_rt_metrics - -// Berkeley packet filter - -const ( - SizeofBpfVersion = C.sizeof_struct_bpf_version - SizeofBpfStat = C.sizeof_struct_bpf_stat - SizeofBpfProgram = C.sizeof_struct_bpf_program - SizeofBpfInsn = C.sizeof_struct_bpf_insn - SizeofBpfHdr = C.sizeof_struct_bpf_hdr -) - -type BpfVersion C.struct_bpf_version - -type BpfStat C.struct_bpf_stat - -type BpfProgram C.struct_bpf_program - -type BpfInsn C.struct_bpf_insn - -type BpfHdr C.struct_bpf_hdr - -// Terminal handling - -type Termios C.struct_termios diff --git a/vendor/golang.org/x/sys/unix/types_freebsd.go b/vendor/golang.org/x/sys/unix/types_freebsd.go deleted file mode 100644 index ae24557ad1..0000000000 --- a/vendor/golang.org/x/sys/unix/types_freebsd.go +++ /dev/null @@ -1,353 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -Input to cgo -godefs. See also mkerrors.sh and mkall.sh -*/ - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package unix - -/* -#define KERNEL -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -enum { - sizeofPtr = sizeof(void*), -}; - -union sockaddr_all { - struct sockaddr s1; // this one gets used for fields - struct sockaddr_in s2; // these pad it out - struct sockaddr_in6 s3; - struct sockaddr_un s4; - struct sockaddr_dl s5; -}; - -struct sockaddr_any { - struct sockaddr addr; - char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; -}; - -// This structure is a duplicate of stat on FreeBSD 8-STABLE. -// See /usr/include/sys/stat.h. -struct stat8 { -#undef st_atimespec st_atim -#undef st_mtimespec st_mtim -#undef st_ctimespec st_ctim -#undef st_birthtimespec st_birthtim - __dev_t st_dev; - ino_t st_ino; - mode_t st_mode; - nlink_t st_nlink; - uid_t st_uid; - gid_t st_gid; - __dev_t st_rdev; -#if __BSD_VISIBLE - struct timespec st_atimespec; - struct timespec st_mtimespec; - struct timespec st_ctimespec; -#else - time_t st_atime; - long __st_atimensec; - time_t st_mtime; - long __st_mtimensec; - time_t st_ctime; - long __st_ctimensec; -#endif - off_t st_size; - blkcnt_t st_blocks; - blksize_t st_blksize; - fflags_t st_flags; - __uint32_t st_gen; - __int32_t st_lspare; -#if __BSD_VISIBLE - struct timespec st_birthtimespec; - unsigned int :(8 / 2) * (16 - (int)sizeof(struct timespec)); - unsigned int :(8 / 2) * (16 - (int)sizeof(struct timespec)); -#else - time_t st_birthtime; - long st_birthtimensec; - unsigned int :(8 / 2) * (16 - (int)sizeof(struct __timespec)); - unsigned int :(8 / 2) * (16 - (int)sizeof(struct __timespec)); -#endif -}; - -// This structure is a duplicate of if_data on FreeBSD 8-STABLE. -// See /usr/include/net/if.h. -struct if_data8 { - u_char ifi_type; - u_char ifi_physical; - u_char ifi_addrlen; - u_char ifi_hdrlen; - u_char ifi_link_state; - u_char ifi_spare_char1; - u_char ifi_spare_char2; - u_char ifi_datalen; - u_long ifi_mtu; - u_long ifi_metric; - u_long ifi_baudrate; - u_long ifi_ipackets; - u_long ifi_ierrors; - u_long ifi_opackets; - u_long ifi_oerrors; - u_long ifi_collisions; - u_long ifi_ibytes; - u_long ifi_obytes; - u_long ifi_imcasts; - u_long ifi_omcasts; - u_long ifi_iqdrops; - u_long ifi_noproto; - u_long ifi_hwassist; - time_t ifi_epoch; - struct timeval ifi_lastchange; -}; - -// This structure is a duplicate of if_msghdr on FreeBSD 8-STABLE. -// See /usr/include/net/if.h. -struct if_msghdr8 { - u_short ifm_msglen; - u_char ifm_version; - u_char ifm_type; - int ifm_addrs; - int ifm_flags; - u_short ifm_index; - struct if_data8 ifm_data; -}; -*/ -import "C" - -// Machine characteristics; for internal use. - -const ( - sizeofPtr = C.sizeofPtr - sizeofShort = C.sizeof_short - sizeofInt = C.sizeof_int - sizeofLong = C.sizeof_long - sizeofLongLong = C.sizeof_longlong -) - -// Basic types - -type ( - _C_short C.short - _C_int C.int - _C_long C.long - _C_long_long C.longlong -) - -// Time - -type Timespec C.struct_timespec - -type Timeval C.struct_timeval - -// Processes - -type Rusage C.struct_rusage - -type Rlimit C.struct_rlimit - -type _Gid_t C.gid_t - -// Files - -const ( // Directory mode bits - S_IFMT = C.S_IFMT - S_IFIFO = C.S_IFIFO - S_IFCHR = C.S_IFCHR - S_IFDIR = C.S_IFDIR - S_IFBLK = C.S_IFBLK - S_IFREG = C.S_IFREG - S_IFLNK = C.S_IFLNK - S_IFSOCK = C.S_IFSOCK - S_ISUID = C.S_ISUID - S_ISGID = C.S_ISGID - S_ISVTX = C.S_ISVTX - S_IRUSR = C.S_IRUSR - S_IWUSR = C.S_IWUSR - S_IXUSR = C.S_IXUSR -) - -type Stat_t C.struct_stat8 - -type Statfs_t C.struct_statfs - -type Flock_t C.struct_flock - -type Dirent C.struct_dirent - -type Fsid C.struct_fsid - -// Advice to Fadvise - -const ( - FADV_NORMAL = C.POSIX_FADV_NORMAL - FADV_RANDOM = C.POSIX_FADV_RANDOM - FADV_SEQUENTIAL = C.POSIX_FADV_SEQUENTIAL - FADV_WILLNEED = C.POSIX_FADV_WILLNEED - FADV_DONTNEED = C.POSIX_FADV_DONTNEED - FADV_NOREUSE = C.POSIX_FADV_NOREUSE -) - -// Sockets - -type RawSockaddrInet4 C.struct_sockaddr_in - -type RawSockaddrInet6 C.struct_sockaddr_in6 - -type RawSockaddrUnix C.struct_sockaddr_un - -type RawSockaddrDatalink C.struct_sockaddr_dl - -type RawSockaddr C.struct_sockaddr - -type RawSockaddrAny C.struct_sockaddr_any - -type _Socklen C.socklen_t - -type Linger C.struct_linger - -type Iovec C.struct_iovec - -type IPMreq C.struct_ip_mreq - -type IPMreqn C.struct_ip_mreqn - -type IPv6Mreq C.struct_ipv6_mreq - -type Msghdr C.struct_msghdr - -type Cmsghdr C.struct_cmsghdr - -type Inet6Pktinfo C.struct_in6_pktinfo - -type IPv6MTUInfo C.struct_ip6_mtuinfo - -type ICMPv6Filter C.struct_icmp6_filter - -const ( - SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in - SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - SizeofSockaddrAny = C.sizeof_struct_sockaddr_any - SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un - SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl - SizeofLinger = C.sizeof_struct_linger - SizeofIPMreq = C.sizeof_struct_ip_mreq - SizeofIPMreqn = C.sizeof_struct_ip_mreqn - SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - SizeofMsghdr = C.sizeof_struct_msghdr - SizeofCmsghdr = C.sizeof_struct_cmsghdr - SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo - SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -// Ptrace requests - -const ( - PTRACE_TRACEME = C.PT_TRACE_ME - PTRACE_CONT = C.PT_CONTINUE - PTRACE_KILL = C.PT_KILL -) - -// Events (kqueue, kevent) - -type Kevent_t C.struct_kevent - -// Select - -type FdSet C.fd_set - -// Routing and interface messages - -const ( - sizeofIfMsghdr = C.sizeof_struct_if_msghdr - SizeofIfMsghdr = C.sizeof_struct_if_msghdr8 - sizeofIfData = C.sizeof_struct_if_data - SizeofIfData = C.sizeof_struct_if_data8 - SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr - SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr - SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr - SizeofRtMsghdr = C.sizeof_struct_rt_msghdr - SizeofRtMetrics = C.sizeof_struct_rt_metrics -) - -type ifMsghdr C.struct_if_msghdr - -type IfMsghdr C.struct_if_msghdr8 - -type ifData C.struct_if_data - -type IfData C.struct_if_data8 - -type IfaMsghdr C.struct_ifa_msghdr - -type IfmaMsghdr C.struct_ifma_msghdr - -type IfAnnounceMsghdr C.struct_if_announcemsghdr - -type RtMsghdr C.struct_rt_msghdr - -type RtMetrics C.struct_rt_metrics - -// Berkeley packet filter - -const ( - SizeofBpfVersion = C.sizeof_struct_bpf_version - SizeofBpfStat = C.sizeof_struct_bpf_stat - SizeofBpfZbuf = C.sizeof_struct_bpf_zbuf - SizeofBpfProgram = C.sizeof_struct_bpf_program - SizeofBpfInsn = C.sizeof_struct_bpf_insn - SizeofBpfHdr = C.sizeof_struct_bpf_hdr - SizeofBpfZbufHeader = C.sizeof_struct_bpf_zbuf_header -) - -type BpfVersion C.struct_bpf_version - -type BpfStat C.struct_bpf_stat - -type BpfZbuf C.struct_bpf_zbuf - -type BpfProgram C.struct_bpf_program - -type BpfInsn C.struct_bpf_insn - -type BpfHdr C.struct_bpf_hdr - -type BpfZbufHeader C.struct_bpf_zbuf_header - -// Terminal handling - -type Termios C.struct_termios diff --git a/vendor/golang.org/x/sys/unix/types_linux.go b/vendor/golang.org/x/sys/unix/types_linux.go deleted file mode 100644 index 7dea79a8ef..0000000000 --- a/vendor/golang.org/x/sys/unix/types_linux.go +++ /dev/null @@ -1,450 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -Input to cgo -godefs. See also mkerrors.sh and mkall.sh -*/ - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package unix - -/* -#define _LARGEFILE_SOURCE -#define _LARGEFILE64_SOURCE -#define _FILE_OFFSET_BITS 64 -#define _GNU_SOURCE - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef TCSETS2 -// On systems that have "struct termios2" use this as type Termios. -typedef struct termios2 termios_t; -#else -typedef struct termios termios_t; -#endif - -enum { - sizeofPtr = sizeof(void*), -}; - -union sockaddr_all { - struct sockaddr s1; // this one gets used for fields - struct sockaddr_in s2; // these pad it out - struct sockaddr_in6 s3; - struct sockaddr_un s4; - struct sockaddr_ll s5; - struct sockaddr_nl s6; -}; - -struct sockaddr_any { - struct sockaddr addr; - char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; -}; - -// copied from /usr/include/linux/un.h -struct my_sockaddr_un { - sa_family_t sun_family; -#if defined(__ARM_EABI__) || defined(__powerpc64__) - // on ARM char is by default unsigned - signed char sun_path[108]; -#else - char sun_path[108]; -#endif -}; - -#ifdef __ARM_EABI__ -typedef struct user_regs PtraceRegs; -#elif defined(__aarch64__) -typedef struct user_pt_regs PtraceRegs; -#elif defined(__powerpc64__) -typedef struct pt_regs PtraceRegs; -#elif defined(__mips__) -typedef struct user PtraceRegs; -#elif defined(__s390x__) -typedef struct _user_regs_struct PtraceRegs; -#else -typedef struct user_regs_struct PtraceRegs; -#endif - -#if defined(__s390x__) -typedef struct _user_psw_struct ptracePsw; -typedef struct _user_fpregs_struct ptraceFpregs; -typedef struct _user_per_struct ptracePer; -#else -typedef struct {} ptracePsw; -typedef struct {} ptraceFpregs; -typedef struct {} ptracePer; -#endif - -// The real epoll_event is a union, and godefs doesn't handle it well. -struct my_epoll_event { - uint32_t events; -#if defined(__ARM_EABI__) || defined(__aarch64__) - // padding is not specified in linux/eventpoll.h but added to conform to the - // alignment requirements of EABI - int32_t padFd; -#elif defined(__powerpc64__) || defined(__s390x__) - int32_t _padFd; -#endif - int32_t fd; - int32_t pad; -}; - -*/ -import "C" - -// Machine characteristics; for internal use. - -const ( - sizeofPtr = C.sizeofPtr - sizeofShort = C.sizeof_short - sizeofInt = C.sizeof_int - sizeofLong = C.sizeof_long - sizeofLongLong = C.sizeof_longlong - PathMax = C.PATH_MAX -) - -// Basic types - -type ( - _C_short C.short - _C_int C.int - _C_long C.long - _C_long_long C.longlong -) - -// Time - -type Timespec C.struct_timespec - -type Timeval C.struct_timeval - -type Timex C.struct_timex - -type Time_t C.time_t - -type Tms C.struct_tms - -type Utimbuf C.struct_utimbuf - -// Processes - -type Rusage C.struct_rusage - -type Rlimit C.struct_rlimit - -type _Gid_t C.gid_t - -// Files - -type Stat_t C.struct_stat - -type Statfs_t C.struct_statfs - -type Dirent C.struct_dirent - -type Fsid C.fsid_t - -type Flock_t C.struct_flock - -// Advice to Fadvise - -const ( - FADV_NORMAL = C.POSIX_FADV_NORMAL - FADV_RANDOM = C.POSIX_FADV_RANDOM - FADV_SEQUENTIAL = C.POSIX_FADV_SEQUENTIAL - FADV_WILLNEED = C.POSIX_FADV_WILLNEED - FADV_DONTNEED = C.POSIX_FADV_DONTNEED - FADV_NOREUSE = C.POSIX_FADV_NOREUSE -) - -// Sockets - -type RawSockaddrInet4 C.struct_sockaddr_in - -type RawSockaddrInet6 C.struct_sockaddr_in6 - -type RawSockaddrUnix C.struct_my_sockaddr_un - -type RawSockaddrLinklayer C.struct_sockaddr_ll - -type RawSockaddrNetlink C.struct_sockaddr_nl - -type RawSockaddrHCI C.struct_sockaddr_hci - -type RawSockaddr C.struct_sockaddr - -type RawSockaddrAny C.struct_sockaddr_any - -type _Socklen C.socklen_t - -type Linger C.struct_linger - -type Iovec C.struct_iovec - -type IPMreq C.struct_ip_mreq - -type IPMreqn C.struct_ip_mreqn - -type IPv6Mreq C.struct_ipv6_mreq - -type Msghdr C.struct_msghdr - -type Cmsghdr C.struct_cmsghdr - -type Inet4Pktinfo C.struct_in_pktinfo - -type Inet6Pktinfo C.struct_in6_pktinfo - -type IPv6MTUInfo C.struct_ip6_mtuinfo - -type ICMPv6Filter C.struct_icmp6_filter - -type Ucred C.struct_ucred - -type TCPInfo C.struct_tcp_info - -const ( - SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in - SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - SizeofSockaddrAny = C.sizeof_struct_sockaddr_any - SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un - SizeofSockaddrLinklayer = C.sizeof_struct_sockaddr_ll - SizeofSockaddrNetlink = C.sizeof_struct_sockaddr_nl - SizeofSockaddrHCI = C.sizeof_struct_sockaddr_hci - SizeofLinger = C.sizeof_struct_linger - SizeofIPMreq = C.sizeof_struct_ip_mreq - SizeofIPMreqn = C.sizeof_struct_ip_mreqn - SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - SizeofMsghdr = C.sizeof_struct_msghdr - SizeofCmsghdr = C.sizeof_struct_cmsghdr - SizeofInet4Pktinfo = C.sizeof_struct_in_pktinfo - SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo - SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter - SizeofUcred = C.sizeof_struct_ucred - SizeofTCPInfo = C.sizeof_struct_tcp_info -) - -// Netlink routing and interface messages - -const ( - IFA_UNSPEC = C.IFA_UNSPEC - IFA_ADDRESS = C.IFA_ADDRESS - IFA_LOCAL = C.IFA_LOCAL - IFA_LABEL = C.IFA_LABEL - IFA_BROADCAST = C.IFA_BROADCAST - IFA_ANYCAST = C.IFA_ANYCAST - IFA_CACHEINFO = C.IFA_CACHEINFO - IFA_MULTICAST = C.IFA_MULTICAST - IFLA_UNSPEC = C.IFLA_UNSPEC - IFLA_ADDRESS = C.IFLA_ADDRESS - IFLA_BROADCAST = C.IFLA_BROADCAST - IFLA_IFNAME = C.IFLA_IFNAME - IFLA_MTU = C.IFLA_MTU - IFLA_LINK = C.IFLA_LINK - IFLA_QDISC = C.IFLA_QDISC - IFLA_STATS = C.IFLA_STATS - IFLA_COST = C.IFLA_COST - IFLA_PRIORITY = C.IFLA_PRIORITY - IFLA_MASTER = C.IFLA_MASTER - IFLA_WIRELESS = C.IFLA_WIRELESS - IFLA_PROTINFO = C.IFLA_PROTINFO - IFLA_TXQLEN = C.IFLA_TXQLEN - IFLA_MAP = C.IFLA_MAP - IFLA_WEIGHT = C.IFLA_WEIGHT - IFLA_OPERSTATE = C.IFLA_OPERSTATE - IFLA_LINKMODE = C.IFLA_LINKMODE - IFLA_LINKINFO = C.IFLA_LINKINFO - IFLA_NET_NS_PID = C.IFLA_NET_NS_PID - IFLA_IFALIAS = C.IFLA_IFALIAS - IFLA_MAX = C.IFLA_MAX - RT_SCOPE_UNIVERSE = C.RT_SCOPE_UNIVERSE - RT_SCOPE_SITE = C.RT_SCOPE_SITE - RT_SCOPE_LINK = C.RT_SCOPE_LINK - RT_SCOPE_HOST = C.RT_SCOPE_HOST - RT_SCOPE_NOWHERE = C.RT_SCOPE_NOWHERE - RT_TABLE_UNSPEC = C.RT_TABLE_UNSPEC - RT_TABLE_COMPAT = C.RT_TABLE_COMPAT - RT_TABLE_DEFAULT = C.RT_TABLE_DEFAULT - RT_TABLE_MAIN = C.RT_TABLE_MAIN - RT_TABLE_LOCAL = C.RT_TABLE_LOCAL - RT_TABLE_MAX = C.RT_TABLE_MAX - RTA_UNSPEC = C.RTA_UNSPEC - RTA_DST = C.RTA_DST - RTA_SRC = C.RTA_SRC - RTA_IIF = C.RTA_IIF - RTA_OIF = C.RTA_OIF - RTA_GATEWAY = C.RTA_GATEWAY - RTA_PRIORITY = C.RTA_PRIORITY - RTA_PREFSRC = C.RTA_PREFSRC - RTA_METRICS = C.RTA_METRICS - RTA_MULTIPATH = C.RTA_MULTIPATH - RTA_FLOW = C.RTA_FLOW - RTA_CACHEINFO = C.RTA_CACHEINFO - RTA_TABLE = C.RTA_TABLE - RTN_UNSPEC = C.RTN_UNSPEC - RTN_UNICAST = C.RTN_UNICAST - RTN_LOCAL = C.RTN_LOCAL - RTN_BROADCAST = C.RTN_BROADCAST - RTN_ANYCAST = C.RTN_ANYCAST - RTN_MULTICAST = C.RTN_MULTICAST - RTN_BLACKHOLE = C.RTN_BLACKHOLE - RTN_UNREACHABLE = C.RTN_UNREACHABLE - RTN_PROHIBIT = C.RTN_PROHIBIT - RTN_THROW = C.RTN_THROW - RTN_NAT = C.RTN_NAT - RTN_XRESOLVE = C.RTN_XRESOLVE - RTNLGRP_NONE = C.RTNLGRP_NONE - RTNLGRP_LINK = C.RTNLGRP_LINK - RTNLGRP_NOTIFY = C.RTNLGRP_NOTIFY - RTNLGRP_NEIGH = C.RTNLGRP_NEIGH - RTNLGRP_TC = C.RTNLGRP_TC - RTNLGRP_IPV4_IFADDR = C.RTNLGRP_IPV4_IFADDR - RTNLGRP_IPV4_MROUTE = C.RTNLGRP_IPV4_MROUTE - RTNLGRP_IPV4_ROUTE = C.RTNLGRP_IPV4_ROUTE - RTNLGRP_IPV4_RULE = C.RTNLGRP_IPV4_RULE - RTNLGRP_IPV6_IFADDR = C.RTNLGRP_IPV6_IFADDR - RTNLGRP_IPV6_MROUTE = C.RTNLGRP_IPV6_MROUTE - RTNLGRP_IPV6_ROUTE = C.RTNLGRP_IPV6_ROUTE - RTNLGRP_IPV6_IFINFO = C.RTNLGRP_IPV6_IFINFO - RTNLGRP_IPV6_PREFIX = C.RTNLGRP_IPV6_PREFIX - RTNLGRP_IPV6_RULE = C.RTNLGRP_IPV6_RULE - RTNLGRP_ND_USEROPT = C.RTNLGRP_ND_USEROPT - SizeofNlMsghdr = C.sizeof_struct_nlmsghdr - SizeofNlMsgerr = C.sizeof_struct_nlmsgerr - SizeofRtGenmsg = C.sizeof_struct_rtgenmsg - SizeofNlAttr = C.sizeof_struct_nlattr - SizeofRtAttr = C.sizeof_struct_rtattr - SizeofIfInfomsg = C.sizeof_struct_ifinfomsg - SizeofIfAddrmsg = C.sizeof_struct_ifaddrmsg - SizeofRtMsg = C.sizeof_struct_rtmsg - SizeofRtNexthop = C.sizeof_struct_rtnexthop -) - -type NlMsghdr C.struct_nlmsghdr - -type NlMsgerr C.struct_nlmsgerr - -type RtGenmsg C.struct_rtgenmsg - -type NlAttr C.struct_nlattr - -type RtAttr C.struct_rtattr - -type IfInfomsg C.struct_ifinfomsg - -type IfAddrmsg C.struct_ifaddrmsg - -type RtMsg C.struct_rtmsg - -type RtNexthop C.struct_rtnexthop - -// Linux socket filter - -const ( - SizeofSockFilter = C.sizeof_struct_sock_filter - SizeofSockFprog = C.sizeof_struct_sock_fprog -) - -type SockFilter C.struct_sock_filter - -type SockFprog C.struct_sock_fprog - -// Inotify - -type InotifyEvent C.struct_inotify_event - -const SizeofInotifyEvent = C.sizeof_struct_inotify_event - -// Ptrace - -// Register structures -type PtraceRegs C.PtraceRegs - -// Structures contained in PtraceRegs on s390x (exported by mkpost.go) -type ptracePsw C.ptracePsw - -type ptraceFpregs C.ptraceFpregs - -type ptracePer C.ptracePer - -// Misc - -type FdSet C.fd_set - -type Sysinfo_t C.struct_sysinfo - -type Utsname C.struct_utsname - -type Ustat_t C.struct_ustat - -type EpollEvent C.struct_my_epoll_event - -const ( - AT_FDCWD = C.AT_FDCWD - AT_REMOVEDIR = C.AT_REMOVEDIR - AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW - AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW -) - -type PollFd C.struct_pollfd - -const ( - POLLIN = C.POLLIN - POLLPRI = C.POLLPRI - POLLOUT = C.POLLOUT - POLLRDHUP = C.POLLRDHUP - POLLERR = C.POLLERR - POLLHUP = C.POLLHUP - POLLNVAL = C.POLLNVAL -) - -type Sigset_t C.sigset_t - -// Terminal handling - -type Termios C.termios_t diff --git a/vendor/golang.org/x/sys/unix/types_netbsd.go b/vendor/golang.org/x/sys/unix/types_netbsd.go deleted file mode 100644 index d15f93d192..0000000000 --- a/vendor/golang.org/x/sys/unix/types_netbsd.go +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -Input to cgo -godefs. See also mkerrors.sh and mkall.sh -*/ - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package unix - -/* -#define KERNEL -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -enum { - sizeofPtr = sizeof(void*), -}; - -union sockaddr_all { - struct sockaddr s1; // this one gets used for fields - struct sockaddr_in s2; // these pad it out - struct sockaddr_in6 s3; - struct sockaddr_un s4; - struct sockaddr_dl s5; -}; - -struct sockaddr_any { - struct sockaddr addr; - char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; -}; - -*/ -import "C" - -// Machine characteristics; for internal use. - -const ( - sizeofPtr = C.sizeofPtr - sizeofShort = C.sizeof_short - sizeofInt = C.sizeof_int - sizeofLong = C.sizeof_long - sizeofLongLong = C.sizeof_longlong -) - -// Basic types - -type ( - _C_short C.short - _C_int C.int - _C_long C.long - _C_long_long C.longlong -) - -// Time - -type Timespec C.struct_timespec - -type Timeval C.struct_timeval - -// Processes - -type Rusage C.struct_rusage - -type Rlimit C.struct_rlimit - -type _Gid_t C.gid_t - -// Files - -type Stat_t C.struct_stat - -type Statfs_t C.struct_statfs - -type Flock_t C.struct_flock - -type Dirent C.struct_dirent - -type Fsid C.fsid_t - -// Sockets - -type RawSockaddrInet4 C.struct_sockaddr_in - -type RawSockaddrInet6 C.struct_sockaddr_in6 - -type RawSockaddrUnix C.struct_sockaddr_un - -type RawSockaddrDatalink C.struct_sockaddr_dl - -type RawSockaddr C.struct_sockaddr - -type RawSockaddrAny C.struct_sockaddr_any - -type _Socklen C.socklen_t - -type Linger C.struct_linger - -type Iovec C.struct_iovec - -type IPMreq C.struct_ip_mreq - -type IPv6Mreq C.struct_ipv6_mreq - -type Msghdr C.struct_msghdr - -type Cmsghdr C.struct_cmsghdr - -type Inet6Pktinfo C.struct_in6_pktinfo - -type IPv6MTUInfo C.struct_ip6_mtuinfo - -type ICMPv6Filter C.struct_icmp6_filter - -const ( - SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in - SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - SizeofSockaddrAny = C.sizeof_struct_sockaddr_any - SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un - SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl - SizeofLinger = C.sizeof_struct_linger - SizeofIPMreq = C.sizeof_struct_ip_mreq - SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - SizeofMsghdr = C.sizeof_struct_msghdr - SizeofCmsghdr = C.sizeof_struct_cmsghdr - SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo - SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -// Ptrace requests - -const ( - PTRACE_TRACEME = C.PT_TRACE_ME - PTRACE_CONT = C.PT_CONTINUE - PTRACE_KILL = C.PT_KILL -) - -// Events (kqueue, kevent) - -type Kevent_t C.struct_kevent - -// Select - -type FdSet C.fd_set - -// Routing and interface messages - -const ( - SizeofIfMsghdr = C.sizeof_struct_if_msghdr - SizeofIfData = C.sizeof_struct_if_data - SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr - SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr - SizeofRtMsghdr = C.sizeof_struct_rt_msghdr - SizeofRtMetrics = C.sizeof_struct_rt_metrics -) - -type IfMsghdr C.struct_if_msghdr - -type IfData C.struct_if_data - -type IfaMsghdr C.struct_ifa_msghdr - -type IfAnnounceMsghdr C.struct_if_announcemsghdr - -type RtMsghdr C.struct_rt_msghdr - -type RtMetrics C.struct_rt_metrics - -type Mclpool C.struct_mclpool - -// Berkeley packet filter - -const ( - SizeofBpfVersion = C.sizeof_struct_bpf_version - SizeofBpfStat = C.sizeof_struct_bpf_stat - SizeofBpfProgram = C.sizeof_struct_bpf_program - SizeofBpfInsn = C.sizeof_struct_bpf_insn - SizeofBpfHdr = C.sizeof_struct_bpf_hdr -) - -type BpfVersion C.struct_bpf_version - -type BpfStat C.struct_bpf_stat - -type BpfProgram C.struct_bpf_program - -type BpfInsn C.struct_bpf_insn - -type BpfHdr C.struct_bpf_hdr - -type BpfTimeval C.struct_bpf_timeval - -// Terminal handling - -type Termios C.struct_termios - -// Sysctl - -type Sysctlnode C.struct_sysctlnode diff --git a/vendor/golang.org/x/sys/unix/types_openbsd.go b/vendor/golang.org/x/sys/unix/types_openbsd.go deleted file mode 100644 index b66fe25f73..0000000000 --- a/vendor/golang.org/x/sys/unix/types_openbsd.go +++ /dev/null @@ -1,244 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -Input to cgo -godefs. See also mkerrors.sh and mkall.sh -*/ - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package unix - -/* -#define KERNEL -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -enum { - sizeofPtr = sizeof(void*), -}; - -union sockaddr_all { - struct sockaddr s1; // this one gets used for fields - struct sockaddr_in s2; // these pad it out - struct sockaddr_in6 s3; - struct sockaddr_un s4; - struct sockaddr_dl s5; -}; - -struct sockaddr_any { - struct sockaddr addr; - char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; -}; - -*/ -import "C" - -// Machine characteristics; for internal use. - -const ( - sizeofPtr = C.sizeofPtr - sizeofShort = C.sizeof_short - sizeofInt = C.sizeof_int - sizeofLong = C.sizeof_long - sizeofLongLong = C.sizeof_longlong -) - -// Basic types - -type ( - _C_short C.short - _C_int C.int - _C_long C.long - _C_long_long C.longlong -) - -// Time - -type Timespec C.struct_timespec - -type Timeval C.struct_timeval - -// Processes - -type Rusage C.struct_rusage - -type Rlimit C.struct_rlimit - -type _Gid_t C.gid_t - -// Files - -const ( // Directory mode bits - S_IFMT = C.S_IFMT - S_IFIFO = C.S_IFIFO - S_IFCHR = C.S_IFCHR - S_IFDIR = C.S_IFDIR - S_IFBLK = C.S_IFBLK - S_IFREG = C.S_IFREG - S_IFLNK = C.S_IFLNK - S_IFSOCK = C.S_IFSOCK - S_ISUID = C.S_ISUID - S_ISGID = C.S_ISGID - S_ISVTX = C.S_ISVTX - S_IRUSR = C.S_IRUSR - S_IWUSR = C.S_IWUSR - S_IXUSR = C.S_IXUSR -) - -type Stat_t C.struct_stat - -type Statfs_t C.struct_statfs - -type Flock_t C.struct_flock - -type Dirent C.struct_dirent - -type Fsid C.fsid_t - -// Sockets - -type RawSockaddrInet4 C.struct_sockaddr_in - -type RawSockaddrInet6 C.struct_sockaddr_in6 - -type RawSockaddrUnix C.struct_sockaddr_un - -type RawSockaddrDatalink C.struct_sockaddr_dl - -type RawSockaddr C.struct_sockaddr - -type RawSockaddrAny C.struct_sockaddr_any - -type _Socklen C.socklen_t - -type Linger C.struct_linger - -type Iovec C.struct_iovec - -type IPMreq C.struct_ip_mreq - -type IPv6Mreq C.struct_ipv6_mreq - -type Msghdr C.struct_msghdr - -type Cmsghdr C.struct_cmsghdr - -type Inet6Pktinfo C.struct_in6_pktinfo - -type IPv6MTUInfo C.struct_ip6_mtuinfo - -type ICMPv6Filter C.struct_icmp6_filter - -const ( - SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in - SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - SizeofSockaddrAny = C.sizeof_struct_sockaddr_any - SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un - SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl - SizeofLinger = C.sizeof_struct_linger - SizeofIPMreq = C.sizeof_struct_ip_mreq - SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - SizeofMsghdr = C.sizeof_struct_msghdr - SizeofCmsghdr = C.sizeof_struct_cmsghdr - SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo - SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -// Ptrace requests - -const ( - PTRACE_TRACEME = C.PT_TRACE_ME - PTRACE_CONT = C.PT_CONTINUE - PTRACE_KILL = C.PT_KILL -) - -// Events (kqueue, kevent) - -type Kevent_t C.struct_kevent - -// Select - -type FdSet C.fd_set - -// Routing and interface messages - -const ( - SizeofIfMsghdr = C.sizeof_struct_if_msghdr - SizeofIfData = C.sizeof_struct_if_data - SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr - SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr - SizeofRtMsghdr = C.sizeof_struct_rt_msghdr - SizeofRtMetrics = C.sizeof_struct_rt_metrics -) - -type IfMsghdr C.struct_if_msghdr - -type IfData C.struct_if_data - -type IfaMsghdr C.struct_ifa_msghdr - -type IfAnnounceMsghdr C.struct_if_announcemsghdr - -type RtMsghdr C.struct_rt_msghdr - -type RtMetrics C.struct_rt_metrics - -type Mclpool C.struct_mclpool - -// Berkeley packet filter - -const ( - SizeofBpfVersion = C.sizeof_struct_bpf_version - SizeofBpfStat = C.sizeof_struct_bpf_stat - SizeofBpfProgram = C.sizeof_struct_bpf_program - SizeofBpfInsn = C.sizeof_struct_bpf_insn - SizeofBpfHdr = C.sizeof_struct_bpf_hdr -) - -type BpfVersion C.struct_bpf_version - -type BpfStat C.struct_bpf_stat - -type BpfProgram C.struct_bpf_program - -type BpfInsn C.struct_bpf_insn - -type BpfHdr C.struct_bpf_hdr - -type BpfTimeval C.struct_bpf_timeval - -// Terminal handling - -type Termios C.struct_termios diff --git a/vendor/golang.org/x/sys/unix/types_solaris.go b/vendor/golang.org/x/sys/unix/types_solaris.go deleted file mode 100644 index c5d5c8f16a..0000000000 --- a/vendor/golang.org/x/sys/unix/types_solaris.go +++ /dev/null @@ -1,262 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -Input to cgo -godefs. See also mkerrors.sh and mkall.sh -*/ - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package unix - -/* -#define KERNEL -// These defines ensure that builds done on newer versions of Solaris are -// backwards-compatible with older versions of Solaris and -// OpenSolaris-based derivatives. -#define __USE_SUNOS_SOCKETS__ // msghdr -#define __USE_LEGACY_PROTOTYPES__ // iovec -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -enum { - sizeofPtr = sizeof(void*), -}; - -union sockaddr_all { - struct sockaddr s1; // this one gets used for fields - struct sockaddr_in s2; // these pad it out - struct sockaddr_in6 s3; - struct sockaddr_un s4; - struct sockaddr_dl s5; -}; - -struct sockaddr_any { - struct sockaddr addr; - char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; -}; - -*/ -import "C" - -// Machine characteristics; for internal use. - -const ( - sizeofPtr = C.sizeofPtr - sizeofShort = C.sizeof_short - sizeofInt = C.sizeof_int - sizeofLong = C.sizeof_long - sizeofLongLong = C.sizeof_longlong - PathMax = C.PATH_MAX - MaxHostNameLen = C.MAXHOSTNAMELEN -) - -// Basic types - -type ( - _C_short C.short - _C_int C.int - _C_long C.long - _C_long_long C.longlong -) - -// Time - -type Timespec C.struct_timespec - -type Timeval C.struct_timeval - -type Timeval32 C.struct_timeval32 - -type Tms C.struct_tms - -type Utimbuf C.struct_utimbuf - -// Processes - -type Rusage C.struct_rusage - -type Rlimit C.struct_rlimit - -type _Gid_t C.gid_t - -// Files - -const ( // Directory mode bits - S_IFMT = C.S_IFMT - S_IFIFO = C.S_IFIFO - S_IFCHR = C.S_IFCHR - S_IFDIR = C.S_IFDIR - S_IFBLK = C.S_IFBLK - S_IFREG = C.S_IFREG - S_IFLNK = C.S_IFLNK - S_IFSOCK = C.S_IFSOCK - S_ISUID = C.S_ISUID - S_ISGID = C.S_ISGID - S_ISVTX = C.S_ISVTX - S_IRUSR = C.S_IRUSR - S_IWUSR = C.S_IWUSR - S_IXUSR = C.S_IXUSR -) - -type Stat_t C.struct_stat - -type Flock_t C.struct_flock - -type Dirent C.struct_dirent - -// Sockets - -type RawSockaddrInet4 C.struct_sockaddr_in - -type RawSockaddrInet6 C.struct_sockaddr_in6 - -type RawSockaddrUnix C.struct_sockaddr_un - -type RawSockaddrDatalink C.struct_sockaddr_dl - -type RawSockaddr C.struct_sockaddr - -type RawSockaddrAny C.struct_sockaddr_any - -type _Socklen C.socklen_t - -type Linger C.struct_linger - -type Iovec C.struct_iovec - -type IPMreq C.struct_ip_mreq - -type IPv6Mreq C.struct_ipv6_mreq - -type Msghdr C.struct_msghdr - -type Cmsghdr C.struct_cmsghdr - -type Inet6Pktinfo C.struct_in6_pktinfo - -type IPv6MTUInfo C.struct_ip6_mtuinfo - -type ICMPv6Filter C.struct_icmp6_filter - -const ( - SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in - SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - SizeofSockaddrAny = C.sizeof_struct_sockaddr_any - SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un - SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl - SizeofLinger = C.sizeof_struct_linger - SizeofIPMreq = C.sizeof_struct_ip_mreq - SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - SizeofMsghdr = C.sizeof_struct_msghdr - SizeofCmsghdr = C.sizeof_struct_cmsghdr - SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo - SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -// Select - -type FdSet C.fd_set - -// Misc - -type Utsname C.struct_utsname - -type Ustat_t C.struct_ustat - -const ( - AT_FDCWD = C.AT_FDCWD - AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW - AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW - AT_REMOVEDIR = C.AT_REMOVEDIR - AT_EACCESS = C.AT_EACCESS -) - -// Routing and interface messages - -const ( - SizeofIfMsghdr = C.sizeof_struct_if_msghdr - SizeofIfData = C.sizeof_struct_if_data - SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr - SizeofRtMsghdr = C.sizeof_struct_rt_msghdr - SizeofRtMetrics = C.sizeof_struct_rt_metrics -) - -type IfMsghdr C.struct_if_msghdr - -type IfData C.struct_if_data - -type IfaMsghdr C.struct_ifa_msghdr - -type RtMsghdr C.struct_rt_msghdr - -type RtMetrics C.struct_rt_metrics - -// Berkeley packet filter - -const ( - SizeofBpfVersion = C.sizeof_struct_bpf_version - SizeofBpfStat = C.sizeof_struct_bpf_stat - SizeofBpfProgram = C.sizeof_struct_bpf_program - SizeofBpfInsn = C.sizeof_struct_bpf_insn - SizeofBpfHdr = C.sizeof_struct_bpf_hdr -) - -type BpfVersion C.struct_bpf_version - -type BpfStat C.struct_bpf_stat - -type BpfProgram C.struct_bpf_program - -type BpfInsn C.struct_bpf_insn - -type BpfTimeval C.struct_bpf_timeval - -type BpfHdr C.struct_bpf_hdr - -// sysconf information - -const _SC_PAGESIZE = C._SC_PAGESIZE - -// Terminal handling - -type Termios C.struct_termios - -type Termio C.struct_termio - -type Winsize C.struct_winsize