This repository has been archived by the owner on Jun 24, 2023. It is now read-only.
/
service.go
272 lines (245 loc) · 9.18 KB
/
service.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
// Copyright 2023 Commonwealth Scientific and Industrial Research Organisation (CSIRO) ABN 41 687 119 230
//
// Licensed 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 cmd
import (
"context"
"fmt"
"os"
"strings"
api "github.com/reinventingscience/ivcap-core-api/http/service"
sdk "github.com/reinventingscience/ivcap-cli/pkg"
a "github.com/reinventingscience/ivcap-cli/pkg/adapter"
"github.com/jedib0t/go-pretty/v6/table"
"github.com/jedib0t/go-pretty/v6/text"
"github.com/spf13/cobra"
)
func init() {
rootCmd.AddCommand(serviceCmd)
serviceCmd.AddCommand(listServiceCmd)
listServiceCmd.Flags().IntVar(&offset, "offset", -1, "record offset into returned list")
listServiceCmd.Flags().IntVar(&limit, "limit", -1, "max number of records to be returned")
listServiceCmd.Flags().StringVarP(&outputFormat, "output", "o", "short", "format to use for list (short, yaml, json)")
serviceCmd.AddCommand(readServiceCmd)
readServiceCmd.Flags().StringVarP(&recordID, "service-id", "i", "", "ID of service to retrieve")
serviceCmd.AddCommand(createServiceCmd)
createServiceCmd.Flags().StringVarP(&serviceFile, "file", "f", "", "Path to service description file")
createServiceCmd.Flags().StringVar(&inputFormat, "format", "", "Format of service description file [json, yaml]")
serviceCmd.AddCommand(updateServiceCmd)
updateServiceCmd.Flags().BoolVarP(&createAnyway, "create", "", false, "Create service record if it doesn't exist")
updateServiceCmd.Flags().StringVarP(&serviceFile, "file", "f", "", "Path to service description file")
updateServiceCmd.Flags().StringVar(&inputFormat, "format", "", "Format of service description file [json, yaml]")
}
var createAnyway bool
var inputFormat string
var serviceFile string
var (
serviceCmd = &cobra.Command{
Use: "service",
Aliases: []string{"s", "services"},
Short: "Create and manage services ",
}
listServiceCmd = &cobra.Command{
Use: "list",
Short: "List existing service",
RunE: func(cmd *cobra.Command, args []string) error {
req := &sdk.ListServiceRequest{Offset: 0, Limit: 50}
if offset > 0 {
req.Offset = offset
}
if limit > 0 {
req.Limit = limit
}
if res, err := sdk.ListServicesRaw(context.Background(), req, CreateAdapter(true), logger); err == nil {
switch outputFormat {
case "json":
a.ReplyPrinter(res, false)
case "yaml":
a.ReplyPrinter(res, true)
default:
var list api.ListResponseBody
res.AsType(&list)
printServiceTable(&list, false)
}
return nil
} else {
return err
}
},
}
readServiceCmd = &cobra.Command{
Use: "get [flags] service_id",
Aliases: []string{"read"},
Short: "Fetch details about a single service",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
recordID := GetHistory(args[0])
req := &sdk.ReadServiceRequest{Id: GetHistory(recordID)}
switch outputFormat {
case "json", "yaml":
if res, err := sdk.ReadServiceRaw(context.Background(), req, CreateAdapter(true), logger); err == nil {
a.ReplyPrinter(res, outputFormat == "yaml")
} else {
return err
}
default:
if service, err := sdk.ReadService(context.Background(), req, CreateAdapter(true), logger); err == nil {
printService(service, false)
} else {
return err
}
}
return nil
},
}
createServiceCmd = &cobra.Command{
Use: "create [flags] -f service-file|-",
Short: "Create a new service",
Long: `Define a new service to available on the platform. The service is
described in a service definition file. If the service definition is provided
through 'stdin' use '-' as the file name and also include the --format flag`,
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) (err error) {
ctxt := context.Background()
pyld, err := payloadFromFile(serviceFile, inputFormat)
if err != nil {
cobra.CheckErr(fmt.Sprintf("While reading service file '%s' - %s", serviceFile, err))
}
var req api.CreateRequestBody
if err = pyld.AsType(&req); err != nil {
return
}
if res, err := sdk.CreateServiceRaw(ctxt, &req, CreateAdapter(true), logger); err == nil {
a.ReplyPrinter(res, outputFormat == "yaml")
} else {
return err
}
return nil
},
}
updateServiceCmd = &cobra.Command{
Use: "update [flags] service-id -f service-file|-",
Short: "Update an existing service",
Long: `Update an existing service description or create it if it does not exist
AND the --create flag is set. If the service definition is provided
through 'stdin' use '-' as the file name and also include the --format flag `,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) (err error) {
ctxt := context.Background()
serviceID := GetHistory(args[0])
// serviceFile := args[1]
isYaml := inputFormat == "yaml" || strings.HasSuffix(serviceFile, ".yaml") || strings.HasSuffix(serviceFile, ".yml")
var pyld a.Payload
if serviceFile != "-" {
pyld, err = a.LoadPayloadFromFile(serviceFile, isYaml)
} else {
pyld, err = a.LoadPayloadFromStdin(isYaml)
}
if err != nil {
cobra.CheckErr(fmt.Sprintf("While reading service file '%s' - %s", serviceFile, err))
}
var req api.UpdateRequestBody
if err = pyld.AsType(&req); err != nil {
return
}
if res, err := sdk.UpdateServiceRaw(ctxt, serviceID, createAnyway, &req, CreateAdapter(true), logger); err == nil {
a.ReplyPrinter(res, outputFormat == "yaml")
} else {
return err
}
return nil
},
}
)
func printServiceTable(list *api.ListResponseBody, wide bool) {
t := table.NewWriter()
t.SetOutputMirror(os.Stdout)
t.AppendHeader(table.Row{"ID", "Name", "Provider"})
rows := make([]table.Row, len(list.Services))
for i, o := range list.Services {
rows[i] = table.Row{MakeHistory(o.ID), safeTruncString(o.Name), safeString(o.Provider.ID)}
}
t.AppendRows(rows)
t.Render()
}
func printService(service *api.ReadResponseBody, wide bool) {
// Name *string `form:"name,omitempty" json:"name,omitempty" xml:"name,omitempty"`
// Label *string `form:"label,omitempty" json:"label,omitempty" xml:"label,omitempty"`
// Type *string `form:"type,omitempty" json:"type,omitempty" xml:"type,omitempty"`
// Description *string `form:"description,omitempty" json:"description,omitempty" xml:"description,omitempty"`
// Unit *string `form:"unit,omitempty" json:"unit,omitempty" xml:"unit,omitempty"`
// Constant *bool `form:"constant,omitempty" json:"constant,omitempty" xml:"constant,omitempty"`
// Optional *bool `form:"optional,omitempty" json:"optional,omitempty" xml:"optional,omitempty"`
// Default *string `form:"default,omitempty" json:"default,omitempty" xml:"default,omitempty"`
// Options []*ParameterOptTResponseBody `form:"options,omitempty" json:"options,omitempty" xml:"options,omitempty"`
tw2 := table.NewWriter()
tw2.SetStyle(table.StyleLight)
tw2.SetColumnConfigs([]table.ColumnConfig{
{Number: 1, Align: text.AlignRight},
{Number: 2, WidthMax: MAX_NAME_COL_LEN},
})
tw2.Style().Options.SeparateRows = true
tw2.AppendHeader(table.Row{"Name", "Description", "Type", "Default"})
rows := make([]table.Row, len(service.Parameters))
for i, p := range service.Parameters {
ptype := getPType(p)
rows[i] = table.Row{safeString(p.Name), safeString(p.Description), ptype, safeString(p.Default)}
}
tw2.AppendRows(rows)
tw := table.NewWriter()
tw.SetStyle(table.StyleLight)
tw.Style().Options.SeparateColumns = false
tw.Style().Options.SeparateRows = false
tw.Style().Options.DrawBorder = false
tw.SetColumnConfigs([]table.ColumnConfig{
{Number: 1, Align: text.AlignRight},
// {Number: 2, WidthMax: 80},
})
tw.AppendRows([]table.Row{
{"ID", *service.ID},
{"Name", safeString(service.Name)},
{"Description", safeString(service.Description)},
{"Status", safeString(service.Status)},
{"Provider ID", safeString(service.Provider.ID)},
{"Account ID", safeString(service.Account.ID)},
{"Parameters", tw2.Render()},
})
fmt.Printf("\n%s\n\n", tw.Render())
}
func getPType(p *api.ParameterDefTResponseBody) string {
if p == nil {
return "???"
}
if p.Options == nil {
// normal type
return *p.Type
}
oa := make([]string, len(p.Options))
for i, el := range p.Options {
oa[i] = *el.Value
}
return fmt.Sprintf("[%s]", strings.Join(oa, ","))
}
func GetServiceNameForId(serviceID *string) string {
if serviceID == nil {
return "???"
}
req := &sdk.ReadServiceRequest{
Id: *serviceID,
}
if resp, err := sdk.ReadService(context.Background(), req, CreateAdapter(true), logger); err == nil {
return *resp.Name
} else {
return *serviceID
}
}