sdnotify.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright 2014 Docker, 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. //
  15. // Code forked from Docker project
  16. package daemon
  17. import (
  18. "net"
  19. "os"
  20. )
  21. // SdNotify sends a message to the init daemon. It is common to ignore the error.
  22. // If `unsetEnvironment` is true, the environment variable `NOTIFY_SOCKET`
  23. // will be unconditionally unset.
  24. //
  25. // It returns one of the following:
  26. // (false, nil) - notification not supported (i.e. NOTIFY_SOCKET is unset)
  27. // (false, err) - notification supported, but failure happened (e.g. error connecting to NOTIFY_SOCKET or while sending data)
  28. // (true, nil) - notification supported, data has been sent
  29. func SdNotify(unsetEnvironment bool, state string) (sent bool, err error) {
  30. socketAddr := &net.UnixAddr{
  31. Name: os.Getenv("NOTIFY_SOCKET"),
  32. Net: "unixgram",
  33. }
  34. // NOTIFY_SOCKET not set
  35. if socketAddr.Name == "" {
  36. return false, nil
  37. }
  38. if unsetEnvironment {
  39. err = os.Unsetenv("NOTIFY_SOCKET")
  40. }
  41. if err != nil {
  42. return false, err
  43. }
  44. conn, err := net.DialUnix(socketAddr.Net, nil, socketAddr)
  45. // Error connecting to NOTIFY_SOCKET
  46. if err != nil {
  47. return false, err
  48. }
  49. defer conn.Close()
  50. _, err = conn.Write([]byte(state))
  51. // Error sending the message
  52. if err != nil {
  53. return false, err
  54. }
  55. return true, nil
  56. }