/
main.go
204 lines (181 loc) · 5.53 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
// Copyright 2012-2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package main
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/juju/cmd"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/utils/exec"
jujucmd "github.com/juju/juju/cmd"
agentcmd "github.com/juju/juju/cmd/jujud/agent"
"github.com/juju/juju/juju/names"
"github.com/juju/juju/juju/sockets"
// Import the providers.
_ "github.com/juju/juju/provider/all"
"github.com/juju/juju/worker/uniter/runner/jujuc"
)
var jujudDoc = `
juju provides easy, intelligent service orchestration on top of environments
such as OpenStack, Amazon AWS, or bare metal. jujud is a component of juju.
https://juju.ubuntu.com/
The jujud command can also forward invocations over RPC for execution by the
juju unit agent. When used in this way, it expects to be called via a symlink
named for the desired remote command, and expects JUJU_AGENT_SOCKET and
JUJU_CONTEXT_ID be set in its environment.
`
const (
// exit_err is the value that is returned when the user has run juju in an invalid way.
exit_err = 2
// exit_panic is the value that is returned when we exit due to an unhandled panic.
exit_panic = 3
)
func getenv(name string) (string, error) {
value := os.Getenv(name)
if value == "" {
return "", fmt.Errorf("%s not set", name)
}
return value, nil
}
func getwd() (string, error) {
dir, err := os.Getwd()
if err != nil {
return "", err
}
abs, err := filepath.Abs(dir)
if err != nil {
return "", err
}
return abs, nil
}
// jujuCMain uses JUJU_CONTEXT_ID and JUJU_AGENT_SOCKET to ask a running unit agent
// to execute a Command on our behalf. Individual commands should be exposed
// by symlinking the command name to this executable.
func jujuCMain(commandName string, ctx *cmd.Context, args []string) (code int, err error) {
code = 1
contextId, err := getenv("JUJU_CONTEXT_ID")
if err != nil {
return
}
dir, err := getwd()
if err != nil {
return
}
req := jujuc.Request{
ContextId: contextId,
Dir: dir,
CommandName: commandName,
Args: args[1:],
}
socketPath, err := getenv("JUJU_AGENT_SOCKET")
if err != nil {
return
}
client, err := sockets.Dial(socketPath)
if err != nil {
return
}
defer client.Close()
var resp exec.ExecResponse
err = client.Call("Jujuc.Main", req, &resp)
if err != nil && err.Error() == jujuc.ErrNoStdin.Error() {
req.Stdin, err = ioutil.ReadAll(os.Stdin)
if err != nil {
err = errors.Annotate(err, "cannot read stdin")
return
}
req.StdinSet = true
err = client.Call("Jujuc.Main", req, &resp)
}
if err != nil {
return
}
os.Stdout.Write(resp.Stdout)
os.Stderr.Write(resp.Stderr)
return resp.Code, nil
}
// Main registers subcommands for the jujud executable, and hands over control
// to the cmd package.
func jujuDMain(args []string, ctx *cmd.Context) (code int, err error) {
jujud := jujucmd.NewSuperCommand(cmd.SuperCommandParams{
Name: "jujud",
Doc: jujudDoc,
})
jujud.Log.Factory = &writerFactory{}
jujud.Register(NewBootstrapCommand())
// TODO(katco-): AgentConf type is doing too much. The
// MachineAgent type has called out the seperate concerns; the
// AgentConf should be split up to follow suite.
agentConf := agentcmd.NewAgentConf("")
machineAgentFactory := agentcmd.MachineAgentFactoryFn(agentConf, agentConf)
jujud.Register(agentcmd.NewMachineAgentCmd(ctx, machineAgentFactory, agentConf, agentConf))
jujud.Register(agentcmd.NewUnitAgent(ctx))
code = cmd.Main(jujud, ctx, args[1:])
return code, nil
}
// Main is not redundant with main(), because it provides an entry point
// for testing with arbitrary command line arguments.
func Main(args []string) {
defer func() {
if r := recover(); r != nil {
buf := make([]byte, 4096)
buf = buf[:runtime.Stack(buf, false)]
logger.Criticalf("Unhandled panic: \n%v\n%s", r, buf)
os.Exit(exit_panic)
}
}()
var code int = 1
ctx, err := cmd.DefaultContext()
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(exit_err)
}
commandName := filepath.Base(args[0])
if commandName == names.Jujud {
code, err = jujuDMain(args, ctx)
} else if commandName == names.Jujuc {
fmt.Fprint(os.Stderr, jujudDoc)
code = exit_err
err = fmt.Errorf("jujuc should not be called directly")
} else if commandName == names.JujuRun {
code = cmd.Main(&RunCommand{}, ctx, args[1:])
} else {
code, err = jujuCMain(commandName, ctx, args)
}
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
}
os.Exit(code)
}
type writerFactory struct{}
func (*writerFactory) NewWriter(target io.Writer) loggo.Writer {
return &jujudWriter{target: target}
}
type jujudWriter struct {
target io.Writer
unitFormatter simpleFormatter
defaultFormatter loggo.DefaultFormatter
}
var _ loggo.Writer = (*jujudWriter)(nil)
func (w *jujudWriter) Write(level loggo.Level, module, filename string, line int, timestamp time.Time, message string) {
if strings.HasPrefix(module, "unit.") {
fmt.Fprintln(w.target, w.unitFormatter.Format(level, module, timestamp, message))
} else {
fmt.Fprintln(w.target, w.defaultFormatter.Format(level, module, filename, line, timestamp, message))
}
}
type simpleFormatter struct{}
func (*simpleFormatter) Format(level loggo.Level, module string, timestamp time.Time, message string) string {
ts := timestamp.In(time.UTC).Format("2006-01-02 15:04:05")
// Just show the last element of the module.
lastDot := strings.LastIndex(module, ".")
module = module[lastDot+1:]
return fmt.Sprintf("%s %s %s %s", ts, level, module, message)
}