files.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 activation implements primitives for systemd socket activation.
  15. package activation
  16. import (
  17. "os"
  18. "strconv"
  19. "syscall"
  20. )
  21. // based on: https://gist.github.com/alberts/4640792
  22. const (
  23. listenFdsStart = 3
  24. )
  25. func Files(unsetEnv bool) []*os.File {
  26. if unsetEnv {
  27. defer os.Unsetenv("LISTEN_PID")
  28. defer os.Unsetenv("LISTEN_FDS")
  29. }
  30. pid, err := strconv.Atoi(os.Getenv("LISTEN_PID"))
  31. if err != nil || pid != os.Getpid() {
  32. return nil
  33. }
  34. nfds, err := strconv.Atoi(os.Getenv("LISTEN_FDS"))
  35. if err != nil || nfds == 0 {
  36. return nil
  37. }
  38. files := make([]*os.File, 0, nfds)
  39. for fd := listenFdsStart; fd < listenFdsStart+nfds; fd++ {
  40. syscall.CloseOnExec(fd)
  41. files = append(files, os.NewFile(uintptr(fd), "LISTEN_FD_"+strconv.Itoa(fd)))
  42. }
  43. return files
  44. }