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