func registerServiceViaDBusAvahi(name, serviceType string, serverPort uint16, txt []string) bool { conn, err := dbus.SystemBus() if err != nil { fmt.Fprintln(os.Stderr, "Failed to connect to D-BUS session bus:", err) return false } obj := conn.Object(AVAHI_DBUS_NAME, "/") var groupPath dbus.ObjectPath call := obj.Call("org.freedesktop.Avahi.Server.EntryGroupNew", 0) if call.Err != nil { fmt.Fprintln(os.Stderr, "Avahi not found on D-BUS") return false } call.Store(&groupPath) group := conn.Object(AVAHI_DBUS_NAME, groupPath) var txtBytes [][]byte for _, s := range txt { txtBytes = append(txtBytes, []byte(s)) } var flags = uint32(0) var domain = string("") var host = string("") group.Call(AVAHI_ENTRYGROUP_ADD_SERVICE, 0, AVAHI_IF_UNSPEC, PROTO_UNSPEC, flags, name, serviceType, domain, host, serverPort, txtBytes) group.Call(AVAHI_ENTRYGROUP_COMMIT, 0) return true }
// machinedRegister checks if nspawn should register the pod to machined func machinedRegister() bool { // machined has a D-Bus interface following versioning guidelines, see: // http://www.freedesktop.org/wiki/Software/systemd/machined/ // Therefore we can just check if the D-Bus method we need exists and we // don't need to check the signature. var found int conn, err := dbus.SystemBus() if err != nil { return false } node, err := introspect.Call(conn.Object("org.freedesktop.machine1", "/org/freedesktop/machine1")) if err != nil { return false } for _, iface := range node.Interfaces { if iface.Name != "org.freedesktop.machine1.Manager" { continue } // machined v215 supports methods "RegisterMachine" and "CreateMachine" called by nspawn v215. // machined v216+ (since commit 5aa4bb) additionally supports methods "CreateMachineWithNetwork" // and "RegisterMachineWithNetwork", called by nspawn v216+. for _, method := range iface.Methods { if method.Name == "CreateMachineWithNetwork" || method.Name == "RegisterMachineWithNetwork" { found++ } } break } return found == 2 }
func main() { conn, err := dbus.SystemBus() if err != nil { log.Fatalln(err) } reply, err := conn.RequestName("system.powermanager", dbus.NameFlagDoNotQueue) if err != nil { log.Fatalln(err) } if reply != dbus.RequestNameReplyPrimaryOwner { log.Fatalln("system.powermanager already registered") } log.Infoln(conn.Names()) pm := NewPowerManager(conn) err = conn.Export(&pm, "/powermanager", "system.powermanager") if err != nil { log.Fatalln("export powermanager:", err) } err = conn.Export(introspect.Introspectable(introRoot), "/", "org.freedesktop.DBus.Introspectable") if err != nil { log.Fatalln("export powermanager (introspectable-root):", err) } err = conn.Export(introspect.Introspectable(intro), "/powermanager", "org.freedesktop.DBus.Introspectable") if err != nil { log.Fatalln("export powermanager (introspectable):", err) } log.Fatalln(exec.Command("/home/steam/app_run.sh").Run()) }
func newDbusServer() (*dbusServer, error) { conn, err := dbus.SystemBus() if err != nil { return nil, err } reply, err := conn.RequestName(busName, dbus.NameFlagDoNotQueue) if err != nil { return nil, err } if reply != dbus.RequestNameReplyPrimaryOwner { return nil, errors.New("Bus name is already owned") } ds := &dbusServer{} if err := conn.Export(ds, objectPath, interfaceName); err != nil { return nil, err } ps := strings.Split(objectPath, "/") path := "/" for _, p := range ps { if len(path) > 1 { path += "/" } path += p if err := conn.Export(ds, dbus.ObjectPath(path), "org.freedesktop.DBus.Introspectable"); err != nil { return nil, err } } ds.conn = conn ds.prompter = newPrompter(conn) return ds, nil }
// StartWithEnv starts this job (an instance, really) with the specified env. func (j *job) StartWithEnv(env map[string]string) error { wait := true // TODO // connect to the system bus conn, err := dbus.SystemBus() if err != nil { return err } jobpath, err := j.dbusPath(conn) if err != nil { return err } // manipulate env map into env arr envarr := []string{} for k, v := range env { envarr = append(envarr, fmt.Sprintf("%s=%s", k, v)) } // start a job instance based on the env err = conn. Object(upstartServiceDBusPath, jobpath). Call("com.ubuntu.Upstart0_6.Job.Start", 0, envarr, wait). Store(&jobpath) if err != nil { return err } return nil }
func main() { bus, err := dbus.SystemBus() bus.RequestName("com.devicehive.alljoyn.test.basic", dbus.NameFlagDoNotQueue) if err != nil { log.Panic(err) } basicService := NewBasicService(bus) bus.Export(basicService, "/com/devicehive/alljoyn/test/basic", "org.alljoyn.About") bus.Export(basicService, "/com/devicehive/alljoyn/test/basic", "org.alljoyn.Bus.sample") bus.Export(basicService, "/com/devicehive/alljoyn/test/basic", "org.freedesktop.DBus.Introspectable") // Now try to register ourself in AllJoyn via dbus go func() { bridge := bus.Object("com.devicehive.alljoyn.bridge", dbus.ObjectPath("/com/devicehive/alljoyn/bridge")) res := bridge.Call("com.devicehive.alljoyn.bridge.AddService", 0, "/com/devicehive/alljoyn/test/basic", "com.devicehive.alljoyn.test.basic", "/sample", "org.alljoyn.Bus.sample", "") log.Printf("Result: %+v", res) res = bridge.Call("com.devicehive.alljoyn.bridge.StartAllJoyn", 0, "com.devicehive.alljoyn.test.basic") }() select {} }
// RegisterMachine with systemd on the host system func RegisterMachine(name string, id string, pid int, root_directory string) error { var ( av []byte err error ) if conn == nil { conn, err = dbus.SystemBus() if err != nil { return err } } av, err = hex.DecodeString(id[0:32]) if err != nil { return err } obj := conn.Object("org.freedesktop.machine1", "/org/freedesktop/machine1") service := os.Getenv("container") if service == "" { service = "runc" } /* return obj.Call("org.freedesktop.machine1.Manager.RegisterMachine", 0, name[0:32], av, service, "container", uint32(pid), root_directory).Err */ return obj.Call("org.freedesktop.machine1.Manager.RegisterMachine", 0, name[0:32], av, service, "container", uint32(pid), "/").Err return nil }
// execute function 'f' for each instance of this job. func (j *job) foreachInstance(f func(*dbus.Conn, dbus.ObjectPath) error) error { conn, err := dbus.SystemBus() if err != nil { return err } jobpath, err := j.dbusPath(conn) if err != nil { return err } // list the instances var instpaths []dbus.ObjectPath err = conn. Object(upstartServiceDBusPath, jobpath). Call("com.ubuntu.Upstart0_6.Job.GetAllInstances", 0). Store(&instpaths) if err != nil { return err } for _, inst := range instpaths { err = f(conn, inst) if err != nil { return err } } return nil }
func (m *unitMonitor) watch() error { conn, err := dbus.SystemBus() if err != nil { return err } m.path = m.getUnitPath() // subscribe the props changes signal props := fmt.Sprintf("type='signal',path='%s',interface='org.freedesktop.DBus.Properties'", m.path) call := conn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, props) if call != nil && call.Err != nil { return call.Err } // unsubscribe on return defer func() { conn.BusObject().Call("org.freedesktop.DBus.RemoveMatch", 0, props) }() signal := make(chan *dbus.Signal, 10) defer close(signal) conn.Signal(signal) log.Printf("watching for %s @%s\n", m.name, m.path) for { select { case ev := <-signal: switch ev.Name { case propertiesChanged: var iName string var changedProps map[string]dbus.Variant var invProps []string if ev.Path == m.path { if err := dbus.Store(ev.Body, &iName, &changedProps, &invProps); err != nil { log.Println(err.Error()) log.Println("aku dead") continue } if iName == "org.freedesktop.systemd1.Unit" { m.chanPub <- m.generateStatus() } } } case <-m.done: return nil } } return nil }
func NewdbusWrapper(path string, iface string) (*dbusWrapper, error) { d := new(dbusWrapper) conn, err := dbus.SystemBus() if err != nil { conn, err = dbus.SessionBus() if err != nil { log.Panic(err) } } d.handlers = make(map[string]signalHandler) d.conn = conn d.path = path d.iface = iface d.queue = &signalQueue{cond: &sync.Cond{L: &sync.Mutex{}}} heap.Init(d.queue) filter := fmt.Sprintf("type='signal',path='%[1]s',interface='%[2]s',sender='%[2]s'", path, iface) log.Printf("Filter: %s", filter) conn.Object("org.freedesktop.DBus", "/org/freedesktop/DBus").Call("org.freedesktop.DBus.AddMatch", 0, filter) go func() { ch := make(chan *dbus.Signal, 2*QueueCapacity) conn.Signal(ch) for signal := range ch { if !((strings.Index(signal.Name, iface) == 0) && (string(signal.Path) == path)) { continue } if val, ok := d.handlers[signal.Name]; ok { for d.queue.Len() > QueueCapacity-1 { item := heap.Remove(d.queue, d.queue.Len()-1) log.Printf("Removing %+v from queue", item) } heap.Push(d.queue, signalItem{handler: val, signal: signal, timestamp: uint64(time.Now().Unix())}) } else { log.Printf("Unhandled signal: %s", signal.Name) } } }() go func() { for { d.queue.cond.L.Lock() for d.queue.Len() == 0 { d.queue.cond.Wait() } d.queue.cond.L.Unlock() item := heap.Pop(d.queue).(signalItem) item.handler.handler(item.signal.Body...) } }() return d, nil }
func main() { bus, err := dbus.SystemBus() if err != nil { log.Fatal(err) } // run as a child if len(spawnUUID) != 0 && len(spawnDbusServiceId) != 0 && len(spawnDbusPath) != 0 { allJoynBridge := NewAllJoynBridge(bus) allJoynBridge.addService(spawnUUID, spawnDbusServiceId, spawnDbusService, spawnDbusPath, spawnAlljoynService) select {} // exit? return } res, err := bus.RequestName("com.devicehive.alljoyn.bridge", dbus.NameFlagDoNotQueue) if err != nil { log.Fatalf("Failed to request dbus name: %s", err) } if res != dbus.RequestNameReplyPrimaryOwner { log.Fatalf("Failed to request dbus name: %+v", res) } allJoynBridge := NewAllJoynBridge(bus) bus.Export(allJoynBridge, "/com/devicehive/alljoyn/bridge", "com.devicehive.alljoyn.bridge") n := &introspect.Node{ Interfaces: []introspect.Interface{ { Name: "com.devicehive.alljoyn.bridge", Methods: introspect.Methods(allJoynBridge), Signals: []introspect.Signal{}, }, }, } root := &introspect.Node{ Children: []introspect.Node{ { Name: "com/devicehive/alljoyn/bridge", }, }, } bus.Export(introspect.NewIntrospectable(n), "/com/devicehive/alljoyn/bridge", "org.freedesktop.DBus.Introspectable") bus.Export(introspect.NewIntrospectable(root), "/", "org.freedesktop.DBus.Introspectable") // workaroud for dbus issue #14 log.Printf("Bridge is Running.") select {} }
func daemon() { conn, err := dbus.SystemBus() if err != nil { log.Fatal(err) } // Subscribe to device state changes so that we get notified when a device // gets activated. We can then trigger a connectivity check. if err := conn.BusObject().Call( "org.freedesktop.DBus.AddMatch", 0, "type='signal',"+ "interface='org.freedesktop.NetworkManager.Device',"+ "member='StateChanged'").Err; err != nil { log.Fatal(err) } connectivityChanged := make(chan bool) // If filterStateChanges does not read signals fast enough, i.e. the signal // channel write blocks, godbus will panic. The intention of the channel // buffer (which was arbitrarily sized) is to make that situation as // unlikely as possible. signals := make(chan *dbus.Signal, 100) conn.Signal(signals) go filterStateChanges(signals, connectivityChanged) for { select { case <-connectivityChanged: log.Printf("Connectivity changed. Waiting for the situation to settle (1m without changes).\n") Settled: for { select { case <-connectivityChanged: log.Printf("Connectivity changed again, waiting another 1m.\n") case <-time.After(1 * time.Minute): break Settled } } log.Printf("could check for an update now\n") if err := pull(); err != nil { log.Fatal(err) } case <-time.After(1 * time.Hour): log.Printf("check opportunistically for an update now\n") if err := pull(); err != nil { log.Fatal(err) } } } }
// TerminateMachine registered with systemd on the host system func TerminateMachine(name string) error { var err error if conn == nil { conn, err = dbus.SystemBus() if err != nil { return err } } obj := conn.Object("org.freedesktop.machine1", "/org/freedesktop/machine1") return obj.Call("org.freedesktop.machine1.Manager.TerminateMachine", 0, name).Err }
// SystemBus is part of Interface func (db *dbusImpl) SystemBus() (Connection, error) { if db.systemBus == nil { bus, err := godbus.SystemBus() if err != nil { return nil, err } db.systemBus = &connImpl{bus} } return db.systemBus, nil }
func ConnectToDBus(bus string) (*DBusClient, error) { c := new(DBusClient) var err error switch bus { case "session": c.bus, err = dbus.SessionBus() case "system": c.bus, err = dbus.SystemBus() default: c.bus, err = dbus.Dial(bus) } if err != nil { return nil, err } if !c.bus.SupportsUnixFDs() { return nil, errors.New("DBus connection does not support file descriptors") } c.path = dbus.ObjectPath("/com/firelizzard/teasvc/Client") err = c.bus.Export(c, c.path, "com.firelizzard.teasvc.Client") if err != nil { return nil, err } c.sigchans = make(map[string](chan *dbus.Signal)) chsig := make(chan *dbus.Signal, 10) go func() { for { sig := <-chsig ch, ok := c.sigchans[sig.Name] if !ok { log.Print("Unhandled signal: " + sig.Name) } select { case ch <- sig: // sent singal, done default: log.Print("Unhandled signal (full channel): " + sig.Name) } } }() c.bus.Signal(chsig) c.bus.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, "type='signal',interface='com.firelizzard.teasvc',member='Pong'") return c, nil }
func Open() (*Connection, error) { bus, err := dbus.SystemBus() if err != nil { return nil, err } conn := Connection{bus: bus} err = conn.Update() if err != nil { conn.Close() return nil, err } return &conn, nil }
func New() *Interface { bus, err := dbus.SystemBus() if err != nil { return &Interface{} } fw := &Interface{ obj: bus.Object(firewalldName, dbus.ObjectPath(firewalldPath)), } go fw.dbusSignalHandler(bus) return fw }
func (s *Service) Enable() (err error) { s.System, err = dbus.SystemBus() if err != nil { return err } s.Session, err = dbus.SessionBus() if err != nil { return err } s.Subscribe("notify", "", s.handleNotify) s.Subscribe("poweroff", "", s.handlePowerOff) return s.setupSignals() }
func NewDbus(path, iface string) (*Dbus, error) { w := new(Dbus) conn, err := dbus.SystemBus() if err != nil { conn, err = dbus.SessionBus() if err != nil { return nil, err } } w.path = path w.iface = iface w.conn = conn return w, nil }
func main() { var err error SystemBus, err = dbus.SystemBus() if err != nil { log.Errorln("connect to system bus:", err) } else { go monitor(SystemBus, "system") } SessionBus, err = dbus.SessionBus() if err != nil { log.Errorln("connect to session bus:", err) } else { go monitor(SessionBus, "session") } log.Fatalln(ListenAndServe(":3000")) }
func main() { say.SetLevelWithConfName("info") configFile, config, err := conf.FromArgs() switch { case err != nil: say.Fatalf("Cannot read configuration in `%s` with error: %s", configFile, err.Error()) case configFile == "": say.Infof("You should specify configuration file. Starting with test configuration: %+v", config) default: say.Infof("Starting DeviceHive gateway with configuration in '%s': %+v", configFile, config) } say.SetLevelWithConfName(config.LoggingLevel) bus, err := dbus.SystemBus() if err != nil { say.Infof("Cannot get system bus with error: %s", err.Error()) say.Infof("Trying to use session bus for testing purposes...") if bus, err = dbus.SessionBus(); err != nil { say.Fatalf("Cannot get session bus with error: %s\n", err.Error()) return } } reply, err := bus.RequestName(DBusConnName, dbus.NameFlagDoNotQueue) switch { case err != nil: say.Fatalf("Cannot request name '%s' with error: %s\n", DBusConnName, err.Error()) case reply != dbus.RequestNameReplyPrimaryOwner: say.Fatalf("The name '%s' already taken.", DBusConnName) } if config.DeviceNotificationReceive == conf.DeviceNotificationReceiveByWS { say.Infof("Starting as websocket...") wsImplementation(bus, config) return } if config.DeviceNotificationReceive == conf.DeviceNotificationReceiveByREST { say.Infof("Starting as rest...") restImplementation(bus, config) return } }
// Detect returns true if the system we're running on has an upstart daemon listening on // its known address and we're able to communicate with it. func Detect() bool { versionPropPath := "com.ubuntu.Upstart0_6.version" // connect to the system bus conn, err := dbus.SystemBus() if err != nil { return false } _, err = conn. Object(upstartServiceDBusPath, upstartManagerObject). GetProperty(versionPropPath) if err != nil { return false } return true }
func waitForMachinedRegistration(uuid string) error { conn, err := dbus.SystemBus() if err != nil { return err } machined := conn.Object("org.freedesktop.machine1", "/org/freedesktop/machine1") machineName := "rkt-" + uuid var o dbus.ObjectPath for i := 0; i < 10; i++ { if err := machined.Call("org.freedesktop.machine1.Manager.GetMachine", 0, machineName).Store(&o); err == nil { return nil } time.Sleep(time.Millisecond * 50) } return errors.New("pod not found") }
func main() { configFile, config, err := conf.FromArgs() switch { case err != nil: log.Fatalf("Failed to read %q configuration (%s)", configFile, err) case configFile == "": log.Warnf("No configuration file provided!") log.Infof("Test configuration is used: %+v", config) default: log.Infof("Starting DeviceHive with %q configuration: %+v", configFile, config) } log.SetLevelByName(config.LoggingLevel) bus, err := dbus.SystemBus() if err != nil { log.Warnf("Cannot get system bus (error: %s)", err) log.Infof("Trying to use session bus for testing purposes...") if bus, err = dbus.SessionBus(); err != nil { log.Fatalf("Cannot get session bus (error: %s)", err) return } } reply, err := bus.RequestName(DBusConnName, dbus.NameFlagDoNotQueue) switch { case err != nil: log.Fatalf("Cannot request name %q (error: %s)", DBusConnName, err) case reply != dbus.RequestNameReplyPrimaryOwner: log.Fatalf("The name %q already taken", DBusConnName) } s, err := devicehive.NewService(config.URL, config.AccessKey) if err != nil { log.Fatalf("Failed to create DeviceHive service (error: %s)", err) } log.Infof("Starting %v", s) mainLoop(bus, s, config) }
func GetVisibleNetworks() ([]string, error) { conn, err := dbus.SystemBus() if err != nil { panic(err) } obj := conn.Object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager") networkDevices := []dbus.ObjectPath{} if err := obj.Call("org.freedesktop.NetworkManager.GetDevices", 0).Store(&networkDevices); err != nil { panic(err) } ret := []string{} for _, el := range networkDevices { obj := conn.Object("org.freedesktop.NetworkManager", el) accessPoints := []dbus.ObjectPath{} if err := obj.Call( "org.freedesktop.NetworkManager.Device.Wireless.GetAccessPoints", 0, ).Store(&accessPoints); err != nil { continue } for _, accessPoint := range accessPoints { obj := conn.Object("org.freedesktop.NetworkManager", accessPoint) ssid, err := obj.GetProperty( "org.freedesktop.NetworkManager.AccessPoint.Ssid", ) if err != nil { panic(err) } ret = append(ret, string(ssid.Value().([]uint8))) } } return ret, nil }
func (m *unitMonitor) getProp(name string) dbus.Variant { var ret dbus.Variant c, err := dbus.SystemBus() if err != nil { log.Println(err) return ret } err = c.Object("org.freedesktop.systemd1", m.path).Call( propGet, 0, "org.freedesktop.systemd1.Unit", name, ).Store(&ret) if err != nil { log.Println(err) } return ret }
func NewdbusWrapper(path string, iface string) (*dbusWrapper, error) { d := new(dbusWrapper) conn, err := dbus.SystemBus() if err != nil { log.Panic(err) } d.handlers = make(map[string]signalHandlerFunc) d.conn = conn d.path = path d.iface = iface d.readingsBuffer = make(map[string]*[]float64) d.scanMap = make(map[string]bool) filter := fmt.Sprintf("type='signal',path='%[1]s',interface='%[2]s',sender='%[2]s'", path, iface) log.Printf("Filter: %s", filter) conn.Object("org.freedesktop.DBus", "/org/freedesktop/DBus").Call("org.freedesktop.DBus.AddMatch", 0, filter) go func() { ch := make(chan *dbus.Signal, 1) conn.Signal(ch) for signal := range ch { if !((strings.Index(signal.Name, iface) == 0) && (string(signal.Path) == path)) { continue } if handler, ok := d.handlers[signal.Name]; ok { go handler(signal.Body...) } else { log.Printf("Unhandled signal: %s", signal.Name) } } }() return d, nil }
func (m *unitMonitor) getUnitPath() dbus.ObjectPath { var ret dbus.ObjectPath c, err := dbus.SystemBus() if err != nil { return ret } obj := c.Object("org.freedesktop.systemd1", "/org/freedesktop/systemd1") call := obj.Call("org.freedesktop.systemd1.Manager.GetUnit", 0, m.name) if call != nil && call.Err != nil { log.Println(err) return ret } if err := call.Store(&ret); err != nil { log.Println(err) return ret } return ret }
func ExportToDBus(proc *Process, bus string) (*DBusServer, error) { s := new(DBusServer) s.proc = proc var err error switch bus { case "session": s.bus, err = dbus.SessionBus() case "system": s.bus, err = dbus.SystemBus() default: s.bus, err = dbus.Dial(bus) } if err != nil { return nil, err } if !s.bus.SupportsUnixFDs() { return nil, errors.New("DBus connection does not support file descriptors") } s.path = dbus.ObjectPath("/com/firelizzard/teasvc/Server") go s.handleSignals() err = s.bus.Export(s, s.path, "com.firelizzard.teasvc.Server") if err != nil { return nil, err } c := s.bus.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, "type='signal',interface='com.firelizzard.teasvc',member='Ping'") if c.Err != nil { return nil, c.Err } return s, nil }
// Innitialize D-Bus connection. func (c *Conn) initConnection() error { var err error c.sysconn, err = dbus.SystemBus() if err != nil { return err } // This never fails, even if the service is not running atm. c.sysobj = c.sysconn.Object(dbusInterface, dbus.ObjectPath(dbusPath)) rule := fmt.Sprintf("type='signal',path='%s',interface='%s',sender='%s',member='Reloaded'", dbusPath, dbusInterface, dbusInterface) c.sysconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, rule) rule = fmt.Sprintf("type='signal',interface='org.freedesktop.DBus',member='NameOwnerChanged',path='/org/freedesktop/DBus',sender='org.freedesktop.DBus',arg0='%s'", dbusInterface) c.sysconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, rule) c.signal = make(chan *dbus.Signal, 10) c.sysconn.Signal(c.signal) return nil }