forked from PaloAltoNetworks/pango
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
2116 lines (1824 loc) · 52.9 KB
/
client.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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package pango
import (
"bytes"
"crypto/tls"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"mime"
"mime/multipart"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/PaloAltoNetworks/pango/errors"
"github.com/PaloAltoNetworks/pango/plugin"
"github.com/PaloAltoNetworks/pango/util"
"github.com/PaloAltoNetworks/pango/version"
)
// These bit flags control what is logged by client connections. Of the flags
// available for use, LogSend and LogReceive will log ALL communication between
// the connection object and the PAN-OS XML API. The API key being used for
// communication will be blanked out, but no other sensitive data will be. As
// such, those two flags should be considered for debugging only. To disable
// all logging, set the logging level as LogQuiet.
//
// As of right now, pango is not officially supported by Palo Alto Networks TAC,
// however using the API itself via cURL is. If you run into an issue and you believe
// it to be a PAN-OS problem, you can enable a cURL output logging style to have pango
// output an equivalent cURL command to use when interfacing with TAC.
//
// If you want to get the cURL command so that you can run it yourself, then set
// the LogCurlWithPersonalData flag, which will output your real API key, hostname,
// and any custom headers you have configured the client to send to PAN-OS.
//
// The bit-wise flags are as follows:
//
// * LogQuiet: disables all logging
// * LogAction: action being performed (Set / Edit / Delete functions)
// * LogQuery: queries being run (Get / Show functions)
// * LogOp: operation commands (Op functions)
// * LogUid: User-Id commands (Uid functions)
// * LogLog: log retrieval commands
// * LogExport: log export commands
// * LogXpath: the resultant xpath
// * LogSend: xml docuemnt being sent
// * LogReceive: xml responses being received
// * LogOsxCurl: output an OSX cURL command for the data being sent in
// * LogCurlWithPersonalData: If doing a curl style logging, then include
// personal data in the curl command instead of tokens.
const (
LogQuiet = 1 << (iota + 1)
LogAction
LogQuery
LogOp
LogUid
LogLog
LogExport
LogImport
LogXpath
LogSend
LogReceive
LogOsxCurl
LogCurlWithPersonalData
)
// Client is a generic connector struct. It provides wrapper functions for
// invoking the various PAN-OS XPath API methods. After creating the client,
// invoke Initialize() to prepare it for use.
//
// Many of the functions attached to this struct will take a param named
// `extras`. Under normal circumstances this will just be nil, but if you have
// some extra values you need to send in with your request you can specify them
// here.
//
// Likewise, a lot of these functions will return a slice of bytes. Under normal
// circumstances, you don't need to do anything with this, but sometimes you do,
// so you can find the raw XML returned from PAN-OS there.
type Client struct {
// Connection properties.
Hostname string `json:"hostname"`
Username string `json:"username"`
Password string `json:"password"`
ApiKey string `json:"api_key"`
Protocol string `json:"protocol"`
Port uint `json:"port"`
Timeout int `json:"timeout"`
Target string `json:"target"`
Headers map[string]string `json:"headers"`
// Set to true if you want to check environment variables
// for auth and connection properties.
CheckEnvironment bool `json:"-"`
// HTTP transport options. Note that the VerifyCertificate setting is
// only used if you do not specify a HTTP transport yourself.
VerifyCertificate bool `json:"verify_certificate"`
Transport *http.Transport `json:"-"`
// Variables determined at runtime.
Version version.Number `json:"-"`
SystemInfo map[string]string `json:"-"`
Plugin []plugin.Info `json:"-"`
MultiConfigure *MultiConfigure `json:"-"`
// Logging level.
Logging uint32 `json:"-"`
LoggingFromInitialize []string `json:"logging"`
// Internal variables.
credsFile string
con *http.Client
api_url string
configTree *util.XmlNode
// Variables for testing, response bytes, headers, and response index.
rp []url.Values
rb [][]byte
rh []http.Header
ri int
authFileContent []byte
}
// String is the string representation of a client connection. Both the
// password and API key are replaced with stars, if set, making it safe
// to print the client connection in log messages.
func (c *Client) String() string {
var passwd string
var api_key string
if c.Password == "" {
passwd = ""
} else {
passwd = "********"
}
if c.ApiKey == "" {
api_key = ""
} else {
api_key = "********"
}
return fmt.Sprintf(
"{Hostname:%s Username:%s Password:%s ApiKey:%s Protocol:%s Port:%d Timeout:%d Logging:%d}",
c.Hostname, c.Username, passwd, api_key, c.Protocol, c.Port, c.Timeout, c.Logging)
}
// Versioning returns the client version number.
func (c *Client) Versioning() version.Number {
return c.Version
}
// Plugins returns the plugin information.
func (c *Client) Plugins() []plugin.Info {
return c.Plugin
}
// Initialize does some initial setup of the Client connection, retrieves
// the API key if it was not already present, then performs "show system
// info" to get the PAN-OS version. The full results are saved into the
// client's SystemInfo map.
//
// If not specified, the following is assumed:
// * Protocol: https
// * Port: (unspecified)
// * Timeout: 10
// * Logging: LogAction | LogUid
func (c *Client) Initialize() error {
if len(c.rb) == 0 {
var e error
if e = c.initCon(); e != nil {
return e
} else if e = c.initApiKey(); e != nil {
return e
} else if e = c.initSystemInfo(); e != nil {
return e
}
} else {
c.Hostname = "localhost"
c.ApiKey = "password"
}
return nil
}
// InitializeUsing does Initialize(), but takes in a filename that contains
// fallback authentication credentials if they aren't specified.
//
// The order of preference for auth / connection settings is:
//
// * explicitly set
// * environment variable (set chkenv to true to enable this)
// * json file
func (c *Client) InitializeUsing(filename string, chkenv bool) error {
c.CheckEnvironment = chkenv
c.credsFile = filename
return c.Initialize()
}
// RetrieveApiKey retrieves the API key, which will require that both the
// username and password are defined.
//
// The currently set ApiKey is forgotten when invoking this function.
func (c *Client) RetrieveApiKey() error {
c.LogAction("%s: Retrieving API key", c.Hostname)
type key_gen_ans struct {
Key string `xml:"result>key"`
}
c.ApiKey = ""
ans := key_gen_ans{}
data := url.Values{}
data.Add("user", c.Username)
data.Add("password", c.Password)
data.Add("type", "keygen")
_, _, err := c.Communicate(data, &ans)
if err != nil {
return err
}
c.ApiKey = ans.Key
return nil
}
// EntryListUsing retrieves an list of entries using the given function, either
// Get or Show.
func (c *Client) EntryListUsing(fn util.Retriever, path []string) ([]string, error) {
var err error
type Entry struct {
Name string `xml:"name,attr"`
}
type resp_struct struct {
Entries []Entry `xml:"result>entry"`
}
if path == nil {
return nil, fmt.Errorf("xpath is empty")
}
path = append(path, "entry", "@name")
resp := resp_struct{}
_, err = fn(path, nil, &resp)
if err != nil {
e2, ok := err.(errors.Panos)
if ok && e2.ObjectNotFound() {
return nil, nil
}
return nil, err
}
ans := make([]string, len(resp.Entries))
for i := range resp.Entries {
ans[i] = resp.Entries[i].Name
}
return ans, nil
}
// MemberListUsing retrieves an list of members using the given function, either
// Get or Show.
func (c *Client) MemberListUsing(fn util.Retriever, path []string) ([]string, error) {
type resp_struct struct {
Members []string `xml:"result>member"`
}
if path == nil {
return nil, fmt.Errorf("xpath is empty")
}
path = append(path, "member")
resp := resp_struct{}
_, err := fn(path, nil, &resp)
if err != nil {
e2, ok := err.(errors.Panos)
if ok && e2.ObjectNotFound() {
return nil, nil
}
return nil, err
}
return resp.Members, nil
}
// RequestPasswordHash requests a password hash of the given string.
func (c *Client) RequestPasswordHash(val string) (string, error) {
c.LogOp("(op) creating password hash")
type phash_req struct {
XMLName xml.Name `xml:"request"`
Val string `xml:"password-hash>password"`
}
type phash_ans struct {
Hash string `xml:"result>phash"`
}
req := phash_req{Val: val}
ans := phash_ans{}
if _, err := c.Op(req, "", nil, &ans); err != nil {
return "", err
}
return ans.Hash, nil
}
// ValidateConfig performs a commit config validation check.
//
// Setting sync to true means that this function will block until the job
// finishes.
//
//
// The sleep param is an optional sleep duration to wait between polling for
// job completion. This param is only used if sync is set to true.
//
// This function returns the job ID and if any errors were encountered.
func (c *Client) ValidateConfig(sync bool, sleep time.Duration) (uint, error) {
var err error
c.LogOp("(op) validating config")
type op_req struct {
XMLName xml.Name `xml:"validate"`
Cmd string `xml:"full"`
}
job_ans := util.JobResponse{}
_, err = c.Op(op_req{}, "", nil, &job_ans)
if err != nil {
return 0, err
}
id := job_ans.Id
if !sync {
return id, nil
}
return id, c.WaitForJob(id, sleep, nil, nil)
}
// RevertToRunningConfig discards any changes made and reverts to the last
// config committed.
func (c *Client) RevertToRunningConfig() error {
c.LogOp("(op) reverting to running config")
_, err := c.Op("<load><config><from>running-config.xml</from></config></load>", "", nil, nil)
return err
}
// ConfigLocks returns any config locks that are currently in place.
//
// If vsys is an empty string, then the vsys will default to "shared".
func (c *Client) ConfigLocks(vsys string) ([]util.Lock, error) {
var err error
var cmd string
ans := configLocks{}
if vsys == "" {
vsys = "shared"
}
if c.Version.Gte(version.Number{9, 1, 0, ""}) {
var tgt string
if vsys == "shared" {
tgt = "all"
} else {
tgt = vsys
}
cmd = fmt.Sprintf("<show><config-locks><vsys>%s</vsys></config-locks></show>", tgt)
} else {
cmd = "<show><config-locks /></show>"
}
c.LogOp("(op) getting config locks for scope %q", vsys)
_, err = c.Op(cmd, vsys, nil, &ans)
if err != nil {
return nil, err
}
return ans.Locks, nil
}
// LockConfig locks the config for the given scope with the given comment.
//
// If vsys is an empty string, the scope defaults to "shared".
func (c *Client) LockConfig(vsys, comment string) error {
if vsys == "" {
vsys = "shared"
}
c.LogOp("(op) locking config for scope %q", vsys)
var inner string
if comment == "" {
inner = "<add />"
} else {
inner = fmt.Sprintf("<add><comment>%s</comment></add>", comment)
}
cmd := fmt.Sprintf("<request><config-lock>%s</config-lock></request>", inner)
_, err := c.Op(cmd, vsys, nil, nil)
return err
}
// UnlockConfig removes the config lock on the given scope.
//
// If vsys is an empty string, the scope defaults to "shared".
func (c *Client) UnlockConfig(vsys string) error {
if vsys == "" {
vsys = "shared"
}
type cmd struct {
XMLName xml.Name `xml:"request"`
Cmd string `xml:"config-lock>remove"`
}
c.LogOp("(op) unlocking config for scope %q", vsys)
_, err := c.Op(cmd{}, vsys, nil, nil)
return err
}
// CommitLocks returns any commit locks that are currently in place.
//
// If vsys is an empty string, then the vsys will default to "shared".
func (c *Client) CommitLocks(vsys string) ([]util.Lock, error) {
if vsys == "" {
vsys = "shared"
}
c.LogOp("(op) getting commit locks for scope %q", vsys)
ans := commitLocks{}
_, err := c.Op("<show><commit-locks /></show>", vsys, nil, &ans)
if err != nil {
return nil, err
}
return ans.Locks, nil
}
// LockCommits locks commits for the given scope with the given comment.
//
// If vsys is an empty string, the scope defaults to "shared".
func (c *Client) LockCommits(vsys, comment string) error {
if vsys == "" {
vsys = "shared"
}
c.LogOp("(op) locking commits for scope %q", vsys)
var inner string
if comment == "" {
inner = "<add />"
} else {
inner = fmt.Sprintf("<add><comment>%s</comment></add>", comment)
}
cmd := fmt.Sprintf("<request><commit-lock>%s</commit-lock></request>", inner)
_, err := c.Op(cmd, vsys, nil, nil)
return err
}
// UnlockCommits removes the commit lock on the given scope owned by the given
// admin, if this admin is someone other than the current acting admin.
//
// If vsys is an empty string, the scope defaults to "shared".
func (c *Client) UnlockCommits(vsys, admin string) error {
if vsys == "" {
vsys = "shared"
}
type cmd struct {
XMLName xml.Name `xml:"request"`
Admin string `xml:"commit-lock>remove>admin,omitempty"`
}
c.LogOp("(op) unlocking commits for scope %q", vsys)
_, err := c.Op(cmd{Admin: admin}, vsys, nil, nil)
return err
}
// WaitForJob polls the device, waiting for the specified job to finish.
//
// The sleep param is the length of time to wait between polling for job
// completion.
//
// The extras param should be either nil or a url.Values{} to be mixed in with
// the constructed request.
//
// If you want to unmarshal the response into a struct, then pass in a
// pointer to the struct for the "resp" param. If you just want to know if
// the job completed with a status other than "FAIL", you only need to check
// the returned error message.
//
// In the case that there are multiple errors returned from the job, the first
// error is returned as the error string, and no unmarshaling is attempted.
func (c *Client) WaitForJob(id uint, sleep time.Duration, extras, resp interface{}) error {
var err error
var prev uint
var data []byte
dp := false
all_ok := true
c.LogOp("(op) waiting for job %d", id)
type op_req struct {
XMLName xml.Name `xml:"show"`
Id uint `xml:"jobs>id"`
}
req := op_req{Id: id}
var ans util.BasicJob
for {
// We need to zero out the response each iteration because the slices
// of strings append to each other instead of zeroing out.
ans = util.BasicJob{}
// Get current percent complete.
data, err = c.Op(req, "", extras, &ans)
if err != nil {
return err
}
// Output percent complete if it's new.
if ans.Progress != prev {
prev = ans.Progress
c.LogOp("(op) job %d: %d percent complete", id, prev)
}
// Check for device commits.
all_done := true
for _, d := range ans.Devices {
c.LogOp("%q result: %s", d.Serial, d.Result)
if d.Result == "PEND" {
all_done = false
break
} else if d.Result != "OK" && all_ok {
all_ok = false
}
}
// Check for end condition.
if ans.Progress == 100 {
if all_done {
break
} else if !dp {
c.LogOp("(op) Waiting for %d device commits ...", len(ans.Devices))
dp = true
}
}
if sleep > 0 {
time.Sleep(sleep)
}
}
// Check the results for a failed commit.
if ans.Result == "FAIL" {
if len(ans.Details.Lines) > 0 {
return fmt.Errorf(ans.Details.String())
} else {
return fmt.Errorf("Job %d has failed to complete successfully", id)
}
} else if !all_ok {
return fmt.Errorf("Commit failed on one or more devices")
}
if resp == nil {
return nil
}
return xml.Unmarshal(data, resp)
}
// LogAction writes a log message for SET/EDIT/DELETE operations if LogAction is set.
func (c *Client) LogAction(msg string, i ...interface{}) {
if c.Logging&LogAction == LogAction {
log.Printf(msg, i...)
}
}
// LogQuery writes a log message for GET/SHOW operations if LogQuery is set.
func (c *Client) LogQuery(msg string, i ...interface{}) {
if c.Logging&LogQuery == LogQuery {
log.Printf(msg, i...)
}
}
// LogOp writes a log message for OP operations if LogOp is set.
func (c *Client) LogOp(msg string, i ...interface{}) {
if c.Logging&LogOp == LogOp {
log.Printf(msg, i...)
}
}
// LogUid writes a log message for User-Id operations if LogUid is set.
func (c *Client) LogUid(msg string, i ...interface{}) {
if c.Logging&LogUid == LogUid {
log.Printf(msg, i...)
}
}
// LogLog writes a log message for LOG operations if LogLog is set.
func (c *Client) LogLog(msg string, i ...interface{}) {
if c.Logging&LogLog == LogLog {
log.Printf(msg, i...)
}
}
// LogExport writes a log message for EXPORT operations if LogExport is set.
func (c *Client) LogExport(msg string, i ...interface{}) {
if c.Logging&LogExport == LogExport {
log.Printf(msg, i...)
}
}
// LogImport writes a log message for IMPORT operations if LogImport is set.
func (c *Client) LogImport(msg string, i ...interface{}) {
if c.Logging&LogImport == LogImport {
log.Printf(msg, i...)
}
}
// Communicate sends the given data to PAN-OS.
//
// The ans param should be a pointer to a struct to unmarshal the response
// into or nil.
//
// Any response received from the server is returned, along with any errors
// encountered.
//
// Even if an answer struct is given, we first check for known error formats. If
// a known error format is detected, unmarshalling into the answer struct is not
// performed.
//
// If the API key is set, but not present in the given data, then it is added in.
func (c *Client) Communicate(data url.Values, ans interface{}) ([]byte, http.Header, error) {
if c.ApiKey != "" && data.Get("key") == "" {
data.Set("key", c.ApiKey)
}
c.logSend(data)
body, hdrs, err := c.post(data)
if err != nil {
return body, hdrs, err
}
return body, hdrs, c.endCommunication(body, ans)
}
// CommunicateFile does a file upload to PAN-OS.
//
// The content param is the content of the file you want to upload.
//
// The filename param is the basename of the file you want to specify in the
// multipart form upload.
//
// The fp param is the name of the param for the file upload.
//
// The ans param should be a pointer to a struct to unmarshal the response
// into or nil.
//
// Any response received from the server is returned, along with any errors
// encountered.
//
// Even if an answer struct is given, we first check for known error formats. If
// a known error format is detected, unmarshalling into the answer struct is not
// performed.
//
// If the API key is set, but not present in the given data, then it is added in.
func (c *Client) CommunicateFile(content, filename, fp string, data url.Values, ans interface{}) ([]byte, http.Header, error) {
var err error
if c.ApiKey != "" && data.Get("key") == "" {
data.Set("key", c.ApiKey)
}
c.logSend(data)
buf := bytes.Buffer{}
w := multipart.NewWriter(&buf)
for k := range data {
w.WriteField(k, data.Get(k))
}
w2, err := w.CreateFormFile(fp, filename)
if err != nil {
return nil, nil, err
}
if _, err = io.Copy(w2, strings.NewReader(content)); err != nil {
return nil, nil, err
}
w.Close()
req, err := http.NewRequest("POST", c.api_url, &buf)
if err != nil {
return nil, nil, err
}
req.Header.Set("Content-Type", w.FormDataContentType())
for k, v := range c.Headers {
req.Header.Set(k, v)
}
res, err := c.con.Do(req)
if err != nil {
return nil, nil, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return body, res.Header, err
}
return body, res.Header, c.endCommunication(body, ans)
}
// Op runs an operational or "op" type command.
//
// The req param can be either a properly formatted XML string or a struct
// that can be marshalled into XML.
//
// The vsys param is the vsys the op command should be executed in, if any.
//
// The extras param should be either nil or a url.Values{} to be mixed in with
// the constructed request.
//
// The ans param should be a pointer to a struct to unmarshal the response
// into or nil.
//
// Any response received from the server is returned, along with any errors
// encountered.
func (c *Client) Op(req interface{}, vsys string, extras, ans interface{}) ([]byte, error) {
var err error
data := url.Values{}
data.Set("type", "op")
if err = addToData("cmd", req, true, &data); err != nil {
return nil, err
}
if vsys != "" {
data.Set("vsys", vsys)
}
if c.Target != "" {
data.Set("target", c.Target)
}
if err = mergeUrlValues(&data, extras); err != nil {
return nil, err
}
b, _, err := c.Communicate(data, ans)
return b, err
}
// Log submits a "log" command.
//
// Use `WaitForLogs` to get the results of the log command.
//
// The extras param should be either nil or a url.Values{} to be mixed in with
// the constructed request.
//
// Any response received from the server is returned, along with any errors
// encountered.
func (c *Client) Log(logType, action, query, dir string, nlogs, skip int, extras, ans interface{}) ([]byte, error) {
data := url.Values{}
data.Set("type", "log")
if logType != "" {
data.Set("log-type", logType)
}
if action != "" {
data.Set("action", action)
}
if query != "" {
data.Set("query", query)
}
if dir != "" {
data.Set("dir", dir)
}
if nlogs != 0 {
data.Set("nlogs", strconv.Itoa(nlogs))
}
if skip != 0 {
data.Set("skip", strconv.Itoa(skip))
}
if err := mergeUrlValues(&data, extras); err != nil {
return nil, err
}
b, _, err := c.Communicate(data, ans)
return b, err
}
// WaitForLogs performs repeated log retrieval operations until the log job is complete
// or the timeout is reached.
//
// Specify a timeout of zero to wait indefinitely.
//
// The ans param should be a pointer to a struct to unmarshal the response
// into or nil.
//
// Any response received from the server is returned, along with any errors
// encountered.
func (c *Client) WaitForLogs(id uint, sleep, timeout time.Duration, ans interface{}) ([]byte, error) {
var err error
var data []byte
var prev string
start := time.Now()
end := start.Add(timeout)
extras := url.Values{}
extras.Set("job-id", fmt.Sprintf("%d", id))
c.LogLog("(log) waiting for logs: %d", id)
var resp util.BasicJob
for {
resp = util.BasicJob{}
data, err = c.Log("", "get", "", "", 0, 0, extras, &resp)
if err != nil {
return data, err
}
if resp.Status != prev {
prev = resp.Status
c.LogLog("(log) job %d status: %s", id, prev)
}
if resp.Status == "FIN" {
break
}
if timeout > 0 && end.After(time.Now()) {
return data, fmt.Errorf("timeout")
}
if sleep > 0 {
time.Sleep(sleep)
}
}
if resp.Result == "FAIL" {
if len(resp.Details.Lines) > 0 {
return data, fmt.Errorf(resp.Details.String())
} else {
return data, fmt.Errorf("Job %d has failed to complete successfully", id)
}
}
if ans == nil {
return data, nil
}
err = xml.Unmarshal(data, ans)
return data, err
}
// Show runs a "show" type command.
//
// The path param should be either a string or a slice of strings.
//
// The extras param should be either nil or a url.Values{} to be mixed in with
// the constructed request.
//
// The ans param should be a pointer to a struct to unmarshal the response
// into or nil.
//
// Any response received from the server is returned, along with any errors
// encountered.
func (c *Client) Show(path, extras, ans interface{}) ([]byte, error) {
data := url.Values{}
xp := util.AsXpath(path)
c.logXpath(xp)
data.Set("xpath", xp)
return c.typeConfig("show", data, nil, extras, ans)
}
// Get runs a "get" type command.
//
// The path param should be either a string or a slice of strings.
//
// The extras param should be either nil or a url.Values{} to be mixed in with
// the constructed request.
//
// The ans param should be a pointer to a struct to unmarshal the response
// into or nil.
//
// Any response received from the server is returned, along with any errors
// encountered.
func (c *Client) Get(path, extras, ans interface{}) ([]byte, error) {
data := url.Values{}
xp := util.AsXpath(path)
c.logXpath(xp)
data.Set("xpath", xp)
return c.typeConfig("get", data, nil, extras, ans)
}
// Delete runs a "delete" type command, removing the supplied xpath and
// everything underneath it.
//
// The path param should be either a string or a slice of strings.
//
// The extras param should be either nil or a url.Values{} to be mixed in with
// the constructed request.
//
// The ans param should be a pointer to a struct to unmarshal the response
// into or nil.
//
// Any response received from the server is returned, along with any errors
// encountered.
func (c *Client) Delete(path, extras, ans interface{}) ([]byte, error) {
data := url.Values{}
xp := util.AsXpath(path)
c.logXpath(xp)
data.Set("xpath", xp)
return c.typeConfig("delete", data, nil, extras, ans)
}
// Set runs a "set" type command, creating the element at the given xpath.
//
// The path param should be either a string or a slice of strings.
//
// The element param can be either a string of properly formatted XML to send
// or a struct which can be marshaled into a string.
//
// The extras param should be either nil or a url.Values{} to be mixed in with
// the constructed request.
//
// The ans param should be a pointer to a struct to unmarshal the response
// into or nil.
//
// Any response received from the server is returned, along with any errors
// encountered.
func (c *Client) Set(path, element, extras, ans interface{}) ([]byte, error) {
data := url.Values{}
xp := util.AsXpath(path)
c.logXpath(xp)
data.Set("xpath", xp)
return c.typeConfig("set", data, element, extras, ans)
}
// Edit runs a "edit" type command, modifying what is at the given xpath
// with the supplied element.
//
// The path param should be either a string or a slice of strings.
//
// The element param can be either a string of properly formatted XML to send
// or a struct which can be marshaled into a string.
//
// The extras param should be either nil or a url.Values{} to be mixed in with
// the constructed request.
//
// The ans param should be a pointer to a struct to unmarshal the response
// into or nil.
//
// Any response received from the server is returned, along with any errors
// encountered.
func (c *Client) Edit(path, element, extras, ans interface{}) ([]byte, error) {
data := url.Values{}
xp := util.AsXpath(path)
c.logXpath(xp)
data.Set("xpath", xp)
return c.typeConfig("edit", data, element, extras, ans)
}
// Move does a "move" type command.
func (c *Client) Move(path interface{}, where, dst string, extras, ans interface{}) ([]byte, error) {
data := url.Values{}
xp := util.AsXpath(path)
c.logXpath(xp)
data.Set("xpath", xp)
if where != "" {
data.Set("where", where)
}
if dst != "" {
data.Set("dst", dst)