-
Notifications
You must be signed in to change notification settings - Fork 838
/
main.go
191 lines (173 loc) · 5.37 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
/*
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 (
"bytes"
"context"
"flag"
"fmt"
"go/format"
"log"
"os"
"runtime"
"runtime/pprof"
"sort"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws/session"
ec22 "github.com/aws/aws-sdk-go/service/ec2"
"github.com/samber/lo"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/aws/karpenter/pkg/operator/options"
"github.com/aws/karpenter/pkg/providers/pricing"
"github.com/aws/karpenter/pkg/test"
)
func getAWSRegions(partition string) []string {
switch partition {
case "aws":
return []string{"us-east-1"}
case "aws-us-gov":
return []string{"us-gov-east-1", "us-gov-west-1"}
case "aws-cn":
return []string{"cn-north-1"}
default:
panic("invalid partition")
}
}
func getPartitionSuffix(partition string) string {
switch partition {
case "aws":
return "AWS"
case "aws-us-gov":
return "USGov"
case "aws-cn":
return "CN"
default:
panic("invalid partition")
}
}
type Options struct {
partition string
output string
}
func NewOptions() *Options {
o := &Options{}
flag.StringVar(&o.partition, "partition", "aws", "The partition to generate prices for. Valid options are \"aws\", \"aws-us-gov\", and \"aws-cn\".")
flag.StringVar(&o.output, "output", "pkg/providers/pricing/zz_generated.pricing_aws.go", "The destination for the generated go file.")
flag.Parse()
if !lo.Contains([]string{"aws", "aws-us-gov", "aws-cn"}, o.partition) {
log.Fatal("invalid partition: must be \"aws\", \"aws-us-gov\", or \"aws-cn\"")
}
return o
}
func main() {
opts := NewOptions()
f, err := os.Create("pricing.heapprofile")
if err != nil {
log.Fatal("could not create memory profile: ", err)
}
defer f.Close() // error handling omitted for example
const region = "us-east-1"
os.Setenv("AWS_SDK_LOAD_CONFIG", "true")
os.Setenv("AWS_REGION", region)
ctx := context.Background()
ctx = options.ToContext(ctx, test.Options())
sess := session.Must(session.NewSession())
ec2 := ec22.New(sess)
src := &bytes.Buffer{}
fmt.Fprintln(src, "//go:build !ignore_autogenerated")
license := lo.Must(os.ReadFile("hack/boilerplate.go.txt"))
fmt.Fprintln(src, string(license))
fmt.Fprintln(src, "package pricing")
now := time.Now().UTC().Format(time.RFC3339)
fmt.Fprintf(src, "// generated at %s for %s\n\n\n", now, region)
fmt.Fprintf(src, "var InitialOnDemandPrices%s = map[string]map[string]float64{\n", getPartitionSuffix(opts.partition))
// record prices for each region we are interested in
for _, region := range getAWSRegions(opts.partition) {
log.Println("fetching for", region)
pricingProvider := pricing.NewProvider(ctx, pricing.NewAPI(sess, region), ec2, region)
controller := pricing.NewController(pricingProvider)
_, err := controller.Reconcile(ctx, reconcile.Request{NamespacedName: types.NamespacedName{}})
if err != nil {
log.Fatalf("failed to initialize pricing provider %s", err)
}
instanceTypes := pricingProvider.InstanceTypes()
sort.Strings(instanceTypes)
writePricing(src, instanceTypes, region, pricingProvider.OnDemandPrice)
}
fmt.Fprintln(src, "}")
formatted, err := format.Source(src.Bytes())
if err != nil {
if err := os.WriteFile(opts.output, src.Bytes(), 0644); err != nil {
log.Fatalf("writing output, %s", err)
}
log.Fatalf("formatting generated source, %s", err)
}
if err := os.WriteFile(opts.output, formatted, 0644); err != nil {
log.Fatalf("writing output, %s", err)
}
runtime.GC()
if err := pprof.WriteHeapProfile(f); err != nil {
log.Fatal("could not write memory profile: ", err)
}
}
func writePricing(src *bytes.Buffer, instanceNames []string, region string, getPrice func(instanceType string) (float64, bool)) {
fmt.Fprintf(src, "// %s\n", region)
fmt.Fprintf(src, "%q: {\n", region)
lineLen := 0
sort.Strings(instanceNames)
previousFamily := ""
for _, instanceName := range instanceNames {
segs := strings.Split(instanceName, ".")
if len(segs) != 2 {
log.Fatalf("parsing instance family %s, got %v", instanceName, segs)
}
price, ok := getPrice(instanceName)
if !ok {
continue
}
// separating by family should lead to smaller diffs instead of just breaking at line endings only
family := segs[0]
if family != previousFamily {
previousFamily = family
newline(src)
fmt.Fprintf(src, "// %s family\n", family)
lineLen = 0
}
n, err := fmt.Fprintf(src, `"%s":%f, `, instanceName, price)
if err != nil {
log.Fatalf("error writing, %s", err)
}
lineLen += n
if lineLen > 80 {
lineLen = 0
fmt.Fprintln(src)
}
}
fmt.Fprintln(src, "\n},")
fmt.Fprintln(src)
}
// newline adds a newline to src, if it does not currently already end with a newline
func newline(src *bytes.Buffer) {
contents := src.Bytes()
// no content yet, so create the new line
if len(contents) == 0 {
fmt.Println(src)
return
}
// already has a newline, so don't write a new one
if contents[len(contents)-1] == '\n' {
return
}
fmt.Fprintln(src)
}