-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpipeline.go
695 lines (651 loc) · 19.6 KB
/
pipeline.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
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
package pipeline
import (
"fmt"
"io"
"log"
"math"
"encoding/xml"
"strings"
"errors"
"github.com/capitancambio/restclient"
)
//Available api entry names
const (
API_ALIVE = "alive"
API_SCRIPT = "script"
API_SCRIPTS = "scripts"
API_DATATYPE = "datatype"
API_STYLESHEET_PARAMETERS = "stylesheet-parameters"
API_JOBREQUEST = "jobRequest"
API_JOB = "job"
API_JOBS = "jobs"
API_BATCH = "batch"
API_DEL_JOB = "del_job"
API_DEL_BATCH = "del_batch"
API_RESULT = "results"
API_LOG = "log"
API_HALT = "halt"
API_CLIENTS = "clients"
API_NEWCLIENT = "new_client"
API_CLIENT = "client"
API_DELETECLIENT = "delete_client"
API_MODIFYCLIENT = "modify_client"
API_PROPERTIES = "properties"
API_SIZE = "size"
API_QUEUE = "queue"
API_MOVE_UP = "move_up"
API_MOVE_DOWN = "move_down"
)
//Defines the information for an api entry
type apiEntry struct {
urlPath string
method string
okStatus int
}
//Available api entries
var apiEntries = map[string]apiEntry{
API_ALIVE: apiEntry{"alive", "GET", 200},
API_SCRIPTS: apiEntry{"scripts", "GET", 200},
API_SCRIPT: apiEntry{"scripts/%v", "GET", 200},
API_DATATYPE: apiEntry{"datatypes/%v", "GET", 200},
API_STYLESHEET_PARAMETERS: apiEntry{"stylesheet-parameters", "POST", 200},
API_JOBREQUEST: apiEntry{"jobs", "POST", 201},
API_JOB: apiEntry{"jobs/%v?msgSeq=%v", "GET", 200},
API_DEL_JOB: apiEntry{"jobs/%v", "DELETE", 204},
API_RESULT: apiEntry{"jobs/%v/result", "GET", 200},
API_JOBS: apiEntry{"jobs", "GET", 200},
API_QUEUE: apiEntry{"queue", "GET", 200},
API_MOVE_UP: apiEntry{"queue/up/%v", "GET", 200},
API_MOVE_DOWN: apiEntry{"queue/down/%v", "GET", 200},
API_LOG: apiEntry{"jobs/%v/log", "GET", 200},
API_HALT: apiEntry{"admin/halt/%v", "GET", 204},
API_CLIENTS: apiEntry{"admin/clients", "GET", 200},
API_NEWCLIENT: apiEntry{"admin/clients", "POST", 201},
API_CLIENT: apiEntry{"admin/clients/%v", "GET", 200},
API_DELETECLIENT: apiEntry{"admin/clients/%v", "DELETE", 204},
API_MODIFYCLIENT: apiEntry{"admin/clients/%v", "PUT", 200},
API_PROPERTIES: apiEntry{"admin/properties", "GET", 200},
API_SIZE: apiEntry{"admin/sizes", "GET", 200},
API_BATCH: apiEntry{"batch/%v", "GET", 200},
API_DEL_BATCH: apiEntry{"batch/%v", "DELETE", 204},
}
//Pipeline struct stores different configuration paramenters
//for the communication with the pipeline framework
type Pipeline struct {
BaseUrl string //baseurl of the framework
clientMaker func() doer //client to perform the rest queries
authenticator func(req *restclient.RequestResponse) //authentication function
}
func NewPipeline(baseUrl string) *Pipeline {
return &Pipeline{
BaseUrl: baseUrl,
authenticator: func(*restclient.RequestResponse) {},
clientMaker: newClient,
}
}
func (p *Pipeline) SetCredentials(clientKey, clientSecret string) {
p.authenticator = authenticator(clientKey, clientSecret)
}
func (p *Pipeline) SetUrl(url string) {
p.BaseUrl = url
}
//Returns a simple string representation of the Alive struct in the format:
//Alive:[#authentication:value #mode:value #version:value]
func (a Alive) String() string {
return fmt.Sprintf("Alive:[#authentication:%v #fsallow:%v #version:%v]", a.Authentication, a.FsAllow, a.Version)
}
//Calls the alive api entry
//TODO link to wiki
func (p Pipeline) Alive() (alive Alive, err error) {
req := p.newResquest(API_ALIVE, &alive, nil)
_, err = p.do(req, defaultErrorHandler())
return
}
//Returns the list of available scripts
func (p Pipeline) Scripts() (scripts Scripts, err error) {
req := p.newResquest(API_SCRIPTS, &scripts, nil)
_, err = p.do(req, defaultErrorHandler())
if err != nil {
err = fmt.Errorf("Error parsing scripts XML: %v", err)
return
}
for _, script := range scripts.Scripts {
err = processInputsAndOptions(p, &script)
if err != nil {
err = fmt.Errorf("Error parsing scripts XML: %v: %v", script.Id, err)
return
}
}
return
}
//Returns the script for a given script id
func (p Pipeline) Script(id string) (script Script, err error) {
req := p.newResquest(API_SCRIPT, &script, nil, id)
_, err = p.do(req, errorHandler(map[int]string{404: "Script " + id + " not found"}))
if err != nil {
return
}
err = processInputsAndOptions(p, &script)
if err != nil {
err = fmt.Errorf("Error parsing script XML: %v: %v", script.Id, err)
}
return
}
func processInputsAndOptions(p Pipeline, script *Script) (err error) {
for i, input := range script.Inputs {
desc := strings.Split(input.LongDesc, "\n")
script.Inputs[i].ShortDesc = desc[0]
// insert empty line after first line
if len(desc) > 1 {
if desc[1] != "" {
desc = append(desc[:1], append([]string{""}, desc[1:]...)...)
}
script.Inputs[i].LongDesc = strings.Join(desc, "\n")
}
}
for i, option := range script.Options {
desc := strings.Split(option.LongDesc, "\n")
script.Options[i].ShortDesc = desc[0]
// insert empty line after first line
if len(desc) > 1 {
if desc[1] != "" {
desc = append(desc[:1], append([]string{""}, desc[1:]...)...)
}
script.Options[i].LongDesc = strings.Join(desc, "\n")
}
// get data type definition
var optionType DataType
optionType, err = p.dataType(option.TypeAttr)
script.Options[i].Type = optionType
}
return
}
//Returns the url for a given script id
func (p Pipeline) ScriptUrl(id string) string {
//This should call the server, but it just would add more overhead
//so it's computed here
req := p.newResquest(API_SCRIPT, nil, nil, id)
return req.Url
}
// the datatype (relaxng) xml
// text nodes that have sibling elements are ignored, except inside a documentation element,
// where the content is treated as text content (markdown)
type datatypeXmlElement struct {
XMLName xml.Name
Attrs []xml.Attr `xml:",any,attr"`
ChildNodes []datatypeXmlElement `xml:",any"`
TextContent string `xml:",chardata"`
}
func (e *datatypeXmlElement) UnmarshalXML(d *xml.Decoder, start xml.StartElement) (err error) {
type elem datatypeXmlElement
err = d.DecodeElement((*elem)(e), &start)
if err != nil {
return
}
e.Attrs = nil
for _, a := range start.Attr {
if (a.Name.Space != "xmlns" && !(a.Name.Space == "" && a.Name.Local == "xmlns")) {
e.Attrs = append(e.Attrs, a)
}
}
if e.XMLName.Local == "documentation" {
e.ChildNodes = nil
} else if len(e.ChildNodes) > 0 {
e.TextContent = ""
}
return
}
func (p Pipeline) dataType(id string) (datatype DataType, err error) {
if id == "" {
datatype = XsString{
XmlDefinition: "<data type=\"string\"/>"}
} else if id == "integer" || id == "xs:integer" {
datatype = XsInteger{
XmlDefinition: "<data type=\"integer\"/>"}
} else if id == "nonNegativeInteger" || id == "xs:nonNegativeInteger" {
datatype = XsNonNegativeInteger{
XmlDefinition: "<data type=\"nonNegativeInteger\"/>"}
} else if id == "boolean" || id == "xs:boolean" {
datatype = XsBoolean{
XmlDefinition: "<data type=\"boolean\"/>"}
} else if id == "anyURI" || id == "xs:anyURI" {
datatype = XsAnyURI{
XmlDefinition: "<data type=\"anyURI\"/>"}
} else if id == "anyFileURI" {
datatype = AnyFileURI{
XmlDefinition: "<data type=\"anyFileURI\" datatypeLibrary=\"http://www.daisy.org/ns/pipeline/xproc\"/>"}
} else if id == "anyDirURI" {
datatype = AnyDirURI{
XmlDefinition: "<data type=\"anyDirURI\" datatypeLibrary=\"http://www.daisy.org/ns/pipeline/xproc\"/>"}
} else if id == "string" || id == "xs:string" {
datatype = XsString{
XmlDefinition: "<data type=\"string\"/>"}
} else {
xmlDefinition := new(datatypeXmlElement)
req := p.newResquest(API_DATATYPE, &xmlDefinition, nil, id)
_, err = p.do(req, errorHandler(map[int]string{404: "Data type " + id + " not found"}))
if err != nil {
return
}
datatype, err = parseDatatypeXmlDefinition(xmlDefinition, "")
}
return
}
func parseDatatypeXmlDefinition(definition *datatypeXmlElement, documentation string) (result DataType, err error) {
var bytes []byte
bytes, err = xml.Marshal(definition)
if err != nil {
return
}
serialized := string(bytes)
switch definition.XMLName.Local {
case "data":
var documentation string
var pattern string
for _, child := range definition.ChildNodes {
switch child.XMLName.Local {
case "documentation":
if documentation != "" {
goto parseError
}
if pattern != "" {
// documentation must come before param
goto parseError
}
documentation = child.TextContent
case "param":
if !child.hasAttr("name", "pattern") {
goto parseError
}
if pattern != "" {
goto parseError
}
if !definition.hasAttr("type", "string") {
goto parseError
}
pattern = child.TextContent
default:
goto parseError
}
}
if pattern != "" {
result = Pattern{
XmlDefinition: serialized,
Pattern: pattern,
Documentation: documentation}
return
}
typeAttr, ok := definition.getAttr("type")
if !ok {
goto parseError
}
switch typeAttr {
case "string":
result = XsString{
XmlDefinition: serialized,
Documentation: documentation}
return
case "integer":
result = XsInteger{
XmlDefinition: serialized,
Documentation: documentation}
return
case "nonNegativeInteger":
result = XsNonNegativeInteger{
XmlDefinition: serialized,
Documentation: documentation}
return
case "boolean":
result = XsBoolean{
XmlDefinition: serialized,
Documentation: documentation}
return
case "anyURI":
result = XsAnyURI{
XmlDefinition: serialized,
Documentation: documentation}
return
case "anyFileURI":
result = AnyFileURI{
XmlDefinition: serialized,
Documentation: documentation}
return
case "anyDirURI":
result = AnyDirURI{
XmlDefinition: serialized,
Documentation: documentation}
return
default:
goto parseError
}
case "choice":
var choices []DataType
if documentation != "" {
goto parseError
}
for i, child := range definition.ChildNodes {
if child.XMLName.Local == "documentation" {
if i == 0 || definition.ChildNodes[i-1].XMLName.Local == "documentation" {
goto parseError
}
} else {
if len(definition.ChildNodes) > i + 1 && definition.ChildNodes[i+1].XMLName.Local == "documentation" {
documentation = definition.ChildNodes[i+1].TextContent
} else {
documentation = ""
}
var choice DataType
switch child.XMLName.Local {
case "value":
choice = Value{
XmlDefinition: serialized,
Documentation: documentation,
Value: child.TextContent}
default:
choice, err = parseDatatypeXmlDefinition(&child, documentation)
if err != nil {
return
}
}
choices = append(choices, choice)
}
}
result = Choice{
XmlDefinition: serialized,
Values: choices}
return
default:
goto parseError
}
parseError:
err = errors.New("invalid datatype xml: " + serialized)
return
}
func (elem *datatypeXmlElement) getAttr(name string) (value string, present bool) {
for _, attr := range elem.Attrs {
if attr.Name.Local == name {
return attr.Value, true
}
}
return "", false
}
func (elem *datatypeXmlElement) hasAttr(name string, value string) bool {
for _, attr := range elem.Attrs {
if attr.Name.Local == name {
return attr.Value == value
}
}
return false
}
//Overrides the xml decoder to get raw data
func multipartResultClientMaker(p Pipeline) func() doer {
return func() doer {
cli := p.clientMaker()
//change the default encodersuppier by the multipart
cli.SetEncoderSupplier(func(r io.Writer) restclient.Encoder {
return NewMultipartEncoder(r)
})
cli.SetContentType("multipart/form-data; boundary=" + boundary)
return cli
}
}
//Sends a JobRequest to the server
func (p Pipeline) JobRequest(newJob JobRequest, data []byte) (job Job, err error) {
var reqData interface{} = &newJob
log.Println("data len request ", len(data))
//check if we have data
if len(data) > 0 {
log.Println("Sending multipart job request")
p.clientMaker = multipartResultClientMaker(p)
reqData = &MultipartData{
data: RawData{&data},
request: newJob,
}
}
log.Println("Sending job request")
log.Println(newJob.Script.Id)
req := p.newResquest(API_JOBREQUEST, &job, reqData)
_, err = p.do(req, errorHandler(map[int]string{
400: "Job request is not valid",
}))
return
}
//Sends a StylesheetParametersRequest to the server
func (p Pipeline) StylesheetParametersRequest(paramReq StylesheetParametersRequest, data []byte) (params StylesheetParameters, err error) {
var reqData interface{} = ¶mReq
log.Println("data len request ", len(data))
//check if we have data
if len(data) > 0 {
log.Println("Sending multipart stylesheet-parameters request")
p.clientMaker = multipartResultClientMaker(p)
reqData = &MultipartData{
data: RawData{&data},
request: paramReq,
}
}
log.Println("Sending stylesheet-parameters request")
req := p.newResquest(API_STYLESHEET_PARAMETERS, ¶ms, reqData)
_, err = p.do(req, errorHandler(map[int]string{
400: "Stylesheet-parameters request is not valid",
}))
if err != nil {
return
}
for i, param := range params.Parameters {
desc := strings.Split(param.LongDesc, "\n")
params.Parameters[i].ShortDesc = desc[0]
// insert empty line after first line
if len(desc) > 1 {
if desc[1] != "" {
desc = append(desc[:1], append([]string{""}, desc[1:]...)...)
}
params.Parameters[i].LongDesc = strings.Join(desc, "\n")
}
// get data type definition
var paramType DataType
paramType, err = p.dataType(param.TypeAttr)
params.Parameters[i].Type = paramType
}
return
}
//Sends a Job query to the webservice
func (p Pipeline) Job(id string, messageSequence int) (job Job, err error) {
req := p.newResquest(API_JOB, &job, nil, id, messageSequence)
_, err = p.do(req, errorHandler(map[int]string{
404: "Job " + id + " not found",
}))
return
}
//Sends a Job query to the webservice
func (p Pipeline) Batch(id string) (jobs Jobs, err error) {
req := p.newResquest(API_BATCH, &jobs, nil, id)
_, err = p.do(req, errorHandler(map[int]string{
404: "Job " + id + " not found",
}))
return
}
//Sends a request to the server in order to get all the jobs
func (p Pipeline) Jobs() (jobs Jobs, err error) {
req := p.newResquest(API_JOBS, &jobs, nil)
_, err = p.do(req, defaultErrorHandler())
return
}
//Deletes a job
func (p Pipeline) DeleteJob(id string) (ok bool, err error) {
req := p.newResquest(API_DEL_JOB, nil, nil, id)
_, err = p.do(req, errorHandler(map[int]string{
404: "Job " + id + " not found",
}))
if err == nil {
ok = true
}
return
}
//Deletes a batch of jobs
func (p Pipeline) DeleteBatch(id string) (ok bool, err error) {
req := p.newResquest(API_DEL_BATCH, nil, nil, id)
_, err = p.do(req, errorHandler(map[int]string{
404: "Job batch " + id + " not found",
}))
ok = err == nil
return
}
//Overrides the xml decoder to get the writer
func resultClientMaker(p Pipeline) func() doer {
return func() doer {
cli := p.clientMaker()
cli.SetDecoderSupplier(func(r io.Reader) restclient.Decoder {
return NewWriterDecoder(r)
})
return cli
}
}
//Returns the results of the job as an array of bytes
func (p Pipeline) Results(id string, w io.Writer) (ok bool, err error) {
//check whether results are available
job := Job{}
req := p.newResquest(API_JOB, &job, nil, id, math.MaxInt32)
_, err = p.do(req, errorHandler(map[int]string{
404: "Job " + id + " not found",
}))
if err == nil {
if job.Results.Href == "" {
return false, err
} else {
//override the client maker
p.clientMaker = resultClientMaker(p)
req = p.newResquest(API_RESULT, w, nil, id)
_, err = p.do(req, errorHandler(map[int]string{
404: "Job " + id + " not found",
}))
}
}
return (err == nil), err
}
//Overrides the xml decoder to get raw data
func rawClientMaker(p Pipeline) func() doer {
return func() doer {
cli := p.clientMaker()
cli.SetDecoderSupplier(func(r io.Reader) restclient.Decoder {
return NewRawDataDecoder(r)
})
return cli
}
}
//Gets the log file for a job
func (p Pipeline) Log(id string) (data []byte, err error) {
p.clientMaker = rawClientMaker(p)
rd := &RawData{Data: new([]byte)}
req := p.newResquest(API_LOG, rd, nil, id)
_, err = p.do(req, errorHandler(map[int]string{
404: "Job " + id + " not found",
}))
if err != nil {
return nil, err
}
return *(rd.Data), nil
}
//Admin api
//Halts the ws
func (p Pipeline) Halt(key string) error {
//override the client maker
req := p.newResquest(API_HALT, nil, nil, key)
_, err := p.do(req, defaultErrorHandler())
return err
}
//Returns the list of clients
func (p Pipeline) Clients() (clients []Client, err error) {
clientsStr := Clients{}
req := p.newResquest(API_CLIENTS, &clientsStr, nil)
_, err = p.do(req, defaultErrorHandler())
if err != nil {
return
}
clients = clientsStr.Clients
return
}
//Creates a new client
func (p Pipeline) NewClient(in Client) (out Client, err error) {
req := p.newResquest(API_NEWCLIENT, &out, &in)
_, err = p.do(req, errorHandler(map[int]string{
400: fmt.Sprintf("Client with id %v may already exist", in.Id),
}))
return
}
//Retrieves a client using the its id
func (p Pipeline) Client(id string) (out Client, err error) {
req := p.newResquest(API_CLIENT, &out, nil, id)
_, err = p.do(req, errorHandler(map[int]string{
404: "Client with id " + id + " not found",
}))
return
}
//Deletes a client
func (p Pipeline) DeleteClient(id string) (ok bool, err error) {
req := p.newResquest(API_DELETECLIENT, nil, nil, id)
_, err = p.do(req, errorHandler(map[int]string{
404: "Client with id " + id + " not found",
}))
if err == nil {
ok = true
}
return
}
//Modifies a client with the new data TODO:include the id in the client structure
func (p Pipeline) ModifyClient(in Client, id string) (out Client, err error) {
req := p.newResquest(API_MODIFYCLIENT, &out, &in, id)
_, err = p.do(req, errorHandler(map[int]string{
404: "Client with id " + id + " not found",
}))
return
}
//Retrieves the list of different properties which describes the framework configuration
func (p Pipeline) Properties() (out []Property, err error) {
props := Properties{}
req := p.newResquest(API_PROPERTIES, &props, nil)
_, err = p.do(req, defaultErrorHandler())
if err != nil {
return
}
return props.Properties, nil
}
//Gets the physical size of the jobs
func (p Pipeline) Sizes() (sizes JobSizes, err error) {
req := p.newResquest(API_SIZE, &sizes, nil)
_, err = p.do(req, defaultErrorHandler())
if err != nil {
return
}
return sizes, nil
}
//Gets execution queue
func (p Pipeline) Queue() (jobs []QueueJob, err error) {
queue := Queue{}
req := p.newResquest(API_QUEUE, &queue, nil)
_, err = p.do(req, defaultErrorHandler())
if err != nil {
return
}
jobs = queue.Jobs
return jobs, nil
}
func (p Pipeline) MoveUp(jobId string) (jobs []QueueJob, err error) {
queue := Queue{}
req := p.newResquest(API_MOVE_UP, &queue, nil, jobId)
_, err = p.do(req, defaultErrorHandler())
if err != nil {
return
}
jobs = queue.Jobs
return jobs, nil
}
func (p Pipeline) MoveDown(jobId string) (jobs []QueueJob, err error) {
queue := Queue{}
req := p.newResquest(API_MOVE_DOWN, &queue, nil, jobId)
_, err = p.do(req, defaultErrorHandler())
if err != nil {
return
}
jobs = queue.Jobs
return jobs, nil
}