route/cmd/routectl/main.go

348 lines
9.6 KiB
Go
Raw Normal View History

2017-04-29 04:18:41 +00:00
package main
import (
"context"
"encoding/json"
2017-04-29 04:18:41 +00:00
"fmt"
2017-04-29 19:53:08 +00:00
"log"
"net/http"
2017-04-29 04:18:41 +00:00
"os"
"path/filepath"
"runtime"
2017-04-29 19:53:08 +00:00
"go.uber.org/atomic"
2017-09-30 13:41:35 +00:00
"git.xeserv.us/xena/route/internal/database"
"git.xeserv.us/xena/route/internal/routecrypto"
proto "git.xeserv.us/xena/route/proto"
2018-01-21 16:35:41 +00:00
"git.xeserv.us/xena/route/proto/route"
2017-04-29 04:18:41 +00:00
"github.com/Xe/ln"
"github.com/Xe/uuid"
"github.com/dickeyxxx/netrc"
2017-04-29 19:53:08 +00:00
"github.com/kr/pretty"
"github.com/olekukonko/tablewriter"
2017-04-29 04:18:41 +00:00
"gopkg.in/alecthomas/kingpin.v2"
)
var allScopes = []string{
"token:get", "token:getall", "token:put", "token:delete", "token:deactivate",
"route:get", "route:getall", "route:put", "route:delete",
"connect",
"backend:list", "backend:kill",
2017-10-01 13:28:13 +00:00
"admin",
2017-04-29 04:18:41 +00:00
}
var whoami string
func userHomeDir() string {
if runtime.GOOS == "windows" {
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if home == "" {
home = os.Getenv("USERPROFILE")
}
return home
}
return os.Getenv("HOME")
}
var (
app = kingpin.New("route", "An interface to routed")
grpcServer = app.Flag("routed-addr", "routed grpc address").Default("127.0.0.1:7268").String()
2017-04-29 04:18:41 +00:00
netrcPath = app.Flag("netrc", "netrc path").Default(filepath.Join(userHomeDir(), ".netrc")).String()
generateKey = app.Command("generate-key", "generate SSL cert crypto key")
backends = app.Command("backend", "backend management")
backendList = backends.Command("list", "list connected backends")
backendListDomain = backendList.Flag("domain", "if set, match backends against this domain name").String()
backendListUser = backendList.Flag("user", "if set, match backends against this username").String()
backendKill = backends.Command("kill", "forcibly disconnect a given backend")
backendKillID = backendKill.Flag("id", "the ID of the backend to remove").Required().String()
2017-04-29 04:18:41 +00:00
routes = app.Command("route", "route management")
routesCreate = routes.Command("create", "create a new route")
routesCreateDomain = routesCreate.Flag("domain", "domain for the route (if not given one will be generated for you)").String()
2018-01-21 16:35:41 +00:00
routesInspect = routes.Command("inspect", "inspect one route")
2017-12-03 02:03:27 +00:00
routesInspectID = routesInspect.Flag("id", "ID of the route to inspect").Required().String()
routesList = routes.Command("list", "list all routes owned by you")
2017-04-29 04:18:41 +00:00
routesRm = routes.Command("rm", "remove a route")
2017-04-29 05:14:08 +00:00
routesRmID = routesRm.Flag("id", "route ID to remove").Required().String()
2017-04-29 04:18:41 +00:00
2017-04-29 19:53:08 +00:00
testServer = app.Command("test-server", "spawn a simple HTTP test server on a TCP address")
testServerAddr = testServer.Flag("addr", "TCP address").Default(":9090").String()
2017-04-29 04:18:41 +00:00
token = app.Command("token", "token management")
tokenCreate = token.Command("create", "create a new token")
tokenCreateScopes = tokenCreate.Flag("scope", "token scopes").Default(allScopes...).Strings()
2017-04-29 04:18:41 +00:00
tokenGenerate = token.Command("generate-root", "generate a root token")
tokenGenerateKey = tokenGenerate.Flag("key", "token crypto key").Required().String()
tokenGenerateScopes = tokenGenerate.Flag("scopes", "token scopes").Default(allScopes...).Strings()
tokenGenerateUsername = tokenGenerate.Flag("username", "token username").Required().String()
tokenGenerateDatabasePath = tokenGenerate.Flag("db", "database file to add the root token to").Required().String()
tokenInspect = token.Command("inspect", "inspect a token")
tokenInspectID = tokenInspect.Flag("token-id", "token id").Required().String()
2017-04-29 04:18:41 +00:00
tokenList = token.Command("list", "list all tokens belonging to you")
tokenListDeactivated = tokenList.Flag("deactivated", "list deactivated tokens?").Default("false").Bool()
2017-04-29 04:18:41 +00:00
tokenRm = token.Command("rm", "remove a token")
tokenRmHard = tokenRm.Flag("hard", "hard-delete the token instead of deactivating it").Default("false").Bool()
tokenRmID = tokenRm.Flag("id", "token id").Required().String()
2017-04-29 19:53:08 +00:00
)
2017-04-29 04:18:41 +00:00
2017-04-29 19:53:08 +00:00
var (
hits *atomic.Int64
2017-04-29 04:18:41 +00:00
)
2017-04-29 19:53:08 +00:00
func init() {
hits = atomic.NewInt64(0)
}
func handle(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Route is go!")
fmt.Fprintf(w, "%s\n", pretty.Sprintf("%s", r.Header))
hn, _ := os.Hostname()
fmt.Fprintf(w, "Served by %s running %s\n", hn, runtime.GOOS)
fmt.Fprintf(w, "Hit count: %d", hits.Inc())
ip := r.Header.Get("X-Remote-Ip")
if ip != "" {
log.Printf("Hit from %s: %s", ip, r.RequestURI)
}
}
2017-04-29 04:18:41 +00:00
func main() {
cmdline := kingpin.MustParse(app.Parse(os.Args[1:]))
2017-10-01 13:28:13 +00:00
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
2017-04-29 04:18:41 +00:00
2017-10-01 13:28:13 +00:00
retry_netrc:
2017-04-29 04:18:41 +00:00
n, err := netrc.Parse(*netrcPath)
if err != nil {
2017-10-01 13:28:13 +00:00
_, err := os.Stat(*netrcPath)
if err == os.ErrNotExist {
fout, err := os.Create(*netrcPath)
if err != nil {
ln.FatalErr(ctx, err, ln.Action("creating netrc"), ln.F{"path": *netrcPath})
}
fout.Close()
goto retry_netrc
}
2017-04-29 04:18:41 +00:00
}
_ = n
switch cmdline {
2017-04-29 19:53:08 +00:00
case "test-server":
http.HandleFunc("/", handle)
2017-10-01 13:28:13 +00:00
ln.FatalErr(ctx, http.ListenAndServe(*testServerAddr, nil), ln.Action("test server listenAndServe"))
2017-04-29 19:53:08 +00:00
return
2017-04-29 04:18:41 +00:00
case "generate-key":
key, err := routecrypto.GenerateKey()
if err != nil {
2017-10-01 13:28:13 +00:00
ln.FatalErr(ctx, err, ln.Action("generating encryption key"))
2017-04-29 04:18:41 +00:00
}
fmt.Println("Your key is:", routecrypto.ShowKey(key))
return
2017-04-29 04:18:41 +00:00
case "token generate-root":
key, err := routecrypto.ParseKey(*tokenGenerateKey)
if err != nil {
2017-10-01 13:28:13 +00:00
ln.FatalErr(ctx, err, ln.Action("parsing encryption key"))
2017-04-29 04:18:41 +00:00
}
db, err := database.NewBoltStorage(*tokenGenerateDatabasePath, key)
if err != nil {
2017-10-01 13:28:13 +00:00
ln.FatalErr(ctx, err, ln.Action("opening routed database"))
2017-04-29 04:18:41 +00:00
}
tBody := uuid.New()
tok := database.Token{
Body: uuid.New(),
Owner: *tokenGenerateUsername,
Scopes: *tokenGenerateScopes,
}
_, err = db.Tokens().Put(context.Background(), tok)
2017-04-29 04:18:41 +00:00
if err != nil {
2017-10-01 13:28:13 +00:00
ln.FatalErr(ctx, err, ln.Action("add newly created token to database"))
2017-04-29 04:18:41 +00:00
}
defer db.Close()
fmt.Println("Your token is:", tBody)
n.AddMachine(*grpcServer, *tokenGenerateUsername, tBody)
err = n.Save()
if err != nil {
2017-10-01 13:28:13 +00:00
ln.FatalErr(ctx, err, ln.Action("add machine to netrc"))
2017-04-29 04:18:41 +00:00
}
return
}
m := n.Machine(*grpcServer)
2018-01-21 16:35:41 +00:00
cl := route.New("https://"+*grpcServer, m.Get("password"), &http.Client{})
switch cmdline {
case "route create":
2018-01-21 16:35:41 +00:00
rt, err := cl.Routes.Put(ctx, &proto.Route{Host: *routesCreateDomain})
if err != nil {
2017-10-01 13:28:13 +00:00
ln.FatalErr(ctx, err, ln.Action("create new route"))
}
fmt.Printf("created route for domain %s, id: %s\n", rt.Host, rt.Id)
2017-10-01 13:28:13 +00:00
return
case "route inspect":
2018-01-21 16:35:41 +00:00
r, err := cl.Routes.Get(context.Background(), &proto.GetRouteRequest{
2017-12-03 02:03:27 +00:00
Id: *routesInspectID,
})
if err != nil {
2017-10-01 13:28:13 +00:00
ln.FatalErr(ctx, err, ln.Action("get single route"), ln.F{"domain": *routesCreateDomain})
}
json.NewEncoder(os.Stdout).Encode(r)
fmt.Println()
return
case "route list":
2018-01-21 16:35:41 +00:00
rts, err := cl.Routes.GetAll(context.Background(), &proto.Nil{})
if err != nil {
2017-10-01 13:28:13 +00:00
ln.FatalErr(ctx, err, ln.Action("get all routes"))
}
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"ID", "Host"})
for _, r := range rts.Routes {
table.Append([]string{r.Id, r.Host})
}
2017-09-30 15:39:43 +00:00
table.Render()
return
case "route rm":
2018-01-21 16:35:41 +00:00
_, err := cl.Routes.Delete(context.Background(), &proto.Route{Id: *routesRmID})
if err != nil {
2017-10-01 13:28:13 +00:00
ln.FatalErr(ctx, err, ln.Action("remove single route"), ln.F{"id": *routesRmID})
}
return
case "backend list":
2018-01-21 16:35:41 +00:00
bkds, err := cl.Backends.List(context.Background(), &proto.BackendSelector{
Domain: *backendListDomain,
User: *backendListUser,
})
if err != nil {
2017-10-01 13:28:13 +00:00
ln.FatalErr(ctx, err, ln.Action("list backends"))
}
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"ID", "Proto", "User", "Domain", "Failure Chance", "Host"})
for _, bknd := range bkds.Backends {
table.Append([]string{bknd.Id, bknd.Proto, bknd.User, bknd.Domain, fmt.Sprint(bknd.Phi), bknd.Host})
}
table.Render()
return
case "backend kill":
2018-01-21 16:35:41 +00:00
_, err := cl.Backends.Kill(context.Background(), &proto.BackendID{Id: *backendKillID})
if err != nil {
2017-10-01 13:28:13 +00:00
ln.FatalErr(ctx, err, ln.Action("attempt to kill backend"), ln.F{"backend_id": *backendKillID})
}
fmt.Println("killed backend " + *backendKillID)
return
case "token list":
2018-01-21 16:35:41 +00:00
lis, err := cl.Tokens.GetAll(ctx, &proto.Nil{})
if err != nil {
ln.FatalErr(ctx, err, ln.Action("get all tokens"))
}
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"ID", "Active", "Scopes"})
for _, tkn := range lis.Tokens {
table.Append([]string{tkn.Id, fmt.Sprint(tkn.Active), fmt.Sprint(tkn.Scopes)})
}
table.Render()
return
case "token create":
scps := *tokenCreateScopes
tkn := &proto.Token{
Scopes: scps,
}
2018-01-21 16:35:41 +00:00
ftkn, err := cl.Tokens.Put(ctx, tkn)
if err != nil {
ln.FatalErr(ctx, err, ln.Action("put token to server"))
}
fmt.Printf("Your token is: %s\n", ftkn.Body)
fmt.Printf("It has permission for the following scopes: %v\n", ftkn.Scopes)
return
case "token inspect":
2018-01-21 16:35:41 +00:00
tkn, err := cl.Tokens.Get(ctx, &proto.GetTokenRequest{Id: *tokenInspectID})
if err != nil {
ln.FatalErr(ctx, err, ln.Action("fetch token from server"), ln.F{"token_id": *tokenInspectID})
}
json.NewEncoder(os.Stdout).Encode(tkn)
2017-10-02 05:25:04 +00:00
return
case "token rm":
2018-01-21 16:35:41 +00:00
tkn, err := cl.Tokens.Get(ctx, &proto.GetTokenRequest{Id: *tokenRmID})
2017-10-02 05:25:04 +00:00
if err != nil {
ln.FatalErr(ctx, err, ln.Action("fetch token from server"), ln.F{"token_id": *tokenRmID})
}
var action ln.Fer
if *tokenRmHard {
2018-01-21 16:35:41 +00:00
_, err = cl.Tokens.Delete(ctx, tkn)
2017-10-02 05:25:04 +00:00
action = ln.Action("actually delete token")
} else {
2018-01-21 16:35:41 +00:00
_, err = cl.Tokens.Deactivate(ctx, tkn)
2017-10-02 05:25:04 +00:00
action = ln.Action("deactivate token")
}
if err != nil {
ln.FatalErr(ctx, err, ln.F{"token_id": *tokenRmID}, action)
}
fmt.Printf("token with id %s and body %s removed.\n", tkn.Id, tkn.Body)
return
}
ln.Fatal(ctx, ln.Action("not implemented"), ln.F{"command": cmdline})
2017-04-29 04:18:41 +00:00
}