dbus.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. Copyright 2015 CoreOS Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // Integration with the systemd machined API. See http://www.freedesktop.org/wiki/Software/systemd/machined/
  14. package machine1
  15. import (
  16. "os"
  17. "strconv"
  18. "github.com/godbus/dbus"
  19. )
  20. const (
  21. dbusInterface = "org.freedesktop.machine1.Manager"
  22. dbusPath = "/org/freedesktop/machine1"
  23. )
  24. // Conn is a connection to systemds dbus endpoint.
  25. type Conn struct {
  26. conn *dbus.Conn
  27. object dbus.BusObject
  28. }
  29. // New() establishes a connection to the system bus and authenticates.
  30. func New() (*Conn, error) {
  31. c := new(Conn)
  32. if err := c.initConnection(); err != nil {
  33. return nil, err
  34. }
  35. return c, nil
  36. }
  37. func (c *Conn) initConnection() error {
  38. var err error
  39. c.conn, err = dbus.SystemBusPrivate()
  40. if err != nil {
  41. return err
  42. }
  43. // Only use EXTERNAL method, and hardcode the uid (not username)
  44. // to avoid a username lookup (which requires a dynamically linked
  45. // libc)
  46. methods := []dbus.Auth{dbus.AuthExternal(strconv.Itoa(os.Getuid()))}
  47. err = c.conn.Auth(methods)
  48. if err != nil {
  49. c.conn.Close()
  50. return err
  51. }
  52. err = c.conn.Hello()
  53. if err != nil {
  54. c.conn.Close()
  55. return err
  56. }
  57. c.object = c.conn.Object("org.freedesktop.machine1", dbus.ObjectPath(dbusPath))
  58. return nil
  59. }
  60. // RegisterMachine registers the container with the systemd-machined
  61. func (c *Conn) RegisterMachine(name string, id []byte, service string, class string, pid int, root_directory string) error {
  62. return c.object.Call(dbusInterface+".RegisterMachine", 0, name, id, service, class, uint32(pid), root_directory).Err
  63. }