/
dumplogs.go
220 lines (193 loc) · 5.96 KB
/
dumplogs.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
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
// A simple command for dumping out the logs stored in
// MongoDB. Intended to be use in emergency situations to recover logs
// when Juju is broken somehow.
package dumplogs
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/juju/clock"
"github.com/juju/cmd/v3"
"github.com/juju/errors"
"github.com/juju/gnuflag"
"github.com/juju/loggo"
"github.com/juju/names/v5"
"github.com/juju/juju/agent"
jujucmd "github.com/juju/juju/cmd"
"github.com/juju/juju/cmd/jujud/agent/agentconf"
corelogger "github.com/juju/juju/core/logger"
corenames "github.com/juju/juju/juju/names"
"github.com/juju/juju/mongo"
"github.com/juju/juju/state"
)
// NewCommand returns a new Command instance which implements the
// "juju-dumplogs" command.
func NewCommand() cmd.Command {
return &dumpLogsCommand{
agentConfig: agentconf.NewAgentConf(""),
}
}
type dumpLogsCommand struct {
cmd.CommandBase
agentConfig agentconf.AgentConf
machineId string
outDir string
}
// Info implements cmd.Command.
func (c *dumpLogsCommand) Info() *cmd.Info {
doc := `
This tool can be used to access Juju's logs when the Juju controller
isn't functioning for some reason. It must be run on a Juju controller
server, connecting to the Juju database instance and generating a log
file for each model that exists in the controller.
Log files are written out to the current working directory by
default. Use -d / --output-directory option to specify an alternate
target directory.
In order to connect to the database, the local machine agent's
configuration is needed. In most circumstances the configuration will
be found automatically. The --data-dir and/or --machine-id options may
be required if the agent configuration can't be found automatically.
`[1:]
return jujucmd.Info(&cmd.Info{
Name: corenames.JujuDumpLogs,
Purpose: "output the logs that are stored in the local Juju database",
Doc: doc,
})
}
// SetFlags implements cmd.Command.
func (c *dumpLogsCommand) SetFlags(f *gnuflag.FlagSet) {
c.agentConfig.AddFlags(f)
f.StringVar(&c.outDir, "d", ".", "directory to write logs files to")
f.StringVar(&c.outDir, "output-directory", ".", "")
f.StringVar(&c.machineId, "machine-id", "", "id of the machine on this host (optional)")
}
// Init implements cmd.Command.
func (c *dumpLogsCommand) Init(args []string) error {
err := c.agentConfig.CheckArgs(args)
if err != nil {
return errors.Trace(err)
}
var agentTag names.Tag
if c.machineId == "" {
agentTag, err = c.findAgentTag(c.agentConfig.DataDir())
if err != nil {
return errors.Trace(err)
}
} else if !names.IsValidMachine(c.machineId) {
return errors.New("--machine-id option expects a non-negative integer")
} else {
agentTag = names.NewMachineTag(c.machineId)
}
err = c.agentConfig.ReadConfig(agentTag.String())
if err != nil {
return errors.Trace(err)
}
return nil
}
// Run implements cmd.Command.
func (c *dumpLogsCommand) Run(ctx *cmd.Context) error {
config := c.agentConfig.CurrentConfig()
info, ok := config.MongoInfo()
if !ok {
return errors.New("no database connection info available (is this a controller host?)")
}
session, err := mongo.DialWithInfo(*info, mongo.DefaultDialOpts())
if err != nil {
return errors.Trace(err)
}
defer session.Close()
statePool, err := state.OpenStatePool(state.OpenParams{
Clock: clock.WallClock,
ControllerTag: config.Controller(),
ControllerModelTag: config.Model(),
MongoSession: session,
})
if err != nil {
return errors.Annotate(err, "failed to connect to database")
}
defer statePool.Close()
st0, err := statePool.SystemState()
if err != nil {
return errors.Trace(err)
}
modelUUIDs, err := st0.AllModelUUIDs()
if err != nil {
return errors.Annotate(err, "failed to look up models")
}
for _, modelUUID := range modelUUIDs {
err := c.dumpLogsForEnv(ctx, statePool, names.NewModelTag(modelUUID))
if err != nil {
return errors.Annotatef(err, "failed to dump logs for model %s", modelUUID)
}
}
return nil
}
func (c *dumpLogsCommand) findAgentTag(dataDir string) (names.Tag, error) {
entries, err := os.ReadDir(agent.BaseDir(dataDir))
if err != nil {
return nil, errors.Annotate(err, "failed to read agent configuration base directory")
}
for _, entry := range entries {
if entry.IsDir() {
var tag names.Tag
tag, err = names.ParseMachineTag(entry.Name())
if err == nil {
return tag, nil
}
tag, err = names.ParseControllerAgentTag(entry.Name())
if err == nil {
return tag, nil
}
}
}
return nil, errors.New("no machine or controller agent configuration found")
}
func (c *dumpLogsCommand) dumpLogsForEnv(ctx *cmd.Context, statePool *state.StatePool, tag names.ModelTag) error {
st, err := statePool.Get(tag.Id())
if err != nil {
if errors.IsNotFound(err) {
ctx.Infof("model with uuid %v has been removed", tag.Id())
return nil
}
return errors.Annotate(err, "failed open model")
}
defer st.Release()
logName := ctx.AbsPath(filepath.Join(c.outDir, fmt.Sprintf("%s.log", tag.Id())))
ctx.Infof("writing to %s", logName)
file, err := os.Create(logName)
if err != nil {
return errors.Annotate(err, "failed to open output file")
}
defer file.Close()
writer := bufio.NewWriter(file)
defer writer.Flush()
tailer, err := state.NewLogTailer(st, corelogger.LogTailerParams{NoTail: true}, nil)
if err != nil {
return errors.Annotate(err, "failed to create a log tailer")
}
logs := tailer.Logs()
for {
rec, ok := <-logs
if !ok {
break
}
_, _ = writer.WriteString(c.format(
rec.Time,
rec.Level,
rec.Entity,
rec.Module,
rec.Message,
rec.Labels,
) + "\n")
}
return nil
}
func (c *dumpLogsCommand) format(timestamp time.Time, level loggo.Level, entity, module, message string, labels []string) string {
ts := timestamp.In(time.UTC).Format("2006-01-02 15:04:05")
return fmt.Sprintf("%s: %s %s %s %s %s", entity, ts, level, module, message, strings.Join(labels, ","))
}