forked from google/cabbie
/
install.go
389 lines (339 loc) · 12.2 KB
/
install.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
// Copyright 2019 Google LLC
//
// 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 (
"golang.org/x/net/context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"flag"
"github.com/google/cabbie/notification"
"github.com/google/cabbie/cablib"
"github.com/google/cabbie/download"
"github.com/google/cabbie/install"
"github.com/google/cabbie/search"
"github.com/google/cabbie/session"
"github.com/google/cabbie/updatecollection"
"github.com/google/deck"
"github.com/google/subcommands"
"github.com/google/glazier/go/helpers"
)
// Available flags
type installCmd struct {
all, drivers, deadlineOnly, Interactive, virusDef bool
kbs string
}
type installRsp struct {
hResult string
resultCode int
rebootRequired bool
}
func (installCmd) Name() string { return "install" }
func (installCmd) Synopsis() string { return "Install selected available updates." }
func (installCmd) Usage() string {
return fmt.Sprintf("%s install [--drivers | --virusDef | --kbs=\"<KBNumber>\" | --all]\n", filepath.Base(os.Args[0]))
}
func (i *installCmd) SetFlags(f *flag.FlagSet) {
// Category Flags
f.BoolVar(&i.all, "all", false, "Install everything.")
f.BoolVar(&i.drivers, "drivers", false, "Install available drivers.")
f.BoolVar(&i.virusDef, "virus_def", false, "Update virus definitions.")
f.StringVar(&i.kbs, "kbs", "", "Comma separated string of KB numbers in the form of 1234567.")
// Behavior Flags
f.BoolVar(&i.deadlineOnly, "deadlineOnly", false, fmt.Sprintf("Install available updates older than %d days", config.Deadline))
}
var errInvalidFlags = errors.New("invalid flag combination")
func vetFlags(i installCmd) error {
f := 0
for _, v := range []bool{i.all, i.drivers, i.virusDef, len(i.kbs) > 0} {
if v {
f++
}
}
if f > 1 {
fmt.Println("Multiple install flags can not be passed at the same time.")
fmt.Printf("%s\nUsage: %s\n", i.Synopsis(), i.Usage())
return errInvalidFlags
}
return nil
}
func (i installCmd) Execute(_ context.Context, flags *flag.FlagSet, _ ...any) subcommands.ExitStatus {
if err := vetFlags(i); err != nil {
return subcommands.ExitUsageError
}
if err := i.installUpdates(); err != nil {
fmt.Printf("Failed to install updates: %v", err)
deck.ErrorfA("Failed to install updates: %v", err).With(eventID(cablib.EvtErrInstallFailure)).Go()
return subcommands.ExitFailure
}
select {
case <-rebootEvent:
fmt.Println("Please reboot to finalize the update installation.")
return 6
default:
fmt.Println("No reboot needed.")
}
return subcommands.ExitSuccess
}
func (i *installCmd) criteria() (string, []string) {
// Set search criteria and required categories.
var c string
var rc []string
switch {
case i.all:
c = search.BasicSearch
deck.InfofA("Starting search for all updates: %s", c).With(eventID(cablib.EvtSearch)).Go()
case i.drivers:
c = "Type='Driver'"
rc = append(rc, "Drivers")
deck.InfofA("Starting search for updated drivers: %s", c).With(eventID(cablib.EvtSearch)).Go()
case i.virusDef:
c = fmt.Sprintf("%s AND CategoryIDs contains '%s'", search.BasicSearch, search.DefinitionUpdates)
rc = append(rc, "Definition Updates")
deck.InfofA("Starting search for virus definitions:\n%s", c).With(eventID(cablib.EvtSearch)).Go()
case i.kbs != "":
c = search.BasicSearch
deck.InfofA("Starting search for KB's %q:\n%s", i.kbs, c).With(eventID(cablib.EvtSearch)).Go()
default:
c = search.BasicSearch
rc = config.RequiredCategories
deck.InfofA("Starting search for general updates: %s", c).With(eventID(cablib.EvtSearch)).Go()
}
return c, rc
}
func installingMessage() {
deck.InfoA("Cabbie is installing new updates.").With(eventID(cablib.EvtInstall)).Go()
if err := notification.NewInstallingMessage().Push(); err != nil {
deck.ErrorfA("Failed to create notification:\n%v", err).With(eventID(cablib.EvtErrNotifications)).Go()
}
}
func rebootMessage(seconds int) {
deck.InfoA("Updates have been installed, please reboot to complete the installation...").With(eventID(cablib.EvtInstallSuccess)).Go()
if err := notification.NewRebootMessage(seconds).Push(); err != nil {
deck.ErrorfA("Failed to create notification:\n%v", err).With(eventID(cablib.EvtErrNotifications)).Go()
}
}
func downloadCollection(s *session.UpdateSession, c *updatecollection.Collection) (int, error) {
d, err := download.NewDownloader(s, c)
if err != nil {
return 0, fmt.Errorf("error creating downloader:\n %v", err)
}
defer d.Close()
if err := d.Download(); err != nil {
return 0, fmt.Errorf("error downloading updates:\n %v", err)
}
return d.ResultCode()
}
func installCollection(s *session.UpdateSession, c *updatecollection.Collection) (*installRsp, error) {
inst, err := install.NewInstaller(s, c)
if err != nil {
return nil, fmt.Errorf("error creating installer: \n %v", err)
}
defer inst.Close()
if err := inst.Install(); err != nil {
return nil, fmt.Errorf("error installing updates:\n %v", err)
}
rc, err := inst.ResultCode()
if err != nil {
return nil, fmt.Errorf("error getting install ResultCode:\n %v", err)
}
hr, err := inst.HResult()
if err != nil {
return nil, fmt.Errorf("error getting install ReturnCode:\n %v", err)
}
rb, err := inst.RebootRequired()
return &installRsp{
hResult: hr,
resultCode: rc,
rebootRequired: rb,
}, err
}
func (i *installCmd) installUpdates() error {
var rebootRequired bool
// Check for reboot status when not installing virus definitions.
if !(i.virusDef) {
rebootRequired, err := cablib.RebootRequired()
if err != nil {
return fmt.Errorf("failed to determine reboot status: %v", err)
}
if rebootRequired {
if i.Interactive {
fmt.Println("Host has existing updates pending reboot.")
rebootEvent <- rebootRequired
return nil
}
t, err := cablib.RebootTime()
if err != nil {
return fmt.Errorf("Error getting reboot time: %v", err)
}
if t.IsZero() {
// Set reboot time if a reboot is pending but no time has been set.
// This can happen when a user installs updates outside of Cabbie.
rebootMessage(int(config.RebootDelay))
if err := cablib.SetRebootTime(config.RebootDelay); err != nil {
return fmt.Errorf("Failed to set reboot time:\n%v", err)
}
}
rebootEvent <- rebootRequired
return nil
}
}
// Start Windows update session
s, err := session.New()
if err != nil {
return fmt.Errorf("failed to create new Windows Update session: %v", err)
}
defer s.Close()
criteria, rc := i.criteria()
q, err := search.NewSearcher(s, criteria, config.WSUSServers, config.EnableThirdParty)
if err != nil {
return fmt.Errorf("failed to create a new searcher object: %v", err)
}
defer q.Close()
uc, err := q.QueryUpdates()
if er := searchHResult.Set(q.SearchHResult); er != nil {
deck.ErrorfA("Error posting metric:\n%v", er).With(eventID(cablib.EvtErrMetricReport)).Go()
}
if err != nil {
return fmt.Errorf("error encountered when attempting to query for updates: %v", err)
}
defer uc.Close()
if len(uc.Updates) == 0 {
deck.InfoA("No updates found to install.").With(eventID(cablib.EvtNoUpdates)).Go()
return nil
}
deck.InfofA("Updates Found:\n%s", strings.Join(uc.Titles(), "\n\n")).With(eventID(cablib.EvtUpdatesFound)).Go()
installMsgPopped := i.virusDef
installingMinOneUpdate := false
kbs := NewKBSet(i.kbs)
for _, u := range uc.Updates {
if !(u.InCategories(rc)) {
deck.InfofA("Skipping update %s.\nRequiredClassifications:\n%v\nUpdate classifications:\n%v",
u.Title,
rc,
u.Categories).With(eventID(cablib.EvtUpdateSkip)).Go()
continue
}
if !(u.EulaAccepted) {
deck.InfofA("Accepting EULA for update: %s", u.Title).With(eventID(cablib.EvtMisc)).Go()
if err := u.AcceptEula(); err != nil {
deck.ErrorfA("Failed to accept EULA for update %s:\n%s", u.Title, err).With(eventID(cablib.EvtErrMisc)).Go()
}
}
if kbs.Size() > 0 {
if !kbs.Search(u.KBArticleIDs) {
deck.InfofA("Skipping update %s.\nRequired KBs:\n%s\nUpdate KBs:\n%v",
u.Title,
kbs,
u.KBArticleIDs).With(eventID(cablib.EvtUpdateSkip)).Go()
continue
}
}
if i.deadlineOnly {
deadline := time.Duration(config.Deadline) * 24 * time.Hour
pastDeadline := time.Now().After(u.LastDeploymentChangeTime.Add(deadline))
if !pastDeadline {
deck.InfofA(
"Skipping update %s.\nUpdate deployed on %v has not reached the %d day threshold.",
u.Title,
u.LastDeploymentChangeTime,
config.Deadline).With(eventID(cablib.EvtUpdateSkip)).Go()
continue
}
deck.InfofA(
"Update %s deployed on %v has exceeded the %d day threshold.",
u.Title,
u.LastDeploymentChangeTime,
config.Deadline).With(eventID(cablib.EvtUpdatesFound)).Go()
}
c, err := updatecollection.New()
if err != nil {
deck.ErrorfA("Failed to create collection: %v", err).With(eventID(cablib.EvtErrMisc)).Go()
continue
}
c.Add(u.Item)
if !installMsgPopped && !u.InCategories([]string{"Definition Updates"}) {
installingMessage()
installMsgPopped = true
ps := filepath.Join(cablib.CabbiePath, "PreUpdate.ps1")
exist, err := helpers.PathExists(ps)
if err != nil {
deck.ErrorfA("PreUpdateScript: error checking existence of %q:\n%v", cablib.CabbiePath+"PreUpdate.ps1", err).With(eventID(cablib.EvtErrUpdateScript)).Go()
} else if exist {
if _, err := helpers.ExecWithVerify(ps, nil, &config.ScriptTimeout, nil); err != nil {
deck.ErrorfA("PreUpdateScript: error running script:\n%v", err).With(eventID(cablib.EvtErrUpdateScript)).Go()
}
}
installingMinOneUpdate = true
}
deck.InfofA("Downloading Update:\n%v", u).With(eventID(cablib.EvtDownload)).Go()
rc, err := downloadCollection(s, c)
if err != nil {
deck.ErrorA(err).With(eventID(cablib.EvtErrMisc)).Go()
c.Close()
continue
}
if rc == 2 {
deck.InfofA("Successfully downloaded update:\n %s", u.Title).With(eventID(cablib.EvtDownload)).Go()
} else {
deck.ErrorfA("Failed to download update:\n %s\n ReturnCode: %d", u.Title, rc).With(eventID(cablib.EvtErrDownloadFailure)).Go()
c.Close()
continue
}
deck.InfofA("Installing Update:\n%v", u).With(eventID(cablib.EvtInstall)).Go()
rsp, err := installCollection(s, c)
if err != nil {
deck.ErrorA(err).With(eventID(cablib.EvtErrMisc)).Go()
c.Close()
continue
}
if err := installHResult.Set(rsp.hResult); err != nil {
deck.ErrorfA("Error posting metric:\n%v", err).With(eventID(cablib.EvtErrMetricReport)).Go()
}
if rsp.resultCode == 2 {
deck.InfofA("Successfully installed update:\n%s\nHResult Code: %s", u.Title, rsp.hResult).With(eventID(cablib.EvtInstall)).Go()
} else {
deck.ErrorfA("Failed to install update:\n%s\nReturnCode: %d\nHResult Code: %s", u.Title, rsp.resultCode, rsp.hResult).With(eventID(cablib.EvtErrInstallFailure)).Go()
c.Close()
continue
}
deck.InfofA("Install Reboot Required: %t", rsp.rebootRequired).With(eventID(cablib.EvtRebootRequired)).Go()
if !rebootRequired {
rebootRequired = rsp.rebootRequired
}
c.Close()
}
if installingMinOneUpdate {
ps := filepath.Join(cablib.CabbiePath, "PostUpdate.ps1")
exist, err := helpers.PathExists(ps)
if err != nil {
deck.ErrorfA("PostUpdateScript: error checking existence of %q:\n%v", cablib.CabbiePath+"PostUpdate.ps1", err).With(eventID(cablib.EvtErrUpdateScript)).Go()
} else if exist {
if _, err := helpers.ExecWithVerify(ps, nil, &config.ScriptTimeout, nil); err != nil {
deck.ErrorfA("PostUpdateScript: error executing script:\n%v", err).With(eventID(cablib.EvtErrUpdateScript)).Go()
}
}
}
if rebootRequired {
rebootMessage(int(config.RebootDelay))
if err := cablib.SetRebootTime(config.RebootDelay); err != nil {
deck.ErrorfA("Failed to run reboot command:\n%v", err).With(eventID(cablib.EvtErrPowerMgmt)).Go()
}
rebootEvent <- rebootRequired
}
return nil
}