File: service.go

package info (click to toggle)
go-dlib 5.6.0.9%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,212 kB
  • sloc: ansic: 4,664; xml: 1,456; makefile: 20; sh: 15
file content (371 lines) | stat: -rw-r--r-- 8,380 bytes parent folder | download | duplicates (3)
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
package dbusutil

import (
	"bytes"
	"errors"
	"fmt"
	"sort"
	"sync"
	"time"
	"unsafe"

	"github.com/godbus/dbus"
	"github.com/godbus/dbus/introspect"
)

type Service struct {
	conn *dbus.Conn
	mu   sync.RWMutex

	hasCall bool

	quit              chan struct{}
	canQuit           func() bool
	quitCheckInterval time.Duration

	objMap        map[dbus.ObjectPath]*ServerObject
	implStaticMap map[string]*implementerStatic
	//                ^interface name
	implObjMap map[unsafe.Pointer]*ServerObject
}

func NewService(conn *dbus.Conn) *Service {
	return &Service{
		conn:          conn,
		objMap:        make(map[dbus.ObjectPath]*ServerObject),
		implStaticMap: make(map[string]*implementerStatic),
		implObjMap:    make(map[unsafe.Pointer]*ServerObject),
	}
}

func NewSessionService() (*Service, error) {
	bus, err := dbus.SessionBus()
	if err != nil {
		return nil, err
	}
	return NewService(bus), nil
}

func NewSystemService() (*Service, error) {
	bus, err := dbus.SystemBus()
	if err != nil {
		return nil, err
	}
	return NewService(bus), nil
}

func (s *Service) Conn() *dbus.Conn {
	return s.conn
}

func (s *Service) RequestName(name string) error {
	reply, err := s.conn.RequestName(name, dbus.NameFlagDoNotQueue)
	if err != nil {
		return err
	}
	if reply != dbus.RequestNameReplyPrimaryOwner {
		return fmt.Errorf("name %s already taken", name)
	}
	return nil
}

func (s *Service) ReleaseName(name string) error {
	_, err := s.conn.ReleaseName(name)
	return err
}

func (s *Service) NewServerObject(path dbus.ObjectPath,
	implementers ...Implementer) (*ServerObject, error) {

	if !path.IsValid() {
		return nil, errors.New("path invalid")
	}

	if len(implementers) == 0 {
		return nil, errors.New("no implementer")
	}

	implMap := make(map[string]Implementer)
	implSlice := make([]*implementer, 0, len(implementers))

	for _, implCore := range implementers {
		ifcName := implCore.GetInterfaceName()
		_, ok := implMap[ifcName]
		if ok {
			return nil, errors.New("interface duplicated")
		}

		impl, err := newImplementer(implCore, s, path)
		if err != nil {
			return nil, err
		}
		implSlice = append(implSlice, impl)
		implMap[ifcName] = implCore
	}

	obj := &ServerObject{
		service:      s,
		path:         path,
		implementers: implSlice,
	}

	return obj, nil
}

func (s *Service) GetServerObject(impl Implementer) *ServerObject {
	ptr := getImplementerPointer(impl)
	s.mu.RLock()
	so := s.implObjMap[ptr]
	s.mu.RUnlock()
	return so
}

func (s *Service) GetServerObjectByPath(path dbus.ObjectPath) *ServerObject {
	s.mu.RLock()
	so := s.objMap[path]
	s.mu.RUnlock()
	return so
}

func (s *Service) Export(path dbus.ObjectPath, implements ...Implementer) error {
	so, err := s.NewServerObject(path, implements...)
	if err != nil {
		return err
	}
	return so.Export()
}

func (s *Service) StopExport(impl Implementer) error {
	so := s.GetServerObject(impl)
	if so == nil {
		return errors.New("server object not found")
	}
	return so.StopExport()
}

func (s *Service) StopExportByPath(path dbus.ObjectPath) error {
	so := s.GetServerObjectByPath(path)
	if so == nil {
		return errors.New("server object not found")
	}
	return so.StopExport()
}

func (s *Service) IsExported(impl Implementer) bool {
	so := s.GetServerObject(impl)
	return so != nil
}

func (s *Service) getImplementerStatic(impl Implementer) *implementerStatic {
	ifcName := impl.GetInterfaceName()
	s.mu.RLock()
	implStatic := s.implStaticMap[ifcName]
	s.mu.RUnlock()
	return implStatic
}

func (s *Service) Emit(v Implementer, signalName string, values ...interface{}) error {
	so := s.GetServerObject(v)
	if so == nil {
		return errors.New("v is not exported")
	}
	implStatic := s.getImplementerStatic(v)

	var signal introspect.Signal
	for _, sig := range implStatic.introspectInterface.Signals {
		if sig.Name == signalName {
			signal = sig
			break
		}
	}

	if signal.Name == "" {
		return errors.New("not found signal")
	}
	if len(values) != len(signal.Args) {
		return errors.New("signal args length not equal")
	}
	for idx, arg := range signal.Args {
		valueType := dbus.SignatureOf(values[idx]).String()
		if valueType != arg.Type {
			return fmt.Errorf("signal arg[%d] type not match", idx)
		}
	}

	return s.conn.Emit(so.path,
		v.GetInterfaceName()+"."+signalName, values...)
}

func (s *Service) EmitPropertyChanged(v Implementer, propertyName string, value interface{}) error {
	so := s.GetServerObject(v)
	if so == nil {
		return errors.New("v is not exported")
	}

	impl := so.getImplementer(v.GetInterfaceName())

	implStatic := s.getImplementerStatic(v)

	err := implStatic.checkPropertyValue(propertyName, value)
	if err != nil {
		return err
	}

	return impl.emitPropChanged(s, so.path, propertyName, value)
}

func (s *Service) DelayEmitPropertyChanged(v Implementer) func() error {
	so := s.GetServerObject(v)
	if so == nil {
		return nil
	}

	impl := so.getImplementer(v.GetInterfaceName())
	if impl == nil {
		return nil
	}

	impl.delayEmitPropChanged()
	return func() error {
		return impl.stopDelayEmitPropChanged(s, so.path)
	}
}

func (s *Service) EmitPropertiesChanged(v Implementer, propValMap map[string]interface{},
	invalidatedProps ...string) error {
	so := s.GetServerObject(v)
	if so == nil {
		return errors.New("v is not exported")
	}

	implStatic := s.getImplementerStatic(v)

	const signalName = orgFreedesktopDBus + ".Properties.PropertiesChanged"
	var changedProps map[string]dbus.Variant
	if len(propValMap) > 0 {
		changedProps = make(map[string]dbus.Variant)
	}
	for propName, val := range propValMap {
		err := implStatic.checkPropertyValue(propName, val)
		if err != nil {
			return err
		}
		changedProps[propName] = dbus.MakeVariant(val)
	}
	for _, propName := range invalidatedProps {
		if _, ok := propValMap[propName]; ok {
			return errors.New("property appears in both propValMap and invalidateProps")
		}

		err := implStatic.checkProperty(propName)
		if err != nil {
			return err
		}
	}
	return s.conn.Emit(so.path, signalName, v.GetInterfaceName(), changedProps, invalidatedProps)
}

func (s *Service) Quit() {
	s.conn.Close()
	close(s.quit)
}

func (s *Service) Wait() {
	s.quit = make(chan struct{})
	if s.quitCheckInterval > 0 {
		go func() {
			ticker := time.NewTicker(s.quitCheckInterval)
			for {
				select {
				case <-s.quit:
					return
				case <-ticker.C:
					s.mu.RLock()
					hasCall := s.hasCall
					s.mu.RUnlock()
					logger.Println("Service.Wait tick hasCall:", hasCall)

					if !hasCall {
						if s.canQuit == nil || s.canQuit() {
							s.Quit()
							return
						}
					} else {
						s.mu.Lock()
						s.hasCall = false
						s.mu.Unlock()
					}
				}
			}
		}()
	}
	<-s.quit
}

func (s *Service) DelayAutoQuit() {
	s.mu.Lock()
	s.hasCall = true
	s.mu.Unlock()
}

func (s *Service) SetAutoQuitHandler(interval time.Duration, canQuit func() bool) {
	s.quitCheckInterval = interval
	s.canQuit = canQuit
}

func (s *Service) GetConnPID(name string) (pid uint32, err error) {
	err = s.conn.BusObject().Call(orgFreedesktopDBus+".GetConnectionUnixProcessID",
		0, name).Store(&pid)
	return
}

func (s *Service) GetConnUID(name string) (uid uint32, err error) {
	err = s.conn.BusObject().Call(orgFreedesktopDBus+".GetConnectionUnixUser",
		0, name).Store(&uid)
	return
}

func (s *Service) GetNameOwner(name string) (owner string, err error) {
	err = s.conn.BusObject().Call(orgFreedesktopDBus+".GetNameOwner",
		0, name).Store(&owner)
	return
}

func (s *Service) NameHasOwner(name string) (hasOwner bool, err error) {
	err = s.conn.BusObject().Call(orgFreedesktopDBus+".NameHasOwner",
		0, name).Store(&hasOwner)
	return
}

func (s *Service) DumpProperties(v Implementer) (string, error) {
	so := s.GetServerObject(v)
	if so == nil {
		return "", errors.New("not exported")
	}

	impl := so.getImplementer(v.GetInterfaceName())
	implStatic := impl.getStatic(s)

	var buf bytes.Buffer

	var propNames []string
	for name := range impl.props {
		propNames = append(propNames, name)
	}
	sort.Strings(propNames)

	for _, name := range propNames {
		p := impl.props[name]
		fmt.Fprintln(&buf, "property name:", name)
		fmt.Fprintf(&buf, "valueMu: %p\n", p.valueMu)

		propStatic := implStatic.props[name]
		fmt.Fprintln(&buf, "signature:", propStatic.signature)
		fmt.Fprintln(&buf, "access:", propStatic.access)
		fmt.Fprintln(&buf, "emit:", propStatic.emit)

		buf.WriteString("\n")
	}

	return buf.String(), nil
}