-
-
Notifications
You must be signed in to change notification settings - Fork 308
/
random1_func.go
163 lines (138 loc) · 4.89 KB
/
random1_func.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
// Mgmt
// Copyright (C) 2013-2021+ James Shubin and the project contributors
// Written by James Shubin <james@shubin.ca> and the project contributors
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package core // TODO: should this be in its own individual package?
import (
"crypto/rand"
"fmt"
"math/big"
"github.com/purpleidea/mgmt/lang/funcs"
"github.com/purpleidea/mgmt/lang/interfaces"
"github.com/purpleidea/mgmt/lang/types"
"github.com/purpleidea/mgmt/util/errwrap"
)
const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
func init() {
funcs.Register("random1", func() interfaces.Func { return &Random1Func{} })
}
// Random1Func returns one random string of a certain length.
// XXX: return a stream instead, and combine this with a first(?) function which
// takes the first value and then puts backpressure on the stream. This should
// notify parent functions somehow that their values are no longer required so
// that they can shutdown if possible. Maybe it should be returning a stream of
// floats [0,1] as well, which someone can later map to the alphabet that they
// want. Should random() take an interval to know how often to spit out values?
// It could also just do it once per second, and we could filter for less. If we
// want something high precision, we could add that in the future... We could
// name that "random" and this one can be "random1" until we deprecate it.
type Random1Func struct {
init *interfaces.Init
finished bool // did we send the random string?
closeChan chan struct{}
}
// ArgGen returns the Nth arg name for this function.
func (obj *Random1Func) ArgGen(index int) (string, error) {
seq := []string{"length"}
if l := len(seq); index >= l {
return "", fmt.Errorf("index %d exceeds arg length of %d", index, l)
}
return seq[index], nil
}
// Validate makes sure we've built our struct properly. It is usually unused for
// normal functions that users can use directly.
func (obj *Random1Func) Validate() error {
return nil
}
// Info returns some static info about itself.
func (obj *Random1Func) Info() *interfaces.Info {
return &interfaces.Info{
Pure: false,
Sig: types.NewType("func(length int) str"),
Err: obj.Validate(),
}
}
// generate generates a random string.
func generate(length uint16) (string, error) {
max := len(alphabet) - 1 // last index
output := ""
// FIXME: have someone verify this is cryptographically secure & correct
for i := uint16(0); i < length; i++ {
big, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
if err != nil {
return "", errwrap.Wrapf(err, "could not generate random string")
}
ix := big.Int64()
output += string(alphabet[ix])
}
if length != 0 && output == "" { // safety against empty strings
return "", fmt.Errorf("string is empty")
}
if uint16(len(output)) != length { // safety against weird bugs
return "", fmt.Errorf("random string is too short") // bug!
}
return output, nil
}
// Init runs some startup code for this function.
func (obj *Random1Func) Init(init *interfaces.Init) error {
obj.init = init
obj.closeChan = make(chan struct{})
return nil
}
// Stream returns the single value that was generated and then closes.
func (obj *Random1Func) Stream() error {
defer close(obj.init.Output) // the sender closes
var result string
for {
select {
case input, ok := <-obj.init.Input:
if !ok {
return nil // can't output any more
}
//if err := input.Type().Cmp(obj.Info().Sig.Input); err != nil {
// return errwrap.Wrapf(err, "wrong function input")
//}
if obj.finished {
// TODO: continue instead?
return fmt.Errorf("you can only pass a single input to random")
}
length := input.Struct()["length"].Int()
// TODO: if negative, randomly pick a length ?
if length < 0 {
return fmt.Errorf("can't generate a negative length")
}
var err error
if result, err = generate(uint16(length)); err != nil {
return err // no errwrap needed b/c helper func
}
case <-obj.closeChan:
return nil
}
select {
case obj.init.Output <- &types.StrValue{
V: result,
}:
// we only send one value, then wait for input to close
obj.finished = true
case <-obj.closeChan:
return nil
}
}
}
// Close runs some shutdown code for this function and turns off the stream.
func (obj *Random1Func) Close() error {
close(obj.closeChan)
return nil
}