// NewChaincodeHandler returns a new instance of the shim side handler. func newChaincodeHandler(peerChatStream PeerChaincodeStream, chaincode Chaincode) *Handler { v := &Handler{ ChatStream: peerChatStream, cc: chaincode, } v.responseChannel = make(map[string]chan pb.ChaincodeMessage) v.nextState = make(chan *nextStateInfo) // Create the shim side FSM v.FSM = fsm.NewFSM( "created", fsm.Events{ {Name: pb.ChaincodeMessage_REGISTERED.String(), Src: []string{"created"}, Dst: "established"}, {Name: pb.ChaincodeMessage_INIT.String(), Src: []string{"established"}, Dst: "init"}, {Name: pb.ChaincodeMessage_READY.String(), Src: []string{"established"}, Dst: "ready"}, {Name: pb.ChaincodeMessage_ERROR.String(), Src: []string{"init"}, Dst: "established"}, {Name: pb.ChaincodeMessage_RESPONSE.String(), Src: []string{"init"}, Dst: "init"}, {Name: pb.ChaincodeMessage_COMPLETED.String(), Src: []string{"init"}, Dst: "ready"}, {Name: pb.ChaincodeMessage_TRANSACTION.String(), Src: []string{"ready"}, Dst: "transaction"}, {Name: pb.ChaincodeMessage_COMPLETED.String(), Src: []string{"transaction"}, Dst: "ready"}, {Name: pb.ChaincodeMessage_ERROR.String(), Src: []string{"transaction"}, Dst: "ready"}, {Name: pb.ChaincodeMessage_RESPONSE.String(), Src: []string{"transaction"}, Dst: "transaction"}, {Name: pb.ChaincodeMessage_RESPONSE.String(), Src: []string{"ready"}, Dst: "ready"}, }, fsm.Callbacks{ "before_" + pb.ChaincodeMessage_REGISTERED.String(): func(e *fsm.Event) { v.beforeRegistered(e) }, "after_" + pb.ChaincodeMessage_RESPONSE.String(): func(e *fsm.Event) { v.afterResponse(e) }, "after_" + pb.ChaincodeMessage_ERROR.String(): func(e *fsm.Event) { v.afterError(e) }, "enter_init": func(e *fsm.Event) { v.enterInitState(e) }, "enter_transaction": func(e *fsm.Event) { v.enterTransactionState(e) }, }, ) return v }
// Create and return a new Node. channels for sending and receiving messages are setup. // And two goroutines are spawned Send and Receive to handle incoming and outgoing messages. func NewNode(conn net.Conn) *Node { n := new(Node) n.Client = NewClient(conn) n.ID = uuid.NewRandom() n.Name = n.ID.String() n.State = UNKNOWN n.fsm = fsm.NewFSM( n.State.S(), fsm.Events{ {Name: "offline", Src: StateList(ONLINE, READY, ASSIGNING, WORKING), Dst: OFFLINE.S()}, {Name: "online", Src: StateList(UNKNOWN, READY, OFFLINE), Dst: ONLINE.S()}, {Name: "ready", Src: StateList(ONLINE, WORKING, ASSIGNING), Dst: READY.S()}, {Name: "assign", Src: StateList(READY), Dst: ASSIGNING.S()}, {Name: "work", Src: StateList(ASSIGNING), Dst: WORKING.S()}, {Name: "service", Src: StateList(UNKNOWN, ONLINE, OFFLINE), Dst: SERVICE.S()}, }, fsm.Callbacks{ "after_event": func(e *fsm.Event) { n.afterEvent(e) }, "before_offline": func(e *fsm.Event) { n.beforeOffline(e) }, OFFLINE.S(): func(e *fsm.Event) { n.offlineNode(e) }, }, ) n.Send = make(chan *proto_msg.KamajiMessage) n.Receive = make(chan *proto_msg.KamajiMessage) n.done = make(chan bool) n.waitGroup = &sync.WaitGroup{} if n.Conn != nil { go n.messageTransmitter() go n.messageReciever() } return n }
// Create a new Command instance and return it. func NewCommand(name string, task *Task) *Command { c := new(Command) c.ID = uuid.NewRandom() c.Name = name c.State = UNKNOWN c.Completion = 0.0 c.created = time.Now() c.priority = 0 c.Task = task if task != nil { task.Commands = append(task.Commands, c) } c.FSM = fsm.NewFSM( c.State.S(), fsm.Events{ {Name: "ready", Src: StateList(UNKNOWN, STOPPED, ASSIGNING), Dst: READY.S()}, {Name: "assign", Src: StateList(READY), Dst: ASSIGNING.S()}, {Name: "start", Src: StateList(UNKNOWN, READY, ASSIGNING, STOPPED), Dst: WORKING.S()}, {Name: "restart", Src: StateList(DONE), Dst: WORKING.S()}, {Name: "finish", Src: StateList(WORKING), Dst: DONE.S()}, {Name: "stop", Src: StateList(WORKING), Dst: STOPPED.S()}, }, fsm.Callbacks{ "after_event": func(e *fsm.Event) { c.afterEvent(e) }, DONE.S(): func(e *fsm.Event) { c.finishCommand(e) }, }, ) return c }
func (self *Core) Start() { mlog.Info("starting core service ...") events := []fsm.EventDesc{ {Name: "import", Src: []string{"idle", "scanning"}, Dst: "scanning"}, {Name: "found", Src: []string{"scanning"}, Dst: "scanning"}, {Name: "scraped", Src: []string{"scanning"}, Dst: "scanning"}, {Name: "status", Src: []string{"idle", "scanning"}, Dst: "scanning"}, {Name: "finish", Src: []string{"scanning"}, Dst: "idle"}, } // some initialization self.fsm = fsm.NewFSM( "idle", events, fsm.Callbacks{ "import": self.importer, "found": self.found, "scraped": self.scraped, "finish": self.finish, }, ) self.context = message.Context{Message: "Idle", Backdrop: "/mAwd34SAC8KqBKRm2MwHPLhLDU5.jpg", Completed: false} go self.react() mlog.Info("core service started") }
func main() { fsm := fsm.NewFSM( "closed", fsm.Events{ {Name: "open", Src: []string{"closed"}, Dst: "open"}, {Name: "close", Src: []string{"open"}, Dst: "closed"}, }, fsm.Callbacks{}, ) fmt.Println(fsm.Current()) err := fsm.Event("open") if err != nil { fmt.Println(err) } fmt.Println(fsm.Current()) err = fsm.Event("close") if err != nil { fmt.Println(err) } fmt.Println(fsm.Current()) }
// NewPeerConnectionFSM creates and returns a PeerConnectionFSM func NewPeerConnectionFSM(to string) *PeerConnectionFSM { d := &PeerConnectionFSM{ To: to, } d.FSM = fsm.NewFSM( "created", fsm.Events{ {Name: "HELLO", Src: []string{"created"}, Dst: "established"}, {Name: "GET_PEERS", Src: []string{"established"}, Dst: "established"}, {Name: "PEERS", Src: []string{"established"}, Dst: "established"}, {Name: "PING", Src: []string{"established"}, Dst: "established"}, {Name: "DISCONNECT", Src: []string{"created", "established"}, Dst: "closed"}, }, fsm.Callbacks{ "enter_state": func(e *fsm.Event) { d.enterState(e) }, "before_HELLO": func(e *fsm.Event) { d.beforeHello(e) }, "after_HELLO": func(e *fsm.Event) { d.afterHello(e) }, "before_PING": func(e *fsm.Event) { d.beforePing(e) }, "after_PING": func(e *fsm.Event) { d.afterPing(e) }, }, ) return d }
func NewManager(_myId string, _members []string) *Manager { self := &Manager{ myId: _myId, members: _members, votes: make(Votes), threshold: util.ComputeQuorumThreshold(len(_members)), C: make(chan bool, 100), } self.state = fsm.NewFSM( "idle", fsm.Events{ {Name: "quorum", Src: []string{"idle", "elected"}, Dst: "electing"}, {Name: "complete", Src: []string{"electing"}, Dst: "elected"}, {Name: "next", Src: []string{"elected"}, Dst: "idle"}, }, fsm.Callbacks{ "electing": func(e *fsm.Event) { self.onElecting() }, "enter_elected": func(e *fsm.Event) { self.onElected(e.Args[0].(string), e.Args[1].(int64)) }, "leave_elected": func(e *fsm.Event) { self.view++ }, }, ) fmt.Printf("EM: Initializing with %d members and a quorum threshold %d\n", len(self.members), self.threshold) return self }
func newChaincodeSupportHandler(chaincodeSupport *ChaincodeSupport, peerChatStream PeerChaincodeStream) *Handler { v := &Handler{ ChatStream: peerChatStream, } v.chaincodeSupport = chaincodeSupport //we want this to block v.nextState = make(chan *nextStateInfo) v.FSM = fsm.NewFSM( createdstate, fsm.Events{ //Send REGISTERED, then, if deploy { trigger INIT(via INIT) } else { trigger READY(via COMPLETED) } {Name: pb.ChaincodeMessage_REGISTER.String(), Src: []string{createdstate}, Dst: establishedstate}, {Name: pb.ChaincodeMessage_INIT.String(), Src: []string{establishedstate}, Dst: initstate}, {Name: pb.ChaincodeMessage_READY.String(), Src: []string{establishedstate}, Dst: readystate}, {Name: pb.ChaincodeMessage_TRANSACTION.String(), Src: []string{readystate}, Dst: transactionstate}, {Name: pb.ChaincodeMessage_PUT_STATE.String(), Src: []string{transactionstate}, Dst: busyxactstate}, {Name: pb.ChaincodeMessage_DEL_STATE.String(), Src: []string{transactionstate}, Dst: busyxactstate}, {Name: pb.ChaincodeMessage_INVOKE_CHAINCODE.String(), Src: []string{transactionstate}, Dst: busyxactstate}, {Name: pb.ChaincodeMessage_PUT_STATE.String(), Src: []string{initstate}, Dst: busyinitstate}, {Name: pb.ChaincodeMessage_DEL_STATE.String(), Src: []string{initstate}, Dst: busyinitstate}, {Name: pb.ChaincodeMessage_INVOKE_CHAINCODE.String(), Src: []string{initstate}, Dst: busyinitstate}, {Name: pb.ChaincodeMessage_COMPLETED.String(), Src: []string{initstate, readystate, transactionstate}, Dst: readystate}, {Name: pb.ChaincodeMessage_GET_STATE.String(), Src: []string{readystate}, Dst: readystate}, {Name: pb.ChaincodeMessage_GET_STATE.String(), Src: []string{initstate}, Dst: initstate}, {Name: pb.ChaincodeMessage_GET_STATE.String(), Src: []string{busyinitstate}, Dst: busyinitstate}, {Name: pb.ChaincodeMessage_GET_STATE.String(), Src: []string{transactionstate}, Dst: transactionstate}, {Name: pb.ChaincodeMessage_GET_STATE.String(), Src: []string{busyxactstate}, Dst: busyxactstate}, {Name: pb.ChaincodeMessage_RANGE_QUERY_STATE.String(), Src: []string{readystate}, Dst: readystate}, {Name: pb.ChaincodeMessage_RANGE_QUERY_STATE.String(), Src: []string{initstate}, Dst: initstate}, {Name: pb.ChaincodeMessage_RANGE_QUERY_STATE.String(), Src: []string{busyinitstate}, Dst: busyinitstate}, {Name: pb.ChaincodeMessage_RANGE_QUERY_STATE.String(), Src: []string{transactionstate}, Dst: transactionstate}, {Name: pb.ChaincodeMessage_RANGE_QUERY_STATE.String(), Src: []string{busyxactstate}, Dst: busyxactstate}, {Name: pb.ChaincodeMessage_ERROR.String(), Src: []string{initstate}, Dst: endstate}, {Name: pb.ChaincodeMessage_ERROR.String(), Src: []string{transactionstate}, Dst: readystate}, {Name: pb.ChaincodeMessage_ERROR.String(), Src: []string{busyinitstate}, Dst: initstate}, {Name: pb.ChaincodeMessage_ERROR.String(), Src: []string{busyxactstate}, Dst: transactionstate}, {Name: pb.ChaincodeMessage_RESPONSE.String(), Src: []string{busyinitstate}, Dst: initstate}, {Name: pb.ChaincodeMessage_RESPONSE.String(), Src: []string{busyxactstate}, Dst: transactionstate}, }, fsm.Callbacks{ "before_" + pb.ChaincodeMessage_REGISTER.String(): func(e *fsm.Event) { v.beforeRegisterEvent(e, v.FSM.Current()) }, "before_" + pb.ChaincodeMessage_COMPLETED.String(): func(e *fsm.Event) { v.beforeCompletedEvent(e, v.FSM.Current()) }, "before_" + pb.ChaincodeMessage_INIT.String(): func(e *fsm.Event) { v.beforeInitState(e, v.FSM.Current()) }, "after_" + pb.ChaincodeMessage_GET_STATE.String(): func(e *fsm.Event) { v.afterGetState(e, v.FSM.Current()) }, "after_" + pb.ChaincodeMessage_RANGE_QUERY_STATE.String(): func(e *fsm.Event) { v.afterRangeQueryState(e, v.FSM.Current()) }, "after_" + pb.ChaincodeMessage_PUT_STATE.String(): func(e *fsm.Event) { v.afterPutState(e, v.FSM.Current()) }, "after_" + pb.ChaincodeMessage_DEL_STATE.String(): func(e *fsm.Event) { v.afterDelState(e, v.FSM.Current()) }, "after_" + pb.ChaincodeMessage_INVOKE_CHAINCODE.String(): func(e *fsm.Event) { v.afterInvokeChaincode(e, v.FSM.Current()) }, "enter_" + establishedstate: func(e *fsm.Event) { v.enterEstablishedState(e, v.FSM.Current()) }, "enter_" + initstate: func(e *fsm.Event) { v.enterInitState(e, v.FSM.Current()) }, "enter_" + readystate: func(e *fsm.Event) { v.enterReadyState(e, v.FSM.Current()) }, "enter_" + busyinitstate: func(e *fsm.Event) { v.enterBusyState(e, v.FSM.Current()) }, "enter_" + busyxactstate: func(e *fsm.Event) { v.enterBusyState(e, v.FSM.Current()) }, "enter_" + endstate: func(e *fsm.Event) { v.enterEndState(e, v.FSM.Current()) }, }, ) return v }
func main() { fsm := fsm.NewFSM( "idle", fsm.Events{ {Name: "scan", Src: []string{"idle"}, Dst: "scanning"}, {Name: "working", Src: []string{"scanning"}, Dst: "scanning"}, {Name: "situation", Src: []string{"scanning"}, Dst: "scanning"}, {Name: "situation", Src: []string{"idle"}, Dst: "idle"}, {Name: "finish", Src: []string{"scanning"}, Dst: "idle"}, }, fsm.Callbacks{ "scan": func(e *fsm.Event) { fmt.Println("after_scan: " + e.FSM.Current()) }, "working": func(e *fsm.Event) { fmt.Println("working: " + e.FSM.Current()) }, "situation": func(e *fsm.Event) { fmt.Println("situation: " + e.FSM.Current()) }, "finish": func(e *fsm.Event) { fmt.Println("finish: " + e.FSM.Current()) }, }, ) fmt.Println(fsm.Current()) err := fsm.Event("scan") if err != nil { fmt.Println(err) } fmt.Println("1:" + fsm.Current()) err = fsm.Event("working") if err != nil { fmt.Println(err) } fmt.Println("2:" + fsm.Current()) err = fsm.Event("situation") if err != nil { fmt.Println(err) } fmt.Println("3:" + fsm.Current()) err = fsm.Event("finish") if err != nil { fmt.Println(err) } fmt.Println("4:" + fsm.Current()) }
// NewPeerHandler returns a new Peer handler // Is instance of HandlerFactory func NewPeerHandler(coord MessageHandlerCoordinator, stream ChatStream, initiatedStream bool, nextHandler MessageHandler) (MessageHandler, error) { d := &Handler{ ChatStream: stream, initiatedStream: initiatedStream, Coordinator: coord, } d.doneChan = make(chan struct{}) d.snapshotRequestHandler = newSyncStateSnapshotRequestHandler() d.syncStateDeltasRequestHandler = newSyncStateDeltasHandler() d.syncBlocksRequestHandler = newSyncBlocksRequestHandler() d.FSM = fsm.NewFSM( "created", fsm.Events{ {Name: pb.Message_DISC_HELLO.String(), Src: []string{"created"}, Dst: "established"}, {Name: pb.Message_DISC_GET_PEERS.String(), Src: []string{"established"}, Dst: "established"}, {Name: pb.Message_DISC_PEERS.String(), Src: []string{"established"}, Dst: "established"}, {Name: pb.Message_SYNC_BLOCK_ADDED.String(), Src: []string{"established"}, Dst: "established"}, {Name: pb.Message_SYNC_GET_BLOCKS.String(), Src: []string{"established"}, Dst: "established"}, {Name: pb.Message_SYNC_BLOCKS.String(), Src: []string{"established"}, Dst: "established"}, {Name: pb.Message_SYNC_STATE_GET_SNAPSHOT.String(), Src: []string{"established"}, Dst: "established"}, {Name: pb.Message_SYNC_STATE_SNAPSHOT.String(), Src: []string{"established"}, Dst: "established"}, {Name: pb.Message_SYNC_STATE_GET_DELTAS.String(), Src: []string{"established"}, Dst: "established"}, {Name: pb.Message_SYNC_STATE_DELTAS.String(), Src: []string{"established"}, Dst: "established"}, }, fsm.Callbacks{ "enter_state": func(e *fsm.Event) { d.enterState(e) }, "before_" + pb.Message_DISC_HELLO.String(): func(e *fsm.Event) { d.beforeHello(e) }, "before_" + pb.Message_DISC_GET_PEERS.String(): func(e *fsm.Event) { d.beforeGetPeers(e) }, "before_" + pb.Message_DISC_PEERS.String(): func(e *fsm.Event) { d.beforePeers(e) }, "before_" + pb.Message_SYNC_BLOCK_ADDED.String(): func(e *fsm.Event) { d.beforeBlockAdded(e) }, "before_" + pb.Message_SYNC_GET_BLOCKS.String(): func(e *fsm.Event) { d.beforeSyncGetBlocks(e) }, "before_" + pb.Message_SYNC_BLOCKS.String(): func(e *fsm.Event) { d.beforeSyncBlocks(e) }, "before_" + pb.Message_SYNC_STATE_GET_SNAPSHOT.String(): func(e *fsm.Event) { d.beforeSyncStateGetSnapshot(e) }, "before_" + pb.Message_SYNC_STATE_SNAPSHOT.String(): func(e *fsm.Event) { d.beforeSyncStateSnapshot(e) }, "before_" + pb.Message_SYNC_STATE_GET_DELTAS.String(): func(e *fsm.Event) { d.beforeSyncStateGetDeltas(e) }, "before_" + pb.Message_SYNC_STATE_DELTAS.String(): func(e *fsm.Event) { d.beforeSyncStateDeltas(e) }, }, ) // If the stream was initiated from this Peer, send an Initial HELLO message if d.initiatedStream { // Send intiial Hello helloMessage, err := d.Coordinator.NewOpenchainDiscoveryHello() if err != nil { return nil, fmt.Errorf("Error getting new HelloMessage: %s", err) } if err := d.SendMessage(helloMessage); err != nil { return nil, fmt.Errorf("Error creating new Peer Handler, error returned sending %s: %s", pb.Message_DISC_HELLO, err) } } return d, nil }
func NewController(_id string, _peers IdentityMap, _connMgr *ConnectionManager) *Controller { var members []string for _, peer := range _peers { members = append(members, peer.Id) } self := &Controller{ peers: _peers, connMgr: _connMgr, myId: _id, activePeers: make(map[string]*Peer), quorumThreshold: util.ComputeQuorumThreshold(len(_peers)) - 1, // We don't include ourselves timer: time.NewTimer(0), pulse: time.NewTicker(1), electionManager: election.NewManager(_id, members), minTmo: 500, maxTmo: 1000, } <-self.timer.C // drain the initial event self.pulse.Stop() <-self.pulse.C // drain the initial event self.state = fsm.NewFSM( "convening", fsm.Events{ {Name: "quorum", Src: []string{"convening"}, Dst: "initializing"}, {Name: "quorum-lost", Src: []string{"initializing", "electing", "electing-restart", "following", "leading"}, Dst: "convening"}, {Name: "elected-self", Src: []string{"initializing", "electing"}, Dst: "leading"}, {Name: "elected-other", Src: []string{"initializing", "electing"}, Dst: "following"}, {Name: "timeout", Src: []string{"initializing", "following", "electing"}, Dst: "electing"}, {Name: "election", Src: []string{"following", "leading"}, Dst: "electing"}, {Name: "heartbeat", Src: []string{"following"}, Dst: "following"}, }, fsm.Callbacks{ "convening": func(e *fsm.Event) { self.onConvening() }, "enter_initializing": func(e *fsm.Event) { self.onInitializing() }, "leave_initializing": func(e *fsm.Event) { self.timer.Stop() }, "enter_following": func(e *fsm.Event) { self.onEnterFollowing() }, "leave_following": func(e *fsm.Event) { self.onLeaveFollowing() }, "enter_electing": func(e *fsm.Event) { self.onElecting() }, "leave_electing": func(e *fsm.Event) { self.timer.Stop() }, "enter_leading": func(e *fsm.Event) { self.onEnterLeading() }, "leave_leading": func(e *fsm.Event) { self.onLeaveLeading() }, "heartbeat": func(e *fsm.Event) { self.onHeartBeat(e.Args[0].(string), e.Args[1].(int64)) }, "before_timeout": func(e *fsm.Event) { self.onTimeout() }, }, ) return self }
func NewDoor(to string) *Door { d := &Door{ To: to, } d.FSM = fsm.NewFSM( "closed", fsm.Events{ {Name: "open", Src: []string{"closed"}, Dst: "open"}, {Name: "close", Src: []string{"open"}, Dst: "closed"}, }, fsm.Callbacks{ "enter_state": func(e *fsm.Event) { d.enterState(e) }, }, ) return d }
// NewChaincodeHandler returns a new instance of the shim side handler. func newChaincodeHandler(to string, peerChatStream PeerChaincodeStream, chaincode Chaincode) *Handler { v := &Handler{ To: to, ChatStream: peerChatStream, cc: chaincode, } v.responseChannel = make(map[string]chan pb.ChaincodeMessage) v.isTransaction = make(map[string]bool) // Create the shim side FSM v.FSM = fsm.NewFSM( "created", fsm.Events{ {Name: pb.ChaincodeMessage_REGISTERED.String(), Src: []string{"created"}, Dst: "established"}, {Name: pb.ChaincodeMessage_INIT.String(), Src: []string{"established"}, Dst: "init"}, {Name: pb.ChaincodeMessage_READY.String(), Src: []string{"established"}, Dst: "ready"}, {Name: pb.ChaincodeMessage_ERROR.String(), Src: []string{"init"}, Dst: "established"}, {Name: pb.ChaincodeMessage_RESPONSE.String(), Src: []string{"init"}, Dst: "init"}, {Name: pb.ChaincodeMessage_COMPLETED.String(), Src: []string{"init"}, Dst: "ready"}, {Name: pb.ChaincodeMessage_TRANSACTION.String(), Src: []string{"ready"}, Dst: "transaction"}, {Name: pb.ChaincodeMessage_COMPLETED.String(), Src: []string{"transaction"}, Dst: "ready"}, {Name: pb.ChaincodeMessage_ERROR.String(), Src: []string{"transaction"}, Dst: "ready"}, {Name: pb.ChaincodeMessage_RESPONSE.String(), Src: []string{"transaction"}, Dst: "transaction"}, {Name: pb.ChaincodeMessage_QUERY.String(), Src: []string{"transaction"}, Dst: "transaction"}, {Name: pb.ChaincodeMessage_QUERY.String(), Src: []string{"ready"}, Dst: "ready"}, {Name: pb.ChaincodeMessage_RESPONSE.String(), Src: []string{"ready"}, Dst: "ready"}, }, fsm.Callbacks{ "before_" + pb.ChaincodeMessage_REGISTERED.String(): func(e *fsm.Event) { v.beforeRegistered(e) }, //"after_" + pb.ChaincodeMessage_INIT.String(): func(e *fsm.Event) { v.beforeInit(e) }, //"after_" + pb.ChaincodeMessage_TRANSACTION.String(): func(e *fsm.Event) { v.beforeTransaction(e) }, "after_" + pb.ChaincodeMessage_RESPONSE.String(): func(e *fsm.Event) { v.afterResponse(e) }, "after_" + pb.ChaincodeMessage_ERROR.String(): func(e *fsm.Event) { v.afterError(e) }, "enter_init": func(e *fsm.Event) { v.enterInitState(e) }, "enter_transaction": func(e *fsm.Event) { v.enterTransactionState(e) }, //"enter_ready": func(e *fsm.Event) { v.enterReadyState(e) }, "after_" + pb.ChaincodeMessage_COMPLETED.String(): func(e *fsm.Event) { v.afterCompleted(e) }, "before_" + pb.ChaincodeMessage_QUERY.String(): func(e *fsm.Event) { v.beforeQuery(e) }, //only checks for QUERY }, ) return v }
func NewConnection(conn *net.UDPConn, raddr *net.UDPAddr, local, remote *CryptoState) *Connection { if remote == nil { remote = NewCryptoState(new(KeyPair), nil, false) } if local == nil { panic("local is nil, fixme") return nil } c := &Connection{ conn: conn, raddr: raddr, isEstablished: false, local: local, remote: remote, rand: rand.Reader, } c.state = fsm.NewFSM("Reset", serverEvents, c.serverEventCallbacks()) return c }
// NewJob create a new Job struct, generates a uuid for it and returns the job. func NewJob(name string) *Job { j := new(Job) j.ID = uuid.NewRandom() j.Name = name j.State = UNKNOWN j.Completion = 0.0 j.Children = []*Task{} j.created = time.Now() j.priority = 0 j.FSM = fsm.NewFSM( j.State.String(), fsm.Events{ {Name: "ready", Src: StateList(UNKNOWN, STOPPED), Dst: READY.S()}, {Name: "start", Src: StateList(READY), Dst: WORKING.S()}, {Name: "finish", Src: StateList(WORKING), Dst: DONE.S()}, {Name: "restart", Src: StateList(DONE), Dst: WORKING.S()}, {Name: "stop", Src: StateList(WORKING), Dst: STOPPED.S()}, }, fsm.Callbacks{ "after_event": func(e *fsm.Event) { j.afterEvent(e) }, }, ) return j }
func GetNextState(currentState, event string) (string, []string) { initialState := currentState notProceedingEvents := map[string]bool{ "NotInterested": true, "ClosedLost": true, "SWJobCancelled": true, "Unresponsive": true, } disqualifiedEvent := map[string]bool{ "Disqualified": true, "Insufficient Credit": true, "Non-ownership": true, } if notProceedingEvents[event] { initialState = "NotProceeding" } else if disqualifiedEvent[event] { initialState = "Disqualified" } fsm := fsm.NewFSM( initialState, fsm.Events{ { Name: "OutboundTask", Src: []string{state["Attempting-Contact:Open"]}, Dst: state["Attempting-Contact:Contacted"], }, { Name: "RequiredDealFieldsFilled", Src: []string{state["Attempting-Contact:Open"], state["Attempting-Contact:Contacted"]}, Dst: state["Qualification:DealInfoVerified"], }, { Name: "ConsultationScheduled", Src: []string{state["Qualification:DealInfoVerified"]}, Dst: state["Qualification:ConsultationScheduled"], }, { Name: "DealUsageNotNull", Src: []string{state["Attempting-Contact:Contacted"], state["Qualification:DealInfoVerified"]}, Dst: state["Consultation:UtilityUsageCollected"], }, { Name: "DealUsageNotNull", Src: []string{state["Qualification:ConsultationScheduled"]}, Dst: state["Consultation:UtilityUsageCollected"], }, { Name: "CreditPassed", Src: []string{state["Qualification:ConsultationScheduled"]}, Dst: state["Consultation:CreditPassed"], }, { Name: "CreditPassed", Src: []string{state["Consultation:UtilityUsageCollected"], state["Consultation:InitialSysDesign"], state["Consultation:ProposalPresented"]}, Dst: state["Consultation:CreditPassed"], }, { Name: "DesignGenerated", Src: []string{state["Qualification:ConsultationScheduled"], state["Consultation:UtilityUsageCollected"], state["Consultation:CreditPassed"]}, Dst: state["Consultation:InitialSysDesign"], }, { Name: "PresentationOpened", Src: []string{state["Consultation:CreditPassed"], state["Consultation:InitialSysDesign"]}, Dst: state["Consultation:Presented"], }, { Name: "IntialContractSigned", Src: []string{state["Consultation:CreditPassed"], state["Consultation:Presented"]}, Dst: state["Consultation:ContractSigned"], }, }, fsm.Callbacks{ "before_IntialContractSigned": func(e *fsm.Event) { }, "onNotProceeding": func(e *fsm.Event) { fmt.Printf("After Not Proceeding") }, "outbound": func(e *fsm.Event) { fmt.Println("after_scan: " + e.FSM.Current()) }, "working": func(e *fsm.Event) { fmt.Println("working: " + e.FSM.Current()) }, "situation": func(e *fsm.Event) { fmt.Println("situation: " + e.FSM.Current()) }, "finish": func(e *fsm.Event) { fmt.Println("finish: " + e.FSM.Current()) }, "onenterstate": func(e *fsm.Event) { fmt.Println("In All states: " + e.FSM.Current()) }, }, ) fsm.Event(event) var possibleEvents []string for k, _ := range state { if fsm.Can(k) { possibleEvents = append(possibleEvents, k) } } return fsm.Current(), possibleEvents }
// Decode decodes the input reader into the config pointer func (d *Decoder) Decode(config *Config) error { tokenBuffer := "" expressionBuffer := "" conditionalNesting := 0 errChan := make(chan error) conditionName := "" var lastOp Operation = nil parserState := fsm.NewFSM( "section", fsm.Events{ {Name: "input", Src: []string{"section"}, Dst: "section_start"}, {Name: "output", Src: []string{"section"}, Dst: "section_start"}, {Name: "filter", Src: []string{"section"}, Dst: "section_start"}, {Name: "{", Src: []string{"section_start"}, Dst: "entity"}, {Name: "}", Src: []string{"entity"}, Dst: "section"}, {Name: "if", Src: []string{"entity"}, Dst: "cond_start"}, {Name: "else", Src: []string{"entity"}, Dst: "cond_start"}, {Name: "{", Src: []string{"cond_start"}, Dst: "entity"}, {Name: "driver", Src: []string{"entity"}, Dst: "entity_start"}, {Name: "{", Src: []string{"entity_start"}, Dst: "driver"}, {Name: "}", Src: []string{"driver"}, Dst: "entity"}, {Name: "key", Src: []string{"driver"}, Dst: "key_start"}, {Name: "=>", Src: []string{"key_start"}, Dst: "value"}, {Name: "val", Src: []string{"value"}, Dst: "driver"}, }, fsm.Callbacks{ "leave_cond_start": func(e *fsm.Event) { conditionalNesting++ }, "leave_entity": func(e *fsm.Event) { if e.Dst == "section" { if conditionalNesting != 0 { conditionalNesting-- e.Cancel() } } if lastOp != nil && e.Event == "}" { lastOp = lastOp.Parent() } }, "leave_driver": func(e *fsm.Event) { if lastOp != nil && e.Event == "}" { lastOp = lastOp.Parent() } }, "enter_section": func(e *fsm.Event) { if conditionalNesting != 0 { errChan <- fmt.Errorf("Empty if/else branch") } }, "enter_cond_start": func(e *fsm.Event) { conditionName = e.Event }, }, ) var buffer []byte = make([]byte, 2) var err error var n int var lastKey string = "" r := d.reader for n, err = r.Read(buffer); err == nil && n > 0; n, err = r.Read(buffer) { for i := 0; i < n; i++ { runeValue, width := utf8.DecodeRuneInString(string(buffer[i:])) if (parserState.Current() != "value" && unicode.IsSpace(runeValue)) || (parserState.Current() == "value" && (uint32(runeValue) == '\n')) { if tokenBuffer != "" { if strings.HasPrefix(parserState.Current(), "section") { if parserState.Can(tokenBuffer) { parserState.Event(tokenBuffer) } else { return fmt.Errorf("Unexpected Token %s", tokenBuffer) } if tokenBuffer != "}" && tokenBuffer != "{" { if tokenBuffer == "input" { config.Input = NewSection(lastOp, "input") lastOp = config.Input } else if tokenBuffer == "output" { config.Output = NewSection(lastOp, "output") lastOp = config.Output } else if tokenBuffer == "filter" { config.Filter = NewSection(lastOp, "filter") lastOp = config.Filter } } } else if strings.HasPrefix(parserState.Current(), "entity") { if parserState.Can(tokenBuffer) { parserState.Event(tokenBuffer) } else { if tokenBuffer == "{}" { parserState.Event("{") parserState.Event("}") tokenBuffer = "" } else if parserState.Can("driver") { l := NewPlugin(lastOp, tokenBuffer) lastOp.Add(l) lastOp = l parserState.Event("driver") } else { return fmt.Errorf("Unexpected Token %s", tokenBuffer) } } } else if strings.HasPrefix(parserState.Current(), "driver") { if parserState.Can(tokenBuffer) { parserState.Event(tokenBuffer) } else { lastKey = tokenBuffer parserState.Event("key") } } else if strings.HasPrefix(parserState.Current(), "key") { if parserState.Can(tokenBuffer) { parserState.Event(tokenBuffer) } else { return fmt.Errorf("Unexpected Token %s", tokenBuffer) } } else if strings.HasPrefix(parserState.Current(), "value") { lastOp.(*Plugin).Set(lastKey, strings.Trim(tokenBuffer, " ")) parserState.Event("val") } else if strings.HasPrefix(parserState.Current(), "cond") { if parserState.Can(tokenBuffer) { l := NewBranch(lastOp, conditionName, expressionBuffer) lastOp.Add(l) lastOp = l parserState.Event(tokenBuffer) expressionBuffer = "" } else if parserState.Current() == "cond_start" { expressionBuffer += tokenBuffer } } } tokenBuffer = "" } else { tokenBuffer += string(buffer[i : i+width]) } } } select { case e := <-errChan: return e default: } if err != nil && err != io.EOF { return err } if parserState.Current() != "section" { return fmt.Errorf("Error parsing config. Unclosed entity") } return nil }