Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
Edan Schwartz committed Nov 22, 2019
1 parent 9cce797 commit 7eb999e
Show file tree
Hide file tree
Showing 28 changed files with 943 additions and 504 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,6 @@ override.tf.json
# Other stuff
*.zip

junit-report/
junit-report/

dce-cli
8 changes: 4 additions & 4 deletions cmd/accounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ var accountsDescribeCmd = &cobra.Command{
Short: "describe an account",
Args: cobra.ExactValidArgs(1),
Run: func(cmd *cobra.Command, args []string) {
service.GetAccount(args[0])
Service.GetAccount(args[0])
},
}

Expand All @@ -42,7 +42,7 @@ var accountsListCmd = &cobra.Command{
Short: "list accounts",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
service.ListAccounts()
Service.ListAccounts()
},
}

Expand All @@ -51,7 +51,7 @@ var accountsAddCmd = &cobra.Command{
Short: "Add an account to the accounts pool",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
service.AddAccount(accountID, adminRoleARN)
Service.AddAccount(accountID, adminRoleARN)
},
}

Expand All @@ -60,6 +60,6 @@ var accountsRemoveCmd = &cobra.Command{
Short: "Remove an account from the accounts pool.",
Args: cobra.ExactValidArgs(1),
Run: func(cmd *cobra.Command, args []string) {
service.RemoveAccount(args[0])
Service.RemoveAccount(args[0])
},
}
8 changes: 3 additions & 5 deletions cmd/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,15 @@ import (
"github.com/spf13/cobra"
)

var authUrl string

func init() {
RootCmd.AddCommand(authCmd)
authCmd.Flags().StringVarP(&authUrl, "url-override", "u", "", "Override the DCE login url")
authCmd.Flags()
}

var authCmd = &cobra.Command{
Use: "auth",
Short: "Login to dce",
Run: func(cmd *cobra.Command, args []string) {
service.Authenticate(authUrl)
RunE: func(cmd *cobra.Command, args []string) error {
return Service.Authenticate()
},
}
2 changes: 1 addition & 1 deletion cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@ var initCmd = &cobra.Command{
Use: "init",
Short: "First time DCE cli setup. Creates config file at ~/.dce.yaml",
Run: func(cmd *cobra.Command, args []string) {
service.InitializeDCE(cfgFile)
Service.InitializeDCE()
},
}
10 changes: 5 additions & 5 deletions cmd/leases.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ var leasesDescribeCmd = &cobra.Command{
Short: "describe a lease",
Args: cobra.ExactValidArgs(1),
Run: func(cmd *cobra.Command, args []string) {
service.GetLease(args[0])
Service.GetLease(args[0])
},
}

Expand All @@ -77,7 +77,7 @@ var leasesListCmd = &cobra.Command{
Short: "List leases using various query filters.",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
service.ListLeases(acctID, principalID, nextAcctID, nextPrincipalID, leaseStatus, pagLimit)
Service.ListLeases(acctID, principalID, nextAcctID, nextPrincipalID, leaseStatus, pagLimit)
},
}

Expand All @@ -86,7 +86,7 @@ var leasesCreateCmd = &cobra.Command{
Short: "Create a lease.",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
service.CreateLease(principalID, budgetAmount, budgetCurrency, email)
Service.CreateLease(principalID, budgetAmount, budgetCurrency, email)
},
}

Expand All @@ -95,7 +95,7 @@ var leasesEndCmd = &cobra.Command{
Short: "Cause a lease to immediately expire",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
service.EndLease(accountID, principalID)
Service.EndLease(accountID, principalID)
},
}

Expand All @@ -104,6 +104,6 @@ var leasesLoginCmd = &cobra.Command{
Short: "Login to a leased DCE account. (Sets AWS CLI credentials if used with no flags)",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
service.LoginToLease(args[0], loginProfile, loginOpenBrowser, loginPrintCreds)
Service.LoginToLease(args[0], loginProfile, loginOpenBrowser, loginPrintCreds)
},
}
142 changes: 84 additions & 58 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ limitations under the License.
package cmd

import (
"errors"
"fmt"
"github.com/mitchellh/go-homedir"
"os"
"path/filepath"

Expand All @@ -27,18 +29,32 @@ import (
svc "github.com/Optum/dce-cli/pkg/service"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var cfgFile string
var config *configs.Root = &configs.Root{}
var service *svc.ServiceContainer
var util *utl.UtilContainer
var observation *observ.ObservationContainer
var Config = &configs.Root{}
var Service *svc.ServiceContainer
var Util *utl.UtilContainer
var Observation *observ.ObservationContainer
// Expose logger as global for ease of use
var log observ.Logger
var Log observ.Logger

func init() {
cobra.OnInitialize(initObservation, initConfig, initUtil, initService)
RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.dce.yaml)")
homeDir, err := homedir.Dir()
if err != nil {
log.Fatalf("error: %v", err)
}

// Global Flags
// ---------------
// --config flag, to specify path to dce.yml config
// default to ~/.dce.yml
RootCmd.PersistentFlags().StringVar(
&cfgFile, "config",
filepath.Join(homeDir, constants.DefaultConfigFileName),
"config file",
)
}

// RootCmd represents the base command when called without any subcommands
Expand All @@ -51,12 +67,36 @@ var RootCmd = &cobra.Command{
- Admins to provision DCE to a master account and administer said account
- Users to lease accounts and execute commands against them`,
PersistentPreRunE: preRun,
}

func preRun(cmd *cobra.Command, args []string) error {
err := onInit(cmd, args)
if err != nil {
return err
}

// Check if the user has valid creds,
// otherwise require authentication
creds := Util.AWSSession.Config.Credentials
_, _ = creds.Get()
hasValidCreds := !creds.IsExpired()
isAuthCommand := cmd.Name() == authCmd.Name()
isInitCommand := cmd.Name() == initCmd.Name()
if !hasValidCreds && !isAuthCommand && !isInitCommand {
log.Print("No valid DCE credentials found")
err := Service.Authenticate()
if err != nil {
return err
}
}

return nil
}

// Execute adds all child commands to the root command and sets flags appropriately.
func Execute() {
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
Expand All @@ -66,13 +106,42 @@ type FmtOutputFormatter struct {

func (f *FmtOutputFormatter) Format(entry *logrus.Entry) ([]byte, error) {
var serialized []byte
var err error
serialized = []byte(entry.Message)
if err != nil {
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
//fmt.Println(string(serialized))
return serialized, nil
}

func onInit(cmd *cobra.Command, args []string) error {
// Configure observation / logging
initObservation()
// Expose global `log` object for ease of use
log = Observation.Logger
Log = log

fsUtil := &utl.FileSystemUtil{Config: Config, ConfigFile: cfgFile}

// Initialize config
// If config file does not exist,
// run the `dce init` command
if !fsUtil.IsExistingFile(cfgFile) {
if cmd.Name() != initCmd.Name() {
return errors.New("Config file not found. Please type 'dce init' to generate one.")
}
} else {
// Load config from dce.yaml
err := fsUtil.ReadInConfig()
if err != nil {
return fmt.Errorf("Failed to parse dce.yml: %s", err)
}
}
fmt.Println(string(serialized))
return nil, nil

// initialize utilities and interfaces to external things
Util = utl.New(Config, cfgFile, Observation)

// initialize business logic services
Service = svc.New(Config, Observation, Util)

return nil
}

// initialize anything related to logging, metrics, or tracing
Expand Down Expand Up @@ -107,48 +176,5 @@ func initObservation() {
logrusInstance.SetFormatter(&logrus.TextFormatter{})
}

observation = observ.New(logrusInstance)
}

// Utils we need before they are normally instantiated
var log observ.Logger
var fsUtil utl.FileSystemer

// initialize config from file or tell user to run 'dce init' if none exists
func initConfig() {

tempUtil := utl.New(config, observation)
fsUtil = tempUtil.FileSystemer
log = observation.Logger

var configFileUsed string
if cfgFile != "" {
configFileUsed = cfgFile
viper.SetConfigFile(configFileUsed)
} else {
home := fsUtil.GetHomeDir()
configFileUsed = filepath.Join(home, constants.DefaultConfigFileName)
viper.SetConfigFile(configFileUsed)
}

if !fsUtil.IsExistingFile(configFileUsed) {
if len(os.Args) < 2 || os.Args[1] != initCmd.Name() {
log.Endln("Config file not found. Please type 'dce init' to generate one.")
}
} else {
if err := viper.ReadInConfig(); err == nil {
viper.BindEnv("githubtoken", "GITHUB_TOKEN")
viper.Unmarshal(config)
}
}
}

// initialize utilities and interfaces to external things
func initUtil() {
util = utl.New(config, observation)
}

// initialize business logic
func initService() {
service = svc.New(config, observation, util)
}
Observation = observ.New(logrusInstance)
}
2 changes: 1 addition & 1 deletion cmd/system.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,6 @@ var systemDeployCmd = &cobra.Command{
Use: "deploy",
Short: "Deploy DCE to a new master account",
Run: func(cmd *cobra.Command, args []string) {
service.Deploy(deployLocalPath, &deployOverrides)
Service.Deploy(deployLocalPath, &deployOverrides)
},
}
2 changes: 1 addition & 1 deletion cmd/usage.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@ var usageCmd = &cobra.Command{
Short: "View lease budget information",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
service.GetUsage(startDate, endDate)
Service.GetUsage(startDate, endDate)
},
}
20 changes: 10 additions & 10 deletions configs/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ package configs

// Root contains config
type Root struct {
System struct {
Auth struct {
LoginURL *string
}
}
API struct {
Host *string
BasePath *string
}
API API
Region *string
GithubToken *string
GithubToken *string `yaml:"githubToken,omitempty"`
}

type API struct {
Host *string
BasePath *string
// Token for authenticating against the API
// token is base64 encoded JSON, containing an STS token.
Token *string `yaml:"token,omitempty"`
}

var Regions = []string{"us-east-1", "us-east-2", "us-west-1", "us-west-2"}
18 changes: 14 additions & 4 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,18 @@ replace github.com/ugorji/go v1.1.4 => github.com/ugorji/go v0.0.0-2018120416352

require (
github.com/aws/aws-sdk-go v1.25.16
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e
github.com/coreos/bbolt v1.3.2 // indirect
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e // indirect
github.com/dsnet/compress v0.0.1 // indirect
github.com/frankban/quicktest v1.7.0 // indirect
github.com/go-openapi/errors v0.19.2
github.com/go-openapi/runtime v0.19.7
github.com/go-openapi/spec v0.19.3
github.com/go-openapi/strfmt v0.19.3
github.com/go-openapi/swag v0.19.5
github.com/go-openapi/validate v0.19.3
github.com/golang/example v0.0.0-20170904185048-46695d81d1fa // indirect
github.com/gogo/protobuf v1.2.1 // indirect
github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef // indirect
github.com/grpc-ecosystem/grpc-gateway v1.9.0 // indirect
github.com/hashicorp/terraform v0.12.10
github.com/manifoldco/promptui v0.3.2
github.com/mholt/archiver v3.1.1+incompatible
Expand All @@ -36,15 +39,22 @@ require (
github.com/nwaples/rardecode v1.0.0 // indirect
github.com/pierrec/lz4 v2.3.0+incompatible // indirect
github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4
github.com/prometheus/client_golang v0.9.3 // indirect
github.com/shurcooL/githubv4 v0.0.0-20191006152017-6d1ea27df521
github.com/shurcooL/graphql v0.0.0-20181231061246-d48a9a75455f // indirect
github.com/sirupsen/logrus v1.2.0
github.com/spf13/cobra v0.0.5
github.com/spf13/viper v1.4.0
github.com/stretchr/testify v1.4.0
github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5 // indirect
github.com/ugorji/go v1.1.7 // indirect
github.com/vektra/mockery v0.0.0-20181123154057-e78b021dcbb5 // indirect
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 // indirect
github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2 // indirect
go.etcd.io/bbolt v1.3.2 // indirect
go.uber.org/atomic v1.4.0 // indirect
go.uber.org/thriftrw v1.20.2
go.uber.org/zap v1.10.0 // indirect
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45
gopkg.in/alecthomas/kingpin.v3-unstable v3.0.0-20191105091915-95d230a53780 // indirect
gopkg.in/yaml.v2 v2.2.4
)
Loading

0 comments on commit 7eb999e

Please sign in to comment.