files.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. Copyright 2013 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. // Package activation implements primitives for systemd socket activation.
  14. package activation
  15. import (
  16. "os"
  17. "strconv"
  18. "syscall"
  19. )
  20. // based on: https://gist.github.com/alberts/4640792
  21. const (
  22. listenFdsStart = 3
  23. )
  24. func Files(unsetEnv bool) []*os.File {
  25. if unsetEnv {
  26. // there is no way to unset env in golang os package for now
  27. // https://code.google.com/p/go/issues/detail?id=6423
  28. defer os.Setenv("LISTEN_PID", "")
  29. defer os.Setenv("LISTEN_FDS", "")
  30. }
  31. pid, err := strconv.Atoi(os.Getenv("LISTEN_PID"))
  32. if err != nil || pid != os.Getpid() {
  33. return nil
  34. }
  35. nfds, err := strconv.Atoi(os.Getenv("LISTEN_FDS"))
  36. if err != nil || nfds == 0 {
  37. return nil
  38. }
  39. var files []*os.File
  40. for fd := listenFdsStart; fd < listenFdsStart+nfds; fd++ {
  41. syscall.CloseOnExec(fd)
  42. files = append(files, os.NewFile(uintptr(fd), "LISTEN_FD_"+strconv.Itoa(fd)))
  43. }
  44. return files
  45. }