-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmodules.go
More file actions
322 lines (272 loc) · 7.79 KB
/
modules.go
File metadata and controls
322 lines (272 loc) · 7.79 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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
// ThingsConstruction, a code generator for WoT-based models
// Copyright (C) 2017,2018 @aschmidt75
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// This program is dual-licensed. For commercial licensing options, please
// contact the author(s).
//
//
package main
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/fsouza/go-dockerclient"
"github.com/gorilla/mux"
"html/template"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
)
type ModuleResponseFile struct {
Permalink *string `json:"permalink"`
FileName string `json:"filename"`
Description *string `json:"desc"`
ContentType *string `json:"ct"`
FileType *string `json:"type"`
Language *string `json:"language"`
}
type ModuleResponseFiles []ModuleResponseFile
type ModuleResponse struct {
Status string `json:"status"`
Message *string `json:"msg"`
Files *ModuleResponseFiles `json:"files"`
}
type ModuleRequestFile struct {
FileName string `json:"filename"`
ContentType string `json:"ct"`
FileType string `json:"type"`
}
type ModuleRequestFiles []ModuleRequestFile
type ModuleRequest struct {
ThingId string `json:"thingid"`
Files *ModuleRequestFiles `json:"files"`
}
type ModuleMetaData struct {
Status string `json:"status"`
Message string `json:"msg"`
Details *interface{}
Files ModuleResponseFiles
}
func NewModuleRequest(id string) *ModuleRequest {
res := &ModuleRequest{
ThingId: id,
Files: &ModuleRequestFiles{},
}
return res
}
func (mr *ModuleRequest) AddInputFile(filePath string) {
*mr.Files = append(*mr.Files, ModuleRequestFile{
FileName: filePath,
ContentType: "application/json",
FileType: "thingdescription",
})
}
func (mr *ModuleRequest) ShipRequest() *strings.Reader {
b, err := json.Marshal(mr)
if err != nil {
return strings.NewReader("")
}
return strings.NewReader(string(b))
}
func MakePermaLink(mrf *ModuleResponseFile) string {
tmpStr := fmt.Sprintf("tc-%s", mrf.FileName)
s := sha256.Sum256([]byte(tmpStr))
sb := []byte(s[:])
return fmt.Sprintf("%s", hex.EncodeToString(sb))
}
func ParseResponseFromModule(b []byte) (*ModuleResponse, error) {
res := &ModuleResponse{}
err := json.Unmarshal(b, res)
if err == nil && res.Files != nil {
// create permalinks over files
for idx := 0; idx < len(*res.Files); idx++ {
file := &(*res.Files)[idx]
file.Permalink = new(string)
*file.Permalink = MakePermaLink(file)
}
}
return res, err
}
type modulePageData struct {
PageData
HtmlOutput template.HTML
}
func ModulePageHandler(w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
moduleId := vars["id"]
// start container to get module spec page
content, err := getModuleSpecContent(moduleId)
if err != nil {
Error.Printf("Error reading module content for id=%s, err=%s\n", moduleId, err)
ServeNotFound(w, req)
return
}
modulePagesServePage(w, req, modulePageData{
PageData: PageData{
Title: "Module specification",
},
HtmlOutput: template.HTML(content),
})
}
func ModuleDataHandler(w http.ResponseWriter, req *http.Request) {
targets, err := ReadGeneratorsConfig()
if err != nil || targets == nil {
Error.Println(err)
w.WriteHeader(500)
fmt.Fprint(w, "Error reading modules data")
return
}
b, err := json.Marshal(targets)
if err != nil {
Error.Println(err)
w.WriteHeader(500)
fmt.Fprint(w, "Error marshaling modules data")
return
}
w.WriteHeader(200)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Write(b)
}
func getModuleSpecContent(moduleId string) ([]byte, error) {
targets, err := ReadGeneratorsConfig()
if err != nil || targets == nil {
return nil, err
}
target := targets.AppGenTargetById(moduleId)
if target == nil {
return nil, errors.New("no module for id")
}
Verbose.Printf("Using target=%#v", target)
client, err := docker.NewClient("unix:///var/run/docker.sock")
if err != nil {
return nil, err
}
client.SkipServerVersionCheck = true
Debug.Printf("cli=%#v\n", client)
outPath := fmt.Sprintf("%s/%s-out", ServerConfig.Paths.ModulePagesPath, moduleId)
if _, err := os.Stat(outPath); err != nil {
if os.IsNotExist(err) {
if err = os.Mkdir(outPath, 0777); err != nil {
return nil, err
}
} else {
return nil, err
}
}
outPath, err = filepath.Abs(outPath)
if err != nil {
return nil, err
}
hostMounts := make([]docker.HostMount, 1)
hostMounts[0] = docker.HostMount{
Target: "/out",
Source: outPath,
Type: "bind",
ReadOnly: false,
}
opts := docker.CreateContainerOptions{
Config: &docker.Config{
Image: target.ImageRepoTag,
OpenStdin: false,
StdinOnce: false,
Env: target.EnvInjection,
},
HostConfig: &docker.HostConfig{
Mounts: hostMounts,
CapDrop: []string{"all"},
CapAdd: []string{"setuid", "setgid"},
AutoRemove: true,
},
}
if ServerConfig.Docker.UserConfig != "" {
opts.Config.User = ServerConfig.Docker.UserConfig
}
// Create the container, start the container
container, err := client.CreateContainer(opts)
if err != nil {
return nil, err
}
Debug.Printf("container=%#v\n", container)
if err = client.StartContainer(container.ID, &docker.HostConfig{}); err != nil {
return nil, err
}
var buf bytes.Buffer
var buferr bytes.Buffer
attachOpts := docker.AttachToContainerOptions{
Container: container.ID,
Stdin: false,
Stdout: true,
Stderr: true,
OutputStream: &buf,
ErrorStream: &buferr,
Stream: true,
Logs: true,
}
if err = client.AttachToContainer(attachOpts); err != nil {
return nil, err
}
// Wait until container has finished. TODO: WaitContainerWithContext, timeout, ...
exitCode, err := client.WaitContainer(container.ID)
if err != nil {
return nil, err
}
// dump some results.
Debug.Printf("Exitcode=%#v\n", exitCode)
if exitCode != 0 {
Error.Printf("Module returned non-zero exit code: %d. Will not continue", exitCode)
return nil, errors.New("Non-zero exit code.")
}
var md ModuleMetaData
if err := json.Unmarshal(buf.Bytes(), &md); err != nil {
return nil, err
}
// go through files, seek a module-spec type..
for _, file := range md.Files {
if *file.FileType == "module-spec" && *file.ContentType == "text/html" {
return ioutil.ReadFile(filepath.Join(outPath, file.FileName))
}
}
// Debug.Println(buf.String())
// Debug.Println(buferr.String())
return nil, errors.New("no suitable module spec found")
}
var ModulePagesTemplates *template.Template
func initializeModuleTemplates() {
if ModulePagesTemplates == nil {
Debug.Printf("Initializing templates for module pages")
var err error
ModulePagesTemplates, err = NewBasicHtmlTemplateSet("staticpage.html.tpl", "staticpage_script.html.tpl")
if err != nil {
Error.Fatalf("Fatal error creating template set: %s\n", err)
}
}
}
func modulePagesServePage(w http.ResponseWriter, req *http.Request, data modulePageData) {
initializeModuleTemplates()
data.SetFeaturesFromConfig()
data.UpdateFeaturesFromContext(req.Context())
err := ModulePagesTemplates.ExecuteTemplate(w, "root", data)
if err != nil {
Error.Printf("Error executing template: %s\n", err)
w.WriteHeader(500)
fmt.Fprint(w, "There was an internal error.")
}
}