2 * Copyright 2018 Intel Corporation, Inc
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
34 pkgerrors "github.com/pkg/errors"
37 //DataJSON stores a list of domains from JSON file
38 type DataJSON struct {
39 //Support single domain: {} structure in JSON
40 Domain SecretDomainJSON `json:"domain,omitempty"`
41 //Support plural domains: [{}] structure in JSON
42 Domains []SecretDomainJSON `json:"domains,omitempty"`
45 //SecretDomainJSON stores a name for the Domain and a list of Secrets
46 type SecretDomainJSON struct {
47 Name string `json:"name"`
48 Secrets []SecretJSON `json:"secrets"`
51 //SecretJSON stores a name for the Secret and a list of Values
52 type SecretJSON struct {
53 Name string `json:"name"`
54 Values map[string]interface{} `json:"values"`
57 //Processes the JSON file and returns a DataJSON struct
58 func processJSONFile(name string) (DataJSON, error) {
60 data, err := ioutil.ReadFile(name)
62 return DataJSON{}, pkgerrors.Cause(err)
66 err = json.Unmarshal(data, &d)
68 return DataJSON{}, pkgerrors.Cause(err)
74 type smsClient struct {
80 httpClient *http.Client
83 func (c *smsClient) init() error {
86 caCert, err := ioutil.ReadFile(c.CaCertPath)
88 fmt.Println(pkgerrors.Cause(err))
89 fmt.Println("Using Insecure Server Verification")
93 tlsConfig := &tls.Config{
94 MinVersion: tls.VersionTLS12,
97 tlsConfig.InsecureSkipVerify = skipVerify
99 // Add cert information when skipVerify is false
100 if skipVerify == false {
101 caCertPool := x509.NewCertPool()
102 caCertPool.AppendCertsFromPEM(caCert)
103 tlsConfig.RootCAs = caCertPool
106 tr := &http.Transport{
107 TLSClientConfig: tlsConfig,
110 c.httpClient = &http.Client{
112 Timeout: time.Duration(c.Timeout) * time.Second,
118 func (c *smsClient) resolveURL(relURL string) (*url.URL, error) {
120 rel, err := url.Parse(relURL)
122 return nil, pkgerrors.Cause(err)
125 return c.BaseURL.ResolveReference(rel), nil
129 func (c *smsClient) sendGetRequest(relURL string) (map[string]interface{}, error) {
131 u, err := c.resolveURL(relURL)
133 return nil, pkgerrors.Cause(err)
136 resp, err := c.httpClient.Get(u.String())
138 return nil, pkgerrors.Cause(err)
141 if resp.StatusCode >= 400 && resp.StatusCode < 600 {
143 errText, _ := ioutil.ReadAll(resp.Body)
144 return nil, pkgerrors.Errorf("Request Failed with: %s and Error: %s",
145 resp.Status, string(errText))
148 var result map[string]interface{}
149 err = json.NewDecoder(resp.Body).Decode(&result)
151 return nil, pkgerrors.Cause(err)
157 func (c *smsClient) sendPostRequest(relURL string, message map[string]interface{}) error {
159 u, err := c.resolveURL(relURL)
161 return pkgerrors.Cause(err)
164 body, err := json.Marshal(message)
166 return pkgerrors.Cause(err)
169 resp, err := c.httpClient.Post(u.String(), "application/json", bytes.NewBuffer(body))
171 return pkgerrors.Cause(err)
174 if resp.StatusCode >= 400 && resp.StatusCode < 600 {
176 errText, _ := ioutil.ReadAll(resp.Body)
177 return pkgerrors.Errorf("Request Failed with: %s and Error: %s",
178 resp.Status, string(errText))
184 func (c *smsClient) createDomain(domain string) error {
186 message := map[string]interface{}{
189 url := "/v1/sms/domain"
190 err := c.sendPostRequest(url, message)
192 return pkgerrors.Cause(err)
197 func (c *smsClient) createSecret(domain string, secret string,
198 values map[string]interface{}) error {
200 message := map[string]interface{}{
205 url := "/v1/sms/domain/" + strings.TrimSpace(domain) + "/secret"
206 err := c.sendPostRequest(url, message)
208 return pkgerrors.Cause(err)
214 func (c *smsClient) isReady() bool {
216 url := "v1/sms/quorum/status"
217 res, err := c.sendGetRequest(url)
219 fmt.Println(pkgerrors.Cause(err))
223 if res["sealstatus"] == true {
230 //uploadToSMS reads through the domain or domains and uploads
231 //their corresponding secrets to SMS service
232 func (c *smsClient) uploadToSMS(data DataJSON) error {
234 var ldata []SecretDomainJSON
236 //Check if Domain is empty
237 if strings.TrimSpace(data.Domain.Name) != "" {
238 ldata = append(ldata, data.Domain)
239 } else if len(data.Domains) != 0 {
240 //Check if plural Domains are empty
241 ldata = append(ldata, data.Domains...)
243 return pkgerrors.New("Invalid JSON Data. No domain or domains found")
246 isReady := make(chan bool)
248 for c.isReady() == false {
249 time.Sleep(5 * time.Second)
250 fmt.Println("Waiting for SMS to accept requests...")
256 fmt.Println("Uploading data...")
258 for _, d := range ldata {
259 err := c.createDomain(d.Name)
261 return pkgerrors.Cause(err)
264 for _, s := range d.Secrets {
265 err = c.createSecret(d.Name, s.Name, s.Values)
267 return pkgerrors.Cause(err)
277 cacert := flag.String("cacert", "/sms/certs/aaf_root_ca.cer",
278 "Path to the CA Certificate file")
279 serviceurl := flag.String("serviceurl", "https://aaf-sms.onap",
280 "Url for the SMS Service")
281 serviceport := flag.String("serviceport", "10443",
282 "Service port if its different than the default")
283 jsondir := flag.String("jsondir", ".",
284 "Folder containing json files to upload")
288 //Clear all trailing/leading spaces from incoming strings
289 *cacert = strings.TrimSpace(*cacert)
290 *serviceurl = strings.TrimSpace(*serviceurl)
291 *serviceport = strings.TrimSpace(*serviceport)
292 *jsondir = strings.TrimSpace(*jsondir)
294 files, err := ioutil.ReadDir(*jsondir)
296 log.Fatal(pkgerrors.Cause(err))
299 //URL validity is checked here
300 serviceURL, err := url.Parse(*serviceurl + ":" + *serviceport)
302 log.Fatal(pkgerrors.Cause(err))
305 client := &smsClient{
312 for _, file := range files {
313 if filepath.Ext(file.Name()) == ".json" {
314 fmt.Println("Processing ", filepath.Join(*jsondir, file.Name()))
315 d, err := processJSONFile(filepath.Join(*jsondir, file.Name()))
317 log.Printf("Error Reading %s : %s", file.Name(), pkgerrors.Cause(err))
321 err = client.uploadToSMS(d)
323 log.Printf("Error Uploading %s : %s", file.Name(), pkgerrors.Cause(err))