Skip to content

Commit d39e149

Browse files
committed
Switch to cobra for cli interaction
1 parent f41b76b commit d39e149

File tree

12 files changed

+322
-152
lines changed

12 files changed

+322
-152
lines changed

cmd/root.go

+156
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
/*
2+
Copyright © 2020 Mmadu Manasseh <[email protected]>
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
package cmd
17+
18+
import (
19+
"encoding/json"
20+
"fmt"
21+
"log"
22+
"os"
23+
"unsafe"
24+
25+
"github.com/spf13/cobra"
26+
27+
homedir "github.com/mitchellh/go-homedir"
28+
"github.com/spf13/viper"
29+
30+
"github.com/mensaah/reka/config"
31+
"github.com/mensaah/reka/provider"
32+
"github.com/mensaah/reka/provider/aws"
33+
"github.com/mensaah/reka/resource"
34+
"github.com/mensaah/reka/rules"
35+
)
36+
37+
var (
38+
cfgFile string
39+
providers []*provider.Provider
40+
)
41+
42+
// rootCmd represents the base command when called without any subcommands
43+
var rootCmd = &cobra.Command{
44+
Use: "reka",
45+
Short: "Run Reka using config file (default $HOME/.reka.yml)",
46+
Long: `A Cloud Infrastructure Management Tool to stop, resume, clean and destroy resources based on tags.`,
47+
// Uncomment the following line if your bare application
48+
// has an action associated with it:
49+
Run: func(cmd *cobra.Command, args []string) {
50+
refreshResources(providers)
51+
},
52+
}
53+
54+
// Execute adds all child commands to the root command and sets flags appropriately.
55+
// This is called by main.main(). It only needs to happen once to the rootCmd.
56+
func Execute() {
57+
if err := rootCmd.Execute(); err != nil {
58+
fmt.Println(err)
59+
os.Exit(1)
60+
}
61+
}
62+
63+
func init() {
64+
cobra.OnInitialize(initConfig)
65+
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.reka.yaml)")
66+
67+
}
68+
69+
// initConfig reads in config file and ENV variables if set.
70+
func initConfig() {
71+
if cfgFile != "" {
72+
// Use config file from the flag.
73+
viper.SetConfigFile(cfgFile)
74+
} else {
75+
// Find home directory.
76+
home, err := homedir.Dir()
77+
if err != nil {
78+
fmt.Println(err)
79+
os.Exit(1)
80+
}
81+
82+
// Search config in home directory with name ".reka" (without extension).
83+
viper.AddConfigPath(home)
84+
viper.SetConfigName(".reka")
85+
}
86+
87+
viper.AutomaticEnv() // read in environment variables that match
88+
89+
// If a config file is found, read it in.
90+
if err := viper.ReadInConfig(); err == nil {
91+
fmt.Println("Using config file:", viper.ConfigFileUsed())
92+
}
93+
94+
// Load Config and Defaults
95+
config.LoadConfig()
96+
cfg := config.GetConfig()
97+
98+
for _, rule := range cfg.Rules {
99+
// Convert Rule in config to rules.Rule type
100+
r := *((*rules.Rule)(unsafe.Pointer(&rule)))
101+
r.Tags = resource.Tags(rule.Tags)
102+
rules.ParseRule(r)
103+
}
104+
105+
// Initialize Provider objects
106+
providers = initProviders()
107+
108+
}
109+
110+
// TODO Add logger to Providers during configuration
111+
func initProviders() []*provider.Provider {
112+
var providers []*provider.Provider
113+
for _, p := range config.GetProviders() {
114+
var (
115+
provider *provider.Provider
116+
err error
117+
)
118+
switch p {
119+
case aws.GetName():
120+
provider, err = aws.NewProvider()
121+
if err != nil {
122+
log.Fatal("Could not initialize AWS Provider: ", err)
123+
}
124+
}
125+
// TODO Config providers
126+
providers = append(providers, provider)
127+
}
128+
return providers
129+
}
130+
131+
// Refresh current status of resources from Providers
132+
func refreshResources(providers []*provider.Provider) {
133+
for _, provider := range providers {
134+
allResources := provider.GetAllResources()
135+
s, err := json.MarshalIndent(allResources, "", "\t")
136+
if err != nil {
137+
fmt.Println(err)
138+
}
139+
fmt.Println(string(s))
140+
141+
// stoppableResources := provider.GetStoppableResources(allResources)
142+
// fmt.Println("Stoppable Resources: ", stoppableResources)
143+
// errs := provider.StopResources(stoppableResources)
144+
// fmt.Println("Errors Stopping Resources: ", errs)
145+
146+
// resumableResources := provider.GetResumableResources(allResources)
147+
// fmt.Println("Resumable Resources: ", resumableResources)
148+
// errs = provider.ResumeResources(resumableResources)
149+
// fmt.Println("Errors Resuming Resources: ", errs)
150+
151+
// destroyableResources := provider.GetDestroyableResources(allResources)
152+
// fmt.Println("Destroyable Resources: ", destroyableResources)
153+
// errs = provider.DestroyResources(destroyableResources)
154+
// fmt.Println("Errors Destroying Resources: ", errs)
155+
}
156+
}

cmd/web.go

+98
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
/*
2+
Copyright © 2020 Mmadu Manasseh <[email protected]>
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
package cmd
17+
18+
import (
19+
"net/http"
20+
"time"
21+
22+
"github.com/gin-gonic/gin"
23+
"github.com/go-co-op/gocron"
24+
log "github.com/sirupsen/logrus"
25+
"github.com/spf13/cobra"
26+
27+
"github.com/mensaah/reka/config"
28+
"github.com/mensaah/reka/web/controllers"
29+
"github.com/mensaah/reka/web/models"
30+
)
31+
32+
var (
33+
scheduler *gocron.Scheduler
34+
)
35+
36+
// webCmd represents the web command
37+
var webCmd = &cobra.Command{
38+
Use: "web",
39+
Short: "A brief description of your command",
40+
Long: `A longer description that spans multiple lines and likely contains examples
41+
and usage of using your command. For example:
42+
43+
Cobra is a CLI library for Go that empowers applications.
44+
This application is a tool to generate the needed files
45+
to quickly create a Cobra application.`,
46+
Run: func(cmd *cobra.Command, args []string) {
47+
models.SetDB(config.GetDB())
48+
err := models.AutoMigrate(providers)
49+
if err != nil {
50+
log.Fatal("Database Migration Error: ", err)
51+
}
52+
initCronJob(config.GetConfig().RefreshInterval)
53+
54+
// Load Templates
55+
controllers.LoadTemplates(providers)
56+
57+
// Creates a gin router with default middleware:
58+
// logger and recovery (crash-free) middleware
59+
router := gin.Default()
60+
router.SetHTMLTemplate(controllers.GetTemplates())
61+
router.StaticFS("/static", http.Dir(config.StaticPath()))
62+
// router.Use(controllers.ContextData())
63+
64+
router.GET("/", controllers.HomeGet)
65+
router.GET("/provider/:provider", controllers.HomeGet)
66+
// router.NoRoute(controllers.NotFound)
67+
// router.NoMethod(controllers.MethodNotAllowed)
68+
69+
// Start cron
70+
scheduler.StartAsync()
71+
72+
router.Run(":8080")
73+
},
74+
}
75+
76+
func init() {
77+
rootCmd.AddCommand(webCmd)
78+
}
79+
80+
//initLogger initializes logrus logger with some defaults
81+
func initLogger() {
82+
log.SetFormatter(&log.TextFormatter{})
83+
//logrus.SetOutput(os.Stderr)
84+
if gin.Mode() == gin.DebugMode {
85+
log.SetLevel(log.DebugLevel)
86+
}
87+
}
88+
89+
func initCronJob(frequency int32) {
90+
scheduler = gocron.NewScheduler(time.UTC)
91+
92+
// Periodic tasks
93+
_, err := scheduler.Every(uint64(frequency)).Hours().StartImmediately().Do(refreshResources, providers)
94+
// _, err := scheduler.Every(uint64(frequency)).Hour().Do(refreshResources, providers)
95+
if err != nil {
96+
log.Errorf("error creating job: %v", err)
97+
}
98+
}

go.mod

+2
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@ require (
1313
github.com/go-co-op/gocron v0.3.2
1414
github.com/jinzhu/now v1.1.1
1515
github.com/labstack/gommon v0.3.0
16+
github.com/mitchellh/go-homedir v1.1.0
1617
github.com/sirupsen/logrus v1.7.0
18+
github.com/spf13/cobra v1.1.1
1719
github.com/spf13/pflag v1.0.5
1820
github.com/spf13/viper v1.7.1
1921
gorm.io/driver/postgres v1.0.5

go.sum

+10
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3Ee
5959
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
6060
github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
6161
github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
62+
github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
6263
github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY=
6364
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
6465
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
@@ -145,6 +146,7 @@ github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0m
145146
github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I=
146147
github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc=
147148
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
149+
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
148150
github.com/jackc/chunkreader v1.0.0 h1:4s39bBR8ByfqH+DKm8rQA3E1LHZWB9XWcrz8fqaZbe0=
149151
github.com/jackc/chunkreader v1.0.0/go.mod h1:RT6O25fNZIuasFJRyZ4R/Y2BbhasbmZXF9QQ7T3kePo=
150152
github.com/jackc/chunkreader/v2 v2.0.0/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk=
@@ -252,7 +254,10 @@ github.com/mattn/go-sqlite3 v1.14.3/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGw
252254
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
253255
github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
254256
github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc=
257+
github.com/mitchellh/go-homedir v1.0.0 h1:vKb8ShqSby24Yrqr/yDYkuFz8d0WUjys40rvnGC8aR0=
255258
github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
259+
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
260+
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
256261
github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI=
257262
github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg=
258263
github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY=
@@ -293,12 +298,14 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR
293298
github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ=
294299
github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU=
295300
github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc=
301+
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
296302
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
297303
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
298304
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
299305
github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4=
300306
github.com/shopspring/decimal v0.0.0-20200227202807-02e2044944cc h1:jUIKcSPO9MoMJBbEoyE/RJoE8vz7Mb8AjvifMMwSyvY=
301307
github.com/shopspring/decimal v0.0.0-20200227202807-02e2044944cc/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o=
308+
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
302309
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
303310
github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q=
304311
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
@@ -314,11 +321,14 @@ github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI=
314321
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
315322
github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8=
316323
github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
324+
github.com/spf13/cobra v1.1.1 h1:KfztREH0tPxJJ+geloSLaAkaPkr4ki2Er5quFV1TDo4=
325+
github.com/spf13/cobra v1.1.1/go.mod h1:WnodtKOvamDL/PwE2M4iKs8aMDBZ5Q5klgD3qfVJQMI=
317326
github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk=
318327
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
319328
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
320329
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
321330
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
331+
github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg=
322332
github.com/spf13/viper v1.7.1 h1:pM5oEahlgWv/WnHXpgbKz7iLIxRf65tye2Ci+XFK5sk=
323333
github.com/spf13/viper v1.7.1/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg=
324334
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=

main.go

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/*
2+
Copyright © 2020 NAME HERE <EMAIL ADDRESS>
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
package main
17+
18+
import "github.com/mensaah/reka/cmd"
19+
20+
func main() {
21+
cmd.Execute()
22+
}

provider/aws/aws.go

+3-8
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
package aws
22

33
import (
4-
"fmt"
5-
64
log "github.com/sirupsen/logrus"
75

86
"github.com/mensaah/reka/config"
@@ -35,15 +33,12 @@ func NewProvider() (*provider.Provider, error) {
3533
aws := provider.Provider{}
3634
aws.Name = providerName
3735

38-
logFile := fmt.Sprintf("%s/logger.log", config.GetConfig().LogPath)
39-
logger = config.GetLogger(providerName, logFile)
40-
// Setup Logger
41-
aws.Logger = logger
36+
aws.SetLogger("logger.log")
4237

4338
cfg := config.GetConfig()
4439

45-
ec2Manager := newEC2Manager(cfg, logFile)
46-
s3Manager := newS3Manager(cfg, logFile)
40+
ec2Manager := newEC2Manager(cfg, aws.LogPath)
41+
s3Manager := newS3Manager(cfg, aws.LogPath)
4742

4843
resourceManagers = map[string]*resource.Manager{
4944
ec2Manager.Name: &ec2Manager,

0 commit comments

Comments
 (0)