forked from PiFoundry/bakery
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfileServer.go
More file actions
160 lines (148 loc) · 4.81 KB
/
fileServer.go
File metadata and controls
160 lines (148 loc) · 4.81 KB
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
package main
import (
"html/template"
"log"
"net/http"
"path"
"regexp"
"io/ioutil"
"fmt"
"os"
"time"
"github.com/gorilla/mux"
"github.com/google/uuid"
)
type fileServer interface {
fileHandler(http.ResponseWriter, *http.Request)
}
type FileServer struct {
nfs fileBackend
piInventory piManager
diskManager *diskManager
}
type templatevars struct {
PiId string
NfsServer string
NfsRoot string
}
func newFileServer(nfs fileBackend, inventory piManager, dm *diskManager) (fileServer, error) {
return &FileServer{
nfs: nfs,
piInventory: inventory,
diskManager: dm,
}, nil
}
func (f *FileServer) fileHandler(w http.ResponseWriter, r *http.Request) {
urlvars := mux.Vars(r)
filename := urlvars["filename"]
piId := urlvars["piId"]
//check if piId is allready registered. If not then register.
pi, err := f.piInventory.GetPi(piId)
if err != nil {
log.Println("Pi not found in inventory. Putting a new one in the fridge.")
pi = f.piInventory.NewPi(piId)
err = pi.Save()
if err != nil {
panic(err)
}
}
//if filename == cmdline.txt then parse the template. else just serve the file
bootLocation := f.nfs.GetBootRoot()+"/2018-04-18-raspbian-stretch-lite"
if pi.Status != NOTINUSE && pi.Status != BOOTING {
bootLocation = pi.SourceBakeform.bootLocation
}
//strings.Replace(bootLocation, "/", "", 1) //remove the first /
fullFilename := path.Join(bootLocation, filename)
//log.Printf("%v requested", fullFilename)
if filename == "cmdline.txt" {
c := templatevars{
NfsServer: f.nfs.GetNfsAddress(),
NfsRoot: f.nfs.GetNfsRoot()+"/481f6eed-275a-4456-9614-0d088dac4a41",
}
if pi.Status != NOTINUSE && pi.Status != BOOTING {
c = templatevars{
NfsServer: f.nfs.GetNfsAddress(),
NfsRoot: pi.Disks[0].Location,
}
}
log.Printf("%v requested for: %v\n", filename, pi.Id)
t, err := template.New("templatefile").ParseFiles(templatePath+"/cmdline.txt")
if err != nil {
panic(err)
}
t.ExecuteTemplate(w, filename, c)
return
} else if filename == "config.txt" {
// we want to make sure we are enabling uart on rpi3s so inject into config.txt
// generate a new config.txt to serve temporarily from the original one without modifying it directly
config_file, err := ioutil.ReadFile(fullFilename) // just pass the file name
if err != nil {
fmt.Println(err)
}
commentlines := regexp.MustCompile("(?m)[\r\n]+^#.*$")
nocomments := commentlines.ReplaceAllString(string(config_file), "")
pattern := regexp.MustCompile("enable_uart=[0-1]")
match := pattern.FindString(string(nocomments))
config_file_new := string(nocomments)
if len(match) == 0 {
config_file_new = string(nocomments) + "\nenable_uart=1"
}
config_file_save := pattern.ReplaceAllString(config_file_new, "enable_uart=1")
random_uuid := uuid.New().String()
err = ioutil.WriteFile("/tmp/"+random_uuid, []byte(config_file_save), 0755)
if err != nil {
fmt.Println(err.Error())
}
http.ServeFile(w, r, "/tmp/"+random_uuid)
err = os.Remove("/tmp/"+random_uuid)
if err != nil {
fmt.Println(err.Error())
}
//return
} else {
http.ServeFile(w, r, fullFilename)
return
}
log.Printf("PiID: %v, PiStatus: %v", pi.Id, pi.Status)
// check if the pi status is booting, if it is not in use and booting poll bushwood to see if it knows the serial number yet
if pi.Status == NOTINUSE {
pi.SetStatus(BOOTING)
//Pi is not in inventory or not in use. Then don't serve files and power it off
log.Printf("Pi %v came online but it's not in use. Powering it off\n", pi.Id)
// poll bushwood
var netClient = &http.Client{
Timeout: time.Second * 10,
}
token := bushwoodToken
req, _ := http.NewRequest("GET", bushwoodServer+"/api/v1/slots/pi/"+pi.Id, nil)
req.Header.Add("apikey", token)
timeout_count := 0
//loop 4 times and break (30 seconds) timeout if no result
for {
if timeout_count == 6 {
break
}
resp, _ := netClient.Do(req)
log.Printf("%v%v%v", bushwoodServer,"/api/v1/slots/pi/",pi.Id)
body, _ := ioutil.ReadAll(resp.Body)
textBytes := []byte(body)
resp.Body.Close()
slotId := string(textBytes)[1 : len(string(textBytes))-1]
//check if our response is empty, if it is, sleep, increment, and try again
if string(slotId) == "" {
time.Sleep(time.Second * 5)
timeout_count++
} else {
break
}
}
pi.SetStatus(NOTINUSE)
log.Printf("PiID: %v, PiStatus: %v", pi.Id, pi.Status)
err = pi.PowerOff()
if err != nil {
log.Println("A Pi just came online but I can't control its power state. Error:" + err.Error())
}
//w.WriteHeader(http.StatusNotFound)
return
}
}