-
Notifications
You must be signed in to change notification settings - Fork 257
/
service.go
98 lines (83 loc) · 2.6 KB
/
service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package db_local
import (
"fmt"
"log"
"os"
"strconv"
"strings"
filehelpers "github.com/turbot/go-kit/files"
"github.com/turbot/steampipe/pkg/constants"
"github.com/turbot/steampipe/pkg/filepaths"
"github.com/turbot/steampipe/pkg/utils"
)
// GetState checks that the database instance is running and returns its details
func GetState() (*RunningDBInstanceInfo, error) {
utils.LogTime("db.GetStatus start")
defer utils.LogTime("db.GetStatus end")
info, err := loadRunningInstanceInfo()
if err != nil {
return nil, err
}
if info == nil {
log.Println("[TRACE] GetRunStatus - loadRunningInstanceInfo returned nil ")
// we do not have a info file
return nil, errorIfUnknownService()
}
pidExists, err := utils.PidExists(info.Pid)
if err != nil {
return nil, err
}
if !pidExists {
log.Printf("[TRACE] GetState - pid %v does not exist\n", info.Pid)
// nothing to do here
os.Remove(filepaths.RunningInfoFilePath())
return nil, nil
}
return info, nil
}
// errorIfUnknownService returns an error if it can find a `postmaster.pid` in the `INSTALL_DIR`
// and the PID recorded in the found `postmaster.pid` is running - nil otherwise.
//
// This is because, this function is called when we cannot find the steampipe service state file.
//
// No steampipe state file indicates that the service is not running, so, if the service
// is running without us knowing about it, then it's an irrecoverable state
func errorIfUnknownService() error {
// no postmaster.pid, we are good
if !filehelpers.FileExists(filepaths.GetPostmasterPidLocation()) {
return nil
}
// read the content of the postmaster.pid file
fileContent, err := os.ReadFile(filepaths.GetPostmasterPidLocation())
if err != nil {
return err
}
// the first line contains the PID
lines := strings.FieldsFunc(string(fileContent), func(r rune) bool {
return r == '\n'
})
// make sure that there's split up content
if len(lines) == 0 {
return nil
}
// extract it
pid, err := strconv.ParseInt(lines[0], 10, 64)
if err != nil {
return err
}
// check if a process with that PID exists
exists, err := utils.PidExists(int(pid))
if err != nil {
return err
}
if exists {
// if it does, then somehow we don't know about it. Error out
return fmt.Errorf("service is running in an unknown state [PID: %d] - try killing it with %s", pid, constants.Bold("steampipe service stop --force"))
}
// the pid does not exist
// this can confuse postgres as per https://postgresapp.com/documentation/troubleshooting.html
// delete it
os.Remove(filepaths.GetPostmasterPidLocation())
// this must be a stale file left over by PG. Ignore
return nil
}