forked from influxdata/influxdb
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server_test.go
2160 lines (1865 loc) · 80.6 KB
/
server_test.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 influxdb_test
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/url"
"os"
"reflect"
"strings"
"testing"
"time"
"github.com/influxdb/influxdb"
"github.com/influxdb/influxdb/influxql"
"github.com/influxdb/influxdb/messaging"
"golang.org/x/crypto/bcrypt"
)
// Ensure the server can be successfully opened and closed.
func TestServer_Open(t *testing.T) {
s := NewServer()
defer s.Close()
if err := s.Server.Open(tempfile()); err != nil {
t.Fatal(err)
}
if err := s.Server.Close(); err != nil {
t.Fatal(err)
}
}
// Ensure an error is returned when opening an already open server.
func TestServer_Open_ErrServerOpen(t *testing.T) { t.Skip("pending") }
// Ensure an error is returned when opening a server without a path.
func TestServer_Open_ErrPathRequired(t *testing.T) { t.Skip("pending") }
// Ensure the server can create a new data node.
func TestServer_CreateDataNode(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
// Create a new node.
u, _ := url.Parse("http://localhost:80000")
if err := s.CreateDataNode(u); err != nil {
t.Fatal(err)
}
s.Restart()
// Verify that the node exists.
if n := s.DataNodeByURL(u); n == nil {
t.Fatalf("data node not found")
} else if n.URL.String() != "http://localhost:80000" {
t.Fatalf("unexpected url: %s", n.URL)
} else if n.ID == 0 {
t.Fatalf("unexpected id: %d", n.ID)
}
}
// Ensure the server returns an error when creating a duplicate node.
func TestServer_CreateDatabase_ErrDataNodeExists(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
// Create a node with the same URL twice.
u, _ := url.Parse("http://localhost:80000")
if err := s.CreateDataNode(u); err != nil {
t.Fatal(err)
}
if err := s.CreateDataNode(u); err != influxdb.ErrDataNodeExists {
t.Fatal(err)
}
}
// Ensure the server can delete a node.
func TestServer_DeleteDataNode(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
// Create a data node and verify it exists.
u, _ := url.Parse("http://localhost:80000")
if err := s.CreateDataNode(u); err != nil {
t.Fatal(err)
} else if s.DataNodeByURL(u) == nil {
t.Fatalf("data node not actually created")
}
s.Restart()
// Drop the node and verify that it's gone.
n := s.DataNodeByURL(u)
if err := s.DeleteDataNode(n.ID); err != nil {
t.Fatal(err)
} else if s.DataNode(n.ID) != nil {
t.Fatalf("data node not actually dropped")
}
}
// Test unuathorized requests logging
func TestServer_UnauthorizedRequests(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
s.SetAuthenticationEnabled(true)
var b bytes.Buffer
s.SetLogOutput(&b)
adminOnlyQuery := &influxql.Query{
Statements: []influxql.Statement{
&influxql.DropDatabaseStatement{Name: "foo"},
},
}
e := s.Authorize(nil, adminOnlyQuery, "foo")
if _, ok := e.(influxdb.ErrAuthorize); !ok {
t.Fatalf("unexpected error. expected %v, actual: %v", influxdb.ErrAuthorize{}, e)
}
if !strings.Contains(b.String(), "unauthorized request") {
t.Log(b.String())
t.Fatalf(`log should contain "unuathorized request"`)
}
b.Reset()
// Create normal database user.
s.CreateUser("user1", "user1", false)
user1 := s.User("user1")
e = s.Authorize(user1, adminOnlyQuery, "foo")
if _, ok := e.(influxdb.ErrAuthorize); !ok {
t.Fatalf("unexpected error. expected %v, actual: %v", influxdb.ErrAuthorize{}, e)
}
if !strings.Contains(b.String(), "unauthorized request") {
t.Log(b.String())
t.Fatalf(`log should contain "unuathorized request"`)
}
}
// Test user privilege authorization.
func TestServer_UserPrivilegeAuthorization(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
// Create cluster admin.
s.CreateUser("admin", "admin", true)
admin := s.User("admin")
// Create normal database user.
s.CreateUser("user1", "user1", false)
user1 := s.User("user1")
user1.Privileges["foo"] = influxql.ReadPrivilege
s.Restart()
// admin user should be authorized for all privileges.
if !admin.Authorize(influxql.AllPrivileges, "") {
t.Fatalf("cluster admin doesn't have influxql.AllPrivileges")
} else if !admin.Authorize(influxql.WritePrivilege, "") {
t.Fatalf("cluster admin doesn't have influxql.WritePrivilege")
}
// Normal user with only read privilege on database foo.
if !user1.Authorize(influxql.ReadPrivilege, "foo") {
t.Fatalf("user1 doesn't have influxql.ReadPrivilege on foo")
} else if user1.Authorize(influxql.WritePrivilege, "foo") {
t.Fatalf("user1 has influxql.WritePrivilege on foo")
} else if user1.Authorize(influxql.ReadPrivilege, "bar") {
t.Fatalf("user1 has influxql.ReadPrivilege on bar")
} else if user1.Authorize(influxql.AllPrivileges, "") {
t.Fatalf("user1 is cluster admin")
}
}
// Test single statement query authorization.
func TestServer_SingleStatementQueryAuthorization(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
// Create cluster admin.
s.CreateUser("admin", "admin", true)
admin := s.User("admin")
// Create normal database user.
s.CreateUser("user", "user", false)
user := s.User("user")
user.Privileges["foo"] = influxql.ReadPrivilege
s.Restart()
// Create a query that only cluster admins can run.
adminOnlyQuery := &influxql.Query{
Statements: []influxql.Statement{
&influxql.DropDatabaseStatement{Name: "foo"},
},
}
// Create a query that requires read on one db and write on another.
readWriteQuery := &influxql.Query{
Statements: []influxql.Statement{
&influxql.CreateContinuousQueryStatement{
Name: "myquery",
Database: "foo",
Source: &influxql.SelectStatement{
Fields: []*influxql.Field{{Expr: &influxql.Call{Name: "count"}}},
Target: &influxql.Target{Measurement: "measure1", Database: "bar"},
Source: &influxql.Measurement{Name: "myseries"},
},
},
},
}
// admin user should be authorized to execute any query.
if err := s.Authorize(admin, adminOnlyQuery, ""); err != nil {
t.Fatal(err)
}
if err := s.Authorize(admin, readWriteQuery, "foo"); err != nil {
t.Fatal(err)
}
// Normal user should not be authorized to execute admin only query.
if err := s.Authorize(user, adminOnlyQuery, ""); err == nil {
t.Fatalf("normal user should not be authorized to execute cluster admin level queries")
}
// Normal user should not be authorized to execute query that selects into another
// database which (s)he doesn't have privileges on.
if err := s.Authorize(user, readWriteQuery, ""); err == nil {
t.Fatalf("normal user should not be authorized to write to database bar")
}
// Grant normal user write privileges on database "bar".
user.Privileges["bar"] = influxql.WritePrivilege
//Authorization on the previous query should now succeed.
if err := s.Authorize(user, readWriteQuery, ""); err != nil {
t.Fatal(err)
}
}
// Test multiple statement query authorization.
func TestServer_MultiStatementQueryAuthorization(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
// Create cluster admin.
s.CreateUser("admin", "admin", true)
admin := s.User("admin")
// Create normal database user.
s.CreateUser("user", "user", false)
user := s.User("user")
user.Privileges["foo"] = influxql.ReadPrivilege
s.Restart()
// Create a query that requires read for one statement and write for the second.
readWriteQuery := &influxql.Query{
Statements: []influxql.Statement{
// Statement that requires read.
&influxql.SelectStatement{
Fields: []*influxql.Field{{Expr: &influxql.Call{Name: "count"}}},
Source: &influxql.Measurement{Name: "cpu"},
},
// Statement that requires write.
&influxql.SelectStatement{
Fields: []*influxql.Field{{Expr: &influxql.Call{Name: "count"}}},
Source: &influxql.Measurement{Name: "cpu"},
Target: &influxql.Target{Measurement: "tmp"},
},
},
}
// Admin should be authorized to execute both statements in the query.
if err := s.Authorize(admin, readWriteQuery, "foo"); err != nil {
t.Fatal(err)
}
// Normal user with only read privileges should not be authorized to execute both statements.
if err := s.Authorize(user, readWriteQuery, "foo"); err == nil {
t.Fatalf("user should not be authorized to execute both statements")
}
}
// Ensure the server can create a database.
func TestServer_CreateDatabase(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
// Create the "foo" database.
if err := s.CreateDatabase("foo"); err != nil {
t.Fatal(err)
}
s.Restart()
// Verify that the database exists.
if !s.DatabaseExists("foo") {
t.Fatalf("database not found")
}
}
// Ensure the server returns an error when creating a duplicate database.
func TestServer_CreateDatabase_ErrDatabaseExists(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
// Create the "foo" database twice.
if err := s.CreateDatabase("foo"); err != nil {
t.Fatal(err)
}
if err := s.CreateDatabase("foo"); err != influxdb.ErrDatabaseExists {
t.Fatal(err)
}
}
// Ensure the server can drop a database.
func TestServer_DropDatabase(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
// Create the "foo" database and verify it exists.
if err := s.CreateDatabase("foo"); err != nil {
t.Fatal(err)
} else if !s.DatabaseExists("foo") {
t.Fatalf("database not actually created")
}
s.Restart()
// Drop the "foo" database and verify that it's gone.
if err := s.DropDatabase("foo"); err != nil {
t.Fatal(err)
} else if s.DatabaseExists("foo") {
t.Fatalf("database not actually dropped")
}
}
// Ensure the server returns an error when dropping a database that doesn't exist.
func TestServer_DropDatabase_ErrDatabaseNotFound(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
// Drop a database that doesn't exist.
if err := s.DropDatabase("no_such_db"); err != influxdb.ErrDatabaseNotFound {
t.Fatal(err)
}
}
// Ensure the server can return a list of all databases.
func TestServer_Databases(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
// Create some databases.
s.CreateDatabase("foo")
s.CreateDatabase("bar")
s.Restart()
// Return the databases.
if a := s.Databases(); len(a) != 2 {
t.Fatalf("unexpected db count: %d", len(a))
} else if a[0] != "bar" {
t.Fatalf("unexpected db(0): %s", a[0])
} else if a[1] != "foo" {
t.Fatalf("unexpected db(1): %s", a[1])
}
}
// Ensure the server can create a new user.
func TestServer_CreateUser(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
// Create a user.
if err := s.CreateUser("susy", "pass", true); err != nil {
t.Fatal(err)
}
s.Restart()
// Verify that the user exists.
if u := s.User("susy"); u == nil {
t.Fatalf("user not found")
} else if u.Name != "susy" {
t.Fatalf("username mismatch: %v", u.Name)
} else if !u.Admin {
t.Fatalf("admin mismatch: %v", u.Admin)
} else if bcrypt.CompareHashAndPassword([]byte(u.Hash), []byte("pass")) != nil {
t.Fatal("invalid password")
}
// Verify that the authenticated user exists.
u, err := s.Authenticate("susy", "pass")
if err != nil {
t.Fatalf("error fetching authenticated user")
} else if u.Name != "susy" {
t.Fatalf("username mismatch: %v", u.Name)
} else if !u.Admin {
t.Fatalf("admin mismatch: %v", u.Admin)
} else if bcrypt.CompareHashAndPassword([]byte(u.Hash), []byte("pass")) != nil {
t.Fatal("invalid password")
}
}
// Ensure the server correctly detects when there is an admin user.
func TestServer_AdminUserExists(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
// A server should start up without any admin user.
if s.AdminUserExists() {
t.Fatalf("admin user unexpectedly exists at start-up")
}
// Create a non-admin user and verify Server agrees there is no admin user.
if err := s.CreateUser("bert", "pass", false); err != nil {
t.Fatal(err)
}
s.Restart()
if s.AdminUserExists() {
t.Fatalf("admin user unexpectedly exists")
}
// Next, create an admin user, and ensure the Server agrees there is an admin user.
if err := s.CreateUser("ernie", "pass", true); err != nil {
t.Fatal(err)
}
s.Restart()
if !s.AdminUserExists() {
t.Fatalf("admin user does not exist")
}
}
// Ensure the server returns an error when creating an user without a name.
func TestServer_CreateUser_ErrUsernameRequired(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
if err := s.CreateUser("", "pass", false); err != influxdb.ErrUsernameRequired {
t.Fatal(err)
}
}
// Ensure the server returns an error when creating a duplicate user.
func TestServer_CreateUser_ErrUserExists(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
if err := s.CreateUser("susy", "pass", false); err != nil {
t.Fatal(err)
}
if err := s.CreateUser("susy", "pass", false); err != influxdb.ErrUserExists {
t.Fatal(err)
}
}
// Ensure the server can delete an existing user.
func TestServer_DeleteUser(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
// Create a user.
if err := s.CreateUser("susy", "pass", false); err != nil {
t.Fatal(err)
} else if s.User("susy") == nil {
t.Fatalf("user not created")
}
// Delete the user.
if err := s.DeleteUser("susy"); err != nil {
t.Fatal(err)
} else if s.User("susy") != nil {
t.Fatalf("user not actually deleted")
}
s.Restart()
if s.User("susy") != nil {
t.Fatalf("user not actually deleted after restart")
}
}
// Ensure the server can return a list of all users.
func TestServer_Users(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
// Create some users.
s.CreateUser("susy", "pass", false)
s.CreateUser("john", "pass", false)
s.Restart()
// Return the users.
if a := s.Users(); len(a) != 2 {
t.Fatalf("unexpected user count: %d", len(a))
} else if a[0].Name != "john" {
t.Fatalf("unexpected user(0): %s", a[0].Name)
} else if a[1].Name != "susy" {
t.Fatalf("unexpected user(1): %s", a[1].Name)
}
}
// Ensure the server does not return non-existent users
func TestServer_NonExistingUsers(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
// Create some users.
s.CreateUser("susy", "pass", false)
s.CreateUser("john", "pass2", false)
s.Restart()
// Ask for users that should not be returned.
u := s.User("bob")
if u != nil {
t.Fatalf("unexpected user found")
}
u, err := s.Authenticate("susy", "wrong_password")
if err == nil {
t.Fatalf("unexpected authenticated user found")
}
}
// Ensure the database can create a new retention policy.
func TestServer_CreateRetentionPolicy(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
// Create a database.
if err := s.CreateDatabase("foo"); err != nil {
t.Fatal(err)
}
// Create a retention policy on the database.
rp := &influxdb.RetentionPolicy{
Name: "bar",
Duration: time.Hour,
ReplicaN: 2,
}
if err := s.CreateRetentionPolicy("foo", rp); err != nil {
t.Fatal(err)
}
s.Restart()
// Verify that the policy exists.
if o, err := s.RetentionPolicy("foo", "bar"); err != nil {
t.Fatalf("unexpected error: %s", err)
} else if o == nil {
t.Fatalf("retention policy not found")
} else if !reflect.DeepEqual(rp, o) {
t.Fatalf("retention policy mismatch: %#v", o)
}
}
// Ensure the server returns an error when creating a retention policy with an invalid db.
func TestServer_CreateRetentionPolicy_ErrDatabaseNotFound(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
if err := s.CreateRetentionPolicy("foo", &influxdb.RetentionPolicy{Name: "bar"}); err != influxdb.ErrDatabaseNotFound {
t.Fatal(err)
}
}
// Ensure the server returns an error when creating a retention policy without a name.
func TestServer_CreateRetentionPolicy_ErrRetentionPolicyNameRequired(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
s.CreateDatabase("foo")
if err := s.CreateRetentionPolicy("foo", &influxdb.RetentionPolicy{Name: ""}); err != influxdb.ErrRetentionPolicyNameRequired {
t.Fatal(err)
}
}
// Ensure the server returns an error when creating a duplicate retention policy.
func TestServer_CreateRetentionPolicy_ErrRetentionPolicyExists(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
s.CreateDatabase("foo")
s.CreateRetentionPolicy("foo", &influxdb.RetentionPolicy{Name: "bar"})
if err := s.CreateRetentionPolicy("foo", &influxdb.RetentionPolicy{Name: "bar"}); err != influxdb.ErrRetentionPolicyExists {
t.Fatal(err)
}
}
// Ensure the database can alter an existing retention policy.
func TestServer_AlterRetentionPolicy(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
// Create a database.
if err := s.CreateDatabase("foo"); err != nil {
t.Fatal(err)
}
// Create a retention policy on the database.
rp := &influxdb.RetentionPolicy{
Name: "bar",
Duration: time.Hour,
ReplicaN: 2,
}
if err := s.CreateRetentionPolicy("foo", rp); err != nil {
t.Fatal(err)
}
// Alter the retention policy.
duration := time.Minute
replicaN := uint32(3)
rp2 := &influxdb.RetentionPolicyUpdate{
Duration: &duration,
ReplicaN: &replicaN,
}
if err := s.UpdateRetentionPolicy("foo", "bar", rp2); err != nil {
t.Fatal(err)
}
// Restart the server to make sure the changes persist afterwards.
s.Restart()
// Verify that the policy exists.
if o, err := s.RetentionPolicy("foo", "bar"); err != nil {
t.Fatalf("unexpected error: %s", err)
} else if o == nil {
t.Fatalf("retention policy not found")
} else if o.Duration != *rp2.Duration {
t.Fatalf("retention policy mismatch:\n\texp Duration = %s\n\tgot Duration = %s\n", rp2.Duration, o.Duration)
} else if o.ReplicaN != *rp2.ReplicaN {
t.Fatalf("retention policy mismatch:\n\texp ReplicaN = %d\n\tgot ReplicaN = %d\n", rp2.ReplicaN, o.ReplicaN)
}
// Test update duration only.
duration = time.Hour
results := s.ExecuteQuery(MustParseQuery(`ALTER RETENTION POLICY bar ON foo DURATION 1h`), "foo", nil)
if results.Error() != nil {
t.Fatalf("unexpected error: %s", results.Error())
}
// Verify results
if o, err := s.RetentionPolicy("foo", "bar"); err != nil {
t.Fatalf("unexpected error: %s", err)
} else if o == nil {
t.Fatalf("retention policy not found")
} else if o.Duration != duration {
t.Fatalf("retention policy mismatch:\n\texp Duration = %s\n\tgot Duration = %s\n", duration, o.Duration)
} else if o.ReplicaN != *rp2.ReplicaN {
t.Fatalf("retention policy mismatch:\n\texp ReplicaN = %d\n\tgot ReplicaN = %d\n", rp2.ReplicaN, o.ReplicaN)
}
}
// Ensure the server can delete an existing retention policy.
func TestServer_DeleteRetentionPolicy(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
// Create a database and retention policy.
s.CreateDatabase("foo")
if err := s.CreateRetentionPolicy("foo", &influxdb.RetentionPolicy{Name: "bar"}); err != nil {
t.Fatal(err)
} else if rp, _ := s.RetentionPolicy("foo", "bar"); rp == nil {
t.Fatal("retention policy not created")
}
// Remove retention policy from database.
if err := s.DeleteRetentionPolicy("foo", "bar"); err != nil {
t.Fatal(err)
} else if rp, _ := s.RetentionPolicy("foo", "bar"); rp != nil {
t.Fatal("retention policy not deleted")
}
s.Restart()
if rp, _ := s.RetentionPolicy("foo", "bar"); rp != nil {
t.Fatal("retention policy not deleted after restart")
}
}
// Ensure the server returns an error when deleting a retention policy on invalid db.
func TestServer_DeleteRetentionPolicy_ErrDatabaseNotFound(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
if err := s.DeleteRetentionPolicy("foo", "bar"); err != influxdb.ErrDatabaseNotFound {
t.Fatal(err)
}
}
// Ensure the server returns an error when deleting a retention policy without a name.
func TestServer_DeleteRetentionPolicy_ErrRetentionPolicyNameRequired(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
s.CreateDatabase("foo")
if err := s.DeleteRetentionPolicy("foo", ""); err != influxdb.ErrRetentionPolicyNameRequired {
t.Fatal(err)
}
}
// Ensure the server returns an error when deleting a non-existent retention policy.
func TestServer_DeleteRetentionPolicy_ErrRetentionPolicyNotFound(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
s.CreateDatabase("foo")
if err := s.DeleteRetentionPolicy("foo", "no_such_policy"); err != influxdb.ErrRetentionPolicyNotFound {
t.Fatal(err)
}
}
// Ensure the server can set the default retention policy
func TestServer_SetDefaultRetentionPolicy(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
s.CreateDatabase("foo")
rp := &influxdb.RetentionPolicy{Name: "bar"}
if err := s.CreateRetentionPolicy("foo", rp); err != nil {
t.Fatal(err)
} else if rp, _ := s.RetentionPolicy("foo", "bar"); rp == nil {
t.Fatal("retention policy not created")
}
// Set bar as default
if err := s.SetDefaultRetentionPolicy("foo", "bar"); err != nil {
t.Fatal(err)
}
if o, _ := s.DefaultRetentionPolicy("foo"); o == nil {
t.Fatal("default policy not set")
} else if !reflect.DeepEqual(rp, o) {
t.Fatalf("retention policy mismatch: %#v", o)
}
s.Restart()
if o, _ := s.DefaultRetentionPolicy("foo"); o == nil {
t.Fatal("default policy not kept after restart")
} else if !reflect.DeepEqual(rp, o) {
t.Fatalf("retention policy mismatch after restart: %#v", o)
}
}
// Ensure the server returns an error when setting the default retention policy to a non-existant one.
func TestServer_SetDefaultRetentionPolicy_ErrRetentionPolicyNotFound(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
s.CreateDatabase("foo")
if err := s.SetDefaultRetentionPolicy("foo", "no_such_policy"); err != influxdb.ErrRetentionPolicyNotFound {
t.Fatal(err)
}
}
// Ensure the server prohibits a zero check interval for retention policy enforcement.
func TestServer_StartRetentionPolicyEnforcement_ErrZeroInterval(t *testing.T) {
s := OpenServer(NewMessagingClient())
defer s.Close()
if err := s.StartRetentionPolicyEnforcement(time.Duration(0)); err == nil {
t.Fatal("failed to prohibit retention policies zero check interval")
}
}
func TestServer_EnforceRetentionPolices(t *testing.T) {
c := NewMessagingClient()
s := OpenServer(c)
defer s.Close()
s.CreateDatabase("foo")
s.CreateRetentionPolicy("foo", &influxdb.RetentionPolicy{Name: "mypolicy", Duration: 30 * time.Minute})
// Create two shard groups for the the new retention policy -- 1 which will age out immediately
// the other in more than an hour.
s.CreateShardGroupIfNotExists("foo", "mypolicy", time.Now().Add(-1*time.Hour))
s.CreateShardGroupIfNotExists("foo", "mypolicy", time.Now().Add(time.Hour))
// Check the two shard groups exist.
var g []*influxdb.ShardGroup
g, err := s.ShardGroups("foo")
if err != nil {
t.Fatal(err)
} else if len(g) != 2 {
t.Fatalf("expected 2 shard group but found %d", len(g))
}
// Run retention enforcement.
s.EnforceRetentionPolicies()
// Ensure enforcement is in effect across restarts.
s.Restart()
// First shard group should have been removed.
g, err = s.ShardGroups("foo")
if err != nil {
t.Fatal(err)
} else if len(g) != 1 {
t.Fatalf("expected 1 shard group but found %d", len(g))
}
}
// Ensure the database can write data to the database.
func TestServer_WriteSeries(t *testing.T) {
c := NewMessagingClient()
s := OpenServer(c)
defer s.Close()
s.CreateDatabase("foo")
s.CreateRetentionPolicy("foo", &influxdb.RetentionPolicy{Name: "mypolicy", Duration: 1 * time.Hour})
s.CreateUser("susy", "pass", false)
// Check if a topic is being subscribed to.
var subscribed bool
c.SubscribeFunc = func(replicaID, topicID uint64) error {
subscribed = true
return nil
}
// Write series with one point to the database.
tags := map[string]string{"host": "servera.influx.com", "region": "uswest"}
index, err := s.WriteSeries("foo", "mypolicy", []influxdb.Point{{Name: "cpu_load", Tags: tags, Timestamp: mustParseTime("2000-01-01T00:00:00Z"), Fields: map[string]interface{}{"value": float64(23.2)}}})
if err != nil {
t.Fatal(err)
} else if err = s.Sync(index); err != nil {
t.Fatalf("sync error: %s", err)
}
// Write another point 10 seconds later so it goes through "raw series".
index, err = s.WriteSeries("foo", "mypolicy", []influxdb.Point{{Name: "cpu_load", Tags: tags, Timestamp: mustParseTime("2000-01-01T00:00:10Z"), Fields: map[string]interface{}{"value": float64(100)}}})
if err != nil {
t.Fatal(err)
} else if err = s.Sync(index); err != nil {
t.Fatalf("sync error: %s", err)
}
// Verify a subscription was made.
if !subscribed {
t.Fatal("expected subscription")
}
// Retrieve first series data point.
if v, err := s.ReadSeries("foo", "mypolicy", "cpu_load", tags, mustParseTime("2000-01-01T00:00:00Z")); err != nil {
t.Fatal(err)
} else if !reflect.DeepEqual(v, map[string]interface{}{"value": float64(23.2)}) {
t.Fatalf("values mismatch: %#v", v)
}
// Retrieve second series data point.
if v, err := s.ReadSeries("foo", "mypolicy", "cpu_load", tags, mustParseTime("2000-01-01T00:00:10Z")); err != nil {
t.Fatal(err)
} else if mustMarshalJSON(v) != mustMarshalJSON(map[string]interface{}{"value": float64(100)}) {
t.Fatalf("values mismatch: %#v", v)
}
// Retrieve non-existent series data point.
if v, err := s.ReadSeries("foo", "mypolicy", "cpu_load", tags, mustParseTime("2000-01-01T00:01:00Z")); err != nil {
t.Fatal(err)
} else if v != nil {
t.Fatalf("expected nil values: %#v", v)
}
}
// Ensure the server can drop a measurement.
func TestServer_DropMeasurement(t *testing.T) {
c := NewMessagingClient()
s := OpenServer(c)
defer s.Close()
s.CreateDatabase("foo")
s.CreateRetentionPolicy("foo", &influxdb.RetentionPolicy{Name: "raw", Duration: 1 * time.Hour})
s.SetDefaultRetentionPolicy("foo", "raw")
s.CreateUser("susy", "pass", false)
// Write series with one point to the database.
tags := map[string]string{"host": "serverA", "region": "uswest"}
index, err := s.WriteSeries("foo", "raw", []influxdb.Point{{Name: "cpu", Tags: tags, Timestamp: mustParseTime("2000-01-01T00:00:00Z"), Fields: map[string]interface{}{"value": float64(23.2)}}})
if err != nil {
t.Fatal(err)
} else if err = s.Sync(index); err != nil {
t.Fatalf("sync error: %s", err)
}
// Ensure measurement exists
results := s.ExecuteQuery(MustParseQuery(`SHOW MEASUREMENTS`), "foo", nil)
if res := results.Results[0]; res.Err != nil {
t.Fatalf("unexpected error: %s", res.Err)
} else if len(res.Series) != 1 {
t.Fatalf("unexpected row count: %d", len(res.Series))
} else if s := mustMarshalJSON(res); s != `{"series":[{"name":"measurements","columns":["name"],"values":[["cpu"]]}]}` {
t.Fatalf("unexpected row(0): %s", s)
}
// Ensure series exists
results = s.ExecuteQuery(MustParseQuery(`SHOW SERIES`), "foo", nil)
if res := results.Results[0]; res.Err != nil {
t.Fatalf("unexpected error: %s", res.Err)
} else if len(res.Series) != 1 {
t.Fatalf("unexpected row count: %d", len(res.Series))
} else if s := mustMarshalJSON(res); s != `{"series":[{"name":"cpu","columns":["id","host","region"],"values":[[1,"serverA","uswest"]]}]}` {
t.Fatalf("unexpected row(0): %s", s)
}
// Drop measurement
results = s.ExecuteQuery(MustParseQuery(`DROP MEASUREMENT cpu`), "foo", nil)
if results.Error() != nil {
t.Fatalf("unexpected error: %s", results.Error())
}
results = s.ExecuteQuery(MustParseQuery(`SHOW MEASUREMENTS`), "foo", nil)
if res := results.Results[0]; res.Err != nil {
t.Fatalf("unexpected error: %s", res.Err)
} else if len(res.Series) != 0 {
t.Fatalf("unexpected row count: %d", len(res.Series))
} else if s := mustMarshalJSON(res); s != `{}` {
t.Fatalf("unexpected row(0): %s", s)
}
results = s.ExecuteQuery(MustParseQuery(`SHOW SERIES`), "foo", nil)
if res := results.Results[0]; res.Err != nil {
t.Fatalf("unexpected error: %s", res.Err)
} else if len(res.Series) != 0 {
t.Fatalf("unexpected row count: %d", len(res.Series))
} else if s := mustMarshalJSON(res); s != `{}` {
t.Fatalf("unexpected row(0): %s", s)
}
}
// Ensure the server can handles drop measurement if none exists.
func TestServer_DropMeasurementNoneExists(t *testing.T) {
c := NewMessagingClient()
s := OpenServer(c)
defer s.Close()
s.CreateDatabase("foo")
s.CreateRetentionPolicy("foo", &influxdb.RetentionPolicy{Name: "raw", Duration: 1 * time.Hour})
s.SetDefaultRetentionPolicy("foo", "raw")
s.CreateUser("susy", "pass", false)
// Drop measurement
results := s.ExecuteQuery(MustParseQuery(`DROP MEASUREMENT bar`), "foo", nil)
if results.Error().Error() != `measurement not found` {
t.Fatalf("unexpected error: %s", results.Error())
}
// Write series with one point to the database.
tags := map[string]string{"host": "serverA", "region": "uswest"}
index, err := s.WriteSeries("foo", "raw", []influxdb.Point{{Name: "cpu", Tags: tags, Timestamp: mustParseTime("2000-01-01T00:00:00Z"), Fields: map[string]interface{}{"value": float64(23.2)}}})
if err != nil {
t.Fatal(err)
} else if err = s.Sync(index); err != nil {
t.Fatalf("sync error: %s", err)
}
// Drop measurement after writing data to ensure we still get the same error
results = s.ExecuteQuery(MustParseQuery(`DROP MEASUREMENT bar`), "foo", nil)
if results.Error().Error() != `measurement not found` {
t.Fatalf("unexpected error: %s", results.Error())
}
}
// Ensure Drop measurement can:
// write to measurement cpu with tags region=uswest host=serverA
// write to measurement memory with tags region=uswest host=serverB
// drop one of those measurements
// ensure that the dropped measurement is gone
// ensure that we can still query: show measurements
// ensure that we can still make various queries:
// select * from memory where region=uswest and host=serverb
// select * from memory where host=serverb
// select * from memory where region=uswest
func TestServer_DropMeasurementSeriesTagsPreserved(t *testing.T) {
c := NewMessagingClient()
s := OpenServer(c)
defer s.Close()
s.CreateDatabase("foo")
s.CreateRetentionPolicy("foo", &influxdb.RetentionPolicy{Name: "raw", Duration: 1 * time.Hour})
s.SetDefaultRetentionPolicy("foo", "raw")
s.CreateUser("susy", "pass", false)
// Write series with one point to the database.
tags := map[string]string{"host": "serverA", "region": "uswest"}
index, err := s.WriteSeries("foo", "raw", []influxdb.Point{{Name: "cpu", Tags: tags, Timestamp: mustParseTime("2000-01-01T00:00:00Z"), Fields: map[string]interface{}{"value": float64(23.2)}}})
if err != nil {
t.Fatal(err)
} else if err = s.Sync(index); err != nil {
t.Fatalf("sync error: %s", err)
}
tags = map[string]string{"host": "serverB", "region": "uswest"}
index, err = s.WriteSeries("foo", "raw", []influxdb.Point{{Name: "memory", Tags: tags, Timestamp: mustParseTime("2000-01-01T00:00:01Z"), Fields: map[string]interface{}{"value": float64(33.2)}}})
if err != nil {
t.Fatal(err)
} else if err = s.Sync(index); err != nil {
t.Fatalf("sync error: %s", err)
}
// Ensure measurement exists
results := s.ExecuteQuery(MustParseQuery(`SHOW MEASUREMENTS`), "foo", nil)
if res := results.Results[0]; res.Err != nil {
t.Fatalf("unexpected error: %s", res.Err)
} else if len(res.Series) != 1 {
t.Fatalf("unexpected row count: %d", len(res.Series))
} else if s := mustMarshalJSON(res); s != `{"series":[{"name":"measurements","columns":["name"],"values":[["cpu"],["memory"]]}]}` {
t.Fatalf("unexpected row(0): %s", s)
}
results = s.ExecuteQuery(MustParseQuery(`SHOW SERIES`), "foo", nil)
if res := results.Results[0]; res.Err != nil {
t.Fatalf("unexpected error: %s", res.Err)
} else if len(res.Series) != 2 {
t.Fatalf("unexpected row count: %d", len(res.Series))
} else if s := mustMarshalJSON(res); s != `{"series":[{"name":"cpu","columns":["id","host","region"],"values":[[1,"serverA","uswest"]]},{"name":"memory","columns":["id","host","region"],"values":[[2,"serverB","uswest"]]}]}` {
t.Fatalf("unexpected row(0): %s", s)
}