Skip to content

Commit

Permalink
Add comments and rename
Browse files Browse the repository at this point in the history
Signed-off-by: Weiqiang TANG <[email protected]>
  • Loading branch information
weiqiangt committed Dec 23, 2019
1 parent 29030b5 commit 783f8bb
Show file tree
Hide file tree
Showing 23 changed files with 614 additions and 541 deletions.
11 changes: 8 additions & 3 deletions cmd/antctl/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"math"
"os"
"path"
"strings"

"github.com/spf13/cobra"
"github.com/spf13/pflag"
Expand All @@ -28,7 +29,11 @@ import (
"github.com/vmware-tanzu/antrea/pkg/antctl"
)

var commandName = path.Base(os.Args[0])
var (
commandName = path.Base(os.Args[0])
inPod = len(os.Getenv("POD_NAME")) != 0
isAgent = strings.HasPrefix(os.Getenv("POD_NAME"), "antrea-agent")
)

var rootCmd = &cobra.Command{
Use: commandName,
Expand All @@ -37,7 +42,7 @@ var rootCmd = &cobra.Command{
}

func init() {
// prevent any unexpected output at first
// prevent any unexpected output at beginning
pflag.CommandLine.MarkHidden("log-flush-frequency")
flag.Set("logtostderr", "true")
flag.Set("alsologtostderr", "true")
Expand All @@ -48,8 +53,8 @@ func init() {
func main() {
logs.InitLogs()
defer logs.FlushLogs()
antctl.Init(rootCmd)

antctl.Manifest.ApplyToRootCommand(rootCmd, isAgent, inPod)
err := rootCmd.Execute()
if err != nil {
logs.FlushLogs()
Expand Down
2 changes: 1 addition & 1 deletion cmd/antrea-controller/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ func run(o *Options) error {
go networkPolicyController.Run(stopCh)

preparedAPIServer := apiServer.GenericAPIServer.PrepareRun()
antctl.Definition.ApplyToAPIServer(preparedAPIServer.GenericAPIServer, controllerMonitor)
antctl.Manifest.ApplyToMux(preparedAPIServer.GenericAPIServer.Handler.NonGoRestfulMux, nil, controllerMonitor)
go preparedAPIServer.Run(stopCh)

antctlStoppedCh := antctl.StartServer(antctlServerOpt, nil, controllerMonitor, stopCh)
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ require (
github.com/coreos/go-iptables v0.4.1
github.com/elazarl/goproxy v0.0.0-20190911111923-ecfe977594f1 // indirect
github.com/evanphx/json-patch v4.5.0+incompatible // indirect
github.com/fatih/structtag v1.2.0
github.com/gogo/protobuf v1.2.1
github.com/golang/mock v1.3.1
github.com/golang/protobuf v1.3.2
Expand Down
19 changes: 10 additions & 9 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@ github.com/evanphx/json-patch v0.0.0-20190203023257-5858425f7550/go.mod h1:50XU6
github.com/evanphx/json-patch v4.1.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk=
github.com/evanphx/json-patch v4.5.0+incompatible h1:ouOWdg56aJriqS0huScTkVXPC5IcNrDCXZ6OoTAWu7M=
github.com/evanphx/json-patch v4.5.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk=
github.com/fatih/structtag v1.1.0 h1:6j4mUV/ES2duvnAzKMFkN6/A5mCaNYPD3xfbAkLLOF8=
github.com/fatih/structtag v1.1.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94=
github.com/fatih/structtag v1.2.0 h1:/OdNE99OxoI/PqaW/SuSK9uxxT3f/tcSZgon/ssNSx4=
github.com/fatih/structtag v1.2.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94=
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/ghodss/yaml v0.0.0-20180820084758-c7ce16629ff4 h1:bRzFpEzvausOAt4va+I/22BZ1vXDtERngp0BNYDKej0=
Expand Down Expand Up @@ -352,8 +352,8 @@ golang.org/x/crypto v0.0.0-20181009213950-7c1a557ab941/go.mod h1:6SG95UA2DQfeDnf
golang.org/x/crypto v0.0.0-20181025213731-e84da0312774/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550 h1:ObdrDkeb4kJdCP557AjRjq69pTHfNouLtWZG7j9rPN8=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191128160524-b544559bb6d1 h1:anGSYQpPhQwXlwsu5wmfq0nWkCNaMEMUwAv13Y92hd8=
golang.org/x/crypto v0.0.0-20191128160524-b544559bb6d1/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4 h1:c2HOrn5iMezYjSlGPncknSEr/8x5LELb/ilJbXi9DEA=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
Expand All @@ -374,8 +374,8 @@ golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73r
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190628185345-da137c7871d7 h1:rTIdg5QFRR7XCaK4LCjBiPbx8j4DQRpdYMnGn/bJUEU=
golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20191126235420-ef20fe5d7933 h1:e6HwijUxhDe+hPNjZQQn9bA5PW3vNmnN64U2ZW759Lk=
golang.org/x/net v0.0.0-20191126235420-ef20fe5d7933/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190402181905-9f3314589c9a/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
Expand All @@ -385,8 +385,9 @@ golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e h1:vcxGaoTs7kV8m5Np9uUNQin4BrLOthgV7252N8V+FwY=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
Expand All @@ -399,8 +400,8 @@ golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190616124812-15dcb6c0061f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191008105621-543471e840be h1:QAcqgptGM8IQBC9K/RC4o+O9YmqEm0diQn9QmZw/0mU=
golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191128015809-6d18c012aee9 h1:ZBzSG/7F4eNKz2L3GE9o300RX0Az1Bw5HF7PDraD+qU=
golang.org/x/sys v0.0.0-20191128015809-6d18c012aee9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20181227161524-e6919f6577db/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
Expand Down
1 change: 1 addition & 0 deletions hack/update-codegen-dockerized.sh
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ MOCKGEN_TARGETS=(
"pkg/agent/openflow Client,FlowOperations"
"pkg/ovs/openflow Bridge,Table,Flow,Action,FlowBuilder"
"pkg/ovs/ovsconfig OVSBridgeClient"
"pkg/monitor AgentQuerier,ControllerQuerier"
)

for target in "${MOCKGEN_TARGETS[@]}"; do
Expand Down
99 changes: 62 additions & 37 deletions pkg/antctl/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,91 +22,123 @@ import (
"net"
"net/http"
"net/url"
"os"
"path"
"strings"
"time"

"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/klog"
)

var isAgent = strings.HasPrefix(os.Getenv("POD_NAME"), "antrea-agent")

// RequestOption contains options to do a request to CLI server.
// RequestOption describes options to issue requests to the antctl server.
type RequestOption struct {
// Kubeconfig is the path to the config file for kubectl.
Kubeconfig string
Name string
Args map[string]string
// Name is the Use of the command going to be requested.
Name string
// Args are the parameters of the ongoing request.
Args map[string]string
// Timeout specifies a time limit for requests made by the client. The timeout
// includes connection time, any redirects, and reading the response body.
TimeOut time.Duration
}

// URI returns the request path of the request option.
func (opt *RequestOption) URI(gv *schema.GroupVersion) string {
// URI constructs the request URI of the request option. It expands Args to query
// parameters in URL. It returns the URI in the format: "/apis/(API Group)/(API Version)/(command Use)[?parameters]".
func (ro *RequestOption) URI(version *schema.GroupVersion) string {
u := new(url.URL)
u.Path = path.Join("/apis", gv.Group, gv.Version, opt.Name)
u.Path = path.Join("/apis", version.Group, version.Version, ro.Name)

q := u.Query()
for k, v := range opt.Args {
for k, v := range ro.Args {
q.Set(k, v)
}
u.RawQuery = q.Encode()

return u.RequestURI()
}

// Client issues requests to a CLI server and gets the response.
type Client struct {
GroupVersion *schema.GroupVersion
Codec serializer.CodecFactory
// client issues requests to an antctl server and gets the response.
type client struct {
// inPod tells the running mode of the client.
inPod bool
// groupVersion describes the group version the corresponding antctl server be installed.
groupVersion *schema.GroupVersion
// codec is the CodecFactory for this command, it is needed for remote accessing.
codec serializer.CodecFactory
}

func (c *Client) resolveKubeconfig(opt *RequestOption) (*rest.Config, error) {
// resolveKubeconfig tries to load the kubeconfig specified in the RequestOption.
// It will return error if the stating of the file failed or the kubeconfig is malformed.
// It will not try to look up InCluster configuration. If the kubeconfig is loaded,
// The GroupVersion and the Codec in the RequestOption will be populated into the
// kubeconfig object.
func (c *client) resolveKubeconfig(opt *RequestOption) (*rest.Config, error) {
kubeconfig, err := clientcmd.BuildConfigFromFlags("", opt.Kubeconfig)
if err != nil {
return nil, err
}
kubeconfig.GroupVersion = c.GroupVersion
kubeconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: c.Codec}
kubeconfig.GroupVersion = c.groupVersion
kubeconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: c.codec}
return kubeconfig, nil
}

func (c *Client) localDo(cmd *cobra.Command, opt *RequestOption) (io.Reader, error) {
// localRequest issues the local request according to the RequestOption. It only cares
// the groupVersion of the RequestOption which will be used to construct the request
// URI. localRequest is basically a raw http request, none authentication and authorization
// will be done during the request. For safety concerns, it communicates with the
// antctl server by a predefined unix domain socket. If the request succeeded, it
// will returns an io.Reader which contains the response data.
func (c *client) localRequest(opt *RequestOption) (io.Reader, error) {
uri := opt.URI(c.groupVersion)
klog.Infof("Requesting URI %s", uri)
client := &http.Client{
Transport: &http.Transport{
DialContext: func(ctx context.Context, _, _ string) (conn net.Conn, err error) {
var cancel context.CancelFunc
if opt.TimeOut != 0 {
ctx, cancel = context.WithTimeout(ctx, opt.TimeOut)
defer cancel()
}
return new(net.Dialer).DialContext(ctx, "unix", unixDomainSockAddr)
},
},
}
uri := opt.URI(c.GroupVersion)
klog.Infof("Requesting URI %s", uri)
resp, err := client.Get("http://antctl" + uri)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Since we are going to close the connection, copying the response.
var buf bytes.Buffer
io.Copy(&buf, resp.Body)
return &buf, nil
_, err = io.Copy(&buf, resp.Body)
return &buf, err
}

// Do issues the appropriate request to the CLI server using the provided command and request options.
func (c *Client) Do(cmd *cobra.Command, opt *RequestOption) (io.Reader, error) {
// Request issues the appropriate request to the antctl server according to the
// request options. If the inPod filed of the client is true, the client will do
// a local request by invoking localRequest. Otherwise, it will check the kubeconfig
// and request the antctl server by the delegation of the kubernetes API server.
// If the request succeeded, it will returns an io.Reader which contains the response
// data.
func (c *client) Request(opt *RequestOption) (io.Reader, error) {
if c.inPod {
klog.Infoln("Antctl runs as local mode")
return c.localRequest(opt)
}
kubeconfig, err := c.resolveKubeconfig(opt)
if err != nil {
klog.Infoln("No kubeconfig, using local mode")
return c.localDo(cmd, opt)
return nil, err
}
restClient, err := rest.RESTClientFor(kubeconfig)
if err != nil {
return nil, fmt.Errorf("failed to create rest client: %w", err)
}
// If timeout is not set, no timeout.
restClient.Client.Timeout, _ = cmd.Flags().GetDuration("timeout")
uri := opt.URI(c.GroupVersion)
restClient.Client.Timeout = opt.TimeOut
uri := opt.URI(c.groupVersion)
result := restClient.Get().RequestURI(uri).Do()
if result.Error() != nil {
return nil, fmt.Errorf("error when requesting URI %s: %w", uri, result.Error())
Expand All @@ -117,10 +149,3 @@ func (c *Client) Do(cmd *cobra.Command, opt *RequestOption) (io.Reader, error) {
}
return bytes.NewReader(raw), nil
}

// Init initializes the root command.
func Init(root *cobra.Command) {
client := new(Client)
Definition.ApplyToClient(client)
Definition.ApplyToRootCommand(root, client, isAgent)
}
Loading

0 comments on commit 783f8bb

Please sign in to comment.