• Stars
    star
    118
  • Rank 299,923 (Top 6 %)
  • Language
    C
  • License
    BSD 2-Clause "Sim...
  • Created over 10 years ago
  • Updated over 9 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

krmt: Kit of Redis Module Tools

krmt: Kit of Redis Module Tools

About

Welcome to a kit of tools you can easily add to Redis.

This repository gives you multiple ready-to-use Redis Add-on Modules.

You can also use the modules here for examples and templates to create your own your own loadable Redis modules.

Note: You must use a Dynamic Redis server if you want to use modules. Regular Redis doesn't know about modules.

@skidder maintains a deployable dockerfile based on the current development branch of dynamic-redis-unstable.

Disclaimers:

  • Redis is single threaded for all command processing.
  • While Redis is inside your command function, nothing else runs.
  • Your command should operate and return as quickly as possible. See existing Redis commands in the main redisCommandTable[] at the top of redis.c for examples of how to write different Redis commands.
  • Make sure to release objects and free memory you allocate. You will introduce memory leaks if you forget to free things.
  • You don't have to write in C. You can use C, C++, Go (?), Guile, Chicken, or anything else generating a shared library with C symbols for your operating system. You can even link additional libraries (want numerical routines? embedded sqlite3? embedded snappy/zippy?)

Writing Your Module

To write your module: start out with the simple module provided in this repository and modify commands, functions, fields, and structs as needed.

You will need to study the existing Redis source to learn how existing Redis commands work.

Also see the notes at Dynamic Redis: Use Command Modules.

Bundled Commands

Included in krmt:

  • json.so - an experiment in storing JSON documents in Redis
  • geo.so - provides efficient geographic coordinate range searches
  • hmsetif.so - provides HMSETIF (renamed from HMSETCK)
  • hmsetnx.so - provides HMSETNX (from a pull request and updated to integrate into more recent Redis versions).
  • bitallpos.so - provides BITALLPOS command returning the positions of all set bits in a string (from a pull request).
  • scriptname.so - provides SCRIPTNAME and EVALNAME commands allowing you to bind user friendly names to loaded script SHA hashes, then you can call scripts by name (using EVALNAME) instead of by a 40 character long hash reference.
    • Right now, this module has the best comment structure and best design patterns for creating your own modules.
    • Use the dynamic-redis-unstable branch to build scriptname.c since scriptname.c depends on a header not exported on released versions yet.
  • poong.so - minimal module showing how the basic Dynamic Redis interface API works.

Building

For building, you need a copy of the Dynamic Redis source tree.

If you want to build against the most recent 2.8 commits, use:

mkdir -p ~/repos
cd ~/repos
# We need YAJL for JSON commands and the Makefile refuses to run without it.
git clone https://github.com/lloyd/yajl
cd yajl
./configure; make
cd ..
git clone https://github.com/mattsta/redis
cd redis
git checkout dynamic-redis-2.8
make
cd ..
git clone https://github.com/mattsta/krmt
cd krmt
make clean; make -j

If you want to build against the current development branch, just change dynamic-redis-2.8 to dynamic-redis-unstable.

Usage

After building your module, you can load it into Dynamic Redis.

Compatability

As Redis adds or removes features, sometimes modules may need to be updated to take into account different functions or interfaces available to them.

Stable releases of Dynamic Redis (as of 0.5.2) define a few DYN_FEATURE_[feature] constants you can use for preprocessor selective including or excluding of code.

The currently defined features are negative features allowing the absense of them to mean "use behavior from unstable branch."

You can check all the current feature defines in version.h of your Dynamic Redis checkout.

For the unstable branch, no features are defined.

Automatic Module Reloading

During development, you can automatically reload your modules using some simple loops. Just run these from the directory where you compile your modules and everything should work.

Linux:

while inotifywait -e modify module.so; do
    redis-cli config set module-add `pwd`/module.so
done

OS X:

brew install kqwait
while kqwait module.so; do
    redis-cli config set module-add `pwd`/module.so
done

Tips

If you are on OS X, you should monitor your redis-server for new memory leaks by running leaks in a persistent terminal window:

watch "leaks redis-server"

Think of leaks as valgrind, except it can monitor leaks in any live process. We run leaks in a watch loop to refresh the check fairly often.

Under some use cases, leaks can cause an infinite loop in OS X's malloc routine. If that happens, rest assured it's a problem with leaks and not your code. You can also try running under jemalloc on OS X (not the default) to clear up any strange OS X malloc issues.

If you are on Linux, you should run your module tests under valgrind after a good day of development. Any changes should also be re-evaluated for memory leaks and invalid memory access.

Perfecting a Redis command takes time and understanding. Using memory allocation debuggers will help you eventually internalize the complexities of how and when Redis uses reference counted objects and malloc'd strings for certain operations.

Sample Output

Sample output on startup on OS X (Linux will complain if you give it a module name without a path):

matt@ununoctium:~/repos/redis/src% ./redis-server --module-strict no --module-add ping.so
[81021] 28 Mar 14:43:14.500 * Module [<builtin>] loaded 145 commands.
[81021] 28 Mar 14:43:14.501 * Loading new [ping.so] module.
[81021] 28 Mar 14:43:14.501 # [ping.so] version mismatch. Module was compiled against 2.9.11, but we are 2.8.8-dynamic-0.5. 
[81021] 28 Mar 14:43:14.501 # Strict version enforcement is disabled. Loading [ping.so] but undefined behavior may occur.
[81021] 28 Mar 14:43:14.501 * Added command poong [ping.so]
[81021] 28 Mar 14:43:14.501 * Added command pooooong [ping.so]
[81021] 28 Mar 14:43:14.501 * Added command pooong [ping.so]
[81021] 28 Mar 14:43:14.501 * Added command pinger [ping.so]
[81021] 28 Mar 14:43:14.501 * Module [ping.so] loaded 4 commands.
[81021] 28 Mar 14:43:14.501 * Running load function of module [ping.so].

Module reloaded with: CONFIG SET module-add /Users/matt/repos/krmt/poong.so

Sample output on reloading a module (using a different filename, but the same module name):

[81021] 28 Mar 14:43:29.796 * Running cleanup function for [ping.so] module.
[81021] 28 Mar 14:43:29.796 * Closed previous [ping.so] module.
[81021] 28 Mar 14:43:29.796 * Loading new [/Users/matt/repos/krmt/poong.so] module.
[81021] 28 Mar 14:43:29.796 * Replaced existing command poong [/Users/matt/repos/krmt/poong.so]
[81021] 28 Mar 14:43:29.796 * Replaced existing command pooooong [/Users/matt/repos/krmt/poong.so]
[81021] 28 Mar 14:43:29.796 * Replaced existing command pooong [/Users/matt/repos/krmt/poong.so]
[81021] 28 Mar 14:43:29.796 * Replaced existing command pinger [/Users/matt/repos/krmt/poong.so]
[81021] 28 Mar 14:43:29.796 * Module [/Users/matt/repos/krmt/poong.so] loaded 4 commands.
[81021] 28 Mar 14:43:29.796 * Running load function of module [/Users/matt/repos/krmt/poong.so].

Sample INFO modules output:

module_<builtin>:filename=<builtin>,compiled_against=2.8.8-dynamic-0.5,
module_version=2.8.8-dynamic-0.5,first_loaded=0,last_loaded=0,commands=get,set,
setnx,setex,psetex,append,strlen,del,exists,setbit,getbit,setrange,getrange,
substr,incr,decr,mget,rpush,lpush,rpushx,lpushx,linsert,rpop,lpop,brpop,
brpoplpush,blpop,llen,lindex,lset,lrange,ltrim,lrem,rpoplpush,sadd,srem,smove,
sismember,scard,spop,srandmember,sinter,sinterstore,sunion,sunionstore,sdiff,
sdiffstore,smembers,sscan,zadd,zincrby,zrem,zremrangebyscore,zremrangebyrank,
zunionstore,zinterstore,zrange,zrangebyscore,zrevrangebyscore,zcount,zrevrange,
zcard,zscore,zrank,zrevrank,zscan,hset,hsetnx,hget,hmset,hmget,hincrby,
hincrbyfloat,hdel,hlen,hkeys,hvals,hgetall,hexists,hscan,incrby,decrby,
incrbyfloat,getset,mset,msetnx,randomkey,select,move,rename,renamenx,expire,
expireat,pexpire,pexpireat,keys,scan,dbsize,auth,ping,echo,save,bgsave,
bgrewriteaof,shutdown,lastsave,type,multi,exec,discard,sync,psync,replconf,
flushdb,flushall,sort,info,monitor,ttl,pttl,persist,slaveof,debug,config,
subscribe,unsubscribe,psubscribe,punsubscribe,publish,pubsub,watch,unwatch,
restore,migrate,dump,object,client,eval,evalsha,slowlog,script,time,bitop,
bitcount,bitpos
module_sh.matt.test.pong:filename=/Users/matt/repos/krmt/poong.so,
compiled_against=2.8.8-dynamic-0.5,module_version=0.0001,
first_loaded=0,last_loaded=1396032209,commands=poong,pooooong,pooong,pinger

Contributions

Did you make a nice Redis Add-On Module? Does it have a beginning, a middle, and an end? Got a protagonist with some obstacles to overcome?

Just open a pull request against this repository if you want to share your modules and get them added to krmt.

Modules are more likely to be accepted if they have meaningful comments, don't leak memory, don't crash Redis, and show us something new and delightful while solving problems we've had forever (or solving problems we didn't even know we had).

More Repositories

1

crcspeed

This make CRC be fast. Included implementations: CRC-64-Jones and CRC-16-CCITT
C
133
star
2

icli

interactive brokers ibkr api command line interface cli giving you the fastest way to lose all your money
Python
112
star
3

ib_insync

Live upstream is now at https://github.com/ib-api-reloaded/ib_async; sadly, the orignial creator Ewald has died and now we must continue without his years of experience creating and growing this project. See the 'Discussions' tab for organization planning. Python sync/async framework for Interactive Brokers API
Python
80
star
4

signal-backup

Archive your Signal conversations to immutable storage (project abandoned, but feel free to use as reference if it helps)
HTML
71
star
5

redis-cluster-playground

The simplest way to get a multi-instance Redis Cluster running for experimentation
Shell
57
star
6

ecache

ecache: Erlang ETS Based TTL Cache
Erlang
56
star
7

erlang-stdinout-pool

stdinout_pool: stuff goes in, stuff goes out. there's never any miscommunication.
Erlang
45
star
8

trade-balancer

low latency, high throughput load balancer for real time stock market trade feed (using polygon.io websocket API)
C
35
star
9

redisfuse

FUSE File System for Redis specializing in CRUDing strings and hashes (and R of everything else) (Note: this is obviously ancient and is only a historical artifact now; not really a good example of code usage or design)
Python
33
star
10

stripe-erlang

Erlang interface to the stripe.com API
Erlang
27
star
11

pcache

An Erlang cache where every stored item is its own process.
Erlang
27
star
12

cbuf

Erlang Circular Buffer/List/LIFO Queue using ETS
Erlang
18
star
13

tradeapis

stock market data helpers including api clients for polygon and tradier
Python
15
star
14

datakit

datakit is a collection of the most memory efficient data structures in the universe
C
15
star
15

netmatt

Python implementation of netstat features
Python
14
star
16

pygreeks

calculate exact black-scholes option value using pytorch autograd and also calculate greeks using either autograd or numerical approximation
Python
10
star
17

lematt

Matt's Let's Encrypt Automation
Python
10
star
18

mailweb

Matt's Ansible Roles Integrated For Server-Side Server Serving
Python
10
star
19

er

er: erlang client for redis with erlang-like return values (best erlang client for redis)
Erlang
9
star
20

crc64-compare

Compare a few different CRC-64 implementations
C
9
star
21

oneshot

oneshot: accept a TCP connection then hand it off to a function
Erlang
8
star
22

zog_web

zog_web is a web serving and domain/page routing platform for erlang applications.
Erlang
8
star
23

osxiso

Burn a bootable USB thinggy on OS X from an ISO
Shell
7
star
24

erlwg

erlang rate limiting web getter
Erlang
7
star
25

rat

Redis Analysis Tool
Python
7
star
26

mpreg

Matt’s Protocol for Results Everywhere Guaranteed
Python
7
star
27

restcp

REST TCP Proxy/Router Thing
Erlang
6
star
28

liveconfig

Watch a directory and do something when files change or are added or removed.
Erlang
6
star
29

libgeoip-erlang

erlang bindings to maxmind geoip C API. Imported from bitbucket (very old).
C
5
star
30

car

content-addressed riak
Erlang
5
star
31

cudacam

experiments in cuda, opencv, and kinect under Linux
Python
4
star
32

varint

C functions for multi-paradigm encoding and decoding of variable byte length integers
C
4
star
33

zlang

if you have to ask, you don't want to know. See examples/
Erlang
4
star
34

riak_pool

the simplest erlang pooling riak client
Erlang
4
star
35

twitter-lister

automatically download tweets from your subscribed twitter lists into a full text search database
Python
4
star
36

rets

replicate a redis server's dataset into ets for lower latency access to distributed configurations
Erlang
4
star
37

egsf

erlang general serializing framework
Erlang
4
star
38

etherpad

This is my non-crapified etherpad fix-up. If you want a *base* etherpad, use this (not the ugly "foundation" stuff). Imported from bitbucket.
Java
4
star
39

beas

basic erlang account system
Erlang
3
star
40

balanced-erlang

balancedpayments erlang client
Erlang
3
star
41

redis-perf-compiler

A script to compile tagged versions of Redis many different ways then run benchmarks on each compiled version.
Shell
3
star
42

hnexport

Download all of HN using massively concurrent and pipelined download operations.
Python
3
star
43

chatty

riak and redis backed conversation storage and retrieval
Erlang
2
star
44

cg

config getter
Erlang
2
star
45

git-shrink

Scripts to drop commits from git history and replace history again.
2
star
46

ossmfa

Open Source Software Maintainer Funding Agreement
2
star
47

mutil

matt's python utilities (async/multiprocessing/dataflow)
Python
2
star
48

notifier

redis-backed hierarchical user alerting/notification system
Erlang
2
star
49

hnf

hacker news filter: remove marketing and drivel. Turns Hacker News into Hacked News. Also a testbed for zfeatures.
Erlang
2
star
50

ghost

generalized hierarchical object storage
Erlang
2
star
51

cmake-cpu-detect

Automatic CMake CPU Feature Flag Availability Detection
CMake
2
star
52

tt

tiny table (big table clone using tokyo tyrant proxies)
Erlang
2
star
53

fantasy_payroll

Calculate your potential take home pay taking into account taxes in most states
Erlang
2
star
54

pyjobby

pyjobby: a python+postgres persistent job queue
Python
2
star
55

zog_common

A place for common zcomponents
Erlang
2
star
56

getTV

getTV: an automated TV episode getter using public torrent APIs
Python
2
star
57

nvidia-smi-sender

push nvidia-smi GPU statistics (power, frequency, temperature) to a victoria metrics server at high frequency
Python
2
star
58

racl

redis-backed access control lists
Erlang
1
star
59

weighter

user karma/point/weight management
Erlang
1
star
60

oms-matt

My modifications to Process One's Flash Media Server
JavaScript
1
star
61

attsearch

Use ATT Internet Availability API From CLI
Python
1
star
62

aws-vpc-global-planner

Create multi-account globally unique non-overlapping VPC cidr/subnet configurations for all AZs in all AWS regions
Python
1
star
63

bess

basic erlang session system
Erlang
1
star
64

allegiance

group membership management
Erlang
1
star
65

kapi-python

Python API for managing your historical life timelines including education and location movements over time. Includes a simple CLI so you don't have to write any code to use the API.
Python
1
star
66

geneticfuckery

curious about storing your variables in a database instead of code? want to automatically optimize your variables without building offcial "machine learning" systems? you are welcome to FAFO.
Python
1
star
67

aws-asg-weight-builder

Automation to help you define a collection of allowable instance types to use for automatic scaling operations.
Python
1
star