Writing an SCU
How to talk to a PACS, a modality or any DICOM peer as a client: verify it,
send it instances, query it and retrieve from it, in Go with
network.SCU
and on the command line. It assumes the terms of
Network concepts.
Overview
An SCU is made from an
SCUConfig,
associates once, runs any number of operations, and releases.
| Operation | Go | Command |
|---|---|---|
| Verification (C‑ECHO) | Echo | go-dicom echoscu |
| Send an instance (C‑STORE) | Store, StoreStream | go-dicom storescu |
| Query (C‑FIND) | Find, FindWithSOPClass, FindEach | go-dicom findscu |
| Retrieve to a third AE (C‑MOVE) | Move, MoveWithSOPClass | go-dicom movescu |
| Retrieve on this association (C‑GET) | Get, GetWithSOPClass | go-dicom getscu |
| Stop a query or retrieve (C‑CANCEL) | Cancel, or end the context of FindEach, MoveWithSOPClass, GetWithSOPClass | |
| N-services, MPPS, UPS, storage commitment | NCreate, NSet, ... | see Workflow services |
The command lines below were run against echoscp, storescp and qrscp
on this machine, with CT_small.dcm and MR_small.dcm from pydicom's test
files as study/ct.dcm and study/mr.dcm.
Connecting
scu := network.NewSCU(network.SCUConfig{
CallingAE: "MY_APP",
CalledAE: "QRSCP",
Address: "127.0.0.1:11112",
Network: network.NetworkConfig{
DIMSETimeout: 2 * time.Minute, // each response has this long to arrive
},
})
if err := scu.Associate(ctx, nil); err != nil { // nil: verification, storage, query/retrieve
return err
}
defer scu.Release(ctx)
if err := scu.Echo(ctx); err != nil {
return err
}Associate(ctx, nil)proposes a default set: Verification, nine common storage classes (CT, Enhanced CT, MR, Enhanced MR, US, Secondary Capture, CR, DX, XA), the Query/Retrieve models and Storage Commitment, each in the four uncompressed transfer syntaxes. Anything else needs contexts of its own: pass a[]network.PresentationContextItem, or one of the helpers (DefaultVerificationContexts,BasicWorklistPresentationContexts,DefaultGetContexts,StoreStreamContexts, ...).- A refused association is an
*AssociationErrorwithResult,SourceandReasonfrom the A-ASSOCIATE-RJ. Releaseends it politely,Abortat once.TLS,DialFunc,EventsandLoggerin the config put the connection on TLS, make it yourself, report what happens, and log to a*slog.Loggerof its own. See TLS and security.
$ go-dicom echoscu -aec ECHOSCP 127.0.0.1:41001
Requesting Association with 127.0.0.1:41001 (AE: ECHOSCP)
Association accepted
Sending C-ECHO...
C-ECHO response: Success (0x0000)
Releasing AssociationSending instances (C-STORE)
Store sends a data set. It picks the accepted context for the data set's
SOP Class UID: its own transfer syntax first, then an uncompressed one,
Explicit VR Little Endian first, then any other. It re-encodes the data set
for that context, decoding or encoding pixel data as needed.
ds, err := readFile("study/ct.dcm") // filereader.ReadDICOMFile(...).GetDataset()
if err != nil {
return err
}
if err := scu.Store(ctx, ds); err != nil {
var dimse *network.DIMSEError
if errors.As(err, &dimse) {
return fmt.Errorf("the peer refused the instance: %s", network.FormatStatus(dimse.Status))
}
return err // no status: the association, the encoding, or no context for the class
}StoreStream sends a stored file as it is, byte for byte, reading it as it
goes, so a large instance costs two PDUs of memory. It uses only a context
for the file's SOP class in exactly the file's transfer syntax (unless
StoreStreamRequest.Transcode is set), and returns the peer's status
whatever it is:
f, err := os.Open("study/mr.dcm")
if err != nil {
return err
}
defer f.Close()
st, err := f.Stat()
if err != nil {
return err
}
req, err := network.StoreStreamRequestFromFile(f, st.Size()) // UIDs and syntax from the file meta
if err != nil {
return err
}
status, err := scu.StoreStream(ctx, req)
if err != nil {
return err // no status was obtained
}
if !network.IsSuccess(status) && !network.IsWarning(status) {
return fmt.Errorf("refused: %s", network.FormatStatus(status))
}On the command line, storescu reads each file's SOP class and transfer
syntax first and proposes a context for each pair, in the file's own syntax
and uncompressed, so a compressed file is sent as it is when the peer
accepts that and decoded when it does not:
$ go-dicom storescu -aec STORESCP 127.0.0.1:41002 study/ct.dcm study/mr.dcm
Requesting Association with 127.0.0.1:41002 (AE: STORESCP)
Association accepted
Sending: study/ct.dcm
Stored successfully
Sending: study/mr.dcm
Stored successfully
Results: 2 sent, 0 failed
$ go-dicom storescu -aec STORESCP -syntax jpeg-ls 127.0.0.1:41002 study/ct.dcm
...
Sending: study/ct.dcm
As JPEG-LS Lossless
Stored successfully-syntax takes the names go-dicom compress -syntax takes (rle,
jpeg-ls, jpeg2000, htj2k, jpeg-lossless, ...), the uncompressed
explicit, implicit, deflated and big-endian, or a UID. The lossy ones
need -quality, -near, -ratio or -psnr; -jpeg-quality offers JPEG
Baseline for 8-bit images. In Go the same choices are NetworkConfig's
JPEGQuality, JPEGLSNear and JPEG2000Rate: without them nothing is coded
lossily, and the send fails with an error that matches
network.ErrLossyNotAllowed.
storescu takes files, not directories: use a shell glob (study/*.dcm).
Querying (C-FIND)
A query is a data set: keys with a value are matched, keys with no value are returned. Build it with the VR of each attribute:
query := dataset.NewDataset()
keys := []struct {
keyword string
vr dataelem.VR
value string
}{
{"QueryRetrieveLevel", dataelem.CS, "STUDY"},
{"PatientName", dataelem.PN, "CompressedSamples*"}, // wildcard matching
{"StudyDate", dataelem.DA, ""}, // empty: match anything, return it
{"StudyInstanceUID", dataelem.UI, ""},
}
for _, k := range keys {
if err := query.AddByKeyword(k.keyword, k.vr, []byte(k.value)); err != nil {
return err
}
}Warning
ds.SetStringByKeyword on a data set that does not hold the attribute yet
adds it with VR OB, not the attribute's own VR. A query built that way
matches nothing. Use AddByKeyword with the VR, as above.
FindWithSOPClass returns the matches on a channel, which closes after the
final response. Drain it, or cancel the context:
results, err := scu.FindWithSOPClass(ctx, network.StudyRootQueryRetrieveFind, query)
if err != nil {
return err
}
for r := range results {
if r.Err != nil {
return r.Err
}
fmt.Println(r.DataSet.GetStringByKeyword("PatientName"), r.DataSet.GetStringByKeyword("StudyInstanceUID"))
}Find does the same on whichever information model the peer accepted,
trying Patient Root, Study Root, Patient/Study Only and Modality Worklist in
that order; name the model with FindWithSOPClass whenever more than one was
negotiated.
FindEach calls a function for each match and returns the final response.
An error from the function, or the end of the context, sends a C-CANCEL and
reads on to the peer's Cancel (FE00) response:
var studies []string
final, err := scu.FindEach(ctx, network.StudyRootQueryRetrieveFind, query, network.FindOptions{},
func(m network.FindMatch) error {
studies = append(studies, m.DataSet.GetStringByKeyword("StudyInstanceUID"))
if len(studies) == 100 {
return errors.New("enough") // sends C-CANCEL; FindEach returns this error
}
return nil
})
if err != nil {
return err
}
if err := final.Err(); err != nil {
return err // a failure status, with final.Status and final.ErrorComment
}FindMatch.Status is FF01 for a match where the SCP did not support some
optional keys. With a deadline instead:
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
final, err := scu.FindEach(ctx, network.StudyRootQueryRetrieveFind, query, network.FindOptions{},
func(m network.FindMatch) error { return nil })
if errors.Is(err, context.DeadlineExceeded) {
return errors.New("stopped after 30 seconds") // a C-CANCEL was sent for it
}To cancel from another goroutine, take the message ID from
FindOptions.OnStart and call scu.Cancel(ctx, messageID).
On the command line:
$ go-dicom findscu -aec QRSCP -level STUDY -patient-name "CompressedSamples*" 127.0.0.1:41003
Querying 127.0.0.1:41003 (level: STUDY)
--- Result 1 ---
Study Date 20040119
Query/Retrieve Level STUDY
Patient's Name CompressedSamples^CT1
Patient ID 1CT1
Study Instance UID 1.3.6.1.4.1.5962.1.2.1.20040119072730.12322
...
Found 2 result(s)
$ go-dicom findscu -aec QRSCP -level SERIES -key 0020,000D=1.3.6.1.4.1.5962.1.2.1.20040119072730.12322 -key 0008,0060 -key 0020,000E 127.0.0.1:41003-key GGGG,EEEE=value adds a key, and an empty value asks for the attribute
without matching on it. -sop-class names the information model.
-worklist queries Modality Worklist; see
Query/retrieve.
Retrieving (C-MOVE and C-GET)
The two differ in where the instances go. C-MOVE has the SCP send them to a third AE, named only by its AE title, over an association the SCP opens. C-GET sends them back on the requestor's own association.
result, err := scu.MoveWithSOPClass(ctx, network.StudyRootQueryRetrieveMove, move, "STORESCP",
network.RetrieveOptions{
OnPending: func(p network.RetrieveProgress) {
fmt.Printf("remaining %d, completed %d, failed %d\n", p.Remaining, p.Completed, p.Failed)
},
})
if err != nil {
return err // canceled, or the association failed
}
if err := result.Err(); err != nil {
return err // cancel or failure; B000 is not an error here
}
fmt.Printf("moved %d, failed %d %v\n", result.Completed, result.Failed, result.FailedSOPInstanceUIDs)move is an identifier with QueryRetrieveLevel and the unique key of each
level down to it (here StudyInstanceUID), built as the query above.
RetrieveResult
holds the final status, the four sub-operation counts and the Failed SOP
Instance UID List. Move is the older form: it returns only an error, a
*DIMSEError for any final status but 0000 and 0001, B000 included.
For C-GET the requestor is the storage SCP of the instances coming back, so it has to propose storage contexts for them and say what to do with each:
contexts := network.DefaultGetContexts(network.StudyRootQueryRetrieveGet)
scu := network.NewSCU(network.SCUConfig{
CallingAE: "MY_APP",
CalledAE: "QRSCP",
Address: "127.0.0.1:11112",
ExtendedNegotiation: &network.ExtendedNegotiation{
RoleSelections: network.DefaultGetRoleSelections(contexts),
},
OnCStore: func(ctx context.Context, sopClass, sopInstance string, ds *dataset.Dataset) uint16 {
kept++ // write ds somewhere; say Success only once it is kept
return network.StatusSuccess
},
})
if err := scu.Associate(ctx, contexts); err != nil {
return err
}
defer scu.Release(ctx)
result, err := scu.GetWithSOPClass(ctx, network.StudyRootQueryRetrieveGet, get, network.RetrieveOptions{})
if err != nil {
return err
}
if err := result.Err(); err != nil {
return err
}- Without
OnCStore(orOnCStoreStream) the instances are acknowledged with Success and discarded: the C-GET completes having kept nothing. OnCStoreStreamreceives each instance as the bytes the peer sent, for an instance too large to hold decoded.DefaultGetContextsproposes 119 contexts: document classes uncompressed and image classes uncompressed and in each compressed syntax, each alone, so an instance can come back as stored.GetContextstakes the classes you expect.
$ go-dicom movescu -aec QRSCP -dest STORESCP -study 1.3.6.1.4.1.5962.1.2.1.20040119072730.12322 127.0.0.1:41003
Moving from 127.0.0.1:41003 to STORESCP (level: STUDY)
C-MOVE completed successfully
$ go-dicom movescu -aec QRSCP -dest NOWHERE -study 1.3.6.1.4.1.5962.1.2.1.20040119072730.12322 127.0.0.1:41003
Moving from 127.0.0.1:41003 to NOWHERE (level: STUDY)
Error: C-MOVE failed: DIMSE error [MOVE_FAILED]: C-MOVE failed with status 0xA801 (status=0xA801)
$ go-dicom getscu -aec QRSCP -study 1.3.6.1.4.1.5962.1.2.1.20040119072730.12322 -output retrieved 127.0.0.1:41003
C-GET from 127.0.0.1:41003 (level: STUDY)
Received: 1.3.6.1.4.1.5962.1.1.1.1.1.20040119072730.12322 -> retrieved/1.3.6.1.4.1.5962.1.1.1.1.1.20040119072730.12322.dcm
C-GET completed: 1 instance(s) retrieved to retrievedmovescu and getscu take -level, -study and -series; movescu
needs -dest. A801 means the SCP cannot resolve the destination title to an
address.
Statuses and errors
| Call | Success | Warning | Failure or cancel | No status at all |
|---|---|---|---|---|
Echo | nil | error | error | |
Store | nil | nil for 0001 only; B000, B006, B007 are a *DIMSEError | *DIMSEError | error |
StoreStream | status, nil | status, nil | status, nil | error |
Find channel | closes | CFindResult.Err | CFindResult.Err | |
FindEach | FindResult, nil | FindResult.Err() is a *DIMSEError | error (the context's, the callback's, the association's) | |
Move | nil | nil for 0001; B000 is a *DIMSEError | *DIMSEError | error |
Get | nil | nil for 0001 and B000 | *DIMSEError | error |
MoveWithSOPClass, GetWithSOPClass | RetrieveResult, Err() nil | B000: Err() nil, see Failed | Err() is a *DIMSEError | error |
- Typed errors.
*AssociationError(negotiation, rejection, no context),*DIMSEError(a status, inStatus),*TimeoutError,*CommunicationError(unwraps to the network error) and*PDUError(unwraps to the coder's error on a failed transcode). All implementNetworkError. errors.Isfindsnetwork.ErrLossyNotAllowed,dataset.ErrNoEncoderandnetwork.ErrStoreStreamTooLargein a failed send.network.IsCanceled(err)is true for a*DIMSEErrorwith statusFE00: a canceledFind,MoveorGet.
Concurrency
An SCU is safe for concurrent use. Operations on one are serialized: one is
in flight at a time unless the peer agreed to an asynchronous operations
window (ExtendedNegotiation.AsyncOperations), so sharing one SCU between
goroutines bounds the number of associations rather than raising throughput.
C-MOVE and C-GET take the association alone. Cancel, Release and Abort
do not wait their turn.
Limits and gotchas
- The default contexts cover nine storage classes. Storing a PET, NM, RT
or SR instance needs a context for its class;
storescubuilds them from the files. StoretreatsB000,B006andB007as failures. The peer kept the instance with a warning; useStoreStream, which returns the status, when that difference matters.Movedoes the same with a finalB000(some sub-operations failed), whereGetreturnsnil;MoveWithSOPClassandGetWithSOPClasstreat both alike and give the counts.getscuproposes no role selection. It associates with the default contexts; an archive that holds to PS3.7 D.3.3.4 may then send nothing. The Go code above proposes it.- A canceled operation is still an error. It did not deliver what was
asked;
IsCanceledtells it apart. - CONFORMANCE.md §2.1 lists the SOP classes supported as an SCU, and §2.5 the cancellation behavior.
See also
- Network concepts
- Building an SCP
- Query/retrieve and worklist
- Coming from dcmtk: the dcmtk commands and their equivalents
network.SCUon pkg.go.dev