/
systray.go
221 lines (190 loc) · 6.19 KB
/
systray.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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-2020 Datadog, Inc.
// +build windows
package main
import (
"flag"
"fmt"
"os"
"os/exec"
"github.com/DataDog/datadog-agent/pkg/util/log"
seelog "github.com/cihub/seelog"
"github.com/DataDog/datadog-agent/pkg/version"
"github.com/lxn/walk"
"golang.org/x/sys/windows"
)
type menuItem struct {
label string
handler walk.EventHandler
enabled bool
}
var (
separator = "SEPARATOR"
ni *walk.NotifyIcon
launchgui bool
eventname = windows.StringToUTF16Ptr("ddtray-event")
)
func init() {
enableLoggingToFile()
}
func createMenuItems(notifyIcon *walk.NotifyIcon) []menuItem {
av, _ := version.Agent()
verstring := av.GetNumberAndPre()
isAdmin, err := isUserAnAdmin()
areAdminButtonsAvailable := isAdmin
if err != nil {
log.Warnf("Failed to call isUserAnAdmin %v", err)
// If we cannot determine if the user is admin or not let the user allow to click on the buttons.
areAdminButtonsAvailable = true
}
checkRightsAndRun := func(action func()) func() {
return func() {
if !areAdminButtonsAvailable {
showCustomMessage(notifyIcon, "You do not have the right to perform this action. "+
"Please login with administrator account.")
} else {
action()
}
}
}
menuitems := make([]menuItem, 0)
menuitems = append(menuitems, menuItem{label: verstring, enabled: false})
menuitems = append(menuitems, menuItem{label: separator})
menuitems = append(menuitems, menuItem{label: "&Start", handler: checkRightsAndRun(onStart), enabled: true})
menuitems = append(menuitems, menuItem{label: "S&top", handler: checkRightsAndRun(onStop), enabled: true})
menuitems = append(menuitems, menuItem{label: "&Restart", handler: checkRightsAndRun(onRestart), enabled: true})
menuitems = append(menuitems, menuItem{label: "&Configure", handler: checkRightsAndRun(onConfigure), enabled: canConfigure()})
menuitems = append(menuitems, menuItem{label: "&Flare", handler: onFlare, enabled: true})
menuitems = append(menuitems, menuItem{label: separator})
menuitems = append(menuitems, menuItem{label: "E&xit", handler: onExit, enabled: true})
return menuitems
}
func isUserAnAdmin() (bool, error) {
shell32 := windows.NewLazySystemDLL("Shell32.dll")
defer windows.FreeLibrary(windows.Handle(shell32.Handle()))
isUserAnAdminProc := shell32.NewProc("IsUserAnAdmin")
ret, _, winError := isUserAnAdminProc.Call()
if winError != windows.NTE_OP_OK {
return false, fmt.Errorf("IsUserAnAdmin returns error code %d", winError)
}
if ret == 0 {
return false, nil
}
return true, nil
}
func showCustomMessage(notifyIcon *walk.NotifyIcon, message string) {
if err := notifyIcon.ShowCustom("Datadog Agent Manager", message); err != nil {
log.Warnf("Failed to show custom message %v", err)
}
}
func onExit() {
walk.App().Exit(0)
}
func main() {
flag.BoolVar(&launchgui, "launch-gui", false, "Launch browser configuration and exit")
flag.Parse()
log.Debugf("launch-gui is %v", launchgui)
if launchgui {
//enableLoggingToConsole()
defer log.Flush()
log.Debug("Preparing to launch configuration interface...")
onConfigure()
}
// check to see if the process is already running. If so, just exit
h, _ := windows.OpenEvent(0x1F0003, // EVENT_ALL_ACCESS
false,
eventname)
if h != windows.Handle(0) {
// was already there. Process already running. We're done
windows.CloseHandle(h)
return
}
// otherwise, create the handle so that nobody else will
h, _ = windows.CreateEvent(nil, 0, 0, eventname)
// should never fail; test just to make sure we don't close unopened handle
if h != windows.Handle(0) {
defer windows.CloseHandle(h)
}
// We need either a walk.MainWindow or a walk.Dialog for their message loop.
// We will not make it visible in this example, though.
mw, err := walk.NewMainWindow()
if err != nil {
log.Errorf("Failed to create main window %v", err)
os.Exit(1)
}
icon, err := walk.NewIconFromResourceId(3)
if err != nil {
log.Warnf("Failed to load icon %v", err)
}
// Create the notify icon and make sure we clean it up on exit.
ni, err = walk.NewNotifyIcon()
if err != nil {
log.Errorf("Failed to create newNotifyIcon %v", err)
os.Exit(2)
}
defer ni.Dispose()
// Set the icon and a tool tip text.
if err := ni.SetIcon(icon); err != nil {
log.Warnf("Failed to set icon %v", err)
}
if err := ni.SetToolTip("Click for info or use the context menu to exit."); err != nil {
log.Warnf("Failed to set tooltip text %v", err)
}
// When the left mouse button is pressed, bring up our balloon.
ni.MouseDown().Attach(func(x, y int, button walk.MouseButton) {
if button != walk.LeftButton {
return
}
showCustomMessage(ni, "Please right click to display available options.")
})
menuitems := createMenuItems(ni)
for _, item := range menuitems {
var action *walk.Action
if item.label == separator {
action = walk.NewSeparatorAction()
} else {
action = walk.NewAction()
if err := action.SetText(item.label); err != nil {
log.Warnf("Failed to set text for item %s %v", item.label, err)
continue
}
action.SetEnabled(item.enabled)
if item.handler != nil {
action.Triggered().Attach(item.handler)
}
}
ni.ContextMenu().Actions().Add(action)
}
// The notify icon is hidden initially, so we have to make it visible.
if err := ni.SetVisible(true); err != nil {
log.Warnf("Failed to set window visibility %v", err)
}
// Run the message loop.
mw.Run()
}
// opens a browser window at the specified URL
func open(url string) error {
return exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
}
func enableLoggingToFile() {
seeConfig := `
<seelog minlevel="debug">
<outputs>
<rollingfile type="size" filename="c:\\ProgramData\\DataDog\\Logs\\ddtray.log" maxsize="1000000" maxrolls="2" />
</outputs>
</seelog>`
logger, _ := seelog.LoggerFromConfigAsBytes([]byte(seeConfig))
log.ReplaceLogger(logger)
}
func enableLoggingToConsole() {
seeConfig := `
<seelog minlevel="debug">
<outputs>
<console />
</outputs>
</seelog>`
logger, _ := seelog.LoggerFromConfigAsBytes([]byte(seeConfig))
log.ReplaceLogger(logger)
}