| 1 |
// Copyright 2018 The Go Cloud Development Kit Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
// Package awsparamstore provides a runtimevar implementation with variables |
| 16 |
// read from AWS Systems Manager Parameter Store |
| 17 |
// (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-paramstore.html) |
| 18 |
// Use OpenVariable to construct a *runtimevar.Variable. |
| 19 |
// |
| 20 |
// # URLs |
| 21 |
// |
| 22 |
// For runtimevar.OpenVariable, awsparamstore registers for the scheme "awsparamstore". |
| 23 |
// The default URL opener will use an AWS session with the default credentials |
| 24 |
// and configuration. |
| 25 |
// |
| 26 |
// To customize the URL opener, or for more details on the URL format, |
| 27 |
// see URLOpener. |
| 28 |
// See https://gocloud.dev/concepts/urls/ for background information. |
| 29 |
// |
| 30 |
// # As |
| 31 |
// |
| 32 |
// awsparamstore exposes the following types for As: |
| 33 |
// - Snapshot: *ssm.GetParameterOutput |
| 34 |
// - Error: any error type returned by the service, notably smithy.APIError |
| 35 |
package awsparamstore // import "gocloud.dev/runtimevar/awsparamstore" |
| 36 |
|
| 37 |
import ( |
| 38 |
"context" |
| 39 |
"errors" |
| 40 |
"fmt" |
| 41 |
"net/url" |
| 42 |
"path" |
| 43 |
"strings" |
| 44 |
"sync" |
| 45 |
"time" |
| 46 |
|
| 47 |
"github.com/aws/aws-sdk-go-v2/aws" |
| 48 |
"github.com/aws/aws-sdk-go-v2/service/ssm" |
| 49 |
"github.com/aws/smithy-go" |
| 50 |
"github.com/google/wire" |
| 51 |
gcaws "gocloud.dev/aws" |
| 52 |
"gocloud.dev/gcerrors" |
| 53 |
"gocloud.dev/runtimevar" |
| 54 |
"gocloud.dev/runtimevar/driver" |
| 55 |
) |
| 56 |
|
| 57 |
func init() { |
| 58 |
runtimevar.DefaultURLMux().RegisterVariable(Scheme, new(lazySessionOpener)) |
| 59 |
} |
| 60 |
|
| 61 |
// Set holds Wire providers for this package. |
| 62 |
var Set = wire.NewSet( |
| 63 |
Dial, |
| 64 |
) |
| 65 |
|
| 66 |
// Dial gets an AWS SSM service client using the AWS SDK V2. |
| 67 |
func Dial(cfg aws.Config) *ssm.Client { |
| 68 |
return ssm.NewFromConfig(cfg) |
| 69 |
} |
| 70 |
|
| 71 |
// URLOpener opens AWS Paramstore URLs like "awsparamstore://myvar". |
| 72 |
// |
| 73 |
// See https://pkg.go.dev/gocloud.dev/aws#V2ConfigFromURLParams. |
| 74 |
// |
| 75 |
// In addition, the following URL parameters are supported: |
| 76 |
// - decoder: The decoder to use. Defaults to URLOpener.Decoder, or |
| 77 |
// runtimevar.BytesDecoder if URLOpener.Decoder is nil. |
| 78 |
// See runtimevar.DecoderByName for supported values. |
| 79 |
// - wait: The poll interval, in time.ParseDuration formats. |
| 80 |
// Defaults to 30s. |
| 81 |
type URLOpener struct { |
| 82 |
// Decoder specifies the decoder to use if one is not specified in the URL. |
| 83 |
// Defaults to runtimevar.BytesDecoder. |
| 84 |
Decoder *runtimevar.Decoder |
| 85 |
|
| 86 |
// Options specifies the options to pass to New. |
| 87 |
Options Options |
| 88 |
} |
| 89 |
|
| 90 |
// lazySessionOpener obtains the AWS session from the environment on the first |
| 91 |
// call to OpenVariableURL. |
| 92 |
type lazySessionOpener struct { |
| 93 |
init sync.Once |
| 94 |
opener *URLOpener |
| 95 |
err error |
| 96 |
} |
| 97 |
|
| 98 |
func (o *lazySessionOpener) OpenVariableURL(ctx context.Context, u *url.URL) (*runtimevar.Variable, error) { |
| 99 |
opener := &URLOpener{} |
| 100 |
return opener.OpenVariableURL(ctx, u) |
| 101 |
} |
| 102 |
|
| 103 |
// Scheme is the URL scheme awsparamstore registers its URLOpener under on runtimevar.DefaultMux. |
| 104 |
const Scheme = "awsparamstore" |
| 105 |
|
| 106 |
// OpenVariableURL opens the variable at the URL's path. See the package doc |
| 107 |
// for more details. |
| 108 |
func (o *URLOpener) OpenVariableURL(ctx context.Context, u *url.URL) (*runtimevar.Variable, error) { |
| 109 |
q := u.Query() |
| 110 |
|
| 111 |
decoderName := q.Get("decoder") |
| 112 |
q.Del("decoder") |
| 113 |
decoder, err := runtimevar.DecoderByName(ctx, decoderName, o.Decoder) |
| 114 |
if err != nil { |
| 115 |
return nil, fmt.Errorf("open variable %v: invalid decoder: %v", u, err) |
| 116 |
} |
| 117 |
opts := o.Options |
| 118 |
if s := q.Get("wait"); s != "" { |
| 119 |
q.Del("wait") |
| 120 |
d, err := time.ParseDuration(s) |
| 121 |
if err != nil { |
| 122 |
return nil, fmt.Errorf("open variable %v: invalid wait %q: %v", u, s, err) |
| 123 |
} |
| 124 |
opts.WaitDuration = d |
| 125 |
} |
| 126 |
|
| 127 |
cfg, err := gcaws.V2ConfigFromURLParams(ctx, q) |
| 128 |
if err != nil { |
| 129 |
return nil, fmt.Errorf("open variable %v: %v", u, err) |
| 130 |
} |
| 131 |
return OpenVariable(ssm.NewFromConfig(cfg), path.Join(u.Host, u.Path), decoder, &opts) |
| 132 |
} |
| 133 |
|
| 134 |
// Options sets options. |
| 135 |
type Options struct { |
| 136 |
// WaitDuration controls the rate at which Parameter Store is polled. |
| 137 |
// Defaults to 30 seconds. |
| 138 |
WaitDuration time.Duration |
| 139 |
} |
| 140 |
|
| 141 |
// OpenVariable constructs a *runtimevar.Variable backed by the variable name in |
| 142 |
// AWS Systems Manager Parameter Store, using AWS SDK V2. |
| 143 |
// Parameter Store returns raw bytes; provide a decoder to decode the raw bytes |
| 144 |
// into the appropriate type for runtimevar.Snapshot.Value. |
| 145 |
// See the runtimevar package documentation for examples of decoders. |
| 146 |
func OpenVariable(client *ssm.Client, name string, decoder *runtimevar.Decoder, opts *Options) (*runtimevar.Variable, error) { |
| 147 |
return runtimevar.New(newWatcher(client, name, decoder, opts)), nil |
| 148 |
} |
| 149 |
|
| 150 |
var OpenVariableV2 = OpenVariable |
| 151 |
|
| 152 |
func newWatcher(client *ssm.Client, name string, decoder *runtimevar.Decoder, opts *Options) *watcher { |
| 153 |
if opts == nil { |
| 154 |
opts = &Options{} |
| 155 |
} |
| 156 |
return &watcher{ |
| 157 |
client: client, |
| 158 |
name: name, |
| 159 |
wait: driver.WaitDuration(opts.WaitDuration), |
| 160 |
decoder: decoder, |
| 161 |
} |
| 162 |
} |
| 163 |
|
| 164 |
// state implements driver.State. |
| 165 |
type state struct { |
| 166 |
val any |
| 167 |
rawGet *ssm.GetParameterOutput |
| 168 |
updateTime time.Time |
| 169 |
version int64 |
| 170 |
err error |
| 171 |
} |
| 172 |
|
| 173 |
// Value implements driver.State.Value. |
| 174 |
func (s *state) Value() (any, error) { |
| 175 |
return s.val, s.err |
| 176 |
} |
| 177 |
|
| 178 |
// UpdateTime implements driver.State.UpdateTime. |
| 179 |
func (s *state) UpdateTime() time.Time { |
| 180 |
return s.updateTime |
| 181 |
} |
| 182 |
|
| 183 |
// As implements driver.State.As. |
| 184 |
func (s *state) As(i any) bool { |
| 185 |
switch p := i.(type) { |
| 186 |
case **ssm.GetParameterOutput: |
| 187 |
*p = s.rawGet |
| 188 |
default: |
| 189 |
return false |
| 190 |
} |
| 191 |
return true |
| 192 |
} |
| 193 |
|
| 194 |
// errorState returns a new State with err, unless prevS also represents |
| 195 |
// the same error, in which case it returns nil. |
| 196 |
func errorState(err error, prevS driver.State) driver.State { |
| 197 |
// Map aws.RequestCanceled to the more standard context package errors. |
| 198 |
if getErrorCode(err) == "CancelledError" { |
| 199 |
msg := err.Error() |
| 200 |
if strings.Contains(msg, "context deadline exceeded") { |
| 201 |
err = context.DeadlineExceeded |
| 202 |
} else { |
| 203 |
err = context.Canceled |
| 204 |
} |
| 205 |
} |
| 206 |
s := &state{err: err} |
| 207 |
if prevS == nil { |
| 208 |
return s |
| 209 |
} |
| 210 |
prev := prevS.(*state) |
| 211 |
if prev.err == nil { |
| 212 |
// New error. |
| 213 |
return s |
| 214 |
} |
| 215 |
if equivalentError(err, prev.err) { |
| 216 |
// Same error, return nil to indicate no change. |
| 217 |
return nil |
| 218 |
} |
| 219 |
return s |
| 220 |
} |
| 221 |
|
| 222 |
// equivalentError returns true iff err1 and err2 represent an equivalent error; |
| 223 |
// i.e., we don't want to return it to the user as a different error. |
| 224 |
func equivalentError(err1, err2 error) bool { |
| 225 |
if err1 == err2 || err1.Error() == err2.Error() { |
| 226 |
return true |
| 227 |
} |
| 228 |
code1 := getErrorCode(err1) |
| 229 |
code2 := getErrorCode(err2) |
| 230 |
return code1 != "" && code1 == code2 |
| 231 |
} |
| 232 |
|
| 233 |
type watcher struct { |
| 234 |
// client is the client to use. |
| 235 |
client *ssm.Client |
| 236 |
// name is the parameter to retrieve. |
| 237 |
name string |
| 238 |
// wait is the amount of time to wait between querying AWS. |
| 239 |
wait time.Duration |
| 240 |
// decoder is the decoder that unmarshals the value in the param. |
| 241 |
decoder *runtimevar.Decoder |
| 242 |
} |
| 243 |
|
| 244 |
func getParameter(ctx context.Context, client *ssm.Client, name string) (int64, []byte, time.Time, *ssm.GetParameterOutput, error) { |
| 245 |
getResp, err := client.GetParameter(ctx, &ssm.GetParameterInput{ |
| 246 |
Name: aws.String(name), |
| 247 |
// Ignored if the parameter is not encrypted. |
| 248 |
WithDecryption: aws.Bool(true), |
| 249 |
}) |
| 250 |
if err != nil { |
| 251 |
return 0, nil, time.Time{}, nil, err |
| 252 |
} |
| 253 |
if getResp.Parameter == nil { |
| 254 |
return 0, nil, time.Time{}, getResp, fmt.Errorf("unable to get %q parameter", name) |
| 255 |
} |
| 256 |
return getResp.Parameter.Version, []byte(aws.ToString(getResp.Parameter.Value)), aws.ToTime(getResp.Parameter.LastModifiedDate), getResp, nil |
| 257 |
} |
| 258 |
|
| 259 |
func (w *watcher) WatchVariable(ctx context.Context, prev driver.State) (driver.State, time.Duration) { |
| 260 |
lastVersion := int64(-1) |
| 261 |
if prev != nil { |
| 262 |
lastVersion = prev.(*state).version |
| 263 |
} |
| 264 |
|
| 265 |
// GetParameter from S3 to get the current value and version. |
| 266 |
newVersion, newVal, newLastModified, rawGet, err := getParameter(ctx, w.client, w.name) |
| 267 |
if err != nil { |
| 268 |
return errorState(err, prev), w.wait |
| 269 |
} |
| 270 |
if newVersion == lastVersion { |
| 271 |
// Version hasn't changed, so no change; return nil. |
| 272 |
return nil, w.wait |
| 273 |
} |
| 274 |
|
| 275 |
// New value (or at least, new version). Decode it. |
| 276 |
val, err := w.decoder.Decode(ctx, newVal) |
| 277 |
if err != nil { |
| 278 |
return errorState(err, prev), w.wait |
| 279 |
} |
| 280 |
return &state{ |
| 281 |
val: val, |
| 282 |
rawGet: rawGet, |
| 283 |
updateTime: newLastModified, |
| 284 |
version: newVersion, |
| 285 |
}, w.wait |
| 286 |
} |
| 287 |
|
| 288 |
// Close implements driver.Close. |
| 289 |
func (w *watcher) Close() error { |
| 290 |
return nil |
| 291 |
} |
| 292 |
|
| 293 |
// ErrorAs implements driver.ErrorAs. |
| 294 |
func (w *watcher) ErrorAs(err error, i any) bool { |
| 295 |
return errors.As(err, i) |
| 296 |
} |
| 297 |
|
| 298 |
func getErrorCode(err error) string { |
| 299 |
var ae smithy.APIError |
| 300 |
if errors.As(err, &ae) { |
| 301 |
return ae.ErrorCode() |
| 302 |
} |
| 303 |
return "" |
| 304 |
} |
| 305 |
|
| 306 |
// ErrorCode implements driver.ErrorCode. |
| 307 |
func (w *watcher) ErrorCode(err error) gcerrors.ErrorCode { |
| 308 |
code := getErrorCode(err) |
| 309 |
if code == "ParameterNotFound" { |
| 310 |
return gcerrors.NotFound |
| 311 |
} |
| 312 |
return gcerrors.Unknown |
| 313 |
} |