-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
180 lines (164 loc) · 5.59 KB
/
main.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
package main
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/antongulenko/golib"
"github.com/bitflow-stream/go-bitflow/bitflow"
"github.com/bitflow-stream/go-bitflow/script/plugin"
"github.com/bitflow-stream/go-bitflow/script/reg"
"github.com/bitflow-stream/go-bitflow/script/script"
"github.com/bitflow-stream/go-bitflow/script/script_go"
defaultPlugin "github.com/bitflow-stream/go-bitflow/steps/bitflow-plugin-default-steps"
log "github.com/sirupsen/logrus"
)
const (
fileFlag = "f"
BitflowScriptSuffix = ".bf"
)
func main() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s <flags> <bitflow script>\nAll flags must be defined before the first non-flag parameter.\nFlags:\n", os.Args[0])
flag.PrintDefaults()
}
fix_arguments(&os.Args)
os.Exit(do_main())
}
func fix_arguments(argsPtr *[]string) {
if n := golib.ParseHashbangArgs(argsPtr); n > 0 {
// Insert -f before the script file, if necessary
args := *argsPtr
if args[n-1] != "-"+fileFlag && args[n-1] != "--"+fileFlag {
args = append(args, "") // Extend by one entry
copy(args[n+1:], args[n:])
args[n] = "-" + fileFlag
*argsPtr = args
}
}
}
func do_main() int {
printAnalyses := flag.Bool("print-analyses", false, "Print a list of available analyses and exit.")
printPipeline := flag.Bool("print-pipeline", false, "Print the parsed pipeline and exit. Can be used to verify the input script.")
printPipelineSchedulingHints := flag.Bool("print-scheduling-hints", false, "Print the subpipelines with scheduling hints as json and exit.")
printCapabilities := flag.Bool("capabilities", false, "Print the capabilities of this pipeline in JSON form and exit.")
useNewScript := flag.Bool("new", false, "Use the new script parser for processing the input script.")
scriptFile := ""
var pluginPaths golib.StringSlice
flag.Var(&pluginPaths, "p", "Plugins to load for additional functionality")
flag.StringVar(&scriptFile, fileFlag, "", "File to read a Bitflow script from (alternative to providing the script on the command line)")
registry := reg.NewProcessorRegistry()
bitflow.RegisterGolibFlags()
registry.Endpoints.RegisterFlags()
flag.Parse()
golib.ConfigureLogging()
golib.Checkerr(load_plugins(registry, pluginPaths))
if *printCapabilities {
golib.Checkerr(registry.PrintJsonCapabilities(os.Stdout))
return 0
}
if *printAnalyses {
fmt.Printf("Available analysis steps:\n%v\n", registry.PrintAllAnalyses())
return 0
}
rawScript, err := get_script(flag.Args(), scriptFile)
golib.Checkerr(err)
if *printPipelineSchedulingHints {
return convertAndPrintSchedulingHints(rawScript)
}
make_pipeline := make_pipeline_old
if *useNewScript {
log.Println("Running using new ANTLR script implementation")
make_pipeline = make_pipeline_new
}
pipe, err := make_pipeline(registry, rawScript)
if err != nil {
log.Errorln(err)
golib.Fatalln("Use -print-analyses to print all available analysis steps.")
}
defer golib.ProfileCpu()()
for _, str := range pipe.FormatLines() {
log.Println(str)
}
if *printPipeline {
return 0
}
return pipe.StartAndWait()
}
func convertAndPrintSchedulingHints(rawScript string) int {
scripts, errs := new(script.BitflowScriptScheduleParser).ParseScript(rawScript)
if errs.NilOrError() != nil {
log.Println(errs.Error())
return 1
}
j, err := JSONMarshal(scripts)
if err != nil {
log.Println(err)
return 1
}
fmt.Println(string(j))
return 0
}
func JSONMarshal(t interface{}) ([]byte, error) {
buffer := &bytes.Buffer{}
encoder := json.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
err := encoder.Encode(t)
return buffer.Bytes(), err
}
func get_script(parsedArgs []string, scriptFile string) (string, error) {
if scriptFile != "" && len(parsedArgs) > 0 {
return "", errors.New("Please provide a bitflow pipeline script either via -f or as parameter, not both.")
}
if len(parsedArgs) == 1 && strings.HasSuffix(parsedArgs[0], BitflowScriptSuffix) {
// Special case when passing a single existing .bf file as positional argument: Treat it as a script file
info, err := os.Stat(parsedArgs[0])
if err == nil && info.Mode().IsRegular() {
scriptFile = parsedArgs[0]
}
}
var rawScript string
if scriptFile != "" {
scriptBytes, err := ioutil.ReadFile(scriptFile)
if err != nil {
return "", fmt.Errorf("Error reading bitflow script file %v: %v", scriptFile, err)
}
rawScript = string(scriptBytes)
} else {
rawScript = strings.TrimSpace(strings.Join(parsedArgs, " "))
}
if rawScript == "" {
return "", errors.New("Please provide a bitflow pipeline script via -f or directly as parameter.")
}
return rawScript, nil
}
func make_pipeline_old(registry reg.ProcessorRegistry, scriptStr string) (*bitflow.SamplePipeline, error) {
queryBuilder := script_go.PipelineBuilder{registry}
parser := script_go.NewParser(bytes.NewReader([]byte(scriptStr)))
pipe, err := parser.Parse()
if err != nil {
return nil, err
}
return queryBuilder.MakePipeline(pipe)
}
func make_pipeline_new(registry reg.ProcessorRegistry, scriptStr string) (*bitflow.SamplePipeline, error) {
s, err := (&script.BitflowScriptParser{Registry: registry}).ParseScript(scriptStr)
return s, err.NilOrError()
}
func load_plugins(registry reg.ProcessorRegistry, pluginPaths []string) error {
loadedNames := make(map[string]bool)
for _, path := range pluginPaths {
if name, err := plugin.LoadPlugin(registry, path); err != nil {
return fmt.Errorf("Failed to load plugin %v: %v", path, err)
} else {
loadedNames[name] = true
}
}
// Load the default pipeline steps
// TODO add a plugin discovery mechanism
return defaultPlugin.Plugin.Init(registry)
}