Skip to content

Commit

Permalink
Refactor into package
Browse files Browse the repository at this point in the history
  • Loading branch information
wpjunior committed Jan 23, 2023
1 parent aaddde1 commit 7f41fef
Show file tree
Hide file tree
Showing 6 changed files with 137 additions and 127 deletions.
6 changes: 3 additions & 3 deletions addrule.go → cmd/addrule.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main
package cmd

import (
"bytes"
Expand All @@ -18,7 +18,7 @@ import (
"github.com/tsuru/acl-api/api/types"
)

var addCustomRuleCmd = &cobra.Command{
var AddCustomRuleCmd = &cobra.Command{
Use: "add",
Short: "Add new rule custom rule",
RunE: func(cmd *cobra.Command, args []string) error {
Expand Down Expand Up @@ -58,7 +58,7 @@ var addCustomRuleCmd = &cobra.Command{
},
}

var addRuleCmd = &cobra.Command{
var AddRuleCmd = &cobra.Command{
Use: "add [service name] [instance name]",
Short: "Add new rule",
Example: `
Expand Down
113 changes: 113 additions & 0 deletions cmd/base.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
package cmd

import (
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"strings"
"sync"
"time"

"github.com/Masterminds/semver"
"github.com/pkg/errors"
"github.com/spf13/viper"
"github.com/tsuru/acl-api/api/version"
)

const (
defaultServiceName = "acl"
userAgent = "AclFromHell-Plugin-http-client/1.0"
)

var (
baseClient = &http.Client{
Transport: &http.Transport{
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
IdleConnTimeout: 20 * time.Second,
},
Timeout: time.Minute,
}

warnOnce sync.Once
)

func serviceInstanceName(args []string, minArgs int) (string, string) {
var instanceName string
serviceName := defaultServiceName
if len(args) == minArgs {
instanceName = args[0]
} else if len(args) > minArgs {
serviceName = args[0]
instanceName = args[1]
}
return serviceName, instanceName
}

func doProxyAdminRequest(method, service, path string, body io.Reader) (*http.Response, error) {
baseURL := viper.GetString("tsuru.target")
fullUrl := fmt.Sprintf("%s/services/proxy/service/%s?callback=%s",
strings.TrimSuffix(baseURL, "/"),
service,
path,
)
return doProxyURLRequest(method, fullUrl, body)
}

func doProxyRequest(method, service, instance, path string, body io.Reader) (*http.Response, error) {
baseURL := viper.GetString("tsuru.target")
fullUrl := fmt.Sprintf("%s/services/%s/proxy/%s?callback=%s",
strings.TrimSuffix(baseURL, "/"),
service,
instance,
path,
)
return doProxyURLRequest(method, fullUrl, body)
}

func doProxyURLRequest(method, fullUrl string, body io.Reader) (*http.Response, error) {
token := viper.GetString("tsuru.token")
req, err := http.NewRequest(method, fullUrl, body)
if err != nil {
return nil, err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("Authorization", "bearer "+token)
req.Header.Set("User-Agent", userAgent)
rsp, err := baseClient.Do(req)
if err != nil {
return nil, err
}
if rsp.StatusCode < 200 || rsp.StatusCode >= 400 {
data, _ := ioutil.ReadAll(rsp.Body)
rsp.Body.Close()
return nil, errors.Errorf("invalid status code %d: %q", rsp.StatusCode, string(data))
}
warnOnce.Do(func() {
warnVersion(rsp.Header)
})
return rsp, nil
}

func warnVersion(headers http.Header) {
versionHeader := headers.Get(version.VersionHeader)
serverVersion, _ := semver.NewVersion(versionHeader)
clientVersion, _ := semver.NewVersion(version.Version)
if serverVersion == nil {
serverVersion = &semver.Version{}
}
if clientVersion == nil {
clientVersion = &semver.Version{}
}
if clientVersion.LessThan(serverVersion) {
fmt.Fprintln(os.Stderr, "There is a new version of the acl plugin available. Please update it.")
}
}
6 changes: 3 additions & 3 deletions listrules.go → cmd/listrules.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main
package cmd

import (
"encoding/json"
Expand All @@ -25,7 +25,7 @@ type serviceRuleData struct {
RulesSync []types.RuleSyncInfo
}

var listAllRulesCmd = &cobra.Command{
var ListAllRulesCmd = &cobra.Command{
Use: "list [service name]",
Short: "List all rules",
RunE: func(cmd *cobra.Command, args []string) error {
Expand Down Expand Up @@ -85,7 +85,7 @@ var listAllRulesCmd = &cobra.Command{
},
}

var listRuleCmd = &cobra.Command{
var ListRuleCmd = &cobra.Command{
Use: "list [service name] [instance name]",
Short: "List rules",
Args: cobra.MinimumNArgs(1),
Expand Down
4 changes: 2 additions & 2 deletions removerule.go → cmd/removerule.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main
package cmd

import (
"fmt"
Expand All @@ -11,7 +11,7 @@ import (
"github.com/spf13/cobra"
)

var removeRuleCmd = &cobra.Command{
var RemoveRuleCmd = &cobra.Command{
Use: "remove [service name] [instance name] [id]",
Short: "Remove rule",
Args: cobra.MinimumNArgs(2),
Expand Down
6 changes: 3 additions & 3 deletions syncrule.go → cmd/syncrule.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main
package cmd

import (
"encoding/json"
Expand All @@ -18,7 +18,7 @@ type forceResponse struct {
Count int `json:"count"`
}

var forceSyncCmd = &cobra.Command{
var ForceSyncCmd = &cobra.Command{
Use: "sync [app name]",
Short: "Force sync rules (for debug/troubleshooting purpose)",
Args: cobra.ExactArgs(1),
Expand All @@ -41,7 +41,7 @@ var forceSyncCmd = &cobra.Command{
},
}

var syncDNSCmd = &cobra.Command{
var SyncDNSCmd = &cobra.Command{
Use: "sync-dns [cname]",
Short: "Force sync rules (for debug/troubleshooting purpose)",
Args: cobra.ExactArgs(1),
Expand Down
129 changes: 13 additions & 116 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,120 +5,17 @@
package main

import (
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"strings"
"sync"
"time"

"github.com/Masterminds/semver"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"github.com/tsuru/acl-api/api/version"
"github.com/tsuru/acl-plugin/cmd"
)

const (
userAgent = "AclFromHell-Plugin-http-client/1.0"
defaultServiceName = "acl"
)

var (
baseClient = &http.Client{
Transport: &http.Transport{
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
IdleConnTimeout: 20 * time.Second,
},
Timeout: time.Minute,
}

warnOnce sync.Once
)

func doProxyAdminRequest(method, service, path string, body io.Reader) (*http.Response, error) {
baseURL := viper.GetString("tsuru.target")
fullUrl := fmt.Sprintf("%s/services/proxy/service/%s?callback=%s",
strings.TrimSuffix(baseURL, "/"),
service,
path,
)
return doProxyURLRequest(method, fullUrl, body)
}

func doProxyRequest(method, service, instance, path string, body io.Reader) (*http.Response, error) {
baseURL := viper.GetString("tsuru.target")
fullUrl := fmt.Sprintf("%s/services/%s/proxy/%s?callback=%s",
strings.TrimSuffix(baseURL, "/"),
service,
instance,
path,
)
return doProxyURLRequest(method, fullUrl, body)
}

func doProxyURLRequest(method, fullUrl string, body io.Reader) (*http.Response, error) {
token := viper.GetString("tsuru.token")
req, err := http.NewRequest(method, fullUrl, body)
if err != nil {
return nil, err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("Authorization", "bearer "+token)
req.Header.Set("User-Agent", userAgent)
rsp, err := baseClient.Do(req)
if err != nil {
return nil, err
}
if rsp.StatusCode < 200 || rsp.StatusCode >= 400 {
data, _ := ioutil.ReadAll(rsp.Body)
rsp.Body.Close()
return nil, errors.Errorf("invalid status code %d: %q", rsp.StatusCode, string(data))
}
warnOnce.Do(func() {
warnVersion(rsp.Header)
})
return rsp, nil
}

func warnVersion(headers http.Header) {
versionHeader := headers.Get(version.VersionHeader)
serverVersion, _ := semver.NewVersion(versionHeader)
clientVersion, _ := semver.NewVersion(version.Version)
if serverVersion == nil {
serverVersion = &semver.Version{}
}
if clientVersion == nil {
clientVersion = &semver.Version{}
}
if clientVersion.LessThan(serverVersion) {
fmt.Fprintln(os.Stderr, "There is a new version of the acl plugin available. Please update it.")
}
}

func serviceInstanceName(args []string, minArgs int) (string, string) {
var instanceName string
serviceName := defaultServiceName
if len(args) == minArgs {
instanceName = args[0]
} else if len(args) > minArgs {
serviceName = args[0]
instanceName = args[1]
}
return serviceName, instanceName
}

func initConfig(rootCmd *cobra.Command) func() {
return func() {
viper.SetConfigName(".acl")
Expand All @@ -145,18 +42,18 @@ func main() {
Use: "rules",
}
rootCmd.AddCommand(rulesCmd)
rulesCmd.AddCommand(addRuleCmd)
rulesCmd.AddCommand(removeRuleCmd)
rulesCmd.AddCommand(listRuleCmd)
rulesCmd.AddCommand(forceSyncCmd)
rulesCmd.AddCommand(syncDNSCmd)
rulesCmd.AddCommand(cmd.AddRuleCmd)
rulesCmd.AddCommand(cmd.RemoveRuleCmd)
rulesCmd.AddCommand(cmd.ListRuleCmd)
rulesCmd.AddCommand(cmd.ForceSyncCmd)
rulesCmd.AddCommand(cmd.SyncDNSCmd)

adminCmd := &cobra.Command{
Use: "admin",
}
rootCmd.AddCommand(adminCmd)
adminCmd.AddCommand(listAllRulesCmd)
adminCmd.AddCommand(addCustomRuleCmd)
adminCmd.AddCommand(cmd.ListAllRulesCmd)
adminCmd.AddCommand(cmd.AddCustomRuleCmd)

rootCmd.PersistentFlags().String("tsuru.target", "", "Tsuru Target URL")
rootCmd.PersistentFlags().String("tsuru.token", "", "Tsuru Token")
Expand All @@ -177,12 +74,12 @@ func main() {
adminFlags.String("src-app-pool", "", "Source Tsuru Pool Name [dev]")
adminFlags.String("owner", "", "Rule owner")

addRuleCmd.Flags().AddFlagSet(dstFlags)
addCustomRuleCmd.Flags().AddFlagSet(adminFlags)
cmd.AddRuleCmd.Flags().AddFlagSet(dstFlags)
cmd.AddCustomRuleCmd.Flags().AddFlagSet(adminFlags)

listRuleCmd.Flags().Bool("show-sync", false, "Show rules latest sync attempt")
listRuleCmd.Flags().Bool("show-extra-sync", false, "Show rules with latest sync attempt details.")
listAllRulesCmd.Flags().Bool("show-extra-sync", false, "Show rules with latest sync attempt details.")
cmd.ListRuleCmd.Flags().Bool("show-sync", false, "Show rules latest sync attempt")
cmd.ListRuleCmd.Flags().Bool("show-extra-sync", false, "Show rules with latest sync attempt details.")
cmd.ListAllRulesCmd.Flags().Bool("show-extra-sync", false, "Show rules with latest sync attempt details.")

if err := rootCmd.Execute(); err != nil {
log.Fatal(err)
Expand Down

0 comments on commit 7f41fef

Please sign in to comment.