This repository has been archived by the owner on Aug 16, 2023. It is now read-only.
forked from EladDolev/aws_audit_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
241 lines (211 loc) · 6.22 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
// Copyright 2016 Qubit Group
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"fmt"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/urfave/cli"
"github.com/bringg/aws_audit_exporter/billing"
"github.com/bringg/aws_audit_exporter/debug"
"github.com/bringg/aws_audit_exporter/postgres"
"github.com/bringg/aws_audit_exporter/sqlmigrations"
)
type options struct {
addr string
dbURL string
duration time.Duration
instanceTags string
region string
spotOS string
}
// We have to construct the set of tags for this based on the program
// args, so it is created in main
var instanceTags = map[string]string{}
var tagl = []string{}
// We'll cache the instance tag labels so that we can use them to separate
// out spot instance spend
var instanceLabelsCache = map[string]prometheus.Labels{}
// will hold the list of OS (products) for which spot prices should be fetched
var pList []*string
// maintainSchema maintains the schema by running migrations
func maintainSchema() error {
// runs init if gopg_migrations table does not exists
if n, err := postgres.DB.Model().
Table("pg_tables").
Where("schemaname = 'public'").
Where("tablename = 'gopg_migrations'").
Count(); err != nil {
return err
} else if n == 0 {
//oldVersion, newVersion, err := migrations.Run(postgres.DB)
if err = sqlmigrations.RunMigrations("init"); err != nil {
return err
}
}
// running migrations
return sqlmigrations.RunMigrations("")
}
func main() {
options := &options{}
app := cli.NewApp()
app.Name = "Prometheus AWS audit exporter"
app.Version = "0.3.1"
app.Usage = "Assists with billing"
app.UsageText = "./aws_audit_exporter [global options] [command] [args]"
app.Commands = []cli.Command{
{
Name: "migrate",
Usage: "runs migrations on postgres database",
Description: "https://github.com/go-pg/migrations#run-migrations",
UsageText: "./aws_audit_exporter migrate [args]",
SkipFlagParsing: false,
HideHelp: false,
Hidden: false,
HelpName: "migrate",
Action: func(c *cli.Context) error {
if len(options.dbURL) == 0 {
log.Fatal("must supply dbURL")
return fmt.Errorf("must supply dbURL")
}
if err := postgres.ConnectPostgres(options.dbURL); err != nil {
log.Fatal(err)
return err
}
defer postgres.DB.Close()
if err := sqlmigrations.RunMigrations(strings.Join(c.Args(), " ")); err != nil {
log.Fatal(err)
return err
}
return nil
},
},
}
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "addr",
Value: ":9190",
Usage: "addr to listen on",
EnvVar: "ADDR",
Destination: &options.addr,
},
cli.BoolFlag{
Name: "debug",
Usage: "Whether to print debug logs and SQL statements",
EnvVar: "DEBUG",
Destination: &debug.Enabled,
},
cli.StringFlag{
Name: "db-url",
Usage: "postgres connection url",
EnvVar: "DB_URL",
Destination: &options.dbURL,
},
cli.DurationFlag{
Name: "duration",
Value: time.Minute * 4,
Usage: "How often to query the API",
EnvVar: "DURATION",
Destination: &options.duration,
},
cli.StringFlag{
Name: "instance-tags",
Usage: "comma seperated list of tag keys to use as metric labels",
EnvVar: "INSTANCE_TAGS",
Destination: &options.instanceTags,
},
cli.StringFlag{
Name: "region",
Value: "us-east-1",
Usage: "the region to query",
EnvVar: "REGION",
Destination: &options.region,
},
cli.StringFlag{
Name: "spot-os",
Value: "Linux",
Usage: "comma seperated list of operating systems to get spot price history for [Linux|SUSE|RHEL|Windows]",
EnvVar: "SPOT_OS",
Destination: &options.spotOS,
},
}
app.Action = func(c *cli.Context) error {
if len(options.instanceTags) > 0 {
for _, tstr := range strings.Split(options.instanceTags, ",") {
ctag := billing.Tagname(tstr)
instanceTags[tstr] = ctag
tagl = append(tagl, ctag)
}
}
sess, err := session.NewSession()
if err != nil {
return fmt.Errorf("failed to create session: %v", err)
}
svc := ec2.New(sess, &aws.Config{Region: aws.String(options.region)})
if pList, err = billing.GetProductDescriptions(options.spotOS, billing.IsClassicLink(svc)); err != nil {
return err
}
if len(options.dbURL) > 0 {
if err := postgres.ConnectPostgres(options.dbURL); err != nil {
log.Fatal(err)
return err
}
defer postgres.DB.Close()
if err := maintainSchema(); err != nil {
return err
}
}
go func() {
billing.RegisterSpotsPricesMetrics()
for {
billing.GetSpotsCurrentPrices(svc, pList)
<-time.After(time.Hour)
}
}()
go func() {
instances := &billing.Instances{
Svc: svc,
InstanceLabelsCache: &instanceLabelsCache,
InstanceTags: instanceTags,
}
spots := &billing.Spots{
Svc: svc,
InstanceLabelsCache: &instanceLabelsCache,
InstanceTags: instanceTags,
}
billing.RegisterInstancesMetrics(tagl)
billing.RegisterReservationsMetrics()
billing.RegisterSpotsMetrics(tagl)
for {
instances.GetInstancesInfo()
go billing.GetReservationsInfo(svc)
go spots.GetSpotsInfo()
<-time.After(options.duration)
}
}()
http.Handle("/metrics", promhttp.Handler())
return http.ListenAndServe(options.addr, nil)
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}