servicecertificates.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package options
  15. import (
  16. "fmt"
  17. "io/ioutil"
  18. "yunion.io/x/jsonutils"
  19. )
  20. type ServiceCertificateCreateOptions struct {
  21. NAME string
  22. Cert string `required:"true" json:"-" help:"path to certificate file"`
  23. Pkey string `required:"true" json:"-" help:"path to private key file"`
  24. CaCert string `help:"path to ca certificate file" json:"-"`
  25. CaPkey string `help:"paht to ca private key file" json:"-"`
  26. }
  27. func serviceCertificateLoadFiles(pathM map[string]string, allowEmpty bool) (*jsonutils.JSONDict, error) {
  28. params := jsonutils.NewDict()
  29. for fieldName, path := range pathM {
  30. if path == "" {
  31. if allowEmpty {
  32. continue
  33. } else {
  34. return nil, fmt.Errorf("%s: empty path", fieldName)
  35. }
  36. }
  37. d, err := ioutil.ReadFile(path)
  38. if err != nil {
  39. return nil, fmt.Errorf("%s: read %s: %s", fieldName, path, err)
  40. }
  41. if len(d) == 0 {
  42. return nil, fmt.Errorf("%s: empty file %s", fieldName, path)
  43. }
  44. params.Set(fieldName, jsonutils.NewString(string(d)))
  45. }
  46. return params, nil
  47. }
  48. func (opts *ServiceCertificateCreateOptions) Params() (*jsonutils.JSONDict, error) {
  49. params, err := StructToParams(opts)
  50. if err != nil {
  51. return nil, err
  52. }
  53. pathM := map[string]string{
  54. "certificate": opts.Cert,
  55. "private_key": opts.Pkey,
  56. }
  57. paramsCertKey, err := serviceCertificateLoadFiles(pathM, false)
  58. if err != nil {
  59. return nil, err
  60. }
  61. params.Update(paramsCertKey)
  62. pathM = map[string]string{
  63. "ca_certificate": opts.CaCert,
  64. "ca_private_key": opts.CaPkey,
  65. }
  66. paramsCertKey, err = serviceCertificateLoadFiles(pathM, false)
  67. if err != nil {
  68. return nil, err
  69. }
  70. params.Update(paramsCertKey)
  71. return params, nil
  72. }