forked from grailbio/go-netdicom
-
Notifications
You must be signed in to change notification settings - Fork 3
/
servicedispatcher.go
203 lines (179 loc) · 6.29 KB
/
servicedispatcher.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
package netdicom
import (
"fmt"
"sync"
"github.com/grailbio/go-dicom/dicomlog"
"github.com/grailbio/go-netdicom/dimse"
)
// serviceDispatcher multiplexes statemachine upcall events to DIMSE commands.
type serviceDispatcher struct {
label string // for logging.
downcallCh chan stateEvent // for sending PDUs to the statemachine.
mu sync.Mutex
//assure that serviceDispatcher is closed once
closeOnce sync.Once
// Set of active DIMSE commands running. Keys are message IDs.
activeCommands map[dimse.MessageID]*serviceCommandState // guarded by mu
// A callback to be called when a dimse request message arrives. Keys
// are DIMSE CommandField. The callback typically creates a new command
// by calling findOrCreateCommand.
streamCallbacks map[int]serviceStreamCallback // guarded by mu
// The last message ID used in newCommand(). Used to avoid creating duplicate
// IDs.
lastMessageID dimse.MessageID
}
type serviceCallback func(msg dimse.Message, data []byte, cs *serviceCommandState)
type serviceStreamCallback func(msg dimse.Message, dataChan chan []byte, cs *serviceCommandState)
// Per-DIMSE-command state.
type serviceCommandState struct {
disp *serviceDispatcher // Parent.
messageID dimse.MessageID // Command's MessageID.
context contextManagerEntry // Transfersyntax/sopclass for this command.
cm *contextManager // For looking up context -> transfersyntax/sopclass mappings
// upcallCh streams command+data for this messageID.
upcallCh chan upcallEvent
}
// Send a command+data combo to the remote peer. data may be nil.
func (cs *serviceCommandState) sendMessage(cmd dimse.Message, data []byte) {
if s := cmd.GetStatus(); s != nil && s.Status != dimse.StatusSuccess && s.Status != dimse.StatusPending {
dicomlog.Vprintf(0, "dicom.serviceDispatcher(%s): Sending DIMSE error: %v", cs.disp.label, cmd)
} else {
dicomlog.Vprintf(1, "dicom.serviceDispatcher(%s): Sending DIMSE message: %v", cs.disp.label, cmd)
}
payload := &stateEventDIMSEPayload{
abstractSyntaxName: cs.context.abstractSyntaxUID,
command: cmd,
data: data,
}
cs.disp.downcallCh <- stateEvent{
event: evt09,
pdu: nil,
conn: nil,
dimsePayload: payload,
}
}
func (disp *serviceDispatcher) findOrCreateCommand(
msgID dimse.MessageID,
cm *contextManager,
context contextManagerEntry) (*serviceCommandState, bool) {
disp.mu.Lock()
defer disp.mu.Unlock()
if cs, ok := disp.activeCommands[msgID]; ok {
return cs, true
}
cs := &serviceCommandState{
disp: disp,
messageID: msgID,
cm: cm,
context: context,
upcallCh: make(chan upcallEvent, 128),
}
disp.activeCommands[msgID] = cs
dicomlog.Vprintf(1, "dicom.serviceDispatcher(%s): Start command %+v", disp.label, cs)
return cs, false
}
// Create a new serviceCommandState with an unused message ID. Returns an error
// if it fails to allocate a message ID.
func (disp *serviceDispatcher) newCommand(
cm *contextManager, context contextManagerEntry) (*serviceCommandState, error) {
disp.mu.Lock()
defer disp.mu.Unlock()
for msgID := disp.lastMessageID + 1; msgID != disp.lastMessageID; msgID++ {
if _, ok := disp.activeCommands[msgID]; ok {
continue
}
cs := &serviceCommandState{
disp: disp,
messageID: msgID,
cm: cm,
context: context,
upcallCh: make(chan upcallEvent, 128),
}
disp.activeCommands[msgID] = cs
disp.lastMessageID = msgID
dicomlog.Vprintf(1, "dicom.serviceDispatcher: Start new command %+v", cs)
return cs, nil
}
return nil, fmt.Errorf("Failed to allocate a message ID (too many outstading?)")
}
func (disp *serviceDispatcher) deleteCommand(cs *serviceCommandState) {
disp.mu.Lock()
dicomlog.Vprintf(1, "dicom.serviceDispatcher(%s): Finish provider command %v", disp.label, cs.messageID)
if _, ok := disp.activeCommands[cs.messageID]; !ok {
panic(fmt.Sprintf("cs %+v", cs))
}
delete(disp.activeCommands, cs.messageID)
disp.mu.Unlock()
}
func (disp *serviceDispatcher) registerStreamCallback(commandField int, cb serviceStreamCallback) {
disp.mu.Lock()
disp.streamCallbacks[commandField] = cb
disp.mu.Unlock()
}
func (disp *serviceDispatcher) registerCallback(commandField int, cb serviceCallback) {
streamCallback := func(msg dimse.Message, dataCh chan []byte, cs *serviceCommandState) {
var data []byte
for bytes := range dataCh {
data = append(data, bytes...)
}
cb(msg, data, cs)
}
disp.mu.Lock()
disp.streamCallbacks[commandField] = streamCallback
disp.mu.Unlock()
}
func (disp *serviceDispatcher) unregisterCallback(commandField int) {
disp.mu.Lock()
delete(disp.streamCallbacks, commandField)
disp.mu.Unlock()
}
func (disp *serviceDispatcher) handleEvent(event upcallEvent) {
if event.eventType == upcallEventHandshakeCompleted {
return
}
doassert(event.eventType == upcallEventData)
doassert(event.command != nil)
context, err := event.cm.lookupByContextID(event.contextID)
if err != nil {
dicomlog.Vprintf(0, "dicom.serviceDispatcher(%s): Invalid context ID %d: %v", disp.label, event.contextID, err)
disp.downcallCh <- stateEvent{event: evt19, pdu: nil, err: err}
return
}
messageID := event.command.GetMessageID()
dc, found := disp.findOrCreateCommand(messageID, event.cm, context)
if found {
dicomlog.Vprintf(1, "dicom.serviceDispatcher(%s): Forwarding command to existing command: %+v %+v", disp.label, event.command, dc)
dc.upcallCh <- event
dicomlog.Vprintf(1, "dicom.serviceDispatcher(%s): Done forwarding command to existing command: %+v %+v", disp.label, event.command, dc)
return
}
disp.mu.Lock()
cb := disp.streamCallbacks[event.command.CommandField()]
disp.mu.Unlock()
go func() {
if cb != nil {
cb(event.command, event.stream, dc)
}
disp.deleteCommand(dc)
}()
}
// Must be called exactly once to shut down the dispatcher.
func (disp *serviceDispatcher) close() {
disp.closeOnce.Do(func() {
disp.mu.Lock()
for _, cs := range disp.activeCommands {
close(cs.upcallCh)
}
disp.mu.Unlock()
})
// TODO(saito): prevent new command from launching.
}
func newServiceDispatcher(label string) *serviceDispatcher {
return &serviceDispatcher{
label: label,
downcallCh: make(chan stateEvent, 128),
activeCommands: make(map[dimse.MessageID]*serviceCommandState),
streamCallbacks: make(map[int]serviceStreamCallback),
lastMessageID: 123,
}
}