forked from open-telemetry/opentelemetry-collector
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapplication_windows.go
More file actions
188 lines (157 loc) · 5.37 KB
/
application_windows.go
File metadata and controls
188 lines (157 loc) · 5.37 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
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
// Copyright The OpenTelemetry 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.
// +build windows
package service
import (
"fmt"
"syscall"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"golang.org/x/sys/windows/svc"
"golang.org/x/sys/windows/svc/eventlog"
)
type WindowsService struct {
params Parameters
app *Application
}
func NewWindowsService(params Parameters) *WindowsService {
return &WindowsService{params: params}
}
// Execute implements https://godoc.org/golang.org/x/sys/windows/svc#Handler
func (s *WindowsService) Execute(args []string, requests <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) {
// The first argument supplied to service.Execute is the service name. If this is
// not provided for some reason, raise a relevant error to the system event log
if len(args) == 0 {
return false, 1213 // 1213: ERROR_INVALID_SERVICENAME
}
elog, err := openEventLog(args[0])
if err != nil {
return false, 1501 // 1501: ERROR_EVENTLOG_CANT_START
}
appErrorChannel := make(chan error, 1)
changes <- svc.Status{State: svc.StartPending}
if err = s.start(elog, appErrorChannel); err != nil {
elog.Error(3, fmt.Sprintf("failed to start service: %v", err))
return false, 1064 // 1064: ERROR_EXCEPTION_IN_SERVICE
}
changes <- svc.Status{State: svc.Running, Accepts: svc.AcceptStop | svc.AcceptShutdown}
for req := range requests {
switch req.Cmd {
case svc.Interrogate:
changes <- req.CurrentStatus
case svc.Stop, svc.Shutdown:
changes <- svc.Status{State: svc.StopPending}
if err := s.stop(appErrorChannel); err != nil {
elog.Error(3, fmt.Sprintf("errors occurred while shutting down the service: %v", err))
}
changes <- svc.Status{State: svc.Stopped}
return false, 0
default:
elog.Error(3, fmt.Sprintf("unexpected service control request #%d", req.Cmd))
return false, 1052 // 1052: ERROR_INVALID_SERVICE_CONTROL
}
}
return false, 0
}
func (s *WindowsService) start(elog *eventlog.Log, appErrorChannel chan error) error {
var err error
s.app, err = newWithWindowsEventLogCore(s.params, elog)
if err != nil {
return err
}
// app.Start blocks until receiving a SIGTERM signal, so needs to be started
// asynchronously, but it will exit early if an error occurs on startup
go func() { appErrorChannel <- s.app.Run() }()
// wait until the app is in the Running state
go func() {
for state := range s.app.GetStateChannel() {
if state == Running {
appErrorChannel <- nil
break
}
}
}()
// wait until the app is in the Running state, or an error was returned
return <-appErrorChannel
}
func (s *WindowsService) stop(appErrorChannel chan error) error {
// simulate a SIGTERM signal to terminate the application
s.app.signalsChannel <- syscall.SIGTERM
// return the response of app.Start
return <-appErrorChannel
}
func openEventLog(serviceName string) (*eventlog.Log, error) {
elog, err := eventlog.Open(serviceName)
if err != nil {
return nil, fmt.Errorf("service failed to open event log: %w", err)
}
return elog, nil
}
func newWithWindowsEventLogCore(params Parameters, elog *eventlog.Log) (*Application, error) {
params.LoggingOptions = append(
params.LoggingOptions,
zap.WrapCore(withWindowsCore(elog)),
)
return New(params)
}
var _ zapcore.Core = (*windowsEventLogCore)(nil)
type windowsEventLogCore struct {
core zapcore.Core
elog *eventlog.Log
encoder zapcore.Encoder
}
func (w windowsEventLogCore) Enabled(level zapcore.Level) bool {
return w.core.Enabled(level)
}
func (w windowsEventLogCore) With(fields []zapcore.Field) zapcore.Core {
return withWindowsCore(w.elog)(w.core.With(fields))
}
func (w windowsEventLogCore) Check(ent zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {
if w.Enabled(ent.Level) {
return ce.AddCore(ent, w)
}
return ce
}
func (w windowsEventLogCore) Write(ent zapcore.Entry, fields []zapcore.Field) error {
buf, err := w.encoder.EncodeEntry(ent, fields)
if err != nil {
w.elog.Warning(2, fmt.Sprintf("failed encoding log entry %v\r\n", err))
return err
}
msg := buf.String()
buf.Free()
switch ent.Level {
case zapcore.FatalLevel, zapcore.PanicLevel, zapcore.DPanicLevel:
// golang.org/x/sys/windows/svc/eventlog does not support Critical level event logs
return w.elog.Error(3, msg)
case zapcore.ErrorLevel:
return w.elog.Error(3, msg)
case zapcore.WarnLevel:
return w.elog.Warning(2, msg)
case zapcore.InfoLevel:
return w.elog.Info(1, msg)
}
// We would not be here if debug were disabled so log as info to not drop.
return w.elog.Info(1, msg)
}
func (w windowsEventLogCore) Sync() error {
return w.core.Sync()
}
func withWindowsCore(elog *eventlog.Log) func(zapcore.Core) zapcore.Core {
return func(core zapcore.Core) zapcore.Core {
encoderConfig := zap.NewProductionEncoderConfig()
encoderConfig.LineEnding = "\r\n"
return windowsEventLogCore{core, elog, zapcore.NewConsoleEncoder(encoderConfig)}
}
}