forked from kubermatic/machine-controller
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.go
More file actions
88 lines (76 loc) · 2.27 KB
/
plugin.go
File metadata and controls
88 lines (76 loc) · 2.27 KB
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
/*
Copyright 2019 The Machine Controller Authors.
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.
*/
//
// Core UserData plugin.
//
// Package plugin provides the plugin side of the plugin mechanism.
// Individual plugins have to implement the provider interface,
// pass it to a new plugin instance, and call run.
package plugin
import (
"encoding/json"
"fmt"
"os"
"github.com/kubermatic/machine-controller/pkg/apis/plugin"
)
// Provider defines the interface each plugin has to implement
// for the retrieval of the userdata based on the given arguments.
type Provider interface {
UserData(req plugin.UserDataRequest) (string, error)
}
// Plugin implements a convenient helper to map the request to the given
// provider and return the response.
type Plugin struct {
provider Provider
debug bool
}
// New creates a new plugin.
func New(provider Provider, debug bool) *Plugin {
return &Plugin{
provider: provider,
debug: debug,
}
}
// Run looks for the given request and executes it.
func (p *Plugin) Run() error {
reqEnv := os.Getenv(plugin.EnvUserDataRequest)
if reqEnv == "" {
resp := plugin.ErrorResponse{
Err: fmt.Sprintf("environment variable '%s' not set", plugin.EnvUserDataRequest),
}
return p.printResponse(resp)
}
// Handle the request for user data.
var req plugin.UserDataRequest
err := json.Unmarshal([]byte(reqEnv), &req)
if err != nil {
return err
}
userData, err := p.provider.UserData(req)
var resp plugin.UserDataResponse
if err != nil {
resp.Err = err.Error()
} else {
resp.UserData = userData
}
return p.printResponse(resp)
}
// printResponse marshals the response and prints it to stdout.
func (p *Plugin) printResponse(resp interface{}) error {
bs, err := json.Marshal(resp)
if err != nil {
return err
}
_, err = fmt.Printf("%s", string(bs))
return err
}