-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis.xml
executable file
·1055 lines (1025 loc) · 29.8 KB
/
redis.xml
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
<?xml version="1.0" encoding="UTF-8"?>
<Export generator="Cache" version="25" zv="Cache for Windows (x86-64) 2013.1 (Build 446U)" ts="2013-08-07 10:36:17">
<Routine name="redis" type="INC" timestamp="63040,75190.786812"><![CDATA[
#define DebugBuild
#define HOME $namespace
#define log ^redis.log
#define loglit "^["""_^||redis.conf("dir")_"""]redis.log"
#define conf ^redis.conf
#define pconf ^redis.conf
#define clients ^redis.clients
#define control ^redis.server
#define nsPrefix "redis"
#define dbPrefix "redis"
#define defaultRedisDB "DB 0"
#define defaultNS $$$nsPrefix_"0"
#define CRLF $get($$$conf("crlf"),$C(13)_$C(10))
#define VERSION "0.1"
#define LOGDEBUG 1000
#define LOGVERBOSE 100
#define LOGNOTICE 10
#define LOGWARNING 0
#define LOGALWAYS "LOG"
#define LogFileLevel(%l) $s(%l=$$$LOGDEBUG:"%",%l=$$$LOGVERBOSE:"$",%l=$$$LOGNOTICE:"#",1:"*")
#define LogLevel ##expression($g($$$conf("loglevel-i"),0))
#define LoggerResource "RedisLogger"
#define fs ##expression(""""_$s($$$isWINDOWS:"\",$$$isUNIX:"/",$$$isVMS:"")_"""")
#ifdef DebugBuild
#define debug(%msg) do logdebug^redis(%msg)
#define CompileStamp ##expression(" /* Compiled on "_$ZDT($ZTS)_" by "_$username_" DEBUG BUILD */")
#else
#define debug(%msg) // no debug
#define CompileStamp ##expression(" /* Compiled on "_$ZDT($ZTS)_" by "_$username_" RELEASE BUILD*/")
#endif
#define keys ^[$$$clients(client,"db")]keys
#define sets ^[$$$clients(client,"db")]sets
#define lists ^[$$$clients(client,"db")]lists
#define hashes ^[$$$clients(client,"db")]hashes
]]></Routine>
<Routine name="redis" type="MAC" languagemode="0" timestamp="63041,37952.690112"><![CDATA[
#Include %occInclude
#Include redis
$$$CompileStamp
/*
* Various logging and system utilities
*
* NOTE: To track log file use
* server>tail -F redis.log
* the "F" rather than "f" will track by filename not inode
*/
dump() public {
w "redis datastore dump: ",$ZDT($ZTS),!
write "DB: ",$namespace,!
zw ^keys
zw ^lists
zw ^sets
zw ^hashes
set ns=$order($$$control("db",""))
while ( ns'="" ) {
write !,"DB: ",ns,!
zw ^[ns]keys
zw ^[ns]lists
zw ^[ns]sets
zw ^[ns]hashes
set ns=$order($$$control("db",ns))
}
}
logo
;; _._
;; _.-``__ ''-._
;; _.-`` `. `_. ''-._ Redis 2.6.14 (00000000/0) 64 bit
;; .-`` .-```. ```\/ _.,_ ''-._
;; ( ' , .-` | `, ) Running in stand alone mode
;; |`-._`-...-` __...-.``-._|'` _.-'| Port: XXPORTXX
;; | `-._ `._ / _.-' | PID: XXpidXX
;; `-._ `-._ `-./ _.-' _.-'
;; |`-._`-._ `-.__.-' _.-'_.-'|
;; | `-._`-._ _.-'_.-' | http://redis.io
;; `-._ `-._`-.__.-'_.-' _.-' http://intersystems.com
;; |`-._`-._ `-.__.-' _.-'_.-'|
;; | `-._`-._ _.-'_.-' |
;; `-._ `-._`-.__.-'_.-' _.-'
;; `-._ `-.__.-' _.-'
;; `-._ _.-'
;; `-.__.-'
return
showLogo() public {
for i=1:1:17 {
set line=$extract($text(logo+i),5,*)
if ( i=6 ) { // port
set line=$replace(line,"XXPORTXX",$$$conf("port"))
}
if ( i=7 ) { // pid
set line=$replace(line,"XXpidXX",$job)
}
do forceLog($$$LOGALWAYS,line)
}
}
initLogger() public {
//return:$isobject($g(%rLogger))
set target=$g($$$conf("logfile"),"stdout")
//break
if ( target'="stdout" ) {
set %rLogger=##class(%Stream.FileCharacter).%New()
set %rLogger.Filename=target
} else {
set %rLogger=##class(%Stream.GlobalCharacter).%New()
}
write "Logging to:",target,!
}
loggerJob() public { // kick off a job
// which sits and spins on the ^||redis.log global
// writing records to the log target (file or stdout)
do initLogger()
set watchLog=1,writeCount=0
while ( watchLog ) {
set ret=$system.Event.WaitMsg($$$LoggerResource,5)
set msg=$list(ret,2)
if ( msg = "EXIT" ) {
set watchLog=0
do %rLogger.%Save()
continue
}
if ( $piece(msg,"~",1)="LOG" ) {
set logi=$piece(msg,"~",2)
set lmsg=$get( ^redis.log(logi), "???" )
do rLoggerWrite(lmsg)
set wc=$increment(writeCount)
}
do:(wc#100)=0 %rLogger.%Save() // write out logfile every 100 entries
}
}
log(level,msg) public {
//write "level=",level," LogLevel=",$$$LogLevel,!
if ( level > $$$LogLevel ) { return }
do forceLog(level,msg)
}
forceLog(level,msg) public {
set msg="["_$job_"] "_$zdt($zts)_" "_$$$LogFileLevel(level)_" "_msg
//do rLoggerWrite(msg)
set i=$increment(^redis.log)
set ^redis.log(i)=msg
do $system.Event.Signal($$$LoggerResource,"LOG"_"~"_i)
}
rLoggerWrite(msg) public {
//do %rLogger.MoveToEnd()
do %rLogger.WriteLine(msg)
//do %rLogger.%Save()
if ( $get($$$conf("logfile"),"stdout") = "stdout" ) {
do %rLogger.OutputToDeviceAt(%rLogger.Size-$length(msg)-1,$length(msg))
write !
}
}
testLog() public {
set $$$conf("dir")=$namespace
set $$$conf("loglevel")="debug"
set $$$conf("loglevel-i")=1000
set $$$conf("logfile")="stdout"
do log^redis($$$LOGWARNING,"redis-cache start")
do showLogo^redis
for i=1:1:50 {
do log^redis($$$LOGVERBOSE,i_": This is a verbose message")
do log^redis($$$LOGWARNING,i_": Danger Will Robinson!")
do log^redis($$$LOGNOTICE,i_":I am serving you notice")
do logdebug^redis(i_": Find that bug, bugger!")
hang 5
}
}
loglist(level,list) public {
do log(level,$listtostring(list))
}
logerror(level,error) public {
do log(level,$system.Status.GetErrorText(error))
}
logdebug(msg) public {
do log($$$LOGDEBUG,msg)
}
createDb(dbname) public {
set sc=$$$OK
new $namespace
set $namespace="%SYS"
$$$debug("createDb dbname="_dbname)
set dbNameU=$zconvert(dbname,"U")
if ( ##class(Config.Databases).Exists(dbNameU,.db) ) {
$$$debug("DB exists")
return $$$OK
}
set dir=$system.Util.ManagerDirectory()_dbname
set dirExists=##class(%File).Exists(dir)
$$$debug("dirExists="_dirExists)
if ( 'dirExists ) {
set created=##class(%File).CreateDirectory(dir)
$$$debug("created dir = "_created)
if ( 'created ) {
return $$$ERROR("Could not create directory '"_dir_"'")
}
}
set p("Directory")=dir
set p("Name")=dbname
set sc=##class(Config.Databases).Create(dbname,.p)
set dbo=##class(Config.Databases).Open(dbname)
set sc=dbo.%Save()
return:$$$ISERR(sc) sc
set db=##class(SYS.Database).%New()
set db.Directory=dir
set sc=db.%Save()
return sc
}
deleteDb(dbname) public {
new $namespace
set $namespace="%SYS"
$$$debug("deleteDb dbname="_dbname)
set result=##class(Config.Databases).Delete(dbname)
$$$debug("deletDb result="_result)
return result
}
ensureNS(ns=$$$defaultNS) [ client ] public {
$$$debug("ensureSN ns="_ns)
return:##class(%SYS.Namespace).Exists(ns) $$$OK
// On SELECT commands, ensure the requested namespace is available
if ( ns?.N ) {
set ns=$$$nsPrefix_ns // support redis "0","1" dbs
}
$$$debug("ensureNS ns="_ns_" did not exist!")
set dbname=ns
new $namespace
set $namespace="%SYS"
set dbo=##class(Config.Databases).%OpenId(dbname)
if ( '$isobject(dbo) ) {
$$$debug("dbo not an object, need to create db")
set sc=$$createDb(dbname)
$$$debug(sc)
if ($$$ISERR(sc) ) {
zn currNS
throw $$error(sc)
}
}
// db exist's, now create ns
set p("Globals")=dbname
set sc=##class(Config.Namespaces).Create(ns,.p)
// create mappings for control structures
$$$debug(sc)
return sc
}
loadConf(conf="redis.conf") public {
try {
if ( '##class(%File).Exists(conf) ) {
write "Warning: no configuration file detected - using default configuration",!
write "Call server^redis(path_to_conf_file) to suppy configuration",!
write "TODO--- Implement all defaults for conf",!
throw "FOO"
}
kill $$$conf
//break
do forceLog($$$LOGALWAYS,"Loading conf from '"_conf_"'")
set fc=##class(%Stream.FileCharacter).%New()
set fc.Filename=conf
do fc.Rewind()
while ( 'fc.AtEnd ) {
set line=fc.ReadLine()
continue:$e(line,1)="#"
continue:line=""
set key=$p(line," ")
set value=$p(line," ",2,$l(line," "))
$$$debug("setconf key="_key_" value="_value)
set $$$conf(key)=value
}
//break
set ll=$$$conf("loglevel")
set $$$conf("loglevel-i")=$select(ll="debug":$$$LOGDEBUG,ll="verbose":$$$LOGVERBOSE,ll="notice":$$$LOGNOTICE,1:$$$LOGWARNING)
do log($$$LOGNOTICE,"Conf loaded")
do initLogger^redis // in case we need a different logger
return $$$OK
} catch (exception) {
do exception.OutputToDevice()
return 0
}
}
testLoadConf(conf="redis.conf") public {
write "testLoadConf",!
set sc=$$loadConf(conf)
zw $$$conf
return
}
sping() public {
set sc=$system.Event.Create("sping")
set sc=$system.Event.Clear("sping")
set r=$system.Event.WaitMsg("sping")
zw r
}
pingpong() public {
try {
set port=6379,$HALT="pphalt"
set sock=##class(%IO.ServerSocket).%New()
set sock.LineTerminator=$$$CRLF
set sock.ConnectionQueueSize=10000
set sock.Port=port
set sock.InputBufferSize=626368,sock.OutputBufferSize=626368
set sock.TCPSendBuffer=626368,sock.TCPReceiveBuffer=626368
set opened=sock.Open()
write "opened=",opened,!
set maxJobs=5
zw sock
Do $ZU(68,57,1) ; turn on PSW2NOTHROTTLE bit to bypass throttle
write "pingpong server listening on port=",port,!
set gotConnection=sock.ListenJob(,"redis.PingServer",,maxJobs,,.sc)
/*
listen
set gotConnection=sock.Listen(,.sc)
write "gotConnection=",gotConnection," sc=",sc,!
if ($$$ISERR(sc)) {
write "Listen Error--- "
do $system.OBJ.DisplayError(sc)
throw ##class(%Exception.StatusException).CreateFromStatus(sc)
}
//do ##class(redis.PingServer).OnConnected(sock,"")
while ( 'sock.AtEnd ) {
set data=sock.ReadLine(,.sc)
write "data=",data," sc=",sc,!
write "codes=",$system.Status.GetErrorCodes(sc),!
//break
if ( +$system.Status.GetErrorCodes(sc)'=6219 ) {
write "ReadLine error---",$ZE,!
do $system.OBJ.DisplayError(sc)
do sock.Disconnect()
goto listen
}
if ( data = "PING" ) {
do sock.Write("+PONG"_$C(13,10),1,.sc)
write "sock.Write sc=",sc,!
}
}
goto listen
*/
} catch (error) {
do error.OutputToDevice()
}
pphalt
write "Got HALT $ZE=",$ZE,!
return
}
lc() public {
do $system.OBJ.Load("/home/jmimick/redis-cache/redis.xml")
}
server(conf="redis.conf") public {
kill $$$log
kill $$$clients
kill $$$conf
set ret=$system.Event.Create($$$LoggerResource)
set ret=$system.Event.Clear($$$LoggerResource)
do initLogger^redis
quit:'$$loadConf(conf)
job:$$$conf("logfile")'="stdout" loggerJob^redis
set $$$conf("dir")=$namespace
/*
if ( $namespace '= $$$defaultNS ) {
throw:$$$ISERR( $$ensureNS() )
//zn $$$defaultNS
}
*/
do showLogo^redis
set sock=##class(%IO.ServerSocket).%New()
set sock.LineTerminator=$$$CRLF
//break
set sock.ConnectionQueueSize = $$$conf("maxclients")+1
set sock.KeepAliveInterval = $$$conf("tcp-keepalive")
set sock.Port=$$$conf("port")
set $HALT="finally"
set res=sock.Open()
do log($$$LOGWARNING,"Server ready to accept connections on port "_$$$conf("port"))
listen
try {
set maxJobs=5
zw sock
set ret=sock.ListenJob(,"redis.Server",$J_"~Parent",,maxJobs,1,.ok)
write "ret=",ret,!
//set ret=sock.Listen(,.ok)
//set sc=##class(redis.Server).OnConnected(sock,$J_"~Parent")
goto:ok=1 listen // keep listening
} catch (exception) {
do log($$$LOGVERBOSE,exception.DisplayString())
if ( exception.Data["<READ>" ) {
goto listen
}
}
finally
//break
write "finally...",!
do log($$$LOGVERBOSE,"s^redis ret="_ret_" ok="_ok)
do log($$$LOGWARNING,"Server Shutting down...")
set ret=$system.Event.Signal($$$LoggerResource,"EXIT")
return
}
/*
* Redis Protocol Command Implementations
*
* All commands expect the following variables
* to be publically accessable - the routines
* are invoked by indirection
*
* args $list() of arguments to command
* result string with 'redisized' result, e.g. "+OK\r\n"
* client ip_addr:port of current connection (optional)
*
* In some cases, commands delegate to other routines.
* For example, "CLIENT LIST" would invoke:
* cCLIENT -> cCLIENTcLIST
*
* Each redis command XYZ maps to "cXYZ"
*/
cPING() [ args, result, client ] public {
kill result
$$$debug("PING client="_client)
set result="+PONG"_$$$CRLF
return
}
cCLIENT() [ args, result, client ] public { // deal with CLIENT commands
set command = $zconvert($list(args,1),"U")
$$$debug("CLIENT command="_command)
if ( "KILL,LIST,SETNAME,GETNAME"'[command ) {
set result = $$error("UNKNOWN CLIENT COMMAND '"_command_"'")
return
}
set tag="cCLIENTc"_command
do @tag
return
}
cCLIENTcLIST() [ args, result, client ] public {
set fields=$lb("addr","age","name","db")
set c=$order($$$clients("")),tr="",cc=0
while ( c'="" ) {
set l=""
for i=1:1:$ll(fields) {
set f = $list(fields,i)
set l = l_f_":"_$get($$$clients(c,f),"???")
set:i<$ll(fields) l=l_" "
}
//set tr=tr_"$"_$length(l)_$$$CRLF
//set tr=tr_l_$$$CRLF,cc=cc+1
set tr=tr_l_$C(10),cc=cc+1
set c=$order($$$clients(c))
//set:(c'="") tr=tr_$C(10)
}
set result="*1"_$$$CRLF_"$"_$l(tr)_$$$CRLF_tr_$$$CRLF
return
}
cCLIENTcKILL() [ args, result, client ] public {
set target=$list(args,2)
if ( '$data($$$clients(target) ) ) {
set result=$$error("CLIENT NOT FOUND")
return
}
if ( $data($$$clients(target,"busy"))) {
set result=$$error("CLIENT BUSY")
return
}
// TODO - use LOCKs on ^redis.clients here
do log^redis($$$LOGWARNING,"CLIENT KILL *** Locks not implemented ***")
kill $$$clients(target)
set result = "+OK"_$$$CRLF
return
}
cCLIENTcSETNAME() [ args, result, client ] public {
set $$$clients(client,"name")=$list(args,2)
set result = "+OK"_$$$CRLF
}
cCLIENTcGETNAME() [ args, result, client ] public {
$$$debug("cCLIENTcGETNAME client="_client)
if ( '$data($$$clients(client,"name")) ) {
set result = "$-1"_$$$CRLF
return
}
set n = $$$clients(client,"name")
set result = "*1"_$$$CRLF_"$"_$l(n)_$$$CRLF_n_$$$CRLF
return
}
cSELECT() [ args, result, client ] public { // select a namespace
set ns=$list(args,1)
if ( '##class(%SYS.Namespace).Exists(ns) ) {
set result = $$error("Namespace does not exist")_$$$CRLF
return
}
set $$$clients(client,"db")=ns
set $$$control("db",ns)="" // mark this namespace a being used
$$$debug("SELECT client="_client_" ns="_ns)
set result = "+OK"_$$$CRLF
return
}
cSET() [ args,result, client ] public {
kill result
if ( $listlength(args)'=2 ) {
throw $$error("SET invalid args")
}
set key=$list(args,1),value=$list(args,2)
set $$$keys(key)=value
$$$debug("SET key="_key_" value="_value)
set result="+OK"_$$$CRLF
return
}
cMSET() [ args, result, client ] public {
if ( ($listlength(args)#2)'=0 ) {
set result=$$error("SET invalid args")
return
}
for i=1:2:$listlength(args) {
set key=$list(args,i)
set value=$list(args,i+1)
set $$$keys(key)=value
}
set result="+OK"_$$$CRLF
return
}
cHSET() [ args,result, client ] public {
kill result
if ( $listlength(args)'=3 ) {
throw $$error("SET invliad args")
}
$$$debug("HSET")
do loglist^redis($$$LOGDEBUG,args)
set hash=$listget(args,1)
set key=$listget(args,2)
set value=$listget(args,3)
$$$debug("HSET hash="_hash_" key="_key_" value="_value)
set $$$hashes(hash,key)=value
set result="+OK"_$$$CRLF
return
}
cAPPEND() [ args, result,client ] public {
kill result
set key=$list(args,1)
set val=$list(args,2)
$$$debug("APPEND key="_key_" val="_val_" old="_$get($$$keys(key)))
set $$$keys(key)=$get($$$keys(key))_val
set result="+OK"_$$$CRLF
return
}
cGET() [ args,result,client ] public {
kill result
set key=$list(args,1)
$$$debug("GET key="_key)
if ( '$data($$$keys(key)) ) {
$$$debug("GET key does not exist")
set result="$-1"_$$$CRLF
return
}
set value=$$$keys(key)
$$$debug("GET key="_key_" value="_value)
if ( value?.N ) {
set result = ":"_value_$$$CRLF // integer
} else {
set result="$"_$length(value)_$$$CRLF_value_$$$CRLF
}
return
}
cGETRANGE() [ args,result, client ] public {
kill result
set key=$list(args,1)
if ( '$data($$$keys(key)) ) {
$$$debug("GETRANGE key does not exist")
set result="$-1"_$$$CRLF
return
}
set value=$$$keys(key)
$$$debug("GETRANGE key="_key_" value="_value)
set start=$list(args,2),end=$list(args,3)
set value=$extract(value,start,end)
$$$debug("GETRANGE start="_start_" end="_end_" value="_value)
if ( value?.N ) {
set result = ":"_value_$$$CRLF // integer
} else {
set result="$"_$length(value)_$$$CRLF_value_$$$CRLF
}
return
}
cHGET() [ args,result,client ] public {
set hash=$list(args,1),field=$list(args,2)
if ( '$data($$$hashes(hash,field)) ) {
$$$debug("HGET hash="_hash_" field="_field_" does not exist")
set result="$-1"_$$$CRLF
return
}
set value=$$$hashes(hash,field)
$$$debug("HGET hash="_hash_" field="_field_" value="_value)
if ( value?.N ) {
set result = ":"_value_$$$CRLF // integer
} else {
set result="$"_$length(value)_$$$CRLF_value_$$$CRLF
}
return
}
cHGETALL() [ args, result,client ] public {
kill counter,result
set hash=$list(args,1)
$$$debug("HGETALL hash="_hash)
set field=$order($$$hashes(hash,""))
set counter=0,result=""
while ( field'="" ) {
// key
set result = result_"$"_$length(field)_$$$CRLF
set result = result_field_$$$CRLF
// value
set value = $$$hashes(hash,field)
set result = result_"$"_$l(value)_$$$CRLF
set result = result_value_$$$CRLF
set field=$order($$$hashes(hash,field))
set counter=counter+1
}
set result = "*"_(2*counter)_$$$CRLF_result
$$$debug("HGETALL result="_result)
return
}
cGETSET() [ args,result,client ] public {
do cGET
set tresult=result
do cSET
set result=tresult
}
cINCR() [ args, result,client ] public {
set key=$list(args,1)
set i=$i($$$keys(key))
$$$debug("INCR key="_key_" value="_i)
set result=":"_i_$$$CRLF
return
}
cINCRBY() [ args, result,client ] public {
set key=$list(args,1)
set by=$list(args,2)
set i=$i($$$keys(key),by)
$$$debug("INCRBY key="_key_" value="_i)
set result=":"_i_$$$CRLF
return
}
cLLEN() [ args, result, client ] public {
set key=$list(args,1)
if ( '$listdata($$$lists(key)) ) {
//nil
set result="$-1"_$$$CRLF
}
set i=$listlength($$$lists(key))
set result=":"_i_$$$CRLF
}
cLPUSH() [ args, result, client ] public {
set key=$list(args,1)
set value=$list(args,2)
$$$debug("LPUSH key="_key_" value="_value)
set $$$lists(key)=$lb(value)_$get($$$lists(key))
set result=":"_$listlength($$$lists(key))_$$$CRLF
return
}
cLPOP() [ args, result, client ] public {
set key=$list(args,1)
if ( '$listdata($$$lists(key) ) ) {
//nill
set result="$-1"_$$$CRLF
return
}
set value=$list($$$lists(key),1)
set $list($$$lists(key),1,1)="" // remove first element
set result="$"_$length(value)_$$$CRLF_value_$$$CRLF
}
cLRANGE() [ args, result, client ] public {
set key=$list(args,1)
if ( '$data($$$lists(key) ) ) {
set result = "$-1"_$$$CRLF
return
}
$$$debug("LRANGE key="_key_" $ll(args)="_$ll(args)_" args="_$listtostring(args))
if ( $listlength(args) '= 3 ) {
set result=$$error("LRANGE needs start,stop parameters")
return
}
set start=+$list(args,2),stop=+$list(args,3)
$$$debug("LRANGE start="_start_" stop="_stop)
set emptyListResult="*0"_$$$CRLF
if ( start > $listlength($$$lists(key)) ) {
set result=emptyListResult
return
}
if ( stop > $listlength( $$$lists(key) ) ) {
set stop=$listlength( $$$lists(key) )
}
set range=$list($$$lists(key),start,stop),result=""
$$$debug("LRANGE range="_$listtostring(range))
for i=1:1:$listlength(range) {
set value=$list(range,i)
set result = result_"$"_$l(value)_$$$CRLF
set result = result_value_$$$CRLF
}
set result = "*"_$listlength(range)_$$$CRLF_result
}
cRPUSH() [ args, result, client ] public {
set key=$list(args,1)
set value=$list(args,2)
$$$debug("RPUSH key="_key_" value="_value)
#if $ZV["2013.2"
set $list($$$lists(key),*+1)=value
#else
set $$$lists(key)=$$$lists(key)_$lb(value)
#endif
set result=":"_$listlength($$$lists(key))_$$$CRLF
}
cRPOP() [ args, result, client ] public {
set key=$list(args,1)
if ( '$listdata($$$lists(key) ) ) {
//nill
set result="$-1"_$$$CRLF
}
#if $ZV["2013.2"
set value=$list($$$lists(key),*)
#else
set value=$list($$$lists(key),$listlength($$$lists(key)))
#endif
set length=$listlength($$$lists(key))
set $list($$$lists(key),length,length)="" // remove last element
set result="$"_$length(value)_$$$CRLF_value_$$$CRLF
}
cSADD() [ args, result, client ] public {
set key=$list(args,1)
set numToAdd=$listlength(args)-1
$$$debug("SADD key="_key_" numToAdd="_numToAdd_" args="_$listtostring($list(args,2,$ll(args))))
for i=1:1:numToAdd {
set e=$list(args,i+1)
if ('$data($$$sets(key,e))) {
set x=$i($$$sets(key))
set $$$sets(key,e)=""
}
}
set result=":"_$$$sets(key)_$$$CRLF
}
cSPOP() [ args, result, client ] public {
// remove and return a random element from a set
set key=$list(args,1)
if ( '$data($$$sets(key) ) ) {
//nill
set result="$-1"_$$$CRLF
return
}
set r=$random($$$sets(key))+1,value=$order($$$sets(key,""))
for i=1:1:(r-1) set value=$order($$$sets(key,value))
$$$debug("r="_r_" value="_value)
set x=$increment($$$sets(key),-1)
if ( x=0 ) {
kill $$$sets(key)
} else {
kill $$$sets(key,value)
}
set result="$"_$length(value)_$$$CRLF_value_$$$CRLF
}
cSMEMBERS() [ args, result, client ] public {
set key=$list(args,1)
if ( '$data($$$sets(key) ) ) {
//nill
set result="$-1"_$$$CRLF
return
}
set value=$order($$$sets(key,"")),result=""
while ( value'="" ) {
set result = result_"$"_$l(value)_$$$CRLF
set result = result_value_$$$CRLF
set value=$order($$$sets(key,value))
}
set result = "*"_$$$sets(key)_$$$CRLF_result
}
cINFO() [ args, result, client ] public {
set xr=$lb("# Server")
set xr=xr_$lb("cache_redis_server_version:"_$$$VERSION)
set xr=xr_$lb("os:"_$ZV)
set xr=xr_$lb("timestamp:"_$system.SYS.TimeStamp())
set xr=xr_$lb("process_id:"_$system.SYS.ProcessID())
set xr=xr_$lb("user_memory_human:"_$piece($view(-1,$job),"^",17))
set xr=xr_$lb(" ")
set xr=xr_$lb("# redis.conf")
set key=$order($$$conf(""))
while ( key'="" ) {
set xr=xr_$lb(key_":"_$$$conf(key))
set key=$order($$$conf(key))
}
set result="*"_$listlength(xr)_$$$CRLF
do loglist^redis($$$LOGDEBUG,xr)
for i=1:1:$ll(xr) {
set li=$listget(xr,i)
set result=result_"$"_$length(li)_$$$CRLF_li_$$$CRLF
}
$$$debug("INFO result="_result)
return
}
cKEYS() [ args, result, client ] public {
do log^redis($$$LOGWARNING,"KEYS command - wildcard, pattern matching not implemented")
set (oq,q)=$listget(args,1,"*"),mode=1
$$$debug("KEYS q="_q_" mode="_mode)
if ( q["?" ) {
set q=$tr(q,"?","*"),mode=2
}
if ( q["[" ) {
set q=$p(q,"[",1)_"*"_$p(q,"]",2),mode=3
}
kill r
set key=$order($$$keys(""))
while ( key'="" ) {
set r($i(r))=key
$$$debug("r("_r_")="_r(r))
set key=$order($$$keys(key))
}
merge s=r
$$$debug("s="_s)
if ( mode = 2 ) {
for i=1:1:r {
if ( $l(r(i))'=$l(oq) ) {
set s=s-1
kill s(i)
}
}
}
if ( mode = 3 ) { // to-do
set result = $$error("Not implemented")
}
set result="*"_s_$$$CRLF
$$$debug(result)
set i=$order(s(""))
while ( i'="" ) {
set v=s(i)
set result = result_"$"_$l(v)_$$$CRLF
set result = result_v_$$$CRLF
set i=$order(s(i))
}
$$$debug(result)
return
}
test1() public {
set crlf=$$$CRLF
set longString=""
for i=1:1:10 { set longString=longString_$r(1000) }
set data(1)=$lb("*3","$3","SET","$5","mykey","$7","myvalue","*2","$3","GET","$5","mykey")
set data(2)=$lb("*3","$3","SET","$10","some.global","$100",longString)
set data(3)=$lb("*2","$3","GET","$10","some.global")
for i=1:1:3 {
set d=data(i)
set wireData = $listtostring(d,crlf)_crlf
write "testing:" zw wireData
//do parse(wireData,.parsed)
//zw parsed
//do process(.parsed,.result)
//zw result
}
return
}
error(message) {
return "-ERR "_message
}
benchmark(options) public {
}
]]></Routine>
<Project name="redis" LastModified="2013-08-07 09:16:18.224976">
<Items>
<ProjectItem name="redis.INC" type="MAC"></ProjectItem>
<ProjectItem name="redis.MAC" type="MAC"></ProjectItem>
<ProjectItem name="redis.Server" type="CLS"></ProjectItem>
<ProjectItem name="redis.PingServer" type="CLS"></ProjectItem>
</Items>
</Project>
<Class name="redis.Server">
<IncludeCode>redis</IncludeCode>
<Super>%RegisteredObject</Super>
<TimeChanged>63041,37620.137727</TimeChanged>
<TimeCreated>63040,68424.573963</TimeCreated>
<Property name="client">
<Description>
Store the client addr</Description>
<Type>%String</Type>
<Final>1</Final>
</Property>
<Method name="%OnNew">
<FormalSpec>initvalue:%String</FormalSpec>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
set ..client = initvalue
return $$$OK
]]></Implementation>
</Method>
<Method name="OnDisconnect">
<FormalSpec>serverSocket:%IO.ServerSocket,pIntentional,pSCReason</FormalSpec>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
//$$$debug("Disconnect client="_..client_" pIntentional="_pIntentional_" pSCReason="_pSCReason)
$$$debug("Client closed connection client="_..client_" serverSocket.Remote="_serverSocket.Remote)
//kill $$$clients(..client)
return $$$OK
]]></Implementation>
</Method>
<Method name="OnConnected">
<Description>
We can do this loop/parsing much easier now.
just read $$$CRLF lines
*n = number of args $CRLF
$n = number of byte in next arg $CRLF
arg_data $CRLF</Description>
<ClassMethod>1</ClassMethod>
<FormalSpec>serverSocket:%IO.ServerSocket,jobArg:%String</FormalSpec>
<PublicList>args,result,client,%rLogger</PublicList>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
set $ZT="errorTrap"
$$$debug("Accepted "_serverSocket.Remote)
// could get Cntr^C here, and no remote endpoint
//return:$g(serverSocket.Remote)="" $$$OK
set serverSocket.LineTerminator=$$$CRLF
set client = $piece(serverSocket.Remote,"|",2)
set disconHandler = ##class(redis.Server).%New(client)
//$$$debug("disconHandler.client="_disconHandler.client)
set serverSocket.DisconnectHandler=disconHandler
set $$$clients(client,"addr")=client
if ( $data( $$$clients("db") ) ) {
set sc=$$ensureNS^redis( $$$clients("db") )
throw:$$$ISERR(sc) sc
} else {
set $$$clients(client,"db")=$namespace
}
readLoop
$$$debug("readLoop")
set data=serverSocket.ReadLine(,,.sc)
$$$debug("data="_data_" sc="_sc)
if ( $$$ISERR(sc) ) {
set exp=##class(%Exception.StatusException).CreateFromStatus(sc)
throw exp
}
if ( 'serverSocket.IsOpen ) {
$$$debug("serverSocket.IsOpen=0 client="_client)
return $$$OK
}
if ( data="" ) { goto readLoop }
if ( data="PING" ) {
// redis-benchmark sends raw "PING"
// which does not follow wire protocol
$$$debug("inline PING detected")
set cmd="c"_data,args=""
goto executeCmd
}
if ( $e(data,1) = "*" ) { // new batch
//set batch=""
set batchSize=$e(data,2,*)
set args="",cmd=""
$$$debug("batchSize="_batchSize)
for i=1:1:2*batchSize {
$$$debug("about to read i="_i)
set dummy=serverSocket.ReadLine(,,.sc) //????
do:$$$ISERR(sc) logerror^redis(sc)
set data=serverSocket.ReadLine(,,.sc)
do:$$$ISERR(sc) logerror^redis(sc)
$$$debug("data="_data)
continue:(i#2=1) // odd read are arg lengths we don't really care about
if ( i=2 ) {
set cmd="c"_$zconvert(data,"U")
} else {
set args=args_$lb(data)
}
}
}
executeCmd
set cmd=cmd_"^redis"
$$$debug(cmd)
do loglist^redis($$$LOGDEBUG,args)
do @cmd
$$$debug(result)
do serverSocket.Write(result,1,.sc)
do:$$$ISERR(sc) logerror^redis(sc)
$$$debug("serverSocket.AtEnd="_serverSocket.AtEnd)
if ( 'serverSocket.AtEnd ) {
goto readLoop
}
return $$$OK
errorTrap
set $ZT="",sendToClient=0
/// if we land here and 'exp' is set, then