forked from aliyun/aliyun-odps-go-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
project.go
411 lines (336 loc) · 10.8 KB
/
project.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
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package odps
import (
"encoding/xml"
"fmt"
"github.com/jiuzhiqian/aliyun-odps-go-sdk/odps/common"
"github.com/jiuzhiqian/aliyun-odps-go-sdk/odps/restclient"
"github.com/jiuzhiqian/aliyun-odps-go-sdk/odps/security"
"github.com/pkg/errors"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
"time"
)
// TODO 将status转换为enum
type ProjectStatus int
const (
_ = iota
ProjectStatusAvailable
ProjectStatusReadOnly
ProjectStatusDeleting
ProjectStatusFrozen
ProjectStatusUnKnown
)
const (
// ProjectTypeManaged ordinary project
ProjectTypeManaged = "managed"
// ProjectExternalExternal external project,like hive
ProjectExternalExternal = "external"
)
type Project struct {
model projectModel
allProperties []common.Property
exists bool
beLoaded bool
odpsIns *Odps
rb common.ResourceBuilder
}
func (p *Project) OdpsIns() *Odps {
return p.odpsIns
}
type projectModel struct {
XMLName xml.Name `xml:"Project"`
Name string `xml:"Name"`
Type string `xml:"Type"`
Comment string `xml:"Comment"`
Status ProjectStatus `xml:"State"`
ProjectGroupName string `xml:"ProjectGroupName"`
Properties []common.Property `xml:"Properties>Property"`
DefaultCluster string `xml:"DefaultCluster"`
Clusters []Cluster `xml:"Clusters"`
ExtendedProperties []common.Property `xml:"ExtendedProperties>Property"`
// 这三个字段在/projects中和/projects/<ProjectName>接口中返回的未知不一样,
// 前者是body的xml数据中,后者在header里
Owner string `xml:"Owner"`
CreationTime common.GMTTime `xml:"CreationTime"`
LastModifiedTime common.GMTTime `xml:"LastModifiedTime"`
}
type OptionalQuota struct {
XMLName xml.Name `xml:"OptionalQuota"`
QuotaId string `xml:"QuotaID"`
Properties common.Properties `xml:"Properties"`
}
type Cluster struct {
Name string `xml:"Name"`
QuotaId string `xml:"QuotaId"`
Quotas []OptionalQuota `xml:"Quotas"`
}
func NewProject(name string, odpsIns *Odps) Project {
return Project{
model: projectModel{Name: name},
odpsIns: odpsIns,
rb: common.ResourceBuilder{ProjectName: name},
}
}
func (p *Project) RestClient() restclient.RestClient {
return p.odpsIns.restClient
}
type optionalParams struct {
// For compatibility. The static class 'Cluster' had strict schema validation. Unmarshalling will
// fail because of the new xml tag 'Quotas'.
usedByGroupApi bool
withAllProperties bool
extendedProperties bool
}
func (p *Project) _loadFromOdps(params optionalParams) (*projectModel, error) {
resource := p.rb.Project()
client := p.RestClient()
var urlQuery = make(url.Values)
if params.usedByGroupApi {
urlQuery.Set("isGroupApi", "true")
}
if params.withAllProperties {
urlQuery.Set("properties", "all")
}
if params.extendedProperties {
urlQuery.Set("extended", "")
}
model := projectModel{}
parseFunc := func(res *http.Response) error {
decoder := xml.NewDecoder(res.Body)
if err := decoder.Decode(&model); err != nil {
return errors.WithStack(err)
}
header := res.Header
model.Owner = header.Get(common.HttpHeaderOdpsOwner)
creationTime, err := common.ParseRFC1123Date(header.Get(common.HttpHeaderOdpsCreationTime))
if err != nil {
log.Printf("/project get creation time error, %v", err)
}
lastModifiedTime, _ := common.ParseRFC1123Date(header.Get(common.HttpHeaderLastModified))
if err != nil {
log.Printf("/project get last modified time error, %v", err)
}
model.CreationTime = common.GMTTime(creationTime)
model.LastModifiedTime = common.GMTTime(lastModifiedTime)
return nil
}
if err := client.GetWithParseFunc(resource, urlQuery, parseFunc); err != nil {
return nil, errors.WithStack(err)
}
return &model, nil
}
// Load should be called before get properties of project
func (p *Project) Load() error {
model, err := p._loadFromOdps(optionalParams{})
p.beLoaded = true
if err != nil {
if httpNoteOk, ok := err.(restclient.HttpNotOk); ok {
if httpNoteOk.StatusCode == 404 {
p.exists = false
}
}
return errors.WithStack(err)
}
p.exists = true
p.model = *model
return nil
}
// IsLoaded whether `Load()` has been called
func (p *Project) IsLoaded() bool {
return p.beLoaded
}
func (p *Project) Name() string {
return p.model.Name
}
func (p *Project) Type() string {
return p.model.Type
}
func (p *Project) Comment() string {
return p.model.Comment
}
func (p *Project) Status() ProjectStatus {
return p.model.Status
}
func (p *Project) ProjectGroupName() string {
return p.model.ProjectGroupName
}
// PropertiesHasBeSet Properties get the properties those have be set for the project
func (p *Project) PropertiesHasBeSet() common.Properties {
return p.model.Properties
}
// GetAllProperties get all the configurable properties of the project, including the
// properties inherit from group.
// **note**, this method may return error when something wrong during loading data
// from the api serer
func (p *Project) GetAllProperties() (common.Properties, error) {
if p.allProperties != nil {
return p.allProperties, nil
}
model, err := p._loadFromOdps(optionalParams{withAllProperties: true})
if err != nil {
return nil, errors.WithStack(err)
}
p.allProperties = model.Properties
return p.allProperties, nil
}
// GetDefaultCluster Get default cluster. This is an internal method for group-api.
// Returns efault cluster when called by group owner, otherwise ,null.
// **note**, this method may return error when something wrong during loading data
// from the api serer
func (p *Project) GetDefaultCluster() (string, error) {
if p.model.DefaultCluster != "" {
return p.model.DefaultCluster, nil
}
model, err := p._loadFromOdps(optionalParams{usedByGroupApi: true})
if err != nil {
return "", errors.WithStack(err)
}
p.model.DefaultCluster = model.DefaultCluster
p.model.Clusters = model.Clusters
return p.model.DefaultCluster, nil
}
// GetClusters Get information of clusters owned by this project. This is an internal
// method for group-api.
// **note**, this method may return error when something wrong during loading data
// from the api serer
func (p *Project) GetClusters() ([]Cluster, error) {
if p.model.Clusters != nil {
return p.model.Clusters, nil
}
model, err := p._loadFromOdps(optionalParams{usedByGroupApi: true})
if err != nil {
return nil, errors.WithStack(err)
}
p.model.DefaultCluster = model.DefaultCluster
p.model.Clusters = model.Clusters
return p.model.Clusters, nil
}
// GetExtendedProperties get the extended properties of the project
// **note**, this method may return error when something wrong during loading data
// from the api serer
func (p *Project) GetExtendedProperties() (common.Properties, error) {
if p.model.ExtendedProperties != nil {
return p.model.ExtendedProperties, nil
}
model, err := p._loadFromOdps(optionalParams{extendedProperties: true})
if err != nil {
return nil, errors.WithStack(err)
}
p.model.ExtendedProperties = model.ExtendedProperties
return p.model.ExtendedProperties, nil
}
func (p *Project) Owner() string {
return p.model.Owner
}
func (p *Project) CreationTime() time.Time {
return time.Time(p.model.CreationTime)
}
func (p *Project) LastModifiedTime() time.Time {
return time.Time(p.model.LastModifiedTime)
}
func (p *Project) Existed() bool {
return p.exists
}
func (p *Project) SecurityManager() security.Manager {
return security.NewSecurityManager(p.odpsIns.restClient, p.Name())
}
func (p *Project) GetTunnelEndpoint() (string, error) {
client := p.odpsIns.restClient
resource := p.rb.Tunnel()
queryArgs := make(url.Values, 1)
queryArgs.Set("service", "")
req, err := client.NewRequestWithUrlQuery(common.HttpMethod.GetMethod, resource, nil, queryArgs)
if err != nil {
return "", errors.WithStack(err)
}
schema := req.URL.Scheme
var tunnelEndpoint string
err = client.DoWithParseFunc(req, func(res *http.Response) error {
b, err := ioutil.ReadAll(res.Body)
if err != nil {
return errors.WithStack(err)
}
tunnelEndpoint = string(b)
return nil
})
return fmt.Sprintf("%s://%s", schema, tunnelEndpoint), errors.WithStack(err)
}
// Update the project properties, the properties are different in different versioned odps.
// When the "properties" is nil, the system will give the project all the default properties.
// You'd better ask technique support help when using this method.
func (p *Project) Update(properties map[string]string) error {
type BodyModel struct {
XMLName xml.Name `xml:"Project"`
Name string
Properties []common.Property `xml:"Properties>Property"`
}
_properties := make([]common.Property, 0, len(properties))
for key, value := range properties {
_properties = append(_properties, common.Property{Name: key, Value: value})
}
var bodyModel = BodyModel{
Name: p.Name(),
Properties: _properties,
}
resource := p.rb.Project()
client := p.RestClient()
return client.DoXmlWithModel(common.HttpMethod.PutMethod, resource, nil, &bodyModel, nil)
}
func (status *ProjectStatus) FromStr(s string) {
switch strings.ToUpper(s) {
case "AVAILABLE":
*status = ProjectStatusAvailable
case "READONLY":
*status = ProjectStatusReadOnly
case "DELETING":
*status = ProjectStatusDeleting
case "FROZEN":
*status = ProjectStatusFrozen
default:
*status = ProjectStatusUnKnown
}
}
func (status ProjectStatus) String() string {
switch status {
case ProjectStatusAvailable:
return "AVAILABLE"
case ProjectStatusReadOnly:
return "READONLY"
case ProjectStatusDeleting:
return "DELETING"
case ProjectStatusFrozen:
return "FROZEN"
default:
return "UNKNOWN"
}
}
func (status *ProjectStatus) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
var s string
if err := d.DecodeElement(&s, &start); err != nil {
return errors.WithStack(err)
}
status.FromStr(s)
return nil
}
func (status ProjectStatus) MarshalXML(d *xml.Encoder, start xml.StartElement) error {
s := status.String()
return errors.WithStack(d.EncodeElement(s, start))
}