forked from davrodpin/mole
-
Notifications
You must be signed in to change notification settings - Fork 0
/
runtime.go
131 lines (101 loc) · 2.37 KB
/
runtime.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package mole
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"strconv"
"github.com/BurntSushi/toml"
"github.com/davrodpin/mole/fsutils"
ps "github.com/mitchellh/go-ps"
)
type Formatter interface {
Format(format string) (string, error)
}
// Runtime holds runtime data about an application instance.
type Runtime Configuration
// Format parses a Runtime object into a string representation based on the given
// format (i.e. toml).
func (rt Runtime) Format(format string) (string, error) {
if format == "toml" {
return rt.ToToml()
} else {
return "", fmt.Errorf("unknown %s format", format)
}
}
func (rt Runtime) ToToml() (string, error) {
var buf bytes.Buffer
e := toml.NewEncoder(&buf)
if err := e.Encode(rt); err != nil {
return "", err
}
return buf.String(), nil
}
type InstancesRuntime []Runtime
func (ir InstancesRuntime) Format(format string) (string, error) {
if format == "toml" {
return ir.ToToml()
} else {
return "", fmt.Errorf("unknown %s format", format)
}
}
func (ir InstancesRuntime) ToToml() (string, error) {
rt := make(map[string]map[string]Runtime)
rt["instances"] = make(map[string]Runtime)
for _, instance := range ir {
rt["instances"][instance.Id] = instance
}
var buf bytes.Buffer
e := toml.NewEncoder(&buf)
if err := e.Encode(rt); err != nil {
return "", err
}
return buf.String(), nil
}
func (c *Client) Runtime() (*Runtime, error) {
runtime := Runtime(*c.Conf)
if c.Tunnel != nil {
source := &AddressInputList{}
destination := &AddressInputList{}
for _, channel := range c.Tunnel.Channels() {
var err error
err = source.Set(channel.Source)
if err != nil {
return nil, err
}
err = destination.Set(channel.Destination)
if err != nil {
return nil, err
}
}
runtime.Source = *source
runtime.Destination = *destination
}
return &runtime, nil
}
// Running checks if an instance of mole is running on the system.
func (c *Client) Running() (bool, error) {
d, err := fsutils.InstanceDir(c.Conf.Id)
if err != nil {
return false, err
}
if _, err := os.Stat(d.PidFile); os.IsNotExist(err) {
return false, nil
}
pd, err := ioutil.ReadFile(d.PidFile)
if err != nil {
return false, err
}
pid, err := strconv.Atoi(string(pd))
if err != nil {
return false, err
}
ps, err := ps.FindProcess(pid)
if err != nil {
return false, err
}
if ps == nil {
return false, nil
}
return true, nil
}