methods.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package dbus
  15. import (
  16. "errors"
  17. "path"
  18. "strconv"
  19. "github.com/godbus/dbus"
  20. )
  21. func (c *Conn) jobComplete(signal *dbus.Signal) {
  22. var id uint32
  23. var job dbus.ObjectPath
  24. var unit string
  25. var result string
  26. dbus.Store(signal.Body, &id, &job, &unit, &result)
  27. c.jobListener.Lock()
  28. out, ok := c.jobListener.jobs[job]
  29. if ok {
  30. out <- result
  31. delete(c.jobListener.jobs, job)
  32. }
  33. c.jobListener.Unlock()
  34. }
  35. func (c *Conn) startJob(ch chan<- string, job string, args ...interface{}) (int, error) {
  36. if ch != nil {
  37. c.jobListener.Lock()
  38. defer c.jobListener.Unlock()
  39. }
  40. var p dbus.ObjectPath
  41. err := c.sysobj.Call(job, 0, args...).Store(&p)
  42. if err != nil {
  43. return 0, err
  44. }
  45. if ch != nil {
  46. c.jobListener.jobs[p] = ch
  47. }
  48. // ignore error since 0 is fine if conversion fails
  49. jobID, _ := strconv.Atoi(path.Base(string(p)))
  50. return jobID, nil
  51. }
  52. // StartUnit enqueues a start job and depending jobs, if any (unless otherwise
  53. // specified by the mode string).
  54. //
  55. // Takes the unit to activate, plus a mode string. The mode needs to be one of
  56. // replace, fail, isolate, ignore-dependencies, ignore-requirements. If
  57. // "replace" the call will start the unit and its dependencies, possibly
  58. // replacing already queued jobs that conflict with this. If "fail" the call
  59. // will start the unit and its dependencies, but will fail if this would change
  60. // an already queued job. If "isolate" the call will start the unit in question
  61. // and terminate all units that aren't dependencies of it. If
  62. // "ignore-dependencies" it will start a unit but ignore all its dependencies.
  63. // If "ignore-requirements" it will start a unit but only ignore the
  64. // requirement dependencies. It is not recommended to make use of the latter
  65. // two options.
  66. //
  67. // If the provided channel is non-nil, a result string will be sent to it upon
  68. // job completion: one of done, canceled, timeout, failed, dependency, skipped.
  69. // done indicates successful execution of a job. canceled indicates that a job
  70. // has been canceled before it finished execution. timeout indicates that the
  71. // job timeout was reached. failed indicates that the job failed. dependency
  72. // indicates that a job this job has been depending on failed and the job hence
  73. // has been removed too. skipped indicates that a job was skipped because it
  74. // didn't apply to the units current state.
  75. //
  76. // If no error occurs, the ID of the underlying systemd job will be returned. There
  77. // does exist the possibility for no error to be returned, but for the returned job
  78. // ID to be 0. In this case, the actual underlying ID is not 0 and this datapoint
  79. // should not be considered authoritative.
  80. //
  81. // If an error does occur, it will be returned to the user alongside a job ID of 0.
  82. func (c *Conn) StartUnit(name string, mode string, ch chan<- string) (int, error) {
  83. return c.startJob(ch, "org.freedesktop.systemd1.Manager.StartUnit", name, mode)
  84. }
  85. // StopUnit is similar to StartUnit but stops the specified unit rather
  86. // than starting it.
  87. func (c *Conn) StopUnit(name string, mode string, ch chan<- string) (int, error) {
  88. return c.startJob(ch, "org.freedesktop.systemd1.Manager.StopUnit", name, mode)
  89. }
  90. // ReloadUnit reloads a unit. Reloading is done only if the unit is already running and fails otherwise.
  91. func (c *Conn) ReloadUnit(name string, mode string, ch chan<- string) (int, error) {
  92. return c.startJob(ch, "org.freedesktop.systemd1.Manager.ReloadUnit", name, mode)
  93. }
  94. // RestartUnit restarts a service. If a service is restarted that isn't
  95. // running it will be started.
  96. func (c *Conn) RestartUnit(name string, mode string, ch chan<- string) (int, error) {
  97. return c.startJob(ch, "org.freedesktop.systemd1.Manager.RestartUnit", name, mode)
  98. }
  99. // TryRestartUnit is like RestartUnit, except that a service that isn't running
  100. // is not affected by the restart.
  101. func (c *Conn) TryRestartUnit(name string, mode string, ch chan<- string) (int, error) {
  102. return c.startJob(ch, "org.freedesktop.systemd1.Manager.TryRestartUnit", name, mode)
  103. }
  104. // ReloadOrRestart attempts a reload if the unit supports it and use a restart
  105. // otherwise.
  106. func (c *Conn) ReloadOrRestartUnit(name string, mode string, ch chan<- string) (int, error) {
  107. return c.startJob(ch, "org.freedesktop.systemd1.Manager.ReloadOrRestartUnit", name, mode)
  108. }
  109. // ReloadOrTryRestart attempts a reload if the unit supports it and use a "Try"
  110. // flavored restart otherwise.
  111. func (c *Conn) ReloadOrTryRestartUnit(name string, mode string, ch chan<- string) (int, error) {
  112. return c.startJob(ch, "org.freedesktop.systemd1.Manager.ReloadOrTryRestartUnit", name, mode)
  113. }
  114. // StartTransientUnit() may be used to create and start a transient unit, which
  115. // will be released as soon as it is not running or referenced anymore or the
  116. // system is rebooted. name is the unit name including suffix, and must be
  117. // unique. mode is the same as in StartUnit(), properties contains properties
  118. // of the unit.
  119. func (c *Conn) StartTransientUnit(name string, mode string, properties []Property, ch chan<- string) (int, error) {
  120. return c.startJob(ch, "org.freedesktop.systemd1.Manager.StartTransientUnit", name, mode, properties, make([]PropertyCollection, 0))
  121. }
  122. // KillUnit takes the unit name and a UNIX signal number to send. All of the unit's
  123. // processes are killed.
  124. func (c *Conn) KillUnit(name string, signal int32) {
  125. c.sysobj.Call("org.freedesktop.systemd1.Manager.KillUnit", 0, name, "all", signal).Store()
  126. }
  127. // ResetFailedUnit resets the "failed" state of a specific unit.
  128. func (c *Conn) ResetFailedUnit(name string) error {
  129. return c.sysobj.Call("org.freedesktop.systemd1.Manager.ResetFailedUnit", 0, name).Store()
  130. }
  131. // getProperties takes the unit name and returns all of its dbus object properties, for the given dbus interface
  132. func (c *Conn) getProperties(unit string, dbusInterface string) (map[string]interface{}, error) {
  133. var err error
  134. var props map[string]dbus.Variant
  135. path := unitPath(unit)
  136. if !path.IsValid() {
  137. return nil, errors.New("invalid unit name: " + unit)
  138. }
  139. obj := c.sysconn.Object("org.freedesktop.systemd1", path)
  140. err = obj.Call("org.freedesktop.DBus.Properties.GetAll", 0, dbusInterface).Store(&props)
  141. if err != nil {
  142. return nil, err
  143. }
  144. out := make(map[string]interface{}, len(props))
  145. for k, v := range props {
  146. out[k] = v.Value()
  147. }
  148. return out, nil
  149. }
  150. // GetUnitProperties takes the unit name and returns all of its dbus object properties.
  151. func (c *Conn) GetUnitProperties(unit string) (map[string]interface{}, error) {
  152. return c.getProperties(unit, "org.freedesktop.systemd1.Unit")
  153. }
  154. func (c *Conn) getProperty(unit string, dbusInterface string, propertyName string) (*Property, error) {
  155. var err error
  156. var prop dbus.Variant
  157. path := unitPath(unit)
  158. if !path.IsValid() {
  159. return nil, errors.New("invalid unit name: " + unit)
  160. }
  161. obj := c.sysconn.Object("org.freedesktop.systemd1", path)
  162. err = obj.Call("org.freedesktop.DBus.Properties.Get", 0, dbusInterface, propertyName).Store(&prop)
  163. if err != nil {
  164. return nil, err
  165. }
  166. return &Property{Name: propertyName, Value: prop}, nil
  167. }
  168. func (c *Conn) GetUnitProperty(unit string, propertyName string) (*Property, error) {
  169. return c.getProperty(unit, "org.freedesktop.systemd1.Unit", propertyName)
  170. }
  171. // GetUnitTypeProperties returns the extra properties for a unit, specific to the unit type.
  172. // Valid values for unitType: Service, Socket, Target, Device, Mount, Automount, Snapshot, Timer, Swap, Path, Slice, Scope
  173. // return "dbus.Error: Unknown interface" if the unitType is not the correct type of the unit
  174. func (c *Conn) GetUnitTypeProperties(unit string, unitType string) (map[string]interface{}, error) {
  175. return c.getProperties(unit, "org.freedesktop.systemd1."+unitType)
  176. }
  177. // SetUnitProperties() may be used to modify certain unit properties at runtime.
  178. // Not all properties may be changed at runtime, but many resource management
  179. // settings (primarily those in systemd.cgroup(5)) may. The changes are applied
  180. // instantly, and stored on disk for future boots, unless runtime is true, in which
  181. // case the settings only apply until the next reboot. name is the name of the unit
  182. // to modify. properties are the settings to set, encoded as an array of property
  183. // name and value pairs.
  184. func (c *Conn) SetUnitProperties(name string, runtime bool, properties ...Property) error {
  185. return c.sysobj.Call("org.freedesktop.systemd1.Manager.SetUnitProperties", 0, name, runtime, properties).Store()
  186. }
  187. func (c *Conn) GetUnitTypeProperty(unit string, unitType string, propertyName string) (*Property, error) {
  188. return c.getProperty(unit, "org.freedesktop.systemd1."+unitType, propertyName)
  189. }
  190. // ListUnits returns an array with all currently loaded units. Note that
  191. // units may be known by multiple names at the same time, and hence there might
  192. // be more unit names loaded than actual units behind them.
  193. func (c *Conn) ListUnits() ([]UnitStatus, error) {
  194. result := make([][]interface{}, 0)
  195. err := c.sysobj.Call("org.freedesktop.systemd1.Manager.ListUnits", 0).Store(&result)
  196. if err != nil {
  197. return nil, err
  198. }
  199. resultInterface := make([]interface{}, len(result))
  200. for i := range result {
  201. resultInterface[i] = result[i]
  202. }
  203. status := make([]UnitStatus, len(result))
  204. statusInterface := make([]interface{}, len(status))
  205. for i := range status {
  206. statusInterface[i] = &status[i]
  207. }
  208. err = dbus.Store(resultInterface, statusInterface...)
  209. if err != nil {
  210. return nil, err
  211. }
  212. return status, nil
  213. }
  214. type UnitStatus struct {
  215. Name string // The primary unit name as string
  216. Description string // The human readable description string
  217. LoadState string // The load state (i.e. whether the unit file has been loaded successfully)
  218. ActiveState string // The active state (i.e. whether the unit is currently started or not)
  219. SubState string // The sub state (a more fine-grained version of the active state that is specific to the unit type, which the active state is not)
  220. Followed string // A unit that is being followed in its state by this unit, if there is any, otherwise the empty string.
  221. Path dbus.ObjectPath // The unit object path
  222. JobId uint32 // If there is a job queued for the job unit the numeric job id, 0 otherwise
  223. JobType string // The job type as string
  224. JobPath dbus.ObjectPath // The job object path
  225. }
  226. type LinkUnitFileChange EnableUnitFileChange
  227. // LinkUnitFiles() links unit files (that are located outside of the
  228. // usual unit search paths) into the unit search path.
  229. //
  230. // It takes a list of absolute paths to unit files to link and two
  231. // booleans. The first boolean controls whether the unit shall be
  232. // enabled for runtime only (true, /run), or persistently (false,
  233. // /etc).
  234. // The second controls whether symlinks pointing to other units shall
  235. // be replaced if necessary.
  236. //
  237. // This call returns a list of the changes made. The list consists of
  238. // structures with three strings: the type of the change (one of symlink
  239. // or unlink), the file name of the symlink and the destination of the
  240. // symlink.
  241. func (c *Conn) LinkUnitFiles(files []string, runtime bool, force bool) ([]LinkUnitFileChange, error) {
  242. result := make([][]interface{}, 0)
  243. err := c.sysobj.Call("org.freedesktop.systemd1.Manager.LinkUnitFiles", 0, files, runtime, force).Store(&result)
  244. if err != nil {
  245. return nil, err
  246. }
  247. resultInterface := make([]interface{}, len(result))
  248. for i := range result {
  249. resultInterface[i] = result[i]
  250. }
  251. changes := make([]LinkUnitFileChange, len(result))
  252. changesInterface := make([]interface{}, len(changes))
  253. for i := range changes {
  254. changesInterface[i] = &changes[i]
  255. }
  256. err = dbus.Store(resultInterface, changesInterface...)
  257. if err != nil {
  258. return nil, err
  259. }
  260. return changes, nil
  261. }
  262. // EnableUnitFiles() may be used to enable one or more units in the system (by
  263. // creating symlinks to them in /etc or /run).
  264. //
  265. // It takes a list of unit files to enable (either just file names or full
  266. // absolute paths if the unit files are residing outside the usual unit
  267. // search paths), and two booleans: the first controls whether the unit shall
  268. // be enabled for runtime only (true, /run), or persistently (false, /etc).
  269. // The second one controls whether symlinks pointing to other units shall
  270. // be replaced if necessary.
  271. //
  272. // This call returns one boolean and an array with the changes made. The
  273. // boolean signals whether the unit files contained any enablement
  274. // information (i.e. an [Install]) section. The changes list consists of
  275. // structures with three strings: the type of the change (one of symlink
  276. // or unlink), the file name of the symlink and the destination of the
  277. // symlink.
  278. func (c *Conn) EnableUnitFiles(files []string, runtime bool, force bool) (bool, []EnableUnitFileChange, error) {
  279. var carries_install_info bool
  280. result := make([][]interface{}, 0)
  281. err := c.sysobj.Call("org.freedesktop.systemd1.Manager.EnableUnitFiles", 0, files, runtime, force).Store(&carries_install_info, &result)
  282. if err != nil {
  283. return false, nil, err
  284. }
  285. resultInterface := make([]interface{}, len(result))
  286. for i := range result {
  287. resultInterface[i] = result[i]
  288. }
  289. changes := make([]EnableUnitFileChange, len(result))
  290. changesInterface := make([]interface{}, len(changes))
  291. for i := range changes {
  292. changesInterface[i] = &changes[i]
  293. }
  294. err = dbus.Store(resultInterface, changesInterface...)
  295. if err != nil {
  296. return false, nil, err
  297. }
  298. return carries_install_info, changes, nil
  299. }
  300. type EnableUnitFileChange struct {
  301. Type string // Type of the change (one of symlink or unlink)
  302. Filename string // File name of the symlink
  303. Destination string // Destination of the symlink
  304. }
  305. // DisableUnitFiles() may be used to disable one or more units in the system (by
  306. // removing symlinks to them from /etc or /run).
  307. //
  308. // It takes a list of unit files to disable (either just file names or full
  309. // absolute paths if the unit files are residing outside the usual unit
  310. // search paths), and one boolean: whether the unit was enabled for runtime
  311. // only (true, /run), or persistently (false, /etc).
  312. //
  313. // This call returns an array with the changes made. The changes list
  314. // consists of structures with three strings: the type of the change (one of
  315. // symlink or unlink), the file name of the symlink and the destination of the
  316. // symlink.
  317. func (c *Conn) DisableUnitFiles(files []string, runtime bool) ([]DisableUnitFileChange, error) {
  318. result := make([][]interface{}, 0)
  319. err := c.sysobj.Call("org.freedesktop.systemd1.Manager.DisableUnitFiles", 0, files, runtime).Store(&result)
  320. if err != nil {
  321. return nil, err
  322. }
  323. resultInterface := make([]interface{}, len(result))
  324. for i := range result {
  325. resultInterface[i] = result[i]
  326. }
  327. changes := make([]DisableUnitFileChange, len(result))
  328. changesInterface := make([]interface{}, len(changes))
  329. for i := range changes {
  330. changesInterface[i] = &changes[i]
  331. }
  332. err = dbus.Store(resultInterface, changesInterface...)
  333. if err != nil {
  334. return nil, err
  335. }
  336. return changes, nil
  337. }
  338. type DisableUnitFileChange struct {
  339. Type string // Type of the change (one of symlink or unlink)
  340. Filename string // File name of the symlink
  341. Destination string // Destination of the symlink
  342. }
  343. // Reload instructs systemd to scan for and reload unit files. This is
  344. // equivalent to a 'systemctl daemon-reload'.
  345. func (c *Conn) Reload() error {
  346. return c.sysobj.Call("org.freedesktop.systemd1.Manager.Reload", 0).Store()
  347. }
  348. func unitPath(name string) dbus.ObjectPath {
  349. return dbus.ObjectPath("/org/freedesktop/systemd1/unit/" + PathBusEscape(name))
  350. }