-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.go
More file actions
284 lines (257 loc) · 7.56 KB
/
main.go
File metadata and controls
284 lines (257 loc) · 7.56 KB
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
// Example code
package main
import (
"context"
"crypto/x509"
"encoding/json"
"flag"
"fmt"
"os"
"time"
"github.com/golang/protobuf/ptypes"
api "github.com/libopenstorage/openstorage-sdk-clients/sdk/golang"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/status"
)
const (
Bytes = uint64(1)
KB = Bytes * uint64(1024)
MB = KB * uint64(1024)
GB = MB * uint64(1024)
)
var (
useTls = flag.Bool("usetls", false, "Connect to server using TLS. Loads CA from the system")
token = flag.String("token", "", "Authorization token if any")
address = flag.String("address", "127.0.0.1:9100", "Address to server as <address>:<port>")
)
type OpenStorageSdkToken struct {
token string
useTls bool
}
func NewOpenStorageSdkToken(token string, useTls bool) OpenStorageSdkToken {
return OpenStorageSdkToken{
token: token,
useTls: useTls,
}
}
func (t OpenStorageSdkToken) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return map[string]string{
"authorization": "bearer " + t.token,
}, nil
}
func (t OpenStorageSdkToken) RequireTransportSecurity() bool {
return t.useTls
}
func main() {
flag.Parse()
// There are two ways to setup a token:
// - One is to setup a client interceptor which adds the token
// to every call automatically using grpc.WithPerRPCCredentials().
// - Second way is just to add it to the context directly as follows:
// import "google.golang.org/grpc/metadata"
// md := metadata.New(map[string]string{
// "authorization": "bearer" + token,
// })
// ctx := metadata.NewOutgoingContext(context.Background(), md)
//
// We will be using the more complicated first model to show how it can be done
//
// To accomplish this, we first need to create an object that satisfies the
// interface needed by grpc.WithPerRPCCredentials(..)
contextToken := NewOpenStorageSdkToken(*token, *useTls)
dialOptions := []grpc.DialOption{grpc.WithInsecure()}
if *useTls {
// Setup a connection
capool, err := x509.SystemCertPool()
if err != nil {
fmt.Printf("Failed to load system certs: %v\n")
os.Exit(1)
}
dialOptions = []grpc.DialOption{grpc.WithTransportCredentials(
credentials.NewClientTLSFromCert(capool, ""),
)}
}
if len(*token) != 0 {
// Add token interceptor
dialOptions = append(dialOptions, grpc.WithPerRPCCredentials(contextToken))
}
conn, err := grpc.Dial(*address, dialOptions...)
if err != nil {
fmt.Printf("Error: %v", err)
os.Exit(1)
}
// Create a cluster client
cluster := api.NewOpenStorageClusterClient(conn)
// Print the cluster information
clusterInfo, err := cluster.InspectCurrent(
context.Background(),
&api.SdkClusterInspectCurrentRequest{})
if err != nil {
gerr, _ := status.FromError(err)
fmt.Printf("Error Code[%d] Message[%s]\n",
gerr.Code(), gerr.Message())
os.Exit(1)
}
fmt.Printf("Connected to Cluster %s\n",
clusterInfo.GetCluster().GetId())
// --- Get Cluster capacity ---
// First, get all node node IDs in this cluster
nodeclient := api.NewOpenStorageNodeClient(conn)
nodeEnumResp, err := nodeclient.Enumerate(
context.Background(),
&api.SdkNodeEnumerateRequest{})
if err != nil {
gerr, _ := status.FromError(err)
fmt.Printf("Error Code[%d] Message[%s]\n",
gerr.Code(), gerr.Message())
os.Exit(1)
}
// Initialize the variable
totalCapacity := uint64(0)
// For each node ID, get its information
for _, nodeID := range nodeEnumResp.GetNodeIds() {
node, err := nodeclient.Inspect(
context.Background(),
&api.SdkNodeInspectRequest{
NodeId: nodeID,
},
)
if err != nil {
gerr, _ := status.FromError(err)
fmt.Printf("Error Code[%d] Message[%s]\n",
gerr.Code(), gerr.Message())
os.Exit(1)
}
// Get size from the pools
// Use Pool instead of the disks, because disks could be in a RAID
// configuration. The Pool returns the usable size.
for _, pool := range node.GetNode().GetPools() {
totalCapacity += pool.GetTotalSize()
}
}
fmt.Printf("Cluster total capacity is %d Gi\n", totalCapacity/GB)
// Create a 100Gi volume
volumes := api.NewOpenStorageVolumeClient(conn)
v, err := volumes.Create(
context.Background(),
&api.SdkVolumeCreateRequest{
Name: "myvol",
Spec: &api.VolumeSpec{
Size: 100 * 1024 * 1024 * 1024,
HaLevel: 3,
},
})
if err != nil {
gerr, _ := status.FromError(err)
fmt.Printf("Error Code[%d] Message[%s]\n",
gerr.Code(), gerr.Message())
os.Exit(1)
}
fmt.Printf("Volume 100Gi created with id %s\n", v.GetVolumeId())
fmt.Println()
// Take a snapshot
snap, err := volumes.SnapshotCreate(
context.Background(),
&api.SdkVolumeSnapshotCreateRequest{
VolumeId: v.GetVolumeId(),
Name: fmt.Sprintf("snap-%v", time.Now().Unix()),
},
)
if err != nil {
gerr, _ := status.FromError(err)
fmt.Printf("Error Code[%d] Message[%s]\n",
gerr.Code(), gerr.Message())
os.Exit(1)
}
fmt.Printf("Snapshot with id %s was create for volume %s\n",
snap.GetSnapshotId(),
v.GetVolumeId())
fmt.Println()
// Create mock credentials
creds := api.NewOpenStorageCredentialsClient(conn)
credResponse, err := creds.Create(context.Background(),
&api.SdkCredentialCreateRequest{
Name: "aws",
CredentialType: &api.SdkCredentialCreateRequest_AwsCredential{
AwsCredential: &api.SdkAwsCredentialRequest{
AccessKey: "dummy-access",
SecretKey: "dummy-secret",
Endpoint: "dummy-endpoint",
Region: "dummy-region",
},
},
})
if err != nil {
gerr, _ := status.FromError(err)
fmt.Printf("Error Code[%d] Message[%s]\n",
gerr.Code(), gerr.Message())
os.Exit(1)
}
credID := credResponse.GetCredentialId()
fmt.Printf("Credentials created with id %s\n", credID)
fmt.Println()
// Create a backup to a cloud provider of our volume
cloudbackups := api.NewOpenStorageCloudBackupClient(conn)
backupCreateResp, err := cloudbackups.Create(context.Background(),
&api.SdkCloudBackupCreateRequest{
VolumeId: v.GetVolumeId(),
CredentialId: credID,
})
if err != nil {
gerr, _ := status.FromError(err)
fmt.Printf("Error Code[%d] Message[%s]\n",
gerr.Code(), gerr.Message())
os.Exit(1)
}
fmt.Printf("Backup started for volume %s with task id %s\n",
v.GetVolumeId(),
backupCreateResp.GetTaskId())
// Now check the status of the backup
backupStatus, err := cloudbackups.Status(context.Background(),
&api.SdkCloudBackupStatusRequest{
VolumeId: v.GetVolumeId(),
})
if err != nil {
gerr, _ := status.FromError(err)
fmt.Printf("Error Code[%d] Message[%s]\n",
gerr.Code(), gerr.Message())
os.Exit(1)
}
for taskId, status := range backupStatus.GetStatuses() {
// There will be only one value in the map, but we use
// a for-loop as an example.
b, _ := json.MarshalIndent(status, "", " ")
fmt.Printf("Backup status for taskId: %s\n"+
"Volume: %s\n"+
"Type: %s\n"+
"Status: %s\n"+
"Full JSON Response: %s\n",
taskId,
status.GetSrcVolumeId(),
status.GetOptype().String(),
status.GetStatus().String(),
string(b))
}
fmt.Println()
// Backup History
historyResp, err := cloudbackups.History(context.Background(),
&api.SdkCloudBackupHistoryRequest{
SrcVolumeId: v.GetVolumeId(),
})
if err != nil {
gerr, _ := status.FromError(err)
fmt.Printf("Error Code[%d] Message[%s]\n",
gerr.Code(), gerr.Message())
os.Exit(1)
}
fmt.Printf("Backup history for volume %s:\n", v.GetVolumeId())
for _, history := range historyResp.GetHistoryList() {
timestamp, _ := ptypes.Timestamp(history.GetTimestamp())
fmt.Printf("Volume:%s \tttime:%v \tstatus:%v\n",
history.GetSrcVolumeId(),
timestamp,
history.GetStatus())
}
fmt.Println()
}