Tizen_4.0 base
[platform/upstream/docker-engine.git] / vendor / github.com / coreos / go-systemd / daemon / watchdog.go
1 // Copyright 2016 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
15 package daemon
16
17 import (
18         "fmt"
19         "os"
20         "strconv"
21         "time"
22 )
23
24 // SdWatchdogEnabled return watchdog information for a service.
25 // Process should send daemon.SdNotify("WATCHDOG=1") every time / 2.
26 // If `unsetEnvironment` is true, the environment variables `WATCHDOG_USEC`
27 // and `WATCHDOG_PID` will be unconditionally unset.
28 //
29 // It returns one of the following:
30 // (0, nil) - watchdog isn't enabled or we aren't the watched PID.
31 // (0, err) - an error happened (e.g. error converting time).
32 // (time, nil) - watchdog is enabled and we can send ping.
33 //   time is delay before inactive service will be killed.
34 func SdWatchdogEnabled(unsetEnvironment bool) (time.Duration, error) {
35         wusec := os.Getenv("WATCHDOG_USEC")
36         wpid := os.Getenv("WATCHDOG_PID")
37         if unsetEnvironment {
38                 wusecErr := os.Unsetenv("WATCHDOG_USEC")
39                 wpidErr := os.Unsetenv("WATCHDOG_PID")
40                 if wusecErr != nil {
41                         return 0, wusecErr
42                 }
43                 if wpidErr != nil {
44                         return 0, wpidErr
45                 }
46         }
47
48         if wusec == "" {
49                 return 0, nil
50         }
51         s, err := strconv.Atoi(wusec)
52         if err != nil {
53                 return 0, fmt.Errorf("error converting WATCHDOG_USEC: %s", err)
54         }
55         if s <= 0 {
56                 return 0, fmt.Errorf("error WATCHDOG_USEC must be a positive number")
57         }
58         interval := time.Duration(s) * time.Microsecond
59
60         if wpid == "" {
61                 return interval, nil
62         }
63         p, err := strconv.Atoi(wpid)
64         if err != nil {
65                 return 0, fmt.Errorf("error converting WATCHDOG_PID: %s", err)
66         }
67         if os.Getpid() != p {
68                 return 0, nil
69         }
70
71         return interval, nil
72 }