├── .gcloudignore ├── deployment ├── overlays │ ├── dev │ │ ├── dev.env │ │ ├── service_nodeport.yaml │ │ └── kustomization.yaml │ └── stage │ │ ├── stage.env │ │ └── kustomization.yaml ├── base │ ├── default.env │ ├── namespace.yaml │ ├── kustomization.yaml │ ├── service.yaml │ ├── init_validation.yaml │ └── deployment.yaml └── postgres │ ├── postgres-service.yaml │ ├── pgdata-persistentvolumeclaim.yaml │ ├── postgres-deployment.yaml │ ├── flyway-job.yaml │ └── kustomization.yaml ├── .dockerignore ├── config ├── dev_vm.args ├── vm.args.src ├── dev_sys.config ├── sys.config.src └── test.config ├── apps ├── service_discovery_grpc │ ├── rebar.config │ ├── src │ │ ├── service_discovery_grpc.app.src │ │ ├── service_discovery_grpc_app.erl │ │ ├── service_discovery_grpc_sup.erl │ │ ├── sd_discovery_service_bhvr.erl │ │ ├── sdg_service.erl │ │ └── sd_discovery_service_client.erl │ └── proto │ │ └── discovery.proto ├── service_discovery_storage │ ├── .gitignore │ └── src │ │ ├── service_discovery_storage.app.src │ │ ├── service_discovery_storage.erl │ │ └── sds_storage.erl ├── service_discovery_postgres │ ├── priv │ │ ├── sql │ │ │ ├── zones.sql │ │ │ └── services.sql │ │ └── migrations │ │ │ ├── V2__Add_updated_at_trigger.sql │ │ │ └── V1__Create_services_endpoints_table.sql │ └── src │ │ ├── service_discovery_postgres_app.erl │ │ ├── service_discovery_postgres.app.src │ │ ├── sdp_query.erl │ │ ├── service_discovery_postgres_sup.erl │ │ ├── sdp_services_storage.erl │ │ └── sdp_erldns_storage.erl ├── service_discovery │ └── src │ │ ├── service_discovery.app.src │ │ ├── service_discovery_app.erl │ │ ├── service_discovery_sup.erl │ │ └── service_discovery.erl └── service_discovery_http │ └── src │ ├── service_discovery_http.app.src │ ├── service_discovery_http_app.erl │ ├── sdh_pool.erl │ ├── sdh_conn.erl │ ├── sdh_socket.erl │ ├── service_discovery_http_sup.erl │ └── sdh_handler.erl ├── .gitignore ├── Tiltfile ├── test ├── sd_test_utils.erl ├── service_discovery_http_SUITE.erl ├── service_discovery_grpc_SUITE.erl ├── service_discovery_SUITE_data │ └── docker-compose.yml └── service_discovery_SUITE.erl ├── ctlptl.yml ├── cloudbuild.yaml ├── .github └── workflows │ ├── junit.yml │ └── ci.yml ├── docker-compose.yml ├── ci ├── Dockerfile.cb ├── Dockerfile.test ├── build_images.sh └── old_build_images.sh ├── Dockerfile ├── rebar.config ├── README.md ├── rebar.lock └── LICENSE /.gcloudignore: -------------------------------------------------------------------------------- 1 | _build 2 | _checkouts -------------------------------------------------------------------------------- /deployment/overlays/dev/dev.env: -------------------------------------------------------------------------------- 1 | LOGGER_LEVEL=debug 2 | -------------------------------------------------------------------------------- /deployment/overlays/stage/stage.env: -------------------------------------------------------------------------------- 1 | LOGGER_LEVEL=notice 2 | -------------------------------------------------------------------------------- /deployment/base/default.env: -------------------------------------------------------------------------------- 1 | LOGGER_LEVEL=debug 2 | SCHEDULERS=1 3 | DB_HOST=127.0.0.1 4 | -------------------------------------------------------------------------------- /deployment/base/namespace.yaml: -------------------------------------------------------------------------------- 1 | kind: Namespace 2 | apiVersion: v1 3 | metadata: 4 | name: service-discovery 5 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | _build 2 | Dockerfile 3 | ci 4 | cloudbuild.yaml 5 | deployment 6 | LICENSE 7 | README 8 | Tiltfile 9 | tilt.profile 10 | test -------------------------------------------------------------------------------- /config/dev_vm.args: -------------------------------------------------------------------------------- 1 | -sname service_discovery@localhost 2 | 3 | -setcookie service_discovery_cookie 4 | 5 | +S 1 6 | 7 | +C multi_time_warp 8 | 9 | +sbwt none 10 | 11 | +A30 12 | -------------------------------------------------------------------------------- /config/vm.args.src: -------------------------------------------------------------------------------- 1 | -sname service_discovery@localhost 2 | 3 | -setcookie service_discovery_cookie 4 | 5 | +S ${SCHEDULERS} 6 | 7 | +C multi_time_warp 8 | 9 | +sbwt none 10 | 11 | +A30 12 | -------------------------------------------------------------------------------- /apps/service_discovery_grpc/rebar.config: -------------------------------------------------------------------------------- 1 | {grpc, [{protos, "proto"}, 2 | {gpb_opts, [{descriptor, true}, 3 | {module_name_prefix, "sdg_"}, 4 | {module_name_suffix, "_pb"}]}]}. 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | tilt.profile 2 | .rebar3 3 | _* 4 | .eunit 5 | *.o 6 | *.beam 7 | *.plt 8 | *.swp 9 | *.swo 10 | .erlang.cookie 11 | ebin 12 | log 13 | erl_crash.dump 14 | .rebar 15 | logs 16 | _build 17 | .idea 18 | *.iml 19 | rebar3.crashdump 20 | *~ 21 | -------------------------------------------------------------------------------- /Tiltfile: -------------------------------------------------------------------------------- 1 | allow_k8s_contexts("kind-adoptingerlang") 2 | default_registry('127.0.0.1:5002') 3 | 4 | docker_build('service_discovery', '.', target='runner') 5 | 6 | k8s_yaml(local('kustomize build deployment/overlays/dev')) 7 | 8 | watch_file('deployment/') 9 | -------------------------------------------------------------------------------- /apps/service_discovery_storage/.gitignore: -------------------------------------------------------------------------------- 1 | .rebar3 2 | _* 3 | .eunit 4 | *.o 5 | *.beam 6 | *.plt 7 | *.swp 8 | *.swo 9 | .erlang.cookie 10 | ebin 11 | log 12 | erl_crash.dump 13 | .rebar 14 | logs 15 | _build 16 | .idea 17 | *.iml 18 | rebar3.crashdump 19 | *~ 20 | -------------------------------------------------------------------------------- /deployment/postgres/postgres-service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | labels: 5 | service: postgres 6 | name: postgres 7 | spec: 8 | ports: 9 | - name: "5432" 10 | port: 5432 11 | targetPort: 5432 12 | selector: 13 | service: postgres 14 | -------------------------------------------------------------------------------- /deployment/postgres/pgdata-persistentvolumeclaim.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: PersistentVolumeClaim 3 | metadata: 4 | labels: 5 | service: pgdata 6 | name: pgdata 7 | spec: 8 | accessModes: 9 | - ReadWriteOnce 10 | resources: 11 | requests: 12 | storage: 100Mi 13 | -------------------------------------------------------------------------------- /apps/service_discovery_postgres/priv/sql/zones.sql: -------------------------------------------------------------------------------- 1 | -- :select_zones 2 | SELECT 3 | name, 4 | version, 5 | authority, 6 | records, 7 | keysets 8 | FROM zones 9 | WHERE name = $1 10 | 11 | -- :insert_zone 12 | INSERT INTO zones (name, version, authority, records, keysets) VALUES ($1, $2, $3, $4, $5) 13 | -------------------------------------------------------------------------------- /deployment/base/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | namespace: service-discovery 4 | resources: 5 | - namespace.yaml 6 | - deployment.yaml 7 | - service.yaml 8 | labels: 9 | - includeSelectors: true 10 | pairs: 11 | app: service-discovery 12 | patches: 13 | - path: init_validation.yaml 14 | -------------------------------------------------------------------------------- /test/sd_test_utils.erl: -------------------------------------------------------------------------------- 1 | -module(sd_test_utils). 2 | 3 | -export([random_service_name/0, 4 | random_name/1]). 5 | 6 | random_service_name() -> 7 | random_name(<<"service-">>). 8 | 9 | random_name(Prefix) -> 10 | Str = re:replace(base64:encode(crypto:strong_rand_bytes(8)), "\\W", "x",[global, {return,binary}]), 11 | <>. 12 | -------------------------------------------------------------------------------- /apps/service_discovery_storage/src/service_discovery_storage.app.src: -------------------------------------------------------------------------------- 1 | {application, service_discovery_storage, 2 | [{description, "Library for abstracting out the service discovery storage layer"}, 3 | {vsn, {git, short}}, 4 | {registered, []}, 5 | {applications, 6 | [kernel, 7 | stdlib 8 | ]}, 9 | {env,[]}, 10 | {modules, []}, 11 | 12 | {licenses, ["Apache 2.0"]}, 13 | {links, []} 14 | ]}. 15 | -------------------------------------------------------------------------------- /deployment/base/service.yaml: -------------------------------------------------------------------------------- 1 | kind: Service 2 | apiVersion: v1 3 | metadata: 4 | name: service-discovery 5 | spec: 6 | selector: 7 | app: service-discovery 8 | ports: 9 | - name: dns 10 | protocol: UDP 11 | port: 8053 12 | targetPort: dns 13 | - name: http 14 | protocol: TCP 15 | port: 3000 16 | targetPort: http 17 | - name: grpc 18 | protocol: TCP 19 | port: 8081 20 | targetPort: grpc 21 | -------------------------------------------------------------------------------- /apps/service_discovery/src/service_discovery.app.src: -------------------------------------------------------------------------------- 1 | {application, service_discovery, 2 | [{description, "Core functionality for service discovery service"}, 3 | {vsn, {git, short}}, 4 | {registered, []}, 5 | {mod, {service_discovery_app, []}}, 6 | {applications, 7 | [kernel, 8 | stdlib, 9 | erldns, 10 | service_discovery_storage 11 | ]}, 12 | {env,[]}, 13 | {modules, []}, 14 | 15 | {licenses, ["Apache 2.0"]}, 16 | {links, []} 17 | ]}. 18 | -------------------------------------------------------------------------------- /apps/service_discovery_grpc/src/service_discovery_grpc.app.src: -------------------------------------------------------------------------------- 1 | {application, service_discovery_grpc, 2 | [{description, "GRPC frontend for service discovery service"}, 3 | {vsn, {git, short}}, 4 | {registered, []}, 5 | {mod, {service_discovery_grpc_app, []}}, 6 | {applications, 7 | [kernel, 8 | stdlib, 9 | service_discovery, 10 | grpcbox 11 | ]}, 12 | {env,[]}, 13 | {modules, []}, 14 | 15 | {licenses, ["Apache 2.0"]}, 16 | {links, []} 17 | ]}. 18 | -------------------------------------------------------------------------------- /ctlptl.yml: -------------------------------------------------------------------------------- 1 | apiVersion: ctlptl.dev/v1alpha1 2 | kind: Registry 3 | name: ctlptl-registry 4 | port: 5002 5 | --- 6 | apiVersion: ctlptl.dev/v1alpha1 7 | kind: Cluster 8 | product: kind 9 | registry: ctlptl-registry 10 | kindV1Alpha4Cluster: 11 | name: adoptingerlang 12 | nodes: 13 | - role: control-plane 14 | extraPortMappings: 15 | - containerPort: 30950 16 | hostPort: 30950 17 | - containerPort: 30053 18 | hostPort: 30053 19 | protocol: UDP 20 | -------------------------------------------------------------------------------- /cloudbuild.yaml: -------------------------------------------------------------------------------- 1 | steps: 2 | - name: 'gcr.io/kaniko-project/executor:latest' 3 | args: 4 | - --target=runner 5 | - --dockerfile=./ci/Dockerfile.cb 6 | - --build-arg=BASE_IMAGE=$_BASE_IMAGE 7 | - --build-arg=RUNNER_IMAGE=$_RUNNER_IMAGE 8 | - --destination=us.gcr.io/$PROJECT_ID/service_discovery:$COMMIT_SHA 9 | - --cache=true 10 | - --cache-ttl=8h 11 | 12 | substitutions: 13 | _BASE_IMAGE: us.gcr.io/$PROJECT_ID/erlang:22.1.1-alpine 14 | _RUNNER_IMAGE: us.gcr.io/$PROJECT_ID/alpine:3.10.2 15 | -------------------------------------------------------------------------------- /apps/service_discovery_http/src/service_discovery_http.app.src: -------------------------------------------------------------------------------- 1 | {application, service_discovery_http, 2 | [{description, "HTTP frontend for service discovery service"}, 3 | {vsn, {git, short}}, 4 | {registered, []}, 5 | {mod, {service_discovery_http_app, []}}, 6 | {applications, 7 | [kernel, 8 | stdlib, 9 | service_discovery, 10 | jsx, 11 | acceptor_pool, 12 | elli 13 | ]}, 14 | {env,[]}, 15 | {modules, []}, 16 | 17 | {licenses, ["Apache 2.0"]}, 18 | {links, []} 19 | ]}. 20 | -------------------------------------------------------------------------------- /apps/service_discovery_postgres/priv/migrations/V2__Add_updated_at_trigger.sql: -------------------------------------------------------------------------------- 1 | CREATE OR REPLACE FUNCTION trigger_set_timestamp() 2 | RETURNS TRIGGER AS $$ 3 | BEGIN 4 | NEW.updated_at = NOW(); 5 | RETURN NEW; 6 | END; 7 | $$ LANGUAGE plpgsql; 8 | 9 | 10 | CREATE TRIGGER set_timestamp 11 | BEFORE UPDATE ON services 12 | FOR EACH ROW 13 | EXECUTE PROCEDURE trigger_set_timestamp(); 14 | 15 | CREATE TRIGGER set_timestamp 16 | BEFORE UPDATE ON endpoints 17 | FOR EACH ROW 18 | EXECUTE PROCEDURE trigger_set_timestamp(); 19 | -------------------------------------------------------------------------------- /deployment/overlays/dev/service_nodeport.yaml: -------------------------------------------------------------------------------- 1 | kind: Service 2 | apiVersion: v1 3 | metadata: 4 | name: service-discovery-nodeport 5 | spec: 6 | type: NodePort 7 | selector: 8 | app: service-discovery 9 | ports: 10 | - name: dns 11 | protocol: UDP 12 | port: 8053 13 | targetPort: dns 14 | nodePort: 30053 15 | - name: http 16 | protocol: TCP 17 | port: 3000 18 | targetPort: http 19 | nodePort: 30950 20 | - name: grpc 21 | protocol: TCP 22 | port: 8081 23 | targetPort: grpc 24 | nodePort: 30081 25 | -------------------------------------------------------------------------------- /deployment/overlays/stage/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | namespace: service-discovery-stage 4 | nameSuffix: -stage 5 | commonLabels: 6 | overlay: stage 7 | bases: 8 | - ../../base 9 | - ../../postgres 10 | images: 11 | - name: flyway/flyway 12 | newName: ghcr.io/adoptingerlang/service_discovery/flyway 13 | newTag: 9.22 14 | - name: postgres 15 | newName: ghcr.io/adoptingerlang/service_discovery/postgres 16 | newTag: 15.4 17 | configMapGenerator: 18 | - name: configmap 19 | envs: 20 | - stage.env 21 | -------------------------------------------------------------------------------- /apps/service_discovery_postgres/src/service_discovery_postgres_app.erl: -------------------------------------------------------------------------------- 1 | %%%------------------------------------------------------------------- 2 | %% @doc service_discovery public API 3 | %% @end 4 | %%%------------------------------------------------------------------- 5 | -module(service_discovery_postgres_app). 6 | 7 | -behaviour(application). 8 | 9 | -export([start/2, stop/1]). 10 | 11 | start(_StartType, _StartArgs) -> 12 | sdp_query:load_sql(), 13 | {ok, DBConfig} = application:get_env(service_discovery_postgres, db_config), 14 | service_discovery_postgres_sup:start_link(DBConfig). 15 | 16 | stop(_State) -> 17 | ok. 18 | 19 | -------------------------------------------------------------------------------- /apps/service_discovery_http/src/service_discovery_http_app.erl: -------------------------------------------------------------------------------- 1 | -module(service_discovery_http_app). 2 | 3 | -behavior(application). 4 | 5 | -export([start/2, 6 | prep_stop/1, 7 | stop/1]). 8 | 9 | -export([is_shutting_down/0]). 10 | 11 | -define(IS_SHUTTING_DOWN, {?MODULE, is_shutting_down}). 12 | 13 | start(_, _) -> 14 | Env = application:get_all_env(service_discovery_http), 15 | service_discovery_http_sup:start_link(Env). 16 | 17 | prep_stop(State) -> 18 | persistent_term:put(?IS_SHUTTING_DOWN, true), 19 | State. 20 | 21 | stop(_) -> 22 | ok. 23 | 24 | is_shutting_down() -> 25 | persistent_term:get(?IS_SHUTTING_DOWN, false). 26 | -------------------------------------------------------------------------------- /apps/service_discovery_storage/src/service_discovery_storage.erl: -------------------------------------------------------------------------------- 1 | -module(service_discovery_storage). 2 | 3 | -export([]). 4 | 5 | -callback create(service_discovery:service()) -> binary() | {error, term()}. 6 | -callback read(unicode:unicode_binary()) -> service_discovery:service() | {error, term()}. 7 | -callback read_endpoints(unicode:unicode_binary()) -> [service_discovery:endpoint()] | {error, term()}. 8 | -callback add_named_ports(unicode:unicode_binary(), service_discovery:named_ports()) -> ok | {error, term()}. 9 | -callback list() -> [service_discovery:service()] | {error, term()}. 10 | -callback register(service_discovery:name(), service_discovery:endpoint()) -> ok | {error, term()}. 11 | -------------------------------------------------------------------------------- /.github/workflows/junit.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: JUnit Report 3 | 4 | on: 5 | workflow_run: 6 | workflows: [CI] 7 | types: [completed] 8 | 9 | permissions: 10 | checks: write 11 | 12 | jobs: 13 | checks: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: Download Test Report 17 | uses: dawidd6/action-download-artifact@v2 18 | with: 19 | name: ct-test-results 20 | workflow: ${{ github.event.workflow.id }} 21 | run_id: ${{ github.event.workflow_run.id }} 22 | - name: Publish Test Report 23 | uses: mikepenz/action-junit-report@v3 24 | with: 25 | commit: ${{github.event.workflow_run.head_sha}} 26 | report_paths: '**/_build/test/logs/*/junit_report.xml' 27 | -------------------------------------------------------------------------------- /apps/service_discovery_postgres/src/service_discovery_postgres.app.src: -------------------------------------------------------------------------------- 1 | {application, service_discovery_postgres, 2 | [{description, "Postgres backend for service discovery service"}, 3 | {vsn, {git, short}}, 4 | {registered, []}, 5 | {mod, {service_discovery_postgres_app, []}}, 6 | {applications, 7 | [kernel, 8 | stdlib, 9 | eql, 10 | pgo, 11 | service_discovery_storage, 12 | service_discovery 13 | ]}, 14 | {env,[{db_config, #{host => "localhost", 15 | port => 5432, 16 | user => "discovery", 17 | password => "password", 18 | database => "discovery"}}]}, 19 | {modules, []}, 20 | 21 | {licenses, ["Apache 2.0"]}, 22 | {links, []} 23 | ]}. 24 | -------------------------------------------------------------------------------- /test/service_discovery_http_SUITE.erl: -------------------------------------------------------------------------------- 1 | -module(service_discovery_http_SUITE). 2 | 3 | -compile(export_all). 4 | 5 | -include_lib("stdlib/include/assert.hrl"). 6 | -include_lib("common_test/include/ct.hrl"). 7 | 8 | all() -> 9 | [initial_start_test]. 10 | 11 | init_per_suite(Config) -> 12 | {ok, _} = application:ensure_all_started(service_discovery), 13 | {ok, _} = application:ensure_all_started(service_discovery_http), 14 | Config. 15 | 16 | end_per_suite(_Config) -> 17 | application:stop(service_discovery_http), 18 | application:stop(service_discovery), 19 | ok. 20 | 21 | initial_start_test(_Config) -> 22 | ?assertMatch({service_discovery_http, _, _}, 23 | lists:keyfind(service_discovery_http, 1, application:which_applications())), 24 | ok. 25 | -------------------------------------------------------------------------------- /apps/service_discovery_http/src/sdh_pool.erl: -------------------------------------------------------------------------------- 1 | -module(sdh_pool). 2 | 3 | -behaviour(acceptor_pool). 4 | 5 | -export([start_link/2, 6 | accept_socket/2]). 7 | 8 | -export([init/1]). 9 | 10 | start_link(ElliOpts, ListenOpts) -> 11 | acceptor_pool:start_link({local, ?MODULE}, ?MODULE, [ElliOpts, ListenOpts]). 12 | 13 | accept_socket(Socket, Acceptors) -> 14 | acceptor_pool:accept_socket(?MODULE, Socket, Acceptors). 15 | 16 | %% TODO: add ssl support 17 | init([ElliOpts, ListenOpts]) -> 18 | ElliCallback = maps:get(callback, ElliOpts), 19 | 20 | %% Grace gives a 5 second shutdown period for open connections 21 | Conn = #{id => sdh_conn, 22 | start => {sdh_conn, {gen_tcp, ElliCallback, maps:to_list(ElliOpts), ListenOpts}, []}, 23 | grace => timer:seconds(5)}, 24 | {ok, {#{}, [Conn]}}. 25 | -------------------------------------------------------------------------------- /apps/service_discovery_http/src/sdh_conn.erl: -------------------------------------------------------------------------------- 1 | -module(sdh_conn). 2 | 3 | -behaviour(acceptor). 4 | 5 | -export([acceptor_init/3, 6 | acceptor_continue/3, 7 | acceptor_terminate/2]). 8 | 9 | acceptor_init(_, _LSocket, {Transport, ElliCallback, ElliOpts, SslOpts}) -> 10 | {ok, {Transport, ElliCallback, ElliOpts, SslOpts}}. 11 | 12 | acceptor_continue(_PeerName, Socket, {ssl, ElliCallback, ElliOpts, SslOpts}) -> 13 | {ok, AcceptSocket} = ssl:handshake(Socket, SslOpts), 14 | elli_http:keepalive_loop({ssl, AcceptSocket}, ElliOpts, ElliCallback); 15 | acceptor_continue(_PeerName, Socket, {gen_tcp, ElliCallback, ElliOpts, _SslOpts}) -> 16 | elli_http:keepalive_loop({plain, Socket}, ElliOpts, ElliCallback). 17 | 18 | acceptor_terminate(Reason, _) -> 19 | % Something went wrong. Either the acceptor_pool is terminating or the 20 | % accept failed. 21 | exit(Reason). 22 | -------------------------------------------------------------------------------- /apps/service_discovery_postgres/src/sdp_query.erl: -------------------------------------------------------------------------------- 1 | -module(sdp_query). 2 | 3 | -export([get/1, 4 | get/2, 5 | run/2, 6 | load_sql/0]). 7 | 8 | get(Name) -> 9 | persistent_term:get({?MODULE, Name}). 10 | 11 | get(Name, Params) -> 12 | lists:map(fun(Key) when is_atom(Key) -> 13 | proplists:get_value(Key, Params); 14 | (S) -> 15 | S 16 | end, ?MODULE:get(Name)). 17 | 18 | run(QueryName, Args) -> 19 | pgo:query(?MODULE:get(QueryName), Args). 20 | 21 | load_sql() -> 22 | PrivDir = code:priv_dir(service_discovery_postgres), 23 | [load_sql(PrivDir, File) || File <- ["zones.sql", "services.sql"]]. 24 | 25 | load_sql(PrivDir, File) -> 26 | SqlFile = filename:join([PrivDir, "sql", File]), 27 | {ok, Queries} = eql:compile(SqlFile), 28 | [persistent_term:put({?MODULE, Name}, Query) || {Name, Query} <- Queries]. 29 | -------------------------------------------------------------------------------- /test/service_discovery_grpc_SUITE.erl: -------------------------------------------------------------------------------- 1 | -module(service_discovery_grpc_SUITE). 2 | 3 | -compile(export_all). 4 | 5 | -include_lib("stdlib/include/assert.hrl"). 6 | -include_lib("common_test/include/ct.hrl"). 7 | 8 | all() -> 9 | [initial_start_test]. 10 | 11 | init_per_suite(Config) -> 12 | {ok, _} = application:ensure_all_started(service_discovery), 13 | {ok, _} = application:ensure_all_started(service_discovery_grpc), 14 | Config. 15 | 16 | end_per_suite(_Config) -> 17 | application:stop(service_discovery_grpc), 18 | application:stop(service_discovery), 19 | ok. 20 | 21 | initial_start_test(_Config) -> 22 | ?assertMatch({service_discovery, _, _}, 23 | lists:keyfind(service_discovery, 1, application:which_applications())), 24 | ?assertMatch({service_discovery_grpc, _, _}, 25 | lists:keyfind(service_discovery_grpc, 1, application:which_applications())), 26 | ok. 27 | -------------------------------------------------------------------------------- /apps/service_discovery_grpc/src/service_discovery_grpc_app.erl: -------------------------------------------------------------------------------- 1 | %%%------------------------------------------------------------------- 2 | %% @doc service_discovery public API 3 | %% @end 4 | %%%------------------------------------------------------------------- 5 | 6 | -module(service_discovery_grpc_app). 7 | 8 | -behaviour(application). 9 | 10 | -export([start/2, stop/1]). 11 | 12 | -define(DEFAULT_GRPC_SERVER, #{grpc_opts => #{service_protos => [sdg_discovery_pb], 13 | services => #{'sd.DiscoveryService' => sdg_service}}, 14 | listen_opts => #{port => 8081, 15 | ip => {0,0,0,0}}}). 16 | 17 | start(_StartType, _StartArgs) -> 18 | ServerOpts = application:get_env(service_discovery_grpc, server, ?DEFAULT_GRPC_SERVER), 19 | service_discovery_grpc_sup:start_link(ServerOpts). 20 | 21 | stop(_State) -> 22 | ok. 23 | -------------------------------------------------------------------------------- /apps/service_discovery/src/service_discovery_app.erl: -------------------------------------------------------------------------------- 1 | %%%------------------------------------------------------------------- 2 | %% @doc service_discovery public API 3 | %% @end 4 | %%%------------------------------------------------------------------- 5 | 6 | -module(service_discovery_app). 7 | 8 | -behaviour(application). 9 | 10 | %% Application callbacks 11 | -export([start/2, stop/1]). 12 | 13 | %%==================================================================== 14 | %% API 15 | %%==================================================================== 16 | 17 | start(_StartType, _StartArgs) -> 18 | {ok, StorageMod} = application:get_env(service_discovery, storage_module), 19 | sds_storage:configure_storage(StorageMod), 20 | service_discovery_sup:start_link(). 21 | 22 | %%-------------------------------------------------------------------- 23 | stop(_State) -> 24 | ok. 25 | 26 | %%==================================================================== 27 | %% Internal functions 28 | %%==================================================================== 29 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | postgres: 4 | image: ghcr.io/adoptingerlang/service_discovery/postgres:15.4 5 | ports: 6 | - 5432:5432 7 | environment: 8 | POSTGRES_DB: discovery 9 | POSTGRES_USER: discovery 10 | POSTGRES_PASSWORD: password 11 | POSTGRES_HOST_AUTH_METHOD: trust 12 | healthcheck: 13 | test: ["CMD", "pg_isready", "-U", "discovery", "-d", "discovery"] 14 | interval: 1s 15 | timeout: 5s 16 | retries: 10 17 | 18 | volumes: 19 | - pgdata:/var/lib/postgresql/data 20 | 21 | flyway: 22 | image: ghcr.io/adoptingerlang/service_discovery/flyway:9.22 23 | command: 24 | - -url=jdbc:postgresql://postgres:5432/discovery 25 | - -user=discovery 26 | - -password=password 27 | - -connectRetries=60 28 | - -skipCheckForUpdate 29 | - migrate 30 | volumes: 31 | - ./apps/service_discovery_postgres/priv/migrations:/flyway/sql 32 | depends_on: 33 | postgres: 34 | condition: service_healthy 35 | 36 | 37 | volumes: 38 | pgdata: 39 | -------------------------------------------------------------------------------- /deployment/postgres/postgres-deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | labels: 5 | service: postgres 6 | name: postgres 7 | spec: 8 | replicas: 1 9 | strategy: 10 | type: Recreate 11 | template: 12 | metadata: 13 | labels: 14 | service: postgres 15 | spec: 16 | containers: 17 | - env: 18 | - name: POSTGRES_DB 19 | value: discovery 20 | - name: POSTGRES_PASSWORD 21 | value: password 22 | - name: POSTGRES_USER 23 | value: discovery 24 | - name: PGDATA 25 | value: /var/lib/postgresql/data/pgdata 26 | image: postgres:15.4 27 | name: postgres 28 | ports: 29 | - containerPort: 5432 30 | resources: {} 31 | volumeMounts: 32 | - mountPath: /var/lib/postgresql/data 33 | name: pgdata 34 | restartPolicy: Always 35 | volumes: 36 | - name: pgdata 37 | emptyDir: {} 38 | # TODO: add this back through a kustomize patch if we use it for stage/prod instead of cloudsql 39 | # persistentVolumeClaim: 40 | # claimName: pgdata 41 | -------------------------------------------------------------------------------- /ci/Dockerfile.cb: -------------------------------------------------------------------------------- 1 | ARG BASE_IMAGE=erlang:22.1.1-alpine 2 | ARG RUNNER_IMAGE=alpine:3.10.2 3 | FROM $BASE_IMAGE as builder 4 | 5 | # git for fetching non-hex depenencies 6 | # add any other Alpine libraries needed to compile the project here 7 | RUN apk add --no-cache git 8 | 9 | WORKDIR /src 10 | 11 | # build and cache dependencies as their own layer 12 | COPY rebar.config rebar.lock ./ 13 | RUN rebar3 compile 14 | 15 | FROM builder as releaser 16 | 17 | # tar for unpacking the target system 18 | RUN apk add --no-cache tar 19 | 20 | WORKDIR /src 21 | RUN mkdir -p /opt/rel 22 | 23 | # copy in the source and build the release tarball 24 | COPY . . 25 | # unpack tarball to be copied into the image built next 26 | RUN rebar3 as prod tar && \ 27 | tar -zxvf /src/_build/prod/rel/*/*.tar.gz -C /opt/rel 28 | 29 | FROM $RUNNER_IMAGE as runner 30 | 31 | # install openssl, needed by the crypto app 32 | RUN apk add --no-cache openssl ncurses 33 | 34 | WORKDIR /opt/service_discovery 35 | 36 | COPY --from=releaser /opt/rel . 37 | 38 | ENV COOKIE service_discovery 39 | # write files generated during startup to /tmp 40 | ENV RELX_OUT_FILE_PATH /tmp 41 | 42 | ENTRYPOINT ["/opt/service_discovery/bin/service_discovery"] 43 | CMD ["foreground"] 44 | -------------------------------------------------------------------------------- /test/service_discovery_SUITE_data/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | postgres: 4 | image: postgres:15.4 5 | ports: 6 | - 5432:5432 7 | environment: 8 | POSTGRES_DB: discovery 9 | POSTGRES_USER: discovery 10 | POSTGRES_PASSWORD: password 11 | volumes: 12 | - pgdata:/var/lib/postgresql/data 13 | 14 | flyway: 15 | image: flyway/flyway:9.22 16 | command: 17 | - -url=jdbc:postgresql://postgres:5432/discovery 18 | - -user=discovery 19 | - -password=password 20 | - -connectRetries=60 21 | - -skipCheckForUpdate 22 | - migrate 23 | volumes: 24 | - ../../apps/service_discovery_postgres/priv/migrations:/flyway/sql 25 | depends_on: 26 | - postgres 27 | 28 | check: 29 | image: flyway/flyway:9.22 30 | entrypoint: /bin/sh 31 | command: 32 | - -c 33 | - | 34 | echo -n "Waiting for services table to be available.." 35 | while ! psql -q -h postgres -U discovery -d discovery -c 'SELECT 1 from services' >/dev/null 2>&1 ; do 36 | echo -n "." 37 | sleep 1 38 | done 39 | echo 40 | environment: 41 | PGPASSWORD: password 42 | depends_on: 43 | - flyway 44 | 45 | volumes: 46 | pgdata: 47 | -------------------------------------------------------------------------------- /deployment/base/init_validation.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: service-discovery 5 | spec: 6 | replicas: 1 7 | template: 8 | spec: 9 | volumes: 10 | - name: migrations 11 | emptyDir: {} 12 | initContainers: 13 | - name: service-discovery-sql 14 | image: service_discovery 15 | volumeMounts: 16 | - name: migrations 17 | mountPath: /flyway/sql 18 | command: ["/bin/sh"] 19 | args: ["-c", "cp /opt/service_discovery/sql/* /flyway/sql"] 20 | 21 | - image: flyway/flyway:9.22 22 | name: flyway-validate 23 | args: 24 | - "-url=jdbc:postgresql://$(POSTGRES_SERVICE):5432/$(POSTGRES_DB)" 25 | - "-user=$(POSTGRES_USER)" 26 | - "-password=$(POSTGRES_PASSWORD)" 27 | - "-connectRetries=60" 28 | - "-skipCheckForUpdate" 29 | - validate 30 | volumeMounts: 31 | - name: migrations 32 | mountPath: /flyway/sql 33 | env: 34 | - name: POSTGRES_SERVICE 35 | value: POSTGRES_SERVICE 36 | - name: POSTGRES_DB 37 | value: POSTGRES_DB 38 | - name: POSTGRES_USER 39 | value: POSTGRES_USER 40 | - name: POSTGRES_PASSWORD 41 | value: POSTGRES_PASSWORD 42 | -------------------------------------------------------------------------------- /apps/service_discovery_postgres/priv/sql/services.sql: -------------------------------------------------------------------------------- 1 | -- :select_service 2 | SELECT 3 | services.name, 4 | services.attributes, 5 | COALESCE(array_agg(named_ports) FILTER (WHERE named_ports IS NOT NULL), '{}'), 6 | COALESCE(array_agg(endpoints) FILTER (WHERE endpoints IS NOT NULL), '{}') 7 | FROM services 8 | LEFT OUTER JOIN named_ports ON named_ports.service_id = services.id 9 | LEFT OUTER JOIN endpoints ON endpoints.service_id = services.id 10 | WHERE services.name = $1 11 | GROUP BY services.name, services.attributes 12 | 13 | 14 | -- :select_all_services 15 | SELECT 16 | name, 17 | attributes 18 | FROM services 19 | 20 | -- :insert_service 21 | INSERT INTO services (name, attributes) VALUES ($1, $2) RETURNING (id) 22 | 23 | -- :insert_endpoint 24 | INSERT INTO endpoints (service_id, ip, tags) 25 | VALUES ((SELECT id FROM services WHERE name = $1), $2, $3) 26 | 27 | -- :insert_named_ports 28 | INSERT INTO named_ports (service_id, port_name, protocol, port) 29 | SELECT (SELECT id FROM services WHERE name = $1), p.port_name, p.protocol, p.port 30 | FROM UNNEST($2::named_ports[]) AS p(service_id, port_name, protocol, port) 31 | 32 | -- :select_endpoints 33 | SELECT 34 | ip, 35 | tags 36 | FROM endpoints 37 | JOIN services ON services.id = endpoints.service_id 38 | WHERE services.name = $1 39 | -------------------------------------------------------------------------------- /apps/service_discovery_postgres/priv/migrations/V1__Create_services_endpoints_table.sql: -------------------------------------------------------------------------------- 1 | CREATE EXTENSION IF NOT EXISTS hstore; 2 | CREATE EXTENSION IF NOT EXISTS pgcrypto; 3 | CREATE EXTENSION citext; 4 | 5 | CREATE TABLE services 6 | ( 7 | id UUID NOT NULL DEFAULT gen_random_uuid(), 8 | name CITEXT UNIQUE NOT NULL, 9 | attributes HSTORE NOT NULL, 10 | created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), 11 | updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), 12 | PRIMARY KEY (id) 13 | ); 14 | 15 | CREATE TABLE named_ports 16 | ( 17 | service_id UUID NOT NULL REFERENCES services (id) ON DELETE CASCADE, 18 | port_name CITEXT NOT NULL, 19 | protocol CITEXT NOT NULL, 20 | port INT2 NOT NULL, 21 | CHECK (port > 0 AND port < 65536), 22 | PRIMARY KEY (service_id, port_name) 23 | ); 24 | 25 | 26 | CREATE TABLE endpoints 27 | ( 28 | service_id UUID NOT NULL REFERENCES services (id) ON DELETE CASCADE, 29 | ip INET NOT NULL, 30 | tags TEXT[] NOT NULL, 31 | created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), 32 | updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), 33 | PRIMARY KEY (service_id, ip) 34 | ); 35 | 36 | CREATE INDEX idx_service_attributes ON services USING GIN(attributes); 37 | CREATE INDEX idx_endpoint_tags ON endpoints USING GIN(tags); 38 | -------------------------------------------------------------------------------- /apps/service_discovery/src/service_discovery_sup.erl: -------------------------------------------------------------------------------- 1 | %%%------------------------------------------------------------------- 2 | %% @doc service_discovery top level supervisor. 3 | %% @end 4 | %%%------------------------------------------------------------------- 5 | 6 | -module(service_discovery_sup). 7 | 8 | -behaviour(supervisor). 9 | 10 | %% API 11 | -export([start_link/0]). 12 | 13 | %% Supervisor callbacks 14 | -export([init/1]). 15 | 16 | -define(SERVER, ?MODULE). 17 | 18 | %%==================================================================== 19 | %% API functions 20 | %%==================================================================== 21 | 22 | start_link() -> 23 | supervisor:start_link({local, ?SERVER}, ?MODULE, []). 24 | 25 | %%==================================================================== 26 | %% Supervisor callbacks 27 | %%==================================================================== 28 | 29 | %% Child :: #{id => Id, start => {M, F, A}} 30 | %% Optional keys are restart, shutdown, type, modules. 31 | %% Before OTP 18 tuples must be used to specify a child. e.g. 32 | %% Child :: {Id,StartFunc,Restart,Shutdown,Type,Modules} 33 | init([]) -> 34 | {ok, {{one_for_all, 0, 1}, []}}. 35 | 36 | %%==================================================================== 37 | %% Internal functions 38 | %%==================================================================== 39 | -------------------------------------------------------------------------------- /deployment/base/deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: service-discovery 5 | spec: 6 | replicas: 1 7 | strategy: 8 | type: RollingUpdate 9 | rollingUpdate: 10 | maxUnavailable: 0 11 | maxSurge: 25% 12 | template: 13 | spec: 14 | shareProcessNamespace: true 15 | containers: 16 | - name: service-discovery 17 | image: service_discovery 18 | ports: 19 | - containerPort: 8053 20 | protocol: UDP 21 | name: dns 22 | - containerPort: 3000 23 | protocol: TCP 24 | name: http 25 | - containerPort: 8081 26 | protocol: TCP 27 | name: grpc 28 | env: 29 | - name: DB_HOST 30 | value: POSTGRES_SERVICE 31 | - name: SCHEDULERS 32 | valueFrom: 33 | resourceFieldRef: 34 | containerName: service-discovery 35 | resource: limits.cpu 36 | divisor: 1 37 | envFrom: 38 | - configMapRef: 39 | name: configmap 40 | 41 | readinessProbe: 42 | httpGet: 43 | path: /ready 44 | port: http 45 | initialDelaySeconds: 3 46 | periodSeconds: 5 47 | 48 | livenessProbe: 49 | httpGet: 50 | path: /healthz 51 | port: http 52 | initialDelaySeconds: 3 53 | periodSeconds: 15 54 | -------------------------------------------------------------------------------- /deployment/postgres/flyway-job.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: batch/v1 2 | kind: Job 3 | metadata: 4 | labels: 5 | service: flyway 6 | name: flyway 7 | spec: 8 | ttlSecondsAfterFinished: 0 9 | template: 10 | metadata: 11 | labels: 12 | service: flyway 13 | spec: 14 | restartPolicy: OnFailure 15 | volumes: 16 | - name: migrations 17 | emptyDir: 18 | medium: Memory 19 | 20 | containers: 21 | - args: 22 | - "-url=jdbc:postgresql://$(POSTGRES_SERVICE):5432/$(POSTGRES_DB)" 23 | - -user=$(POSTGRES_USER) 24 | - -password=$(POSTGRES_PASSWORD) 25 | - -connectRetries=60 26 | - -skipCheckForUpdate 27 | - migrate 28 | image: flyway/flyway:9.22 29 | name: flyway 30 | volumeMounts: 31 | - name: migrations 32 | mountPath: /flyway/sql 33 | env: 34 | - name: POSTGRES_SERVICE 35 | value: POSTGRES_SERVICE 36 | - name: POSTGRES_DB 37 | value: POSTGRES_DB 38 | - name: POSTGRES_USER 39 | value: POSTGRES_USER 40 | - name: POSTGRES_PASSWORD 41 | value: POSTGRES_PASSWORD 42 | 43 | initContainers: 44 | - name: service-discovery-sql 45 | image: service_discovery 46 | command: ["/bin/sh"] 47 | args: ["-c", "cp /opt/service_discovery/sql/* /flyway/sql"] 48 | volumeMounts: 49 | - name: migrations 50 | mountPath: /flyway/sql 51 | -------------------------------------------------------------------------------- /apps/service_discovery_grpc/src/service_discovery_grpc_sup.erl: -------------------------------------------------------------------------------- 1 | %%%------------------------------------------------------------------- 2 | %% @doc service_discovery top level supervisor. 3 | %% @end 4 | %%%------------------------------------------------------------------- 5 | 6 | -module(service_discovery_grpc_sup). 7 | 8 | -behaviour(supervisor). 9 | 10 | -export([start_link/1]). 11 | 12 | -export([init/1]). 13 | 14 | -define(SERVER, ?MODULE). 15 | 16 | start_link(Opts) -> 17 | GrpcOpts = maps:get(grpc_opts, Opts, #{}), 18 | ServerOpts = maps:get(server_opts, Opts, #{}), 19 | ListenOpts = maps:get(listen_opts, Opts, #{}), 20 | PoolOpts = maps:get(pool_opts, Opts, #{}), 21 | TransportOpts = maps:get(transport_opts, Opts, #{}), 22 | supervisor:start_link({local, ?SERVER}, ?MODULE, [ServerOpts, GrpcOpts, ListenOpts, 23 | PoolOpts, TransportOpts]). 24 | 25 | init([ServerOpts, GrpcOpts, ListenOpts, PoolOpts, TransportOpts]) -> 26 | SupFlags = #{strategy => one_for_one, 27 | intensity => 5, 28 | period => 10}, 29 | ChildSpecs = [#{id => grpcbox_services_sup, 30 | start => {grpcbox_services_sup, start_link, [ServerOpts, GrpcOpts, ListenOpts, 31 | PoolOpts, TransportOpts]}, 32 | type => supervisor, 33 | restart => transient, 34 | shutdown => 1000}], 35 | {ok, {SupFlags, ChildSpecs}}. 36 | -------------------------------------------------------------------------------- /apps/service_discovery_storage/src/sds_storage.erl: -------------------------------------------------------------------------------- 1 | -module(sds_storage). 2 | 3 | -behaviour(service_discovery_storage). 4 | 5 | -export([configure_storage/1, 6 | create/1, 7 | read/1, 8 | read_endpoints/1, 9 | add_named_ports/2, 10 | list/0, 11 | register/2]). 12 | 13 | -define(STORAGE_KEY, {?MODULE, storage_module}). 14 | -define(STORAGE_MOD, (persistent_term:get(?STORAGE_KEY))). 15 | 16 | configure_storage(StorageMod) -> 17 | persistent_term:put(?STORAGE_KEY, StorageMod). 18 | 19 | -spec create(service_discovery:service()) -> binary() | {error, term()}. 20 | create(Service) -> 21 | ?STORAGE_MOD:create(Service). 22 | 23 | -spec read(unicode:unicode_binary()) -> service_discovery:service() | {error, term()}. 24 | read(ServiceName) -> 25 | ?STORAGE_MOD:read(ServiceName). 26 | 27 | -spec read_endpoints(unicode:unicode_binary()) -> [service_discovery:endpoint()] | {error, term()}. 28 | read_endpoints(ServiceName) -> 29 | ?STORAGE_MOD:read_endpoints(ServiceName). 30 | 31 | -spec add_named_ports(unicode:unicode_binary(), service_discovery:named_ports()) -> ok | {error, term()}. 32 | add_named_ports(ServiceName, NamedPorts) -> 33 | ?STORAGE_MOD:add_named_ports(ServiceName, NamedPorts). 34 | 35 | -spec list() -> [service_discovery:service()] | {error, term()}. 36 | list() -> 37 | ?STORAGE_MOD:list(). 38 | 39 | -spec register(service_discovery:name(), service_discovery:endpoint()) -> ok. 40 | register(ServiceName, Endpoint) -> 41 | ?STORAGE_MOD:register(ServiceName, Endpoint). 42 | -------------------------------------------------------------------------------- /ci/Dockerfile.test: -------------------------------------------------------------------------------- 1 | # syntax=docker/dockerfile:1.2 2 | FROM ghcr.io/adoptingerlang/service_discovery/erlang:26.0.2 as builder 3 | 4 | WORKDIR /app/src 5 | ENV REBAR_BASE_DIR /app/_build 6 | 7 | RUN rm -f /etc/apt/apt.conf.d/docker-clean 8 | 9 | # Install git for fetching non-hex depenencies. 10 | # Add any other Debian libraries needed to compile the project here. 11 | RUN --mount=target=/var/lib/apt/lists,id=apt-lists,type=cache,sharing=locked \ 12 | --mount=type=cache,id=apt,target=/var/cache/apt \ 13 | apt update && apt install --no-install-recommends -y git 14 | 15 | # build and cache dependencies as their own layer 16 | COPY rebar.config rebar.lock . 17 | RUN --mount=id=hex-cache,type=cache,sharing=locked,target=/root/.cache/rebar3 \ 18 | rebar3 compile 19 | 20 | FROM builder as test_compiled 21 | 22 | RUN --mount=target=. \ 23 | --mount=id=hex-cache,type=cache,target=/root/.cache/rebar3 \ 24 | rebar3 as test compile 25 | 26 | # image for running common test suites 27 | FROM test_compiled as tester 28 | 29 | RUN apk add --no-cache py-pip python-dev libffi-dev openssl-dev gcc libc-dev make && \ 30 | pip install docker-compose 31 | 32 | RUN --mount=target=. \ 33 | --mount=id=hex-cache,type=cache,sharing=locked,target=/root/.cache/rebar3 \ 34 | rebar3 as test compile 35 | 36 | ENTRYPOINT ["rebar3"] 37 | CMD ["ct"] 38 | 39 | # image for caching dialyzer plt 40 | FROM builder as plt 41 | 42 | RUN --mount=id=hex-cache,type=cache,sharing=locked,target=/root/.cache/rebar3 \ 43 | rebar3 dialyzer --succ-typings=false 44 | 45 | ENTRYPOINT ["rebar3"] 46 | CMD ["dialyzer"] 47 | -------------------------------------------------------------------------------- /test/service_discovery_SUITE.erl: -------------------------------------------------------------------------------- 1 | -module(service_discovery_SUITE). 2 | 3 | -compile(export_all). 4 | 5 | -include_lib("stdlib/include/assert.hrl"). 6 | -include_lib("common_test/include/ct.hrl"). 7 | 8 | all() -> 9 | [create_service]. 10 | 11 | suite() -> 12 | %% don't use compose hook in circleci 13 | case os:getenv("CI") of 14 | false -> 15 | %% this won't work until it can properly wait for the db migration to complete 16 | %% [{ct_hooks, [docker_compose_cth]}]; 17 | []; 18 | _ -> 19 | [] 20 | end. 21 | 22 | init_per_suite(Config) -> 23 | {ok, _} = application:ensure_all_started(service_discovery_postgres), 24 | Config. 25 | 26 | end_per_suite(_Config) -> 27 | application:stop(service_discovery_postgres), 28 | ok. 29 | 30 | create_service(_Config) -> 31 | ServiceName = sd_test_utils:random_service_name(), 32 | ServiceAttributes = #{<<"test-key-1">> => <<"test-value-1">>}, 33 | _Uuid = service_discovery:create(#{name => ServiceName, 34 | attributes => ServiceAttributes}), 35 | ?assertMatch(#{name := ServiceName, 36 | attributes := ServiceAttributes}, service_discovery:lookup(ServiceName)), 37 | 38 | service_discovery:register(ServiceName, #{ip => {127,0,0,1}, 39 | tags => []}), 40 | ?assertMatch([{127,0,0,1}], dns_a_lookup(ServiceName)), 41 | 42 | ok. 43 | 44 | %% 45 | 46 | dns_a_lookup(ServiceName) -> 47 | inet_res:lookup(binary_to_list(ServiceName), in, a, [{nameservers, [{{127,0,0,1}, 8053}]}]). 48 | -------------------------------------------------------------------------------- /apps/service_discovery_grpc/src/sd_discovery_service_bhvr.erl: -------------------------------------------------------------------------------- 1 | %%%------------------------------------------------------------------- 2 | %% @doc Behaviour to implement for grpc service sd.DiscoveryService. 3 | %% @end 4 | %%%------------------------------------------------------------------- 5 | 6 | %% this module was generated on 2019-07-05T14:33:23+00:00 and should not be modified manually 7 | 8 | -module(sd_discovery_service_bhvr). 9 | 10 | %% @doc Unary RPC 11 | -callback get_service(ctx:ctx(), sdg_discovery_pb:get_service_request()) -> 12 | {ok, sdg_discovery_pb:get_service_response(), ctx:ctx()} | grpcbox_stream:grpc_error_response(). 13 | 14 | %% @doc Unary RPC 15 | -callback create_service(ctx:ctx(), sdg_discovery_pb:create_service_request()) -> 16 | {ok, sdg_discovery_pb:create_service_response(), ctx:ctx()} | grpcbox_stream:grpc_error_response(). 17 | 18 | %% @doc Unary RPC 19 | -callback list_services(ctx:ctx(), sdg_discovery_pb:list_services_request()) -> 20 | {ok, sdg_discovery_pb:list_services_response(), ctx:ctx()} | grpcbox_stream:grpc_error_response(). 21 | 22 | %% @doc Unary RPC 23 | -callback add_named_ports(ctx:ctx(), sdg_discovery_pb:add_named_ports_request()) -> 24 | {ok, sdg_discovery_pb:add_named_ports_response(), ctx:ctx()} | grpcbox_stream:grpc_error_response(). 25 | 26 | %% @doc Unary RPC 27 | -callback lookup_endpoints(ctx:ctx(), sdg_discovery_pb:lookup_endpoints_request()) -> 28 | {ok, sdg_discovery_pb:lookup_endpoints_response(), ctx:ctx()} | grpcbox_stream:grpc_error_response(). 29 | 30 | %% @doc Unary RPC 31 | -callback register_endpoint(ctx:ctx(), sdg_discovery_pb:register_endpoint_request()) -> 32 | {ok, sdg_discovery_pb:register_endpoint_response(), ctx:ctx()} | grpcbox_stream:grpc_error_response(). 33 | 34 | -------------------------------------------------------------------------------- /deployment/postgres/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | namespace: service-discovery 4 | resources: 5 | - flyway-job.yaml 6 | - postgres-deployment.yaml 7 | - postgres-service.yaml 8 | - pgdata-persistentvolumeclaim.yaml 9 | 10 | # this is overridden by the overlays replacement 11 | # so the dev overlway will set POSTGRES_SERVICE to postgres-dev 12 | replacements: 13 | - source: 14 | version: v1 15 | kind: Service 16 | name: postgres 17 | targets: 18 | - select: 19 | kind: Job 20 | name: flyway 21 | fieldPaths: 22 | - spec.template.spec.containers.[name=flyway].env.[name=POSTGRES_SERVICE].value 23 | - source: 24 | version: v1 25 | kind: Deployment 26 | name: postgres 27 | fieldPath: spec.template.spec.containers.[name=postgres].env.[name=POSTGRES_DB].value 28 | targets: 29 | - select: 30 | kind: Job 31 | name: flyway 32 | fieldPaths: 33 | - spec.template.spec.containers.[name=flyway].env.[name=POSTGRES_DB].value 34 | - source: 35 | version: v1 36 | kind: Deployment 37 | name: postgres 38 | fieldPath: spec.template.spec.containers.[name=postgres].env.[name=POSTGRES_USER].value 39 | targets: 40 | - select: 41 | kind: Job 42 | name: flyway 43 | fieldPaths: 44 | - spec.template.spec.containers.[name=flyway].env.[name=POSTGRES_USER].value 45 | - source: 46 | version: v1 47 | kind: Deployment 48 | name: postgres 49 | fieldPath: spec.template.spec.containers.[name=postgres].env.[name=POSTGRES_PASSWORD].value 50 | targets: 51 | - select: 52 | kind: Job 53 | name: flyway 54 | fieldPaths: 55 | - spec.template.spec.containers.[name=flyway].env.[name=POSTGRES_PASSWORD].value 56 | 57 | labels: 58 | - includeSelectors: true 59 | pairs: 60 | app: postgres 61 | -------------------------------------------------------------------------------- /apps/service_discovery_grpc/proto/discovery.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package sd; 4 | 5 | service DiscoveryService { 6 | rpc GetService(GetServiceRequest) returns (GetServiceResponse); 7 | rpc CreateService(CreateServiceRequest) returns (CreateServiceResponse); 8 | rpc ListServices(ListServicesRequest) returns (ListServicesResponse); 9 | rpc AddNamedPorts(AddNamedPortsRequest) returns (AddNamedPortsResponse); 10 | rpc LookupEndpoints(LookupEndpointsRequest) returns (LookupEndpointsResponse); 11 | rpc RegisterEndpoint(RegisterEndpointRequest) returns (RegisterEndpointResponse); 12 | } 13 | 14 | message NamedPort { 15 | string name = 1; 16 | string protocol = 2; 17 | int32 port = 3; 18 | } 19 | 20 | message Service { 21 | string name = 1; 22 | map attributes = 2; 23 | map named_ports = 3; 24 | } 25 | 26 | message Endpoint { 27 | string service_name = 1; 28 | string ip = 2; 29 | repeated string tags = 5; 30 | } 31 | 32 | message GetServiceRequest { 33 | string service_name = 1; 34 | } 35 | 36 | message GetServiceResponse { 37 | Service service = 1; 38 | } 39 | 40 | message CreateServiceRequest { 41 | Service service = 1; 42 | } 43 | 44 | message CreateServiceResponse { 45 | 46 | } 47 | 48 | message ListServicesRequest { 49 | } 50 | 51 | message ListServicesResponse { 52 | repeated Service services = 1; 53 | } 54 | 55 | message AddNamedPortsRequest { 56 | string service_name = 1; 57 | map named_ports = 2; 58 | } 59 | 60 | message AddNamedPortsResponse { 61 | } 62 | 63 | message LookupEndpointsRequest { 64 | string service_name = 1; 65 | } 66 | 67 | message LookupEndpointsResponse { 68 | repeated Endpoint endpoints = 1; 69 | } 70 | 71 | message RegisterEndpointRequest { 72 | string service_name = 1; 73 | Endpoint endpoint = 2; 74 | } 75 | 76 | message RegisterEndpointResponse { 77 | 78 | } -------------------------------------------------------------------------------- /ci/build_images.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -ex 4 | 5 | # change working directory to top level of the project 6 | SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 7 | cd $SCRIPT_DIR/.. 8 | 9 | type=image 10 | push= 11 | target=runner 12 | registry= 13 | 14 | usage() { 15 | echo "Usage: $0 [-p] [-l] [-t {builder|releaser|runner|plt}] [-r ]" 16 | echo 17 | echo " -p Enable pushing images to registry after build" 18 | echo " -t Target image to build (default: runner)" 19 | echo " -r Registry to push images" 20 | } 21 | 22 | while getopts ":t:r:pl" opt; do 23 | case ${opt} in 24 | l ) 25 | type="docker" 26 | ;; 27 | p ) 28 | push="--push" 29 | ;; 30 | t ) 31 | target=$OPTARG 32 | ;; 33 | r ) 34 | registry=${OPTARG}/ 35 | ;; 36 | : ) 37 | echo "Invalid Option: -$OPTARG requires an argument" 1>&2 38 | exit 1 39 | ;; 40 | \? ) 41 | usage 42 | exit 1 43 | ;; 44 | esac 45 | done 46 | shift $((OPTIND -1)) 47 | 48 | # must export this so experimental Dockerfile features work 49 | export DOCKER_BUILDKIT=1 50 | 51 | IMAGE=${registry}service_discovery 52 | 53 | GIT_REF=$(git rev-parse HEAD) # or with --short 54 | GIT_BRANCH=$(git symbolic-ref --short HEAD) 55 | 56 | # because of issues with using buildx as a plugin in CircleCI, 57 | # buildx is called directly in this script 58 | ~/.docker/cli-plugins/docker-buildx build --target $target \ 59 | $push \ 60 | -o type=$type \ 61 | --tag "${IMAGE}:${GIT_BRANCH}" \ 62 | --tag "${IMAGE}:${GIT_REF}" \ 63 | --cache-from="${IMAGE}:${GIT_BRANCH}" \ 64 | --cache-from="${IMAGE}:main" \ 65 | --cache-to=type=inline \ 66 | . 67 | 68 | echo "Finished building ${IMAGE}:${GIT_REF}" 69 | -------------------------------------------------------------------------------- /apps/service_discovery/src/service_discovery.erl: -------------------------------------------------------------------------------- 1 | -module(service_discovery). 2 | 3 | -export([create/1, 4 | lookup/1, 5 | lookup_endpoints/1, 6 | add_named_ports/2, 7 | list/0, 8 | register/2]). 9 | 10 | -type name() :: unicode:unicode_binary(). 11 | -type named_ports() :: #{name() => #{protocol := name(), 12 | port := non_neg_integer()}}. 13 | 14 | -type attributes() :: #{unicode:unicode_binary() => unicode:unicode_binary()}. 15 | -type service() :: #{name := name(), 16 | attributes := attributes(), 17 | endpoints => [endpoint()], 18 | named_ports => named_ports()}. 19 | 20 | -type tag() :: unicode:unicode_binary(). 21 | -type endpoint() :: #{service_name => name(), 22 | ip := inet:ip_address(), 23 | tags := [tag()]}. 24 | 25 | -export_type([service/0, 26 | named_ports/0, 27 | endpoint/0, 28 | tag/0, 29 | attributes/0]). 30 | 31 | -spec create(service()) -> binary() | {error, term()}. 32 | create(Service) -> 33 | sds_storage:create(Service). 34 | 35 | -spec lookup(unicode:unicode_binary()) -> service() | {error, term()}. 36 | lookup(ServiceName) -> 37 | sds_storage:read(ServiceName). 38 | 39 | -spec lookup_endpoints(unicode:unicode_binary()) -> [endpoint()] | {error, term()}. 40 | lookup_endpoints(ServiceName) -> 41 | sds_storage:read_endpoints(ServiceName). 42 | 43 | -spec add_named_ports(unicode:unicode_binary(), named_ports()) -> ok | {error, term()}. 44 | add_named_ports(ServiceName, NamedPorts) -> 45 | sds_storage:add_named_ports(ServiceName, NamedPorts). 46 | 47 | -spec list() -> [service()] | {error, term()}. 48 | list() -> 49 | sds_storage:list(). 50 | 51 | -spec register(name(), endpoint()) -> ok. 52 | register(ServiceName, Endpoint) -> 53 | sds_storage:register(ServiceName, Endpoint). 54 | -------------------------------------------------------------------------------- /config/dev_sys.config: -------------------------------------------------------------------------------- 1 | [ 2 | {service_discovery, [{storage_module, sdp_services_storage}]}, 3 | 4 | {service_discovery_postgres, [{db_config, #{host => "localhost", 5 | port => 5432, 6 | user => "discovery", 7 | password => "password", 8 | database => "discovery"}}]}, 9 | 10 | 11 | {service_discovery_grpc, 12 | [{server, #{grpc_opts => #{service_protos => [sdg_discovery_pb, 13 | grpcbox_health_pb, 14 | grpcbox_reflection_pb], 15 | services => #{'sd.DiscoveryService' => sdg_service, 16 | 'grpc.health.v1.Health' => grpcbox_health_service, 17 | 'grpc.reflection.v1alpha.ServerReflection' => 18 | grpcbox_reflection_service}}, 19 | 20 | listen_opts => #{port => 8081, 21 | ip => {0,0,0,0}}}}]}, 22 | 23 | 24 | {erldns, 25 | [%% DB Config 26 | {storage, 27 | [{type, sdp_erldns_storage}, 28 | {dir, "db"}]}, 29 | {servers, [ 30 | [{name, inet_localhost_1}, 31 | {address, "127.0.0.1"}, 32 | {port, 8053}, 33 | {family, inet}, 34 | {processes, 2}] 35 | ]}, 36 | 37 | {use_root_hints, false}, 38 | {catch_exceptions, false}, 39 | 40 | {pools, [ 41 | {tcp_worker_pool, erldns_worker, [ 42 | {size, 10}, 43 | {max_overflow, 20} 44 | ]} 45 | ]} 46 | ]}, 47 | 48 | {kernel, [{logger, [{handler, default, logger_std_h, 49 | #{level => debug, 50 | formatter => {logger_formatter, #{single_line => true}}}}]}]} 51 | ]. 52 | -------------------------------------------------------------------------------- /config/sys.config.src: -------------------------------------------------------------------------------- 1 | [ 2 | {service_discovery, [{storage_module, sdp_services_storage}]}, 3 | 4 | {service_discovery_postgres, [{db_config, #{host => "${DB_HOST}", 5 | port => 5432, 6 | user => "discovery", 7 | password => "password", 8 | database => "discovery"}}]}, 9 | {service_discovery_grpc, 10 | [{server, #{grpc_opts => #{service_protos => [sdg_discovery_pb, 11 | grpcbox_health_pb, 12 | grpcbox_reflection_pb], 13 | services => #{'sd.DiscoveryService' => sdg_service, 14 | 'grpc.health.v1.Health' => grpcbox_health_service, 15 | 'grpc.reflection.v1alpha.ServerReflection' => 16 | grpcbox_reflection_service}}, 17 | 18 | listen_opts => #{port => 8081, 19 | ip => {0,0,0,0}}}}]}, 20 | 21 | {erldns, 22 | [%% DB Config 23 | {storage, 24 | [{type, sdp_erldns_storage}, 25 | {dir, "db"}]}, 26 | {servers, [ 27 | [{name, inet_localhost_1}, 28 | {address, "127.0.0.1"}, 29 | {port, 8053}, 30 | {family, inet}, 31 | {processes, 2}] 32 | ]}, 33 | 34 | {use_root_hints, false}, 35 | {catch_exceptions, false}, 36 | 37 | {pools, [ 38 | {tcp_worker_pool, erldns_worker, [ 39 | {size, 10}, 40 | {max_overflow, 20} 41 | ]} 42 | ]} 43 | ]}, 44 | 45 | {kernel, [{logger, [{handler, default, logger_std_h, 46 | #{level => ${LOGGER_LEVEL}, 47 | formatter => {logger_formatter, #{single_line => true}}}}]}]} 48 | ]. 49 | -------------------------------------------------------------------------------- /config/test.config: -------------------------------------------------------------------------------- 1 | [ 2 | {service_discovery, [{storage_module, sdp_services_storage}]}, 3 | 4 | {service_discovery_postgres, [{db_config, #{host => "localhost", 5 | port => 5432, 6 | user => "discovery", 7 | password => "password", 8 | database => "discovery"}}]}, 9 | 10 | {service_discovery_grpc, 11 | [{server, #{grpc_opts => #{service_protos => [sdg_discovery_pb, 12 | grpcbox_health_pb, 13 | grpcbox_reflection_pb], 14 | services => #{'sd.DiscoveryService' => sdg_service, 15 | 'grpc.health.v1.Health' => grpcbox_health_service, 16 | 'grpc.reflection.v1alpha.ServerReflection' => 17 | grpcbox_reflection_service}}, 18 | 19 | listen_opts => #{port => 8081, 20 | ip => {0,0,0,0}}}}]}, 21 | 22 | {erldns, 23 | [%% DB Config 24 | {storage, 25 | [{type, sdp_erldns_storage}, 26 | {dir, "db"}]}, 27 | {servers, [ 28 | [{name, inet_localhost_1}, 29 | {address, "127.0.0.1"}, 30 | {port, 8053}, 31 | {family, inet}, 32 | {processes, 2}] 33 | ]}, 34 | 35 | {use_root_hints, false}, 36 | {catch_exceptions, false}, 37 | %% {zones, ""}, 38 | 39 | {pools, [ 40 | {tcp_worker_pool, erldns_worker, [ 41 | {size, 10}, 42 | {max_overflow, 20} 43 | ]} 44 | ]} 45 | ]}, 46 | 47 | {kernel, [{logger, [{handler, default, logger_std_h, 48 | #{level => debug, 49 | formatter => {logger_formatter, #{single_line => true}}}}]}]} 50 | ]. 51 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # syntax=docker/dockerfile:1.2 2 | FROM ghcr.io/adoptingerlang/service_discovery/erlang:26.0.2 as builder 3 | 4 | WORKDIR /app/src 5 | ENV REBAR_BASE_DIR /app/_build 6 | 7 | RUN rm -f /etc/apt/apt.conf.d/docker-clean 8 | 9 | # Install git for fetching non-hex depenencies. 10 | # Add any other Debian libraries needed to compile the project here. 11 | RUN --mount=target=/var/lib/apt/lists,id=apt-lists,type=cache,sharing=locked \ 12 | --mount=type=cache,id=apt,target=/var/cache/apt \ 13 | apt update && apt install --no-install-recommends -y git 14 | 15 | # build and cache dependencies as their own layer 16 | COPY rebar.config rebar.lock . 17 | RUN --mount=id=hex-cache,type=cache,sharing=locked,target=/root/.cache/rebar3 \ 18 | rebar3 compile 19 | 20 | FROM builder as prod_compiled 21 | 22 | RUN --mount=target=. \ 23 | --mount=id=hex-cache,type=cache,sharing=locked,target=/root/.cache/rebar3 \ 24 | rebar3 as prod compile 25 | 26 | FROM prod_compiled as releaser 27 | 28 | # create the directory to unpack the release to 29 | RUN mkdir -p /opt/rel 30 | 31 | RUN --mount=target=. \ 32 | --mount=id=hex-cache,type=cache,sharing=locked,target=/root/.cache/rebar3 \ 33 | rebar3 as prod tar && \ 34 | tar -zxvf $REBAR_BASE_DIR/prod/rel/*/*.tar.gz -C /opt/rel 35 | 36 | FROM ghcr.io/adoptingerlang/service_discovery/debian:bullseye as runner 37 | 38 | WORKDIR /opt/service_discovery 39 | 40 | ENV COOKIE=service_discovery \ 41 | # write files generated during startup to /tmp 42 | RELX_OUT_FILE_PATH=/tmp \ 43 | # service_discovery specific env variables to act as defaults 44 | DB_HOST=127.0.0.1 \ 45 | LOGGER_LEVEL=debug \ 46 | SCHEDULERS=1 47 | 48 | RUN rm -f /etc/apt/apt.conf.d/docker-clean 49 | 50 | # openssl needed by the crypto app 51 | RUN --mount=target=/var/lib/apt/lists,id=apt-lists,type=cache,sharing=locked \ 52 | --mount=type=cache,id=apt,sharing=locked,target=/var/cache/apt \ 53 | apt install --no-install-recommends -y openssl ncurses-bin 54 | 55 | COPY --from=releaser /opt/rel . 56 | 57 | ENTRYPOINT ["/opt/service_discovery/bin/service_discovery"] 58 | CMD ["foreground"] 59 | 60 | -------------------------------------------------------------------------------- /apps/service_discovery_postgres/src/service_discovery_postgres_sup.erl: -------------------------------------------------------------------------------- 1 | %%%------------------------------------------------------------------- 2 | %% @doc service_discovery top level supervisor. 3 | %% @end 4 | %%%------------------------------------------------------------------- 5 | 6 | -module(service_discovery_postgres_sup). 7 | 8 | -behaviour(supervisor). 9 | 10 | %% API 11 | -export([start_link/1]). 12 | 13 | %% Supervisor callbacks 14 | -export([init/1]). 15 | 16 | -define(SERVER, ?MODULE). 17 | 18 | %%==================================================================== 19 | %% API functions 20 | %%==================================================================== 21 | 22 | start_link(DBConfig) -> 23 | supervisor:start_link({local, ?SERVER}, ?MODULE, [DBConfig]). 24 | 25 | %%==================================================================== 26 | %% Supervisor callbacks 27 | %%==================================================================== 28 | 29 | %% Child :: #{id => Id, start => {M, F, A}} 30 | %% Optional keys are restart, shutdown, type, modules. 31 | %% Before OTP 18 tuples must be used to specify a child. e.g. 32 | %% Child :: {Id,StartFunc,Restart,Shutdown,Type,Modules} 33 | init([DBConfig]) -> 34 | PoolConfig = DBConfig#{ 35 | %% pool specific settings 36 | %% pool_size => integer(), 37 | %% queue_target => integer(), 38 | %% queue_interval => integer(), 39 | %% idle_interval => integer(), 40 | queue => true, 41 | trace => false, 42 | decode_opts => []}, 43 | 44 | SupFlags = #{strategy => one_for_one, 45 | intensity => 5, 46 | period => 10}, 47 | ChildSpec = #{id => sdp_pool, 48 | start => {pgo_pool, start_link, [default, PoolConfig]}}, 49 | {ok, {SupFlags, [ChildSpec]}}. 50 | 51 | %%==================================================================== 52 | %% Internal functions 53 | %%==================================================================== 54 | -------------------------------------------------------------------------------- /apps/service_discovery_http/src/sdh_socket.erl: -------------------------------------------------------------------------------- 1 | -module(sdh_socket). 2 | 3 | -behaviour(gen_server). 4 | 5 | -export([start_link/2]). 6 | 7 | -export([init/1, 8 | handle_call/3, 9 | handle_cast/2, 10 | handle_info/2, 11 | code_change/3, 12 | terminate/2]). 13 | 14 | %% public api 15 | 16 | start_link(ListenOpts, AcceptorOpts) -> 17 | gen_server:start_link({local, ?MODULE}, ?MODULE, [ListenOpts, AcceptorOpts], []). 18 | 19 | %% gen_server api 20 | 21 | init([ListenOpts, AcceptorOpts]) -> 22 | Port = maps:get(port, ListenOpts, 3000), 23 | IPAddress = maps:get(ip, ListenOpts, {0,0,0,0}), 24 | AcceptorPoolSize = maps:get(pool_size, AcceptorOpts, 10), 25 | SocketOpts = maps:get(socket_opts, ListenOpts, [{reuseaddr, true}, 26 | {nodelay, true}, 27 | {reuseaddr, true}, 28 | {backlog, 32768}, 29 | {keepalive, true}]), 30 | % Trapping exit so can close socket in terminate/2 31 | _ = process_flag(trap_exit, true), 32 | Opts = [{active, false}, {mode, binary}, {packet, raw}, {ip, IPAddress} | SocketOpts], 33 | case gen_tcp:listen(Port, Opts) of 34 | {ok, Socket} -> 35 | MRef = monitor(port, Socket), 36 | sdh_pool:accept_socket(Socket, AcceptorPoolSize), 37 | {ok, {Socket, MRef}}; 38 | {error, Reason} -> 39 | {stop, Reason} 40 | end. 41 | 42 | handle_call(Req, _, State) -> 43 | {stop, {bad_call, Req}, State}. 44 | 45 | handle_cast(Req, State) -> 46 | {stop, {bad_cast, Req}, State}. 47 | 48 | handle_info({'DOWN', MRef, port, Socket, Reason}, {Socket, MRef} = State) -> 49 | {stop, Reason, State}; 50 | handle_info(_, State) -> 51 | {noreply, State}. 52 | 53 | code_change(_, State, _) -> 54 | {ok, State}. 55 | 56 | terminate(_, {Socket, MRef}) -> 57 | % Socket may already be down but need to ensure it is closed to avoid 58 | % eaddrinuse error on restart 59 | case demonitor(MRef, [flush, info]) of 60 | true -> gen_tcp:close(Socket); 61 | false -> ok 62 | end. 63 | -------------------------------------------------------------------------------- /deployment/overlays/dev/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | namespace: service-discovery-dev 4 | nameSuffix: -dev 5 | images: 6 | - name: service_discovery 7 | newTag: main 8 | 9 | configMapGenerator: 10 | - envs: 11 | - dev.env 12 | name: configmap 13 | resources: 14 | - service_nodeport.yaml 15 | - ../../base 16 | - ../../postgres 17 | 18 | replacements: 19 | - source: 20 | version: v1 21 | kind: Service 22 | name: postgres 23 | targets: 24 | - select: 25 | kind: Deployment 26 | name: service-discovery 27 | fieldPaths: 28 | - spec.template.spec.containers.[name=service-discovery].env.[name=DB_HOST].value 29 | - select: 30 | kind: Job 31 | name: flyway 32 | fieldPaths: 33 | - spec.template.spec.containers.[name=flyway].env.[name=POSTGRES_SERVICE].value 34 | - select: 35 | kind: Deployment 36 | name: service-discovery 37 | fieldPaths: 38 | - spec.template.spec.initContainers.[name=flyway-validate].env.[name=POSTGRES_SERVICE].value 39 | - source: 40 | version: v1 41 | kind: Deployment 42 | name: postgres 43 | fieldPath: spec.template.spec.containers.[name=postgres].env.[name=POSTGRES_DB].value 44 | targets: 45 | - select: 46 | version: v1 47 | kind: Deployment 48 | name: service-discovery 49 | fieldPaths: 50 | - spec.template.spec.initContainers.[name=flyway-validate].env.[name=POSTGRES_DB].value 51 | - source: 52 | version: v1 53 | kind: Deployment 54 | name: postgres 55 | fieldPath: spec.template.spec.containers.[name=postgres].env.[name=POSTGRES_USER].value 56 | targets: 57 | - select: 58 | version: v1 59 | kind: Deployment 60 | name: service-discovery 61 | fieldPaths: 62 | - spec.template.spec.initContainers.[name=flyway-validate].env.[name=POSTGRES_USER].value 63 | - source: 64 | version: v1 65 | kind: Deployment 66 | name: postgres 67 | fieldPath: spec.template.spec.containers.[name=postgres].env.[name=POSTGRES_PASSWORD].value 68 | targets: 69 | - select: 70 | version: v1 71 | kind: Deployment 72 | name: service-discovery 73 | fieldPaths: 74 | - spec.template.spec.initContainers.[name=flyway-validate].env.[name=POSTGRES_PASSWORD].value 75 | labels: 76 | - includeSelectors: true 77 | pairs: 78 | overlay: dev 79 | -------------------------------------------------------------------------------- /rebar.config: -------------------------------------------------------------------------------- 1 | {erl_opts, [debug_info]}. 2 | 3 | {deps, [{erldns, {git, "https://github.com/tsloughter/erldns.git", {branch, "revamp"}}}, 4 | {dns, {git, "https://github.com/tsloughter/dns_erlang.git", {branch, "hex-deps"}}}, 5 | 6 | recon, 7 | eql, 8 | jsx, 9 | {uuid, "2.0.6", {pkg, uuid_erl}}, 10 | {elli, "~> 3.3.0"}, 11 | {grpcbox, "~> 0.16.0"}, 12 | {pgo, "~> 0.14.0"}]}. 13 | 14 | {relx, [{release, {service_discovery, {git, long}}, 15 | [service_discovery_postgres, 16 | service_discovery, 17 | service_discovery_http, 18 | service_discovery_grpc, 19 | recon]}, 20 | 21 | {sys_config, "./config/dev_sys.config"}, 22 | {vm_args, "./config/dev_vm.args"}, 23 | 24 | {dev_mode, true}, 25 | {include_erts, false}, 26 | 27 | {extended_start_script, true}, 28 | 29 | {overlay, [{copy, "apps/service_discovery_postgres/priv/migrations/*", "sql/"}]}]}. 30 | 31 | {shell, [{apps, [service_discovery_postgres, service_discovery, 32 | service_discovery_http, 33 | service_discovery_grpc, recon]}, 34 | {env_file, "deployment/base/default.env"}]}. 35 | %% {dist_node, [{name, 'sd@127.0.0.1'}]}. 36 | 37 | {profiles, [{prod, [{relx, [{sys_config_src, "./config/sys.config.src"}, 38 | {vm_args_src, "./config/vm.args.src"}, 39 | 40 | {dev_mode, false}, 41 | {include_src, false}, 42 | {include_erts, true}, 43 | {debug_info, strip}]}]}, 44 | {test, [{erl_opts, [nowarn_export_all]}, 45 | {deps, [docker_compose_cth]}]}] 46 | }. 47 | 48 | {project_plugins, [covertool, grpcbox_plugin]}. 49 | 50 | {cover_enabled, true}. 51 | {cover_export_enabled, true}. 52 | {covertool, [{coverdata_files, ["ct.coverdata"]}]}. 53 | 54 | 55 | {ct_opts, [{sys_config, "config/test.config"}, 56 | %% generate junit xml report from test results 57 | {ct_hooks, [cth_surefire]}]}. 58 | 59 | {overrides, [{override, base32, [{plugins, []}]}]}. 60 | 61 | {xref_checks,[undefined_function_calls, undefined_functions, %% locals_not_used, 62 | deprecated_function_calls, deprecated_functions]}. 63 | 64 | {dialyzer, [{warnings, [no_unknown]}]}. 65 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | service_discovery 2 | ===== 3 | 4 | This project contains applications for creating and updating services over HTTP and grpc that can be queried through DNS. The provided backing storage is through Postgres. 5 | 6 | **Disclaimer:** The purpose of creating this project was the need [Adopting Erlang](https://adoptingerlang.org/) had for a "real-world-esque" project to show the development and production patterns, structure and workflow we use. However, some decisions are made for the purpose of demonstration only, and not because we sat down and determined a certain strategy was optimal for some use case. The use of Postgres as the default storage backend is an example of this. This doesn't mean Postgres isn't a perfectly valid solution for a service discovery backend, and for many use cases even an optimal backend. The point is that it was chosen so that working with Postgres connections, queries and migrations from Erlang could be covered. 7 | 8 | ## Running Locally 9 | 10 | A Postgres instance can be started and have the migrations in the directory `sql/` run on it with `docker-compose`: 11 | 12 | ``` shell 13 | $ docker-compose up 14 | ``` 15 | 16 | This will bring up the database and run the migrations in the foreground, you can use `-d` to start them in the background. 17 | 18 | With the database running the `service_discovery` applications can be started and drop you into a shell with: 19 | 20 | ``` shell 21 | $ rebar3 shell 22 | ``` 23 | 24 | This will be running an HTTP interface on port `3000` and grpc on `8081`. The following `curl` commands will add a service named `webapp` with a single endpoint `127.0.0.1` and port named `http` with value `8000` : 25 | 26 | ``` shell 27 | $ curl -v -XPUT http://localhost:3000/service -d '{"name": "webapp", "attributes": {"attr-1": "value-1"}}' 28 | $ curl -v -XPUT http://localhost:3000/service/webapp/register -d '{"ip": "127.0.0.1", "tags": []}' 29 | $ curl -v -XPUT http://localhost:3000/service/webapp/ports -d '{"http": {"protocol": "tcp", "port": 8000}}' 30 | ``` 31 | 32 | `service_discovery` will also be running a DNS server on port `8053` and after adding the endpoint and port it can be queried with `dig` for the new service `webapp`: 33 | 34 | ``` shell 35 | $ dig -p8053 @127.0.0.1 _http._tcp.webapp.svc.cluster.local SRV 36 | ... 37 | _http._tcp.webapp.svc.cluster.local. 3600 IN SRV 1 1 8000 webapp.svc.cluster.local. 38 | ... 39 | $ dig -p8053 @127.0.0.1 webapp.svc.cluster.local A 40 | ... 41 | webapp.svc.cluster.local. 3600 IN A 127.0.0.1 42 | ... 43 | ``` 44 | 45 | 46 | ## Running in Kubernetes Locally 47 | 48 | ``` shell 49 | $ microk8s.enable registry 50 | $ microk8s.enable dns 51 | ``` 52 | `/etc/docker/daemon.json`: 53 | 54 | ``` shell 55 | { 56 | ... 57 | "insecure-registries" : ["localhost:32000"] 58 | ... 59 | } 60 | ``` 61 | 62 | ``` shell 63 | $ tilt up 64 | ``` 65 | -------------------------------------------------------------------------------- /apps/service_discovery_http/src/service_discovery_http_sup.erl: -------------------------------------------------------------------------------- 1 | %%%------------------------------------------------------------------- 2 | %% @doc service_discovery top level supervisor. 3 | %% @end 4 | %%%------------------------------------------------------------------- 5 | 6 | -module(service_discovery_http_sup). 7 | 8 | -behaviour(supervisor). 9 | 10 | -export([start_link/1]). 11 | 12 | -export([init/1]). 13 | 14 | -define(DEFAULT_ELLI_OPTS, #{callback => {sdh_handler, []}, 15 | accept_timeout => 10000, 16 | request_timeout => 60000, 17 | header_timeout => 10000, 18 | body_timeout => 30000, 19 | max_body_size => 1024000}). 20 | -define(DEFAULT_LISTEN_OPTS, #{port => 3000, 21 | socket_opts => [{reuseaddr, true}, 22 | {nodelay, true}, 23 | {reuseaddr, true}, 24 | {backlog, 32768}, 25 | {keepalive, true}]}). 26 | -define(DEFAULT_ACCEPTOR_OPTS, #{pool_size => 10}). 27 | 28 | start_link(Opts) -> 29 | ElliOpts = proplists:get_value(elli_opts, Opts, #{}), 30 | ListenOpts = proplists:get_value(listen_opts, Opts, #{}), 31 | AcceptorOpts = proplists:get_value(acceptor_opts, Opts, #{}), 32 | start_link(ElliOpts, ListenOpts, AcceptorOpts). 33 | 34 | start_link(ElliOpts, ListenOpts, AcceptorOpts) -> 35 | supervisor:start_link({local, ?MODULE}, ?MODULE, [maps:merge(?DEFAULT_ELLI_OPTS, ElliOpts), 36 | maps:merge(?DEFAULT_LISTEN_OPTS, ListenOpts), 37 | maps:merge(?DEFAULT_ACCEPTOR_OPTS, AcceptorOpts)]). 38 | 39 | init([ElliOpts, ListenOpts, AcceptorOpts]) -> 40 | RestartStrategy = #{strategy => rest_for_one, 41 | intensity => 5, 42 | period => 10}, 43 | Pool = #{id => sdh_pool, 44 | start => {sdh_pool, start_link, [ElliOpts, ListenOpts]}, 45 | restart => permanent, 46 | shutdown => 5000, 47 | type => worker, 48 | modules => [sdh_handler]}, 49 | Socket = #{id => sdh_socket, 50 | start => {sdh_socket, start_link, [ListenOpts, AcceptorOpts]}, 51 | restart => permanent, 52 | shutdown => 5000, 53 | type => worker, 54 | modules => [sdh_socket]}, 55 | 56 | %% NOTE: The order is important here. Socket is terminated first when the supervisor stops. 57 | %% This means the listen socket will be closed before the pool of acceptors will shutdown. 58 | %% We want the listen socket to stop listening before we start shutting down acceptors. 59 | {ok, {RestartStrategy, [Pool, Socket]}}. 60 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: CI 3 | 4 | on: 5 | pull_request: 6 | branches: 7 | - 'main' 8 | push: 9 | branches: 10 | - 'main' 11 | 12 | permissions: 13 | checks: write 14 | 15 | jobs: 16 | build: 17 | name: Test on OTP ${{ matrix.otp_version }} and ${{ matrix.os }} 18 | runs-on: ${{ matrix.os }} 19 | strategy: 20 | matrix: 21 | otp_version: ['26.0'] 22 | rebar3_version: ['3.22.1'] 23 | os: [ubuntu-20.04] 24 | env: 25 | OTP_VERSION: ${{ matrix.otp_version }} 26 | steps: 27 | - uses: actions/checkout@v4 28 | - name: Run Collector 29 | run: docker compose up -d 30 | - uses: erlef/setup-beam@v1 31 | with: 32 | otp-version: ${{ matrix.otp_version }} 33 | rebar3-version: ${{ matrix.rebar3_version }} 34 | version-type: 'strict' 35 | - uses: actions/cache@v3 36 | name: Cache 37 | with: 38 | path: | 39 | _build 40 | key: ${{ runner.os }}-build-${{ matrix.otp_version }}-${{ hashFiles(format('rebar.lock')) }}-1 41 | restore-keys: | 42 | ${{ runner.os }}-build-${{ matrix.otp_version }}-1- 43 | - name: Compile 44 | run: rebar3 compile 45 | - name: Common Test tests 46 | run: rebar3 ct --cover 47 | 48 | - name: Upload Test Report 49 | uses: actions/upload-artifact@v3 50 | if: always() # always run even if the previous step fails 51 | with: 52 | name: ct-test-results 53 | path: '**/_build/test/logs' 54 | 55 | - name: Covertool 56 | if: ${{ always() }} 57 | run: rebar3 covertool generate 58 | - uses: codecov/codecov-action@v3 59 | if: ${{ always() }} 60 | with: 61 | directory: ./_build/test/covertool/ 62 | files: service_discovery.covertool.xml,service_discovery_postgres.covertool.xml,service_discovery_grpc.covertool.xml,service_discovery_storage.covertool.xml,service_discovery_http.covertool.xml 63 | env_vars: OTP_VERSION 64 | 65 | - name: XRef 66 | run: rebar3 xref 67 | 68 | dialyzer: 69 | name: Dialyze on OTP ${{ matrix.otp_version }} and ${{ matrix.os }} 70 | runs-on: ${{ matrix.os }} 71 | strategy: 72 | matrix: 73 | otp_version: ['26.0'] 74 | rebar3_version: ['3.22.1'] 75 | os: [ubuntu-20.04] 76 | steps: 77 | - uses: actions/checkout@v4 78 | - uses: erlef/setup-beam@v1 79 | with: 80 | otp-version: ${{ matrix.otp_version }} 81 | rebar3-version: ${{ matrix.rebar3_version }} 82 | version-type: 'strict' 83 | - uses: actions/cache@v3 84 | name: Cache 85 | with: 86 | path: | 87 | _build 88 | key: ${{ runner.os }}-build-${{ matrix.otp_version }}-${{ hashFiles('rebar.lock') }}-1 89 | restore-keys: | 90 | ${{ runner.os }}-dialyzer-${{ matrix.otp_version }}-1- 91 | - name: Compile 92 | run: rebar3 compile 93 | - name: Dialyzer 94 | run: rebar3 dialyzer 95 | -------------------------------------------------------------------------------- /ci/old_build_images.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | # change working directory to top level of the project 6 | SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 7 | cd $SCRIPT_DIR/.. 8 | 9 | push=false 10 | target=all 11 | registry= 12 | 13 | usage() { 14 | echo "Usage: $0 [-p] [-t {builder|releaser|runner|plt|all}] [-r ]" 15 | echo 16 | echo " -p Enable pushing images to registry after build" 17 | echo " -t Target image to build (default: all)" 18 | echo " -r Registry to push images" 19 | } 20 | 21 | while getopts ":t:r:p" opt; do 22 | case ${opt} in 23 | p ) 24 | push=true 25 | ;; 26 | t ) 27 | target=$OPTARG 28 | ;; 29 | r ) 30 | registry=$OPTARG/ 31 | ;; 32 | : ) 33 | echo "Invalid Option: -$OPTARG requires an argument" 1>&2 34 | exit 1 35 | ;; 36 | \? ) 37 | usage 38 | exit 1 39 | ;; 40 | esac 41 | done 42 | shift $((OPTIND -1)) 43 | 44 | # must export this so experimental Dockerfile features work 45 | export DOCKER_BUILDKIT=1 46 | 47 | IMAGE=${registry}service_discovery 48 | BUILD_IMAGE=${IMAGE}:builder 49 | RELEASER_IMAGE=${IMAGE}:releaser 50 | PLT_IMAGE=${IMAGE}:plt 51 | 52 | CHKSUM_CMD=${CHKSUM_CMD:-cksum} 53 | 54 | CHKSUM=$(cat rebar.config rebar.lock | $CHKSUM_CMD | awk '{print $1}') 55 | GIT_REF=$(git rev-parse HEAD) # or with --short 56 | 57 | # takes the name of the image to build and the names of images to use as caches 58 | build_and_push() { 59 | local target=$1 60 | shift 61 | local image=$1 62 | local cache_images=("$@") 63 | 64 | # prepend --cache-from to each image to use as caches 65 | cache_images=( "${cache_images[@]/#/--cache-from=}" ) 66 | 67 | docker build --target $target --tag $image --cache-from=$image "${cache_images[@]}" \ 68 | -f Dockerfile . 69 | 70 | ! $push || docker push $image 71 | } 72 | 73 | case ${target} in 74 | all ) 75 | build_and_push plt "$PLT_IMAGE-$CHKSUM" "$BUILD_IMAGE-$CHKSUM" 76 | build_and_push runner "$IMAGE:$GIT_REF" "$BUILD_IMAGE-$CHKSUM" "$RELEASER_IMAGE-$GIT_REF" 77 | build_and_push releaser "$RELEASER_IMAGE-$GIT_REF" "$BUILD_IMAGE-$CHKSUM" 78 | build_and_push builder "$BUILD_IMAGE-$CHKSUM" 79 | ;; 80 | builder ) 81 | build_and_push builder "$BUILD_IMAGE-$CHKSUM" 82 | ;; 83 | releaser ) 84 | build_and_push releaser "$RELEASER_IMAGE-$GIT_REF" "$BUILD_IMAGE-$CHKSUM" 85 | build_and_push builder "$BUILD_IMAGE-$CHKSUM" 86 | ;; 87 | runner ) 88 | build_and_push runner "$IMAGE:$GIT_REF" "$BUILD_IMAGE-$CHKSUM" "$RELEASER_IMAGE-$GIT_REF" 89 | build_and_push releaser "$RELEASER_IMAGE-$GIT_REF" "$BUILD_IMAGE-$CHKSUM" 90 | build_and_push builder "$BUILD_IMAGE-$CHKSUM" 91 | ;; 92 | plt ) 93 | build_and_push plt "$PLT_IMAGE-$CHKSUM" "$BUILD_IMAGE-$CHKSUM" 94 | build_and_push builder "$BUILD_IMAGE-$CHKSUM" 95 | ;; 96 | * ) 97 | echo "Invalid image target: ${target}" 1>&2 98 | usage 99 | exit 1 100 | ;; 101 | esac 102 | 103 | echo "Finished building ${IMAGE}:${GIT_REF}" 104 | -------------------------------------------------------------------------------- /apps/service_discovery_grpc/src/sdg_service.erl: -------------------------------------------------------------------------------- 1 | -module(sdg_service). 2 | 3 | -behaviour(sd_discovery_service_bhvr). 4 | 5 | -export([get_service/2, 6 | create_service/2, 7 | list_services/2, 8 | add_named_ports/2, 9 | lookup_endpoints/2, 10 | register_endpoint/2]). 11 | 12 | get_service(Ctx, #{service_name := ServiceName}) -> 13 | case service_discovery:lookup(ServiceName) of 14 | {error, _} -> 15 | {ok, #{}, Ctx}; 16 | Service -> 17 | {ok, #{service => pb_from_service(Service)}, Ctx} 18 | end. 19 | 20 | create_service(Ctx, #{service := ServicePb}) -> 21 | service_discovery:create(service_from_pb(ServicePb)), 22 | {ok, #{}, Ctx}. 23 | 24 | list_services(Ctx, _Request) -> 25 | Services = service_discovery:list(), 26 | PbServices = pb_from_services(Services), 27 | {ok, #{services => PbServices}, Ctx}. 28 | 29 | add_named_ports(Ctx, #{service_name := ServiceName, 30 | named_ports := NamedPortsPb}) -> 31 | NamedPorts = named_ports_from_pb(NamedPortsPb), 32 | ok = service_discovery:add_named_ports(ServiceName, NamedPorts), 33 | {ok, #{}, Ctx}. 34 | 35 | lookup_endpoints(Ctx, #{service_name := ServiceName}) -> 36 | Endpoints = service_discovery:lookup_endpoints(ServiceName), 37 | PbEndpoints = pb_from_endpoints(ServiceName, Endpoints), 38 | {ok, #{endpoints => PbEndpoints}, Ctx}. 39 | 40 | register_endpoint(Ctx, #{service_name := ServiceName, 41 | endpoint := EndpointPb}) -> 42 | {ok, Endpoint} = endpoint_from_pb(ServiceName, EndpointPb), 43 | ok = service_discovery:register(ServiceName, Endpoint), 44 | {ok, #{}, Ctx}. 45 | 46 | %% 47 | 48 | service_from_pb(#{name := Name, 49 | attributes := Attributes}) -> 50 | #{name => Name, 51 | attributes => Attributes}. 52 | 53 | -spec named_ports_from_pb(map()) -> service_discovery:named_ports(). 54 | named_ports_from_pb(Map) -> 55 | maps:fold(fun(K, #{protocol := Protocol, 56 | port := Port}, Acc) -> 57 | Acc#{K => #{protocol => Protocol, 58 | port => Port}} 59 | end, #{}, Map). 60 | 61 | pb_from_services(Services) -> 62 | pb_from_services(Services, []). 63 | 64 | pb_from_services([], Acc) -> 65 | Acc; 66 | pb_from_services([#{name := Name, 67 | attributes := Attributes} | Rest], Acc) -> 68 | pb_from_services(Rest, [#{name => Name, 69 | attributes => Attributes} | Acc]). 70 | 71 | pb_from_service(#{name := Name, 72 | attributes := Attributes}) -> 73 | #{name => Name, 74 | attributes => Attributes}. 75 | 76 | pb_from_endpoints(ServiceName, Endpoints) -> 77 | pb_from_endpoints(ServiceName, Endpoints, []). 78 | 79 | pb_from_endpoints(_ServiceName, [], Acc) -> 80 | Acc; 81 | pb_from_endpoints(ServiceName, [#{ip := IP, 82 | tags := Tags} | Rest], Acc) -> 83 | pb_from_endpoints(ServiceName, Rest, [#{service_name => ServiceName, 84 | ip => inet:ntoa(IP), 85 | tags => Tags} | Acc]). 86 | 87 | endpoint_from_pb(ServiceName, #{ip := IPString, 88 | tags := Tags}) -> 89 | case inet:parse_address(binary_to_list(IPString)) of 90 | {ok, IP} -> 91 | {ok, #{service_name => ServiceName, 92 | ip => IP, 93 | tags => Tags}}; 94 | {error, einval}=Error -> 95 | Error 96 | end. 97 | -------------------------------------------------------------------------------- /apps/service_discovery_postgres/src/sdp_services_storage.erl: -------------------------------------------------------------------------------- 1 | -module(sdp_services_storage). 2 | 3 | -behaviour(service_discovery_storage). 4 | 5 | -export([create/1, 6 | register/2, 7 | add_named_ports/2, 8 | list/0, 9 | read/1, 10 | read_service_and_endpoints/1, 11 | read_endpoints/1]). 12 | 13 | -spec create(service_discovery:service()) -> binary() | {error, term()}. 14 | create(Service) -> 15 | case sdp_query:run(insert_service, service_to_row(Service)) of 16 | #{command := insert, 17 | num_rows := 1, 18 | rows := [{ServiceId}]} -> 19 | ServiceId; 20 | {error, {pgsql_error, #{code := <<"23505">>}}} -> 21 | {error, already_exists}; 22 | {error, _Reason}=Error -> 23 | Error 24 | end. 25 | 26 | -spec register(unicode:unicode_binary(), service_discovery:endpoint()) -> ok | {error, term()}. 27 | register(ServiceName, Endpoint) -> 28 | case sdp_query:run(insert_endpoint, endpoint_to_row(ServiceName, Endpoint)) of 29 | #{command := insert, 30 | num_rows := 1} -> 31 | ok; 32 | {error, _Reason}=Error -> 33 | Error 34 | end. 35 | 36 | -spec add_named_ports(unicode:unicode_binary(), service_discovery:named_ports()) -> ok | {error, term()}. 37 | add_named_ports(ServiceName, NamedPorts) -> 38 | case sdp_query:run(insert_named_ports, named_ports_to_rows(ServiceName, NamedPorts)) of 39 | #{command := insert, 40 | num_rows := _N} -> 41 | ok; 42 | {error, _Reason}=Error -> 43 | Error 44 | end. 45 | 46 | -spec read(unicode:unicode_binary()) -> service_discovery:service() | {error, term()}. 47 | read(ServiceName) -> 48 | case sdp_query:run(select_service, [ServiceName]) of 49 | #{rows := [Row]} -> 50 | service_from_row(Row); 51 | #{rows := []} -> 52 | {error, not_found}; 53 | {error, Reason} -> 54 | {error, Reason} 55 | end. 56 | 57 | -spec list() -> [service_discovery:service()]. 58 | list() -> 59 | case sdp_query:run(select_all_services, []) of 60 | #{rows := Rows} -> 61 | [base_service_from_row(Row) || Row <- Rows]; 62 | {error, Reason} -> 63 | {error, Reason} 64 | end. 65 | 66 | -spec read_service_and_endpoints(unicode:unicode_binary()) -> {service_discovery:service(), 67 | [service_discovery:endpoint()]} | 68 | {error, term()}. 69 | read_service_and_endpoints(ServiceName) -> 70 | case sdp_query:run(select_endpoints, [ServiceName]) of 71 | #{rows := Rows} -> 72 | [endpoint_from_row(ServiceName, Row) || Row <- Rows]; 73 | {error, Reason} -> 74 | {error, Reason} 75 | end. 76 | 77 | -spec read_endpoints(unicode:unicode_binary()) -> [service_discovery:endpoint()] | {error, term()}. 78 | read_endpoints(ServiceName) -> 79 | case sdp_query:run(select_endpoints, [ServiceName]) of 80 | #{rows := Rows} -> 81 | [endpoint_from_row(ServiceName, Row) || Row <- Rows]; 82 | {error, Reason} -> 83 | {error, Reason} 84 | end. 85 | 86 | %% 87 | 88 | base_service_from_row({Name, Attributes}) -> 89 | #{name => Name, 90 | attributes => Attributes}. 91 | 92 | service_from_row({Name, Attributes, NamedPorts, Endpoints}) -> 93 | #{name => Name, 94 | attributes => Attributes, 95 | named_ports => named_ports_from_rows(NamedPorts), 96 | endpoints => [endpoint_from_row(Name, Endpoint) || Endpoint <- Endpoints]}. 97 | 98 | named_ports_to_rows(ServiceName, NamePorts) -> 99 | [ServiceName, maps:fold(fun(PortName, #{protocol := Protocol, 100 | port := Port}, Acc) -> 101 | [{<<>>, PortName, Protocol, Port} | Acc] 102 | end, [], NamePorts)]. 103 | 104 | named_ports_from_rows(NamedPorts) -> 105 | named_ports_from_rows(NamedPorts, #{}). 106 | 107 | named_ports_from_rows([], Acc) -> 108 | Acc; 109 | named_ports_from_rows([{_, Name, Protocol, Port} | H], Acc) -> 110 | named_ports_from_rows(H, Acc#{Name => #{protocol => Protocol, 111 | port => Port}}). 112 | 113 | endpoint_from_row(ServiceName, {IP, Tags}) -> 114 | #{service_name => ServiceName, 115 | ip => IP, 116 | tags => Tags}; 117 | endpoint_from_row(ServiceName, {_, IP, Tags, _, _}) -> 118 | #{service_name => ServiceName, 119 | ip => IP, 120 | tags => Tags}. 121 | 122 | service_to_row(#{name := Name, 123 | attributes := Attributes}) -> 124 | [Name, Attributes]. 125 | 126 | endpoint_to_row(ServiceName, #{ip := IP, 127 | tags := Tags}) -> 128 | [ServiceName, IP, Tags]. 129 | -------------------------------------------------------------------------------- /apps/service_discovery_postgres/src/sdp_erldns_storage.erl: -------------------------------------------------------------------------------- 1 | -module(sdp_erldns_storage). 2 | 3 | -include_lib("erldns/include/erldns.hrl"). 4 | -include_lib("kernel/include/logger.hrl"). 5 | -include_lib("dns/include/dns.hrl"). 6 | 7 | %% API 8 | -export([create/1, 9 | insert/2, 10 | delete_table/1, 11 | delete/2, 12 | backup_table/1, 13 | backup_tables/0, 14 | select/2, 15 | select/3, 16 | foldl/3, 17 | empty_table/1, 18 | list_table/1]). 19 | 20 | -define(SOA(Key), [#dns_rr{name = Key, 21 | type = ?DNS_TYPE_SOA, 22 | ttl = 3600, 23 | data = #dns_rrdata_soa{mname = <<"ns1.", Key/binary>>, 24 | rname = <<"admin.", Key/binary>>, 25 | serial = 2013022001, 26 | refresh = 86400, 27 | retry = 7200, 28 | expire = 604800, 29 | minimum = 300}}]). 30 | 31 | -spec create(atom()) -> ok. 32 | create(schema) -> 33 | ok; 34 | create(zones) -> 35 | ok; 36 | create(authorities) -> 37 | ok. 38 | 39 | -spec insert(atom(), any()) -> any(). 40 | insert(_, _) -> 41 | ok. 42 | 43 | -spec delete_table(atom()) -> ok | {aborted, any()}. 44 | delete_table(_Table) -> 45 | ok. 46 | 47 | -spec delete(Table :: atom(), Key :: term()) -> ok | any(). 48 | delete(_Table, _Key)-> 49 | ok. 50 | 51 | -spec backup_table(atom()) -> ok | {error, Reason :: term()}. 52 | backup_table(_Table)-> 53 | ok. 54 | 55 | -spec backup_tables() -> ok | {error, Reason :: term()}. 56 | backup_tables()-> 57 | ok. 58 | 59 | -spec select(Table :: atom(), Key :: term()) -> [tuple()] | {error, not_implemented}. 60 | select(zones, Key)-> 61 | case string:split(Key, ".", all) -- [<<"svc">>, <<"cluster">>, <<"local">>] of 62 | [Service] -> 63 | case sdp_services_storage:read(Service) of 64 | {error, _}-> 65 | []; 66 | #{named_ports := NamedPorts, 67 | endpoints := Endpoints} -> 68 | Version = <<>>, 69 | Authorities = ?SOA(Key), 70 | SrvRecords = named_ports_to_srv_records(Key, NamedPorts), 71 | Records = SrvRecords ++ endpoints_to_a_records(Key, Endpoints), 72 | [{Key, #zone{name=Key, 73 | version=Version, 74 | authority=Authorities, 75 | record_count = length(Records), 76 | records=Records, 77 | records_by_name=build_named_index(Records), 78 | keysets=[]}}] 79 | end; 80 | _ -> 81 | [] 82 | end; 83 | select(_Table, _Key)-> 84 | {error, not_implemented}. 85 | 86 | -spec(build_named_index([#dns_rr{}]) -> #{binary() => [#dns_rr{}]}). 87 | build_named_index(Records) -> 88 | Idx0 = lists:foldl(fun (R, Idx) -> 89 | Name = erldns:normalize_name(R#dns_rr.name), 90 | maps:update_with(Name, fun (RR) -> [R | RR] end, [R], Idx) 91 | end, #{}, Records), 92 | maps:map(fun (_K, V) -> lists:reverse(V) end, Idx0). 93 | 94 | -spec select(atom(), list(), infinite | integer()) -> [tuple()] | {error, not_implemented}. 95 | select(_Table, _MatchSpec, _Limit) -> 96 | {error, not_implemented}. 97 | 98 | -spec foldl(fun(), list(), atom()) -> Acc :: term() | {error, Reason :: term()}. 99 | foldl(_Iterator, _Acc, _Table) -> 100 | {error, not_implemented}. 101 | 102 | -spec empty_table(atom()) -> ok | {aborted, term()}. 103 | empty_table(_Table) -> 104 | {aborted, not_implemented}. 105 | 106 | -spec list_table(atom()) -> [] | [#zone{}] | [#authorities{}] | [tuple()] | 107 | {error, doesnt_exist} | {error, not_implemented}. 108 | list_table(zones) -> 109 | {error, not_implemented}; 110 | list_table(authorities) -> 111 | {error, not_implemented}; 112 | list_table(_Name) -> 113 | {error, doesnt_exist}. 114 | 115 | %% 116 | 117 | named_ports_to_srv_records(Key, NamedPorts) -> 118 | maps:fold(fun(PortName, #{protocol := Protocol, 119 | port := Port}, Acc) -> 120 | [#dns_rr{name = <<"_", PortName/binary, "._", Protocol/binary, ".", Key/binary>>, 121 | type = ?DNS_TYPE_SRV, 122 | ttl = 3600, 123 | data = #dns_rrdata_srv{port=Port, 124 | target = Key, 125 | priority=1, 126 | weight=1}} | Acc] 127 | end, [], NamedPorts). 128 | 129 | endpoints_to_a_records(Key, Endpoints) -> 130 | [#dns_rr{ 131 | name = Key, 132 | type = ?DNS_TYPE_A, 133 | ttl = 3600, 134 | data = #dns_rrdata_a{ip = IP} 135 | } || #{ip := IP} <- Endpoints]. 136 | 137 | -------------------------------------------------------------------------------- /rebar.lock: -------------------------------------------------------------------------------- 1 | {"1.2.0", 2 | [{<<"acceptor_pool">>,{pkg,<<"acceptor_pool">>,<<"1.0.0">>},1}, 3 | {<<"backoff">>,{pkg,<<"backoff">>,<<"1.1.6">>},1}, 4 | {<<"base32">>,{pkg,<<"base32">>,<<"0.1.0">>},1}, 5 | {<<"chatterbox">>,{pkg,<<"ts_chatterbox">>,<<"0.13.0">>},1}, 6 | {<<"counters">>,{pkg,<<"counters">>,<<"0.2.1">>},2}, 7 | {<<"ctx">>,{pkg,<<"ctx">>,<<"0.6.0">>},1}, 8 | {<<"dns">>, 9 | {git,"https://github.com/tsloughter/dns_erlang.git", 10 | {ref,"86d8d1be7323a3f0dd9bb6ae44f782eceeca0b06"}}, 11 | 0}, 12 | {<<"elli">>,{pkg,<<"elli">>,<<"3.3.0">>},0}, 13 | {<<"eql">>,{pkg,<<"eql">>,<<"0.2.0">>},0}, 14 | {<<"erldns">>, 15 | {git,"https://github.com/tsloughter/erldns.git", 16 | {ref,"cd8606bbf36518bbf31f805c74f8e87b96dce5ad"}}, 17 | 0}, 18 | {<<"gproc">>,{pkg,<<"gproc">>,<<"0.8.0">>},1}, 19 | {<<"grpcbox">>,{pkg,<<"grpcbox">>,<<"0.16.0">>},0}, 20 | {<<"hpack">>,{pkg,<<"hpack_erl">>,<<"0.2.3">>},2}, 21 | {<<"iso8601">>,{pkg,<<"iso8601">>,<<"1.3.1">>},1}, 22 | {<<"jsx">>,{pkg,<<"jsx">>,<<"3.1.0">>},0}, 23 | {<<"opencensus">>,{pkg,<<"opencensus">>,<<"0.9.2">>},1}, 24 | {<<"opentelemetry_api">>,{pkg,<<"opentelemetry_api">>,<<"1.2.2">>},1}, 25 | {<<"opentelemetry_semantic_conventions">>, 26 | {pkg,<<"opentelemetry_semantic_conventions">>,<<"0.2.0">>}, 27 | 2}, 28 | {<<"pg_types">>,{pkg,<<"pg_types">>,<<"0.4.0">>},1}, 29 | {<<"pgo">>,{pkg,<<"pgo">>,<<"0.14.0">>},0}, 30 | {<<"quickrand">>,{pkg,<<"quickrand">>,<<"2.0.6">>},1}, 31 | {<<"recon">>,{pkg,<<"recon">>,<<"2.5.4">>},0}, 32 | {<<"telemetry">>,{pkg,<<"telemetry">>,<<"0.4.0">>},1}, 33 | {<<"uuid">>,{pkg,<<"uuid_erl">>,<<"2.0.6">>},0}, 34 | {<<"wts">>,{pkg,<<"wts">>,<<"0.4.0">>},2}]}. 35 | [ 36 | {pkg_hash,[ 37 | {<<"acceptor_pool">>, <<"43C20D2ACAE35F0C2BCD64F9D2BDE267E459F0F3FD23DAB26485BF518C281B21">>}, 38 | {<<"backoff">>, <<"83B72ED2108BA1EE8F7D1C22E0B4A00CFE3593A67DBC792799E8CCE9F42F796B">>}, 39 | {<<"base32">>, <<"044F6DC95709727CA2176F3E97A41DDAA76B5BC690D3536908618C0CB32616A2">>}, 40 | {<<"chatterbox">>, <<"6F059D97BCAA758B8EA6FFFE2B3B81362BD06B639D3EA2BB088335511D691EBF">>}, 41 | {<<"counters">>, <<"AA3D97E88F92573488987193D0F48EFCE0F3B2CD1443BF4EE760BC7F99322F0C">>}, 42 | {<<"ctx">>, <<"8FF88B70E6400C4DF90142E7F130625B82086077A45364A78D208ED3ED53C7FE">>}, 43 | {<<"elli">>, <<"089218762A7FF3D20AE81C8E911BD0F73EE4EE0ED85454226D1FC6B4FFF3B4F6">>}, 44 | {<<"eql">>, <<"598ABC19A1CF6AFB8EF89FFEA869F43BAEBB1CEC3260DD5065112FEE7D8CE3E2">>}, 45 | {<<"gproc">>, <<"CEA02C578589C61E5341FCE149EA36CCEF236CC2ECAC8691FBA408E7EA77EC2F">>}, 46 | {<<"grpcbox">>, <<"B83F37C62D6EECA347B77F9B1EC7E9F62231690CDFEB3A31BE07CD4002BA9C82">>}, 47 | {<<"hpack">>, <<"17670F83FF984AE6CD74B1C456EDDE906D27FF013740EE4D9EFAA4F1BF999633">>}, 48 | {<<"iso8601">>, <<"D1CEE73F56D71C35590C6B2DB2074873BF410BABAAB768F6EA566366D8CA4810">>}, 49 | {<<"jsx">>, <<"D12516BAA0BB23A59BB35DCCAF02A1BD08243FCBB9EFE24F2D9D056CCFF71268">>}, 50 | {<<"opencensus">>, <<"AB36B0C4E4500B976180BD088CEA7520D345711A72DF2D7188E2D7B9573A8728">>}, 51 | {<<"opentelemetry_api">>, <<"693F47B0D8C76DA2095FE858204CFD6350C27FE85D00E4B763DEECC9588CF27A">>}, 52 | {<<"opentelemetry_semantic_conventions">>, <<"B67FE459C2938FCAB341CB0951C44860C62347C005ACE1B50F8402576F241435">>}, 53 | {<<"pg_types">>, <<"3CE365C92903C5BB59C0D56382D842C8C610C1B6F165E20C4B652C96FA7E9C14">>}, 54 | {<<"pgo">>, <<"F53711D103D7565DB6FC6061FCF4FF1007AB39892439BE1BB02D9F686D7E6663">>}, 55 | {<<"quickrand">>, <<"37E49398D614534F2861633F8E1155828676DF31ED90872616E4A526E6B9CF38">>}, 56 | {<<"recon">>, <<"05DD52A119EE4059FA9DAA1AB7CE81BC7A8161A2F12E9D42E9D551FFD2BA901C">>}, 57 | {<<"telemetry">>, <<"8339BEE3FA8B91CB84D14C2935F8ECF399CCD87301AD6DA6B71C09553834B2AB">>}, 58 | {<<"uuid">>, <<"8767AAE0D93A0EFD062B5B30BB21188E121721C683200E164445065C08C2100A">>}, 59 | {<<"wts">>, <<"62D9DC400AD29F0D233F0665B9C75C8F8EB0A8AF75EEC921056BA4A73B0605A2">>}]}, 60 | {pkg_hash_ext,[ 61 | {<<"acceptor_pool">>, <<"0CBCD83FDC8B9AD2EEE2067EF8B91A14858A5883CB7CD800E6FCD5803E158788">>}, 62 | {<<"backoff">>, <<"CF0CFFF8995FB20562F822E5CC47D8CCF664C5ECDC26A684CBE85C225F9D7C39">>}, 63 | {<<"base32">>, <<"10A73951D857D8CB1ECEEA8EB96C6941F6A76E105947AD09C2B73977DEE07638">>}, 64 | {<<"chatterbox">>, <<"B93D19104D86AF0B3F2566C4CBA2A57D2E06D103728246BA1AC6C3C0FF010AA7">>}, 65 | {<<"counters">>, <<"A020C714992F7DB89178D27E1F39909E5D77DA3B80DAA4D6015877ED0C94B8AB">>}, 66 | {<<"ctx">>, <<"A14ED2D1B67723DBEBBE423B28D7615EB0BDCBA6FF28F2D1F1B0A7E1D4AA5FC2">>}, 67 | {<<"elli">>, <<"698B13B33D05661DB9FE7EFCBA41B84825A379CCE86E486CF6AFF9285BE0CCF8">>}, 68 | {<<"eql">>, <<"513BE6B36EE86E8292B2B7475C257ABB66CED5AAD40CBF7AD21E233D0A3BF51D">>}, 69 | {<<"gproc">>, <<"580ADAFA56463B75263EF5A5DF4C86AF321F68694E7786CB057FD805D1E2A7DE">>}, 70 | {<<"grpcbox">>, <<"294DF743AE20A7E030889F00644001370A4F7CE0121F3BBDAF13CF3169C62913">>}, 71 | {<<"hpack">>, <<"06F580167C4B8B8A6429040DF36CC93BBA6D571FAEAEC1B28816523379CBB23A">>}, 72 | {<<"iso8601">>, <<"A8B00594F4309A41D17BA4AEAB2B94DFE1F4BE99F263BC1F46DAC9002CE99A29">>}, 73 | {<<"jsx">>, <<"0C5CC8FDC11B53CC25CF65AC6705AD39E54ECC56D1C22E4ADB8F5A53FB9427F3">>}, 74 | {<<"opencensus">>, <<"B453A796C2F6145F198AFB4B24D61EB1617FB13053AD70E66CFB3148308D743E">>}, 75 | {<<"opentelemetry_api">>, <<"DC77B9A00F137A858E60A852F14007BB66EDA1FFBEB6C05D5FE6C9E678B05E9D">>}, 76 | {<<"opentelemetry_semantic_conventions">>, <<"D61FA1F5639EE8668D74B527E6806E0503EFC55A42DB7B5F39939D84C07D6895">>}, 77 | {<<"pg_types">>, <<"B02EFA785CAECECF9702C681C80A9CA12A39F9161A846CE17B01FB20AEEED7EB">>}, 78 | {<<"pgo">>, <<"71016C22599936E042DC0012EE4589D24C71427D266292F775EBF201D97DF9C9">>}, 79 | {<<"quickrand">>, <<"86A03C7FC96B9C6B9FA6BEF5FCEB773E359C772EE3814BE60B8EB44B54F99140">>}, 80 | {<<"recon">>, <<"E9AB01AC7FC8572E41EB59385EFEB3FB0FF5BF02103816535BACAEDF327D0263">>}, 81 | {<<"telemetry">>, <<"E9E3CACFD37C1531C0CA70CA7C0C30CE2DBB02998A4F7719DE180FE63F8D41E4">>}, 82 | {<<"uuid">>, <<"1D54D5DE4CC66317D882F62347A21655601E84CCCE913E80AADE202CDB3A8C65">>}, 83 | {<<"wts">>, <<"711BB675DE2CE2B3EBAB80A613AC93B994F74DF44AF4CFF7970DC9EEBE724869">>}]} 84 | ]. 85 | -------------------------------------------------------------------------------- /apps/service_discovery_http/src/sdh_handler.erl: -------------------------------------------------------------------------------- 1 | -module(sdh_handler). 2 | 3 | -behaviour(elli_handler). 4 | 5 | -export([handle/2, 6 | handle_event/3]). 7 | 8 | -include_lib("elli/include/elli.hrl"). 9 | 10 | -define(CONTENT_TYPE_JSON, {<<"Content-Type">>, <<"application/json">>}). 11 | 12 | handle(Req, _Args) -> 13 | handle(Req#req.method, elli_request:path(Req), Req). 14 | 15 | handle('GET', [<<"healthz">>], _Req) -> 16 | {ok, [], <<>>}; 17 | handle('GET', [<<"ready">>], _Req) -> 18 | case service_discovery_http_app:is_shutting_down() of 19 | true -> 20 | {503, [], <<>>}; 21 | _ -> 22 | {ok, [], <<>>} 23 | end; 24 | 25 | handle('GET', [<<"services">>], Req) -> 26 | Services = service_discovery:list(), 27 | ServicesJson = json_encode_services(is_pretty(Req), Services), 28 | {ok, [?CONTENT_TYPE_JSON], ServicesJson}; 29 | 30 | handle('GET', [<<"service">>, ServiceName], Req) -> 31 | Service = service_discovery:lookup(ServiceName), 32 | ServiceJson = json_encode_service(is_pretty(Req), Service), 33 | {ok, [?CONTENT_TYPE_JSON], ServiceJson}; 34 | handle('PUT', [<<"service">>], Req) -> 35 | Body = elli_request:body(Req), 36 | DecodedBody = jsx:decode(Body, [return_maps]), 37 | case create_service(DecodedBody) of 38 | {error, Reason} -> 39 | {400, [], io_lib:format("error: ~p", [Reason])}; 40 | ServiceId -> 41 | {ok, [], uuid:uuid_to_string(ServiceId, binary_standard)} 42 | end; 43 | 44 | handle('GET', [<<"service">>, ServiceName, <<"endpoints">>], Req) -> 45 | Endpoints = service_discovery:lookup_endpoints(ServiceName), 46 | EndpointsJson = json_encode_endpoints(is_pretty(Req), Endpoints), 47 | {ok, [?CONTENT_TYPE_JSON], EndpointsJson}; 48 | handle('PUT', [<<"service">>, ServiceName, <<"ports">>], Req) -> 49 | Body = elli_request:body(Req), 50 | DecodedBody = jsx:decode(Body, [return_maps]), 51 | case add_named_ports(ServiceName, DecodedBody) of 52 | ok -> 53 | {ok, [], <<>>}; 54 | {error, Reason} -> 55 | {400, [], io_lib:format("error: ~p", [Reason])} 56 | end; 57 | handle('PUT', [<<"service">>, ServiceName, <<"register">>], Req) -> 58 | Body = elli_request:body(Req), 59 | DecodedBody = jsx:decode(Body, [return_maps]), 60 | case register_service(ServiceName, DecodedBody) of 61 | ok -> 62 | {ok, [], <<>>}; 63 | {error, Reason} -> 64 | {400, [], io_lib:format("error: ~p", [Reason])} 65 | end; 66 | handle('PUT', [<<"service">>, <<"deregister">>, _ServiceId], _Req) -> 67 | {ok, [], <<>>}; 68 | 69 | handle(_, _, _Req) -> 70 | {404, [], <<"Not Found">>}. 71 | 72 | handle_event(_Event, _Data, _Args) -> 73 | ok. 74 | 75 | %% 76 | 77 | create_service(ServiceJson) -> 78 | case service_from_json(ServiceJson) of 79 | {error, _}=Error -> 80 | Error; 81 | Service -> 82 | service_discovery:create(Service) 83 | end. 84 | 85 | -spec json_encode_service(boolean(), service_discovery:service()) -> binary(). 86 | json_encode_service(Pretty, Service=#{name := _Name, 87 | attributes := _Attributes, 88 | named_ports := _NamedPorts}) -> 89 | json_encode(Pretty, Service). 90 | 91 | -spec json_encode_services(boolean(), [service_discovery:service()]) -> binary(). 92 | json_encode_services(Pretty, Services) -> 93 | json_encode(Pretty, json_encode_services_(Services, [])). 94 | 95 | json_encode_services_([], Acc) -> 96 | Acc; 97 | json_encode_services_([#{name := _ServiceName, 98 | attributes := _Attributes}=Service | Rest], Acc) -> 99 | json_encode_services_(Rest, [Service | Acc]). 100 | 101 | -spec json_encode_endpoints(boolean(), [service_discovery:endpoints()]) -> binary(). 102 | json_encode_endpoints(Pretty, Endpoints) -> 103 | json_encode(Pretty, json_encode_endpoints_(Endpoints, [])). 104 | 105 | -spec json_encode_endpoints_([service_discovery:endpoint()], [map()]) -> [map()]. 106 | json_encode_endpoints_([], Acc) -> 107 | Acc; 108 | json_encode_endpoints_([#{service_name := ServiceName, 109 | ip := IP, 110 | tags := Tags} | Rest], Acc) -> 111 | case inet:ntoa(IP) of 112 | {error, einval} -> 113 | %% add log 114 | json_encode_endpoints_(Rest, Acc); 115 | IPString -> 116 | json_encode_endpoints_(Rest, [#{service_name => ServiceName, 117 | ip => list_to_binary(IPString), 118 | tags => Tags} | Acc]) 119 | end. 120 | 121 | 122 | json_encode(true, ToEncode) -> 123 | jsx:prettify(jsx:encode(ToEncode)); 124 | json_encode(_, ToEncode) -> 125 | jsx:encode(ToEncode). 126 | 127 | is_pretty(Req) -> 128 | case proplists:get_value(<<"pretty">>, elli_request:get_args(Req)) of 129 | Pretty when Pretty =:= <<"true">> ; Pretty =:= true -> 130 | true; 131 | _ -> 132 | false 133 | end. 134 | 135 | %% decoded json to service or endpoint maps 136 | 137 | service_from_json(#{<<"name">> := Name, 138 | <<"attributes">> := Attributes, 139 | <<"named_ports">> := NamedPorts}) -> 140 | #{name => Name, 141 | attributes => Attributes, 142 | named_ports => named_ports_from_json(NamedPorts)}; 143 | service_from_json(#{<<"name">> := Name, 144 | <<"attributes">> := Attributes}) -> 145 | #{name => Name, 146 | attributes => Attributes, 147 | named_ports => #{}}; 148 | service_from_json(_) -> 149 | {error, bad_service_json}. 150 | 151 | -spec named_ports_from_json(map()) -> service_discovery:named_ports(). 152 | named_ports_from_json(Map) -> 153 | maps:fold(fun(K, #{<<"protocol">> := Protocol, 154 | <<"port">> := Port}, Acc) -> 155 | Acc#{K => #{protocol => Protocol, 156 | port => Port}} 157 | end, #{}, Map). 158 | 159 | add_named_ports(ServiceName, Json) -> 160 | service_discovery:add_named_ports(ServiceName, named_ports_from_json(Json)). 161 | 162 | register_service(ServiceName, Json) -> 163 | case endpoint_from_json(ServiceName, Json) of 164 | {ok, Endpoint} -> 165 | service_discovery:register(ServiceName, Endpoint); 166 | {error, _Reason}=Error -> 167 | Error 168 | end. 169 | 170 | -spec endpoint_from_json(unicode:unicode_binary(), map()) -> {ok, service_discovery:endpoint()} | 171 | {error, term()}. 172 | endpoint_from_json(ServiceName, #{<<"ip">> := IPString, 173 | <<"tags">> := Tags}) -> 174 | case inet:parse_address(binary_to_list(IPString)) of 175 | {ok, IP} -> 176 | {ok, #{service_name => ServiceName, 177 | ip => IP, 178 | tags => Tags}}; 179 | {error, einval}=Error -> 180 | Error 181 | end; 182 | endpoint_from_json(_, _) -> 183 | {error, bad_endpoint_json}. 184 | 185 | -------------------------------------------------------------------------------- /apps/service_discovery_grpc/src/sd_discovery_service_client.erl: -------------------------------------------------------------------------------- 1 | %%%------------------------------------------------------------------- 2 | %% @doc Client module for grpc service sd.DiscoveryService. 3 | %% @end 4 | %%%------------------------------------------------------------------- 5 | 6 | %% this module was generated on 2019-07-05T14:33:23+00:00 and should not be modified manually 7 | 8 | -module(sd_discovery_service_client). 9 | 10 | -compile(export_all). 11 | -compile(nowarn_export_all). 12 | 13 | -include_lib("grpcbox/include/grpcbox.hrl"). 14 | 15 | -define(is_ctx(Ctx), is_tuple(Ctx) andalso element(1, Ctx) =:= ctx). 16 | 17 | -define(SERVICE, 'sd.DiscoveryService'). 18 | -define(PROTO_MODULE, 'sdg_discovery_pb'). 19 | -define(MARSHAL_FUN(T), fun(I) -> ?PROTO_MODULE:encode_msg(I, T) end). 20 | -define(UNMARSHAL_FUN(T), fun(I) -> ?PROTO_MODULE:decode_msg(I, T) end). 21 | -define(DEF(Input, Output, MessageType), #grpcbox_def{service=?SERVICE, 22 | message_type=MessageType, 23 | marshal_fun=?MARSHAL_FUN(Input), 24 | unmarshal_fun=?UNMARSHAL_FUN(Output)}). 25 | 26 | %% @doc Unary RPC 27 | -spec get_service(sdg_discovery_pb:get_service_request()) -> 28 | {ok, sdg_discovery_pb:get_service_response(), grpcbox:metadata()} | grpcbox_stream:grpc_error_response(). 29 | get_service(Input) -> 30 | get_service(ctx:new(), Input, #{}). 31 | 32 | -spec get_service(ctx:t() | sdg_discovery_pb:get_service_request(), sdg_discovery_pb:get_service_request() | grpcbox_client:options()) -> 33 | {ok, sdg_discovery_pb:get_service_response(), grpcbox:metadata()} | grpcbox_stream:grpc_error_response(). 34 | get_service(Ctx, Input) when ?is_ctx(Ctx) -> 35 | get_service(Ctx, Input, #{}); 36 | get_service(Input, Options) -> 37 | get_service(ctx:new(), Input, Options). 38 | 39 | -spec get_service(ctx:t(), sdg_discovery_pb:get_service_request(), grpcbox_client:options()) -> 40 | {ok, sdg_discovery_pb:get_service_response(), grpcbox:metadata()} | grpcbox_stream:grpc_error_response(). 41 | get_service(Ctx, Input, Options) -> 42 | grpcbox_client:unary(Ctx, <<"/sd.DiscoveryService/GetService">>, Input, ?DEF(get_service_request, get_service_response, <<"sd.GetServiceRequest">>), Options). 43 | 44 | %% @doc Unary RPC 45 | -spec create_service(sdg_discovery_pb:create_service_request()) -> 46 | {ok, sdg_discovery_pb:create_service_response(), grpcbox:metadata()} | grpcbox_stream:grpc_error_response(). 47 | create_service(Input) -> 48 | create_service(ctx:new(), Input, #{}). 49 | 50 | -spec create_service(ctx:t() | sdg_discovery_pb:create_service_request(), sdg_discovery_pb:create_service_request() | grpcbox_client:options()) -> 51 | {ok, sdg_discovery_pb:create_service_response(), grpcbox:metadata()} | grpcbox_stream:grpc_error_response(). 52 | create_service(Ctx, Input) when ?is_ctx(Ctx) -> 53 | create_service(Ctx, Input, #{}); 54 | create_service(Input, Options) -> 55 | create_service(ctx:new(), Input, Options). 56 | 57 | -spec create_service(ctx:t(), sdg_discovery_pb:create_service_request(), grpcbox_client:options()) -> 58 | {ok, sdg_discovery_pb:create_service_response(), grpcbox:metadata()} | grpcbox_stream:grpc_error_response(). 59 | create_service(Ctx, Input, Options) -> 60 | grpcbox_client:unary(Ctx, <<"/sd.DiscoveryService/CreateService">>, Input, ?DEF(create_service_request, create_service_response, <<"sd.CreateServiceRequest">>), Options). 61 | 62 | %% @doc Unary RPC 63 | -spec list_services(sdg_discovery_pb:list_services_request()) -> 64 | {ok, sdg_discovery_pb:list_services_response(), grpcbox:metadata()} | grpcbox_stream:grpc_error_response(). 65 | list_services(Input) -> 66 | list_services(ctx:new(), Input, #{}). 67 | 68 | -spec list_services(ctx:t() | sdg_discovery_pb:list_services_request(), sdg_discovery_pb:list_services_request() | grpcbox_client:options()) -> 69 | {ok, sdg_discovery_pb:list_services_response(), grpcbox:metadata()} | grpcbox_stream:grpc_error_response(). 70 | list_services(Ctx, Input) when ?is_ctx(Ctx) -> 71 | list_services(Ctx, Input, #{}); 72 | list_services(Input, Options) -> 73 | list_services(ctx:new(), Input, Options). 74 | 75 | -spec list_services(ctx:t(), sdg_discovery_pb:list_services_request(), grpcbox_client:options()) -> 76 | {ok, sdg_discovery_pb:list_services_response(), grpcbox:metadata()} | grpcbox_stream:grpc_error_response(). 77 | list_services(Ctx, Input, Options) -> 78 | grpcbox_client:unary(Ctx, <<"/sd.DiscoveryService/ListServices">>, Input, ?DEF(list_services_request, list_services_response, <<"sd.ListServicesRequest">>), Options). 79 | 80 | %% @doc Unary RPC 81 | -spec add_named_ports(sdg_discovery_pb:add_named_ports_request()) -> 82 | {ok, sdg_discovery_pb:add_named_ports_response(), grpcbox:metadata()} | grpcbox_stream:grpc_error_response(). 83 | add_named_ports(Input) -> 84 | add_named_ports(ctx:new(), Input, #{}). 85 | 86 | -spec add_named_ports(ctx:t() | sdg_discovery_pb:add_named_ports_request(), sdg_discovery_pb:add_named_ports_request() | grpcbox_client:options()) -> 87 | {ok, sdg_discovery_pb:add_named_ports_response(), grpcbox:metadata()} | grpcbox_stream:grpc_error_response(). 88 | add_named_ports(Ctx, Input) when ?is_ctx(Ctx) -> 89 | add_named_ports(Ctx, Input, #{}); 90 | add_named_ports(Input, Options) -> 91 | add_named_ports(ctx:new(), Input, Options). 92 | 93 | -spec add_named_ports(ctx:t(), sdg_discovery_pb:add_named_ports_request(), grpcbox_client:options()) -> 94 | {ok, sdg_discovery_pb:add_named_ports_response(), grpcbox:metadata()} | grpcbox_stream:grpc_error_response(). 95 | add_named_ports(Ctx, Input, Options) -> 96 | grpcbox_client:unary(Ctx, <<"/sd.DiscoveryService/AddNamedPorts">>, Input, ?DEF(add_named_ports_request, add_named_ports_response, <<"sd.AddNamedPortsRequest">>), Options). 97 | 98 | %% @doc Unary RPC 99 | -spec lookup_endpoints(sdg_discovery_pb:lookup_endpoints_request()) -> 100 | {ok, sdg_discovery_pb:lookup_endpoints_response(), grpcbox:metadata()} | grpcbox_stream:grpc_error_response(). 101 | lookup_endpoints(Input) -> 102 | lookup_endpoints(ctx:new(), Input, #{}). 103 | 104 | -spec lookup_endpoints(ctx:t() | sdg_discovery_pb:lookup_endpoints_request(), sdg_discovery_pb:lookup_endpoints_request() | grpcbox_client:options()) -> 105 | {ok, sdg_discovery_pb:lookup_endpoints_response(), grpcbox:metadata()} | grpcbox_stream:grpc_error_response(). 106 | lookup_endpoints(Ctx, Input) when ?is_ctx(Ctx) -> 107 | lookup_endpoints(Ctx, Input, #{}); 108 | lookup_endpoints(Input, Options) -> 109 | lookup_endpoints(ctx:new(), Input, Options). 110 | 111 | -spec lookup_endpoints(ctx:t(), sdg_discovery_pb:lookup_endpoints_request(), grpcbox_client:options()) -> 112 | {ok, sdg_discovery_pb:lookup_endpoints_response(), grpcbox:metadata()} | grpcbox_stream:grpc_error_response(). 113 | lookup_endpoints(Ctx, Input, Options) -> 114 | grpcbox_client:unary(Ctx, <<"/sd.DiscoveryService/LookupEndpoints">>, Input, ?DEF(lookup_endpoints_request, lookup_endpoints_response, <<"sd.LookupEndpointsRequest">>), Options). 115 | 116 | %% @doc Unary RPC 117 | -spec register_endpoint(sdg_discovery_pb:register_endpoint_request()) -> 118 | {ok, sdg_discovery_pb:register_endpoint_response(), grpcbox:metadata()} | grpcbox_stream:grpc_error_response(). 119 | register_endpoint(Input) -> 120 | register_endpoint(ctx:new(), Input, #{}). 121 | 122 | -spec register_endpoint(ctx:t() | sdg_discovery_pb:register_endpoint_request(), sdg_discovery_pb:register_endpoint_request() | grpcbox_client:options()) -> 123 | {ok, sdg_discovery_pb:register_endpoint_response(), grpcbox:metadata()} | grpcbox_stream:grpc_error_response(). 124 | register_endpoint(Ctx, Input) when ?is_ctx(Ctx) -> 125 | register_endpoint(Ctx, Input, #{}); 126 | register_endpoint(Input, Options) -> 127 | register_endpoint(ctx:new(), Input, Options). 128 | 129 | -spec register_endpoint(ctx:t(), sdg_discovery_pb:register_endpoint_request(), grpcbox_client:options()) -> 130 | {ok, sdg_discovery_pb:register_endpoint_response(), grpcbox:metadata()} | grpcbox_stream:grpc_error_response(). 131 | register_endpoint(Ctx, Input, Options) -> 132 | grpcbox_client:unary(Ctx, <<"/sd.DiscoveryService/RegisterEndpoint">>, Input, ?DEF(register_endpoint_request, register_endpoint_response, <<"sd.RegisterEndpointRequest">>), Options). 133 | 134 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | Copyright 2019, Tristan Sloughter . 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | 192 | --------------------------------------------------------------------------------