Skip to content

Commit 9fc440f

Browse files
DavidGOrtegarestyled-io[bot]restyled-commits0x2b3bfa0
authored
Logrus logs (#423)
* logs fix * Restyled by gofmt (#424) Co-authored-by: Restyled.io <commits@restyled.io> * DEBUG level * basicFormatter * Restyled by gofmt (#431) Co-authored-by: Restyled.io <commits@restyled.io> * improvements Co-authored-by: restyled-io[bot] <32688539+restyled-io[bot]@users.noreply.github.com> Co-authored-by: Restyled.io <commits@restyled.io> Co-authored-by: Helio Machado <0x2b3bfa0+git@googlemail.com>
1 parent 7718196 commit 9fc440f

File tree

7 files changed

+390
-103
lines changed

7 files changed

+390
-103
lines changed

go.mod

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ require (
2727
github.com/hashicorp/terraform-plugin-sdk/v2 v2.8.0
2828
github.com/rclone/rclone v1.57.0
2929
github.com/sebdah/goldie/v2 v2.5.3
30+
github.com/sirupsen/logrus v1.8.1
3031
github.com/stretchr/testify v1.7.0
3132
golang.org/x/crypto v0.0.0-20210817164053-32db794688a5
3233
golang.org/x/oauth2 v0.0.0-20210819190943-2bc19b11175f

iterative/resource_task.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
1515
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
1616

17+
"terraform-provider-iterative/iterative/utils"
1718
"terraform-provider-iterative/task"
1819
"terraform-provider-iterative/task/common"
1920
)
@@ -234,8 +235,13 @@ func resourceTaskRead(ctx context.Context, d *schema.ResourceData, m interface{}
234235
return diagnostic(diags, err, diag.Warning)
235236
}
236237
d.Set("logs", logs)
237-
238238
d.SetId(task.GetIdentifier(ctx).Long())
239+
240+
logger := utils.TpiLogger(d)
241+
logger.Info("instance")
242+
logger.Info("logs")
243+
logger.Info("status")
244+
239245
return diags
240246
}
241247

iterative/utils/logger.go

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
package utils
2+
3+
import (
4+
"fmt"
5+
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
6+
"github.com/sirupsen/logrus"
7+
"strings"
8+
"time"
9+
)
10+
11+
var baseTimestamp = time.Now()
12+
var colors = make(map[string]int)
13+
14+
type basicFormatter struct{}
15+
16+
func (f *basicFormatter) Format(entry *logrus.Entry) ([]byte, error) {
17+
levelText := strings.ToUpper(entry.Level.String())
18+
levelColor := colors[levelText]
19+
tpl := "[%s] 🚀\x1b[%dmTPI\x1b[0m %s\n"
20+
return []byte(fmt.Sprintf(tpl, levelText, levelColor, entry.Message)), nil
21+
}
22+
23+
func init() {
24+
colors["DEBUG"] = 34
25+
colors["INFO"] = 36
26+
colors["WARN"] = 33
27+
colors["ERROR"] = 31
28+
colors["FATAL"] = 31
29+
colors["foreground"] = 35
30+
31+
logrus.SetLevel(logrus.DebugLevel)
32+
logrus.SetFormatter(&basicFormatter{})
33+
}
34+
35+
type tpiFormatter struct{}
36+
37+
func (f *tpiFormatter) Format(entry *logrus.Entry) ([]byte, error) {
38+
data := make(logrus.Fields)
39+
for k, v := range entry.Data {
40+
data[k] = v
41+
}
42+
43+
d := data["d"].(*schema.ResourceData)
44+
message := entry.Message
45+
levelText := strings.ToUpper(entry.Level.String())
46+
levelColor := colors[levelText]
47+
48+
if message == "instance" {
49+
cloud := d.Get("cloud").(string)
50+
machine := d.Get("machine").(string)
51+
region := d.Get("region").(string)
52+
spot := d.Get("spot").(float64)
53+
54+
spottext := ""
55+
if spot > 0 {
56+
spottext = fmt.Sprintf("(Spot %f/h)", spot)
57+
}
58+
message = fmt.Sprintf("%s %s%s in %s", cloud, machine, spottext, region)
59+
}
60+
61+
if message == "status" {
62+
status := d.Get("status").(map[string]interface{})
63+
terminatedStr := "terminated 🔵"
64+
65+
running := "queued 🟣"
66+
if status["running"] != nil {
67+
running = terminatedStr
68+
if status["running"].(int) == 1 {
69+
running = "running 🟡"
70+
}
71+
}
72+
73+
success := ""
74+
if running == terminatedStr {
75+
success = "without any output"
76+
if status["succeeded"] != nil && status["succeeded"].(int) == 1 {
77+
success = "succesfully 🟢"
78+
}
79+
if status["failed"] != nil && status["failed"].(int) == 1 {
80+
success = "with errors 🔴"
81+
}
82+
}
83+
84+
message = fmt.Sprintf("Task %s %s", running, success)
85+
}
86+
87+
if message == "logs" {
88+
logs := d.Get("logs").([]interface{})
89+
taskLogs := "No logs"
90+
if len(logs) > 0 {
91+
taskLogs = strings.Replace(logs[0].(string), "\n", fmt.Sprintf("\n[%s] ", levelText), -1)
92+
}
93+
94+
message = fmt.Sprintf("Task logs:\x1b[%dm%s\x1b[0m", colors["foreground"], taskLogs)
95+
}
96+
97+
tpl := "[%s] \x1b[%dm🚀TPI %s\x1b[0m %s'\n"
98+
return []byte(fmt.Sprintf(tpl, levelText, levelColor, d.Id(), message)), nil
99+
}
100+
101+
func TpiLogger(d *schema.ResourceData) *logrus.Entry {
102+
logrus.SetFormatter(&tpiFormatter{})
103+
104+
return logrus.WithFields(logrus.Fields{"d": d})
105+
}

iterative/utils/logger_test.go

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
package utils
2+
3+
import (
4+
"testing"
5+
6+
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
7+
)
8+
9+
func TestState(t *testing.T) {
10+
d := generateSchemaData(t, map[string]interface{}{
11+
"name": "mytask",
12+
"status": map[string]interface{}{
13+
"running": 0,
14+
"failed": 0,
15+
},
16+
})
17+
18+
logger := TpiLogger(d)
19+
logger.Info("status")
20+
}
21+
22+
func TestState2(t *testing.T) {
23+
d := generateSchemaData(t, map[string]interface{}{
24+
"name": "mytask",
25+
"status": map[string]interface{}{
26+
"running": 0,
27+
"failed": 1,
28+
},
29+
})
30+
31+
logger := TpiLogger(d)
32+
logger.Info("status")
33+
}
34+
35+
func TestState3(t *testing.T) {
36+
d := generateSchemaData(t, map[string]interface{}{
37+
"name": "mytask",
38+
"status": map[string]interface{}{
39+
"running": 0,
40+
"succeeded": 1,
41+
},
42+
})
43+
44+
logger := TpiLogger(d)
45+
logger.Info("status")
46+
}
47+
48+
func TestLogs(t *testing.T) {
49+
logs := make([]interface{}, 0)
50+
logs = append(logs, "-- Logs begin at Tue 2022-03-01 12:25:09 UTC, end at Tue 2022-03-01 12:30:30 UTC. --\nMar 01 12:25:50 tpi000000 systemd[1]: Started tpi-task.service.\nMar 01 12:25:50 tpi000000 sudo[1706]: root : TTY=unknown ; PWD=/tmp/tpi-task ; USER=root ; COMMAND=/usr/bin/apt update\nMar 01 12:25:50 tpi000000 sudo[1706]: pam_unix(sudo:session): session opened for user root by (uid=0)\nMar 01 12:25:50 tpi000000 tpi-task[1711]: WARNING: apt does not have a stable CLI interface. Use with caution in scripts.\nMar 01 12:25:50 tpi000000 tpi-task[1711]: Hit:1 http://azure.archive.ubuntu.com/ubuntu focal InRelease\nMar 01 12:25:50 tpi000000 tpi-task[1711]: Get:2 http://azure.archive.ubuntu.com/ubuntu focal-updates InRelease [114 kB]\nMar 01 12:25:50 tpi000000 tpi-task[1711]: Get:3 http://azure.archive.ubuntu.com/ubuntu focal-backports InRelease [108 kB]\nMar 01 12:25:51 tpi000000 tpi-task[1711]: Get:4 http://security.ubuntu.com/ubuntu focal-security InRelease [114 kB]\nMar 01 12:25:51 tpi000000 tpi-task[1711]: Get:5 http://azure.archive.ubuntu.com/ubuntu focal/universe amd64 Packages [8628 kB]\n")
51+
52+
d := generateSchemaData(t, map[string]interface{}{
53+
"name": "mytask",
54+
"logs": logs,
55+
})
56+
57+
logger := TpiLogger(d)
58+
logger.Info("logs")
59+
}
60+
61+
func TestMachine(t *testing.T) {
62+
d := generateSchemaData(t, map[string]interface{}{
63+
"name": "mytask",
64+
"cloud": "aws",
65+
"machine": "t2.micro",
66+
"spot": 0.2,
67+
"region": "us-west",
68+
})
69+
70+
logger := TpiLogger(d)
71+
logger.Info("instance")
72+
}
73+
74+
func generateSchemaData(t *testing.T, raw map[string]interface{}) *schema.ResourceData {
75+
sch := map[string]*schema.Schema{
76+
"name": {
77+
Type: schema.TypeString,
78+
ForceNew: true,
79+
Optional: true,
80+
},
81+
"cloud": {
82+
Type: schema.TypeString,
83+
ForceNew: true,
84+
Required: true,
85+
},
86+
"region": {
87+
Type: schema.TypeString,
88+
ForceNew: true,
89+
Optional: true,
90+
Default: "us-west",
91+
},
92+
"machine": {
93+
Type: schema.TypeString,
94+
ForceNew: true,
95+
Optional: true,
96+
Default: "m",
97+
},
98+
"disk_size": {
99+
Type: schema.TypeInt,
100+
ForceNew: true,
101+
Optional: true,
102+
Default: 30,
103+
},
104+
"spot": {
105+
Type: schema.TypeFloat,
106+
ForceNew: true,
107+
Optional: true,
108+
Default: -1,
109+
},
110+
"image": {
111+
Type: schema.TypeString,
112+
ForceNew: true,
113+
Optional: true,
114+
Default: "ubuntu",
115+
},
116+
"addresses": {
117+
Type: schema.TypeList,
118+
Computed: true,
119+
Elem: &schema.Schema{
120+
Type: schema.TypeString,
121+
},
122+
},
123+
"status": {
124+
Type: schema.TypeMap,
125+
Computed: true,
126+
Elem: &schema.Schema{
127+
Type: schema.TypeInt,
128+
},
129+
},
130+
"events": {
131+
Type: schema.TypeList,
132+
Computed: true,
133+
Elem: &schema.Schema{
134+
Type: schema.TypeString,
135+
},
136+
},
137+
"logs": {
138+
Type: schema.TypeList,
139+
Computed: true,
140+
Elem: &schema.Schema{
141+
Type: schema.TypeString,
142+
},
143+
},
144+
"script": {
145+
Type: schema.TypeString,
146+
ForceNew: true,
147+
Required: true,
148+
},
149+
"workdir": {
150+
Optional: true,
151+
Type: schema.TypeSet,
152+
Elem: &schema.Resource{
153+
Schema: map[string]*schema.Schema{
154+
"input": {
155+
Type: schema.TypeString,
156+
ForceNew: true,
157+
Optional: true,
158+
Default: "",
159+
},
160+
"output": {
161+
Type: schema.TypeString,
162+
ForceNew: false,
163+
Optional: true,
164+
Default: "",
165+
},
166+
},
167+
},
168+
},
169+
}
170+
171+
return schema.TestResourceDataRaw(t, sch, raw)
172+
}

0 commit comments

Comments
 (0)