README.md
1# Golang Admin Client API Reference [![Slack](https://slack.min.io/slack?type=svg)](https://slack.min.io)
2The MinIO Admin Golang Client SDK provides APIs to manage MinIO services.
3
4This quickstart guide will show you how to install the MinIO Admin client SDK, connect to MinIO admin service, and provide a walkthrough of a simple file uploader.
5
6This document assumes that you have a working [Golang setup](https://golang.org/doc/install).
7
8## Initialize MinIO Admin Client object.
9
10## MinIO
11
12```go
13
14package main
15
16import (
17 "fmt"
18
19 "github.com/minio/madmin-go"
20)
21
22func main() {
23 // Use a secure connection.
24 ssl := true
25
26 // Initialize minio client object.
27 mdmClnt, err := madmin.New("your-minio.example.com:9000", "YOUR-ACCESSKEYID", "YOUR-SECRETKEY", ssl)
28 if err != nil {
29 fmt.Println(err)
30 return
31 }
32
33 // Fetch service status.
34 st, err := mdmClnt.ServerInfo()
35 if err != nil {
36 fmt.Println(err)
37 return
38 }
39 for _, peerInfo := range serversInfo {
40 log.Printf("Node: %s, Info: %v\n", peerInfo.Addr, peerInfo.Data)
41 }
42}
43
44```
45
46| Service operations | Info operations | Healing operations | Config operations |
47|:------------------------------------|:-----------------------------------------|:-------------------|:--------------------------|
48| [`ServiceTrace`](#ServiceTrace) | [`ServerInfo`](#ServerInfo) | [`Heal`](#Heal) | [`GetConfig`](#GetConfig) |
49| [`ServiceStop`](#ServiceStop) | [`StorageInfo`](#StorageInfo) | | [`SetConfig`](#SetConfig) |
50| [`ServiceRestart`](#ServiceRestart) | [`AccountInfo`](#AccountInfo) | | |
51
52
53
54| Top operations | IAM operations | Misc | KMS |
55|:------------------------|:--------------------------------------|:--------------------------------------------------|:--------------------------------|
56| [`TopLocks`](#TopLocks) | [`AddUser`](#AddUser) | [`StartProfiling`](#StartProfiling) | [`GetKeyStatus`](#GetKeyStatus) |
57| | [`SetPolicy`](#SetPolicy) | [`DownloadProfilingData`](#DownloadProfilingData) | |
58| | [`ListUsers`](#ListUsers) | [`ServerUpdate`](#ServerUpdate) | |
59| | [`AddCannedPolicy`](#AddCannedPolicy) | | |
60
61## 1. Constructor
62<a name="MinIO"></a>
63
64### New(endpoint string, accessKeyID string, secretAccessKey string, ssl bool) (*AdminClient, error)
65Initializes a new admin client object.
66
67__Parameters__
68
69| Param | Type | Description |
70|:------------------|:---------|:----------------------------------------------------------|
71| `endpoint` | _string_ | MinIO endpoint. |
72| `accessKeyID` | _string_ | Access key for the object storage endpoint. |
73| `secretAccessKey` | _string_ | Secret key for the object storage endpoint. |
74| `ssl` | _bool_ | Set this value to 'true' to enable secure (HTTPS) access. |
75
76## 2. Service operations
77
78<a name="ServiceStatus"></a>
79### ServiceStatus(ctx context.Context) (ServiceStatusMetadata, error)
80Fetch service status, replies disk space used, backend type and total disks offline/online (applicable in distributed mode).
81
82| Param | Type | Description |
83|-----------------|-------------------------|------------------------------------------------------------|
84| `serviceStatus` | _ServiceStatusMetadata_ | Represents current server status info in following format: |
85
86
87| Param | Type | Description |
88|-----------------------------|-----------------|------------------------------------|
89| `st.ServerVersion.Version` | _string_ | Server version. |
90| `st.ServerVersion.CommitID` | _string_ | Server commit id. |
91| `st.Uptime` | _time.Duration_ | Server uptime duration in seconds. |
92
93 __Example__
94
95 ```go
96
97 st, err := madmClnt.ServiceStatus(context.Background())
98 if err != nil {
99 log.Fatalln(err)
100 }
101 log.Printf("%#v\n", st)
102
103 ```
104
105<a name="ServiceRestart"></a>
106### ServiceRestart(ctx context.Context) error
107Sends a service action restart command to MinIO server.
108
109 __Example__
110
111```go
112 // To restart the service, restarts all servers in the cluster.
113 err := madmClnt.ServiceRestart(context.Background())
114 if err != nil {
115 log.Fatalln(err)
116 }
117 log.Println("Success")
118```
119
120<a name="ServiceStop"></a>
121### ServiceStop(ctx context.Context) error
122Sends a service action stop command to MinIO server.
123
124 __Example__
125
126```go
127 // To stop the service, stops all servers in the cluster.
128 err := madmClnt.ServiceStop(context.Background())
129 if err != nil {
130 log.Fatalln(err)
131 }
132 log.Println("Success")
133```
134
135<a name="ServiceTrace"></a>
136### ServiceTrace(ctx context.Context, allTrace bool, doneCh <-chan struct{}) <-chan TraceInfo
137Enable HTTP request tracing on all nodes in a MinIO cluster
138
139__Example__
140
141``` go
142 doneCh := make(chan struct{})
143 defer close(doneCh)
144 // listen to all trace including internal API calls
145 allTrace := true
146 // Start listening on all trace activity.
147 traceCh := madmClnt.ServiceTrace(context.Background(), allTrace, doneCh)
148 for traceInfo := range traceCh {
149 fmt.Println(traceInfo.String())
150 }
151```
152
153## 3. Info operations
154
155<a name="ServerInfo"></a>
156### ServerInfo(ctx context.Context) ([]ServerInfo, error)
157Fetches information for all cluster nodes, such as server properties, storage information, network statistics, etc.
158
159| Param | Type | Description |
160|----------------------------------|--------------------|--------------------------------------------------------------------|
161| `si.Addr` | _string_ | Address of the server the following information is retrieved from. |
162| `si.ConnStats` | _ServerConnStats_ | Connection statistics from the given server. |
163| `si.HTTPStats` | _ServerHTTPStats_ | HTTP connection statistics from the given server. |
164| `si.Properties` | _ServerProperties_ | Server properties such as region, notification targets. |
165
166| Param | Type | Description |
167|-----------------------------|-----------------|----------------------------------------------------|
168| `ServerProperties.Uptime` | _time.Duration_ | Total duration in seconds since server is running. |
169| `ServerProperties.Version` | _string_ | Current server version. |
170| `ServerProperties.CommitID` | _string_ | Current server commitID. |
171| `ServerProperties.Region` | _string_ | Configured server region. |
172| `ServerProperties.SQSARN` | _[]string_ | List of notification target ARNs. |
173
174| Param | Type | Description |
175|------------------------------------|----------|-------------------------------------|
176| `ServerConnStats.TotalInputBytes` | _uint64_ | Total bytes received by the server. |
177| `ServerConnStats.TotalOutputBytes` | _uint64_ | Total bytes sent by the server. |
178
179| Param | Type | Description |
180|--------------------------------------|-------------------------|---------------------------------------------------------|
181| `ServerHTTPStats.TotalHEADStats` | _ServerHTTPMethodStats_ | Total statistics regarding HEAD operations |
182| `ServerHTTPStats.SuccessHEADStats` | _ServerHTTPMethodStats_ | Total statistics regarding successful HEAD operations |
183| `ServerHTTPStats.TotalGETStats` | _ServerHTTPMethodStats_ | Total statistics regarding GET operations |
184| `ServerHTTPStats.SuccessGETStats` | _ServerHTTPMethodStats_ | Total statistics regarding successful GET operations |
185| `ServerHTTPStats.TotalPUTStats` | _ServerHTTPMethodStats_ | Total statistics regarding PUT operations |
186| `ServerHTTPStats.SuccessPUTStats` | _ServerHTTPMethodStats_ | Total statistics regarding successful PUT operations |
187| `ServerHTTPStats.TotalPOSTStats` | _ServerHTTPMethodStats_ | Total statistics regarding POST operations |
188| `ServerHTTPStats.SuccessPOSTStats` | _ServerHTTPMethodStats_ | Total statistics regarding successful POST operations |
189| `ServerHTTPStats.TotalDELETEStats` | _ServerHTTPMethodStats_ | Total statistics regarding DELETE operations |
190| `ServerHTTPStats.SuccessDELETEStats` | _ServerHTTPMethodStats_ | Total statistics regarding successful DELETE operations |
191
192| Param | Type | Description |
193|-------------------------------------|----------|-------------------------------------------------|
194| `ServerHTTPMethodStats.Count` | _uint64_ | Total number of operations. |
195| `ServerHTTPMethodStats.AvgDuration` | _string_ | Average duration of Count number of operations. |
196
197| Param | Type | Description |
198|----------------------|----------|-------------------------------------------------------|
199| `DriveInfo.UUID` | _string_ | Unique ID for each disk provisioned by server format. |
200| `DriveInfo.Endpoint` | _string_ | Endpoint location of the remote/local disk. |
201| `DriveInfo.State` | _string_ | Current state of the disk at endpoint. |
202
203 __Example__
204
205 ```go
206
207 serversInfo, err := madmClnt.ServerInfo(context.Background())
208 if err != nil {
209 log.Fatalln(err)
210 }
211
212 for _, peerInfo := range serversInfo {
213 log.Printf("Node: %s, Info: %v\n", peerInfo.Addr, peerInfo.Data)
214 }
215
216 ```
217
218<a name="StorageInfo"></a>
219### StorageInfo(ctx context.Context) (StorageInfo, error)
220
221Fetches Storage information for all cluster nodes.
222
223| Param | Type | Description |
224|-------------------------|------------|---------------------------------------------|
225| `storageInfo.Used` | _[]int64_ | Used disk spaces. |
226| `storageInfo.Total` | _[]int64_ | Total disk spaces. |
227| `storageInfo.Available` | _[]int64_ | Available disk spaces. |
228| `StorageInfo.Backend` | _struct{}_ | Represents backend type embedded structure. |
229
230| Param | Type | Description |
231|----------------------------|-----------------|--------------------------------------------------------------------------------------------------------------------------|
232| `Backend.Type` | _BackendType_ | Type of backend used by the server currently only FS or Erasure. |
233| `Backend.OnlineDisks` | _BackendDisks_ | Total number of disks online per node (only applies to Erasure backend) represented in map[string]int, is empty for FS. |
234| `Backend.OfflineDisks` | _BackendDisks_ | Total number of disks offline per node (only applies to Erasure backend) represented in map[string]int, is empty for FS. |
235| `Backend.StandardSCParity` | _int_ | Parity disks set for standard storage class, is empty for FS. |
236| `Backend.RRSCParity` | _int_ | Parity disks set for reduced redundancy storage class, is empty for FS. |
237| `Backend.Sets` | _[][]DriveInfo_ | Represents topology of drives in erasure coded sets. |
238
239__Example__
240
241 ```go
242
243 storageInfo, err := madmClnt.StorageInfo(context.Background())
244 if err != nil {
245 log.Fatalln(err)
246 }
247
248 log.Println(storageInfo)
249
250 ```
251
252<a name="AccountInfo"></a>
253
254### AccountInfo(ctx context.Context) (AccountInfo, error)
255
256Fetches accounting usage information for the current authenticated user
257
258| Param | Type | Description |
259|--------------------------------|----------------------|-------------------------|
260| `AccountInfo.AccountName` | _string_ | Account name. |
261| `AccountInfo.Buckets` | _[]BucketAccessInfo_ | Bucket usage info. |
262
263
264| Param | Type | Description |
265|----------------------------|-----------------|-----------------------------------------|
266| `BucketAccessInfo.Name` | _string_ | The name of the current bucket
267| `BucketAccessInfo.Size` | _uint64_ | The total size of the current bucket
268| `BucketAccessInfo.Created` | _time.Time_ | Bucket creation time
269| `BucketAccessInfo.Access` | _AccountAccess_ | Type of access of the current account
270
271
272| Param | Type | Description |
273|------------------------|---------|------------------------------------------------------------------|
274| `AccountAccess.Read` | _bool_ | Indicate if the bucket is readable by the current account name. |
275| `AccountAccess.Write` | _bool_ | Indocate if the bucket is writable by the current account name. |
276
277
278__Example__
279
280```go
281
282 accountInfo, err := madmClnt.AccountInfo(context.Background())
283 if err != nil {
284 log.Fatalln(err)
285 }
286
287 log.Println(accountInfo)
288
289```
290
291
292
293## 5. Heal operations
294
295<a name="Heal"></a>
296### Heal(ctx context.Context, bucket, prefix string, healOpts HealOpts, clientToken string, forceStart bool, forceStop bool) (start HealStartSuccess, status HealTaskStatus, err error)
297
298Start a heal sequence that scans data under given (possible empty)
299`bucket` and `prefix`. The `recursive` bool turns on recursive
300traversal under the given path. `dryRun` does not mutate on-disk data,
301but performs data validation.
302
303Two heal sequences on overlapping paths may not be initiated.
304
305The progress of a heal should be followed using the same API `Heal`
306by providing the `clientToken` previously obtained from a `Heal`
307API. The server accumulates results of the heal traversal and waits
308for the client to receive and acknowledge them using the status
309request by providing `clientToken`.
310
311__Example__
312
313``` go
314
315 opts := madmin.HealOpts{
316 Recursive: true,
317 DryRun: false,
318 }
319 forceStart := false
320 forceStop := false
321 healPath, err := madmClnt.Heal(context.Background(), "", "", opts, "", forceStart, forceStop)
322 if err != nil {
323 log.Fatalln(err)
324 }
325 log.Printf("Heal sequence started at %s", healPath)
326
327```
328
329#### HealStartSuccess structure
330
331| Param | Type | Description |
332|-------------------|-------------|----------------------------------------------------------------------------------------------------------------------------------|
333| `s.ClientToken` | _string_ | A unique token for a successfully started heal operation, this token is used to request realtime progress of the heal operation. |
334| `s.ClientAddress` | _string_ | Address of the client which initiated the heal operation, the client address has the form "host:port". |
335| `s.StartTime` | _time.Time_ | Time when heal was initially started. |
336
337#### HealTaskStatus structure
338
339| Param | Type | Description |
340|-------------------|--------------------|---------------------------------------------------|
341| `s.Summary` | _string_ | Short status of heal sequence |
342| `s.FailureDetail` | _string_ | Error message in case of heal sequence failure |
343| `s.HealSettings` | _HealOpts_ | Contains the booleans set in the `HealStart` call |
344| `s.Items` | _[]HealResultItem_ | Heal records for actions performed by server |
345
346#### HealResultItem structure
347
348| Param | Type | Description |
349|------------------------|----------------|-----------------------------------------------------------------|
350| `ResultIndex` | _int64_ | Index of the heal-result record |
351| `Type` | _HealItemType_ | Represents kind of heal operation in the heal record |
352| `Bucket` | _string_ | Bucket name |
353| `Object` | _string_ | Object name |
354| `Detail` | _string_ | Details about heal operation |
355| `DiskInfo.AvailableOn` | _[]int_ | List of disks on which the healed entity is present and healthy |
356| `DiskInfo.HealedOn` | _[]int_ | List of disks on which the healed entity was restored |
357l
358## 6. Config operations
359
360<a name="GetConfig"></a>
361### GetConfig(ctx context.Context) ([]byte, error)
362Get current `config.json` of a MinIO server.
363
364__Example__
365
366``` go
367 configBytes, err := madmClnt.GetConfig(context.Background())
368 if err != nil {
369 log.Fatalf("failed due to: %v", err)
370 }
371
372 // Pretty-print config received as json.
373 var buf bytes.Buffer
374 err = json.Indent(buf, configBytes, "", "\t")
375 if err != nil {
376 log.Fatalf("failed due to: %v", err)
377 }
378
379 log.Println("config received successfully: ", string(buf.Bytes()))
380```
381
382
383<a name="SetConfig"></a>
384### SetConfig(ctx context.Context, config io.Reader) error
385Set a new `config.json` for a MinIO server.
386
387__Example__
388
389``` go
390 config := bytes.NewReader([]byte(`config.json contents go here`))
391 if err := madmClnt.SetConfig(context.Background(), config); err != nil {
392 log.Fatalf("failed due to: %v", err)
393 }
394 log.Println("SetConfig was successful")
395```
396
397## 7. Top operations
398
399<a name="TopLocks"></a>
400### TopLocks(ctx context.Context) (LockEntries, error)
401Get the oldest locks from MinIO server.
402
403__Example__
404
405``` go
406 locks, err := madmClnt.TopLocks(context.Background())
407 if err != nil {
408 log.Fatalf("failed due to: %v", err)
409 }
410
411 out, err := json.Marshal(locks)
412 if err != nil {
413 log.Fatalf("Marshal failed due to: %v", err)
414 }
415
416 log.Println("TopLocks received successfully: ", string(out))
417```
418
419## 8. IAM operations
420
421<a name="AddCannedPolicy"></a>
422### AddCannedPolicy(ctx context.Context, policyName string, policy *iampolicy.Policy) error
423Create a new canned policy on MinIO server.
424
425__Example__
426
427```
428 policy, err := iampolicy.ParseConfig(strings.NewReader(`{"Version": "2012-10-17","Statement": [{"Action": ["s3:GetObject"],"Effect": "Allow","Resource": ["arn:aws:s3:::my-bucketname/*"],"Sid": ""}]}`))
429 if err != nil {
430 log.Fatalln(err)
431 }
432
433 if err = madmClnt.AddCannedPolicy(context.Background(), "get-only", policy); err != nil {
434 log.Fatalln(err)
435 }
436```
437
438<a name="AddUser"></a>
439### AddUser(ctx context.Context, user string, secret string) error
440Add a new user on a MinIO server.
441
442__Example__
443
444``` go
445 if err = madmClnt.AddUser(context.Background(), "newuser", "newstrongpassword"); err != nil {
446 log.Fatalln(err)
447 }
448```
449
450<a name="SetPolicy"></a>
451### SetPolicy(ctx context.Context, policyName, entityName string, isGroup bool) error
452Enable a canned policy `get-only` for a given user or group on MinIO server.
453
454__Example__
455
456``` go
457 if err = madmClnt.SetPolicy(context.Background(), "get-only", "newuser", false); err != nil {
458 log.Fatalln(err)
459 }
460```
461
462<a name="ListUsers"></a>
463### ListUsers(ctx context.Context) (map[string]UserInfo, error)
464Lists all users on MinIO server.
465
466__Example__
467
468``` go
469 users, err := madmClnt.ListUsers(context.Background());
470 if err != nil {
471 log.Fatalln(err)
472 }
473 for k, v := range users {
474 fmt.Printf("User %s Status %s\n", k, v.Status)
475 }
476```
477
478## 9. Misc operations
479
480<a name="ServerUpdate"></a>
481### ServerUpdate(ctx context.Context, updateURL string) (ServerUpdateStatus, error)
482Sends a update command to MinIO server, to update MinIO server to latest release. In distributed setup it updates all servers atomically.
483
484 __Example__
485
486```go
487 // Updates all servers and restarts all the servers in the cluster.
488 // optionally takes an updateURL, which is used to update the binary.
489 us, err := madmClnt.ServerUpdate(context.Background(), updateURL)
490 if err != nil {
491 log.Fatalln(err)
492 }
493 if us.CurrentVersion != us.UpdatedVersion {
494 log.Printf("Updated server version from %s to %s successfully", us.CurrentVersion, us.UpdatedVersion)
495 }
496```
497
498<a name="StartProfiling"></a>
499### StartProfiling(ctx context.Context, profiler string) error
500Ask all nodes to start profiling using the specified profiler mode
501
502__Example__
503
504``` go
505 startProfilingResults, err = madmClnt.StartProfiling(context.Background(), "cpu")
506 if err != nil {
507 log.Fatalln(err)
508 }
509 for _, result := range startProfilingResults {
510 if !result.Success {
511 log.Printf("Unable to start profiling on node `%s`, reason = `%s`\n", result.NodeName, result.Error)
512 } else {
513 log.Printf("Profiling successfully started on node `%s`\n", result.NodeName)
514 }
515 }
516
517```
518
519<a name="DownloadProfilingData"></a>
520### DownloadProfilingData(ctx context.Context) ([]byte, error)
521Download profiling data of all nodes in a zip format.
522
523__Example__
524
525``` go
526 profilingData, err := madmClnt.DownloadProfilingData(context.Background())
527 if err != nil {
528 log.Fatalln(err)
529 }
530
531 profilingFile, err := os.Create("/tmp/profiling-data.zip")
532 if err != nil {
533 log.Fatal(err)
534 }
535
536 if _, err := io.Copy(profilingFile, profilingData); err != nil {
537 log.Fatal(err)
538 }
539
540 if err := profilingFile.Close(); err != nil {
541 log.Fatal(err)
542 }
543
544 if err := profilingData.Close(); err != nil {
545 log.Fatal(err)
546 }
547
548 log.Println("Profiling data successfully downloaded.")
549```
550
551## 11. KMS
552
553<a name="GetKeyStatus"></a>
554### GetKeyStatus(ctx context.Context, keyID string) (*KMSKeyStatus, error)
555Requests status information about one particular KMS master key
556from a MinIO server. The keyID is optional and the server will
557use the default master key (configured via `MINIO_KMS_VAULT_KEY_NAME`
558or `MINIO_KMS_MASTER_KEY`) if the keyID is empty.
559
560__Example__
561
562``` go
563 keyInfo, err := madmClnt.GetKeyStatus(context.Background(), "my-minio-key")
564 if err != nil {
565 log.Fatalln(err)
566 }
567 if keyInfo.EncryptionErr != "" {
568 log.Fatalf("Failed to perform encryption operation using '%s': %v\n", keyInfo.KeyID, keyInfo.EncryptionErr)
569 }
570 if keyInfo.UpdateErr != "" {
571 log.Fatalf("Failed to perform key re-wrap operation using '%s': %v\n", keyInfo.KeyID, keyInfo.UpdateErr)
572 }
573 if keyInfo.DecryptionErr != "" {
574 log.Fatalf("Failed to perform decryption operation using '%s': %v\n", keyInfo.KeyID, keyInfo.DecryptionErr)
575 }
576```
577
578## License
579This SDK is distributed under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0), see [LICENSE](https://github.com/minio/madmin-go/blob/master/LICENSE).
580