From 63af4a5cbe49e4ad482c78d0d57d30cdca8e586e Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Sat, 30 Sep 2017 08:50:18 +0900 Subject: [PATCH 01/55] Initial commit; middle of transition --- zx | 1902 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1902 insertions(+) create mode 100755 zx diff --git a/zx b/zx new file mode 100755 index 0000000..60bb198 --- /dev/null +++ b/zx @@ -0,0 +1,1902 @@ +#! /usr/bin/env escript + +%%% zx +%%% +%%% A general dependency and packaging tool that works together with the zomp +%%% package manager. Given a project directory with a standard layout, zx can: +%%% - Initialize your project for packaging and semver tracking under zomp. +%%% - Add dependencies (recursively) defined in any zomp repository realm. +%%% - Update dependencies (recursively) defined in any zomp repository realm. +%%% - Remove dependencies. +%%% - Update, upgrade or run any application from source that zomp tracks. +%%% - Locally install packages from files and locally stored public keys. +%%% - Build and run a local project from source using zomp dependencies. + +-module(zx). +-mode(compile). +-export([main/1]). + + +-record(s, + {realm = "otpr" :: name(), + app = none :: none | name(), + version = {z, z, z} :: version(), + pid = none :: none | pid(), + mon = none :: none | reference()}). + + +-type state() :: #s{}. +-type name() :: string(). +-type version() :: {Major :: z | non_neg_integer(), + Minor :: z | non_neg_integer(), + Patch :: z | non_neg_integer()}. +-type app_id() :: {Realm :: name(), + App :: name(), + Version :: version()}. +-type option() :: {string(), term()}. +-type peer() :: {inet:hostname() | inet:ip_address(), inet:port_number()}. + + + +-spec main(Args) -> no_return() + when Args :: [string()]. +%% @private +%% The automatically exposed function initially called by escript to kick things off. +%% Args is a list of command-line provided arguments, all presented as a list of strings +%% delimited by whitespace in the shell. + +main(Args) -> + ok = ensure_zomp_home(), + start(Args). + + +-spec start(Args) -> no_return() + when Args :: [string()]. +%% Dispatch work functions based on the nature of the input arguments. + +start(["help"]) -> + usage_exit(0); +start(["run", AppString | Args]) -> + execute(AppString, Args); +start(["init", "app", AppString]) -> + AppID = appstring_to_appid(AppString), + initialize(app, AppID); +start(["init", "lib", AppString]) -> + AppID = appstring_to_appid(AppString), + initialize(lib, AppID); +start(["install", PackageFile]) -> + assimilate(PackageFile); +start(["set", "dep", AppString]) -> + set_dep(AppString); +start(["set", "version", VersionString]) -> + set_version(VersionString); +start(["drop", "dep", AppString]) -> + AppID = appstring_to_appid(AppString), + drop_dep(AppID); +start(["drop", "key", KeyID]) -> + drop_key(KeyID); +start(["verup", Level]) -> + verup(Level); +start(["runlocal"]) -> + run_local([]); +start(["runlocal", Args]) -> + run_local(Args); +start(["package"]) -> + {ok, TargetDir} = file:get_cwd(), + package(TargetDir); +start(["package", TargetDir]) -> + case filelib:is_dir(TargetDir) of + true -> + package(TargetDir); + false -> + ok = log(error, "Target directory ~tp does not exist!", [TargetDir]), + halt(22) + end; +start(["submit", PackageFile]) -> + submit(PackageFile); +start(["keygen"]) -> + keygen(); +start(["genplt"]) -> + genplt(); +start(["dialyze"]) -> + dialyze(); +start(_) -> + usage_exit(22). + + + +%%% Execution of application + + +-spec execute(Identifier, Args) -> no_return() + when Identifier :: string(), + Args :: [string()]. +%% @private +%% Given a program Identifier and a list of Args, attempt to locate the program and its +%% dependencies and run the program. This implies determining whether the program and +%% its dependencies are installed, available, need to be downloaded, or are inaccessible +%% given the current system condition (they could also be bogus, of course). The +%% Identifier provided should be a valid AppString of the form `realm-appname-version' +%% where the realm and appname should follow standard realm and app package naming +%% conventions and the version should be represented as a semver in string form (where +%% ommitted elements of the version always default to whatever is most current). +%% +%% Once the target program is running this process, which will run with the registered +%% name `vx' will sit in an `exec_wait' state, waiting for either a direct message from +%% a child program or for calls made via vx_lib to assist in environment discovery. +%% +%% If there is a problem anywhere in the locationg, discovery, building, and loading +%% procedure the runtime will halt with an error message. + +execute(Identifier, Args) -> + true = register(zx, self()), + ok = inets:start(), + AppID = {Realm, App, Version} = appstring_to_appid(Identifier), + ok = file:set_cwd(zomp_dir()), + AppRoot = filename:join("lib", Identifier), + ok = ensure_installed(AppID), + {ok, Meta} = file:consult(filename:join(AppRoot, "zomp.meta")), + {deps, Deps} = lists:keyfind(deps, 1, Meta), + Required = [AppID | Deps], + Needed = scrub(Required), + ok = fetch(Needed), + ok = lists:foreach(fun install/1, Needed), + ok = lists:foreach(fun build/1, Required), + ok = file:set_cwd(AppRoot), + case lists:keyfind(type, 1, Meta) of + {type, app} -> + ok = log(info, "Starting ~ts", [appid_to_appstring(AppID)]), + AppMod = list_to_atom(App), + {ok, Pid} = AppMod:start(normal, Args), + Mon = monitor(process, Pid), + Shell = spawn(shell, start, []), + ok = log(info, "Your shell is ~p, application is: ~p", [Shell, Pid]), + State = #s{realm = Realm, + app = App, + version = Version, + pid = Pid, + mon = Mon}, + exec_wait(State); + {type, lib} -> + Message = "Lib ~ts is available on the system, but is not a standalone app.", + ok = log(info, Message, [appid_to_appstring(AppID)]), + halt(0) + end. + + + +%%% Project initialization + + +-spec initialize(Type, AppID) -> no_return() + when Type :: app | lib, + AppID :: app_id(). +%% @private +%% Initialize an application in the local directory based on the AppID provided. +%% This function does not care about the name of the current directory and leaves +%% providing a complete, proper and accurate AppID. +%% This function will check the current `lib/' directory for zomp-style dependencies. +%% If this is not the intended function or if there are non-compliant directory names +%% in `lib/' then the project will need to be rearranged to become zomp compliant or +%% the `deps' section of the resulting meta file will need to be manually updated. + +initialize(Type, AppID) -> + AppString = appid_to_appstring(AppID), + ok = log(info, "Initializing ~s...", [AppString]), + Meta = [{app_id, AppID}, + {deps, []}, + {type, Type}], + ok = write_terms("zomp.meta", Meta), + ok = log(info, "Project ~tp initialized.", [AppString]), + Message = + "NOTICE:~n" + " This project is currently listed as having no dependencies.~n" + " If this is not true then run `zx set dep DepID` for each current dependency.~n" + " (run `zx help` for more information on usage)~n", + ok = io:format(Message), + halt(0). + + + +%%% Add a package from a local file + + +-spec assimilate(PackageFile) -> AppID + when PackageFile :: file:filename(), + AppID :: app_id(). +%% @private +%% Receives a path to a file containing package data, examines it, and copies it to a +%% canonical location under a canonical name, returning the AppID of the package +%% contents. + +assimilate(PackageFile) -> + Files = extract_zrp(PackageFile), + {ok, CWD} = file:get_cwd(), + ok = file:set_cwd(zomp_dir()), + {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), + Meta = binary_to_term(MetaBin), + {package_id, AppID} = lists:keyfind(package_id, 1, Meta), + TgzFile = namify_tgz(AppID), + {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files), + {sig, {KeyID, Signature}} = lists:keyfind(sig, 1, Meta), + KeyFile = filename:join("key", KeyID), + {ok, PubKey} = loadkey(public, KeyFile), + ok = + case public_key:verify(TgzData, sha512, Signature, PubKey) of + true -> + ZrpPath = filename:join("zrp", namify_zrp(AppID)), + erl_tar:create(ZrpPath, Files); + false -> + error_exit("Bad package signature: ~ts", [PackageFile], ?FILE, ?LINE) + end, + ok = file:set_cwd(CWD), + Message = "~ts is now locally available.", + ok = log(info, Message, [appid_to_appstring(AppID)]), + halt(0). + + + +%%% Set dependency + + +-spec set_dep(AppString) -> no_return() + when AppString :: string(). +%% @private +%% Set a specific dependency in the current project. If the project currently has a +%% dependency on the same Realm-App then the version of that dependency is updated to +%% reflect that in the AppString argument. The AppString is permitted to be incomplete. +%% Incomplete elements of the included VersionString (if included) will default to the +%% latest version available at the indicated level. + +set_dep(AppString) -> + AppID = appstring_to_appid(AppString), + Meta = read_meta(), + {deps, Deps} = lists:keyfind(deps, 1, Meta), + case lists:member(AppID, Deps) of + true -> + ok = log(info, "~ts is already a dependency", [AppString]), + halt(0); + false -> + set_dep(AppID, Deps, Meta) + end. + + +-spec set_dep(AppID, Deps, Meta) -> no_return() + when AppID :: app_id(), + Deps :: [app_id()], + Meta :: [term()]. +%% @private +%% Given the AppID, list of Deps and the current contents of the project Meta, add or +%% update Deps to include (or update) Deps to reflect a dependency on AppID, if such a +%% dependency is not already present. Then write the project meta back to its file and +%% exit. + +set_dep(AppID = {Realm, App, NewVersion}, Deps, Meta) -> + {ok, CWD} = file:get_cwd(), + ok = file:set_cwd(zomp_dir()), + ok = ensure_installed(AppID), + ok = file:set_cwd(CWD), + ExistingApp = fun ({R, A, _}) -> {R, A} == {Realm, App} end, + NewDeps = + case lists:partition(ExistingApp, Deps) of + {[{Realm, App, OldVersion}], Rest} -> + Message = "Updating dep ~ts to ~ts", + OldAppString = appid_to_appstring({Realm, App, OldVersion}), + NewAppString = appid_to_appstring({Realm, App, NewVersion}), + ok = log(info, Message, [OldAppString, NewAppString]), + [AppID | Rest]; + {[], Deps} -> + ok = log(info, "Adding dep ~ts", [appid_to_appstring(AppID)]), + [AppID | Deps] + end, + NewMeta = lists:keystore(deps, 1, Meta, {deps, NewDeps}), + ok = write_terms("zomp.meta", NewMeta), + halt(0). + + +-spec ensure_installed(app_id()) -> ok | no_return(). +%% @private +%% Given an AppID, check whether it is installed on the system, and if not, ensure +%% that the package is either in the cache or can be downloaded. If all attempts at +%% locating or acquiring the package fail, then exit with an error. + +ensure_installed(AppID) -> + AppString = appid_to_appstring(AppID), + AppDir = filename:join("lib", AppString), + case filelib:is_dir(AppDir) of + true -> ok; + false -> ensure_dep(AppID) + end. + + +-spec ensure_dep(app_id()) -> ok | no_return(). +%% @private +%% Given an AppID as an argument, check whether its package file exists in the system +%% cache, and if not download it. Should return `ok' whenever the file is sourced, but +%% exit with an error if it cannot locate or acquire the package. + +ensure_dep(AppID) -> + ZrpFile = filename:join("zrp", namify_zrp(AppID)), + ok = + case filelib:is_regular(ZrpFile) of + true -> + ok; + false -> + AppString = appid_to_appstring(AppID), + log(error, "Would fetch ~ts now, but not implemented", [AppString]), + halt(0) + end, + install(AppID). + + + +%%% Set version + + +-spec set_version(VersionString) -> no_return() + when VersionString :: string(). +%% @private +%% Convert a version string to a new version, sanitizing it in the process and returning +%% a reasonable error message on bad input. + +set_version(VersionString) -> + NewVersion = + case check_version(VersionString) of + {_, _, z} -> + Message = "'set version' arguments must be complete, ex: 1.2.3", + ok = log(error, Message), + halt(22); + Version -> + Version + end, + update_version(NewVersion). + + +-spec update_version(Level) -> no_return() + when Level :: major + | minor + | patch + | VersionString, + VersionString :: string(). % Of the form "Major.Minor.Patch" +%% @private +%% Update a project's `zomp.meta' file by either incrementing the indicated component, +%% or setting the version number to the one specified in VersionString. +%% This part of the procedure guards for the case when the zomp.meta file cannot be +%% read for some reason. + +update_version(Arg) -> + Meta = read_meta(), + {app_id, AppID} = lists:keyfind(app_id, 1, Meta), + update_version(Arg, AppID, Meta). + + +-spec update_version(Level, AppID, Meta) -> no_return() + when Level :: major + | minor + | patch + | version(), + AppID :: app_id(), + Meta :: [{atom(), term()}]. +%% @private +%% Update a project's `zomp.meta' file by either incrementing the indicated component, +%% or setting the version number to the one specified in VersionString. +%% This part of the procedure does the actual update calculation, to include calling to +%% convert the VersionString (if it is passed) to a `version()' type and check its +%% validity (or halt if it is a bad string). + +update_version(major, {Realm, App, OldVersion = {Major, _, _}}, OldMeta) -> + NewVersion = {Major + 1, 0, 0}, + update_version(Realm, App, OldVersion, NewVersion, OldMeta); +update_version(minor, {Realm, App, OldVersion = {Major, Minor, _}}, OldMeta) -> + NewVersion = {Major, Minor + 1, 0}, + update_version(Realm, App, OldVersion, NewVersion, OldMeta); +update_version(patch, {Realm, App, OldVersion = {Major, Minor, Patch}}, OldMeta) -> + NewVersion = {Major, Minor, Patch + 1}, + update_version(Realm, App, OldVersion, NewVersion, OldMeta); +update_version(NewVersion, {Realm, App, OldVersion}, OldMeta) -> + update_version(Realm, App, OldVersion, NewVersion, OldMeta). + + +-spec update_version(Realm, App, OldVersion, NewVersion, OldMeta) -> no_return() + when Realm :: name(), + App :: name(), + OldVersion :: version(), + NewVersion :: version(), + OldMeta :: [{atom(), term()}]. +%% @private +%% Update a project's `zomp.meta' file by either incrementing the indicated component, +%% or setting the version number to the one specified in VersionString. +%% This part of the procedure updates the meta and does the final write, if the write +%% turns out to be possible. If successful it will indicate to the user what was +%% changed. + +update_version(Realm, App, OldVersion, NewVersion, OldMeta) -> + NewMeta = lists:keystore(app_id, 1, OldMeta, {app_id, {Realm, App, NewVersion}}), + ok = write_terms("zomp.meta", NewMeta), + ok = log(info, + "Version changed from ~s to ~s.", + [version_to_string(OldVersion), version_to_string(NewVersion)]), + halt(0). + + + +%%% Drop dependency + + +-spec drop_dep(app_id()) -> no_return(). +%% @private +%% Remove the indicate dependency from the local project's zomp.meta record. + +drop_dep(AppID) -> + AppString = appid_to_appstring(AppID), + Meta = read_meta(), + {deps, Deps} = lists:keyfind(deps, 1, Meta), + case lists:member(AppID, Deps) of + true -> + NewDeps = lists:delete(AppID, Deps), + NewMeta = lists:keystore(deps, 1, Meta, {deps, NewDeps}), + ok = write_terms("zomp.meta", NewMeta), + Message = "~ts removed from dependencies.", + ok = log(info, Message, [AppString]), + halt(0); + false -> + ok = log(info, "~ts not found in dependencies.", [AppString]), + halt(0) + end. + + + +%%% Drop key + + +-spec drop_key(KeyID) -> no_return() + when KeyID :: file:filename(). +%% @private +%% Given a KeyID, remove the related public and private keys from the keystore, if they +%% exist. If not, exit with a message that no keys were found, but do not return an +%% error exit value (this instruction is idempotent if used in shell scripts). + +drop_key(KeyID) -> + ok = file:set_cwd(zomp_dir()), + KeyDir = filename:join(zomp_dir(), "key"), + Pattern = KeyID ++ ".{key,pub}.der", + case filelib:wildcard(filename:join(KeyDir, Pattern)) of + [] -> + ok = log(warning, "KeyID ~ts not found", [KeyID]), + halt(0); + Files -> + ok = lists:foreach(fun file:delete/1, Files), + ok = log(info, "Keyset ~ts removed", [KeyID]), + halt(0) + end. + + + +%%% Update version + + +-spec verup(Level) -> no_return() + when Level :: string(). +%% @private +%% Convert input string arguments to acceptable atoms for use in update_version/1. + +verup("major") -> update_version(major); +verup("minor") -> update_version(minor); +verup("patch") -> update_version(patch); +verup(_) -> usage_exit(22). + + + +%%% Run local project + +-spec run_local(Args) -> no_return() + when Args :: [term()]. +%% @private +%% Execute a local project from source from the current directory, satisfying dependency +%% requirements via the locally installed zomp lib cache. The project must be +%% initialized as a zomp project (it must have a valid `zomp.meta' file). +%% +%% The most common use case for this function is during development. Using zomp support +%% via the local lib cache allows project authors to worry only about their own code +%% and use zx commands to add or drop dependencies made available via zomp. + +run_local(Args) -> + true = register(zx, self()), + ok = inets:start(), + {ok, ProjectRoot} = file:get_cwd(), + {ok, Meta} = file:consult("zomp.meta"), + {app_id, AppID = {Realm, App, Version}} = lists:keyfind(app_id, 1, Meta), + ok = build(), + ok = file:set_cwd(zomp_dir()), + {deps, Deps} = lists:keyfind(deps, 1, Meta), + Needed = scrub(Deps), + ok = fetch(Needed), + ok = lists:foreach(fun install/1, Needed), + ok = lists:foreach(fun build/1, Deps), + ok = file:set_cwd(ProjectRoot), + case lists:keyfind(type, 1, Meta) of + {type, app} -> + ok = log(info, "Starting ~ts", [appid_to_appstring(AppID)]), + AppMod = list_to_atom(App), + {ok, Pid} = AppMod:start(normal, Args), + Mon = monitor(process, Pid), + Shell = spawn(shell, start, []), + ok = log(info, "Your shell is ~p, application is: ~p", [Shell, Pid]), + State = #s{realm = Realm, + app = App, + version = Version, + pid = Pid, + mon = Mon}, + exec_wait(State); + {type, lib} -> + Message = "Lib ~ts is available on the system, but is not a standalone app", + ok = log(info, Message, [appid_to_appstring(AppID)]), + halt(0) + end. + + + +%%% Package generation + +-spec package(TargetDir) -> no_return() + when TargetDir :: file:filename(). +%% @private +%% Turn a target project directory into a package, prompting the user for appropriate +%% key selection or generation actions along the way. + +package(TargetDir) -> + ok = log(info, "Packaging ~ts", [TargetDir]), + KeyDir = filename:join(zomp_dir(), "key"), + ok = force_dir(KeyDir), + Pattern = KeyDir ++ "/*.key.der", + case [filename:basename(F, ".key.der") || F <- filelib:wildcard(Pattern)] of + [] -> + ok = log(info, "Need to generate key"), + KeyPrefix = prompt_keygen(KeyDir), + ok = generate_rsa(KeyPrefix), + package(KeyPrefix, TargetDir); + [KeyPrefix] -> + ok = log(info, "Using key: ~ts", [KeyPrefix]), + package(KeyPrefix, TargetDir); + KeyPrefixes -> + KeyPrefix = select_string(KeyPrefixes), + package(KeyPrefix, TargetDir) + end. + + +-spec package(KeyPrefix, TargetDir) -> no_return() + when KeyPrefix :: string(), + TargetDir :: file:filename(). +%% @private +%% Accept a KeyPrefix for signing and a TargetDir containing a project to package and +%% build a zrp package file ready to be submitted to a repository. + +package(KeyPrefix, TargetDir) -> + KeyID = KeyPrefix ++ ".key.der", + PubID = KeyPrefix ++ ".pub.der", + {ok, Meta} = file:consult(filename:join(TargetDir, "zomp.meta")), + {app_id, AppID} = lists:keyfind(app_id, 1, Meta), + AppString = appid_to_appstring(AppID), + ZrpFile = AppString ++ ".zrp", + TgzFile = AppString ++ ".tgz", + ok = halt_if_exists(ZrpFile), + ok = remove_binaries(TargetDir), + {ok, Everything} = file:list_dir(TargetDir), + DotFiles = filelib:wildcard(".*", TargetDir), + Ignores = ["lib" | DotFiles], + Targets = lists:subtract(Everything, Ignores), + {ok, CWD} = file:get_cwd(), + ok = file:set_cwd(TargetDir), + ok = erl_tar:create(filename:join(CWD, TgzFile), Targets, [compressed]), + ok = file:set_cwd(CWD), + KeyFile = filename:join([zomp_dir(), "key", KeyID]), + {ok, Key} = loadkey(private, KeyFile), + {ok, TgzBin} = file:read_file(TgzFile), + Sig = public_key:sign(TgzBin, sha512, Key), + FinalMeta = [{sig, {PubID, Sig}} | Meta], + ok = file:write_file("zomp.meta", term_to_binary(FinalMeta)), + ok = erl_tar:create(ZrpFile, ["zomp.meta", TgzFile]), + ok = file:delete(TgzFile), + ok = file:delete("zomp.meta"), + ok = log(info, "Wrote archive ~ts", [ZrpFile]), + halt(0). + + +-spec remove_binaries(TargetDir) -> ok + when TargetDir :: file:filename(). +%% @private +%% Procedure to delete all .beam and .ez files from a given directory starting at +%% TargetDir. Called as part of the pre-packaging sanitization procedure. + +remove_binaries(TargetDir) -> + Beams = filelib:wildcard("**/*.{beam,ez}", TargetDir), + case [filename:join(TargetDir, Beam) || Beam <- Beams] of + [] -> + ok; + ToDelete -> + ok = log(info, "Removing: ~tp", [ToDelete]), + lists:foreach(fun file:delete/1, ToDelete) + end. + + + +%%% App execution loop + +-spec exec_wait(State) -> no_return() + when State :: state(). +%% @private +%% Execution maintenance loop. +%% Once an application is started by zompc this process will wait for a message from +%% the application if that application was written in a way to take advantage of zompc +%% facilities such as post-start upgrade checking. +%% +%% NOTE: +%% Adding clauses to this `receive' is where new functionality belongs. +%% It may make sense to add a `zompc_lib' as an available dependency authors could +%% use to interact with zompc without burying themselves under the complexity that +%% can come with naked send operations. (Would it make sense, for example, to have +%% the registered zompc process convert itself to a gen_server via zompc_lib to +%% provide more advanced functionality?) + +exec_wait(State = #s{pid = Pid, mon = Mon}) -> + receive + {check_update, Requester, Ref} -> + {Response, NewState} = check_update(State), + Requester ! {Ref, Response}, + exec_wait(NewState); + {exit, Reason} -> + ok = log(info, "Exiting with: ~tp", [Reason]), + halt(0); + {'DOWN', Mon, process, Pid, normal} -> + ok = log(info, "Application exited normally."), + halt(0); + {'DOWN', Mon, process, Pid, Reason} -> + ok = log(warning, "Application exited with: ~tp", [Reason]), + halt(1); + Unexpected -> + ok = log(warning, "Unexpected message: ~tp", [Unexpected]), + exec_wait(State) + end. + + +-spec check_update(State) -> {Response, NewState} + when State :: state(), + Response :: term(), + NewState :: state(). +%% @private +%% Check for updated version availability of the current application. +%% The return value should probably provide up to three results, a Major, Minor and +%% Patch update, and allow the Requestor to determine what to do with it via some +%% interaction. + +check_update(State) -> + ok = log(info, "Would be checking for an update of the current application now..."), + Response = "Nothing was checked, but you can imagine it to have been.", + {Response, State}. + + + +%%% Package submission + + +-spec submit(PackageFile) -> no_return() + when PackageFile :: file:filename(). +%% @private +%% Submit a package to the appropriate "prime" server for the given realm. + +submit(PackageFile) -> + Files = extract_zrp(PackageFile), + {ok, PackageData} = file:read_file(PackageFile), + {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), + Meta = binary_to_term(MetaBin), + {app_id, {Realm, Package, Version}} = lists:keyfind(app_id, 1, Meta), + {sig, {PublicKeyFile, _}} = lists:keyfind(sig, 1, Meta), + KeyID = filename:rootname(PublicKeyFile, ".pub.der"), + true = ensure_keypair(KeyID), + RealmData = realm_data(Realm), + {prime, Prime} = lists:keyfind(prime, 1, RealmData), + Socket = connect(Prime), + ok = send(Socket, {submit, {Realm, Package, Version}}), + ok = + receive + {tcp, Socket, Response} -> + case binary_to_term(Response, [safe]) of + ready -> + ok; + {error, Reason} -> + ok = log(info, "Server refused with ~tp", [Reason]), + halt(0) + end; + after 5000 -> + ok = log(warning, "Server timed out!"), + halt(0) + end, + ok = send(Socket, PackageData), + ok = log(info, "Done sending contents of ~tp", [PackageFile]), + ok = + receive + {tcp, Socket, Response} -> + log(info, "Response: ~tp", [Response]); + Other -> + log(warning, "Unexpected message: ~tp", [Other]) + after 5000 -> + log(warning, "Server timed out!") + end, + ok = disconnect(Socket), + halt(0). + + +-spec send(Socket, Message) -> ok + when Socket :: gen_tcp:socket(), + Message :: term(). +%% @private +%% Wrapper for the procedure necessary to send an internal message over the wire. + +send(Socket, Message) -> + BinMessage = term_to_binary(Message), + gen_tcp:send(Socket, Message). + + +-spec connect(peer()) -> inet:socket() | no_return(). +%% @private +%% Connect to one of the servers in the realm constellation. + +connect({Host, Port}) -> + Options = [{packet, 4}, {mode, binary}, {active, true}], + case gen_tcp:connect(Host, Port, Options) of + {ok, Socket} -> + confirm_server(Socket); + {error, Error} -> + ok = log(warning, "Connection problem: ~tp", [Error]), + halt(0) + end. + + +-spec confirm_server(inet:socket()) -> inet:socket() | no_return(). +%% @private +%% Send a protocol ID string to notify the server what we're up to, disconnect +%% if it does not return an "OK" response within 5 seconds. + +confirm_server(Socket) -> + {ok, {Addr, Port}} = inet:peername(Socket), + Host = inet:ntoa(Addr), + ok = gen_tcp:send(Socket, <<"OTPR 1 CLIENT">>), + receive + {tcp, Socket, <<"OK">>} -> + ok = log(info, "Connected to ~s:~p", [Host, Port]), + Socket; + Other -> + Message = "Unexpected response from ~s:~p:~n~tp", + ok = log(warning, Message, [Host, Port, Other]), + ok = disconnect(Socket), + halt(0) + after 5000 -> + ok = log(warning, "Host ~s:~p timed out.", [Host, Port]), + halt(0) + end. + + +-spec disconnect(inet:socket()) -> ok. +%% @private +%% Gracefully shut down a socket, logging (but sidestepping) the case when the socket +%% has already been closed by the other side. + +disconnect(Socket) -> + case gen_tcp:shutdown(Socket, read_write) of + ok -> + log(info, "Disconnected from ~tp", [Socket]); + {error, Error} -> + Message = "Shutdown connection ~p failed with: ~p", + log(warning, Message, [Socket, Error]) + end. + + +-spec ensure_keypair(KeyID) -> true | no_return() + when KeyID :: string(). +%% @private +%% Check if both the public and private key based on KeyID exists. + +ensure_keypair(KeyID) -> + case {have_public_key(KeyID), have_private_key(KeyID)} of + {true, true} -> + true; + {false, true} -> + ok = log(error, "Public key for ~tp cannot be found", [KeyID]), + halt(1); + {true, false} -> + ok = log(error, "Private key for ~tp cannot be found", [KeyID]), + halt(1); + {false, false} -> + Message = "Key pair for ~tp cannot be found", + ok = log(error, Message, [KeyID]), + halt(1) + end. + + +-spec have_public_key(KeyID) -> boolean() + when KeyID :: string(). +%% @private +%% Determine whether the public key indicated by KeyID is in the keystore. + +have_public_key(KeyID) -> + PublicKeyFile = KeyID ++ ".pub.der", + PublicKeyPath = filename:join([zomp_dir(), "key", PublicKeyFile]), + filelib:is_regular(PublicKeyPath). + + +-spec have_private_key(KeyID) -> boolean() + when KeyID :: string(). +%% @private +%% Determine whether the private key indicated by KeyID is in the keystore. + +have_private_key(KeyID) -> + PrivateKeyFile = KeyID ++ ".key.der", + PrivateKeyPath = filename:join([zomp_dir(), "key", PrivateKeyFile]), + filelib:is_regular(PrivateKeyPath). + + +-spec realm_data(Realm) -> Data | no_return() + when Realm :: string(), + Data :: [{atom(), term()}]. +%% @private +%% Given a realm name, try to locate and read the realm's configuration file if it +%% exists, exiting with an appropriate error message if there is a problem reading +%% the file. + +realm_data(Realm) -> + RealmFile = filename:join([zomp_dir(), Realm ++ ".realm"]), + case file:consult(RealmFile) of + {ok, Data} -> + Data; + {error, enoent} -> + ok = log(error, "No realm file for ~ts", [Realm]), + halt(1); + Error -> + Message = "Open realm file ~ts failed with ~ts", + error_exit(Message, [RealmFile, Error], ?FILE, ?LINE) + end. + + +%%% Key generation + + +-spec prompt_keygen(KeyDir) -> KeyPrefix + when KeyDir :: file:filename(), + KeyPrefix :: string(). +%% @private +%% Prompt the user for a valid KeyPrefix to use for naming a new RSA keypair. + +prompt_keygen(KeyDir) -> + Message = + " Enter a name for your new keys.~n" + " Valid names must start with a lower-case letter, and can include~n" + " only lower-case letters, numbers, and periods, but no series of~n" + " consecutive periods.~n", + ok = io:format(Message), + Input = io:get_line("(^C to quit): "), + case validate_prefix(Input) of + {ok, Value} -> + Value; + error -> + ok = io:format("Bad name. Try again.~n"), + prompt_keygen(KeyDir) + end. + + +-spec validate_prefix(Prefix) -> {ok, Validated} | error + when Prefix :: string(), + Validated :: string(). +%% @private +%% Validate that a provided key prefix is legal according to the naming convention +%% provided in the prefix explanation prompt. + +validate_prefix([Char | Rest]) + when $a =< Char, Char =< $z -> + validate_prefix(Rest, Char, [Char]); +validate_prefix(_) -> + error. + + +-spec validate_prefix(Prefix, Last, Accumulator) -> {ok, Validated} | error + when Prefix :: string(), + Last :: char(), + Accumulator :: [char()], + Validated :: string(). + +%% @private +%% Validate that a provided key prefix is legal according to the naming convention +%% provided in the prefix explanation prompt. + +validate_prefix([$. | _], $., _) -> + error; +validate_prefix([Char | Rest], _, Acc) + when $a =< Char, Char =< $z; + $0 =< Char, Char =< $9; + Char == $. -> + validate_prefix(Rest, Char, [Char | Acc]); +validate_prefix([$\n], _, Acc) -> + {ok, lists:reverse(Acc)}; +validate_prefix(_, _, _) -> + error. + + +-spec keygen() -> no_return(). +%% @private +%% Execute the key generation procedure for 16k RSA keys once and then terminate. + +keygen() -> + ok = file:set_cwd(zomp_dir()), + KeyDir = filename:join(zomp_dir(), "key"), + Prefix = prompt_keygen(KeyDir), + case generate_rsa(Prefix) of + ok -> + halt(0); + Error -> + error_exit("keygen failed with ~tp", [Error], ?FILE, ?LINE) + end. + + +-spec generate_rsa(Prefix) -> Result + when Prefix :: string(), + Result :: {ok, KeyFile, PubFile} + | {error, keygen_fail}, + KeyFile :: file:filename(), + PubFile :: file:filename(). +%% @private +%% Generate an RSA keypair and write them in der format to the current directory, using +%% filenames derived from Prefix. +%% NOTE: The current version of this command is likely to only work on a unix system. + +generate_rsa(Prefix) -> + ZompDir = zomp_dir(), + PemFile = filename:join([ZompDir, "key", Prefix ++ ".pub.pem"]), + KeyFile = filename:join([ZompDir, "key", Prefix ++ ".key.der"]), + PubFile = filename:join([ZompDir, "key", Prefix ++ ".pub.der"]), + ok = lists:foreach(fun halt_if_exists/1, [PemFile, KeyFile, PubFile]), + ok = log(info, "Generating ~p and ~p. Please be patient...", [KeyFile, PubFile]), + ok = gen_p_key(KeyFile), + ok = der_to_pem(KeyFile, PemFile), + {ok, PemBin} = file:read_file(PemFile), + [PemData] = public_key:pem_decode(PemBin), + Pub = public_key:pem_entry_decode(PemData), + PubDer = public_key:der_encode('RSAPublicKey', Pub), + ok = file:write_file(PubFile, PubDer), + case check_key(KeyFile, PubFile) of + true -> + ok = file:delete(PemFile), + ok = log(info, "~ts and ~ts agree", [KeyFile, PubFile]), + ok = log(info, "Wrote private key to: ~ts.", [KeyFile]), + ok = log(info, "Wrote public key to: ~ts.", [PubFile]), + ok; + false -> + ok = lists:foreach(fun file:delete/1, [PemFile, KeyFile, PubFile]), + ok = log(error, "Something has gone wrong."), + {error, keygen_fail} + end. + + +-spec halt_if_exists(file:filename()) -> ok | no_return(). +%% @private +%% A helper function to guard against overwriting an existing file. Halts execution if +%% the file is found to exist. + +halt_if_exists(Path) -> + case filelib:is_file(Path) of + true -> + ok = log(error, "~ts already exists! Halting.", [Path]), + halt(1); + false -> + ok + end. + + +-spec gen_p_key(KeyFile) -> ok + when KeyFile :: file:filename(). +%% @private +%% Format an openssl shell command that will generate proper 16k RSA keys. + +gen_p_key(KeyFile) -> + Command = + io_lib:format("~ts genpkey" + " -algorithm rsa" + " -out ~ts" + " -outform DER" + " -pkeyopt rsa_keygen_bits:16384", + [openssl(), KeyFile]), + Out = os:cmd(Command), + io:format(Out). + + +-spec der_to_pem(KeyFile, PemFile) -> ok + when KeyFile :: file:filename(), + PemFile :: file:filename(). +%% @private +%% Format an openssl shell command that will convert the given keyfile to a pemfile. +%% The reason for this conversion is to sidestep some formatting weirdness that OpenSSL +%% injects into its generated DER formatted key output (namely, a few empty headers) +%% which Erlang's ASN.1 defintion files do not take into account. A conversion to PEM +%% then a conversion back to DER (via Erlang's ASN.1 module) resolves this in a reliable +%% way. + +der_to_pem(KeyFile, PemFile) -> + Command = + io_lib:format("~ts rsa" + " -inform DER" + " -in ~ts" + " -outform PEM" + " -pubout" + " -out ~ts", + [openssl(), KeyFile, PemFile]), + Out = os:cmd(Command), + io:format(Out). + + +-spec check_key(KeyFile, PubFile) -> Result + when KeyFile :: file:filename(), + PubFile :: file:filename(), + Result :: true | false. +%% @private +%% Compare two keys for pairedness. + +check_key(KeyFile, PubFile) -> + {ok, KeyBin} = file:read_file(KeyFile), + {ok, PubBin} = file:read_file(PubFile), + Key = public_key:der_decode('RSAPrivateKey', KeyBin), + Pub = public_key:der_decode('RSAPublicKey', PubBin), + TestMessage = <<"Some test data to sign.">>, + Signature = public_key:sign(TestMessage, sha512, Key), + public_key:verify(TestMessage, sha512, Signature, Pub). + + +-spec openssl() -> Executable | no_return() + when Executable :: file:filename(). +%% @private +%% Attempt to locate the installed openssl executable for use in shell commands. +%% Halts execution with an error message if the executable cannot be found. + +openssl() -> + OpenSSL = + case os:type() of + {unix, _} -> "openssl"; + {win32, _} -> "openssl.exe" + end, + ok = + case os:find_executable(OpenSSL) of + false -> + ok = log(error, "OpenSSL could not be found in this system's PATH."), + ok = log(error, "Install OpenSSL and then retry."), + error_exit("Missing system dependenct: OpenSSL", ?FILE, ?LINE); + Path -> + log(info, "OpenSSL executable found at: ~ts", [Path]) + end, + OpenSSL. + + +-spec loadkey(Type, File) -> Result + when Type :: private | public, + File :: file:filename(), + Result :: {ok, DecodedKey :: term()} + | {error, Reason :: term()}. +%% @private +%% Hide the details behind reading and loading DER encoded RSA key files. + +loadkey(Type, File) -> + DerType = + case Type of + private -> 'RSAPrivateKey'; + public -> 'RSAPublicKey' + end, + ok = log(info, "Loading key from file ~ts", [File]), + case file:read_file(File) of + {ok, Bin} -> {ok, public_key:der_decode(DerType, Bin)}; + Error -> Error + end. + + + +%%% Generate PLT + + +-spec genplt() -> no_return(). +%% @private +%% Generate a fresh PLT file that includes most basic core applications needed to +%% make a resonable estimate of a type system, write the name of the PLT to stdout, +%% and exit. + +genplt() -> + ok = build_plt(), + halt(0). + + +build_plt() -> + PLT = default_plt(), + Template = + "dialyzer --build_plt" + " --output_plt ~ts" + " --apps asn1 reltool wx common_test crypto erts eunit inets" + " kernel mnesia public_key sasl ssh ssl stdlib", + Command = io_lib:format(Template, [PLT]), + Message = + "Generating PLT file and writing to: ~tp~n" + " There will be a list of \"unknown functions\" in the final output.~n" + " Don't panic. This is normal. Turtles all the way down, after all...", + ok = log(info, Message, [PLT]), + ok = log(info, "This may take a while. Patience is a virtue."), + Out = os:cmd(Command), + log(info, Out). + + +default_plt() -> + filename:join(zomp_dir(), "basic.plt"). + + + +%%% Dialyze + +-spec dialyze() -> no_return(). +%% @private +%% Preps a copy of this script for typechecking with Dialyzer. + +dialyze() -> + PLT = default_plt(), + ok = + case filelib:is_regular(PLT) of + true -> log(info, "Using PLT: ~tp", [PLT]); + false -> build_plt() + end, + TmpDir = filename:join(zomp_dir(), "tmp"), + Me = escript:script_name(), + EvilTwin = filename:join(TmpDir, filename:basename(Me ++ ".erl")), + ok = log(info, "Temporarily reconstructing ~tp as ~tp", [Me, EvilTwin]), + Sed = io_lib:format("sed 's/^#!.*$//' ~s > ~s", [Me, EvilTwin]), + "" = os:cmd(Sed), + ok = case dialyzer:run([{init_plt, PLT}, {from, src_code}, {files, [EvilTwin]}]) of + [] -> + io:format("Dialyzer found no errors and returned no warnings! Yay!~n"); + Warnings -> + Mine = [dialyzer:format_warning({Tag, {Me, Line}, Msg}) + || {Tag, {_, Line}, Msg} <- Warnings], + lists:foreach(fun io:format/1, Mine) + end, + ok = file:delete(EvilTwin), + halt(0). + + + +%%% Network operations and package utilities + + +-spec install(app_id()) -> ok. +%% @private +%% Install a package from the cache into the local system. + +install(AppID) -> + AppString = appid_to_appstring(AppID), + ok = log(info, "Installing ~ts", [AppString]), + ZrpFile = filename:join("zrp", namify_zrp(AppID)), + Files = extract_zrp(ZrpFile), + TgzFile = namify_tgz(AppID), + {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files), + {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), + Meta = binary_to_term(MetaBin), + {sig, {KeyID, Signature}} = lists:keyfind(sig, 1, Meta), + KeyFile = filename:join("key", KeyID), + {ok, PubKey} = loadkey(public, KeyFile), + ok = ensure_app_dirs(AppID), + AppDir = filename:join("lib", AppString), + ok = force_dir(AppDir), + ok = verify(TgzData, Signature, PubKey), + ok = erl_tar:extract({binary, TgzData}, [compressed, {cwd, AppDir}]), + log(info, "~ts installed", [AppString]). + + +-spec extract_zrp(FileName) -> Files | no_return() + when FileName :: file:filename(), + Files :: [{file:filename(), binary()}]. +%% @private +%% Extract a zrp archive, if possible. If not possible, halt execution with as accurate +%% an error message as can be managed. + +extract_zrp(FileName) -> + case erl_tar:extract(FileName, [memory]) of + {ok, Files} -> + Files; + {error, {FileName, enoent}} -> + Message = "Can't find file ~ts.", + error_exit(Message, [FileName], ?FILE, ?LINE); + {error, invalid_tar_checksum} -> + Message = "~ts is not a valid zrp archive.", + error_exit(Message, [FileName], ?FILE, ?LINE); + {error, Reason} -> + Message = "Extracting package file failed with: ~tp.", + error_exit(Message, [Reason], ?FILE, ?LINE) + end. + + +-spec read_meta() -> [term()] | no_return(). +%% @private +%% Read the `zomp.meta' file from the current directory, if possible. If not possible +%% then halt execution with an appropriate error message. + +read_meta() -> + case file:consult("zomp.meta") of + {ok, Meta} -> + Meta; + Error -> + ok = log(error, "Failed to open \"zomp.meta\" with ~tp", [Error]), + ok = log(error, "Wrong directory?"), + halt(1) + end. + + +-spec verify(Data, Signature, PubKey) -> ok | no_return() + when Data :: binary(), + Signature :: binary(), + PubKey :: public_key:rsa_public_key(). +%% @private +%% Verify the RSA Signature of some Data against the given PubKey or halt execution. +%% This function always assumes sha512 is the algorithm being used. + +verify(Data, Signature, PubKey) -> + case public_key:verify(Data, sha512, Signature, PubKey) of + true -> ok; + false -> error_exit("Bad package signature!", ?FILE, ?LINE) + end. + + +-spec fetch([app_id()]) -> ok. +%% @private +%% Download a list of deps to the local package cache. + +fetch(Needed) -> + Namified = lists:map(fun namify_zrp/1, Needed), + {Have, Lack} = lists:partition(fun filelib:is_regular/1, Namified), + ok = lists:foreach(fun(A) -> log(info, "Have ~ts", [A]) end, Have), + ok = lists:foreach(fun(A) -> log(info, "Lack ~ts", [A]) end, Lack), + log(info, "Done fake fetching"). + + +% Grouped = group_by_realm(Needed), +% Realms = [R || {R, _} <- Grouped], +% Sockets = connect(Realms), +% fetch(Sockets, Groups). +% +% +%-spec group_by_realm(AppIDs) -> GroupedAppIDs +% when AppIDs :: [app_id()], +% GroupedAppIDs :: [{realm(), [app_id()]}]. +%%% @private +%%% Group apps by realm. +% +%group_by_realm(AppIDs) -> +% Group = +% fun(AppID = {Realm, _, _}, Groups) -> +% case lists:keyfind(Realm, Groups) of +% {Realm, Members} -> +% lists:keystore(Realm, 1, Groups, {Realm, [AppID | Members]}); +% false -> +% lists:keystore(Realm, 1, Groups, {Realm, [AppID]}) +% end +% end, +% lists:foldl(Group, AppIDs). +% +% +% ZrpFile = namify_zrp(AppID), +% case filelib:is_regular(filename:join("zrp", ZrpFile)) of +% true -> +% log(info, "Found in cache: ~ts", [ZrpFile]); +% false -> +% log(info, "Would download: ~ts", [ZrpFile]) +% end. + + + +%%% Utility functions + +-spec write_terms(Filename, Terms) -> ok + when Filename :: file:filename(), + Terms :: [term()]. +%% @private +%% Provides functionality roughly inverse to file:consult/1. + +write_terms(Filename, List) -> + Format = fun(Term) -> io_lib:format("~tp.~n", [Term]) end, + Text = lists:map(Format, List), + file:write_file(Filename, Text). + + +-spec build(app_id()) -> ok. +%% @private +%% Given an AppID, build the project from source and add it to the current lib path. + +build(AppID) -> + {ok, CWD} = file:get_cwd(), + ok = file:set_cwd(app_home(AppID)), + ok = build(), + file:set_cwd(CWD). + + +-spec build() -> ok. +%% @private +%% Run any local `zxmake' script needed by the project for non-Erlang code (if present), +%% then add the local `ebin/' directory to the runtime search path, and finally build +%% the Erlang part of the project with make:all/0 according to the local `Emakefile'. + +build() -> + ZxMake = "zxmake", + ok = + case filelib:is_regular(ZxMake) of + true -> + Out = os:cmd(ZxMake), + log(info, Out); + false -> + ok + end, + true = code:add_patha(filename:absname("ebin")), + up_to_date = make:all(), + ok. + + +-spec scrub(Deps) -> Scrubbed + when Deps :: [app_id()], + Scrubbed :: [app_id()]. +%% @private +%% Take a list of dependencies and return a list of dependencies that are not yet +%% installed on the system. + +scrub(Deps) -> + {ok, Names} = file:list_dir("lib"), + Existing = lists:map(fun appstring_to_appid/1, Names), + Need = ordsets:from_list(Deps), + Have = ordsets:from_list(Existing), + ordsets:to_list(ordsets:subtract(Need, Have)). + + + +%%% Input argument mangling + +-spec check_name(string()) -> string() | no_return(). +%% @private +%% Ensure that the name provided adheres to the rules: +%% Name must start with a character between and including `a' and `z' +%% Name can only include lowercase `a' through `z', numbers and underscores. +%% This function halts execution with an error message to STDOUT if an invalid string +%% is provided as an argument. + +check_name([Char | Rest]) + when $a =< Char, Char =< $z -> + case check_name(Rest, [Char]) of + {ok, Name} -> Name; + error -> error_exit("Bad name.", ?FILE, ?LINE) + end; +check_name(_) -> + error_exit("Bad name.", ?FILE, ?LINE). + + +-spec check_name(string(), list()) -> Result + when Result :: {ok, AppName :: string()} + | error. +%% @private +%% Does the work of checking whether the argument to check_name/1 is valid. + +check_name([Char | Rest], Acc) + when $a =< Char, Char =< $z; + $0 =< Char, Char =< $9; + Char == $_ -> + check_name(Rest, [Char | Acc]); +check_name("", Acc) -> + App = lists:reverse(Acc), + {ok, App}; +check_name(_, _) -> + error. + + +-spec check_version(string()) -> version() | no_return(). +%% @private +%% Checks that a version string is a valid string of the form `X.Y.Z'. Halts execution +%% on bad input after printing a message to STDOUT. + +check_version(String) -> + case string_to_version(String) of + {true, Version} -> Version; + false -> error_exit("Bad version ~tp", [String], ?FILE, ?LINE) + end. + + +-spec string_to_version(String) -> Result + when String :: string(), + Result :: {true, version()} + | false. +%% @private +%% @equiv string_to_version(string(), "", {z, z, z}) + +string_to_version(String) -> + string_to_version(String, "", {z, z, z}). + + +-spec string_to_version(String, Acc, Version) -> Result + when String :: string(), + Acc :: list(), + Version :: version(), + Result :: {true, version()} + | false. +%% @private +%% Accepts a full or partial version string of the form `X.Y.Z', `X.Y' or `X' and +%% returns an internal representation of the version indicated as `{true, Version}' or +%% `false'. The reason for this return type is to allow it to work smoothly with +%% functions from the `lists' module. + +string_to_version([Char | Rest], Acc, Version) when $0 =< Char andalso Char =< $9 -> + string_to_version(Rest, [Char | Acc], Version); +string_to_version([$.], _, _) -> + false; +string_to_version([$. | Rest], Acc, {z, z, z}) -> + X = list_to_integer(lists:reverse(Acc)), + string_to_version(Rest, "", {X, z, z}); +string_to_version([$. | Rest], Acc, {X, z, z}) -> + Y = list_to_integer(lists:reverse(Acc)), + string_to_version(Rest, "", {X, Y, z}); +string_to_version("", "", Version) -> + {true, Version}; +string_to_version([], Acc, {z, z, z}) -> + X = list_to_integer(lists:reverse(Acc)), + {true, {X, z, z}}; +string_to_version([], Acc, {X, z, z}) -> + Y = list_to_integer(lists:reverse(Acc)), + {true, {X, Y, z}}; +string_to_version([], Acc, {X, Y, z}) -> + Z = list_to_integer(lists:reverse(Acc)), + {true, {X, Y, Z}}; +string_to_version(_, _, _) -> + false. + + +-spec version_to_string(version()) -> string(). +%% @private +%% Inverse of string_to_version/3. + +version_to_string({z, z, z}) -> + ""; +version_to_string({X, z, z}) -> + integer_to_list(X); +version_to_string({X, Y, z}) -> + lists:flatten(lists:join($., [integer_to_list(Element) || Element <- [X, Y]])); +version_to_string({X, Y, Z}) -> + lists:flatten(lists:join($., [integer_to_list(Element) || Element <- [X, Y, Z]])). + + +-spec appstring_to_appid(string()) -> app_id(). +%% @private +%% Converts a proper appstring to an app_id(). +%% This function takes into account missing version elements. +%% Examples: +%% `{"foo", "bar", {1, 2, 3}} = appstring_to_appid("foo-bar-1.2.3")' +%% `{"foo", "bar", {1, 2, z}} = appstring_to_appid("foo-bar-1.2")' +%% `{"foo", "bar", {1, z, z}} = appstring_to_appid("foo-bar-1")' +%% `{"foo", "bar", {z, z, z}} = appstring_to_appid("foo-bar")' + +appstring_to_appid(String) -> + case string:lexemes(String, [$-]) of + [Realm, App, VersionString] -> + Realm = check_name(Realm), + App = check_name(App), + Version = check_version(VersionString), + {Realm, App, Version}; + [Realm, App] -> + Realm = check_name(Realm), + App = check_name(App), + {Realm, App, {z, z, z}}; + [App] -> + App = check_name(App), + {"otpr", App, {z, z, z}} + end. + + +-spec appid_to_appstring(app_id()) -> string(). +%% @private +%% Map an AppID to a correct string representation. +%% This function takes into account missing version elements. +%% Examples: +%% `"foo-bar-1.2.3" = appid_to_appstring({"foo", "bar", {1, 2, 3}})' +%% `"foo-bar-1.2" = appid_to_appstring({"foo", "bar", {1, 2, z}})' +%% `"foo-bar-1" = appid_to_appstring({"foo", "bar", {1, z, z}})' +%% `"foo-bar" = appid_to_appstring({"foo", "bar", {z, z, z}})' + +appid_to_appstring({Realm, App, {z, z, z}}) -> + lists:flatten(lists:join($-, [Realm, App])); +appid_to_appstring({Realm, App, Version}) -> + VersionString = version_to_string(Version), + lists:flatten(lists:join($-, [Realm, App, VersionString])). + + +-spec namify_zrp(AppID) -> ZrpFileName + when AppID :: app_id(), + ZrpFileName :: file:filename(). +%% @private +%% Map an AppID to its correct .zrp package file name. + +namify_zrp(AppID) -> namify(AppID, "zrp"). + + +-spec namify_tgz(AppID) -> TgzFileName + when AppID :: app_id(), + TgzFileName :: file:filename(). +%% @private +%% Map an AppID to its correct gzipped tarball source bundle filename. + +namify_tgz(AppID) -> namify(AppID, "tgz"). + + +-spec namify(AppID, Suffix) -> FileName + when AppID :: app_id(), + Suffix :: string(), + FileName :: file:filename(). +%% @private +%% Converts an AppID to a canonical string, then appends the provided filename Suffix. + +namify(AppID, Suffix) -> + AppString = appid_to_appstring(AppID), + AppString ++ "." ++ Suffix. + + + +%%% User menu interface (terminal) + + +-spec select(Options) -> Selected + when Options :: [option()], + Selected :: term(). +%% @private +%% Take a list of Options to present the user, then return the indicated option to the +%% caller once the user selects something. + +select(Options) -> + Max = show(Options), + case pick(string:to_integer(io:get_line("(or ^C to quit)~n ? ")), Max) of + error -> + ok = hurr(), + select(Options); + I -> + {_, Value} = lists:nth(I, Options), + Value + end. + + +-spec select_string(Strings) -> Selected + when Strings :: [string()], + Selected :: string(). +%% @private +%% @equiv select([{S, S} || S <- Strings]) + +select_string(Strings) -> + select([{S, S} || S <- Strings]). + + +-spec show(Options) -> Index + when Options :: [option()], + Index :: pos_integer(). +%% @private +%% @equiv show(Options, 0). + +show(Options) -> + show(Options, 0). + + +-spec show(Options, Index) -> Count + when Options :: [option()], + Index :: non_neg_integer(), + Count :: pos_integer(). +%% @private +%% Display the list of options needed to the user, and return the option total count. + +show([], I) -> + I; +show([{Label, _} | Rest], I) -> + Z = I + 1, + ok = io:format(" ~2w - ~ts~n", [Z, Label]), + show(Rest, Z). + + +-spec pick({Selection, term()}, Max) -> Result + when Selection :: error | integer(), + Max :: pos_integer(), + Result :: pos_integer() | error. +%% @private +%% Interpret a user's selection returning either a valid selection index or `error'. + +pick({error, _}, _) -> error; +pick({I, _}, Max) when 0 < I, I =< Max -> I; +pick(_, _) -> error. + + +-spec hurr() -> ok. +%% @private +%% Present an appropriate response when the user derps on selection. + +hurr() -> io:format("That isn't an option.~n"). + + + +%%% Directory Management + + +-spec ensure_zomp_home() -> ok. +%% @private +%% Ensure the zomp home directory exists and is populated. +%% Every entry function should run this initially. + +ensure_zomp_home() -> + ZompDir = zomp_dir(), + case filelib:is_dir(ZompDir) of + true -> + ok; + false -> + {ok, CWD} = file:get_cwd(), + force_dir(ZompDir), + ok = file:set_cwd(ZompDir), + SubDirs = ["tmp", "key", "var", "lib", "zrp", "etc"], + ok = lists:foreach(fun file:make_dir/1, SubDirs), + ok = write_terms(default_realm_file(), default_realm()), + ok = file:write_file(default_pubkey_file(), default_pubkey()), + ok = log(info, "Zomp userland directory initialized."), + file:set_cwd(CWD) + end. + + +-spec zomp_dir() -> file:filename(). +%% @private +%% Check the host OS and return the absolute path to the zomp filesystem root. + +zomp_dir() -> + case os:type() of + {unix, _} -> + Home = os:getenv("HOME"), + Dir = ".zomp", + filename:join(Home, Dir); + {win32, _} -> + Drive = os:getenv("HOMEDRIVE"), + Path = os:getenv("HOMEPATH"), + Dir = "zomp", + filename:join([Drive, Path, Dir]) + end. + + +-spec ensure_app_dirs(app_id()) -> ok. +%% @private +%% Procedure to guarantee that directory locations necessary for the indicated app to +%% run have been created or halt execution. + +ensure_app_dirs(AppID) -> + AppHome = app_home(AppID), + AppData = app_dir("var", AppID), + AppConf = app_dir("etc", AppID), + Dirs = [AppHome, AppData, AppConf], + ok = lists:foreach(fun force_dir/1, Dirs), + log(info, "Created dirs:~n\t~ts~n\t~ts~n\t~ts", Dirs). + + +-spec app_home(AppID) -> AppHome + when AppID :: app_id(), + AppHome :: file:filename(). +%% @private +%% Accept an AppID and return the installation directory for the indicated application. +%% NOTE: +%% This system does NOT anticipate symlinks of incomplete versions to their latest +%% installed version (for example, an incomplete `{1, 2, z}' resolving to a symlink +%% `lib/foo-bar-1.2' which is always updated to point to the latest version 1.2.x). + +app_home(AppID) -> + filename:join([zomp_dir(), "lib", appid_to_appstring(AppID)]). + + +-spec app_dir(Prefix, AppID) -> AppDataDir + when Prefix :: string(), + AppID :: app_id(), + AppDataDir :: file:filename(). +%% @private +%% Create an absolute path to an application directory prefixed by the inclued argument. + +app_dir(Prefix, {Realm, App, _}) -> + RealmApp = Realm ++ "-" ++ App, + filename:join([zomp_dir(), Prefix, RealmApp]). + + +-spec force_dir(Path) -> Result + when Path :: file:filename(), + Result :: ok + | {error, file:posix()}. +%% @private +%% Guarantee a directory path is created if it is possible to create or if it already +%% exists. + +force_dir(Path) -> + case filelib:is_dir(Path) of + true -> ok; + false -> filelib:ensure_dir(filename:join(Path, "foo")) + end. + + + +%%% Persistent Zomp State +%%% +%%% The following functions maintain constants or very light convenience functions +%%% that make use of system-wide constants such as the default realm name, default +%%% public key, and other data necessary to bootstrap the system. + + +-spec default_realm_file() -> RealmFileName + when RealmFileName :: file:filename(). +%% @private +%% Return the base filename of the default realm file. + +default_realm_file() -> + realm_file(default_realm_name()). + + +-spec default_realm_name() -> Name + when Name :: string(). +%% @private +%% Return the name of the default realm. + +default_realm_name() -> + "otpr". + + +-spec realm_file(Realm) -> RealmFileName + when Realm :: string(), + RealmFileName :: file:filename(). +%% @private +%% Take a realm name, and return the name of the realm filename that would result. + +realm_file(Realm) -> + Realm ++ ".realm". + + +-spec default_realm() -> RealmData + when RealmData :: [{atom(), term()}]. +%% @private +%% Returns the default realm file's data contents for the default "otpr" realm. + +default_realm() -> + [{name, "otpr"}, + {prime, {"repo.psychobitch.party", 11311}}, + {pubkey, default_pubkey_file()}, + {serial, 0}, + {mirrors, []}]. + + +-spec default_pubkey_file() -> file:filename(). +%% @private +%% Returns the default filename of the default public key. + +default_pubkey_file() -> + "key/otpr.1.pub.der". + + +-spec default_pubkey() -> binary(). +%% @private +%% This function stores the binary contents of the default public key in DER format. +%% Doing this in a function is essentially like using a herefile in Bash. + +default_pubkey() -> + <<1170526623609313331798826318972097080557896621948083159586373016346811570540623523814426011993490293167510658875163780852129579343891111576406428675491227868125570029553836721253582239727832008666977889522526670373902361492830918639140761847180559556687253204307494936306069307171528877400209962142787058308740221939755312361860413975531508150223291108422638532792576263104963638096818852870688582998502102536693308795214193253585166432265144396969870581676155216529809785753049835842318198805379857414606363727445230640910295705259948273015496668069952400995675937310182784823621435512613227257682702758407858036197683634666558131083559654726498186745235163628111760825026969986395769481087197994986427088838210048234736434112178729013032345213637282290815839027637504309538687095441687636356524193476275012030156571775013858217400602512194340193440681965829477411264954556799403863486012736713903706193506878410947578154040532592626008808497608835124296529017804159705286317715644155305350224257244260965453649874471033452253082499940845996170964558413968751507443986189697350023010630553524737002017543233621194508406455743465763341654345366274867913624544034721065244860576536017333528275040881674913063184272153529110886460286503455305330851192409414251325951739930514383412398798397169143552351929225078321776410580550088942920371869276662363003778677125037156672547734001647521245835866935294771855501141038223226549689862909953059166203977747766244019902323008152684587630882351278639697258019126733864910210128726118293540255959256597047563483255422642476502931615170150279457262340283463240052013184396583425577647694479205638188304711342708918448926127873312263215725459445847837288305565332375343953499300740443134048756072889091269830410360478466021318806219775513929766205963920179119585525683940978348051934951531003108279739296413836014878110298764281501544267131870022937730804080147990914120458451989661878314958524775077357936603530507381414681306510832486998678859256113064859502255575935373463709491675650991615474781558091560988205268798622776917923800097513069754689850980381850490662482961403587126912566501355644996590916922352735199214989138312856189875740424585814665007172318472691695957369820456341466786796592662135451831988129143024570641715114511174217352536557906484463741194647291182294337994718316817204867347695280457082728945911284833182013377663664430399865622471148347081767689841618546822415385957879982189694968028649835009229433349600455509536803831313830531746047425571328569634168722980491088303167148354034563578494773467308480373559768673286318322053544821433023042519594934353482721862948302631174310147010936830502360070216922584309962755494775082047690911998699570511078636376582952731884810583686700059291779239354983531555181641890341326596564548265142534064300496297926337825631921898202540803202984034394784105085299461195927463845508809485122164029528839799785844442443320039670416946533059409608926282019699119974258605650707621139750878861541251137000244133051922824004103328765954846809123299108643057388278106591988288588948726535195014652816533709432709443954841948958140326831643843906635067011302827793775757370405519240285135798743643797930642236731316466261629711900502696653563418054590076289653489719291121150266002099855392711464520928906433276097459061937053797457493166175864841786220404163949123451204756345296224150348843428777300804284267552332261715309580834396983346300530128191498649494481252342446265281499938013011901846865327797551832040198638001834019915656624142453248674154025598865589700532971711073725385563400552303085348956272116643141577079495146481883784661063082399836741351657205056526803513667042134368197760702297797779121467458147679998609606364108573808591354056588770173469993932525100580531597375569598234130308636537517111449993369547954653263045866310538500083896993112212303722148462970005994202673301481606806414256044693412925931019110552827804892050433228331280670562421203245853375417503339200768693046544396231856765919093252078432727627221414636522639011044239359484661269388619025699989119275623338551483041590123908337000853294371085777425084159087803966041644743349623092361390058115563570787103198976595362533473421958104661160820266906203090829648646902638295050336316799572281472144754384682003756790117478811155220025535420078485563985223415989335480370251115982845339833011445261624828025843177973576483738938303080242315615333593789609241843889852679993907685041671938947639167721054076202421174520920916996533102606039402530751673420224664619445635819542316713250359524898015718931583729548373297621243023115983588963506710418076848806241677618452223292483533560902680339825696167663170302616711331313490757011906928728140010004845723770802553281761773606296962670294026670439797097955228790673139658966545527614535446680187443733681726438681960897106751213102099950826404109307953852794370653372653043187474529370340385390651752792530497659674388660225:16496>>. + + + + +%%% Usage + + +-spec usage_exit(Code) -> no_return() + when Code :: integer(). +%% @private +%% A convenience function that will display the zx usage message before halting +%% with the provided exit code. + +usage_exit(Code) -> + ok = usage(), + halt(Code). + + +-spec usage() -> ok. +%% @private +%% Display the zx command line usage message. + +usage() -> + T = "~n" + "zx~n" + "~n" + "Usage:~n" + " zx help~n" + " zx run AppID [Args]~n" + " zx init Type AppID~n" + " zx install Package~n" + " zx set dep AppID~n" + " zx set version Version~n" + " zx drop dep AppID~n" + " zx drop key KeyID~n" + " zx verup Level~n" + " zx runlocal~n" + " zx package [Path]~n" + " zx submit Package~n" + " zx keygen~n" + " zx genplt~n" + "~n" + "Where~n" + " AppID :: A string of the form Realm-App-Version~n" + " Args :: Arguments to pass to the application~n" + " Package :: A .zrp package path/filename~n" + " Type :: The project type: a standalone \"app\" or a \"lib\"~n" + " Version :: Version string X, X.Y, or X.Y.Z: \"1\", \"1.2\", \"1.2.3\"~n" + " KeyID :: The prefix of a keypair to drop~n" + " Level :: The version level, one of \"major\", \"minor\", or \"patch\"~n" + " Path :: Path to a valid project directory~n" + "~n", + io:format(T). + + + +%%% Error exits + + +-spec error_exit(Error, Path, Line) -> no_return() + when Error :: term(), + Path :: file:filename(), + Line :: non_neg_integer(). +%% @private +%% Format an error message in a way that makes it easy to locate. + +error_exit(Error, Path, Line) -> + File = filename:basename(Path), + ok = log(error, "~ts:~tp: ~tp", [File, Line, Error]), + halt(1). + + +-spec error_exit(Format, Args, Path, Line) -> no_return() + when Format :: string(), + Args :: [term()], + Path :: file:filename(), + Line :: non_neg_integer(). +%% @private +%% Format an error message in a way that makes it easy to locate. + +error_exit(Format, Args, Path, Line) -> + File = filename:basename(Path), + ok = log(error, "~ts:~tp: " ++ Format, [File, Line | Args]), + halt(1). + + + +%%% Logger + +-spec log(Level, Format) -> ok + when Level :: info + | warning + | error, + Format :: string(). +%% @private +%% @equiv log(Level, Format, []) + +log(Level, Format) -> + log(Level, Format, []). + + +-spec log(Level, Format, Args) -> ok + when Level :: info + | warning + | error, + Format :: string(), + Args :: [term()]. +%% @private +%% A logging abstraction to hide whatever logging back end is actually in use. +%% Format must adhere to Erlang format string rules, and the arity of Args must match +%% the provided format. + +log(Level, Format, Args) -> + Tag = + case Level of + info -> "[INFO]"; + warning -> "[WARNING]"; + error -> "[ERROR]" + end, + io:format("~s ~p: " ++ Format ++ "~n", [Tag, self() | Args]). From fafea57954678dff5ea144f7472c3e9628313a29 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Mon, 6 Nov 2017 21:39:14 +0900 Subject: [PATCH 02/55] Adjust types --- zx | 894 +++++++++++++++++++++++++++++++------------------------------ 1 file changed, 453 insertions(+), 441 deletions(-) diff --git a/zx b/zx index 60bb198..e1a35e3 100755 --- a/zx +++ b/zx @@ -19,22 +19,29 @@ -record(s, {realm = "otpr" :: name(), - app = none :: none | name(), + name = none :: none | name(), version = {z, z, z} :: version(), pid = none :: none | pid(), mon = none :: none | reference()}). --type state() :: #s{}. --type name() :: string(). --type version() :: {Major :: z | non_neg_integer(), - Minor :: z | non_neg_integer(), - Patch :: z | non_neg_integer()}. --type app_id() :: {Realm :: name(), - App :: name(), - Version :: version()}. --type option() :: {string(), term()}. --type peer() :: {inet:hostname() | inet:ip_address(), inet:port_number()}. +-type state() :: #s{}. +%-type serial() :: pos_integer(). +-type package_id() :: {realm(), name(), version()}. +%-type package() :: {realm(), name()}. +-type realm() :: lower0_9(). +-type name() :: lower0_9(). +-type version() :: {Major :: non_neg_integer() | z, + Minor :: non_neg_integer() | z, + Patch :: non_neg_integer() | z}. +-type option() :: {string(), term()}. +-type host() :: {string() | inet:ip_address(), inet:port_number()}. +%-type keybin() :: {ID :: key_id(), +% Type :: public | private, +% DER :: binary()}. +-type key_id() :: {realm(), KeyName :: lower0_9()}. +-type lower0_9() :: [$a..$z | $0..$9 | $_]. +%-type label() :: [$a..$z | $0..$9 | $_ | $- | $.]. @@ -56,23 +63,23 @@ main(Args) -> start(["help"]) -> usage_exit(0); -start(["run", AppString | Args]) -> - execute(AppString, Args); -start(["init", "app", AppString]) -> - AppID = appstring_to_appid(AppString), - initialize(app, AppID); -start(["init", "lib", AppString]) -> - AppID = appstring_to_appid(AppString), - initialize(lib, AppID); +start(["run", PackageString | Args]) -> + execute(PackageString, Args); +start(["init", "app", PackageString]) -> + PackageID = package_id(PackageString), + initialize(app, PackageID); +start(["init", "lib", PackageString]) -> + PackageID = package_id(PackageString), + initialize(lib, PackageID); start(["install", PackageFile]) -> assimilate(PackageFile); -start(["set", "dep", AppString]) -> - set_dep(AppString); +start(["set", "dep", PackageString]) -> + set_dep(PackageString); start(["set", "version", VersionString]) -> set_version(VersionString); -start(["drop", "dep", AppString]) -> - AppID = appstring_to_appid(AppString), - drop_dep(AppID); +start(["drop", "dep", PackageString]) -> + PackageID = package_id(PackageString), + drop_dep(PackageID); start(["drop", "key", KeyID]) -> drop_key(KeyID); start(["verup", Level]) -> @@ -116,13 +123,13 @@ start(_) -> %% dependencies and run the program. This implies determining whether the program and %% its dependencies are installed, available, need to be downloaded, or are inaccessible %% given the current system condition (they could also be bogus, of course). The -%% Identifier provided should be a valid AppString of the form `realm-appname-version' +%% Identifier provided should be a valid PackageString of the form `realm-appname-version' %% where the realm and appname should follow standard realm and app package naming %% conventions and the version should be represented as a semver in string form (where %% ommitted elements of the version always default to whatever is most current). %% -%% Once the target program is running this process, which will run with the registered -%% name `vx' will sit in an `exec_wait' state, waiting for either a direct message from +%% Once the target program is running, this process, (which will run with the registered +%% name `zx') will sit in an `exec_wait' state, waiting for either a direct message from %% a child program or for calls made via vx_lib to assist in environment discovery. %% %% If there is a problem anywhere in the locationg, discovery, building, and loading @@ -131,35 +138,37 @@ start(_) -> execute(Identifier, Args) -> true = register(zx, self()), ok = inets:start(), - AppID = {Realm, App, Version} = appstring_to_appid(Identifier), + PackageID = {Realm, Name, Version} = package_id(Identifier), ok = file:set_cwd(zomp_dir()), - AppRoot = filename:join("lib", Identifier), - ok = ensure_installed(AppID), - {ok, Meta} = file:consult(filename:join(AppRoot, "zomp.meta")), + PackageRoot = filename:join("lib", Identifier), + ok = ensure_installed(PackageID), + {ok, Meta} = file:consult(filename:join(PackageRoot, "zomp.meta")), {deps, Deps} = lists:keyfind(deps, 1, Meta), - Required = [AppID | Deps], + Required = [PackageID | Deps], Needed = scrub(Required), - ok = fetch(Needed), + Host = {"localhost", 11411}, + Socket = connect(Host, user), + ok = fetch(Socket, Needed), ok = lists:foreach(fun install/1, Needed), ok = lists:foreach(fun build/1, Required), - ok = file:set_cwd(AppRoot), + ok = file:set_cwd(PackageRoot), case lists:keyfind(type, 1, Meta) of {type, app} -> - ok = log(info, "Starting ~ts", [appid_to_appstring(AppID)]), - AppMod = list_to_atom(App), - {ok, Pid} = AppMod:start(normal, Args), + ok = log(info, "Starting ~ts", [package_string(PackageID)]), + PackageMod = list_to_atom(Name), + {ok, Pid} = PackageMod:start(normal, Args), Mon = monitor(process, Pid), Shell = spawn(shell, start, []), ok = log(info, "Your shell is ~p, application is: ~p", [Shell, Pid]), State = #s{realm = Realm, - app = App, + name = Name, version = Version, pid = Pid, mon = Mon}, exec_wait(State); {type, lib} -> Message = "Lib ~ts is available on the system, but is not a standalone app.", - ok = log(info, Message, [appid_to_appstring(AppID)]), + ok = log(info, Message, [package_string(PackageID)]), halt(0) end. @@ -168,26 +177,26 @@ execute(Identifier, Args) -> %%% Project initialization --spec initialize(Type, AppID) -> no_return() - when Type :: app | lib, - AppID :: app_id(). +-spec initialize(Type, PackageID) -> no_return() + when Type :: app | lib, + PackageID :: package_id(). %% @private -%% Initialize an application in the local directory based on the AppID provided. +%% Initialize an application in the local directory based on the PackageID provided. %% This function does not care about the name of the current directory and leaves -%% providing a complete, proper and accurate AppID. +%% providing a complete, proper and accurate PackageID. %% This function will check the current `lib/' directory for zomp-style dependencies. %% If this is not the intended function or if there are non-compliant directory names %% in `lib/' then the project will need to be rearranged to become zomp compliant or %% the `deps' section of the resulting meta file will need to be manually updated. -initialize(Type, AppID) -> - AppString = appid_to_appstring(AppID), - ok = log(info, "Initializing ~s...", [AppString]), - Meta = [{app_id, AppID}, - {deps, []}, - {type, Type}], +initialize(Type, PackageID) -> + PackageString = package_string(PackageID), + ok = log(info, "Initializing ~s...", [PackageString]), + Meta = [{package_id, PackageID}, + {deps, []}, + {type, Type}], ok = write_terms("zomp.meta", Meta), - ok = log(info, "Project ~tp initialized.", [AppString]), + ok = log(info, "Project ~tp initialized.", [PackageString]), Message = "NOTICE:~n" " This project is currently listed as having no dependencies.~n" @@ -201,12 +210,12 @@ initialize(Type, AppID) -> %%% Add a package from a local file --spec assimilate(PackageFile) -> AppID +-spec assimilate(PackageFile) -> PackageID when PackageFile :: file:filename(), - AppID :: app_id(). + PackageID :: package_id(). %% @private %% Receives a path to a file containing package data, examines it, and copies it to a -%% canonical location under a canonical name, returning the AppID of the package +%% canonical location under a canonical name, returning the PackageID of the package %% contents. assimilate(PackageFile) -> @@ -215,23 +224,22 @@ assimilate(PackageFile) -> ok = file:set_cwd(zomp_dir()), {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), Meta = binary_to_term(MetaBin), - {package_id, AppID} = lists:keyfind(package_id, 1, Meta), - TgzFile = namify_tgz(AppID), + {package_id, PackageID} = lists:keyfind(package_id, 1, Meta), + TgzFile = namify_tgz(PackageID), {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files), {sig, {KeyID, Signature}} = lists:keyfind(sig, 1, Meta), - KeyFile = filename:join("key", KeyID), - {ok, PubKey} = loadkey(public, KeyFile), + {ok, PubKey} = loadkey(public, KeyID), ok = case public_key:verify(TgzData, sha512, Signature, PubKey) of true -> - ZrpPath = filename:join("zrp", namify_zrp(AppID)), + ZrpPath = filename:join("zrp", namify_zrp(PackageID)), erl_tar:create(ZrpPath, Files); false -> error_exit("Bad package signature: ~ts", [PackageFile], ?FILE, ?LINE) end, ok = file:set_cwd(CWD), Message = "~ts is now locally available.", - ok = log(info, Message, [appid_to_appstring(AppID)]), + ok = log(info, Message, [package_string(PackageID)]), halt(0). @@ -239,94 +247,94 @@ assimilate(PackageFile) -> %%% Set dependency --spec set_dep(AppString) -> no_return() - when AppString :: string(). +-spec set_dep(PackageString) -> no_return() + when PackageString :: string(). %% @private %% Set a specific dependency in the current project. If the project currently has a -%% dependency on the same Realm-App then the version of that dependency is updated to -%% reflect that in the AppString argument. The AppString is permitted to be incomplete. -%% Incomplete elements of the included VersionString (if included) will default to the -%% latest version available at the indicated level. +%% dependency on the same package then the version of that dependency is updated to +%% reflect that in the PackageString argument. The AppString is permitted to be +%% incomplete. Incomplete elements of the VersionString (if included) will default to +%% the latest version available at the indicated level. -set_dep(AppString) -> - AppID = appstring_to_appid(AppString), +set_dep(PackageString) -> + PackageID = package_id(PackageString), Meta = read_meta(), {deps, Deps} = lists:keyfind(deps, 1, Meta), - case lists:member(AppID, Deps) of + case lists:member(PackageID, Deps) of true -> - ok = log(info, "~ts is already a dependency", [AppString]), + ok = log(info, "~ts is already a dependency", [PackageString]), halt(0); false -> - set_dep(AppID, Deps, Meta) + set_dep(PackageID, Deps, Meta) end. --spec set_dep(AppID, Deps, Meta) -> no_return() - when AppID :: app_id(), - Deps :: [app_id()], - Meta :: [term()]. +-spec set_dep(PackageID, Deps, Meta) -> no_return() + when PackageID :: package_id(), + Deps :: [package_id()], + Meta :: [term()]. %% @private -%% Given the AppID, list of Deps and the current contents of the project Meta, add or -%% update Deps to include (or update) Deps to reflect a dependency on AppID, if such a -%% dependency is not already present. Then write the project meta back to its file and -%% exit. +%% Given the PackageID, list of Deps and the current contents of the project Meta, add +%% or update Deps to include (or update) Deps to reflect a dependency on PackageID, if +%% such a dependency is not already present. Then write the project meta back to its +%% file and exit. -set_dep(AppID = {Realm, App, NewVersion}, Deps, Meta) -> +set_dep(PackageID = {Realm, Name, NewVersion}, Deps, Meta) -> {ok, CWD} = file:get_cwd(), ok = file:set_cwd(zomp_dir()), - ok = ensure_installed(AppID), + ok = ensure_installed(PackageID), ok = file:set_cwd(CWD), - ExistingApp = fun ({R, A, _}) -> {R, A} == {Realm, App} end, + ExistingPackageIDs = fun ({R, N, _}) -> {R, N} == {Realm, Name} end, NewDeps = - case lists:partition(ExistingApp, Deps) of - {[{Realm, App, OldVersion}], Rest} -> + case lists:partition(ExistingPackageIDs, Deps) of + {[{Realm, Name, OldVersion}], Rest} -> Message = "Updating dep ~ts to ~ts", - OldAppString = appid_to_appstring({Realm, App, OldVersion}), - NewAppString = appid_to_appstring({Realm, App, NewVersion}), - ok = log(info, Message, [OldAppString, NewAppString]), - [AppID | Rest]; + OldPackageString = package_string({Realm, Name, OldVersion}), + NewPackageString = package_string({Realm, Name, NewVersion}), + ok = log(info, Message, [OldPackageString, NewPackageString]), + [PackageID | Rest]; {[], Deps} -> - ok = log(info, "Adding dep ~ts", [appid_to_appstring(AppID)]), - [AppID | Deps] + ok = log(info, "Adding dep ~ts", [package_string(PackageID)]), + [PackageID | Deps] end, NewMeta = lists:keystore(deps, 1, Meta, {deps, NewDeps}), ok = write_terms("zomp.meta", NewMeta), halt(0). --spec ensure_installed(app_id()) -> ok | no_return(). +-spec ensure_installed(package_id()) -> ok | no_return(). %% @private -%% Given an AppID, check whether it is installed on the system, and if not, ensure +%% Given a PackageID, check whether it is installed on the system, and if not, ensure %% that the package is either in the cache or can be downloaded. If all attempts at %% locating or acquiring the package fail, then exit with an error. -ensure_installed(AppID) -> - AppString = appid_to_appstring(AppID), - AppDir = filename:join("lib", AppString), - case filelib:is_dir(AppDir) of +ensure_installed(PackageID) -> + PackageString = package_string(PackageID), + PackageDir = filename:join("lib", PackageString), + case filelib:is_dir(PackageDir) of true -> ok; - false -> ensure_dep(AppID) + false -> ensure_dep(PackageID) end. --spec ensure_dep(app_id()) -> ok | no_return(). +-spec ensure_dep(package_id()) -> ok | no_return(). %% @private -%% Given an AppID as an argument, check whether its package file exists in the system -%% cache, and if not download it. Should return `ok' whenever the file is sourced, but -%% exit with an error if it cannot locate or acquire the package. +%% Given an PackageID as an argument, check whether its package file exists in the +%% system cache, and if not download it. Should return `ok' whenever the file is +%% sourced, but exit with an error if it cannot locate or acquire the package. -ensure_dep(AppID) -> - ZrpFile = filename:join("zrp", namify_zrp(AppID)), +ensure_dep(PackageID) -> + ZrpFile = filename:join("zrp", namify_zrp(PackageID)), ok = case filelib:is_regular(ZrpFile) of true -> ok; false -> - AppString = appid_to_appstring(AppID), - log(error, "Would fetch ~ts now, but not implemented", [AppString]), + PackageString = package_string(PackageID), + log(error, "Would fetch ~ts now, but not implemented", [PackageString]), halt(0) end, - install(AppID). + install(PackageID). @@ -341,7 +349,7 @@ ensure_dep(AppID) -> set_version(VersionString) -> NewVersion = - case check_version(VersionString) of + case string_to_version(VersionString) of {_, _, z} -> Message = "'set version' arguments must be complete, ex: 1.2.3", ok = log(error, Message), @@ -366,17 +374,17 @@ set_version(VersionString) -> update_version(Arg) -> Meta = read_meta(), - {app_id, AppID} = lists:keyfind(app_id, 1, Meta), - update_version(Arg, AppID, Meta). + {package_id, PackageID} = lists:keyfind(package_id, 1, Meta), + update_version(Arg, PackageID, Meta). --spec update_version(Level, AppID, Meta) -> no_return() - when Level :: major - | minor - | patch - | version(), - AppID :: app_id(), - Meta :: [{atom(), term()}]. +-spec update_version(Level, PackageID, Meta) -> no_return() + when Level :: major + | minor + | patch + | version(), + PackageID :: package_id(), + Meta :: [{atom(), term()}]. %% @private %% Update a project's `zomp.meta' file by either incrementing the indicated component, %% or setting the version number to the one specified in VersionString. @@ -384,22 +392,22 @@ update_version(Arg) -> %% convert the VersionString (if it is passed) to a `version()' type and check its %% validity (or halt if it is a bad string). -update_version(major, {Realm, App, OldVersion = {Major, _, _}}, OldMeta) -> +update_version(major, {Realm, Name, OldVersion = {Major, _, _}}, OldMeta) -> NewVersion = {Major + 1, 0, 0}, - update_version(Realm, App, OldVersion, NewVersion, OldMeta); -update_version(minor, {Realm, App, OldVersion = {Major, Minor, _}}, OldMeta) -> + update_version(Realm, Name, OldVersion, NewVersion, OldMeta); +update_version(minor, {Realm, Name, OldVersion = {Major, Minor, _}}, OldMeta) -> NewVersion = {Major, Minor + 1, 0}, - update_version(Realm, App, OldVersion, NewVersion, OldMeta); -update_version(patch, {Realm, App, OldVersion = {Major, Minor, Patch}}, OldMeta) -> + update_version(Realm, Name, OldVersion, NewVersion, OldMeta); +update_version(patch, {Realm, Name, OldVersion = {Major, Minor, Patch}}, OldMeta) -> NewVersion = {Major, Minor, Patch + 1}, - update_version(Realm, App, OldVersion, NewVersion, OldMeta); -update_version(NewVersion, {Realm, App, OldVersion}, OldMeta) -> - update_version(Realm, App, OldVersion, NewVersion, OldMeta). + update_version(Realm, Name, OldVersion, NewVersion, OldMeta); +update_version(NewVersion, {Realm, Name, OldVersion}, OldMeta) -> + update_version(Realm, Name, OldVersion, NewVersion, OldMeta). --spec update_version(Realm, App, OldVersion, NewVersion, OldMeta) -> no_return() - when Realm :: name(), - App :: name(), +-spec update_version(Realm, Name, OldVersion, NewVersion, OldMeta) -> no_return() + when Realm :: realm(), + Name :: name(), OldVersion :: version(), NewVersion :: version(), OldMeta :: [{atom(), term()}]. @@ -410,8 +418,9 @@ update_version(NewVersion, {Realm, App, OldVersion}, OldMeta) -> %% turns out to be possible. If successful it will indicate to the user what was %% changed. -update_version(Realm, App, OldVersion, NewVersion, OldMeta) -> - NewMeta = lists:keystore(app_id, 1, OldMeta, {app_id, {Realm, App, NewVersion}}), +update_version(Realm, Name, OldVersion, NewVersion, OldMeta) -> + PackageID = {Realm, Name, NewVersion}, + NewMeta = lists:keystore(package_id, 1, OldMeta, {package_id, PackageID}), ok = write_terms("zomp.meta", NewMeta), ok = log(info, "Version changed from ~s to ~s.", @@ -423,24 +432,24 @@ update_version(Realm, App, OldVersion, NewVersion, OldMeta) -> %%% Drop dependency --spec drop_dep(app_id()) -> no_return(). +-spec drop_dep(package_id()) -> no_return(). %% @private %% Remove the indicate dependency from the local project's zomp.meta record. -drop_dep(AppID) -> - AppString = appid_to_appstring(AppID), +drop_dep(PackageID) -> + PackageString = package_string(PackageID), Meta = read_meta(), {deps, Deps} = lists:keyfind(deps, 1, Meta), - case lists:member(AppID, Deps) of + case lists:member(PackageID, Deps) of true -> - NewDeps = lists:delete(AppID, Deps), + NewDeps = lists:delete(PackageID, Deps), NewMeta = lists:keystore(deps, 1, Meta, {deps, NewDeps}), ok = write_terms("zomp.meta", NewMeta), Message = "~ts removed from dependencies.", - ok = log(info, Message, [AppString]), + ok = log(info, Message, [PackageString]), halt(0); false -> - ok = log(info, "~ts not found in dependencies.", [AppString]), + ok = log(info, "~ts not found in dependencies.", [PackageString]), halt(0) end. @@ -449,24 +458,22 @@ drop_dep(AppID) -> %%% Drop key --spec drop_key(KeyID) -> no_return() - when KeyID :: file:filename(). +-spec drop_key(key_id()) -> no_return(). %% @private %% Given a KeyID, remove the related public and private keys from the keystore, if they %% exist. If not, exit with a message that no keys were found, but do not return an %% error exit value (this instruction is idempotent if used in shell scripts). -drop_key(KeyID) -> +drop_key({Realm, KeyName}) -> ok = file:set_cwd(zomp_dir()), - KeyDir = filename:join(zomp_dir(), "key"), - Pattern = KeyID ++ ".{key,pub}.der", - case filelib:wildcard(filename:join(KeyDir, Pattern)) of + Pattern = filename:join([zomp_dir(), "key", Realm, KeyName ++ ".{key,pub}.der"]), + case filelib:wildcard(Pattern) of [] -> - ok = log(warning, "KeyID ~ts not found", [KeyID]), + ok = log(warning, "Key ~ts/~ts not found", [Realm, KeyName]), halt(0); Files -> ok = lists:foreach(fun file:delete/1, Files), - ok = log(info, "Keyset ~ts removed", [KeyID]), + ok = log(info, "Keyset ~ts/~ts removed", [Realm, KeyName]), halt(0) end. @@ -504,33 +511,36 @@ run_local(Args) -> true = register(zx, self()), ok = inets:start(), {ok, ProjectRoot} = file:get_cwd(), - {ok, Meta} = file:consult("zomp.meta"), - {app_id, AppID = {Realm, App, Version}} = lists:keyfind(app_id, 1, Meta), + Meta = read_meta(), + {package_id, PackageID} = lists:keyfind(package_id, 1, Meta), + {Realm, Name, Version} = PackageID, ok = build(), ok = file:set_cwd(zomp_dir()), {deps, Deps} = lists:keyfind(deps, 1, Meta), Needed = scrub(Deps), - ok = fetch(Needed), + Host = {"localhost", 11411}, + Socket = connect(Host, user), + ok = fetch(Socket, Needed), ok = lists:foreach(fun install/1, Needed), ok = lists:foreach(fun build/1, Deps), ok = file:set_cwd(ProjectRoot), case lists:keyfind(type, 1, Meta) of {type, app} -> - ok = log(info, "Starting ~ts", [appid_to_appstring(AppID)]), - AppMod = list_to_atom(App), + ok = log(info, "Starting ~ts", [package_string(PackageID)]), + AppMod = list_to_atom(Name), {ok, Pid} = AppMod:start(normal, Args), Mon = monitor(process, Pid), Shell = spawn(shell, start, []), ok = log(info, "Your shell is ~p, application is: ~p", [Shell, Pid]), State = #s{realm = Realm, - app = App, + name = Name, version = Version, pid = Pid, mon = Mon}, exec_wait(State); {type, lib} -> Message = "Lib ~ts is available on the system, but is not a standalone app", - ok = log(info, Message, [appid_to_appstring(AppID)]), + ok = log(info, Message, [package_string(PackageID)]), halt(0) end. @@ -546,39 +556,41 @@ run_local(Args) -> package(TargetDir) -> ok = log(info, "Packaging ~ts", [TargetDir]), - KeyDir = filename:join(zomp_dir(), "key"), + {ok, Meta} = file:consult(filename:join(TargetDir, "zomp.meta")), + {package_id, {Realm, _, _}} = lists:keyfind(package_id, 1, Meta), + KeyDir = filename:join([zomp_dir(), "key", Realm]), ok = force_dir(KeyDir), Pattern = KeyDir ++ "/*.key.der", case [filename:basename(F, ".key.der") || F <- filelib:wildcard(Pattern)] of [] -> ok = log(info, "Need to generate key"), - KeyPrefix = prompt_keygen(KeyDir), - ok = generate_rsa(KeyPrefix), - package(KeyPrefix, TargetDir); - [KeyPrefix] -> - ok = log(info, "Using key: ~ts", [KeyPrefix]), - package(KeyPrefix, TargetDir); - KeyPrefixes -> - KeyPrefix = select_string(KeyPrefixes), - package(KeyPrefix, TargetDir) + KeyID = prompt_keygen(), + ok = generate_rsa(KeyID), + package(KeyID, TargetDir); + [KeyName] -> + KeyID = {Realm, KeyName}, + ok = log(info, "Using key: ~ts/~ts", [Realm, KeyName]), + package(KeyID, TargetDir); + KeyNames -> + KeyName = select_string(KeyNames), + package({Realm, KeyName}, TargetDir) end. --spec package(KeyPrefix, TargetDir) -> no_return() - when KeyPrefix :: string(), +-spec package(KeyID, TargetDir) -> no_return() + when KeyID :: key_id(), TargetDir :: file:filename(). %% @private %% Accept a KeyPrefix for signing and a TargetDir containing a project to package and %% build a zrp package file ready to be submitted to a repository. -package(KeyPrefix, TargetDir) -> - KeyID = KeyPrefix ++ ".key.der", - PubID = KeyPrefix ++ ".pub.der", +package(KeyID, TargetDir) -> {ok, Meta} = file:consult(filename:join(TargetDir, "zomp.meta")), - {app_id, AppID} = lists:keyfind(app_id, 1, Meta), - AppString = appid_to_appstring(AppID), - ZrpFile = AppString ++ ".zrp", - TgzFile = AppString ++ ".tgz", + {package_id, PackageID} = lists:keyfind(package_id, 1, Meta), + true = element(1, PackageID) == element(1, KeyID), + PackageString = package_string(PackageID), + ZrpFile = PackageString ++ ".zrp", + TgzFile = PackageString ++ ".tgz", ok = halt_if_exists(ZrpFile), ok = remove_binaries(TargetDir), {ok, Everything} = file:list_dir(TargetDir), @@ -587,13 +599,15 @@ package(KeyPrefix, TargetDir) -> Targets = lists:subtract(Everything, Ignores), {ok, CWD} = file:get_cwd(), ok = file:set_cwd(TargetDir), + ok = build(), + Modules = [filename:basename(M, ".beam") || M <- filelib:wildcard("*.beam", "ebin")], + ok = remove_binaries("."), ok = erl_tar:create(filename:join(CWD, TgzFile), Targets, [compressed]), ok = file:set_cwd(CWD), - KeyFile = filename:join([zomp_dir(), "key", KeyID]), - {ok, Key} = loadkey(private, KeyFile), + {ok, Key} = loadkey(private, KeyID), {ok, TgzBin} = file:read_file(TgzFile), Sig = public_key:sign(TgzBin, sha512, Key), - FinalMeta = [{sig, {PubID, Sig}} | Meta], + FinalMeta = [{modules, Modules}, {sig, {KeyID, Sig}} | Meta], ok = file:write_file("zomp.meta", term_to_binary(FinalMeta)), ok = erl_tar:create(ZrpFile, ["zomp.meta", TgzFile]), ok = file:delete(TgzFile), @@ -689,24 +703,23 @@ submit(PackageFile) -> {ok, PackageData} = file:read_file(PackageFile), {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), Meta = binary_to_term(MetaBin), - {app_id, {Realm, Package, Version}} = lists:keyfind(app_id, 1, Meta), - {sig, {PublicKeyFile, _}} = lists:keyfind(sig, 1, Meta), - KeyID = filename:rootname(PublicKeyFile, ".pub.der"), + {package_id, {Realm, Package, Version}} = lists:keyfind(package_id, 1, Meta), + {sig, {KeyID, _}} = lists:keyfind(sig, 1, Meta), true = ensure_keypair(KeyID), RealmData = realm_data(Realm), {prime, Prime} = lists:keyfind(prime, 1, RealmData), - Socket = connect(Prime), + Socket = connect(Prime, {auth, KeyID}), ok = send(Socket, {submit, {Realm, Package, Version}}), ok = receive - {tcp, Socket, Response} -> - case binary_to_term(Response, [safe]) of + {tcp, Socket, Response1} -> + case binary_to_term(Response1, [safe]) of ready -> ok; {error, Reason} -> ok = log(info, "Server refused with ~tp", [Reason]), halt(0) - end; + end after 5000 -> ok = log(warning, "Server timed out!"), halt(0) @@ -715,8 +728,8 @@ submit(PackageFile) -> ok = log(info, "Done sending contents of ~tp", [PackageFile]), ok = receive - {tcp, Socket, Response} -> - log(info, "Response: ~tp", [Response]); + {tcp, Socket, Response2} -> + log(info, "Response: ~tp", [Response2]); Other -> log(warning, "Unexpected message: ~tp", [Other]) after 5000 -> @@ -733,34 +746,56 @@ submit(PackageFile) -> %% Wrapper for the procedure necessary to send an internal message over the wire. send(Socket, Message) -> - BinMessage = term_to_binary(Message), - gen_tcp:send(Socket, Message). + Bin = term_to_binary(Message), + gen_tcp:send(Socket, Bin). --spec connect(peer()) -> inet:socket() | no_return(). +-spec connect(Node, Type) -> gen_tcp:socket() | no_return() + when Node :: host(), + Type :: user | {auth, key_id()}. %% @private %% Connect to one of the servers in the realm constellation. -connect({Host, Port}) -> +connect({Host, Port}, Type) -> Options = [{packet, 4}, {mode, binary}, {active, true}], case gen_tcp:connect(Host, Port, Options) of {ok, Socket} -> - confirm_server(Socket); + confirm_server(Socket, Type); {error, Error} -> ok = log(warning, "Connection problem: ~tp", [Error]), halt(0) end. --spec confirm_server(inet:socket()) -> inet:socket() | no_return(). +-spec confirm_server(Socket, Type) -> gen_tcp:socket() | no_return() + when Socket :: gen_tcp:socket(), + Type :: user | {auth, key_id()}. %% @private %% Send a protocol ID string to notify the server what we're up to, disconnect %% if it does not return an "OK" response within 5 seconds. -confirm_server(Socket) -> +confirm_server(Socket, user) -> {ok, {Addr, Port}} = inet:peername(Socket), Host = inet:ntoa(Addr), - ok = gen_tcp:send(Socket, <<"OTPR 1 CLIENT">>), + ok = gen_tcp:send(Socket, <<"OTPR USER 1">>), + receive + {tcp, Socket, <<"OK">>} -> + ok = log(info, "Connected to ~s:~p", [Host, Port]), + Socket; + Other -> + Message = "Unexpected response from ~s:~p:~n~tp", + ok = log(warning, Message, [Host, Port, Other]), + ok = disconnect(Socket), + halt(0) + after 5000 -> + ok = log(warning, "Host ~s:~p timed out.", [Host, Port]), + halt(0) + end; +confirm_server(Socket, {auth, KeyID}) -> + ok = log(info, "Would now be trying to connect as AUTH using ~tp", [KeyID]), + {ok, {Addr, Port}} = inet:peername(Socket), + Host = inet:ntoa(Addr), + ok = gen_tcp:send(Socket, <<"OTPR AUTH 1">>), receive {tcp, Socket, <<"OK">>} -> ok = log(info, "Connected to ~s:~p", [Host, Port]), @@ -776,7 +811,7 @@ confirm_server(Socket) -> end. --spec disconnect(inet:socket()) -> ok. +-spec disconnect(gen_tcp:socket()) -> ok. %% @private %% Gracefully shut down a socket, logging (but sidestepping) the case when the socket %% has already been closed by the other side. @@ -791,47 +826,46 @@ disconnect(Socket) -> end. --spec ensure_keypair(KeyID) -> true | no_return() - when KeyID :: string(). +-spec ensure_keypair(key_id()) -> true | no_return(). %% @private %% Check if both the public and private key based on KeyID exists. -ensure_keypair(KeyID) -> +ensure_keypair(KeyID = {Realm, KeyName}) -> case {have_public_key(KeyID), have_private_key(KeyID)} of {true, true} -> true; {false, true} -> - ok = log(error, "Public key for ~tp cannot be found", [KeyID]), + Message = "Public key for ~tp/~tp cannot be found", + ok = log(error, Message, [Realm, KeyName]), halt(1); {true, false} -> - ok = log(error, "Private key for ~tp cannot be found", [KeyID]), + Message = "Private key for ~tp/~tp cannot be found", + ok = log(error, Message, [Realm, KeyName]), halt(1); {false, false} -> - Message = "Key pair for ~tp cannot be found", - ok = log(error, Message, [KeyID]), + Message = "Key pair for ~tp/~tp cannot be found", + ok = log(error, Message, [Realm, KeyName]), halt(1) end. --spec have_public_key(KeyID) -> boolean() - when KeyID :: string(). +-spec have_public_key(key_id()) -> boolean(). %% @private %% Determine whether the public key indicated by KeyID is in the keystore. -have_public_key(KeyID) -> - PublicKeyFile = KeyID ++ ".pub.der", - PublicKeyPath = filename:join([zomp_dir(), "key", PublicKeyFile]), +have_public_key({Realm, KeyName}) -> + PublicKeyFile = KeyName ++ ".pub.der", + PublicKeyPath = filename:join([zomp_dir(), "key", Realm, PublicKeyFile]), filelib:is_regular(PublicKeyPath). --spec have_private_key(KeyID) -> boolean() - when KeyID :: string(). +-spec have_private_key(key_id()) -> boolean(). %% @private %% Determine whether the private key indicated by KeyID is in the keystore. -have_private_key(KeyID) -> - PrivateKeyFile = KeyID ++ ".key.der", - PrivateKeyPath = filename:join([zomp_dir(), "key", PrivateKeyFile]), +have_private_key({Realm, KeyName}) -> + PrivateKeyFile = KeyName ++ ".key.der", + PrivateKeyPath = filename:join([zomp_dir(), "key", Realm, PrivateKeyFile]), filelib:is_regular(PrivateKeyPath). @@ -844,7 +878,7 @@ have_private_key(KeyID) -> %% the file. realm_data(Realm) -> - RealmFile = filename:join([zomp_dir(), Realm ++ ".realm"]), + RealmFile = filename:join(zomp_dir(), Realm ++ ".realm"), case file:consult(RealmFile) of {ok, Data} -> Data; @@ -860,75 +894,43 @@ realm_data(Realm) -> %%% Key generation --spec prompt_keygen(KeyDir) -> KeyPrefix - when KeyDir :: file:filename(), - KeyPrefix :: string(). +-spec prompt_keygen() -> key_id(). %% @private %% Prompt the user for a valid KeyPrefix to use for naming a new RSA keypair. -prompt_keygen(KeyDir) -> +prompt_keygen() -> Message = " Enter a name for your new keys.~n" " Valid names must start with a lower-case letter, and can include~n" " only lower-case letters, numbers, and periods, but no series of~n" " consecutive periods.~n", ok = io:format(Message), - Input = io:get_line("(^C to quit): "), - case validate_prefix(Input) of - {ok, Value} -> - Value; - error -> - ok = io:format("Bad name. Try again.~n"), - prompt_keygen(KeyDir) + Input = string:trim(io:get_line("(^C to quit): ")), + {Realm, KeyName} = + case string:lexemes(Input, " ") of + [R, K] -> {R, K}; + [K] -> {"otpr", K} + end, + case {valid_lower0_9(Realm), valid_label(KeyName)} of + {true, true} -> + {Realm, KeyName}; + {false, _} -> + ok = io:format("Bad realm name ~tp. Try again.~n", [Realm]), + prompt_keygen(); + {true, false} -> + ok = io:format("Bad key name ~tp. Try again.~n", [KeyName]), + prompt_keygen() end. --spec validate_prefix(Prefix) -> {ok, Validated} | error - when Prefix :: string(), - Validated :: string(). -%% @private -%% Validate that a provided key prefix is legal according to the naming convention -%% provided in the prefix explanation prompt. - -validate_prefix([Char | Rest]) - when $a =< Char, Char =< $z -> - validate_prefix(Rest, Char, [Char]); -validate_prefix(_) -> - error. - - --spec validate_prefix(Prefix, Last, Accumulator) -> {ok, Validated} | error - when Prefix :: string(), - Last :: char(), - Accumulator :: [char()], - Validated :: string(). - -%% @private -%% Validate that a provided key prefix is legal according to the naming convention -%% provided in the prefix explanation prompt. - -validate_prefix([$. | _], $., _) -> - error; -validate_prefix([Char | Rest], _, Acc) - when $a =< Char, Char =< $z; - $0 =< Char, Char =< $9; - Char == $. -> - validate_prefix(Rest, Char, [Char | Acc]); -validate_prefix([$\n], _, Acc) -> - {ok, lists:reverse(Acc)}; -validate_prefix(_, _, _) -> - error. - - -spec keygen() -> no_return(). %% @private %% Execute the key generation procedure for 16k RSA keys once and then terminate. keygen() -> ok = file:set_cwd(zomp_dir()), - KeyDir = filename:join(zomp_dir(), "key"), - Prefix = prompt_keygen(KeyDir), - case generate_rsa(Prefix) of + KeyID = prompt_keygen(), + case generate_rsa(KeyID) of ok -> halt(0); Error -> @@ -936,8 +938,8 @@ keygen() -> end. --spec generate_rsa(Prefix) -> Result - when Prefix :: string(), +-spec generate_rsa(KeyID) -> Result + when KeyID :: key_id(), Result :: {ok, KeyFile, PubFile} | {error, keygen_fail}, KeyFile :: file:filename(), @@ -947,11 +949,12 @@ keygen() -> %% filenames derived from Prefix. %% NOTE: The current version of this command is likely to only work on a unix system. -generate_rsa(Prefix) -> - ZompDir = zomp_dir(), - PemFile = filename:join([ZompDir, "key", Prefix ++ ".pub.pem"]), - KeyFile = filename:join([ZompDir, "key", Prefix ++ ".key.der"]), - PubFile = filename:join([ZompDir, "key", Prefix ++ ".pub.der"]), +generate_rsa({Realm, KeyName}) -> + KeyDir = filename:join([zomp_dir(), "key", Realm]), + ok = force_dir(KeyDir), + PemFile = filename:join(KeyDir, KeyName ++ ".pub.pem"), + KeyFile = filename:join(KeyDir, KeyName ++ ".key.der"), + PubFile = filename:join(KeyDir, KeyName ++ ".pub.der"), ok = lists:foreach(fun halt_if_exists/1, [PemFile, KeyFile, PubFile]), ok = log(info, "Generating ~p and ~p. Please be patient...", [KeyFile, PubFile]), ok = gen_p_key(KeyFile), @@ -1057,7 +1060,7 @@ check_key(KeyFile, PubFile) -> openssl() -> OpenSSL = case os:type() of - {unix, _} -> "openssl"; + {unix, _} -> "openssl"; {win32, _} -> "openssl.exe" end, ok = @@ -1072,22 +1075,26 @@ openssl() -> OpenSSL. --spec loadkey(Type, File) -> Result - when Type :: private | public, - File :: file:filename(), - Result :: {ok, DecodedKey :: term()} - | {error, Reason :: term()}. +-spec loadkey(Type, KeyID) -> Result + when Type :: private | public, + KeyID :: key_id(), + Result :: {ok, DecodedKey :: term()} + | {error, Reason :: term()}. %% @private %% Hide the details behind reading and loading DER encoded RSA key files. -loadkey(Type, File) -> - DerType = +loadkey(Type, {Realm, KeyName}) -> + {DerType, Path} = case Type of - private -> 'RSAPrivateKey'; - public -> 'RSAPublicKey' + private -> + P = filename:join([zomp_dir(), "key", Realm, KeyName ++ "key.der"]), + {'RSAPrivateKey', P}; + public -> + P = filename:join([zomp_dir(), "key", Realm, KeyName ++ "pub.der"]), + {'RSAPublicKey', P} end, - ok = log(info, "Loading key from file ~ts", [File]), - case file:read_file(File) of + ok = log(info, "Loading key from file ~ts", [Path]), + case file:read_file(Path) of {ok, Bin} -> {ok, public_key:der_decode(DerType, Bin)}; Error -> Error end. @@ -1166,28 +1173,27 @@ dialyze() -> %%% Network operations and package utilities --spec install(app_id()) -> ok. +-spec install(package_id()) -> ok. %% @private %% Install a package from the cache into the local system. -install(AppID) -> - AppString = appid_to_appstring(AppID), - ok = log(info, "Installing ~ts", [AppString]), - ZrpFile = filename:join("zrp", namify_zrp(AppID)), +install(PackageID) -> + PackageString = package_string(PackageID), + ok = log(info, "Installing ~ts", [PackageString]), + ZrpFile = filename:join("zrp", namify_zrp(PackageID)), Files = extract_zrp(ZrpFile), - TgzFile = namify_tgz(AppID), + TgzFile = namify_tgz(PackageID), {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files), {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), Meta = binary_to_term(MetaBin), {sig, {KeyID, Signature}} = lists:keyfind(sig, 1, Meta), - KeyFile = filename:join("key", KeyID), - {ok, PubKey} = loadkey(public, KeyFile), - ok = ensure_app_dirs(AppID), - AppDir = filename:join("lib", AppString), - ok = force_dir(AppDir), + {ok, PubKey} = loadkey(public, KeyID), + ok = ensure_package_dirs(PackageID), + PackageDir = filename:join("lib", PackageString), + ok = force_dir(PackageDir), ok = verify(TgzData, Signature, PubKey), - ok = erl_tar:extract({binary, TgzData}, [compressed, {cwd, AppDir}]), - log(info, "~ts installed", [AppString]). + ok = erl_tar:extract({binary, TgzData}, [compressed, {cwd, PackageDir}]), + log(info, "~ts installed", [PackageString]). -spec extract_zrp(FileName) -> Files | no_return() @@ -1244,15 +1250,16 @@ verify(Data, Signature, PubKey) -> end. --spec fetch([app_id()]) -> ok. +-spec fetch(gen_tcp:socket(), [package_id()]) -> ok. %% @private %% Download a list of deps to the local package cache. -fetch(Needed) -> +fetch(Socket, Needed) -> Namified = lists:map(fun namify_zrp/1, Needed), {Have, Lack} = lists:partition(fun filelib:is_regular/1, Namified), ok = lists:foreach(fun(A) -> log(info, "Have ~ts", [A]) end, Have), ok = lists:foreach(fun(A) -> log(info, "Lack ~ts", [A]) end, Lack), + ok = send(Socket, "Would be sending fetch requests now."), log(info, "Done fake fetching"). @@ -1305,13 +1312,13 @@ write_terms(Filename, List) -> file:write_file(Filename, Text). --spec build(app_id()) -> ok. +-spec build(package_id()) -> ok. %% @private %% Given an AppID, build the project from source and add it to the current lib path. -build(AppID) -> +build(PackageID) -> {ok, CWD} = file:get_cwd(), - ok = file:set_cwd(app_home(AppID)), + ok = file:set_cwd(package_home(PackageID)), ok = build(), file:set_cwd(CWD). @@ -1338,15 +1345,15 @@ build() -> -spec scrub(Deps) -> Scrubbed - when Deps :: [app_id()], - Scrubbed :: [app_id()]. + when Deps :: [package_id()], + Scrubbed :: [package_id()]. %% @private %% Take a list of dependencies and return a list of dependencies that are not yet %% installed on the system. scrub(Deps) -> {ok, Names} = file:list_dir("lib"), - Existing = lists:map(fun appstring_to_appid/1, Names), + Existing = lists:map(fun package_id/1, Names), Need = ordsets:from_list(Deps), Have = ordsets:from_list(Existing), ordsets:to_list(ordsets:subtract(Need, Have)). @@ -1355,58 +1362,68 @@ scrub(Deps) -> %%% Input argument mangling --spec check_name(string()) -> string() | no_return(). -%% @private -%% Ensure that the name provided adheres to the rules: -%% Name must start with a character between and including `a' and `z' -%% Name can only include lowercase `a' through `z', numbers and underscores. -%% This function halts execution with an error message to STDOUT if an invalid string -%% is provided as an argument. -check_name([Char | Rest]) +-spec valid_lower0_9(string()) -> boolean(). +%% @private +%% Check whether a provided string is a valid lower0_9. + +valid_lower0_9([Char | Rest]) when $a =< Char, Char =< $z -> - case check_name(Rest, [Char]) of - {ok, Name} -> Name; - error -> error_exit("Bad name.", ?FILE, ?LINE) - end; -check_name(_) -> - error_exit("Bad name.", ?FILE, ?LINE). + valid_lower0_9(Rest, Char); +valid_lower0_9(_) -> + false. --spec check_name(string(), list()) -> Result - when Result :: {ok, AppName :: string()} - | error. +-spec valid_lower0_9(String, Last) -> boolean() + when String :: string(), + Last :: char(). + +valid_lower0_9([$_ | _], $_) -> + false; +valid_lower0_9([Char | Rest], _) + when $a =< Char, Char =< $z; + $0 =< Char, Char =< $9 -> + valid_lower0_9(Rest, Char); +valid_lower0_9([], _) -> + true; +valid_lower0_9(_, _) -> + false. + + +-spec valid_label(string()) -> boolean(). %% @private -%% Does the work of checking whether the argument to check_name/1 is valid. +%% Check whether a provided string is a valid label. -check_name([Char | Rest], Acc) +valid_label([Char | Rest]) + when $a =< Char, Char =< $z -> + valid_label(Rest, Char); +valid_label(_) -> + false. + + +-spec valid_label(String, Last) -> boolean() + when String :: string(), + Last :: char(). + +valid_label([$. | _], $.) -> + false; +valid_label([$_ | _], $_) -> + false; +valid_label([$- | _], $-) -> + false; +valid_label([Char | Rest], _) when $a =< Char, Char =< $z; $0 =< Char, Char =< $9; - Char == $_ -> - check_name(Rest, [Char | Acc]); -check_name("", Acc) -> - App = lists:reverse(Acc), - {ok, App}; -check_name(_, _) -> - error. + Char == $_; Char == $-; + Char == $. -> + valid_label(Rest, Char); +valid_label([], _) -> + true; +valid_label(_, _) -> + false. --spec check_version(string()) -> version() | no_return(). -%% @private -%% Checks that a version string is a valid string of the form `X.Y.Z'. Halts execution -%% on bad input after printing a message to STDOUT. - -check_version(String) -> - case string_to_version(String) of - {true, Version} -> Version; - false -> error_exit("Bad version ~tp", [String], ?FILE, ?LINE) - end. - - --spec string_to_version(String) -> Result - when String :: string(), - Result :: {true, version()} - | false. +-spec string_to_version(string()) -> version(). %% @private %% @equiv string_to_version(string(), "", {z, z, z}) @@ -1418,18 +1435,13 @@ string_to_version(String) -> when String :: string(), Acc :: list(), Version :: version(), - Result :: {true, version()} - | false. + Result :: version(). %% @private %% Accepts a full or partial version string of the form `X.Y.Z', `X.Y' or `X' and -%% returns an internal representation of the version indicated as `{true, Version}' or -%% `false'. The reason for this return type is to allow it to work smoothly with -%% functions from the `lists' module. +%% returns a zomp-type version tuple or crashes on bad data. string_to_version([Char | Rest], Acc, Version) when $0 =< Char andalso Char =< $9 -> string_to_version(Rest, [Char | Acc], Version); -string_to_version([$.], _, _) -> - false; string_to_version([$. | Rest], Acc, {z, z, z}) -> X = list_to_integer(lists:reverse(Acc)), string_to_version(Rest, "", {X, z, z}); @@ -1437,18 +1449,16 @@ string_to_version([$. | Rest], Acc, {X, z, z}) -> Y = list_to_integer(lists:reverse(Acc)), string_to_version(Rest, "", {X, Y, z}); string_to_version("", "", Version) -> - {true, Version}; + Version; string_to_version([], Acc, {z, z, z}) -> X = list_to_integer(lists:reverse(Acc)), - {true, {X, z, z}}; + {X, z, z}; string_to_version([], Acc, {X, z, z}) -> Y = list_to_integer(lists:reverse(Acc)), - {true, {X, Y, z}}; + {X, Y, z}; string_to_version([], Acc, {X, Y, z}) -> Z = list_to_integer(lists:reverse(Acc)), - {true, {X, Y, Z}}; -string_to_version(_, _, _) -> - false. + {X, Y, Z}. -spec version_to_string(version()) -> string(). @@ -1465,78 +1475,79 @@ version_to_string({X, Y, Z}) -> lists:flatten(lists:join($., [integer_to_list(Element) || Element <- [X, Y, Z]])). --spec appstring_to_appid(string()) -> app_id(). +-spec package_id(string()) -> package_id(). %% @private -%% Converts a proper appstring to an app_id(). +%% Converts a proper package_string to a package_id(). %% This function takes into account missing version elements. %% Examples: -%% `{"foo", "bar", {1, 2, 3}} = appstring_to_appid("foo-bar-1.2.3")' -%% `{"foo", "bar", {1, 2, z}} = appstring_to_appid("foo-bar-1.2")' -%% `{"foo", "bar", {1, z, z}} = appstring_to_appid("foo-bar-1")' -%% `{"foo", "bar", {z, z, z}} = appstring_to_appid("foo-bar")' +%% `{"foo", "bar", {1, 2, 3}} = package_id("foo-bar-1.2.3")' +%% `{"foo", "bar", {1, 2, z}} = package_id("foo-bar-1.2")' +%% `{"foo", "bar", {1, z, z}} = package_id("foo-bar-1")' +%% `{"foo", "bar", {z, z, z}} = package_id("foo-bar")' -appstring_to_appid(String) -> +package_id(String) -> case string:lexemes(String, [$-]) of - [Realm, App, VersionString] -> - Realm = check_name(Realm), - App = check_name(App), - Version = check_version(VersionString), - {Realm, App, Version}; - [Realm, App] -> - Realm = check_name(Realm), - App = check_name(App), - {Realm, App, {z, z, z}}; - [App] -> - App = check_name(App), - {"otpr", App, {z, z, z}} + [Realm, Name, VersionString] -> + true = valid_lower0_9(Realm), + true = valid_lower0_9(Name), + Version = string_to_version(VersionString), + {Realm, Name, Version}; + [Realm, Name] -> + true = valid_lower0_9(Realm), + true = valid_lower0_9(Name), + {Realm, Name, {z, z, z}}; + [Name] -> + true = valid_lower0_9(Name), + {"otpr", Name, {z, z, z}} end. --spec appid_to_appstring(app_id()) -> string(). +-spec package_string(package_id()) -> string(). %% @private -%% Map an AppID to a correct string representation. +%% Map an PackageID to a correct string representation. %% This function takes into account missing version elements. %% Examples: -%% `"foo-bar-1.2.3" = appid_to_appstring({"foo", "bar", {1, 2, 3}})' -%% `"foo-bar-1.2" = appid_to_appstring({"foo", "bar", {1, 2, z}})' -%% `"foo-bar-1" = appid_to_appstring({"foo", "bar", {1, z, z}})' -%% `"foo-bar" = appid_to_appstring({"foo", "bar", {z, z, z}})' +%% `"foo-bar-1.2.3" = package_string({"foo", "bar", {1, 2, 3}})' +%% `"foo-bar-1.2" = package_string({"foo", "bar", {1, 2, z}})' +%% `"foo-bar-1" = package_string({"foo", "bar", {1, z, z}})' +%% `"foo-bar" = package_string({"foo", "bar", {z, z, z}})' -appid_to_appstring({Realm, App, {z, z, z}}) -> - lists:flatten(lists:join($-, [Realm, App])); -appid_to_appstring({Realm, App, Version}) -> +package_string({Realm, Name, {z, z, z}}) -> + lists:flatten(lists:join($-, [Realm, Name])); +package_string({Realm, Name, Version}) -> VersionString = version_to_string(Version), - lists:flatten(lists:join($-, [Realm, App, VersionString])). + lists:flatten(lists:join($-, [Realm, Name, VersionString])). --spec namify_zrp(AppID) -> ZrpFileName - when AppID :: app_id(), +-spec namify_zrp(PackageID) -> ZrpFileName + when PackageID :: package_id(), ZrpFileName :: file:filename(). %% @private -%% Map an AppID to its correct .zrp package file name. +%% Map an PackageID to its correct .zrp package file name. -namify_zrp(AppID) -> namify(AppID, "zrp"). +namify_zrp(PackageID) -> namify(PackageID, "zrp"). --spec namify_tgz(AppID) -> TgzFileName - when AppID :: app_id(), +-spec namify_tgz(PackageID) -> TgzFileName + when PackageID :: package_id(), TgzFileName :: file:filename(). %% @private -%% Map an AppID to its correct gzipped tarball source bundle filename. +%% Map an PackageID to its correct gzipped tarball source bundle filename. -namify_tgz(AppID) -> namify(AppID, "tgz"). +namify_tgz(PackageID) -> namify(PackageID, "tgz"). --spec namify(AppID, Suffix) -> FileName - when AppID :: app_id(), - Suffix :: string(), - FileName :: file:filename(). +-spec namify(PackageID, Suffix) -> FileName + when PackageID :: package_id(), + Suffix :: string(), + FileName :: file:filename(). %% @private -%% Converts an AppID to a canonical string, then appends the provided filename Suffix. +%% Converts an PackageID to a canonical string, then appends the provided +%% filename Suffix. -namify(AppID, Suffix) -> - AppString = appid_to_appstring(AppID), - AppString ++ "." ++ Suffix. +namify(PackageID, Suffix) -> + PackageString = package_string(PackageID), + PackageString ++ "." ++ Suffix. @@ -1661,44 +1672,45 @@ zomp_dir() -> end. --spec ensure_app_dirs(app_id()) -> ok. +-spec ensure_package_dirs(package_id()) -> ok. %% @private %% Procedure to guarantee that directory locations necessary for the indicated app to %% run have been created or halt execution. -ensure_app_dirs(AppID) -> - AppHome = app_home(AppID), - AppData = app_dir("var", AppID), - AppConf = app_dir("etc", AppID), - Dirs = [AppHome, AppData, AppConf], +ensure_package_dirs(PackageID) -> + PackageHome = package_home(PackageID), + PackageData = package_dir("var", PackageID), + PackageConf = package_dir("etc", PackageID), + Dirs = [PackageHome, PackageData, PackageConf], ok = lists:foreach(fun force_dir/1, Dirs), log(info, "Created dirs:~n\t~ts~n\t~ts~n\t~ts", Dirs). --spec app_home(AppID) -> AppHome - when AppID :: app_id(), - AppHome :: file:filename(). +-spec package_home(PackageID) -> PackageHome + when PackageID :: package_id(), + PackageHome :: file:filename(). %% @private -%% Accept an AppID and return the installation directory for the indicated application. +%% Accept an PackageID and return the installation directory for the indicated +%% application. %% NOTE: %% This system does NOT anticipate symlinks of incomplete versions to their latest %% installed version (for example, an incomplete `{1, 2, z}' resolving to a symlink %% `lib/foo-bar-1.2' which is always updated to point to the latest version 1.2.x). -app_home(AppID) -> - filename:join([zomp_dir(), "lib", appid_to_appstring(AppID)]). +package_home(PackageID) -> + filename:join([zomp_dir(), "lib", package_string(PackageID)]). --spec app_dir(Prefix, AppID) -> AppDataDir - when Prefix :: string(), - AppID :: app_id(), - AppDataDir :: file:filename(). +-spec package_dir(Prefix, PackageID) -> PackageDataDir + when Prefix :: string(), + PackageID :: package_id(), + PackageDataDir :: file:filename(). %% @private %% Create an absolute path to an application directory prefixed by the inclued argument. -app_dir(Prefix, {Realm, App, _}) -> - RealmApp = Realm ++ "-" ++ App, - filename:join([zomp_dir(), Prefix, RealmApp]). +package_dir(Prefix, {Realm, Name, _}) -> + PackageName = Realm ++ "-" ++ Name, + filename:join([zomp_dir(), Prefix, PackageName]). -spec force_dir(Path) -> Result @@ -1807,30 +1819,30 @@ usage() -> "zx~n" "~n" "Usage:~n" - " zx help~n" - " zx run AppID [Args]~n" - " zx init Type AppID~n" - " zx install Package~n" - " zx set dep AppID~n" - " zx set version Version~n" - " zx drop dep AppID~n" - " zx drop key KeyID~n" - " zx verup Level~n" - " zx runlocal~n" - " zx package [Path]~n" - " zx submit Package~n" - " zx keygen~n" - " zx genplt~n" + " zx help~n" + " zx run PackageID [Args]~n" + " zx init Type PackageID~n" + " zx install PackageID~n" + " zx set dep PackageID~n" + " zx set version Version~n" + " zx drop dep PackageID~n" + " zx drop key Realm KeyName~n" + " zx verup Level~n" + " zx runlocal~n" + " zx package [Path]~n" + " zx submit Path~n" + " zx keygen~n" + " zx genplt~n" "~n" "Where~n" - " AppID :: A string of the form Realm-App-Version~n" - " Args :: Arguments to pass to the application~n" - " Package :: A .zrp package path/filename~n" - " Type :: The project type: a standalone \"app\" or a \"lib\"~n" - " Version :: Version string X, X.Y, or X.Y.Z: \"1\", \"1.2\", \"1.2.3\"~n" - " KeyID :: The prefix of a keypair to drop~n" - " Level :: The version level, one of \"major\", \"minor\", or \"patch\"~n" - " Path :: Path to a valid project directory~n" + " PackageID :: A string of the form Realm-Name[-Version]~n" + " Args :: Arguments to pass to the application~n" + " Type :: The project type: a standalone \"app\" or a \"lib\"~n" + " Version :: Version string X, X.Y, or X.Y.Z: \"1\", \"1.2\", \"1.2.3\"~n" + " Realm :: The name of a realm as a string [:a-z:]~n" + " KeyName :: The prefix of a keypair to drop~n" + " Level :: The version level, one of \"major\", \"minor\", or \"patch\"~n" + " Path :: Path to a valid project directory or .zrp file~n" "~n", io:format(T). From 34656bef64ca523f34fc3b5dd8094c62342b5b66 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Tue, 14 Nov 2017 08:05:24 +0900 Subject: [PATCH 03/55] messy --- zx | 433 +++++++++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 318 insertions(+), 115 deletions(-) diff --git a/zx b/zx index e1a35e3..4573149 100755 --- a/zx +++ b/zx @@ -21,6 +21,10 @@ {realm = "otpr" :: name(), name = none :: none | name(), version = {z, z, z} :: version(), + type = app :: app | lib + deps = [] :: [package_id()], + dir = none :: none | file:filename(), + socket = none :: none | gen_tcp:socket(), pid = none :: none | pid(), mon = none :: none | reference()}). @@ -39,7 +43,8 @@ %-type keybin() :: {ID :: key_id(), % Type :: public | private, % DER :: binary()}. --type key_id() :: {realm(), KeyName :: lower0_9()}. +-type key_id() :: {realm(), key_name()}. +-type key_name() :: lower0_9(). -type lower0_9() :: [$a..$z | $0..$9 | $_]. %-type label() :: [$a..$z | $0..$9 | $_ | $- | $.]. @@ -64,7 +69,7 @@ main(Args) -> start(["help"]) -> usage_exit(0); start(["run", PackageString | Args]) -> - execute(PackageString, Args); + run(PackageString, Args); start(["init", "app", PackageString]) -> PackageID = package_id(PackageString), initialize(app, PackageID); @@ -84,9 +89,7 @@ start(["drop", "key", KeyID]) -> drop_key(KeyID); start(["verup", Level]) -> verup(Level); -start(["runlocal"]) -> - run_local([]); -start(["runlocal", Args]) -> +start(["runlocal" | Args]) -> run_local(Args); start(["package"]) -> {ok, TargetDir} = file:get_cwd(), @@ -115,7 +118,7 @@ start(_) -> %%% Execution of application --spec execute(Identifier, Args) -> no_return() +-spec run(Identifier, Args) -> no_return() when Identifier :: string(), Args :: [string()]. %% @private @@ -123,7 +126,7 @@ start(_) -> %% dependencies and run the program. This implies determining whether the program and %% its dependencies are installed, available, need to be downloaded, or are inaccessible %% given the current system condition (they could also be bogus, of course). The -%% Identifier provided should be a valid PackageString of the form `realm-appname-version' +%% Identifier should be a valid PackageString of the form `realm-appname-version' %% where the realm and appname should follow standard realm and app package naming %% conventions and the version should be represented as a semver in string form (where %% ommitted elements of the version always default to whatever is most current). @@ -135,15 +138,21 @@ start(_) -> %% If there is a problem anywhere in the locationg, discovery, building, and loading %% procedure the runtime will halt with an error message. -execute(Identifier, Args) -> - true = register(zx, self()), - ok = inets:start(), +run(Identifier, Args) -> PackageID = {Realm, Name, Version} = package_id(Identifier), ok = file:set_cwd(zomp_dir()), PackageRoot = filename:join("lib", Identifier), - ok = ensure_installed(PackageID), - {ok, Meta} = file:consult(filename:join(PackageRoot, "zomp.meta")), - {deps, Deps} = lists:keyfind(deps, 1, Meta), + State = #s{realm = Realm, + name = Name, + version = Version, + dir = PackageRoot}, + NextState = ensure_installed(State), + Meta = read_meta(PackageRoot), + Deps = maps:get(deps, Meta), + NewState = ensure_deps(NextState#s{deps = Deps}), + execute(State). + + Required = [PackageID | Deps], Needed = scrub(Required), Host = {"localhost", 11411}, @@ -152,8 +161,10 @@ execute(Identifier, Args) -> ok = lists:foreach(fun install/1, Needed), ok = lists:foreach(fun build/1, Required), ok = file:set_cwd(PackageRoot), - case lists:keyfind(type, 1, Meta) of - {type, app} -> + case maps:get(type, Meta) of + app -> + true = register(zx, self()), + ok = inets:start(), ok = log(info, "Starting ~ts", [package_string(PackageID)]), PackageMod = list_to_atom(Name), {ok, Pid} = PackageMod:start(normal, Args), @@ -166,7 +177,7 @@ execute(Identifier, Args) -> pid = Pid, mon = Mon}, exec_wait(State); - {type, lib} -> + lib -> Message = "Lib ~ts is available on the system, but is not a standalone app.", ok = log(info, Message, [package_string(PackageID)]), halt(0) @@ -195,7 +206,7 @@ initialize(Type, PackageID) -> Meta = [{package_id, PackageID}, {deps, []}, {type, Type}], - ok = write_terms("zomp.meta", Meta), + ok = write_meta(Meta), ok = log(info, "Project ~tp initialized.", [PackageString]), Message = "NOTICE:~n" @@ -224,10 +235,10 @@ assimilate(PackageFile) -> ok = file:set_cwd(zomp_dir()), {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), Meta = binary_to_term(MetaBin), - {package_id, PackageID} = lists:keyfind(package_id, 1, Meta), + PackageID = maps:get(package_id, Meta), TgzFile = namify_tgz(PackageID), {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files), - {sig, {KeyID, Signature}} = lists:keyfind(sig, 1, Meta), + {KeyID, Signature} = maps:get(sig, Meta), {ok, PubKey} = loadkey(public, KeyID), ok = case public_key:verify(TgzData, sha512, Signature, PubKey) of @@ -259,7 +270,7 @@ assimilate(PackageFile) -> set_dep(PackageString) -> PackageID = package_id(PackageString), Meta = read_meta(), - {deps, Deps} = lists:keyfind(deps, 1, Meta), + Deps = maps:get(deps, Meta), case lists:member(PackageID, Deps) of true -> ok = log(info, "~ts is already a dependency", [PackageString]), @@ -279,11 +290,9 @@ set_dep(PackageString) -> %% such a dependency is not already present. Then write the project meta back to its %% file and exit. -set_dep(PackageID = {Realm, Name, NewVersion}, Deps, Meta) -> +set_dep(PackageID = {Realm, Name, Version}, Deps, Meta) -> {ok, CWD} = file:get_cwd(), - ok = file:set_cwd(zomp_dir()), - ok = ensure_installed(PackageID), - ok = file:set_cwd(CWD), + LatestVersion = latest_version(PackageID), ExistingPackageIDs = fun ({R, N, _}) -> {R, N} == {Realm, Name} end, NewDeps = case lists:partition(ExistingPackageIDs, Deps) of @@ -297,18 +306,37 @@ set_dep(PackageID = {Realm, Name, NewVersion}, Deps, Meta) -> ok = log(info, "Adding dep ~ts", [package_string(PackageID)]), [PackageID | Deps] end, - NewMeta = lists:keystore(deps, 1, Meta, {deps, NewDeps}), - ok = write_terms("zomp.meta", NewMeta), + NewMeta = maps:put(deps, NewDeps, Meta), + ok = write_meta(NewMeta), halt(0). --spec ensure_installed(package_id()) -> ok | no_return(). +-spec latest_version(package_id()) -> version(). +%% @private +%% Query the relevant realm for the latest version of a given package. + +latest_version({Realm, Name, Version}) -> + Socket = connect(Realm), + ok = send(Socket, {latest, Realm, Name, Version}), + Response = + receive + {tcp, Socket, Bin} -> binary_to_term(Bin, [safe]) + after 5000 -> {error, timeout} + end, + ok = disconnect(Socket). + + +-spec ensure_installed(State) -> NewState | no_return() + when State :: state(), + NewState :: state(). %% @private %% Given a PackageID, check whether it is installed on the system, and if not, ensure %% that the package is either in the cache or can be downloaded. If all attempts at %% locating or acquiring the package fail, then exit with an error. -ensure_installed(PackageID) -> +ensure_installed(State = #s{realm = Realm, name = Name, version = Version}) -> + % If the startup style is to always check first, match for the exact version, + % If the startup style is to run a matching latest and then check PackageString = package_string(PackageID), PackageDir = filename:join("lib", PackageString), case filelib:is_dir(PackageDir) of @@ -421,7 +449,7 @@ update_version(NewVersion, {Realm, Name, OldVersion}, OldMeta) -> update_version(Realm, Name, OldVersion, NewVersion, OldMeta) -> PackageID = {Realm, Name, NewVersion}, NewMeta = lists:keystore(package_id, 1, OldMeta, {package_id, PackageID}), - ok = write_terms("zomp.meta", NewMeta), + ok = write_meta(NewMeta), ok = log(info, "Version changed from ~s to ~s.", [version_to_string(OldVersion), version_to_string(NewVersion)]), @@ -444,7 +472,7 @@ drop_dep(PackageID) -> true -> NewDeps = lists:delete(PackageID, Deps), NewMeta = lists:keystore(deps, 1, Meta, {deps, NewDeps}), - ok = write_terms("zomp.meta", NewMeta), + ok = write_meta(NewMeta), Message = "~ts removed from dependencies.", ok = log(info, Message, [PackageString]), halt(0); @@ -508,15 +536,51 @@ verup(_) -> usage_exit(22). %% and use zx commands to add or drop dependencies made available via zomp. run_local(Args) -> - true = register(zx, self()), - ok = inets:start(), - {ok, ProjectRoot} = file:get_cwd(), Meta = read_meta(), {package_id, PackageID} = lists:keyfind(package_id, 1, Meta), {Realm, Name, Version} = PackageID, - ok = build(), - ok = file:set_cwd(zomp_dir()), + {type, Type} = lists:keyfind(type, 1, Meta), {deps, Deps} = lists:keyfind(deps, 1, Meta), + ok = build(), + {ok, Dir} = file:get_cwd(), + ok = file:set_cwd(zomp_dir()), + State = #s{realm = Realm, + name = Name, + version = Version, + type = Type, + deps = Deps, + dir = Dir}, + NewState = ensure_deps(State), + execute(State). + + +ensure_deps(Deps, State) -> + + execute(State). + + +execute(State = #s{type = app}) -> + true = register(zx, self()), + ok = inets:start(), + ok = log(info, "Starting ~ts", [package_string(PackageID)]), + AppMod = list_to_atom(Name), + {ok, Pid} = AppMod:start(normal, Args), + Mon = monitor(process, Pid), + Shell = spawn(shell, start, []), + ok = log(info, "Your shell is ~p, application is: ~p", [Shell, Pid]), + State = #s{realm = Realm, + name = Name, + version = Version, + pid = Pid, + mon = Mon}, + exec_wait(State); +execute(State = #s{type = lib}) -> + Message = "Lib ~ts is available on the system, but is not a standalone app", + ok = log(info, Message, [package_string(PackageID)]), + halt(0). + + + Needed = scrub(Deps), Host = {"localhost", 11411}, Socket = connect(Host, user), @@ -524,25 +588,6 @@ run_local(Args) -> ok = lists:foreach(fun install/1, Needed), ok = lists:foreach(fun build/1, Deps), ok = file:set_cwd(ProjectRoot), - case lists:keyfind(type, 1, Meta) of - {type, app} -> - ok = log(info, "Starting ~ts", [package_string(PackageID)]), - AppMod = list_to_atom(Name), - {ok, Pid} = AppMod:start(normal, Args), - Mon = monitor(process, Pid), - Shell = spawn(shell, start, []), - ok = log(info, "Your shell is ~p, application is: ~p", [Shell, Pid]), - State = #s{realm = Realm, - name = Name, - version = Version, - pid = Pid, - mon = Mon}, - exec_wait(State); - {type, lib} -> - Message = "Lib ~ts is available on the system, but is not a standalone app", - ok = log(info, Message, [package_string(PackageID)]), - halt(0) - end. @@ -556,7 +601,7 @@ run_local(Args) -> package(TargetDir) -> ok = log(info, "Packaging ~ts", [TargetDir]), - {ok, Meta} = file:consult(filename:join(TargetDir, "zomp.meta")), + Meta = read_meta(TargetDir), {package_id, {Realm, _, _}} = lists:keyfind(package_id, 1, Meta), KeyDir = filename:join([zomp_dir(), "key", Realm]), ok = force_dir(KeyDir), @@ -585,7 +630,7 @@ package(TargetDir) -> %% build a zrp package file ready to be submitted to a repository. package(KeyID, TargetDir) -> - {ok, Meta} = file:consult(filename:join(TargetDir, "zomp.meta")), + Meta = read_meta(TargetDir), {package_id, PackageID} = lists:keyfind(package_id, 1, Meta), true = element(1, PackageID) == element(1, KeyID), PackageString = package_string(PackageID), @@ -704,11 +749,9 @@ submit(PackageFile) -> {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), Meta = binary_to_term(MetaBin), {package_id, {Realm, Package, Version}} = lists:keyfind(package_id, 1, Meta), - {sig, {KeyID, _}} = lists:keyfind(sig, 1, Meta), + {sig, {KeyID = {Realm, KeyName}, _}} = lists:keyfind(sig, 1, Meta), true = ensure_keypair(KeyID), - RealmData = realm_data(Realm), - {prime, Prime} = lists:keyfind(prime, 1, RealmData), - Socket = connect(Prime, {auth, KeyID}), + {ok, Socket = connect_auth(Realm, KeyName), ok = send(Socket, {submit, {Realm, Package, Version}}), ok = receive @@ -730,8 +773,6 @@ submit(PackageFile) -> receive {tcp, Socket, Response2} -> log(info, "Response: ~tp", [Response2]); - Other -> - log(warning, "Unexpected message: ~tp", [Other]) after 5000 -> log(warning, "Server timed out!") end, @@ -750,67 +791,196 @@ send(Socket, Message) -> gen_tcp:send(Socket, Bin). --spec connect(Node, Type) -> gen_tcp:socket() | no_return() - when Node :: host(), - Type :: user | {auth, key_id()}. +-spec connect_user(realm()) -> gen_tcp:socket() | no_return(). %% @private -%% Connect to one of the servers in the realm constellation. +%% Connect to a given realm, whatever method is required. -connect({Host, Port}, Type) -> - Options = [{packet, 4}, {mode, binary}, {active, true}], - case gen_tcp:connect(Host, Port, Options) of +connect_user(Realm) -> + Hosts = + case file:consult(hosts_cache_file(Realm)) of + {ok, Cached} -> Cached; + {error, enoent} -> [] + end, + connect_user(Realm, Hosts). + + +-spec connect_user(realm(), [host()]) -> gen_tcp:socket() | no_return(). +%% @private +%% Try to connect to a subordinate host, if there are none then connect to prime. + +connect_user(Realm, []) -> + {Host, Port} = get_prime(Realm), + case gen_tcp:connect(Host, Port, connect_options(), 5000) of {ok, Socket} -> - confirm_server(Socket, Type); + confirm_user(Realm, Socket, []); {error, Error} -> - ok = log(warning, "Connection problem: ~tp", [Error]), + ok = log(warning, "Connection problem with prime: ~tp", [Error]), halt(0) + end; +connect_user(Realm, Hosts = [Node = {Host, Port} | Rest]) -> + case gen_tcp:connect(Host, Port, connect_options(), 5000) of + {ok, Socket} -> + confirm_user(Realm, Socket, Hosts); + {error, Error} -> + ok = log(warning, "Connection problem with ~tp: ~tp", [Node, Error]), + connect_user(Realm, Rest) end. --spec confirm_server(Socket, Type) -> gen_tcp:socket() | no_return() - when Socket :: gen_tcp:socket(), - Type :: user | {auth, key_id()}. +-spec confirm_user(Realm, Socket, Hosts) -> Socket | no_return() + when Realm :: realm(), + Socket :: gen_tcp:socket(), + Hosts :: [host()]. %% @private -%% Send a protocol ID string to notify the server what we're up to, disconnect -%% if it does not return an "OK" response within 5 seconds. +%% Confirm the zomp node can handle "OTPR USER 1" and is accepting connections or try another node. -confirm_server(Socket, user) -> +confirm_user(Realm, Socket, Hosts) -> {ok, {Addr, Port}} = inet:peername(Socket), Host = inet:ntoa(Addr), ok = gen_tcp:send(Socket, <<"OTPR USER 1">>), receive - {tcp, Socket, <<"OK">>} -> - ok = log(info, "Connected to ~s:~p", [Host, Port]), - Socket; - Other -> - Message = "Unexpected response from ~s:~p:~n~tp", - ok = log(warning, Message, [Host, Port, Other]), - ok = disconnect(Socket), - halt(0) + {tcp, Socket, Bin} -> + case binary_to_term(Bin, [safe]) of + ok -> + ok = log(info, "Connected to ~s:~p", [Host, Port]), + confirm_serial(Realm, Socket, Hosts, user); + {redirect, Next} -> + ok = log(info, "Redirected..."), + ok = disconnect(Socket), + connect_user(Realm, Next ++ Hosts) + end after 5000 -> ok = log(warning, "Host ~s:~p timed out.", [Host, Port]), - halt(0) - end; -confirm_server(Socket, {auth, KeyID}) -> - ok = log(info, "Would now be trying to connect as AUTH using ~tp", [KeyID]), + ok = disconnect(Socket), + connect_user(Realm, tl(Hosts)) + end. + + +-spec confirm_serial(Realm, Socket, Hosts) -> Socket | no_return() + when Realm :: realm(), + Socket :: gen_tcp:socket(), + Hosts :: [host()]. +%% @private +%% Confirm that the connected host has a valid serial for the realm zx is trying to +%% reach, and if not retry on another node. + +confirm_serial(Realm, Socket, Hosts) -> + SerialFile = filename:join(zomp_dir(), "realm.serials"), + Serials = + case file:consult(SerialFile) of + {ok, Serials} -> Serials; + {error, enoent} -> [] + end, + Serial = + case lists:keyfind(Realm, 1, Serials) of + false -> 1; + {Realm, S} -> S + end, + ok = send(Socket, {latest, Realm}), + receive + {tcp, Socket, Bin} -> + case binary_to_term(Bin, [safe]) of + {ok, Serial} -> + ok = log(info, "Node's serial same as ours."), + Socket; + {ok, Current} when Current > Serial -> + ok = log(info, "Node's serial newer than ours. Storing."), + NewSerials = lists:keystore(Realm, 1, Current, Serials), + ok = write_terms(hosts_cache_file(Realm), Hosts), + ok = write_terms(SerialFile, NewSerials), + Socket; + {ok, Current} when Current < Serial -> + ok = log(info, "Node's serial older than ours. Trying another."), + ok = disconnect(Socket), + connect_user(Realm, tl(Hosts)); + {error, bad_realm} -> + ok = log(info, "Node is no longer serving realm. Trying another."), + ok = disconnect(Socket), + connect_user(Realm, tl(Hosts)) + end + after 5000 -> + ok = log(info, "Host timed out on confirm_serial. Trying another."), + ok = disconnect(Socket), + connect_user(Realm, tl(Hosts)) + end. + + +-spec connect_auth(Realm, KeyName) -> Result + when Realm :: realm(), + KeyName :: key_name(), + Result :: {ok, gen_tcp:socket()} + | {error, Reason :: term()}. +%% @private +%% Connect to one of the servers in the realm constellation. + +connect_auth(Realm, KeyName) -> + {ok, Key} = loadkey(private, {Realm, KeyName}), + {Host, Port} = get_prime(Realm), + case gen_tcp:connect(Host, Port, connect_options(), 5000) of + {ok, Socket} -> + ok = log(info, "Connected to ~tp prime.", [Realm]), + confirm_auth(Socket, Key); + Error = {error, E} -> + ok = log(warning, "Connection problem: ~tp", [E]), + {error, Error} + end. + + + +-spec confirm_auth(Socket, Key) -> Result + when Socket :: gen_tcp:socket(), + Key :: term(), + Result :: {ok, gen_tcp:socket()} + | {error, timeout}. +%% @private +%% Send a protocol ID string to notify the server what we're up to, disconnect +%% if it does not return an "OK" response within 5 seconds. + +confirm_auth(Socket, Key) -> + ok = log(info, "Would be using key ~tp now", [Key]), {ok, {Addr, Port}} = inet:peername(Socket), - Host = inet:ntoa(Addr), ok = gen_tcp:send(Socket, <<"OTPR AUTH 1">>), receive {tcp, Socket, <<"OK">>} -> - ok = log(info, "Connected to ~s:~p", [Host, Port]), - Socket; - Other -> - Message = "Unexpected response from ~s:~p:~n~tp", - ok = log(warning, Message, [Host, Port, Other]), - ok = disconnect(Socket), - halt(0) + {ok, Socket} after 5000 -> ok = log(warning, "Host ~s:~p timed out.", [Host, Port]), - halt(0) + {error, auth_timeout} end. +-spec connect_options() -> [gen_tcp:connect_option()]. +%% @private +%% Hide away the default options used for TCP connections. + +connect_options() -> + [{packet, 4}, {mode, binary}, {active, true}]. + + +-spec get_prime(realm()) -> host(). +%% @private +%% Check the given Realm's config file for the current prime node and return it. + +get_prime(Realm) -> + RealmFile = filename:join(zomp_dir(), Realm ++ ".realm"), + case file:consult(RealmFile) of + {ok, RealmMeta} -> + {prime, Prime} = lists:keyfind(prime, 1, RealmMeta), + Prime; + {error, enoent} -> + ok = log(error, "Missing realm file for ~tp (~tp).", [Realm, RealmFile]), + halt(1) + end. + + +-spec hosts_cache_file(realm()) -> file:filename(). +%% @private +%% Given a Realm name, construct a realm's .hosts filename and return it. + +hosts_cache_file(Realm) -> + filename:join(zomp_dir(), Realm ++ ".hosts"). + + -spec disconnect(gen_tcp:socket()) -> ok. %% @private %% Gracefully shut down a socket, logging (but sidestepping) the case when the socket @@ -1219,22 +1389,6 @@ extract_zrp(FileName) -> end. --spec read_meta() -> [term()] | no_return(). -%% @private -%% Read the `zomp.meta' file from the current directory, if possible. If not possible -%% then halt execution with an appropriate error message. - -read_meta() -> - case file:consult("zomp.meta") of - {ok, Meta} -> - Meta; - Error -> - ok = log(error, "Failed to open \"zomp.meta\" with ~tp", [Error]), - ok = log(error, "Wrong directory?"), - halt(1) - end. - - -spec verify(Data, Signature, PubKey) -> ok | no_return() when Data :: binary(), Signature :: binary(), @@ -1300,6 +1454,52 @@ fetch(Socket, Needed) -> %%% Utility functions +-spec read_meta() -> package_meta() | no_return(). +%% @private +%% @equiv read_meta(".") + +read_meta() -> + read_meta("."). + + +-spec read_meta(Dir) -> package_meta() | no_return() + when Dir :: file:filename(). +%% @private +%% Read the `zomp.meta' file from the indicated directory, if possible. If not possible +%% then halt execution with an appropriate error message. + +read_meta(Dir) -> + Path = filename:join(Dir, "zomp.meta"), + case file:consult(Path) of + {ok, Meta} -> + maps:from_list(Meta); + Error -> + ok = log(error, "Failed to open \"zomp.meta\" with ~tp", [Error]), + ok = log(error, "Wrong directory?"), + halt(1) + end. + + +-spec write_meta(package_meta()) -> ok. +%% @private +%% @equiv write_meta(".") + +write_meta() -> + write_meta("."). + + +-spec write_meta(Dir, Meta) -> ok + when Dir :: file:filename(), + Meta :: package_meta(). +%% @private +%% Write the contents of the provided meta structure (a map these days) as a list of +%% Erlang K/V terms. + +write_meta(Dir, Meta) -> + Path = filename:join(Dir, "zomp.meta"), + ok = write_terms(Path, maps:to_list(Meta)). + + -spec write_terms(Filename, Terms) -> ok when Filename :: file:filename(), Terms :: [term()]. @@ -1351,6 +1551,8 @@ build() -> %% Take a list of dependencies and return a list of dependencies that are not yet %% installed on the system. +scrub([]) -> + []; scrub(Deps) -> {ok, Names} = file:list_dir("lib"), Existing = lists:map(fun package_id/1, Names), @@ -1382,7 +1584,8 @@ valid_lower0_9([$_ | _], $_) -> false; valid_lower0_9([Char | Rest], _) when $a =< Char, Char =< $z; - $0 =< Char, Char =< $9 -> + $0 =< Char, Char =< $9; + Char == $_ -> valid_lower0_9(Rest, Char); valid_lower0_9([], _) -> true; From 3e3f72359a616d8c2a620d2ea380448b67305d81 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Wed, 15 Nov 2017 12:47:56 +0900 Subject: [PATCH 04/55] Thinking about fetch --- zx | 164 +++++++++++++++++++++++++++++++++++++++---------------------- 1 file changed, 105 insertions(+), 59 deletions(-) diff --git a/zx b/zx index 4573149..a66d838 100755 --- a/zx +++ b/zx @@ -21,7 +21,7 @@ {realm = "otpr" :: name(), name = none :: none | name(), version = {z, z, z} :: version(), - type = app :: app | lib + type = app :: app | lib, deps = [] :: [package_id()], dir = none :: none | file:filename(), socket = none :: none | gen_tcp:socket(), @@ -139,49 +139,49 @@ start(_) -> %% procedure the runtime will halt with an error message. run(Identifier, Args) -> - PackageID = {Realm, Name, Version} = package_id(Identifier), + {Realm, Name, Version} = package_id(Identifier), ok = file:set_cwd(zomp_dir()), - PackageRoot = filename:join("lib", Identifier), State = #s{realm = Realm, name = Name, - version = Version, - dir = PackageRoot}, - NextState = ensure_installed(State), - Meta = read_meta(PackageRoot), + version = Version}, + NextState = #s{version = Installed} = ensure_installed(State), + PackageID = {Realm, Name, Installed}, + Dir = filename:join("lib", package_string(PackageID)), + Meta = read_meta(Dir), Deps = maps:get(deps, Meta), - NewState = ensure_deps(NextState#s{deps = Deps}), - execute(State). + NewState = ensure_deps(NextState#s{dir = Dir, deps = Deps}), + execute(NewState). - Required = [PackageID | Deps], - Needed = scrub(Required), - Host = {"localhost", 11411}, - Socket = connect(Host, user), - ok = fetch(Socket, Needed), - ok = lists:foreach(fun install/1, Needed), - ok = lists:foreach(fun build/1, Required), - ok = file:set_cwd(PackageRoot), - case maps:get(type, Meta) of - app -> - true = register(zx, self()), - ok = inets:start(), - ok = log(info, "Starting ~ts", [package_string(PackageID)]), - PackageMod = list_to_atom(Name), - {ok, Pid} = PackageMod:start(normal, Args), - Mon = monitor(process, Pid), - Shell = spawn(shell, start, []), - ok = log(info, "Your shell is ~p, application is: ~p", [Shell, Pid]), - State = #s{realm = Realm, - name = Name, - version = Version, - pid = Pid, - mon = Mon}, - exec_wait(State); - lib -> - Message = "Lib ~ts is available on the system, but is not a standalone app.", - ok = log(info, Message, [package_string(PackageID)]), - halt(0) - end. +% Required = [PackageID | Deps], +% Needed = scrub(Required), +% Host = {"localhost", 11411}, +% Socket = connect(Host, user), +% ok = fetch(Socket, Needed), +% ok = lists:foreach(fun install/1, Needed), +% ok = lists:foreach(fun build/1, Required), +% ok = file:set_cwd(PackageRoot), +% case maps:get(type, Meta) of +% app -> +% true = register(zx, self()), +% ok = inets:start(), +% ok = log(info, "Starting ~ts", [package_string(PackageID)]), +% PackageMod = list_to_atom(Name), +% {ok, Pid} = PackageMod:start(normal, Args), +% Mon = monitor(process, Pid), +% Shell = spawn(shell, start, []), +% ok = log(info, "Your shell is ~p, application is: ~p", [Shell, Pid]), +% State = #s{realm = Realm, +% name = Name, +% version = Version, +% pid = Pid, +% mon = Mon}, +% exec_wait(State); +% lib -> +% Message = "Lib ~ts is available on the system, but is not a standalone app.", +% ok = log(info, Message, [package_string(PackageID)]), +% halt(0) +% end. @@ -335,16 +335,55 @@ latest_version({Realm, Name, Version}) -> %% locating or acquiring the package fail, then exit with an error. ensure_installed(State = #s{realm = Realm, name = Name, version = Version}) -> - % If the startup style is to always check first, match for the exact version, - % If the startup style is to run a matching latest and then check - PackageString = package_string(PackageID), - PackageDir = filename:join("lib", PackageString), - case filelib:is_dir(PackageDir) of - true -> ok; - false -> ensure_dep(PackageID) + case resolve_installed_version({Realm, Name, Version}) of + exact -> State; + {ok, Installed} -> State#s{version = Installed}; + not_found -> ensure_dep(State) end. +-spec resolve_installed_version(PackageID) -> Result + when PackageID :: package_id(), + Result :: not_found + | exact + | {ok, Installed :: version()}. +%% @private +%% Resolve the provided PackageID to the latest matching installed package directory version +%% if one exists, returning a value that indicates whether an exact match was found (in the +%% case of a full version input), a version matching a partial version input was found, or no +%% match was found at all. + +resolve_installed_version(PackageID) -> + PackageString = package_string(PackageID), + Pattern = PackageString ++ "*", + case filelib:wildcard(Pattern, "lib") of + [] -> + not_found; + [PackageString] -> + exact; + [Dir] -> + {_, _, Version} = package_id(Dir), + {ok, Versoin}; + Dirs -> + Dir = lists:last(lists:sort(Dirs)), + {_, _, Version} = package_id(Dir), + {ok, Version} + end. + + +ensure_deps(State = #s{realm = Realm, deps = Deps, socket = MaybeSocket}) -> + case scrub(Deps) of + [] -> + State; + Needed -> + Sorted = lists:sort(Needed), + Partition = + fun(D = {R, _, _}, M) -> + maps:update_with(R, fun(Ds) -> [D | Ds] end, [D], M) + end, + Partitioned = lists:foldl(Partition, #{}, Needed), + + -spec ensure_dep(package_id()) -> ok | no_return(). %% @private %% Given an PackageID as an argument, check whether its package file exists in the @@ -581,13 +620,13 @@ execute(State = #s{type = lib}) -> - Needed = scrub(Deps), - Host = {"localhost", 11411}, - Socket = connect(Host, user), - ok = fetch(Socket, Needed), - ok = lists:foreach(fun install/1, Needed), - ok = lists:foreach(fun build/1, Deps), - ok = file:set_cwd(ProjectRoot), +% Needed = scrub(Deps), +% Host = {"localhost", 11411}, +% Socket = connect(Host, user), +% ok = fetch(Socket, Needed), +% ok = lists:foreach(fun install/1, Needed), +% ok = lists:foreach(fun build/1, Deps), +% ok = file:set_cwd(ProjectRoot), @@ -751,7 +790,7 @@ submit(PackageFile) -> {package_id, {Realm, Package, Version}} = lists:keyfind(package_id, 1, Meta), {sig, {KeyID = {Realm, KeyName}, _}} = lists:keyfind(sig, 1, Meta), true = ensure_keypair(KeyID), - {ok, Socket = connect_auth(Realm, KeyName), + {ok, Socket} = connect_auth(Realm, KeyName), ok = send(Socket, {submit, {Realm, Package, Version}}), ok = receive @@ -772,7 +811,7 @@ submit(PackageFile) -> ok = receive {tcp, Socket, Response2} -> - log(info, "Response: ~tp", [Response2]); + log(info, "Response: ~tp", [Response2]) after 5000 -> log(warning, "Server timed out!") end, @@ -1554,11 +1593,18 @@ build() -> scrub([]) -> []; scrub(Deps) -> - {ok, Names} = file:list_dir("lib"), - Existing = lists:map(fun package_id/1, Names), - Need = ordsets:from_list(Deps), - Have = ordsets:from_list(Existing), - ordsets:to_list(ordsets:subtract(Need, Have)). + lists:filter(fun(PackageID) -> not installed(PackageID) end, Deps). + + +-spec installed(package_id()) -> boolean(). +%% @private +%% True to its name, returns `true' if the package is installed (its directory found), +%% `false' otherwise. + +installed(PackageID) -> + PackageString = package_string(PackageID), + PackageDir = filename:join("lib", PackageString), + filelib:is_dir(PackageDir). From a1af4182ee9e8903e7d95e2e8f8fec353fd5909e Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Wed, 15 Nov 2017 21:01:56 +0900 Subject: [PATCH 05/55] blah --- zx | 196 +++++++++++++++++++++++++------------------------------------ 1 file changed, 80 insertions(+), 116 deletions(-) diff --git a/zx b/zx index a66d838..0f21ff0 100755 --- a/zx +++ b/zx @@ -144,44 +144,13 @@ run(Identifier, Args) -> State = #s{realm = Realm, name = Name, version = Version}, - NextState = #s{version = Installed} = ensure_installed(State), + NewState = #s{version = Installed} = ensure_installed(State), PackageID = {Realm, Name, Installed}, Dir = filename:join("lib", package_string(PackageID)), Meta = read_meta(Dir), Deps = maps:get(deps, Meta), - NewState = ensure_deps(NextState#s{dir = Dir, deps = Deps}), - execute(NewState). - - -% Required = [PackageID | Deps], -% Needed = scrub(Required), -% Host = {"localhost", 11411}, -% Socket = connect(Host, user), -% ok = fetch(Socket, Needed), -% ok = lists:foreach(fun install/1, Needed), -% ok = lists:foreach(fun build/1, Required), -% ok = file:set_cwd(PackageRoot), -% case maps:get(type, Meta) of -% app -> -% true = register(zx, self()), -% ok = inets:start(), -% ok = log(info, "Starting ~ts", [package_string(PackageID)]), -% PackageMod = list_to_atom(Name), -% {ok, Pid} = PackageMod:start(normal, Args), -% Mon = monitor(process, Pid), -% Shell = spawn(shell, start, []), -% ok = log(info, "Your shell is ~p, application is: ~p", [Shell, Pid]), -% State = #s{realm = Realm, -% name = Name, -% version = Version, -% pid = Pid, -% mon = Mon}, -% exec_wait(State); -% lib -> -% Message = "Lib ~ts is available on the system, but is not a standalone app.", -% ok = log(info, Message, [package_string(PackageID)]), -% halt(0) -% end. + ok = ensure_deps(Deps), + execute(NewState#s{dir = Dir, deps = Deps}). @@ -348,10 +317,10 @@ ensure_installed(State = #s{realm = Realm, name = Name, version = Version}) -> | exact | {ok, Installed :: version()}. %% @private -%% Resolve the provided PackageID to the latest matching installed package directory version -%% if one exists, returning a value that indicates whether an exact match was found (in the -%% case of a full version input), a version matching a partial version input was found, or no -%% match was found at all. +%% Resolve the provided PackageID to the latest matching installed package directory +%% version if one exists, returning a value that indicates whether an exact match was +%% found (in the case of a full version input), a version matching a partial version +%% input was found, or no match was found at all. resolve_installed_version(PackageID) -> PackageString = package_string(PackageID), @@ -371,35 +340,52 @@ resolve_installed_version(PackageID) -> end. -ensure_deps(State = #s{realm = Realm, deps = Deps, socket = MaybeSocket}) -> +ensure_deps(Deps) -> case scrub(Deps) of [] -> - State; + ok; Needed -> - Sorted = lists:sort(Needed), - Partition = - fun(D = {R, _, _}, M) -> - maps:update_with(R, fun(Ds) -> [D | Ds] end, [D], M) + Partitioned = partition_by_realm(Needed), + EnsureDeps = + fun({Realm, Packages}) -> + Socket = connect_user(Realm), + ok = ensure_deps(Socket, Realm, Packages), + ok = disconnect(Socket), + log(info, "Disconnecting from realm: ~ts", [Realm]), end, - Partitioned = lists:foldl(Partition, #{}, Needed), + lists:foreach(EnsureDeps, Partitioned) + end. --spec ensure_dep(package_id()) -> ok | no_return(). +partition_by_realm(PackageIDs) -> + Sorted = lists:sort(Needed), + PartitionMap = lists:foldl(fun partition_by_realm/2, #{}, Needed), + maps:to_list(PartitionMap). + + +partition_by_realm({R, P, V}, M) -> + maps:update_with(R, fun(Ps) -> [{P, V} | Ps] end, [{P, V}], M). + + +ensure_deps(_, _, []) -> + ok; +ensure_deps(Socket, Realm, [{Name, Version} | Rest]) -> + ok = ensure_dep(Socket, {Realm, Name, Version}), + ensure_deps(Socket, Realm, Rest). + + +-spec ensure_dep(gen_tcp:socket(), package_id()) -> ok | no_return(). %% @private %% Given an PackageID as an argument, check whether its package file exists in the %% system cache, and if not download it. Should return `ok' whenever the file is %% sourced, but exit with an error if it cannot locate or acquire the package. -ensure_dep(PackageID) -> +ensure_dep(Socket, PackageID) -> ZrpFile = filename:join("zrp", namify_zrp(PackageID)), ok = case filelib:is_regular(ZrpFile) of - true -> - ok; - false -> - PackageString = package_string(PackageID), - log(error, "Would fetch ~ts now, but not implemented", [PackageString]), - halt(0) + true -> ok; + false -> fetch(Socket, PackageID) end, install(PackageID). @@ -576,10 +562,9 @@ verup(_) -> usage_exit(22). run_local(Args) -> Meta = read_meta(), - {package_id, PackageID} = lists:keyfind(package_id, 1, Meta), - {Realm, Name, Version} = PackageID, - {type, Type} = lists:keyfind(type, 1, Meta), - {deps, Deps} = lists:keyfind(deps, 1, Meta), + {Realm, Name, Version} = maps:get(package_id, Meta), + Type = maps:get(type, Meta), + Deps = maps:get(deps, Meta), ok = build(), {ok, Dir} = file:get_cwd(), ok = file:set_cwd(zomp_dir()), @@ -589,12 +574,8 @@ run_local(Args) -> type = Type, deps = Deps, dir = Dir}, - NewState = ensure_deps(State), - execute(State). - - -ensure_deps(Deps, State) -> - + ok = ensure_deps(Deps), + ok = file:set_cwd(Dir), execute(State). @@ -613,23 +594,14 @@ execute(State = #s{type = app}) -> pid = Pid, mon = Mon}, exec_wait(State); -execute(State = #s{type = lib}) -> +execute(State = #s{type = lib, realm = Realm, name = Name, version = Version}) -> Message = "Lib ~ts is available on the system, but is not a standalone app", - ok = log(info, Message, [package_string(PackageID)]), + PackageString = package_string({Realm, Name, Version}), + ok = log(info, Message, [PackageString]), halt(0). -% Needed = scrub(Deps), -% Host = {"localhost", 11411}, -% Socket = connect(Host, user), -% ok = fetch(Socket, Needed), -% ok = lists:foreach(fun install/1, Needed), -% ok = lists:foreach(fun build/1, Deps), -% ok = file:set_cwd(ProjectRoot), - - - %%% Package generation -spec package(TargetDir) -> no_return() @@ -1443,53 +1415,45 @@ verify(Data, Signature, PubKey) -> end. --spec fetch(gen_tcp:socket(), [package_id()]) -> ok. +-spec fetch(gen_tcp:socket(), package_id()) -> ok. %% @private -%% Download a list of deps to the local package cache. +%% Download a package to the local cache. -fetch(Socket, Needed) -> - Namified = lists:map(fun namify_zrp/1, Needed), - {Have, Lack} = lists:partition(fun filelib:is_regular/1, Namified), - ok = lists:foreach(fun(A) -> log(info, "Have ~ts", [A]) end, Have), - ok = lists:foreach(fun(A) -> log(info, "Lack ~ts", [A]) end, Lack), - ok = send(Socket, "Would be sending fetch requests now."), - log(info, "Done fake fetching"). +fetch(Socket, PackageID) -> + ok = send(Socket, {fetch, PackageID}), + ok = await_zrp(Socket, PackageID), + ok = receive_zrp(Socket, PackageID), + log(info, "Fetched ~ts", [package_string(PackageID)]). -% Grouped = group_by_realm(Needed), -% Realms = [R || {R, _} <- Grouped], -% Sockets = connect(Realms), -% fetch(Sockets, Groups). -% -% -%-spec group_by_realm(AppIDs) -> GroupedAppIDs -% when AppIDs :: [app_id()], -% GroupedAppIDs :: [{realm(), [app_id()]}]. -%%% @private -%%% Group apps by realm. -% -%group_by_realm(AppIDs) -> -% Group = -% fun(AppID = {Realm, _, _}, Groups) -> -% case lists:keyfind(Realm, Groups) of -% {Realm, Members} -> -% lists:keystore(Realm, 1, Groups, {Realm, [AppID | Members]}); -% false -> -% lists:keystore(Realm, 1, Groups, {Realm, [AppID]}) -% end -% end, -% lists:foldl(Group, AppIDs). -% -% -% ZrpFile = namify_zrp(AppID), -% case filelib:is_regular(filename:join("zrp", ZrpFile)) of -% true -> -% log(info, "Found in cache: ~ts", [ZrpFile]); -% false -> -% log(info, "Would download: ~ts", [ZrpFile]) -% end. +await_zrp(Socket, PackageID) -> + receive + {tcp, Socket, Bin} -> + case binary_to_term(Bin, [safe]) of + sending -> + ok; + Error = {error, Reason} -> + PackageString = package_string(PackageID), + Message = "Error receiving package ~ts: ~tp", + ok = log(info, Message, [PackageString, Reason]), + Error + after 60000 -> + {error, timeout} + end. +receive_zrp(Socket, PackageID) -> + receive + {tcp, Socket, Bin} -> + ZrpPath = filename:join("zrp", namify_zrp(PackageID)), + ok = file:write_file(ZrpPath, Bin), + ok = send(Socket, ok), + log(info, "Wrote ~ts", [ZrpPath]) + after 60000 -> + ok = log(error, "Timeout in socket receive for ~tp", [PackageID]), + {error, timeout} + end. + %%% Utility functions From 684e4507fc8817d48573b7c1c727f263e3f95b76 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Tue, 21 Nov 2017 07:51:35 +0900 Subject: [PATCH 06/55] wip --- zx | 197 +++++++++++++++++++++++++++++++++---------------------------- 1 file changed, 106 insertions(+), 91 deletions(-) diff --git a/zx b/zx index 0f21ff0..b7d768b 100755 --- a/zx +++ b/zx @@ -18,7 +18,7 @@ -record(s, - {realm = "otpr" :: name(), + {realm = "otpr" :: realm(), name = none :: none | name(), version = {z, z, z} :: version(), type = app :: app | lib, @@ -47,6 +47,7 @@ -type key_name() :: lower0_9(). -type lower0_9() :: [$a..$z | $0..$9 | $_]. %-type label() :: [$a..$z | $0..$9 | $_ | $- | $.]. +-type package_meta() :: #{}. @@ -79,7 +80,8 @@ start(["init", "lib", PackageString]) -> start(["install", PackageFile]) -> assimilate(PackageFile); start(["set", "dep", PackageString]) -> - set_dep(PackageString); + PackageID = package_id(PackageString), + set_dep(PackageID); start(["set", "version", VersionString]) -> set_version(VersionString); start(["drop", "dep", PackageString]) -> @@ -133,24 +135,25 @@ start(_) -> %% %% Once the target program is running, this process, (which will run with the registered %% name `zx') will sit in an `exec_wait' state, waiting for either a direct message from -%% a child program or for calls made via vx_lib to assist in environment discovery. +%% a child program or for calls made via zx_lib to assist in environment discovery. %% -%% If there is a problem anywhere in the locationg, discovery, building, and loading +%% If there is a problem anywhere in the locating, discovery, building, and loading %% procedure the runtime will halt with an error message. run(Identifier, Args) -> - {Realm, Name, Version} = package_id(Identifier), + MaybeID = package_id(Identifier), + {ok, PackageID = {Realm, Name, Version}} = ensure_installed(MaybeID), ok = file:set_cwd(zomp_dir()), - State = #s{realm = Realm, - name = Name, - version = Version}, - NewState = #s{version = Installed} = ensure_installed(State), - PackageID = {Realm, Name, Installed}, Dir = filename:join("lib", package_string(PackageID)), Meta = read_meta(Dir), Deps = maps:get(deps, Meta), ok = ensure_deps(Deps), - execute(NewState#s{dir = Dir, deps = Deps}). + State = #s{realm = Realm, + name = Name, + version = Version, + dir = Dir, + deps = Deps}, + execute(State, Args). @@ -227,8 +230,7 @@ assimilate(PackageFile) -> %%% Set dependency --spec set_dep(PackageString) -> no_return() - when PackageString :: string(). +-spec set_dep(package_id()) -> no_return(). %% @private %% Set a specific dependency in the current project. If the project currently has a %% dependency on the same package then the version of that dependency is updated to @@ -236,17 +238,27 @@ assimilate(PackageFile) -> %% incomplete. Incomplete elements of the VersionString (if included) will default to %% the latest version available at the indicated level. -set_dep(PackageString) -> - PackageID = package_id(PackageString), +set_dep(PackageID = {_, _, {X, Y, Z}}) + when is_integer(X), is_integer(Y), is_integer(Z) -> Meta = read_meta(), Deps = maps:get(deps, Meta), case lists:member(PackageID, Deps) of true -> - ok = log(info, "~ts is already a dependency", [PackageString]), + ok = log(info, "~ts is already a dependency", [package_string(PackageID)]), halt(0); false -> set_dep(PackageID, Deps, Meta) - end. + end; +set_dep({Realm, Name, {z, z, z}}) -> + Socket = connect_user(Realm), + {ok, Version} = query_latest(Socket, {Realm, Name}), + ok = disconnect(Socket), + set_dep({Realm, Name, Version}); +set_dep({Realm, Name, Version}) -> + Socket = connect_user(Realm), + {ok, Latest} = query_latest(Socket, {Realm, Name, Version}), + ok = disconnect(Socket), + set_dep({Realm, Name, Latest}). -spec set_dep(PackageID, Deps, Meta) -> no_return() @@ -259,9 +271,7 @@ set_dep(PackageString) -> %% such a dependency is not already present. Then write the project meta back to its %% file and exit. -set_dep(PackageID = {Realm, Name, Version}, Deps, Meta) -> - {ok, CWD} = file:get_cwd(), - LatestVersion = latest_version(PackageID), +set_dep(PackageID = {Realm, Name, NewVersion}, Deps, Meta) -> ExistingPackageIDs = fun ({R, N, _}) -> {R, N} == {Realm, Name} end, NewDeps = case lists:partition(ExistingPackageIDs, Deps) of @@ -280,34 +290,42 @@ set_dep(PackageID = {Realm, Name, Version}, Deps, Meta) -> halt(0). --spec latest_version(package_id()) -> version(). -%% @private -%% Query the relevant realm for the latest version of a given package. - -latest_version({Realm, Name, Version}) -> - Socket = connect(Realm), - ok = send(Socket, {latest, Realm, Name, Version}), - Response = - receive - {tcp, Socket, Bin} -> binary_to_term(Bin, [safe]) - after 5000 -> {error, timeout} - end, - ok = disconnect(Socket). - - --spec ensure_installed(State) -> NewState | no_return() - when State :: state(), - NewState :: state(). +-spec ensure_installed(PackageID) -> Result | no_return() + when PackageID :: package_id(), + Result :: {ok, ActualID :: package_id()}. %% @private %% Given a PackageID, check whether it is installed on the system, and if not, ensure %% that the package is either in the cache or can be downloaded. If all attempts at %% locating or acquiring the package fail, then exit with an error. -ensure_installed(State = #s{realm = Realm, name = Name, version = Version}) -> - case resolve_installed_version({Realm, Name, Version}) of - exact -> State; - {ok, Installed} -> State#s{version = Installed}; - not_found -> ensure_dep(State) +ensure_installed(PackageID = {Realm, Name, Version}) -> + case resolve_installed_version(PackageID) of + exact -> {ok, PackageID}; + {ok, Installed} -> {ok, {Realm, Name, Installed}}; + not_found -> ensure_installed(Realm, Name, Version) + end. + + +ensure_installed(Realm, Name, Version) -> + Socket = connect_user(Realm), + {ok, LatestVersion} = query_latest(Socket, {Realm, Name, Version}), + LatestID = {Realm, Name, LatestVersion}, + ok = ensure_dep(Socket, LatestID), + ok = disconnect(Socket), + {ok, LatestID}. + + +query_latest(Socket, {Realm, Name}) -> + ok = send(Socket, {latest, Realm, Name}), + receive + {tcp, Socket, Bin} -> binary_to_term(Bin, [safe]) + after 5000 -> {error, timeout} + end; +query_latest(Socket, {Realm, Name, Version}) -> + ok = send(Socket, {latest, Realm, Name, Version}), + receive + {tcp, Socket, Bin} -> binary_to_term(Bin, [safe]) + after 5000 -> {error, timeout} end. @@ -332,7 +350,7 @@ resolve_installed_version(PackageID) -> exact; [Dir] -> {_, _, Version} = package_id(Dir), - {ok, Versoin}; + {ok, Version}; Dirs -> Dir = lists:last(lists:sort(Dirs)), {_, _, Version} = package_id(Dir), @@ -351,15 +369,14 @@ ensure_deps(Deps) -> Socket = connect_user(Realm), ok = ensure_deps(Socket, Realm, Packages), ok = disconnect(Socket), - log(info, "Disconnecting from realm: ~ts", [Realm]), + log(info, "Disconnecting from realm: ~ts", [Realm]) end, lists:foreach(EnsureDeps, Partitioned) end. partition_by_realm(PackageIDs) -> - Sorted = lists:sort(Needed), - PartitionMap = lists:foldl(fun partition_by_realm/2, #{}, Needed), + PartitionMap = lists:foldl(fun partition_by_realm/2, #{}, PackageIDs), maps:to_list(PartitionMap). @@ -387,13 +404,13 @@ ensure_dep(Socket, PackageID) -> true -> ok; false -> fetch(Socket, PackageID) end, - install(PackageID). + ok = install(PackageID), + build(PackageID). %%% Set version - -spec set_version(VersionString) -> no_return() when VersionString :: string(). %% @private @@ -576,26 +593,21 @@ run_local(Args) -> dir = Dir}, ok = ensure_deps(Deps), ok = file:set_cwd(Dir), - execute(State). + execute(State, Args). -execute(State = #s{type = app}) -> +execute(State = #s{type = app, realm = Realm, name = Name, version = Version}, Args) -> true = register(zx, self()), ok = inets:start(), - ok = log(info, "Starting ~ts", [package_string(PackageID)]), + ok = log(info, "Starting ~ts", [package_string({Realm, Name, Version})]), AppMod = list_to_atom(Name), {ok, Pid} = AppMod:start(normal, Args), Mon = monitor(process, Pid), Shell = spawn(shell, start, []), ok = log(info, "Your shell is ~p, application is: ~p", [Shell, Pid]), - State = #s{realm = Realm, - name = Name, - version = Version, - pid = Pid, - mon = Mon}, - exec_wait(State); -execute(State = #s{type = lib, realm = Realm, name = Name, version = Version}) -> - Message = "Lib ~ts is available on the system, but is not a standalone app", + exec_wait(State#s{pid = Pid, mon = Mon}); +execute(#s{type = lib, realm = Realm, name = Name, version = Version}, _) -> + Message = "Lib ~ts is available on the system, but is not a standalone app.", PackageString = package_string({Realm, Name, Version}), ok = log(info, Message, [PackageString]), halt(0). @@ -807,6 +819,7 @@ send(Socket, Message) -> %% Connect to a given realm, whatever method is required. connect_user(Realm) -> + ok = log(info, "Connecting to realm ~ts...", [Realm]), Hosts = case file:consult(hosts_cache_file(Realm)) of {ok, Cached} -> Cached; @@ -821,6 +834,7 @@ connect_user(Realm) -> connect_user(Realm, []) -> {Host, Port} = get_prime(Realm), + ok = log(info, "Realm host at ~tp:~tp", [Host, Port]), case gen_tcp:connect(Host, Port, connect_options(), 5000) of {ok, Socket} -> confirm_user(Realm, Socket, []); @@ -854,7 +868,7 @@ confirm_user(Realm, Socket, Hosts) -> case binary_to_term(Bin, [safe]) of ok -> ok = log(info, "Connected to ~s:~p", [Host, Port]), - confirm_serial(Realm, Socket, Hosts, user); + confirm_serial(Realm, Socket, Hosts); {redirect, Next} -> ok = log(info, "Redirected..."), ok = disconnect(Socket), @@ -863,7 +877,7 @@ confirm_user(Realm, Socket, Hosts) -> after 5000 -> ok = log(warning, "Host ~s:~p timed out.", [Host, Port]), ok = disconnect(Socket), - connect_user(Realm, tl(Hosts)) + connect_user(Realm, Hosts) end. @@ -879,7 +893,7 @@ confirm_serial(Realm, Socket, Hosts) -> SerialFile = filename:join(zomp_dir(), "realm.serials"), Serials = case file:consult(SerialFile) of - {ok, Serials} -> Serials; + {ok, Ss} -> Ss; {error, enoent} -> [] end, Serial = @@ -897,22 +911,24 @@ confirm_serial(Realm, Socket, Hosts) -> {ok, Current} when Current > Serial -> ok = log(info, "Node's serial newer than ours. Storing."), NewSerials = lists:keystore(Realm, 1, Current, Serials), - ok = write_terms(hosts_cache_file(Realm), Hosts), + {ok, Host} = inet:peername(Socket), + ok = write_terms(hosts_cache_file(Realm), [Host | Hosts]), ok = write_terms(SerialFile, NewSerials), Socket; {ok, Current} when Current < Serial -> + log(info, "Our serial: ~tp, node serial: ~tp.", [Serial, Current]), ok = log(info, "Node's serial older than ours. Trying another."), ok = disconnect(Socket), - connect_user(Realm, tl(Hosts)); + connect_user(Realm, Hosts); {error, bad_realm} -> ok = log(info, "Node is no longer serving realm. Trying another."), ok = disconnect(Socket), - connect_user(Realm, tl(Hosts)) + connect_user(Realm, Hosts) end after 5000 -> ok = log(info, "Host timed out on confirm_serial. Trying another."), ok = disconnect(Socket), - connect_user(Realm, tl(Hosts)) + connect_user(Realm, Hosts) end. @@ -949,7 +965,7 @@ connect_auth(Realm, KeyName) -> confirm_auth(Socket, Key) -> ok = log(info, "Would be using key ~tp now", [Key]), - {ok, {Addr, Port}} = inet:peername(Socket), + {ok, {Host, Port}} = inet:peername(Socket), ok = gen_tcp:send(Socket, <<"OTPR AUTH 1">>), receive {tcp, Socket, <<"OK">>} -> @@ -973,15 +989,9 @@ connect_options() -> %% Check the given Realm's config file for the current prime node and return it. get_prime(Realm) -> - RealmFile = filename:join(zomp_dir(), Realm ++ ".realm"), - case file:consult(RealmFile) of - {ok, RealmMeta} -> - {prime, Prime} = lists:keyfind(prime, 1, RealmMeta), - Prime; - {error, enoent} -> - ok = log(error, "Missing realm file for ~tp (~tp).", [Realm, RealmFile]), - halt(1) - end. + RealmMeta = realm_meta(Realm), + {prime, Prime} = lists:keyfind(prime, 1, RealmMeta), + Prime. -spec hosts_cache_file(realm()) -> file:filename(). @@ -1050,19 +1060,19 @@ have_private_key({Realm, KeyName}) -> filelib:is_regular(PrivateKeyPath). --spec realm_data(Realm) -> Data | no_return() +-spec realm_meta(Realm) -> Meta | no_return() when Realm :: string(), - Data :: [{atom(), term()}]. + Meta :: [{atom(), term()}]. %% @private %% Given a realm name, try to locate and read the realm's configuration file if it %% exists, exiting with an appropriate error message if there is a problem reading %% the file. -realm_data(Realm) -> +realm_meta(Realm) -> RealmFile = filename:join(zomp_dir(), Realm ++ ".realm"), case file:consult(RealmFile) of - {ok, Data} -> - Data; + {ok, Meta} -> + Meta; {error, enoent} -> ok = log(error, "No realm file for ~ts", [Realm]), halt(1); @@ -1415,28 +1425,32 @@ verify(Data, Signature, PubKey) -> end. --spec fetch(gen_tcp:socket(), package_id()) -> ok. +-spec fetch(Socket, PackageID) -> Result + when Socket :: gen_tcp:socket(), + PackageID :: package_id(), + Result :: ok. %% @private %% Download a package to the local cache. fetch(Socket, PackageID) -> - ok = send(Socket, {fetch, PackageID}), - ok = await_zrp(Socket, PackageID), + ok = request_zrp(Socket, PackageID), ok = receive_zrp(Socket, PackageID), log(info, "Fetched ~ts", [package_string(PackageID)]). -await_zrp(Socket, PackageID) -> +request_zrp(Socket, PackageID) -> + ok = send(Socket, {fetch, PackageID}), receive {tcp, Socket, Bin} -> case binary_to_term(Bin, [safe]) of - sending -> - ok; + {sending, LatestID} -> + {ok, LatestID}; Error = {error, Reason} -> PackageString = package_string(PackageID), Message = "Error receiving package ~ts: ~tp", ok = log(info, Message, [PackageString, Reason]), Error + end after 60000 -> {error, timeout} end. @@ -1487,8 +1501,8 @@ read_meta(Dir) -> %% @private %% @equiv write_meta(".") -write_meta() -> - write_meta("."). +write_meta(Meta) -> + write_meta(".", Meta). -spec write_meta(Dir, Meta) -> ok @@ -1984,7 +1998,8 @@ realm_file(Realm) -> default_realm() -> [{name, "otpr"}, - {prime, {"repo.psychobitch.party", 11311}}, +% {prime, {"repo.psychobitch.party", 11311}}, + {prime, {"localhost", 11311}}, {pubkey, default_pubkey_file()}, {serial, 0}, {mirrors, []}]. From ccd1fd1095a48a0ab7292525037675bb047af412 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Wed, 22 Nov 2017 21:00:43 +0900 Subject: [PATCH 07/55] wip --- zx | 44 +++++++++++++++++++++++++++++--------------- 1 file changed, 29 insertions(+), 15 deletions(-) diff --git a/zx b/zx index b7d768b..c01203e 100755 --- a/zx +++ b/zx @@ -308,23 +308,37 @@ ensure_installed(PackageID = {Realm, Name, Version}) -> ensure_installed(Realm, Name, Version) -> Socket = connect_user(Realm), - {ok, LatestVersion} = query_latest(Socket, {Realm, Name, Version}), - LatestID = {Realm, Name, LatestVersion}, - ok = ensure_dep(Socket, LatestID), - ok = disconnect(Socket), - {ok, LatestID}. + case query_latest(Socket, {Realm, Name, Version}) of + {ok, LatestVersion} -> + LatestID = {Realm, Name, LatestVersion}, + ok = ensure_dep(Socket, LatestID), + ok = disconnect(Socket), + {ok, LatestID}; + {error, bad_realm} -> + PackageString = package_string({Realm, Name, Version}), + ok = log(warning, "Bad realm: ~ts.", [PackageString]), + halt(1); + {error, bad_package} -> + PackageString = package_string({Realm, Name, Version}), + ok = log(warning, "Bad package: ~ts.", [PackageString]), + halt(1); + {error, bad_version} -> + PackageString = package_string({Realm, Name, Version}), + ok = log(warning, "Bad version: ~s.", [PackageString]), + halt(1) + end. query_latest(Socket, {Realm, Name}) -> ok = send(Socket, {latest, Realm, Name}), receive - {tcp, Socket, Bin} -> binary_to_term(Bin, [safe]) + {tcp, Socket, Bin} -> binary_to_term(Bin) after 5000 -> {error, timeout} end; query_latest(Socket, {Realm, Name, Version}) -> ok = send(Socket, {latest, Realm, Name, Version}), receive - {tcp, Socket, Bin} -> binary_to_term(Bin, [safe]) + {tcp, Socket, Bin} -> binary_to_term(Bin) after 5000 -> {error, timeout} end. @@ -779,7 +793,7 @@ submit(PackageFile) -> ok = receive {tcp, Socket, Response1} -> - case binary_to_term(Response1, [safe]) of + case binary_to_term(Response1) of ready -> ok; {error, Reason} -> @@ -834,7 +848,7 @@ connect_user(Realm) -> connect_user(Realm, []) -> {Host, Port} = get_prime(Realm), - ok = log(info, "Realm host at ~tp:~tp", [Host, Port]), + ok = log(info, "Realm host at ~ts:~tp", [inet:ntoa(Host), Port]), case gen_tcp:connect(Host, Port, connect_options(), 5000) of {ok, Socket} -> confirm_user(Realm, Socket, []); @@ -865,9 +879,9 @@ confirm_user(Realm, Socket, Hosts) -> ok = gen_tcp:send(Socket, <<"OTPR USER 1">>), receive {tcp, Socket, Bin} -> - case binary_to_term(Bin, [safe]) of + case binary_to_term(Bin) of ok -> - ok = log(info, "Connected to ~s:~p", [Host, Port]), + ok = log(info, "Connected to ~ts:~p", [Host, Port]), confirm_serial(Realm, Socket, Hosts); {redirect, Next} -> ok = log(info, "Redirected..."), @@ -875,7 +889,7 @@ confirm_user(Realm, Socket, Hosts) -> connect_user(Realm, Next ++ Hosts) end after 5000 -> - ok = log(warning, "Host ~s:~p timed out.", [Host, Port]), + ok = log(warning, "Host ~ts:~p timed out.", [Host, Port]), ok = disconnect(Socket), connect_user(Realm, Hosts) end. @@ -898,13 +912,13 @@ confirm_serial(Realm, Socket, Hosts) -> end, Serial = case lists:keyfind(Realm, 1, Serials) of - false -> 1; + false -> 0; {Realm, S} -> S end, ok = send(Socket, {latest, Realm}), receive {tcp, Socket, Bin} -> - case binary_to_term(Bin, [safe]) of + case binary_to_term(Bin) of {ok, Serial} -> ok = log(info, "Node's serial same as ours."), Socket; @@ -1442,7 +1456,7 @@ request_zrp(Socket, PackageID) -> ok = send(Socket, {fetch, PackageID}), receive {tcp, Socket, Bin} -> - case binary_to_term(Bin, [safe]) of + case binary_to_term(Bin) of {sending, LatestID} -> {ok, LatestID}; Error = {error, Reason} -> From 7b3fc3f3a963e606ed06152b68add2ed0dadbcd0 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Fri, 24 Nov 2017 08:15:09 +0900 Subject: [PATCH 08/55] wip --- zx | 53 ++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 40 insertions(+), 13 deletions(-) diff --git a/zx b/zx index c01203e..46c2555 100755 --- a/zx +++ b/zx @@ -32,7 +32,7 @@ -type state() :: #s{}. %-type serial() :: pos_integer(). -type package_id() :: {realm(), name(), version()}. -%-type package() :: {realm(), name()}. +-type package() :: {realm(), name()}. -type realm() :: lower0_9(). -type name() :: lower0_9(). -type version() :: {Major :: non_neg_integer() | z, @@ -306,9 +306,20 @@ ensure_installed(PackageID = {Realm, Name, Version}) -> end. +-spec ensure_installed(Realm, Name, Version) -> Result + when Realm :: realm(), + Name :: name(), + Version :: version(), + Result :: exact + | {ok, version()} + | not_found. +%% @private +%% Fetch and install the latest compatible version of the given package ID, whether +%% the version indicator is complete, partial or blank. + ensure_installed(Realm, Name, Version) -> Socket = connect_user(Realm), - case query_latest(Socket, {Realm, Name, Version}) of + case query_latest(Socket, {Realm, Name, Version}) of {ok, LatestVersion} -> LatestID = {Realm, Name, LatestVersion}, ok = ensure_dep(Socket, LatestID), @@ -329,6 +340,18 @@ ensure_installed(Realm, Name, Version) -> end. +-spec query_latest(Socket, Object) -> Result + when Socket :: gen_tcp:socket(), + Object :: package() | package_id(), + Result :: {ok, version()} + | {error, Reason}, + Reason :: bad_realm + | bad_package + | bad_version. +%% @private +%% Queries the connected zomp node for the latest version of a package or package +%% version (complete or incomplete version number). + query_latest(Socket, {Realm, Name}) -> ok = send(Socket, {latest, Realm, Name}), receive @@ -848,7 +871,7 @@ connect_user(Realm) -> connect_user(Realm, []) -> {Host, Port} = get_prime(Realm), - ok = log(info, "Realm host at ~ts:~tp", [inet:ntoa(Host), Port]), + ok = log(info, "Trying prime at ~ts:~tp", [inet:ntoa(Host), Port]), case gen_tcp:connect(Host, Port, connect_options(), 5000) of {ok, Socket} -> confirm_user(Realm, Socket, []); @@ -857,6 +880,7 @@ connect_user(Realm, []) -> halt(0) end; connect_user(Realm, Hosts = [Node = {Host, Port} | Rest]) -> + ok = log(info, "Trying node at ~ts:~tp", [inet:ntoa(Host), Port]), case gen_tcp:connect(Host, Port, connect_options(), 5000) of {ok, Socket} -> confirm_user(Realm, Socket, Hosts); @@ -1105,10 +1129,13 @@ realm_meta(Realm) -> prompt_keygen() -> Message = - " Enter a name for your new keys.~n" + "~n Enter a name for your new keys.~n~n" " Valid names must start with a lower-case letter, and can include~n" " only lower-case letters, numbers, and periods, but no series of~n" - " consecutive periods.~n", + " consecutive periods. (That is: [a-z0-9\\.])~n~n" + " To designate the key as realm-specific, enter the realm name and~n" + " key name separated by a space.~n~n" + " Example: some.realm my.key~n", ok = io:format(Message), Input = string:trim(io:get_line("(^C to quit): ")), {Realm, KeyName} = @@ -1136,10 +1163,8 @@ keygen() -> ok = file:set_cwd(zomp_dir()), KeyID = prompt_keygen(), case generate_rsa(KeyID) of - ok -> - halt(0); - Error -> - error_exit("keygen failed with ~tp", [Error], ?FILE, ?LINE) + ok -> halt(0); + Error -> error_exit("keygen failed with ~tp", [Error], ?FILE, ?LINE) end. @@ -1733,10 +1758,12 @@ package_id(String) -> true = valid_lower0_9(Name), Version = string_to_version(VersionString), {Realm, Name, Version}; - [Realm, Name] -> - true = valid_lower0_9(Realm), - true = valid_lower0_9(Name), - {Realm, Name, {z, z, z}}; + [A, B] -> + true = valid_lower0_9(A), + case valid_lower0_9(B) of + true -> {A, B, {z, z, z}}; + false -> {"otpr", A, string_to_version(B)} + end; [Name] -> true = valid_lower0_9(Name), {"otpr", Name, {z, z, z}} From 5d7d6599a96048807d05df6ca7984bfbe6c68df3 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Fri, 24 Nov 2017 11:53:11 +0900 Subject: [PATCH 09/55] wip --- zx | 122 +++++++++++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 95 insertions(+), 27 deletions(-) diff --git a/zx b/zx index 46c2555..bfc7072 100755 --- a/zx +++ b/zx @@ -23,6 +23,7 @@ version = {z, z, z} :: version(), type = app :: app | lib, deps = [] :: [package_id()], + serial = 0 :: serial(), dir = none :: none | file:filename(), socket = none :: none | gen_tcp:socket(), pid = none :: none | pid(), @@ -30,7 +31,7 @@ -type state() :: #s{}. -%-type serial() :: pos_integer(). +-type serial() :: pos_integer(). -type package_id() :: {realm(), name(), version()}. -type package() :: {realm(), name()}. -type realm() :: lower0_9(). @@ -44,9 +45,9 @@ % Type :: public | private, % DER :: binary()}. -type key_id() :: {realm(), key_name()}. --type key_name() :: lower0_9(). +-type key_name() :: label(). -type lower0_9() :: [$a..$z | $0..$9 | $_]. -%-type label() :: [$a..$z | $0..$9 | $_ | $- | $.]. +-type label() :: [$a..$z | $0..$9 | $_ | $- | $.]. -type package_meta() :: #{}. @@ -106,12 +107,16 @@ start(["package", TargetDir]) -> end; start(["submit", PackageFile]) -> submit(PackageFile); -start(["keygen"]) -> - keygen(); -start(["genplt"]) -> - genplt(); start(["dialyze"]) -> dialyze(); +start(["create", "keypair"]) -> + create_keypair(); +start(["create", "plt"]) -> + create_plt(); +start(["create", "realm"]) -> + create_realm(); +start(["create", "sysop"]) -> + create_sysop(); start(_) -> usage_exit(22). @@ -119,7 +124,6 @@ start(_) -> %%% Execution of application - -spec run(Identifier, Args) -> no_return() when Identifier :: string(), Args :: [string()]. @@ -159,7 +163,6 @@ run(Identifier, Args) -> %%% Project initialization - -spec initialize(Type, PackageID) -> no_return() when Type :: app | lib, PackageID :: package_id(). @@ -192,7 +195,6 @@ initialize(Type, PackageID) -> %%% Add a package from a local file - -spec assimilate(PackageFile) -> PackageID when PackageFile :: file:filename(), PackageID :: package_id(). @@ -229,7 +231,6 @@ assimilate(PackageFile) -> %%% Set dependency - -spec set_dep(package_id()) -> no_return(). %% @private %% Set a specific dependency in the current project. If the project currently has a @@ -538,7 +539,6 @@ update_version(Realm, Name, OldVersion, NewVersion, OldMeta) -> %%% Drop dependency - -spec drop_dep(package_id()) -> no_return(). %% @private %% Remove the indicate dependency from the local project's zomp.meta record. @@ -564,7 +564,6 @@ drop_dep(PackageID) -> %%% Drop key - -spec drop_key(key_id()) -> no_return(). %% @private %% Given a KeyID, remove the related public and private keys from the keystore, if they @@ -588,7 +587,6 @@ drop_key({Realm, KeyName}) -> %%% Update version - -spec verup(Level) -> no_return() when Level :: string(). %% @private @@ -797,7 +795,6 @@ check_update(State) -> %%% Package submission - -spec submit(PackageFile) -> no_return() when PackageFile :: file:filename(). %% @private @@ -895,7 +892,8 @@ connect_user(Realm, Hosts = [Node = {Host, Port} | Rest]) -> Socket :: gen_tcp:socket(), Hosts :: [host()]. %% @private -%% Confirm the zomp node can handle "OTPR USER 1" and is accepting connections or try another node. +%% Confirm the zomp node can handle "OTPR USER 1" and is accepting connections or try +%% another node. confirm_user(Realm, Socket, Hosts) -> {ok, {Addr, Port}} = inet:peername(Socket), @@ -1120,8 +1118,8 @@ realm_meta(Realm) -> end. -%%% Key generation +%%% Key generation -spec prompt_keygen() -> key_id(). %% @private @@ -1137,7 +1135,7 @@ prompt_keygen() -> " key name separated by a space.~n~n" " Example: some.realm my.key~n", ok = io:format(Message), - Input = string:trim(io:get_line("(^C to quit): ")), + Input = get_input(), {Realm, KeyName} = case string:lexemes(Input, " ") of [R, K] -> {R, K}; @@ -1155,16 +1153,16 @@ prompt_keygen() -> end. --spec keygen() -> no_return(). +-spec create_keypair() -> no_return(). %% @private %% Execute the key generation procedure for 16k RSA keys once and then terminate. -keygen() -> +create_keypair() -> ok = file:set_cwd(zomp_dir()), KeyID = prompt_keygen(), case generate_rsa(KeyID) of ok -> halt(0); - Error -> error_exit("keygen failed with ~tp", [Error], ?FILE, ?LINE) + Error -> error_exit("create_keypair/0 failed with ~tp", [Error], ?FILE, ?LINE) end. @@ -1333,14 +1331,13 @@ loadkey(Type, {Realm, KeyName}) -> %%% Generate PLT - --spec genplt() -> no_return(). +-spec create_plt() -> no_return(). %% @private %% Generate a fresh PLT file that includes most basic core applications needed to %% make a resonable estimate of a type system, write the name of the PLT to stdout, %% and exit. -genplt() -> +create_plt() -> ok = build_plt(), halt(0). @@ -1400,6 +1397,66 @@ dialyze() -> +%%% Create Realm & Sysop + +create_realm() -> + RealmMessage = + "~n Enter a name for your new realm.~n" + " Valid names can contain only lower-case letters, numbers and the underscore.~n" + " Valid names must begin with a lower-case letter.~n", + ok = io:format(RealmMessage), + Realm = get_input(), + case valid_lower0_9(Realm) of + true -> + RealmFile = filename:join(zomp_dir(), Realm ++ ".realm"), + case filelib:is_regular(RealmFile) of + false -> + create_realm(Realm); + true -> + ok = io:format("That realm already exists. Be more original.~n"), + create_realm() + end; + false -> + ok = io:format("Bad realm name ~tp. Try again.~n", [Realm]), + create_realm() + end. + +create_realm(Realm) -> + UserNameMessage = + "~n Enter a username for the realm sysop.~n" + " Valid names can contain only lower-case letters, numbers and the underscore.~n" + " Valid names must begin with a lower-case letter.~n", + ok = io:format(UserNameMessage), + UserName = get_input(), + case valid_lower0_9(UserName) of + true -> + create_realm(Realm, UserName); + false -> + ok = io:format("Bad username ~tp. Try again.~n", [UserName]), + create_realm(Realm) + end. + + + +create_realm(Realm, UserName, UserRecord, Prime, RealmKey, PackageKey) -> + RealmMeta = + [{realm, Realm}, + {prime, Prime}, + {realm_keys, [RealmKey], + {package_keys, [PacakageKey] + {revision, 0}, + {serial, 0}, + {mirrors, []}], + ok = log(info, "Seriously, we would be creating a realm now."), + halt(0). + + +create_sysop() -> + ok = log(info, "Fo' realz, yo! We be sysoppin up in hurr!"), + halt(0). + + + %%% Network operations and package utilities @@ -1822,6 +1879,14 @@ namify(PackageID, Suffix) -> %%% User menu interface (terminal) +-spec get_input() -> string(). +%% @private +%% Provide a standard input prompt and newline sanitized return value. + +get_input() -> + string:trim(io:get_line("(^C to quit): ")). + + -spec select(Options) -> Selected when Options :: [option()], Selected :: term(). @@ -2089,6 +2154,7 @@ usage() -> "~n" "Usage:~n" " zx help~n" + " zx run~n" " zx run PackageID [Args]~n" " zx init Type PackageID~n" " zx install PackageID~n" @@ -2097,11 +2163,13 @@ usage() -> " zx drop dep PackageID~n" " zx drop key Realm KeyName~n" " zx verup Level~n" - " zx runlocal~n" + " zx runlocal [Args]~n" " zx package [Path]~n" " zx submit Path~n" - " zx keygen~n" - " zx genplt~n" + " zx create keypair~n" + " zx create plt~n" + " zx create realm~n" + " zx create sysop~n" "~n" "Where~n" " PackageID :: A string of the form Realm-Name[-Version]~n" From cc4d55288db63122a4231b5dccf4db3918cd6765 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Fri, 24 Nov 2017 19:58:06 +0900 Subject: [PATCH 10/55] wip --- zx | 188 +++++++++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 165 insertions(+), 23 deletions(-) diff --git a/zx b/zx index bfc7072..3bd8b25 100755 --- a/zx +++ b/zx @@ -668,7 +668,7 @@ package(TargetDir) -> [] -> ok = log(info, "Need to generate key"), KeyID = prompt_keygen(), - ok = generate_rsa(KeyID), + {ok, _, _} = generate_rsa(KeyID), package(KeyID, TargetDir); [KeyName] -> KeyID = {Realm, KeyName}, @@ -1144,11 +1144,14 @@ prompt_keygen() -> case {valid_lower0_9(Realm), valid_label(KeyName)} of {true, true} -> {Realm, KeyName}; - {false, _} -> + {false, true} -> ok = io:format("Bad realm name ~tp. Try again.~n", [Realm]), prompt_keygen(); {true, false} -> ok = io:format("Bad key name ~tp. Try again.~n", [KeyName]), + prompt_keygen(); + {false, false} -> + ok = io:format("NUTS! Both the key and realm names are illegal. Try again.~n"), prompt_keygen() end. @@ -1161,8 +1164,8 @@ create_keypair() -> ok = file:set_cwd(zomp_dir()), KeyID = prompt_keygen(), case generate_rsa(KeyID) of - ok -> halt(0); - Error -> error_exit("create_keypair/0 failed with ~tp", [Error], ?FILE, ?LINE) + {ok, _, _} -> halt(0); + Error -> error_exit("create_keypair/0 failed with ~tp", [Error], ?FILE, ?LINE) end. @@ -1198,7 +1201,7 @@ generate_rsa({Realm, KeyName}) -> ok = log(info, "~ts and ~ts agree", [KeyFile, PubFile]), ok = log(info, "Wrote private key to: ~ts.", [KeyFile]), ok = log(info, "Wrote public key to: ~ts.", [PubFile]), - ok; + {ok, KeyFile, PubFile}; false -> ok = lists:foreach(fun file:delete/1, [PemFile, KeyFile, PubFile]), ok = log(error, "Something has gone wrong."), @@ -1400,11 +1403,12 @@ dialyze() -> %%% Create Realm & Sysop create_realm() -> - RealmMessage = - "~n Enter a name for your new realm.~n" + Instructions = + "~n" + " Enter a name for your new realm.~n" " Valid names can contain only lower-case letters, numbers and the underscore.~n" " Valid names must begin with a lower-case letter.~n", - ok = io:format(RealmMessage), + ok = io:format(Instructions), Realm = get_input(), case valid_lower0_9(Realm) of true -> @@ -1422,32 +1426,144 @@ create_realm() -> end. create_realm(Realm) -> - UserNameMessage = - "~n Enter a username for the realm sysop.~n" + HostInstructions = + "~n" + " Enter the prime (permanent) server's publicly accessible hostname or~n" + " address. If prime is identified by an address and not a name, enter it~n" + " as either a normal IPv4 dot-notation or IPv6 colon-notation.~n" + " Note that address ranges will not be checked for validity.~n", + ok = io:format(HostInstructions), + HostString = get_input(), + Host = + case inet:parse_address(HostString) of + {ok, Address} -> Address; + {error, einval} -> HostString + end, + PortInstructions = + " Enter the port number the host will be listening on.~n" + " The port can be any number from 1 to 65535.~n" + " [Press enter for the default: 11311]~n", + ok = io:format(PortInstructions), + case get_input() of + "" -> + create_realm(Realm, {HostString, 11311}); + S -> + try + case list_to_integer(S) of + Port when 16#ffff >= Port, Port > 0 -> + create_realm(Realm, {Host, Port}); + Illegal -> + Whoops = "~p is out of bounds (1~65535). Try again...", + ok = io:format(Whoops, [Illegal]), + create_realm(Realm) + end + catch error:badarg -> + Error = "~tp is not a port number. Try again...", + ok = io:format(Error, [S]), + create_realm(Realm) + end + end. + +create_realm(Realm, Prime) -> + Instructions = + "~n" + " Enter a username for the realm sysop.~n" " Valid names can contain only lower-case letters, numbers and the underscore.~n" " Valid names must begin with a lower-case letter.~n", - ok = io:format(UserNameMessage), + ok = io:format(Instructions), UserName = get_input(), case valid_lower0_9(UserName) of true -> - create_realm(Realm, UserName); + create_realm(Realm, Prime, UserName); false -> ok = io:format("Bad username ~tp. Try again.~n", [UserName]), - create_realm(Realm) + create_realm(Realm, Prime) end. +create_realm(Realm, Prime, UserName) -> + Instructions = + "~n" + " Enter an email address for the realm sysop.~n" + " Valid email address rules apply though the checking done here is quite~n" + " minimal. Check the address you enter carefully. The only people who will~n" + " suffer from an invalid address are your users.~n", + ok = io:format(Instructions), + Email = get_input(), + [User, Host] = string:lexemes(Email, "@"), + case {valid_lower0_9(User), valid_label(Host)} of + {true, true} -> + create_realm(Realm, Prime, UserName, Email); + {false, true} -> + Message = "The user part of the email address seems invalid. Try again.~n", + ok = io:format(Message), + create_realm(Realm, Prime, UserName); + {true, false} -> + Message = "The host part of the email address seems invalid. Try again.~n", + ok = io:format(Message), + create_realm(Realm, Prime, UserName); + {false, false} -> + Message = "This email address seems like its totally bonkers. Try again.~n", + ok = io:format(Message), + create_realm(Realm, Prime, UserName) + end. - -create_realm(Realm, UserName, UserRecord, Prime, RealmKey, PackageKey) -> +create_realm(Realm, Prime, UserName, Email) -> + Instructions = + "~n" + " Enter the real name (or whatever name people will recognize) for the sysop.~n" + " There are no rules for this one. Any valid UTF-8 printables are legal.~n", + ok = io:format(Instructions), + RealName = get_input(), + ok = io:format("~nGenerating keys. This might take a while, so settle in...~n"), + {ok, RealmKey, RealmPub} = generate_rsa({Realm, Realm ++ ".1.realm"}), + {ok, PackageKey, PackagePub} = generate_rsa({Realm, Realm ++ ".1.package"}), + {ok, SysopKey, SysopPub} = generate_rsa({Realm, UserName ++ ".1"}), + AllKeys = [RealmKey, RealmPub, PackageKey, PackagePub, SysopKey, SysopPub], + Copy = + fun(From) -> + To = filename:basename(From), + case filelib:is_file(To) of + true -> + M = "Whoops! Keyfile local destination ~tp exists! Aborting", + ok = log(error, M, [To]), + ok = log(info, "Undoing all changes..."), + ok = lists:foreach(fun file:delete/1, AllKeys), + halt(0); + false -> + {ok, _} = file:copy(From, To), + log(info, "Copying ~tp to the local directory", [From]) + end + end, + Drop = + fun(File) -> + ok = file:delete(File), + log(info, "Deleting ~tp", [File]) + end, + DangerousKeys = [PackageKey, SysopKey], + ok = lists:foreach(Copy, AllKeys), + ok = lists:foreach(Drop, DangerousKeys), + Message = + "~n" + " All of the keys generated have been moved to the current directory.~n" + " MAKE AND SECURELY STORE COPIES OF THESE KEYS.~n" + " The private package key and private sysop login key have been deleted from the~n" + " zomp key directory. These should only exist on your local system, not a prime.~n" + " realm server (particularly if other services are run on that machine).~n" + " Your package and sysop keys will need to be copied to the ~~/.zomp/keys/~p/~n" + " directory on your personal or dev machine.", + ok = io:format(Message, [Realm]), + Timestamp = calendar:now_to_universal_time(erlang:timestamp()), + UserRecord = {{UserName, Realm}, [SysopPub], Email, RealName, 1, Timestamp}, RealmMeta = [{realm, Realm}, - {prime, Prime}, - {realm_keys, [RealmKey], - {package_keys, [PacakageKey] {revision, 0}, - {serial, 0}, - {mirrors, []}], - ok = log(info, "Seriously, we would be creating a realm now."), + {prime, Prime}, + {private, []}, + {mirrors, []}, + {sysops, [UserRecord]}, + {realm_keys, [RealmPub]}, + {package_keys, [PackagePub]}], + ok = log(info, "Would be writing ~tp", [RealmMeta]), halt(0). @@ -1961,7 +2077,33 @@ hurr() -> io:format("That isn't an option.~n"). -%%% Directory Management +%%% Directory & File Management + +%-spec move_file(From, To) -> Result +% when From :: file:filename(), +% To :: file:filename(), +% Result :: ok +% | {error, Reason}, +% Reason :: bad_source +% | destination_exists +% | file:posix(). +%%% @private +%%% Utility function to safely copy a file From one path To another without clobbering the +%%% destination in the event it already exists. Both the source and the destination must be +%%% complete filenames, not directories. +% +%move_file(From, To) -> +% case {filelib:is_regular(From), filelib:is_file(To)} of +% {false, false} -> +% case file:copy(From, To) of +% {ok, _} -> file:delete(From); +% Error -> Error +% end; +% {true, _} -> +% {error, bad_source}; +% {false, true} -> +% {error, destination_exists} +% end. -spec ensure_zomp_home() -> ok. @@ -2248,4 +2390,4 @@ log(Level, Format, Args) -> warning -> "[WARNING]"; error -> "[ERROR]" end, - io:format("~s ~p: " ++ Format ++ "~n", [Tag, self() | Args]). + io:format("~p ~s: " ++ Format ++ "~n", [self(), Tag | Args]). From e765209ee33039236dc7aeaeebb458cbfcdaf7d8 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Fri, 24 Nov 2017 22:40:05 +0900 Subject: [PATCH 11/55] wip --- zx | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/zx b/zx index 3bd8b25..91d3505 100755 --- a/zx +++ b/zx @@ -1151,7 +1151,7 @@ prompt_keygen() -> ok = io:format("Bad key name ~tp. Try again.~n", [KeyName]), prompt_keygen(); {false, false} -> - ok = io:format("NUTS! Both the key and realm names are illegal. Try again.~n"), + ok = io:format("NUTS! Both key and realm names are illegal. Try again.~n"), prompt_keygen() end. @@ -1165,7 +1165,7 @@ create_keypair() -> KeyID = prompt_keygen(), case generate_rsa(KeyID) of {ok, _, _} -> halt(0); - Error -> error_exit("create_keypair/0 failed with ~tp", [Error], ?FILE, ?LINE) + Error -> error_exit("create_keypair/0 error: ~tp", [Error], ?FILE, ?LINE) end. @@ -1406,8 +1406,8 @@ create_realm() -> Instructions = "~n" " Enter a name for your new realm.~n" - " Valid names can contain only lower-case letters, numbers and the underscore.~n" - " Valid names must begin with a lower-case letter.~n", + " Names can contain only lower-case letters, numbers and the underscore.~n" + " Names must begin with a lower-case letter.~n", ok = io:format(Instructions), Realm = get_input(), case valid_lower0_9(Realm) of @@ -1440,6 +1440,7 @@ create_realm(Realm) -> {error, einval} -> HostString end, PortInstructions = + "~n" " Enter the port number the host will be listening on.~n" " The port can be any number from 1 to 65535.~n" " [Press enter for the default: 11311]~n", @@ -1468,8 +1469,8 @@ create_realm(Realm, Prime) -> Instructions = "~n" " Enter a username for the realm sysop.~n" - " Valid names can contain only lower-case letters, numbers and the underscore.~n" - " Valid names must begin with a lower-case letter.~n", + " Names can contain only lower-case letters, numbers and the underscore.~n" + " Names must begin with a lower-case letter.~n", ok = io:format(Instructions), UserName = get_input(), case valid_lower0_9(UserName) of @@ -1510,7 +1511,7 @@ create_realm(Realm, Prime, UserName) -> create_realm(Realm, Prime, UserName, Email) -> Instructions = "~n" - " Enter the real name (or whatever name people will recognize) for the sysop.~n" + " Enter the real name (or whatever name people recognize) for the sysop.~n" " There are no rules for this one. Any valid UTF-8 printables are legal.~n", ok = io:format(Instructions), RealName = get_input(), @@ -1531,13 +1532,13 @@ create_realm(Realm, Prime, UserName, Email) -> halt(0); false -> {ok, _} = file:copy(From, To), - log(info, "Copying ~tp to the local directory", [From]) + log(info, "Copying to local directory: ~ts", [From]) end end, Drop = fun(File) -> ok = file:delete(File), - log(info, "Deleting ~tp", [File]) + log(info, "Deleting ~ts", [File]) end, DangerousKeys = [PackageKey, SysopKey], ok = lists:foreach(Copy, AllKeys), @@ -1546,11 +1547,11 @@ create_realm(Realm, Prime, UserName, Email) -> "~n" " All of the keys generated have been moved to the current directory.~n" " MAKE AND SECURELY STORE COPIES OF THESE KEYS.~n" - " The private package key and private sysop login key have been deleted from the~n" - " zomp key directory. These should only exist on your local system, not a prime.~n" + " The private package and sysop login keys have been deleted from the~n" + " key directory. These should only exist on your local system, not a prime.~n" " realm server (particularly if other services are run on that machine).~n" - " Your package and sysop keys will need to be copied to the ~~/.zomp/keys/~p/~n" - " directory on your personal or dev machine.", + " The package and sysop keys will need to be copied to the ~~/.zomp/keys/~p/~n" + " directory on your personal or dev machine.~n", ok = io:format(Message, [Realm]), Timestamp = calendar:now_to_universal_time(erlang:timestamp()), UserRecord = {{UserName, Realm}, [SysopPub], Email, RealName, 1, Timestamp}, @@ -1563,7 +1564,7 @@ create_realm(Realm, Prime, UserName, Email) -> {sysops, [UserRecord]}, {realm_keys, [RealmPub]}, {package_keys, [PackagePub]}], - ok = log(info, "Would be writing ~tp", [RealmMeta]), + ok = log(info, "Would be writing~n ~tp", [RealmMeta]), halt(0). From 82ea25f1ec2084c78cfab6d9a8baa3636d50f437 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Wed, 29 Nov 2017 07:32:23 +0900 Subject: [PATCH 12/55] wip --- zx | 162 ++++++++++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 124 insertions(+), 38 deletions(-) diff --git a/zx b/zx index 91d3505..6bfc07b 100755 --- a/zx +++ b/zx @@ -1403,6 +1403,11 @@ dialyze() -> %%% Create Realm & Sysop create_realm() -> + ConfFile = filename:join(zomp_dir(), "zomp.conf"), + {ok, ZompConf} = file:consult(ConfFile), + create_realm(ZompConf). + +create_realm(ZompConf) -> Instructions = "~n" " Enter a name for your new realm.~n" @@ -1415,22 +1420,64 @@ create_realm() -> RealmFile = filename:join(zomp_dir(), Realm ++ ".realm"), case filelib:is_regular(RealmFile) of false -> - create_realm(Realm); + create_realm(ZompConf, Realm); true -> ok = io:format("That realm already exists. Be more original.~n"), - create_realm() + create_realm(ZompConf) end; false -> ok = io:format("Bad realm name ~tp. Try again.~n", [Realm]), - create_realm() + create_realm(ZompConf) end. -create_realm(Realm) -> +create_realm(ZompConf, Realm) -> + {external_address, XA} = lists:keyfind(external_address, 1, ZompConf), + XAString = + case inet:ntoa(XA) of + {error, einval} -> XA; + String -> String + end, + Message = + "~n" + " Enter a static, valid hostname or IPv4 or IPv6 address at which this host " + "can be reached from the public internet (or internal network if it will never " + "need to be reached from the internet).~n" + " The current public address is: ~ts. Press to keep this address.~n" + " DO NOT INCLUDE A PORT NUMBER IN THIS STEP~n", + ok = io:format(Message, [XAString]), + Input = get_input(), + ExAddress = + case + + + + {Host, Port} = + case proplists:get(external_address, 1, ZompConf) of + {external_address, ExAddress} -> + {external_port, ExPort} = lists:keyfind(external_port, 1, ZompConf), + {ExAddress, ExPort}; + false -> + prompt_prime(Realm) + end, + HostString = + Instructions = + "~n" + " Accept current config?~n" + " Host: ~ts Port: ~w~n", + ok = io:format(Instructions, [Host, Port]), + case string:trim(io:get_line("(^C to quit) [Y]/n: ")) of + "" -> create_realm(Realm, Prime); + "Y" -> create_realm(Realm, Prime); + "y" -> create_realm(Realm, Prime); + _ -> prompt_prime(Realm) + end. + +prompt_prime(Realm) -> HostInstructions = "~n" - " Enter the prime (permanent) server's publicly accessible hostname or~n" - " address. If prime is identified by an address and not a name, enter it~n" - " as either a normal IPv4 dot-notation or IPv6 colon-notation.~n" + " Enter the prime (permanent) server's publicly accessible hostname or " + "address. If prime is identified by an address and not a name, enter it " + "as either a normal IPv4 dot-notation or IPv6 colon-notation.~n" " Note that address ranges will not be checked for validity.~n", ok = io:format(HostInstructions), HostString = get_input(), @@ -1439,29 +1486,43 @@ create_realm(Realm) -> {ok, Address} -> Address; {error, einval} -> HostString end, - PortInstructions = - "~n" - " Enter the port number the host will be listening on.~n" - " The port can be any number from 1 to 65535.~n" - " [Press enter for the default: 11311]~n", - ok = io:format(PortInstructions), + +create_prime(Realm, Host) -> + ok = io:format("~n Enter the local port number on which the host listen.~n"), + case prompt_port_number() of + {ok, ExPort} -> create_prime(Realm, Host, ExPort); + error -> create_prime(Realm, Host) + end. + + +create_realm(Realm, Host, InPort) -> + Message = "~n Enter the global port number on which the host will be available.~n", + ok = io:format(Message), + case prompt_port_number() of + {ok, ExPort} -> create_prime(Realm, Host, ExPort, InPort); + error -> create_prime(Realm, Host, ExPort) + end. + +prompt_port_number() -> + Instructions = + " A port can be any number from 1 to 65535.~n" + " [Press enter to accept the default port: 11311]~n", + ok = io:format(Instructions), case get_input() of "" -> - create_realm(Realm, {HostString, 11311}); + {ok, 11311}; S -> try case list_to_integer(S) of Port when 16#ffff >= Port, Port > 0 -> - create_realm(Realm, {Host, Port}); + {ok, Port}; Illegal -> Whoops = "~p is out of bounds (1~65535). Try again...", - ok = io:format(Whoops, [Illegal]), - create_realm(Realm) + error end catch error:badarg -> - Error = "~tp is not a port number. Try again...", - ok = io:format(Error, [S]), - create_realm(Realm) + ok = io:format("~tp is not a port number. Try again...", [S]), + error end end. @@ -1485,9 +1546,9 @@ create_realm(Realm, Prime, UserName) -> Instructions = "~n" " Enter an email address for the realm sysop.~n" - " Valid email address rules apply though the checking done here is quite~n" - " minimal. Check the address you enter carefully. The only people who will~n" - " suffer from an invalid address are your users.~n", + " Valid email address rules apply though the checking done here is quite " + "minimal. Check the address you enter carefully. The only people who will " + "suffer from an invalid address are your users.~n", ok = io:format(Instructions), Email = get_input(), [User, Host] = string:lexemes(Email, "@"), @@ -1519,7 +1580,8 @@ create_realm(Realm, Prime, UserName, Email) -> {ok, RealmKey, RealmPub} = generate_rsa({Realm, Realm ++ ".1.realm"}), {ok, PackageKey, PackagePub} = generate_rsa({Realm, Realm ++ ".1.package"}), {ok, SysopKey, SysopPub} = generate_rsa({Realm, UserName ++ ".1"}), - AllKeys = [RealmKey, RealmPub, PackageKey, PackagePub, SysopKey, SysopPub], + AllKeys = [RealmKey, RealmPub, PackageKey, PackagePub, SysopKey, SysopPub], + DangerousKeys = [PackageKey, SysopKey], Copy = fun(From) -> To = filename:basename(From), @@ -1540,21 +1602,23 @@ create_realm(Realm, Prime, UserName, Email) -> ok = file:delete(File), log(info, "Deleting ~ts", [File]) end, - DangerousKeys = [PackageKey, SysopKey], ok = lists:foreach(Copy, AllKeys), ok = lists:foreach(Drop, DangerousKeys), Message = "~n" " All of the keys generated have been moved to the current directory.~n" + "~n" " MAKE AND SECURELY STORE COPIES OF THESE KEYS.~n" - " The private package and sysop login keys have been deleted from the~n" - " key directory. These should only exist on your local system, not a prime.~n" - " realm server (particularly if other services are run on that machine).~n" - " The package and sysop keys will need to be copied to the ~~/.zomp/keys/~p/~n" + "~n" + " The private package and sysop login keys have been deleted from the " + "key directory. These should only exist on your local system, not a prime " + "realm server (particularly if other services are run on that machine).~n" + " The package and sysop keys will need to be copied to the ~~/.zomp/keys/~s/~n" " directory on your personal or dev machine.~n", ok = io:format(Message, [Realm]), Timestamp = calendar:now_to_universal_time(erlang:timestamp()), UserRecord = {{UserName, Realm}, [SysopPub], Email, RealName, 1, Timestamp}, + RealmFile = filename:join(zomp_dir(), Realm ++ ".realm"), RealmMeta = [{realm, Realm}, {revision, 0}, @@ -1564,7 +1628,15 @@ create_realm(Realm, Prime, UserName, Email) -> {sysops, [UserRecord]}, {realm_keys, [RealmPub]}, {package_keys, [PackagePub]}], - ok = log(info, "Would be writing~n ~tp", [RealmMeta]), + ZompFile = filename:join(zomp_dir(), "zomp.conf"), + ZompConf = + [{prime, Prime}, + {external_port, ExPort}, + {internal_port, InPort}], + ok = write_terms(RealmFile, RealmMeta), + ok = write_terms(ZompFile, ZompConf), + ok = log(info, "Wrote to ~ts:~n ~tp", [RealmFile, RealmMeta]), + ok = log(info, "Wrote to ~ts:~n ~tp", [ZompFile, ZompConf]), halt(0). @@ -2124,6 +2196,7 @@ ensure_zomp_home() -> SubDirs = ["tmp", "key", "var", "lib", "zrp", "etc"], ok = lists:foreach(fun file:make_dir/1, SubDirs), ok = write_terms(default_realm_file(), default_realm()), + ok = write_terms("zomp.conf", default_conf()), ok = file:write_file(default_pubkey_file(), default_pubkey()), ok = log(info, "Zomp userland directory initialized."), file:set_cwd(CWD) @@ -2240,18 +2313,31 @@ realm_file(Realm) -> Realm ++ ".realm". --spec default_realm() -> RealmData - when RealmData :: [{atom(), term()}]. +-spec default_realm() -> [{Key :: atom(), Value :: term()}]. %% @private %% Returns the default realm file's data contents for the default "otpr" realm. default_realm() -> - [{name, "otpr"}, -% {prime, {"repo.psychobitch.party", 11311}}, - {prime, {"localhost", 11311}}, - {pubkey, default_pubkey_file()}, - {serial, 0}, - {mirrors, []}]. + [{realm, "otpr"}, + {revision, 0}, + {prime, {"repo.psychobitch.party", 11311}}, + {private, [{"localhost", 11311}]}, + {mirrors, []}, + {sysops, [{"otpr, ""zxq9"}]}, + {realm_keys, []}, + {package_keys, [default_pubkey_file()]}]. + + +-spec default_conf() -> [{Key :: atom(), Value :: term()}]. +%% @private +%% Return the default local config values for a zomp server. +%% The external and local port values are global values needed to make a zomp server +%% work in the face of unique port forwarding and NAT configurations outside the control +%% of the zomp server itself. zx references these values in a few places (namely when +%% setting up a mirror or prime realm). +default_conf() -> + [{external_port, 11311}, + {local_port, 11311}]. -spec default_pubkey_file() -> file:filename(). From 20f27cbcab085ab298d64caeeff2bd2bd74cfdcc Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Wed, 29 Nov 2017 14:04:44 +0900 Subject: [PATCH 13/55] Realm creation --- zx | 227 +++++++++++++++++++++++++++++++++++-------------------------- 1 file changed, 129 insertions(+), 98 deletions(-) diff --git a/zx b/zx index 6bfc07b..6f83b5b 100755 --- a/zx +++ b/zx @@ -1404,8 +1404,10 @@ dialyze() -> create_realm() -> ConfFile = filename:join(zomp_dir(), "zomp.conf"), - {ok, ZompConf} = file:consult(ConfFile), - create_realm(ZompConf). + case file:consult(ConfFile) of + {ok, ZompConf} -> create_realm(ZompConf); + {error, enoent} -> create_realm([]) + end. create_realm(ZompConf) -> Instructions = @@ -1426,107 +1428,115 @@ create_realm(ZompConf) -> create_realm(ZompConf) end; false -> - ok = io:format("Bad realm name ~tp. Try again.~n", [Realm]), + ok = io:format("Bad realm name \"~ts\". Try again.~n", [Realm]), create_realm(ZompConf) end. create_realm(ZompConf, Realm) -> - {external_address, XA} = lists:keyfind(external_address, 1, ZompConf), + ExAddress = + case lists:keyfind(external_address, 1, ZompConf) of + false -> prompt_external_address(); + {external_address, none} -> prompt_external_address(); + {external_address, Current} -> prompt_external_address(Current) + end, + create_realm(ZompConf, Realm, ExAddress). + +prompt_external_address() -> + Message = external_address_prompt(), + ok = io:format(Message), + case get_input() of + "" -> + ok = io:format("You need to enter an address.~n"), + prompt_external_address(); + String -> + parse_address(String) + end. + +prompt_external_address(Current) -> XAString = - case inet:ntoa(XA) of - {error, einval} -> XA; - String -> String + case inet:ntoa(Current) of + {error, einval} -> Current; + XAS -> XAS + end, + Message = + external_address_prompt() ++ + " [The current public address is: ~ts. Press to keep this address.]~n", + ok = io:format(Message, [XAString]), + case get_input() of + "" -> Current; + String -> parse_address(String) + end. + +external_address_prompt() -> + "~n" + " Enter a static, valid hostname or IPv4 or IPv6 address at which this host " + "can be reached from the public internet (or internal network if it will never " + "need to be reached from the internet).~n" + " DO NOT INCLUDE A PORT NUMBER IN THIS STEP~n". + +parse_address(String) -> + case inet:parse_address(String) of + {ok, Address} -> Address; + {error, einval} -> String + end. + +create_realm(ZompConf, Realm, ExAddress) -> + Current = + case lists:keyfind(external_port, 1, ZompConf) of + false -> 11311; + {external_port, none} -> 11311; + {external_port, P} -> P end, Message = "~n" - " Enter a static, valid hostname or IPv4 or IPv6 address at which this host " - "can be reached from the public internet (or internal network if it will never " - "need to be reached from the internet).~n" - " The current public address is: ~ts. Press to keep this address.~n" - " DO NOT INCLUDE A PORT NUMBER IN THIS STEP~n", - ok = io:format(Message, [XAString]), - Input = get_input(), - ExAddress = - case - - - - {Host, Port} = - case proplists:get(external_address, 1, ZompConf) of - {external_address, ExAddress} -> - {external_port, ExPort} = lists:keyfind(external_port, 1, ZompConf), - {ExAddress, ExPort}; - false -> - prompt_prime(Realm) - end, - HostString = - Instructions = - "~n" - " Accept current config?~n" - " Host: ~ts Port: ~w~n", - ok = io:format(Instructions, [Host, Port]), - case string:trim(io:get_line("(^C to quit) [Y]/n: ")) of - "" -> create_realm(Realm, Prime); - "Y" -> create_realm(Realm, Prime); - "y" -> create_realm(Realm, Prime); - _ -> prompt_prime(Realm) - end. - -prompt_prime(Realm) -> - HostInstructions = - "~n" - " Enter the prime (permanent) server's publicly accessible hostname or " - "address. If prime is identified by an address and not a name, enter it " - "as either a normal IPv4 dot-notation or IPv6 colon-notation.~n" - " Note that address ranges will not be checked for validity.~n", - ok = io:format(HostInstructions), - HostString = get_input(), - Host = - case inet:parse_address(HostString) of - {ok, Address} -> Address; - {error, einval} -> HostString - end, - -create_prime(Realm, Host) -> - ok = io:format("~n Enter the local port number on which the host listen.~n"), - case prompt_port_number() of - {ok, ExPort} -> create_prime(Realm, Host, ExPort); - error -> create_prime(Realm, Host) - end. - - -create_realm(Realm, Host, InPort) -> - Message = "~n Enter the global port number on which the host will be available.~n", + " Enter the public (external) port number at which this service should be " + "available. (This might be different from the local port number if you are " + "forwarding ports or have a complex network layout.)~n", ok = io:format(Message), - case prompt_port_number() of - {ok, ExPort} -> create_prime(Realm, Host, ExPort, InPort); - error -> create_prime(Realm, Host, ExPort) - end. + ExPort = prompt_port_number(Current), + create_realm(ZompConf, Realm, ExAddress, ExPort). -prompt_port_number() -> +create_realm(ZompConf, Realm, ExAddress, ExPort) -> + Current = + case lists:keyfind(internal_port, 1, ZompConf) of + false -> 11311; + {internal_port, none} -> 11311; + {internal_port, P} -> P + end, + Message = + "~n" + " Enter the local (internal/LAN) port number at which this service should be " + "available. (This might be different from the public port visible from the internet" + "if you are port forwarding or have a complex network layout.)~n", + ok = io:format(Message), + InPort = prompt_port_number(Current), + create_realm(ZompConf, Realm, ExAddress, ExPort, InPort). + +prompt_port_number(Current) -> Instructions = - " A port can be any number from 1 to 65535.~n" - " [Press enter to accept the default port: 11311]~n", - ok = io:format(Instructions), + " A valid port is any number from 1 to 65535." + " [Press enter to accept the current setting: ~tw]~n", + ok = io:format(Instructions, [Current]), case get_input() of "" -> - {ok, 11311}; + Current; S -> try case list_to_integer(S) of Port when 16#ffff >= Port, Port > 0 -> - {ok, Port}; + Port; Illegal -> - Whoops = "~p is out of bounds (1~65535). Try again...", - error + Whoops = "Whoops! ~tw is out of bounds (1~65535). Try again...~n", + ok = io:format(Whoops, [Illegal]), + prompt_port_number(Current) end catch error:badarg -> ok = io:format("~tp is not a port number. Try again...", [S]), - error + prompt_port_number(Current) end end. -create_realm(Realm, Prime) -> +create_realm(ZompConf, Realm, ExAddress, ExPort, InPort) -> Instructions = "~n" " Enter a username for the realm sysop.~n" @@ -1536,13 +1546,13 @@ create_realm(Realm, Prime) -> UserName = get_input(), case valid_lower0_9(UserName) of true -> - create_realm(Realm, Prime, UserName); + create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName); false -> ok = io:format("Bad username ~tp. Try again.~n", [UserName]), - create_realm(Realm, Prime) + create_realm(ZompConf, Realm, ExAddress, ExPort, InPort) end. -create_realm(Realm, Prime, UserName) -> +create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName) -> Instructions = "~n" " Enter an email address for the realm sysop.~n" @@ -1554,22 +1564,22 @@ create_realm(Realm, Prime, UserName) -> [User, Host] = string:lexemes(Email, "@"), case {valid_lower0_9(User), valid_label(Host)} of {true, true} -> - create_realm(Realm, Prime, UserName, Email); + create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email); {false, true} -> Message = "The user part of the email address seems invalid. Try again.~n", ok = io:format(Message), - create_realm(Realm, Prime, UserName); + create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName); {true, false} -> Message = "The host part of the email address seems invalid. Try again.~n", ok = io:format(Message), - create_realm(Realm, Prime, UserName); + create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName); {false, false} -> Message = "This email address seems like its totally bonkers. Try again.~n", ok = io:format(Message), - create_realm(Realm, Prime, UserName) + create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName) end. -create_realm(Realm, Prime, UserName, Email) -> +create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email) -> Instructions = "~n" " Enter the real name (or whatever name people recognize) for the sysop.~n" @@ -1604,6 +1614,21 @@ create_realm(Realm, Prime, UserName, Email) -> end, ok = lists:foreach(Copy, AllKeys), ok = lists:foreach(Drop, DangerousKeys), + Timestamp = calendar:now_to_universal_time(erlang:timestamp()), + {ok, RealmPubData} = file:read_file(RealmPub), + RealmPubRecord = + {{Realm, filename:basename(RealmPub)}, + realm, + {realm, Realm}, + crypto:hash(sha512, RealmPubData), + Timestamp}, + {ok, PackagePubData} = file:read_file(PackagePub), + PackagePubRecord = + {{Realm, filename:basename(PackagePub)}, + package, + {realm, Realm}, + crypto:hash(sha512, PackagePubData), + Timestamp}, Message = "~n" " All of the keys generated have been moved to the current directory.~n" @@ -1616,27 +1641,33 @@ create_realm(Realm, Prime, UserName, Email) -> " The package and sysop keys will need to be copied to the ~~/.zomp/keys/~s/~n" " directory on your personal or dev machine.~n", ok = io:format(Message, [Realm]), - Timestamp = calendar:now_to_universal_time(erlang:timestamp()), UserRecord = {{UserName, Realm}, [SysopPub], Email, RealName, 1, Timestamp}, RealmFile = filename:join(zomp_dir(), Realm ++ ".realm"), RealmMeta = [{realm, Realm}, {revision, 0}, - {prime, Prime}, + {prime, {ExAddress, ExPort}}, {private, []}, {mirrors, []}, {sysops, [UserRecord]}, - {realm_keys, [RealmPub]}, - {package_keys, [PackagePub]}], + {realm_keys, [RealmPubRecord]}, + {package_keys, [PackagePubRecord]}], + Realms = + case lists:keyfind(managed, 1, ZompConf) of + {managed, M} -> [Realm | M]; + false -> [Realm] + end, ZompFile = filename:join(zomp_dir(), "zomp.conf"), - ZompConf = - [{prime, Prime}, - {external_port, ExPort}, - {internal_port, InPort}], + Update = fun({K, V}, ZC) -> lists:keystore(K, 1, ZC, {K, V}) end, + NewConf = + [{managed, Realms}, + {external_address, ExAddress}, + {external_port, ExPort}, + {internal_port, InPort}], + NewZompConf = lists:foldl(Update, ZompConf, NewConf), ok = write_terms(RealmFile, RealmMeta), - ok = write_terms(ZompFile, ZompConf), - ok = log(info, "Wrote to ~ts:~n ~tp", [RealmFile, RealmMeta]), - ok = log(info, "Wrote to ~ts:~n ~tp", [ZompFile, ZompConf]), + ok = write_terms(ZompFile, NewZompConf), + ok = log(info, "Realm ~ts created.", [Realm]), halt(0). From eeac89c4c9c78ea25d7b600bab5456716caf307e Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Wed, 29 Nov 2017 16:04:11 +0900 Subject: [PATCH 14/55] Types --- zx | 141 ++++++++++++++++++++++++++++++++++++++++++------------------- 1 file changed, 97 insertions(+), 44 deletions(-) diff --git a/zx b/zx index 6f83b5b..9b711fa 100755 --- a/zx +++ b/zx @@ -31,7 +31,7 @@ -type state() :: #s{}. --type serial() :: pos_integer(). +-type serial() :: integer(). -type package_id() :: {realm(), name(), version()}. -type package() :: {realm(), name()}. -type realm() :: lower0_9(). @@ -48,7 +48,7 @@ -type key_name() :: label(). -type lower0_9() :: [$a..$z | $0..$9 | $_]. -type label() :: [$a..$z | $0..$9 | $_ | $- | $.]. --type package_meta() :: #{}. +-type package_meta() :: map(). @@ -178,9 +178,10 @@ run(Identifier, Args) -> initialize(Type, PackageID) -> PackageString = package_string(PackageID), ok = log(info, "Initializing ~s...", [PackageString]), - Meta = [{package_id, PackageID}, - {deps, []}, - {type, Type}], + MetaList = [{package_id, PackageID}, + {deps, []}, + {type, Type}], + Meta = maps:from_list(MetaList), ok = write_meta(Meta), ok = log(info, "Project ~tp initialized.", [PackageString]), Message = @@ -312,7 +313,7 @@ ensure_installed(PackageID = {Realm, Name, Version}) -> Name :: name(), Version :: version(), Result :: exact - | {ok, version()} + | {ok, package_id()} | not_found. %% @private %% Fetch and install the latest compatible version of the given package ID, whether @@ -482,7 +483,7 @@ set_version(VersionString) -> update_version(Arg) -> Meta = read_meta(), - {package_id, PackageID} = lists:keyfind(package_id, 1, Meta), + PackageID = maps:get(package_id, Meta), update_version(Arg, PackageID, Meta). @@ -528,7 +529,7 @@ update_version(NewVersion, {Realm, Name, OldVersion}, OldMeta) -> update_version(Realm, Name, OldVersion, NewVersion, OldMeta) -> PackageID = {Realm, Name, NewVersion}, - NewMeta = lists:keystore(package_id, 1, OldMeta, {package_id, PackageID}), + NewMeta = maps:put(package_id, PackageID, OldMeta), ok = write_meta(NewMeta), ok = log(info, "Version changed from ~s to ~s.", @@ -546,11 +547,11 @@ update_version(Realm, Name, OldVersion, NewVersion, OldMeta) -> drop_dep(PackageID) -> PackageString = package_string(PackageID), Meta = read_meta(), - {deps, Deps} = lists:keyfind(deps, 1, Meta), + Deps = maps:get(deps, Meta), case lists:member(PackageID, Deps) of true -> NewDeps = lists:delete(PackageID, Deps), - NewMeta = lists:keystore(deps, 1, Meta, {deps, NewDeps}), + NewMeta = maps:put(deps, NewDeps, Meta), ok = write_meta(NewMeta), Message = "~ts removed from dependencies.", ok = log(info, Message, [PackageString]), @@ -660,7 +661,7 @@ execute(#s{type = lib, realm = Realm, name = Name, version = Version}, _) -> package(TargetDir) -> ok = log(info, "Packaging ~ts", [TargetDir]), Meta = read_meta(TargetDir), - {package_id, {Realm, _, _}} = lists:keyfind(package_id, 1, Meta), + {Realm, _, _} = maps:get(package_id, Meta), KeyDir = filename:join([zomp_dir(), "key", Realm]), ok = force_dir(KeyDir), Pattern = KeyDir ++ "/*.key.der", @@ -689,7 +690,7 @@ package(TargetDir) -> package(KeyID, TargetDir) -> Meta = read_meta(TargetDir), - {package_id, PackageID} = lists:keyfind(package_id, 1, Meta), + PackageID = maps:get(package_id, Meta), true = element(1, PackageID) == element(1, KeyID), PackageString = package_string(PackageID), ZrpFile = PackageString ++ ".zrp", @@ -710,7 +711,8 @@ package(KeyID, TargetDir) -> {ok, Key} = loadkey(private, KeyID), {ok, TgzBin} = file:read_file(TgzFile), Sig = public_key:sign(TgzBin, sha512, Key), - FinalMeta = [{modules, Modules}, {sig, {KeyID, Sig}} | Meta], + Add = fun({K, V}, M) -> maps:put(K, V, M) end, + FinalMeta = lists:foldl(Add, Meta, [{modules, Modules}, {sig, {KeyID, Sig}}]), ok = file:write_file("zomp.meta", term_to_binary(FinalMeta)), ok = erl_tar:create(ZrpFile, ["zomp.meta", TgzFile]), ok = file:delete(TgzFile), @@ -946,7 +948,7 @@ confirm_serial(Realm, Socket, Hosts) -> Socket; {ok, Current} when Current > Serial -> ok = log(info, "Node's serial newer than ours. Storing."), - NewSerials = lists:keystore(Realm, 1, Current, Serials), + NewSerials = lists:keystore(Realm, 1, Current, {Realm, Serials}), {ok, Host} = inet:peername(Socket), ok = write_terms(hosts_cache_file(Realm), [Host | Hosts]), ok = write_terms(SerialFile, NewSerials), @@ -1402,6 +1404,12 @@ dialyze() -> %%% Create Realm & Sysop +-spec create_realm() -> no_return(). +%% @private +%% Prompt the user to input the information necessary to create a new zomp realm, +%% package the data appropriately for the server and deliver the final keys and +%% realm file to the user. + create_realm() -> ConfFile = filename:join(zomp_dir(), "zomp.conf"), case file:consult(ConfFile) of @@ -1409,6 +1417,10 @@ create_realm() -> {error, enoent} -> create_realm([]) end. + +-spec create_realm(ZompConf) -> no_return() + when ZompConf :: [{Key :: atom(), Value :: term()}]. + create_realm(ZompConf) -> Instructions = "~n" @@ -1432,6 +1444,11 @@ create_realm(ZompConf) -> create_realm(ZompConf) end. + +-spec create_realm(ZompConf, Realm) -> no_return() + when ZompConf :: [{Key :: atom(), Value :: term()}], + Realm :: realm(). + create_realm(ZompConf, Realm) -> ExAddress = case lists:keyfind(external_address, 1, ZompConf) of @@ -1441,6 +1458,10 @@ create_realm(ZompConf, Realm) -> end, create_realm(ZompConf, Realm, ExAddress). + +-spec prompt_external_address() -> Result + when Result :: inet:hostname() | inet:ip_address(). + prompt_external_address() -> Message = external_address_prompt(), ok = io:format(Message), @@ -1452,6 +1473,11 @@ prompt_external_address() -> parse_address(String) end. + +-spec prompt_external_address(Current) -> Result + when Current :: inet:hostname() | inet:ip_address(), + Result :: inet:hostname() | inet:ip_address(). + prompt_external_address(Current) -> XAString = case inet:ntoa(Current) of @@ -1467,6 +1493,9 @@ prompt_external_address(Current) -> String -> parse_address(String) end. + +-spec external_address_prompt() -> string(). + external_address_prompt() -> "~n" " Enter a static, valid hostname or IPv4 or IPv6 address at which this host " @@ -1474,12 +1503,21 @@ external_address_prompt() -> "need to be reached from the internet).~n" " DO NOT INCLUDE A PORT NUMBER IN THIS STEP~n". + +-spec parse_address(string()) -> inet:hostname() | inet:ip_address(). + parse_address(String) -> case inet:parse_address(String) of {ok, Address} -> Address; {error, einval} -> String end. + +-spec create_realm(ZompConf, Realm, ExAddress) -> no_return() + when ZompConf :: [{Key :: atom(), Value :: term()}], + Realm :: realm(), + ExAddress :: inet:hostname() | inet:ip_address(). + create_realm(ZompConf, Realm, ExAddress) -> Current = case lists:keyfind(external_port, 1, ZompConf) of @@ -1496,6 +1534,13 @@ create_realm(ZompConf, Realm, ExAddress) -> ExPort = prompt_port_number(Current), create_realm(ZompConf, Realm, ExAddress, ExPort). + +-spec create_realm(ZompConf, Realm, ExAddress, ExPort) -> no_return() + when ZompConf :: [{Key :: atom(), Value :: term()}], + Realm :: realm(), + ExAddress :: inet:hostname() | inet:ip_address(), + ExPort :: inet:port_number(). + create_realm(ZompConf, Realm, ExAddress, ExPort) -> Current = case lists:keyfind(internal_port, 1, ZompConf) of @@ -1512,6 +1557,11 @@ create_realm(ZompConf, Realm, ExAddress, ExPort) -> InPort = prompt_port_number(Current), create_realm(ZompConf, Realm, ExAddress, ExPort, InPort). + +-spec prompt_port_number(Current) -> Result + when Current :: inet:port_number(), + Result :: inet:port_number(). + prompt_port_number(Current) -> Instructions = " A valid port is any number from 1 to 65535." @@ -1536,6 +1586,14 @@ prompt_port_number(Current) -> end end. + +-spec create_realm(ZompConf, Realm, ExAddress, ExPort, InPort) -> no_return() + when ZompConf :: [{Key :: atom(), Value :: term()}], + Realm :: realm(), + ExAddress :: inet:hostname() | inet:ip_address(), + ExPort :: inet:port_number(), + InPort :: inet:port_number(). + create_realm(ZompConf, Realm, ExAddress, ExPort, InPort) -> Instructions = "~n" @@ -1552,6 +1610,15 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort) -> create_realm(ZompConf, Realm, ExAddress, ExPort, InPort) end. + +-spec create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName) -> no_return() + when ZompConf :: [{Key :: atom(), Value :: term()}], + Realm :: realm(), + ExAddress :: inet:hostname() | inet:ip_address(), + ExPort :: inet:port_number(), + InPort :: inet:port_number(), + UserName :: string(). + create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName) -> Instructions = "~n" @@ -1579,6 +1646,17 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName) -> create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName) end. + +-spec create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email) -> + no_return() + when ZompConf :: [{Key :: atom(), Value :: term()}], + Realm :: realm(), + ExAddress :: inet:hostname() | inet:ip_address(), + ExPort :: inet:port_number(), + InPort :: inet:port_number(), + UserName :: string(), + Email :: string(). + create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email) -> Instructions = "~n" @@ -1671,6 +1749,8 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email) -> halt(0). +-spec create_sysop() -> no_return(). + create_sysop() -> ok = log(info, "Fo' realz, yo! We be sysoppin up in hurr!"), halt(0). @@ -1749,9 +1829,9 @@ verify(Data, Signature, PubKey) -> %% Download a package to the local cache. fetch(Socket, PackageID) -> - ok = request_zrp(Socket, PackageID), - ok = receive_zrp(Socket, PackageID), - log(info, "Fetched ~ts", [package_string(PackageID)]). + {ok, LatestID} = request_zrp(Socket, PackageID), + ok = receive_zrp(Socket, LatestID), + log(info, "Fetched ~ts", [package_string(LatestID)]). request_zrp(Socket, PackageID) -> @@ -2183,33 +2263,6 @@ hurr() -> io:format("That isn't an option.~n"). %%% Directory & File Management -%-spec move_file(From, To) -> Result -% when From :: file:filename(), -% To :: file:filename(), -% Result :: ok -% | {error, Reason}, -% Reason :: bad_source -% | destination_exists -% | file:posix(). -%%% @private -%%% Utility function to safely copy a file From one path To another without clobbering the -%%% destination in the event it already exists. Both the source and the destination must be -%%% complete filenames, not directories. -% -%move_file(From, To) -> -% case {filelib:is_regular(From), filelib:is_file(To)} of -% {false, false} -> -% case file:copy(From, To) of -% {ok, _} -> file:delete(From); -% Error -> Error -% end; -% {true, _} -> -% {error, bad_source}; -% {false, true} -> -% {error, destination_exists} -% end. - - -spec ensure_zomp_home() -> ok. %% @private %% Ensure the zomp home directory exists and is populated. From 71661e2027dec152a22d8e9371803f3734dcd97a Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Wed, 29 Nov 2017 16:08:36 +0900 Subject: [PATCH 15/55] More types --- zx | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/zx b/zx index 9b711fa..437f0cd 100755 --- a/zx +++ b/zx @@ -1834,6 +1834,12 @@ fetch(Socket, PackageID) -> log(info, "Fetched ~ts", [package_string(LatestID)]). +-spec request_zrp(Socket, PackageID) -> Result + when Socket :: gen_tcp:socket(), + PackageID :: package_id(), + Result :: {ok, Latest :: package_id()} + | {error, Reason :: timeout | term()}. + request_zrp(Socket, PackageID) -> ok = send(Socket, {fetch, PackageID}), receive @@ -1852,6 +1858,11 @@ request_zrp(Socket, PackageID) -> end. +-spec receive_zrp(Socket, PackageID) -> Result + when Socket :: gen_tcp:socket(), + PackageID :: package_id(), + Result :: ok | {error, timeout}. + receive_zrp(Socket, PackageID) -> receive {tcp, Socket, Bin} -> From e60a5d419195aa006709a99a78c41e5e870a212d Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Wed, 29 Nov 2017 17:53:15 +0900 Subject: [PATCH 16/55] Realmfile creation --- zx | 85 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 81 insertions(+), 4 deletions(-) diff --git a/zx b/zx index 437f0cd..e4a7dc8 100755 --- a/zx +++ b/zx @@ -85,11 +85,15 @@ start(["set", "dep", PackageString]) -> set_dep(PackageID); start(["set", "version", VersionString]) -> set_version(VersionString); +start(["add", "realm", RealmFile]) -> + add_realm(RealmFile); start(["drop", "dep", PackageString]) -> PackageID = package_id(PackageString), drop_dep(PackageID); start(["drop", "key", KeyID]) -> drop_key(KeyID); +start(["drop", "realm", Realm]) -> + drop_realm(Realm); start(["verup", Level]) -> verup(Level); start(["runlocal" | Args]) -> @@ -115,6 +119,8 @@ start(["create", "plt"]) -> create_plt(); start(["create", "realm"]) -> create_realm(); +start(["create", "realmfile", Realm]) -> + create_realmfile(Realm); start(["create", "sysop"]) -> create_sysop(); start(_) -> @@ -538,6 +544,22 @@ update_version(Realm, Name, OldVersion, NewVersion, OldMeta) -> +%%% Add realm + +-spec add_realm(Path) -> no_return() + when Path :: file:filename(). + +add_realm(Path) -> + case filelib:is_regular(Path) of + true -> + ok = log(info, "I would install this now, were I implemented."), + halt(0); + false -> + ok = log(warning, "Realm file not found at ~ts.", [Path]), + halt(1) + end. + + %%% Drop dependency -spec drop_dep(package_id()) -> no_return(). @@ -585,6 +607,15 @@ drop_key({Realm, KeyName}) -> end. +%%% Drop realm + +-spec drop_realm(realm()) -> no_return(). + +drop_realm(Realm) -> + ok = log(info, "I would totally drop ~ts right now if I could.", [Realm]), + halt(0). + + %%% Update version @@ -1695,14 +1726,14 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email) -> Timestamp = calendar:now_to_universal_time(erlang:timestamp()), {ok, RealmPubData} = file:read_file(RealmPub), RealmPubRecord = - {{Realm, filename:basename(RealmPub)}, + {{Realm, filename:basename(RealmPub, ".pub.der")}, realm, {realm, Realm}, crypto:hash(sha512, RealmPubData), Timestamp}, {ok, PackagePubData} = file:read_file(PackagePub), PackagePubRecord = - {{Realm, filename:basename(PackagePub)}, + {{Realm, filename:basename(PackagePub, ".pub.der")}, package, {realm, Realm}, crypto:hash(sha512, PackagePubData), @@ -1719,7 +1750,13 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email) -> " The package and sysop keys will need to be copied to the ~~/.zomp/keys/~s/~n" " directory on your personal or dev machine.~n", ok = io:format(Message, [Realm]), - UserRecord = {{UserName, Realm}, [SysopPub], Email, RealName, 1, Timestamp}, + UserRecord = + {{UserName, Realm}, + [filename:basename(SysopPub, ".pub.der")], + Email, + RealName, + 1, + Timestamp}, RealmFile = filename:join(zomp_dir(), Realm ++ ".realm"), RealmMeta = [{realm, Realm}, @@ -1749,6 +1786,42 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email) -> halt(0). +-spec create_realmfile(realm()) -> no_return(). + +create_realmfile(Realm) -> + ConfPath = filename:join(zomp_dir(), realm_file(Realm)), + case file:consult(ConfPath) of + {ok, RealmConf} -> + ok = log(info, "Realm found, creating realm file..."), + {realm_keys, RealmKeys} = lists:keyfind(realm_keys, 1, RealmConf), + {package_keys, PackageKeys} = lists:keyfind(package_keys, 1, RealmConf), + RealmKeyIDs = [element(1, K) || K <- RealmKeys], + PackageKeyIDs = [element(1, K) || K <- PackageKeys], + create_realmfile(Realm, ConfPath, RealmKeyIDs, PackageKeyIDs); + {error, enoent} -> + ok = log(warning, "There is no configured realm called ~ts.", [Realm]), + halt(1) + end. + +-spec create_realmfile(Realm, ConfPath, RealmKeyIDs, PackageKeyIDs) -> ok + when Realm :: realm(), + ConfPath :: file:filename(), + RealmKeyIDs :: [key_id()], + PackageKeyIDs :: [key_id()]. + +create_realmfile(Realm, ConfPath, RealmKeyIDs, PackageKeyIDs) -> + {ok, CWD} = file:get_cwd(), + ok = file:set_cwd(zomp_dir()), + KeyPath = fun({R, K}) -> filename:join(["key", R, K ++ ".pub.der"]) end, + RealmKeyPaths = lists:map(KeyPath, RealmKeyIDs), + PackageKeyPaths = lists:map(KeyPath, PackageKeyIDs), + Targets = [filename:basename(ConfPath) | RealmKeyPaths ++ PackageKeyPaths], + OutFile = filename:join(CWD, Realm ++ ".zrf"), + ok = erl_tar:create(OutFile, Targets, [compressed]), + ok = log(info, "Realm file written to ~ts", [OutFile]), + halt(0). + + -spec create_sysop() -> no_return(). create_sysop() -> @@ -1835,7 +1908,7 @@ fetch(Socket, PackageID) -> -spec request_zrp(Socket, PackageID) -> Result - when Socket :: gen_tcp:socket(), + when Socket :: gen_tcp:socket(), PackageID :: package_id(), Result :: {ok, Latest :: package_id()} | {error, Reason :: timeout | term()}. @@ -2484,8 +2557,10 @@ usage() -> " zx install PackageID~n" " zx set dep PackageID~n" " zx set version Version~n" + " zx add realm RealmFile~n" " zx drop dep PackageID~n" " zx drop key Realm KeyName~n" + " zx drop realm Realm~n" " zx verup Level~n" " zx runlocal [Args]~n" " zx package [Path]~n" @@ -2493,6 +2568,7 @@ usage() -> " zx create keypair~n" " zx create plt~n" " zx create realm~n" + " zx create realmfile Realm~n" " zx create sysop~n" "~n" "Where~n" @@ -2500,6 +2576,7 @@ usage() -> " Args :: Arguments to pass to the application~n" " Type :: The project type: a standalone \"app\" or a \"lib\"~n" " Version :: Version string X, X.Y, or X.Y.Z: \"1\", \"1.2\", \"1.2.3\"~n" + " RealmFile :: Path to a valid .zrf realm file~n" " Realm :: The name of a realm as a string [:a-z:]~n" " KeyName :: The prefix of a keypair to drop~n" " Level :: The version level, one of \"major\", \"minor\", or \"patch\"~n" From c37da63bdcd4870f5fa99d9dc1cacac6e9d2a943 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Wed, 29 Nov 2017 18:08:52 +0900 Subject: [PATCH 17/55] wip --- zx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zx b/zx index e4a7dc8..d068cbe 100755 --- a/zx +++ b/zx @@ -1818,8 +1818,8 @@ create_realmfile(Realm, ConfPath, RealmKeyIDs, PackageKeyIDs) -> Targets = [filename:basename(ConfPath) | RealmKeyPaths ++ PackageKeyPaths], OutFile = filename:join(CWD, Realm ++ ".zrf"), ok = erl_tar:create(OutFile, Targets, [compressed]), - ok = log(info, "Realm file written to ~ts", [OutFile]), - halt(0). + ok = log(info, "Realm conf file written to ~ts", [OutFile]), + create_realmfile(Realm). -spec create_sysop() -> no_return(). From dac06ff5b4a765ce350669fdea38ddd12e5000fd Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Thu, 30 Nov 2017 07:01:02 +0900 Subject: [PATCH 18/55] wip --- zx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zx b/zx index d068cbe..16c101a 100755 --- a/zx +++ b/zx @@ -1783,7 +1783,7 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email) -> ok = write_terms(RealmFile, RealmMeta), ok = write_terms(ZompFile, NewZompConf), ok = log(info, "Realm ~ts created.", [Realm]), - halt(0). + create_realmfile(Realm). -spec create_realmfile(realm()) -> no_return(). @@ -1819,7 +1819,7 @@ create_realmfile(Realm, ConfPath, RealmKeyIDs, PackageKeyIDs) -> OutFile = filename:join(CWD, Realm ++ ".zrf"), ok = erl_tar:create(OutFile, Targets, [compressed]), ok = log(info, "Realm conf file written to ~ts", [OutFile]), - create_realmfile(Realm). + halt(0). -spec create_sysop() -> no_return(). From 3d2ea1d291ed8dffe1b9cd8f58459477251e78fa Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Thu, 30 Nov 2017 21:11:55 +0900 Subject: [PATCH 19/55] wip --- zx | 200 +++++++++++++++++++++++++++++++------------------------------ 1 file changed, 101 insertions(+), 99 deletions(-) diff --git a/zx b/zx index 16c101a..d7215b0 100755 --- a/zx +++ b/zx @@ -550,16 +550,41 @@ update_version(Realm, Name, OldVersion, NewVersion, OldMeta) -> when Path :: file:filename(). add_realm(Path) -> - case filelib:is_regular(Path) of - true -> - ok = log(info, "I would install this now, were I implemented."), - halt(0); - false -> - ok = log(warning, "Realm file not found at ~ts.", [Path]), + case file:read_file(Path) of + {ok, Data} -> + Digest = crypto:hash(sha512, Data), + Text = integer_to_list(binary:decode_unsigned(Digest, big), 16), + ok = log(info, "SHA512 of ~ts: ~ts", [Path, Text]), + add_realm(Path, Data); + {error, enoent} -> + ok = log(warning, "FAILED: ~ts does not exist.", [Path]), + halt(1); + {error, eisdir} -> + ok = log(warning, "FAILED: ~ts is a directory, not a realm file.", [Path]), halt(1) end. +-spec add_realm(Path, Data) -> no_return() + when Path :: file:filename(), + Data :: binary(). + +add_realm(Path, Data) -> + case erl_tar:extract({binary, Data}, [compressed, {cwd, zomp_dir()}]) of + ok -> + {Realm, _} = string:take(filename:basename(Path), ".", true), + ok = log(info, "Realm ~ts is now visible to this system.", [Realm]), + halt(0); + {error, invalid_tar_checksum} -> + ok = log(warning, "FAILED: ~ts is not a valid realm file.", [Path]), + halt(1); + {error, eof} -> + ok = log(warning, "FAILED: ~ts is not a valid realm file.", [Path]), + halt(1) + end. + + + %%% Drop dependency -spec drop_dep(package_id()) -> no_return(). @@ -612,8 +637,46 @@ drop_key({Realm, KeyName}) -> -spec drop_realm(realm()) -> no_return(). drop_realm(Realm) -> - ok = log(info, "I would totally drop ~ts right now if I could.", [Realm]), - halt(0). + ok = file:set_cwd(zomp_dir()), + RealmConf = realm_conf(Realm), + case filelib:is_regular(RealmConf) of + true -> + Message = + "~n" + " WARNING: Are you SURE you want to remove realm ~ts?~n" + " (Only \"Y\" will confirm this action.)~n", + ok = io:format(Message, [Realm]), + case get_input() of + "Y" -> + ok = file:delete(RealmConf), + clear_keys(Realm); + _ -> + ok = log(info, "Aborting."), + halt(0) + end; + false -> + ok = log(warning, "Realm conf ~ts not found.", [RealmConf]), + clear_keys(Realm) + end. + + +-spec clear_keys(realm()) -> no_return(). + +clear_keys(Realm) -> + KeyDir = filename:join([zomp_dir(), "key", Realm]), + case filelib:is_dir(KeyDir) of + true -> + ok = log(info, "Wiping key dir ~ts", [KeyDir]), + Keys = filelib:wildcard(KeyDir ++ "/**"), + Delete = fun(K) -> file:delete(K) end, + ok = lists:foreach(Delete, Keys), + ok = file:del_dir(KeyDir), + ok = log(info, "Done!"), + halt(0); + false -> + ok = log(warning, "Keydir ~ts not found", [KeyDir]), + halt(1) + end. @@ -1789,34 +1852,36 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email) -> -spec create_realmfile(realm()) -> no_return(). create_realmfile(Realm) -> - ConfPath = filename:join(zomp_dir(), realm_file(Realm)), + ConfPath = filename:join(zomp_dir(), realm_conf(Realm)), case file:consult(ConfPath) of {ok, RealmConf} -> ok = log(info, "Realm found, creating realm file..."), + {revision, Revision} = lists:keyfind(revision, 1, RealmConf), {realm_keys, RealmKeys} = lists:keyfind(realm_keys, 1, RealmConf), {package_keys, PackageKeys} = lists:keyfind(package_keys, 1, RealmConf), RealmKeyIDs = [element(1, K) || K <- RealmKeys], PackageKeyIDs = [element(1, K) || K <- PackageKeys], - create_realmfile(Realm, ConfPath, RealmKeyIDs, PackageKeyIDs); + create_realmfile(Realm, ConfPath, Revision, RealmKeyIDs, PackageKeyIDs); {error, enoent} -> ok = log(warning, "There is no configured realm called ~ts.", [Realm]), halt(1) end. --spec create_realmfile(Realm, ConfPath, RealmKeyIDs, PackageKeyIDs) -> ok +-spec create_realmfile(Realm, ConfPath, Revision, RealmKeyIDs, PackageKeyIDs) -> ok when Realm :: realm(), ConfPath :: file:filename(), + Revision :: non_neg_integer(), RealmKeyIDs :: [key_id()], PackageKeyIDs :: [key_id()]. -create_realmfile(Realm, ConfPath, RealmKeyIDs, PackageKeyIDs) -> +create_realmfile(Realm, ConfPath, Revision, RealmKeyIDs, PackageKeyIDs) -> {ok, CWD} = file:get_cwd(), ok = file:set_cwd(zomp_dir()), KeyPath = fun({R, K}) -> filename:join(["key", R, K ++ ".pub.der"]) end, RealmKeyPaths = lists:map(KeyPath, RealmKeyIDs), PackageKeyPaths = lists:map(KeyPath, PackageKeyIDs), Targets = [filename:basename(ConfPath) | RealmKeyPaths ++ PackageKeyPaths], - OutFile = filename:join(CWD, Realm ++ ".zrf"), + OutFile = filename:join(CWD, Realm ++ "." ++ integer_to_list(Revision) ++ ".zrf"), ok = erl_tar:create(OutFile, Targets, [compressed]), ok = log(info, "Realm conf file written to ~ts", [OutFile]), halt(0). @@ -2355,22 +2420,30 @@ hurr() -> io:format("That isn't an option.~n"). ensure_zomp_home() -> ZompDir = zomp_dir(), case filelib:is_dir(ZompDir) of - true -> - ok; - false -> - {ok, CWD} = file:get_cwd(), - force_dir(ZompDir), - ok = file:set_cwd(ZompDir), - SubDirs = ["tmp", "key", "var", "lib", "zrp", "etc"], - ok = lists:foreach(fun file:make_dir/1, SubDirs), - ok = write_terms(default_realm_file(), default_realm()), - ok = write_terms("zomp.conf", default_conf()), - ok = file:write_file(default_pubkey_file(), default_pubkey()), - ok = log(info, "Zomp userland directory initialized."), - file:set_cwd(CWD) + true -> ok; + false -> setup(ZompDir) end. +-spec setup(ZompDir :: file:filename()) -> ok. + +setup(ZompDir) -> + {ok, CWD} = file:get_cwd(), + ok = force_dir(ZompDir), + ok = file:set_cwd(ZompDir), + SubDirs = ["tmp", "key", "var", "lib", "zrp", "etc"], + ok = lists:foreach(fun file:make_dir/1, SubDirs), + ok = setup_otpr(), + ok = log(info, "Zomp userland directory initialized."), + file:set_cwd(CWD). + + +-spec setup_otpr() -> ok. + +setup_otpr() -> + log(info, "Here should pull otpr.0.zrf and install it..."). + + -spec zomp_dir() -> file:filename(). %% @private %% Check the host OS and return the absolute path to the zomp filesystem root. @@ -2445,87 +2518,16 @@ force_dir(Path) -> end. - -%%% Persistent Zomp State -%%% -%%% The following functions maintain constants or very light convenience functions -%%% that make use of system-wide constants such as the default realm name, default -%%% public key, and other data necessary to bootstrap the system. - - --spec default_realm_file() -> RealmFileName - when RealmFileName :: file:filename(). -%% @private -%% Return the base filename of the default realm file. - -default_realm_file() -> - realm_file(default_realm_name()). - - --spec default_realm_name() -> Name - when Name :: string(). -%% @private -%% Return the name of the default realm. - -default_realm_name() -> - "otpr". - - --spec realm_file(Realm) -> RealmFileName +-spec realm_conf(Realm) -> RealmFileName when Realm :: string(), RealmFileName :: file:filename(). %% @private %% Take a realm name, and return the name of the realm filename that would result. -realm_file(Realm) -> +realm_conf(Realm) -> Realm ++ ".realm". --spec default_realm() -> [{Key :: atom(), Value :: term()}]. -%% @private -%% Returns the default realm file's data contents for the default "otpr" realm. - -default_realm() -> - [{realm, "otpr"}, - {revision, 0}, - {prime, {"repo.psychobitch.party", 11311}}, - {private, [{"localhost", 11311}]}, - {mirrors, []}, - {sysops, [{"otpr, ""zxq9"}]}, - {realm_keys, []}, - {package_keys, [default_pubkey_file()]}]. - - --spec default_conf() -> [{Key :: atom(), Value :: term()}]. -%% @private -%% Return the default local config values for a zomp server. -%% The external and local port values are global values needed to make a zomp server -%% work in the face of unique port forwarding and NAT configurations outside the control -%% of the zomp server itself. zx references these values in a few places (namely when -%% setting up a mirror or prime realm). -default_conf() -> - [{external_port, 11311}, - {local_port, 11311}]. - - --spec default_pubkey_file() -> file:filename(). -%% @private -%% Returns the default filename of the default public key. - -default_pubkey_file() -> - "key/otpr.1.pub.der". - - --spec default_pubkey() -> binary(). -%% @private -%% This function stores the binary contents of the default public key in DER format. -%% Doing this in a function is essentially like using a herefile in Bash. - -default_pubkey() -> - <<1170526623609313331798826318972097080557896621948083159586373016346811570540623523814426011993490293167510658875163780852129579343891111576406428675491227868125570029553836721253582239727832008666977889522526670373902361492830918639140761847180559556687253204307494936306069307171528877400209962142787058308740221939755312361860413975531508150223291108422638532792576263104963638096818852870688582998502102536693308795214193253585166432265144396969870581676155216529809785753049835842318198805379857414606363727445230640910295705259948273015496668069952400995675937310182784823621435512613227257682702758407858036197683634666558131083559654726498186745235163628111760825026969986395769481087197994986427088838210048234736434112178729013032345213637282290815839027637504309538687095441687636356524193476275012030156571775013858217400602512194340193440681965829477411264954556799403863486012736713903706193506878410947578154040532592626008808497608835124296529017804159705286317715644155305350224257244260965453649874471033452253082499940845996170964558413968751507443986189697350023010630553524737002017543233621194508406455743465763341654345366274867913624544034721065244860576536017333528275040881674913063184272153529110886460286503455305330851192409414251325951739930514383412398798397169143552351929225078321776410580550088942920371869276662363003778677125037156672547734001647521245835866935294771855501141038223226549689862909953059166203977747766244019902323008152684587630882351278639697258019126733864910210128726118293540255959256597047563483255422642476502931615170150279457262340283463240052013184396583425577647694479205638188304711342708918448926127873312263215725459445847837288305565332375343953499300740443134048756072889091269830410360478466021318806219775513929766205963920179119585525683940978348051934951531003108279739296413836014878110298764281501544267131870022937730804080147990914120458451989661878314958524775077357936603530507381414681306510832486998678859256113064859502255575935373463709491675650991615474781558091560988205268798622776917923800097513069754689850980381850490662482961403587126912566501355644996590916922352735199214989138312856189875740424585814665007172318472691695957369820456341466786796592662135451831988129143024570641715114511174217352536557906484463741194647291182294337994718316817204867347695280457082728945911284833182013377663664430399865622471148347081767689841618546822415385957879982189694968028649835009229433349600455509536803831313830531746047425571328569634168722980491088303167148354034563578494773467308480373559768673286318322053544821433023042519594934353482721862948302631174310147010936830502360070216922584309962755494775082047690911998699570511078636376582952731884810583686700059291779239354983531555181641890341326596564548265142534064300496297926337825631921898202540803202984034394784105085299461195927463845508809485122164029528839799785844442443320039670416946533059409608926282019699119974258605650707621139750878861541251137000244133051922824004103328765954846809123299108643057388278106591988288588948726535195014652816533709432709443954841948958140326831643843906635067011302827793775757370405519240285135798743643797930642236731316466261629711900502696653563418054590076289653489719291121150266002099855392711464520928906433276097459061937053797457493166175864841786220404163949123451204756345296224150348843428777300804284267552332261715309580834396983346300530128191498649494481252342446265281499938013011901846865327797551832040198638001834019915656624142453248674154025598865589700532971711073725385563400552303085348956272116643141577079495146481883784661063082399836741351657205056526803513667042134368197760702297797779121467458147679998609606364108573808591354056588770173469993932525100580531597375569598234130308636537517111449993369547954653263045866310538500083896993112212303722148462970005994202673301481606806414256044693412925931019110552827804892050433228331280670562421203245853375417503339200768693046544396231856765919093252078432727627221414636522639011044239359484661269388619025699989119275623338551483041590123908337000853294371085777425084159087803966041644743349623092361390058115563570787103198976595362533473421958104661160820266906203090829648646902638295050336316799572281472144754384682003756790117478811155220025535420078485563985223415989335480370251115982845339833011445261624828025843177973576483738938303080242315615333593789609241843889852679993907685041671938947639167721054076202421174520920916996533102606039402530751673420224664619445635819542316713250359524898015718931583729548373297621243023115983588963506710418076848806241677618452223292483533560902680339825696167663170302616711331313490757011906928728140010004845723770802553281761773606296962670294026670439797097955228790673139658966545527614535446680187443733681726438681960897106751213102099950826404109307953852794370653372653043187474529370340385390651752792530497659674388660225:16496>>. - - - %%% Usage From b64ddffe8b4b52be87e320e98d5b8612fd6a800e Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Fri, 1 Dec 2017 23:34:16 +0900 Subject: [PATCH 20/55] wip --- zx | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/zx b/zx index d7215b0..26b26f2 100755 --- a/zx +++ b/zx @@ -730,12 +730,9 @@ execute(State = #s{type = app, realm = Realm, name = Name, version = Version}, A true = register(zx, self()), ok = inets:start(), ok = log(info, "Starting ~ts", [package_string({Realm, Name, Version})]), - AppMod = list_to_atom(Name), - {ok, Pid} = AppMod:start(normal, Args), - Mon = monitor(process, Pid), - Shell = spawn(shell, start, []), - ok = log(info, "Your shell is ~p, application is: ~p", [Shell, Pid]), - exec_wait(State#s{pid = Pid, mon = Mon}); + {ok, Apps} = application:ensure_all_started(list_to_atom(Name)), + ok = log(info, "Started, ~tp", [Apps]), + exec_wait(State#s{}); execute(#s{type = lib, realm = Realm, name = Name, version = Version}, _) -> Message = "Lib ~ts is available on the system, but is not a standalone app.", PackageString = package_string({Realm, Name, Version}), From 996e2e29b2e1586f266aebd504d73c8f9328274b Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Sun, 3 Dec 2017 16:03:08 +0900 Subject: [PATCH 21/55] wip --- zx | 368 ++++++++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 306 insertions(+), 62 deletions(-) diff --git a/zx b/zx index 26b26f2..6180a47 100755 --- a/zx +++ b/zx @@ -46,6 +46,8 @@ % DER :: binary()}. -type key_id() :: {realm(), key_name()}. -type key_name() :: label(). +-type user() :: {realm(), username()}. +-type username() :: label(). -type lower0_9() :: [$a..$z | $0..$9 | $_]. -type label() :: [$a..$z | $0..$9 | $_ | $- | $.]. -type package_meta() :: map(). @@ -87,6 +89,8 @@ start(["set", "version", VersionString]) -> set_version(VersionString); start(["add", "realm", RealmFile]) -> add_realm(RealmFile); +start(["add", "package", PackageName]) -> + add_package(PackageName); start(["drop", "dep", PackageString]) -> PackageID = package_id(PackageString), drop_dep(PackageID); @@ -584,6 +588,67 @@ add_realm(Path, Data) -> end. +-spec add_package(PackageName) -> no_return() + when PackageName :: package(). + +add_package(PackageName) -> + ok = file:set_cwd(zomp_dir()), + case string:lexemes(PackageName, "-") of + [Realm, Name] -> + case {valid_lower0_9(Realm), valid_lower0_9(Name)} of + {true, true} -> + add_package(Realm, Name); + {false, true} -> + ok = log(warning, "Invalid realm name: ~tp", [Realm]), + halt(1); + {true, false} -> + ok = log(warning, "Invalid package name: ~tp", [Name]), + halt(1); + {false, false} -> + ok = log(warning, "Invalid realm and package names."), + halt(1) + end; + _ -> + ok = log(warning, "Name ~tp is not a valid package name.", [PackageName]), + halt(1) + end. + + +-spec add_package(Realm, Name) -> no_return() + when Realm :: realm(), + Name :: name(). +%% @private +%% This sysop-only command can add a package to a realm operated by the caller. + +add_package(Realm, Name) -> + Socket = + case connect_auth(Realm) of + {ok, S} -> + S; + Error -> + M1 = "Connection failed to realm prime with ~160tp.", + ok = log(warning, M1, [Error]), + halt(1) + end, + ok = send(Socket, {add_package, {Realm, Name}}), + receive + {tcp, Socket, Bin} -> + case binary_to_term(Bin, [safe]) of + ok -> + ok = log(info, "\"~ts-~ts\" added successfully.", [Realm, Name]), + halt(0); + {error, Reason} -> + M2 = "Operation failed. Server sends reason: ~160tp", + ok = log(error, M2, [Reason]), + halt(1) + end; + {tcp_closed, Socket} -> + halt_on_unexpected_close() + after 5000 -> + ok = log(warning, "Operation timed After submission to server."), + halt(1) + end. + %%% Drop dependency @@ -649,7 +714,10 @@ drop_realm(Realm) -> case get_input() of "Y" -> ok = file:delete(RealmConf), - clear_keys(Realm); + ok = drop_prime(Realm), + ok = clear_keys(Realm), + ok = log(info, "All traces of realm ~ts have been removed."), + halt(0); _ -> ok = log(info, "Aborting."), halt(0) @@ -659,8 +727,23 @@ drop_realm(Realm) -> clear_keys(Realm) end. +-spec drop_prime(realm()) -> ok. --spec clear_keys(realm()) -> no_return(). +drop_prime(Realm) -> + Path = "zomp.conf", + case file:consult(Path) of + {ok, Conf} -> + {managed, Primes} = lists:keyfind(managed, 1, Conf), + NewPrimes = lists:delete(Realm, Primes), + NewConf = lists:keystore(managed, 1, Primes, {managed, NewPrimes}), + ok = write_terms(Path, NewConf), + log(info, "Ensuring ~ts is not a prime in ~ts", [Realm, Path]); + {error, enoent} -> + ok + end. + + +-spec clear_keys(realm()) -> ok. clear_keys(Realm) -> KeyDir = filename:join([zomp_dir(), "key", Realm]), @@ -671,11 +754,9 @@ clear_keys(Realm) -> Delete = fun(K) -> file:delete(K) end, ok = lists:foreach(Delete, Keys), ok = file:del_dir(KeyDir), - ok = log(info, "Done!"), - halt(0); + log(info, "Done!"); false -> - ok = log(warning, "Keydir ~ts not found", [KeyDir]), - halt(1) + log(warning, "Keydir ~ts not found", [KeyDir]) end. @@ -726,13 +807,22 @@ run_local(Args) -> execute(State, Args). +-spec execute(State, Args) -> no_return() + when State :: state(), + Args :: [string()]. +%% @private +%% Gets all the target application's ducks in a row and launches them, then enters +%% the exec_wait/1 loop to wait for any queries from the application. + execute(State = #s{type = app, realm = Realm, name = Name, version = Version}, Args) -> true = register(zx, self()), ok = inets:start(), ok = log(info, "Starting ~ts", [package_string({Realm, Name, Version})]), - {ok, Apps} = application:ensure_all_started(list_to_atom(Name)), + AppMod = list_to_atom(Name), + {ok, Apps} = application:ensure_all_started(AppMod), ok = log(info, "Started, ~tp", [Apps]), - exec_wait(State#s{}); + ok = pass_argv(AppMod, Args), + exec_wait(State); execute(#s{type = lib, realm = Realm, name = Name, version = Version}, _) -> Message = "Lib ~ts is available on the system, but is not a standalone app.", PackageString = package_string({Realm, Name, Version}), @@ -740,6 +830,20 @@ execute(#s{type = lib, realm = Realm, name = Name, version = Version}, _) -> halt(0). +-spec pass_argv(AppMod, Args) -> ok + when AppMod :: module(), + Args :: [string()]. +%% @private +%% Check whether the AppMod:accept_argv/1 is implemented. If so, pass in the +%% command line arguments provided. + +pass_argv(AppMod, Args) -> + case lists:member({accept_argv, 1}, AppMod:module_info(exports)) of + true -> AppMod:accept_argv(Args); + false -> ok + end. + + %%% Package generation @@ -848,6 +952,15 @@ remove_binaries(TargetDir) -> %% the registered zompc process convert itself to a gen_server via zompc_lib to %% provide more advanced functionality?) +exec_wait(State = #s{pid = none, mon = none}) -> + receive + {monitor, Pid} -> + Mon = monitor(process, Pid), + exec_wait(State#s{pid = Pid, mon = Mon}); + Unexpected -> + ok = log(warning, "Unexpected message: ~tp", [Unexpected]), + exec_wait(State) + end; exec_wait(State = #s{pid = Pid, mon = Mon}) -> receive {check_update, Requester, Ref} -> @@ -899,9 +1012,7 @@ submit(PackageFile) -> {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), Meta = binary_to_term(MetaBin), {package_id, {Realm, Package, Version}} = lists:keyfind(package_id, 1, Meta), - {sig, {KeyID = {Realm, KeyName}, _}} = lists:keyfind(sig, 1, Meta), - true = ensure_keypair(KeyID), - {ok, Socket} = connect_auth(Realm, KeyName), + {ok, Socket} = connect_auth(Realm), ok = send(Socket, {submit, {Realm, Package, Version}}), ok = receive @@ -912,7 +1023,9 @@ submit(PackageFile) -> {error, Reason} -> ok = log(info, "Server refused with ~tp", [Reason]), halt(0) - end + end; + {tcp_closed, Socket} -> + halt_on_unexpected_close() after 5000 -> ok = log(warning, "Server timed out!"), halt(0) @@ -922,7 +1035,9 @@ submit(PackageFile) -> ok = receive {tcp, Socket, Response2} -> - log(info, "Response: ~tp", [Response2]) + log(info, "Response: ~tp", [Response2]); + {tcp_closed, Socket} -> + halt_on_unexpected_close() after 5000 -> log(warning, "Server timed out!") end, @@ -941,6 +1056,13 @@ send(Socket, Message) -> gen_tcp:send(Socket, Bin). +-spec halt_on_unexpected_close() -> no_return(). + +halt_on_unexpected_close() -> + ok = log(warning, "Socket closed unexpectedly."), + halt(1). + + -spec connect_user(realm()) -> gen_tcp:socket() | no_return(). %% @private %% Connect to a given realm, whatever method is required. @@ -961,7 +1083,12 @@ connect_user(Realm) -> connect_user(Realm, []) -> {Host, Port} = get_prime(Realm), - ok = log(info, "Trying prime at ~ts:~tp", [inet:ntoa(Host), Port]), + HostString = + case io_lib:printable_unicode_list(Host) of + true -> Host; + false -> inet:ntoa(Host) + end, + ok = log(info, "Trying prime at ~ts:~160tp", [HostString, Port]), case gen_tcp:connect(Host, Port, connect_options(), 5000) of {ok, Socket} -> confirm_user(Realm, Socket, []); @@ -1002,7 +1129,9 @@ confirm_user(Realm, Socket, Hosts) -> ok = log(info, "Redirected..."), ok = disconnect(Socket), connect_user(Realm, Next ++ Hosts) - end + end; + {tcp_closed, Socket} -> + halt_on_unexpected_close() after 5000 -> ok = log(warning, "Host ~ts:~p timed out.", [Host, Port]), ok = disconnect(Socket), @@ -1053,7 +1182,9 @@ confirm_serial(Realm, Socket, Hosts) -> ok = log(info, "Node is no longer serving realm. Trying another."), ok = disconnect(Socket), connect_user(Realm, Hosts) - end + end; + {tcp_closed, Socket} -> + halt_on_unexpected_close() after 5000 -> ok = log(info, "Host timed out on confirm_serial. Trying another."), ok = disconnect(Socket), @@ -1061,30 +1192,32 @@ confirm_serial(Realm, Socket, Hosts) -> end. --spec connect_auth(Realm, KeyName) -> Result - when Realm :: realm(), - KeyName :: key_name(), - Result :: {ok, gen_tcp:socket()} - | {error, Reason :: term()}. +-spec connect_auth(Realm) -> Result + when Realm :: realm(), + Result :: {ok, gen_tcp:socket()} + | {error, Reason :: term()}. %% @private %% Connect to one of the servers in the realm constellation. -connect_auth(Realm, KeyName) -> - {ok, Key} = loadkey(private, {Realm, KeyName}), - {Host, Port} = get_prime(Realm), +connect_auth(Realm) -> + RealmConf = load_realm_conf(Realm), + {User, KeyID, Key} = prep_auth(Realm, RealmConf), + {prime, {Host, Port}} = lists:keyfind(prime, 1, RealmConf), case gen_tcp:connect(Host, Port, connect_options(), 5000) of {ok, Socket} -> ok = log(info, "Connected to ~tp prime.", [Realm]), - confirm_auth(Socket, Key); + connect_auth(Socket, Realm, User, KeyID, Key); Error = {error, E} -> ok = log(warning, "Connection problem: ~tp", [E]), {error, Error} end. - --spec confirm_auth(Socket, Key) -> Result +-spec connect_auth(Socket, Realm, User, KeyID, Key) -> Result when Socket :: gen_tcp:socket(), + Realm :: realm(), + User :: user(), + KeyID :: key_id(), Key :: term(), Result :: {ok, gen_tcp:socket()} | {error, timeout}. @@ -1092,19 +1225,118 @@ connect_auth(Realm, KeyName) -> %% Send a protocol ID string to notify the server what we're up to, disconnect %% if it does not return an "OK" response within 5 seconds. -confirm_auth(Socket, Key) -> - ok = log(info, "Would be using key ~tp now", [Key]), - {ok, {Host, Port}} = inet:peername(Socket), +connect_auth(Socket, Realm, User, KeyID, Key) -> ok = gen_tcp:send(Socket, <<"OTPR AUTH 1">>), receive - {tcp, Socket, <<"OK">>} -> - {ok, Socket} + {tcp, Socket, Bin} -> + ok = binary_to_term(Bin, [safe]), + confirm_auth(Socket, Realm, User, KeyID, Key); + {tcp_closed, Socket} -> + halt_on_unexpected_close() after 5000 -> - ok = log(warning, "Host ~s:~p timed out.", [Host, Port]), + ok = log(warning, "Host realm ~160tp prime timed out.", [Realm]), {error, auth_timeout} end. +confirm_auth(Socket, Realm, User, KeyID, Key) -> + ok = send(Socket, {User, KeyID}), + receive + {tcp, Socket, Bin} -> + case binary_to_term(Bin, [safe]) of + {sign, Blob} -> + Sig = public_key:sign(Blob, sha512, Key), + ok = send(Socket, {signed, Sig}), + confirm_auth(Socket); + {error, not_prime} -> + M1 = "Connected node is not prime for realm ~160tp", + ok = log(warning, M1, [Realm]), + ok = disconnect(Socket), + {error, not_prime}; + {error, bad_user} -> + M2 = "Bad user record ~160tp", + ok = log(warning, M2, [User]), + ok = disconnect(Socket), + {error, bad_user}; + {error, unauthorized_key} -> + M3 = "Unauthorized user key ~160tp", + ok = log(warning, M3, [KeyID]), + ok = disconnect(Socket), + {error, unauthorized_key}; + {error, Reason} -> + Message = "Could not begin auth exchange. Failed with ~160tp", + ok = log(warning, Message, [Reason]), + ok = disconnect(Socket), + {error, Reason} + end; + {tcp_closed, Socket} -> + halt_on_unexpected_close() + after 5000 -> + ok = log(warning, "Host realm ~tp prime timed out.", [Realm]), + {error, auth_timeout} + end. + + +confirm_auth(Socket) -> + receive + {tcp, Socket, Bin} -> + case binary_to_term(Bin, [safe]) of + ok -> {ok, Socket}; + Other -> {error, Other} + end; + {tcp_closed, Socket} -> + halt_on_unexpected_close() + after 5000 -> + {error, timeout} + end. + + +-spec prep_auth(Realm, RealmConf) -> {User, KeyID, Key} | no_return() + when Realm :: realm(), + RealmConf :: [term()], + User :: user(), + KeyID :: key_id(), + Key :: term(). +%% @private +%% Loads the appropriate User, KeyID and reads in a registered key for use in +%% connect_auth/4. + +prep_auth(Realm, RealmConf) -> + Users = + case file:consult("zomp.users") of + {ok, U} -> + U; + {error, enoent} -> + ok = log(warning, "You do not have any users configured."), + halt(1) + end, + {User, KeyIDs} = + case lists:keyfind(Realm, 1, Users) of + {Realm, UserName, []} -> + W = "User ~tp does not have any keys registered for realm ~tp.", + ok = log(warning, W, [UserName, Realm]), + ok = log(info, "Contact the following sysop(s) to register a key:"), + {sysops, Sysops} = lists:keyfind(sysops, 1, RealmConf), + PrintContact = + fun({_, _, Email, Name, _, _}) -> + log(info, "Sysop: ~ts Email: ~ts", [Name, Email]) + end, + ok = lists:foreach(PrintContact, Sysops), + halt(1); + {Realm, UserName, KeyNames} -> + KIDs = [{Realm, KeyName} || KeyName <- KeyNames], + {{Realm, UserName}, KIDs}; + false -> + Message = "You are not a user of the given realm: ~160tp.", + ok = log(warning, Message, [Realm]), + halt(1) + end, + KeyID = hd(KeyIDs), + true = ensure_keypair(KeyID), + {ok, Key} = loadkey(private, KeyID), + {User, KeyID, Key}. + + -spec connect_options() -> [gen_tcp:connect_option()]. %% @private %% Hide away the default options used for TCP connections. @@ -1411,10 +1643,10 @@ loadkey(Type, {Realm, KeyName}) -> {DerType, Path} = case Type of private -> - P = filename:join([zomp_dir(), "key", Realm, KeyName ++ "key.der"]), + P = filename:join([zomp_dir(), "key", Realm, KeyName ++ ".key.der"]), {'RSAPrivateKey', P}; public -> - P = filename:join([zomp_dir(), "key", Realm, KeyName ++ "pub.der"]), + P = filename:join([zomp_dir(), "key", Realm, KeyName ++ ".pub.der"]), {'RSAPublicKey', P} end, ok = log(info, "Loading key from file ~ts", [Path]), @@ -1642,8 +1874,8 @@ create_realm(ZompConf, Realm, ExAddress, ExPort) -> Message = "~n" " Enter the local (internal/LAN) port number at which this service should be " - "available. (This might be different from the public port visible from the internet" - "if you are port forwarding or have a complex network layout.)~n", + "available. (This might be different from the public port visible from the " + "internet if you are port forwarding or have a complex network layout.)~n", ok = io:format(Message), InPort = prompt_port_number(Current), create_realm(ZompConf, Realm, ExAddress, ExPort, InPort). @@ -1667,7 +1899,7 @@ prompt_port_number(Current) -> Port when 16#ffff >= Port, Port > 0 -> Port; Illegal -> - Whoops = "Whoops! ~tw is out of bounds (1~65535). Try again...~n", + Whoops = "Whoops! ~tw is out of bounds (1~65535). Try again.~n", ok = io:format(Whoops, [Illegal]), prompt_port_number(Current) end @@ -1811,12 +2043,10 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email) -> " directory on your personal or dev machine.~n", ok = io:format(Message, [Realm]), UserRecord = - {{UserName, Realm}, + {{Realm, UserName}, [filename:basename(SysopPub, ".pub.der")], Email, - RealName, - 1, - Timestamp}, + RealName}, RealmFile = filename:join(zomp_dir(), Realm ++ ".realm"), RealmMeta = [{realm, Realm}, @@ -1849,35 +2079,29 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email) -> -spec create_realmfile(realm()) -> no_return(). create_realmfile(Realm) -> - ConfPath = filename:join(zomp_dir(), realm_conf(Realm)), - case file:consult(ConfPath) of - {ok, RealmConf} -> - ok = log(info, "Realm found, creating realm file..."), - {revision, Revision} = lists:keyfind(revision, 1, RealmConf), - {realm_keys, RealmKeys} = lists:keyfind(realm_keys, 1, RealmConf), - {package_keys, PackageKeys} = lists:keyfind(package_keys, 1, RealmConf), - RealmKeyIDs = [element(1, K) || K <- RealmKeys], - PackageKeyIDs = [element(1, K) || K <- PackageKeys], - create_realmfile(Realm, ConfPath, Revision, RealmKeyIDs, PackageKeyIDs); - {error, enoent} -> - ok = log(warning, "There is no configured realm called ~ts.", [Realm]), - halt(1) - end. + RealmConf = load_realm_conf(Realm), + ok = log(info, "Realm found, creating realm file..."), + {revision, Revision} = lists:keyfind(revision, 1, RealmConf), + {realm_keys, RealmKeys} = lists:keyfind(realm_keys, 1, RealmConf), + {package_keys, PackageKeys} = lists:keyfind(package_keys, 1, RealmConf), + RealmKeyIDs = [element(1, K) || K <- RealmKeys], + PackageKeyIDs = [element(1, K) || K <- PackageKeys], + create_realmfile(Realm, Revision, RealmKeyIDs, PackageKeyIDs). --spec create_realmfile(Realm, ConfPath, Revision, RealmKeyIDs, PackageKeyIDs) -> ok + +-spec create_realmfile(Realm, Revision, RealmKeyIDs, PackageKeyIDs) -> ok when Realm :: realm(), - ConfPath :: file:filename(), Revision :: non_neg_integer(), RealmKeyIDs :: [key_id()], PackageKeyIDs :: [key_id()]. -create_realmfile(Realm, ConfPath, Revision, RealmKeyIDs, PackageKeyIDs) -> +create_realmfile(Realm, Revision, RealmKeyIDs, PackageKeyIDs) -> {ok, CWD} = file:get_cwd(), ok = file:set_cwd(zomp_dir()), KeyPath = fun({R, K}) -> filename:join(["key", R, K ++ ".pub.der"]) end, RealmKeyPaths = lists:map(KeyPath, RealmKeyIDs), PackageKeyPaths = lists:map(KeyPath, PackageKeyIDs), - Targets = [filename:basename(ConfPath) | RealmKeyPaths ++ PackageKeyPaths], + Targets = [realm_conf(Realm) | RealmKeyPaths ++ PackageKeyPaths], OutFile = filename:join(CWD, Realm ++ "." ++ integer_to_list(Revision) ++ ".zrf"), ok = erl_tar:create(OutFile, Targets, [compressed]), ok = log(info, "Realm conf file written to ~ts", [OutFile]), @@ -1987,7 +2211,9 @@ request_zrp(Socket, PackageID) -> Message = "Error receiving package ~ts: ~tp", ok = log(info, Message, [PackageString, Reason]), Error - end + end; + {tcp_closed, Socket} -> + halt_on_unexpected_close() after 60000 -> {error, timeout} end. @@ -2004,7 +2230,9 @@ receive_zrp(Socket, PackageID) -> ZrpPath = filename:join("zrp", namify_zrp(PackageID)), ok = file:write_file(ZrpPath, Bin), ok = send(Socket, ok), - log(info, "Wrote ~ts", [ZrpPath]) + log(info, "Wrote ~ts", [ZrpPath]); + {tcp_closed, Socket} -> + halt_on_unexpected_close() after 60000 -> ok = log(error, "Timeout in socket receive for ~tp", [PackageID]), {error, timeout} @@ -2525,6 +2753,22 @@ realm_conf(Realm) -> Realm ++ ".realm". +-spec load_realm_conf(Realm) -> RealmConf | no_return() + when Realm :: realm(), + RealmConf :: list(). +%% @private +%% Load the config for the given realm or halt with an error. + +load_realm_conf(Realm) -> + Path = filename:join(zomp_dir(), realm_conf(Realm)), + case file:consult(Path) of + {ok, C} -> + C; + {error, enoent} -> + ok = log(warning, "Realm ~tp is not configured.", [Realm]), + halt(1) + end. + %%% Usage From 58aafaf6921c5e53629fa57e3d6d21a6e808a8ec Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Mon, 4 Dec 2017 07:56:04 +0900 Subject: [PATCH 22/55] wip --- zx | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/zx b/zx index 6180a47..64b87d5 100755 --- a/zx +++ b/zx @@ -1011,13 +1011,13 @@ submit(PackageFile) -> {ok, PackageData} = file:read_file(PackageFile), {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), Meta = binary_to_term(MetaBin), - {package_id, {Realm, Package, Version}} = lists:keyfind(package_id, 1, Meta), + {Realm, Package, Version} = maps:get(package_id, Meta), {ok, Socket} = connect_auth(Realm), ok = send(Socket, {submit, {Realm, Package, Version}}), ok = receive - {tcp, Socket, Response1} -> - case binary_to_term(Response1) of + {tcp, Socket, RB1} -> + case binary_to_term(RB1) of ready -> ok; {error, Reason} -> @@ -1030,12 +1030,13 @@ submit(PackageFile) -> ok = log(warning, "Server timed out!"), halt(0) end, - ok = send(Socket, PackageData), + ok = gen_tcp:send(Socket, PackageData), ok = log(info, "Done sending contents of ~tp", [PackageFile]), ok = receive - {tcp, Socket, Response2} -> - log(info, "Response: ~tp", [Response2]); + {tcp, Socket, RB2} -> + Outcome = binary_to_term(RB2), + log(info, "Response: ~tp", [Outcome]); {tcp_closed, Socket} -> halt_on_unexpected_close() after 5000 -> @@ -1302,8 +1303,9 @@ confirm_auth(Socket) -> %% connect_auth/4. prep_auth(Realm, RealmConf) -> + UsersFile = filename:join(zomp_dir(), "zomp.users"), Users = - case file:consult("zomp.users") of + case file:consult(UsersFile) of {ok, U} -> U; {error, enoent} -> From 8476f3a89ad27722e0308925bd44a3b5f6cdf1c3 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Wed, 6 Dec 2017 00:48:38 +0900 Subject: [PATCH 23/55] wip --- zx | 310 +++++++++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 284 insertions(+), 26 deletions(-) diff --git a/zx b/zx index 64b87d5..f8c5246 100755 --- a/zx +++ b/zx @@ -87,10 +87,60 @@ start(["set", "dep", PackageString]) -> set_dep(PackageID); start(["set", "version", VersionString]) -> set_version(VersionString); +start(["list", "realms"]) -> + list_realms(); +start(["list", "packages", Realm]) -> + case valid_lower0_9(Realm) of + true -> + list_packages(Realm); + false -> + ok = log(error, "Bad realm name."), + halt(1) + end; +start(["list", "versions", Package]) -> + case string:lexemes(Package, "-") of + [Realm, Name] -> + list_versions({Realm, Name}); + _ -> + ok = log(error, "Bad package name."), + halt(1) + end; +start(["list", "pending", Package]) -> + case string:lexemes(Package, "-") of + [Realm, Name] -> + list_pending({Realm, Name}); + _ -> + ok = log(error, "Bad package name."), + halt(1) + end; +start(["list", "resigns", Realm]) -> + case valid_lower0_9(Realm) of + true -> + list_resigns(Realm); + false -> + ok = log(error, "Bad realm name."), + halt(1) + end; start(["add", "realm", RealmFile]) -> add_realm(RealmFile); start(["add", "package", PackageName]) -> add_package(PackageName); +start(["add", "packager", Package, UserName]) -> + add_packager(Package, UserName); +start(["add", "maintainer", Package, UserName]) -> + add_maintainer(Package, UserName); +start(["review", PackageString]) -> + PackageID = package_id(PackageString), + review(PackageID); +start(["approve", PackageString]) -> + PackageID = package_id(PackageString), + approve(PackageID); +start(["reject", PackageString]) -> + PackageID = package_id(PackageString), + reject(PackageID); +start(["resign", PackageString]) -> + PackageID = package_id(PackageString), + resign(PackageID); start(["drop", "dep", PackageString]) -> PackageID = package_id(PackageString), drop_dep(PackageID); @@ -548,6 +598,104 @@ update_version(Realm, Name, OldVersion, NewVersion, OldMeta) -> +%%% List Functions + +-spec list_realms() -> no_return(). +%% @private +%% List all currently configured realms. The definition of a "configured realm" is a +%% realm for which a .realm file exists in ~/.zomp/. The realms will be printed to +%% stdout and the program will exit. + +list_realms() -> + Pattern = filename:join(zomp_dir(), "*.realm"), + RealmFiles = filelib:wildcard(Pattern), + Realms = [filename:basename(RF, ".realm") || RF <- RealmFiles], + ok = lists:foreach(fun(R) -> io:format("~ts~n", [R]) end, Realms), + halt(0). + + +-spec list_packages(realm()) -> no_return(). +%% @private +%% Contact the indicated realm and query it for a list of registered packages and print +%% them to stdout. + +list_packages(Realm) -> + Socket = connect_user(Realm), + ok = send(Socket, {list, Realm}), + case recv_or_die(Socket) of + {ok, []} -> + ok = log(info, "Realm ~tp has no packages available.", [Realm]), + halt(0); + {ok, Packages} -> + Print = fun({R, N}) -> io:format("~ts-~ts~n", [R, N]) end, + ok = lists:foreach(Print, Packages), + halt(0); + end. + + +-spec list_versions(package()) -> no_return(). + +list_versions(Package = {Realm, Name}) -> + ok = valid_package(Package), + Socket = connect_user(Realm), + ok = send(Socket, {list, Realm, Name}), + case recv_or_die(Socket) of + {ok, []} -> + Message = "Package ~ts-~ts has no versions available.", + ok = log(info, Message, [Realm, Name]), + halt(0); + {ok, Versions} -> + Print = + fun(Version) -> + PackageString = package_string({Realm, Name, Version}), + io:format("~ts~n", [PackageString]) + end, + ok = lists:foreach(Print, Versions), + halt(0) + end. + + +-spec list_pending(package()) -> no_return(). + +list_pending(Package = {Realm, Name}) -> + ok = valid_package(Package), + Socket = connect_user(Realm), + ok = send(Socket, {pending, Package}), + case recv_or_die(Socket) of + {ok, []} -> + Message = "Package ~ts-~ts has no versions pending.", + ok = log(info, Message, [Realm, Name]), + halt(0); + {ok, Versions} -> + Print = + fun(Version) -> + PackageString = package_string({Realm, Name, Version}), + io:format("~ts~n", [PackageString]) + end, + ok = lists:foreach(Print, Versions), + halt(0) + end. + + +-spec valid_package(package()) -> ok | no_return(). + +valid_package({Realm, Name}) -> + case {valid_lower0_9(Realm), valid_lower0_9(Name)} of + {true, true} -> + ok; + {false, true} -> + ok = log(error, "Invalid realm name: ~tp", [Realm]), + halt(1); + {true, false} -> + ok = log(error, "Invalid package name: ~tp", [Name]), + halt(1); + {false, false} -> + ok = log(error, "Invalid realm ~tp and package ~tp", [Realm, Name]), + halt(1) + end. + + + %%% Add realm -spec add_realm(Path) -> no_return() @@ -621,35 +769,95 @@ add_package(PackageName) -> %% This sysop-only command can add a package to a realm operated by the caller. add_package(Realm, Name) -> - Socket = - case connect_auth(Realm) of - {ok, S} -> - S; - Error -> - M1 = "Connection failed to realm prime with ~160tp.", - ok = log(warning, M1, [Error]), - halt(1) - end, + Socket = connect_auth_or_die(Realm), ok = send(Socket, {add_package, {Realm, Name}}), - receive - {tcp, Socket, Bin} -> - case binary_to_term(Bin, [safe]) of - ok -> - ok = log(info, "\"~ts-~ts\" added successfully.", [Realm, Name]), - halt(0); - {error, Reason} -> - M2 = "Operation failed. Server sends reason: ~160tp", - ok = log(error, M2, [Reason]), - halt(1) - end; - {tcp_closed, Socket} -> - halt_on_unexpected_close() - after 5000 -> - ok = log(warning, "Operation timed After submission to server."), - halt(1) + ok = recv_or_die(Socket), + ok = log(info, "\"~ts-~ts\" added successfully.", [Realm, Name]), + halt(0). + + +list_resigns(Realm) -> + Socket = connect_auth_or_die(Realm), + ok = send(Socket, {list_resigns, Realm}), + case recv_or_die(Socket) of + {ok, []} -> + Message = "No packages pending signature in ~tp.", + ok = log(info, Message, [Realm]), + halt(0); + {ok, PackageIDs} -> + Print = + fun(PackageID) -> + PackageString = package_string(PackageID), + io:format("~ts~n", [PackageString]) + end, + ok = lists:foreach(Print, PackageIDs), + halt(0) end. +add_packager(Package, UserName) -> + ok = log(info, "Would add ~ts to packagers for ~160tp now.", [UserName, Package]), + halt(0). + + +add_maintainer(Package, UserName) -> + ok = log(info, "Would add ~ts to maintainer for ~160tp now.", [UserName, Package]), + halt(0). + + +review(PackageID) -> + PackageString = package_string(PackageID), + ZrpPath = PackageString ++ ".zrp", + ok = log(info, "Saving to ~ts, unpacking to ./~ts/", [ZrpPath, PackageString]), + ok = + case {filelib:is_file(ZrpPath), filelib:is_file(PackageString)} of + {false, false} -> + ok; + {true, false} -> + ok = log(error, "~ts already exists. Aborting.", [ZrpPath]), + halt(1); + {false, true} -> + ok = log(error, "~ts already exists. Aborting.", [PackageString]), + halt(1); + {true true} -> + Message = "~ts and ~ts already exist. Aborting.", + ok = log(error, Message, [ZrpPath, PackageString]), + halt(1); + end, + Socket = connect_auth_or_die(), + ok = send(Socket, {review, PackageID}), + ok = receive_or_die(Socket), + {ok, ZrpBin} = recieve_or_die(Socket), + ok = file:write_file(ZrpPath, ZrpBin), + ok = disconnect(Socket), + {"zomp.meta", MetaBin} = erl_tar:extract(ZrpBin, [memory, {files, "zomp.meta"}]), + Meta = binary_to_term(MetaBin, [safe]), + + + +approve(PackageID = {Realm, _, _}) -> + Socket = connect_auth_or_die(Realm), + ok = send(Socket, {approve, PackageID}), + ok = recv_or_die(Socket), + ok = log(info, "ok"), + halt(0). + + +reject(PackageID = {Realm, _, _}) -> + Socket = connect_auth_or_die(Realm), + ok = send(Socket, {reject, PackageID}), + ok = recv_or_die(Socket), + ok = log(info, "ok"), + halt(0). + + +resign(PackageID) -> + M = "Pull the indicated package", + ok = log(info, M, [PackageID]), + halt(0). + + + %%% Drop dependency -spec drop_dep(package_id()) -> no_return(). @@ -1057,6 +1265,43 @@ send(Socket, Message) -> gen_tcp:send(Socket, Bin). +-spec recv_or_die(Socket) -> Result | no_return() + when Socket :: gen_tcp:socket(), + Result :: ok | {ok, term()}. + +recv_or_die(Socket) -> + receive + {tcp, Socket, Bin} -> + case binary_to_term(Bin, [safe]) of + ok -> + ok; + {ok, Response} -> + {ok, Response}; + {error, bad_realm} -> + ok = log(warning, "No such realm at the connected node."). + halt(1); + {error, bad_package} -> + ok = log(warning, "No such package."). + halt(1) + {error, bad_version} -> + ok = log(warning, "No such version."), + halt(1); + {error, not_in_queue} -> + ok = log(warning, "Version is not queued."), + halt(1); + {error, bad_message} -> + ok = log(error, "Oh noes! zx sent an illegal message!"), + halt(1) + end; + {tcp_closed, Socket} -> + ok = log(warning, "Lost connection to node unexpectedly."), + halt(1) + after 5000 -> + ok = log(warning, "Node timed out."), + halt(1) + end. + + -spec halt_on_unexpected_close() -> no_return(). halt_on_unexpected_close() -> @@ -1169,7 +1414,7 @@ confirm_serial(Realm, Socket, Hosts) -> Socket; {ok, Current} when Current > Serial -> ok = log(info, "Node's serial newer than ours. Storing."), - NewSerials = lists:keystore(Realm, 1, Current, {Realm, Serials}), + NewSerials = lists:keystore(Realm, 1, Serials, {Realm, Current}), {ok, Host} = inet:peername(Socket), ok = write_terms(hosts_cache_file(Realm), [Host | Hosts]), ok = write_terms(SerialFile, NewSerials), @@ -1193,6 +1438,19 @@ confirm_serial(Realm, Socket, Hosts) -> end. +-spec connect_auth_or_die(realm()) -> gen_tcp:socket() | no_return(). + +connect_auth_or_die(Realm) -> + case connect_auth(Realm) of + {ok, Socket} -> + Socket; + Error -> + M1 = "Connection failed to realm prime with ~160tp.", + ok = log(warning, M1, [Error]), + halt(1) + end. + + -spec connect_auth(Realm) -> Result when Realm :: realm(), Result :: {ok, gen_tcp:socket()} From 8d97664056404ceed69620755e2a776c0faafdc9 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Wed, 6 Dec 2017 14:05:21 +0900 Subject: [PATCH 24/55] wip --- zx | 231 ++++++++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 152 insertions(+), 79 deletions(-) diff --git a/zx b/zx index f8c5246..72dbfac 100755 --- a/zx +++ b/zx @@ -90,37 +90,17 @@ start(["set", "version", VersionString]) -> start(["list", "realms"]) -> list_realms(); start(["list", "packages", Realm]) -> - case valid_lower0_9(Realm) of - true -> - list_packages(Realm); - false -> - ok = log(error, "Bad realm name."), - halt(1) - end; + ok = valid_realm(Realm), + list_packages(Realm); start(["list", "versions", Package]) -> - case string:lexemes(Package, "-") of - [Realm, Name] -> - list_versions({Realm, Name}); - _ -> - ok = log(error, "Bad package name."), - halt(1) - end; -start(["list", "pending", Package]) -> - case string:lexemes(Package, "-") of - [Realm, Name] -> - list_pending({Realm, Name}); - _ -> - ok = log(error, "Bad package name."), - halt(1) - end; + Package = string_to_package(PackageName), + list_versions(Package); +start(["list", "pending", PackageName]) -> + Package = string_to_package(PackageName), + list_pending(Package); start(["list", "resigns", Realm]) -> - case valid_lower0_9(Realm) of - true -> - list_resigns(Realm); - false -> - ok = log(error, "Bad realm name."), - halt(1) - end; + ok = valid_realm(Realm), + list_resigns(Realm); start(["add", "realm", RealmFile]) -> add_realm(RealmFile); start(["add", "package", PackageName]) -> @@ -130,8 +110,7 @@ start(["add", "packager", Package, UserName]) -> start(["add", "maintainer", Package, UserName]) -> add_maintainer(Package, UserName); start(["review", PackageString]) -> - PackageID = package_id(PackageString), - review(PackageID); + review(PackageString); start(["approve", PackageString]) -> PackageID = package_id(PackageString), approve(PackageID); @@ -167,6 +146,8 @@ start(["submit", PackageFile]) -> submit(PackageFile); start(["dialyze"]) -> dialyze(); +start(["create", "user", Realm, Name]) -> + create_user(Realm, Name); start(["create", "keypair"]) -> create_keypair(); start(["create", "plt"]) -> @@ -634,6 +615,10 @@ list_packages(Realm) -> -spec list_versions(package()) -> no_return(). +%% @private +%% List the available versions of the package indicated. The user enters a string-form +%% package name (such as "otpr-zomp") and the return values will be full package strings +%% of the form "otpr-zomp-1.2.3", one per line printed to stdout. list_versions(Package = {Realm, Name}) -> ok = valid_package(Package), @@ -656,6 +641,10 @@ list_versions(Package = {Realm, Name}) -> -spec list_pending(package()) -> no_return(). +%% @private +%% List the versions of a package that are pending review. The package name is input by the +%% user as a string of the form "otpr-zomp" and the output is a list of full package IDs, +%% printed one per line to stdout (like "otpr-zomp-3.2.2"). list_pending(Package = {Realm, Name}) -> ok = valid_package(Package), @@ -677,7 +666,34 @@ list_pending(Package = {Realm, Name}) -> end. +-spec list_resigns(realm()) -> no_return(). +%% @private +%% List the package ids of all packages waiting in the resign queue for the given realm, +%% printed to stdout one per line. + +list_resigns(Realm) -> + Socket = connect_auth_or_die(Realm), + ok = send(Socket, {list_resigns, Realm}), + case recv_or_die(Socket) of + {ok, []} -> + Message = "No packages pending signature in ~tp.", + ok = log(info, Message, [Realm]), + halt(0); + {ok, PackageIDs} -> + Print = + fun(PackageID) -> + PackageString = package_string(PackageID), + io:format("~ts~n", [PackageString]) + end, + ok = lists:foreach(Print, PackageIDs), + halt(0) + end. + + -spec valid_package(package()) -> ok | no_return(). +%% @private +%% Test whether a package() type is a valid value or not. If not, halt execution with +%% a non-zero error code, if so then return `ok'. valid_package({Realm, Name}) -> case {valid_lower0_9(Realm), valid_lower0_9(Name)} of @@ -692,6 +708,40 @@ valid_package({Realm, Name}) -> {false, false} -> ok = log(error, "Invalid realm ~tp and package ~tp", [Realm, Name]), halt(1) + end; +valid_package(Bad) -> + ok = log(error, "Invalid package() value: ~160tp", [Bad]), + halt(1). + + +-spec string_to_package(string()) -> ok | no_return(). +%% @private +%% Convert a string to a package() type if possible. If not then halt the system. + +string_to_package(String) -> + case string:lexemes(Package, "-") of + [Realm, Name] -> + Package = {Realm, Name}, + ok = valid_package(Package), + Package; + _ -> + ok = log(error, "Bad package name."), + halt(1) + end. + + +-spec valid_realm(realm()) -> ok | no_return(). +%% @private +%% Test whether a realm name is a valid realm() type (that is, a lower0_9()) or not. If not, +%% halt execution with a non-zero error code, if so then return `ok'. + +valid_realm(Realm) -> + case valid_lower0_9(Realm) of + true -> + ok; + false -> + ok = log(error, "Bad realm name."), + halt(1) end. @@ -776,25 +826,6 @@ add_package(Realm, Name) -> halt(0). -list_resigns(Realm) -> - Socket = connect_auth_or_die(Realm), - ok = send(Socket, {list_resigns, Realm}), - case recv_or_die(Socket) of - {ok, []} -> - Message = "No packages pending signature in ~tp.", - ok = log(info, Message, [Realm]), - halt(0); - {ok, PackageIDs} -> - Print = - fun(PackageID) -> - PackageString = package_string(PackageID), - io:format("~ts~n", [PackageString]) - end, - ok = lists:foreach(Print, PackageIDs), - halt(0) - end. - - add_packager(Package, UserName) -> ok = log(info, "Would add ~ts to packagers for ~160tp now.", [UserName, Package]), halt(0). @@ -805,34 +836,34 @@ add_maintainer(Package, UserName) -> halt(0). -review(PackageID) -> - PackageString = package_string(PackageID), - ZrpPath = PackageString ++ ".zrp", - ok = log(info, "Saving to ~ts, unpacking to ./~ts/", [ZrpPath, PackageString]), - ok = - case {filelib:is_file(ZrpPath), filelib:is_file(PackageString)} of - {false, false} -> - ok; - {true, false} -> - ok = log(error, "~ts already exists. Aborting.", [ZrpPath]), - halt(1); - {false, true} -> - ok = log(error, "~ts already exists. Aborting.", [PackageString]), - halt(1); - {true true} -> - Message = "~ts and ~ts already exist. Aborting.", - ok = log(error, Message, [ZrpPath, PackageString]), - halt(1); - end, +review(PackageString) -> + PackageID = package_id(PackageString), Socket = connect_auth_or_die(), ok = send(Socket, {review, PackageID}), - ok = receive_or_die(Socket), - {ok, ZrpBin} = recieve_or_die(Socket), - ok = file:write_file(ZrpPath, ZrpBin), + sending = recv_or_die(Socket), + {ok, ZrpBin} = recv_or_die(Socket), ok = disconnect(Socket), - {"zomp.meta", MetaBin} = erl_tar:extract(ZrpBin, [memory, {files, "zomp.meta"}]), + {ok, Files} = erl_tar:extract({binary, ZrpBin}, [memory]), + {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), Meta = binary_to_term(MetaBin, [safe]), - + PackageID = maps:get(package_id, Meta), + {KeyID, Signature} = maps:get(sig, Meta), + {ok, PubKey} = loadkey(public, KeyID), + TgzFile = PackageString ++ ".tgz", + {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files), + ok = verify(TgzData, Signature, PubKey), + ok = + case file:make_dir(PackageString) of + ok -> + log(info, "Will unpack to directory ./~ts", [PackageString]); + {error, Error} -> + Message = "Creating dir ./~ts failed with ~ts. Aborting." + ok = log(error, Message, [PackageString, Error]), + halt(1) + end, + ok = erl_tar:extract({binary, TgzData}, [compressed, {cwd, PackageString}]), + ok = log(info, "Unpacked and awaiting inspection."), + halt(0). approve(PackageID = {Realm, _, _}) -> @@ -851,8 +882,36 @@ reject(PackageID = {Realm, _, _}) -> halt(0). -resign(PackageID) -> - M = "Pull the indicated package", +resign(PackageString) -> + PackageID = {Realm, _, _} = package_id(PackageString), + Socket = connect_auth_or_die(Realm), + ok = send(Socket, {resign, PackageID}), + sending = recv_or_die(Socket), + {ok, ZrpBin} = recv_or_die(Socket), + {ok, Files} = erl_tar:extract({binary, ZrpBin}, [memory]), + {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), + Meta = binary_to_term(MetaBin, [safe]), + PackageID = maps:get(package_id, Meta), + {KeyID, Signature} = maps:get(sig, Meta), + {ok, PubKey} = loadkey(public, KeyID), + TgzFile = PackageString ++ ".tgz", + {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files), + ok = verify(TgzData, Signature, PubKey), + RealmConf = read_realm_conf(Realm), + {package_keys, PackageKeys} = lists:keyfind(package_keys, 1, RealmConf), + PackageKeyName = select(PackageKeys), + PackageKeyID = {Realm, PackageKeyName} + {ok, PackageKey} = loadkey(private, PackageKeyID), + ReSignature = public_key:sign(TgzData, sha512, PackageKey), + FinalMeta = maps:put(sig, {PackageKeyID, ReSignature}), + NewFiles = lists:keystore("zomp.meta", 1, term_to_binary(FinalMeta)), + ResignedZrp = PackageString ++ ".zrp", + ok = erl_tar:create(ResignedZrp, NewFiles), + {ok, ResignedBin} = file:read_file(ResignedFile), + ok = send(Socket, {resigned, ResignedBin}), + ok = recv_or_die(Socket), + ok = file:delete(ResignedZrp), + ok = disconnect(Socket), ok = log(info, M, [PackageID]), halt(0). @@ -2392,7 +2451,7 @@ install(PackageID) -> {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files), {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), Meta = binary_to_term(MetaBin), - {sig, {KeyID, Signature}} = lists:keyfind(sig, 1, Meta), + {KeyID, Signature} = maps:get(sig, 1, Meta), {ok, PubKey} = loadkey(public, KeyID), ok = ensure_package_dirs(PackageID), PackageDir = filename:join("lib", PackageString), @@ -3052,15 +3111,28 @@ usage() -> T = "~n" "zx~n" "~n" - "Usage:~n" + "Usage: zx [command] [object] [args]~n" + "~n" + "Examples:~n" " zx help~n" - " zx run~n" " zx run PackageID [Args]~n" " zx init Type PackageID~n" " zx install PackageID~n" " zx set dep PackageID~n" " zx set version Version~n" + " zx list realms~n" + " zx list packages Realm~n" + " zx list versions PackageName~n" + " zx list pending PackageName~n" + " zx list resigns Realm~n" " zx add realm RealmFile~n" + " zx add package PackageName~n" + " zx add packager PackageName~n" + " zx add maintainer PackageName~n" + " zx review PackageID~n" + " zx approve PackageID~n" + " zx reject PackageID~n" + " zx resign PackageID~n" " zx drop dep PackageID~n" " zx drop key Realm KeyName~n" " zx drop realm Realm~n" @@ -3068,6 +3140,7 @@ usage() -> " zx runlocal [Args]~n" " zx package [Path]~n" " zx submit Path~n" + " zx create user Realm Username~n" " zx create keypair~n" " zx create plt~n" " zx create realm~n" From d9cd20a41fe75b53516e52242aa132c8b5da17e2 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Fri, 8 Dec 2017 23:01:44 +0900 Subject: [PATCH 25/55] Basic repo function --- zx | 100 ++++++++++++++++++++++++++++++------------------------------- 1 file changed, 50 insertions(+), 50 deletions(-) diff --git a/zx b/zx index 72dbfac..d741cf6 100755 --- a/zx +++ b/zx @@ -92,7 +92,7 @@ start(["list", "realms"]) -> start(["list", "packages", Realm]) -> ok = valid_realm(Realm), list_packages(Realm); -start(["list", "versions", Package]) -> +start(["list", "versions", PackageName]) -> Package = string_to_package(PackageName), list_versions(Package); start(["list", "pending", PackageName]) -> @@ -118,8 +118,7 @@ start(["reject", PackageString]) -> PackageID = package_id(PackageString), reject(PackageID); start(["resign", PackageString]) -> - PackageID = package_id(PackageString), - resign(PackageID); + resign(PackageString); start(["drop", "dep", PackageString]) -> PackageID = package_id(PackageString), drop_dep(PackageID); @@ -610,7 +609,7 @@ list_packages(Realm) -> {ok, Packages} -> Print = fun({R, N}) -> io:format("~ts-~ts~n", [R, N]) end, ok = lists:foreach(Print, Packages), - halt(0); + halt(0) end. @@ -719,7 +718,7 @@ valid_package(Bad) -> %% Convert a string to a package() type if possible. If not then halt the system. string_to_package(String) -> - case string:lexemes(Package, "-") of + case string:lexemes(String, "-") of [Realm, Name] -> Package = {Realm, Name}, ok = valid_package(Package), @@ -837,11 +836,11 @@ add_maintainer(Package, UserName) -> review(PackageString) -> - PackageID = package_id(PackageString), - Socket = connect_auth_or_die(), + PackageID = {Realm, _, _} = package_id(PackageString), + Socket = connect_auth_or_die(Realm), ok = send(Socket, {review, PackageID}), - sending = recv_or_die(Socket), {ok, ZrpBin} = recv_or_die(Socket), + ok = send(Socket, ok), ok = disconnect(Socket), {ok, Files} = erl_tar:extract({binary, ZrpBin}, [memory]), {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), @@ -857,7 +856,7 @@ review(PackageString) -> ok -> log(info, "Will unpack to directory ./~ts", [PackageString]); {error, Error} -> - Message = "Creating dir ./~ts failed with ~ts. Aborting." + Message = "Creating dir ./~ts failed with ~ts. Aborting.", ok = log(error, Message, [PackageString, Error]), halt(1) end, @@ -886,7 +885,6 @@ resign(PackageString) -> PackageID = {Realm, _, _} = package_id(PackageString), Socket = connect_auth_or_die(Realm), ok = send(Socket, {resign, PackageID}), - sending = recv_or_die(Socket), {ok, ZrpBin} = recv_or_die(Socket), {ok, Files} = erl_tar:extract({binary, ZrpBin}, [memory]), {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), @@ -897,22 +895,24 @@ resign(PackageString) -> TgzFile = PackageString ++ ".tgz", {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files), ok = verify(TgzData, Signature, PubKey), - RealmConf = read_realm_conf(Realm), + RealmConf = load_realm_conf(Realm), {package_keys, PackageKeys} = lists:keyfind(package_keys, 1, RealmConf), - PackageKeyName = select(PackageKeys), - PackageKeyID = {Realm, PackageKeyName} + KeySelection = [{K, {R, K}} || {R, K} <- [element(1, K) || K <- PackageKeys]], + PackageKeyID = select(KeySelection), {ok, PackageKey} = loadkey(private, PackageKeyID), ReSignature = public_key:sign(TgzData, sha512, PackageKey), - FinalMeta = maps:put(sig, {PackageKeyID, ReSignature}), - NewFiles = lists:keystore("zomp.meta", 1, term_to_binary(FinalMeta)), - ResignedZrp = PackageString ++ ".zrp", + FinalMeta = maps:put(sig, {PackageKeyID, ReSignature}, Meta), + NewMetaBin = term_to_binary(FinalMeta), + NewFiles = lists:keystore("zomp.meta", 1, Files, {"zomp.meta", NewMetaBin}), + ResignedZrp = PackageString ++ ".zrp.resign", ok = erl_tar:create(ResignedZrp, NewFiles), - {ok, ResignedBin} = file:read_file(ResignedFile), - ok = send(Socket, {resigned, ResignedBin}), + {ok, ResignedBin} = file:read_file(ResignedZrp), + ok = gen_tcp:send(Socket, ResignedBin), ok = recv_or_die(Socket), ok = file:delete(ResignedZrp), + ok = recv_or_die(Socket), ok = disconnect(Socket), - ok = log(info, M, [PackageID]), + ok = log(info, "Resigned ~ts", [PackageString]), halt(0). @@ -1281,34 +1281,11 @@ submit(PackageFile) -> {Realm, Package, Version} = maps:get(package_id, Meta), {ok, Socket} = connect_auth(Realm), ok = send(Socket, {submit, {Realm, Package, Version}}), - ok = - receive - {tcp, Socket, RB1} -> - case binary_to_term(RB1) of - ready -> - ok; - {error, Reason} -> - ok = log(info, "Server refused with ~tp", [Reason]), - halt(0) - end; - {tcp_closed, Socket} -> - halt_on_unexpected_close() - after 5000 -> - ok = log(warning, "Server timed out!"), - halt(0) - end, + ok = recv_or_die(Socket), ok = gen_tcp:send(Socket, PackageData), ok = log(info, "Done sending contents of ~tp", [PackageFile]), - ok = - receive - {tcp, Socket, RB2} -> - Outcome = binary_to_term(RB2), - log(info, "Response: ~tp", [Outcome]); - {tcp_closed, Socket} -> - halt_on_unexpected_close() - after 5000 -> - log(warning, "Server timed out!") - end, + Outcome = recv_or_die(Socket), + log(info, "Response: ~tp", [Outcome]), ok = disconnect(Socket), halt(0). @@ -1331,17 +1308,17 @@ send(Socket, Message) -> recv_or_die(Socket) -> receive {tcp, Socket, Bin} -> - case binary_to_term(Bin, [safe]) of + case binary_to_term(Bin) of ok -> ok; {ok, Response} -> {ok, Response}; {error, bad_realm} -> - ok = log(warning, "No such realm at the connected node."). + ok = log(warning, "No such realm at the connected node."), halt(1); {error, bad_package} -> - ok = log(warning, "No such package."). - halt(1) + ok = log(warning, "No such package."), + halt(1); {error, bad_version} -> ok = log(warning, "No such version."), halt(1); @@ -1350,6 +1327,16 @@ recv_or_die(Socket) -> halt(1); {error, bad_message} -> ok = log(error, "Oh noes! zx sent an illegal message!"), + halt(1); + {error, already_exists} -> + ok = log(warning, "Server refuses: already_exists"), + halt(1); + {error, {system, Reason}} -> + Message = "Node experienced system error: ~160tp", + ok = log(warning, Message, [{error, Reason}]), + halt(1); + Unexpected -> + ok = log(warning, "Unexpected message: ~tp", [Unexpected]), halt(1) end; {tcp_closed, Socket} -> @@ -2046,6 +2033,19 @@ dialyze() -> %%% Create Realm & Sysop +-spec create_user(realm(), username()) -> no_return(). +%% @private +%% Validate the realm and username provided, prompt the user to either select a keypair +%% to use or generate a new one, and bundle a .zuser file for conveyance of the user +%% data and his relevant keys (for import into an existing zomp server via `add' +%% command like "add packager", "add maintainer" and "add sysop". + +create_user(Realm, Username) -> + Message = "Would be generating a user file for {~160tp, ~160to}.", + ok = log(info, Message, [Realm, Username]), + halt(0). + + -spec create_realm() -> no_return(). %% @private %% Prompt the user to input the information necessary to create a new zomp realm, @@ -2479,7 +2479,7 @@ extract_zrp(FileName) -> Message = "~ts is not a valid zrp archive.", error_exit(Message, [FileName], ?FILE, ?LINE); {error, Reason} -> - Message = "Extracting package file failed with: ~tp.", + Message = "Extracting package file failed with: ~160tp.", error_exit(Message, [Reason], ?FILE, ?LINE) end. From 428f7e05658bfaecfd8978747ff6a4ee81487a3f Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Fri, 8 Dec 2017 23:09:37 +0900 Subject: [PATCH 26/55] Reorder to avoid timeout --- zx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/zx b/zx index d741cf6..c6e31fc 100755 --- a/zx +++ b/zx @@ -883,6 +883,11 @@ reject(PackageID = {Realm, _, _}) -> resign(PackageString) -> PackageID = {Realm, _, _} = package_id(PackageString), + RealmConf = load_realm_conf(Realm), + {package_keys, PackageKeys} = lists:keyfind(package_keys, 1, RealmConf), + KeySelection = [{K, {R, K}} || {R, K} <- [element(1, K) || K <- PackageKeys]], + PackageKeyID = select(KeySelection), + {ok, PackageKey} = loadkey(private, PackageKeyID), Socket = connect_auth_or_die(Realm), ok = send(Socket, {resign, PackageID}), {ok, ZrpBin} = recv_or_die(Socket), @@ -895,11 +900,6 @@ resign(PackageString) -> TgzFile = PackageString ++ ".tgz", {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files), ok = verify(TgzData, Signature, PubKey), - RealmConf = load_realm_conf(Realm), - {package_keys, PackageKeys} = lists:keyfind(package_keys, 1, RealmConf), - KeySelection = [{K, {R, K}} || {R, K} <- [element(1, K) || K <- PackageKeys]], - PackageKeyID = select(KeySelection), - {ok, PackageKey} = loadkey(private, PackageKeyID), ReSignature = public_key:sign(TgzData, sha512, PackageKey), FinalMeta = maps:put(sig, {PackageKeyID, ReSignature}, Meta), NewMetaBin = term_to_binary(FinalMeta), From 11d5f3f767b1629b8c6170dd859aedd889079376 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Tue, 12 Dec 2017 08:31:25 +0900 Subject: [PATCH 27/55] wip --- zx | 208 +++++++++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 148 insertions(+), 60 deletions(-) diff --git a/zx b/zx index c6e31fc..ddd3501 100755 --- a/zx +++ b/zx @@ -348,7 +348,7 @@ ensure_installed(PackageID = {Realm, Name, Version}) -> end. --spec ensure_installed(Realm, Name, Version) -> Result +-spec ensure_installed(Realm, Name, Version) -> Result | no_return() when Realm :: realm(), Name :: name(), Version :: version(), @@ -707,13 +707,10 @@ valid_package({Realm, Name}) -> {false, false} -> ok = log(error, "Invalid realm ~tp and package ~tp", [Realm, Name]), halt(1) - end; -valid_package(Bad) -> - ok = log(error, "Invalid package() value: ~160tp", [Bad]), - halt(1). + end. --spec string_to_package(string()) -> ok | no_return(). +-spec string_to_package(string()) -> package() | no_return(). %% @private %% Convert a string to a package() type if possible. If not then halt the system. @@ -2306,35 +2303,31 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email) -> " There are no rules for this one. Any valid UTF-8 printables are legal.~n", ok = io:format(Instructions), RealName = get_input(), + create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email, RealName). + + +-spec create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email, RealName) -> + no_return() + when ZompConf :: [{Key :: atom(), Value :: term()}], + Realm :: realm(), + ExAddress :: inet:hostname() | inet:ip_address(), + ExPort :: inet:port_number(), + InPort :: inet:port_number(), + UserName :: string(), + Email :: string(), + RealName :: string(). + +create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email, RealName) -> ok = io:format("~nGenerating keys. This might take a while, so settle in...~n"), {ok, RealmKey, RealmPub} = generate_rsa({Realm, Realm ++ ".1.realm"}), {ok, PackageKey, PackagePub} = generate_rsa({Realm, Realm ++ ".1.package"}), {ok, SysopKey, SysopPub} = generate_rsa({Realm, UserName ++ ".1"}), - AllKeys = [RealmKey, RealmPub, PackageKey, PackagePub, SysopKey, SysopPub], - DangerousKeys = [PackageKey, SysopKey], - Copy = - fun(From) -> - To = filename:basename(From), - case filelib:is_file(To) of - true -> - M = "Whoops! Keyfile local destination ~tp exists! Aborting", - ok = log(error, M, [To]), - ok = log(info, "Undoing all changes..."), - ok = lists:foreach(fun file:delete/1, AllKeys), - halt(0); - false -> - {ok, _} = file:copy(From, To), - log(info, "Copying to local directory: ~ts", [From]) - end - end, - Drop = - fun(File) -> - ok = file:delete(File), - log(info, "Deleting ~ts", [File]) - end, - ok = lists:foreach(Copy, AllKeys), - ok = lists:foreach(Drop, DangerousKeys), + ok = log(info, "Generated 16k RSA pair ~ts ~ts", [RealmKey, RealmPub]), + ok = log(info, "Generated 16k RSA pair ~ts ~ts", [PackageKey, PackagePub]), + ok = log(info, "Generated 16k RSA pair ~ts ~ts", [SysopKey, SysopPub]), + Timestamp = calendar:now_to_universal_time(erlang:timestamp()), + {ok, RealmPubData} = file:read_file(RealmPub), RealmPubRecord = {{Realm, filename:basename(RealmPub, ".pub.der")}, @@ -2349,25 +2342,12 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email) -> {realm, Realm}, crypto:hash(sha512, PackagePubData), Timestamp}, - Message = - "~n" - " All of the keys generated have been moved to the current directory.~n" - "~n" - " MAKE AND SECURELY STORE COPIES OF THESE KEYS.~n" - "~n" - " The private package and sysop login keys have been deleted from the " - "key directory. These should only exist on your local system, not a prime " - "realm server (particularly if other services are run on that machine).~n" - " The package and sysop keys will need to be copied to the ~~/.zomp/keys/~s/~n" - " directory on your personal or dev machine.~n", - ok = io:format(Message, [Realm]), UserRecord = {{Realm, UserName}, [filename:basename(SysopPub, ".pub.der")], Email, RealName}, - RealmFile = filename:join(zomp_dir(), Realm ++ ".realm"), - RealmMeta = + RealmSettings = [{realm, Realm}, {revision, 0}, {prime, {ExAddress, ExPort}}, @@ -2376,23 +2356,86 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email) -> {sysops, [UserRecord]}, {realm_keys, [RealmPubRecord]}, {package_keys, [PackagePubRecord]}], - Realms = - case lists:keyfind(managed, 1, ZompConf) of - {managed, M} -> [Realm | M]; - false -> [Realm] - end, - ZompFile = filename:join(zomp_dir(), "zomp.conf"), - Update = fun({K, V}, ZC) -> lists:keystore(K, 1, ZC, {K, V}) end, - NewConf = - [{managed, Realms}, + ZompSettings = + [{managed, [Realm]}, {external_address, ExAddress}, {external_port, ExPort}, {internal_port, InPort}], - NewZompConf = lists:foldl(Update, ZompConf, NewConf), - ok = write_terms(RealmFile, RealmMeta), - ok = write_terms(ZompFile, NewZompConf), - ok = log(info, "Realm ~ts created.", [Realm]), - create_realmfile(Realm). + + RealmFN = Realm ++ ".realm", + RealmConf = filename:join(zomp_dir(), RealmFN), + ok = write_terms(RealmConf, RealmSettings), + {ok, CWD} = file:get_cwd(), + {ok, TempDir} = mktemp_dir("zomp"), + ok = file:set_cwd(TempDir), + KeyDir = filename:join("key", Realm), + ok = filelib:ensure_dir(KeyDir), + ok = file:make_dir(KeyDir), + KeyCopy = + fun(K) -> + {ok, _} = file:copy(K, filename:join(KeyDir, filename:basename(K))), + ok + end, + TarOpts = [compressed, {cwd, TempDir}], + + ok = write_terms(RealmFN, RealmSettings), + ok = KeyCopy(PackagePub), + ok = KeyCopy(RealmPub), + PublicZRF = filename:join(CWD, Realm ++ ".zrf"), + Files = filelib:wildcard("**"), + ok = erl_tar:create(PublicZRF, [RealmFN, "key"], TarOpts), + + ok = KeyCopy(SysopPub), + ok = write_terms("zomp.conf", ZompSettings), + PrimeZRF = filename:join(CWD, Realm ++ ".zpf"), + ok = erl_tar:create(PrimeZRF, [RealmFN, "zomp.conf", "key"], TarOpts), + + ok = file:set_cwd(zomp_dir()), + KeyBundle = filename:join(CWD, Realm ++ ".zkf"), + ok = erl_tar:create(KeyBundle, [KeyDir], [compressed]), + + ok = file:set_cwd(CWD), + ok = rm_rf(TempDir), + + Message = + "============================================================================~n" + "DONE!~n" + "~n" + "The realm ~ts has been created and is accessible from the current system.~n" + "Three configuration bundles have been created in the current directory:~n" + "~n" + " 1. ~ts ~n" + "This is the PRIVATE realm file you will need to install on the realm's prime~n" + "node. It includes the your (the sysop's) public key.~n" + "~n" + " 2. ~ts ~n" + "This file is the PUBLIC realm file other zomp nodes and zx users will need to~n" + "access the realm. It does not include your (the sysop's) public key.~n" + "~n" + " 3. ~ts ~n" + "This is the bundle of ALL KEYS that are defined in this realm at the moment.~n" + "~n" + "Now you need to make copies of these three files and back them up.~n" + "~n" + "On the PRIME NODE you need to run `zx add realm ~ts` and follow the prompts~n" + "to cause it to begin serving that realm as prime. (Node restart required.)~n" + "~n" + "On all zx CLIENTS that want to access your new realm and on all subordinate~n" + "MIRROR NODES the command `zx add realm ~ts` will need to be run.~n" + "The method of public realm file distribution (~ts) is up to you.~n" + "~n" + "~n" + "Public & Private key installation (if you need to recover them or perform~n" + "sysop functions from another computer) is `zx add keybundle ~ts`.~n" + "============================================================================~n", + Substitutions = + [Realm, + PrimeZRF, PublicZRF, KeyBundle, + PrimeZRF, + PublicZRF, PublicZRF, + KeyBundle], + ok = io:format(Message, Substitutions), + halt(0). -spec create_realmfile(realm()) -> no_return(). @@ -2451,7 +2494,7 @@ install(PackageID) -> {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files), {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), Meta = binary_to_term(MetaBin), - {KeyID, Signature} = maps:get(sig, 1, Meta), + {KeyID, Signature} = maps:get(sig, Meta), {ok, PubKey} = loadkey(public, KeyID), ok = ensure_package_dirs(PackageID), PackageDir = filename:join("lib", PackageString), @@ -2558,6 +2601,24 @@ receive_zrp(Socket, PackageID) -> end. +-spec mktemp_dir(Prefix) -> Result + when Prefix :: string(), + Result :: {ok, TempDir :: file:filename()} + | {error, Reason :: file:posix()}. + +mktemp_dir(Prefix) -> + Rand = integer_to_list(binary:decode_unsigned(crypto:strong_rand_bytes(8)), 36), + TempPath = filename:basedir(user_cache, Prefix), + TempDir = filename:join(TempPath, Rand), + Result1 = filelib:ensure_dir(TempDir), + Result2 = file:make_dir(TempDir), + case {Result1, Result2} of + {ok, ok} -> {ok, TempDir}; + {ok, Error} -> Error; + {Error, _} -> Error + end. + + %%% Utility functions -spec read_meta() -> package_meta() | no_return(). @@ -2674,6 +2735,33 @@ installed(PackageID) -> filelib:is_dir(PackageDir). +-spec rm_rf(file:filename()) -> ok | {error, file:posix()}. +%% @private +%% Recursively remove files and directories, equivalent to `rm -rf' on unix. + +rm_rf(Path) -> + case filelib:is_dir(Path) of + true -> + Pattern = filename:join(Path, "**"), + Contents = lists:reverse(lists:sort(filelib:wildcard(Pattern))), + ok = lists:foreach(fun rm/1, Contents), + file:del_dir(Path); + false -> + file:delete(Path) + end. + + +-spec rm(file:filename()) -> ok | {error, file:posix()}. +%% @private +%% An omnibus delete helper. + +rm(Path) -> + case filelib:is_dir(Path) of + true -> file:del_dir(Path); + false -> file:delete(Path) + end. + + %%% Input argument mangling @@ -3225,4 +3313,4 @@ log(Level, Format, Args) -> warning -> "[WARNING]"; error -> "[ERROR]" end, - io:format("~p ~s: " ++ Format ++ "~n", [self(), Tag | Args]). + io:format("~s ~p: " ++ Format ++ "~n", [Tag, self() | Args]). From 24738f5278f82810144443b3539e1517bfa9037a Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Tue, 12 Dec 2017 10:10:52 +0900 Subject: [PATCH 28/55] Less magic --- Emakefile | 1 + ebin/zx.app | 6 ++++ zx => src/zx.erl | 79 ++++++----------------------------------------- src/zx_daemon.erl | 72 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 88 insertions(+), 70 deletions(-) create mode 100644 Emakefile create mode 100644 ebin/zx.app rename zx => src/zx.erl (97%) mode change 100755 => 100644 create mode 100644 src/zx_daemon.erl diff --git a/Emakefile b/Emakefile new file mode 100644 index 0000000..68c7b67 --- /dev/null +++ b/Emakefile @@ -0,0 +1 @@ +{"src/*", [debug_info, {i, "include/"}, {outdir, "ebin/"}]}. diff --git a/ebin/zx.app b/ebin/zx.app new file mode 100644 index 0000000..4e623c4 --- /dev/null +++ b/ebin/zx.app @@ -0,0 +1,6 @@ +{application, zx, + [{description, "Zomp client program"}, + {vsn, "0.1.0"}, + {applications, [stdlib, kernel]}, + {modules, [zx, zx_daemon]}, + {mod, {zx, []}}]}. diff --git a/zx b/src/zx.erl old mode 100755 new mode 100644 similarity index 97% rename from zx rename to src/zx.erl index ddd3501..43ad019 --- a/zx +++ b/src/zx.erl @@ -1,6 +1,5 @@ -#! /usr/bin/env escript - -%%% zx +%%% @doc +%%% ZX %%% %%% A general dependency and packaging tool that works together with the zomp %%% package manager. Given a project directory with a standard layout, zx can: @@ -11,10 +10,15 @@ %%% - Update, upgrade or run any application from source that zomp tracks. %%% - Locally install packages from files and locally stored public keys. %%% - Build and run a local project from source using zomp dependencies. +%%% @end -module(zx). --mode(compile). --export([main/1]). +-export([start/2, main/1]). + + +-export_type([serial/0, package_id/0, package/0, realm/0, name/0, version/0, option/0, + host/0, key_id/0, key_name/0, user/0, username/0, lower0_9/0, label/0, + package_meta/0]). -record(s, @@ -1195,71 +1199,6 @@ remove_binaries(TargetDir) -> ok = log(info, "Removing: ~tp", [ToDelete]), lists:foreach(fun file:delete/1, ToDelete) end. - - - -%%% App execution loop - --spec exec_wait(State) -> no_return() - when State :: state(). -%% @private -%% Execution maintenance loop. -%% Once an application is started by zompc this process will wait for a message from -%% the application if that application was written in a way to take advantage of zompc -%% facilities such as post-start upgrade checking. -%% -%% NOTE: -%% Adding clauses to this `receive' is where new functionality belongs. -%% It may make sense to add a `zompc_lib' as an available dependency authors could -%% use to interact with zompc without burying themselves under the complexity that -%% can come with naked send operations. (Would it make sense, for example, to have -%% the registered zompc process convert itself to a gen_server via zompc_lib to -%% provide more advanced functionality?) - -exec_wait(State = #s{pid = none, mon = none}) -> - receive - {monitor, Pid} -> - Mon = monitor(process, Pid), - exec_wait(State#s{pid = Pid, mon = Mon}); - Unexpected -> - ok = log(warning, "Unexpected message: ~tp", [Unexpected]), - exec_wait(State) - end; -exec_wait(State = #s{pid = Pid, mon = Mon}) -> - receive - {check_update, Requester, Ref} -> - {Response, NewState} = check_update(State), - Requester ! {Ref, Response}, - exec_wait(NewState); - {exit, Reason} -> - ok = log(info, "Exiting with: ~tp", [Reason]), - halt(0); - {'DOWN', Mon, process, Pid, normal} -> - ok = log(info, "Application exited normally."), - halt(0); - {'DOWN', Mon, process, Pid, Reason} -> - ok = log(warning, "Application exited with: ~tp", [Reason]), - halt(1); - Unexpected -> - ok = log(warning, "Unexpected message: ~tp", [Unexpected]), - exec_wait(State) - end. - - --spec check_update(State) -> {Response, NewState} - when State :: state(), - Response :: term(), - NewState :: state(). -%% @private -%% Check for updated version availability of the current application. -%% The return value should probably provide up to three results, a Major, Minor and -%% Patch update, and allow the Requestor to determine what to do with it via some -%% interaction. - -check_update(State) -> - ok = log(info, "Would be checking for an update of the current application now..."), - Response = "Nothing was checked, but you can imagine it to have been.", - {Response, State}. diff --git a/src/zx_daemon.erl b/src/zx_daemon.erl new file mode 100644 index 0000000..e8073a0 --- /dev/null +++ b/src/zx_daemon.erl @@ -0,0 +1,72 @@ +%%% @doc +%%% ZX Daemon +%%% +%%% Resident execution daemon and runtime interface to Zomp. +%%% @end + +-module(zx_daemon). +-export([]). + + +%%% App execution loop + +-spec exec_wait(State) -> no_return() + when State :: state(). +%% @private +%% Execution maintenance loop. +%% Once an application is started by zompc this process will wait for a message from +%% the application if that application was written in a way to take advantage of zompc +%% facilities such as post-start upgrade checking. +%% +%% NOTE: +%% Adding clauses to this `receive' is where new functionality belongs. +%% It may make sense to add a `zompc_lib' as an available dependency authors could +%% use to interact with zompc without burying themselves under the complexity that +%% can come with naked send operations. (Would it make sense, for example, to have +%% the registered zompc process convert itself to a gen_server via zompc_lib to +%% provide more advanced functionality?) + +exec_wait(State = #s{pid = none, mon = none}) -> + receive + {monitor, Pid} -> + Mon = monitor(process, Pid), + exec_wait(State#s{pid = Pid, mon = Mon}); + Unexpected -> + ok = log(warning, "Unexpected message: ~tp", [Unexpected]), + exec_wait(State) + end; +exec_wait(State = #s{pid = Pid, mon = Mon}) -> + receive + {check_update, Requester, Ref} -> + {Response, NewState} = check_update(State), + Requester ! {Ref, Response}, + exec_wait(NewState); + {exit, Reason} -> + ok = log(info, "Exiting with: ~tp", [Reason]), + halt(0); + {'DOWN', Mon, process, Pid, normal} -> + ok = log(info, "Application exited normally."), + halt(0); + {'DOWN', Mon, process, Pid, Reason} -> + ok = log(warning, "Application exited with: ~tp", [Reason]), + halt(1); + Unexpected -> + ok = log(warning, "Unexpected message: ~tp", [Unexpected]), + exec_wait(State) + end. + + +-spec check_update(State) -> {Response, NewState} + when State :: state(), + Response :: term(), + NewState :: state(). +%% @private +%% Check for updated version availability of the current application. +%% The return value should probably provide up to three results, a Major, Minor and +%% Patch update, and allow the Requestor to determine what to do with it via some +%% interaction. + +check_update(State) -> + ok = log(info, "Would be checking for an update of the current application now..."), + Response = "Nothing was checked, but you can imagine it to have been.", + {Response, State}. From c47a88c319676a73227fa5a70f54bb5dcfb6f191 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Mon, 18 Dec 2017 13:27:22 +0900 Subject: [PATCH 29/55] Breaking up & porting --- src/zx.erl | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/src/zx.erl b/src/zx.erl index 43ad019..c03de85 100644 --- a/src/zx.erl +++ b/src/zx.erl @@ -13,13 +13,21 @@ %%% @end -module(zx). --export([start/2, main/1]). +-behavior(application). +-author("Craig Everett "). +-copyright("Craig Everett "). +-license("GPL-3.0"). +-export([start/1, stop/0]). +-export([start/2, stop/1]). + -export_type([serial/0, package_id/0, package/0, realm/0, name/0, version/0, option/0, host/0, key_id/0, key_name/0, user/0, username/0, lower0_9/0, label/0, package_meta/0]). +-include("zx_logger.hrl"). + -record(s, {realm = "otpr" :: realm(), @@ -34,6 +42,9 @@ mon = none :: none | reference()}). + +%%% Type Definitions + -type state() :: #s{}. -type serial() :: integer(). -type package_id() :: {realm(), name(), version()}. @@ -58,18 +69,6 @@ --spec main(Args) -> no_return() - when Args :: [string()]. -%% @private -%% The automatically exposed function initially called by escript to kick things off. -%% Args is a list of command-line provided arguments, all presented as a list of strings -%% delimited by whitespace in the shell. - -main(Args) -> - ok = ensure_zomp_home(), - start(Args). - - -spec start(Args) -> no_return() when Args :: [string()]. %% Dispatch work functions based on the nature of the input arguments. From 83a7a6884403fef0b230dd107f539fd4f0471754 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Mon, 18 Dec 2017 13:29:06 +0900 Subject: [PATCH 30/55] Addins --- include/zx_logger.hrl | 34 ++++++++++++++++++++++++++++++ zmake | 48 +++++++++++++++++++++++++++++++++++++++++++ zx.bash | 13 ++++++++++++ 3 files changed, 95 insertions(+) create mode 100644 include/zx_logger.hrl create mode 100755 zmake create mode 100755 zx.bash diff --git a/include/zx_logger.hrl b/include/zx_logger.hrl new file mode 100644 index 0000000..763af58 --- /dev/null +++ b/include/zx_logger.hrl @@ -0,0 +1,34 @@ +-export([log/2, log/3]). + + +-spec log(Level, Format) -> ok + when Level :: info + | warning + | error, + Format :: string(). +%% @private +%% @equiv log(Level, Format, []) + +log(Level, Format) -> + log(Level, Format, []). + + +-spec log(Level, Format, Args) -> ok + when Level :: info + | warning + | error, + Format :: string(), + Args :: [term()]. +%% @private +%% A logging abstraction to hide whatever logging back end is actually in use. +%% Format must adhere to Erlang format string rules, and the arity of Args must match +%% the provided format. + +log(Level, Format, Args) -> + Tag = + case Level of + info -> "[INFO]"; + warning -> "[WARNING]"; + error -> "[ERROR]" + end, + io:format("~s ~p: " ++ Format ++ "~n", [Tag, self() | Args]). diff --git a/zmake b/zmake new file mode 100755 index 0000000..75f3a21 --- /dev/null +++ b/zmake @@ -0,0 +1,48 @@ +#! /usr/bin/env escript + +-mode(compile). + +main(Args) -> + ok = make(), + ok = lists:foreach(fun dispatch/1, Args), + halt(0). + + +dispatch("edoc") -> + ok = edoc(); +dispatch("dialyze") -> + ok = dialyze(); +dispatch("test") -> + ok = test(); +dispatch(Unknown) -> + ok = io:format("zmake: Unknown directive: ~tp~n", [Unknown]), + halt(1). + + +make() -> + true = code:add_patha("ebin"), + up_to_date = make:all(), + halt(0). + + +edoc() -> + ok = io:format("EDOC: Writing docs...~n"), + ok = edoc:application(zomp, ".", []), + halt(0). + + +dialyze() -> + ok = + case dialyzer:run([{from, src_code}, {files_rec, ["./src"]}]) of + [] -> + io:format("Dialyzer found no errors and returned no warnings! Yay!~n"); + Warnings -> + Messages = [dialyzer:format_warning(W) || W <- Warnings], + lists:foreach(fun io:format/1, Messages) + end, + halt(0). + + +test() -> + ok = io:format("TEST: If I only had a brain.~n"), + halt(0). diff --git a/zx.bash b/zx.bash new file mode 100755 index 0000000..fb0967f --- /dev/null +++ b/zx.bash @@ -0,0 +1,13 @@ +#! /bin/bash + +# set -x + +ZOMP_DIR="$HOME/.zomp" +ORIGIN="$(pwd)" +VERSION="$(ls $ZOMP_DIR/lib/otpr-zx/ | sort --field-separator=. --reverse | head --lines=1)" +ZX_DIR="$ZOMP_DIR/lib/otpr-zx/$VERSION" + +cd "$ZX_DIR" +./zmake +cd "$ZOMP_DIR" +erl -pa "$ZX_DIR/ebin" -run zx start $@ From 649a75c2bf8e4b7a2a85b3fd8d6c14d2bdd14c9f Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Thu, 4 Jan 2018 20:30:15 +0900 Subject: [PATCH 31/55] Nothing --- src/zx.erl | 36 ------------------------------------ zx_install.escript | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 36 deletions(-) create mode 100644 zx_install.escript diff --git a/src/zx.erl b/src/zx.erl index c03de85..aa83610 100644 --- a/src/zx.erl +++ b/src/zx.erl @@ -3216,39 +3216,3 @@ error_exit(Format, Args, Path, Line) -> File = filename:basename(Path), ok = log(error, "~ts:~tp: " ++ Format, [File, Line | Args]), halt(1). - - - -%%% Logger - --spec log(Level, Format) -> ok - when Level :: info - | warning - | error, - Format :: string(). -%% @private -%% @equiv log(Level, Format, []) - -log(Level, Format) -> - log(Level, Format, []). - - --spec log(Level, Format, Args) -> ok - when Level :: info - | warning - | error, - Format :: string(), - Args :: [term()]. -%% @private -%% A logging abstraction to hide whatever logging back end is actually in use. -%% Format must adhere to Erlang format string rules, and the arity of Args must match -%% the provided format. - -log(Level, Format, Args) -> - Tag = - case Level of - info -> "[INFO]"; - warning -> "[WARNING]"; - error -> "[ERROR]" - end, - io:format("~s ~p: " ++ Format ++ "~n", [Tag, self() | Args]). diff --git a/zx_install.escript b/zx_install.escript new file mode 100644 index 0000000..dbb9b2e --- /dev/null +++ b/zx_install.escript @@ -0,0 +1,42 @@ +#! /usr/bin/env escript + +%% ZX install script + +-spec main(Argv :: [string()]) -> no_return(). + +main(_) -> + ZompDir = zomp_dir(), + case filelib:is_dir(ZompDir) of + false -> unpack(ZompDir); + true -> halt(0) + end. + + +-spec unpack(ZompDir :: file:filename()) -> no_return(). + +unpack(ZompDir) -> + ZompFile = filename:join(ZompDir, "zomp.conf"), + ok = filelib:ensure_dir(ZompFile), + ok = erl_tar:extract("zx.tgz", [compressed, {cwd, ZompFile}]), + halt(0). + + +-spec zomp_dir() -> file:filename(). +%% @private +%% Check the host OS and return the absolute path to the zomp filesystem root. + +zomp_dir() -> + case os:type() of + {unix, _} -> + Home = os:getenv("HOME"), + Dir = ".zomp", + filename:join(Home, Dir); + {win32, _} -> + Drive = os:getenv("HOMEDRIVE"), + Path = os:getenv("HOMEPATH"), + Dir = "zomp", + filename:join([Drive, Path, Dir]); + Unknown -> + ok = io:format("zx_install: ERROR Unknown host system type: ~tp", [Unknown]), + halt(1) + end. From ae7b1178285c8557e6b4af723b0ca7e964b23363 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Thu, 11 Jan 2018 19:09:31 +0900 Subject: [PATCH 32/55] Moving stuff around --- README.md | 66 +- README.unix | 29 + README.windows | 2 + install.escript | 119 ++++ install_unix | 9 + install_windows.cmd | 16 + notify.vbs | 2 + packup | 24 + zomp/key/otpr/otpr.1.package.pub.der | Bin 0 -> 2062 bytes zomp/key/otpr/otpr.1.realm.pub.der | Bin 0 -> 2062 bytes Emakefile => zomp/lib/otpr-zx/0.1.0/Emakefile | 0 zomp/lib/otpr-zx/0.1.0/LICENSE | 674 ++++++++++++++++++ {ebin => zomp/lib/otpr-zx/0.1.0/ebin}/zx.app | 0 .../lib/otpr-zx/0.1.0/include}/zx_logger.hrl | 0 {src => zomp/lib/otpr-zx/0.1.0/src}/zx.erl | 4 +- .../lib/otpr-zx/0.1.0/src}/zx_daemon.erl | 0 zmake => zomp/lib/otpr-zx/0.1.0/zmake | 0 zomp/otpr.realm | 22 + zx.bash => zomp/zx.sh | 4 +- zx_install.escript | 42 -- 20 files changed, 965 insertions(+), 48 deletions(-) create mode 100644 README.unix create mode 100644 README.windows create mode 100755 install.escript create mode 100755 install_unix create mode 100644 install_windows.cmd create mode 100644 notify.vbs create mode 100755 packup create mode 100644 zomp/key/otpr/otpr.1.package.pub.der create mode 100644 zomp/key/otpr/otpr.1.realm.pub.der rename Emakefile => zomp/lib/otpr-zx/0.1.0/Emakefile (100%) create mode 100644 zomp/lib/otpr-zx/0.1.0/LICENSE rename {ebin => zomp/lib/otpr-zx/0.1.0/ebin}/zx.app (100%) rename {include => zomp/lib/otpr-zx/0.1.0/include}/zx_logger.hrl (100%) rename {src => zomp/lib/otpr-zx/0.1.0/src}/zx.erl (99%) rename {src => zomp/lib/otpr-zx/0.1.0/src}/zx_daemon.erl (100%) rename zmake => zomp/lib/otpr-zx/0.1.0/zmake (100%) create mode 100644 zomp/otpr.realm rename zx.bash => zomp/zx.sh (86%) delete mode 100644 zx_install.escript diff --git a/README.md b/README.md index dcd052b..7ab57e7 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,64 @@ -# zx -Zomp user client +ZX: The Zomp client. + +Project information can be found at https://zxq9com/zx/ and https://github.com/zxq9/zx/ + + +ZX is delivered as a zip file containing: +- `zomp.tar.gz`: An archive of a current working zx/zomp installation +- `install.escript`: The main installation script +- `install_unix` and `install_windows.cms`: System-specific installation starters +- `README.*` files such as this one +- `LICENSE` +- `notify.vbs`: A hacky VBS script to communicate with the Windows GUI during setup + + +Installation + +To install ZX the `install.escript` program needs to run. In order to run it requires +an Erlang environment to be envoked via the Escript interpreter. The system-specific +installation starter scripts exist to locate the Erlang installation on the local +system. + +The installer will unpack the ZX client and the relevant parts of Zomp (the package +system underlying everything) to a directory in your home directory called "zomp". +Once everything is unpacked it will add a link called `zx` to your command environment +so that you can invoke zx the normal way. + +For further information about installation, consult the relevant README file in this +directory. + + +Features + +ZX has a number of features, most of them useful to developers and testers, but the +most important feature is for users of programs. To run any program from a configured +Zomp realm you run the command: + `zx run [program_name]` + +If the version number of the program is omitted (the typical case) then the latest +version will always be installed and run. If a version number is provided then that +specific version will be installed and run. + +ZX updates itself in the same manner it updates other installed programs. Occasionally +you may receive a message indicating that you should re-run ZX because a newer version +has been installed. + +At the moment ZX only works from the command line, though desktop links to launchers +for GUI programs can be easily created. + +To create a desktop launcher for a program the launcher must invoke zx the same way +you do from the command line: + `zx run [program_name]` + +In the event you need to write an installer for a system you have released through a +Zomp repository all the installer needs to do is provide an icon set and create a +launcher for the program that invokes zx the same way you would from the command line. + +The default Zomp realm is called "otpr". It is installed automatically and contains +only FOSS software. + + +ZX supports fetching and resolution of multiple realms at the same time, similar to +how Linux distribution package managers usually permit configuration of multiple +repository sources. To create and host your own, possibly private or proprietary, Zomp +realm consult the Zomp documentation directly. diff --git a/README.unix b/README.unix new file mode 100644 index 0000000..6dfac7e --- /dev/null +++ b/README.unix @@ -0,0 +1,29 @@ +Unix installation information for ZX + + +This file contains information about how to install and run ZX on a Unix-type system. +Consult README.md for general information about ZX as a program and as a project. + +Current versions of ZX and this file can be found at https://zxq9.com/zx/ + + +The unix startup script, "install_unix", is a BASH script and must be set as executable +to be used. To set the script as executable: + + +From the command line: + +To set the file permission correctly you will need to run the following command: + chmod +x install_unix +Then to execute the installer you will need to run the following command: + ./install_unix + + +From a GUI: + +If you are using a GUI you will need to do something like right-click the install_unix +file, then select "properties" (or "permissions" or something similar), and change the +file "mode" or "permissions" to include "execution" by the owner of the file (the user +account you are currently using should be the owner of the file). Once the file is set +as executable, run the file (probably by clicking on it). + diff --git a/README.windows b/README.windows new file mode 100644 index 0000000..4e0ad05 --- /dev/null +++ b/README.windows @@ -0,0 +1,2 @@ +This file contains information about how to install and run ZX on a Windows system. +Consult README.md for general information about ZX as a program and as a project. diff --git a/install.escript b/install.escript new file mode 100755 index 0000000..cc905b3 --- /dev/null +++ b/install.escript @@ -0,0 +1,119 @@ +#! /usr/bin/env escript + +%% ZX install script + +-mode(compile). + +-spec main(Argv :: [string()]) -> no_return(). + +main(_) -> + OS = os:type(), + ZompDir = zomp_dir(OS), + case filelib:is_dir(ZompDir) of + true -> + Message = "Installation directory (~ts) already exists. Aborting.~n", + ok = io:format(Message, [ZompDir]), + halt(0); + false -> + unpack(OS, ZompDir) + end. + + +-spec unpack(OS, ZompDir) -> no_return() + when OS :: {Family :: unix | win32, + Name :: atom()}, + ZompDir :: file:filename(). + +unpack(OS, ZompDir) -> + BaseDir = filename:dirname(ZompDir), + ok = erl_tar:extract("zomp.tar.gz", [compressed, {cwd, BaseDir}]), + add_launcher(OS, ZompDir). + + +-spec add_launcher(OS, ZompDir) -> no_return() + when OS :: {Family :: unix | win32, + Name :: atom()}, + ZompDir :: file:filename(). + +add_launcher({unix, linux}, ZompDir) -> + add_unix_link(ZompDir), + ok = io:format("Should attempt a FreeDesktop icon addition here.~n"), + halt(0); +add_launcher({unix, _}, ZompDir) -> + add_unix_link(ZompDir), + halt(0); +add_launcher({win32, nt}, _ZompDir) -> + ok = io:format("This is going to be a bit of a rodeo...~n"), + halt(0). + + +-spec add_unix_link(ZompDir) -> ok + when ZompDir :: file:filename(). + +add_unix_link(ZompDir) -> + Home = filename:dirname(ZompDir), + Link = filename:join(Home, "bin/zx"), + HomeBin = filename:dirname(Link), + Target = filename:join(ZompDir, "zx.sh"), + ok = filelib:ensure_dir(Link), + LinkCommand = "env LANG=en ln -s " ++ Target ++ " " ++ Link, + ModeCommand = "env LANG=en chmod +x " ++ Target, + ok = os_cmd(LinkCommand), + ok = os_cmd(ModeCommand), + Path = os:getenv("PATH"), + Parts = string:lexemes(Path, ":"), + Message = + case lists:member(HomeBin, Parts) of + true -> + "A link to ~ts has been created at ~ts.~n" + "~ts seems to be in $PATH already.~n" + "You should be able to run any zomp/zx program by typing `zx` " + "from anywhere in your system.~n" + "Creating launchers to the link that start specific programs may be " + "conveinent.~n" + "A desktop launcher would need to run the command:~n" + " zx run [some_program]~n" + "Or alternately (if ~~/bin/ is not in your launcher's $PATH):~n" + " ~ts run [some_program]~n"; + false -> + "A link to ~ts has been created at ~ts. " + "~ts seems to be NOT in your $PATH. " + "You will need to add that to $PATH if you want to be able to run " + "zx by simply typing `zx` from anywhere in your system." + "Creating launchers to the link that start specific programs may be " + "conveinent.~n" + "A desktop launcher would need to run the command:~n" + " ~ts run [some_program]~n" + end, + io:format(Message, [Target, Link, HomeBin, Target]). + + +-spec os_cmd(Command :: string()) -> ok. + +os_cmd(Command) -> + case os:cmd(Command) of + "" -> + ok; + Output -> + ok = io:format("Output of: ~tp~n", [Command]), + io:format("~ts~n", [Output]) + end. + + +-spec zomp_dir(OS) -> file:filename() + when OS :: {Family :: unix | win32, + Name :: atom()}. +%% @private +%% Check the host OS and return the absolute path to the zomp filesystem root. + +zomp_dir({unix, _}) -> + Home = os:getenv("HOME"), + filename:join(Home, "zomp"); +zomp_dir({win32, _}) -> + Drive = os:getenv("HOMEDRIVE"), + Path = os:getenv("HOMEPATH"), + filename:join([Drive, Path, "zomp"]); +zomp_dir(Unknown) -> + Message = "zx_install: ERROR Unknown host system type: ~tp", + ok = io:format(Message, [Unknown]), + halt(1). diff --git a/install_unix b/install_unix new file mode 100755 index 0000000..eb2a16c --- /dev/null +++ b/install_unix @@ -0,0 +1,9 @@ +#! /bin/sh + +if escript_path=$(command -v escript) + then + echo "Using escript found at $escript_path" + escript install.escript + else + echo "Could not locate an Erlang installation." +fi diff --git a/install_windows.cmd b/install_windows.cmd new file mode 100644 index 0000000..90b00d2 --- /dev/null +++ b/install_windows.cmd @@ -0,0 +1,16 @@ +@echo off +setlocal + +set versions=9.2 + +for %%v in (%versions%) do ( + if exist "%ProgramFiles%\erl%%v\bin\escript.exe" ( + "%ProgramFiles%\erl%%v\bin\escript.exe" install.escript + notify "Done!" + exit /b + ) +) + +echo Could not find the Erlang escript.exe executable +notify "Could not locate a expected Erlang runtime. Consult the README.windows file in this directory for more information." +exit /b \ No newline at end of file diff --git a/notify.vbs b/notify.vbs new file mode 100644 index 0000000..99e38b5 --- /dev/null +++ b/notify.vbs @@ -0,0 +1,2 @@ +messageText = WScript.Arguments(0) +MsgBox messageText \ No newline at end of file diff --git a/packup b/packup new file mode 100755 index 0000000..bbe2964 --- /dev/null +++ b/packup @@ -0,0 +1,24 @@ +#! /usr/bin/env escript + + +main([Version]) -> + Tar = "zomp.tar.gz", + ok = erl_tar:create(Tar, ["zomp"], [compressed]), + Zip = "zx-" ++ Version ++ ".zip", + ZipFiles = + ["install.escript", + "install_unix", + "install_windows.cmd", + "notify.vbs", + "README.md", + "README.unix", + "README.windows", + "LICENSE", + Tar], + {ok, Zip} = zip:create(Zip, ZipFiles), + ok = file:delete(Tar), + ok = io:format("Wrote ~ts.~n", [Zip]), + halt(0); +main(_) -> + ok = io:format("Provide a single version or extension string as an argument.~n"), + halt(1). diff --git a/zomp/key/otpr/otpr.1.package.pub.der b/zomp/key/otpr/otpr.1.package.pub.der new file mode 100644 index 0000000000000000000000000000000000000000..e844a3bfb704c026ff00c05bee00a3db78380102 GIT binary patch literal 2062 zcmV+p2=VtYf(Qx%f(QWs+4~Y8{hu^D9WI+v*(Kd+X^!qnl?)??wZi+0@JH$Oz(Wl} zmx4lZ0Y8K&cm(U1LMGHmB$^ihD37Jxlp|hZ!*lp>Llr;cl)*NGrgBC$bnj!fj-4gF zW%d9ZSV<6~Ke=CS3Fs*qvX>pO;4+!!p^iPDWax%<9>X7-0mKY+d9d~(t$Y1cLqO66-b1>y8=E+$m;awhr=q)#Nj6T6C)I!SF$RIsmvI8{MT|vo$Ac!4})M*KvtGBOPQ0N+mYf$&#r@KziaCHdMndI%AOo#1QkDst8Hre?w%#AW*31G9-k*pjHIpbdpR zdjbc8d;r{qyqbV6)f~f~N> z6~(@spo)B}cYW*g5*il2-d` zvb9Lo5J%I!kcg0rO9M%y(%Dz3`~{mIIu|YvrXInA*5*>7PFJJpH{Ro%}Z$7dazfY(s<%X+jspz zXMDYdIWFBf%&GjV(YSc}RTOtgYNCA;E4~c?g=>|ag&d;t5QAeJIM^mye$$}?8D4)U z>wJ5Z(G_CWFB>Q0S z^;h4Rc7y79nS)cI+FPi7&)Yz}mYpD84wu~iI3yJ0ERj)jxK9>mG^mFx;Uqa7 z$r*d20JQSRJ(r5idk?~W@pVs=?TXOxZTQuO&V}xe8KET4%TN)l% zsYD~|3x-d5dPg{ZrnvE^(9<3mbCWJC?1NAYJy?RUW}A!-qlT41-s*H$*bZe1l)ab= zE=+qW(XhW+Q^9@fm(3KZhGb%uP_U0>xQP`k^ocG$AtwOUFuSSAUx#U#_5;-H%Kw$d zuM=u{UVGl$mJ|MY#O>HRzT{F{?^J*x`xvXJJ<|wY1KyC8LkpTZ4#F~Bd6E76pwTFg z&z!E&tEx<~_NyS`HX7n<9;qj1@Y2sGwqTws_-#Idb{^{e28qY<48Cp|5jc@I=3yyAIJj4CH(UU zz;X$kuqK2H9z8PLOBwwg^CDZP+`O55WFuKnbP3f5 z9H-b%q&3&CdW?DXBs05f7OP6Iei(_~>leOY+yqmkIdJi$c;0rukwlMST=HE%FK@^D(4fFbBoOuJr>ggG5lv->1dy`#o(h$B?~%7#8?(&zDa+8F&2ksPp2e?9I|y=1JO=yRERjZTA7nFtyL8Ie!ZEf! zwgP@cG-JRMh9;3ADx)RqqgL`>Up%YMti~Q)qdqNNA8(-ST!OlJKBFGFzR|V%klVaa zck(C=wpA#&H4Dfx7xP&C$dcg)1DnNfM7aMgN9kmgFo^r25%xE9!x6`K%oQ;QZA6(S z$t{lF-3Tv)6hI_Rz32BCcy3Ejm4DVir9Ulese!Ez@I4MSBf5wBE@Z>Cv&?=;G+=9Y zCva~%8v#WONS&FEu2-WQK@WS3h^&M0e8q$H1piC##28aBg**T72gOIo^Xofy7f>H# zfQ7{p4tl8HC{_yikXy^dn$X=(BR`dTY{y2nJA(r=VY_^~otvwOCGnLlOb=~m#*?LZ zLOz~s!Y*+WgmZQQLTHW#LMQG)MYd+-Tak9PD+y@SRlFD>#rg|u2uBc7^Eo2R5#;Nk sc&wqfkxHKrMYU40l%%>V!Z literal 0 HcmV?d00001 diff --git a/zomp/key/otpr/otpr.1.realm.pub.der b/zomp/key/otpr/otpr.1.realm.pub.der new file mode 100644 index 0000000000000000000000000000000000000000..a4df4cb9b6fa962bbbd555ad8b528d4ad389aceb GIT binary patch literal 2062 zcmV+p2=VtYf(Qx%f(QWs$#_sbM_lA3`Zv{ZlTrR)r@oRGPvR;Xd zv8HYpK9kr5jo%#yKtBJ21?fZ9l4@-Ngzn(8J-aYGGfr^B+oI!0u8b$Rj$Kl%-sngP zX`DtWk8+Hj4>`+nwX%UPMED$ zc`CccSD7}GyZQ8n;>X98z(!~2%+DmRgHF}@SPNX1@Kh*qQvSx#Tt}UysVD-6*8VOwcV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Y5 z_$eg+TS}^t!CmgT1N2K81eE5snO&c=C~R8!!;gUM~MVnXK(UHT95h0Fg@UX;26a1XpcJ z`HTT>6N@KBk|jIMpMdU)vbpN*FjEAO?OV`HWM{uRd?m|(u*zSVRR+|#f~bV`9E-Ry zoiB4Ta|$^oZ$==p=RVkZ6WByPW^%k4Q>zazvAAdEME9ot3O#vfKB-TZvz9lS`SWEF z$T6YuOh3w`WiR;8V0H*uOt>mUl$8tmrWWdhC`v}h4wuf@3KILpm+`Nn5Tbe(jxY`i zsRy}z97^r{8EPwut#^qv8C#OnQ+Cs`kW0_vWo8RE2dGp)R*1qDXTa**IH|1>Mr(lw z0&;dd$=Pjxqqf87fj&i=Nl_jO3^k`x$0~<7$zon3wiK(fakEBPHf&@g zjN&MxO`bQoN<~PoeN4h;5I3+cdB$l!Wgfc%IC3ccL6gXeCuU6C7#^ILO0iZJ*)SPI zR2ev%HK*ID*yQvdZR!s1TIa2nB4C{(1OEVf20L~id~?jIOb(5WX(qJIq&lMuvgqIv z+Hnp!B7_ate+6^kBf)6-YS|H?!Z{i2Ryw=@0@M&y2YmupLu@A6?vx(OMI#*f;IY}0 z*ml;rS_N+YIZ%5-?gIkY9Y>lD5T4c6rLR>3?8)Ly`6hW({#Zp;g5s1hjR$&98Z)+g zn|I4T;Ws5+JFU*f-rPD{T{DQ#P@ulpRl(B*Xl;J08;p`P8`Q+a`Whs}CJ>m_4yWY+ sd5OXfD_Q$6sjdP + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/ebin/zx.app b/zomp/lib/otpr-zx/0.1.0/ebin/zx.app similarity index 100% rename from ebin/zx.app rename to zomp/lib/otpr-zx/0.1.0/ebin/zx.app diff --git a/include/zx_logger.hrl b/zomp/lib/otpr-zx/0.1.0/include/zx_logger.hrl similarity index 100% rename from include/zx_logger.hrl rename to zomp/lib/otpr-zx/0.1.0/include/zx_logger.hrl diff --git a/src/zx.erl b/zomp/lib/otpr-zx/0.1.0/src/zx.erl similarity index 99% rename from src/zx.erl rename to zomp/lib/otpr-zx/0.1.0/src/zx.erl index aa83610..8741ca7 100644 --- a/src/zx.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx.erl @@ -586,7 +586,7 @@ update_version(Realm, Name, OldVersion, NewVersion, OldMeta) -> -spec list_realms() -> no_return(). %% @private %% List all currently configured realms. The definition of a "configured realm" is a -%% realm for which a .realm file exists in ~/.zomp/. The realms will be printed to +%% realm for which a .realm file exists in ~/zomp/. The realms will be printed to %% stdout and the program will exit. list_realms() -> @@ -3022,7 +3022,7 @@ zomp_dir() -> case os:type() of {unix, _} -> Home = os:getenv("HOME"), - Dir = ".zomp", + Dir = "zomp", filename:join(Home, Dir); {win32, _} -> Drive = os:getenv("HOMEDRIVE"), diff --git a/src/zx_daemon.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl similarity index 100% rename from src/zx_daemon.erl rename to zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl diff --git a/zmake b/zomp/lib/otpr-zx/0.1.0/zmake similarity index 100% rename from zmake rename to zomp/lib/otpr-zx/0.1.0/zmake diff --git a/zomp/otpr.realm b/zomp/otpr.realm new file mode 100644 index 0000000..081eb55 --- /dev/null +++ b/zomp/otpr.realm @@ -0,0 +1,22 @@ +{realm,"otpr"}. +{revision,0}. +{prime,{"otpr.psychobitch.party",11311}}. +{private,[]}. +{mirrors,[]}. +{sysops,[{{"otpr","zxq9"},["zxq9.1"],"zxq9@zxq9.com","Craig Everett"}]}. +{realm_keys,[{{"otpr","otpr.1.realm"}, + realm, + {realm,"otpr"}, + <<206,129,232,15,23,149,65,167,9,157,25,210,91,113,55,56,14,12, + 153,218,37,83,148,3,89,208,61,43,95,89,51,228,245,78,115,52,15, + 82,23,100,53,189,136,19,104,58,222,216,184,87,75,231,151,18,90, + 243,115,160,244,32,232,71,57,95>>, + {{2018,1,10},{6,36,41}}}]}. +{package_keys,[{{"otpr","otpr.1.package"}, + package, + {realm,"otpr"}, + <<77,10,171,53,73,87,21,251,153,215,83,119,244,217,207,77,44, + 210,177,77,46,86,52,232,16,64,23,109,214,94,207,140,12,145, + 23,130,151,151,37,82,61,240,82,146,142,199,95,114,77,219,148, + 200,140,85,128,77,110,142,179,137,169,188,223,192>>, + {{2018,1,10},{6,36,41}}}]}. diff --git a/zx.bash b/zomp/zx.sh similarity index 86% rename from zx.bash rename to zomp/zx.sh index fb0967f..dc91166 100755 --- a/zx.bash +++ b/zomp/zx.sh @@ -1,8 +1,8 @@ -#! /bin/bash +#! /bin/sh # set -x -ZOMP_DIR="$HOME/.zomp" +ZOMP_DIR="$HOME/zomp" ORIGIN="$(pwd)" VERSION="$(ls $ZOMP_DIR/lib/otpr-zx/ | sort --field-separator=. --reverse | head --lines=1)" ZX_DIR="$ZOMP_DIR/lib/otpr-zx/$VERSION" diff --git a/zx_install.escript b/zx_install.escript deleted file mode 100644 index dbb9b2e..0000000 --- a/zx_install.escript +++ /dev/null @@ -1,42 +0,0 @@ -#! /usr/bin/env escript - -%% ZX install script - --spec main(Argv :: [string()]) -> no_return(). - -main(_) -> - ZompDir = zomp_dir(), - case filelib:is_dir(ZompDir) of - false -> unpack(ZompDir); - true -> halt(0) - end. - - --spec unpack(ZompDir :: file:filename()) -> no_return(). - -unpack(ZompDir) -> - ZompFile = filename:join(ZompDir, "zomp.conf"), - ok = filelib:ensure_dir(ZompFile), - ok = erl_tar:extract("zx.tgz", [compressed, {cwd, ZompFile}]), - halt(0). - - --spec zomp_dir() -> file:filename(). -%% @private -%% Check the host OS and return the absolute path to the zomp filesystem root. - -zomp_dir() -> - case os:type() of - {unix, _} -> - Home = os:getenv("HOME"), - Dir = ".zomp", - filename:join(Home, Dir); - {win32, _} -> - Drive = os:getenv("HOMEDRIVE"), - Path = os:getenv("HOMEPATH"), - Dir = "zomp", - filename:join([Drive, Path, Dir]); - Unknown -> - ok = io:format("zx_install: ERROR Unknown host system type: ~tp", [Unknown]), - halt(1) - end. From 2fc295fe070d2ccb77333a653c475045885b3943 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Thu, 25 Jan 2018 22:35:58 +0900 Subject: [PATCH 33/55] Finally some time to play with this again! --- README.md | 2 +- zomp/lib/otpr-zx/0.1.0/ebin/zx.app | 2 +- zomp/lib/otpr-zx/0.1.0/src/zx.erl | 1202 +++++++----------- zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl | 71 ++ zomp/lib/otpr-zx/0.1.0/src/zx_conn_sup.erl | 72 ++ zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl | 485 ++++++- zomp/lib/otpr-zx/0.1.0/src/zx_daemon_sup.erl | 60 + zomp/lib/otpr-zx/0.1.0/src/zx_lib.erl | 523 ++++++++ zomp/zx.sh | 2 +- zx_dev.sh | 13 + 10 files changed, 1627 insertions(+), 805 deletions(-) create mode 100644 zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl create mode 100644 zomp/lib/otpr-zx/0.1.0/src/zx_conn_sup.erl create mode 100644 zomp/lib/otpr-zx/0.1.0/src/zx_daemon_sup.erl create mode 100644 zomp/lib/otpr-zx/0.1.0/src/zx_lib.erl create mode 100755 zx_dev.sh diff --git a/README.md b/README.md index 7ab57e7..bb339c7 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Project information can be found at https://zxq9com/zx/ and https://github.com/z ZX is delivered as a zip file containing: - `zomp.tar.gz`: An archive of a current working zx/zomp installation - `install.escript`: The main installation script -- `install_unix` and `install_windows.cms`: System-specific installation starters +- `install_unix` and `install_windows.cmd`: System-specific installation starters - `README.*` files such as this one - `LICENSE` - `notify.vbs`: A hacky VBS script to communicate with the Windows GUI during setup diff --git a/zomp/lib/otpr-zx/0.1.0/ebin/zx.app b/zomp/lib/otpr-zx/0.1.0/ebin/zx.app index 4e623c4..646143b 100644 --- a/zomp/lib/otpr-zx/0.1.0/ebin/zx.app +++ b/zomp/lib/otpr-zx/0.1.0/ebin/zx.app @@ -2,5 +2,5 @@ [{description, "Zomp client program"}, {vsn, "0.1.0"}, {applications, [stdlib, kernel]}, - {modules, [zx, zx_daemon]}, + {modules, [zx, zxd_sup, zxd]}, {mod, {zx, []}}]}. diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx.erl b/zomp/lib/otpr-zx/0.1.0/src/zx.erl index 8741ca7..9d1fc3f 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx.erl @@ -19,33 +19,24 @@ -license("GPL-3.0"). --export([start/1, stop/0]). +-export([do/1]). +-export([subscribe/1, unsubscribe/0]). +-export([start/0, stop/0]). -export([start/2, stop/1]). --export_type([serial/0, package_id/0, package/0, realm/0, name/0, version/0, option/0, - host/0, key_id/0, key_name/0, user/0, username/0, lower0_9/0, label/0, +-export_type([serial/0, package_id/0, package/0, realm/0, name/0, version/0, + option/0, + host/0, + key_id/0, key_name/0, + user/0, username/0, lower0_9/0, label/0, package_meta/0]). -include("zx_logger.hrl"). --record(s, - {realm = "otpr" :: realm(), - name = none :: none | name(), - version = {z, z, z} :: version(), - type = app :: app | lib, - deps = [] :: [package_id()], - serial = 0 :: serial(), - dir = none :: none | file:filename(), - socket = none :: none | gen_tcp:socket(), - pid = none :: none | pid(), - mon = none :: none | reference()}). - - %%% Type Definitions --type state() :: #s{}. -type serial() :: integer(). -type package_id() :: {realm(), name(), version()}. -type package() :: {realm(), name()}. @@ -56,9 +47,6 @@ Patch :: non_neg_integer() | z}. -type option() :: {string(), term()}. -type host() :: {string() | inet:ip_address(), inet:port_number()}. -%-type keybin() :: {ID :: key_id(), -% Type :: public | private, -% DER :: binary()}. -type key_id() :: {realm(), key_name()}. -type key_name() :: label(). -type user() :: {realm(), username()}. @@ -69,74 +57,73 @@ --spec start(Args) -> no_return() +%%% Command Dispatch + +-spec do(Args) -> no_return() when Args :: [string()]. %% Dispatch work functions based on the nature of the input arguments. -start(["help"]) -> +do(["help"]) -> usage_exit(0); -start(["run", PackageString | Args]) -> +do(["run", PackageString | Args]) -> run(PackageString, Args); -start(["init", "app", PackageString]) -> - PackageID = package_id(PackageString), - initialize(app, PackageID); -start(["init", "lib", PackageString]) -> - PackageID = package_id(PackageString), - initialize(lib, PackageID); -start(["install", PackageFile]) -> +do(["runlocal" | ArgV]) -> + run_local(ArgV); +do(["init", "app", PackageString]) -> + initialize(app, PackageString); +do(["init", "lib", PackageString]) -> + initialize(lib, PackageString); +do(["install", PackageFile]) -> assimilate(PackageFile); -start(["set", "dep", PackageString]) -> - PackageID = package_id(PackageString), - set_dep(PackageID); -start(["set", "version", VersionString]) -> +do(["set", "dep", PackageString]) -> + set_dep(PackageString); +do(["set", "version", VersionString]) -> set_version(VersionString); -start(["list", "realms"]) -> +do(["list", "realms"]) -> list_realms(); -start(["list", "packages", Realm]) -> +do(["list", "packages", Realm]) -> ok = valid_realm(Realm), list_packages(Realm); -start(["list", "versions", PackageName]) -> +do(["list", "versions", PackageName]) -> Package = string_to_package(PackageName), list_versions(Package); -start(["list", "pending", PackageName]) -> +do(["list", "pending", PackageName]) -> Package = string_to_package(PackageName), list_pending(Package); -start(["list", "resigns", Realm]) -> +do(["list", "resigns", Realm]) -> ok = valid_realm(Realm), list_resigns(Realm); -start(["add", "realm", RealmFile]) -> +do(["add", "realm", RealmFile]) -> add_realm(RealmFile); -start(["add", "package", PackageName]) -> +do(["add", "package", PackageName]) -> add_package(PackageName); -start(["add", "packager", Package, UserName]) -> +do(["add", "packager", Package, UserName]) -> add_packager(Package, UserName); -start(["add", "maintainer", Package, UserName]) -> +do(["add", "maintainer", Package, UserName]) -> add_maintainer(Package, UserName); -start(["review", PackageString]) -> +do(["review", PackageString]) -> review(PackageString); -start(["approve", PackageString]) -> - PackageID = package_id(PackageString), +do(["approve", PackageString]) -> + PackageID = zx_lib:package_id(PackageString), approve(PackageID); -start(["reject", PackageString]) -> - PackageID = package_id(PackageString), +do(["reject", PackageString]) -> + PackageID = zx_lib:package_id(PackageString), reject(PackageID); -start(["resign", PackageString]) -> +do(["resign", PackageString]) -> resign(PackageString); -start(["drop", "dep", PackageString]) -> - PackageID = package_id(PackageString), +do(["drop", "dep", PackageString]) -> + PackageID = zx_lib:package_id(PackageString), drop_dep(PackageID); -start(["drop", "key", KeyID]) -> +do(["drop", "key", KeyID]) -> drop_key(KeyID); -start(["drop", "realm", Realm]) -> +do(["drop", "realm", Realm]) -> drop_realm(Realm); -start(["verup", Level]) -> +do(["verup", Level]) -> verup(Level); -start(["runlocal" | Args]) -> - run_local(Args); -start(["package"]) -> +do(["package"]) -> {ok, TargetDir} = file:get_cwd(), package(TargetDir); -start(["package", TargetDir]) -> +do(["package", TargetDir]) -> case filelib:is_dir(TargetDir) of true -> package(TargetDir); @@ -144,41 +131,123 @@ start(["package", TargetDir]) -> ok = log(error, "Target directory ~tp does not exist!", [TargetDir]), halt(22) end; -start(["submit", PackageFile]) -> +do(["submit", PackageFile]) -> submit(PackageFile); -start(["dialyze"]) -> +do(["dialyze"]) -> dialyze(); -start(["create", "user", Realm, Name]) -> +do(["create", "user", Realm, Name]) -> create_user(Realm, Name); -start(["create", "keypair"]) -> +do(["create", "keypair"]) -> create_keypair(); -start(["create", "plt"]) -> +do(["create", "plt"]) -> create_plt(); -start(["create", "realm"]) -> +do(["create", "realm"]) -> create_realm(); -start(["create", "realmfile", Realm]) -> +do(["create", "realmfile", Realm]) -> create_realmfile(Realm); -start(["create", "sysop"]) -> +do(["create", "sysop"]) -> create_sysop(); -start(_) -> +do(_) -> usage_exit(22). +%%% Daemon Controls + +-spec subscribe(package()) -> ok | {error, Reason :: term()}. +%% @doc +%% Initiates the zx_daemon and instructs it to subscribe to a package. +%% +%% Any events in the Zomp network that apply to the subscribed package will be +%% forwarded to the process that originally called subscribe/1. How the original +%% caller reacts to these notifications is up to the author -- not reply or "ack" +%% is expected. +%% +%% Package subscriptions can be used as the basis for user notification of updates, +%% automatic upgrade restarts, package catalog tracking, etc. + +subscribe(Package) -> + case application:start(?MODULE, normal) of + ok -> zx_daemon:subscribe(Package); + Error -> Error + end. + + +-spec unsubscribe() -> ok | {error, Reason :: term()}. +%% @doc +%% Unsubscribes from package updates. + +unsubscribe() -> + zx_daemon:unsubscribe(). + + + +%%% Application Start/Stop + +-spec start() -> ok | {error, Reason :: term()}. +%% @doc +%% An alias for `application:ensure_started(zx)', meaning it is safe to call this +%% function more than once, or within a system where you are unsure whether zx is +%% already running (perhaps due to complex dependencies that require zx already). +%% In the typical case this function does not ever need to be called, because the +%% zx_daemon is always started in the background whenever an application is started +%% using the command `zx run [app_id]'. +%% @equiv application:ensure_started(zx). + +start() -> + application:ensure_started(zx). + + +-spec stop() -> ok | {error, Reason :: term()}. +%% @doc +%% A safe wrapper for `application:stop(zx)'. Similar to `ensure_started/1,2', returns +%% `ok' in the case that zx is already stopped. + +stop() -> + case application:stop(zx) of + ok -> ok; + {error, {not_started, zx}} -> ok; + Error -> Error + end. + + +%%% Application Callbacks + +-spec start(StartType, StartArgs) -> Result + when StartType :: normal, + StartArgs :: [], + Result :: {ok, pid()}. +%% @private +%% Application callback. Not to be called directly. + +start(normal, []) -> + ok = application:ensure_started(inets), + zx_daemon:start_link(). + + +-spec stop(term()) -> ok. +%% @private +%% Application callback. Not to be called directly. + +stop(_) -> + ok. + + + %%% Execution of application --spec run(Identifier, Args) -> no_return() +-spec run(Identifier, RunArgs) -> no_return() when Identifier :: string(), - Args :: [string()]. + RunArgs :: [string()]. %% @private %% Given a program Identifier and a list of Args, attempt to locate the program and its %% dependencies and run the program. This implies determining whether the program and %% its dependencies are installed, available, need to be downloaded, or are inaccessible %% given the current system condition (they could also be bogus, of course). The -%% Identifier should be a valid PackageString of the form `realm-appname-version' -%% where the realm and appname should follow standard realm and app package naming -%% conventions and the version should be represented as a semver in string form (where -%% ommitted elements of the version always default to whatever is most current). +%% Identifier must be a valid package string of the form `realm-appname[-version]' +%% where the `realm()' and `name()' must follow Zomp package naming conventions and the +%% version should be represented as a semver in string form (where ommitted elements of +%% the version always default to whatever is most current). %% %% Once the target program is running, this process, (which will run with the registered %% name `zx') will sit in an `exec_wait' state, waiting for either a direct message from @@ -187,28 +256,127 @@ start(_) -> %% If there is a problem anywhere in the locating, discovery, building, and loading %% procedure the runtime will halt with an error message. -run(Identifier, Args) -> - MaybeID = package_id(Identifier), - {ok, PackageID = {Realm, Name, Version}} = ensure_installed(MaybeID), - ok = file:set_cwd(zomp_dir()), - Dir = filename:join("lib", package_string(PackageID)), - Meta = read_meta(Dir), +run(Identifier, RunArgs) -> + ok = file:set_cwd(zx_lib:zomp_home()), + ok = start(), + FuzzyID = + case zx_lib:package_id(Identifier) of + {ok, Fuzzy} -> + Fuzzy; + {error, invalid_package_string} -> + error_exit("Bad package string: ~ts", [Identifier], ?LINE) + end, + {ok, PackageID} = ensure_installed(FuzzyID), + ok = build(PackageID), + Dir = zx_lib:package_dir(PackageID), + {ok, Meta} = zx_lib:read_project_meta(Dir), + execute(PackageID, Meta, Dir, RunArgs). + + + +%%% Execution of local project + +-spec run_local(RunArgs) -> no_return() + when RunArgs :: [term()]. +%% @private +%% Execute a local project from source from the current directory, satisfying dependency +%% requirements via the locally installed zomp lib cache. The project must be +%% initialized as a zomp project (it must have a valid `zomp.meta' file). +%% +%% The most common use case for this function is during development. Using zomp support +%% via the local lib cache allows project authors to worry only about their own code +%% and use zx commands to add or drop dependencies made available via zomp. + +run_local(RunArgs) -> + Meta = zx_lib:read_project_meta(), + PackageID = maps:get(package_id, Meta), + ok = build(), + {ok, Dir} = file:get_cwd(), + ok = file:set_cwd(zx_lib:zomp_home()), + ok = start(), + execute(PackageID, Meta, Dir, RunArgs). + + +-spec execute(PackageID, Meta, Dir, RunArgs) -> no_return() + when PackageID :: package_id(), + Meta :: package_meta(), + Dir :: file:filename(), + RunArgs :: [string()]. +%% @private +%% Execution prep common to all packages. + +execute(PackageID, Meta, Dir, RunArgs) -> + PackageString = zx_lib:package_string(PackageID), + ok = log(info, "Preparing ~ts...", [PackageString]), + Type = maps:get(type, Meta), Deps = maps:get(deps, Meta), - ok = ensure_deps(Deps), - State = #s{realm = Realm, - name = Name, - version = Version, - dir = Dir, - deps = Deps}, - execute(State, Args). + case zx_daemon:fetch(Deps) of + {{ok, _}, {error, []}} -> + ok = lists:foreach(fun install/1, Deps), + ok = lists:foreach(fun build/1, Deps), + execute(Type, PackageID, Dir, Meta, RunArgs); + {{ok, _}, {error, Errors}} -> + error_exit("Failed package fetches: ~tp", [Errors], ?LINE) + end. + + +-spec execute(Type, PackageID, Meta, Dir, RunArgs) -> no_return() + when Type :: app | lib, + Meta :: package_meta(), + Dir :: file:filename(), + RunArgs :: [string()]. +%% @private +%% Gets all the target application's ducks in a row and launches them, then enters +%% the exec_wait/1 loop to wait for any queries from the application. + +execute(app, PackageID, Meta, Dir, RunArgs) -> + PackageString = zx_lib:package_string(PackageID), + ok = log(info, "Starting ~ts.", [PackageString]), + Name = element(2, PackageID), + AppMod = list_to_atom(Name), + ok = zx_daemon:pass_meta(Meta, Dir), + ok = ensure_all_started(AppMod), + ok = pass_argv(AppMod, RunArgs), + exec_wait(State); +execute(lib, PackageID, _, _, _) -> + Message = "Lib ~ts is available on the system, but is not a standalone app.", + PackageString = package_string(PackageID), + ok = log(info, Message, [PackageString]), + halt(0). + + +-spec ensure_all_started(AppMod) -> ok + when AppMod :: module(). +%% @private +%% Wrap a call to application:ensure_all_started/1 to selectively provide output +%% in the case any dependencies are actually started by the call. Might remove this +%% depending on whether SASL winds up becoming a standard part of the system and +%% whether it becomes common for dependencies to all signal their own start states +%% somehow. + +ensure_all_started(AppMod) -> + case application:ensure_all_started(AppMod) of + {ok, []} -> ok; + {ok, Apps} -> log(info, "Started ~tp", [Apps]) + end. + + +-spec pass_argv(AppMod, Args) -> ok + when AppMod :: module(), + Args :: [string()]. +%% @private +%% Check whether the AppMod:accept_argv/1 is implemented. If so, pass in the +%% command line arguments provided. + +pass_argv(AppMod, Args) -> %%% Project initialization --spec initialize(Type, PackageID) -> no_return() - when Type :: app | lib, - PackageID :: package_id(). +-spec initialize(Type, PackageString) -> no_return() + when Type :: app | lib, + PackageString :: string(). %% @private %% Initialize an application in the local directory based on the PackageID provided. %% This function does not care about the name of the current directory and leaves @@ -218,14 +386,21 @@ run(Identifier, Args) -> %% in `lib/' then the project will need to be rearranged to become zomp compliant or %% the `deps' section of the resulting meta file will need to be manually updated. -initialize(Type, PackageID) -> - PackageString = package_string(PackageID), +initialize(Type, PackageString) -> + PackageID = + case zx_lib:package_id(PackageString) of + {ok, ID} -> + ID; + {error, invalid_package_string} -> + error_exit("Invalid package string.", ?LINE) + end, ok = log(info, "Initializing ~s...", [PackageString]), - MetaList = [{package_id, PackageID}, - {deps, []}, - {type, Type}], + MetaList = + [{package_id, PackageID}, + {deps, []}, + {type, Type}], Meta = maps:from_list(MetaList), - ok = write_meta(Meta), + ok = zx_lib:write_project_meta(Meta), ok = log(info, "Project ~tp initialized.", [PackageString]), Message = "NOTICE:~n" @@ -248,23 +423,23 @@ initialize(Type, PackageID) -> %% contents. assimilate(PackageFile) -> - Files = extract_zrp(PackageFile), + Files = extract_zrp_or_die(PackageFile), {ok, CWD} = file:get_cwd(), - ok = file:set_cwd(zomp_dir()), + ok = file:set_cwd(zx_lib:zomp_home()), {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), Meta = binary_to_term(MetaBin), PackageID = maps:get(package_id, Meta), - TgzFile = namify_tgz(PackageID), + TgzFile = zx_lib:namify_tgz(PackageID), {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files), {KeyID, Signature} = maps:get(sig, Meta), {ok, PubKey} = loadkey(public, KeyID), ok = case public_key:verify(TgzData, sha512, Signature, PubKey) of true -> - ZrpPath = filename:join("zrp", namify_zrp(PackageID)), - erl_tar:create(ZrpPath, Files); + ZrpPath = filename:join("zrp", zx_lib:namify_zrp(PackageID)), + file:copy(PackageFile, ZrpPath); false -> - error_exit("Bad package signature: ~ts", [PackageFile], ?FILE, ?LINE) + error_exit("Bad package signature: ~ts", [PackageFile], ?LINE) end, ok = file:set_cwd(CWD), Message = "~ts is now locally available.", @@ -275,7 +450,7 @@ assimilate(PackageFile) -> %%% Set dependency --spec set_dep(package_id()) -> no_return(). +-spec set_dep(Identifier :: string()) -> no_return(). %% @private %% Set a specific dependency in the current project. If the project currently has a %% dependency on the same package then the version of that dependency is updated to @@ -283,9 +458,27 @@ assimilate(PackageFile) -> %% incomplete. Incomplete elements of the VersionString (if included) will default to %% the latest version available at the indicated level. -set_dep(PackageID = {_, _, {X, Y, Z}}) - when is_integer(X), is_integer(Y), is_integer(Z) -> - Meta = read_meta(), +set_dep(Identifier) -> + {ok, {Realm, Name, FuzzyVersion}} = zx_lib:package_id(Identifier), + Version = + case FuzzyVersion of + {z, z, z} -> + ok = start(), + {ok, V} = zx_daemon:query_latest({Realm, Name}), + V; + {X, Y, Z} when is_integer(X), is_integer(Y), is_integer(Z) -> + {X, Y, Z}; + _ -> + ok = start(), + {ok, V} = zx_daemon:query_latest({Realm, Name, FuzzyVersion}), + V + end, + set_dep({Realm, Name}, Version). + + +set_dep({Realm, Name}, Version) -> + PackageID = {Realm, Name, Version}, + {ok, Meta} = zx_lib:read_project_meta(), Deps = maps:get(deps, Meta), case lists:member(PackageID, Deps) of true -> @@ -293,17 +486,7 @@ set_dep(PackageID = {_, _, {X, Y, Z}}) halt(0); false -> set_dep(PackageID, Deps, Meta) - end; -set_dep({Realm, Name, {z, z, z}}) -> - Socket = connect_user(Realm), - {ok, Version} = query_latest(Socket, {Realm, Name}), - ok = disconnect(Socket), - set_dep({Realm, Name, Version}); -set_dep({Realm, Name, Version}) -> - Socket = connect_user(Realm), - {ok, Latest} = query_latest(Socket, {Realm, Name, Version}), - ok = disconnect(Socket), - set_dep({Realm, Name, Latest}). + end. -spec set_dep(PackageID, Deps, Meta) -> no_return() @@ -317,7 +500,7 @@ set_dep({Realm, Name, Version}) -> %% file and exit. set_dep(PackageID = {Realm, Name, NewVersion}, Deps, Meta) -> - ExistingPackageIDs = fun ({R, N, _}) -> {R, N} == {Realm, Name} end, + ExistingPackageIDs = fun({R, N, _}) -> {R, N} == {Realm, Name} end, NewDeps = case lists:partition(ExistingPackageIDs, Deps) of {[{Realm, Name, OldVersion}], Rest} -> @@ -331,7 +514,7 @@ set_dep(PackageID = {Realm, Name, NewVersion}, Deps, Meta) -> [PackageID | Deps] end, NewMeta = maps:put(deps, NewDeps, Meta), - ok = write_meta(NewMeta), + ok = zx_lib:write_project_meta(NewMeta), halt(0). @@ -347,7 +530,26 @@ ensure_installed(PackageID = {Realm, Name, Version}) -> case resolve_installed_version(PackageID) of exact -> {ok, PackageID}; {ok, Installed} -> {ok, {Realm, Name, Installed}}; - not_found -> ensure_installed(Realm, Name, Version) + not_found -> fetch({Realm, Name, Version}) + end. + + +-spec fetch_one(PackageID) -> {ok, ActualID} | no_return() + when PackageID :: package_id(), + ActualID :: package_id(). +%% @private +%% A helper function to deal with the special case of downloading and installing a +%% single primary application package with a possibly incomplete version designator. +%% All other fetches are for arbitrarily long lists of package IDs with complete +%% version numbers (dependency fetches). + +fetch_one(PackageID) -> + case zx_daemon:fetch([PackageID]) of + {{ok, [ActualID]}, {error, []}} -> + ok = install(ActualID), + {ok, ActualID}; + {{ok, []}, {error, [{PackageID, Reason}]}} -> + error_exit("Package fetch failed with: ~tp", [Reason], ?LINE) end. @@ -363,12 +565,10 @@ ensure_installed(PackageID = {Realm, Name, Version}) -> %% the version indicator is complete, partial or blank. ensure_installed(Realm, Name, Version) -> - Socket = connect_user(Realm), - case query_latest(Socket, {Realm, Name, Version}) of + case zx_daemon:query_latest({Realm, Name, Version}) of {ok, LatestVersion} -> LatestID = {Realm, Name, LatestVersion}, ok = ensure_dep(Socket, LatestID), - ok = disconnect(Socket), {ok, LatestID}; {error, bad_realm} -> PackageString = package_string({Realm, Name, Version}), @@ -385,32 +585,6 @@ ensure_installed(Realm, Name, Version) -> end. --spec query_latest(Socket, Object) -> Result - when Socket :: gen_tcp:socket(), - Object :: package() | package_id(), - Result :: {ok, version()} - | {error, Reason}, - Reason :: bad_realm - | bad_package - | bad_version. -%% @private -%% Queries the connected zomp node for the latest version of a package or package -%% version (complete or incomplete version number). - -query_latest(Socket, {Realm, Name}) -> - ok = send(Socket, {latest, Realm, Name}), - receive - {tcp, Socket, Bin} -> binary_to_term(Bin) - after 5000 -> {error, timeout} - end; -query_latest(Socket, {Realm, Name, Version}) -> - ok = send(Socket, {latest, Realm, Name, Version}), - receive - {tcp, Socket, Bin} -> binary_to_term(Bin) - after 5000 -> {error, timeout} - end. - - -spec resolve_installed_version(PackageID) -> Result when PackageID :: package_id(), Result :: not_found @@ -422,74 +596,27 @@ query_latest(Socket, {Realm, Name, Version}) -> %% found (in the case of a full version input), a version matching a partial version %% input was found, or no match was found at all. -resolve_installed_version(PackageID) -> - PackageString = package_string(PackageID), - Pattern = PackageString ++ "*", - case filelib:wildcard(Pattern, "lib") of - [] -> - not_found; - [PackageString] -> - exact; - [Dir] -> - {_, _, Version} = package_id(Dir), - {ok, Version}; - Dirs -> - Dir = lists:last(lists:sort(Dirs)), - {_, _, Version} = package_id(Dir), - {ok, Version} +resolve_installed_version({Realm, Name, Version}) -> + PackageDir = filename:join(["lib", Realm, Name]), + case filelib:is_dir(PackageDir) of + true -> resolve_installed_version(PackageDir, Version); + false -> not_found end. -ensure_deps(Deps) -> - case scrub(Deps) of - [] -> - ok; - Needed -> - Partitioned = partition_by_realm(Needed), - EnsureDeps = - fun({Realm, Packages}) -> - Socket = connect_user(Realm), - ok = ensure_deps(Socket, Realm, Packages), - ok = disconnect(Socket), - log(info, "Disconnecting from realm: ~ts", [Realm]) - end, - lists:foreach(EnsureDeps, Partitioned) +resolve_installed_version(PackageDir, Version) -> + DirStrings = filelib:wildcard("*", PackageDir), + Versions = lists:fold(fun tuplize/2, [], DirStrings), + zx_lib:find_latest_compatible(Version, Versions). + + +tuplize(String, Acc) -> + case zx_lib:string_to_version(String) of + {ok, Version} -> [Version | Acc]; + _ -> Acc end. -partition_by_realm(PackageIDs) -> - PartitionMap = lists:foldl(fun partition_by_realm/2, #{}, PackageIDs), - maps:to_list(PartitionMap). - - -partition_by_realm({R, P, V}, M) -> - maps:update_with(R, fun(Ps) -> [{P, V} | Ps] end, [{P, V}], M). - - -ensure_deps(_, _, []) -> - ok; -ensure_deps(Socket, Realm, [{Name, Version} | Rest]) -> - ok = ensure_dep(Socket, {Realm, Name, Version}), - ensure_deps(Socket, Realm, Rest). - - --spec ensure_dep(gen_tcp:socket(), package_id()) -> ok | no_return(). -%% @private -%% Given an PackageID as an argument, check whether its package file exists in the -%% system cache, and if not download it. Should return `ok' whenever the file is -%% sourced, but exit with an error if it cannot locate or acquire the package. - -ensure_dep(Socket, PackageID) -> - ZrpFile = filename:join("zrp", namify_zrp(PackageID)), - ok = - case filelib:is_regular(ZrpFile) of - true -> ok; - false -> fetch(Socket, PackageID) - end, - ok = install(PackageID), - build(PackageID). - - %%% Set version @@ -501,7 +628,7 @@ ensure_dep(Socket, PackageID) -> set_version(VersionString) -> NewVersion = - case string_to_version(VersionString) of + case zx_lib:string_to_version(VersionString) of {_, _, z} -> Message = "'set version' arguments must be complete, ex: 1.2.3", ok = log(error, Message), @@ -525,7 +652,7 @@ set_version(VersionString) -> %% read for some reason. update_version(Arg) -> - Meta = read_meta(), + {ok, Meta} = zx_lib:read_project_meta(), PackageID = maps:get(package_id, Meta), update_version(Arg, PackageID, Meta). @@ -573,10 +700,11 @@ update_version(NewVersion, {Realm, Name, OldVersion}, OldMeta) -> update_version(Realm, Name, OldVersion, NewVersion, OldMeta) -> PackageID = {Realm, Name, NewVersion}, NewMeta = maps:put(package_id, PackageID, OldMeta), - ok = write_meta(NewMeta), + ok = zx_lib:write_project_meta(NewMeta), ok = log(info, "Version changed from ~s to ~s.", - [version_to_string(OldVersion), version_to_string(NewVersion)]), + [zx_lib:version_to_string(OldVersion), + zx_lib:version_to_string(NewVersion)]), halt(0). @@ -590,7 +718,7 @@ update_version(Realm, Name, OldVersion, NewVersion, OldMeta) -> %% stdout and the program will exit. list_realms() -> - Pattern = filename:join(zomp_dir(), "*.realm"), + Pattern = filename:join(zx_lib:zomp_home(), "*.realm"), RealmFiles = filelib:wildcard(Pattern), Realms = [filename:basename(RF, ".realm") || RF <- RealmFiles], ok = lists:foreach(fun(R) -> io:format("~ts~n", [R]) end, Realms), @@ -603,16 +731,23 @@ list_realms() -> %% them to stdout. list_packages(Realm) -> - Socket = connect_user(Realm), - ok = send(Socket, {list, Realm}), - case recv_or_die(Socket) of + case zx_daemon:list_packages(Realm) of {ok, []} -> ok = log(info, "Realm ~tp has no packages available.", [Realm]), halt(0); {ok, Packages} -> Print = fun({R, N}) -> io:format("~ts-~ts~n", [R, N]) end, ok = lists:foreach(Print, Packages), - halt(0) + halt(0); + {error, bad_realm} -> + ok = log(error, "Bad realm name."), + halt(1); + {error, no_realm} -> + ok = log(error, "Realm \"~ts\" is not configured.", [Realm]), + halt(1); + {error, network} -> + ok = log(error, "Network issues are preventing connection to the realm."), + halt(1) end. @@ -698,7 +833,7 @@ list_resigns(Realm) -> %% a non-zero error code, if so then return `ok'. valid_package({Realm, Name}) -> - case {valid_lower0_9(Realm), valid_lower0_9(Name)} of + case {zx_lib:valid_lower0_9(Realm), zx_lib:valid_lower0_9(Name)} of {true, true} -> ok; {false, true} -> @@ -735,7 +870,7 @@ string_to_package(String) -> %% halt execution with a non-zero error code, if so then return `ok'. valid_realm(Realm) -> - case valid_lower0_9(Realm) of + case zx_lib:valid_lower0_9(Realm) of true -> ok; false -> @@ -771,7 +906,7 @@ add_realm(Path) -> Data :: binary(). add_realm(Path, Data) -> - case erl_tar:extract({binary, Data}, [compressed, {cwd, zomp_dir()}]) of + case erl_tar:extract({binary, Data}, [compressed, {cwd, zx_lib:zomp_home()}]) of ok -> {Realm, _} = string:take(filename:basename(Path), ".", true), ok = log(info, "Realm ~ts is now visible to this system.", [Realm]), @@ -789,10 +924,10 @@ add_realm(Path, Data) -> when PackageName :: package(). add_package(PackageName) -> - ok = file:set_cwd(zomp_dir()), + ok = file:set_cwd(zx_lib:zomp_home()), case string:lexemes(PackageName, "-") of [Realm, Name] -> - case {valid_lower0_9(Realm), valid_lower0_9(Name)} of + case {zx_lib:valid_lower0_9(Realm), zx_lib:valid_lower0_9(Name)} of {true, true} -> add_package(Realm, Name); {false, true} -> @@ -836,7 +971,7 @@ add_maintainer(Package, UserName) -> review(PackageString) -> - PackageID = {Realm, _, _} = package_id(PackageString), + PackageID = {Realm, _, _} = zx_lib:package_id(PackageString), Socket = connect_auth_or_die(Realm), ok = send(Socket, {review, PackageID}), {ok, ZrpBin} = recv_or_die(Socket), @@ -882,7 +1017,7 @@ reject(PackageID = {Realm, _, _}) -> resign(PackageString) -> - PackageID = {Realm, _, _} = package_id(PackageString), + PackageID = {Realm, _, _} = zx_lib:package_id(PackageString), RealmConf = load_realm_conf(Realm), {package_keys, PackageKeys} = lists:keyfind(package_keys, 1, RealmConf), KeySelection = [{K, {R, K}} || {R, K} <- [element(1, K) || K <- PackageKeys]], @@ -925,13 +1060,13 @@ resign(PackageString) -> drop_dep(PackageID) -> PackageString = package_string(PackageID), - Meta = read_meta(), + {ok, Meta} = zx_lib:read_project_meta(), Deps = maps:get(deps, Meta), case lists:member(PackageID, Deps) of true -> NewDeps = lists:delete(PackageID, Deps), NewMeta = maps:put(deps, NewDeps, Meta), - ok = write_meta(NewMeta), + ok = zx_lib:write_project_meta(NewMeta), Message = "~ts removed from dependencies.", ok = log(info, Message, [PackageString]), halt(0); @@ -951,8 +1086,8 @@ drop_dep(PackageID) -> %% error exit value (this instruction is idempotent if used in shell scripts). drop_key({Realm, KeyName}) -> - ok = file:set_cwd(zomp_dir()), - Pattern = filename:join([zomp_dir(), "key", Realm, KeyName ++ ".{key,pub}.der"]), + ok = file:set_cwd(zx_lib:zomp_home()), + Pattern = filename:join([zx_lib:zomp_home(), "key", Realm, KeyName ++ ".{key,pub}.der"]), case filelib:wildcard(Pattern) of [] -> ok = log(warning, "Key ~ts/~ts not found", [Realm, KeyName]), @@ -969,7 +1104,7 @@ drop_key({Realm, KeyName}) -> -spec drop_realm(realm()) -> no_return(). drop_realm(Realm) -> - ok = file:set_cwd(zomp_dir()), + ok = file:set_cwd(zx_lib:zomp_home()), RealmConf = realm_conf(Realm), case filelib:is_regular(RealmConf) of true -> @@ -1003,7 +1138,7 @@ drop_prime(Realm) -> {managed, Primes} = lists:keyfind(managed, 1, Conf), NewPrimes = lists:delete(Realm, Primes), NewConf = lists:keystore(managed, 1, Primes, {managed, NewPrimes}), - ok = write_terms(Path, NewConf), + ok = zx_lib:write_terms(Path, NewConf), log(info, "Ensuring ~ts is not a prime in ~ts", [Realm, Path]); {error, enoent} -> ok @@ -1013,7 +1148,7 @@ drop_prime(Realm) -> -spec clear_keys(realm()) -> ok. clear_keys(Realm) -> - KeyDir = filename:join([zomp_dir(), "key", Realm]), + KeyDir = filename:join([zx_lib:zomp_home(), "key", Realm]), case filelib:is_dir(KeyDir) of true -> ok = log(info, "Wiping key dir ~ts", [KeyDir]), @@ -1042,76 +1177,6 @@ verup(_) -> usage_exit(22). -%%% Run local project - --spec run_local(Args) -> no_return() - when Args :: [term()]. -%% @private -%% Execute a local project from source from the current directory, satisfying dependency -%% requirements via the locally installed zomp lib cache. The project must be -%% initialized as a zomp project (it must have a valid `zomp.meta' file). -%% -%% The most common use case for this function is during development. Using zomp support -%% via the local lib cache allows project authors to worry only about their own code -%% and use zx commands to add or drop dependencies made available via zomp. - -run_local(Args) -> - Meta = read_meta(), - {Realm, Name, Version} = maps:get(package_id, Meta), - Type = maps:get(type, Meta), - Deps = maps:get(deps, Meta), - ok = build(), - {ok, Dir} = file:get_cwd(), - ok = file:set_cwd(zomp_dir()), - State = #s{realm = Realm, - name = Name, - version = Version, - type = Type, - deps = Deps, - dir = Dir}, - ok = ensure_deps(Deps), - ok = file:set_cwd(Dir), - execute(State, Args). - - --spec execute(State, Args) -> no_return() - when State :: state(), - Args :: [string()]. -%% @private -%% Gets all the target application's ducks in a row and launches them, then enters -%% the exec_wait/1 loop to wait for any queries from the application. - -execute(State = #s{type = app, realm = Realm, name = Name, version = Version}, Args) -> - true = register(zx, self()), - ok = inets:start(), - ok = log(info, "Starting ~ts", [package_string({Realm, Name, Version})]), - AppMod = list_to_atom(Name), - {ok, Apps} = application:ensure_all_started(AppMod), - ok = log(info, "Started, ~tp", [Apps]), - ok = pass_argv(AppMod, Args), - exec_wait(State); -execute(#s{type = lib, realm = Realm, name = Name, version = Version}, _) -> - Message = "Lib ~ts is available on the system, but is not a standalone app.", - PackageString = package_string({Realm, Name, Version}), - ok = log(info, Message, [PackageString]), - halt(0). - - --spec pass_argv(AppMod, Args) -> ok - when AppMod :: module(), - Args :: [string()]. -%% @private -%% Check whether the AppMod:accept_argv/1 is implemented. If so, pass in the -%% command line arguments provided. - -pass_argv(AppMod, Args) -> - case lists:member({accept_argv, 1}, AppMod:module_info(exports)) of - true -> AppMod:accept_argv(Args); - false -> ok - end. - - - %%% Package generation -spec package(TargetDir) -> no_return() @@ -1122,9 +1187,9 @@ pass_argv(AppMod, Args) -> package(TargetDir) -> ok = log(info, "Packaging ~ts", [TargetDir]), - Meta = read_meta(TargetDir), + {ok, Meta} = zx_lib:read_project_meta(TargetDir), {Realm, _, _} = maps:get(package_id, Meta), - KeyDir = filename:join([zomp_dir(), "key", Realm]), + KeyDir = filename:join([zx_lib:zomp_home(), "key", Realm]), ok = force_dir(KeyDir), Pattern = KeyDir ++ "/*.key.der", case [filename:basename(F, ".key.der") || F <- filelib:wildcard(Pattern)] of @@ -1151,7 +1216,7 @@ package(TargetDir) -> %% build a zrp package file ready to be submitted to a repository. package(KeyID, TargetDir) -> - Meta = read_meta(TargetDir), + {ok, Meta} = zx_lib:read_project_meta(TargetDir), PackageID = maps:get(package_id, Meta), true = element(1, PackageID) == element(1, KeyID), PackageString = package_string(PackageID), @@ -1209,7 +1274,7 @@ remove_binaries(TargetDir) -> %% Submit a package to the appropriate "prime" server for the given realm. submit(PackageFile) -> - Files = extract_zrp(PackageFile), + Files = extract_zrp_or_die(PackageFile), {ok, PackageData} = file:read_file(PackageFile), {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), Meta = binary_to_term(MetaBin), @@ -1297,7 +1362,7 @@ halt_on_unexpected_close() -> connect_user(Realm) -> ok = log(info, "Connecting to realm ~ts...", [Realm]), Hosts = - case file:consult(hosts_cache_file(Realm)) of + case file:consult(zx_lib:hosts_cache_file(Realm)) of {ok, Cached} -> Cached; {error, enoent} -> [] end, @@ -1309,7 +1374,7 @@ connect_user(Realm) -> %% Try to connect to a subordinate host, if there are none then connect to prime. connect_user(Realm, []) -> - {Host, Port} = get_prime(Realm), + {Host, Port} = zx_lib:get_prime(Realm), HostString = case io_lib:printable_unicode_list(Host) of true -> Host; @@ -1375,7 +1440,7 @@ confirm_user(Realm, Socket, Hosts) -> %% reach, and if not retry on another node. confirm_serial(Realm, Socket, Hosts) -> - SerialFile = filename:join(zomp_dir(), "realm.serials"), + SerialFile = filename:join(zx_lib:zomp_home(), "realm.serials"), Serials = case file:consult(SerialFile) of {ok, Ss} -> Ss; @@ -1397,8 +1462,9 @@ confirm_serial(Realm, Socket, Hosts) -> ok = log(info, "Node's serial newer than ours. Storing."), NewSerials = lists:keystore(Realm, 1, Serials, {Realm, Current}), {ok, Host} = inet:peername(Socket), - ok = write_terms(hosts_cache_file(Realm), [Host | Hosts]), - ok = write_terms(SerialFile, NewSerials), + CacheFile = zx_lib:hosts_cache_file(Realm), + ok = zx_lib:write_terms(CacheFile, [Host | Hosts]), + ok = zx_lib:write_terms(SerialFile, NewSerials), Socket; {ok, Current} when Current < Serial -> log(info, "Our serial: ~tp, node serial: ~tp.", [Serial, Current]), @@ -1542,7 +1608,7 @@ confirm_auth(Socket) -> %% connect_auth/4. prep_auth(Realm, RealmConf) -> - UsersFile = filename:join(zomp_dir(), "zomp.users"), + UsersFile = filename:join(zx_lib:zomp_home(), "zomp.users"), Users = case file:consult(UsersFile) of {ok, U} -> @@ -1586,24 +1652,6 @@ connect_options() -> [{packet, 4}, {mode, binary}, {active, true}]. --spec get_prime(realm()) -> host(). -%% @private -%% Check the given Realm's config file for the current prime node and return it. - -get_prime(Realm) -> - RealmMeta = realm_meta(Realm), - {prime, Prime} = lists:keyfind(prime, 1, RealmMeta), - Prime. - - --spec hosts_cache_file(realm()) -> file:filename(). -%% @private -%% Given a Realm name, construct a realm's .hosts filename and return it. - -hosts_cache_file(Realm) -> - filename:join(zomp_dir(), Realm ++ ".hosts"). - - -spec disconnect(gen_tcp:socket()) -> ok. %% @private %% Gracefully shut down a socket, logging (but sidestepping) the case when the socket @@ -1648,7 +1696,7 @@ ensure_keypair(KeyID = {Realm, KeyName}) -> have_public_key({Realm, KeyName}) -> PublicKeyFile = KeyName ++ ".pub.der", - PublicKeyPath = filename:join([zomp_dir(), "key", Realm, PublicKeyFile]), + PublicKeyPath = filename:join([zx_lib:zomp_home(), "key", Realm, PublicKeyFile]), filelib:is_regular(PublicKeyPath). @@ -1658,32 +1706,10 @@ have_public_key({Realm, KeyName}) -> have_private_key({Realm, KeyName}) -> PrivateKeyFile = KeyName ++ ".key.der", - PrivateKeyPath = filename:join([zomp_dir(), "key", Realm, PrivateKeyFile]), + PrivateKeyPath = filename:join([zx_lib:zomp_home(), "key", Realm, PrivateKeyFile]), filelib:is_regular(PrivateKeyPath). --spec realm_meta(Realm) -> Meta | no_return() - when Realm :: string(), - Meta :: [{atom(), term()}]. -%% @private -%% Given a realm name, try to locate and read the realm's configuration file if it -%% exists, exiting with an appropriate error message if there is a problem reading -%% the file. - -realm_meta(Realm) -> - RealmFile = filename:join(zomp_dir(), Realm ++ ".realm"), - case file:consult(RealmFile) of - {ok, Meta} -> - Meta; - {error, enoent} -> - ok = log(error, "No realm file for ~ts", [Realm]), - halt(1); - Error -> - Message = "Open realm file ~ts failed with ~ts", - error_exit(Message, [RealmFile, Error], ?FILE, ?LINE) - end. - - %%% Key generation @@ -1707,7 +1733,7 @@ prompt_keygen() -> [R, K] -> {R, K}; [K] -> {"otpr", K} end, - case {valid_lower0_9(Realm), valid_label(KeyName)} of + case {zx_lib:valid_lower0_9(Realm), zx_lib:valid_label(KeyName)} of {true, true} -> {Realm, KeyName}; {false, true} -> @@ -1727,11 +1753,11 @@ prompt_keygen() -> %% Execute the key generation procedure for 16k RSA keys once and then terminate. create_keypair() -> - ok = file:set_cwd(zomp_dir()), + ok = file:set_cwd(zx_lib:zomp_home()), KeyID = prompt_keygen(), case generate_rsa(KeyID) of {ok, _, _} -> halt(0); - Error -> error_exit("create_keypair/0 error: ~tp", [Error], ?FILE, ?LINE) + Error -> error_exit("create_keypair/0 error: ~tp", [Error], ?LINE) end. @@ -1747,7 +1773,7 @@ create_keypair() -> %% NOTE: The current version of this command is likely to only work on a unix system. generate_rsa({Realm, KeyName}) -> - KeyDir = filename:join([zomp_dir(), "key", Realm]), + KeyDir = filename:join([zx_lib:zomp_home(), "key", Realm]), ok = force_dir(KeyDir), PemFile = filename:join(KeyDir, KeyName ++ ".pub.pem"), KeyFile = filename:join(KeyDir, KeyName ++ ".key.der"), @@ -1865,7 +1891,7 @@ openssl() -> false -> ok = log(error, "OpenSSL could not be found in this system's PATH."), ok = log(error, "Install OpenSSL and then retry."), - error_exit("Missing system dependenct: OpenSSL", ?FILE, ?LINE); + error_exit("Missing system dependenct: OpenSSL", ?LINE); Path -> log(info, "OpenSSL executable found at: ~ts", [Path]) end, @@ -1884,10 +1910,10 @@ loadkey(Type, {Realm, KeyName}) -> {DerType, Path} = case Type of private -> - P = filename:join([zomp_dir(), "key", Realm, KeyName ++ ".key.der"]), + P = filename:join([zx_lib:zomp_home(), "key", Realm, KeyName ++ ".key.der"]), {'RSAPrivateKey', P}; public -> - P = filename:join([zomp_dir(), "key", Realm, KeyName ++ ".pub.der"]), + P = filename:join([zx_lib:zomp_home(), "key", Realm, KeyName ++ ".pub.der"]), {'RSAPublicKey', P} end, ok = log(info, "Loading key from file ~ts", [Path]), @@ -1930,7 +1956,7 @@ build_plt() -> default_plt() -> - filename:join(zomp_dir(), "basic.plt"). + filename:join(zx_lib:zomp_home(), "basic.plt"). @@ -1947,7 +1973,7 @@ dialyze() -> true -> log(info, "Using PLT: ~tp", [PLT]); false -> build_plt() end, - TmpDir = filename:join(zomp_dir(), "tmp"), + TmpDir = filename:join(zx_lib:zomp_home(), "tmp"), Me = escript:script_name(), EvilTwin = filename:join(TmpDir, filename:basename(Me ++ ".erl")), ok = log(info, "Temporarily reconstructing ~tp as ~tp", [Me, EvilTwin]), @@ -1988,7 +2014,7 @@ create_user(Realm, Username) -> %% realm file to the user. create_realm() -> - ConfFile = filename:join(zomp_dir(), "zomp.conf"), + ConfFile = filename:join(zx_lib:zomp_home(), "zomp.conf"), case file:consult(ConfFile) of {ok, ZompConf} -> create_realm(ZompConf); {error, enoent} -> create_realm([]) @@ -2006,9 +2032,9 @@ create_realm(ZompConf) -> " Names must begin with a lower-case letter.~n", ok = io:format(Instructions), Realm = get_input(), - case valid_lower0_9(Realm) of + case zx_lib:valid_lower0_9(Realm) of true -> - RealmFile = filename:join(zomp_dir(), Realm ++ ".realm"), + RealmFile = filename:join(zx_lib:zomp_home(), Realm ++ ".realm"), case filelib:is_regular(RealmFile) of false -> create_realm(ZompConf, Realm); @@ -2179,7 +2205,7 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort) -> " Names must begin with a lower-case letter.~n", ok = io:format(Instructions), UserName = get_input(), - case valid_lower0_9(UserName) of + case zx_lib:valid_lower0_9(UserName) of true -> create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName); false -> @@ -2206,7 +2232,7 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName) -> ok = io:format(Instructions), Email = get_input(), [User, Host] = string:lexemes(Email, "@"), - case {valid_lower0_9(User), valid_label(Host)} of + case {zx_lib:valid_lower0_9(User), zx_lib:valid_label(Host)} of {true, true} -> create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email); {false, true} -> @@ -2301,8 +2327,8 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email, RealNa {internal_port, InPort}], RealmFN = Realm ++ ".realm", - RealmConf = filename:join(zomp_dir(), RealmFN), - ok = write_terms(RealmConf, RealmSettings), + RealmConf = filename:join(zx_lib:zomp_home(), RealmFN), + ok = zx_lib:write_terms(RealmConf, RealmSettings), {ok, CWD} = file:get_cwd(), {ok, TempDir} = mktemp_dir("zomp"), ok = file:set_cwd(TempDir), @@ -2316,7 +2342,7 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email, RealNa end, TarOpts = [compressed, {cwd, TempDir}], - ok = write_terms(RealmFN, RealmSettings), + ok = zx_lib:write_terms(RealmFN, RealmSettings), ok = KeyCopy(PackagePub), ok = KeyCopy(RealmPub), PublicZRF = filename:join(CWD, Realm ++ ".zrf"), @@ -2324,11 +2350,11 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email, RealNa ok = erl_tar:create(PublicZRF, [RealmFN, "key"], TarOpts), ok = KeyCopy(SysopPub), - ok = write_terms("zomp.conf", ZompSettings), + ok = zx_lib:write_terms("zomp.conf", ZompSettings), PrimeZRF = filename:join(CWD, Realm ++ ".zpf"), ok = erl_tar:create(PrimeZRF, [RealmFN, "zomp.conf", "key"], TarOpts), - ok = file:set_cwd(zomp_dir()), + ok = file:set_cwd(zx_lib:zomp_home()), KeyBundle = filename:join(CWD, Realm ++ ".zkf"), ok = erl_tar:create(KeyBundle, [KeyDir], [compressed]), @@ -2397,7 +2423,7 @@ create_realmfile(Realm) -> create_realmfile(Realm, Revision, RealmKeyIDs, PackageKeyIDs) -> {ok, CWD} = file:get_cwd(), - ok = file:set_cwd(zomp_dir()), + ok = file:set_cwd(zx_lib:zomp_home()), KeyPath = fun({R, K}) -> filename:join(["key", R, K ++ ".pub.der"]) end, RealmKeyPaths = lists:map(KeyPath, RealmKeyIDs), PackageKeyPaths = lists:map(KeyPath, PackageKeyIDs), @@ -2422,13 +2448,19 @@ create_sysop() -> -spec install(package_id()) -> ok. %% @private %% Install a package from the cache into the local system. +%% Before calling this function it must be known that: +%% - The zrp file is in the cache +%% - The zrp file is valid +%% - This function will only be called on startup by the launch process +%% - The package is not already installed +%% - If this function crashes it will completely halt the system install(PackageID) -> PackageString = package_string(PackageID), ok = log(info, "Installing ~ts", [PackageString]), - ZrpFile = filename:join("zrp", namify_zrp(PackageID)), - Files = extract_zrp(ZrpFile), - TgzFile = namify_tgz(PackageID), + ZrpFile = filename:join("zrp", zx_lib:namify_zrp(PackageID)), + Files = extract_zrp_or_die(ZrpFile), + TgzFile = zx_lib:namify_tgz(PackageID), {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files), {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), Meta = binary_to_term(MetaBin), @@ -2442,29 +2474,6 @@ install(PackageID) -> log(info, "~ts installed", [PackageString]). --spec extract_zrp(FileName) -> Files | no_return() - when FileName :: file:filename(), - Files :: [{file:filename(), binary()}]. -%% @private -%% Extract a zrp archive, if possible. If not possible, halt execution with as accurate -%% an error message as can be managed. - -extract_zrp(FileName) -> - case erl_tar:extract(FileName, [memory]) of - {ok, Files} -> - Files; - {error, {FileName, enoent}} -> - Message = "Can't find file ~ts.", - error_exit(Message, [FileName], ?FILE, ?LINE); - {error, invalid_tar_checksum} -> - Message = "~ts is not a valid zrp archive.", - error_exit(Message, [FileName], ?FILE, ?LINE); - {error, Reason} -> - Message = "Extracting package file failed with: ~160tp.", - error_exit(Message, [Reason], ?FILE, ?LINE) - end. - - -spec verify(Data, Signature, PubKey) -> ok | no_return() when Data :: binary(), Signature :: binary(), @@ -2472,11 +2481,12 @@ extract_zrp(FileName) -> %% @private %% Verify the RSA Signature of some Data against the given PubKey or halt execution. %% This function always assumes sha512 is the algorithm being used. +%% Should only ever be called by the initial launch process. verify(Data, Signature, PubKey) -> case public_key:verify(Data, sha512, Signature, PubKey) of true -> ok; - false -> error_exit("Bad package signature!", ?FILE, ?LINE) + false -> error_exit("Bad package signature!", ?LINE) end. @@ -2527,7 +2537,7 @@ request_zrp(Socket, PackageID) -> receive_zrp(Socket, PackageID) -> receive {tcp, Socket, Bin} -> - ZrpPath = filename:join("zrp", namify_zrp(PackageID)), + ZrpPath = filename:join("zrp", zx_lib:namify_zrp(PackageID)), ok = file:write_file(ZrpPath, Bin), ok = send(Socket, ok), log(info, "Wrote ~ts", [ZrpPath]); @@ -2559,63 +2569,6 @@ mktemp_dir(Prefix) -> %%% Utility functions --spec read_meta() -> package_meta() | no_return(). -%% @private -%% @equiv read_meta(".") - -read_meta() -> - read_meta("."). - - --spec read_meta(Dir) -> package_meta() | no_return() - when Dir :: file:filename(). -%% @private -%% Read the `zomp.meta' file from the indicated directory, if possible. If not possible -%% then halt execution with an appropriate error message. - -read_meta(Dir) -> - Path = filename:join(Dir, "zomp.meta"), - case file:consult(Path) of - {ok, Meta} -> - maps:from_list(Meta); - Error -> - ok = log(error, "Failed to open \"zomp.meta\" with ~tp", [Error]), - ok = log(error, "Wrong directory?"), - halt(1) - end. - - --spec write_meta(package_meta()) -> ok. -%% @private -%% @equiv write_meta(".") - -write_meta(Meta) -> - write_meta(".", Meta). - - --spec write_meta(Dir, Meta) -> ok - when Dir :: file:filename(), - Meta :: package_meta(). -%% @private -%% Write the contents of the provided meta structure (a map these days) as a list of -%% Erlang K/V terms. - -write_meta(Dir, Meta) -> - Path = filename:join(Dir, "zomp.meta"), - ok = write_terms(Path, maps:to_list(Meta)). - - --spec write_terms(Filename, Terms) -> ok - when Filename :: file:filename(), - Terms :: [term()]. -%% @private -%% Provides functionality roughly inverse to file:consult/1. - -write_terms(Filename, List) -> - Format = fun(Term) -> io_lib:format("~tp.~n", [Term]) end, - Text = lists:map(Format, List), - file:write_file(Filename, Text). - -spec build(package_id()) -> ok. %% @private @@ -2623,7 +2576,7 @@ write_terms(Filename, List) -> build(PackageID) -> {ok, CWD} = file:get_cwd(), - ok = file:set_cwd(package_home(PackageID)), + ok = file:set_cwd(zx_lib:package_dir(PackageID)), ok = build(), file:set_cwd(CWD). @@ -2649,30 +2602,6 @@ build() -> ok. --spec scrub(Deps) -> Scrubbed - when Deps :: [package_id()], - Scrubbed :: [package_id()]. -%% @private -%% Take a list of dependencies and return a list of dependencies that are not yet -%% installed on the system. - -scrub([]) -> - []; -scrub(Deps) -> - lists:filter(fun(PackageID) -> not installed(PackageID) end, Deps). - - --spec installed(package_id()) -> boolean(). -%% @private -%% True to its name, returns `true' if the package is installed (its directory found), -%% `false' otherwise. - -installed(PackageID) -> - PackageString = package_string(PackageID), - PackageDir = filename:join("lib", PackageString), - filelib:is_dir(PackageDir). - - -spec rm_rf(file:filename()) -> ok | {error, file:posix()}. %% @private %% Recursively remove files and directories, equivalent to `rm -rf' on unix. @@ -2689,215 +2618,9 @@ rm_rf(Path) -> end. --spec rm(file:filename()) -> ok | {error, file:posix()}. -%% @private -%% An omnibus delete helper. - -rm(Path) -> - case filelib:is_dir(Path) of - true -> file:del_dir(Path); - false -> file:delete(Path) - end. - - - -%%% Input argument mangling - - --spec valid_lower0_9(string()) -> boolean(). -%% @private -%% Check whether a provided string is a valid lower0_9. - -valid_lower0_9([Char | Rest]) - when $a =< Char, Char =< $z -> - valid_lower0_9(Rest, Char); -valid_lower0_9(_) -> - false. - - --spec valid_lower0_9(String, Last) -> boolean() - when String :: string(), - Last :: char(). - -valid_lower0_9([$_ | _], $_) -> - false; -valid_lower0_9([Char | Rest], _) - when $a =< Char, Char =< $z; - $0 =< Char, Char =< $9; - Char == $_ -> - valid_lower0_9(Rest, Char); -valid_lower0_9([], _) -> - true; -valid_lower0_9(_, _) -> - false. - - --spec valid_label(string()) -> boolean(). -%% @private -%% Check whether a provided string is a valid label. - -valid_label([Char | Rest]) - when $a =< Char, Char =< $z -> - valid_label(Rest, Char); -valid_label(_) -> - false. - - --spec valid_label(String, Last) -> boolean() - when String :: string(), - Last :: char(). - -valid_label([$. | _], $.) -> - false; -valid_label([$_ | _], $_) -> - false; -valid_label([$- | _], $-) -> - false; -valid_label([Char | Rest], _) - when $a =< Char, Char =< $z; - $0 =< Char, Char =< $9; - Char == $_; Char == $-; - Char == $. -> - valid_label(Rest, Char); -valid_label([], _) -> - true; -valid_label(_, _) -> - false. - - --spec string_to_version(string()) -> version(). -%% @private -%% @equiv string_to_version(string(), "", {z, z, z}) - -string_to_version(String) -> - string_to_version(String, "", {z, z, z}). - - --spec string_to_version(String, Acc, Version) -> Result - when String :: string(), - Acc :: list(), - Version :: version(), - Result :: version(). -%% @private -%% Accepts a full or partial version string of the form `X.Y.Z', `X.Y' or `X' and -%% returns a zomp-type version tuple or crashes on bad data. - -string_to_version([Char | Rest], Acc, Version) when $0 =< Char andalso Char =< $9 -> - string_to_version(Rest, [Char | Acc], Version); -string_to_version([$. | Rest], Acc, {z, z, z}) -> - X = list_to_integer(lists:reverse(Acc)), - string_to_version(Rest, "", {X, z, z}); -string_to_version([$. | Rest], Acc, {X, z, z}) -> - Y = list_to_integer(lists:reverse(Acc)), - string_to_version(Rest, "", {X, Y, z}); -string_to_version("", "", Version) -> - Version; -string_to_version([], Acc, {z, z, z}) -> - X = list_to_integer(lists:reverse(Acc)), - {X, z, z}; -string_to_version([], Acc, {X, z, z}) -> - Y = list_to_integer(lists:reverse(Acc)), - {X, Y, z}; -string_to_version([], Acc, {X, Y, z}) -> - Z = list_to_integer(lists:reverse(Acc)), - {X, Y, Z}. - - --spec version_to_string(version()) -> string(). -%% @private -%% Inverse of string_to_version/3. - -version_to_string({z, z, z}) -> - ""; -version_to_string({X, z, z}) -> - integer_to_list(X); -version_to_string({X, Y, z}) -> - lists:flatten(lists:join($., [integer_to_list(Element) || Element <- [X, Y]])); -version_to_string({X, Y, Z}) -> - lists:flatten(lists:join($., [integer_to_list(Element) || Element <- [X, Y, Z]])). - - --spec package_id(string()) -> package_id(). -%% @private -%% Converts a proper package_string to a package_id(). -%% This function takes into account missing version elements. -%% Examples: -%% `{"foo", "bar", {1, 2, 3}} = package_id("foo-bar-1.2.3")' -%% `{"foo", "bar", {1, 2, z}} = package_id("foo-bar-1.2")' -%% `{"foo", "bar", {1, z, z}} = package_id("foo-bar-1")' -%% `{"foo", "bar", {z, z, z}} = package_id("foo-bar")' - -package_id(String) -> - case string:lexemes(String, [$-]) of - [Realm, Name, VersionString] -> - true = valid_lower0_9(Realm), - true = valid_lower0_9(Name), - Version = string_to_version(VersionString), - {Realm, Name, Version}; - [A, B] -> - true = valid_lower0_9(A), - case valid_lower0_9(B) of - true -> {A, B, {z, z, z}}; - false -> {"otpr", A, string_to_version(B)} - end; - [Name] -> - true = valid_lower0_9(Name), - {"otpr", Name, {z, z, z}} - end. - - --spec package_string(package_id()) -> string(). -%% @private -%% Map an PackageID to a correct string representation. -%% This function takes into account missing version elements. -%% Examples: -%% `"foo-bar-1.2.3" = package_string({"foo", "bar", {1, 2, 3}})' -%% `"foo-bar-1.2" = package_string({"foo", "bar", {1, 2, z}})' -%% `"foo-bar-1" = package_string({"foo", "bar", {1, z, z}})' -%% `"foo-bar" = package_string({"foo", "bar", {z, z, z}})' - -package_string({Realm, Name, {z, z, z}}) -> - lists:flatten(lists:join($-, [Realm, Name])); -package_string({Realm, Name, Version}) -> - VersionString = version_to_string(Version), - lists:flatten(lists:join($-, [Realm, Name, VersionString])). - - --spec namify_zrp(PackageID) -> ZrpFileName - when PackageID :: package_id(), - ZrpFileName :: file:filename(). -%% @private -%% Map an PackageID to its correct .zrp package file name. - -namify_zrp(PackageID) -> namify(PackageID, "zrp"). - - --spec namify_tgz(PackageID) -> TgzFileName - when PackageID :: package_id(), - TgzFileName :: file:filename(). -%% @private -%% Map an PackageID to its correct gzipped tarball source bundle filename. - -namify_tgz(PackageID) -> namify(PackageID, "tgz"). - - --spec namify(PackageID, Suffix) -> FileName - when PackageID :: package_id(), - Suffix :: string(), - FileName :: file:filename(). -%% @private -%% Converts an PackageID to a canonical string, then appends the provided -%% filename Suffix. - -namify(PackageID, Suffix) -> - PackageString = package_string(PackageID), - PackageString ++ "." ++ Suffix. - - %%% User menu interface (terminal) - -spec get_input() -> string(). %% @private %% Provide a standard input prompt and newline sanitized return value. @@ -2988,7 +2711,7 @@ hurr() -> io:format("That isn't an option.~n"). %% Every entry function should run this initially. ensure_zomp_home() -> - ZompDir = zomp_dir(), + ZompDir = zx_lib:zomp_home(), case filelib:is_dir(ZompDir) of true -> ok; false -> setup(ZompDir) @@ -3014,65 +2737,21 @@ setup_otpr() -> log(info, "Here should pull otpr.0.zrf and install it..."). --spec zomp_dir() -> file:filename(). -%% @private -%% Check the host OS and return the absolute path to the zomp filesystem root. - -zomp_dir() -> - case os:type() of - {unix, _} -> - Home = os:getenv("HOME"), - Dir = "zomp", - filename:join(Home, Dir); - {win32, _} -> - Drive = os:getenv("HOMEDRIVE"), - Path = os:getenv("HOMEPATH"), - Dir = "zomp", - filename:join([Drive, Path, Dir]) - end. - - -spec ensure_package_dirs(package_id()) -> ok. %% @private %% Procedure to guarantee that directory locations necessary for the indicated app to %% run have been created or halt execution. -ensure_package_dirs(PackageID) -> - PackageHome = package_home(PackageID), - PackageData = package_dir("var", PackageID), - PackageConf = package_dir("etc", PackageID), +ensure_package_dirs(PackageID = {Realm, Name, _}) -> + Package = {Realm, Name}, + PackageHome = zx_lib:package_dir(PackageID), + PackageData = zx_lib:package_dir("var", Package), + PackageConf = zx_lib:package_dir("etc", Package), Dirs = [PackageHome, PackageData, PackageConf], ok = lists:foreach(fun force_dir/1, Dirs), log(info, "Created dirs:~n\t~ts~n\t~ts~n\t~ts", Dirs). --spec package_home(PackageID) -> PackageHome - when PackageID :: package_id(), - PackageHome :: file:filename(). -%% @private -%% Accept an PackageID and return the installation directory for the indicated -%% application. -%% NOTE: -%% This system does NOT anticipate symlinks of incomplete versions to their latest -%% installed version (for example, an incomplete `{1, 2, z}' resolving to a symlink -%% `lib/foo-bar-1.2' which is always updated to point to the latest version 1.2.x). - -package_home(PackageID) -> - filename:join([zomp_dir(), "lib", package_string(PackageID)]). - - --spec package_dir(Prefix, PackageID) -> PackageDataDir - when Prefix :: string(), - PackageID :: package_id(), - PackageDataDir :: file:filename(). -%% @private -%% Create an absolute path to an application directory prefixed by the inclued argument. - -package_dir(Prefix, {Realm, Name, _}) -> - PackageName = Realm ++ "-" ++ Name, - filename:join([zomp_dir(), Prefix, PackageName]). - - -spec force_dir(Path) -> Result when Path :: file:filename(), Result :: ok @@ -3105,7 +2784,7 @@ realm_conf(Realm) -> %% Load the config for the given realm or halt with an error. load_realm_conf(Realm) -> - Path = filename:join(zomp_dir(), realm_conf(Realm)), + Path = filename:join(zx_lib:zomp_home(), realm_conf(Realm)), case file:consult(Path) of {ok, C} -> C; @@ -3115,6 +2794,29 @@ load_realm_conf(Realm) -> end. +-spec extract_zrp_or_die(FileName) -> Files | no_return() + when FileName :: file:filename(), + Files :: [{file:filename(), binary()}]. +%% @private +%% Extract a zrp archive, if possible. If not possible, halt execution with as accurate +%% an error message as can be managed. + +extract_zrp_or_die(FileName) -> + case erl_tar:extract(FileName, [memory]) of + {ok, Files} -> + Files; + {error, {FileName, enoent}} -> + Message = "Can't find file ~ts.", + error_exit(Message, [FileName], ?LINE); + {error, invalid_tar_checksum} -> + Message = "~ts is not a valid zrp archive.", + error_exit(Message, [FileName], ?LINE); + {error, Reason} -> + Message = "Extracting package file failed with: ~160tp.", + error_exit(Message, [Reason], ?LINE) + end. + + %%% Usage @@ -3191,28 +2893,24 @@ usage() -> %%% Error exits --spec error_exit(Error, Path, Line) -> no_return() +-spec error_exit(Error, Line) -> no_return() when Error :: term(), - Path :: file:filename(), Line :: non_neg_integer(). %% @private %% Format an error message in a way that makes it easy to locate. -error_exit(Error, Path, Line) -> - File = filename:basename(Path), - ok = log(error, "~ts:~tp: ~tp", [File, Line, Error]), - halt(1). +error_exit(Error, Line) -> + error_exit(Error, [], Line). --spec error_exit(Format, Args, Path, Line) -> no_return() +-spec error_exit(Format, Args, Line) -> no_return() when Format :: string(), Args :: [term()], - Path :: file:filename(), Line :: non_neg_integer(). %% @private %% Format an error message in a way that makes it easy to locate. -error_exit(Format, Args, Path, Line) -> - File = filename:basename(Path), +error_exit(Format, Args, Line) -> + File = filename:basename(?FILE), ok = log(error, "~ts:~tp: " ++ Format, [File, Line | Args]), halt(1). diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl new file mode 100644 index 0000000..f585bc7 --- /dev/null +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl @@ -0,0 +1,71 @@ +%%% @doc +%%% ZX Connector +%%% +%%% This module represents a connection to a Zomp server. +%%% Multiple connections can exist at a given time, but each one of these processes +%%% only represents a single connection at a time. +%%% @end + +-module(zx_conn). +-author("Craig Everett "). +-copyright("Craig Everett "). +-license("GPL-3.0"). + +-export([start/1, stop/0]). +-export([start_link/1]). + +-include("zx_logger.erl"). + + + +%%% Startup + +-spec start(Target) -> Result + when Target :: zx:host(), + Result :: {ok, pid()} + | {error, Reason}, + Reason :: term(). + +start(Target) -> + zx_conn_sup:start_conn(Target). + + +-spec start_link(Target) -> + when Target :: zx:host(), + Result :: {ok, pid()} + | {error, Reason}, + Reason :: term(). +%% @private +%% Starts a connector with a target host in its state. + +start_link(Target) -> + proc_lib:start_link(?MODULE, init, [self(), Target]). + + +-spec init(Parent, Target) -> no_return() + when Parent :: pid(), + Target :: zx:host(). + +init(Parent, Target) -> + ok = log(info, "Connecting to ~tp", [Target]), + Debug = sys:debug_options([]), + ok = proc_lib:init_ack(Parent, {ok, self()}), + connect(Parent, Debug, Target). + + +-spec connect(Parent, Debug, Target) -> no_return(). + +connect(Parent, Debug, {Host, Port}) -> + Options = [{packet, 4}, {mode, binary}, {active, true}], + case gen_tcp:connect(Host, Port, Options, 5000) of + {ok, Socket} -> + confirm(Parent, Debug, Socket); + {error, Error} -> + ok = log(warning, "Connection problem with ~tp: ~tp", [Node, Error]), + ok = zx_daemon:report( + connect_user(Realm, Rest) + end. + + +confirm(Parent, Debug, Socket) -> + diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_conn_sup.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_conn_sup.erl new file mode 100644 index 0000000..7efd8cd --- /dev/null +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_conn_sup.erl @@ -0,0 +1,72 @@ +%%% @doc +%%% The ZX Connection Supervisor +%%% +%%% This supervisor maintains the lifecycle of all zomp_client worker processes. +%%% @end + +-module(zx_conn_sup). +-behavior(supervisor). +-author("Craig Everett "). +-copyright("Craig Everett "). +-license("GPL-3.0"). + +-export([start_conn/1]). +-export([start_link/0]). +-export([init/1]). + + + +%%% Interface Functions + +-spec start_conn(Host) -> Result + when Host :: zx:host(), + Result :: {ok, pid()} + | {error, Reason}, + Reason :: term(). +%% @doc +%% Start an upstream connection handler. +%% (Should only be called from zx_conn). + +start_conn(Host) -> + supervisor:start_child(?MODULE, [Host]). + + + +%%% Startup + +-spec start_link() -> Result + when Result :: {ok, pid()} + | {error, Reason}, + Reason :: {already_started, pid()} + | {shutdown, term()} + | term(). +%% @private +%% Called by zx_daemon_sup. +%% +%% Spawns a single, registered supervisor process. +%% +%% Error conditions, supervision strategies, and other important issues are +%% explained in the supervisor module docs: +%% http://erlang.org/doc/man/supervisor.html + +start_link() -> + supervisor:start_link({local, ?MODULE}, ?MODULE, none). + + +-spec init(none) -> {ok, {supervisor:sup_flags(), [supervisor:child_spec()]}}. +%% @private +%% Do not call this function directly -- it is exported only because it is a +%% necessary part of the OTP supervisor behavior. + +init(none) -> + RestartStrategy = {simple_one_for_one, 1, 60}, + + Client = {zx_conn, + {zx_conn, start_link, []}, + temporary, + brutal_kill, + worker, + [zx_conn]}, + + Children = [Client], + {ok, {RestartStrategy, Children}}. diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl index e8073a0..d7efa4c 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl @@ -2,71 +2,456 @@ %%% ZX Daemon %%% %%% Resident execution daemon and runtime interface to Zomp. +%%% +%%% The daemon lives in the system and does background tasks and also acts as the +%%% serial interface for any complex functions involving network tasks that may fail +%%% and need to be retried or may span realms. +%%% +%%% In particular, the functions accessible to programs launched by ZX can interact +%%% with Zomp realms via the zx_daemon, and non-administrative tasks that involve +%%% maintaining a connection with a Zomp constellation can be abstracted behind the +%%% zx_daemon. Administrative tasks, however, essentially stateless request/response +%%% pairs. %%% @end -module(zx_daemon). --export([]). +-behavior(gen_server). +-author("Craig Everett "). +-copyright("Craig Everett "). +-license("GPL-3.0"). -%%% App execution loop +-export([pass_meta/3, + subscribe/1, unsubscribe/0, + list_packages/1, list_versions/1, query_latest/1, + fetch/1]). +-export([report/1]). +-export([start_link/0]). +-export([init/1, handle_call/3, handle_cast/2, handle_info/2, + code_change/3, terminate/2]). --spec exec_wait(State) -> no_return() - when State :: state(). +-include("zx_logger.hrl"). + + + +%%% Type Definitions + +-record(s, + {meta = none :: none | zx:package_meta(), + dir = none :: none | file:filename(), + argv = none :: none | [string()], + reqp = none :: none | pid(), + reqm = none :: none | reference(), + connp = none :: none | pid(), + connm = none :: none | reference(), + prime = none :: none | zx:realm(), + hosts = [] :: #s{zx:realm() := [zx:host()]}}). + +-type state() :: #s{}. + +-type hosts() :: #{zx:realm() := [zx:host()]}. +-type conn_report() :: {connected, Realms :: [zx:realm()]} + | conn_fail + | disconnected. + + +%%% Service Interface + +-spec pass_meta(Meta, Dir, ArgV) -> ok + when Meta :: zx:package_meta(), + Dir :: file:filename(), + ArgV :: [string()]. %% @private -%% Execution maintenance loop. -%% Once an application is started by zompc this process will wait for a message from -%% the application if that application was written in a way to take advantage of zompc -%% facilities such as post-start upgrade checking. +%% Load the daemon with the primary running application's meta data and location within +%% the filesystem. This step allows running development code from any location in +%% the filesystem against installed dependencies without requiring any magical +%% references. %% -%% NOTE: -%% Adding clauses to this `receive' is where new functionality belongs. -%% It may make sense to add a `zompc_lib' as an available dependency authors could -%% use to interact with zompc without burying themselves under the complexity that -%% can come with naked send operations. (Would it make sense, for example, to have -%% the registered zompc process convert itself to a gen_server via zompc_lib to -%% provide more advanced functionality?) +%% This call blocks specifically so that we can be certain that the target application +%% cannot be started before the impact of this call has taken full effect. It cannot +%% be known whether the very first thing the target application will do is send this +%% process an async message. That implies that this should only ever be called once, +%% by the launching process (which normally terminates shortly thereafter). -exec_wait(State = #s{pid = none, mon = none}) -> +pass_meta(Meta, Dir, ArgV) -> + gen_server:call(?MODULE, {pass_meta, Meta, Dir, ArgV}). + + +-spec subscribe(Package) -> Result + when Package :: zx:package(), + Result :: ok + | {error, Reason}, + Reason :: illegal_requestor + | {already_subscribed, zx:package()}. +%% @doc +%% Subscribe to update notification for a for a particular package. +%% The daemon is designed to monitor a single package at a time, so a second call to +%% subscribe/1 will return an `already_subscribed' error, or possibly an +%% `illegal_requestor' error in the case that a second call is made from a different +%% process than the original requestor. +%% Other functions can be used to query the status of a package at an arbitrary time. + +subscribe(Package) -> + gen_server:call(?MODULE, {subscribe, self(), Package}). + + +-spec unsubscribe() -> ok. +%% @doc +%% Instructs the daemon to unsubscribe if subscribed. Has no effect if not subscribed. + +unsubscribe() -> + gen_server:call(?MODULE, unsubscribe). + + +-spec list_packages(Realm) -> Result + when Realm :: zx:realm(), + Result :: {ok, Packages :: [zx:package()]} + | {error, Reason}, + Reason :: bad_realm + | no_realm + | network. + +list_packages(Realm) -> + gen_server:call(?MODULE, {list, Realm}). + + +-spec list_versions(Package) -> Result + when Package :: zx:package(), + Result :: {ok, Versions :: [zx:version()]} + | {error, Reason}, + Reason :: bad_realm + | bad_package + | network. +%% @doc +%% List all versions of a given package. Useful especially for developers wanting to +%% see a full list of maintained packages to include as dependencies. + +list_versions(Package) -> + gen_server:call(?MODULE, {list_versions, Package}). + + +-spec query_latest(Object) -> Result + when Object :: zx:package() | zx:package_id(), + Result :: {ok, version()} + | {error, Reason}, + Reason :: bad_realm + | bad_package + | bad_version + | network. +%% @doc +%% Check for the latest version of a package, with or without a version provided to +%% indicate subversion limit. Useful mostly for developers checking for a latest +%% version of a package. +%% +%% While this function could be used as a primitive operation in a dynamic dependency +%% upgrade scheme, that is not its intent. You will eventually divide by zero trying +%% to implement such a feature, open a portal to Oblivion, and monsters will consume +%% all you love. See? That's a horrible idea. You have been warned. + +query_latest(Object) -> + gen_server:call(?MODULE, {query_latest, Object}). + + +-spec fetch(PackageIDs) -> Result + when PackageIDs :: [zx:package_id()], + Result :: {{ok, [zx:package_id()]}, + {error, [{zx:package_id(), Reason}]}}, + Reason :: bad_realm + | bad_package + | bad_version + | network. +%% @doc +%% Ensure a list of packages is available locally, fetching any missing packages in +%% the process. This is intended to abstract the task of ensuring that a list of +%% dependencies is available locally prior to building/running a dependent app or lib. + +fetch([]) -> + {{ok, []}, {error, []}}; +fetch(PackageIDs) -> + gen_server:call(?MODULE, {fetch, PackageIDs}). + + + +%%% Connection interface + +-spec report(Message) -> ok + when Message :: {connected, Realms :: [zx:realm()]} + | conn_fail + | disconnected. +%% @private +%% Should only be called by a zx_conn. This function is how a zx_conn reports its +%% current connection status. + +report(Message) -> + gen_server:cast(?MODULE, {report, self(), Message}). + + +%%% Startup + +-spec start_link() -> {ok, pid()} | {error, term()}. +%% @private +%% Startup function -- intended to be called by supervisor. + +start_link() -> + gen_server:start_link({local, ?MODULE}, ?MODULE, none, []). + + +-spec init(none) -> {ok, state()}. + +init(none) -> + {ok, #s{}}. + + + +%%% gen_server + +%% @private +%% gen_server callback for OTP calls + +handle_call({pass_meta, Meta, Dir, ArgV}, _, State) -> + {Result, NewState} = do_pass_meta(Requestor, Package, ArgV, State), + {reply, Result, NewState}; +handle_call({subscribe, Requestor, Package}, _, State) -> + {Result, NewState} = do_subscribe(Requestor, Package, State), + {reply, Result, NewState}; +handle_call({query_latest, Object}, _, State) -> + {Result, NewState} = do_query_latest(Object, State), + {reply, Result, NewState}; +handle_call({fetch, Packages}, _, State) -> + {Result, NewState} = do_fetch(Packages, State), + {reply, Result, NewState}; +handle_call(Unexpected, From, State) -> + ok = log(warning, "Unexpected call ~tp: ~tp", [From, Unexpected]), + {noreply, State}. + + +%% @private +%% gen_server callback for OTP casts + +handle_cast(unsubscribe, State) -> + NewState = do_unsubscribe(State), + {noreply, NewState}; +handle_cast({report, From, Message}, State) -> + NewState = do_report(From, Message, State), + {noreply, NewState}; +handle_cast(Unexpected, State) -> + ok = log(warning, "Unexpected cast: ~tp", [Unexpected]), + {noreply, State}. + + +%% @private +%% gen_sever callback for general Erlang message handling + +handle_info(Unexpected, State) -> + ok = log(warning, "Unexpected info: ~tp", [Unexpected]), + {noreply, State}. + + +%% @private +%% gen_server callback to handle state transformations necessary for hot +%% code updates. This template performs no transformation. + +code_change(_, State, _) -> + {ok, State}. + + +%% @private +%% gen_server callback to handle shutdown/cleanup tasks on receipt of a clean +%% termination request. + +terminate(_, _) -> + ok. + + + +%%% Doer Functions + +-spec do_pass_meta(Meta, Dir, ArgV, State) -> {Result, NewState} + when Meta :: zx:package_meta(), + Dir :: file:filename(), + ArgV :: [string()], + State :: state(), + Result :: ok, + Newstate :: state(). + +do_pass_meta(Meta, Dir, ArgV, State) -> + NewState = State#s{meta = Meta, dir = Dir, argv = ArgV}, + {ok, NewState}. + + +-spec do_subscribe(Requestor, Package, State) -> {Result, NewState} + when Requestor :: pid(), + Package :: zx:package(), + State :: state(), + Result :: ok + | {error, Reason}, + Reason :: illegal_requestor + | {already_subscribed, zx:package()}, + NewState :: state(). + +do_subscribe(Requestor, + {Realm, Name}, + State = #s{name = none, connp = none, reqp = none, hosts = Hosts}) -> + Monitor = monitor(process, Requestor), + {Host, NewHosts} = select_host(Realm, Hosts), + {ok, ConnP} = zx_conn:start(Host), + ConnM = monitor(process, ConnP), + NewState = State#s{realm = Realm, name = Name, + connp = ConnP, connm = ConnM, + reqp = Requestor, reqm = Monitor, + hosts = NewHosts}, + {ok, NewState}; +do_subscribe(_, _, State = #s{realm = Realm, name = Name}) -> + {{error, {already_subscribed, {Realm, Name}}}, State}. + + +-spec select_host(Realm, Hosts) -> {Host, NewHosts} + when Realm :: zx:realm(), + Hosts :: none | hosts(), + Host :: zx:host(), + NewHosts :: hosts(). + +select_host(Realm, none) -> + List = + case file:consult(zx_lib:hosts_cache_file(Realm)) of + {ok, Cached} -> Cached; + {error, enoent} -> [zx_lib:get_prime(Realm)] + end, + NewState = State#s{hosts = #{Realm => List}}, + select_host(Realm, NewState); +select_host(Realm, Hosts) -> + {Target, Rest} = + case maps:find(Realm, Hosts) of + {ok, [H | Hs]} -> {H, Hs}; + {ok, []} -> {zx_lib:get_prime(Realm), []}; + error -> {zx_lib:get_prime(Realm), []} + end, + NewHosts = maps:put(Realm, Hosts, Rest), + {Target, NewHosts}. + + +-spec do_query_latest(Object, State) -> {Result, NewState} + when Object :: zx:package() | zx:package_id(), + State :: state(), + Result :: {ok, zx:version()} + | {error, Reason}, + Reason :: bad_realm + | bad_package + | bad_version, + NewState :: state(). +%% @private +%% Queries a zomp realm for the latest version of a package or package +%% version (complete or incomplete version number). + +query_latest(Socket, {Realm, Name}) -> + ok = send(Socket, {latest, Realm, Name}), receive - {monitor, Pid} -> - Mon = monitor(process, Pid), - exec_wait(State#s{pid = Pid, mon = Mon}); - Unexpected -> - ok = log(warning, "Unexpected message: ~tp", [Unexpected]), - exec_wait(State) + {tcp, Socket, Bin} -> binary_to_term(Bin) + after 5000 -> {error, timeout} end; -exec_wait(State = #s{pid = Pid, mon = Mon}) -> +query_latest(Socket, {Realm, Name, Version}) -> + ok = send(Socket, {latest, Realm, Name, Version}), receive - {check_update, Requester, Ref} -> - {Response, NewState} = check_update(State), - Requester ! {Ref, Response}, - exec_wait(NewState); - {exit, Reason} -> - ok = log(info, "Exiting with: ~tp", [Reason]), - halt(0); - {'DOWN', Mon, process, Pid, normal} -> - ok = log(info, "Application exited normally."), - halt(0); - {'DOWN', Mon, process, Pid, Reason} -> - ok = log(warning, "Application exited with: ~tp", [Reason]), - halt(1); - Unexpected -> - ok = log(warning, "Unexpected message: ~tp", [Unexpected]), - exec_wait(State) + {tcp, Socket, Bin} -> binary_to_term(Bin) + after 5000 -> {error, timeout} end. --spec check_update(State) -> {Response, NewState} +-spec do_unsubscribe(State) -> {ok, NewState} when State :: state(), - Response :: term(), NewState :: state(). -%% @private -%% Check for updated version availability of the current application. -%% The return value should probably provide up to three results, a Major, Minor and -%% Patch update, and allow the Requestor to determine what to do with it via some -%% interaction. -check_update(State) -> - ok = log(info, "Would be checking for an update of the current application now..."), - Response = "Nothing was checked, but you can imagine it to have been.", - {Response, State}. +do_unsubscribe(State = #s{connp = none}) -> + {ok, State}; +do_unsubscribe(State = #s{connp = ConnP, connm = ConnM}) -> + true = demonitor(ConnM), + ok = zx_conn:stop(ConnP), + NewState = State#s{realm = none, name = none, version = none, + connp = ConnP, connm = ConnM}, + {ok, NewState}. + + +-spec do_report(From, Message, State) -> NewState + when From :: pid(), + Message :: conn_report(), + State :: state(), + NewState :: state(). + +do_report(From, {connected, Realms}, State = #s{ + + + +-spec do_fetch(PackageIDs) -> Result + when PackageIDs :: [zx:package_id()], + Result :: ok + | {error, Reason}, + Reason :: bad_realm + | bad_package + | bad_version + | network. +%% @private +%% + +do_fetch(PackageIDs, State) -> +% FIXME: Need to create a job queue divided by realm and dispatched to connectors, +% and cleared from the master pending queue kept here by the daemon as the +% workers succeed. Basic task queue management stuff... which never existed +% in ZX before... grrr... + case scrub(PackageIDs) of + [] -> + ok; + Needed -> + Partitioned = partition_by_realm(Needed), + EnsureDeps = + fun({Realm, Packages}) -> + ok = zx_conn:queue_package(Pid, Realm, Packages), + log(info, "Disconnecting from realm: ~ts", [Realm]) + end, + lists:foreach(EnsureDeps, Partitioned) + end. + + +partition_by_realm(PackageIDs) -> + PartitionMap = lists:foldl(fun partition_by_realm/2, #{}, PackageIDs), + maps:to_list(PartitionMap). + + +partition_by_realm({R, P, V}, M) -> + maps:update_with(R, fun(Ps) -> [{P, V} | Ps] end, [{P, V}], M). + + +ensure_deps(_, _, []) -> + ok; +ensure_deps(Socket, Realm, [{Name, Version} | Rest]) -> + ok = ensure_dep(Socket, {Realm, Name, Version}), + ensure_deps(Socket, Realm, Rest). + + +-spec ensure_dep(gen_tcp:socket(), package_id()) -> ok | no_return(). +%% @private +%% Given an PackageID as an argument, check whether its package file exists in the +%% system cache, and if not download it. Should return `ok' whenever the file is +%% sourced, but exit with an error if it cannot locate or acquire the package. + +ensure_dep(Socket, PackageID) -> + ZrpFile = filename:join("zrp", namify_zrp(PackageID)), + ok = + case filelib:is_regular(ZrpFile) of + true -> ok; + false -> fetch(Socket, PackageID) + end, + ok = install(PackageID), + build(PackageID). + + +-spec scrub(Deps) -> Scrubbed + when Deps :: [package_id()], + Scrubbed :: [package_id()]. +%% @private +%% Take a list of dependencies and return a list of dependencies that are not yet +%% installed on the system. + +scrub([]) -> + []; +scrub(Deps) -> + lists:filter(fun(PackageID) -> not zx_lib:installed(PackageID) end, Deps). diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon_sup.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon_sup.erl new file mode 100644 index 0000000..52f04f0 --- /dev/null +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon_sup.erl @@ -0,0 +1,60 @@ +%%% @doc +%%% ZX Daemon Supervisor +%%% +%%% This supervisor maintains the lifecycle of the zxd worker process. +%%% @end + +-module(zx_daemon_sup). +-behavior(supervisor). +-author("Craig Everett "). +-copyright("Craig Everett "). +-license("GPL-3.0"). + +-export([start_link/0, init/1]). + + + +%%% Startup + +-spec start_link() -> Result + when Result :: {ok, pid()} + | {error, Reason}, + Reason :: {already_started, pid()} + | {shutdown, term()} + | term(). +%% @private +%% Called by zx:subscribe/1. +%% Starts this single, registered supervisor. +%% +%% Error conditions, supervision strategies, and other important issues are +%% explained in the supervisor module docs: +%% http://erlang.org/doc/man/supervisor.html + +start_link() -> + supervisor:start_link({local, ?MODULE}, ?MODULE, none). + + +-spec init(none) -> {ok, {supervisor:sup_flags(), [supervisor:child_spec()]}}. +%% @private +%% Do not call this function directly -- it is exported only because it is a +%% necessary part of the OTP supervisor behavior. + +init(none) -> + RestartStrategy = {rest_for_one, 1, 60}, + + Daemon = {zx_daemon, + {zx_daemon, start_link, []}, + permanent, + 10000, + worker, + [zx_daemon]}, + + ConnSup = {zx_conn_sup, + {zx_conn_sup, start_link, []}, + permanent, + brutal_kill, + supervisor, + [zx_conn_sup]}, + + Children = [Daemon, ConnSup], + {ok, {RestartStrategy, Children}}. diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_lib.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_lib.erl new file mode 100644 index 0000000..2f0b39a --- /dev/null +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_lib.erl @@ -0,0 +1,523 @@ +%%% @doc +%%% ZX Library +%%% +%%% This module contains a set of common-use functions internal to the ZX project. +%%% These functions are subject to radical change, are not publicly documented and +%%% should NOT be used by other projects. +%%% +%%% The public interface to the externally useful parts of this library are maintained +%%% in the otpr-zxxl package. +%%% @end + +-module(zx_lib). +-author("Craig Everett "). +-copyright("Craig Everett "). +-license("GPL-3.0"). + + +-export([zomp_home/0, find_zomp_home/0, + hosts_cache_file/1, get_prime/1, realm_meta/1, + read_project_meta/0, read_project_meta/1, read_package_meta/1, + write_project_meta/1, write_project_meta/2, + write_terms/2, + valid_lower0_9/1, valid_label/1, + string_to_version/1, version_to_string/1, + package_id/1, package_string/1, + package_dir/1, package_dir/2, + namify_zrp/1, namify_tgz/1, + find_latest_compatible/2, installed/1]). + +-include("zx_logger.hrl"). + + + +%%% Functions + +zomp_home() -> + case os:getenv("ZOMP_HOME") of + false -> + ZompHome = find_zomp_home(), + true = os:putenv("ZOMP_HOME", ZompHome), + ZompHome; + ZompHome -> + ZompHome + end. + + +-spec find_zomp_home() -> file:filename(). +%% @private +%% Check the host OS and return the absolute path to the zomp filesystem root. + +find_zomp_home() -> + case os:type() of + {unix, _} -> + Home = os:getenv("HOME"), + Dir = "zomp", + filename:join(Home, Dir); + {win32, _} -> + Drive = os:getenv("HOMEDRIVE"), + Path = os:getenv("HOMEPATH"), + Dir = "zomp", + filename:join([Drive, Path, Dir]) + end. + + +-spec hosts_cache_file(zx:realm()) -> file:filename(). +%% @private +%% Given a Realm name, construct a realm's .hosts filename and return it. + +hosts_cache_file(Realm) -> + filename:join(zomp_home(), Realm ++ ".hosts"). + + +-spec get_prime(Realm) -> Result + when Realm :: zx:realm(), + Result :: {ok, zx:host()} + | {error, file:posix()}. +%% @private +%% Check the given Realm's config file for the current prime node and return it. + +get_prime(Realm) -> + case realm_meta(Realm) of + {ok, RealmMeta} -> + {prime, Prime} = lists:keyfind(prime, 1, RealmMeta), + {ok, Prime}; + Error -> + Error + end. + + +-spec realm_meta(Realm) -> Result + when Realm :: string(), + Result :: {ok, Meta} + | {error, Reason}, + Meta :: [{atom(), term()}], + Reason :: file:posix(). +%% @private +%% Given a realm name, try to locate and read the realm's configuration file if it +%% exists, exiting with an appropriate error message if there is a problem reading +%% the file. + +realm_meta(Realm) -> + RealmFile = filename:join(zomp_home(), Realm ++ ".realm"), + file:consult(RealmFile). + + +-spec read_project_meta() -> Result + when Result :: {ok, zx:package_meta()} + | {error, file:posix()}. +%% @private +%% @equiv read_meta(".") + +read_project_meta() -> + read_project_meta("."). + + +-spec read_project_meta(Dir) -> Result + when Dir :: file:filename(), + Result :: {ok, zx:package_meta()} + | {error, file:posix()}. +%% @private +%% Read the `zomp.meta' file from the indicated directory, if possible. + +read_project_meta(Dir) -> + Path = filename:join(Dir, "zomp.meta"), + case file:consult(Path) of + {ok, Meta} -> + maps:from_list(Meta); + Error -> + ok = log(error, "Failed to open \"zomp.meta\" with ~tp", [Error]), + ok = log(error, "Wrong directory?"), + Error + end. + + +-spec read_package_meta(PackageID) -> Result + when PackageID :: zx:package_id(), + Result :: {ok, zx:package_meta()} + | {error, file:posix()}. + +read_package_meta({Realm, Name, Version}) -> + VersionString = Version, + Path = filename:join([zomp_home(), "lib", Realm, Name, VersionString]), + read_project_meta(Path). + + +-spec write_project_meta(Meta) -> Result + when Meta :: zx:package_meta(), + Result :: ok + | {error, Reason}, + Reason :: badarg + | terminated + | system_limit + | file:posix(). +%% @private +%% @equiv write_meta(".") + +write_project_meta(Meta) -> + write_project_meta(".", Meta). + + +-spec write_project_meta(Dir, Meta) -> ok + when Dir :: file:filename(), + Meta :: zx:package_meta(). +%% @private +%% Write the contents of the provided meta structure (a map these days) as a list of +%% Erlang K/V terms. + +write_project_meta(Dir, Meta) -> + Path = filename:join(Dir, "zomp.meta"), + write_terms(Path, maps:to_list(Meta)). + + +-spec write_terms(Filename, Terms) -> Result + when Filename :: file:filename(), + Terms :: [term()], + Result :: ok + | {error, Reason}, + Reason :: badarg + | terminated + | system_limit + | file:posix(). +%% @private +%% Provides functionality roughly inverse to file:consult/1. + +write_terms(Filename, List) -> + Format = fun(Term) -> io_lib:format("~tp.~n", [Term]) end, + Text = lists:map(Format, List), + file:write_file(Filename, Text). + + +-spec valid_lower0_9(string()) -> boolean(). +%% @private +%% Check whether a provided string is a valid lower0_9. + +valid_lower0_9([Char | Rest]) + when $a =< Char, Char =< $z -> + valid_lower0_9(Rest, Char); +valid_lower0_9(_) -> + false. + + +-spec valid_lower0_9(String, Last) -> boolean() + when String :: string(), + Last :: char(). + +valid_lower0_9([$_ | _], $_) -> + false; +valid_lower0_9([Char | Rest], _) + when $a =< Char, Char =< $z; + $0 =< Char, Char =< $9; + Char == $_ -> + valid_lower0_9(Rest, Char); +valid_lower0_9([], _) -> + true; +valid_lower0_9(_, _) -> + false. + + +-spec valid_label(string()) -> boolean(). +%% @private +%% Check whether a provided string is a valid label. + +valid_label([Char | Rest]) + when $a =< Char, Char =< $z -> + valid_label(Rest, Char); +valid_label(_) -> + false. + + +-spec valid_label(String, Last) -> boolean() + when String :: string(), + Last :: char(). + +valid_label([$. | _], $.) -> + false; +valid_label([$_ | _], $_) -> + false; +valid_label([$- | _], $-) -> + false; +valid_label([Char | Rest], _) + when $a =< Char, Char =< $z; + $0 =< Char, Char =< $9; + Char == $_; Char == $-; + Char == $. -> + valid_label(Rest, Char); +valid_label([], _) -> + true; +valid_label(_, _) -> + false. + + +-spec string_to_version(VersionString) -> Result + when VersionString :: string(), + Result :: {ok, zx:version()} + | {error, invalid_version_string}. +%% @private +%% @equiv string_to_version(string(), "", {z, z, z}) + +string_to_version(String) -> + string_to_version(String, "", {z, z, z}). + + +-spec string_to_version(String, Acc, Version) -> Result + when String :: string(), + Acc :: list(), + Version :: zx:version(), + Result :: {ok, zx:version()} + | {error, invalid_version_string}. +%% @private +%% Accepts a full or partial version string of the form `X.Y.Z', `X.Y' or `X' and +%% returns a zomp-type version tuple or crashes on bad data. + +string_to_version([Char | Rest], Acc, Version) when $0 =< Char andalso Char =< $9 -> + string_to_version(Rest, [Char | Acc], Version); +string_to_version("", "", Version) -> + {ok, Version}; +string_to_version(_, "", _) -> + {error, invalid_version_string}; +string_to_version([$. | Rest], Acc, {z, z, z}) -> + X = list_to_integer(lists:reverse(Acc)), + string_to_version(Rest, "", {X, z, z}); +string_to_version([$. | Rest], Acc, {X, z, z}) -> + Y = list_to_integer(lists:reverse(Acc)), + string_to_version(Rest, "", {X, Y, z}); +string_to_version([], Acc, {z, z, z}) -> + X = list_to_integer(lists:reverse(Acc)), + {ok, {X, z, z}}; +string_to_version([], Acc, {X, z, z}) -> + Y = list_to_integer(lists:reverse(Acc)), + {ok, {X, Y, z}}; +string_to_version([], Acc, {X, Y, z}) -> + Z = list_to_integer(lists:reverse(Acc)), + {ok, {X, Y, Z}}; +string_to_version(_, _, _) -> + {error, invalid_version_string}. + + +-spec version_to_string(zx:version()) -> {ok, string()} | {error, invalid_version}. +%% @private +%% Inverse of string_to_version/3. + +version_to_string({z, z, z}) -> + {ok, ""}; +version_to_string({X, z, z}) when is_integer(X) -> + {ok, integer_to_list(X)}; +version_to_string({X, Y, z}) when is_integer(X), is_integer(Y) -> + DeepList = lists:join($., [integer_to_list(Element) || Element <- [X, Y]]), + FlatString = lists:flatten(DeepList), + {ok, FlatString}; +version_to_string({X, Y, Z}) when is_integer(X), is_integer(Y), is_integer(Z) -> + DeepList = lists:join($., [integer_to_list(Element) || Element <- [X, Y, Z]]), + FlatString = lists:flatten(DeepList), + {ok, FlatString}; +version_to_string(_) -> + {error, invalid_version}. + + +-spec package_id(string()) -> {ok, zx:package_id()} | {error, invalid_package_string}. +%% @private +%% Converts a proper package_string to a package_id(). +%% This function takes into account missing version elements. +%% Examples: +%% `{ok, {"foo", "bar", {1, 2, 3}}} = package_id("foo-bar-1.2.3")' +%% `{ok, {"foo", "bar", {1, 2, z}}} = package_id("foo-bar-1.2")' +%% `{ok, {"foo", "bar", {1, z, z}}} = package_id("foo-bar-1")' +%% `{ok, {"foo", "bar", {z, z, z}}} = package_id("foo-bar")' +%% `{error, invalid_package_string} = package_id("Bad-Input")' + +package_id(String) -> + case dash_split(String) of + [Realm, Name, VersionString] -> + package_id(Realm, Name, VersionString); + [A, B] -> + case valid_lower0_9(B) of + true -> package_id(A, B, ""); + false -> package_id("otpr", A, B) + end; + [Name] -> + package_id("otpr", Name, ""); + _ -> + {error, invalid_package_string} + end. + + +-spec dash_split(string()) -> [string()] | error. +%% @private +%% An explicit, strict token split that ensures invalid names with leading, trailing or +%% double dashes don't slip through (a problem discovered with using string:tokens/2 +%% and string:lexemes/2. +%% Intended only as a helper function for package_id/1 + +dash_split(String) -> + dash_split(String, "", []). + + +dash_split([$- | Rest], Acc, Elements) -> + Element = lists:reverse(Acc), + dash_split(Rest, "", [Element | Elements]); +dash_split([Char | Rest], Acc, Elements) -> + dash_split(Rest, [Char | Acc], Elements); +dash_split("", Acc, Elements) -> + Element = lists:reverse(Acc), + lists:reverse([Element | Elements]); +dash_split(_, _, _) -> + error. + + +-spec package_id(Realm, Name, VersionString) -> Result + when Realm :: zx:realm(), + Name :: zx:name(), + VersionString :: string(), + Result :: {ok, zx:package_id()} + | {error, invalid_package_string}. + +package_id(Realm, Name, VersionString) -> + ValidRealm = valid_lower0_9(Realm), + ValidName = valid_lower0_9(Name), + MaybeVersion = string_to_version(VersionString), + case {ValidRealm, ValidName, MaybeVersion} of + {true, true, {ok, Version}} -> {ok, {Realm, Name, Version}}; + _ -> {error, invalid_package_string} + end. + + +-spec package_string(zx:package_id()) -> {ok, string()} | {error, invalid_package_id}. +%% @private +%% Map an PackageID to a correct string representation. +%% This function takes into account missing version elements. +%% Examples: +%% `{ok, "foo-bar-1.2.3"} = package_string({"foo", "bar", {1, 2, 3}})' +%% `{ok, "foo-bar-1.2"} = package_string({"foo", "bar", {1, 2, z}})' +%% `{ok, "foo-bar-1"} = package_string({"foo", "bar", {1, z, z}})' +%% `{ok, "foo-bar"} = package_string({"foo", "bar", {z, z, z}})' +%% `{error, invalid_package_id = package_string({"Bad", "Input"})' + +package_string({Realm, Name, {z, z, z}}) -> + ValidRealm = valid_lower0_9(Realm), + ValidName = valid_lower0_9(Name), + case ValidRealm and ValidName of + true -> + PackageString = lists:flatten(lists:join($-, [Realm, Name])), + {ok, PackageString}; + false -> + {error, invalid_package_id} + end; +package_string({Realm, Name, Version}) -> + ValidRealm = valid_lower0_9(Realm), + ValidName = valid_lower0_9(Name), + MaybeVersionString = version_to_string(Version), + case {ValidRealm, ValidName, MaybeVersionString} of + {true, true, {ok, VerString}} -> + PackageString = lists:flatten(lists:join($-, [Realm, Name, VerString])), + {ok, PackageString}; + _ -> + {error, invalid_package_id} + end; +package_string({Realm, Name}) -> + package_string({Realm, Name, {z, z, z}}); +package_string(_) -> + {error, invalid_package_id}. + + +-spec package_dir(zx:package_id()) -> file:filename(). +%% @private +%% Returns the path to a package installation. Crashes if PackageID is not a valid +%% identitifer or if the version is incomplete (it is not possible to create a path +%% to a partial version number). + +package_dir({Realm, Name, Version = {X, Y, Z}}) + when is_integer(X), is_integer(Y), is_integer(Z) -> + {ok, PackageDir} = package_string({Realm, Name}), + {ok, VersionDir} = version_to_string(Version), + filename:join([zomp_home(), "lib", PackageDir, VersionDir]). + + +-spec package_dir(Prefix, Package) -> PackageDataDir + when Prefix :: string(), + Package :: zx:package(), + PackageDataDir :: file:filename(). +%% @private +%% Create an absolute path to an application directory prefixed by the inclued argument. + +package_dir(Prefix, {Realm, Name}) -> + PackageString = package_string({Realm, Name, {z, z, z}}), + filename:join([zomp_home(), Prefix, PackageString]). + + +-spec namify_zrp(PackageID) -> ZrpFileName + when PackageID :: package_id(), + ZrpFileName :: file:filename(). +%% @private +%% Map an PackageID to its correct .zrp package file name. + +namify_zrp(PackageID) -> namify(PackageID, "zrp"). + + +-spec namify_tgz(PackageID) -> TgzFileName + when PackageID :: package_id(), + TgzFileName :: file:filename(). +%% @private +%% Map an PackageID to its correct gzipped tarball source bundle filename. + +namify_tgz(PackageID) -> namify(PackageID, "tgz"). + + +-spec namify(PackageID, Suffix) -> FileName + when PackageID :: package_id(), + Suffix :: string(), + FileName :: file:filename(). +%% @private +%% Converts an PackageID to a canonical string, then appends the provided +%% filename Suffix. + +namify(PackageID, Suffix) -> + {ok, PackageString} = package_string(PackageID), + PackageString ++ "." ++ Suffix. + + +-spec find_latest_compatible(Version, Versions) -> Result + when Version :: zx:version(), + Versions :: [zx:version()], + Result :: exact + | {ok, zx:version()} + | not_found. +%% @private +%% Find the latest compatible version from a list of versions. Returns the atom +%% `exact' in the case a full version is specified and it exists, the tuple +%% `{ok, Version}' in the case a compatible version was found against a partial +%% version tuple, and the atom `not_found' in the case no compatible version exists +%% in the list. Will fail with `not_found' if the input `Version' is not a valid +%% `zx:version()' tuple. + +find_latest_compatible(Version, Versions) -> + Descending = lists:reverse(lists:sort(Versions)), + latest_compatible(Version, Descending). + + +latest_compatible({z, z, z}, Versions) -> + {ok, hd(Versions)}; +latest_compatible({X, z, z}, Versions) -> + case lists:keyfind(X, 1, Versions) of + false -> not_found; + Version -> {ok, Version} + end; +latest_compatible({X, Y, z}, Versions) -> + NotMatch = fun({Q, W, _}) -> not (Q == X andalso W == Y) end, + case lists:dropwhile(NotMatch, Versions) of + [] -> not_found; + Vs -> {ok, hd(Vs)} + end; +latest_compatible(Version, Versions) -> + case lists:member(Version, Versions) of + true -> exact; + false -> not_found + end. + + +-spec installed(zx:package_id()) -> boolean(). +%% @private +%% True to its name, tells whether a package's install directory is found. + +installed(PackageID) -> + filelib:is_dir(package_dir(PackageID)). diff --git a/zomp/zx.sh b/zomp/zx.sh index dc91166..c439460 100755 --- a/zomp/zx.sh +++ b/zomp/zx.sh @@ -1,6 +1,6 @@ #! /bin/sh -# set -x +set -x ZOMP_DIR="$HOME/zomp" ORIGIN="$(pwd)" diff --git a/zx_dev.sh b/zx_dev.sh new file mode 100755 index 0000000..f02735a --- /dev/null +++ b/zx_dev.sh @@ -0,0 +1,13 @@ +#! /bin/sh + +set -x + +ZOMP_DIR="$HOME/vcs/zx/zomp" +ORIGIN="$(pwd)" +VERSION="$(ls $ZOMP_DIR/lib/otpr-zx/ | sort --field-separator=. --reverse | head --lines=1)" +ZX_DIR="$ZOMP_DIR/lib/otpr-zx/$VERSION" + +cd "$ZX_DIR" +./zmake +cd "$ZOMP_DIR" +erl -pa "$ZX_DIR/ebin" -run zx start $@ From 64d599d6ab3c84e5374329a819c7a03f1096cbf2 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Fri, 26 Jan 2018 13:58:13 +0900 Subject: [PATCH 34/55] Move moving around... --- zomp/lib/otpr-zx/0.1.0/src/zx.erl | 735 ++++++++----------------- zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl | 200 +++++++ zomp/lib/otpr-zx/0.1.0/src/zx_lib.erl | 43 +- 3 files changed, 452 insertions(+), 526 deletions(-) diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx.erl b/zomp/lib/otpr-zx/0.1.0/src/zx.erl index 9d1fc3f..f08d944 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx.erl @@ -369,6 +369,10 @@ ensure_all_started(AppMod) -> %% command line arguments provided. pass_argv(AppMod, Args) -> + case lists:member({accept_argv, 1}, AppMod:module_info(exports)) of + true -> AppMod:accept_argv(Args); + false -> ok +end. @@ -530,7 +534,7 @@ ensure_installed(PackageID = {Realm, Name, Version}) -> case resolve_installed_version(PackageID) of exact -> {ok, PackageID}; {ok, Installed} -> {ok, {Realm, Name, Installed}}; - not_found -> fetch({Realm, Name, Version}) + not_found -> fetch_one({Realm, Name, Version}) end. @@ -553,38 +557,6 @@ fetch_one(PackageID) -> end. --spec ensure_installed(Realm, Name, Version) -> Result | no_return() - when Realm :: realm(), - Name :: name(), - Version :: version(), - Result :: exact - | {ok, package_id()} - | not_found. -%% @private -%% Fetch and install the latest compatible version of the given package ID, whether -%% the version indicator is complete, partial or blank. - -ensure_installed(Realm, Name, Version) -> - case zx_daemon:query_latest({Realm, Name, Version}) of - {ok, LatestVersion} -> - LatestID = {Realm, Name, LatestVersion}, - ok = ensure_dep(Socket, LatestID), - {ok, LatestID}; - {error, bad_realm} -> - PackageString = package_string({Realm, Name, Version}), - ok = log(warning, "Bad realm: ~ts.", [PackageString]), - halt(1); - {error, bad_package} -> - PackageString = package_string({Realm, Name, Version}), - ok = log(warning, "Bad package: ~ts.", [PackageString]), - halt(1); - {error, bad_version} -> - PackageString = package_string({Realm, Name, Version}), - ok = log(warning, "Bad version: ~s.", [PackageString]), - halt(1) - end. - - -spec resolve_installed_version(PackageID) -> Result when PackageID :: package_id(), Result :: not_found @@ -629,59 +601,18 @@ tuplize(String, Acc) -> set_version(VersionString) -> NewVersion = case zx_lib:string_to_version(VersionString) of - {_, _, z} -> + {ok, {_, _, z}} -> Message = "'set version' arguments must be complete, ex: 1.2.3", - ok = log(error, Message), - halt(22); - Version -> - Version + error_exit(Message, ?LINE); + {ok, Version} -> + Version; + {error, invalid_version_string} -> + Message = "Invalid version string: ~tp", + error_exit(Message, [VersionString], ?LINE) end, - update_version(NewVersion). - - --spec update_version(Level) -> no_return() - when Level :: major - | minor - | patch - | VersionString, - VersionString :: string(). % Of the form "Major.Minor.Patch" -%% @private -%% Update a project's `zomp.meta' file by either incrementing the indicated component, -%% or setting the version number to the one specified in VersionString. -%% This part of the procedure guards for the case when the zomp.meta file cannot be -%% read for some reason. - -update_version(Arg) -> {ok, Meta} = zx_lib:read_project_meta(), - PackageID = maps:get(package_id, Meta), - update_version(Arg, PackageID, Meta). - - --spec update_version(Level, PackageID, Meta) -> no_return() - when Level :: major - | minor - | patch - | version(), - PackageID :: package_id(), - Meta :: [{atom(), term()}]. -%% @private -%% Update a project's `zomp.meta' file by either incrementing the indicated component, -%% or setting the version number to the one specified in VersionString. -%% This part of the procedure does the actual update calculation, to include calling to -%% convert the VersionString (if it is passed) to a `version()' type and check its -%% validity (or halt if it is a bad string). - -update_version(major, {Realm, Name, OldVersion = {Major, _, _}}, OldMeta) -> - NewVersion = {Major + 1, 0, 0}, - update_version(Realm, Name, OldVersion, NewVersion, OldMeta); -update_version(minor, {Realm, Name, OldVersion = {Major, Minor, _}}, OldMeta) -> - NewVersion = {Major, Minor + 1, 0}, - update_version(Realm, Name, OldVersion, NewVersion, OldMeta); -update_version(patch, {Realm, Name, OldVersion = {Major, Minor, Patch}}, OldMeta) -> - NewVersion = {Major, Minor, Patch + 1}, - update_version(Realm, Name, OldVersion, NewVersion, OldMeta); -update_version(NewVersion, {Realm, Name, OldVersion}, OldMeta) -> - update_version(Realm, Name, OldVersion, NewVersion, OldMeta). + {Realm, Name, OldVersion} = maps:get(package_id, Meta), + update_version(Realm, Name, OldVersion, NewVersion, Meta). -spec update_version(Realm, Name, OldVersion, NewVersion, OldMeta) -> no_return() @@ -689,7 +620,7 @@ update_version(NewVersion, {Realm, Name, OldVersion}, OldMeta) -> Name :: name(), OldVersion :: version(), NewVersion :: version(), - OldMeta :: [{atom(), term()}]. + OldMeta :: project_meta(). %% @private %% Update a project's `zomp.meta' file by either incrementing the indicated component, %% or setting the version number to the one specified in VersionString. @@ -701,10 +632,9 @@ update_version(Realm, Name, OldVersion, NewVersion, OldMeta) -> PackageID = {Realm, Name, NewVersion}, NewMeta = maps:put(package_id, PackageID, OldMeta), ok = zx_lib:write_project_meta(NewMeta), - ok = log(info, - "Version changed from ~s to ~s.", - [zx_lib:version_to_string(OldVersion), - zx_lib:version_to_string(NewVersion)]), + OldVS = zx_lib:version_to_string(OldVersion), + NewVS = zx_lib:version_to_string(NewVersion), + ok = log(info, "Version changed from ~s to ~s.", [OldVS, NewVS]), halt(0). @@ -714,7 +644,7 @@ update_version(Realm, Name, OldVersion, NewVersion, OldMeta) -> -spec list_realms() -> no_return(). %% @private %% List all currently configured realms. The definition of a "configured realm" is a -%% realm for which a .realm file exists in ~/zomp/. The realms will be printed to +%% realm for which a .realm file exists in $ZOMP_HOME. The realms will be printed to %% stdout and the program will exit. list_realms() -> @@ -731,6 +661,7 @@ list_realms() -> %% them to stdout. list_packages(Realm) -> + ok = start(), case zx_daemon:list_packages(Realm) of {ok, []} -> ok = log(info, "Realm ~tp has no packages available.", [Realm]), @@ -740,14 +671,12 @@ list_packages(Realm) -> ok = lists:foreach(Print, Packages), halt(0); {error, bad_realm} -> - ok = log(error, "Bad realm name."), - halt(1); + error_exit("Bad realm name.", ?LINE); {error, no_realm} -> - ok = log(error, "Realm \"~ts\" is not configured.", [Realm]), - halt(1); + error_exit("Realm \"~ts\" is not configured.", ?LINE); {error, network} -> - ok = log(error, "Network issues are preventing connection to the realm."), - halt(1) + Message = "Network issues are preventing connection to the realm.", + error_exit(Message, ?LINE); end. @@ -757,12 +686,10 @@ list_packages(Realm) -> %% package name (such as "otpr-zomp") and the return values will be full package strings %% of the form "otpr-zomp-1.2.3", one per line printed to stdout. -list_versions(Package = {Realm, Name}) -> - ok = valid_package(Package), - Socket = connect_user(Realm), - ok = send(Socket, {list, Realm, Name}), - case recv_or_die(Socket) of - {ok, []} -> +list_versions(Package) -> + ok = start(), + case zx_daemon:list_versions(Package) of + {ok, []} Message = "Package ~ts-~ts has no versions available.", ok = log(info, Message, [Realm, Name]), halt(0); @@ -773,21 +700,26 @@ list_versions(Package = {Realm, Name}) -> io:format("~ts~n", [PackageString]) end, ok = lists:foreach(Print, Versions), - halt(0) + halt(0); + {error, bad_realm} -> + error_exit("Bad realm name.", ?LINE); + {error, bad_package} -> + error_exit("Bad package name.", ?LINE); + {error, network} -> + Message = "Network issues are preventing connection to the realm.", + error_exit(Message, ?LINE) end. -spec list_pending(package()) -> no_return(). %% @private -%% List the versions of a package that are pending review. The package name is input by the -%% user as a string of the form "otpr-zomp" and the output is a list of full package IDs, -%% printed one per line to stdout (like "otpr-zomp-3.2.2"). +%% List the versions of a package that are pending review. The package name is input by +%% the user as a string of the form "otpr-zomp" and the output is a list of full +%% package IDs, printed one per line to stdout (like "otpr-zomp-3.2.2"). -list_pending(Package = {Realm, Name}) -> - ok = valid_package(Package), - Socket = connect_user(Realm), - ok = send(Socket, {pending, Package}), - case recv_or_die(Socket) of +list_pending(Package) -> + ok = start(), + case zx_daemon:list_pending(Package) of {ok, []} -> Message = "Package ~ts-~ts has no versions pending.", ok = log(info, Message, [Realm, Name]), @@ -799,7 +731,14 @@ list_pending(Package = {Realm, Name}) -> io:format("~ts~n", [PackageString]) end, ok = lists:foreach(Print, Versions), - halt(0) + halt(0); + {error, bad_realm} -> + error_exit("Bad realm name.", ?LINE); + {error, bad_package} -> + error_exit("Bad package name.", ?LINE); + {error, network} -> + Message = "Network issues are preventing connection to the realm.", + error_exit(Message, ?LINE) end. @@ -809,9 +748,8 @@ list_pending(Package = {Realm, Name}) -> %% printed to stdout one per line. list_resigns(Realm) -> - Socket = connect_auth_or_die(Realm), - ok = send(Socket, {list_resigns, Realm}), - case recv_or_die(Socket) of + ok = start(), + case zx_daemon:list_resigns(Realm) of {ok, []} -> Message = "No packages pending signature in ~tp.", ok = log(info, Message, [Realm]), @@ -823,59 +761,14 @@ list_resigns(Realm) -> io:format("~ts~n", [PackageString]) end, ok = lists:foreach(Print, PackageIDs), - halt(0) - end. - - --spec valid_package(package()) -> ok | no_return(). -%% @private -%% Test whether a package() type is a valid value or not. If not, halt execution with -%% a non-zero error code, if so then return `ok'. - -valid_package({Realm, Name}) -> - case {zx_lib:valid_lower0_9(Realm), zx_lib:valid_lower0_9(Name)} of - {true, true} -> - ok; - {false, true} -> - ok = log(error, "Invalid realm name: ~tp", [Realm]), - halt(1); - {true, false} -> - ok = log(error, "Invalid package name: ~tp", [Name]), - halt(1); - {false, false} -> - ok = log(error, "Invalid realm ~tp and package ~tp", [Realm, Name]), - halt(1) - end. - - --spec string_to_package(string()) -> package() | no_return(). -%% @private -%% Convert a string to a package() type if possible. If not then halt the system. - -string_to_package(String) -> - case string:lexemes(String, "-") of - [Realm, Name] -> - Package = {Realm, Name}, - ok = valid_package(Package), - Package; - _ -> - ok = log(error, "Bad package name."), - halt(1) - end. - - --spec valid_realm(realm()) -> ok | no_return(). -%% @private -%% Test whether a realm name is a valid realm() type (that is, a lower0_9()) or not. If not, -%% halt execution with a non-zero error code, if so then return `ok'. - -valid_realm(Realm) -> - case zx_lib:valid_lower0_9(Realm) of - true -> - ok; - false -> - ok = log(error, "Bad realm name."), - halt(1) + halt(0); + {error, bad_realm} -> + error_exit("Bad realm name.", ?LINE); + {error, no_realm} -> + error_exit("Realm \"~ts\" is not configured.", ?LINE); + {error, network} -> + Message = "Network issues are preventing connection to the realm.", + error_exit(Message, ?LINE) end. @@ -884,6 +777,11 @@ valid_realm(Realm) -> -spec add_realm(Path) -> no_return() when Path :: file:filename(). +%% @private +%% Add a .realm file to $ZOMP_HOME from a location in the filesystem. +%% Print the SHA512 of the .realm file for the user so they can verify that the file +%% is authentic. This implies, of course, that .realm maintainers are going to +%% post SHA512 sums somewhere visible. add_realm(Path) -> case file:read_file(Path) of @@ -912,45 +810,30 @@ add_realm(Path, Data) -> ok = log(info, "Realm ~ts is now visible to this system.", [Realm]), halt(0); {error, invalid_tar_checksum} -> - ok = log(warning, "FAILED: ~ts is not a valid realm file.", [Path]), - halt(1); + error_exit("~ts is not a valid realm file.", [Path], ?LINE); {error, eof} -> - ok = log(warning, "FAILED: ~ts is not a valid realm file.", [Path]), - halt(1) + error_exit("~ts is not a valid realm file.", [Path], ?LINE) end. -spec add_package(PackageName) -> no_return() when PackageName :: package(). +%% @private +%% A sysop command that adds a package to a realm operated by the caller. add_package(PackageName) -> ok = file:set_cwd(zx_lib:zomp_home()), - case string:lexemes(PackageName, "-") of - [Realm, Name] -> - case {zx_lib:valid_lower0_9(Realm), zx_lib:valid_lower0_9(Name)} of - {true, true} -> - add_package(Realm, Name); - {false, true} -> - ok = log(warning, "Invalid realm name: ~tp", [Realm]), - halt(1); - {true, false} -> - ok = log(warning, "Invalid package name: ~tp", [Name]), - halt(1); - {false, false} -> - ok = log(warning, "Invalid realm and package names."), - halt(1) - end; + case zx_lib:package_id(PackageName) of + {ok, {Realm, Name, {z, z, z}} -> + add_package(Realm, Name); _ -> - ok = log(warning, "Name ~tp is not a valid package name.", [PackageName]), - halt(1) + error_exit("~tp is not a valid package name.", [PackageName], ?LINE) end. -spec add_package(Realm, Name) -> no_return() when Realm :: realm(), Name :: name(). -%% @private -%% This sysop-only command can add a package to a realm operated by the caller. add_package(Realm, Name) -> Socket = connect_auth_or_die(Realm), @@ -1087,7 +970,8 @@ drop_dep(PackageID) -> drop_key({Realm, KeyName}) -> ok = file:set_cwd(zx_lib:zomp_home()), - Pattern = filename:join([zx_lib:zomp_home(), "key", Realm, KeyName ++ ".{key,pub}.der"]), + KeyGlob = KeyName ++ ".{key,pub},der", + Pattern = filename:join([zx_lib:zomp_home(), "key", Realm, KeyGlob]), case filelib:wildcard(Pattern) of [] -> ok = log(warning, "Key ~ts/~ts not found", [Realm, KeyName]), @@ -1105,7 +989,7 @@ drop_key({Realm, KeyName}) -> drop_realm(Realm) -> ok = file:set_cwd(zx_lib:zomp_home()), - RealmConf = realm_conf(Realm), + RealmConf = zx_lib:realm_conf(Realm), case filelib:is_regular(RealmConf) of true -> Message = @@ -1129,6 +1013,7 @@ drop_realm(Realm) -> clear_keys(Realm) end. + -spec drop_prime(realm()) -> ok. drop_prime(Realm) -> @@ -1150,15 +1035,8 @@ drop_prime(Realm) -> clear_keys(Realm) -> KeyDir = filename:join([zx_lib:zomp_home(), "key", Realm]), case filelib:is_dir(KeyDir) of - true -> - ok = log(info, "Wiping key dir ~ts", [KeyDir]), - Keys = filelib:wildcard(KeyDir ++ "/**"), - Delete = fun(K) -> file:delete(K) end, - ok = lists:foreach(Delete, Keys), - ok = file:del_dir(KeyDir), - log(info, "Done!"); - false -> - log(warning, "Keydir ~ts not found", [KeyDir]) + true -> rm_rf(KeyDir); + false -> log(warning, "Keydir ~ts not found", [KeyDir]) end. @@ -1170,12 +1048,53 @@ clear_keys(Realm) -> %% @private %% Convert input string arguments to acceptable atoms for use in update_version/1. -verup("major") -> update_version(major); -verup("minor") -> update_version(minor); -verup("patch") -> update_version(patch); +verup("major") -> version_up(major); +verup("minor") -> version_up(minor); +verup("patch") -> version_up(patch); verup(_) -> usage_exit(22). +-spec version_up(Level) -> no_return() + when Level :: major + | minor + | patch. +%% @private +%% Update a project's `zomp.meta' file by either incrementing the indicated component, +%% or setting the version number to the one specified in VersionString. +%% This part of the procedure guards for the case when the zomp.meta file cannot be +%% read for some reason. + +version_up(Arg) -> + {ok, Meta} = zx_lib:read_project_meta(), + PackageID = maps:get(package_id, Meta), + version_up(Arg, PackageID, Meta). + + +-spec version_up(Level, PackageID, Meta) -> no_return() + when Level :: major + | minor + | patch + | version(), + PackageID :: package_id(), + Meta :: [{atom(), term()}]. +%% @private +%% Update a project's `zomp.meta' file by either incrementing the indicated component, +%% or setting the version number to the one specified in VersionString. +%% This part of the procedure does the actual update calculation, to include calling to +%% convert the VersionString (if it is passed) to a `version()' type and check its +%% validity (or halt if it is a bad string). + +version_up(major, {Realm, Name, OldVersion = {Major, _, _}}, OldMeta) -> + NewVersion = {Major + 1, 0, 0}, + update_version(Realm, Name, OldVersion, NewVersion, OldMeta); +version_up(minor, {Realm, Name, OldVersion = {Major, Minor, _}}, OldMeta) -> + NewVersion = {Major, Minor + 1, 0}, + update_version(Realm, Name, OldVersion, NewVersion, OldMeta); +version_up(patch, {Realm, Name, OldVersion = {Major, Minor, Patch}}, OldMeta) -> + NewVersion = {Major, Minor, Patch + 1}, + update_version(Realm, Name, OldVersion, NewVersion, OldMeta). + + %%% Package generation @@ -1231,7 +1150,8 @@ package(KeyID, TargetDir) -> {ok, CWD} = file:get_cwd(), ok = file:set_cwd(TargetDir), ok = build(), - Modules = [filename:basename(M, ".beam") || M <- filelib:wildcard("*.beam", "ebin")], + Modules = + [filename:basename(M, ".beam") || M <- filelib:wildcard("*.beam", "ebin")], ok = remove_binaries("."), ok = erl_tar:create(filename:join(CWD, TgzFile), Targets, [compressed]), ok = file:set_cwd(CWD), @@ -1290,6 +1210,9 @@ submit(PackageFile) -> halt(0). + +%%% Authenticated communication with prime + -spec send(Socket, Message) -> ok when Socket :: gen_tcp:socket(), Message :: term(). @@ -1313,175 +1236,15 @@ recv_or_die(Socket) -> ok; {ok, Response} -> {ok, Response}; - {error, bad_realm} -> - ok = log(warning, "No such realm at the connected node."), - halt(1); - {error, bad_package} -> - ok = log(warning, "No such package."), - halt(1); - {error, bad_version} -> - ok = log(warning, "No such version."), - halt(1); - {error, not_in_queue} -> - ok = log(warning, "Version is not queued."), - halt(1); - {error, bad_message} -> - ok = log(error, "Oh noes! zx sent an illegal message!"), - halt(1); - {error, already_exists} -> - ok = log(warning, "Server refuses: already_exists"), - halt(1); - {error, {system, Reason}} -> - Message = "Node experienced system error: ~160tp", - ok = log(warning, Message, [{error, Reason}]), - halt(1); + {error, Reason} -> + error_exit("Action failed with: ~tp", [Reason], ?LINE); Unexpected -> - ok = log(warning, "Unexpected message: ~tp", [Unexpected]), - halt(1) + error_exit("Unexpected message: ~tp", [Unexpected], ?LINE) end; {tcp_closed, Socket} -> - ok = log(warning, "Lost connection to node unexpectedly."), - halt(1) + error_exit("Lost connection to node unexpectedly.", ?LINE) after 5000 -> - ok = log(warning, "Node timed out."), - halt(1) - end. - - --spec halt_on_unexpected_close() -> no_return(). - -halt_on_unexpected_close() -> - ok = log(warning, "Socket closed unexpectedly."), - halt(1). - - --spec connect_user(realm()) -> gen_tcp:socket() | no_return(). -%% @private -%% Connect to a given realm, whatever method is required. - -connect_user(Realm) -> - ok = log(info, "Connecting to realm ~ts...", [Realm]), - Hosts = - case file:consult(zx_lib:hosts_cache_file(Realm)) of - {ok, Cached} -> Cached; - {error, enoent} -> [] - end, - connect_user(Realm, Hosts). - - --spec connect_user(realm(), [host()]) -> gen_tcp:socket() | no_return(). -%% @private -%% Try to connect to a subordinate host, if there are none then connect to prime. - -connect_user(Realm, []) -> - {Host, Port} = zx_lib:get_prime(Realm), - HostString = - case io_lib:printable_unicode_list(Host) of - true -> Host; - false -> inet:ntoa(Host) - end, - ok = log(info, "Trying prime at ~ts:~160tp", [HostString, Port]), - case gen_tcp:connect(Host, Port, connect_options(), 5000) of - {ok, Socket} -> - confirm_user(Realm, Socket, []); - {error, Error} -> - ok = log(warning, "Connection problem with prime: ~tp", [Error]), - halt(0) - end; -connect_user(Realm, Hosts = [Node = {Host, Port} | Rest]) -> - ok = log(info, "Trying node at ~ts:~tp", [inet:ntoa(Host), Port]), - case gen_tcp:connect(Host, Port, connect_options(), 5000) of - {ok, Socket} -> - confirm_user(Realm, Socket, Hosts); - {error, Error} -> - ok = log(warning, "Connection problem with ~tp: ~tp", [Node, Error]), - connect_user(Realm, Rest) - end. - - --spec confirm_user(Realm, Socket, Hosts) -> Socket | no_return() - when Realm :: realm(), - Socket :: gen_tcp:socket(), - Hosts :: [host()]. -%% @private -%% Confirm the zomp node can handle "OTPR USER 1" and is accepting connections or try -%% another node. - -confirm_user(Realm, Socket, Hosts) -> - {ok, {Addr, Port}} = inet:peername(Socket), - Host = inet:ntoa(Addr), - ok = gen_tcp:send(Socket, <<"OTPR USER 1">>), - receive - {tcp, Socket, Bin} -> - case binary_to_term(Bin) of - ok -> - ok = log(info, "Connected to ~ts:~p", [Host, Port]), - confirm_serial(Realm, Socket, Hosts); - {redirect, Next} -> - ok = log(info, "Redirected..."), - ok = disconnect(Socket), - connect_user(Realm, Next ++ Hosts) - end; - {tcp_closed, Socket} -> - halt_on_unexpected_close() - after 5000 -> - ok = log(warning, "Host ~ts:~p timed out.", [Host, Port]), - ok = disconnect(Socket), - connect_user(Realm, Hosts) - end. - - --spec confirm_serial(Realm, Socket, Hosts) -> Socket | no_return() - when Realm :: realm(), - Socket :: gen_tcp:socket(), - Hosts :: [host()]. -%% @private -%% Confirm that the connected host has a valid serial for the realm zx is trying to -%% reach, and if not retry on another node. - -confirm_serial(Realm, Socket, Hosts) -> - SerialFile = filename:join(zx_lib:zomp_home(), "realm.serials"), - Serials = - case file:consult(SerialFile) of - {ok, Ss} -> Ss; - {error, enoent} -> [] - end, - Serial = - case lists:keyfind(Realm, 1, Serials) of - false -> 0; - {Realm, S} -> S - end, - ok = send(Socket, {latest, Realm}), - receive - {tcp, Socket, Bin} -> - case binary_to_term(Bin) of - {ok, Serial} -> - ok = log(info, "Node's serial same as ours."), - Socket; - {ok, Current} when Current > Serial -> - ok = log(info, "Node's serial newer than ours. Storing."), - NewSerials = lists:keystore(Realm, 1, Serials, {Realm, Current}), - {ok, Host} = inet:peername(Socket), - CacheFile = zx_lib:hosts_cache_file(Realm), - ok = zx_lib:write_terms(CacheFile, [Host | Hosts]), - ok = zx_lib:write_terms(SerialFile, NewSerials), - Socket; - {ok, Current} when Current < Serial -> - log(info, "Our serial: ~tp, node serial: ~tp.", [Serial, Current]), - ok = log(info, "Node's serial older than ours. Trying another."), - ok = disconnect(Socket), - connect_user(Realm, Hosts); - {error, bad_realm} -> - ok = log(info, "Node is no longer serving realm. Trying another."), - ok = disconnect(Socket), - connect_user(Realm, Hosts) - end; - {tcp_closed, Socket} -> - halt_on_unexpected_close() - after 5000 -> - ok = log(info, "Host timed out on confirm_serial. Trying another."), - ok = disconnect(Socket), - connect_user(Realm, Hosts) + error_exit("Connection timed out.", ?LINE) end. @@ -1509,7 +1272,8 @@ connect_auth(Realm) -> RealmConf = load_realm_conf(Realm), {User, KeyID, Key} = prep_auth(Realm, RealmConf), {prime, {Host, Port}} = lists:keyfind(prime, 1, RealmConf), - case gen_tcp:connect(Host, Port, connect_options(), 5000) of + Options = [{packet, 4}, {mode, binary}, {active, true}], + case gen_tcp:connect(Host, Port, Options, 5000) of {ok, Socket} -> ok = log(info, "Connected to ~tp prime.", [Realm]), connect_auth(Socket, Realm, User, KeyID, Key); @@ -1644,14 +1408,6 @@ prep_auth(Realm, RealmConf) -> {User, KeyID, Key}. --spec connect_options() -> [gen_tcp:connect_option()]. -%% @private -%% Hide away the default options used for TCP connections. - -connect_options() -> - [{packet, 4}, {mode, binary}, {active, true}]. - - -spec disconnect(gen_tcp:socket()) -> ok. %% @private %% Gracefully shut down a socket, logging (but sidestepping) the case when the socket @@ -1667,6 +1423,9 @@ disconnect(Socket) -> end. + +%%% Key utilities + -spec ensure_keypair(key_id()) -> true | no_return(). %% @private %% Check if both the public and private key based on KeyID exists. @@ -1808,11 +1567,8 @@ generate_rsa({Realm, KeyName}) -> halt_if_exists(Path) -> case filelib:is_file(Path) of - true -> - ok = log(error, "~ts already exists! Halting.", [Path]), - halt(1); - false -> - ok + true -> error_exit("~ts already exists! Halting.", [Path], ?LINE); + false -> ok end. @@ -1910,10 +1666,12 @@ loadkey(Type, {Realm, KeyName}) -> {DerType, Path} = case Type of private -> - P = filename:join([zx_lib:zomp_home(), "key", Realm, KeyName ++ ".key.der"]), + KeyDer = KeyName ++ ".key.der", + P = filename:join([zx_lib:zomp_home(), "key", Realm, KeyDer]), {'RSAPrivateKey', P}; public -> - P = filename:join([zx_lib:zomp_home(), "key", Realm, KeyName ++ ".pub.der"]), + PubDer = KeyName ++ ".pub.der" + P = filename:join([zx_lib:zomp_home(), "key", Realm, PubDer]), {'RSAPublicKey', P} end, ok = log(info, "Loading key from file ~ts", [Path]), @@ -1937,13 +1695,18 @@ create_plt() -> halt(0). +-spec build_plt() -> ok. +%% @private +%% Build a general plt file for Dialyzer based on the core Erland distro. +%% TODO: Make a per-package + dependencies version of this. + build_plt() -> PLT = default_plt(), Template = "dialyzer --build_plt" - " --output_plt ~ts" - " --apps asn1 reltool wx common_test crypto erts eunit inets" - " kernel mnesia public_key sasl ssh ssl stdlib", + " --output_plt ~ts" + " --apps asn1 reltool wx common_test crypto erts eunit inets" + " kernel mnesia public_key sasl ssh ssl stdlib", Command = io_lib:format(Template, [PLT]), Message = "Generating PLT file and writing to: ~tp~n" @@ -1955,6 +1718,8 @@ build_plt() -> log(info, Out). +-spec default_plt() -> file:filename(). + default_plt() -> filename:join(zx_lib:zomp_home(), "basic.plt"). @@ -1965,6 +1730,8 @@ default_plt() -> -spec dialyze() -> no_return(). %% @private %% Preps a copy of this script for typechecking with Dialyzer. +%% TODO: Create a package_id() based version of this to handle dialyzation of complex +%% projects. dialyze() -> PLT = default_plt(), @@ -2270,7 +2037,9 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email) -> create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email, RealName). --spec create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email, RealName) -> +-spec create_realm(ZompConf, Realm, + ExAddress, ExPort, InPort, + UserName, Email, RealName) -> no_return() when ZompConf :: [{Key :: atom(), Value :: term()}], Realm :: realm(), @@ -2362,7 +2131,7 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email, RealNa ok = rm_rf(TempDir), Message = - "============================================================================~n" + "===========================================================================~n" "DONE!~n" "~n" "The realm ~ts has been created and is accessible from the current system.~n" @@ -2373,8 +2142,8 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email, RealNa "node. It includes the your (the sysop's) public key.~n" "~n" " 2. ~ts ~n" - "This file is the PUBLIC realm file other zomp nodes and zx users will need to~n" - "access the realm. It does not include your (the sysop's) public key.~n" + "This file is the PUBLIC realm file other zomp nodes and zx users will need~n" + "to access the realm. It does not include your (the sysop's) public key.~n" "~n" " 3. ~ts ~n" "This is the bundle of ALL KEYS that are defined in this realm at the moment.~n" @@ -2391,7 +2160,7 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email, RealNa "~n" "Public & Private key installation (if you need to recover them or perform~n" "sysop functions from another computer) is `zx add keybundle ~ts`.~n" - "============================================================================~n", + "===========================================================================~n", Substitutions = [Realm, PrimeZRF, PublicZRF, KeyBundle, @@ -2427,7 +2196,7 @@ create_realmfile(Realm, Revision, RealmKeyIDs, PackageKeyIDs) -> KeyPath = fun({R, K}) -> filename:join(["key", R, K ++ ".pub.der"]) end, RealmKeyPaths = lists:map(KeyPath, RealmKeyIDs), PackageKeyPaths = lists:map(KeyPath, PackageKeyIDs), - Targets = [realm_conf(Realm) | RealmKeyPaths ++ PackageKeyPaths], + Targets = [zx_lib:realm_conf(Realm) | RealmKeyPaths ++ PackageKeyPaths], OutFile = filename:join(CWD, Realm ++ "." ++ integer_to_list(Revision) ++ ".zrf"), ok = erl_tar:create(OutFile, Targets, [compressed]), ok = log(info, "Realm conf file written to ~ts", [OutFile]), @@ -2442,7 +2211,7 @@ create_sysop() -> -%%% Network operations and package utilities +%%% Package utilities -spec install(package_id()) -> ok. @@ -2490,86 +2259,6 @@ verify(Data, Signature, PubKey) -> end. --spec fetch(Socket, PackageID) -> Result - when Socket :: gen_tcp:socket(), - PackageID :: package_id(), - Result :: ok. -%% @private -%% Download a package to the local cache. - -fetch(Socket, PackageID) -> - {ok, LatestID} = request_zrp(Socket, PackageID), - ok = receive_zrp(Socket, LatestID), - log(info, "Fetched ~ts", [package_string(LatestID)]). - - --spec request_zrp(Socket, PackageID) -> Result - when Socket :: gen_tcp:socket(), - PackageID :: package_id(), - Result :: {ok, Latest :: package_id()} - | {error, Reason :: timeout | term()}. - -request_zrp(Socket, PackageID) -> - ok = send(Socket, {fetch, PackageID}), - receive - {tcp, Socket, Bin} -> - case binary_to_term(Bin) of - {sending, LatestID} -> - {ok, LatestID}; - Error = {error, Reason} -> - PackageString = package_string(PackageID), - Message = "Error receiving package ~ts: ~tp", - ok = log(info, Message, [PackageString, Reason]), - Error - end; - {tcp_closed, Socket} -> - halt_on_unexpected_close() - after 60000 -> - {error, timeout} - end. - - --spec receive_zrp(Socket, PackageID) -> Result - when Socket :: gen_tcp:socket(), - PackageID :: package_id(), - Result :: ok | {error, timeout}. - -receive_zrp(Socket, PackageID) -> - receive - {tcp, Socket, Bin} -> - ZrpPath = filename:join("zrp", zx_lib:namify_zrp(PackageID)), - ok = file:write_file(ZrpPath, Bin), - ok = send(Socket, ok), - log(info, "Wrote ~ts", [ZrpPath]); - {tcp_closed, Socket} -> - halt_on_unexpected_close() - after 60000 -> - ok = log(error, "Timeout in socket receive for ~tp", [PackageID]), - {error, timeout} - end. - - --spec mktemp_dir(Prefix) -> Result - when Prefix :: string(), - Result :: {ok, TempDir :: file:filename()} - | {error, Reason :: file:posix()}. - -mktemp_dir(Prefix) -> - Rand = integer_to_list(binary:decode_unsigned(crypto:strong_rand_bytes(8)), 36), - TempPath = filename:basedir(user_cache, Prefix), - TempDir = filename:join(TempPath, Rand), - Result1 = filelib:ensure_dir(TempDir), - Result2 = file:make_dir(TempDir), - case {Result1, Result2} of - {ok, ok} -> {ok, TempDir}; - {ok, Error} -> Error; - {Error, _} -> Error - end. - - -%%% Utility functions - - -spec build(package_id()) -> ok. %% @private %% Given an AppID, build the project from source and add it to the current lib path. @@ -2602,22 +2291,6 @@ build() -> ok. --spec rm_rf(file:filename()) -> ok | {error, file:posix()}. -%% @private -%% Recursively remove files and directories, equivalent to `rm -rf' on unix. - -rm_rf(Path) -> - case filelib:is_dir(Path) of - true -> - Pattern = filename:join(Path, "**"), - Contents = lists:reverse(lists:sort(filelib:wildcard(Pattern))), - ok = lists:foreach(fun rm/1, Contents), - file:del_dir(Path); - false -> - file:delete(Path) - end. - - %%% User menu interface (terminal) @@ -2705,6 +2378,40 @@ hurr() -> io:format("That isn't an option.~n"). %%% Directory & File Management +-spec mktemp_dir(Prefix) -> Result + when Prefix :: string(), + Result :: {ok, TempDir :: file:filename()} + | {error, Reason :: file:posix()}. + +mktemp_dir(Prefix) -> + Rand = integer_to_list(binary:decode_unsigned(crypto:strong_rand_bytes(8)), 36), + TempPath = filename:basedir(user_cache, Prefix), + TempDir = filename:join(TempPath, Rand), + Result1 = filelib:ensure_dir(TempDir), + Result2 = file:make_dir(TempDir), + case {Result1, Result2} of + {ok, ok} -> {ok, TempDir}; + {ok, Error} -> Error; + {Error, _} -> Error + end. + + +-spec rm_rf(file:filename()) -> ok | {error, file:posix()}. +%% @private +%% Recursively remove files and directories. Equivalent to `rm -rf'. + +rm_rf(Path) -> + case filelib:is_dir(Path) of + true -> + Pattern = filename:join(Path, "**"), + Contents = lists:reverse(lists:sort(filelib:wildcard(Pattern))), + ok = lists:foreach(fun rm/1, Contents), + file:del_dir(Path); + false -> + file:delete(Path) + end. + + -spec ensure_zomp_home() -> ok. %% @private %% Ensure the zomp home directory exists and is populated. @@ -2767,33 +2474,6 @@ force_dir(Path) -> end. --spec realm_conf(Realm) -> RealmFileName - when Realm :: string(), - RealmFileName :: file:filename(). -%% @private -%% Take a realm name, and return the name of the realm filename that would result. - -realm_conf(Realm) -> - Realm ++ ".realm". - - --spec load_realm_conf(Realm) -> RealmConf | no_return() - when Realm :: realm(), - RealmConf :: list(). -%% @private -%% Load the config for the given realm or halt with an error. - -load_realm_conf(Realm) -> - Path = filename:join(zx_lib:zomp_home(), realm_conf(Realm)), - case file:consult(Path) of - {ok, C} -> - C; - {error, enoent} -> - ok = log(warning, "Realm ~tp is not configured.", [Realm]), - halt(1) - end. - - -spec extract_zrp_or_die(FileName) -> Files | no_return() when FileName :: file:filename(), Files :: [{file:filename(), binary()}]. @@ -2817,6 +2497,23 @@ extract_zrp_or_die(FileName) -> end. +-spec load_realm_conf(Realm) -> RealmConf | no_return() + when Realm :: realm(), + RealmConf :: list(). +%% @private +%% Load the config for the given realm or halt with an error. + +load_realm_conf(Realm) -> + case zx_lib:load_realm_conf(Realm) of + {ok, C} -> + C; + {error, enoent} -> + ok = log(warning, "Realm ~tp is not configured.", [Realm]), + halt(1) + end. + + + %%% Usage diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl index f585bc7..ccd3ab4 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl @@ -68,4 +68,204 @@ connect(Parent, Debug, {Host, Port}) -> confirm(Parent, Debug, Socket) -> + + +-spec connect_user(realm()) -> gen_tcp:socket() | no_return(). +%% @private +%% Connect to a given realm, whatever method is required. + +connect_user(Realm) -> + ok = log(info, "Connecting to realm ~ts...", [Realm]), + Hosts = + case file:consult(zx_lib:hosts_cache_file(Realm)) of + {ok, Cached} -> Cached; + {error, enoent} -> [] + end, + connect_user(Realm, Hosts). + + +-spec connect_user(realm(), [host()]) -> gen_tcp:socket() | no_return(). +%% @private +%% Try to connect to a subordinate host, if there are none then connect to prime. + +connect_user(Realm, []) -> + {Host, Port} = zx_lib:get_prime(Realm), + HostString = + case io_lib:printable_unicode_list(Host) of + true -> Host; + false -> inet:ntoa(Host) + end, + ok = log(info, "Trying prime at ~ts:~160tp", [HostString, Port]), + case gen_tcp:connect(Host, Port, connect_options(), 5000) of + {ok, Socket} -> + confirm_user(Realm, Socket, []); + {error, Error} -> + ok = log(warning, "Connection problem with prime: ~tp", [Error]), + halt(0) + end; +connect_user(Realm, Hosts = [Node = {Host, Port} | Rest]) -> + ok = log(info, "Trying node at ~ts:~tp", [inet:ntoa(Host), Port]), + case gen_tcp:connect(Host, Port, connect_options(), 5000) of + {ok, Socket} -> + confirm_user(Realm, Socket, Hosts); + {error, Error} -> + ok = log(warning, "Connection problem with ~tp: ~tp", [Node, Error]), + connect_user(Realm, Rest) + end. + + +-spec confirm_user(Realm, Socket, Hosts) -> Socket | no_return() + when Realm :: realm(), + Socket :: gen_tcp:socket(), + Hosts :: [host()]. +%% @private +%% Confirm the zomp node can handle "OTPR USER 1" and is accepting connections or try +%% another node. + +confirm_user(Realm, Socket, Hosts) -> + {ok, {Addr, Port}} = inet:peername(Socket), + Host = inet:ntoa(Addr), + ok = gen_tcp:send(Socket, <<"OTPR USER 1">>), + receive + {tcp, Socket, Bin} -> + case binary_to_term(Bin) of + ok -> + ok = log(info, "Connected to ~ts:~p", [Host, Port]), + confirm_serial(Realm, Socket, Hosts); + {redirect, Next} -> + ok = log(info, "Redirected..."), + ok = disconnect(Socket), + connect_user(Realm, Next ++ Hosts) + end; + {tcp_closed, Socket} -> + halt_on_unexpected_close() + after 5000 -> + ok = log(warning, "Host ~ts:~p timed out.", [Host, Port]), + ok = disconnect(Socket), + connect_user(Realm, Hosts) + end. + + +-spec confirm_serial(Realm, Socket, Hosts) -> Socket | no_return() + when Realm :: realm(), + Socket :: gen_tcp:socket(), + Hosts :: [host()]. +%% @private +%% Confirm that the connected host has a valid serial for the realm zx is trying to +%% reach, and if not retry on another node. + +confirm_serial(Realm, Socket, Hosts) -> + SerialFile = filename:join(zx_lib:zomp_home(), "realm.serials"), + Serials = + case file:consult(SerialFile) of + {ok, Ss} -> Ss; + {error, enoent} -> [] + end, + Serial = + case lists:keyfind(Realm, 1, Serials) of + false -> 0; + {Realm, S} -> S + end, + ok = send(Socket, {latest, Realm}), + receive + {tcp, Socket, Bin} -> + case binary_to_term(Bin) of + {ok, Serial} -> + ok = log(info, "Node's serial same as ours."), + Socket; + {ok, Current} when Current > Serial -> + ok = log(info, "Node's serial newer than ours. Storing."), + NewSerials = lists:keystore(Realm, 1, Serials, {Realm, Current}), + {ok, Host} = inet:peername(Socket), + CacheFile = zx_lib:hosts_cache_file(Realm), + ok = zx_lib:write_terms(CacheFile, [Host | Hosts]), + ok = zx_lib:write_terms(SerialFile, NewSerials), + Socket; + {ok, Current} when Current < Serial -> + log(info, "Our serial: ~tp, node serial: ~tp.", [Serial, Current]), + ok = log(info, "Node's serial older than ours. Trying another."), + ok = disconnect(Socket), + connect_user(Realm, Hosts); + {error, bad_realm} -> + ok = log(info, "Node is no longer serving realm. Trying another."), + ok = disconnect(Socket), + connect_user(Realm, Hosts) + end; + {tcp_closed, Socket} -> + halt_on_unexpected_close() + after 5000 -> + ok = log(info, "Host timed out on confirm_serial. Trying another."), + ok = disconnect(Socket), + connect_user(Realm, Hosts) + end. + + +-spec halt_on_unexpected_close() -> no_return(). + +halt_on_unexpected_close() -> + ok = log(warning, "Socket closed unexpectedly."), + halt(1). + + + + + + +-spec fetch(Socket, PackageID) -> Result + when Socket :: gen_tcp:socket(), + PackageID :: package_id(), + Result :: ok. +%% @private +%% Download a package to the local cache. + +fetch(Socket, PackageID) -> + {ok, LatestID} = request_zrp(Socket, PackageID), + ok = receive_zrp(Socket, LatestID), + log(info, "Fetched ~ts", [package_string(LatestID)]). + + +-spec request_zrp(Socket, PackageID) -> Result + when Socket :: gen_tcp:socket(), + PackageID :: package_id(), + Result :: {ok, Latest :: package_id()} + | {error, Reason :: timeout | term()}. + +request_zrp(Socket, PackageID) -> + ok = send(Socket, {fetch, PackageID}), + receive + {tcp, Socket, Bin} -> + case binary_to_term(Bin) of + {sending, LatestID} -> + {ok, LatestID}; + Error = {error, Reason} -> + PackageString = package_string(PackageID), + Message = "Error receiving package ~ts: ~tp", + ok = log(info, Message, [PackageString, Reason]), + Error + end; + {tcp_closed, Socket} -> + halt_on_unexpected_close() + after 60000 -> + {error, timeout} + end. + + +-spec receive_zrp(Socket, PackageID) -> Result + when Socket :: gen_tcp:socket(), + PackageID :: package_id(), + Result :: ok | {error, timeout}. + +receive_zrp(Socket, PackageID) -> + receive + {tcp, Socket, Bin} -> + ZrpPath = filename:join("zrp", zx_lib:namify_zrp(PackageID)), + ok = file:write_file(ZrpPath, Bin), + ok = send(Socket, ok), + log(info, "Wrote ~ts", [ZrpPath]); + {tcp_closed, Socket} -> + halt_on_unexpected_close() + after 60000 -> + ok = log(error, "Timeout in socket receive for ~tp", [PackageID]), + {error, timeout} + end. diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_lib.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_lib.erl index 2f0b39a..315a2fb 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx_lib.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_lib.erl @@ -328,26 +328,25 @@ version_to_string(_) -> package_id(String) -> case dash_split(String) of - [Realm, Name, VersionString] -> + {ok, [Realm, Name, VersionString]} -> package_id(Realm, Name, VersionString); - [A, B] -> + {ok, [A, B]} -> case valid_lower0_9(B) of true -> package_id(A, B, ""); false -> package_id("otpr", A, B) end; - [Name] -> + {ok, [Name]} -> package_id("otpr", Name, ""); - _ -> + error -> {error, invalid_package_string} end. --spec dash_split(string()) -> [string()] | error. +-spec dash_split(string()) -> {ok, [string()]} | error. %% @private %% An explicit, strict token split that ensures invalid names with leading, trailing or %% double dashes don't slip through (a problem discovered with using string:tokens/2 %% and string:lexemes/2. -%% Intended only as a helper function for package_id/1 dash_split(String) -> dash_split(String, "", []). @@ -360,7 +359,7 @@ dash_split([Char | Rest], Acc, Elements) -> dash_split(Rest, [Char | Acc], Elements); dash_split("", Acc, Elements) -> Element = lists:reverse(Acc), - lists:reverse([Element | Elements]); + {ok, lists:reverse([Element | Elements])}; dash_split(_, _, _) -> error. @@ -521,3 +520,33 @@ latest_compatible(Version, Versions) -> installed(PackageID) -> filelib:is_dir(package_dir(PackageID)). + + + + +-spec realm_conf(Realm) -> RealmFileName + when Realm :: string(), + RealmFileName :: file:filename(). +%% @private +%% Take a realm name, and return the name of the realm filename that would result. + +realm_conf(Realm) -> + Realm ++ ".realm". + + +-spec load_realm_conf(Realm) -> Result + when Realm :: realm(), + Result :: {ok, RealmConf} + | {error, Reason}, + RealmConf :: list(), + Reason :: badarg + | terminated + | system_limit + | file:posix() + | {Line :: integer(), Mod :: module(), Cause :: term()}. +%% @private +%% Load the config for the given realm or halt with an error. + +load_realm_conf(Realm) -> + Path = filename:join(zx_lib:zomp_home(), realm_conf(Realm)), + file:consult(Path). From 7f352da2f3ca629b7793fd89a8120e7009bea530 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Fri, 26 Jan 2018 19:08:44 +0900 Subject: [PATCH 35/55] =?UTF-8?q?=E3=81=BE=E3=81=A0=E3=81=BE=E3=81=A0?= =?UTF-8?q?=E3=81=A7=E3=81=99=E2=80=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- zomp/lib/otpr-zx/0.1.0/src/zx.erl | 280 ++++++++++++------------------ 1 file changed, 107 insertions(+), 173 deletions(-) diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx.erl b/zomp/lib/otpr-zx/0.1.0/src/zx.erl index f08d944..71332ec 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx.erl @@ -82,16 +82,12 @@ do(["set", "version", VersionString]) -> do(["list", "realms"]) -> list_realms(); do(["list", "packages", Realm]) -> - ok = valid_realm(Realm), list_packages(Realm); do(["list", "versions", PackageName]) -> - Package = string_to_package(PackageName), - list_versions(Package); + list_versions(PackageName); do(["list", "pending", PackageName]) -> - Package = string_to_package(PackageName), - list_pending(Package); + list_pending(PackageName); do(["list", "resigns", Realm]) -> - ok = valid_realm(Realm), list_resigns(Realm); do(["add", "realm", RealmFile]) -> add_realm(RealmFile); @@ -321,10 +317,11 @@ execute(PackageID, Meta, Dir, RunArgs) -> -spec execute(Type, PackageID, Meta, Dir, RunArgs) -> no_return() - when Type :: app | lib, - Meta :: package_meta(), - Dir :: file:filename(), - RunArgs :: [string()]. + when Type :: app | lib, + PackageID :: package_id(), + Meta :: package_meta(), + Dir :: file:filename(), + RunArgs :: [string()]. %% @private %% Gets all the target application's ducks in a row and launches them, then enters %% the exec_wait/1 loop to wait for any queries from the application. @@ -337,10 +334,10 @@ execute(app, PackageID, Meta, Dir, RunArgs) -> ok = zx_daemon:pass_meta(Meta, Dir), ok = ensure_all_started(AppMod), ok = pass_argv(AppMod, RunArgs), - exec_wait(State); + log(info, "Launcher complete."); execute(lib, PackageID, _, _, _) -> Message = "Lib ~ts is available on the system, but is not a standalone app.", - PackageString = package_string(PackageID), + {ok, PackageString} = zx_lib:package_string(PackageID), ok = log(info, Message, [PackageString]), halt(0). @@ -447,7 +444,8 @@ assimilate(PackageFile) -> end, ok = file:set_cwd(CWD), Message = "~ts is now locally available.", - ok = log(info, Message, [package_string(PackageID)]), + {ok, PackageString} = zx_lib:package_string(PackageID), + ok = log(info, Message, [PackageString]), halt(0). @@ -486,7 +484,8 @@ set_dep({Realm, Name}, Version) -> Deps = maps:get(deps, Meta), case lists:member(PackageID, Deps) of true -> - ok = log(info, "~ts is already a dependency", [package_string(PackageID)]), + {ok, PackageString} = zx_lib:package_string(PackageID), + ok = log(info, "~ts is already a dependency", [PackageString]), halt(0); false -> set_dep(PackageID, Deps, Meta) @@ -509,12 +508,13 @@ set_dep(PackageID = {Realm, Name, NewVersion}, Deps, Meta) -> case lists:partition(ExistingPackageIDs, Deps) of {[{Realm, Name, OldVersion}], Rest} -> Message = "Updating dep ~ts to ~ts", - OldPackageString = package_string({Realm, Name, OldVersion}), - NewPackageString = package_string({Realm, Name, NewVersion}), - ok = log(info, Message, [OldPackageString, NewPackageString]), + {ok, OldPS} = zx_lib:package_string({Realm, Name, OldVersion}), + {ok, NewPS} = zx_lib:package_string({Realm, Name, NewVersion}), + ok = log(info, Message, [OldPS, NewPS]), [PackageID | Rest]; {[], Deps} -> - ok = log(info, "Adding dep ~ts", [package_string(PackageID)]), + {ok, PackageString} = zx_lib:package_string(PackageID), + ok = log(info, "Adding dep ~ts", [PackageString]), [PackageID | Deps] end, NewMeta = maps:put(deps, NewDeps, Meta), @@ -620,7 +620,7 @@ set_version(VersionString) -> Name :: name(), OldVersion :: version(), NewVersion :: version(), - OldMeta :: project_meta(). + OldMeta :: package_meta(). %% @private %% Update a project's `zomp.meta' file by either incrementing the indicated component, %% or setting the version number to the one specified in VersionString. @@ -676,27 +676,34 @@ list_packages(Realm) -> error_exit("Realm \"~ts\" is not configured.", ?LINE); {error, network} -> Message = "Network issues are preventing connection to the realm.", - error_exit(Message, ?LINE); + error_exit(Message, ?LINE) end. --spec list_versions(package()) -> no_return(). +-spec list_versions(PackageName :: string()) -> no_return(). %% @private %% List the available versions of the package indicated. The user enters a string-form %% package name (such as "otpr-zomp") and the return values will be full package strings %% of the form "otpr-zomp-1.2.3", one per line printed to stdout. -list_versions(Package) -> +list_versions(PackageName) -> + Package = {Realm, Name} = + case zx_lib:package_id(PackageName) of + {ok, {R, N, {z, z, z}}} -> + {R, N}; + {error, invalid_package_string} -> + error_exit("~tp is not a valid package name.", [PackageName], ?LINE) + end, ok = start(), case zx_daemon:list_versions(Package) of - {ok, []} - Message = "Package ~ts-~ts has no versions available.", - ok = log(info, Message, [Realm, Name]), + {ok, []} -> + Message = "Package ~ts has no versions available.", + ok = log(info, Message, [PackageName]), halt(0); {ok, Versions} -> Print = fun(Version) -> - PackageString = package_string({Realm, Name, Version}), + {ok, PackageString} = zx_lib:package_string({Realm, Name, Version}), io:format("~ts~n", [PackageString]) end, ok = lists:foreach(Print, Versions), @@ -711,23 +718,30 @@ list_versions(Package) -> end. --spec list_pending(package()) -> no_return(). +-spec list_pending(PackageName :: string()) -> no_return(). %% @private %% List the versions of a package that are pending review. The package name is input by %% the user as a string of the form "otpr-zomp" and the output is a list of full %% package IDs, printed one per line to stdout (like "otpr-zomp-3.2.2"). -list_pending(Package) -> +list_pending(PackageName) -> + Package = {Realm, Name} = + case zx_lib:package_id(PackageName) of + {ok, {R, N, {z, z, z}}} -> + {R, N}; + {error, invalid_package_string} -> + error_exit("~tp is not a valid package name.", [PackageName], ?LINE) + end, ok = start(), case zx_daemon:list_pending(Package) of {ok, []} -> - Message = "Package ~ts-~ts has no versions pending.", - ok = log(info, Message, [Realm, Name]), + Message = "Package ~ts has no versions pending.", + ok = log(info, Message, [PackageName]), halt(0); {ok, Versions} -> Print = fun(Version) -> - PackageString = package_string({Realm, Name, Version}), + {ok, PackageString} = zx_lib:package_string({Realm, Name, Version}), io:format("~ts~n", [PackageString]) end, ok = lists:foreach(Print, Versions), @@ -757,7 +771,7 @@ list_resigns(Realm) -> {ok, PackageIDs} -> Print = fun(PackageID) -> - PackageString = package_string(PackageID), + {ok, PackageString} = zx_lib:package_string(PackageID), io:format("~ts~n", [PackageString]) end, ok = lists:foreach(Print, PackageIDs), @@ -824,7 +838,7 @@ add_realm(Path, Data) -> add_package(PackageName) -> ok = file:set_cwd(zx_lib:zomp_home()), case zx_lib:package_id(PackageName) of - {ok, {Realm, Name, {z, z, z}} -> + {ok, {Realm, Name, {z, z, z}}} -> add_package(Realm, Name); _ -> error_exit("~tp is not a valid package name.", [PackageName], ?LINE) @@ -942,7 +956,7 @@ resign(PackageString) -> %% Remove the indicate dependency from the local project's zomp.meta record. drop_dep(PackageID) -> - PackageString = package_string(PackageID), + {ok, PackageString} = zx_lib:package_string(PackageID), {ok, Meta} = zx_lib:read_project_meta(), Deps = maps:get(deps, Meta), case lists:member(PackageID, Deps) of @@ -1138,7 +1152,7 @@ package(KeyID, TargetDir) -> {ok, Meta} = zx_lib:read_project_meta(TargetDir), PackageID = maps:get(package_id, Meta), true = element(1, PackageID) == element(1, KeyID), - PackageString = package_string(PackageID), + {ok, PackageString} = zx_lib:package_string(PackageID), ZrpFile = PackageString ++ ".zrp", TgzFile = PackageString ++ ".tgz", ok = halt_if_exists(ZrpFile), @@ -1302,7 +1316,8 @@ connect_auth(Socket, Realm, User, KeyID, Key) -> ok = binary_to_term(Bin, [safe]), confirm_auth(Socket, Realm, User, KeyID, Key); {tcp_closed, Socket} -> - halt_on_unexpected_close() + ok = log(warning, "Socket closed unexpectedly."), + halt(1) after 5000 -> ok = log(warning, "Host realm ~160tp prime timed out.", [Realm]), {error, auth_timeout} @@ -1340,7 +1355,8 @@ confirm_auth(Socket, Realm, User, KeyID, Key) -> {error, Reason} end; {tcp_closed, Socket} -> - halt_on_unexpected_close() + ok = log(warning, "Socket closed unexpectedly."), + halt(1) after 5000 -> ok = log(warning, "Host realm ~tp prime timed out.", [Realm]), {error, auth_timeout} @@ -1355,7 +1371,8 @@ confirm_auth(Socket) -> Other -> {error, Other} end; {tcp_closed, Socket} -> - halt_on_unexpected_close() + ok = log(warning, "Socket closed unexpectedly."), + halt(1) after 5000 -> {error, timeout} end. @@ -1670,7 +1687,7 @@ loadkey(Type, {Realm, KeyName}) -> P = filename:join([zx_lib:zomp_home(), "key", Realm, KeyDer]), {'RSAPrivateKey', P}; public -> - PubDer = KeyName ++ ".pub.der" + PubDer = KeyName ++ ".pub.der", P = filename:join([zx_lib:zomp_home(), "key", Realm, PubDer]), {'RSAPublicKey', P} end, @@ -1781,17 +1798,6 @@ create_user(Realm, Username) -> %% realm file to the user. create_realm() -> - ConfFile = filename:join(zx_lib:zomp_home(), "zomp.conf"), - case file:consult(ConfFile) of - {ok, ZompConf} -> create_realm(ZompConf); - {error, enoent} -> create_realm([]) - end. - - --spec create_realm(ZompConf) -> no_return() - when ZompConf :: [{Key :: atom(), Value :: term()}]. - -create_realm(ZompConf) -> Instructions = "~n" " Enter a name for your new realm.~n" @@ -1804,29 +1810,23 @@ create_realm(ZompConf) -> RealmFile = filename:join(zx_lib:zomp_home(), Realm ++ ".realm"), case filelib:is_regular(RealmFile) of false -> - create_realm(ZompConf, Realm); + create_realm(Realm); true -> ok = io:format("That realm already exists. Be more original.~n"), - create_realm(ZompConf) + create_realm() end; false -> ok = io:format("Bad realm name \"~ts\". Try again.~n", [Realm]), - create_realm(ZompConf) + create_realm() end. --spec create_realm(ZompConf, Realm) -> no_return() - when ZompConf :: [{Key :: atom(), Value :: term()}], - Realm :: realm(). +-spec create_realm(Realm) -> no_return() + when Realm :: realm(). -create_realm(ZompConf, Realm) -> - ExAddress = - case lists:keyfind(external_address, 1, ZompConf) of - false -> prompt_external_address(); - {external_address, none} -> prompt_external_address(); - {external_address, Current} -> prompt_external_address(Current) - end, - create_realm(ZompConf, Realm, ExAddress). +create_realm(Realm) -> + ExAddress = prompt_external_address(), + create_realm(Realm, ExAddress). -spec prompt_external_address() -> Result @@ -1844,26 +1844,6 @@ prompt_external_address() -> end. --spec prompt_external_address(Current) -> Result - when Current :: inet:hostname() | inet:ip_address(), - Result :: inet:hostname() | inet:ip_address(). - -prompt_external_address(Current) -> - XAString = - case inet:ntoa(Current) of - {error, einval} -> Current; - XAS -> XAS - end, - Message = - external_address_prompt() ++ - " [The current public address is: ~ts. Press to keep this address.]~n", - ok = io:format(Message, [XAString]), - case get_input() of - "" -> Current; - String -> parse_address(String) - end. - - -spec external_address_prompt() -> string(). external_address_prompt() -> @@ -1883,49 +1863,35 @@ parse_address(String) -> end. --spec create_realm(ZompConf, Realm, ExAddress) -> no_return() - when ZompConf :: [{Key :: atom(), Value :: term()}], - Realm :: realm(), +-spec create_realm(Realm, ExAddress) -> no_return() + when Realm :: realm(), ExAddress :: inet:hostname() | inet:ip_address(). -create_realm(ZompConf, Realm, ExAddress) -> - Current = - case lists:keyfind(external_port, 1, ZompConf) of - false -> 11311; - {external_port, none} -> 11311; - {external_port, P} -> P - end, +create_realm(Realm, ExAddress) -> Message = "~n" " Enter the public (external) port number at which this service should be " "available. (This might be different from the local port number if you are " "forwarding ports or have a complex network layout.)~n", ok = io:format(Message), - ExPort = prompt_port_number(Current), - create_realm(ZompConf, Realm, ExAddress, ExPort). + ExPort = prompt_port_number(11311), + create_realm(Realm, ExAddress, ExPort). --spec create_realm(ZompConf, Realm, ExAddress, ExPort) -> no_return() - when ZompConf :: [{Key :: atom(), Value :: term()}], - Realm :: realm(), +-spec create_realm(Realm, ExAddress, ExPort) -> no_return() + when Realm :: realm(), ExAddress :: inet:hostname() | inet:ip_address(), ExPort :: inet:port_number(). -create_realm(ZompConf, Realm, ExAddress, ExPort) -> - Current = - case lists:keyfind(internal_port, 1, ZompConf) of - false -> 11311; - {internal_port, none} -> 11311; - {internal_port, P} -> P - end, +create_realm(Realm, ExAddress, ExPort) -> Message = "~n" " Enter the local (internal/LAN) port number at which this service should be " "available. (This might be different from the public port visible from the " "internet if you are port forwarding or have a complex network layout.)~n", ok = io:format(Message), - InPort = prompt_port_number(Current), - create_realm(ZompConf, Realm, ExAddress, ExPort, InPort). + InPort = prompt_port_number(11311), + create_realm(Realm, ExAddress, ExPort, InPort). -spec prompt_port_number(Current) -> Result @@ -1957,14 +1923,13 @@ prompt_port_number(Current) -> end. --spec create_realm(ZompConf, Realm, ExAddress, ExPort, InPort) -> no_return() - when ZompConf :: [{Key :: atom(), Value :: term()}], - Realm :: realm(), +-spec create_realm(Realm, ExAddress, ExPort, InPort) -> no_return() + when Realm :: realm(), ExAddress :: inet:hostname() | inet:ip_address(), ExPort :: inet:port_number(), InPort :: inet:port_number(). -create_realm(ZompConf, Realm, ExAddress, ExPort, InPort) -> +create_realm(Realm, ExAddress, ExPort, InPort) -> Instructions = "~n" " Enter a username for the realm sysop.~n" @@ -1974,22 +1939,21 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort) -> UserName = get_input(), case zx_lib:valid_lower0_9(UserName) of true -> - create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName); + create_realm(Realm, ExAddress, ExPort, InPort, UserName); false -> ok = io:format("Bad username ~tp. Try again.~n", [UserName]), - create_realm(ZompConf, Realm, ExAddress, ExPort, InPort) + create_realm(Realm, ExAddress, ExPort, InPort) end. --spec create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName) -> no_return() - when ZompConf :: [{Key :: atom(), Value :: term()}], - Realm :: realm(), +-spec create_realm(Realm, ExAddress, ExPort, InPort, UserName) -> no_return() + when Realm :: realm(), ExAddress :: inet:hostname() | inet:ip_address(), ExPort :: inet:port_number(), InPort :: inet:port_number(), UserName :: string(). -create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName) -> +create_realm(Realm, ExAddress, ExPort, InPort, UserName) -> Instructions = "~n" " Enter an email address for the realm sysop.~n" @@ -2001,48 +1965,43 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName) -> [User, Host] = string:lexemes(Email, "@"), case {zx_lib:valid_lower0_9(User), zx_lib:valid_label(Host)} of {true, true} -> - create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email); + create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email); {false, true} -> Message = "The user part of the email address seems invalid. Try again.~n", ok = io:format(Message), - create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName); + create_realm(Realm, ExAddress, ExPort, InPort, UserName); {true, false} -> Message = "The host part of the email address seems invalid. Try again.~n", ok = io:format(Message), - create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName); + create_realm(Realm, ExAddress, ExPort, InPort, UserName); {false, false} -> Message = "This email address seems like its totally bonkers. Try again.~n", ok = io:format(Message), - create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName) + create_realm(Realm, ExAddress, ExPort, InPort, UserName) end. --spec create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email) -> +-spec create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email) -> no_return() - when ZompConf :: [{Key :: atom(), Value :: term()}], - Realm :: realm(), + when Realm :: realm(), ExAddress :: inet:hostname() | inet:ip_address(), ExPort :: inet:port_number(), InPort :: inet:port_number(), UserName :: string(), Email :: string(). -create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email) -> +create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email) -> Instructions = "~n" " Enter the real name (or whatever name people recognize) for the sysop.~n" " There are no rules for this one. Any valid UTF-8 printables are legal.~n", ok = io:format(Instructions), RealName = get_input(), - create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email, RealName). + create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email, RealName). --spec create_realm(ZompConf, Realm, - ExAddress, ExPort, InPort, - UserName, Email, RealName) -> - no_return() - when ZompConf :: [{Key :: atom(), Value :: term()}], - Realm :: realm(), +-spec create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email, RealName) -> no_return() + when Realm :: realm(), ExAddress :: inet:hostname() | inet:ip_address(), ExPort :: inet:port_number(), InPort :: inet:port_number(), @@ -2050,7 +2009,7 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email) -> Email :: string(), RealName :: string(). -create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email, RealName) -> +create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email, RealName) -> ok = io:format("~nGenerating keys. This might take a while, so settle in...~n"), {ok, RealmKey, RealmPub} = generate_rsa({Realm, Realm ++ ".1.realm"}), {ok, PackageKey, PackagePub} = generate_rsa({Realm, Realm ++ ".1.package"}), @@ -2095,9 +2054,6 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email, RealNa {external_port, ExPort}, {internal_port, InPort}], - RealmFN = Realm ++ ".realm", - RealmConf = filename:join(zx_lib:zomp_home(), RealmFN), - ok = zx_lib:write_terms(RealmConf, RealmSettings), {ok, CWD} = file:get_cwd(), {ok, TempDir} = mktemp_dir("zomp"), ok = file:set_cwd(TempDir), @@ -2109,22 +2065,21 @@ create_realm(ZompConf, Realm, ExAddress, ExPort, InPort, UserName, Email, RealNa {ok, _} = file:copy(K, filename:join(KeyDir, filename:basename(K))), ok end, - TarOpts = [compressed, {cwd, TempDir}], + PublicZRF = filename:join(CWD, Realm ++ ".zrf"), + RealmFN = Realm ++ ".realm", ok = zx_lib:write_terms(RealmFN, RealmSettings), ok = KeyCopy(PackagePub), ok = KeyCopy(RealmPub), - PublicZRF = filename:join(CWD, Realm ++ ".zrf"), - Files = filelib:wildcard("**"), - ok = erl_tar:create(PublicZRF, [RealmFN, "key"], TarOpts), + ok = erl_tar:create(PublicZRF, [RealmFN, "key"], [compressed]), + PrimeZRF = filename:join(CWD, Realm ++ ".zpf"), ok = KeyCopy(SysopPub), ok = zx_lib:write_terms("zomp.conf", ZompSettings), - PrimeZRF = filename:join(CWD, Realm ++ ".zpf"), - ok = erl_tar:create(PrimeZRF, [RealmFN, "zomp.conf", "key"], TarOpts), + ok = erl_tar:create(PrimeZRF, [RealmFN, "zomp.conf", "key"], [compressed]), - ok = file:set_cwd(zx_lib:zomp_home()), KeyBundle = filename:join(CWD, Realm ++ ".zkf"), + ok = lists:foreach(KeyCopy, [PackageKey, RealmKey, SysopKey]), ok = erl_tar:create(KeyBundle, [KeyDir], [compressed]), ok = file:set_cwd(CWD), @@ -2225,7 +2180,7 @@ create_sysop() -> %% - If this function crashes it will completely halt the system install(PackageID) -> - PackageString = package_string(PackageID), + {ok, PackageString} = zx_lib:package_string(PackageID), ok = log(info, "Installing ~ts", [PackageString]), ZrpFile = filename:join("zrp", zx_lib:namify_zrp(PackageID)), Files = extract_zrp_or_die(ZrpFile), @@ -2412,36 +2367,15 @@ rm_rf(Path) -> end. --spec ensure_zomp_home() -> ok. +-spec rm(file:filename()) -> ok | {error, file:posix()}. %% @private -%% Ensure the zomp home directory exists and is populated. -%% Every entry function should run this initially. +%% An omnibus delete helper. -ensure_zomp_home() -> - ZompDir = zx_lib:zomp_home(), - case filelib:is_dir(ZompDir) of - true -> ok; - false -> setup(ZompDir) - end. - - --spec setup(ZompDir :: file:filename()) -> ok. - -setup(ZompDir) -> - {ok, CWD} = file:get_cwd(), - ok = force_dir(ZompDir), - ok = file:set_cwd(ZompDir), - SubDirs = ["tmp", "key", "var", "lib", "zrp", "etc"], - ok = lists:foreach(fun file:make_dir/1, SubDirs), - ok = setup_otpr(), - ok = log(info, "Zomp userland directory initialized."), - file:set_cwd(CWD). - - --spec setup_otpr() -> ok. - -setup_otpr() -> - log(info, "Here should pull otpr.0.zrf and install it..."). +rm(Path) -> + case filelib:is_dir(Path) of + true -> file:del_dir(Path); + false -> file:delete(Path) +end. -spec ensure_package_dirs(package_id()) -> ok. From 71e31c48b23b0ba9d98e959d1f3df0dec8d8b4ed Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Tue, 6 Feb 2018 22:56:19 +0900 Subject: [PATCH 36/55] Playing with connectivity ideas --- zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl | 276 +++++++++++---------- zomp/lib/otpr-zx/0.1.0/src/zx_conn_sup.erl | 9 +- zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl | 115 +++++++-- zomp/lib/otpr-zx/0.1.0/src/zx_lib.erl | 11 +- zomp/lib/otpr-zx/0.1.0/src/zx_net.erl | 68 +++++ 5 files changed, 319 insertions(+), 160 deletions(-) create mode 100644 zomp/lib/otpr-zx/0.1.0/src/zx_net.erl diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl index ccd3ab4..f7d243e 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl @@ -11,7 +11,7 @@ -copyright("Craig Everett "). -license("GPL-3.0"). --export([start/1, stop/0]). +-export([start/1, stop/1]). -export([start_link/1]). -include("zx_logger.erl"). @@ -25,18 +25,41 @@ Result :: {ok, pid()} | {error, Reason}, Reason :: term(). +%% @doc +%% Starts a connection to a given target Zomp node. This call itself should never fail, +%% but this process may fail to connect or crash immediately after spawning. Should +%% only be called by zx_daemon. start(Target) -> zx_conn_sup:start_conn(Target). +-spec stop(Conn :: pid()) -> ok. +%% @doc +%% Signals the connection to disconnect and retire immediately. + +stop(Conn) -> + Conn ! stop, + ok. + + +-spec subscribe(Conn, Realm) -> ok + when Conn :: pid(), + Realm :: zx:realm(), + Result :: ok. + +subscribe(Conn, Realm) -> + Conn ! {subscribe, Realm}, + ok. + + -spec start_link(Target) -> when Target :: zx:host(), Result :: {ok, pid()} | {error, Reason}, Reason :: term(). %% @private -%% Starts a connector with a target host in its state. +%% The supervisor's way of spawning a new connector. start_link(Target) -> proc_lib:start_link(?MODULE, init, [self(), Target]). @@ -45,6 +68,8 @@ start_link(Target) -> -spec init(Parent, Target) -> no_return() when Parent :: pid(), Target :: zx:host(). +%% @private +%% gen_server callback. For more information refer to the OTP documentation. init(Parent, Target) -> ok = log(info, "Connecting to ~tp", [Target]), @@ -53,163 +78,133 @@ init(Parent, Target) -> connect(Parent, Debug, Target). --spec connect(Parent, Debug, Target) -> no_return(). + +%%% Connection Procedure + +-spec connect(Parent, Debug, Target) -> no_return() + when Parent :: pid(), + Debug :: [sys:dbg_opt()], + Target :: zx:host(). connect(Parent, Debug, {Host, Port}) -> Options = [{packet, 4}, {mode, binary}, {active, true}], case gen_tcp:connect(Host, Port, Options, 5000) of {ok, Socket} -> - confirm(Parent, Debug, Socket); + confirm_service(Parent, Debug, Socket); {error, Error} -> ok = log(warning, "Connection problem with ~tp: ~tp", [Node, Error]), - ok = zx_daemon:report( - connect_user(Realm, Rest) + ok = zx_daemon:report(failed) + terminate() end. -confirm(Parent, Debug, Socket) -> - - --spec connect_user(realm()) -> gen_tcp:socket() | no_return(). -%% @private -%% Connect to a given realm, whatever method is required. - -connect_user(Realm) -> - ok = log(info, "Connecting to realm ~ts...", [Realm]), - Hosts = - case file:consult(zx_lib:hosts_cache_file(Realm)) of - {ok, Cached} -> Cached; - {error, enoent} -> [] - end, - connect_user(Realm, Hosts). - - --spec connect_user(realm(), [host()]) -> gen_tcp:socket() | no_return(). -%% @private -%% Try to connect to a subordinate host, if there are none then connect to prime. - -connect_user(Realm, []) -> - {Host, Port} = zx_lib:get_prime(Realm), - HostString = - case io_lib:printable_unicode_list(Host) of - true -> Host; - false -> inet:ntoa(Host) - end, - ok = log(info, "Trying prime at ~ts:~160tp", [HostString, Port]), - case gen_tcp:connect(Host, Port, connect_options(), 5000) of - {ok, Socket} -> - confirm_user(Realm, Socket, []); - {error, Error} -> - ok = log(warning, "Connection problem with prime: ~tp", [Error]), - halt(0) - end; -connect_user(Realm, Hosts = [Node = {Host, Port} | Rest]) -> - ok = log(info, "Trying node at ~ts:~tp", [inet:ntoa(Host), Port]), - case gen_tcp:connect(Host, Port, connect_options(), 5000) of - {ok, Socket} -> - confirm_user(Realm, Socket, Hosts); - {error, Error} -> - ok = log(warning, "Connection problem with ~tp: ~tp", [Node, Error]), - connect_user(Realm, Rest) - end. - - --spec confirm_user(Realm, Socket, Hosts) -> Socket | no_return() - when Realm :: realm(), - Socket :: gen_tcp:socket(), - Hosts :: [host()]. +-spec confirm_service(Parent, Debug, Socket) -> no_return() + when Parent :: pid(), + Debug :: [sys:dbg_opt()], + Socket :: gen_tcp:socket(). %% @private %% Confirm the zomp node can handle "OTPR USER 1" and is accepting connections or try %% another node. -confirm_user(Realm, Socket, Hosts) -> - {ok, {Addr, Port}} = inet:peername(Socket), - Host = inet:ntoa(Addr), +confirm_service(Parent, Debug, Socket) -> ok = gen_tcp:send(Socket, <<"OTPR USER 1">>), receive {tcp, Socket, Bin} -> - case binary_to_term(Bin) of + case binary_to_term(Bin, [safe]) of ok -> - ok = log(info, "Connected to ~ts:~p", [Host, Port]), - confirm_serial(Realm, Socket, Hosts); - {redirect, Next} -> - ok = log(info, "Redirected..."), - ok = disconnect(Socket), - connect_user(Realm, Next ++ Hosts) + query_realms(Parent, Debug, Socket); + {redirect, Hosts} -> + ok = zx_daemon:report({redirect, Hosts}), + ok = zx_net:disconnect(Socket), + terminate() end; {tcp_closed, Socket} -> - halt_on_unexpected_close() + handle_unexpected_close() after 5000 -> - ok = log(warning, "Host ~ts:~p timed out.", [Host, Port]), - ok = disconnect(Socket), - connect_user(Realm, Hosts) + handle_timeout(Socket) end. --spec confirm_serial(Realm, Socket, Hosts) -> Socket | no_return() - when Realm :: realm(), - Socket :: gen_tcp:socket(), - Hosts :: [host()]. +-spec query_realms(Parent, Debug, Socket) -> no_return() + when Parent :: pid(), + Debug :: [sys:dbg_opt()], + Socket :: gen_tcp:socket(). %% @private %% Confirm that the connected host has a valid serial for the realm zx is trying to %% reach, and if not retry on another node. -confirm_serial(Realm, Socket, Hosts) -> - SerialFile = filename:join(zx_lib:zomp_home(), "realm.serials"), - Serials = - case file:consult(SerialFile) of - {ok, Ss} -> Ss; - {error, enoent} -> [] - end, - Serial = - case lists:keyfind(Realm, 1, Serials) of - false -> 0; - {Realm, S} -> S - end, - ok = send(Socket, {latest, Realm}), +query_realms(Parent, Debug, Socket) -> + ok = zx_net:send(Socket, list), receive {tcp, Socket, Bin} -> - case binary_to_term(Bin) of - {ok, Serial} -> - ok = log(info, "Node's serial same as ours."), - Socket; - {ok, Current} when Current > Serial -> - ok = log(info, "Node's serial newer than ours. Storing."), - NewSerials = lists:keystore(Realm, 1, Serials, {Realm, Current}), - {ok, Host} = inet:peername(Socket), - CacheFile = zx_lib:hosts_cache_file(Realm), - ok = zx_lib:write_terms(CacheFile, [Host | Hosts]), - ok = zx_lib:write_terms(SerialFile, NewSerials), - Socket; - {ok, Current} when Current < Serial -> - log(info, "Our serial: ~tp, node serial: ~tp.", [Serial, Current]), - ok = log(info, "Node's serial older than ours. Trying another."), - ok = disconnect(Socket), - connect_user(Realm, Hosts); - {error, bad_realm} -> - ok = log(info, "Node is no longer serving realm. Trying another."), - ok = disconnect(Socket), - connect_user(Realm, Hosts) - end; + {ok, Realms} = binary_to_term(Bin, [safe]), + ok = zx_daemon:report({connected, Realms}), + loop(Parent, Debug, Socket); {tcp_closed, Socket} -> - halt_on_unexpected_close() + handle_unexpected_close() after 5000 -> - ok = log(info, "Host timed out on confirm_serial. Trying another."), - ok = disconnect(Socket), - connect_user(Realm, Hosts) + handle_timeout(Socket) end. - - - --spec halt_on_unexpected_close() -> no_return(). - -halt_on_unexpected_close() -> - ok = log(warning, "Socket closed unexpectedly."), - halt(1). +%%% Service Loop +-spec loop(Parent, Debug, Socket) -> no_return() + when Parent :: pid(), + Debug :: [sys:dbg_opt()], + Socket :: gen_tcp:socket(). +%% @private +%% Service loop. Messages incoming from the connected Zomp node, the zx_daemon, and +%% OTP system messages all come here. This is the only catch-all receive loop, so +%% messages that occur in a specific state must not be accidentally received here out +%% of order or else whatever sequenced communication was happening will be corrupted. + +loop(Parent, Debug, Socket) -> + receive + {tcp, Socket, Bin} -> + ok = handle(Bin, Socket), + ok = inet:setopts(Socket, [{active, once}]), + loop(Parent, Debug, Socket); + stop -> + ok = zx_net:disconnect(Socket), + terminat(); + Unexpected -> + ok = log(warning, "Unexpected message: ~tp", [Unexpected]), + loop(Parent, Debug, Socket) + end. + + +-spec handle(Bin, Socket) -> ok | no_return() + when Bin :: binary(), + Socket :: gen_tcp:socket(). +%% @private +%% Single point to convert a binary message to a safe internal message. Actual handling +%% of the converted message occurs in dispatch/2. + +handle(Bin, Socket) -> + Message = binary_to_term(Bin, [safe]), + ok = log(info, "Received network message: ~tp", [Message]), + dispatch(Message, Socket). + + +-spec dispatch(Message, Socket) -> ok | no_return() + when Message :: incoming(), + Socket :: gen_tcp:socket(). +%% @private +%% Dispatch a procedure based on the received message. +%% Tranfers and other procedures that involve a sequence of messages occur in discrete +%% states defined in other functions -- this only dispatches based on a valid initial +%% message received in the default waiting-loop state. + +dispatch(ping, Socket) -> + zx_net:send(Socket, pong); +dispatch(Invalid, Socket) -> + {ok, {Addr, Port}} = zomp:peername(Socket), + Host = inet:ntoa(Addr), + ok = log(warning, "Invalid message from ~tp:~p: ", [Invalid]), + ok = zx_net:disconnect(Socket), + terminate(). -spec fetch(Socket, PackageID) -> Result @@ -232,7 +227,7 @@ fetch(Socket, PackageID) -> | {error, Reason :: timeout | term()}. request_zrp(Socket, PackageID) -> - ok = send(Socket, {fetch, PackageID}), + ok = zx_net:send(Socket, {fetch, PackageID}), receive {tcp, Socket, Bin} -> case binary_to_term(Bin) of @@ -245,7 +240,7 @@ request_zrp(Socket, PackageID) -> Error end; {tcp_closed, Socket} -> - halt_on_unexpected_close() + handle_unexpected_close() after 60000 -> {error, timeout} end. @@ -261,11 +256,40 @@ receive_zrp(Socket, PackageID) -> {tcp, Socket, Bin} -> ZrpPath = filename:join("zrp", zx_lib:namify_zrp(PackageID)), ok = file:write_file(ZrpPath, Bin), - ok = send(Socket, ok), + ok = zx_net:send(Socket, ok), log(info, "Wrote ~ts", [ZrpPath]); {tcp_closed, Socket} -> - halt_on_unexpected_close() + handle_unexpected_close() after 60000 -> ok = log(error, "Timeout in socket receive for ~tp", [PackageID]), {error, timeout} end. + + + +%%% Terminal handlers + +-spec handle_unexpected_close() -> no_return(). + +handle_unexpected_close() -> + ok = zx_daemon:report(disconnected), + terminate(). + + +-spec handle_timeout(gen_tcp:socket()) -> no_return() + +handle_timeout(Socket) -> + ok = zx_daemon:report(timeout), + ok = disconnect(Socket), + terminate(). + + +-spec terminate() -> no_return(). +%% @private +%% Convenience wrapper around the suicide call. +%% In the case that a more formal retirement procedure is required, consider notifying +%% the supervisor with `supervisor:terminate_child(zomp_client_sup, PID)' and writing +%% a proper system_terminate/2. + +terminate() -> + exit(normal). diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_conn_sup.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_conn_sup.erl index 7efd8cd..f21b163 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx_conn_sup.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_conn_sup.erl @@ -10,7 +10,7 @@ -copyright("Craig Everett "). -license("GPL-3.0"). --export([start_conn/1]). +-export([start_conn/2]). -export([start_link/0]). -export([init/1]). @@ -18,8 +18,9 @@ %%% Interface Functions --spec start_conn(Host) -> Result +-spec start_conn(Host, Serial) -> Result when Host :: zx:host(), + Serial :: zx:serial(), Result :: {ok, pid()} | {error, Reason}, Reason :: term(). @@ -27,8 +28,8 @@ %% Start an upstream connection handler. %% (Should only be called from zx_conn). -start_conn(Host) -> - supervisor:start_child(?MODULE, [Host]). +start_conn(Host, Serial) -> + supervisor:start_child(?MODULE, [Host, Serial]). diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl index d7efa4c..beeb489 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl @@ -3,15 +3,54 @@ %%% %%% Resident execution daemon and runtime interface to Zomp. %%% -%%% The daemon lives in the system and does background tasks and also acts as the -%%% serial interface for any complex functions involving network tasks that may fail -%%% and need to be retried or may span realms. +%%% The daemon lives in the background once started and awaits action requests from +%%% callers running within the system. The daemon is only capable of handling +%%% unprivileged (user) actions such as querying a Zomp node or fetching packages. %%% -%%% In particular, the functions accessible to programs launched by ZX can interact -%%% with Zomp realms via the zx_daemon, and non-administrative tasks that involve -%%% maintaining a connection with a Zomp constellation can be abstracted behind the -%%% zx_daemon. Administrative tasks, however, essentially stateless request/response -%%% pairs. +%%% +%%% Connection handling +%%% +%%% The daemon is structured as a service manager in a service -> worker structure. +%%% http://zxq9.com/archives/1311 +%%% It is in charge of the high-level task of servicing requested actions and returning +%%% responses to callers as well as mapping successful connections to configured realms +%%% and repairing failed connections to various realms by searching for and directing +%%% that connections be made to various realms to satisfy action request requirements. +%%% +%%% When the zx_daemon is started it checks local configuration and cache files to +%%% determine what realms must be found and what cached Zomp nodes it is aware of. +%%% It populates an internal record #hx{} (typed as host_index()) with realm config +%%% and host cache data and then immediately initiates three connection attempts to +%%% cached nodes for each realm configured. If a host is known to service more than +%%% one configured realm only one attempt will be made at a time to connect to it. +%%% If all cached hosts for a given realm have been tried already, or if none are +%%% known, then the daemon will direct a connection be made to the prime node. +%%% +%%% Once the connection attempts have been initiated (via zx_conn:start/1) the daemon +%%% waits in receive for either a connection report from a connection or an action +%%% request from elsewhere in the system. +%%% +%%% A connection request is made with a call to report/1 and indicates to the daemon +%%% whether a connection has failed, been disconneocted, redirected, or succeeded. +%%% Connection handling is as follows: +%%% - A failure can occur at any time. In the event a connected and assigned zx_conn +%%% has failed (whether it was connected and assigned, or never succeeded at all) the +%%% target host will be dropped from the hosts cache and another attempt will be made +%%% in its place if other hosts are known. +%%% - If a connection is disconnected then the host will be placed at the back of the +%%% hosts cache. +%%% - If a connection is redirected then the redirecting host will be placed at the +%%% back of the hosts cache and the list of new Zomp nodes provided by the redirect +%%% will be added at the front of the connect queue. +%%% - In the event a connection succeeds then the list of provided realms and their +%%% current serials will be compared to the list of known realms and serials, and +%%% the host will be added to the relevant realm host index if not already present +%%% and the provided serial is newer than the currently known one (but the realm +%%% serial will not be updated at this point, only the host added). After the +%%% host's record is updated across the realm indices the daemon will assign it to +%%% whatever realms it provides that are not yet services by a connection, and in +%%% the case it does not service any required and unassigned realms it will be +%%% instructed to disconnect. %%% @end -module(zx_daemon). @@ -37,21 +76,25 @@ %%% Type Definitions -record(s, - {meta = none :: none | zx:package_meta(), - dir = none :: none | file:filename(), - argv = none :: none | [string()], - reqp = none :: none | pid(), - reqm = none :: none | reference(), - connp = none :: none | pid(), - connm = none :: none | reference(), - prime = none :: none | zx:realm(), - hosts = [] :: #s{zx:realm() := [zx:host()]}}). + {meta = none :: none | zx:package_meta(), + home = none :: none | file:filename(), + argv = none :: none | [string()], + reqp = none :: none | pid(), + reqm = none :: none | reference(), + actions = queue:new() :: queue:queue(action()), + realms = #{} :: #{zx:realm() := zx:serial()}, + primes = #{} :: #{zx:realm() := zx:host()}, + hosts = #{} :: #{zx:realm() := [zx:host()]}, + conns = [] :: [{pid(), reference()}]}). + -type state() :: #s{}. --type hosts() :: #{zx:realm() := [zx:host()]}. --type conn_report() :: {connected, Realms :: [zx:realm()]} - | conn_fail +-type action() :: {subscribe, zx:package()}, + | unsubscribe + | {list, +-type conn_report() :: {connected, Realms :: [{zx:realm(), zx:serial()}]} + | failed | disconnected. @@ -175,12 +218,13 @@ fetch(PackageIDs) -> %%% Connection interface -spec report(Message) -> ok - when Message :: {connected, Realms :: [zx:realm()]} - | conn_fail + when Message :: {connected, Realms :: [{zx:realm(), zx:serial()}]} + | {redirect, Hosts :: [{zx:host(), [zx:realm()]}]} + | failed | disconnected. %% @private %% Should only be called by a zx_conn. This function is how a zx_conn reports its -%% current connection status. +%% current connection status and job results. report(Message) -> gen_server:cast(?MODULE, {report, self(), Message}). @@ -199,7 +243,21 @@ start_link() -> -spec init(none) -> {ok, state()}. init(none) -> - {ok, #s{}}. + SerialFile = filename:join(zx_lib:zomp_home(), "realm.serials"), + Serials = + case file:consult(SerialFile) of + {ok, Ss} -> + maps:from_list(Ss); + {error, enoent} -> + ok = log(info, "Initializing zomp/realm.serials..."), + maps:new(); + {error, Reason} -> + Message = "Reading zomp/realm.serials failed with ~tp. Recreating..." + ok = log(error, Message, [Reason]), + maps:new() + end, + State = #s{serials = Serials}, + {ok, State}. @@ -291,9 +349,15 @@ do_pass_meta(Meta, Dir, ArgV, State) -> do_subscribe(Requestor, {Realm, Name}, - State = #s{name = none, connp = none, reqp = none, hosts = Hosts}) -> + State = #s{name = none, connp = none, reqp = none, + hosts = Hosts, serials = Serials}) -> Monitor = monitor(process, Requestor), {Host, NewHosts} = select_host(Realm, Hosts), + Serial = + case lists:keyfind(Realm, 1, Serials) of + false -> 0; + {Realm, S} -> S + end, {ok, ConnP} = zx_conn:start(Host), ConnM = monitor(process, ConnP), NewState = State#s{realm = Realm, name = Name, @@ -378,6 +442,7 @@ do_unsubscribe(State = #s{connp = ConnP, connm = ConnM}) -> NewState :: state(). do_report(From, {connected, Realms}, State = #s{ + diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_lib.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_lib.erl index 315a2fb..41e621e 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx_lib.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_lib.erl @@ -25,7 +25,8 @@ package_id/1, package_string/1, package_dir/1, package_dir/2, namify_zrp/1, namify_tgz/1, - find_latest_compatible/2, installed/1]). + find_latest_compatible/2, installed/1, + realm_conf/1, load_realm_conf/1]). -include("zx_logger.hrl"). @@ -445,7 +446,7 @@ package_dir(Prefix, {Realm, Name}) -> -spec namify_zrp(PackageID) -> ZrpFileName - when PackageID :: package_id(), + when PackageID :: zx:package_id(), ZrpFileName :: file:filename(). %% @private %% Map an PackageID to its correct .zrp package file name. @@ -454,7 +455,7 @@ namify_zrp(PackageID) -> namify(PackageID, "zrp"). -spec namify_tgz(PackageID) -> TgzFileName - when PackageID :: package_id(), + when PackageID :: zx:package_id(), TgzFileName :: file:filename(). %% @private %% Map an PackageID to its correct gzipped tarball source bundle filename. @@ -463,7 +464,7 @@ namify_tgz(PackageID) -> namify(PackageID, "tgz"). -spec namify(PackageID, Suffix) -> FileName - when PackageID :: package_id(), + when PackageID :: zx:package_id(), Suffix :: string(), FileName :: file:filename(). %% @private @@ -535,7 +536,7 @@ realm_conf(Realm) -> -spec load_realm_conf(Realm) -> Result - when Realm :: realm(), + when Realm :: zx:realm(), Result :: {ok, RealmConf} | {error, Reason}, RealmConf :: list(), diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_net.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_net.erl new file mode 100644 index 0000000..ee67951 --- /dev/null +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_net.erl @@ -0,0 +1,68 @@ +%%% @doc +%%% ZX Network Functions +%%% +%%% A few common network functions concentrated in one place. +%%% @end + +-module(zx_net). +-author("Craig Everett "). +-copyright("Craig Everett "). +-license("GPL-3.0"). + +-export([send/2, disconnect/1]). + +-include("zx_logger.hrl"). + + +-spec send(Socket, Message) -> Result + when Socket :: gen_tcp:socket(), + Message :: term(), + Result :: ok + | {error, Reason}, + Reason :: closed | inet:posix(). +%% @doc +%% Packages an Erlang term and sends it to the indicated socket. + +send(Socket, Message) -> + BinMessage = term_to_binary(Message), + gen_tcp:send(Socket, BinMessage). + + +-spec disconnect(Socket) -> ok + when Socket :: gen_tcp:socket(). +%% @doc +%% Disconnects from a socket, handling the case where the socket is already +%% disconnected on the other side. + +disconnect(Socket) -> + case zomp:peername(Socket) of + {ok, {Addr, Port}} -> + Host = inet:ntoa(Addr), + disconnect(Socket, Host, Port); + {error, Reason} -> + log(warning, "Disconnect failed with: ~p", [Reason]) + end. + + +-spec disconnect(Socket, Host, Port) -> ok + when Socket :: gen_tcp:socket(), + Host :: string(), + Port :: inet:port_number(). + +disconnect(Socket, Host, Port) -> + case gen_tcp:shutdown(Socket, read_write) of + ok -> + log(info, "~ts:~w disconnected", [Host, Port]); + {error, enotconn} -> + log(info, "~ts:~w disconnected", [Host, Port]), + receive + {tcp_closed, Socket} -> ok + after 0 -> ok + end; + {error, E} -> + log(warning, "~ts:~w disconnect failed with: ~p", [Host, Port, E]), + receive + {tcp_closed, Socket} -> ok + after 0 -> ok + end + end. From 9aea2d189b4e8c71506a5faebc2f7c38aa3e6b67 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Wed, 7 Feb 2018 19:37:45 +0900 Subject: [PATCH 37/55] Moving connection index into ADT. For the lulz. --- zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl | 131 +++++++++++++++++++++-- 1 file changed, 123 insertions(+), 8 deletions(-) diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl index beeb489..495a0dd 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl @@ -19,13 +19,19 @@ %%% %%% When the zx_daemon is started it checks local configuration and cache files to %%% determine what realms must be found and what cached Zomp nodes it is aware of. -%%% It populates an internal record #hx{} (typed as host_index()) with realm config +%%% It populates an internal record #cx{} (typed as conn_index()) with realm config %%% and host cache data and then immediately initiates three connection attempts to %%% cached nodes for each realm configured. If a host is known to service more than %%% one configured realm only one attempt will be made at a time to connect to it. %%% If all cached hosts for a given realm have been tried already, or if none are %%% known, then the daemon will direct a connection be made to the prime node. %%% +%%% The conn_index() type is abstract across the module, handled expicitly via use +%%% of manipulation functions called cx_*. The details of index manipulation can +%%% easily litter the code with incidental complexity (as far as a reader is concerned) +%%% so hiding that as abstract data leaves more mental cycles to consider the goals +%%% of the program. +%%% %%% Once the connection attempts have been initiated (via zx_conn:start/1) the daemon %%% waits in receive for either a connection report from a connection or an action %%% request from elsewhere in the system. @@ -36,7 +42,7 @@ %%% - A failure can occur at any time. In the event a connected and assigned zx_conn %%% has failed (whether it was connected and assigned, or never succeeded at all) the %%% target host will be dropped from the hosts cache and another attempt will be made -%%% in its place if other hosts are known. +%%% in its place. %%% - If a connection is disconnected then the host will be placed at the back of the %%% hosts cache. %%% - If a connection is redirected then the redirecting host will be placed at the @@ -51,6 +57,24 @@ %%% whatever realms it provides that are not yet services by a connection, and in %%% the case it does not service any required and unassigned realms it will be %%% instructed to disconnect. +%%% +%%% Because the daemon always initiates connection attempts on startup success or +%%% failure messages are guaranteed to be received without any need for a timer. For +%%% that reason there is no timed re-inspection mechanism present in this module. +%%% +%%% Action requests are queued within the zx_daemon, so requests to download a package, +%%% for example, look the same as several requests to download several packages. Each +%%% request that requires dispatching to a zx_conn is held in the active action slot +%%% until complete, paired with the pid of the zx_conn handling the action. If a +%%% zx_conn dies before completing an action or between the time an action request is +%%% received by the daemon and dispatch to the zx_conn occurs then the daemon will +%%% receive the terminal monitor message and be able to put the pending action back +%%% into the action queue, re-establish a connection to the necessary realm, and then +%%% re-dispatch the action to the new zx_conn. +%%% +%%% A bit of state handling is required (queueing requests and storing the current +%%% action state), but this permits the system above the daemon to interact with it in +%%% a blocking way, but zx_daemon and zx_conn to work asynchronously with one another. %%% @end -module(zx_daemon). @@ -81,18 +105,109 @@ argv = none :: none | [string()], reqp = none :: none | pid(), reqm = none :: none | reference(), + action = none :: none | action(), actions = queue:new() :: queue:queue(action()), - realms = #{} :: #{zx:realm() := zx:serial()}, - primes = #{} :: #{zx:realm() := zx:host()}, - hosts = #{} :: #{zx:realm() := [zx:host()]}, - conns = [] :: [{pid(), reference()}]}). - + cx = #cx{} :: conn_index()}). + + +-record(cx, + {realms = #{} :: #{zx:realm() := zx:serial()}, + primes = #{} :: #{zx:realm() := zx:host()}, + hosts = #{} :: #{zx:realm() := queue:queue(zx:host())}, + conns = #{} :: #{zx:realm() := pid()}, + attempts = #{} :: #{pid() := zx:host()}, + zx_conns = sets:new() :: sets:set({pid(), reference()})}). + +-spec cx_connected(Available, Conn, CX) -> Result + when Available :: [{zx:realm(), zx:serial()}], + Conn :: pid(), + CX :: conn_index(), + Result :: {Assignment, NewCX}, + Assignment :: assigned | unassigned, + NewCX :: conn_index(). +%% @private +%% An abstract data handler which is called whenever a new connection is successfully +%% established by a zx_conn. Any unconnected realms with a valid serial will be +%% assigned to the new connection; if none are needed then the connection is closed. +%% The successful host is placed back in the hosts queue for each available realm. +%% The return value is a tuple that indicates whether the new connection was assigned +%% or not and the updated CX data value. + +cx_connected(Available, Conn, CX) -> + cx_connected(unassigned, Available, Conn, CX). + + +cx_connected(A, [{Realm, Serial} | Rest], Conn, CX = #cx{realms = Realms}) -> + case maps:find(Realm, Realms) of + {ok, S} when S < Serial -> + NewRealms = maps:update(Realm, Serial, Realms), + {NewA, NewCX} = cx_assign(A, Conn, Realm, CX#cx{realms = NewRealms}), + cx_connected(NewA, Rest, Conn, NewCX); + {ok, S} when S == Serial -> + {NewA, NewCX} = cx_assign(A, Conn, Realm, CX), + cx_connected(NewA, Rest, Conn, NewCX); + {ok, S} when S > Serial -> + cx_connected(A, Rest, Conn, CX); + error -> + cx_connected(A, Rest, Conn, CX) + end; +cx_connected(A, [], Conn, CX = #cx{attempts = Attempts}) -> + NewCX = CX#cx{attempts = maps:remove(Conn, Attempts)}, + {A, NewCX}. + + +cx_assign(A, Conn, Realm, CX = #cx{hosts = Hosts, conns = Conns, attempts = Attempts}) -> + Host = maps:get(Conn, Attempts), + Enqueue = fun(Q) -> queue:in(Host, Q) end, + NewHosts = maps:update_with(Realm, Enqueue, Hosts), + case maps:is_key(Realm, Conns) of + true -> + {A, CX#cx{hosts = NewHosts}}; + false -> + NewConns = maps:put(Realm, Conn, Conns), + {assigned, CX#cx{hosts = NewHosts, conns = NewConns}} + end. + + +-spec cx_disconnect(Conn, CX) -> NewCX + +cx_disconnected(Conn, CX) -> + + +-spec cx_failed(Conn, CX) -> NewCX + +cx_failed(Conn, CX) -> + + +-spec cx_next(Realm, CX) -> + +cx_next(Realm, CX) -> + + +-spec cx_resolve(Realm, CX) -> Conn + +cx_resolve(Realm, CX) -> + + -type state() :: #s{}. +-type conn_index() :: #cx{}. -type action() :: {subscribe, zx:package()}, | unsubscribe - | {list, + | {list, zx:realm()} + | {list, zx:realm(), zx:name()} + | {list, zx:realm(), zx:name(), zx:version()} + | {latest, zx:realm()} + | {latest, zx:realm(), zx:name()} + | {latest, zx:realm(), zx:name(), zx:version()} + | {fetch, zx:package_id()} + | {key, zx:key_id()} + | {pending, zx:package()} + | {packagers, zx:package()} + | {maintainers, zx:package()} + | sysops + | {subscribe, zx:realm(), zx:name()}. -type conn_report() :: {connected, Realms :: [{zx:realm(), zx:serial()}]} | failed | disconnected. From e5308bbad051399d027c648091deb71178fdf2fb Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Tue, 13 Feb 2018 09:59:30 +0900 Subject: [PATCH 38/55] foo --- zomp/lib/otpr-zx/0.1.0/src/zx.erl | 4 +- zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl | 16 +- zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl | 554 +++++++++++++++++------ zomp/otpr.realm | 2 - 4 files changed, 442 insertions(+), 134 deletions(-) diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx.erl b/zomp/lib/otpr-zx/0.1.0/src/zx.erl index 71332ec..4d10cf2 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx.erl @@ -53,7 +53,9 @@ -type username() :: label(). -type lower0_9() :: [$a..$z | $0..$9 | $_]. -type label() :: [$a..$z | $0..$9 | $_ | $- | $.]. --type package_meta() :: map(). +-type package_meta() :: #{package_id := package_id(), + deps := [package_id()], + type := app | lib,}. diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl index f7d243e..efad4ba 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl @@ -11,7 +11,7 @@ -copyright("Craig Everett "). -license("GPL-3.0"). --export([start/1, stop/1]). +-export([start_monitor/1, stop/1]). -export([start_link/1]). -include("zx_logger.erl"). @@ -20,9 +20,9 @@ %%% Startup --spec start(Target) -> Result +-spec start_monitor(Target) -> Result when Target :: zx:host(), - Result :: {ok, pid()} + Result :: {ok, PID :: pid(), Mon :: reference()} | {error, Reason}, Reason :: term(). %% @doc @@ -30,8 +30,14 @@ %% but this process may fail to connect or crash immediately after spawning. Should %% only be called by zx_daemon. -start(Target) -> - zx_conn_sup:start_conn(Target). +start_monitor(Target) -> + case zx_conn_sup:start_conn(Target) of + {ok, Pid} -> + Mon = monitor(process, Pid), + {ok, Pid, Mon}; + Error -> + Error + end. -spec stop(Conn :: pid()) -> ok. diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl index 495a0dd..2b0dc65 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl @@ -100,100 +100,39 @@ %%% Type Definitions -record(s, - {meta = none :: none | zx:package_meta(), - home = none :: none | file:filename(), - argv = none :: none | [string()], - reqp = none :: none | pid(), - reqm = none :: none | reference(), - action = none :: none | action(), - actions = queue:new() :: queue:queue(action()), - cx = #cx{} :: conn_index()}). + {meta = none :: none | zx:package_meta(), + home = none :: none | file:filename(), + argv = none :: none | [string()], + reqp = none :: none | pid(), + reqm = none :: none | reference(), + action = none :: none | action(), + actions = queue:new() :: queue:queue(action()), + cx = cx_load() :: conn_index()}). -record(cx, - {realms = #{} :: #{zx:realm() := zx:serial()}, - primes = #{} :: #{zx:realm() := zx:host()}, - hosts = #{} :: #{zx:realm() := queue:queue(zx:host())}, - conns = #{} :: #{zx:realm() := pid()}, - attempts = #{} :: #{pid() := zx:host()}, - zx_conns = sets:new() :: sets:set({pid(), reference()})}). - --spec cx_connected(Available, Conn, CX) -> Result - when Available :: [{zx:realm(), zx:serial()}], - Conn :: pid(), - CX :: conn_index(), - Result :: {Assignment, NewCX}, - Assignment :: assigned | unassigned, - NewCX :: conn_index(). -%% @private -%% An abstract data handler which is called whenever a new connection is successfully -%% established by a zx_conn. Any unconnected realms with a valid serial will be -%% assigned to the new connection; if none are needed then the connection is closed. -%% The successful host is placed back in the hosts queue for each available realm. -%% The return value is a tuple that indicates whether the new connection was assigned -%% or not and the updated CX data value. - -cx_connected(Available, Conn, CX) -> - cx_connected(unassigned, Available, Conn, CX). + {realms = #{} :: #{zx:realm() := realm_meta()}, + assigned = [] :: [{zx:realm(), pid()}], + attempts = [] :: [{pid(), reference(), zx:host()}], + conns = [] :: [{pid(), reference(), zx:host()}]}). -cx_connected(A, [{Realm, Serial} | Rest], Conn, CX = #cx{realms = Realms}) -> - case maps:find(Realm, Realms) of - {ok, S} when S < Serial -> - NewRealms = maps:update(Realm, Serial, Realms), - {NewA, NewCX} = cx_assign(A, Conn, Realm, CX#cx{realms = NewRealms}), - cx_connected(NewA, Rest, Conn, NewCX); - {ok, S} when S == Serial -> - {NewA, NewCX} = cx_assign(A, Conn, Realm, CX), - cx_connected(NewA, Rest, Conn, NewCX); - {ok, S} when S > Serial -> - cx_connected(A, Rest, Conn, CX); - error -> - cx_connected(A, Rest, Conn, CX) - end; -cx_connected(A, [], Conn, CX = #cx{attempts = Attempts}) -> - NewCX = CX#cx{attempts = maps:remove(Conn, Attempts)}, - {A, NewCX}. - - -cx_assign(A, Conn, Realm, CX = #cx{hosts = Hosts, conns = Conns, attempts = Attempts}) -> - Host = maps:get(Conn, Attempts), - Enqueue = fun(Q) -> queue:in(Host, Q) end, - NewHosts = maps:update_with(Realm, Enqueue, Hosts), - case maps:is_key(Realm, Conns) of - true -> - {A, CX#cx{hosts = NewHosts}}; - false -> - NewConns = maps:put(Realm, Conn, Conns), - {assigned, CX#cx{hosts = NewHosts, conns = NewConns}} - end. - - --spec cx_disconnect(Conn, CX) -> NewCX - -cx_disconnected(Conn, CX) -> - - --spec cx_failed(Conn, CX) -> NewCX - -cx_failed(Conn, CX) -> - - --spec cx_next(Realm, CX) -> - -cx_next(Realm, CX) -> - - --spec cx_resolve(Realm, CX) -> Conn - -cx_resolve(Realm, CX) -> - +-record(rmeta, + {revision = 0 :: non_neg_integer(), + serial = 0 :: non_neg_integer(), + prime = {"zomp.psychobitch.party", 11311} :: zx:host(), + private = [] :: [zx:host()], + mirrors = queue:new() :: queue:queue(zx:host()), + realm_keys = [] :: [zx:key_meta()], + package_keys = [] :: [zx:key_meta()], + sysops = [] :: [zx:sysop_meta()]}). -type state() :: #s{}. -type conn_index() :: #cx{}. +-type realm_meta() :: #rmeta{}. --type action() :: {subscribe, zx:package()}, +-type action() :: {subscribe, zx:package()} | unsubscribe | {list, zx:realm()} | {list, zx:realm(), zx:name()} @@ -290,7 +229,7 @@ list_versions(Package) -> -spec query_latest(Object) -> Result when Object :: zx:package() | zx:package_id(), - Result :: {ok, version()} + Result :: {ok, zx:version()} | {error, Reason}, Reason :: bad_realm | bad_package @@ -358,23 +297,30 @@ start_link() -> -spec init(none) -> {ok, state()}. init(none) -> - SerialFile = filename:join(zx_lib:zomp_home(), "realm.serials"), - Serials = - case file:consult(SerialFile) of - {ok, Ss} -> - maps:from_list(Ss); - {error, enoent} -> - ok = log(info, "Initializing zomp/realm.serials..."), - maps:new(); - {error, Reason} -> - Message = "Reading zomp/realm.serials failed with ~tp. Recreating..." - ok = log(error, Message, [Reason]), - maps:new() - end, - State = #s{serials = Serials}, + CX = cx_load(), + {ok, NewCX} = init_connections(CX), + State = #s{cx = NewCX}, {ok, State}. +init_connections(CX) -> + Realms = cx_realms(CX), + init_connections(Realms, CX). + + +init_connections([Realm | Realms], CX}) -> + {ok, Hosts, NextCX} = cx_next_hosts(3, Realm, CX), + StartConn = + fun(Host) -> + {ok, Pid, Mon} = zx_conn:start_monitor(Host), + {Pid, Mon, Host} + end, + NewAttempts = lists:map(StartConn, Hosts), + NewCX = lists:map(fun cx_add_attempt/2, NextCX, NewAttempts), + init_connections(Realms, NewCX); +init_connections([], CX) -> + {ok, CX}. + %%% gen_server @@ -464,7 +410,7 @@ do_pass_meta(Meta, Dir, ArgV, State) -> do_subscribe(Requestor, {Realm, Name}, - State = #s{name = none, connp = none, reqp = none, + State = #s{meta = none, reqp = none, hosts = Hosts, serials = Serials}) -> Monitor = monitor(process, Requestor), {Host, NewHosts} = select_host(Realm, Hosts), @@ -484,31 +430,6 @@ do_subscribe(_, _, State = #s{realm = Realm, name = Name}) -> {{error, {already_subscribed, {Realm, Name}}}, State}. --spec select_host(Realm, Hosts) -> {Host, NewHosts} - when Realm :: zx:realm(), - Hosts :: none | hosts(), - Host :: zx:host(), - NewHosts :: hosts(). - -select_host(Realm, none) -> - List = - case file:consult(zx_lib:hosts_cache_file(Realm)) of - {ok, Cached} -> Cached; - {error, enoent} -> [zx_lib:get_prime(Realm)] - end, - NewState = State#s{hosts = #{Realm => List}}, - select_host(Realm, NewState); -select_host(Realm, Hosts) -> - {Target, Rest} = - case maps:find(Realm, Hosts) of - {ok, [H | Hs]} -> {H, Hs}; - {ok, []} -> {zx_lib:get_prime(Realm), []}; - error -> {zx_lib:get_prime(Realm), []} - end, - NewHosts = maps:put(Realm, Hosts, Rest), - {Target, NewHosts}. - - -spec do_query_latest(Object, State) -> {Result, NewState} when Object :: zx:package() | zx:package_id(), State :: state(), @@ -556,7 +477,12 @@ do_unsubscribe(State = #s{connp = ConnP, connm = ConnM}) -> State :: state(), NewState :: state(). -do_report(From, {connected, Realms}, State = #s{ +do_report(From, {connected, Realms}, State) -> + % FIXME + ok = log(info, + "Would do_report(~tp, {connected, ~tp}, ~tp) here", + [From, Realms, State]), + State. @@ -635,3 +561,379 @@ scrub([]) -> []; scrub(Deps) -> lists:filter(fun(PackageID) -> not zx_lib:installed(PackageID) end, Deps). + + + +%%% Connection Cache ADT Interface Functions +%%% +%%% Functions to manipulate the conn_index() data type are in this section. This +%%% data should be treated as abstract by functions outside of this section, as it is +%%% a deep structure and future requirements are likely to wind up causing it to +%%% change a little. For the same reason, these functions are all pure functions, +%%% testable independently of the rest of the module and having no side effects. +%%% Return values usually carry some status information with them, and it is up to the +%%% caller to react to those responses in an appropriate way. + +-spec cx_load() -> conn_index(). +%% @private +%% Used to load a connection index populated with necessary realm configuration data +%% and cached mirror data, if such things can be found in the system, otherwise return +%% a blank connection index structure. + +cx_load() -> + case cx_populate() of + {ok, CX} -> + CX; + {error, Reason} -> + ok = log(error, "Cache load failed with: ~tp", [Reason]), + ok = log(warning, "No realms configured."), + #cx{} + end. + + +-spec cx_populate() -> Result + when Result :: {ok, conn_index()} + | {error, Reason}, + Reason :: no_realms + | file:posix(). + +cx_populate() -> + Home = zx_lib:zomp_home(), + Pattern = filename:join(Home, "*.realm"), + case filelib:wildcard(Pattern) of + [] -> {error, no_realms}; + RealmFiles -> cx_fetch_cache(RealmFiles, #cx{}) + end. + + +cx_populate([File | Files], CX) -> + case file:consult(File) of + {ok, Meta} -> + cx_load_realm_meta(Meta, CX); + {error, Reason} -> + Message = "Realm file ~tp could not be read. Failed with: ~tp. Skipping.", + ok = log(warning, Message, [File, Reason]), + populate(Files, CX) + end. + + +cx_load_realm_meta(Meta, CX = #cx{realms = Realms}) -> + {realm, Realm} = lists:keyfind(realm, 1, Meta), + {revision, Revision} = lists:keyfind(revision, 1, Meta), + {prime, Prime} = lists:keyfind(prime, 1, Meta), + {realm_keys, RealmKeys} = lists:keyfind(realm_keys, 1, Meta), + {package_keys, PackageKeys} = lists:keyfind(packge_keys, 1, Meta), + {sysops, Sysops} = lists:keyfind(sysops, 1, Meta), + Basic = + #rmeta{revision = Revision, + serial = Serial, + prime = Prime, + realm_keys = RealmKeys, + package_keys = PackageKeys, + sysops = Sysops}, + Complete = cx_fetch_cache(Realm, Basic), + NewRealms = maps:put(Realm, Complete, Realms), + CX#cx{realms = NewRealms}. + + +cx_fetch_cache(Realm, Basic) -> + CacheFile = cx_cache_file(Realm), + case file:consult(CacheFile) of + {ok, Cache} -> + {serial, Serial} = lists:keyfind(serial, 1, Cache), + {private, Private} = lists:keyfind(private, 1, Cache), + {mirrors, Mirrors} = lists:keyfind(mirrors, 1, Cache), + PQueue = queue:from_list(Private), + Enqueue = fun(H, Q) -> queue:in(H, Q) end, + MQueue = lists:foldl(Enqueue, Mirrors, PQueue), + Basic#rmeta{serial = Serial, private = Private, mirrors = MQueue}; + {error, enoent} -> + Basic + end. + + +-spec cx_store_cache(CX) -> Result + when CX :: conn_index(), + Result :: ok + | {error, file:posix()}. + +cx_store_cache(#cx{realms = Realms}) -> + lists:foreach(fun cx_write_cache/1, maps:to_list(Realms)). + + +-spec cx_write_cache({zx:realm(), realm_meta()}) -> ok. + +cx_write_cache({Realm, + #rmeta{serial = Serial, private = Private, mirrors = Mirrors}}) -> + CacheFile = cx_cache_file(Realm), + MList = queue:to_list(Mirrors), + ActualMirrors = lists:subtract(MList, Private), + CacheMeta = [{serial, Serial}, {mirrors, ActualMirrors}], + ok = zx_lib:write_terms(CacheFile, CacheMeta), + log(info, "Wrote cache for realm ~ts", [Realm]). + + +-spec cx_cache_file(zx:realm()) -> file:filename(). + +cx_cache_file(Realm) -> + filename:join(zx_lib:zomp_home(), Realm ++ ".cache"). + + +-spec cx_realms(conn_index()) -> [zx:realms()]. + +cx_realms(#cx{realms = Realms}) -> + maps:keys(Realms). + + +-spec cx_next_host(Realm, CX) -> Result + when Realm :: zx:realm(), + CX :: conn_index(), + Result :: {ok, Next, NewCX} + | {prime, Prime, NewCX} + | {error, Reason}, + Next :: zx:host(), + Prime :: zx:host(), + NewCX :: conn_index(), + Reason :: bad_realm + | connected. +%% @private +%% Given a realm, retun the next cached host location to which to connect. Returns an +%% error if the realm is already assigned or if the realm is not configured. + +cx_next_host(Realm, CX = #cx{assigned = Assigned}) -> + case lists:keymember(Realm, 1, Assigned) of + false -> cx_next_host2(Realm, CX); + true -> {error, connected} + end. + +cx_next_host2(Realm, CX = #cx{realm = Realms}) -> + case maps:find(Realm, Realms) of + {ok, Meta} -> + {Result, Host, NewMeta} = cx_next_host3(Meta), + NewRealms = maps:put(Realm, NewMeta, Realms), + {Result, Host, CX#cx{realms = NewRealms}}; + error -> + {error, bad_realm} + end. + + +-spec cx_next_host3(RealmMeta) -> Result + when RealmMeta :: realm_meta(), + Result :: {ok, Next, NewRealmMeta} + | {prime, Prime, NewRealmMeta}, + Next :: zx:host(), + Prime :: zx:host(), + NewRealmMeta :: realm_meta(). +%% @private +%% Match on the important success cases first. +%% If there is a locally configured set of private mirrors (usually on the same LAN, +%% or public ones an organization hosts for its own users) then try those first. +%% Trying "first" is a relative concept in long-lived systems that experience a high +%% frequency of network churn. When the daemon is initialized a queue is created from +%% the known public mirrors, and then the private mirrors are enqueued at the head of +%% the mirrors so they will be encountered first. +%% If the entire combined mirrors list is exhausted then the prime node will be +%% returned, but also as a consequence the prime mirrors will be reloaded at the head +%% once again so if the prime fails (or causes a redirect) the private mirrors will +%% once again occur in the queue. +%% If the prime node is returned it is indicated with the atom `prime', which should +%% indicate to the caller that any iterative host scanning or connection procedures +%% should treat this as the last value of interest (and stop spawning connections). + +cx_next_host3(Meta = #rmeta{prime = Prime, private = Privae, mirrors = Mirrors}) -> + case queue:is_empty(Mirrors) of + false -> + {{value, Next}, NewMirrors} = queue:out(Mirrors), + {ok, Next, Meta#rmeta{mirrors = NewMirrors}}; + true -> + Enqueue = fun(H, Q) -> queue:in(H, Q) end, + NewMirrors = lists:foldl(Enqueue, Private, Mirrors), + {prime, Prime, Meta#rmeta{mirrors = NewMirrors}} + end. + + +-spec cx_next_hosts(N, Realm, CX) -> Result + when N :: non_neg_integer(), + Realm :: zx:realm(), + CX :: conn_index(), + Result :: {ok, Hosts, NewCX} + | {error, Reason}, + Hosts :: [zx:host()], + NewCX :: conn_index(), + Reason :: bad_realm + | connected. +%% @private +%% This function allows recruiting an arbitrary number of hosts from the host cache +%% of a given realm, taking private mirrors first, then public mirrors, and ending +%% with the prime node for the realm if no others exist. + +cx_next_hosts(N, Realm, CX = #cx{assigned = Assigned}) -> + case lists:keymember(Realm, 1, Assigned) of + false -> cx_next_hosts2(N, Realm, CX); + true -> {error, connected} + end. + + +cx_next_hosts2(N, Realm, CX = #cx{realms = Realms}) -> + case maps:find(Realm, Realms) of + {ok, Meta} -> + {ok, Hosts, NewMeta} = cx_next_hosts3(N, [], Meta), + NewRealms = maps:put(Realm, NewMeta, Realms), + {ok, Hosts, CX#cx{realms = NewRealms}}; + error -> + {error, bad_realm} + end. + + +cx_next_hosts3(N, Hosts, Meta) when N < 1 -> + {ok, Hosts, Meta}; +cx_next_hosts3(N, Hosts, Meta) -> + case cx_next_host3(Meta) of + {ok, Host, NewMeta} -> cx_next_hosts3(N - 1, [Host | Hosts], NewMeta); + {prime, Prime, NewMeta} -> {ok, [Prime | Hosts], NewMeta} + end. + + +-spec cx_add_attempt(New, CX) -> NewCX + when New :: {pid(), reference(), zx:host()}, + CX :: conn_index(), + NewCX :: conn_index(). + +cx_add_attempt(New, CX = #cx{attempts = Attempts}) -> + CX#cx{attempts = [New | Attempts]}. + + +-spec cx_connected(Available, Conn, CX) -> Result + when Available :: [{zx:realm(), zx:serial()}], + Conn :: pid(), + CX :: conn_index(), + Result :: {Assignment, NewCX}, + Assignment :: assigned | unassigned, + NewCX :: conn_index(). +%% @private +%% An abstract data handler which is called whenever a new connection is successfully +%% established by a zx_conn. Any unconnected realms with a valid serial will be +%% assigned to the new connection; if none are needed then the connection is closed. +%% The successful host is placed back in the hosts queue for each available realm. +%% The return value is a tuple that indicates whether the new connection was assigned +%% or not and the updated CX data value. + +cx_connected(Available, Conn, CX) -> + cx_connected(unassigned, Available, Conn, CX). + + +cx_connected(A, [{Realm, Serial} | Rest], Conn, CX = #cx{realms = Realms}) -> + case maps:find(Realm, Realms) of + {ok, Meta = #rmeta{serial = S}} when S < Serial -> + NewMeta = Meta#rmeta{serial = Serial}, + {NewA, NewCX} = cx_connected(A, Realm, Conn, NewMeta, CX), + cx_connected(NewA, Rest, Conn, NewCX); + {ok, Meta = #rmeta{serial = S}} when S == Serial -> + {NewA, NewCX} = cx_connected(A, Realm, Conn, Meta, CX), + cx_connected(NewA, Rest, Conn, NewCX); + {ok, #rmeta{serial = S}} when S > Serial -> + cx_connected(A, Rest, Conn, CX); + error -> + cx_connected(A, Rest, Conn, CX) + end; +cx_connected(A, [], Conn, CX = #cx{attempts = Attempts, conns = Conns}) -> + {value, ConnRec, NewAttempts} = lists:keytake(Conn, 1, Attempts), + NewConns = [ConnRec | Conns], + NewCX = CX#cx{attempts = NewAttempts, conns = NewConns}, + {A, NewCX}. + + +cx_connected(A, + Realm, + Conn, + Meta = #rmeta{prime = Prime, mirrors = Mirrors}, + CX = #cx{realms = Realms, assigned = Assigned, attempts = Attempts}) -> + {NewMirrors, Node} = + case lists:keyfind(Conn, 1, Attempts) of + {_, _, Prime} -> {Mirrors, Prime}; + {_, _, Host} -> {enqueue_unique(Host, Mirrors), Host} + end, + {NewA, NewAssigned} = + case lists:keymember(Realm, 1, Assigned) of + true -> {A, Assigned}; + false -> {assigned, [{Realm, Pid} | Assigned]} + end, + NewMeta = Meta#rmeta{mirrors = NewMirrors}, + NewRealms = maps:put(Realm, NewMeta, Realms), + NewCX = CX#cx{realms = NewRealms, assigned = NewAssigned}, + {NewA, NewCX}. + + +-spec enqueue_unique(term(), queue:queue()) -> queue:queue(). +%% @private +%% Simple function to ensure that only unique elements are added to a queue. Obviously +%% this operation is extremely general and O(n) in complexity due to the use of +%% queue:member/2. + +enqueue_unique(Element, Queue) -> + case queue:member(Element, Queue) of + true -> Queue; + false -> queue:in(Element, Queue) + end. + + +-spec cx_disconnected(Conn, CX) -> Result + when Conn :: pid(), + CX :: conn_index(), + Result :: {ok, Mon, UnassignedRealms, NewCX} + | {error, unknown}, + Mon :: reference(), + UnassignedRealms :: [zx:realm()], + NewCX :: conn_index(). +%% @private +%% An abstract data handler which is called whenever a connection terminates. +%% This function removes all data related to the disconnected pid and its assigned +%% realms, and returns the monitor reference of the pid, a list of realms that are now +%% unassigned, and an updated connection index. + +cx_disconnected(Conn, CX = #cx{assigned = Assigned, conns = Conns}) -> + case lists:keytake(Con, Conns) of + {value, {Pid, Mon, Conn}, NewConns} -> + {UnassignedRealms, NewAssigned} = cx_scrub_assigned(Pid, Assigned), + NewCX = CX#cx{assigned = NewAssigned, conns = NewConns}, + {ok, Mon, UnassignedRealms, NewCX}; + false -> + {error, unknown} + end. + + +-spec cx_scrub_assigned(Pid, Assigned) -> {UnassignedRealms, NewAssigned} + when Pid :: pid(), + Assigned :: [{zx:realm(), pid()}], + UnassignedRealms :: [zx:realm()], + NewAssigned :: [{zx:realm(), pid()}]. +%% @private +%% This could have been performed as a set of two list operations (a partition and a +%% map), but to make the procedure perfectly clear it is written out explicitly. + +cx_scrub_assigned(Pid, Assigned) -> + cx_scrub_assigned(Pid, Assigned, [], []). + + +cx_scrub_assigned(Pid, [{Realm, Pid} | Rest], Unassigned, Assigned) -> + cx_scrub_assigned(Pid, Rest, [Realm | Unassigned], Assigned); +cx_scrub_assigned(Pid, [A | Rest], Unassigned, Assigned) -> + cx_scrub_assigned(Pid, Rest, Unassigned, [A | Assigned]); +cx_scrub_assigned(_, [], Unassigned, Assigned) -> + {Unassigned, Assigned}. + + +-spec cx_resolve(Realm, CX) -> Result + when Realm :: zx:realm(), + CX :: conn_index(), + Result :: {ok, Conn :: pid()} + | unassigned. +%% @private +%% Check the registry of assigned realms and return the pid of the appropriate +%% connection, or an `unassigned' indication if the realm is not yet connected. + +cx_resolve(Realm, #cx{assigned = Assigned}) -> + case lists:keyfind(Realm, 1, Assigned) of + {Realm, Conn} -> {ok, Conn}; + false -> unassigned + end. diff --git a/zomp/otpr.realm b/zomp/otpr.realm index 081eb55..c0c267c 100644 --- a/zomp/otpr.realm +++ b/zomp/otpr.realm @@ -1,8 +1,6 @@ {realm,"otpr"}. {revision,0}. {prime,{"otpr.psychobitch.party",11311}}. -{private,[]}. -{mirrors,[]}. {sysops,[{{"otpr","zxq9"},["zxq9.1"],"zxq9@zxq9.com","Craig Everett"}]}. {realm_keys,[{{"otpr","otpr.1.realm"}, realm, From 107da5f41d79811e714cca99a0923bf2341b9878 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Thu, 22 Feb 2018 08:19:44 +0900 Subject: [PATCH 39/55] Indexing madness --- zomp/lib/otpr-zx/0.1.0/src/zx.erl | 4 +- zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl | 4 +- zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl | 814 +++++++++++++++++------ 3 files changed, 619 insertions(+), 203 deletions(-) diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx.erl b/zomp/lib/otpr-zx/0.1.0/src/zx.erl index 4d10cf2..9c5b057 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx.erl @@ -25,6 +25,7 @@ -export([start/2, stop/1]). -export_type([serial/0, package_id/0, package/0, realm/0, name/0, version/0, + identifier/0, option/0, host/0, key_id/0, key_name/0, @@ -45,6 +46,7 @@ -type version() :: {Major :: non_neg_integer() | z, Minor :: non_neg_integer() | z, Patch :: non_neg_integer() | z}. +-type identifier() :: realm() | package() | package_id(). -type option() :: {string(), term()}. -type host() :: {string() | inet:ip_address(), inet:port_number()}. -type key_id() :: {realm(), key_name()}. @@ -55,7 +57,7 @@ -type label() :: [$a..$z | $0..$9 | $_ | $- | $.]. -type package_meta() :: #{package_id := package_id(), deps := [package_id()], - type := app | lib,}. + type := app | lib}. diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl index efad4ba..ba8d1c5 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl @@ -99,7 +99,7 @@ connect(Parent, Debug, {Host, Port}) -> confirm_service(Parent, Debug, Socket); {error, Error} -> ok = log(warning, "Connection problem with ~tp: ~tp", [Node, Error]), - ok = zx_daemon:report(failed) + ok = zx_daemon:report(disconnected) terminate() end. @@ -174,7 +174,7 @@ loop(Parent, Debug, Socket) -> loop(Parent, Debug, Socket); stop -> ok = zx_net:disconnect(Socket), - terminat(); + terminate(); Unexpected -> ok = log(warning, "Unexpected message: ~tp", [Unexpected]), loop(Parent, Debug, Socket) diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl index 2b0dc65..a684394 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl @@ -85,10 +85,11 @@ -export([pass_meta/3, - subscribe/1, unsubscribe/0, - list_packages/1, list_versions/1, query_latest/1, - fetch/1]). --export([report/1]). + subscribe/1, unsubscribe/1, + list/1, latest/1, + fetch/1, key/1, + pending/1, packagers/1, maintainers/1, sysops/1]). +-export([report/1, result/2, notice/2]). -export([start_link/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, code_change/3, terminate/2]). @@ -100,59 +101,124 @@ %%% Type Definitions -record(s, - {meta = none :: none | zx:package_meta(), - home = none :: none | file:filename(), - argv = none :: none | [string()], - reqp = none :: none | pid(), - reqm = none :: none | reference(), - action = none :: none | action(), - actions = queue:new() :: queue:queue(action()), - cx = cx_load() :: conn_index()}). + {meta = none :: none | zx:package_meta(), + home = none :: none | file:filename(), + argv = none :: none | [string()], + actions = [] :: [request() | {reference(), request()}], + responses = maps:new() :: #{reference() := request()}, + subs = [] :: [{pid(), zx:package()}], + mx = mx_new() :: monitor_index(), + cx = cx_load() :: conn_index()}). -record(cx, {realms = #{} :: #{zx:realm() := realm_meta()}, assigned = [] :: [{zx:realm(), pid()}], - attempts = [] :: [{pid(), reference(), zx:host()}], - conns = [] :: [{pid(), reference(), zx:host()}]}). + attempts = [] :: [{pid(), zx:host()}], + conns = [] :: [{pid(), zx:host()}]}). -record(rmeta, - {revision = 0 :: non_neg_integer(), - serial = 0 :: non_neg_integer(), - prime = {"zomp.psychobitch.party", 11311} :: zx:host(), - private = [] :: [zx:host()], - mirrors = queue:new() :: queue:queue(zx:host()), - realm_keys = [] :: [zx:key_meta()], - package_keys = [] :: [zx:key_meta()], - sysops = [] :: [zx:sysop_meta()]}). + {revision = 0 :: non_neg_integer(), + serial = 0 :: non_neg_integer(), + prime = {"zomp.tsuriai.jp", 11311} :: zx:host(), + private = [] :: [zx:host()], + mirrors = queue:new() :: queue:queue(zx:host()), + realm_keys = [] :: [zx:key_meta()], + package_keys = [] :: [zx:key_meta()], + sysops = [] :: [zx:sysop_meta()]}). + +%% State Types +-type state() :: #s{}. +-type monitor_index() :: [{reference(), pid(), category()}], +-type conn_index() :: #cx{}. +-type realm_meta() :: #rmeta{}. +-type category() :: {Subs :: non_neg_integer(), Reqs :: non_neg_integer()} + | conn_attempt + | conn. + +%% Conn Communication +-type conn_report() :: {connected, Realms :: [{zx:realm(), zx:serial()}]} + | disconnected. + +%% Subscriber / Requestor Communication +% Incoming Request messages +-type request() :: {Requestor :: pid(), Action :: action() | subunsub()}. +-type action() :: {list, realms | zx:identifier()} + | {latest, zx:identifier()} + | {fetch, zx:package_id()} + | {key, zx:key_id()} + | {pending, zx:package()} + | {packagers, zx:package()} + | {maintainers, zx:package()} + | {sysops, zx:realm()}. +-type subunsub() :: {subscribe, zx:package()} + | {unsubscribe, zx:package()}. + +% Outgoing Result Messages +-type result() :: sub_result() + | list_result() + | latest_result() + | fetch_result() + | key_result() + | pending_result() + | pack_result() + | maint_result() + | sysop_result(). +-type sub_result() :: {subscription, zx:package(), + Message :: {update, zx:package_id()} + | {error, bad_realm | bad_package}}. +-type list_result() :: {list, realms, + Message :: {ok, [zx:realm()]}} + | {list, zx:realm(), + Message :: {ok, [zx:name()]} + | {error, bad_realm | timeout}} + | {list, zx:package(), + Message :: {ok, [zx:version]} + | {error, bad_realm + | bad_package + | timeout}} +-type latest_result() :: {latest, + Package :: zx:package() + | zx:package_id(), + Message :: {ok, zx:package_id()} + | {error, bad_realm + | bad_package + | bad_version + | timeout}}. +-type fetch_result() :: {fetch, zx:package_id(), + Message :: {hops, non_neg_integer()} + | done + | {error, bad_realm + | bad_package + | bad_version + | timeout}}. +-type key_result() :: {key, zx:key_id(), + Message :: {ok, binary()} + | {error, bad_key + | timeout}}. +-type pending_result() :: {pending, zx:package(), + Message :: {ok, [zx:version()]} + | {error, bad_realm + | bad_package + | timeout}}. +-type pack_result() :: {packagers, zx:package(), + Message :: {ok, [zx:user()]} + | {error, bad_realm + | bad_package + | timeout}}. +-type maint_result() :: {maintainers, zx:package(), + Message :: {ok, [zx:user()]} + | {error, bad_realm + | bad_package + | timeout}}. +-type sysop_result() :: {sysops, zx:realm(), + Message :: {ok, [zx:user()]} + | {error, bad_host + | timeout}. --type state() :: #s{}. --type conn_index() :: #cx{}. --type realm_meta() :: #rmeta{}. - --type action() :: {subscribe, zx:package()} - | unsubscribe - | {list, zx:realm()} - | {list, zx:realm(), zx:name()} - | {list, zx:realm(), zx:name(), zx:version()} - | {latest, zx:realm()} - | {latest, zx:realm(), zx:name()} - | {latest, zx:realm(), zx:name(), zx:version()} - | {fetch, zx:package_id()} - | {key, zx:key_id()} - | {pending, zx:package()} - | {packagers, zx:package()} - | {maintainers, zx:package()} - | sysops - | {subscribe, zx:realm(), zx:name()}. --type conn_report() :: {connected, Realms :: [{zx:realm(), zx:serial()}]} - | failed - | disconnected. - - -%%% Service Interface +%%% Requestor Interface -spec pass_meta(Meta, Dir, ArgV) -> ok when Meta :: zx:package_meta(), @@ -171,7 +237,7 @@ %% by the launching process (which normally terminates shortly thereafter). pass_meta(Meta, Dir, ArgV) -> - gen_server:call(?MODULE, {pass_meta, Meta, Dir, ArgV}). + gen_server:cast(?MODULE, {pass_meta, Meta, Dir, ArgV}). -spec subscribe(Package) -> Result @@ -189,83 +255,102 @@ pass_meta(Meta, Dir, ArgV) -> %% Other functions can be used to query the status of a package at an arbitrary time. subscribe(Package) -> - gen_server:call(?MODULE, {subscribe, self(), Package}). + gen_server:cast(?MODULE, {subscribe, self(), Package}). --spec unsubscribe() -> ok. +-spec unsubscribe(zx:package()) -> ok. %% @doc %% Instructs the daemon to unsubscribe if subscribed. Has no effect if not subscribed. -unsubscribe() -> - gen_server:call(?MODULE, unsubscribe). +unsubscribe(Package) -> + gen_server:cast(?MODULE, {unsubscribe, self(), Package}). --spec list_packages(Realm) -> Result - when Realm :: zx:realm(), - Result :: {ok, Packages :: [zx:package()]} - | {error, Reason}, - Reason :: bad_realm - | no_realm - | network. - -list_packages(Realm) -> - gen_server:call(?MODULE, {list, Realm}). - - --spec list_versions(Package) -> Result - when Package :: zx:package(), - Result :: {ok, Versions :: [zx:version()]} - | {error, Reason}, - Reason :: bad_realm - | bad_package - | network. +-spec list(Identifier) -> ok + when Identifier :: realms + | zx:identifier(). %% @doc -%% List all versions of a given package. Useful especially for developers wanting to -%% see a full list of maintained packages to include as dependencies. +%% Requests a list of realms, packages, or package versions depending on the +%% identifier provided. -list_versions(Package) -> - gen_server:call(?MODULE, {list_versions, Package}). +list(Identifier) -> + request({list, Identifier}). --spec query_latest(Object) -> Result - when Object :: zx:package() | zx:package_id(), - Result :: {ok, zx:version()} - | {error, Reason}, - Reason :: bad_realm - | bad_package - | bad_version - | network. +-spec latest(Identifier) -> ok. + when Identifier :: zx:package() | zx:package_id(). %% @doc -%% Check for the latest version of a package, with or without a version provided to -%% indicate subversion limit. Useful mostly for developers checking for a latest -%% version of a package. +%% Request the lastest version of a package within the scope of the identifier. +%% If a package with no version is provided, the absolute latest version will be +%% sent once queried. If a partial version is provided then only the latest version +%% within the provided scope will be returned. %% -%% While this function could be used as a primitive operation in a dynamic dependency -%% upgrade scheme, that is not its intent. You will eventually divide by zero trying -%% to implement such a feature, open a portal to Oblivion, and monsters will consume -%% all you love. See? That's a horrible idea. You have been warned. +%% If package {"foo", "bar"} has [{1,2,3}, {1,2,5}, {1,3,1}, {2,4,5}] available, +%% querying {"foo", "bar"} or {"foo", "bar", {z,z,z}} will result in {2,4,5}, but +%% querying {"foo", "bar", {1,z,z}} will result in {1,3,1}, granted that the realm +%% "foo" is reachable. -query_latest(Object) -> - gen_server:call(?MODULE, {query_latest, Object}). +latest(Identifier) -> + request({latest, Identifier}). --spec fetch(PackageIDs) -> Result - when PackageIDs :: [zx:package_id()], - Result :: {{ok, [zx:package_id()]}, - {error, [{zx:package_id(), Reason}]}}, - Reason :: bad_realm - | bad_package - | bad_version - | network. +-spec fetch(zx:package_id()) -> ok. %% @doc -%% Ensure a list of packages is available locally, fetching any missing packages in -%% the process. This is intended to abstract the task of ensuring that a list of -%% dependencies is available locally prior to building/running a dependent app or lib. +%% Ensure a package is available locally, or queue it for download otherwise. -fetch([]) -> - {{ok, []}, {error, []}}; -fetch(PackageIDs) -> - gen_server:call(?MODULE, {fetch, PackageIDs}). +fetch(PackageID) -> + request({fetch, PackageID}). + + +-spec key(zx:key_id()) -> ok. +%% @doc +%% Request a public key be fetched from its relevant realm. + +key(KeyID) -> + request({key, KeyID}). + + +-spec pending(zx:package()) -> ok. +%% @doc +%% Request the list of versions of a given package that have been submitted but not +%% signed and included in their relevant realm. + +pending(Package) -> + request({pending, Package}). + + +-spec packagers(zx:package()) -> ok. +%% @doc +%% Request a list of packagers assigned to work on a given package. + +packagers(Package) -> + request({packagers, Package}). + + +-spec maintainers(zx:package()) -> ok. +%% @doc +%% Request a list of maintainers assigned to work on a given package. + +maintainers(Package) -> + request({maintainers, Package}). + + +-spec sysops(zx:realm()) -> ok. +%% @doc +%% Request a list of sysops in charge of maintaining a given realm. What this +%% effectively does is request the sysops of the prime host of the given realm. + +sysops(Realm) -> + request({sysops, Realm}). + + +%% Public Caster +-spec request(action()) -> ok. +%% @private +%% Private function to wrap the necessary bits up. + +request(Action) -> + gen_server:cast(?MODULE, {request, make_ref(), self(), Action}), @@ -284,6 +369,25 @@ report(Message) -> gen_server:cast(?MODULE, {report, self(), Message}). +-spec result(reference(), result()) -> ok. +%% @private +%% Return a tagged result back to the daemon to be forwarded to the original requestor. + +result(Reference, Result) -> + gen_server:cast(?MODULE, {result, Reference, Result}). + + +-spec notice(Package, Message) -> ok + when Package :: zx:package(), + Message :: term(). +%% @private +%% Function called by a connection when a subscribed update arrives. + +notify(Package, Message) -> + gen_server:cast(?MODULE, {notice, Package, Message}). + + + %%% Startup -spec start_link() -> {ok, pid()} | {error, term()}. @@ -297,29 +401,33 @@ start_link() -> -spec init(none) -> {ok, state()}. init(none) -> - CX = cx_load(), - {ok, NewCX} = init_connections(CX), - State = #s{cx = NewCX}, + {ok, MX, CX} = init_connections(), + State = #s{mx = MX, cx = NewCX}, {ok, State}. -init_connections(CX) -> +init_connections() -> + CX = cx_load(), + MX = mx_new(), Realms = cx_realms(CX), - init_connections(Realms, CX). + init_connections(Realms, MX, CX). -init_connections([Realm | Realms], CX}) -> +init_connections([Realm | Realms], Monitors, CX) -> {ok, Hosts, NextCX} = cx_next_hosts(3, Realm, CX), StartConn = fun(Host) -> - {ok, Pid, Mon} = zx_conn:start_monitor(Host), - {Pid, Mon, Host} + {ok, Pid} = zx_conn:start(Host), + {Pid, Host} end, NewAttempts = lists:map(StartConn, Hosts), - NewCX = lists:map(fun cx_add_attempt/2, NextCX, NewAttempts), - init_connections(Realms, NewCX); -init_connections([], CX) -> - {ok, CX}. + AddMonitor = fun({P, _}, M) -> mx_add_monitor(P, conn_attempt, M) end, + NewMX = lists:foldl(AddMonitor, MX, NewAttempts), + NewCX = lists:foldl(fun cx_add_attempt/2, NextCX, NewAttempts), + init_connections(Realms, NewMX, NewCX); +init_connections([], MX, CX) -> + {ok, MX, CX}. + %%% gen_server @@ -327,18 +435,6 @@ init_connections([], CX) -> %% @private %% gen_server callback for OTP calls -handle_call({pass_meta, Meta, Dir, ArgV}, _, State) -> - {Result, NewState} = do_pass_meta(Requestor, Package, ArgV, State), - {reply, Result, NewState}; -handle_call({subscribe, Requestor, Package}, _, State) -> - {Result, NewState} = do_subscribe(Requestor, Package, State), - {reply, Result, NewState}; -handle_call({query_latest, Object}, _, State) -> - {Result, NewState} = do_query_latest(Object, State), - {reply, Result, NewState}; -handle_call({fetch, Packages}, _, State) -> - {Result, NewState} = do_fetch(Packages, State), - {reply, Result, NewState}; handle_call(Unexpected, From, State) -> ok = log(warning, "Unexpected call ~tp: ~tp", [From, Unexpected]), {noreply, State}. @@ -347,11 +443,31 @@ handle_call(Unexpected, From, State) -> %% @private %% gen_server callback for OTP casts -handle_cast(unsubscribe, State) -> - NewState = do_unsubscribe(State), +handle_cast({report, Conn, Message}, State) -> + NextState = do_report(Conn, Message, State), + NewState = eval_queue(NextState), {noreply, NewState}; -handle_cast({report, From, Message}, State) -> - NewState = do_report(From, Message, State), +handle_cast({request, Ref, Requestor, Action}, State) -> + NextState = do_request(Ref, Requestpr, Action, State), + NewState = eval_queue(NextState), + {noreply, NewState}; +handle_cast({result, Ref, Result}, State) -> + NextState = do_result(Ref, Result, State), + NewState = eval_queue(NextState), + {noreply, NewState}; +handle_cast({notice, Package, Update}, State) -> + ok = do_notice(Package, Update, State), + {noreply, State}; +handle_cast({subscribe, Pid, Package}, State) -> + NextState = do_request(subscribe, Pid, Package, State), + NewState = eval_queue(NextState), + {noreply, NewState}; +handle_cast({unsubscribe, Pid, Package}, State) -> + NextState = do_request(unsubscribe, Pid, Package, State), + NewState = eval_queue(NextState), + {noreply, NewState}; +handle_cast({pass_meta, Meta, Dir, ArgV}, State) -> + NewState = do_pass_meta(Meta, Dir, ArgV, State), {noreply, NewState}; handle_cast(Unexpected, State) -> ok = log(warning, "Unexpected cast: ~tp", [Unexpected]), @@ -385,49 +501,236 @@ terminate(_, _) -> %%% Doer Functions --spec do_pass_meta(Meta, Dir, ArgV, State) -> {Result, NewState} +-spec do_pass_meta(Meta, Home, ArgV, State) -> NewState when Meta :: zx:package_meta(), - Dir :: file:filename(), + Home :: file:filename(), ArgV :: [string()], State :: state(), - Result :: ok, - Newstate :: state(). + NewState :: state(). -do_pass_meta(Meta, Dir, ArgV, State) -> - NewState = State#s{meta = Meta, dir = Dir, argv = ArgV}, - {ok, NewState}. +do_pass_meta(Meta, Home, ArgV, State) -> + PackageID = maps:get(package_id, Meta), + {ok, PackageString} = zx_lib:package_string(PackageID), + ok = log(info, "Received meta for ~tp.", [PackageString]), + State#s{meta = Meta, home = Home, argv = ArgV}. --spec do_subscribe(Requestor, Package, State) -> {Result, NewState} - when Requestor :: pid(), - Package :: zx:package(), +-spec do_request(Ref, Req, Action, State) -> NextState + when Ref :: reference(), + Req :: pid(), + Action :: action(), State :: state(), - Result :: ok - | {error, Reason}, - Reason :: illegal_requestor - | {already_subscribed, zx:package()}, - NewState :: state(). + NextState :: state(). +%% @private +%% Enqueue requests and update relevant index. -do_subscribe(Requestor, - {Realm, Name}, - State = #s{meta = none, reqp = none, - hosts = Hosts, serials = Serials}) -> - Monitor = monitor(process, Requestor), - {Host, NewHosts} = select_host(Realm, Hosts), - Serial = - case lists:keyfind(Realm, 1, Serials) of - false -> 0; - {Realm, S} -> S +do_request(subscribe, Req, Package, State = #s{actions = Actions}) -> + NewActions = [{Req, {subscribe, Package}} | Actions], + State#s{actions = NewActions}; +do_request(unsubscribe, Req, Package, State = #s{actions = Actions}) -> + NewActions = [{Req, {unsubscribe, Package}} | Actions], + State#s{actions = NewActions}; +do_request(Ref, Req, Action, State = #s{actions = Actions}) -> + NewActions = [{Ref, Req, Action} | Actions], + State#s{actions = NewActions}. + + +-spec do_report(Conn, Message, State) -> NewState + when Conn :: pid(), + Message :: conn_report(), + State :: state(), + NewState :: state(). +%% @private +%% Receive a report from a connection process and update the connection index and +%% possibly retry connections. + +do_report(Conn, {connected, Realms}, State = #s{mx = MX, cx = CX}) -> + {ok, NextMX} = mx_swap_categories(Conn, MX), + {NewMX, NewCX} = + case cx_connected(Realms, Conn, CX) of + {assigned, NextCX} -> + {NextMX, NextCX}; + {unassigned, NextCX} -> + ScrubbedMX = mx_del_monitor(Conn, conn, NextMX), + ok = zx_conn:stop(Conn), + {ScrubbedMX, NextCX} end, - {ok, ConnP} = zx_conn:start(Host), - ConnM = monitor(process, ConnP), - NewState = State#s{realm = Realm, name = Name, - connp = ConnP, connm = ConnM, - reqp = Requestor, reqm = Monitor, - hosts = NewHosts}, - {ok, NewState}; -do_subscribe(_, _, State = #s{realm = Realm, name = Name}) -> - {{error, {already_subscribed, {Realm, Name}}}, State}. + State#s{mx = NewMX, cx = NewCX}; +do_report(Conn, disconnected, State = #s{mx = MX, cx = CX}) -> + {Unassigned, NextMX, NextCX} = + case mx_lookup_category(Conn, MX) of + conn_attempt -> + {ok, [], ScrubbedCX} cx_disconnected(Conn, attempt, CX), + ScrubbedMX = mx_del_monitor(Conn, conn_attempt, MX), + {[], ScrubbedMX, ScrubbedCX}; + conn -> + {ok, Dropped, ScrubbedCX} = cx_disconnected(Conn, conn, CX), + ScrubbedMX = mx_del_monitor(Conn, conn, MX), + {Dropped, ScrubbedMX, ScrubbedCX} + end, + {NewMX, NewCX} = init_connection(Unassigned, NextMX, NextCX), + State#s{mx = NewMX, cx = NewCX}. + + +-spec init_connection(Realms, MX, CX) -> {NewMX, NewCX} + when Realms :: [zx:realm()], + MX :: monitor_index() + CX :: conn_index(), + NewMX :: monitor_index(), + NewCX :: conn_index(). +%% @private +%% Initiates a single connection and updates the relevant structures. + +init_connection([Realm | Realms], MX, CX) -> + {ok, Host, NextCX} = cx_next_hosts(Realm, CX), + {ok, Pid} = zx_conn:start(Host), + NewMX = mx_add_monitor(Pid, conn_attempt, MX), + NewCX = cx_add_attempt({Pid, Host}, CX), + init_connection(Realms, NewMX, NewCX); +init_connection([], MX, CX) -> + {MX, CX}. + + +-spec do_result(Ref, Result, State) -> NewState + when Ref :: reference(), + Result :: result(), + State :: state(), + NewState :: state(). +%% @private +%% Receive the result of a sent request and route it back to the original requestor. + +do_result(Ref, Result, State = #s{responses = Responses}) -> + NewResponses = + case maps:take(Ref, Responses) of + {{Req, {Type, Object}}, NextResponses} -> + Req ! {result, {Type, Object, Result}}, + NextResponses; + error -> + ok = log(warning, "Received unqueued result ~tp:~tp", [Ref, Result]), + Responses + end, + State#s{responses = NewResponses}. + + +-spec do_notice(Package, Update, State) -> ok + when Package :: zx:package(), + Update :: term(), + State :: state(). +%% @private +%% Forward an update message to the subscriber. + +do_notice(Package, Update, #s{subs = Subs}) -> + case maps:find(Package, Subs) of + {ok, Subscribers} -> + Notify = fun(P) -> P ! {Package, Update} end, + lists:foreach(Notify, Subscribers); + error -> + Message = "Received package update for 0 subscribers: {~tp, ~tp}", + log(warning, Message, [Package, Update]) + end. + + +-spec eval_queue(State) -> NewState + when State :: state(), + NewState :: state(). +%% @private +%% This is one of the two engines that drives everything, the other being do_report/3. +%% This function must iterate as far as it can into the request queue, adding response +%% entries to the pending response structure as it goes. + +eval_queue(State = #s{actions = Actions}) -> + InOrder = lists:reverse(Actions), + eval_queue(InOrder, State#s{actions = []}). + + +eval_queue([], State) -> + State; +eval_queue([Action = {Pid, {subscribe, Package}} | Rest], + State = #s{actions = Actions, subs = Subs, mx = MX, cx = CX}) -> + Realm = element(1, Package), + {NewActions, NewSubs, NewMX} = + case cx_resolve(Realm, CX) of + {ok, Conn} -> + ok = zx_conn:subscribe(Package), + NextSubs = [{Pid, Package} | Subs], + NextMX = mx_add_monitor(Pid, subscriber, MX), + {Actions, NextSubs, NextMX}; + unassigned -> + NextActions = [Action | Actions], + NextMX = mx_add_monitor(Pid, subscriber, MX), + {NextActions, Subs, NextMX}; + unconfigured -> + Pid ! {subscription, Realm, {error, bad_realm}}, + {Actions, Subs, MX} + end, + eval_queue(Rest, State#s{actions = NewActions, subs = NewSubs, mx = NewMX}); +eval_queue([Action = {Pid, {unsubscribe, Package}} | Rest], + State = #s{actions = Actions, subs = Subs, mx = MX, cx = CX}) -> + NewActions = lists:delete(Action, Actions), + NewSubs = lists:delete({Pid, Package}, Subs), + NewMX = mx_del_monitor(Pid, subscriber, MX), + Realm = element(1, Package), + ok = + case cx_resolve(Realm, CX) of + {ok, Conn} -> cx_conn:unsubscribe(Package); + unassigned -> ok + end, + eval_queue(Rest, State#s{actions = NewActions, subs = NewSubs, mx = NewMX}); +eval_queue([{Ref, Pid, {list, realms}} | Rest], State = #s{cx = CX}) -> + Realms = cx_realms(CX), + ok = send_result(Pid, Ref, {list, realms, {ok, Realms}}), + eval_queue(Rest, State); +eval_queue([Action = {Ref, Pid, {list, Realm}} | Rest], + State = #s{actions = Actions, responses = Responses, mx = MX, cx = CX}) + when is_list(Realm) -> + {NewActions, NewResponses, NewMX} = + case cx_resolve(Realm, CX) of + {ok, Conn} -> + ok = cx_conn:list_packages(Conn, Ref), + Request = {Pid, list, Realm}, + NextRequests = maps:put(Ref, Request, Requests), + NextMX = mx_add_monitor(Pid, requestor, MX), + {Actions, NextRequests, NextMX}; + unassigned -> + NextMX = mx_add_monitor(Pid, requestor, MX), + NextActions = [Action | Actions], + {NextActions, Responses, NextMX}; + unconfigured -> + Pid ! {Ref, {list, Realm, {error, bad_realm}}}, + {Actions, Responses, MX} + end, + NewState = State#s{actions = NewActions, responses = NewResponses, mx = NewMX}, + eval_queue(Rest, NewState); +%% FIXME: Universalize the cx_resolve result, leave only message form explicit. +eval_queue([Action = {Ref, Pid, Message} | Actions], + State = #s{actions = Actions, responses = Responses, mx = MX, cx = CX}) + Realm = element(1, element(2, Message)), + {NewActions, NewResponses, NewMX} = + case cx_resolve(Realm, CX) of + {ok, Conn} -> + ok = cx_conn:list_packages(Conn, Ref), + NextResponses = maps:put(Ref, {Pid, Message}, Responses), + NextMX = mx_add_monitor(Pid, requestor, MX), + {Actions, NextResponses, NextMX}; + unassigned -> + NextActions = [Action | Actions], + {NextActions, Responses, MX}; + unconfigured -> + Pid ! {Ref, {list, Realm, {error, bad_realm}}} + {Actions, Responses, MX} + end, + NewState = State#s{actions = NewActions, responses = NewResponses, mx = NewMX}, + eval_queue(Rest, NewState). + + +-spec send_result(pid(), reference(), term()) -> ok. +%% @private +%% Send a message by reference to a process. +%% Probably don't need this function. + +send_result(Pid, Ref, Message) -> + Pid ! {Ref, Message}, + ok. -spec do_query_latest(Object, State) -> {Result, NewState} @@ -443,14 +746,14 @@ do_subscribe(_, _, State = #s{realm = Realm, name = Name}) -> %% Queries a zomp realm for the latest version of a package or package %% version (complete or incomplete version number). -query_latest(Socket, {Realm, Name}) -> - ok = send(Socket, {latest, Realm, Name}), +do_query_latest(Socket, {Realm, Name}) -> + ok = zx_net:send(Socket, {latest, Realm, Name}), receive {tcp, Socket, Bin} -> binary_to_term(Bin) after 5000 -> {error, timeout} end; -query_latest(Socket, {Realm, Name, Version}) -> - ok = send(Socket, {latest, Realm, Name, Version}), +do_query_latest(Socket, {Realm, Name, Version}) -> + ok = zx_net:send(Socket, {latest, Realm, Name, Version}), receive {tcp, Socket, Bin} -> binary_to_term(Bin) after 5000 -> {error, timeout} @@ -471,22 +774,6 @@ do_unsubscribe(State = #s{connp = ConnP, connm = ConnM}) -> {ok, NewState}. --spec do_report(From, Message, State) -> NewState - when From :: pid(), - Message :: conn_report(), - State :: state(), - NewState :: state(). - -do_report(From, {connected, Realms}, State) -> - % FIXME - ok = log(info, - "Would do_report(~tp, {connected, ~tp}, ~tp) here", - [From, Realms, State]), - State. - - - - -spec do_fetch(PackageIDs) -> Result when PackageIDs :: [zx:package_id()], Result :: ok @@ -564,7 +851,120 @@ scrub(Deps) -> -%%% Connection Cache ADT Interface Functions +%%% Monitor Index ADT Interface Functions +%%% +%%% Very simple structure, but explicit handling of it becomes bothersome in other +%%% code, so it is all just packed down here. + +-spec mx_new() -> monitor_index(). +%% @private +%% Returns a new, empty monitor index. + +mx_new() -> []. + + +-spec mx_del_monitor(pid(), category(), monitor_index()) -> monitor_index(). +%% @private +%% Begin monitoring the given Pid, keeping track of its category. + +mx_add_monitor(Pid, subscriber, MX) -> + case lists:keytake(Pid, 2, MX) of + {value, {Ref, Pid, {Subs, Reqs}}, NextMX} -> + [{Ref, Pid, {Subs + 1, Reqs}} | NextMX]; + false -> + Ref = monitor(process, Pid), + [{Ref, Pid, {1, 0}} | MX] + end; +mx_add_monitor(Pid, requestor, MX) -> + case lists:keytake(Pid, 2, MX) of + {value, {Ref, Pid, {Subs, Reqs}}, NextMX} -> + [{Ref, Pid, {Subs, Reqs + 1}} | NextMX]; + false -> + Ref = monitor(process, Pid), + [{Ref, Pid, {0, 1}} | MX] + end; +mx_add_monitor(Pid, conn_attempt, MX) -> + false = lists:keymember(Pid, 2, MX), + Ref = monitor(process, Pid), + [{Ref, Pid, conn_attempt} | MX]; +mx_add_monitor(Pid, conn, MX) -> + {value, {Ref, Pid, conn_attempt}, NextMX} = lists:keytake(Pid, 2, MX), + [{Ref, Pid, conn} | NextMX], + + +-spec mx_del_monitor(pid(), category(), monitor_index()) -> monitor_index(). +%% @private +%% Drop a monitor category, removing the entire monitor in the case only one category +%% exists. + +mx_del_monitor(Pid, subscriber, MX) -> + case lists:keytake(Pid, 2, MX) of + {value, {Ref, Pid, {1, 0}}, NextMX} -> + true = demonitor(Ref, [flush]), + NextMX; + {value, {Ref, Pid, {Subs, Reqs}}, NextMX} -> + [{Ref, Pid, {Subs - 1, Reqs}} | NextMX]; + false -> + MX + end; +mx_del_monitor(Pid, requestor, MX) -> + case lists:keytake(Pid, 2, MX) of + {value, {Ref, Pid, {0, 1}}, NextMX} -> + true = demonitor(Ref, [flush]), + NextMX; + {value, {Ref, Pid, {Subs, Reqs}}, NextMX} -> + [{Ref, Pid, {Subs, Reqs - 1}} | NextMX]; + false -> + MX + end; +mx_del_monitor(Pid, Category, MX) -> + {value, {Ref, Pid, Category}, NewMX} = lists:keytake(Pid, 2, MX), + true = demonitor(Ref, [flush]), + NewMX. + + +-spec mx_lookup_category(pid(), monitor_index()) -> Result + when Result :: conn_attempt + | conn + | requestor + | subscriber + | sub_req + | error. +%% @private +%% Lookup a monitor's categories. + +mx_lookup_category(Pid, MX) -> + case lists:keyfind(Pid, 2, MX) of + {_, _, conn_attempt} -> conn_attempt; + {_, _, conn} -> conn; + {_, _, {0, _}} -> requestor; + {_, _, {_, 0}} -> subscriber; + {_, _, _} -> sub_req; + false -> error + end. + + +-spec mx_upgrade_conn(Pid, MX) -> Result + when Pid :: pid(), + MX :: monitor_index(), + Result :: {ok, NewMX} + | {error, not_found}, + NewMX :: monitor_index(). +%% @private +%% Upgrade a conn_attempt to a conn. + +mx_upgrade_conn(Pid, MX) -> + case lists:keytake(Pid, 2, MX) of + {value, {Ref, Pid, conn_attempt}, NextMX} -> + NewMX = [{Ref, Pid, conn} | NextMX], + {ok, NewMX}; + false -> + {error, not_found} + end. + + + +%%% Connection Index ADT Interface Functions %%% %%% Functions to manipulate the conn_index() data type are in this section. This %%% data should be treated as abstract by functions outside of this section, as it is @@ -880,7 +1280,7 @@ enqueue_unique(Element, Queue) -> -spec cx_disconnected(Conn, CX) -> Result when Conn :: pid(), CX :: conn_index(), - Result :: {ok, Mon, UnassignedRealms, NewCX} + Result :: {ok, UnassignedRealms, NewCX} | {error, unknown}, Mon :: reference(), UnassignedRealms :: [zx:realm()], @@ -891,12 +1291,20 @@ enqueue_unique(Element, Queue) -> %% realms, and returns the monitor reference of the pid, a list of realms that are now %% unassigned, and an updated connection index. -cx_disconnected(Conn, CX = #cx{assigned = Assigned, conns = Conns}) -> - case lists:keytake(Con, Conns) of - {value, {Pid, Mon, Conn}, NewConns} -> - {UnassignedRealms, NewAssigned} = cx_scrub_assigned(Pid, Assigned), +cx_disconnected(Conn, attempt, #cx{attempts = Attempts}) -> + case lists:keytake(Conn, 1, Attempts) of + {value, {Conn, Host}, NewAttempts} -> + NewCX = CX#cx{attempts = NewAttempts}, + {ok, [], NewCX}; + false -> + {error, unknown} + end; +cx_disconnected(Conn, conn, CX = #cx{assigned = Assigned, conns = Conns}) -> + case lists:keytake(Conn, 1, Conns) of + {value, {Conn, Host}, NewConns} -> + {UnassignedRealms, NewAssigned} = cx_scrub_assigned(Conn, Assigned), NewCX = CX#cx{assigned = NewAssigned, conns = NewConns}, - {ok, Mon, UnassignedRealms, NewCX}; + {ok, UnassignedRealms, NewCX}; false -> {error, unknown} end. @@ -927,13 +1335,19 @@ cx_scrub_assigned(_, [], Unassigned, Assigned) -> when Realm :: zx:realm(), CX :: conn_index(), Result :: {ok, Conn :: pid()} - | unassigned. + | unassigned + | unconfigured. %% @private %% Check the registry of assigned realms and return the pid of the appropriate %% connection, or an `unassigned' indication if the realm is not yet connected. -cx_resolve(Realm, #cx{assigned = Assigned}) -> +cx_resolve(Realm, #cx{realms = Realms, assigned = Assigned}) -> case lists:keyfind(Realm, 1, Assigned) of - {Realm, Conn} -> {ok, Conn}; - false -> unassigned + {Realm, Conn} -> + {ok, Conn}; + false -> + case maps:is_key(Realm, Realms) -> + true -> unassigned; + false -> unconfigured + end end. From eac31b0e90bec55b4654ca8b2855811269ca5a06 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Wed, 28 Feb 2018 08:04:21 +0900 Subject: [PATCH 40/55] Blah blah blah --- zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl | 420 +++++++++++++++-------- 1 file changed, 268 insertions(+), 152 deletions(-) diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl index a684394..f2f4704 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl @@ -3,9 +3,29 @@ %%% %%% Resident execution daemon and runtime interface to Zomp. %%% -%%% The daemon lives in the background once started and awaits action requests from -%%% callers running within the system. The daemon is only capable of handling -%%% unprivileged (user) actions such as querying a Zomp node or fetching packages. +%%% The daemon lives in the background once started and awaits query requests and +%%% subscriptions from from other processes. The daemon is only capable of handling +%%% unprivileged (user) actions. +%%% +%%% +%%% Discrete state and local abstract data types +%%% +%%% The daemon must keep track of requestors, subscribers, and zx_conn processes by +%%% using monitors, and because the various types of clients are found in different +%%% locations the monitors are maintained in a data type called monitor_index(), +%%% shortened to "mx" throughout the module. This structure is treated as an opaque +%%% data type and is handled by a set of functions defined toward the end of the module +%%% as mx_*/N. +%%% +%%% Node connections (cx_conn processes) must also be tracked for status and realm +%%% availability. This is done using a type called the conn_index(), shortened to +%%% "cx" throughout the modue. conn_index() is treated as an abstract, opaque data +%%% type across the module in the same way as the monitor_index() mentioned above, +%%% and is handled via a set of cx_*/N functions defined at the end of the module +%%% after the mx_*/N section. +%%% +%%% Do NOT directly access data within these structures, use (or write) an accessor +%%% function that does what you want. %%% %%% %%% Connection handling @@ -14,63 +34,57 @@ %%% http://zxq9.com/archives/1311 %%% It is in charge of the high-level task of servicing requested actions and returning %%% responses to callers as well as mapping successful connections to configured realms -%%% and repairing failed connections to various realms by searching for and directing -%%% that connections be made to various realms to satisfy action request requirements. +%%% and repairing failed connections to nodes that reduce availability of configured +%%% realms. %%% %%% When the zx_daemon is started it checks local configuration and cache files to -%%% determine what realms must be found and what cached Zomp nodes it is aware of. -%%% It populates an internal record #cx{} (typed as conn_index()) with realm config -%%% and host cache data and then immediately initiates three connection attempts to -%%% cached nodes for each realm configured. If a host is known to service more than -%%% one configured realm only one attempt will be made at a time to connect to it. -%%% If all cached hosts for a given realm have been tried already, or if none are -%%% known, then the daemon will direct a connection be made to the prime node. +%%% determine what realms must be available and what cached Zomp nodes it is aware of. +%%% It populates the CX (conn_index(), mentioned above) with realm config and host +%%% cache data, and then immediately initiates three connection attempts to cached +%%% nodes for each realm configured (see init_connections/0). %%% -%%% The conn_index() type is abstract across the module, handled expicitly via use -%%% of manipulation functions called cx_*. The details of index manipulation can -%%% easily litter the code with incidental complexity (as far as a reader is concerned) -%%% so hiding that as abstract data leaves more mental cycles to consider the goals -%%% of the program. +%%% Once connection attempts have been initiated the daemon waits in receive for +%%% either a connection report (success or failure) or an action request from +%%% elsewhere in the system. %%% -%%% Once the connection attempts have been initiated (via zx_conn:start/1) the daemon -%%% waits in receive for either a connection report from a connection or an action -%%% request from elsewhere in the system. +%%% Connection status is relayed with report/1 and indicates to the daemon whether +%%% a connection has failed, been disconneocted, redirected, or succeeded. See the +%%% zx_conn internals for details. If a connection is successful then the zx_conn +%%% will relay the connected node's realm availability status to the daemon, and +%%% the daemon will match the node's provided realms with the configured realm list. +%%% Any realms that are not yet provided by another connection will be assigned to +%%% the reporting successful zx_conn. If no unserviced realms are provided by the +%%% node the zx_conn will be shut down but the host info will be cached for future +%%% use. Any realms that have an older serial than the serial currently known to +%%% zx will be disregarded (which may result in termination of the connection if it +%%% means there are no useful realms available on a given node). %%% -%%% A connection request is made with a call to report/1 and indicates to the daemon -%%% whether a connection has failed, been disconneocted, redirected, or succeeded. -%%% Connection handling is as follows: -%%% - A failure can occur at any time. In the event a connected and assigned zx_conn -%%% has failed (whether it was connected and assigned, or never succeeded at all) the -%%% target host will be dropped from the hosts cache and another attempt will be made -%%% in its place. -%%% - If a connection is disconnected then the host will be placed at the back of the -%%% hosts cache. -%%% - If a connection is redirected then the redirecting host will be placed at the -%%% back of the hosts cache and the list of new Zomp nodes provided by the redirect -%%% will be added at the front of the connect queue. -%%% - In the event a connection succeeds then the list of provided realms and their -%%% current serials will be compared to the list of known realms and serials, and -%%% the host will be added to the relevant realm host index if not already present -%%% and the provided serial is newer than the currently known one (but the realm -%%% serial will not be updated at this point, only the host added). After the -%%% host's record is updated across the realm indices the daemon will assign it to -%%% whatever realms it provides that are not yet services by a connection, and in -%%% the case it does not service any required and unassigned realms it will be -%%% instructed to disconnect. +%%% A failure can occur at any time. In the event a connected and assigned zx_conn +%%% has failed the target host will be dropped from the hosts cache, the zx_conn will +%%% terminate and a new one will be spawned in its place if there is a gap in +%%% configured realm coverage. %%% -%%% Because the daemon always initiates connection attempts on startup success or -%%% failure messages are guaranteed to be received without any need for a timer. For -%%% that reason there is no timed re-inspection mechanism present in this module. +%%% Nodes may be too busy (their client slots full) to accept a new connection. In +%%% this case the node should give the zx_conn a redirect instruction during protocol +%%% negotiation. The zx_conn will report the redirect and host list to the daemon, +%%% and the daemon will add the hosts to the host cache and the redirecting host will +%%% be placed at the rear of the host cache unless it is the prime node for the target +%%% realm. %%% -%%% Action requests are queued within the zx_daemon, so requests to download a package, -%%% for example, look the same as several requests to download several packages. Each -%%% request that requires dispatching to a zx_conn is held in the active action slot -%%% until complete, paired with the pid of the zx_conn handling the action. If a -%%% zx_conn dies before completing an action or between the time an action request is -%%% received by the daemon and dispatch to the zx_conn occurs then the daemon will -%%% receive the terminal monitor message and be able to put the pending action back -%%% into the action queue, re-establish a connection to the necessary realm, and then -%%% re-dispatch the action to the new zx_conn. +%%% +%%% Request queues +%%% +%%% Requests, reports and subscription updates are all either forwarded to affected +%%% processes or entered into a work queue. All such work requests are received as +%%% asynchronous messages and cause the work queue to first be updated, and then, +%%% as a separate step, the work queue is re-evaluated in its entirety. Any work that +%%% cannot be completed (due to a realm not being available, for example) is recycled +%%% to the queue. A connection report also triggers a queue re-evaluation, so there +%%% should not be cases where the work queue stalls on active requests. +%%% +%%% Requestors sending either download or realm query requests are given a reference +%%% to match on for receipt of their result messages or to be used to cancel the +%%% requested work (timeouts are handled by the caller, not by the daemon). %%% %%% A bit of state handling is required (queueing requests and storing the current %%% action state), but this permits the system above the daemon to interact with it in @@ -113,9 +127,8 @@ -record(cx, {realms = #{} :: #{zx:realm() := realm_meta()}, - assigned = [] :: [{zx:realm(), pid()}], - attempts = [] :: [{pid(), zx:host()}], - conns = [] :: [{pid(), zx:host()}]}). + attempts = [] :: [{pid(), zx:host(), [zx:realm()]}], + conns = [] :: [{pid(), zx:host(), [zx:realm()]}]}). -record(rmeta, @@ -126,7 +139,9 @@ mirrors = queue:new() :: queue:queue(zx:host()), realm_keys = [] :: [zx:key_meta()], package_keys = [] :: [zx:key_meta()], - sysops = [] :: [zx:sysop_meta()]}). + sysops = [] :: [zx:sysop_meta()], + assigned = none :: none | pid(), + available = [] :: [pid()]}). %% State Types -type state() :: #s{}. @@ -134,17 +149,20 @@ -type conn_index() :: #cx{}. -type realm_meta() :: #rmeta{}. -type category() :: {Subs :: non_neg_integer(), Reqs :: non_neg_integer()} - | conn_attempt + | attempt | conn. %% Conn Communication -type conn_report() :: {connected, Realms :: [{zx:realm(), zx:serial()}]} + | {redirect, Hosts :: [zx:host()]} | disconnected. %% Subscriber / Requestor Communication % Incoming Request messages --type request() :: {Requestor :: pid(), Action :: action() | subunsub()}. --type action() :: {list, realms | zx:identifier()} +-type action () :: {Requestor :: pid(), + Request :: request() | subunsub()}. + +-type request() :: {list, realms | zx:identifier()} | {latest, zx:identifier()} | {fetch, zx:package_id()} | {key, zx:key_id()} @@ -156,6 +174,12 @@ | {unsubscribe, zx:package()}. % Outgoing Result Messages +% +% Results are sent wrapped a triple: {result, Ref, Result} +% where the result itself is a triple: {Type, Identifier, Content} +% +% Subscription messages are a separate type below. + -type result() :: sub_result() | list_result() | latest_result() @@ -165,9 +189,6 @@ | pack_result() | maint_result() | sysop_result(). --type sub_result() :: {subscription, zx:package(), - Message :: {update, zx:package_id()} - | {error, bad_realm | bad_package}}. -type list_result() :: {list, realms, Message :: {ok, [zx:realm()]}} | {list, zx:realm(), @@ -177,7 +198,7 @@ Message :: {ok, [zx:version]} | {error, bad_realm | bad_package - | timeout}} + | timeout}}. -type latest_result() :: {latest, Package :: zx:package() | zx:package_id(), @@ -218,6 +239,12 @@ | timeout}. +% Subscription Results +-type sub_message() :: {subscription, zx:package(), + Message :: {update, zx:package_id()} + | {error, bad_realm | bad_package}}. + + %%% Requestor Interface -spec pass_meta(Meta, Dir, ArgV) -> ok @@ -240,19 +267,12 @@ pass_meta(Meta, Dir, ArgV) -> gen_server:cast(?MODULE, {pass_meta, Meta, Dir, ArgV}). --spec subscribe(Package) -> Result - when Package :: zx:package(), - Result :: ok - | {error, Reason}, - Reason :: illegal_requestor - | {already_subscribed, zx:package()}. +-spec subscribe(Package) -> ok + when Package :: zx:package(). %% @doc %% Subscribe to update notification for a for a particular package. -%% The daemon is designed to monitor a single package at a time, so a second call to -%% subscribe/1 will return an `already_subscribed' error, or possibly an -%% `illegal_requestor' error in the case that a second call is made from a different -%% process than the original requestor. -%% Other functions can be used to query the status of a package at an arbitrary time. +%% The caller will receive update notifications of type sub_result() as Erlang +%% messages whenever an update occurs. subscribe(Package) -> gen_server:cast(?MODULE, {subscribe, self(), Package}). @@ -354,7 +374,7 @@ request(Action) -> -%%% Connection interface +%%% Upstream Zomp connection interface -spec report(Message) -> ok when Message :: {connected, Realms :: [{zx:realm(), zx:serial()}]} @@ -402,7 +422,7 @@ start_link() -> init(none) -> {ok, MX, CX} = init_connections(), - State = #s{mx = MX, cx = NewCX}, + State = #s{mx = MX, cx = CX}, {ok, State}. @@ -413,15 +433,20 @@ init_connections() -> init_connections(Realms, MX, CX). -init_connections([Realm | Realms], Monitors, CX) -> +init_connections([Realm | Realms], MX, CX = #cx{attempts = Attempts}) -> {ok, Hosts, NextCX} = cx_next_hosts(3, Realm, CX), StartConn = - fun(Host) -> - {ok, Pid} = zx_conn:start(Host), - {Pid, Host} + fun(Host, A) -> + case lists:keymember(Host, 2, Attempts) of + false -> + {ok, Pid} = zx_conn:start(Host), + [{Pid, Host} | A]; + true -> + A + end end, - NewAttempts = lists:map(StartConn, Hosts), - AddMonitor = fun({P, _}, M) -> mx_add_monitor(P, conn_attempt, M) end, + NewAttempts = lists:foldl(StartConn, [], Hosts), + AddMonitor = fun({P, _}, M) -> mx_add_monitor(P, attempt, M) end, NewMX = lists:foldl(AddMonitor, MX, NewAttempts), NewCX = lists:foldl(fun cx_add_attempt/2, NextCX, NewAttempts), init_connections(Realms, NewMX, NewCX); @@ -556,16 +581,21 @@ do_report(Conn, {connected, Realms}, State = #s{mx = MX, cx = CX}) -> {ScrubbedMX, NextCX} end, State#s{mx = NewMX, cx = NewCX}; +do_report(Conn, {redirect, Hosts}, State = #s{mx = MX, cx = CX}) -> + NextMX = mx_del_monitor(Conn, attempt, MX), + {Unassigned, NextCX} = cx_redirect(Conn, Hosts, CX), + {NewMX, NewCX} = init_connection(Unassigned, NextMX, NextCX) + State#s{mx = NewMX, cx = NewCX}; do_report(Conn, disconnected, State = #s{mx = MX, cx = CX}) -> {Unassigned, NextMX, NextCX} = case mx_lookup_category(Conn, MX) of - conn_attempt -> - {ok, [], ScrubbedCX} cx_disconnected(Conn, attempt, CX), - ScrubbedMX = mx_del_monitor(Conn, conn_attempt, MX), + attempt -> + ScrubbedMX = mx_del_monitor(Conn, attempt, MX), + ScrubbedCX = cx_failed(Conn, CX), {[], ScrubbedMX, ScrubbedCX}; conn -> - {ok, Dropped, ScrubbedCX} = cx_disconnected(Conn, conn, CX), ScrubbedMX = mx_del_monitor(Conn, conn, MX), + {ok, Dropped, ScrubbedCX} = cx_disconnected(Conn, conn, CX), {Dropped, ScrubbedMX, ScrubbedCX} end, {NewMX, NewCX} = init_connection(Unassigned, NextMX, NextCX), @@ -581,11 +611,21 @@ do_report(Conn, disconnected, State = #s{mx = MX, cx = CX}) -> %% @private %% Initiates a single connection and updates the relevant structures. -init_connection([Realm | Realms], MX, CX) -> - {ok, Host, NextCX} = cx_next_hosts(Realm, CX), - {ok, Pid} = zx_conn:start(Host), - NewMX = mx_add_monitor(Pid, conn_attempt, MX), - NewCX = cx_add_attempt({Pid, Host}, CX), +init_connection([Realm | Realms], MX, CX = #cx{realms = Metas}) -> + {NewMX, NewCX} = + case maps:get(Realm) of + #rmeta{available = []} -> + {ok, Host, UpdatedCX} = cx_next_hosts(Realm, CX), + {ok, Pid} = zx_conn:start(Host), + NextMX = mx_add_monitor(Pid, attempt, MX), + NextCX = cx_add_attempt({Pid, Host}, UpdatedCX), + {NextMX, NextCX}; + Meta = #rmeta{available = [Conn | Conns]} -> + NewMeta = Meta#rmeta{assigned = Conn, available = Conns}, + NewMetas = maps:put(Realm, NewMeta, Metas), + NextCX = CX#cx{realms = NewMetas}, + {MX, NewCX} + end, init_connection(Realms, NewMX, NewCX); init_connection([], MX, CX) -> {MX, CX}. @@ -883,12 +923,12 @@ mx_add_monitor(Pid, requestor, MX) -> Ref = monitor(process, Pid), [{Ref, Pid, {0, 1}} | MX] end; -mx_add_monitor(Pid, conn_attempt, MX) -> +mx_add_monitor(Pid, attempt, MX) -> false = lists:keymember(Pid, 2, MX), Ref = monitor(process, Pid), - [{Ref, Pid, conn_attempt} | MX]; + [{Ref, Pid, attempt} | MX]; mx_add_monitor(Pid, conn, MX) -> - {value, {Ref, Pid, conn_attempt}, NextMX} = lists:keytake(Pid, 2, MX), + {value, {Ref, Pid, attempt}, NextMX} = lists:keytake(Pid, 2, MX), [{Ref, Pid, conn} | NextMX], @@ -924,7 +964,7 @@ mx_del_monitor(Pid, Category, MX) -> -spec mx_lookup_category(pid(), monitor_index()) -> Result - when Result :: conn_attempt + when Result :: attempt | conn | requestor | subscriber @@ -935,7 +975,7 @@ mx_del_monitor(Pid, Category, MX) -> mx_lookup_category(Pid, MX) -> case lists:keyfind(Pid, 2, MX) of - {_, _, conn_attempt} -> conn_attempt; + {_, _, attempt} -> attempt; {_, _, conn} -> conn; {_, _, {0, _}} -> requestor; {_, _, {_, 0}} -> subscriber; @@ -951,11 +991,11 @@ mx_lookup_category(Pid, MX) -> | {error, not_found}, NewMX :: monitor_index(). %% @private -%% Upgrade a conn_attempt to a conn. +%% Upgrade a attempt to a conn. mx_upgrade_conn(Pid, MX) -> case lists:keytake(Pid, 2, MX) of - {value, {Ref, Pid, conn_attempt}, NextMX} -> + {value, {Ref, Pid, attempt}, NextMX} -> NewMX = [{Ref, Pid, conn} | NextMX], {ok, NewMX}; false -> @@ -1002,19 +1042,22 @@ cx_populate() -> Pattern = filename:join(Home, "*.realm"), case filelib:wildcard(Pattern) of [] -> {error, no_realms}; - RealmFiles -> cx_fetch_cache(RealmFiles, #cx{}) + RealmFiles -> {ok, cx_populate(RealmFiles, #cx{})} end. cx_populate([File | Files], CX) -> case file:consult(File) of {ok, Meta} -> - cx_load_realm_meta(Meta, CX); + NewCX = cx_load_realm_meta(Meta, CX), + cx_populate(Files, NewCX); {error, Reason} -> Message = "Realm file ~tp could not be read. Failed with: ~tp. Skipping.", ok = log(warning, Message, [File, Reason]), - populate(Files, CX) - end. + cx_populate(Files, CX) + end; +cx_populate([], CX) -> + CX. cx_load_realm_meta(Meta, CX = #cx{realms = Realms}) -> @@ -1167,10 +1210,11 @@ cx_next_host3(Meta = #rmeta{prime = Prime, private = Privae, mirrors = Mirrors}) %% of a given realm, taking private mirrors first, then public mirrors, and ending %% with the prime node for the realm if no others exist. -cx_next_hosts(N, Realm, CX = #cx{assigned = Assigned}) -> - case lists:keymember(Realm, 1, Assigned) of - false -> cx_next_hosts2(N, Realm, CX); - true -> {error, connected} +cx_next_hosts(N, Realm, CX = #cx{realms = Realms}) -> + case maps:find(Realm, Realms) of + {ok, #rmeta{assigned = none}} -> cx_next_hosts2(N, Realm, CX); + {ok, _} -> {error, connected}; + error -> {error, bad_realm} end. @@ -1195,7 +1239,7 @@ cx_next_hosts3(N, Hosts, Meta) -> -spec cx_add_attempt(New, CX) -> NewCX - when New :: {pid(), reference(), zx:host()}, + when New :: {pid(), zx:host()}, CX :: conn_index(), NewCX :: conn_index(). @@ -1218,19 +1262,20 @@ cx_add_attempt(New, CX = #cx{attempts = Attempts}) -> %% The return value is a tuple that indicates whether the new connection was assigned %% or not and the updated CX data value. -cx_connected(Available, Conn, CX) -> - cx_connected(unassigned, Available, Conn, CX). +cx_connected(Available, Conn, CX = #cx{attempts = Attempts, conns = Conns}) -> + {value, {Conn, Host}, NewAttempts} = lists:keytake(Conn, 1, Attempts), + Realms = [element(1, A) || A <- Available], + NewConns = [{Conn, Host, Realms} | Conns], + NewCX = CX#cx{attempts = NewAttempts, conns = NewConns}, + cx_connected(unassigned, Available, Conn, NewCX). cx_connected(A, [{Realm, Serial} | Rest], Conn, CX = #cx{realms = Realms}) -> case maps:find(Realm, Realms) of - {ok, Meta = #rmeta{serial = S}} when S < Serial -> - NewMeta = Meta#rmeta{serial = Serial}, + {ok, Meta = #rmeta{serial = S, available = Available}} when S =< Serial -> + NewMeta = Meta#rmeta{serial = Serial, available = [Conn | Available]}, {NewA, NewCX} = cx_connected(A, Realm, Conn, NewMeta, CX), cx_connected(NewA, Rest, Conn, NewCX); - {ok, Meta = #rmeta{serial = S}} when S == Serial -> - {NewA, NewCX} = cx_connected(A, Realm, Conn, Meta, CX), - cx_connected(NewA, Rest, Conn, NewCX); {ok, #rmeta{serial = S}} when S > Serial -> cx_connected(A, Rest, Conn, CX); error -> @@ -1247,11 +1292,11 @@ cx_connected(A, Realm, Conn, Meta = #rmeta{prime = Prime, mirrors = Mirrors}, - CX = #cx{realms = Realms, assigned = Assigned, attempts = Attempts}) -> + CX = #cx{realms = Realms, attempts = Attempts}) -> {NewMirrors, Node} = case lists:keyfind(Conn, 1, Attempts) of - {_, _, Prime} -> {Mirrors, Prime}; - {_, _, Host} -> {enqueue_unique(Host, Mirrors), Host} + {_, Prime} -> {Mirrors, Prime}; + {_, Host} -> {enqueue_unique(Host, Mirrors), Host} end, {NewA, NewAssigned} = case lists:keymember(Realm, 1, Assigned) of @@ -1277,6 +1322,72 @@ enqueue_unique(Element, Queue) -> end. +-spec cx_failed(Conn, CX) -> NewCX + when Conn :: pid(), + CX :: conn_index(), + NewCX :: conn_index(). +%% @private +%% Remove a failed attempt and all its associations. + +cx_failed(Conn, #cx{attempts = Attempts}) -> + NewAttempts = lists:keydelete(Conn, 1, Attempts), + CX#cx{attempts = NewAttempts}. + + +-spec cx_redirect(Conn, Hosts, CX) -> {Unassigned, NextCX} + when Conn :: pid(), + Hosts :: [{zx:host(), [zx:realm()]}], + CX :: conn_index(), + Unassigned :: [zx:realm()], + NextCX :: conn_index(). + +cx_redirect(Conn, Hosts, CX) -> + NextCX = cx_failed(Conn, CX), + NewCX = #cx{realms = Realms} = cx_redirect(Hosts, NextCX), + Unassigned = cx_unassigned(NewCX), + {Unassigned, NewCX}. + + +-spec cx_redirect(Hosts, CX) -> NewCX + when Hosts :: [{zx:host(), [zx:realm()]}], + CX :: conn_index(), + NextCX :: conn_index(). +%% @private +%% Add host to any realm mirror queues that are known to provide the realm. + +cx_redirect([{Host, Provided} | Rest], CX = #cx{realms = Realms}) -> + Apply = + fun(R, M) -> + case maps:find(R, M) of + {ok, Meta = #rmeta{mirrors = Mirrors}} -> + NewMirrors = + case queue:member(Host, Mirrors) of + true -> Mirrors; + false -> queue:in(Host, Mirrors) + end, + NewMeta = Meta#rmeta{mirrors = NewMirrors}, + maps:put(R, Meta, M); + error -> + M + end + end, + NewRealms = lists:foldl(Apply, Realms, Provided), + cx_redirect(Rest, CX#cx{realms = NewRealms}); +cx_redirect([], CX) -> + CX. + + +cx_unassigned(#cx{realms = Realms}) -> + NotAssigned = + fun(Realm, #rmeta{assigned = Conn}, Unassigned) -> + case Conn == none of + true -> [Realm | Unassigned]; + false -> Unassigned + end + end, + maps:fold(NotAssigned, [], Realms). + + -spec cx_disconnected(Conn, CX) -> Result when Conn :: pid(), CX :: conn_index(), @@ -1291,44 +1402,53 @@ enqueue_unique(Element, Queue) -> %% realms, and returns the monitor reference of the pid, a list of realms that are now %% unassigned, and an updated connection index. -cx_disconnected(Conn, attempt, #cx{attempts = Attempts}) -> - case lists:keytake(Conn, 1, Attempts) of - {value, {Conn, Host}, NewAttempts} -> - NewCX = CX#cx{attempts = NewAttempts}, - {ok, [], NewCX}; - false -> - {error, unknown} - end; -cx_disconnected(Conn, conn, CX = #cx{assigned = Assigned, conns = Conns}) -> +cx_disconnected(Conn, CX = #cx{realms = Realms, conns = Conns}) -> case lists:keytake(Conn, 1, Conns) of - {value, {Conn, Host}, NewConns} -> - {UnassignedRealms, NewAssigned} = cx_scrub_assigned(Conn, Assigned), - NewCX = CX#cx{assigned = NewAssigned, conns = NewConns}, + {value, {Conn, Host, Realms}, NewConns} -> + {UnassignedRealms, NewRealms} = cx_scrub_assigned(Conn, Host, Realms), + NewCX = CX#cx{realms = NewRealms, conns = NewConns}, {ok, UnassignedRealms, NewCX}; false -> {error, unknown} end. --spec cx_scrub_assigned(Pid, Assigned) -> {UnassignedRealms, NewAssigned} +-spec cx_scrub_assigned(Pid, Host, Realms) -> {UnassignedRealms, NewRealms} when Pid :: pid(), - Assigned :: [{zx:realm(), pid()}], + Host :: zx:host(), + Realms :: realm_meta(), UnassignedRealms :: [zx:realm()], - NewAssigned :: [{zx:realm(), pid()}]. + NewRealms :: realm_meta(). %% @private %% This could have been performed as a set of two list operations (a partition and a %% map), but to make the procedure perfectly clear it is written out explicitly. -cx_scrub_assigned(Pid, Assigned) -> - cx_scrub_assigned(Pid, Assigned, [], []). - - -cx_scrub_assigned(Pid, [{Realm, Pid} | Rest], Unassigned, Assigned) -> - cx_scrub_assigned(Pid, Rest, [Realm | Unassigned], Assigned); -cx_scrub_assigned(Pid, [A | Rest], Unassigned, Assigned) -> - cx_scrub_assigned(Pid, Rest, Unassigned, [A | Assigned]); -cx_scrub_assigned(_, [], Unassigned, Assigned) -> - {Unassigned, Assigned}. +cx_scrub_assigned(Pid, Host, Realms) -> + Scrub = + fun + (Realm, + Meta = #rmeta{mirrors = Mirrors, + assigned = Assigned, + available = Available}, + {Unassigned, Metas}) -> + {NewUnassigned, NewAssigned} = + case Assigned of + Pid -> {[Realm | Unassigned], none}; + Other -> {Unassigned, Other} + end, + NewMirrors = + case queue:member(Host, Mirrors) of + false -> queue:in(Host, Mirrors); + true -> Mirrors + end, + NewAvailable = lists:delete(Pid, Available), + NewMeta = Meta#rmeta{mirrors = NewMirrors, + assigned = NewAssigned, + available = NewAvailable}, + NewMetas = maps:put(Realm, NewMeta, Metas), + {NewUnassigned, NewMetas} + end, + maps:fold(Scrub, {[], maps:new()}, Realms). -spec cx_resolve(Realm, CX) -> Result @@ -1341,13 +1461,9 @@ cx_scrub_assigned(_, [], Unassigned, Assigned) -> %% Check the registry of assigned realms and return the pid of the appropriate %% connection, or an `unassigned' indication if the realm is not yet connected. -cx_resolve(Realm, #cx{realms = Realms, assigned = Assigned}) -> - case lists:keyfind(Realm, 1, Assigned) of - {Realm, Conn} -> - {ok, Conn}; - false -> - case maps:is_key(Realm, Realms) -> - true -> unassigned; - false -> unconfigured - end +cx_resolve(Realm, #cx{realms = Realms}) -> + case maps:find(Realm, Realms) of + {ok, #rmeta{assigned = none}} -> unassigned; + {ok, #rmeta{assigned = Conn}} -> {ok, Conn}; + error -> unconfigured end. From 62385cd088cf7ffeb31021f95327c5ab095678a0 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Mon, 5 Mar 2018 00:24:09 +0900 Subject: [PATCH 41/55] blah --- TODO | 17 + zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl | 734 ++++++++++++++--------- 2 files changed, 469 insertions(+), 282 deletions(-) create mode 100644 TODO diff --git a/TODO b/TODO new file mode 100644 index 0000000..52ccf5f --- /dev/null +++ b/TODO @@ -0,0 +1,17 @@ + - zomp nodes must report the realms they provide to upstream nodes to which they connect. + On redirect a list of hosts of the form [{zx:host(), [zx:realm()]}] must be provided to the downstream client. + This is the only way that downstream clients can determine which redirect hosts are useful to it. + + - The ZX daemon should be able to retry requests that were submitted but did not receive a response before the relevant + connection was terminated for whatever reason. + The most obvious way to do this would be to keep a set or queue of references in each connection monitor's section, + clearing them when they receive responses, and pushing them back into the action queue (from the responses reference map) + when they fail. + + - The same issue as the one above, but with subscriptions. Currently there is no obvious way to track what subscriptions flow + through which connections, and on termination or change of a connection there is no way to ensure that the subscription request + finds its way back into the action queue to resubmission once a realm becomes available again. + + - The request tracking ref list is currently passing through the MX record. That is exactly the wrong place to put it. + It should DEFINITELY be in the CX record. + MOVE IT. diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl index f2f4704..352839b 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl @@ -3,7 +3,7 @@ %%% %%% Resident execution daemon and runtime interface to Zomp. %%% -%%% The daemon lives in the background once started and awaits query requests and +%%% The daemon resides in the background once started and awaits query requests and %%% subscriptions from from other processes. The daemon is only capable of handling %%% unprivileged (user) actions. %%% @@ -18,11 +18,10 @@ %%% as mx_*/N. %%% %%% Node connections (cx_conn processes) must also be tracked for status and realm -%%% availability. This is done using a type called the conn_index(), shortened to -%%% "cx" throughout the modue. conn_index() is treated as an abstract, opaque data -%%% type across the module in the same way as the monitor_index() mentioned above, -%%% and is handled via a set of cx_*/N functions defined at the end of the module -%%% after the mx_*/N section. +%%% availability. This is done using a type called conn_index(), shortened to "cx" +%%% throughout the module. conn_index() is treated as an abstract, opaque datatype +%%% throughout the module, and is handled via a set of cx_*/N functions (after the +%%% mx_*/N section). %%% %%% Do NOT directly access data within these structures, use (or write) an accessor %%% function that does what you want. @@ -41,7 +40,7 @@ %%% determine what realms must be available and what cached Zomp nodes it is aware of. %%% It populates the CX (conn_index(), mentioned above) with realm config and host %%% cache data, and then immediately initiates three connection attempts to cached -%%% nodes for each realm configured (see init_connections/0). +%%% nodes for each realm configured (if possible; see init_connections/0). %%% %%% Once connection attempts have been initiated the daemon waits in receive for %%% either a connection report (success or failure) or an action request from @@ -88,7 +87,9 @@ %%% %%% A bit of state handling is required (queueing requests and storing the current %%% action state), but this permits the system above the daemon to interact with it in -%%% a blocking way, but zx_daemon and zx_conn to work asynchronously with one another. +%%% a blocking way, establishing its own receive timeouts or implementing either an +%%% asynchronous or synchronous interface library atop zx_daemon interface function, +%%% but leaving zx_daemon and zx_conn alone to work asynchronously with one another. %%% @end -module(zx_daemon). @@ -103,7 +104,7 @@ list/1, latest/1, fetch/1, key/1, pending/1, packagers/1, maintainers/1, sysops/1]). --export([report/1, result/2, notice/2]). +-export([report/1, result/2, notify/2]). -export([start_link/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, code_change/3, terminate/2]). @@ -115,20 +116,20 @@ %%% Type Definitions -record(s, - {meta = none :: none | zx:package_meta(), - home = none :: none | file:filename(), - argv = none :: none | [string()], - actions = [] :: [request() | {reference(), request()}], - responses = maps:new() :: #{reference() := request()}, - subs = [] :: [{pid(), zx:package()}], - mx = mx_new() :: monitor_index(), - cx = cx_load() :: conn_index()}). + {meta = none :: none | zx:package_meta(), + home = none :: none | file:filename(), + argv = none :: none | [string()], + actions = [] :: [request() | {reference(), request()}], + requests = maps:new() :: #{reference() := request()}, + subs = [] :: [{pid(), zx:package()}], + mx = mx_new() :: monitor_index(), + cx = cx_load() :: conn_index()}). -record(cx, {realms = #{} :: #{zx:realm() := realm_meta()}, attempts = [] :: [{pid(), zx:host(), [zx:realm()]}], - conns = [] :: [{pid(), zx:host(), [zx:realm()]}]}). + conns = [] :: [connection()]}). -record(rmeta, @@ -143,11 +144,21 @@ assigned = none :: none | pid(), available = [] :: [pid()]}). + +-record(conn, + {pid :: pid(), + host :: zx:host(), + realms :: [zx:realm()], + requests :: [reference()], + subs :: [zx:package()]}). + + %% State Types -type state() :: #s{}. --type monitor_index() :: [{reference(), pid(), category()}], +-type monitor_index() :: [{reference(), pid(), category()}]. -type conn_index() :: #cx{}. -type realm_meta() :: #rmeta{}. +-type connection() :: #conn{}. -type category() :: {Subs :: non_neg_integer(), Reqs :: non_neg_integer()} | attempt | conn. @@ -180,7 +191,7 @@ % % Subscription messages are a separate type below. --type result() :: sub_result() +-type result() :: sub_message() | list_result() | latest_result() | fetch_result() @@ -195,7 +206,7 @@ Message :: {ok, [zx:name()]} | {error, bad_realm | timeout}} | {list, zx:package(), - Message :: {ok, [zx:version]} + Message :: {ok, [zx:version()]} | {error, bad_realm | bad_package | timeout}}. @@ -236,7 +247,7 @@ -type sysop_result() :: {sysops, zx:realm(), Message :: {ok, [zx:user()]} | {error, bad_host - | timeout}. + | timeout}}. % Subscription Results @@ -262,15 +273,23 @@ %% be known whether the very first thing the target application will do is send this %% process an async message. That implies that this should only ever be called once, %% by the launching process (which normally terminates shortly thereafter). +%% +%% FIXME: I don't like something about this idea. Either it is wrong to be passing in +%% the primary project's meta, or it is wrong to be doing it this way, or it is +%% wrong to have only *one* primary app in the EVM instance. Or something. +%% Something smells off about this. +%% We WILL need to maintain and know meta. +%% We DON'T know when or why it will be important to running programs. +%% Once we understand this better we need to come back and fix or replace it. +%% (2018-03-01 -CRE) pass_meta(Meta, Dir, ArgV) -> gen_server:cast(?MODULE, {pass_meta, Meta, Dir, ArgV}). --spec subscribe(Package) -> ok - when Package :: zx:package(). +-spec subscribe(zx:package()) -> ok. %% @doc -%% Subscribe to update notification for a for a particular package. +%% Subscribe to update notifications for a for a particular package. %% The caller will receive update notifications of type sub_result() as Erlang %% messages whenever an update occurs. @@ -297,7 +316,7 @@ list(Identifier) -> request({list, Identifier}). --spec latest(Identifier) -> ok. +-spec latest(Identifier) -> ok when Identifier :: zx:package() | zx:package_id(). %% @doc %% Request the lastest version of a package within the scope of the identifier. @@ -370,7 +389,7 @@ sysops(Realm) -> %% Private function to wrap the necessary bits up. request(Action) -> - gen_server:cast(?MODULE, {request, make_ref(), self(), Action}), + gen_server:cast(?MODULE, {request, make_ref(), self(), Action}). @@ -394,10 +413,10 @@ report(Message) -> %% Return a tagged result back to the daemon to be forwarded to the original requestor. result(Reference, Result) -> - gen_server:cast(?MODULE, {result, Reference, Result}). + gen_server:cast(?MODULE, {result, self(), Reference, Result}). --spec notice(Package, Message) -> ok +-spec notify(Package, Message) -> ok when Package :: zx:package(), Message :: term(). %% @private @@ -426,6 +445,16 @@ init(none) -> {ok, State}. +-spec init_connections() -> {ok, MX, CX} + when MX :: monitor_index(), + CX :: conn_index(). +%% @private +%% Starting from a stateless condition, recruit and resolve all realm relevant data, +%% populate host caches, and initiate connections to required realms. On completion +%% return a populated MX and CX to the caller. Should only ever be called by init/1. +%% Returns an `ok' tuple to disambiguate it from pure functions *and* to leave an +%% obvious place to populate error returns in the future if desired. + init_connections() -> CX = cx_load(), MX = mx_new(), @@ -433,22 +462,28 @@ init_connections() -> init_connections(Realms, MX, CX). -init_connections([Realm | Realms], MX, CX = #cx{attempts = Attempts}) -> +-spec init_connections(Realms, MX, CX) -> {ok, NewMX, NewCX} + when Realms :: [zx:realm()], + MX :: monitor_index(), + CX :: conn_index(), + NewMX :: monitor_index(), + NewCX :: conn_index(). + +init_connections([Realm | Realms], MX, CX) -> {ok, Hosts, NextCX} = cx_next_hosts(3, Realm, CX), - StartConn = - fun(Host, A) -> - case lists:keymember(Host, 2, Attempts) of - false -> + MaybeAttempt = + fun(Host, {M, C}) -> + case cx_maybe_add_attempt(Host, Realm, C) of + not_connected -> {ok, Pid} = zx_conn:start(Host), - [{Pid, Host} | A]; - true -> - A + NewM = mx_add_monitor(Pid, attempt, M), + NewC = cx_add_attempt(Pid, Host, Realm, C), + {NewM, NewC}; + {ok, NewC} -> + {M, NewC} end end, - NewAttempts = lists:foldl(StartConn, [], Hosts), - AddMonitor = fun({P, _}, M) -> mx_add_monitor(P, attempt, M) end, - NewMX = lists:foldl(AddMonitor, MX, NewAttempts), - NewCX = lists:foldl(fun cx_add_attempt/2, NextCX, NewAttempts), + {NewMX, NewCX} = lists:foldl(MaybeAttempt, {MX, NextCX}, Hosts), init_connections(Realms, NewMX, NewCX); init_connections([], MX, CX) -> {ok, MX, CX}. @@ -468,32 +503,32 @@ handle_call(Unexpected, From, State) -> %% @private %% gen_server callback for OTP casts +handle_cast({pass_meta, Meta, Dir, ArgV}, State) -> + NewState = do_pass_meta(Meta, Dir, ArgV, State), + {noreply, NewState}; +handle_cast({subscribe, Pid, Package}, State) -> + NextState = do_subscribe(Pid, Package, State), + NewState = eval_queue(NextState), + {noreply, NewState}; +handle_cast({unsubscribe, Pid, Package}, State) -> + NextState = do_unsubscribe(Pid, Package, State), + NewState = eval_queue(NextState), + {noreply, NewState}; +handle_cast({request, Ref, Requestor, Action}, State) -> + NextState = do_request(Ref, Requestor, Action, State), + NewState = eval_queue(NextState), + {noreply, NewState}; handle_cast({report, Conn, Message}, State) -> NextState = do_report(Conn, Message, State), NewState = eval_queue(NextState), {noreply, NewState}; -handle_cast({request, Ref, Requestor, Action}, State) -> - NextState = do_request(Ref, Requestpr, Action, State), - NewState = eval_queue(NextState), - {noreply, NewState}; -handle_cast({result, Ref, Result}, State) -> - NextState = do_result(Ref, Result, State), +handle_cast({result, Conn, Ref, Result}, State) -> + NextState = do_result(Conn, Ref, Result, State), NewState = eval_queue(NextState), {noreply, NewState}; handle_cast({notice, Package, Update}, State) -> ok = do_notice(Package, Update, State), {noreply, State}; -handle_cast({subscribe, Pid, Package}, State) -> - NextState = do_request(subscribe, Pid, Package, State), - NewState = eval_queue(NextState), - {noreply, NewState}; -handle_cast({unsubscribe, Pid, Package}, State) -> - NextState = do_request(unsubscribe, Pid, Package, State), - NewState = eval_queue(NextState), - {noreply, NewState}; -handle_cast({pass_meta, Meta, Dir, ArgV}, State) -> - NewState = do_pass_meta(Meta, Dir, ArgV, State), - {noreply, NewState}; handle_cast(Unexpected, State) -> ok = log(warning, "Unexpected cast: ~tp", [Unexpected]), {noreply, State}. @@ -540,23 +575,43 @@ do_pass_meta(Meta, Home, ArgV, State) -> State#s{meta = Meta, home = Home, argv = ArgV}. --spec do_request(Ref, Req, Action, State) -> NextState +-spec do_subscribe(Pid, Package, State) -> NextState + when Pid :: pid(), + Package :: zx:package(), + State :: state(), + NextState :: state(). +%% @private +%% Enqueue a subscription request. + +do_subscribe(Pid, Package, State = #s{actions = Actions}) -> + NewActions = [{Pid, {subscribe, Package}} | Actions], + State#s{actions = NewActions}. + + +-spec do_unsubscribe(Pid, Package, State) -> NextState + when Pid :: pid(), + Package :: zx:package(), + State :: state(), + NextState :: state(). +%% @private +%% Clear or dequeue a subscription request. + +do_unsubscribe(Pid, Package, State = #s{actions = Actions}) -> + NewActions = [{Pid, {unsubscribe, Package}} | Actions], + State#s{actions = NewActions}. + + +-spec do_request(Ref, Requestor, Action, State) -> NextState when Ref :: reference(), - Req :: pid(), + Requestor :: pid(), Action :: action(), State :: state(), NextState :: state(). %% @private %% Enqueue requests and update relevant index. -do_request(subscribe, Req, Package, State = #s{actions = Actions}) -> - NewActions = [{Req, {subscribe, Package}} | Actions], - State#s{actions = NewActions}; -do_request(unsubscribe, Req, Package, State = #s{actions = Actions}) -> - NewActions = [{Req, {unsubscribe, Package}} | Actions], - State#s{actions = NewActions}; -do_request(Ref, Req, Action, State = #s{actions = Actions}) -> - NewActions = [{Ref, Req, Action} | Actions], +do_request(Ref, Requestor, Action, State = #s{actions = Actions}) -> + NewActions = [{Ref, Requestor, Action} | Actions], State#s{actions = NewActions}. @@ -566,90 +621,98 @@ do_request(Ref, Req, Action, State = #s{actions = Actions}) -> State :: state(), NewState :: state(). %% @private -%% Receive a report from a connection process and update the connection index and +%% Receive a report from a connection process, and update the connection index and %% possibly retry connections. do_report(Conn, {connected, Realms}, State = #s{mx = MX, cx = CX}) -> - {ok, NextMX} = mx_swap_categories(Conn, MX), + NextMX = mx_upgrade_conn(Conn, MX), {NewMX, NewCX} = case cx_connected(Realms, Conn, CX) of {assigned, NextCX} -> {NextMX, NextCX}; {unassigned, NextCX} -> - ScrubbedMX = mx_del_monitor(Conn, conn, NextMX), + {ok, ScrubbedMX, []} = mx_del_monitor(Conn, conn, NextMX), ok = zx_conn:stop(Conn), {ScrubbedMX, NextCX} end, State#s{mx = NewMX, cx = NewCX}; do_report(Conn, {redirect, Hosts}, State = #s{mx = MX, cx = CX}) -> - NextMX = mx_del_monitor(Conn, attempt, MX), + {ok, NextMX} = mx_del_monitor(Conn, attempt, MX), {Unassigned, NextCX} = cx_redirect(Conn, Hosts, CX), - {NewMX, NewCX} = init_connection(Unassigned, NextMX, NextCX) - State#s{mx = NewMX, cx = NewCX}; -do_report(Conn, disconnected, State = #s{mx = MX, cx = CX}) -> - {Unassigned, NextMX, NextCX} = - case mx_lookup_category(Conn, MX) of - attempt -> - ScrubbedMX = mx_del_monitor(Conn, attempt, MX), - ScrubbedCX = cx_failed(Conn, CX), - {[], ScrubbedMX, ScrubbedCX}; - conn -> - ScrubbedMX = mx_del_monitor(Conn, conn, MX), - {ok, Dropped, ScrubbedCX} = cx_disconnected(Conn, conn, CX), - {Dropped, ScrubbedMX, ScrubbedCX} - end, {NewMX, NewCX} = init_connection(Unassigned, NextMX, NextCX), - State#s{mx = NewMX, cx = NewCX}. + State#s{mx = NewMX, cx = NewCX}; +do_report(Conn, + disconnected, + State = #s{actions = Actions, requests = Requests, mx = MX, cx = CX}) -> + case mx_lookup_category(Conn, MX) of + attempt -> + {ok, NewMX} = mx_del_monitor(Conn, attempt, MX), + NewCX = cx_failed(Conn, CX), + State#s{mx = NewMX, cx = NewCX}; + conn -> + {ok, ScrubbedMX, ReqRefs} = mx_del_monitor(Conn, conn, MX), + ScrubbedCX = cx_disconnected(Conn, CX), + Unassigned = cx_unassigned(ScrubbedCX), + NewActions = maps:to_list(maps:with(ReqRefs, Requests)) ++ Actions, + NewRequests = maps:without(ReqRefs, Requests), + {NewMX, NewCX} = init_connection(Unassigned, ScrubbedMX, ScrubbedCX), + State#s{actions = NewActions, + requests = NewRequests, + mx = NewMX, + cx = NewCX} + end + -spec init_connection(Realms, MX, CX) -> {NewMX, NewCX} when Realms :: [zx:realm()], - MX :: monitor_index() + MX :: monitor_index(), CX :: conn_index(), NewMX :: monitor_index(), NewCX :: conn_index(). %% @private -%% Initiates a single connection and updates the relevant structures. +%% Initiates a connection to a single realm at a time, taking into account whether +%% connected but unassigned nodes are alterantive providers of the needed realm. +%% Returns updated monitor and connection indices. -init_connection([Realm | Realms], MX, CX = #cx{realms = Metas}) -> +init_connection([Realm | Realms], MX, CX = #cx{realms = RMetas}) -> {NewMX, NewCX} = - case maps:get(Realm) of + case maps:get(Realm, RMetas) of #rmeta{available = []} -> - {ok, Host, UpdatedCX} = cx_next_hosts(Realm, CX), - {ok, Pid} = zx_conn:start(Host), - NextMX = mx_add_monitor(Pid, attempt, MX), - NextCX = cx_add_attempt({Pid, Host}, UpdatedCX), + {ok, NextMX, NextCX} = init_connections([Realm], MX, CX), {NextMX, NextCX}; Meta = #rmeta{available = [Conn | Conns]} -> NewMeta = Meta#rmeta{assigned = Conn, available = Conns}, - NewMetas = maps:put(Realm, NewMeta, Metas), - NextCX = CX#cx{realms = NewMetas}, - {MX, NewCX} + NewRMetas = maps:put(Realm, NewMeta, RMetas), + NextCX = CX#cx{realms = NewRMetas}, + {MX, NextCX} end, init_connection(Realms, NewMX, NewCX); init_connection([], MX, CX) -> {MX, CX}. --spec do_result(Ref, Result, State) -> NewState - when Ref :: reference(), +-spec do_result(Conn, Ref, Result, State) -> NewState + when Conn :: pid(), + Ref :: reference(), Result :: result(), State :: state(), NewState :: state(). %% @private %% Receive the result of a sent request and route it back to the original requestor. -do_result(Ref, Result, State = #s{responses = Responses}) -> - NewResponses = - case maps:take(Ref, Responses) of - {{Req, {Type, Object}}, NextResponses} -> +do_result(Conn, Ref, Result, State = #s{requests = Requests, mx = MX}) -> + NewRequests = + case maps:take(Ref, Requests) of + {{Req, {Type, Object}}, NextRequests} -> Req ! {result, {Type, Object, Result}}, - NextResponses; + NextRequests; error -> ok = log(warning, "Received unqueued result ~tp:~tp", [Ref, Result]), - Responses + Requests end, - State#s{responses = NewResponses}. + NewMX = mx_clear_request(Conn, Ref, MX), + State#s{requests = NewRequests, mx = NewMX}. -spec do_notice(Package, Update, State) -> ok @@ -708,7 +771,7 @@ eval_queue([Action = {Pid, {unsubscribe, Package}} | Rest], State = #s{actions = Actions, subs = Subs, mx = MX, cx = CX}) -> NewActions = lists:delete(Action, Actions), NewSubs = lists:delete({Pid, Package}, Subs), - NewMX = mx_del_monitor(Pid, subscriber, MX), + {ok, NewMX} = mx_del_monitor(Pid, subscriber, MX), Realm = element(1, Package), ok = case cx_resolve(Realm, CX) of @@ -721,9 +784,9 @@ eval_queue([{Ref, Pid, {list, realms}} | Rest], State = #s{cx = CX}) -> ok = send_result(Pid, Ref, {list, realms, {ok, Realms}}), eval_queue(Rest, State); eval_queue([Action = {Ref, Pid, {list, Realm}} | Rest], - State = #s{actions = Actions, responses = Responses, mx = MX, cx = CX}) + State = #s{actions = Actions, requests = Requests, mx = MX, cx = CX}) when is_list(Realm) -> - {NewActions, NewResponses, NewMX} = + {NewActions, NewRequests, NewMX} = case cx_resolve(Realm, CX) of {ok, Conn} -> ok = cx_conn:list_packages(Conn, Ref), @@ -734,32 +797,32 @@ eval_queue([Action = {Ref, Pid, {list, Realm}} | Rest], unassigned -> NextMX = mx_add_monitor(Pid, requestor, MX), NextActions = [Action | Actions], - {NextActions, Responses, NextMX}; + {NextActions, Requests, NextMX}; unconfigured -> Pid ! {Ref, {list, Realm, {error, bad_realm}}}, - {Actions, Responses, MX} + {Actions, Requests, MX} end, - NewState = State#s{actions = NewActions, responses = NewResponses, mx = NewMX}, + NewState = State#s{actions = NewActions, requests = NewRequests, mx = NewMX}, eval_queue(Rest, NewState); %% FIXME: Universalize the cx_resolve result, leave only message form explicit. -eval_queue([Action = {Ref, Pid, Message} | Actions], - State = #s{actions = Actions, responses = Responses, mx = MX, cx = CX}) +eval_queue([Action = {Ref, Pid, Message} | Rest], + State = #s{actions = Actions, requests = Requests, mx = MX, cx = CX}) -> Realm = element(1, element(2, Message)), - {NewActions, NewResponses, NewMX} = + {NewActions, NewRequests, NewMX} = case cx_resolve(Realm, CX) of {ok, Conn} -> ok = cx_conn:list_packages(Conn, Ref), - NextResponses = maps:put(Ref, {Pid, Message}, Responses), + NextRequests = maps:put(Ref, {Pid, Message}, Requests), NextMX = mx_add_monitor(Pid, requestor, MX), - {Actions, NextResponses, NextMX}; + {Actions, NextRequests, NextMX}; unassigned -> NextActions = [Action | Actions], - {NextActions, Responses, MX}; + {NextActions, Requests, MX}; unconfigured -> - Pid ! {Ref, {list, Realm, {error, bad_realm}}} - {Actions, Responses, MX} + Pid ! {Ref, {list, Realm, {error, bad_realm}}}, + {Actions, Requests, MX} end, - NewState = State#s{actions = NewActions, responses = NewResponses, mx = NewMX}, + NewState = State#s{actions = NewActions, requests = NewRequests, mx = NewMX}, eval_queue(Rest, NewState). @@ -903,7 +966,7 @@ scrub(Deps) -> mx_new() -> []. --spec mx_del_monitor(pid(), category(), monitor_index()) -> monitor_index(). +-spec mx_add_monitor(pid(), category(), monitor_index()) -> monitor_index(). %% @private %% Begin monitoring the given Pid, keeping track of its category. @@ -926,41 +989,95 @@ mx_add_monitor(Pid, requestor, MX) -> mx_add_monitor(Pid, attempt, MX) -> false = lists:keymember(Pid, 2, MX), Ref = monitor(process, Pid), - [{Ref, Pid, attempt} | MX]; -mx_add_monitor(Pid, conn, MX) -> + [{Ref, Pid, attempt} | MX]. + + +-spec mx_upgrade_conn(Pid, MX) -> NewMX + when Pid :: pid(), + MX :: monitor_index(), + NewMX :: monitor_index(). +%% @private +%% Upgrade an `attempt' monitor to a `conn' monitor. + +mx_upgrade_conn(Pid, MX) -> {value, {Ref, Pid, attempt}, NextMX} = lists:keytake(Pid, 2, MX), - [{Ref, Pid, conn} | NextMX], + [{Ref, Pid, {conn, []}} | NextMX]. +-spec mx_del_monitor(Conn, Category, MX) -> Result + when Conn :: pid(), + Category :: subscriber + | requestor + | attempt + | conn, + MX :: monitor_index(), + Result :: {ok, NewMX} + | {ok, NewMX, RequestRefs}, + NewMX :: monitor_index(), + RequestRefs :: [reference()]. + -spec mx_del_monitor(pid(), category(), monitor_index()) -> monitor_index(). %% @private %% Drop a monitor category, removing the entire monitor in the case only one category -%% exists. +%% exists. Returns a tuple including the remaining request references in the case of +%% a conn type. mx_del_monitor(Pid, subscriber, MX) -> - case lists:keytake(Pid, 2, MX) of - {value, {Ref, Pid, {1, 0}}, NextMX} -> - true = demonitor(Ref, [flush]), - NextMX; - {value, {Ref, Pid, {Subs, Reqs}}, NextMX} -> - [{Ref, Pid, {Subs - 1, Reqs}} | NextMX]; - false -> - MX - end; + NewMX = + case lists:keytake(Pid, 2, MX) of + {value, {Ref, Pid, {1, 0}}, NextMX} -> + true = demonitor(Ref, [flush]), + NextMX; + {value, {Ref, Pid, {Subs, Reqs}}, NextMX} when Subs > 0 -> + [{Ref, Pid, {Subs - 1, Reqs}} | NextMX] + end, + {ok, NewMX}; mx_del_monitor(Pid, requestor, MX) -> - case lists:keytake(Pid, 2, MX) of - {value, {Ref, Pid, {0, 1}}, NextMX} -> - true = demonitor(Ref, [flush]), - NextMX; - {value, {Ref, Pid, {Subs, Reqs}}, NextMX} -> - [{Ref, Pid, {Subs, Reqs - 1}} | NextMX]; - false -> - MX - end; -mx_del_monitor(Pid, Category, MX) -> - {value, {Ref, Pid, Category}, NewMX} = lists:keytake(Pid, 2, MX), + NewMX = + case lists:keytake(Pid, 2, MX) of + {value, {Ref, Pid, {0, 1}}, NextMX} -> + true = demonitor(Ref, [flush]), + NextMX; + {value, {Ref, Pid, {Subs, Reqs}}, NextMX} when Reqs > 0 -> + [{Ref, Pid, {Subs, Reqs - 1}} | NextMX] + end, + {ok, NewMX}; +mx_del_monitor(Pid, attempt, MX) -> + {value, {Ref, Pid, attempt}, NewMX} = lists:keytake(Pid, 2, MX), true = demonitor(Ref, [flush]), - NewMX. + {ok, NewMX}; +mx_del_monitor(Pid, conn, MX) -> + {value, {Ref, Pid, {conn, RequestRefs}}, NewMX} = lists:keytake(Pid, 2, MX), + true = demonitor(Ref, [flush]), + {ok, NewMX, RequestRefs}. + + +-spec mx_stash_request(Conn, RequestRef, MX) -> NewMX + when Conn :: pid(), + RequestRef :: reference(), + MX :: monitor_index(), + NewMX :: monitor_index(). +%% @private +%% Add a pending request reference to the connection monitor's record. + +mx_stash_request(Conn, RequestRef, MX) -> + {value, {Ref, Conn, {conn, Pending}}, NextMX} = lists:keytake(Conn, 2, MX), + NewPending = [RequestRef | Pending], + [{Ref, Conn, {conn, NewPending}} | NextMX]. + + +-spec mx_clear_request(Conn, RequestRef, MX) -> NewMX + when Conn :: pid(), + RequestRef :: reference(), + MX :: monitor_index(), + NewMX :: monitor_index(). +%% @private +%% Remove a pending request reference from the connection monitor's record. + +mx_clear_request(Conn, RequestRef, MX) -> + {value, {Ref, Conn, {conn, Pending}}, NextMX} = lists:keytake(Conn, 2, MX), + NewPending = lists:delete(RequestRef, Pending), + [{Ref, Conn, {conn, NewPending}} | NextMX]. -spec mx_lookup_category(pid(), monitor_index()) -> Result @@ -968,38 +1085,18 @@ mx_del_monitor(Pid, Category, MX) -> | conn | requestor | subscriber - | sub_req - | error. + | sub_req. %% @private %% Lookup a monitor's categories. mx_lookup_category(Pid, MX) -> - case lists:keyfind(Pid, 2, MX) of - {_, _, attempt} -> attempt; - {_, _, conn} -> conn; - {_, _, {0, _}} -> requestor; - {_, _, {_, 0}} -> subscriber; - {_, _, _} -> sub_req; - false -> error - end. - - --spec mx_upgrade_conn(Pid, MX) -> Result - when Pid :: pid(), - MX :: monitor_index(), - Result :: {ok, NewMX} - | {error, not_found}, - NewMX :: monitor_index(). -%% @private -%% Upgrade a attempt to a conn. - -mx_upgrade_conn(Pid, MX) -> - case lists:keytake(Pid, 2, MX) of - {value, {Ref, Pid, attempt}, NextMX} -> - NewMX = [{Ref, Pid, conn} | NextMX], - {ok, NewMX}; - false -> - {error, not_found} + Monitor = lists:keyfind(Pid, 2, MX), + case element(3, Monitor) of + attempt -> attempt; + {conn, _} -> conn; + {0, _} -> requestor; + {_, 0} -> subscriber; + {_, _} -> sub_req end. @@ -1009,10 +1106,10 @@ mx_upgrade_conn(Pid, MX) -> %%% Functions to manipulate the conn_index() data type are in this section. This %%% data should be treated as abstract by functions outside of this section, as it is %%% a deep structure and future requirements are likely to wind up causing it to -%%% change a little. For the same reason, these functions are all pure functions, -%%% testable independently of the rest of the module and having no side effects. -%%% Return values usually carry some status information with them, and it is up to the -%%% caller to react to those responses in an appropriate way. +%%% change a little. For the same reason, these functions are all pure, independently +%%% testable, and have no side effects. +%%% +%%% Return values often carry some status information with them. -spec cx_load() -> conn_index(). %% @private @@ -1025,7 +1122,8 @@ cx_load() -> {ok, CX} -> CX; {error, Reason} -> - ok = log(error, "Cache load failed with: ~tp", [Reason]), + Message = "Realm data and host cache load failed with : ~tp", + ok = log(error, Message, [Reason]), ok = log(warning, "No realms configured."), #cx{} end. @@ -1036,6 +1134,12 @@ cx_load() -> | {error, Reason}, Reason :: no_realms | file:posix(). +%% @private +%% This procedure, relying zx_lib:zomp_home() allows the system to load zomp data +%% from any arbitrary home for zomp. This has been included mostly to make testing of +%% Zomp and ZX easier, but incidentally opens the possibility that an arbitrary Zomp +%% home could be selected by an installer (especially on consumer systems like Windows +%% where any number of wild things might be going on in the user's filesystem). cx_populate() -> Home = zx_lib:zomp_home(), @@ -1046,6 +1150,15 @@ cx_populate() -> end. +-spec cx_populate(RealmFiles, CX) -> NewCX + when RealmFiles :: file:filename(), + CX :: conn_index(), + NewCX :: conn_index(). +%% @private +%% Pack an initially empty conn_index() with realm meta and host cache data. +%% Should not halt on a corrupted, missing, malformed, etc. realm file but will log +%% any loading errors. + cx_populate([File | Files], CX) -> case file:consult(File) of {ok, Meta} -> @@ -1060,6 +1173,13 @@ cx_populate([], CX) -> CX. +-spec cx_load_realm_meta(Meta, CX) -> NewCX + when Meta :: [{Key :: atom(), Value :: term()}], + CX :: conn_index(), + NewCX :: conn_index(). +%% @private +%% This function MUST adhere to the realmfile definition found at. + cx_load_realm_meta(Meta, CX = #cx{realms = Realms}) -> {realm, Realm} = lists:keyfind(realm, 1, Meta), {revision, Revision} = lists:keyfind(revision, 1, Meta), @@ -1074,12 +1194,27 @@ cx_load_realm_meta(Meta, CX = #cx{realms = Realms}) -> realm_keys = RealmKeys, package_keys = PackageKeys, sysops = Sysops}, - Complete = cx_fetch_cache(Realm, Basic), + Complete = cx_load_cache(Realm, Basic), NewRealms = maps:put(Realm, Complete, Realms), CX#cx{realms = NewRealms}. -cx_fetch_cache(Realm, Basic) -> +-spec cx_load_cache(Realm, Basic) -> Complete + when Realm :: zx:realm(), + Basic :: realm_meta(), + Complete :: realm_meta(). +%% @private +%% Receive a realm_meta() that lacks any cache data and load the realm's cache file +%% if it exists, and return it fully populated. +%% FIXME: If several instances of zomp or zx are running at once it may be possible +%% to run into file access contention or receive an incomplete read on some +%% systems. At the moment this is only a remote possibility and for now should +%% be handled by simply re-running whatever command caused the failure. +%% Better file contention and parallel-executing system handling should +%% eventually be implemented, especially if zx becomes common for end-user +%% GUI programs. + +cx_load_cache(Realm, Basic) -> CacheFile = cx_cache_file(Realm), case file:consult(CacheFile) of {ok, Cache} -> @@ -1105,6 +1240,8 @@ cx_store_cache(#cx{realms = Realms}) -> -spec cx_write_cache({zx:realm(), realm_meta()}) -> ok. +%% @private +%% FIXME: The same concerns as noted in the cx_load_cache/2 FIXME comment apply here. cx_write_cache({Realm, #rmeta{serial = Serial, private = Private, mirrors = Mirrors}}) -> @@ -1183,7 +1320,7 @@ cx_next_host2(Realm, CX = #cx{realm = Realms}) -> %% indicate to the caller that any iterative host scanning or connection procedures %% should treat this as the last value of interest (and stop spawning connections). -cx_next_host3(Meta = #rmeta{prime = Prime, private = Privae, mirrors = Mirrors}) -> +cx_next_host3(Meta = #rmeta{prime = Prime, private = Private, mirrors = Mirrors}) -> case queue:is_empty(Mirrors) of false -> {{value, Next}, NewMirrors} = queue:out(Mirrors), @@ -1203,8 +1340,8 @@ cx_next_host3(Meta = #rmeta{prime = Prime, private = Privae, mirrors = Mirrors}) | {error, Reason}, Hosts :: [zx:host()], NewCX :: conn_index(), - Reason :: bad_realm - | connected. + Reason :: {connected, Conn :: pid()} + | bad_realm. %% @private %% This function allows recruiting an arbitrary number of hosts from the host cache %% of a given realm, taking private mirrors first, then public mirrors, and ending @@ -1212,21 +1349,16 @@ cx_next_host3(Meta = #rmeta{prime = Prime, private = Privae, mirrors = Mirrors}) cx_next_hosts(N, Realm, CX = #cx{realms = Realms}) -> case maps:find(Realm, Realms) of - {ok, #rmeta{assigned = none}} -> cx_next_hosts2(N, Realm, CX); - {ok, _} -> {error, connected}; - error -> {error, bad_realm} + {ok, Meta = #rmeta{assigned = none}} -> cx_next_hosts2(N, Realm, Meta, CX); + {ok, #rmeta{assigned = Conn}} -> {error, {connected, Conn}}; + error -> {error, bad_realm} end. -cx_next_hosts2(N, Realm, CX = #cx{realms = Realms}) -> - case maps:find(Realm, Realms) of - {ok, Meta} -> - {ok, Hosts, NewMeta} = cx_next_hosts3(N, [], Meta), - NewRealms = maps:put(Realm, NewMeta, Realms), - {ok, Hosts, CX#cx{realms = NewRealms}}; - error -> - {error, bad_realm} - end. +cx_next_hosts2(N, Realm, Meta, CX = #cx{realms = Realms}) -> + {ok, Hosts, NewMeta} = cx_next_hosts3(N, [], Meta), + NewRealms = maps:put(Realm, NewMeta, Realms), + {ok, Hosts, CX#cx{realms = NewRealms}}. cx_next_hosts3(N, Hosts, Meta) when N < 1 -> @@ -1238,13 +1370,34 @@ cx_next_hosts3(N, Hosts, Meta) -> end. --spec cx_add_attempt(New, CX) -> NewCX - when New :: {pid(), zx:host()}, +-spec cx_maybe_add_attempt(Host, Realm, CX) -> Result + when Host :: zx:host(), + Realm :: zx:realm(), + CX :: conn_index(), + Result :: not_connected + | {ok, NewCX}, + NewCX :: conn_index(). + +cx_maybe_add_attempt(Host, Realm, CX = #cx{attempts = Attempts}) -> + case lists:keytake(Host, 2, Attempts) of + false -> + not_connected; + {value, {Pid, Host, Realms}, NextAttempts} -> + NewAttempts = [{Pid, Host, [Realm | Realms]} | Attempts], + NewCX = CX#cx{attempts = NewAttempts}, + {ok, NewCX} + end. + + +-spec cx_add_attempt(Pid, Host, Realm, CX) -> NewCX + when Pid :: pid(), + Host :: zx:host(), + Realm :: zx:realm(), CX :: conn_index(), NewCX :: conn_index(). -cx_add_attempt(New, CX = #cx{attempts = Attempts}) -> - CX#cx{attempts = [New | Attempts]}. +cx_add_attempt(Pid, Host, Realm, CX = #cx{attempts = Attempts}) -> + CX#cx{attempts = [{Pid, Host, [Realm]} | Attempts]}. -spec cx_connected(Available, Conn, CX) -> Result @@ -1262,18 +1415,29 @@ cx_add_attempt(New, CX = #cx{attempts = Attempts}) -> %% The return value is a tuple that indicates whether the new connection was assigned %% or not and the updated CX data value. -cx_connected(Available, Conn, CX = #cx{attempts = Attempts, conns = Conns}) -> - {value, {Conn, Host}, NewAttempts} = lists:keytake(Conn, 1, Attempts), - Realms = [element(1, A) || A <- Available], - NewConns = [{Conn, Host, Realms} | Conns], - NewCX = CX#cx{attempts = NewAttempts, conns = NewConns}, - cx_connected(unassigned, Available, Conn, NewCX). +cx_connected(Available, Conn, CX = #cx{attempts = Attempts}) -> + {value, {Pid, Host, _}, NewAttempts} = lists:keytake(Conn, 1, Attempts), + Realms = [R || {R, _} <- Available], + NewCX = CX#cx{attempts = NewAttempts}, + cx_connected(unassigned, Available, {Pid, Host, Realms}, NewCX). +-spec cx_connected(A, Available, Conn, CX) -> {NewA, NewCX} + when A :: unassigned | assigned, + Available :: [{zx:realm(), zx:serial()}], + Conn :: {pid(), zx:host(), [zx:realm()]}, + CX :: conn_index(), + NewA :: unassigned | assigned, + NewCX :: conn_index(). +%% @private +%% Only accept a new realm as available if the reported serial is equal or newer to the +%% highest known serial. + cx_connected(A, [{Realm, Serial} | Rest], Conn, CX = #cx{realms = Realms}) -> case maps:find(Realm, Realms) of {ok, Meta = #rmeta{serial = S, available = Available}} when S =< Serial -> - NewMeta = Meta#rmeta{serial = Serial, available = [Conn | Available]}, + Pid = element(1, Conn), + NewMeta = Meta#rmeta{serial = Serial, available = [Pid | Available]}, {NewA, NewCX} = cx_connected(A, Realm, Conn, NewMeta, CX), cx_connected(NewA, Rest, Conn, NewCX); {ok, #rmeta{serial = S}} when S > Serial -> @@ -1281,32 +1445,59 @@ cx_connected(A, [{Realm, Serial} | Rest], Conn, CX = #cx{realms = Realms}) -> error -> cx_connected(A, Rest, Conn, CX) end; -cx_connected(A, [], Conn, CX = #cx{attempts = Attempts, conns = Conns}) -> - {value, ConnRec, NewAttempts} = lists:keytake(Conn, 1, Attempts), - NewConns = [ConnRec | Conns], - NewCX = CX#cx{attempts = NewAttempts, conns = NewConns}, - {A, NewCX}. +cx_connected(A, [], Conn, CX = #cx{conns = Conns}) -> + {A, CX#cx{conns = [Conn | Conns]}}. +-spec cx_connected(A, Realm, Conn, Meta, CX) -> {NewA, NewCX} + when A :: unassigned | assigned, + Realm :: zx:host(), + Conn :: {pid(), zx:host(), [zx:realm()]}, + Meta :: realm_meta(), + CX :: conn_index(), + NewA :: unassigned | assigned, + NewCX :: conn_index(). +%% @private +%% This function matches on two elements: +%% - Whether or not the realm is already assigned (and if so, set `A' to `assigned' +%% - Whether the host node is the prime node (and if not, ensure it is a member of +%% of the mirror queue). + cx_connected(A, Realm, - Conn, - Meta = #rmeta{prime = Prime, mirrors = Mirrors}, - CX = #cx{realms = Realms, attempts = Attempts}) -> - {NewMirrors, Node} = - case lists:keyfind(Conn, 1, Attempts) of - {_, Prime} -> {Mirrors, Prime}; - {_, Host} -> {enqueue_unique(Host, Mirrors), Host} - end, - {NewA, NewAssigned} = - case lists:keymember(Realm, 1, Assigned) of - true -> {A, Assigned}; - false -> {assigned, [{Realm, Pid} | Assigned]} - end, - NewMeta = Meta#rmeta{mirrors = NewMirrors}, + {Pid, Prime, _}, + Meta = #rmeta{prime = Prime, assigned = none}, + CX = #cx{realms = Realms}) -> + NewMeta = Meta#rmeta{assigned = Pid}, NewRealms = maps:put(Realm, NewMeta, Realms), - NewCX = CX#cx{realms = NewRealms, assigned = NewAssigned}, - {NewA, NewCX}. + NewCX = CX#cx{realms = NewRealms}, + {assigned, NewCX}; +cx_connected(A, + Realm, + {Pid, Host, _}, + Meta = #rmeta{mirrors = Mirrors, assigned = none}, + CX = #cx{realms = Realms, attempts = Attempts}) -> + NewMirrors = enqueue_unique(Host, Mirrors), + NewMeta = Meta#rmeta{mirrors = NewMirrors, assigned = Pid}, + NewRealms = maps:put(Realm, NewMeta, Realms), + NewCX = CX#cx{realms = NewRealms}, + {assigned, NewCX}; +cx_connected(A, + _, + {_, Prime, _}, + #rmeta{prime = Prime}, + CX) -> + {A, CX}; +cx_connected(A, + Realm, + {_, Host, _}, + Meta = #rmeta{mirrors = Mirrors}, + CX = #cx{realms = Realms}) -> + NewMirrors = enqueue_unique(Host, Mirrors), + NetMeta = Meta#rmeta{mirrors = NewMirrors}, + NewRealms = maps:put(Realm, NewMeta, Realms), + NewCX = CX#cx{realms = NewRealms}, + {A, NewCX}. -spec enqueue_unique(term(), queue:queue()) -> queue:queue(). @@ -1353,22 +1544,18 @@ cx_redirect(Conn, Hosts, CX) -> CX :: conn_index(), NextCX :: conn_index(). %% @private -%% Add host to any realm mirror queues that are known to provide the realm. +%% Add the host to any realm mirror queues that it provides. cx_redirect([{Host, Provided} | Rest], CX = #cx{realms = Realms}) -> Apply = - fun(R, M) -> - case maps:find(R, M) of + fun(R, Rs) -> + case maps:find(R, Rs) of {ok, Meta = #rmeta{mirrors = Mirrors}} -> - NewMirrors = - case queue:member(Host, Mirrors) of - true -> Mirrors; - false -> queue:in(Host, Mirrors) - end, + NewMirrors = enqueue_unique(Host, Mirrors), NewMeta = Meta#rmeta{mirrors = NewMirrors}, - maps:put(R, Meta, M); + maps:put(R, NewMeta, Rs); error -> - M + R end end, NewRealms = lists:foldl(Apply, Realms, Provided), @@ -1377,6 +1564,13 @@ cx_redirect([], CX) -> CX. +-spec cx_unassigned(CX) -> Unassigned + when CX :: conn_index(), + Unassigned :: [zx:realm()]. +%% @private +%% Scan the CX record for unassigned realms;return a list of all unassigned +%% realm names. + cx_unassigned(#cx{realms = Realms}) -> NotAssigned = fun(Realm, #rmeta{assigned = Conn}, Unassigned) -> @@ -1388,14 +1582,10 @@ cx_unassigned(#cx{realms = Realms}) -> maps:fold(NotAssigned, [], Realms). --spec cx_disconnected(Conn, CX) -> Result - when Conn :: pid(), - CX :: conn_index(), - Result :: {ok, UnassignedRealms, NewCX} - | {error, unknown}, - Mon :: reference(), - UnassignedRealms :: [zx:realm()], - NewCX :: conn_index(). +-spec cx_disconnected(Conn, CX) -> NewCX + when Conn :: pid(), + CX :: conn_index(), + NewCX :: conn_index(). %% @private %% An abstract data handler which is called whenever a connection terminates. %% This function removes all data related to the disconnected pid and its assigned @@ -1403,22 +1593,16 @@ cx_unassigned(#cx{realms = Realms}) -> %% unassigned, and an updated connection index. cx_disconnected(Conn, CX = #cx{realms = Realms, conns = Conns}) -> - case lists:keytake(Conn, 1, Conns) of - {value, {Conn, Host, Realms}, NewConns} -> - {UnassignedRealms, NewRealms} = cx_scrub_assigned(Conn, Host, Realms), - NewCX = CX#cx{realms = NewRealms, conns = NewConns}, - {ok, UnassignedRealms, NewCX}; - false -> - {error, unknown} - end. + {value, {Pid, Host, _}, NewConns} = lists:keytake(Conn, 1, Conns), + NewRealms = cx_scrub_assigned(Pid, Host, Realms), + CX#cx{realms = NewRealms, conns = NewConns}. --spec cx_scrub_assigned(Pid, Host, Realms) -> {UnassignedRealms, NewRealms} +-spec cx_scrub_assigned(Pid, Host, Realms) -> NewRealms when Pid :: pid(), Host :: zx:host(), - Realms :: realm_meta(), - UnassignedRealms :: [zx:realm()], - NewRealms :: realm_meta(). + Realms :: [realm_meta()], + NewRealms :: [realm_meta()]. %% @private %% This could have been performed as a set of two list operations (a partition and a %% map), but to make the procedure perfectly clear it is written out explicitly. @@ -1426,29 +1610,15 @@ cx_disconnected(Conn, CX = #cx{realms = Realms, conns = Conns}) -> cx_scrub_assigned(Pid, Host, Realms) -> Scrub = fun - (Realm, - Meta = #rmeta{mirrors = Mirrors, - assigned = Assigned, - available = Available}, - {Unassigned, Metas}) -> - {NewUnassigned, NewAssigned} = - case Assigned of - Pid -> {[Realm | Unassigned], none}; - Other -> {Unassigned, Other} - end, - NewMirrors = - case queue:member(Host, Mirrors) of - false -> queue:in(Host, Mirrors); - true -> Mirrors - end, - NewAvailable = lists:delete(Pid, Available), - NewMeta = Meta#rmeta{mirrors = NewMirrors, - assigned = NewAssigned, - available = NewAvailable}, - NewMetas = maps:put(Realm, NewMeta, Metas), - {NewUnassigned, NewMetas} + (_, V = #rmeta{mirrors = M, available = A, assigned = C}) when C == Pid -> + V#rmeta{mirrors = enqueue_unique(Host, M), + available = lists:delete(Pid, A), + assigned = none}; + (_, V = #rmeta{mirrors = M, available = A}) -> + V#rmeta{mirrors = enqueue_unique(Host, M), + available = lists:delete(Pid, A)} end, - maps:fold(Scrub, {[], maps:new()}, Realms). + maps:map(Scrub, Realms). -spec cx_resolve(Realm, CX) -> Result From 3dfa14d20cb63ffc08886aae15528071c06eb9cb Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Thu, 8 Mar 2018 10:05:36 +0900 Subject: [PATCH 42/55] blah blah blah --- TODO | 56 +- zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl | 675 ++++++++++++----------- 2 files changed, 384 insertions(+), 347 deletions(-) diff --git a/TODO b/TODO index 52ccf5f..3ee9152 100644 --- a/TODO +++ b/TODO @@ -2,16 +2,50 @@ On redirect a list of hosts of the form [{zx:host(), [zx:realm()]}] must be provided to the downstream client. This is the only way that downstream clients can determine which redirect hosts are useful to it. - - The ZX daemon should be able to retry requests that were submitted but did not receive a response before the relevant - connection was terminated for whatever reason. - The most obvious way to do this would be to keep a set or queue of references in each connection monitor's section, - clearing them when they receive responses, and pushing them back into the action queue (from the responses reference map) - when they fail. + - Connect attempts and established connections should have different report statuses. + An established connection does not necessarily have other attempts being made concurrently, so a termination should initiate 3 new connect attempts as init. + An attempt is just an attempt. It can fall flat and be replaced only 1::1. - - The same issue as the one above, but with subscriptions. Currently there is no obvious way to track what subscriptions flow - through which connections, and on termination or change of a connection there is no way to ensure that the subscription request - finds its way back into the action queue to resubmission once a realm becomes available again. - - The request tracking ref list is currently passing through the MX record. That is exactly the wrong place to put it. - It should DEFINITELY be in the CX record. - MOVE IT. + +New Feature: ZX Universal lock + Cross-instance communication + We don't want multiple zx_daemons doing funny things to the filesystem at the same time. + We DO want to be able to run multiple ZX programs to be able to run at the same time. + The solution is to guarantee that there is only ever one zx_daemon running at a given time. + IPC is messy to get straight across various host systems, but network sockets to localhost work in a normal way. + The first zx_daemon to start up will check for a lock file in the $ZOMP_HOME directory. + If there is no lock file present it will write a lock file with a timestamp, begin listening on a local port, and then update the lock file with the listening port number. + If it finds a lock file in $ZOMP_HOME it will attempt to connect to the running zx_daemon on the port indicated in the lock file. If only a timestamp exists with no port number then it will wait two seconds from the time indicated in the timestamp in the lock file before re-reading it -- if the second read still contains no port number it will remove the lock file and assume the primary role for the system itself. + If a connection cannot be established then it will assume the instance that had written the lock file failed to delete it for Bad Reasons, remove the lock file, open a port, and write its own lock file, taking over as the lead zx_daemon. + + Any new zx_daemons that come up in the system will establish a connection to the zx_daemon that wrote the lock file, and proxy all requests through that primary zx_daemon. + When a zx_daemon that is acting as primary for the system retires it will complete all ongoing actions first, then begin queueing requests without acting on them, designate the oldest peer as the new leader, get confirmation that the new leader has a port open, update the original lock file with the new port number, redirect all connections to the new zx_daemon, and then retire. + + +init(Args) -> + Stuff = do_stuff(), + Tries = 3, + Path = lock_file(), + case check_for_leader(Tries, Path) of + no_leader -> + {found, Socket} -> + end. + + +check_for_leader(0, _) -> + no_leader; +check_for_leader(Tries, Path) -> + case file:open(Path, [write, exclusive]) of + {ok, FD} -> become_leader(FD); + {error, eexist} -> contact_leader() + end. + + + case file:consult(Path) of + {ok, Data} -> + + {error, enoexist} -> + check_file(Path); + end + end, \ No newline at end of file diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl index 352839b..c1f6bef 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl @@ -105,7 +105,7 @@ fetch/1, key/1, pending/1, packagers/1, maintainers/1, sysops/1]). -export([report/1, result/2, notify/2]). --export([start_link/0]). +-export([start_link/0, stop/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, code_change/3, terminate/2]). @@ -119,7 +119,7 @@ {meta = none :: none | zx:package_meta(), home = none :: none | file:filename(), argv = none :: none | [string()], - actions = [] :: [request() | {reference(), request()}], + actions = [] :: [{pid(), subunsub()} | {reference(), request()}], requests = maps:new() :: #{reference() := request()}, subs = [] :: [{pid(), zx:package()}], mx = mx_new() :: monitor_index(), @@ -155,7 +155,8 @@ %% State Types -type state() :: #s{}. --type monitor_index() :: [{reference(), pid(), category()}]. +%-type monitor_index() :: [{reference(), pid(), category()}]. +-type monitor_index() :: #{pid() := {reference(), category()}}. -type conn_index() :: #cx{}. -type realm_meta() :: #rmeta{}. -type connection() :: #conn{}. @@ -398,7 +399,7 @@ request(Action) -> -spec report(Message) -> ok when Message :: {connected, Realms :: [{zx:realm(), zx:serial()}]} | {redirect, Hosts :: [{zx:host(), [zx:realm()]}]} - | failed + | aborted | disconnected. %% @private %% Should only be called by a zx_conn. This function is how a zx_conn reports its @@ -413,7 +414,7 @@ report(Message) -> %% Return a tagged result back to the daemon to be forwarded to the original requestor. result(Reference, Result) -> - gen_server:cast(?MODULE, {result, self(), Reference, Result}). + gen_server:cast(?MODULE, {result, Reference, Result}). -spec notify(Package, Message) -> ok @@ -490,6 +491,17 @@ init_connections([], MX, CX) -> +%%% Shutdown + +-spec stop() -> ok. +%% @doc +%% A polite way to shut down the daemon without doing a bunch of vile things. + +stop() -> + gen_server:cast(?MODULE, stop). + + + %%% gen_server %% @private @@ -522,13 +534,15 @@ handle_cast({report, Conn, Message}, State) -> NextState = do_report(Conn, Message, State), NewState = eval_queue(NextState), {noreply, NewState}; -handle_cast({result, Conn, Ref, Result}, State) -> - NextState = do_result(Conn, Ref, Result, State), +handle_cast({result, Ref, Result}, State) -> + NextState = do_result(Ref, Result, State), NewState = eval_queue(NextState), {noreply, NewState}; handle_cast({notice, Package, Update}, State) -> ok = do_notice(Package, Update, State), {noreply, State}; +handle_cast(stop, State) -> + {stop, normal, State}; handle_cast(Unexpected, State) -> ok = log(warning, "Unexpected cast: ~tp", [Unexpected]), {noreply, State}. @@ -554,8 +568,15 @@ code_change(_, State, _) -> %% gen_server callback to handle shutdown/cleanup tasks on receipt of a clean %% termination request. -terminate(_, _) -> - ok. +terminate(normal, #s{cx = CX}) -> + ok = log(info, "zx_daemon shutting down..."), + case cx_store_cache(CX) of + ok -> + log(info, "Cache written."); + {error, Reason} -> + Message = "Cache write failed with ~tp", + log(error, Message, [Reason]) + end. @@ -641,27 +662,48 @@ do_report(Conn, {redirect, Hosts}, State = #s{mx = MX, cx = CX}) -> {Unassigned, NextCX} = cx_redirect(Conn, Hosts, CX), {NewMX, NewCX} = init_connection(Unassigned, NextMX, NextCX), State#s{mx = NewMX, cx = NewCX}; -do_report(Conn, - disconnected, - State = #s{actions = Actions, requests = Requests, mx = MX, cx = CX}) -> - case mx_lookup_category(Conn, MX) of - attempt -> - {ok, NewMX} = mx_del_monitor(Conn, attempt, MX), - NewCX = cx_failed(Conn, CX), - State#s{mx = NewMX, cx = NewCX}; - conn -> - {ok, ScrubbedMX, ReqRefs} = mx_del_monitor(Conn, conn, MX), - ScrubbedCX = cx_disconnected(Conn, CX), - Unassigned = cx_unassigned(ScrubbedCX), - NewActions = maps:to_list(maps:with(ReqRefs, Requests)) ++ Actions, - NewRequests = maps:without(ReqRefs, Requests), - {NewMX, NewCX} = init_connection(Unassigned, ScrubbedMX, ScrubbedCX), - State#s{actions = NewActions, - requests = NewRequests, - mx = NewMX, - cx = NewCX} - end - +do_report(Conn, aborted, State = #s{mx = MX, cx = CX}) -> + {ok, NewMX} = mx_del_monitor(Conn, attempt, MX), + {Realms, NextCX} = cx_failed(Conn, CX), + {NewMX, NewCX} = init_connection(Realms, NextCX), + State#s{mx = NewMX, cx = NewCX}; +do_report(Conn, disconnected, State) -> + ScrubbedMX = mx_del_monitor(Conn, conn, MX), + {Pending, LostSubs, ScrubbedCX} = cx_disconnected(Conn, CX), + Unassigned = cx_unassigned(ScrubbedCX), + UnSub = fun(S) -> lists:member(element(2, S), LostSubs) end, + {UnSubbed, NewSubs} = lists:partition(UnSub, Subs), + ReSubs = [{S, {subscribe, P}} || {S, P} <- UnSubbed], + {Dequeued, NewRequests} = maps:fold(dequeue(Pending), {#{}, #{}}, Requests), + ReReqs = maps:to_list(Dequeued), + NewActions = ReReqs ++ ReSubs ++ Actions, + {NewMX, NewCX} = init_connection(Unassigned, ScrubbedMX, ScrubbedCX), + State#s{actions = NewActions, + requests = NewRequests, + subs = NewSubs, + mx = NewMX, + cx = NewCX}. + + +-spec dequeue(Pending) -> fun(K, V, {D, R}) -> {NewD, NewR} + when Pending :: [reference()], + K :: reference(), + V :: request(), + D :: #{reference(), request()}, + R :: #{reference(), request()}, + NewD :: #{reference(), request()}, + NewR :: #{reference(), request()}. +%% @private +%% Return a function that partitions the current Request map into two maps, one that +%% matches the closed `Pending' list of references and ones that don't. + +dequeue(Pending) -> + fun(K, V, {D, R}) -> + case lists:member(K, Pending) of + true -> {maps:put(K, V, D), R}; + false -> {D, maps:put(K, V, R)} + end + end. -spec init_connection(Realms, MX, CX) -> {NewMX, NewCX} @@ -692,27 +734,26 @@ init_connection([], MX, CX) -> {MX, CX}. --spec do_result(Conn, Ref, Result, State) -> NewState - when Conn :: pid(), - Ref :: reference(), - Result :: result(), - State :: state(), - NewState :: state(). +-spec do_result(Reference, Result, State) -> NewState + when Reference :: reference(), + Result :: result(), + State :: state(), + NewState :: state(). %% @private %% Receive the result of a sent request and route it back to the original requestor. -do_result(Conn, Ref, Result, State = #s{requests = Requests, mx = MX}) -> +do_result(Reference, Result, State = #s{requests = Requests}) -> NewRequests = - case maps:take(Ref, Requests) of - {{Req, {Type, Object}}, NextRequests} -> - Req ! {result, {Type, Object, Result}}, + case maps:take(Reference, Requests) of + {{Requestor, {Type, Object}}, NextRequests} -> + Requestor ! {result, {Type, Object, Result}}, NextRequests; error -> - ok = log(warning, "Received unqueued result ~tp:~tp", [Ref, Result]), + Message = "Received unqueued result ~tp: ~tp", + ok = log(warning, Message, [Reference, Result]), Requests end, - NewMX = mx_clear_request(Conn, Ref, MX), - State#s{requests = NewRequests, mx = NewMX}. + State#s{requests = NewRequests}. -spec do_notice(Package, Update, State) -> ok @@ -754,7 +795,7 @@ eval_queue([Action = {Pid, {subscribe, Package}} | Rest], {NewActions, NewSubs, NewMX} = case cx_resolve(Realm, CX) of {ok, Conn} -> - ok = zx_conn:subscribe(Package), + ok = zx_conn:subscribe(Conn, Package), NextSubs = [{Pid, Package} | Subs], NextMX = mx_add_monitor(Pid, subscriber, MX), {Actions, NextSubs, NextMX}; @@ -775,7 +816,7 @@ eval_queue([Action = {Pid, {unsubscribe, Package}} | Rest], Realm = element(1, Package), ok = case cx_resolve(Realm, CX) of - {ok, Conn} -> cx_conn:unsubscribe(Package); + {ok, Conn} -> cx_conn:unsubscribe(Conn, Package); unassigned -> ok end, eval_queue(Rest, State#s{actions = NewActions, subs = NewSubs, mx = NewMX}); @@ -836,121 +877,109 @@ send_result(Pid, Ref, Message) -> ok. --spec do_query_latest(Object, State) -> {Result, NewState} - when Object :: zx:package() | zx:package_id(), - State :: state(), - Result :: {ok, zx:version()} - | {error, Reason}, - Reason :: bad_realm - | bad_package - | bad_version, - NewState :: state(). +%-spec do_query_latest(Object, State) -> {Result, NewState} +% when Object :: zx:package() | zx:package_id(), +% State :: state(), +% Result :: {ok, zx:version()} +% | {error, Reason}, +% Reason :: bad_realm +% | bad_package +% | bad_version, +% NewState :: state(). %% @private %% Queries a zomp realm for the latest version of a package or package %% version (complete or incomplete version number). - -do_query_latest(Socket, {Realm, Name}) -> - ok = zx_net:send(Socket, {latest, Realm, Name}), - receive - {tcp, Socket, Bin} -> binary_to_term(Bin) - after 5000 -> {error, timeout} - end; -do_query_latest(Socket, {Realm, Name, Version}) -> - ok = zx_net:send(Socket, {latest, Realm, Name, Version}), - receive - {tcp, Socket, Bin} -> binary_to_term(Bin) - after 5000 -> {error, timeout} - end. +% +%do_query_latest(Socket, {Realm, Name}) -> +% ok = zx_net:send(Socket, {latest, Realm, Name}), +% receive +% {tcp, Socket, Bin} -> binary_to_term(Bin) +% after 5000 -> {error, timeout} +% end; +%do_query_latest(Socket, {Realm, Name, Version}) -> +% ok = zx_net:send(Socket, {latest, Realm, Name, Version}), +% receive +% {tcp, Socket, Bin} -> binary_to_term(Bin) +% after 5000 -> {error, timeout} +% end. --spec do_unsubscribe(State) -> {ok, NewState} - when State :: state(), - NewState :: state(). - -do_unsubscribe(State = #s{connp = none}) -> - {ok, State}; -do_unsubscribe(State = #s{connp = ConnP, connm = ConnM}) -> - true = demonitor(ConnM), - ok = zx_conn:stop(ConnP), - NewState = State#s{realm = none, name = none, version = none, - connp = ConnP, connm = ConnM}, - {ok, NewState}. - - --spec do_fetch(PackageIDs) -> Result - when PackageIDs :: [zx:package_id()], - Result :: ok - | {error, Reason}, - Reason :: bad_realm - | bad_package - | bad_version - | network. +%-spec do_fetch(PackageIDs, State) -> NewState +% when PackageIDs :: [zx:package_id()], +% State :: state(), +% NewState :: state(), +% Result :: ok +% | {error, Reason}, +% Reason :: bad_realm +% | bad_package +% | bad_version +% | network. %% @private %% - -do_fetch(PackageIDs, State) -> +% +%do_fetch(PackageIDs, State) -> % FIXME: Need to create a job queue divided by realm and dispatched to connectors, % and cleared from the master pending queue kept here by the daemon as the % workers succeed. Basic task queue management stuff... which never existed % in ZX before... grrr... - case scrub(PackageIDs) of - [] -> - ok; - Needed -> - Partitioned = partition_by_realm(Needed), - EnsureDeps = - fun({Realm, Packages}) -> - ok = zx_conn:queue_package(Pid, Realm, Packages), - log(info, "Disconnecting from realm: ~ts", [Realm]) - end, - lists:foreach(EnsureDeps, Partitioned) - end. - - -partition_by_realm(PackageIDs) -> - PartitionMap = lists:foldl(fun partition_by_realm/2, #{}, PackageIDs), - maps:to_list(PartitionMap). - - -partition_by_realm({R, P, V}, M) -> - maps:update_with(R, fun(Ps) -> [{P, V} | Ps] end, [{P, V}], M). - - -ensure_deps(_, _, []) -> - ok; -ensure_deps(Socket, Realm, [{Name, Version} | Rest]) -> - ok = ensure_dep(Socket, {Realm, Name, Version}), - ensure_deps(Socket, Realm, Rest). - - --spec ensure_dep(gen_tcp:socket(), package_id()) -> ok | no_return(). +% case scrub(PackageIDs) of +% [] -> +% ok; +% Needed -> +% Partitioned = partition_by_realm(Needed), +% EnsureDeps = +% fun({Realm, Packages}) -> +% ok = zx_conn:queue_package(Pid, Realm, Packages), +% log(info, "Disconnecting from realm: ~ts", [Realm]) +% end, +% lists:foreach(EnsureDeps, Partitioned) +% end. +% +% +%partition_by_realm(PackageIDs) -> +% PartitionMap = lists:foldl(fun partition_by_realm/2, #{}, PackageIDs), +% maps:to_list(PartitionMap). +% +% +%partition_by_realm({R, P, V}, M) -> +% maps:update_with(R, fun(Ps) -> [{P, V} | Ps] end, [{P, V}], M). +% +% +%ensure_deps(_, _, []) -> +% ok; +%ensure_deps(Socket, Realm, [{Name, Version} | Rest]) -> +% ok = ensure_dep(Socket, {Realm, Name, Version}), +% ensure_deps(Socket, Realm, Rest). +% +% +%-spec ensure_dep(gen_tcp:socket(), package_id()) -> ok | no_return(). %% @private %% Given an PackageID as an argument, check whether its package file exists in the %% system cache, and if not download it. Should return `ok' whenever the file is %% sourced, but exit with an error if it cannot locate or acquire the package. - -ensure_dep(Socket, PackageID) -> - ZrpFile = filename:join("zrp", namify_zrp(PackageID)), - ok = - case filelib:is_regular(ZrpFile) of - true -> ok; - false -> fetch(Socket, PackageID) - end, - ok = install(PackageID), - build(PackageID). - - --spec scrub(Deps) -> Scrubbed - when Deps :: [package_id()], - Scrubbed :: [package_id()]. +% +%ensure_dep(Socket, PackageID) -> +% ZrpFile = filename:join("zrp", namify_zrp(PackageID)), +% ok = +% case filelib:is_regular(ZrpFile) of +% true -> ok; +% false -> fetch(Socket, PackageID) +% end, +% ok = install(PackageID), +% build(PackageID). +% +% +%-spec scrub(Deps) -> Scrubbed +% when Deps :: [package_id()], +% Scrubbed :: [package_id()]. %% @private %% Take a list of dependencies and return a list of dependencies that are not yet %% installed on the system. - -scrub([]) -> - []; -scrub(Deps) -> - lists:filter(fun(PackageID) -> not zx_lib:installed(PackageID) end, Deps). +% +%scrub([]) -> +% []; +%scrub(Deps) -> +% lists:filter(fun(PackageID) -> not zx_lib:installed(PackageID) end, Deps). @@ -963,33 +992,40 @@ scrub(Deps) -> %% @private %% Returns a new, empty monitor index. -mx_new() -> []. +mx_new() -> + maps:new(). --spec mx_add_monitor(pid(), category(), monitor_index()) -> monitor_index(). +-spec mx_add_monitor(Pid, Category, MX) -> NewMX + when Pid :: pid(), + Category :: subscriber + | requestor + | attempt, + MX :: monitor_index(), + NewMX :: monitor_index(). %% @private %% Begin monitoring the given Pid, keeping track of its category. mx_add_monitor(Pid, subscriber, MX) -> - case lists:keytake(Pid, 2, MX) of - {value, {Ref, Pid, {Subs, Reqs}}, NextMX} -> - [{Ref, Pid, {Subs + 1, Reqs}} | NextMX]; - false -> + case maps:take(Pid, MX) of + {{Ref, {Subs, Reqs}}, NextMX} -> + maps:put(Pid, {Ref, {Subs + 1, Reqs}}, NextMX); + error -> Ref = monitor(process, Pid), - [{Ref, Pid, {1, 0}} | MX] + maps:put(Pid, {Ref, {1, 0}}, MX) end; mx_add_monitor(Pid, requestor, MX) -> - case lists:keytake(Pid, 2, MX) of - {value, {Ref, Pid, {Subs, Reqs}}, NextMX} -> - [{Ref, Pid, {Subs, Reqs + 1}} | NextMX]; - false -> + case maps:take(Pid, MX) of + {{Ref, {Subs, Reqs}}, NextMX} -> + maps:put(Pid, {Ref, {Subs, Reqs + 1}}, NextMX); + error -> Ref = monitor(process, Pid), - [{Ref, Pid, {0, 1}} | MX] + maps:put(Pid, {Ref, {0, 1}}, MX) end; mx_add_monitor(Pid, attempt, MX) -> - false = lists:keymember(Pid, 2, MX), + false = maps:is_key(Pid, MX), Ref = monitor(process, Pid), - [{Ref, Pid, attempt} | MX]. + maps:put(Pid, {Ref, attempt}, MX). -spec mx_upgrade_conn(Pid, MX) -> NewMX @@ -1000,88 +1036,49 @@ mx_add_monitor(Pid, attempt, MX) -> %% Upgrade an `attempt' monitor to a `conn' monitor. mx_upgrade_conn(Pid, MX) -> - {value, {Ref, Pid, attempt}, NextMX} = lists:keytake(Pid, 2, MX), - [{Ref, Pid, {conn, []}} | NextMX]. + {{Ref, attempt}, NextMX} = maps:take(Pid, MX), + maps:put(Pid, {Ref, conn}, NextMX). --spec mx_del_monitor(Conn, Category, MX) -> Result +-spec mx_del_monitor(Conn, Category, MX) -> NewMX when Conn :: pid(), Category :: subscriber | requestor | attempt | conn, MX :: monitor_index(), - Result :: {ok, NewMX} - | {ok, NewMX, RequestRefs}, - NewMX :: monitor_index(), - RequestRefs :: [reference()]. - --spec mx_del_monitor(pid(), category(), monitor_index()) -> monitor_index(). + NewMX :: monitor_index(). %% @private %% Drop a monitor category, removing the entire monitor in the case only one category %% exists. Returns a tuple including the remaining request references in the case of %% a conn type. mx_del_monitor(Pid, subscriber, MX) -> - NewMX = - case lists:keytake(Pid, 2, MX) of - {value, {Ref, Pid, {1, 0}}, NextMX} -> - true = demonitor(Ref, [flush]), - NextMX; - {value, {Ref, Pid, {Subs, Reqs}}, NextMX} when Subs > 0 -> - [{Ref, Pid, {Subs - 1, Reqs}} | NextMX] - end, - {ok, NewMX}; + case maps:take(Pid, MX) of + {{Ref, {1, 0}}, NewMX} -> + true = demonitor(Ref, [flush]), + NewMX; + {{Ref, {Subs, Reqs}}, NextMX} when Subs > 0 -> + maps:put(Pid, {Ref, {Subs - 1, Reqs}}, NextMX) + end; mx_del_monitor(Pid, requestor, MX) -> - NewMX = - case lists:keytake(Pid, 2, MX) of - {value, {Ref, Pid, {0, 1}}, NextMX} -> - true = demonitor(Ref, [flush]), - NextMX; - {value, {Ref, Pid, {Subs, Reqs}}, NextMX} when Reqs > 0 -> - [{Ref, Pid, {Subs, Reqs - 1}} | NextMX] - end, - {ok, NewMX}; -mx_del_monitor(Pid, attempt, MX) -> - {value, {Ref, Pid, attempt}, NewMX} = lists:keytake(Pid, 2, MX), + case maps:take(Pid, MX) of + {{Ref, {0, 1}}, NewMX} -> + true = demonitor(Ref, [flush]), + NewMX; + {{Ref, {Subs, Reqs}}, NextMX} when Reqs > 0 -> + maps:put(Pid, {Ref, {Subs, Reqs - 1}}, NextMX) + end; +mx_del_monitor(Pid, Category, MX) -> + {{Ref, Category}, NewMX} = maps;take(Pid, MX), true = demonitor(Ref, [flush]), - {ok, NewMX}; -mx_del_monitor(Pid, conn, MX) -> - {value, {Ref, Pid, {conn, RequestRefs}}, NewMX} = lists:keytake(Pid, 2, MX), - true = demonitor(Ref, [flush]), - {ok, NewMX, RequestRefs}. + NewMX. --spec mx_stash_request(Conn, RequestRef, MX) -> NewMX - when Conn :: pid(), - RequestRef :: reference(), - MX :: monitor_index(), - NewMX :: monitor_index(). -%% @private -%% Add a pending request reference to the connection monitor's record. - -mx_stash_request(Conn, RequestRef, MX) -> - {value, {Ref, Conn, {conn, Pending}}, NextMX} = lists:keytake(Conn, 2, MX), - NewPending = [RequestRef | Pending], - [{Ref, Conn, {conn, NewPending}} | NextMX]. - - --spec mx_clear_request(Conn, RequestRef, MX) -> NewMX - when Conn :: pid(), - RequestRef :: reference(), - MX :: monitor_index(), - NewMX :: monitor_index(). -%% @private -%% Remove a pending request reference from the connection monitor's record. - -mx_clear_request(Conn, RequestRef, MX) -> - {value, {Ref, Conn, {conn, Pending}}, NextMX} = lists:keytake(Conn, 2, MX), - NewPending = lists:delete(RequestRef, Pending), - [{Ref, Conn, {conn, NewPending}} | NextMX]. - - --spec mx_lookup_category(pid(), monitor_index()) -> Result - when Result :: attempt +-spec mx_lookup_category(Pid, MX) -> Result + when Pid :: pid(), + MX :: monitor_index(), + Result :: attempt | conn | requestor | subscriber @@ -1090,13 +1087,13 @@ mx_clear_request(Conn, RequestRef, MX) -> %% Lookup a monitor's categories. mx_lookup_category(Pid, MX) -> - Monitor = lists:keyfind(Pid, 2, MX), - case element(3, Monitor) of - attempt -> attempt; - {conn, _} -> conn; - {0, _} -> requestor; - {_, 0} -> subscriber; - {_, _} -> sub_req + Monitor = maps:get(Pid, MX), + case element(2, Monitor) of + attempt -> attempt; + conn -> conn; + {0, _} -> requestor; + {_, 0} -> subscriber; + {_, _} -> sub_req end. @@ -1119,8 +1116,8 @@ mx_lookup_category(Pid, MX) -> cx_load() -> case cx_populate() of - {ok, CX} -> - CX; + {ok, Realms} -> + #cx{realms = maps:from_list(Realms)}; {error, Reason} -> Message = "Realm data and host cache load failed with : ~tp", ok = log(error, Message, [Reason]), @@ -1146,41 +1143,42 @@ cx_populate() -> Pattern = filename:join(Home, "*.realm"), case filelib:wildcard(Pattern) of [] -> {error, no_realms}; - RealmFiles -> {ok, cx_populate(RealmFiles, #cx{})} + RealmFiles -> {ok, cx_populate(RealmFiles, [])} end. --spec cx_populate(RealmFiles, CX) -> NewCX +-spec cx_populate(RealmFiles, Realms) -> NewRealms when RealmFiles :: file:filename(), - CX :: conn_index(), - NewCX :: conn_index(). + Realms :: [{zx:realm(), realm_meta()}], + NewRealms :: [{zx:realm(), realm_meta()}]. %% @private %% Pack an initially empty conn_index() with realm meta and host cache data. %% Should not halt on a corrupted, missing, malformed, etc. realm file but will log %% any loading errors. -cx_populate([File | Files], CX) -> - case file:consult(File) of - {ok, Meta} -> - NewCX = cx_load_realm_meta(Meta, CX), - cx_populate(Files, NewCX); - {error, Reason} -> - Message = "Realm file ~tp could not be read. Failed with: ~tp. Skipping.", - ok = log(warning, Message, [File, Reason]), - cx_populate(Files, CX) - end; -cx_populate([], CX) -> - CX. +cx_populate([File | Files], Realms) -> + NewRealms = + case file:consult(File) of + {ok, Meta} -> + Realm = cx_load_realm_meta(Meta), + [Realm | Realms]; + {error, Reason} -> + Message = "Loading realm file ~tp failed with: ~tp. Skipping...", + ok = log(warning, Message, [File, Reason]), + Realms + end, + cx_populate(Files, NewRealms); +cx_populate([], Realms) -> + Realms. --spec cx_load_realm_meta(Meta, CX) -> NewCX - when Meta :: [{Key :: atom(), Value :: term()}], - CX :: conn_index(), - NewCX :: conn_index(). +-spec cx_load_realm_meta(Meta) -> Result + when Meta :: [{Key :: atom(), Value :: term()}], + Result :: {zx:realm(), realm_meta()}. %% @private %% This function MUST adhere to the realmfile definition found at. -cx_load_realm_meta(Meta, CX = #cx{realms = Realms}) -> +cx_load_realm_meta(Meta) -> {realm, Realm} = lists:keyfind(realm, 1, Meta), {revision, Revision} = lists:keyfind(revision, 1, Meta), {prime, Prime} = lists:keyfind(prime, 1, Meta), @@ -1189,14 +1187,12 @@ cx_load_realm_meta(Meta, CX = #cx{realms = Realms}) -> {sysops, Sysops} = lists:keyfind(sysops, 1, Meta), Basic = #rmeta{revision = Revision, - serial = Serial, prime = Prime, realm_keys = RealmKeys, package_keys = PackageKeys, sysops = Sysops}, Complete = cx_load_cache(Realm, Basic), - NewRealms = maps:put(Realm, Complete, Realms), - CX#cx{realms = NewRealms}. + {Realm, Complete}. -spec cx_load_cache(Realm, Basic) -> Complete @@ -1213,6 +1209,7 @@ cx_load_realm_meta(Meta, CX = #cx{realms = Realms}) -> %% Better file contention and parallel-executing system handling should %% eventually be implemented, especially if zx becomes common for end-user %% GUI programs. +%% NOTE: This "fixme" will only apply until the zx universal lock is implemented. cx_load_cache(Realm, Basic) -> CacheFile = cx_cache_file(Realm), @@ -1242,6 +1239,7 @@ cx_store_cache(#cx{realms = Realms}) -> -spec cx_write_cache({zx:realm(), realm_meta()}) -> ok. %% @private %% FIXME: The same concerns as noted in the cx_load_cache/2 FIXME comment apply here. +%% NOTE: This "fixme" will only apply until the zx universal lock is implemented. cx_write_cache({Realm, #rmeta{serial = Serial, private = Private, mirrors = Mirrors}}) -> @@ -1270,62 +1268,53 @@ cx_realms(#cx{realms = Realms}) -> CX :: conn_index(), Result :: {ok, Next, NewCX} | {prime, Prime, NewCX} - | {error, Reason}, + | {error, Reason, NewCX}, Next :: zx:host(), Prime :: zx:host(), NewCX :: conn_index(), Reason :: bad_realm | connected. %% @private -%% Given a realm, retun the next cached host location to which to connect. Returns an -%% error if the realm is already assigned or if the realm is not configured. +%% Given a realm, retun the next cached host location to which to connect. Returns +%% error if the realm is already assigned, if it is available but should have been +%% assigned, or if the realm is not configured. +%% If all cached mirrors are exhausted it will return the realm's prime host and +%% reload the mirrors queue with private mirrors. -cx_next_host(Realm, CX = #cx{assigned = Assigned}) -> - case lists:keymember(Realm, 1, Assigned) of - false -> cx_next_host2(Realm, CX); - true -> {error, connected} - end. - -cx_next_host2(Realm, CX = #cx{realm = Realms}) -> +cx_next_host(Realm, CX = #cx{realms = Realms}) -> case maps:find(Realm, Realms) of - {ok, Meta} -> - {Result, Host, NewMeta} = cx_next_host3(Meta), + {ok, Meta = #rmeta{assigned = none, available = [Pid | Pids]}} -> + ok = log(warning, "Call to cx_next_host/2 when connection available."), + NewMeta = Meta#rmeta{assigned = Pid, available = Pids}, NewRealms = maps:put(Realm, NewMeta, Realms), - {Result, Host, CX#cx{realms = NewRealms}}; + NewCX = CX#cx{realms = NewRealms}, + {error, connected, NewCX}; + {ok, Meta = #rmeta{assigned = none, available = []}} -> + {Outcome, Host, NewMeta} = cx_next_host(Meta), + NewRealms = maps:put(Realm, NewMeta, Realms), + NewCX = CX#cx{realms = NewRealms}, + {Outcome, Host, NewCX}; + {ok, Meta = #rmeta{assigned = Conn}} when is_pid(Conn) -> + ok = log(warning, "Call to cx_next_host/2 when connection assigned."), + {error, connected, CX}; error -> - {error, bad_realm} + {error, bad_realm, CX} end. --spec cx_next_host3(RealmMeta) -> Result - when RealmMeta :: realm_meta(), - Result :: {ok, Next, NewRealmMeta} - | {prime, Prime, NewRealmMeta}, - Next :: zx:host(), - Prime :: zx:host(), - NewRealmMeta :: realm_meta(). -%% @private -%% Match on the important success cases first. -%% If there is a locally configured set of private mirrors (usually on the same LAN, -%% or public ones an organization hosts for its own users) then try those first. -%% Trying "first" is a relative concept in long-lived systems that experience a high -%% frequency of network churn. When the daemon is initialized a queue is created from -%% the known public mirrors, and then the private mirrors are enqueued at the head of -%% the mirrors so they will be encountered first. -%% If the entire combined mirrors list is exhausted then the prime node will be -%% returned, but also as a consequence the prime mirrors will be reloaded at the head -%% once again so if the prime fails (or causes a redirect) the private mirrors will -%% once again occur in the queue. -%% If the prime node is returned it is indicated with the atom `prime', which should -%% indicate to the caller that any iterative host scanning or connection procedures -%% should treat this as the last value of interest (and stop spawning connections). +-spec cx_next_host(Meta) -> Result + when Meta :: realm_meta(), + Result :: {ok, Next, NewMeta} + | {prime, Prime, NewMeta}, + Next :: zx:host(), + Prime :: zx:host(), + NewMeta :: realm_meta(). -cx_next_host3(Meta = #rmeta{prime = Prime, private = Private, mirrors = Mirrors}) -> - case queue:is_empty(Mirrors) of - false -> - {{value, Next}, NewMirrors} = queue:out(Mirrors), +cx_next_host(Meta = #rmeta{prime = Prime, private = Private, mirrors = Mirrors}) -> + case queue:out(Mirrors) of + {{value, Next}, NewMirrors} -> {ok, Next, Meta#rmeta{mirrors = NewMirrors}}; - true -> + {empty, Mirrors} -> Enqueue = fun(H, Q) -> queue:in(H, Q) end, NewMirrors = lists:foldl(Enqueue, Private, Mirrors), {prime, Prime, Meta#rmeta{mirrors = NewMirrors}} @@ -1364,7 +1353,7 @@ cx_next_hosts2(N, Realm, Meta, CX = #cx{realms = Realms}) -> cx_next_hosts3(N, Hosts, Meta) when N < 1 -> {ok, Hosts, Meta}; cx_next_hosts3(N, Hosts, Meta) -> - case cx_next_host3(Meta) of + case cx_next_host(Meta) of {ok, Host, NewMeta} -> cx_next_hosts3(N - 1, [Host | Hosts], NewMeta); {prime, Prime, NewMeta} -> {ok, [Prime | Hosts], NewMeta} end. @@ -1400,9 +1389,9 @@ cx_add_attempt(Pid, Host, Realm, CX = #cx{attempts = Attempts}) -> CX#cx{attempts = [{Pid, Host, [Realm]} | Attempts]}. --spec cx_connected(Available, Conn, CX) -> Result +-spec cx_connected(Available, Pid, CX) -> Result when Available :: [{zx:realm(), zx:serial()}], - Conn :: pid(), + Pid :: pid(), CX :: conn_index(), Result :: {Assignment, NewCX}, Assignment :: assigned | unassigned, @@ -1415,11 +1404,13 @@ cx_add_attempt(Pid, Host, Realm, CX = #cx{attempts = Attempts}) -> %% The return value is a tuple that indicates whether the new connection was assigned %% or not and the updated CX data value. -cx_connected(Available, Conn, CX = #cx{attempts = Attempts}) -> - {value, {Pid, Host, _}, NewAttempts} = lists:keytake(Conn, 1, Attempts), - Realms = [R || {R, _} <- Available], +cx_connected(Available, Pid, CX = #cx{attempts = Attempts}) -> + {value, Attempt, NewAttempts} = lists:keytake(Pid, 1, Attempts), + Host = element(2, Attempt), + Realms = [element(1, R) || R <- Available], NewCX = CX#cx{attempts = NewAttempts}, - cx_connected(unassigned, Available, {Pid, Host, Realms}, NewCX). + Conn = #conn{pid = Pid, host = Host, realms = Realms}, + cx_connected(unassigned, Available, Conn, NewCX). -spec cx_connected(A, Available, Conn, CX) -> {NewA, NewCX} @@ -1433,10 +1424,12 @@ cx_connected(Available, Conn, CX = #cx{attempts = Attempts}) -> %% Only accept a new realm as available if the reported serial is equal or newer to the %% highest known serial. -cx_connected(A, [{Realm, Serial} | Rest], Conn, CX = #cx{realms = Realms}) -> +cx_connected(A, + [{Realm, Serial} | Rest], + Conn = #conn{pid = Pid}, + CX = #cx{realms = Realms}) -> case maps:find(Realm, Realms) of {ok, Meta = #rmeta{serial = S, available = Available}} when S =< Serial -> - Pid = element(1, Conn), NewMeta = Meta#rmeta{serial = Serial, available = [Pid | Available]}, {NewA, NewCX} = cx_connected(A, Realm, Conn, NewMeta, CX), cx_connected(NewA, Rest, Conn, NewCX); @@ -1445,7 +1438,10 @@ cx_connected(A, [{Realm, Serial} | Rest], Conn, CX = #cx{realms = Realms}) -> error -> cx_connected(A, Rest, Conn, CX) end; -cx_connected(A, [], Conn, CX = #cx{conns = Conns}) -> +cx_connected(A, + [], + Conn, + CX = #cx{conns = Conns}) -> {A, CX#cx{conns = [Conn | Conns]}}. @@ -1465,7 +1461,7 @@ cx_connected(A, [], Conn, CX = #cx{conns = Conns}) -> cx_connected(A, Realm, - {Pid, Prime, _}, + #conn{pid = Pid, host = Prime}, Meta = #rmeta{prime = Prime, assigned = none}, CX = #cx{realms = Realms}) -> NewMeta = Meta#rmeta{assigned = Pid}, @@ -1474,67 +1470,70 @@ cx_connected(A, {assigned, NewCX}; cx_connected(A, Realm, - {Pid, Host, _}, + #conn{pid = Pid, host = Host}, Meta = #rmeta{mirrors = Mirrors, assigned = none}, CX = #cx{realms = Realms, attempts = Attempts}) -> - NewMirrors = enqueue_unique(Host, Mirrors), + NewMirrors = cx_enqueue_unique(Host, Mirrors), NewMeta = Meta#rmeta{mirrors = NewMirrors, assigned = Pid}, NewRealms = maps:put(Realm, NewMeta, Realms), NewCX = CX#cx{realms = NewRealms}, {assigned, NewCX}; cx_connected(A, _, - {_, Prime, _}, + #conn{host = Prime}, #rmeta{prime = Prime}, CX) -> {A, CX}; cx_connected(A, Realm, - {_, Host, _}, + #conn{host = Host}, Meta = #rmeta{mirrors = Mirrors}, CX = #cx{realms = Realms}) -> - NewMirrors = enqueue_unique(Host, Mirrors), - NetMeta = Meta#rmeta{mirrors = NewMirrors}, + NewMirrors = cx_enqueue_unique(Host, Mirrors), + NewMeta = Meta#rmeta{mirrors = NewMirrors}, NewRealms = maps:put(Realm, NewMeta, Realms), NewCX = CX#cx{realms = NewRealms}, {A, NewCX}. --spec enqueue_unique(term(), queue:queue()) -> queue:queue(). +-spec cx_enqueue_unique(term(), queue:queue()) -> queue:queue(). %% @private %% Simple function to ensure that only unique elements are added to a queue. Obviously %% this operation is extremely general and O(n) in complexity due to the use of %% queue:member/2. -enqueue_unique(Element, Queue) -> +cx_enqueue_unique(Element, Queue) -> case queue:member(Element, Queue) of true -> Queue; false -> queue:in(Element, Queue) end. --spec cx_failed(Conn, CX) -> NewCX - when Conn :: pid(), - CX :: conn_index(), - NewCX :: conn_index(). +-spec cx_failed(Conn, CX) -> {Realms, NewCX} + when Conn :: pid(), + CX :: conn_index(), + Realms :: [zx:realm()], + NewCX :: conn_index(). %% @private %% Remove a failed attempt and all its associations. -cx_failed(Conn, #cx{attempts = Attempts}) -> - NewAttempts = lists:keydelete(Conn, 1, Attempts), - CX#cx{attempts = NewAttempts}. +cx_failed(Conn, CX = #cx{attempts = Attempts}) -> + {value, Attempt, NewAttempts = lists:keytake(Conn, 1, Attempts), + Realms = element(3, Attempt), + {Realms, CX#cx{attempts = NewAttempts}}. --spec cx_redirect(Conn, Hosts, CX) -> {Unassigned, NextCX} +-spec cx_redirect(Conn, Hosts, CX) -> {Unassigned, NewCX} when Conn :: pid(), Hosts :: [{zx:host(), [zx:realm()]}], CX :: conn_index(), Unassigned :: [zx:realm()], - NextCX :: conn_index(). + NewCX :: conn_index(). -cx_redirect(Conn, Hosts, CX) -> - NextCX = cx_failed(Conn, CX), - NewCX = #cx{realms = Realms} = cx_redirect(Hosts, NextCX), +cx_redirect(Conn, Hosts, CX = #cx{attempts = Attempts}) -> + NewAttempts = lists:keydelete(Conn, 1, Attempts), + NextCX = CX#cx{attempts = NewAttempts}, + NewCX = cx_redirect(Hosts, NextCX), Unassigned = cx_unassigned(NewCX), {Unassigned, NewCX}. @@ -1542,7 +1541,7 @@ cx_redirect(Conn, Hosts, CX) -> -spec cx_redirect(Hosts, CX) -> NewCX when Hosts :: [{zx:host(), [zx:realm()]}], CX :: conn_index(), - NextCX :: conn_index(). + NewCX :: conn_index(). %% @private %% Add the host to any realm mirror queues that it provides. @@ -1551,7 +1550,7 @@ cx_redirect([{Host, Provided} | Rest], CX = #cx{realms = Realms}) -> fun(R, Rs) -> case maps:find(R, Rs) of {ok, Meta = #rmeta{mirrors = Mirrors}} -> - NewMirrors = enqueue_unique(Host, Mirrors), + NewMirrors = cx_enqueue_unique(Host, Mirrors), NewMeta = Meta#rmeta{mirrors = NewMirrors}, maps:put(R, NewMeta, Rs); error -> @@ -1582,20 +1581,24 @@ cx_unassigned(#cx{realms = Realms}) -> maps:fold(NotAssigned, [], Realms). --spec cx_disconnected(Conn, CX) -> NewCX - when Conn :: pid(), - CX :: conn_index(), - NewCX :: conn_index(). +-spec cx_disconnected(Conn, CX) -> {Requests, Subs, NewCX} + when Conn :: pid(), + CX :: conn_index(), + Requests :: [reference()], + Subs :: [zx:package()], + NewCX :: conn_index(). %% @private %% An abstract data handler which is called whenever a connection terminates. %% This function removes all data related to the disconnected pid and its assigned %% realms, and returns the monitor reference of the pid, a list of realms that are now %% unassigned, and an updated connection index. -cx_disconnected(Conn, CX = #cx{realms = Realms, conns = Conns}) -> - {value, {Pid, Host, _}, NewConns} = lists:keytake(Conn, 1, Conns), +cx_disconnected(Pid, CX = #cx{realms = Realms, conns = Conns}) -> + {value, Conn, NewConns} = lists:keytake(Pid, #conn.pid, Conns), + #conn{host = Host, requests = Requests, subs = Subs} = Conn, NewRealms = cx_scrub_assigned(Pid, Host, Realms), - CX#cx{realms = NewRealms, conns = NewConns}. + NewCX = CX#cx{realms = NewRealms, conns = NewConns}, + {Requests, Subs, NewCX}. -spec cx_scrub_assigned(Pid, Host, Realms) -> NewRealms @@ -1611,11 +1614,11 @@ cx_scrub_assigned(Pid, Host, Realms) -> Scrub = fun (_, V = #rmeta{mirrors = M, available = A, assigned = C}) when C == Pid -> - V#rmeta{mirrors = enqueue_unique(Host, M), + V#rmeta{mirrors = cx_enqueue_unique(Host, M), available = lists:delete(Pid, A), assigned = none}; (_, V = #rmeta{mirrors = M, available = A}) -> - V#rmeta{mirrors = enqueue_unique(Host, M), + V#rmeta{mirrors = cx_enqueue_unique(Host, M), available = lists:delete(Pid, A)} end, maps:map(Scrub, Realms). From c26f6737dc845810047bc4fd62075e50175223bc Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Thu, 15 Mar 2018 16:52:21 +0900 Subject: [PATCH 43/55] Bleh --- TODO | 18 +- zomp/lib/otpr-zx/0.1.0/src/zx.erl | 2 +- zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl | 38 +- zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl | 1073 +++++++++++++++------- zomp/lib/otpr-zx/0.1.0/src/zx_lib.erl | 25 +- 5 files changed, 796 insertions(+), 360 deletions(-) diff --git a/TODO b/TODO index 3ee9152..fed003f 100644 --- a/TODO +++ b/TODO @@ -2,11 +2,23 @@ On redirect a list of hosts of the form [{zx:host(), [zx:realm()]}] must be provided to the downstream client. This is the only way that downstream clients can determine which redirect hosts are useful to it. - - Connect attempts and established connections should have different report statuses. - An established connection does not necessarily have other attempts being made concurrently, so a termination should initiate 3 new connect attempts as init. - An attempt is just an attempt. It can fall flat and be replaced only 1::1. + - Change zx_daemon request references to counters. + Count everything. + This will be the only way to sort of track stats other than log analysis. + Log analysis sucks. + + - Double-indexing must happen everywhere for anything to be discoverable without traversing the entire state of zx_daemon whenever a client or conn crashes. + + - zx_daemon request() types have been changes to flat, wide tuples as in the main zx module. + This change is not yet refected in the using code. + + - Write a logging process. + Pick a log rotation scheme. + Eventually make it so that it can shed log loads in the event they get out of hand. + - Create zx_daemon primes. + See below New Feature: ZX Universal lock Cross-instance communication diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx.erl b/zomp/lib/otpr-zx/0.1.0/src/zx.erl index 9c5b057..306bb91 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx.erl @@ -50,7 +50,7 @@ -type option() :: {string(), term()}. -type host() :: {string() | inet:ip_address(), inet:port_number()}. -type key_id() :: {realm(), key_name()}. --type key_name() :: label(). +-type key_name() :: lower0_9(). -type user() :: {realm(), username()}. -type username() :: label(). -type lower0_9() :: [$a..$z | $0..$9 | $_]. diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl index ba8d1c5..4cefbad 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl @@ -11,7 +11,7 @@ -copyright("Craig Everett "). -license("GPL-3.0"). --export([start_monitor/1, stop/1]). +-export([start/1, stop/1]). -export([start_link/1]). -include("zx_logger.erl"). @@ -20,24 +20,17 @@ %%% Startup --spec start_monitor(Target) -> Result +-spec start(Target) -> Result when Target :: zx:host(), - Result :: {ok, PID :: pid(), Mon :: reference()} - | {error, Reason}, - Reason :: term(). + Result :: {ok, pid()} + | {error, Reason :: term()}. %% @doc %% Starts a connection to a given target Zomp node. This call itself should never fail, %% but this process may fail to connect or crash immediately after spawning. Should %% only be called by zx_daemon. -start_monitor(Target) -> - case zx_conn_sup:start_conn(Target) of - {ok, Pid} -> - Mon = monitor(process, Pid), - {ok, Pid, Mon}; - Error -> - Error - end. +start(Target) -> + zx_conn_sup:start_conn(Target). -spec stop(Conn :: pid()) -> ok. @@ -49,16 +42,24 @@ stop(Conn) -> ok. --spec subscribe(Conn, Realm) -> ok - when Conn :: pid(), - Realm :: zx:realm(), - Result :: ok. +-spec subscribe(Conn, Package) -> ok + when Conn :: pid(), + Package :: zx:package(). subscribe(Conn, Realm) -> Conn ! {subscribe, Realm}, ok. +-spec unsubscribe(Conn, Package) -> ok + when Conn :: pid(), + Package :: zx:package(). + +unsubscribe(Conn, Package) -> + Conn ! {unsubscribe, Package}, + ok. + + -spec start_link(Target) -> when Target :: zx:host(), Result :: {ok, pid()} @@ -172,6 +173,9 @@ loop(Parent, Debug, Socket) -> ok = handle(Bin, Socket), ok = inet:setopts(Socket, [{active, once}]), loop(Parent, Debug, Socket); + {subscribe, Package} -> + {unsubscribe, Package} -> + stop -> ok = zx_net:disconnect(Socket), terminate(); diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl index c1f6bef..caf10fe 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl @@ -98,10 +98,9 @@ -copyright("Craig Everett "). -license("GPL-3.0"). - -export([pass_meta/3, subscribe/1, unsubscribe/1, - list/1, latest/1, + list/0, list/1, list/2, list/3, latest/1, fetch/1, key/1, pending/1, packagers/1, maintainers/1, sysops/1]). -export([report/1, result/2, notify/2]). @@ -109,6 +108,14 @@ -export([init/1, handle_call/3, handle_cast/2, handle_info/2, code_change/3, terminate/2]). + +-export_type([id/0, result/0, + realm_list/0, package_list/0, version_list/0, latest_result/0, + fetch_result/0, key_result/0, + pending_result/0, pack_result/0, maint_result/0, sysop_result/0, + sub_message/0]). + + -include("zx_logger.hrl"). @@ -119,9 +126,10 @@ {meta = none :: none | zx:package_meta(), home = none :: none | file:filename(), argv = none :: none | [string()], - actions = [] :: [{pid(), subunsub()} | {reference(), request()}], - requests = maps:new() :: #{reference() := request()}, - subs = [] :: [{pid(), zx:package()}], + id = 0 :: id(), + actions = [] :: [request()], + requests = maps:new() :: requests(), + dropped = maps:new() :: requests(), mx = mx_new() :: monitor_index(), cx = cx_load() :: conn_index()}). @@ -149,18 +157,22 @@ {pid :: pid(), host :: zx:host(), realms :: [zx:realm()], - requests :: [reference()], - subs :: [zx:package()]}). + requests :: [id()], + subs :: [{pid(), zx:package()}]}). %% State Types -type state() :: #s{}. -%-type monitor_index() :: [{reference(), pid(), category()}]. +-opaque id() :: non_neg_integer(). +-type request() :: {subscribe, pid(), zx:package()} + | {unsubscribe, pid(), zx:package()} + | {request, pid(), id(), action()}. +-type requests() :: #{id() := {pid(), action()}}. -type monitor_index() :: #{pid() := {reference(), category()}}. -type conn_index() :: #cx{}. -type realm_meta() :: #rmeta{}. -type connection() :: #conn{}. --type category() :: {Subs :: non_neg_integer(), Reqs :: non_neg_integer()} +-type category() :: {Reqs :: [id()], Subs :: [zx:package()]} | attempt | conn. @@ -171,19 +183,18 @@ %% Subscriber / Requestor Communication % Incoming Request messages --type action () :: {Requestor :: pid(), - Request :: request() | subunsub()}. - --type request() :: {list, realms | zx:identifier()} - | {latest, zx:identifier()} - | {fetch, zx:package_id()} - | {key, zx:key_id()} - | {pending, zx:package()} - | {packagers, zx:package()} - | {maintainers, zx:package()} +% This form allows a bit of cheating with blind calls to `element(2, Request)'. +-type action() :: list + | {list, zx:realm()} + | {list, zx:realm(), zx:name()} + | {list, zx:realm(), zx:name(), zx:version()} + | {latest, zx:realm(), zx:name(), zx:version()} + | {fetch, zx:realm(), zx:name(), zx:version()} + | {key, zx:realm(), zx:key_name()} + | {pending, zx:realm(), zx:name()} + | {packagers, zx:realm(), zx:name()} + | {maintainers, zx:realm(), zx:name()} | {sysops, zx:realm()}. --type subunsub() :: {subscribe, zx:package()} - | {unsubscribe, zx:package()}. % Outgoing Result Messages % @@ -192,67 +203,62 @@ % % Subscription messages are a separate type below. --type result() :: sub_message() - | list_result() - | latest_result() - | fetch_result() - | key_result() - | pending_result() - | pack_result() - | maint_result() - | sysop_result(). --type list_result() :: {list, realms, - Message :: {ok, [zx:realm()]}} - | {list, zx:realm(), - Message :: {ok, [zx:name()]} - | {error, bad_realm | timeout}} - | {list, zx:package(), - Message :: {ok, [zx:version()]} - | {error, bad_realm - | bad_package - | timeout}}. --type latest_result() :: {latest, - Package :: zx:package() - | zx:package_id(), - Message :: {ok, zx:package_id()} - | {error, bad_realm - | bad_package - | bad_version - | timeout}}. --type fetch_result() :: {fetch, zx:package_id(), - Message :: {hops, non_neg_integer()} - | done - | {error, bad_realm - | bad_package - | bad_version - | timeout}}. --type key_result() :: {key, zx:key_id(), - Message :: {ok, binary()} - | {error, bad_key - | timeout}}. --type pending_result() :: {pending, zx:package(), - Message :: {ok, [zx:version()]} - | {error, bad_realm - | bad_package - | timeout}}. --type pack_result() :: {packagers, zx:package(), - Message :: {ok, [zx:user()]} - | {error, bad_realm - | bad_package - | timeout}}. --type maint_result() :: {maintainers, zx:package(), - Message :: {ok, [zx:user()]} - | {error, bad_realm - | bad_package - | timeout}}. --type sysop_result() :: {sysops, zx:realm(), - Message :: {ok, [zx:user()]} - | {error, bad_host - | timeout}}. +-type result() :: {z_result, + RequestID :: id(), + Message :: realm_list() + | package_list() + | version_list() + | latest_result() + | fetch_result() + | key_result() + | pending_result() + | pack_result() + | maint_result() + | sysop_result()}. + +-type realm_list() :: [zx:realm()]. +-type package_list() :: {ok, [zx:name()]} + | {error, bad_realm + | timeout}. +-type version_list() :: {ok, [zx:version()]} + | {error, bad_realm + | bad_package + | timeout}. +-type latest_result() :: {ok, zx:version()} + | {error, bad_realm + | bad_package + | bad_version + | timeout}. +-type fetch_result() :: {hops, non_neg_integer()} + | done + | {error, bad_realm + | bad_package + | bad_version + | timeout}. +-type key_result() :: done + | {error, bad_realm + | bad_key + | timeout}. +-type pending_result() :: {ok, [zx:version()]} + | {error, bad_realm + | bad_package + | timeout}. +-type pack_result() :: {ok, [zx:user()]} + | {error, bad_realm + | bad_package + | timeout}. +-type maint_result() :: {ok, [zx:user()]} + | {error, bad_realm + | bad_package + | timeout}. +-type sysop_result() :: {ok, [zx:user()]} + | {error, bad_host + | timeout}. % Subscription Results --type sub_message() :: {subscription, zx:package(), +-type sub_message() :: {z_sub, + zx:package(), Message :: {update, zx:package_id()} | {error, bad_realm | bad_package}}. @@ -274,123 +280,236 @@ %% be known whether the very first thing the target application will do is send this %% process an async message. That implies that this should only ever be called once, %% by the launching process (which normally terminates shortly thereafter). -%% -%% FIXME: I don't like something about this idea. Either it is wrong to be passing in -%% the primary project's meta, or it is wrong to be doing it this way, or it is -%% wrong to have only *one* primary app in the EVM instance. Or something. -%% Something smells off about this. -%% We WILL need to maintain and know meta. -%% We DON'T know when or why it will be important to running programs. -%% Once we understand this better we need to come back and fix or replace it. -%% (2018-03-01 -CRE) pass_meta(Meta, Dir, ArgV) -> gen_server:cast(?MODULE, {pass_meta, Meta, Dir, ArgV}). --spec subscribe(zx:package()) -> ok. +-spec subscribe(Package) -> ok + when Package :: zx:package(). %% @doc %% Subscribe to update notifications for a for a particular package. -%% The caller will receive update notifications of type sub_result() as Erlang +%% The caller will receive update notifications of type `sub_message()' as Erlang %% messages whenever an update occurs. +%% Crashes the caller if the Realm or Name of the Package argument are illegal +%% `zx:lower0_9' strings. -subscribe(Package) -> +subscribe(Package = {Realm, Name}) -> + true = zx_lib:valid_lower0_9(Realm), + true = zx_lib:valid_lower0_9(Name), gen_server:cast(?MODULE, {subscribe, self(), Package}). --spec unsubscribe(zx:package()) -> ok. +-spec unsubscribe(Package) -> ok + when Package :: zx:package(). %% @doc %% Instructs the daemon to unsubscribe if subscribed. Has no effect if not subscribed. +%% Crashes the caller if the Realm or Name of the Package argument are illegal +%% `lower0_9' strings. -unsubscribe(Package) -> +unsubscribe(Package = {Realm, Name}) -> + true = zx_lib:valid_lower0_9(Realm), + true = zx_lib:valid_lower0_9(Name), gen_server:cast(?MODULE, {unsubscribe, self(), Package}). --spec list(Identifier) -> ok - when Identifier :: realms - | zx:identifier(). +-spec list() -> realm_list(). %% @doc -%% Requests a list of realms, packages, or package versions depending on the -%% identifier provided. +%% Request a list of currently configured realms. Because this call is entirely local +%% it is the only one that does not involve a round-trip -list(Identifier) -> - request({list, Identifier}). +list() -> + gen_server:call(?MODULE, {request, list}). --spec latest(Identifier) -> ok - when Identifier :: zx:package() | zx:package_id(). +-spec list(Realm) -> {ok, RequestID} + when Realm :: zx:realm(), + RequestID :: term(). %% @doc -%% Request the lastest version of a package within the scope of the identifier. -%% If a package with no version is provided, the absolute latest version will be -%% sent once queried. If a partial version is provided then only the latest version -%% within the provided scope will be returned. +%% Requests a list of packages provided by the given realm. +%% Returns a request ID which will be returned in a message with the result from an +%% upstream zomp node. Crashes the caller if Realm is an illegal string. %% -%% If package {"foo", "bar"} has [{1,2,3}, {1,2,5}, {1,3,1}, {2,4,5}] available, -%% querying {"foo", "bar"} or {"foo", "bar", {z,z,z}} will result in {2,4,5}, but -%% querying {"foo", "bar", {1,z,z}} will result in {1,3,1}, granted that the realm -%% "foo" is reachable. +%% Response messages are of the type `result()' where the third element is of the +%% type `package_list()'. -latest(Identifier) -> - request({latest, Identifier}). +list(Realm) -> + true = zx_lib:valid_lower0_9(Realm), + request({list, Realm}). --spec fetch(zx:package_id()) -> ok. +-spec list(Realm, Name) -> {ok, RequestID} + when Realm :: zx:realm(), + Name :: zx:name(), + RequestID :: term(). +%% @doc +%% Requests a list of package versions. +%% Returns a request ID which will be returned in a message with the result from an +%% upstream zomp node. Crashes the if Realm or Name are illegal strings. +%% +%% Response messages are of the type `result()' where the third element is of the +%% type `version_list()'. + +list(Realm, Name) -> + true = zx_lib:valid_lower0_9(Realm), + true = zx_lib:valid_lower0_9(Name), + request({list, Realm, Name}). + + +-spec list(Realm, Name, Version) -> {ok, RequestID} + when Realm :: zx:realm(), + Name :: zx:name(), + Version :: zx:version(), + RequestID :: term(). +%% @doc +%% Request a list of package versions constrained by a partial version. +%% Returns a request ID which will be returned in a message with the result from an +%% upstream zomp node. Can be used to check for a specific version by testing for a +%% response of `{error, bad_version}' when a full version number is provided. +%% Crashes the caller on an illegal realm name, package name, or version tuple. +%% +%% Response messages are of the type `result()' where the third element is of the +%% type `list_result()'. + +list(Realm, Name, Version) -> + true = zx_lib:valid_lower0_9(Realm), + true = zx_lib:valid_lower0_9(Name), + true = zx_lib:valid_version(Version), + request({list, Realm, Name, Version}). + + +-spec latest(Identifier) -> {ok, RequestID} + when Identifier :: zx:package() | zx:package_id(), + RequestID :: integer(). +%% @doc +%% Request the lastest version of a package within the provided version constraint. +%% If no version is provided then the latest version overall will be returned. +%% Returns a request ID which will be returned in a message with the result from an +%% upstream zomp node. Crashes the caller on an illegal realm name, package name or +%% version tuple. +%% +%% Response messages are of the type `result()' where the third element is of the +%% type `latest_result()'. + +latest({Realm, Name}) -> + true = zx_lib:valid_lower0_9(Realm), + true = zx_lib:valid_lower0_9(Name), + request({latest, Realm, Name, {z, z, z}}); +latest({Realm, Name, Version}) -> + true = zx_lib:valid_lower0_9(Realm), + true = zx_lib:valid_lower0_9(Name), + true = zx_lib:valid_version(Version), + request({latest, Realm, Name, Version}). + + +-spec fetch(PackageID) -> {ok, RequestID} + when PackageID :: zx:package_id(), + RequestID :: integer(). %% @doc %% Ensure a package is available locally, or queue it for download otherwise. +%% Returns a request ID which will be returned in a message with the result from an +%% upstream zomp node. Crashes the caller on an illegal realm name, package name or +%% version tuple. +%% +%% Response messages are of the type `result()' where the third element is of the +%% type `fetch_result()'. -fetch(PackageID) -> - request({fetch, PackageID}). +fetch({Realm, Name, Version}) -> + true = zx_lib:valid_lower0_9(Realm), + true = zx_lib:valid_lower0_9(Name), + true = zx_lib:valid_version(Version), + request({fetch, Realm, Name, Version}). --spec key(zx:key_id()) -> ok. +-spec key(KeyID) -> {ok, RequestID} + when KeyID :: zx:key_id(), + RequestID :: id(). %% @doc %% Request a public key be fetched from its relevant realm. +%% Crashes the caller if either component of the KeyID is illegal. +%% +%% Response messages are of the type `result()' where the third element is of the +%% type `key_result()'. -key(KeyID) -> - request({key, KeyID}). +key({Realm, KeyName}) -> + true = zx_lib:valid_lower0_9(Realm), + true = zx_lib:valid_lower0_9(KeyName), + request({key, Realm, KeyName}). --spec pending(zx:package()) -> ok. +-spec pending(Package) -> {ok, RequestID} + when Package :: zx:package(), + RequestID :: id(). %% @doc %% Request the list of versions of a given package that have been submitted but not %% signed and included in their relevant realm. +%% Crashes the caller if either component of the Package is illegal. +%% +%% Response messages are of the type `result()' where the third element is of the +%% type `pending_result()'. -pending(Package) -> - request({pending, Package}). +pending({Realm, Name}) -> + true = zx_lib:valid_lower0_9(Realm), + true = zx_lib:valid_lower0_9(Name), + request({pending, Realm, Name}). --spec packagers(zx:package()) -> ok. +-spec packagers(Package) -> {ok, RequestID} + when Package :: zx:package(), + RequestID :: id(). %% @doc %% Request a list of packagers assigned to work on a given package. +%% Crashes the caller if either component of the Package is illegal. +%% +%% Response messages are of the type `result()' where the third element is of the +%% type `pack_result()'. -packagers(Package) -> - request({packagers, Package}). +packagers({Realm, Name}) -> + true = zx_lib:valid_lower0_9(Realm), + true = zx_lib:valid_lower0_9(Name), + request({packagers, Realm, Name}). --spec maintainers(zx:package()) -> ok. +-spec maintainers(Package) -> {ok, RequestID} + when Package :: zx:package(), + RequestID :: id(). %% @doc %% Request a list of maintainers assigned to work on a given package. +%% Crashes the caller if either component of the Package is illegal. +%% +%% Response messages are of the type `result()' where the third element is of the +%% type `maint_result()'. -maintainers(Package) -> - request({maintainers, Package}). +maintainers({Realm, Name}) -> + true = zx_lib:valid_lower0_9(Realm), + true = zx_lib:valid_lower0_9(Name), + request({maintainers, Realm, Name}). --spec sysops(zx:realm()) -> ok. +-spec sysops(Realm) -> {ok, RequestID} + when Realm :: zx:realm(), + RequestID :: id(). %% @doc %% Request a list of sysops in charge of maintaining a given realm. What this %% effectively does is request the sysops of the prime host of the given realm. +%% Crashes the caller if the Realm string is illegal. +%% +%% Response messages are of the type `result()' where the third element is of the +%% type `sysops_result()'. sysops(Realm) -> + true = zx_lib:valid_lower0_9(Realm), request({sysops, Realm}). -%% Public Caster --spec request(action()) -> ok. +%% Request Caster +-spec request(action()) -> {ok, RequestID} + when RequestID :: integer(). %% @private %% Private function to wrap the necessary bits up. request(Action) -> - gen_server:cast(?MODULE, {request, make_ref(), self(), Action}). + gen_server:call(?MODULE, {request, self(), Action}). @@ -399,7 +518,7 @@ request(Action) -> -spec report(Message) -> ok when Message :: {connected, Realms :: [{zx:realm(), zx:serial()}]} | {redirect, Hosts :: [{zx:host(), [zx:realm()]}]} - | aborted + | failed | disconnected. %% @private %% Should only be called by a zx_conn. This function is how a zx_conn reports its @@ -424,7 +543,7 @@ result(Reference, Result) -> %% Function called by a connection when a subscribed update arrives. notify(Package, Message) -> - gen_server:cast(?MODULE, {notice, Package, Message}). + gen_server:cast(?MODULE, {notify, self(), Package, Message}). @@ -441,11 +560,21 @@ start_link() -> -spec init(none) -> {ok, state()}. init(none) -> + Blank = blank_state(), {ok, MX, CX} = init_connections(), - State = #s{mx = MX, cx = CX}, + State = Blank#s{mx = MX, cx = CX}, {ok, State}. +-spec blank_state() -> state(). +%% @private +%% Used to generate a correct, but exactly empty state. +%% Useful mostly for testing and validation, though also actually used in the program. + +blank_state() -> + #s{}. + + -spec init_connections() -> {ok, MX, CX} when MX :: monitor_index(), CX :: conn_index(). @@ -507,6 +636,15 @@ stop() -> %% @private %% gen_server callback for OTP calls +handle_call({request, list}, _, State = #s{cx = CX}) -> + Realms = cx_realms(CX), + {reply, {ok, Realms}, State}; +handle_call({request, Requestor, Action}, From, State = #s{id = ID}) -> + NewID = ID + 1, + _ = gen_server:reply(From, {ok, NewID}), + NextState = do_request(Requestor, Action, State#s{id = NewID}), + NewState = eval_queue(NextState), + {noreply, NewState}; handle_call(Unexpected, From, State) -> ok = log(warning, "Unexpected call ~tp: ~tp", [From, Unexpected]), {noreply, State}. @@ -526,10 +664,6 @@ handle_cast({unsubscribe, Pid, Package}, State) -> NextState = do_unsubscribe(Pid, Package, State), NewState = eval_queue(NextState), {noreply, NewState}; -handle_cast({request, Ref, Requestor, Action}, State) -> - NextState = do_request(Ref, Requestor, Action, State), - NewState = eval_queue(NextState), - {noreply, NewState}; handle_cast({report, Conn, Message}, State) -> NextState = do_report(Conn, Message, State), NewState = eval_queue(NextState), @@ -538,8 +672,8 @@ handle_cast({result, Ref, Result}, State) -> NextState = do_result(Ref, Result, State), NewState = eval_queue(NextState), {noreply, NewState}; -handle_cast({notice, Package, Update}, State) -> - ok = do_notice(Package, Update, State), +handle_cast({notify, Conn, Package, Update}, State) -> + ok = do_notify(Conn, Package, Update, State), {noreply, State}; handle_cast(stop, State) -> {stop, normal, State}; @@ -551,6 +685,9 @@ handle_cast(Unexpected, State) -> %% @private %% gen_sever callback for general Erlang message handling +handle_info({'DOWN', Ref, process, Pid, Reason}, State) -> + NewState = clear_monitor(Pid, Ref, Reason, State), + {noreply, NewState}; handle_info(Unexpected, State) -> ok = log(warning, "Unexpected info: ~tp", [Unexpected]), {noreply, State}. @@ -605,7 +742,7 @@ do_pass_meta(Meta, Home, ArgV, State) -> %% Enqueue a subscription request. do_subscribe(Pid, Package, State = #s{actions = Actions}) -> - NewActions = [{Pid, {subscribe, Package}} | Actions], + NewActions = [{subscribe, Pid, Package} | Actions], State#s{actions = NewActions}. @@ -618,21 +755,20 @@ do_subscribe(Pid, Package, State = #s{actions = Actions}) -> %% Clear or dequeue a subscription request. do_unsubscribe(Pid, Package, State = #s{actions = Actions}) -> - NewActions = [{Pid, {unsubscribe, Package}} | Actions], + NewActions = [{unsubscribe, Pid, Package} | Actions], State#s{actions = NewActions}. --spec do_request(Ref, Requestor, Action, State) -> NextState - when Ref :: reference(), - Requestor :: pid(), +-spec do_request(Requestor, Action, State) -> NextState + when Requestor :: pid(), Action :: action(), State :: state(), NextState :: state(). %% @private %% Enqueue requests and update relevant index. -do_request(Ref, Requestor, Action, State = #s{actions = Actions}) -> - NewActions = [{Ref, Requestor, Action} | Actions], +do_request(Requestor, Action, State = #s{id = ID, actions = Actions}) -> + NewActions = [{request, Requestor, ID, Action} | Actions], State#s{actions = NewActions}. @@ -652,47 +788,53 @@ do_report(Conn, {connected, Realms}, State = #s{mx = MX, cx = CX}) -> {assigned, NextCX} -> {NextMX, NextCX}; {unassigned, NextCX} -> - {ok, ScrubbedMX, []} = mx_del_monitor(Conn, conn, NextMX), + {ok, ScrubbedMX} = mx_del_monitor(Conn, conn, NextMX), ok = zx_conn:stop(Conn), {ScrubbedMX, NextCX} end, State#s{mx = NewMX, cx = NewCX}; do_report(Conn, {redirect, Hosts}, State = #s{mx = MX, cx = CX}) -> - {ok, NextMX} = mx_del_monitor(Conn, attempt, MX), + NextMX = mx_del_monitor(Conn, attempt, MX), {Unassigned, NextCX} = cx_redirect(Conn, Hosts, CX), - {NewMX, NewCX} = init_connection(Unassigned, NextMX, NextCX), + {NewMX, NewCX} = ensure_connection(Unassigned, NextMX, NextCX), State#s{mx = NewMX, cx = NewCX}; -do_report(Conn, aborted, State = #s{mx = MX, cx = CX}) -> - {ok, NewMX} = mx_del_monitor(Conn, attempt, MX), +do_report(Conn, failed, State = #s{mx = MX, cx = CX}) -> + NewMX = mx_del_monitor(Conn, attempt, MX), + failed(Conn, State#s{mx = NewMX}); +do_report(Conn, disconnected, State = #s{mx = MX}) -> + NewMX = mx_del_monitor(Conn, conn, MX), + disconnected(Conn, State#s{mx = NewMX}). + + +failed(Conn, State#s{mx = MX, cx = CX}) -> {Realms, NextCX} = cx_failed(Conn, CX), - {NewMX, NewCX} = init_connection(Realms, NextCX), - State#s{mx = NewMX, cx = NewCX}; -do_report(Conn, disconnected, State) -> - ScrubbedMX = mx_del_monitor(Conn, conn, MX), + {NewMX, NewCX} = ensure_connection(Realms, MX, NextCX), + State#s{mx = NewMX, cx = NewCX}. + + +disconnected(Conn, + State = #s{actions = Actions, requests = Requests, mx = MX, cx = CX}) -> {Pending, LostSubs, ScrubbedCX} = cx_disconnected(Conn, CX), Unassigned = cx_unassigned(ScrubbedCX), - UnSub = fun(S) -> lists:member(element(2, S), LostSubs) end, - {UnSubbed, NewSubs} = lists:partition(UnSub, Subs), - ReSubs = [{S, {subscribe, P}} || {S, P} <- UnSubbed], + ReSubs = [{S, {subscribe, P}} || {S, P} <- LostSubs], {Dequeued, NewRequests} = maps:fold(dequeue(Pending), {#{}, #{}}, Requests), ReReqs = maps:to_list(Dequeued), NewActions = ReReqs ++ ReSubs ++ Actions, - {NewMX, NewCX} = init_connection(Unassigned, ScrubbedMX, ScrubbedCX), + {NewMX, NewCX} = ensure_connection(Unassigned, ScrubbedMX, ScrubbedCX), State#s{actions = NewActions, requests = NewRequests, - subs = NewSubs, mx = NewMX, cx = NewCX}. --spec dequeue(Pending) -> fun(K, V, {D, R}) -> {NewD, NewR} - when Pending :: [reference()], - K :: reference(), +-spec dequeue(Pending) -> fun((K, V, {D, R}) -> {NewD, NewR}) + when Pending :: [id()], + K :: id(), V :: request(), - D :: #{reference(), request()}, - R :: #{reference(), request()}, - NewD :: #{reference(), request()}, - NewR :: #{reference(), request()}. + D :: #{id() := request()}, + R :: #{id() := request()}, + NewD :: #{id() := request()}, + NewR :: #{id() := request()}. %% @private %% Return a function that partitions the current Request map into two maps, one that %% matches the closed `Pending' list of references and ones that don't. @@ -706,7 +848,7 @@ dequeue(Pending) -> end. --spec init_connection(Realms, MX, CX) -> {NewMX, NewCX} +-spec ensure_connection(Realms, MX, CX) -> {NewMX, NewCX} when Realms :: [zx:realm()], MX :: monitor_index(), CX :: conn_index(), @@ -717,7 +859,7 @@ dequeue(Pending) -> %% connected but unassigned nodes are alterantive providers of the needed realm. %% Returns updated monitor and connection indices. -init_connection([Realm | Realms], MX, CX = #cx{realms = RMetas}) -> +ensure_connection([Realm | Realms], MX, CX = #cx{realms = RMetas}) -> {NewMX, NewCX} = case maps:get(Realm, RMetas) of #rmeta{available = []} -> @@ -729,49 +871,74 @@ init_connection([Realm | Realms], MX, CX = #cx{realms = RMetas}) -> NextCX = CX#cx{realms = NewRMetas}, {MX, NextCX} end, - init_connection(Realms, NewMX, NewCX); -init_connection([], MX, CX) -> + ensure_connection(Realms, NewMX, NewCX); +ensure_connection([], MX, CX) -> {MX, CX}. --spec do_result(Reference, Result, State) -> NewState - when Reference :: reference(), - Result :: result(), - State :: state(), - NewState :: state(). +-spec do_result(ID, Result, State) -> NewState + when ID :: id(), + Result :: result(), + State :: state(), + NewState :: state(). %% @private %% Receive the result of a sent request and route it back to the original requestor. -do_result(Reference, Result, State = #s{requests = Requests}) -> - NewRequests = - case maps:take(Reference, Requests) of - {{Requestor, {Type, Object}}, NextRequests} -> - Requestor ! {result, {Type, Object, Result}}, - NextRequests; +do_result(ID, Result, State = #s{requests = Requests, dropped = Dropped, mx = MX}) -> + {NewDropped, NewRequests, NewMX} = + case maps:take(ID, Requests) of + {Request, NextRequests} -> + Requestor = element(1, Request), + Requestor ! {z_result, ID, Result}, + NextMX = mx_del_monitor(Requestor, {requestor, ID}, MX), + {Dropped, NextRequests, NextMX}; error -> - Message = "Received unqueued result ~tp: ~tp", - ok = log(warning, Message, [Reference, Result]), - Requests + NextDropped = handle_orphan_result(ID, Result, Dropped), + {NextDropped, Requests, MX} end, - State#s{requests = NewRequests}. + State#s{requests = NewRequests, dropped = NewDropped, mx = NewMX}. --spec do_notice(Package, Update, State) -> ok - when Package :: zx:package(), - Update :: term(), +-spec handle_orphan_result(ID, Result, Dropped) -> NewDropped + when ID :: id(), + Result :: result(), + Dropped :: requests(), + NewDropped :: requests(). +%% @private +%% Log request results if they have been orphaned by their original requestor. +%% Log a warning if the result is totally unknown. + +handle_orphan_result(ID, Result, Dropped) -> + case maps:take(ID, Dropped) of + {Request, NewDropped} -> + Message = "Received orphan result for ~tp, ~tp: ~tp", + ok = log(info, Message, [ID, Request, Result]), + NewDropped; + error -> + Message = "Received unknown request result ~tp: ~tp", + ok = log(warning, Message, [ID, Result]), + Dropped + end. + + +-spec do_notify(Conn, Channel, Message, State) -> ok + when Conn :: pid(), + Channel :: term(), + Message :: term(), State :: state(). %% @private -%% Forward an update message to the subscriber. +%% Broadcast a subscription message to all subscribers of a channel. +%% At the moment the only possible sub channels are packages, but this will almost +%% certainly change in the future to include general realm update messages (new keys, +%% packages, user announcements, etc.) and whatever else becomes relevant as the +%% system evolves. The types here are deliberately a bit abstract to prevent future +%% type tracing with Dialyzer, since we know the functions calling this routine and +%% are already tightly typed. -do_notice(Package, Update, #s{subs = Subs}) -> - case maps:find(Package, Subs) of - {ok, Subscribers} -> - Notify = fun(P) -> P ! {Package, Update} end, - lists:foreach(Notify, Subscribers); - error -> - Message = "Received package update for 0 subscribers: {~tp, ~tp}", - log(warning, Message, [Package, Update]) - end. +do_notify(Conn, Channel, Message, #s{cx = CX}) -> + Subscribers = cx_get_subscribers(Conn, Channel, CX), + Notify = fun(P) -> P ! {z_sub, Channel, Message} end, + lists:foreach(Notify, Subscribers). -spec eval_queue(State) -> NewState @@ -789,92 +956,169 @@ eval_queue(State = #s{actions = Actions}) -> eval_queue([], State) -> State; -eval_queue([Action = {Pid, {subscribe, Package}} | Rest], - State = #s{actions = Actions, subs = Subs, mx = MX, cx = CX}) -> - Realm = element(1, Package), - {NewActions, NewSubs, NewMX} = - case cx_resolve(Realm, CX) of - {ok, Conn} -> - ok = zx_conn:subscribe(Conn, Package), - NextSubs = [{Pid, Package} | Subs], - NextMX = mx_add_monitor(Pid, subscriber, MX), - {Actions, NextSubs, NextMX}; - unassigned -> - NextActions = [Action | Actions], - NextMX = mx_add_monitor(Pid, subscriber, MX), - {NextActions, Subs, NextMX}; - unconfigured -> - Pid ! {subscription, Realm, {error, bad_realm}}, - {Actions, Subs, MX} - end, - eval_queue(Rest, State#s{actions = NewActions, subs = NewSubs, mx = NewMX}); -eval_queue([Action = {Pid, {unsubscribe, Package}} | Rest], - State = #s{actions = Actions, subs = Subs, mx = MX, cx = CX}) -> - NewActions = lists:delete(Action, Actions), - NewSubs = lists:delete({Pid, Package}, Subs), - {ok, NewMX} = mx_del_monitor(Pid, subscriber, MX), - Realm = element(1, Package), - ok = - case cx_resolve(Realm, CX) of - {ok, Conn} -> cx_conn:unsubscribe(Conn, Package); - unassigned -> ok - end, - eval_queue(Rest, State#s{actions = NewActions, subs = NewSubs, mx = NewMX}); -eval_queue([{Ref, Pid, {list, realms}} | Rest], State = #s{cx = CX}) -> - Realms = cx_realms(CX), - ok = send_result(Pid, Ref, {list, realms, {ok, Realms}}), - eval_queue(Rest, State); -eval_queue([Action = {Ref, Pid, {list, Realm}} | Rest], - State = #s{actions = Actions, requests = Requests, mx = MX, cx = CX}) - when is_list(Realm) -> - {NewActions, NewRequests, NewMX} = - case cx_resolve(Realm, CX) of - {ok, Conn} -> - ok = cx_conn:list_packages(Conn, Ref), - Request = {Pid, list, Realm}, - NextRequests = maps:put(Ref, Request, Requests), - NextMX = mx_add_monitor(Pid, requestor, MX), - {Actions, NextRequests, NextMX}; - unassigned -> - NextMX = mx_add_monitor(Pid, requestor, MX), - NextActions = [Action | Actions], - {NextActions, Requests, NextMX}; - unconfigured -> - Pid ! {Ref, {list, Realm, {error, bad_realm}}}, - {Actions, Requests, MX} - end, - NewState = State#s{actions = NewActions, requests = NewRequests, mx = NewMX}, - eval_queue(Rest, NewState); -%% FIXME: Universalize the cx_resolve result, leave only message form explicit. -eval_queue([Action = {Ref, Pid, Message} | Rest], +eval_queue([Action = {request, Pid, ID, Message} | Rest], State = #s{actions = Actions, requests = Requests, mx = MX, cx = CX}) -> - Realm = element(1, element(2, Message)), - {NewActions, NewRequests, NewMX} = - case cx_resolve(Realm, CX) of - {ok, Conn} -> - ok = cx_conn:list_packages(Conn, Ref), - NextRequests = maps:put(Ref, {Pid, Message}, Requests), + {NewActions, NewRequests, NewMX, NewCX} = + case dispatch_request(Message, ID, CX) of + {dispatched, NextCX} -> + NextRequests = maps:put(ID, {Pid, Message}, Requests), NextMX = mx_add_monitor(Pid, requestor, MX), - {Actions, NextRequests, NextMX}; - unassigned -> + {Actions, NextRequests, NextMX, NextCX}; + {result, Response} -> + Pid ! Response, + {Actions, Requests, CX}; + wait -> NextActions = [Action | Actions], - {NextActions, Requests, MX}; - unconfigured -> - Pid ! {Ref, {list, Realm, {error, bad_realm}}}, - {Actions, Requests, MX} + NextMX = mx_add_monitor(Pid, requestor, MX), + {NextActions, Requests, NextMX, CX} end, - NewState = State#s{actions = NewActions, requests = NewRequests, mx = NewMX}, - eval_queue(Rest, NewState). + NewState = + State#s{actions = NewActions, + requests = NewRequests, + mx = NewMX, + cx = NewCX}, + eval_queue(Rest, NewState); +eval_queue([Action = {subscribe, Pid, Package} | Rest], + State = #s{actions = Actions, mx = MX, cx = CX}) -> + {NewActions, NewMX, NewCX} = + case cx_add_sub(Pid, Package, CX) of + {need_sub, Conn, NextCX} -> + ok = zx_conn:subscribe(Conn, Package), + NextMX = mx_add_monitor(Pid, subscriber, MX), + {Actions, NextMX, NextCX}; + {have_sub, NextCX} + NextMX = mx_add_monitor(Pid, subscriber, MX), + {Actions, NextMX, NextCX}; + unassigned -> + NextMX = mx_add_monitor(Pid, subscriber, MX), + {[Action | Actions], NextMX, CX}; + unconfigured -> + Pid ! {z_sub, Package, {error, bad_realm}}, + {Actions, MX, CX} + end, + eval_queue(Rest, State#s{actions = NewActions, mx = NewMX, cx = NewCX}); +eval_queue([{unsubscribe, Pid, Package} | Rest], + State = #s{mx = MX, cx = CX}) -> + {ok, NewMX} = mx_del_monitor(Pid, {subscription, Package}, MX), + NewCX = + case cx_del_sub(Pid, Package, CX) of + {drop_sub, NextCX} -> + ok = zx_conn:unsubscribe(Conn, Package), + NextCX; + {keep_sub, NextCX} -> + NextCX; + unassigned -> + CX; + unconfigured -> + Message = "Received 'unsubscribe' request for unconfigured realm: ~tp", + ok = log(warning, Message, [Package]), + CX + end, + eval_queue(Rest, State#s{mx = NewMX, cx = NewCX}). --spec send_result(pid(), reference(), term()) -> ok. +-spec dispatch_request(Action, ID, CX) -> Result + when Action :: action(), + ID :: id(), + CX :: conn_index(), + Result :: {dispatched, NewCX} + | {result, Response} + | wait, + NewCX :: conn_index(), + Response :: result(). + +dispatch_request(list, ID, CX) -> + Realms = cx_realms(CX), + {result, ID, Realms}; +dispatch_request(Action, ID, CX) -> + Realm = element(2, Action), + case cx_pre_send(Realm, ID, CX) of + {ok, Conn, NewCX} -> + ok = zx_conn:make_request(Conn, ID, Action), + {dispatched, NewCX}; + unassigned -> + wait; + unconfigured -> + Error = {error, bad_realm}, + {result, ID, Error} + end. + + +-spec clear_monitor(Pid, Ref, Reason, State) -> NewState + when Pid :: pid(), + Ref :: reference(), + Reason :: term(), + State :: state(), + NewState :: state(). %% @private -%% Send a message by reference to a process. -%% Probably don't need this function. +%% Deal with a crashed requestor, subscriber or connector. -send_result(Pid, Ref, Message) -> - Pid ! {Ref, Message}, - ok. +clear_monitor(Pid, + Ref, + Reason, + State = #s{actions = Actions, + requests = Requests, + dropped = Dropped, + mx = MX, + cx = CX}) -> + case mx_crashed_monitor(Pid, MX) of + {attempt, NextMX} -> + failed( + {conn, NextMX} -> + disconnected(Pid, State#s{mx = NextMX}); + {{Reqs, Subs}, NextMX} -> + case mx_lookup_category(Pid, MX) of + attempt -> + do_report(Pid, failed, State); + conn -> + do_report(Pid, disconnected, State); + {Reqs, Subs} -> + NewActions = drop_actions(Pid, Actions), + {NewDropped, NewRequests} = drop_requests(Pid, Dropped, Requests), + NewCX = cx_clear_client(Pid, Reqs, Subs, CX), + NewMX = mx_del_monitor(Pid, crashed, MX), + State#s{actions = NewActions, + requests = NewRequests, + dropped = NewDropped, + mx = NewMX, + cx = NewCX}; + error -> + Unexpected = {'DOWN', Ref, process, Pid, Reason}, + ok = log(warning, "Unexpected info: ~tp", [Unexpected]), + State + end. + + +-spec drop_actions(Requestor, Actions) -> NewActions + when Requestor :: pid(), + Actions :: [request()], + NewActions :: [request()]. + +drop_actions(Pid, Actions) -> + Clear = + fun + ({request, P, _}) -> P /= Pid; + ({subscribe, P, _}) -> P /= Pid; + ({unsubscribe, _, _}) -> false + end, + lists:filter(Clear, Actions). + + +-spec drop_requests(ReqIDs, Dropped, Requests) -> {NewDropped, NewRequests} + when ReqIDs :: [id()], + Dropped :: requests(), + Requests :: requests(), + NewDropped :: requests(), + NewRequests :: requests(). + +drop_requests(ReqIDs, Dropped, Requests) -> + Partition = + fun(K, {Drop, Keep}) -> + {V, NewKeep} = maps:take(K, Keep), + NewDrop = maps:put(K, V, Drop), + {NewDrop, NewKeep} + end, + lists:fold(Partition, {Dropped, Requests}, ReqIDs). %-spec do_query_latest(Object, State) -> {Result, NewState} @@ -1042,10 +1286,10 @@ mx_upgrade_conn(Pid, MX) -> -spec mx_del_monitor(Conn, Category, MX) -> NewMX when Conn :: pid(), - Category :: subscriber - | requestor - | attempt - | conn, + Category :: attempt + | conn + | {requestor, id()}, + | {subscriber, Sub :: tuple()}, MX :: monitor_index(), NewMX :: monitor_index(). %% @private @@ -1053,26 +1297,52 @@ mx_upgrade_conn(Pid, MX) -> %% exists. Returns a tuple including the remaining request references in the case of %% a conn type. -mx_del_monitor(Pid, subscriber, MX) -> - case maps:take(Pid, MX) of - {{Ref, {1, 0}}, NewMX} -> - true = demonitor(Ref, [flush]), - NewMX; - {{Ref, {Subs, Reqs}}, NextMX} when Subs > 0 -> - maps:put(Pid, {Ref, {Subs - 1, Reqs}}, NextMX) - end; -mx_del_monitor(Pid, requestor, MX) -> - case maps:take(Pid, MX) of - {{Ref, {0, 1}}, NewMX} -> - true = demonitor(Ref, [flush]), - NewMX; - {{Ref, {Subs, Reqs}}, NextMX} when Reqs > 0 -> - maps:put(Pid, {Ref, {Subs, Reqs - 1}}, NextMX) - end; -mx_del_monitor(Pid, Category, MX) -> - {{Ref, Category}, NewMX} = maps;take(Pid, MX), +mx_del_monitor(Pid, attempt, MX) -> + {{Ref, attempt}, NewMX} = maps:take(Pid, MX), true = demonitor(Ref, [flush]), - NewMX. + NewMX; +mx_del_monitor(Pid, conn, MX) -> + {{Ref, conn}, NewMX} = maps:take(Pid, MX), + true = demonitor(Ref, [flush]), + NewMX; +mx_del_monitor(Pid, {requestor, ID}, MX) -> + case maps:take(Pid, MX) of + {{Ref, {[ID], []}}, NextMX} -> + true = demonitor(Ref, [flush]), + NextMX; + {{Ref, {Reqs, Subs}}, NextMX} when Reqs > 0 -> + NewReqs = lists:subtract(ID, Reqs), + maps:put(Pid, {NewReqs, Subs}, NextMX) + end, +mx_del_monitor(Pid, {subscriber, Sub}, MX) -> + case maps:take(Pid, MX) of + {{Ref, {[], [Package]}}, NextMX} -> + true = demonitor(Ref, [flush]), + NextMX; + {{Ref, {Reqs, Subs}}, NextMX} when Subs > 0 -> + NewSubs = lists:delete(Sub, Subs), + maps:put(Pid, {Ref, {Reqs, NewSubs}}, NextMX) + end. + + +-spec mx_crashed_monitor(Pid, MX) -> Result + when Pid :: pid(), + MX :: monitor_index(), + Result :: {Type, NewMX} + | error, + Type :: attempt + | conn + | {Reqs :: [id()], Subs :: [tuple()]}, + NewMX :: monitor_index(). + +mx_crashed_monitor(Pid, MX) -> + case maps:take(Pid, MX) of + {{Ref, Type}, NewMX} -> + true = demonitor(Mon, [flush]), + {Type, NewMX}; + error -> + error + end. -spec mx_lookup_category(Pid, MX) -> Result @@ -1080,20 +1350,15 @@ mx_del_monitor(Pid, Category, MX) -> MX :: monitor_index(), Result :: attempt | conn - | requestor - | subscriber - | sub_req. + | {Reqs :: [reference()], Subs :: [zx:package()]} + | error. %% @private %% Lookup a monitor's categories. mx_lookup_category(Pid, MX) -> - Monitor = maps:get(Pid, MX), - case element(2, Monitor) of - attempt -> attempt; - conn -> conn; - {0, _} -> requestor; - {_, 0} -> subscriber; - {_, _} -> sub_req + case maps:find(Pid, MX) of + {ok, Mon} -> element(2, Mon); + error -> error end. @@ -1294,7 +1559,7 @@ cx_next_host(Realm, CX = #cx{realms = Realms}) -> NewRealms = maps:put(Realm, NewMeta, Realms), NewCX = CX#cx{realms = NewRealms}, {Outcome, Host, NewCX}; - {ok, Meta = #rmeta{assigned = Conn}} when is_pid(Conn) -> + {ok, #rmeta{assigned = Conn}} when is_pid(Conn) -> ok = log(warning, "Call to cx_next_host/2 when connection assigned."), {error, connected, CX}; error -> @@ -1336,27 +1601,18 @@ cx_next_host(Meta = #rmeta{prime = Prime, private = Private, mirrors = Mirrors}) %% of a given realm, taking private mirrors first, then public mirrors, and ending %% with the prime node for the realm if no others exist. -cx_next_hosts(N, Realm, CX = #cx{realms = Realms}) -> - case maps:find(Realm, Realms) of - {ok, Meta = #rmeta{assigned = none}} -> cx_next_hosts2(N, Realm, Meta, CX); - {ok, #rmeta{assigned = Conn}} -> {error, {connected, Conn}}; - error -> {error, bad_realm} - end. +cx_next_hosts(N, Realm, CX) -> + cx_next_hosts(N, Realm, [], CX). -cx_next_hosts2(N, Realm, Meta, CX = #cx{realms = Realms}) -> - {ok, Hosts, NewMeta} = cx_next_hosts3(N, [], Meta), - NewRealms = maps:put(Realm, NewMeta, Realms), - {ok, Hosts, CX#cx{realms = NewRealms}}. - - -cx_next_hosts3(N, Hosts, Meta) when N < 1 -> - {ok, Hosts, Meta}; -cx_next_hosts3(N, Hosts, Meta) -> - case cx_next_host(Meta) of - {ok, Host, NewMeta} -> cx_next_hosts3(N - 1, [Host | Hosts], NewMeta); - {prime, Prime, NewMeta} -> {ok, [Prime | Hosts], NewMeta} - end. +cx_next_hosts(N, Realm, Hosts, CX) when N > 0 -> + case cx_next_host(Realm, CX) of + {ok, Host, NewCX} -> cx_next_hosts(N - 1, Realm, [Host | Hosts], NewCX); + {prime, Host, NewCX} -> {ok, [Host | Hosts], NewCX}; + Error -> Error + end; +cx_next_hosts(0, _, Hosts, CX) -> + {ok, Hosts, CX}. -spec cx_maybe_add_attempt(Host, Realm, CX) -> Result @@ -1372,7 +1628,7 @@ cx_maybe_add_attempt(Host, Realm, CX = #cx{attempts = Attempts}) -> false -> not_connected; {value, {Pid, Host, Realms}, NextAttempts} -> - NewAttempts = [{Pid, Host, [Realm | Realms]} | Attempts], + NewAttempts = [{Pid, Host, [Realm | Realms]} | NextAttempts], NewCX = CX#cx{attempts = NewAttempts}, {ok, NewCX} end. @@ -1459,7 +1715,7 @@ cx_connected(A, %% - Whether the host node is the prime node (and if not, ensure it is a member of %% of the mirror queue). -cx_connected(A, +cx_connected(_, Realm, #conn{pid = Pid, host = Prime}, Meta = #rmeta{prime = Prime, assigned = none}, @@ -1468,11 +1724,11 @@ cx_connected(A, NewRealms = maps:put(Realm, NewMeta, Realms), NewCX = CX#cx{realms = NewRealms}, {assigned, NewCX}; -cx_connected(A, +cx_connected(_, Realm, #conn{pid = Pid, host = Host}, Meta = #rmeta{mirrors = Mirrors, assigned = none}, - CX = #cx{realms = Realms, attempts = Attempts}) -> + CX = #cx{realms = Realms}) -> NewMirrors = cx_enqueue_unique(Host, Mirrors), NewMeta = Meta#rmeta{mirrors = NewMirrors, assigned = Pid}, NewRealms = maps:put(Realm, NewMeta, Realms), @@ -1518,7 +1774,7 @@ cx_enqueue_unique(Element, Queue) -> %% Remove a failed attempt and all its associations. cx_failed(Conn, CX = #cx{attempts = Attempts}) -> - {value, Attempt, NewAttempts = lists:keytake(Conn, 1, Attempts), + {value, Attempt, NewAttempts} = lists:keytake(Conn, 1, Attempts), Realms = element(3, Attempt), {Realms, CX#cx{attempts = NewAttempts}}. @@ -1640,3 +1896,148 @@ cx_resolve(Realm, #cx{realms = Realms}) -> {ok, #rmeta{assigned = Conn}} -> {ok, Conn}; error -> unconfigured end. + + +-spec cx_pre_send(Realm, ID, CX) -> Result + when Realm :: zx:realm(), + ID :: id(), + CX :: conn_index(), + Result :: {ok, pid(), NewCX :: conn_index()} + | unassigned + | unconfigured. +%% @private +%% Prepare a request to be sent by queueing it in the connection active request +%% reference list and returning the Pid of the connection handling the required realm +%% if it is available, otherwise return an atom indicating the status of the realm.. + +cx_pre_send(Realm, ID, CX = #cx{conns = Conns}) -> + case cx_resolve(Realm, CX) of + {ok, Pid} -> + {value, Conn, NextConns} = lists:keytake(Pid, #conn.pid, Conns), + #conn{requests = Requests} = Conn, + NewRequests = [ID | Requests], + NewConn = Conn#conn{requests = NewRequests}, + NewCX = CX#cx{conns = [NewConn | NextConns]}, + {ok, Pid, NewCX}; + NoGo -> + NoGo + end. + + +-spec cx_add_sub(Subscriber, Channel, CX) -> Result + when Subscriber :: pid(), + Channel :: tuple(), + CX :: conn_index(), + Result :: {need_sub, Conn, NewCX} + | {have_sub, NewCX} + | unassigned + | unconfigured, + Conn :: pid(), + NewCX :: conn_index(). +%% @private +%% Adds a subscription to the current list of subs, and returns a value indicating +%% whether the connection needs to be told to subscribe or not based on whether it +%% is already subscribed to that particular channel. + +cx_add_sub(Subscriber, Channel, CX = #cx{conns = Conns}) -> + Realm = element(1, Channel), + case cx_resolve(Realm, CX) of + {ok, Pid} -> + {value, Conn, NewConns} = lists:keytake(Pid, #conn.pid, Conns), + cx_maybe_new_sub(Conn, {Subscriber, Channel}, CX#cx{conns = NewConns}); + Other -> + Other + end. + + +-spec cx_maybe_new_sub(Conn, Sub, CX) -> Result + when Conn :: connection(), + Sub :: {pid(), tuple()}, + CX :: conn_index(), + Result :: {need_sub, ConnPid, NewCX} + | {have_sub, NewCX}, + ConnPid :: pid(), + NewCX :: conn_index(). + +cx_maybe_new_sub(Conn = #conn{pid = ConnPid, subs = Subs}, + Sub = {Subscriber, Channel}, + CX = #cx{conns = Conns}) -> + NewSubs = [{Subscriber, Channel} | Subs], + NewConn = Conn#conn{subs = NewSubs}, + NewConns = [NewConn | NextConns], + NewCX = CX#cx{conns = NewConns}, + case lists:keymember(Channel, 2, Subs) of + false -> {need_sub, ConnPid, NewCX}; + true -> {have_sub, NewCX} + end. + + +-spec cx_del_sub(Subscriber, Channel, CX) -> Result + when Subscriber :: pid(), + Channel :: tuple(), + CX :: conn_index(), + Result :: {drop_sub, NewCX} + | {keep_sub, NewCX} + | unassigned + | unconfigured, + NewCX :: conn_index(). +%% @private +%% Remove a subscription from the list of subs, and return a value indicating whether +%% the connection needs to be told to unsubscribe entirely. + +cx_del_sub(Subscriber, Channel, CX = #cx{conns = Conns}) -> + Realm = element(1, Channel), + case cx_resolve(Realm, CX) of + {ok, Pid} -> + {value, Conn, NewConns} = lists:keytake(Pid, #conn.pid, Conns), + cx_maybe_last_sub(Conn, {Subscriber, Channel}, CX#cx{conns = NewConns}; + Other -> + Other + end. + + +cx_maybe_last_sub(Conn = #conn{pid = ConnPid, subs = Subs}, + Sub = {Subscriber, Channel}, + CX = #cx{conns = Conns}) -> + NewSubs = lists:delete(Sub, Subs), + NewConn = Conn#conn{subs = NewSubs}, + NewConns = [NewConn | NextConns], + NewCX = CX#cx{conns = NewConns}, + MaybeDrop = + case lists:keymember(Channel, 2, NewSubs) of + false -> drop_sub; + true -> keep_sub + end, + {MaybeDrop, NewCX}. + + +-spec cx_get_subscribers(Conn, Channel, CX) -> Subscribers + when Conn :: pid(), + Channel :: term(), + CX :: conn_index(), + Subscribers :: [pid()]. + +cx_get_subscribers(Conn, Channel, #cx{conns = Conns}) -> + #conn{subs = Subs} = lists:keyfind(Conn, #conn.pid, Conns), + lists:fold(registered_to(Channel), [], Subs). + + +registered_to(Channel) -> + fun({P, C}, A) -> + case C == Channel of + true -> [P | A]; + false -> A + end + end. + + +cx_clear_client(Pid, DeadReqs, DeadSubs, CX = #cx{conns = Conns}) -> + DropSubs = [{S, Pid} || S <- DeadSubs], + Clear = + fun(C = #conn{requests = Requests, subs = Subs}) -> + NewSubs = lists:subtract(Subs, DropSubs), + NewRequests = lists:subtract(Requests, DeadReqs), + C#conn{requests = NewRequests, subs = NewSubs} + end, + NewConns = lists:map(Clear, Conns), + CX#cx{conns = NewConns}. diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_lib.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_lib.erl index 41e621e..935821c 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx_lib.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_lib.erl @@ -14,13 +14,12 @@ -copyright("Craig Everett "). -license("GPL-3.0"). - -export([zomp_home/0, find_zomp_home/0, hosts_cache_file/1, get_prime/1, realm_meta/1, read_project_meta/0, read_project_meta/1, read_package_meta/1, write_project_meta/1, write_project_meta/2, write_terms/2, - valid_lower0_9/1, valid_label/1, + valid_lower0_9/1, valid_label/1, valid_version/1, string_to_version/1, version_to_string/1, package_id/1, package_string/1, package_dir/1, package_dir/2, @@ -139,7 +138,7 @@ read_project_meta(Dir) -> | {error, file:posix()}. read_package_meta({Realm, Name, Version}) -> - VersionString = Version, + {ok, VersionString} = version_to_string(Version), Path = filename:join([zomp_home(), "lib", Realm, Name, VersionString]), read_project_meta(Path). @@ -250,6 +249,26 @@ valid_label(_, _) -> false. +-spec valid_version(zx:version()) -> boolean(). + +valid_version({z, z, z}) -> + true; +valid_version({X, z, z}) + when is_integer(X), X >= 0 -> + true; +valid_version({X, Y, z}) + when is_integer(X), X >= 0, + is_integer(Y), Y >= 0 -> + true; +valid_version({X, Y, Z}) + when is_integer(X), X >= 0, + is_integer(Y), Y >= 0, + is_integer(Z), Z >= 0 -> + true; +valid_version(_) -> + false. + + -spec string_to_version(VersionString) -> Result when VersionString :: string(), Result :: {ok, zx:version()} From 08972f01608fc28adfab5a3334eb0630a1945dc2 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Thu, 22 Mar 2018 19:04:34 +0900 Subject: [PATCH 44/55] blah --- zomp/lib/otpr-zx/0.1.0/src/.zx_daemon.erl.swp | Bin 0 -> 147456 bytes zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl | 106 +++++ zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl | 402 +++++++++--------- 3 files changed, 296 insertions(+), 212 deletions(-) create mode 100644 zomp/lib/otpr-zx/0.1.0/src/.zx_daemon.erl.swp diff --git a/zomp/lib/otpr-zx/0.1.0/src/.zx_daemon.erl.swp b/zomp/lib/otpr-zx/0.1.0/src/.zx_daemon.er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K@ncp6+C1qGhd!(6XZ-$rXV*V;l(ToR*v@xcE zhjLS5k#E|>OJ(M<%)C6yWD`7jJMk|0P$d#pV%%1$!g47JtESaFOzQfRb*Kns$b5yxm@_;lmpXhx3IA)kg8-r^~U*V+s9+Go?b{Q#N%GlZqKx@+zCZH$&5(ew7$<`D~1&y{{)A0PnM#y#N3J literal 0 HcmV?d00001 diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl index 4cefbad..ec6644f 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl @@ -303,3 +303,109 @@ handle_timeout(Socket) -> terminate() -> exit(normal). + + + +%-spec do_query_latest(Object, State) -> {Result, NewState} +% when Object :: zx:package() | zx:package_id(), +% State :: state(), +% Result :: {ok, zx:version()} +% | {error, Reason}, +% Reason :: bad_realm +% | bad_package +% | bad_version, +% NewState :: state(). +%% @private +%% Queries a zomp realm for the latest version of a package or package +%% version (complete or incomplete version number). +% +%do_query_latest(Socket, {Realm, Name}) -> +% ok = zx_net:send(Socket, {latest, Realm, Name}), +% receive +% {tcp, Socket, Bin} -> binary_to_term(Bin) +% after 5000 -> {error, timeout} +% end; +%do_query_latest(Socket, {Realm, Name, Version}) -> +% ok = zx_net:send(Socket, {latest, Realm, Name, Version}), +% receive +% {tcp, Socket, Bin} -> binary_to_term(Bin) +% after 5000 -> {error, timeout} +% end. + + +%-spec do_fetch(PackageIDs, State) -> NewState +% when PackageIDs :: [zx:package_id()], +% State :: state(), +% NewState :: state(), +% Result :: ok +% | {error, Reason}, +% Reason :: bad_realm +% | bad_package +% | bad_version +% | network. +%% @private +%% +% +%do_fetch(PackageIDs, State) -> +% FIXME: Need to create a job queue divided by realm and dispatched to connectors, +% and cleared from the master pending queue kept here by the daemon as the +% workers succeed. Basic task queue management stuff... which never existed +% in ZX before... grrr... +% case scrub(PackageIDs) of +% [] -> +% ok; +% Needed -> +% Partitioned = partition_by_realm(Needed), +% EnsureDeps = +% fun({Realm, Packages}) -> +% ok = zx_conn:queue_package(Pid, Realm, Packages), +% log(info, "Disconnecting from realm: ~ts", [Realm]) +% end, +% lists:foreach(EnsureDeps, Partitioned) +% end. +% +% +%partition_by_realm(PackageIDs) -> +% PartitionMap = lists:foldl(fun partition_by_realm/2, #{}, PackageIDs), +% maps:to_list(PartitionMap). +% +% +%partition_by_realm({R, P, V}, M) -> +% maps:update_with(R, fun(Ps) -> [{P, V} | Ps] end, [{P, V}], M). +% +% +%ensure_deps(_, _, []) -> +% ok; +%ensure_deps(Socket, Realm, [{Name, Version} | Rest]) -> +% ok = ensure_dep(Socket, {Realm, Name, Version}), +% ensure_deps(Socket, Realm, Rest). +% +% +%-spec ensure_dep(gen_tcp:socket(), package_id()) -> ok | no_return(). +%% @private +%% Given an PackageID as an argument, check whether its package file exists in the +%% system cache, and if not download it. Should return `ok' whenever the file is +%% sourced, but exit with an error if it cannot locate or acquire the package. +% +%ensure_dep(Socket, PackageID) -> +% ZrpFile = filename:join("zrp", namify_zrp(PackageID)), +% ok = +% case filelib:is_regular(ZrpFile) of +% true -> ok; +% false -> fetch(Socket, PackageID) +% end, +% ok = install(PackageID), +% build(PackageID). +% +% +%-spec scrub(Deps) -> Scrubbed +% when Deps :: [package_id()], +% Scrubbed :: [package_id()]. +%% @private +%% Take a list of dependencies and return a list of dependencies that are not yet +%% installed on the system. +% +%scrub([]) -> +% []; +%scrub(Deps) -> +% lists:filter(fun(PackageID) -> not zx_lib:installed(PackageID) end, Deps). diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl index caf10fe..b078f0b 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl @@ -1,30 +1,31 @@ %%% @doc %%% ZX Daemon %%% -%%% Resident execution daemon and runtime interface to Zomp. +%%% Resident task daemon and runtime interface to Zomp. %%% %%% The daemon resides in the background once started and awaits query requests and -%%% subscriptions from from other processes. The daemon is only capable of handling +%%% subscriptions from other processes. The daemon is only capable of handling %%% unprivileged (user) actions. %%% %%% %%% Discrete state and local abstract data types %%% %%% The daemon must keep track of requestors, subscribers, and zx_conn processes by -%%% using monitors, and because the various types of clients are found in different -%%% locations the monitors are maintained in a data type called monitor_index(), +%%% using monitors. Because these various types of clients are found in different +%%% structures the monitors are maintained in a data type called monitor_index(), %%% shortened to "mx" throughout the module. This structure is treated as an opaque %%% data type and is handled by a set of functions defined toward the end of the module %%% as mx_*/N. %%% -%%% Node connections (cx_conn processes) must also be tracked for status and realm +%%% Node connections (zx_conn processes) must also be tracked for status and realm %%% availability. This is done using a type called conn_index(), shortened to "cx" %%% throughout the module. conn_index() is treated as an abstract, opaque datatype %%% throughout the module, and is handled via a set of cx_*/N functions (after the %%% mx_*/N section). %%% %%% Do NOT directly access data within these structures, use (or write) an accessor -%%% function that does what you want. +%%% function that does what you want. Accessor functions MUST be pure with the sole +%%% exception of the mx_* functions that create and destroy monitors. %%% %%% %%% Connection handling @@ -40,7 +41,7 @@ %%% determine what realms must be available and what cached Zomp nodes it is aware of. %%% It populates the CX (conn_index(), mentioned above) with realm config and host %%% cache data, and then immediately initiates three connection attempts to cached -%%% nodes for each realm configured (if possible; see init_connections/0). +%%% nodes for each realm configured if possible (see init_connections/0). %%% %%% Once connection attempts have been initiated the daemon waits in receive for %%% either a connection report (success or failure) or an action request from @@ -90,6 +91,44 @@ %%% a blocking way, establishing its own receive timeouts or implementing either an %%% asynchronous or synchronous interface library atop zx_daemon interface function, %%% but leaving zx_daemon and zx_conn alone to work asynchronously with one another. +%%% +%%% +%%% Race Avoidance +%%% +%%% Each runtime can only have one zx_daemon alive at a time, and each system can +%%% only have one zx_daemon directly performing actions at a time. This is to prevent +%%% problems where multiple zx instances are running at the same time using the same +%%% home directory and might clash with one another (overwriting each other's data, +%%% corrupting package or key files, etc.). OTP makes running a single registered +%%% process simple within a single runtime, but there is no standard cross-platform +%%% method for ensuring a given process is the only one of its type in a given scope +%%% within a host system. +%%% +%%% When zx starts the daemon will attempt an exclusive write to a lock file called +%%% $ZOMP_HOME/zomp.lock using file:open(LockFile, [exclusive]), writing a system +%%% timestamp. If the write succeeds then the daemon knows it is the master for the +%%% system and will begin initiating connections as described above as well as open a +%%% local socket to listen for other zx instances which will need to proxy their own +%%% actions through the master. Once the socket is open, the lock file is updated with +%%% the local port number. If the write fails then the file is read and if a port +%%% number is indicated then the daemon connects to the master zx_daemon and proxies +%%% its requests through it. If no port number exists then the daemon waits 5 seconds, +%%% checks again, and if there is still no port number then it checks whether the +%%% timestamp is more than 5 seconds old or in the future. If the timestamp is more +%%% than 5 seconds old or in the future then the file is deleted and the process +%%% of master identification starts again. +%%% +%%% If a master daemon's runtime is shutting down it will designate its oldest peer +%%% daemon connection as the new master. At that point the new master will open a port +%%% and rewrite the lock file. Once written the old master will drop all its node +%%% connections and dequeue all current requests, then pass a local redirect message +%%% to the subordinate daemons telling them the new port to which they should connect. +%%% +%%% Even if there is considrable churn within a system from, for example, scripted +%%% initiation of several small utilities that have never been executed before, the +%%% longest-living daemon should always become the master. This is not the most +%%% efficient procedure, but it is the easiest to understand and debug across various +%%% platforms. %%% @end -module(zx_daemon). @@ -274,12 +313,6 @@ %% the filesystem. This step allows running development code from any location in %% the filesystem against installed dependencies without requiring any magical %% references. -%% -%% This call blocks specifically so that we can be certain that the target application -%% cannot be started before the impact of this call has taken full effect. It cannot -%% be known whether the very first thing the target application will do is send this -%% process an async message. That implies that this should only ever be called once, -%% by the launching process (which normally terminates shortly thereafter). pass_meta(Meta, Dir, ArgV) -> gen_server:cast(?MODULE, {pass_meta, Meta, Dir, ArgV}). @@ -288,11 +321,11 @@ pass_meta(Meta, Dir, ArgV) -> -spec subscribe(Package) -> ok when Package :: zx:package(). %% @doc -%% Subscribe to update notifications for a for a particular package. +%% Subscribe to update notifications for a for a package. %% The caller will receive update notifications of type `sub_message()' as Erlang %% messages whenever an update occurs. %% Crashes the caller if the Realm or Name of the Package argument are illegal -%% `zx:lower0_9' strings. +%% `zx:lower0_9()' strings. subscribe(Package = {Realm, Name}) -> true = zx_lib:valid_lower0_9(Realm), @@ -558,6 +591,8 @@ start_link() -> -spec init(none) -> {ok, state()}. +%% @private +%% TODO: Implement lockfile checking and master lock acquisition. init(none) -> Blank = blank_state(), @@ -674,7 +709,8 @@ handle_cast({result, Ref, Result}, State) -> {noreply, NewState}; handle_cast({notify, Conn, Package, Update}, State) -> ok = do_notify(Conn, Package, Update, State), - {noreply, State}; + NewState = eval_queue(State), + {noreply, NewState}; handle_cast(stop, State) -> {stop, normal, State}; handle_cast(Unexpected, State) -> @@ -704,6 +740,7 @@ code_change(_, State, _) -> %% @private %% gen_server callback to handle shutdown/cleanup tasks on receipt of a clean %% termination request. +%% TODO: Implement new master selection, dequeuing and request queue passing. terminate(normal, #s{cx = CX}) -> ok = log(info, "zx_daemon shutting down..."), @@ -778,7 +815,7 @@ do_request(Requestor, Action, State = #s{id = ID, actions = Actions}) -> State :: state(), NewState :: state(). %% @private -%% Receive a report from a connection process, and update the connection index and +%% Receive a report from a connection process, update the connection index and %% possibly retry connections. do_report(Conn, {connected, Realms}, State = #s{mx = MX, cx = CX}) -> @@ -788,7 +825,7 @@ do_report(Conn, {connected, Realms}, State = #s{mx = MX, cx = CX}) -> {assigned, NextCX} -> {NextMX, NextCX}; {unassigned, NextCX} -> - {ok, ScrubbedMX} = mx_del_monitor(Conn, conn, NextMX), + ScrubbedMX = mx_del_monitor(Conn, conn, NextMX), ok = zx_conn:stop(Conn), {ScrubbedMX, NextCX} end, @@ -796,9 +833,9 @@ do_report(Conn, {connected, Realms}, State = #s{mx = MX, cx = CX}) -> do_report(Conn, {redirect, Hosts}, State = #s{mx = MX, cx = CX}) -> NextMX = mx_del_monitor(Conn, attempt, MX), {Unassigned, NextCX} = cx_redirect(Conn, Hosts, CX), - {NewMX, NewCX} = ensure_connection(Unassigned, NextMX, NextCX), + {NewMX, NewCX} = ensure_connections(Unassigned, NextMX, NextCX), State#s{mx = NewMX, cx = NewCX}; -do_report(Conn, failed, State = #s{mx = MX, cx = CX}) -> +do_report(Conn, failed, State = #s{mx = MX}) -> NewMX = mx_del_monitor(Conn, attempt, MX), failed(Conn, State#s{mx = NewMX}); do_report(Conn, disconnected, State = #s{mx = MX}) -> @@ -806,21 +843,30 @@ do_report(Conn, disconnected, State = #s{mx = MX}) -> disconnected(Conn, State#s{mx = NewMX}). -failed(Conn, State#s{mx = MX, cx = CX}) -> +-spec failed(Conn, State) -> NewState + when Conn :: pid(), + State :: state(), + NewState :: state(). + +failed(Conn, State = #s{mx = MX, cx = CX}) -> {Realms, NextCX} = cx_failed(Conn, CX), - {NewMX, NewCX} = ensure_connection(Realms, MX, NextCX), + {NewMX, NewCX} = ensure_connections(Realms, MX, NextCX), State#s{mx = NewMX, cx = NewCX}. - + + +-spec disconnected(Conn, State) -> NewState + when Conn :: pid(), + State :: state(), + NewState :: state(). disconnected(Conn, State = #s{actions = Actions, requests = Requests, mx = MX, cx = CX}) -> - {Pending, LostSubs, ScrubbedCX} = cx_disconnected(Conn, CX), - Unassigned = cx_unassigned(ScrubbedCX), + {Pending, LostSubs, Unassigned, ScrubbedCX} = cx_disconnected(Conn, CX), ReSubs = [{S, {subscribe, P}} || {S, P} <- LostSubs], {Dequeued, NewRequests} = maps:fold(dequeue(Pending), {#{}, #{}}, Requests), ReReqs = maps:to_list(Dequeued), NewActions = ReReqs ++ ReSubs ++ Actions, - {NewMX, NewCX} = ensure_connection(Unassigned, ScrubbedMX, ScrubbedCX), + {NewMX, NewCX} = ensure_connections(Unassigned, MX, ScrubbedCX), State#s{actions = NewActions, requests = NewRequests, mx = NewMX, @@ -848,32 +894,48 @@ dequeue(Pending) -> end. --spec ensure_connection(Realms, MX, CX) -> {NewMX, NewCX} +-spec ensure_connections(Realms, MX, CX) -> {NewMX, NewCX} when Realms :: [zx:realm()], MX :: monitor_index(), CX :: conn_index(), NewMX :: monitor_index(), NewCX :: conn_index(). %% @private -%% Initiates a connection to a single realm at a time, taking into account whether -%% connected but unassigned nodes are alterantive providers of the needed realm. -%% Returns updated monitor and connection indices. +%% Check the list of unprovided realms with all available connections that can provide +%% it, and allocate accordingly. If any realms cannot be provided by existing +%% connections, new connections are initiated for all unprovided realms. -ensure_connection([Realm | Realms], MX, CX = #cx{realms = RMetas}) -> - {NewMX, NewCX} = +ensure_connections(Realms, MX, CX) -> + {NextCX, Unavailable} = reassign_conns(Realms, CX, []), + {ok, NewMX, NewCX} = init_connections(Unavailable, MX, NextCX), + {NewMX, NewCX}. + + +-spec reassign_conns(Realms, CX, Unavailable) -> {NewCX, NewUnavailable} + when Realms :: [zx:realm()], + CX :: conn_index(), + Unavailable :: [zx:realm()], + NewCX :: conn_index(), + NewUnavailable :: [zx:realm()]. +%% @private +%% Finds connections that provide a requested realm and assigns that connection to +%% take over realm provision. Returns the updated CX and a list of all the realms +%% that could not be provided by any available connection. + +reassign_conns([Realm | Realms], CX = #cx{realms = RMetas}, Unassigned) -> + {NewUnassigned, NewCX} = case maps:get(Realm, RMetas) of #rmeta{available = []} -> - {ok, NextMX, NextCX} = init_connections([Realm], MX, CX), - {NextMX, NextCX}; + {[Realm | Unassigned], CX}; Meta = #rmeta{available = [Conn | Conns]} -> NewMeta = Meta#rmeta{assigned = Conn, available = Conns}, NewRMetas = maps:put(Realm, NewMeta, RMetas), NextCX = CX#cx{realms = NewRMetas}, - {MX, NextCX} + {Unassigned, NextCX} end, - ensure_connection(Realms, NewMX, NewCX); -ensure_connection([], MX, CX) -> - {MX, CX}. + reassign_conns(Realms, NewCX, NewUnassigned); +reassign_conns([], CX, Unassigned) -> + {CX, Unassigned}. -spec do_result(ID, Result, State) -> NewState @@ -915,7 +977,7 @@ handle_orphan_result(ID, Result, Dropped) -> ok = log(info, Message, [ID, Request, Result]), NewDropped; error -> - Message = "Received unknown request result ~tp: ~tp", + Message = "Received untracked request result ~tp: ~tp", ok = log(warning, Message, [ID, Result]), Dropped end. @@ -954,6 +1016,16 @@ eval_queue(State = #s{actions = Actions}) -> eval_queue(InOrder, State#s{actions = []}). +-spec eval_queue(Actions, State) -> NewState + when Actions :: [action()], + State :: state(), + NewState :: state(). +%% @private +%% This is essentially a big, gnarly fold over the action list with State as the +%% accumulator. It repacks the State#s.actions list with whatever requests were not +%% able to be handled and updates State in whatever way necessary according to the +%% handled requests. + eval_queue([], State) -> State; eval_queue([Action = {request, Pid, ID, Message} | Rest], @@ -966,7 +1038,7 @@ eval_queue([Action = {request, Pid, ID, Message} | Rest], {Actions, NextRequests, NextMX, NextCX}; {result, Response} -> Pid ! Response, - {Actions, Requests, CX}; + {Actions, Requests, MX, CX}; wait -> NextActions = [Action | Actions], NextMX = mx_add_monitor(Pid, requestor, MX), @@ -986,7 +1058,7 @@ eval_queue([Action = {subscribe, Pid, Package} | Rest], ok = zx_conn:subscribe(Conn, Package), NextMX = mx_add_monitor(Pid, subscriber, MX), {Actions, NextMX, NextCX}; - {have_sub, NextCX} + {have_sub, NextCX} -> NextMX = mx_add_monitor(Pid, subscriber, MX), {Actions, NextMX, NextCX}; unassigned -> @@ -1002,8 +1074,8 @@ eval_queue([{unsubscribe, Pid, Package} | Rest], {ok, NewMX} = mx_del_monitor(Pid, {subscription, Package}, MX), NewCX = case cx_del_sub(Pid, Package, CX) of - {drop_sub, NextCX} -> - ok = zx_conn:unsubscribe(Conn, Package), + {{drop_sub, ConnPid}, NextCX} -> + ok = zx_conn:unsubscribe(ConnPid, Package), NextCX; {keep_sub, NextCX} -> NextCX; @@ -1026,10 +1098,13 @@ eval_queue([{unsubscribe, Pid, Package} | Rest], | wait, NewCX :: conn_index(), Response :: result(). +%% @private +%% Routes a request to the correct realm connector, if it is available. If it is not +%% available but configured it will return `wait' indicating that the caller should +%% repack the request and attempt to re-evaluate it later. If the realm is not +%% configured at all, the process is short-circuited by forming an error response +%% directly. -dispatch_request(list, ID, CX) -> - Realms = cx_realms(CX), - {result, ID, Realms}; dispatch_request(Action, ID, CX) -> Realm = element(2, Action), case cx_pre_send(Realm, ID, CX) of @@ -1062,27 +1137,20 @@ clear_monitor(Pid, mx = MX, cx = CX}) -> case mx_crashed_monitor(Pid, MX) of - {attempt, NextMX} -> - failed( - {conn, NextMX} -> - disconnected(Pid, State#s{mx = NextMX}); - {{Reqs, Subs}, NextMX} -> - case mx_lookup_category(Pid, MX) of - attempt -> - do_report(Pid, failed, State); - conn -> - do_report(Pid, disconnected, State); - {Reqs, Subs} -> + {attempt, NewMX} -> + failed(Pid, State#s{mx = NewMX}); + {conn, NewMX} -> + disconnected(Pid, State#s{mx = NewMX}); + {{Reqs, Subs}, NewMX} -> NewActions = drop_actions(Pid, Actions), {NewDropped, NewRequests} = drop_requests(Pid, Dropped, Requests), NewCX = cx_clear_client(Pid, Reqs, Subs, CX), - NewMX = mx_del_monitor(Pid, crashed, MX), State#s{actions = NewActions, requests = NewRequests, dropped = NewDropped, mx = NewMX, cx = NewCX}; - error -> + unknown -> Unexpected = {'DOWN', Ref, process, Pid, Reason}, ok = log(warning, "Unexpected info: ~tp", [Unexpected]), State @@ -1121,116 +1189,8 @@ drop_requests(ReqIDs, Dropped, Requests) -> lists:fold(Partition, {Dropped, Requests}, ReqIDs). -%-spec do_query_latest(Object, State) -> {Result, NewState} -% when Object :: zx:package() | zx:package_id(), -% State :: state(), -% Result :: {ok, zx:version()} -% | {error, Reason}, -% Reason :: bad_realm -% | bad_package -% | bad_version, -% NewState :: state(). -%% @private -%% Queries a zomp realm for the latest version of a package or package -%% version (complete or incomplete version number). -% -%do_query_latest(Socket, {Realm, Name}) -> -% ok = zx_net:send(Socket, {latest, Realm, Name}), -% receive -% {tcp, Socket, Bin} -> binary_to_term(Bin) -% after 5000 -> {error, timeout} -% end; -%do_query_latest(Socket, {Realm, Name, Version}) -> -% ok = zx_net:send(Socket, {latest, Realm, Name, Version}), -% receive -% {tcp, Socket, Bin} -> binary_to_term(Bin) -% after 5000 -> {error, timeout} -% end. - - -%-spec do_fetch(PackageIDs, State) -> NewState -% when PackageIDs :: [zx:package_id()], -% State :: state(), -% NewState :: state(), -% Result :: ok -% | {error, Reason}, -% Reason :: bad_realm -% | bad_package -% | bad_version -% | network. -%% @private -%% -% -%do_fetch(PackageIDs, State) -> -% FIXME: Need to create a job queue divided by realm and dispatched to connectors, -% and cleared from the master pending queue kept here by the daemon as the -% workers succeed. Basic task queue management stuff... which never existed -% in ZX before... grrr... -% case scrub(PackageIDs) of -% [] -> -% ok; -% Needed -> -% Partitioned = partition_by_realm(Needed), -% EnsureDeps = -% fun({Realm, Packages}) -> -% ok = zx_conn:queue_package(Pid, Realm, Packages), -% log(info, "Disconnecting from realm: ~ts", [Realm]) -% end, -% lists:foreach(EnsureDeps, Partitioned) -% end. -% -% -%partition_by_realm(PackageIDs) -> -% PartitionMap = lists:foldl(fun partition_by_realm/2, #{}, PackageIDs), -% maps:to_list(PartitionMap). -% -% -%partition_by_realm({R, P, V}, M) -> -% maps:update_with(R, fun(Ps) -> [{P, V} | Ps] end, [{P, V}], M). -% -% -%ensure_deps(_, _, []) -> -% ok; -%ensure_deps(Socket, Realm, [{Name, Version} | Rest]) -> -% ok = ensure_dep(Socket, {Realm, Name, Version}), -% ensure_deps(Socket, Realm, Rest). -% -% -%-spec ensure_dep(gen_tcp:socket(), package_id()) -> ok | no_return(). -%% @private -%% Given an PackageID as an argument, check whether its package file exists in the -%% system cache, and if not download it. Should return `ok' whenever the file is -%% sourced, but exit with an error if it cannot locate or acquire the package. -% -%ensure_dep(Socket, PackageID) -> -% ZrpFile = filename:join("zrp", namify_zrp(PackageID)), -% ok = -% case filelib:is_regular(ZrpFile) of -% true -> ok; -% false -> fetch(Socket, PackageID) -% end, -% ok = install(PackageID), -% build(PackageID). -% -% -%-spec scrub(Deps) -> Scrubbed -% when Deps :: [package_id()], -% Scrubbed :: [package_id()]. -%% @private -%% Take a list of dependencies and return a list of dependencies that are not yet -%% installed on the system. -% -%scrub([]) -> -% []; -%scrub(Deps) -> -% lists:filter(fun(PackageID) -> not zx_lib:installed(PackageID) end, Deps). - - %%% Monitor Index ADT Interface Functions -%%% -%%% Very simple structure, but explicit handling of it becomes bothersome in other -%%% code, so it is all just packed down here. -spec mx_new() -> monitor_index(). %% @private @@ -1288,7 +1248,7 @@ mx_upgrade_conn(Pid, MX) -> when Conn :: pid(), Category :: attempt | conn - | {requestor, id()}, + | {requestor, id()} | {subscriber, Sub :: tuple()}, MX :: monitor_index(), NewMX :: monitor_index(). @@ -1311,12 +1271,12 @@ mx_del_monitor(Pid, {requestor, ID}, MX) -> true = demonitor(Ref, [flush]), NextMX; {{Ref, {Reqs, Subs}}, NextMX} when Reqs > 0 -> - NewReqs = lists:subtract(ID, Reqs), - maps:put(Pid, {NewReqs, Subs}, NextMX) - end, + NewReqs = lists:delete(ID, Reqs), + maps:put(Pid, {Ref, {NewReqs, Subs}}, NextMX) + end; mx_del_monitor(Pid, {subscriber, Sub}, MX) -> case maps:take(Pid, MX) of - {{Ref, {[], [Package]}}, NextMX} -> + {{Ref, {[], [Sub]}}, NextMX} -> true = demonitor(Ref, [flush]), NextMX; {{Ref, {Reqs, Subs}}, NextMX} when Subs > 0 -> @@ -1338,27 +1298,10 @@ mx_del_monitor(Pid, {subscriber, Sub}, MX) -> mx_crashed_monitor(Pid, MX) -> case maps:take(Pid, MX) of {{Ref, Type}, NewMX} -> - true = demonitor(Mon, [flush]), + true = demonitor(Ref, [flush]), {Type, NewMX}; error -> - error - end. - - --spec mx_lookup_category(Pid, MX) -> Result - when Pid :: pid(), - MX :: monitor_index(), - Result :: attempt - | conn - | {Reqs :: [reference()], Subs :: [zx:package()]} - | error. -%% @private -%% Lookup a monitor's categories. - -mx_lookup_category(Pid, MX) -> - case maps:find(Pid, MX) of - {ok, Mon} -> element(2, Mon); - error -> error + unknown end. @@ -1672,7 +1615,7 @@ cx_connected(Available, Pid, CX = #cx{attempts = Attempts}) -> -spec cx_connected(A, Available, Conn, CX) -> {NewA, NewCX} when A :: unassigned | assigned, Available :: [{zx:realm(), zx:serial()}], - Conn :: {pid(), zx:host(), [zx:realm()]}, + Conn :: connection(), CX :: conn_index(), NewA :: unassigned | assigned, NewCX :: conn_index(). @@ -1704,7 +1647,7 @@ cx_connected(A, -spec cx_connected(A, Realm, Conn, Meta, CX) -> {NewA, NewCX} when A :: unassigned | assigned, Realm :: zx:host(), - Conn :: {pid(), zx:host(), [zx:realm()]}, + Conn :: connection(), Meta :: realm_meta(), CX :: conn_index(), NewA :: unassigned | assigned, @@ -1785,6 +1728,12 @@ cx_failed(Conn, CX = #cx{attempts = Attempts}) -> CX :: conn_index(), Unassigned :: [zx:realm()], NewCX :: conn_index(). +%% @private +%% Remove a redirected connection attempt from CX, add its redirect hosts to the +%% mirror queue, and proceed to make further connection atempts to all unassigned +%% realms. This can cause an inflationary number of new connection attempts, but this +%% is considered preferrable because the more mirrors fail the longer the user is +%% waiting and the more urgent the need to discover a working node becomes. cx_redirect(Conn, Hosts, CX = #cx{attempts = Attempts}) -> NewAttempts = lists:keydelete(Conn, 1, Attempts), @@ -1810,7 +1759,7 @@ cx_redirect([{Host, Provided} | Rest], CX = #cx{realms = Realms}) -> NewMeta = Meta#rmeta{mirrors = NewMirrors}, maps:put(R, NewMeta, Rs); error -> - R + Rs end end, NewRealms = lists:foldl(Apply, Realms, Provided), @@ -1823,7 +1772,7 @@ cx_redirect([], CX) -> when CX :: conn_index(), Unassigned :: [zx:realm()]. %% @private -%% Scan the CX record for unassigned realms;return a list of all unassigned +%% Scan CX#cx.realms for unassigned realms and return a list of all unassigned %% realm names. cx_unassigned(#cx{realms = Realms}) -> @@ -1837,12 +1786,13 @@ cx_unassigned(#cx{realms = Realms}) -> maps:fold(NotAssigned, [], Realms). --spec cx_disconnected(Conn, CX) -> {Requests, Subs, NewCX} - when Conn :: pid(), - CX :: conn_index(), - Requests :: [reference()], - Subs :: [zx:package()], - NewCX :: conn_index(). +-spec cx_disconnected(Conn, CX) -> {Requests, Subs, Unassigned, NewCX} + when Conn :: pid(), + CX :: conn_index(), + Requests :: [id()], + Subs :: [zx:package()], + Unassigned :: [zx:realm()], + NewCX :: conn_index(). %% @private %% An abstract data handler which is called whenever a connection terminates. %% This function removes all data related to the disconnected pid and its assigned @@ -1854,7 +1804,8 @@ cx_disconnected(Pid, CX = #cx{realms = Realms, conns = Conns}) -> #conn{host = Host, requests = Requests, subs = Subs} = Conn, NewRealms = cx_scrub_assigned(Pid, Host, Realms), NewCX = CX#cx{realms = NewRealms, conns = NewConns}, - {Requests, Subs, NewCX}. + Unassigned = cx_unassigned(NewCX), + {Requests, Subs, Unassigned, NewCX}. -spec cx_scrub_assigned(Pid, Host, Realms) -> NewRealms @@ -1960,11 +1911,11 @@ cx_add_sub(Subscriber, Channel, CX = #cx{conns = Conns}) -> NewCX :: conn_index(). cx_maybe_new_sub(Conn = #conn{pid = ConnPid, subs = Subs}, - Sub = {Subscriber, Channel}, + Sub = {_, Channel}, CX = #cx{conns = Conns}) -> - NewSubs = [{Subscriber, Channel} | Subs], + NewSubs = [Sub | Subs], NewConn = Conn#conn{subs = NewSubs}, - NewConns = [NewConn | NextConns], + NewConns = [NewConn | Conns], NewCX = CX#cx{conns = NewConns}, case lists:keymember(Channel, 2, Subs) of false -> {need_sub, ConnPid, NewCX}; @@ -1990,25 +1941,35 @@ cx_del_sub(Subscriber, Channel, CX = #cx{conns = Conns}) -> case cx_resolve(Realm, CX) of {ok, Pid} -> {value, Conn, NewConns} = lists:keytake(Pid, #conn.pid, Conns), - cx_maybe_last_sub(Conn, {Subscriber, Channel}, CX#cx{conns = NewConns}; + cx_maybe_last_sub(Conn, {Subscriber, Channel}, CX#cx{conns = NewConns}); Other -> Other end. +-spec cx_maybe_last_sub(Conn, Sub, CX) -> {Verdict, NewCX} + when Conn :: connection(), + Sub :: {pid(), term()}, + CX :: conn_index(), + Verdict :: {drop_sub, Conn :: pid()} | keep_sub, + NewCX :: conn_index(). +%% @private +%% Tells us whether a sub is still valid for any clients. If a sub is unsubbed by all +%% then it needs to be unsubscribed at the upstream node. + cx_maybe_last_sub(Conn = #conn{pid = ConnPid, subs = Subs}, - Sub = {Subscriber, Channel}, + Sub = {_, Channel}, CX = #cx{conns = Conns}) -> NewSubs = lists:delete(Sub, Subs), NewConn = Conn#conn{subs = NewSubs}, - NewConns = [NewConn | NextConns], + NewConns = [NewConn | Conns], NewCX = CX#cx{conns = NewConns}, - MaybeDrop = + Verdict = case lists:keymember(Channel, 2, NewSubs) of - false -> drop_sub; + false -> {drop_sub, ConnPid}; true -> keep_sub end, - {MaybeDrop, NewCX}. + {Verdict, NewCX}. -spec cx_get_subscribers(Conn, Channel, CX) -> Subscribers @@ -2022,6 +1983,16 @@ cx_get_subscribers(Conn, Channel, #cx{conns = Conns}) -> lists:fold(registered_to(Channel), [], Subs). +-spec registered_to(Channel) -> fun(({P, C}, A) -> NewA) + when Channel :: term(), + P :: pid(), + C :: term(), + A :: [pid()], + NewA :: [pid()]. +%% @private +%% Matching function that closes over a given channel in a subscriber list. +%% This function exists mostly to make its parent function read nicely. + registered_to(Channel) -> fun({P, C}, A) -> case C == Channel of @@ -2031,8 +2002,15 @@ registered_to(Channel) -> end. +-spec cx_clear_client(Pid, DeadReqs, DeadSubs, CX) -> NewCX + when Pid :: pid(), + DeadReqs :: [id()], + DeadSubs :: [term()], + CX :: conn_index(), + NewCX :: conn_index(). + cx_clear_client(Pid, DeadReqs, DeadSubs, CX = #cx{conns = Conns}) -> - DropSubs = [{S, Pid} || S <- DeadSubs], + DropSubs = [{Pid, Sub} || Sub <- DeadSubs], Clear = fun(C = #conn{requests = Requests, subs = Subs}) -> NewSubs = lists:subtract(Subs, DropSubs), From 66b65d3fd4626d0853266f5c0456f3e22b06b63a Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Thu, 22 Mar 2018 19:10:02 +0900 Subject: [PATCH 45/55] blah --- .gitignore | 1 + zomp/lib/otpr-zx/0.1.0/ebin/zx.app | 8 +++++++- zomp/lib/otpr-zx/0.1.0/src/.zx_daemon.erl.swp | Bin 147456 -> 0 bytes zomp/lib/otpr-zx/0.1.0/src/zx_conn_sup.erl | 2 +- .../src/{zx_daemon_sup.erl => zx_sup.erl} | 2 +- 5 files changed, 10 insertions(+), 3 deletions(-) delete mode 100644 zomp/lib/otpr-zx/0.1.0/src/.zx_daemon.erl.swp rename zomp/lib/otpr-zx/0.1.0/src/{zx_daemon_sup.erl => zx_sup.erl} (98%) diff --git a/.gitignore b/.gitignore index 3826c85..bbcd1d5 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ deps *.o *.beam *.plt +*.swp erl_crash.dump ebin/*.beam rel/example_project diff --git a/zomp/lib/otpr-zx/0.1.0/ebin/zx.app b/zomp/lib/otpr-zx/0.1.0/ebin/zx.app index 646143b..23be553 100644 --- a/zomp/lib/otpr-zx/0.1.0/ebin/zx.app +++ b/zomp/lib/otpr-zx/0.1.0/ebin/zx.app @@ -2,5 +2,11 @@ [{description, "Zomp client program"}, {vsn, "0.1.0"}, {applications, [stdlib, kernel]}, - {modules, [zx, zxd_sup, zxd]}, + {modules, [zx, + zx_sup, + zx_daemon, + zx_conn_sup, + zx_conn, + zx_lib, + zx_net]}, {mod, {zx, []}}]}. diff --git a/zomp/lib/otpr-zx/0.1.0/src/.zx_daemon.erl.swp b/zomp/lib/otpr-zx/0.1.0/src/.zx_daemon.erl.swp deleted file mode 100644 index 1b7e5a7fbf601a9917d534322d8b2b3d6cff5b7f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 147456 zcmeF437lLe^uT6`pvPsGB%KZG#~vmJMZ=D z*GF}ARdsds?vpRvu(5LY$-9p6xyjhrlOFcki(hu!Wn=fg%h*`0zOUY?_jo@3l@Lo=-s0&aI^)E zw!qOAINAb7Ti|F59BqN4EpW62{=aI0-rS0@hf$+H2(|j7@O`bm?>`K`&j{Z)=(~Sh z_gZNl$shwn%9-M@9;??ZjRZxw$3S@^E@-M?k{9W|Qg_T9fl`2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_conn_sup.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_conn_sup.erl @@ -42,7 +42,7 @@ start_conn(Host, Serial) -> | {shutdown, term()} | term(). %% @private -%% Called by zx_daemon_sup. +%% Called by zx_sup. %% %% Spawns a single, registered supervisor process. %% diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon_sup.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_sup.erl similarity index 98% rename from zomp/lib/otpr-zx/0.1.0/src/zx_daemon_sup.erl rename to zomp/lib/otpr-zx/0.1.0/src/zx_sup.erl index 52f04f0..5f07fba 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon_sup.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_sup.erl @@ -4,7 +4,7 @@ %%% This supervisor maintains the lifecycle of the zxd worker process. %%% @end --module(zx_daemon_sup). +-module(zx_sup). -behavior(supervisor). -author("Craig Everett "). -copyright("Craig Everett "). From 2e9df29149d100074ac18be53627868d591386d7 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Mon, 23 Apr 2018 07:58:56 +0900 Subject: [PATCH 46/55] bleh --- TODO | 42 +++-- Zomp Protocol Specification.odt | Bin 0 -> 19362 bytes zomp/lib/otpr-zx/0.1.0/src/zx.erl | 1 + zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl | 218 +++++++++++++++++------ zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl | 25 ++- 5 files changed, 206 insertions(+), 80 deletions(-) create mode 100644 Zomp Protocol Specification.odt diff --git a/TODO b/TODO index fed003f..8041787 100644 --- a/TODO +++ b/TODO @@ -1,24 +1,36 @@ - - zomp nodes must report the realms they provide to upstream nodes to which they connect. - On redirect a list of hosts of the form [{zx:host(), [zx:realm()]}] must be provided to the downstream client. - This is the only way that downstream clients can determine which redirect hosts are useful to it. +- Make the create project command fail if the realm is invalid or the project bame already exists. - - Change zx_daemon request references to counters. - Count everything. - This will be the only way to sort of track stats other than log analysis. - Log analysis sucks. +- Add a module name conflict checker to ZX - - Double-indexing must happen everywhere for anything to be discoverable without traversing the entire state of zx_daemon whenever a client or conn crashes. +- Check whether the "repo name doesn't have to be the same as package, package doesn't have to be the same as main interface module" statement is true. - - zx_daemon request() types have been changes to flat, wide tuples as in the main zx module. - This change is not yet refected in the using code. +- Make the "create user" bundle command check whether a user already exists at that realm. - - Write a logging process. - Pick a log rotation scheme. - Eventually make it so that it can shed log loads in the event they get out of hand. +- Define the user bundle file contents: .zuf +- Make it possible for a site administrator to declare specific versions for programs executed by clients. + Site adminisration via an organizational mirror should not be ricket science. + +- zomp nodes must report the realms they provide to upstream nodes to which they connect. + On redirect a list of hosts of the form [{zx:host(), [zx:realm()]}] must be provided to the downstream client. + This is the only way that downstream clients can determine which redirect hosts are useful to it. + +- Write a logging process. + Pick a log rotation scheme. + Eventually make it so that it can shed log loads in the event they get out of hand. + +- Create zx_daemon primes. + See below + +- Create persistent Windows alias for "zx" using the doskey command and adding it to the localuser's registry. + The installation escript will need to be updated to update the windows registry for HKEY_CURRENT_USER\Software\Microsoft\Command Processor + AutoRun will need to be set for %USERPROFILE%\zomp_alias.cmd + zomp_alias.cmd will need to do something like: + `doskey zx="werl.exe -pa %zx_dir%/ebin -run zx start $*"` + https://stackoverflow.com/questions/20530996/aliases-in-windows-command-prompt + Whatever happens, local users must be able to do `zx $@` and get the expected results. + Somewhat more tricky is how to make the creation of shortcuts less taxing on the lay user... ? - - Create zx_daemon primes. - See below New Feature: ZX Universal lock Cross-instance communication diff --git a/Zomp Protocol Specification.odt b/Zomp Protocol Specification.odt new file mode 100644 index 0000000000000000000000000000000000000000..2e6118067696b487c41162dd059f9bc92990f2f8 GIT binary patch literal 19362 zcmaI71B_@*)GgSyZQHhO+qP}nwr$(CyKi^jwr#uTe*esS$xQO5l1f!}oxRUVPNlMH zt-Tebfk99J03ZMWzJmQ_^v0NA$N>NV{_Fot0JfI4rY@ciriKmy|8g43%;^OJ?@$uo|?dRv`-v|Ew{!Wxw5d#3= zBu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>8?+YmoxLX-@PWf(A;E3-mZ5aH`lcDXV|6R`tb7BBM9XgC+yDID8aZ)}?~I;uk4X0I%oDGDOP4ohX64`upmGc%{;_Toj+qM7E) zCHXZ2mfEYV*#B#1+}=0sJ=^WU%XvggV`3H97#O%TVKocvYzSaw0tZq+mUDhyT4s7_ z5%^SyVk7;6{DRT~;875z`l!c1z%>CGphZIH`Z9A9(^HG}oia;u6AOy*XvSt~aYn3w5gvV@vnS9k1-X-SU1>S_i6yD{?84^8lKlLfg2cSk9H<+yt-1moxPk7*#N_1E zoK#@=<`?NFmlhR4*G@5m;|ZvqfeAza0q*d|=5>&B@OvG!oD1DC1x5MkMXAL|L5B`1Ey^etoom33EkV* zH#sbD$*NcLuRLDoW_-VI%j~y_GAFt>tvDEBlB}tE$|GazOKq#&dOMfiwz_p=o3{Kc z*^gPxOXq9tD$mohjGxx3YtEB%e)A%Yidmm+{P!pwylPSC!E~rmVL*_MR?(e&pkEJk&KJwky#dNaeR#0^3`nTyn^~_!$J;i*JP55IfD?5mgy(FM=vF1o(x;6x6B>)sx8O vHfnk{aY3!>U_OBb4{{L%D%TO9*cC@9AK=XjY " zx add package PackageName~n" " zx add packager PackageName~n" " zx add maintainer PackageName~n" + " zx add sysop UserID~n" " zx review PackageID~n" " zx approve PackageID~n" " zx reject PackageID~n" diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl index ec6644f..119c27e 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl @@ -1,4 +1,4 @@ -%%% @doc +%% @doc %%% ZX Connector %%% %%% This module represents a connection to a Zomp server. @@ -11,12 +11,59 @@ -copyright("Craig Everett "). -license("GPL-3.0"). +-export([subscribe/2, unsubscribe/2, fetch/3, query/3]). -export([start/1, stop/1]). --export([start_link/1]). +-export([start_link/1, init/2]). --include("zx_logger.erl"). +-include("zx_logger.hrl"). +%%% Types + +-type incoming() :: ping + | {sub, Channel :: term(), Message :: term()} + | term(). + + +%%% Interface + +-spec subscribe(Conn, Package) -> ok + when Conn :: pid(), + Package :: zx:package(). + +subscribe(Conn, Realm) -> + Conn ! {subscribe, Realm}, + ok. + + +-spec unsubscribe(Conn, Package) -> ok + when Conn :: pid(), + Package :: zx:package(). + +unsubscribe(Conn, Package) -> + Conn ! {unsubscribe, Package}, + ok. + + +-spec fetch(Conn, ID, Object) -> ok + when Conn :: pid(), + ID :: zx_daemon:id(), + Object :: zx_daemon:object(). + +fetch(Conn, ID, Object) -> + Conn ! {fetch, ID, Object}, + ok. + + +-spec query(Conn, ID, Action) -> ok + when Conn :: pid(), + ID :: zx_daemon:id(), + Action :: zx_daemon:action(). + +query(Conn, ID, Action) -> + Conn ! {query, ID, Action}, + ok. + %%% Startup @@ -42,25 +89,7 @@ stop(Conn) -> ok. --spec subscribe(Conn, Package) -> ok - when Conn :: pid(), - Package :: zx:package(). - -subscribe(Conn, Realm) -> - Conn ! {subscribe, Realm}, - ok. - - --spec unsubscribe(Conn, Package) -> ok - when Conn :: pid(), - Package :: zx:package(). - -unsubscribe(Conn, Package) -> - Conn ! {unsubscribe, Package}, - ok. - - --spec start_link(Target) -> +-spec start_link(Target) -> Result when Target :: zx:host(), Result :: {ok, pid()} | {error, Reason}, @@ -94,13 +123,13 @@ init(Parent, Target) -> Target :: zx:host(). connect(Parent, Debug, {Host, Port}) -> - Options = [{packet, 4}, {mode, binary}, {active, true}], + Options = [{packet, 4}, {mode, binary}, {nodelay, true}, {active, true}], case gen_tcp:connect(Host, Port, Options, 5000) of {ok, Socket} -> confirm_service(Parent, Debug, Socket); {error, Error} -> - ok = log(warning, "Connection problem with ~tp: ~tp", [Node, Error]), - ok = zx_daemon:report(disconnected) + ok = log(warning, "Connection problem with ~tp: ~tp", [Host, Error]), + ok = zx_daemon:report(failed), terminate() end. @@ -170,12 +199,23 @@ query_realms(Parent, Debug, Socket) -> loop(Parent, Debug, Socket) -> receive {tcp, Socket, Bin} -> - ok = handle(Bin, Socket), + ok = handle_message(Socket, Bin), ok = inet:setopts(Socket, [{active, once}]), loop(Parent, Debug, Socket); {subscribe, Package} -> + ok = zx_net:send(Socket, {subscribe, Package}), + loop(Parent, Debug, Socket); {unsubscribe, Package} -> - + ok = zx_net:send(Socket, {unsubscribe, Package}), + loop(Parent, Debug, Socket); + {fetch, ID, Object} -> + {ok, Outcome} = handle_fetch(Socket, Object), + ok = zx_daemon:result(ID, Outcome), + loop(Parent, Debug, Socket); + {query, ID, Action} -> + {ok, Outcome} = handle_query(Socket, Action), + ok = zx_daemon:result(ID, Outcome), + loop(Parent, Debug, Socket); stop -> ok = zx_net:disconnect(Socket), terminate(); @@ -185,41 +225,106 @@ loop(Parent, Debug, Socket) -> end. --spec handle(Bin, Socket) -> ok | no_return() - when Bin :: binary(), - Socket :: gen_tcp:socket(). + +%%% Idle Incoming Upstream Messages + +-spec handle_message(Socket, Bin) -> ok | no_return() + when Socket :: gen_tcp:socket(), + Bin :: binary(). %% @private %% Single point to convert a binary message to a safe internal message. Actual handling %% of the converted message occurs in dispatch/2. -handle(Bin, Socket) -> +handle_message(Socket, Bin) -> Message = binary_to_term(Bin, [safe]), ok = log(info, "Received network message: ~tp", [Message]), - dispatch(Message, Socket). + case binary_to_term(Bin, [safe]) of + ping -> + zx_net:send(Socket, pong); + {sub, Channel, Message} -> + log("Sub: ~tp - ~tp", [Channel, Message]); + {update, Message} -> + log("Update: ~tp", [Message]); + {redirect, Nodes} -> + log("Redirected to ~tp", [Nodes]); + Invalid -> + {ok, {Addr, Port}} = zomp:peername(Socket), + Host = inet:ntoa(Addr), + ok = log(warning, "Invalid message from ~tp:~p: ", [Invalid]), + ok = zx_net:disconnect(Socket), + terminate() + end. --spec dispatch(Message, Socket) -> ok | no_return() - when Message :: incoming(), - Socket :: gen_tcp:socket(). -%% @private -%% Dispatch a procedure based on the received message. -%% Tranfers and other procedures that involve a sequence of messages occur in discrete -%% states defined in other functions -- this only dispatches based on a valid initial -%% message received in the default waiting-loop state. -dispatch(ping, Socket) -> - zx_net:send(Socket, pong); -dispatch(Invalid, Socket) -> - {ok, {Addr, Port}} = zomp:peername(Socket), - Host = inet:ntoa(Addr), - ok = log(warning, "Invalid message from ~tp:~p: ", [Invalid]), - ok = zx_net:disconnect(Socket), - terminate(). +%%% Incoming Request Actions + +-spec handle_request(Socket, Action) -> Result + when Socket :: gen_tcp:socket(), + Action :: term(), + Result :: {ok, Outcome :: term()}. + +handle_request(Socket, Action) -> + ok = zx_net:send(Socket, Action), + case element(1, Action) of + list -> + do_list(Action, Socket); + latest -> + do_latest(Action, Socket); + fetch -> + do_fetch(Action, Socket); + key -> + do_key(Action, Socket); + pending -> + do_pending(Action, Socket); + packagers -> + do_packagers(Action, Socket); + maintainers -> + do_maintainers(Action, Socket); + sysops -> + do_sysops(Action, Socket) + end, + handle_response(Socket, Response). + + + +handle_response(Socket, Command) -> + receive + {tcp, Socket, Bin} -> + Outcome = binary_to_term(Bin, [safe]), + interpret_response(Socket, Outcome, Command); + {tcp_closed, Socket} -> + handle_unexpected_close() + after 5000 -> + handle_timeout(Socket) + end. + + +interpret_response(Socket, ping, Command) -> + ok = zx_net:send(Socket, pong), + handle_response(Socket, Command); +interpret_response(Socket, {sub, Channel, Message}, Command) -> + ok = zx_daemon:notify(Channel, Message), + handle_response(Socket, Command); +interpret_response(Socket, {update, Message}, Command) -> +interpret_response(Socket, Response, list) -> +interpret_response(Socket, Response, latest) -> +interpret_response(Socket, Response, fetch) -> +interpret_response(Socket, Response, key) -> +interpret_response(Socket, Response, pending) -> +interpret_response(Socket, Response, packagers) -> +interpret_response(Socket, Response, maintainers) -> +interpret_response(Socket, Response, sysops) -> + + + + case element(1, Action) of + end, -spec fetch(Socket, PackageID) -> Result when Socket :: gen_tcp:socket(), - PackageID :: package_id(), + PackageID :: zx:package_id(), Result :: ok. %% @private %% Download a package to the local cache. @@ -227,13 +332,14 @@ dispatch(Invalid, Socket) -> fetch(Socket, PackageID) -> {ok, LatestID} = request_zrp(Socket, PackageID), ok = receive_zrp(Socket, LatestID), - log(info, "Fetched ~ts", [package_string(LatestID)]). + Latest = zx_lib:package_string(LatestID), + log(info, "Fetched ~ts", [Latest]). -spec request_zrp(Socket, PackageID) -> Result when Socket :: gen_tcp:socket(), - PackageID :: package_id(), - Result :: {ok, Latest :: package_id()} + PackageID :: zx:package_id(), + Result :: {ok, Latest :: zx:package_id()} | {error, Reason :: timeout | term()}. request_zrp(Socket, PackageID) -> @@ -244,7 +350,7 @@ request_zrp(Socket, PackageID) -> {sending, LatestID} -> {ok, LatestID}; Error = {error, Reason} -> - PackageString = package_string(PackageID), + PackageString = zx_lib:package_string(PackageID), Message = "Error receiving package ~ts: ~tp", ok = log(info, Message, [PackageString, Reason]), Error @@ -258,7 +364,7 @@ request_zrp(Socket, PackageID) -> -spec receive_zrp(Socket, PackageID) -> Result when Socket :: gen_tcp:socket(), - PackageID :: package_id(), + PackageID :: zx:package_id(), Result :: ok | {error, timeout}. receive_zrp(Socket, PackageID) -> @@ -286,11 +392,11 @@ handle_unexpected_close() -> terminate(). --spec handle_timeout(gen_tcp:socket()) -> no_return() +-spec handle_timeout(gen_tcp:socket()) -> no_return(). handle_timeout(Socket) -> ok = zx_daemon:report(timeout), - ok = disconnect(Socket), + ok = zx_net:disconnect(Socket), terminate(). diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl index b078f0b..cc78934 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl @@ -218,7 +218,9 @@ %% Conn Communication -type conn_report() :: {connected, Realms :: [{zx:realm(), zx:serial()}]} | {redirect, Hosts :: [zx:host()]} - | disconnected. + | failed + | disconnected + | timeout. %% Subscriber / Requestor Communication % Incoming Request messages @@ -229,8 +231,9 @@ | {list, zx:realm(), zx:name(), zx:version()} | {latest, zx:realm(), zx:name(), zx:version()} | {fetch, zx:realm(), zx:name(), zx:version()} - | {key, zx:realm(), zx:key_name()} + | {fetchkey, zx:realm(), zx:key_name()} | {pending, zx:realm(), zx:name()} + | {resigns, zx:realm()} | {packagers, zx:realm(), zx:name()} | {maintainers, zx:realm(), zx:name()} | {sysops, zx:realm()}. @@ -447,14 +450,14 @@ latest({Realm, Name, Version}) -> %% Response messages are of the type `result()' where the third element is of the %% type `fetch_result()'. -fetch({Realm, Name, Version}) -> +fetch_zsp(PackageID = {Realm, Name, Version}) -> true = zx_lib:valid_lower0_9(Realm), true = zx_lib:valid_lower0_9(Name), true = zx_lib:valid_version(Version), - request({fetch, Realm, Name, Version}). + request({fetch, zsp, PackageID}). --spec key(KeyID) -> {ok, RequestID} +-spec fetch_key(KeyID) -> {ok, RequestID} when KeyID :: zx:key_id(), RequestID :: id(). %% @doc @@ -464,10 +467,10 @@ fetch({Realm, Name, Version}) -> %% Response messages are of the type `result()' where the third element is of the %% type `key_result()'. -key({Realm, KeyName}) -> +fetch_key(KeyID = {Realm, KeyName}) -> true = zx_lib:valid_lower0_9(Realm), true = zx_lib:valid_lower0_9(KeyName), - request({key, Realm, KeyName}). + request({fetch, key, KeyID}). -spec pending(Package) -> {ok, RequestID} @@ -561,7 +564,7 @@ report(Message) -> gen_server:cast(?MODULE, {report, self(), Message}). --spec result(reference(), result()) -> ok. +-spec result(id(), result()) -> ok. %% @private %% Return a tagged result back to the daemon to be forwarded to the original requestor. @@ -839,6 +842,10 @@ do_report(Conn, failed, State = #s{mx = MX}) -> NewMX = mx_del_monitor(Conn, attempt, MX), failed(Conn, State#s{mx = NewMX}); do_report(Conn, disconnected, State = #s{mx = MX}) -> + NewMX = mx_del_monitor(Conn, conn, MX), + disconnected(Conn, State#s{mx = NewMX}); +do_report(Conn, timeout, State = #s{mx = MX}) -> + ok = log(warning, "Connection ~tp timed out.", [Conn]), NewMX = mx_del_monitor(Conn, conn, MX), disconnected(Conn, State#s{mx = NewMX}). @@ -1109,7 +1116,7 @@ dispatch_request(Action, ID, CX) -> Realm = element(2, Action), case cx_pre_send(Realm, ID, CX) of {ok, Conn, NewCX} -> - ok = zx_conn:make_request(Conn, ID, Action), + ok = zx_conn:request(Conn, ID, Action), {dispatched, NewCX}; unassigned -> wait; From 72062f80d48ec4a5b94dcf5049d83e43cf0bb481 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Mon, 7 May 2018 14:40:22 +0900 Subject: [PATCH 47/55] boo --- zomp/lib/otpr-zx/0.1.0/src/zx.erl | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx.erl b/zomp/lib/otpr-zx/0.1.0/src/zx.erl index e8c1414..c9b8423 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx.erl @@ -28,7 +28,7 @@ identifier/0, option/0, host/0, - key_id/0, key_name/0, + key_id/0, key_name/0, key_data/0, user/0, username/0, lower0_9/0, label/0, package_meta/0]). @@ -51,8 +51,12 @@ -type host() :: {string() | inet:ip_address(), inet:port_number()}. -type key_id() :: {realm(), key_name()}. -type key_name() :: lower0_9(). --type user() :: {realm(), username()}. --type username() :: label(). +-type key_data() :: {key_id(), public | private, binary()}. +-type user_id() :: {realm(), user_name()}. +-type user_name() :: label(). +-type user_data() :: {ID :: user_id(), + RealName :: string(), + Email :: string()}. -type lower0_9() :: [$a..$z | $0..$9 | $_]. -type label() :: [$a..$z | $0..$9 | $_ | $- | $.]. -type package_meta() :: #{package_id := package_id(), From 1a661866e59c655dd3e30c84b5f2ce1ba0ec384f Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Fri, 11 May 2018 08:19:02 +0900 Subject: [PATCH 48/55] boo --- zomp/lib/otpr-zx/0.1.0/src/zx.erl | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx.erl b/zomp/lib/otpr-zx/0.1.0/src/zx.erl index c9b8423..f98d445 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx.erl @@ -51,12 +51,16 @@ -type host() :: {string() | inet:ip_address(), inet:port_number()}. -type key_id() :: {realm(), key_name()}. -type key_name() :: lower0_9(). --type key_data() :: {key_id(), public | private, binary()}. +-type key_data() :: {ID :: key_id(), + Public :: binary() | none, + Private :: binary() | none}. -type user_id() :: {realm(), user_name()}. -type user_name() :: label(). +-type contact_info() :: {Type :: string(), Data :: string()}. -type user_data() :: {ID :: user_id(), RealName :: string(), - Email :: string()}. + Contact :: contact_info(), + KeyData :: [key_data()]}. -type lower0_9() :: [$a..$z | $0..$9 | $_]. -type label() :: [$a..$z | $0..$9 | $_ | $- | $.]. -type package_meta() :: #{package_id := package_id(), From 8302d7eec5348f99191c1b9eb095f08bb453dfb5 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Wed, 16 May 2018 11:23:32 +0900 Subject: [PATCH 49/55] bleh --- zomp/lib/otpr-zx/0.1.0/src/zx.erl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx.erl b/zomp/lib/otpr-zx/0.1.0/src/zx.erl index f98d445..7f93cbb 100644 --- a/zomp/lib/otpr-zx/0.1.0/src/zx.erl +++ b/zomp/lib/otpr-zx/0.1.0/src/zx.erl @@ -52,8 +52,8 @@ -type key_id() :: {realm(), key_name()}. -type key_name() :: lower0_9(). -type key_data() :: {ID :: key_id(), - Public :: binary() | none, - Private :: binary() | none}. + Public :: binary() | <<>>, + Private :: binary() | <<>>}. -type user_id() :: {realm(), user_name()}. -type user_name() :: label(). -type contact_info() :: {Type :: string(), Data :: string()}. From e92d2b3153c84c83e7f9b1e35163831819e8c9f5 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Thu, 24 May 2018 08:03:39 +0900 Subject: [PATCH 50/55] foo --- install.escript | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/install.escript b/install.escript index cc905b3..6793603 100755 --- a/install.escript +++ b/install.escript @@ -110,9 +110,8 @@ zomp_dir({unix, _}) -> Home = os:getenv("HOME"), filename:join(Home, "zomp"); zomp_dir({win32, _}) -> - Drive = os:getenv("HOMEDRIVE"), - Path = os:getenv("HOMEPATH"), - filename:join([Drive, Path, "zomp"]); + Path = os:getenv("LOCALAPPDATA"), + filename:join(Path, "zomp"); zomp_dir(Unknown) -> Message = "zx_install: ERROR Unknown host system type: ~tp", ok = io:format(Message, [Unknown]), From 77f6c9b9f194019dd311bd1452f681e7953d1046 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Thu, 24 May 2018 13:25:13 +0900 Subject: [PATCH 51/55] foo --- zomp/lib/{otpr-zx => otpr/zx}/0.1.0/Emakefile | 0 zomp/lib/{otpr-zx => otpr/zx}/0.1.0/LICENSE | 0 zomp/lib/{otpr-zx => otpr/zx}/0.1.0/ebin/zx.app | 0 zomp/lib/{otpr-zx => otpr/zx}/0.1.0/include/zx_logger.hrl | 0 zomp/lib/{otpr-zx => otpr/zx}/0.1.0/src/zx.erl | 0 zomp/lib/{otpr-zx => otpr/zx}/0.1.0/src/zx_conn.erl | 0 zomp/lib/{otpr-zx => otpr/zx}/0.1.0/src/zx_conn_sup.erl | 0 zomp/lib/{otpr-zx => otpr/zx}/0.1.0/src/zx_daemon.erl | 0 zomp/lib/{otpr-zx => otpr/zx}/0.1.0/src/zx_lib.erl | 0 zomp/lib/{otpr-zx => otpr/zx}/0.1.0/src/zx_net.erl | 0 zomp/lib/{otpr-zx => otpr/zx}/0.1.0/src/zx_sup.erl | 0 zomp/lib/{otpr-zx => otpr/zx}/0.1.0/zmake | 0 zomp/{zx.sh => zx} | 6 +++--- zx_dev.sh => zx_dev | 2 +- 14 files changed, 4 insertions(+), 4 deletions(-) rename zomp/lib/{otpr-zx => otpr/zx}/0.1.0/Emakefile (100%) rename zomp/lib/{otpr-zx => otpr/zx}/0.1.0/LICENSE (100%) rename zomp/lib/{otpr-zx => otpr/zx}/0.1.0/ebin/zx.app (100%) rename zomp/lib/{otpr-zx => otpr/zx}/0.1.0/include/zx_logger.hrl (100%) rename zomp/lib/{otpr-zx => otpr/zx}/0.1.0/src/zx.erl (100%) rename zomp/lib/{otpr-zx => otpr/zx}/0.1.0/src/zx_conn.erl (100%) rename zomp/lib/{otpr-zx => otpr/zx}/0.1.0/src/zx_conn_sup.erl (100%) rename zomp/lib/{otpr-zx => otpr/zx}/0.1.0/src/zx_daemon.erl (100%) rename zomp/lib/{otpr-zx => otpr/zx}/0.1.0/src/zx_lib.erl (100%) rename zomp/lib/{otpr-zx => otpr/zx}/0.1.0/src/zx_net.erl (100%) rename zomp/lib/{otpr-zx => otpr/zx}/0.1.0/src/zx_sup.erl (100%) rename zomp/lib/{otpr-zx => otpr/zx}/0.1.0/zmake (100%) rename zomp/{zx.sh => zx} (57%) rename zx_dev.sh => zx_dev (96%) diff --git a/zomp/lib/otpr-zx/0.1.0/Emakefile b/zomp/lib/otpr/zx/0.1.0/Emakefile similarity index 100% rename from zomp/lib/otpr-zx/0.1.0/Emakefile rename to zomp/lib/otpr/zx/0.1.0/Emakefile diff --git a/zomp/lib/otpr-zx/0.1.0/LICENSE b/zomp/lib/otpr/zx/0.1.0/LICENSE similarity index 100% rename from zomp/lib/otpr-zx/0.1.0/LICENSE rename to zomp/lib/otpr/zx/0.1.0/LICENSE diff --git a/zomp/lib/otpr-zx/0.1.0/ebin/zx.app b/zomp/lib/otpr/zx/0.1.0/ebin/zx.app similarity index 100% rename from zomp/lib/otpr-zx/0.1.0/ebin/zx.app rename to zomp/lib/otpr/zx/0.1.0/ebin/zx.app diff --git a/zomp/lib/otpr-zx/0.1.0/include/zx_logger.hrl b/zomp/lib/otpr/zx/0.1.0/include/zx_logger.hrl similarity index 100% rename from zomp/lib/otpr-zx/0.1.0/include/zx_logger.hrl rename to zomp/lib/otpr/zx/0.1.0/include/zx_logger.hrl diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx.erl b/zomp/lib/otpr/zx/0.1.0/src/zx.erl similarity index 100% rename from zomp/lib/otpr-zx/0.1.0/src/zx.erl rename to zomp/lib/otpr/zx/0.1.0/src/zx.erl diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_conn.erl similarity index 100% rename from zomp/lib/otpr-zx/0.1.0/src/zx_conn.erl rename to zomp/lib/otpr/zx/0.1.0/src/zx_conn.erl diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_conn_sup.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_conn_sup.erl similarity index 100% rename from zomp/lib/otpr-zx/0.1.0/src/zx_conn_sup.erl rename to zomp/lib/otpr/zx/0.1.0/src/zx_conn_sup.erl diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_daemon.erl similarity index 100% rename from zomp/lib/otpr-zx/0.1.0/src/zx_daemon.erl rename to zomp/lib/otpr/zx/0.1.0/src/zx_daemon.erl diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_lib.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_lib.erl similarity index 100% rename from zomp/lib/otpr-zx/0.1.0/src/zx_lib.erl rename to zomp/lib/otpr/zx/0.1.0/src/zx_lib.erl diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_net.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_net.erl similarity index 100% rename from zomp/lib/otpr-zx/0.1.0/src/zx_net.erl rename to zomp/lib/otpr/zx/0.1.0/src/zx_net.erl diff --git a/zomp/lib/otpr-zx/0.1.0/src/zx_sup.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_sup.erl similarity index 100% rename from zomp/lib/otpr-zx/0.1.0/src/zx_sup.erl rename to zomp/lib/otpr/zx/0.1.0/src/zx_sup.erl diff --git a/zomp/lib/otpr-zx/0.1.0/zmake b/zomp/lib/otpr/zx/0.1.0/zmake similarity index 100% rename from zomp/lib/otpr-zx/0.1.0/zmake rename to zomp/lib/otpr/zx/0.1.0/zmake diff --git a/zomp/zx.sh b/zomp/zx similarity index 57% rename from zomp/zx.sh rename to zomp/zx index c439460..c93a206 100755 --- a/zomp/zx.sh +++ b/zomp/zx @@ -1,11 +1,11 @@ -#! /bin/sh +#!/bin/sh set -x ZOMP_DIR="$HOME/zomp" ORIGIN="$(pwd)" -VERSION="$(ls $ZOMP_DIR/lib/otpr-zx/ | sort --field-separator=. --reverse | head --lines=1)" -ZX_DIR="$ZOMP_DIR/lib/otpr-zx/$VERSION" +VERSION="$(ls $ZOMP_DIR/lib/otpr/zx/ | sort --field-separator=. --reverse | head --lines=1)" +ZX_DIR="$ZOMP_DIR/lib/otpr/zx/$VERSION" cd "$ZX_DIR" ./zmake diff --git a/zx_dev.sh b/zx_dev similarity index 96% rename from zx_dev.sh rename to zx_dev index f02735a..6a1d577 100755 --- a/zx_dev.sh +++ b/zx_dev @@ -1,4 +1,4 @@ -#! /bin/sh +#!/bin/sh set -x From 18d814fddf08329acd1b38bcdbfb7aa7e46f7721 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Thu, 24 May 2018 22:22:42 +0900 Subject: [PATCH 52/55] foo more --- Zomp Protocol Specification.odt | Bin 19362 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 Zomp Protocol Specification.odt diff --git a/Zomp Protocol Specification.odt b/Zomp Protocol Specification.odt deleted file mode 100644 index 2e6118067696b487c41162dd059f9bc92990f2f8..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 19362 zcmaI71B_@*)GgSyZQHhO+qP}nwr$(CyKi^jwr#uTe*esS$xQO5l1f!}oxRUVPNlMH zt-Tebfk99J03ZMWzJmQ_^v0NA$N>NV{_Fot0JfI4rY@ciriKmy|8g43%;^OJ?@$uo|?dRv`-v|Ew{!Wxw5d#3= zBuI(~s(5T%>qe(-vL!uxAiZkq94J=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aH`lcDXV|6R`tb7BBM9XgC+yDID8aZ)}?~I;uk4X0I%oDGDOP4ohX64`upmGc%{;_Toj+qM7E) zCHXZ2mfEYV*#B#1+}=0sJ=^WU%XvggV`3H97#O%TVKocvYzSaw0tZq+mUDhyT4s7_ z5%^SyVk7;6{DRT~;875z`l!c1z%>CGphZIH`Z9A9(^HG}oia;u6AOy*XvSt~aYn3w5gvV@vnS9k1-X-SU1>S_i6yD{?84^8lKlLfg2cSk9H<+yt-1moxPk7*#N_1E zoK#@=<`?NFmlhR4*G@5m;|ZvqfeAza0q*d|=5>&B@OvG!oD1DC1x5MkMXAL|L5B`1Ey^etoom33EkV* zH#sbD$*NcLuRLDoW_-VI%j~y_GAFt>tvDEBlB}tE$|GazOKq#&dOMfiwz_p=o3{Kc z*^gPxOXq9tD$mohjGxx3YtEB%e)A%Yidmm+{P!pwylPSC!E~rmVL*_MR?(e&pkEJk&KJwky#dNaeR#0^3`nTyn^~_!$J;i*JP55IfD?5mgy(FM=vF1o(x;6x6B>)sx8O vHfnk{aY3!>U_OBb4{{L%D%TO9*cC@9AK=XjY Date: Mon, 28 May 2018 08:33:04 +0900 Subject: [PATCH 53/55] foo --- zomp/etc/otpr/realm.conf | 4 + zomp/etc/sys.conf | 5 + zomp/etc/version.txt | 1 + zomp/key/otpr/otpr.1.package.pub.der | Bin 2062 -> 0 bytes zomp/key/otpr/otpr.1.realm.pub.der | Bin 2062 -> 0 bytes zomp/key/otpr/zxq9-root.pub.der | Bin 0 -> 2062 bytes zomp/lib/otpr/zx/0.1.0/make_zx | 39 ++++ zomp/lib/otpr/zx/0.1.0/src/zx.erl | 9 +- zomp/lib/otpr/zx/0.1.0/src/zx_conf_sys.erl | 251 +++++++++++++++++++++ zomp/lib/otpr/zx/0.1.0/src/zx_conn.erl | 86 ++++--- zomp/lib/otpr/zx/0.1.0/src/zx_daemon.erl | 48 ++-- zomp/lib/otpr/zx/0.1.0/src/zx_lib.erl | 90 ++++++-- zomp/lib/otpr/zx/0.1.0/zmake | 48 ---- zomp/otpr.realm | 20 -- zomp/zx | 11 +- zomp/zx.cmd | 9 + zx_dev | 18 +- 17 files changed, 478 insertions(+), 161 deletions(-) create mode 100644 zomp/etc/otpr/realm.conf create mode 100644 zomp/etc/sys.conf create mode 100644 zomp/etc/version.txt delete mode 100644 zomp/key/otpr/otpr.1.package.pub.der delete mode 100644 zomp/key/otpr/otpr.1.realm.pub.der create mode 100644 zomp/key/otpr/zxq9-root.pub.der create mode 100755 zomp/lib/otpr/zx/0.1.0/make_zx create mode 100644 zomp/lib/otpr/zx/0.1.0/src/zx_conf_sys.erl delete mode 100755 zomp/lib/otpr/zx/0.1.0/zmake delete mode 100644 zomp/otpr.realm create mode 100644 zomp/zx.cmd diff --git a/zomp/etc/otpr/realm.conf b/zomp/etc/otpr/realm.conf new file mode 100644 index 0000000..fbff7c3 --- /dev/null +++ b/zomp/etc/otpr/realm.conf @@ -0,0 +1,4 @@ +{realm, "otpr"}. +{prime, {"otpr.psychobitch.party",11311}}. +{sysop, "zxq9"}. +{key, "zxq9-root"}. diff --git a/zomp/etc/sys.conf b/zomp/etc/sys.conf new file mode 100644 index 0000000..aeeb3d0 --- /dev/null +++ b/zomp/etc/sys.conf @@ -0,0 +1,5 @@ +{timeout, 5}. +{retry, 3}. +{maxconn, 5}. +{managed, []}. +{mirrors, []}. diff --git a/zomp/etc/version.txt b/zomp/etc/version.txt new file mode 100644 index 0000000..6e8bf73 --- /dev/null +++ b/zomp/etc/version.txt @@ -0,0 +1 @@ +0.1.0 diff --git a/zomp/key/otpr/otpr.1.package.pub.der b/zomp/key/otpr/otpr.1.package.pub.der deleted file mode 100644 index e844a3bfb704c026ff00c05bee00a3db78380102..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2062 zcmV+p2=VtYf(Qx%f(QWs+4~Y8{hu^D9WI+v*(Kd+X^!qnl?)??wZi+0@JH$Oz(Wl} zmx4lZ0Y8K&cm(U1LMGHmB$^ihD37Jxlp|hZ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gL`>Up%YMti~Q)qdqNNA8(-ST!OlJKBFGFzR|V%klVaa zck(C=wpA#&H4Dfx7xP&C$dcg)1DnNfM7aMgN9kmgFo^r25%xE9!x6`K%oQ;QZA6(S z$t{lF-3Tv)6hI_Rz32BCcy3Ejm4DVir9Ulese!Ez@I4MSBf5wBE@Z>Cv&?=;G+=9Y zCva~%8v#WONS&FEu2-WQK@WS3h^&M0e8q$H1piC##28aBg**T72gOIo^Xofy7f>H# zfQ7{p4tl8HC{_yikXy^dn$X=(BR`dTY{y2nJA(r=VY_^~otvwOCGnLlOb=~m#*?LZ zLOz~s!Y*+WgmZQQLTHW#LMQG)MYd+-Tak9PD+y@SRlFD>#rg|u2uBc7^Eo2R5#;Nk sc&wqfkxHKrMYU40l%%>V!Z diff --git a/zomp/key/otpr/otpr.1.realm.pub.der b/zomp/key/otpr/otpr.1.realm.pub.der deleted file mode 100644 index a4df4cb9b6fa962bbbd555ad8b528d4ad389aceb..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2062 zcmV+p2=VtYf(Qx%f(QWs$#_sbM_lA3`Zv{ZlTrR)r@oRGPvR;Xd zv8HYpK9kr5jo%#yKtBJ21?fZ9l4@-Ngzn(8J-aYGGfr^B+oI!0u8b$Rj$Kl%-sngP zX`DtWk8+Hj4>`+nwX%UPMED$ zc`CccSD7}GyZQ8n;>X98z(!~2%+DmRgHF}@SPNX1@Kh*qQvSx#Tt}UysVD-6*8VOwcV!E2Uib|0{QT5BB!gZ| zArkQ>+`cAd3r&obc`dh)bm6o86p?>xzH#!$?<2!*? zn-uF)T=~#Ka%W3_G^KfJs{ob{W{6lXeNh{-nWKl1MNNPA@+9sC?XT33C2y*ptecc< zC0A4HH^8?MI>Eoo1Q5uEJSCr*Qf1&~;6vBO(GdguF)UUT4hfOrS=uJq``8(ShZ^DT zV|ge)C$RV@97+i}SG`SXUXImt&>^d{#TzkVDQ6Ib`t-YP&K>JT1%$PLZI#5r3$bgT zr8&2v>9*j4s{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-HsRZN(-K^$E$#5Ue%fR-+Fg{WohSe}Z@R3Ln4KQql sRdp>M(2%ki%p0K)%tT#GhZ%uSQhE^rl;rv(C96lz;ei_g0s{d60Ra=~`v3p{ literal 0 HcmV?d00001 diff --git a/zomp/lib/otpr/zx/0.1.0/make_zx b/zomp/lib/otpr/zx/0.1.0/make_zx new file mode 100755 index 0000000..1ca8077 --- /dev/null +++ b/zomp/lib/otpr/zx/0.1.0/make_zx @@ -0,0 +1,39 @@ +#! /usr/bin/env escript + +-mode(compile). + +main(Args) -> + true = code:add_patha("ebin"), + up_to_date = make:all(), + ok = lists:foreach(fun dispatch/1, Args), + halt(0). + + +dispatch("edoc") -> + ok = edoc(); +dispatch("dialyze") -> + ok = dialyze(); +dispatch("test") -> + ok = test(); +dispatch(Unknown) -> + ok = io:format("make_zx: Unknown directive: ~tp~n", [Unknown]), + halt(1). + + +edoc() -> + ok = io:format("EDOC: Writing docs...~n"), + edoc:application(zx, ".", []). + + +dialyze() -> + case dialyzer:run([{from, src_code}, {files_rec, ["./src"]}]) of + [] -> + io:format("Dialyzer found no errors and returned no warnings! Yay!~n"); + Warnings -> + Messages = [dialyzer:format_warning(W) || W <- Warnings], + lists:foreach(fun io:format/1, Messages) + end. + + +test() -> + io:format("TEST: If I only had a brain.~n"). diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx.erl b/zomp/lib/otpr/zx/0.1.0/src/zx.erl index 7f93cbb..0cc4b4d 100644 --- a/zomp/lib/otpr/zx/0.1.0/src/zx.erl +++ b/zomp/lib/otpr/zx/0.1.0/src/zx.erl @@ -29,7 +29,7 @@ option/0, host/0, key_id/0, key_name/0, key_data/0, - user/0, username/0, lower0_9/0, label/0, + user_id/0, user_name/0, lower0_9/0, label/0, package_meta/0]). -include("zx_logger.hrl"). @@ -46,7 +46,6 @@ -type version() :: {Major :: non_neg_integer() | z, Minor :: non_neg_integer() | z, Patch :: non_neg_integer() | z}. --type identifier() :: realm() | package() | package_id(). -type option() :: {string(), term()}. -type host() :: {string() | inet:ip_address(), inet:port_number()}. -type key_id() :: {realm(), key_name()}. @@ -1312,7 +1311,7 @@ connect_auth(Realm) -> -spec connect_auth(Socket, Realm, User, KeyID, Key) -> Result when Socket :: gen_tcp:socket(), Realm :: realm(), - User :: user(), + User :: user_id(), KeyID :: key_id(), Key :: term(), Result :: {ok, gen_tcp:socket()} @@ -1393,7 +1392,7 @@ confirm_auth(Socket) -> -spec prep_auth(Realm, RealmConf) -> {User, KeyID, Key} | no_return() when Realm :: realm(), RealmConf :: [term()], - User :: user(), + User :: user_id(), KeyID :: key_id(), Key :: term(). %% @private @@ -1790,7 +1789,7 @@ dialyze() -> %%% Create Realm & Sysop --spec create_user(realm(), username()) -> no_return(). +-spec create_user(realm(), user_name()) -> no_return(). %% @private %% Validate the realm and username provided, prompt the user to either select a keypair %% to use or generate a new one, and bundle a .zuser file for conveyance of the user diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_conf_sys.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_conf_sys.erl new file mode 100644 index 0000000..d487626 --- /dev/null +++ b/zomp/lib/otpr/zx/0.1.0/src/zx_conf_sys.erl @@ -0,0 +1,251 @@ +%%% @doc +%%% zx_conf_sys: An interface to etc/sys.conf +%%% +%%% It may seem overkill to write an interface module for a config file that only tracks +%%% five things, but scattering this all around the project is just a bit too l33t for +%%% an infrastructure project like ZX. +%%% +%%% Each exported function that is named after an attribute has two versions, one of +%%% arity-1 and one of arity-2. The arity-1 version is a "getter", and the arity-2 +%%% version is a "setter". Other functions deal with the data in a way that returns +%%% an answer and updates the state accordingly. +%%% +%%% Bad configuration data causes a reset to defaults so that the system can function. +%%% @end + +-module(zx_conf_sys). +-author("Craig Everett "). +-copyright("Craig Everett "). +-license("GPL-3.0"). + +-export([load/0, save/1, + timeout/1, timeout/2, + retries/1, retries/2, retry/1, retries_left/1, + maxconn/1, maxconn/2, + managed/1, managed/2, add_managed/2, rem_managed/2, + mirrors/1, mirrors/2, add_mirror/2, rem_mirror/2, next_mirror/1, + reset/0]). + +-export_type([data/0]). + +-include("zx_logger.hrl"). + + + +%%% Type Definitions + +-record(d, + {timeout = 5 :: pos_integer(), + retries = {0, 3} :: non_neg_integer(), + maxconn = 5 :: pos_integer(), + managed = sets:new() :: sets:set(zx:realm()), + mirrors = queue:new() :: queue:queue(zx:host())}). + +-opaque data() :: #d{}. + + + +%%% Interface functions + +-spec load() -> data(). +%% @doc +%% Read from etc/sys.conf and return a populated data() record if it exists, or +%% populate default values and write a new one if it does not. If a damaged sys.conf +%% is discovered it will be repaired. This function is side-effecty so should only +%% be called by zx_daemon and utility code. + +load() -> + case file:consult(path()) of + {ok, List} -> + populate_data(List); + {error, Reason} -> + ok = log(error, "Load etc/sys.conf failed with: ~tp", [Reason]), + Data = #d{}, + ok = save(Data), + Data + end. + + +populate_data(List) -> + Timeout = + case proplists:get_value(timeout, List, 5) of + V when is_integer(V) and V > 0 -> V; + _ -> 5 + end, + Retry = + case proplists:get_value(retry, List, 3) of + V when is_integer(V) and V > 0 -> V; + _ -> 3 + end, + MaxConn = + case proplists:get_value(maxconn, List, 5) of + V when is_integer(V) and V > 0 -> V; + _ -> 5 + end, + Managed = + case proplists:get_value(managed, List, []) of + V when is_list(V) -> sets:from_list(V); + _ -> sets:new() + end, + Mirrors = + case proplists:get_value(mirrors, List, []) of + V when is_list(V) -> queue:from_list(V); + _ -> queue:new() + end, + #d{timeout = Timeout, + retries = Retries, + maxconn = MaxConn, + managed = Managed, + mirrors = Mirrors}. + + +-spec save(data()) -> ok. +%% @doc +%% Save the current etc/sys.conf to disk. + +save(#d{timeout = Timeout, + retries = {_, Retries}, + maxconn = MaxConn, + managed = Managed, + mirrors = Mirrors}) -> + Terms = + [{timeout, Timeout}, + {retries, Retries}, + {maxconn, MaxConn}, + {managed, sets:to_list(Managed)}, + {mirrors, queue:to_list(Mirrors)}], + ok = zx_lib:write_terms(path(), Terms), + log(info, "Wrote etc/sys.conf"). + + +-spec timeout(data()) -> pos_integer(). +%% @doc +%% Return the timeout value. + +timeout(#d{timeout = Timeout}) -> + Timeout. + + +-spec timeout(Data, Value) -> NewData + when Data :: data(), + Value :: pos_integer(), + NewData :: data(). +%% @doc +%% Set the timeout attribute to a new value. + +timeout(Data, Value) + when is_integer(Value) and Value > 0 -> + Data#d{timeout = Value}. + + +-spec retries(data()) -> non_neg_integer(). +%% @doc +%% Return the retries value. + +retries(#d{retries = Retries}) -> + Retries. + + +-spec retries(Data, Value) -> NewData + when Data :: data(), + Value :: non_neg_integer(), + NewData :: data(). +%% @doc +%% Set the retries attribute to a new value. + +retries(Data = #d{retries = {Remaining, _}, Value) -> + when is_integer(Value) and Value >= 0 -> + Data#d{retries = {Remaining, Value}}. + + +-spec retry(Data) -> Result + when Data :: data(), + Result :: {ok, NewData} + | no_retries, + NewData :: data(). +%% @doc +%% Tell the caller whether there are any more retries remaining or return `ok' and +%% update the state. + +retry(#d{retries = {0, _}}) -> + no_retries; +retry(Data = #d{retries = {Remaining, Setting}}) -> + NewRemaining = Current - 1, + NewData = Data#d{retries = {NewRemaining, Setting}}, + {ok, NewData}. + + +-spec retries_left(data()) -> non_neg_integer(). +%% @doc +%% Return the number of retries remaining. + +retries_left(#d{retries = {Remaining, _}}) -> + Remaining. + + +-spec maxconn(data()) -> pos_integer(). +%% @doc +%% Return the value of maxconn. + +maxconn(#d{maxconn = MaxConn}) -> + MaxConn. + + +-spec maxconn(Data, Value) -> NewData + when Data :: data(), + Value :: pos_integer(), + NewData :: data(). +%% @doc +%% Set the value of maxconn. + +maxconn(Data, Value) + when is_integer(Value) and Value > 0 -> + Data#d{maxconn = Value}. + + +-spec managed(data()) -> list(zx:realm()). +%% @doc +%% Return the list of realms managed by the current node. + +managed(#d{managed = Managed}) -> + sets:to_list(Managed). + + +-spec managed(Data, List) -> NewData + when Data :: data(), + List :: [zx:realm()], + NewData :: data(). +%% @doc +%% Reset the set of managed realms entirely. +%% The realms must be configured on the current realm at a minimum. + +managed(Data, List) -> + Scrubbed = scrub_realms(List), + NewManaged = sets:from_list(Scrubbed), + Data#d{managed = NewManaged}. + + +scrub_realms(List) -> + %... + []. + + +-spec add_managed(Data, Realm) -> {ok, + when Data :: data(), + Realm :: zx:realm(), + NewData :: data(). +%% @doc +%% Add a new realm to the list of managed realms. The new realm must be configured on +%% the current node. + +add_managed(Data = #d{managed = Managed}, Realm) -> + case zx_lib:valid_lower0_9(Realm) of + + + +-spec path() -> file:filename(). +%% @private +%% Return the path to $ZOMP_DIR/etc/sys.conf. + +path() -> + filename:join(zx_lib:path(etc), "sys.conf"). diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_conn.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_conn.erl index 119c27e..1c84891 100644 --- a/zomp/lib/otpr/zx/0.1.0/src/zx_conn.erl +++ b/zomp/lib/otpr/zx/0.1.0/src/zx_conn.erl @@ -266,27 +266,49 @@ handle_message(Socket, Bin) -> handle_request(Socket, Action) -> ok = zx_net:send(Socket, Action), - case element(1, Action) of - list -> - do_list(Action, Socket); - latest -> - do_latest(Action, Socket); - fetch -> - do_fetch(Action, Socket); - key -> - do_key(Action, Socket); - pending -> - do_pending(Action, Socket); - packagers -> - do_packagers(Action, Socket); - maintainers -> - do_maintainers(Action, Socket); - sysops -> - do_sysops(Action, Socket) + Response = + case element(1, Action) of + list -> + do_list(Action, Socket); + latest -> + do_latest(Action, Socket); + fetch -> + do_fetch(Action, Socket); + key -> + do_key(Action, Socket); + pending -> + do_pending(Action, Socket); + packagers -> + do_packagers(Action, Socket); + maintainers -> + do_maintainers(Action, Socket); + sysops -> + do_sysops(Action, Socket) end, handle_response(Socket, Response). +handle_fetch(_, _) -> {error, nyi}. + +handle_query(_, _) -> {error, nyi}. + +do_list(_, _) -> {error, nyi}. + +do_latest(_, _) -> {error, nyi}. + +do_fetch(_, _) -> {error, nyi}. + +do_key(_, _) -> {error, nyi}. + +do_pending(_, _) -> {error, nyi}. + +do_packagers(_, _) -> {error, nyi}. + +do_maintainers(_, _) -> {error, nyi}. + +do_sysops(_, _) -> {error, nyi}. + + handle_response(Socket, Command) -> receive @@ -305,21 +327,21 @@ interpret_response(Socket, ping, Command) -> handle_response(Socket, Command); interpret_response(Socket, {sub, Channel, Message}, Command) -> ok = zx_daemon:notify(Channel, Message), - handle_response(Socket, Command); -interpret_response(Socket, {update, Message}, Command) -> -interpret_response(Socket, Response, list) -> -interpret_response(Socket, Response, latest) -> -interpret_response(Socket, Response, fetch) -> -interpret_response(Socket, Response, key) -> -interpret_response(Socket, Response, pending) -> -interpret_response(Socket, Response, packagers) -> -interpret_response(Socket, Response, maintainers) -> -interpret_response(Socket, Response, sysops) -> - - - - case element(1, Action) of - end, + handle_response(Socket, Command). +%interpret_response(Socket, {update, Message}, Command) -> +%interpret_response(Socket, Response, list) -> +%interpret_response(Socket, Response, latest) -> +%interpret_response(Socket, Response, fetch) -> +%interpret_response(Socket, Response, key) -> +%interpret_response(Socket, Response, pending) -> +%interpret_response(Socket, Response, packagers) -> +%interpret_response(Socket, Response, maintainers) -> +%interpret_response(Socket, Response, sysops) -> +% +% +% +% case element(1, Action) of +% end, -spec fetch(Socket, PackageID) -> Result diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_daemon.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_daemon.erl index cc78934..86296c1 100644 --- a/zomp/lib/otpr/zx/0.1.0/src/zx_daemon.erl +++ b/zomp/lib/otpr/zx/0.1.0/src/zx_daemon.erl @@ -5,13 +5,13 @@ %%% %%% The daemon resides in the background once started and awaits query requests and %%% subscriptions from other processes. The daemon is only capable of handling -%%% unprivileged (user) actions. +%%% unprivileged ("leaf") actions. %%% %%% %%% Discrete state and local abstract data types %%% -%%% The daemon must keep track of requestors, subscribers, and zx_conn processes by -%%% using monitors. Because these various types of clients are found in different +%%% The daemon must keep track of requestors, subscribers, peers, and zx_conn processes +%%% by using monitors. Because these various types of clients are found in different %%% structures the monitors are maintained in a data type called monitor_index(), %%% shortened to "mx" throughout the module. This structure is treated as an opaque %%% data type and is handled by a set of functions defined toward the end of the module @@ -20,18 +20,23 @@ %%% Node connections (zx_conn processes) must also be tracked for status and realm %%% availability. This is done using a type called conn_index(), shortened to "cx" %%% throughout the module. conn_index() is treated as an abstract, opaque datatype -%%% throughout the module, and is handled via a set of cx_*/N functions (after the +%%% throughout the module and is handled via a set of cx_*/N functions (after the %%% mx_*/N section). %%% %%% Do NOT directly access data within these structures, use (or write) an accessor -%%% function that does what you want. Accessor functions MUST be pure with the sole -%%% exception of the mx_* functions that create and destroy monitors. +%%% function that does what you want. Accessor functions MUST be pure with the +%%% exception of mx_add_monitor/3 and mx_del_monitor/3 that create and destroy +%%% monitors. %%% %%% %%% Connection handling %%% %%% The daemon is structured as a service manager in a service -> worker structure. %%% http://zxq9.com/archives/1311 +%%% This allows it to abstract the servicing of tasks at a high level, making it +%%% unnecessary for other processes to talk directly to any zx_conn processes or care +%%% whether the current runtime is the host's zx proxy or a peer instance. +%%% %%% It is in charge of the high-level task of servicing requested actions and returning %%% responses to callers as well as mapping successful connections to configured realms %%% and repairing failed connections to nodes that reduce availability of configured @@ -40,8 +45,9 @@ %%% When the zx_daemon is started it checks local configuration and cache files to %%% determine what realms must be available and what cached Zomp nodes it is aware of. %%% It populates the CX (conn_index(), mentioned above) with realm config and host -%%% cache data, and then immediately initiates three connection attempts to cached -%%% nodes for each realm configured if possible (see init_connections/0). +%%% cache data, and then initiates a connection attempt to each configured prime node +%%% and up to maxconn connection attempts to cached nodes for each realm as well. +%%% (See init_connections/0). %%% %%% Once connection attempts have been initiated the daemon waits in receive for %%% either a connection report (success or failure) or an action request from @@ -83,6 +89,7 @@ %%% should not be cases where the work queue stalls on active requests. %%% %%% Requestors sending either download or realm query requests are given a reference +%%% (an integer, not an Erlang reference, as the message may cross node boundaries) %%% to match on for receipt of their result messages or to be used to cancel the %%% requested work (timeouts are handled by the caller, not by the daemon). %%% @@ -105,7 +112,7 @@ %%% within a host system. %%% %%% When zx starts the daemon will attempt an exclusive write to a lock file called -%%% $ZOMP_HOME/zomp.lock using file:open(LockFile, [exclusive]), writing a system +%%% $ZOMP_DIR/john.locke using file:open(LockFile, [exclusive]), writing a system %%% timestamp. If the write succeeds then the daemon knows it is the master for the %%% system and will begin initiating connections as described above as well as open a %%% local socket to listen for other zx instances which will need to proxy their own @@ -140,7 +147,7 @@ -export([pass_meta/3, subscribe/1, unsubscribe/1, list/0, list/1, list/2, list/3, latest/1, - fetch/1, key/1, + fetch_zsp/1, fetch_key/1, pending/1, packagers/1, maintainers/1, sysops/1]). -export([report/1, result/2, notify/2]). -export([start_link/0, stop/0]). @@ -162,15 +169,16 @@ %%% Type Definitions -record(s, - {meta = none :: none | zx:package_meta(), - home = none :: none | file:filename(), - argv = none :: none | [string()], - id = 0 :: id(), - actions = [] :: [request()], - requests = maps:new() :: requests(), - dropped = maps:new() :: requests(), - mx = mx_new() :: monitor_index(), - cx = cx_load() :: conn_index()}). + {meta = none :: none | zx:package_meta(), + home = none :: none | file:filename(), + argv = none :: none | [string()], + sys_conf = zx_conf_sys:load() :: zx_conf_sys:data(), + id = 0 :: id(), + actions = [] :: [request()], + requests = maps:new() :: requests(), + dropped = maps:new() :: requests(), + mx = mx_new() :: monitor_index(), + cx = cx_load() :: conn_index()}). -record(cx, @@ -438,7 +446,7 @@ latest({Realm, Name, Version}) -> request({latest, Realm, Name, Version}). --spec fetch(PackageID) -> {ok, RequestID} +-spec fetch_zsp(PackageID) -> {ok, RequestID} when PackageID :: zx:package_id(), RequestID :: integer(). %% @doc diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_lib.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_lib.erl index 935821c..afd1665 100644 --- a/zomp/lib/otpr/zx/0.1.0/src/zx_lib.erl +++ b/zomp/lib/otpr/zx/0.1.0/src/zx_lib.erl @@ -14,7 +14,8 @@ -copyright("Craig Everett "). -license("GPL-3.0"). --export([zomp_home/0, find_zomp_home/0, +-export([zomp_dir/0, find_zomp_dir/0, + path/1, path/2, path/3, hosts_cache_file/1, get_prime/1, realm_meta/1, read_project_meta/0, read_project_meta/1, read_package_meta/1, write_project_meta/1, write_project_meta/2, @@ -33,41 +34,92 @@ %%% Functions -zomp_home() -> - case os:getenv("ZOMP_HOME") of +-spec zomp_dir() -> file:filename(). +%% @doc +%% Return the path to the Zomp/ZX installation directory. + +zomp_dir() -> + case os:getenv("ZOMP_DIR") of false -> - ZompHome = find_zomp_home(), - true = os:putenv("ZOMP_HOME", ZompHome), - ZompHome; - ZompHome -> - ZompHome + ZompDir = find_zomp_dir(), + true = os:putenv("ZOMP_DIR", ZompDir), + ZompDir; + ZompDir -> + ZompDir end. --spec find_zomp_home() -> file:filename(). +-spec find_zomp_dir() -> file:filename(). %% @private %% Check the host OS and return the absolute path to the zomp filesystem root. -find_zomp_home() -> +find_zomp_dir() -> case os:type() of {unix, _} -> Home = os:getenv("HOME"), Dir = "zomp", filename:join(Home, Dir); {win32, _} -> - Drive = os:getenv("HOMEDRIVE"), - Path = os:getenv("HOMEPATH"), + Home = os:getenv("LOCALAPPDATA"), Dir = "zomp", - filename:join([Drive, Path, Dir]) + filename:join(Home, Dir) end. +-spec path(Type) -> Result + when Type :: etc + | var + | tmp + | log + | lib, + Result :: file:filename(). +%% @doc +%% Return the top-level path of the given type in the Zomp/ZX system. + +path(etc) -> filename:join(zomp_dir(), "etc"); +path(var) -> filename:join(zomp_dir(), "var"); +path(tmp) -> filename:join(zomp_dir(), "tmp"); +path(log) -> filename:join(zomp_dir(), "log"); +path(lib) -> filename:join(zomp_dir(), "lib"). + + +-spec path(Type, Realm) -> Result + when Type :: etc + | var + | tmp + | log + | lib, + Realm :: zx:realm(), + Result :: file:filename(). +%% @doc +%% Return the realm-level path of the given type in the Zomp/ZX system. + +path(Type, Realm) -> + filename:join(path(Type), Realm). + + +-spec path(Type, Realm, Name) -> Result + when Type :: etc + | var + | tmp + | log + | lib, + Realm :: zx:realm(), + Name :: zx:name(), + Result :: file:filename(). +%% @doc +%% Return the package-level path of the given type in the Zomp/ZX system. + +path(Type, Realm, Name) -> + filename:join([path(Type), Realm, Name]). + + -spec hosts_cache_file(zx:realm()) -> file:filename(). %% @private %% Given a Realm name, construct a realm's .hosts filename and return it. hosts_cache_file(Realm) -> - filename:join(zomp_home(), Realm ++ ".hosts"). + filename:join(zomp_dir(), Realm ++ ".hosts"). -spec get_prime(Realm) -> Result @@ -99,7 +151,7 @@ get_prime(Realm) -> %% the file. realm_meta(Realm) -> - RealmFile = filename:join(zomp_home(), Realm ++ ".realm"), + RealmFile = filename:join(zomp_dir(), Realm ++ ".realm"), file:consult(RealmFile). @@ -139,7 +191,7 @@ read_project_meta(Dir) -> read_package_meta({Realm, Name, Version}) -> {ok, VersionString} = version_to_string(Version), - Path = filename:join([zomp_home(), "lib", Realm, Name, VersionString]), + Path = filename:join([zomp_dir(), "lib", Realm, Name, VersionString]), read_project_meta(Path). @@ -449,7 +501,7 @@ package_dir({Realm, Name, Version = {X, Y, Z}}) when is_integer(X), is_integer(Y), is_integer(Z) -> {ok, PackageDir} = package_string({Realm, Name}), {ok, VersionDir} = version_to_string(Version), - filename:join([zomp_home(), "lib", PackageDir, VersionDir]). + filename:join([zomp_dir(), "lib", PackageDir, VersionDir]). -spec package_dir(Prefix, Package) -> PackageDataDir @@ -461,7 +513,7 @@ package_dir({Realm, Name, Version = {X, Y, Z}}) package_dir(Prefix, {Realm, Name}) -> PackageString = package_string({Realm, Name, {z, z, z}}), - filename:join([zomp_home(), Prefix, PackageString]). + filename:join([zomp_dir(), Prefix, PackageString]). -spec namify_zrp(PackageID) -> ZrpFileName @@ -568,5 +620,5 @@ realm_conf(Realm) -> %% Load the config for the given realm or halt with an error. load_realm_conf(Realm) -> - Path = filename:join(zx_lib:zomp_home(), realm_conf(Realm)), + Path = filename:join(zomp_dir(), realm_conf(Realm)), file:consult(Path). diff --git a/zomp/lib/otpr/zx/0.1.0/zmake b/zomp/lib/otpr/zx/0.1.0/zmake deleted file mode 100755 index 75f3a21..0000000 --- a/zomp/lib/otpr/zx/0.1.0/zmake +++ /dev/null @@ -1,48 +0,0 @@ -#! /usr/bin/env escript - --mode(compile). - -main(Args) -> - ok = make(), - ok = lists:foreach(fun dispatch/1, Args), - halt(0). - - -dispatch("edoc") -> - ok = edoc(); -dispatch("dialyze") -> - ok = dialyze(); -dispatch("test") -> - ok = test(); -dispatch(Unknown) -> - ok = io:format("zmake: Unknown directive: ~tp~n", [Unknown]), - halt(1). - - -make() -> - true = code:add_patha("ebin"), - up_to_date = make:all(), - halt(0). - - -edoc() -> - ok = io:format("EDOC: Writing docs...~n"), - ok = edoc:application(zomp, ".", []), - halt(0). - - -dialyze() -> - ok = - case dialyzer:run([{from, src_code}, {files_rec, ["./src"]}]) of - [] -> - io:format("Dialyzer found no errors and returned no warnings! Yay!~n"); - Warnings -> - Messages = [dialyzer:format_warning(W) || W <- Warnings], - lists:foreach(fun io:format/1, Messages) - end, - halt(0). - - -test() -> - ok = io:format("TEST: If I only had a brain.~n"), - halt(0). diff --git a/zomp/otpr.realm b/zomp/otpr.realm deleted file mode 100644 index c0c267c..0000000 --- a/zomp/otpr.realm +++ /dev/null @@ -1,20 +0,0 @@ -{realm,"otpr"}. -{revision,0}. -{prime,{"otpr.psychobitch.party",11311}}. -{sysops,[{{"otpr","zxq9"},["zxq9.1"],"zxq9@zxq9.com","Craig Everett"}]}. -{realm_keys,[{{"otpr","otpr.1.realm"}, - realm, - {realm,"otpr"}, - <<206,129,232,15,23,149,65,167,9,157,25,210,91,113,55,56,14,12, - 153,218,37,83,148,3,89,208,61,43,95,89,51,228,245,78,115,52,15, - 82,23,100,53,189,136,19,104,58,222,216,184,87,75,231,151,18,90, - 243,115,160,244,32,232,71,57,95>>, - {{2018,1,10},{6,36,41}}}]}. -{package_keys,[{{"otpr","otpr.1.package"}, - package, - {realm,"otpr"}, - <<77,10,171,53,73,87,21,251,153,215,83,119,244,217,207,77,44, - 210,177,77,46,86,52,232,16,64,23,109,214,94,207,140,12,145, - 23,130,151,151,37,82,61,240,82,146,142,199,95,114,77,219,148, - 200,140,85,128,77,110,142,179,137,169,188,223,192>>, - {{2018,1,10},{6,36,41}}}]}. diff --git a/zomp/zx b/zomp/zx index c93a206..8f3cea1 100755 --- a/zomp/zx +++ b/zomp/zx @@ -1,13 +1,10 @@ #!/bin/sh -set -x - ZOMP_DIR="$HOME/zomp" -ORIGIN="$(pwd)" -VERSION="$(ls $ZOMP_DIR/lib/otpr/zx/ | sort --field-separator=. --reverse | head --lines=1)" +VERSION=$(cat "$ZOMP_DIR/etc/version.txt") ZX_DIR="$ZOMP_DIR/lib/otpr/zx/$VERSION" -cd "$ZX_DIR" -./zmake -cd "$ZOMP_DIR" +pushd "$ZX_DIR" +./make_zx +popd erl -pa "$ZX_DIR/ebin" -run zx start $@ diff --git a/zomp/zx.cmd b/zomp/zx.cmd new file mode 100644 index 0000000..a7ed5a3 --- /dev/null +++ b/zomp/zx.cmd @@ -0,0 +1,9 @@ +REM Prepare the environment for ZX and launch it + +set ZOMP_DIR="%LOCALAPPDATA%\zomp" +set VERSION=<"%ZOMP_DIR%\etc\version.txt" +set ZX_DIR="%ZOMP_DIR%\lib\otpr\zx\%VERSION%" +pushd "%ZX_DIR%" +escript.exe make_zx +popd +erl.exe -pa "%ZX_DIR%/ebin" -run zx start "%*" diff --git a/zx_dev b/zx_dev index 6a1d577..596b40b 100755 --- a/zx_dev +++ b/zx_dev @@ -1,13 +1,11 @@ -#!/bin/sh +#!/bin/bash -set -x +ZX_DEV_ROOT=$(dirname $BASH_SOURCE) +ZOMP_DIR="$ZX_DEV_ROOT/zomp" +VERSION=$(cat "$ZOMP_DIR/etc/version.txt") +ZX_DIR="$ZOMP_DIR/lib/otpr/zx/$VERSION" -ZOMP_DIR="$HOME/vcs/zx/zomp" -ORIGIN="$(pwd)" -VERSION="$(ls $ZOMP_DIR/lib/otpr-zx/ | sort --field-separator=. --reverse | head --lines=1)" -ZX_DIR="$ZOMP_DIR/lib/otpr-zx/$VERSION" - -cd "$ZX_DIR" -./zmake -cd "$ZOMP_DIR" +pushd "$ZX_DIR" +./make_zx +popd erl -pa "$ZX_DIR/ebin" -run zx start $@ From bd6c7472070a9dbaa0b3341ccf2cae7ec5c067f6 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Mon, 28 May 2018 14:04:38 +0900 Subject: [PATCH 54/55] foo --- zomp/etc/sys.conf | 10 +- zomp/lib/otpr/zx/0.1.0/src/zx.erl | 1119 +++----------------- zomp/lib/otpr/zx/0.1.0/src/zx_auth.erl | 452 ++++++++ zomp/lib/otpr/zx/0.1.0/src/zx_conf_sys.erl | 152 ++- zomp/lib/otpr/zx/0.1.0/src/zx_conn.erl | 16 +- zomp/lib/otpr/zx/0.1.0/src/zx_daemon.erl | 6 +- zomp/lib/otpr/zx/0.1.0/src/zx_key.erl | 280 +++++ zomp/lib/otpr/zx/0.1.0/src/zx_lib.erl | 92 +- zomp/lib/otpr/zx/0.1.0/src/zx_tty.erl | 101 ++ zomp/zx | 6 +- zx_dev | 14 +- 11 files changed, 1194 insertions(+), 1054 deletions(-) create mode 100644 zomp/lib/otpr/zx/0.1.0/src/zx_auth.erl create mode 100644 zomp/lib/otpr/zx/0.1.0/src/zx_key.erl create mode 100644 zomp/lib/otpr/zx/0.1.0/src/zx_tty.erl diff --git a/zomp/etc/sys.conf b/zomp/etc/sys.conf index aeeb3d0..075c2dd 100644 --- a/zomp/etc/sys.conf +++ b/zomp/etc/sys.conf @@ -1,5 +1,5 @@ -{timeout, 5}. -{retry, 3}. -{maxconn, 5}. -{managed, []}. -{mirrors, []}. +{timeout,5}. +{retries,3}. +{maxconn,5}. +{managed,[]}. +{mirrors,[]}. diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx.erl b/zomp/lib/otpr/zx/0.1.0/src/zx.erl index 0cc4b4d..977b688 100644 --- a/zomp/lib/otpr/zx/0.1.0/src/zx.erl +++ b/zomp/lib/otpr/zx/0.1.0/src/zx.erl @@ -19,17 +19,17 @@ -license("GPL-3.0"). --export([do/1]). +-export([start/1]). -export([subscribe/1, unsubscribe/0]). --export([start/0, stop/0]). --export([start/2, stop/1]). +-export([start/2, stop/1, stop/0]). +-export([error_exit/2, error_exit/3]). -export_type([serial/0, package_id/0, package/0, realm/0, name/0, version/0, identifier/0, - option/0, host/0, key_id/0, key_name/0, key_data/0, - user_id/0, user_name/0, lower0_9/0, label/0, + user_id/0, user_name/0, contact_info/0, user_data/0, + lower0_9/0, label/0, package_meta/0]). -include("zx_logger.hrl"). @@ -46,7 +46,6 @@ -type version() :: {Major :: non_neg_integer() | z, Minor :: non_neg_integer() | z, Patch :: non_neg_integer() | z}. --type option() :: {string(), term()}. -type host() :: {string() | inet:ip_address(), inet:port_number()}. -type key_id() :: {realm(), key_name()}. -type key_name() :: lower0_9(). @@ -70,67 +69,52 @@ %%% Command Dispatch --spec do(Args) -> no_return() +-spec start(Args) -> no_return() when Args :: [string()]. %% Dispatch work functions based on the nature of the input arguments. -do(["help"]) -> +start(["help"]) -> usage_exit(0); -do(["run", PackageString | Args]) -> +start(["run", PackageString | Args]) -> + ok = start(), run(PackageString, Args); -do(["runlocal" | ArgV]) -> +start(["runlocal" | ArgV]) -> + ok = start(), run_local(ArgV); -do(["init", "app", PackageString]) -> +start(["init", "app", PackageString]) -> initialize(app, PackageString); -do(["init", "lib", PackageString]) -> +start(["init", "lib", PackageString]) -> initialize(lib, PackageString); -do(["install", PackageFile]) -> +start(["install", PackageFile]) -> + ok = start(), assimilate(PackageFile); -do(["set", "dep", PackageString]) -> +start(["set", "dep", PackageString]) -> set_dep(PackageString); -do(["set", "version", VersionString]) -> +start(["set", "version", VersionString]) -> set_version(VersionString); -do(["list", "realms"]) -> +start(["list", "realms"]) -> list_realms(); -do(["list", "packages", Realm]) -> +start(["list", "packages", Realm]) -> + ok = start(), list_packages(Realm); -do(["list", "versions", PackageName]) -> +start(["list", "versions", PackageName]) -> + ok = start(), list_versions(PackageName); -do(["list", "pending", PackageName]) -> - list_pending(PackageName); -do(["list", "resigns", Realm]) -> - list_resigns(Realm); -do(["add", "realm", RealmFile]) -> +start(["add", "realm", RealmFile]) -> add_realm(RealmFile); -do(["add", "package", PackageName]) -> - add_package(PackageName); -do(["add", "packager", Package, UserName]) -> - add_packager(Package, UserName); -do(["add", "maintainer", Package, UserName]) -> - add_maintainer(Package, UserName); -do(["review", PackageString]) -> - review(PackageString); -do(["approve", PackageString]) -> - PackageID = zx_lib:package_id(PackageString), - approve(PackageID); -do(["reject", PackageString]) -> - PackageID = zx_lib:package_id(PackageString), - reject(PackageID); -do(["resign", PackageString]) -> - resign(PackageString); -do(["drop", "dep", PackageString]) -> +start(["drop", "dep", PackageString]) -> PackageID = zx_lib:package_id(PackageString), drop_dep(PackageID); -do(["drop", "key", KeyID]) -> +start(["drop", "key", KeyID]) -> drop_key(KeyID); -do(["drop", "realm", Realm]) -> +start(["drop", "realm", Realm]) -> drop_realm(Realm); -do(["verup", Level]) -> +start(["verup", Level]) -> verup(Level); -do(["package"]) -> +start(["package"]) -> {ok, TargetDir} = file:get_cwd(), package(TargetDir); -do(["package", TargetDir]) -> +start(["package", TargetDir]) -> case filelib:is_dir(TargetDir) of true -> package(TargetDir); @@ -138,57 +122,47 @@ do(["package", TargetDir]) -> ok = log(error, "Target directory ~tp does not exist!", [TargetDir]), halt(22) end; -do(["submit", PackageFile]) -> - submit(PackageFile); -do(["dialyze"]) -> +start(["dialyze"]) -> dialyze(); -do(["create", "user", Realm, Name]) -> +start(["create", "user", Realm, Name]) -> create_user(Realm, Name); -do(["create", "keypair"]) -> - create_keypair(); -do(["create", "plt"]) -> +start(["create", "keypair"]) -> + zx_key:create_keypair(); +start(["create", "plt"]) -> create_plt(); -do(["create", "realm"]) -> +start(["create", "realm"]) -> create_realm(); -do(["create", "realmfile", Realm]) -> +start(["create", "realmfile", Realm]) -> create_realmfile(Realm); -do(["create", "sysop"]) -> - create_sysop(); -do(_) -> +start(["list", "pending", PackageName]) -> + zx_auth:list_pending(PackageName); +start(["list", "resigns", Realm]) -> + zx_auth:list_resigns(Realm); +start(["submit", PackageFile]) -> + zx_auth:submit(PackageFile); +start(["review", PackageString]) -> + zx_auth:review(PackageString); +start(["approve", PackageString]) -> + PackageID = zx_lib:package_id(PackageString), + zx_auth:approve(PackageID); +start(["reject", PackageString]) -> + PackageID = zx_lib:package_id(PackageString), + zx_auth:reject(PackageID); +start(["accept", PackageString]) -> + zx_auth:accept(PackageString); +start(["add", "packager", Package, UserName]) -> + zx_auth:add_packager(Package, UserName); +start(["add", "maintainer", Package, UserName]) -> + zx_auth:add_maintainer(Package, UserName); +start(["add", "sysop", Package, UserName]) -> + zx_auth:add_sysop(Package, UserName); +start(["add", "package", PackageName]) -> + zx_auth:add_package(PackageName); +start(_) -> usage_exit(22). -%%% Daemon Controls - --spec subscribe(package()) -> ok | {error, Reason :: term()}. -%% @doc -%% Initiates the zx_daemon and instructs it to subscribe to a package. -%% -%% Any events in the Zomp network that apply to the subscribed package will be -%% forwarded to the process that originally called subscribe/1. How the original -%% caller reacts to these notifications is up to the author -- not reply or "ack" -%% is expected. -%% -%% Package subscriptions can be used as the basis for user notification of updates, -%% automatic upgrade restarts, package catalog tracking, etc. - -subscribe(Package) -> - case application:start(?MODULE, normal) of - ok -> zx_daemon:subscribe(Package); - Error -> Error - end. - - --spec unsubscribe() -> ok | {error, Reason :: term()}. -%% @doc -%% Unsubscribes from package updates. - -unsubscribe() -> - zx_daemon:unsubscribe(). - - - %%% Application Start/Stop -spec start() -> ok | {error, Reason :: term()}. @@ -241,6 +215,36 @@ stop(_) -> +%%% Daemon Controls + +-spec subscribe(package()) -> ok | {error, Reason :: term()}. +%% @doc +%% Initiates the zx_daemon and instructs it to subscribe to a package. +%% +%% Any events in the Zomp network that apply to the subscribed package will be +%% forwarded to the process that originally called subscribe/1. How the original +%% caller reacts to these notifications is up to the author -- not reply or "ack" +%% is expected. +%% +%% Package subscriptions can be used as the basis for user notification of updates, +%% automatic upgrade restarts, package catalog tracking, etc. + +subscribe(Package) -> + case application:start(?MODULE, normal) of + ok -> zx_daemon:subscribe(Package); + Error -> Error + end. + + +-spec unsubscribe() -> ok | {error, Reason :: term()}. +%% @doc +%% Unsubscribes from package updates. + +unsubscribe() -> + zx_daemon:unsubscribe(). + + + %%% Execution of application -spec run(Identifier, RunArgs) -> no_return() @@ -264,7 +268,7 @@ stop(_) -> %% procedure the runtime will halt with an error message. run(Identifier, RunArgs) -> - ok = file:set_cwd(zx_lib:zomp_home()), + ok = file:set_cwd(zx_lib:zomp_dir()), ok = start(), FuzzyID = case zx_lib:package_id(Identifier) of @@ -299,7 +303,7 @@ run_local(RunArgs) -> PackageID = maps:get(package_id, Meta), ok = build(), {ok, Dir} = file:get_cwd(), - ok = file:set_cwd(zx_lib:zomp_home()), + ok = file:set_cwd(zx_lib:zomp_dir()), ok = start(), execute(PackageID, Meta, Dir, RunArgs). @@ -435,20 +439,20 @@ initialize(Type, PackageString) -> %% contents. assimilate(PackageFile) -> - Files = extract_zrp_or_die(PackageFile), + Files = zx_lib:extract_zsp_or_die(PackageFile), {ok, CWD} = file:get_cwd(), - ok = file:set_cwd(zx_lib:zomp_home()), + ok = file:set_cwd(zx_lib:zomp_dir()), {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), Meta = binary_to_term(MetaBin), PackageID = maps:get(package_id, Meta), TgzFile = zx_lib:namify_tgz(PackageID), {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files), {KeyID, Signature} = maps:get(sig, Meta), - {ok, PubKey} = loadkey(public, KeyID), + {ok, PubKey} = zx_key:load(public, KeyID), ok = case public_key:verify(TgzData, sha512, Signature, PubKey) of true -> - ZrpPath = filename:join("zrp", zx_lib:namify_zrp(PackageID)), + ZrpPath = filename:join("zsp", zx_lib:namify_zsp(PackageID)), file:copy(PackageFile, ZrpPath); false -> error_exit("Bad package signature: ~ts", [PackageFile], ?LINE) @@ -659,10 +663,7 @@ update_version(Realm, Name, OldVersion, NewVersion, OldMeta) -> %% stdout and the program will exit. list_realms() -> - Pattern = filename:join(zx_lib:zomp_home(), "*.realm"), - RealmFiles = filelib:wildcard(Pattern), - Realms = [filename:basename(RF, ".realm") || RF <- RealmFiles], - ok = lists:foreach(fun(R) -> io:format("~ts~n", [R]) end, Realms), + ok = lists:foreach(fun(R) -> io:format("~ts~n", [R]) end, zx_lib:list_realms()), halt(0). @@ -729,74 +730,6 @@ list_versions(PackageName) -> end. --spec list_pending(PackageName :: string()) -> no_return(). -%% @private -%% List the versions of a package that are pending review. The package name is input by -%% the user as a string of the form "otpr-zomp" and the output is a list of full -%% package IDs, printed one per line to stdout (like "otpr-zomp-3.2.2"). - -list_pending(PackageName) -> - Package = {Realm, Name} = - case zx_lib:package_id(PackageName) of - {ok, {R, N, {z, z, z}}} -> - {R, N}; - {error, invalid_package_string} -> - error_exit("~tp is not a valid package name.", [PackageName], ?LINE) - end, - ok = start(), - case zx_daemon:list_pending(Package) of - {ok, []} -> - Message = "Package ~ts has no versions pending.", - ok = log(info, Message, [PackageName]), - halt(0); - {ok, Versions} -> - Print = - fun(Version) -> - {ok, PackageString} = zx_lib:package_string({Realm, Name, Version}), - io:format("~ts~n", [PackageString]) - end, - ok = lists:foreach(Print, Versions), - halt(0); - {error, bad_realm} -> - error_exit("Bad realm name.", ?LINE); - {error, bad_package} -> - error_exit("Bad package name.", ?LINE); - {error, network} -> - Message = "Network issues are preventing connection to the realm.", - error_exit(Message, ?LINE) - end. - - --spec list_resigns(realm()) -> no_return(). -%% @private -%% List the package ids of all packages waiting in the resign queue for the given realm, -%% printed to stdout one per line. - -list_resigns(Realm) -> - ok = start(), - case zx_daemon:list_resigns(Realm) of - {ok, []} -> - Message = "No packages pending signature in ~tp.", - ok = log(info, Message, [Realm]), - halt(0); - {ok, PackageIDs} -> - Print = - fun(PackageID) -> - {ok, PackageString} = zx_lib:package_string(PackageID), - io:format("~ts~n", [PackageString]) - end, - ok = lists:foreach(Print, PackageIDs), - halt(0); - {error, bad_realm} -> - error_exit("Bad realm name.", ?LINE); - {error, no_realm} -> - error_exit("Realm \"~ts\" is not configured.", ?LINE); - {error, network} -> - Message = "Network issues are preventing connection to the realm.", - error_exit(Message, ?LINE) - end. - - %%% Add realm @@ -829,7 +762,7 @@ add_realm(Path) -> Data :: binary(). add_realm(Path, Data) -> - case erl_tar:extract({binary, Data}, [compressed, {cwd, zx_lib:zomp_home()}]) of + case erl_tar:extract({binary, Data}, [compressed, {cwd, zx_lib:zomp_dir()}]) of ok -> {Realm, _} = string:take(filename:basename(Path), ".", true), ok = log(info, "Realm ~ts is now visible to this system.", [Realm]), @@ -841,124 +774,6 @@ add_realm(Path, Data) -> end. --spec add_package(PackageName) -> no_return() - when PackageName :: package(). -%% @private -%% A sysop command that adds a package to a realm operated by the caller. - -add_package(PackageName) -> - ok = file:set_cwd(zx_lib:zomp_home()), - case zx_lib:package_id(PackageName) of - {ok, {Realm, Name, {z, z, z}}} -> - add_package(Realm, Name); - _ -> - error_exit("~tp is not a valid package name.", [PackageName], ?LINE) - end. - - --spec add_package(Realm, Name) -> no_return() - when Realm :: realm(), - Name :: name(). - -add_package(Realm, Name) -> - Socket = connect_auth_or_die(Realm), - ok = send(Socket, {add_package, {Realm, Name}}), - ok = recv_or_die(Socket), - ok = log(info, "\"~ts-~ts\" added successfully.", [Realm, Name]), - halt(0). - - -add_packager(Package, UserName) -> - ok = log(info, "Would add ~ts to packagers for ~160tp now.", [UserName, Package]), - halt(0). - - -add_maintainer(Package, UserName) -> - ok = log(info, "Would add ~ts to maintainer for ~160tp now.", [UserName, Package]), - halt(0). - - -review(PackageString) -> - PackageID = {Realm, _, _} = zx_lib:package_id(PackageString), - Socket = connect_auth_or_die(Realm), - ok = send(Socket, {review, PackageID}), - {ok, ZrpBin} = recv_or_die(Socket), - ok = send(Socket, ok), - ok = disconnect(Socket), - {ok, Files} = erl_tar:extract({binary, ZrpBin}, [memory]), - {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), - Meta = binary_to_term(MetaBin, [safe]), - PackageID = maps:get(package_id, Meta), - {KeyID, Signature} = maps:get(sig, Meta), - {ok, PubKey} = loadkey(public, KeyID), - TgzFile = PackageString ++ ".tgz", - {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files), - ok = verify(TgzData, Signature, PubKey), - ok = - case file:make_dir(PackageString) of - ok -> - log(info, "Will unpack to directory ./~ts", [PackageString]); - {error, Error} -> - Message = "Creating dir ./~ts failed with ~ts. Aborting.", - ok = log(error, Message, [PackageString, Error]), - halt(1) - end, - ok = erl_tar:extract({binary, TgzData}, [compressed, {cwd, PackageString}]), - ok = log(info, "Unpacked and awaiting inspection."), - halt(0). - - -approve(PackageID = {Realm, _, _}) -> - Socket = connect_auth_or_die(Realm), - ok = send(Socket, {approve, PackageID}), - ok = recv_or_die(Socket), - ok = log(info, "ok"), - halt(0). - - -reject(PackageID = {Realm, _, _}) -> - Socket = connect_auth_or_die(Realm), - ok = send(Socket, {reject, PackageID}), - ok = recv_or_die(Socket), - ok = log(info, "ok"), - halt(0). - - -resign(PackageString) -> - PackageID = {Realm, _, _} = zx_lib:package_id(PackageString), - RealmConf = load_realm_conf(Realm), - {package_keys, PackageKeys} = lists:keyfind(package_keys, 1, RealmConf), - KeySelection = [{K, {R, K}} || {R, K} <- [element(1, K) || K <- PackageKeys]], - PackageKeyID = select(KeySelection), - {ok, PackageKey} = loadkey(private, PackageKeyID), - Socket = connect_auth_or_die(Realm), - ok = send(Socket, {resign, PackageID}), - {ok, ZrpBin} = recv_or_die(Socket), - {ok, Files} = erl_tar:extract({binary, ZrpBin}, [memory]), - {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), - Meta = binary_to_term(MetaBin, [safe]), - PackageID = maps:get(package_id, Meta), - {KeyID, Signature} = maps:get(sig, Meta), - {ok, PubKey} = loadkey(public, KeyID), - TgzFile = PackageString ++ ".tgz", - {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files), - ok = verify(TgzData, Signature, PubKey), - ReSignature = public_key:sign(TgzData, sha512, PackageKey), - FinalMeta = maps:put(sig, {PackageKeyID, ReSignature}, Meta), - NewMetaBin = term_to_binary(FinalMeta), - NewFiles = lists:keystore("zomp.meta", 1, Files, {"zomp.meta", NewMetaBin}), - ResignedZrp = PackageString ++ ".zrp.resign", - ok = erl_tar:create(ResignedZrp, NewFiles), - {ok, ResignedBin} = file:read_file(ResignedZrp), - ok = gen_tcp:send(Socket, ResignedBin), - ok = recv_or_die(Socket), - ok = file:delete(ResignedZrp), - ok = recv_or_die(Socket), - ok = disconnect(Socket), - ok = log(info, "Resigned ~ts", [PackageString]), - halt(0). - - %%% Drop dependency @@ -994,9 +809,9 @@ drop_dep(PackageID) -> %% error exit value (this instruction is idempotent if used in shell scripts). drop_key({Realm, KeyName}) -> - ok = file:set_cwd(zx_lib:zomp_home()), + ok = file:set_cwd(zx_lib:zomp_dir()), KeyGlob = KeyName ++ ".{key,pub},der", - Pattern = filename:join([zx_lib:zomp_home(), "key", Realm, KeyGlob]), + Pattern = filename:join([zx_lib:zomp_dir(), "key", Realm, KeyGlob]), case filelib:wildcard(Pattern) of [] -> ok = log(warning, "Key ~ts/~ts not found", [Realm, KeyName]), @@ -1013,7 +828,7 @@ drop_key({Realm, KeyName}) -> -spec drop_realm(realm()) -> no_return(). drop_realm(Realm) -> - ok = file:set_cwd(zx_lib:zomp_home()), + ok = file:set_cwd(zx_lib:zomp_dir()), RealmConf = zx_lib:realm_conf(Realm), case filelib:is_regular(RealmConf) of true -> @@ -1022,7 +837,7 @@ drop_realm(Realm) -> " WARNING: Are you SURE you want to remove realm ~ts?~n" " (Only \"Y\" will confirm this action.)~n", ok = io:format(Message, [Realm]), - case get_input() of + case zx_tty:get_input() of "Y" -> ok = file:delete(RealmConf), ok = drop_prime(Realm), @@ -1058,7 +873,7 @@ drop_prime(Realm) -> -spec clear_keys(realm()) -> ok. clear_keys(Realm) -> - KeyDir = filename:join([zx_lib:zomp_home(), "key", Realm]), + KeyDir = filename:join([zx_lib:zomp_dir(), "key", Realm]), case filelib:is_dir(KeyDir) of true -> rm_rf(KeyDir); false -> log(warning, "Keydir ~ts not found", [KeyDir]) @@ -1133,21 +948,21 @@ package(TargetDir) -> ok = log(info, "Packaging ~ts", [TargetDir]), {ok, Meta} = zx_lib:read_project_meta(TargetDir), {Realm, _, _} = maps:get(package_id, Meta), - KeyDir = filename:join([zx_lib:zomp_home(), "key", Realm]), - ok = force_dir(KeyDir), + KeyDir = filename:join([zx_lib:zomp_dir(), "key", Realm]), + ok = zx_lib:force_dir(KeyDir), Pattern = KeyDir ++ "/*.key.der", case [filename:basename(F, ".key.der") || F <- filelib:wildcard(Pattern)] of [] -> ok = log(info, "Need to generate key"), - KeyID = prompt_keygen(), - {ok, _, _} = generate_rsa(KeyID), + KeyID = zx_key:prompt_keygen(), + {ok, _, _} = zx_key:generate_rsa(KeyID), package(KeyID, TargetDir); [KeyName] -> KeyID = {Realm, KeyName}, ok = log(info, "Using key: ~ts/~ts", [Realm, KeyName]), package(KeyID, TargetDir); KeyNames -> - KeyName = select_string(KeyNames), + KeyName = zx_tty:select_string(KeyNames), package({Realm, KeyName}, TargetDir) end. @@ -1157,16 +972,16 @@ package(TargetDir) -> TargetDir :: file:filename(). %% @private %% Accept a KeyPrefix for signing and a TargetDir containing a project to package and -%% build a zrp package file ready to be submitted to a repository. +%% build a zsp package file ready to be submitted to a repository. package(KeyID, TargetDir) -> {ok, Meta} = zx_lib:read_project_meta(TargetDir), PackageID = maps:get(package_id, Meta), true = element(1, PackageID) == element(1, KeyID), {ok, PackageString} = zx_lib:package_string(PackageID), - ZrpFile = PackageString ++ ".zrp", + ZrpFile = PackageString ++ ".zsp", TgzFile = PackageString ++ ".tgz", - ok = halt_if_exists(ZrpFile), + ok = zx_lib:halt_if_exists(ZrpFile), ok = remove_binaries(TargetDir), {ok, Everything} = file:list_dir(TargetDir), DotFiles = filelib:wildcard(".*", TargetDir), @@ -1180,7 +995,7 @@ package(KeyID, TargetDir) -> ok = remove_binaries("."), ok = erl_tar:create(filename:join(CWD, TgzFile), Targets, [compressed]), ok = file:set_cwd(CWD), - {ok, Key} = loadkey(private, KeyID), + {ok, Key} = zx_key:load(private, KeyID), {ok, TgzBin} = file:read_file(TgzFile), Sig = public_key:sign(TgzBin, sha512, Key), Add = fun({K, V}, M) -> maps:put(K, V, M) end, @@ -1208,505 +1023,6 @@ remove_binaries(TargetDir) -> ok = log(info, "Removing: ~tp", [ToDelete]), lists:foreach(fun file:delete/1, ToDelete) end. - - - -%%% Package submission - --spec submit(PackageFile) -> no_return() - when PackageFile :: file:filename(). -%% @private -%% Submit a package to the appropriate "prime" server for the given realm. - -submit(PackageFile) -> - Files = extract_zrp_or_die(PackageFile), - {ok, PackageData} = file:read_file(PackageFile), - {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), - Meta = binary_to_term(MetaBin), - {Realm, Package, Version} = maps:get(package_id, Meta), - {ok, Socket} = connect_auth(Realm), - ok = send(Socket, {submit, {Realm, Package, Version}}), - ok = recv_or_die(Socket), - ok = gen_tcp:send(Socket, PackageData), - ok = log(info, "Done sending contents of ~tp", [PackageFile]), - Outcome = recv_or_die(Socket), - log(info, "Response: ~tp", [Outcome]), - ok = disconnect(Socket), - halt(0). - - - -%%% Authenticated communication with prime - --spec send(Socket, Message) -> ok - when Socket :: gen_tcp:socket(), - Message :: term(). -%% @private -%% Wrapper for the procedure necessary to send an internal message over the wire. - -send(Socket, Message) -> - Bin = term_to_binary(Message), - gen_tcp:send(Socket, Bin). - - --spec recv_or_die(Socket) -> Result | no_return() - when Socket :: gen_tcp:socket(), - Result :: ok | {ok, term()}. - -recv_or_die(Socket) -> - receive - {tcp, Socket, Bin} -> - case binary_to_term(Bin) of - ok -> - ok; - {ok, Response} -> - {ok, Response}; - {error, Reason} -> - error_exit("Action failed with: ~tp", [Reason], ?LINE); - Unexpected -> - error_exit("Unexpected message: ~tp", [Unexpected], ?LINE) - end; - {tcp_closed, Socket} -> - error_exit("Lost connection to node unexpectedly.", ?LINE) - after 5000 -> - error_exit("Connection timed out.", ?LINE) - end. - - --spec connect_auth_or_die(realm()) -> gen_tcp:socket() | no_return(). - -connect_auth_or_die(Realm) -> - case connect_auth(Realm) of - {ok, Socket} -> - Socket; - Error -> - M1 = "Connection failed to realm prime with ~160tp.", - ok = log(warning, M1, [Error]), - halt(1) - end. - - --spec connect_auth(Realm) -> Result - when Realm :: realm(), - Result :: {ok, gen_tcp:socket()} - | {error, Reason :: term()}. -%% @private -%% Connect to one of the servers in the realm constellation. - -connect_auth(Realm) -> - RealmConf = load_realm_conf(Realm), - {User, KeyID, Key} = prep_auth(Realm, RealmConf), - {prime, {Host, Port}} = lists:keyfind(prime, 1, RealmConf), - Options = [{packet, 4}, {mode, binary}, {active, true}], - case gen_tcp:connect(Host, Port, Options, 5000) of - {ok, Socket} -> - ok = log(info, "Connected to ~tp prime.", [Realm]), - connect_auth(Socket, Realm, User, KeyID, Key); - Error = {error, E} -> - ok = log(warning, "Connection problem: ~tp", [E]), - {error, Error} - end. - - --spec connect_auth(Socket, Realm, User, KeyID, Key) -> Result - when Socket :: gen_tcp:socket(), - Realm :: realm(), - User :: user_id(), - KeyID :: key_id(), - Key :: term(), - Result :: {ok, gen_tcp:socket()} - | {error, timeout}. -%% @private -%% Send a protocol ID string to notify the server what we're up to, disconnect -%% if it does not return an "OK" response within 5 seconds. - -connect_auth(Socket, Realm, User, KeyID, Key) -> - ok = gen_tcp:send(Socket, <<"OTPR AUTH 1">>), - receive - {tcp, Socket, Bin} -> - ok = binary_to_term(Bin, [safe]), - confirm_auth(Socket, Realm, User, KeyID, Key); - {tcp_closed, Socket} -> - ok = log(warning, "Socket closed unexpectedly."), - halt(1) - after 5000 -> - ok = log(warning, "Host realm ~160tp prime timed out.", [Realm]), - {error, auth_timeout} - end. - - -confirm_auth(Socket, Realm, User, KeyID, Key) -> - ok = send(Socket, {User, KeyID}), - receive - {tcp, Socket, Bin} -> - case binary_to_term(Bin, [safe]) of - {sign, Blob} -> - Sig = public_key:sign(Blob, sha512, Key), - ok = send(Socket, {signed, Sig}), - confirm_auth(Socket); - {error, not_prime} -> - M1 = "Connected node is not prime for realm ~160tp", - ok = log(warning, M1, [Realm]), - ok = disconnect(Socket), - {error, not_prime}; - {error, bad_user} -> - M2 = "Bad user record ~160tp", - ok = log(warning, M2, [User]), - ok = disconnect(Socket), - {error, bad_user}; - {error, unauthorized_key} -> - M3 = "Unauthorized user key ~160tp", - ok = log(warning, M3, [KeyID]), - ok = disconnect(Socket), - {error, unauthorized_key}; - {error, Reason} -> - Message = "Could not begin auth exchange. Failed with ~160tp", - ok = log(warning, Message, [Reason]), - ok = disconnect(Socket), - {error, Reason} - end; - {tcp_closed, Socket} -> - ok = log(warning, "Socket closed unexpectedly."), - halt(1) - after 5000 -> - ok = log(warning, "Host realm ~tp prime timed out.", [Realm]), - {error, auth_timeout} - end. - - -confirm_auth(Socket) -> - receive - {tcp, Socket, Bin} -> - case binary_to_term(Bin, [safe]) of - ok -> {ok, Socket}; - Other -> {error, Other} - end; - {tcp_closed, Socket} -> - ok = log(warning, "Socket closed unexpectedly."), - halt(1) - after 5000 -> - {error, timeout} - end. - - --spec prep_auth(Realm, RealmConf) -> {User, KeyID, Key} | no_return() - when Realm :: realm(), - RealmConf :: [term()], - User :: user_id(), - KeyID :: key_id(), - Key :: term(). -%% @private -%% Loads the appropriate User, KeyID and reads in a registered key for use in -%% connect_auth/4. - -prep_auth(Realm, RealmConf) -> - UsersFile = filename:join(zx_lib:zomp_home(), "zomp.users"), - Users = - case file:consult(UsersFile) of - {ok, U} -> - U; - {error, enoent} -> - ok = log(warning, "You do not have any users configured."), - halt(1) - end, - {User, KeyIDs} = - case lists:keyfind(Realm, 1, Users) of - {Realm, UserName, []} -> - W = "User ~tp does not have any keys registered for realm ~tp.", - ok = log(warning, W, [UserName, Realm]), - ok = log(info, "Contact the following sysop(s) to register a key:"), - {sysops, Sysops} = lists:keyfind(sysops, 1, RealmConf), - PrintContact = - fun({_, _, Email, Name, _, _}) -> - log(info, "Sysop: ~ts Email: ~ts", [Name, Email]) - end, - ok = lists:foreach(PrintContact, Sysops), - halt(1); - {Realm, UserName, KeyNames} -> - KIDs = [{Realm, KeyName} || KeyName <- KeyNames], - {{Realm, UserName}, KIDs}; - false -> - Message = "You are not a user of the given realm: ~160tp.", - ok = log(warning, Message, [Realm]), - halt(1) - end, - KeyID = hd(KeyIDs), - true = ensure_keypair(KeyID), - {ok, Key} = loadkey(private, KeyID), - {User, KeyID, Key}. - - --spec disconnect(gen_tcp:socket()) -> ok. -%% @private -%% Gracefully shut down a socket, logging (but sidestepping) the case when the socket -%% has already been closed by the other side. - -disconnect(Socket) -> - case gen_tcp:shutdown(Socket, read_write) of - ok -> - log(info, "Disconnected from ~tp", [Socket]); - {error, Error} -> - Message = "Shutdown connection ~p failed with: ~p", - log(warning, Message, [Socket, Error]) - end. - - - -%%% Key utilities - --spec ensure_keypair(key_id()) -> true | no_return(). -%% @private -%% Check if both the public and private key based on KeyID exists. - -ensure_keypair(KeyID = {Realm, KeyName}) -> - case {have_public_key(KeyID), have_private_key(KeyID)} of - {true, true} -> - true; - {false, true} -> - Message = "Public key for ~tp/~tp cannot be found", - ok = log(error, Message, [Realm, KeyName]), - halt(1); - {true, false} -> - Message = "Private key for ~tp/~tp cannot be found", - ok = log(error, Message, [Realm, KeyName]), - halt(1); - {false, false} -> - Message = "Key pair for ~tp/~tp cannot be found", - ok = log(error, Message, [Realm, KeyName]), - halt(1) - end. - - --spec have_public_key(key_id()) -> boolean(). -%% @private -%% Determine whether the public key indicated by KeyID is in the keystore. - -have_public_key({Realm, KeyName}) -> - PublicKeyFile = KeyName ++ ".pub.der", - PublicKeyPath = filename:join([zx_lib:zomp_home(), "key", Realm, PublicKeyFile]), - filelib:is_regular(PublicKeyPath). - - --spec have_private_key(key_id()) -> boolean(). -%% @private -%% Determine whether the private key indicated by KeyID is in the keystore. - -have_private_key({Realm, KeyName}) -> - PrivateKeyFile = KeyName ++ ".key.der", - PrivateKeyPath = filename:join([zx_lib:zomp_home(), "key", Realm, PrivateKeyFile]), - filelib:is_regular(PrivateKeyPath). - - - -%%% Key generation - --spec prompt_keygen() -> key_id(). -%% @private -%% Prompt the user for a valid KeyPrefix to use for naming a new RSA keypair. - -prompt_keygen() -> - Message = - "~n Enter a name for your new keys.~n~n" - " Valid names must start with a lower-case letter, and can include~n" - " only lower-case letters, numbers, and periods, but no series of~n" - " consecutive periods. (That is: [a-z0-9\\.])~n~n" - " To designate the key as realm-specific, enter the realm name and~n" - " key name separated by a space.~n~n" - " Example: some.realm my.key~n", - ok = io:format(Message), - Input = get_input(), - {Realm, KeyName} = - case string:lexemes(Input, " ") of - [R, K] -> {R, K}; - [K] -> {"otpr", K} - end, - case {zx_lib:valid_lower0_9(Realm), zx_lib:valid_label(KeyName)} of - {true, true} -> - {Realm, KeyName}; - {false, true} -> - ok = io:format("Bad realm name ~tp. Try again.~n", [Realm]), - prompt_keygen(); - {true, false} -> - ok = io:format("Bad key name ~tp. Try again.~n", [KeyName]), - prompt_keygen(); - {false, false} -> - ok = io:format("NUTS! Both key and realm names are illegal. Try again.~n"), - prompt_keygen() - end. - - --spec create_keypair() -> no_return(). -%% @private -%% Execute the key generation procedure for 16k RSA keys once and then terminate. - -create_keypair() -> - ok = file:set_cwd(zx_lib:zomp_home()), - KeyID = prompt_keygen(), - case generate_rsa(KeyID) of - {ok, _, _} -> halt(0); - Error -> error_exit("create_keypair/0 error: ~tp", [Error], ?LINE) - end. - - --spec generate_rsa(KeyID) -> Result - when KeyID :: key_id(), - Result :: {ok, KeyFile, PubFile} - | {error, keygen_fail}, - KeyFile :: file:filename(), - PubFile :: file:filename(). -%% @private -%% Generate an RSA keypair and write them in der format to the current directory, using -%% filenames derived from Prefix. -%% NOTE: The current version of this command is likely to only work on a unix system. - -generate_rsa({Realm, KeyName}) -> - KeyDir = filename:join([zx_lib:zomp_home(), "key", Realm]), - ok = force_dir(KeyDir), - PemFile = filename:join(KeyDir, KeyName ++ ".pub.pem"), - KeyFile = filename:join(KeyDir, KeyName ++ ".key.der"), - PubFile = filename:join(KeyDir, KeyName ++ ".pub.der"), - ok = lists:foreach(fun halt_if_exists/1, [PemFile, KeyFile, PubFile]), - ok = log(info, "Generating ~p and ~p. Please be patient...", [KeyFile, PubFile]), - ok = gen_p_key(KeyFile), - ok = der_to_pem(KeyFile, PemFile), - {ok, PemBin} = file:read_file(PemFile), - [PemData] = public_key:pem_decode(PemBin), - Pub = public_key:pem_entry_decode(PemData), - PubDer = public_key:der_encode('RSAPublicKey', Pub), - ok = file:write_file(PubFile, PubDer), - case check_key(KeyFile, PubFile) of - true -> - ok = file:delete(PemFile), - ok = log(info, "~ts and ~ts agree", [KeyFile, PubFile]), - ok = log(info, "Wrote private key to: ~ts.", [KeyFile]), - ok = log(info, "Wrote public key to: ~ts.", [PubFile]), - {ok, KeyFile, PubFile}; - false -> - ok = lists:foreach(fun file:delete/1, [PemFile, KeyFile, PubFile]), - ok = log(error, "Something has gone wrong."), - {error, keygen_fail} - end. - - --spec halt_if_exists(file:filename()) -> ok | no_return(). -%% @private -%% A helper function to guard against overwriting an existing file. Halts execution if -%% the file is found to exist. - -halt_if_exists(Path) -> - case filelib:is_file(Path) of - true -> error_exit("~ts already exists! Halting.", [Path], ?LINE); - false -> ok - end. - - --spec gen_p_key(KeyFile) -> ok - when KeyFile :: file:filename(). -%% @private -%% Format an openssl shell command that will generate proper 16k RSA keys. - -gen_p_key(KeyFile) -> - Command = - io_lib:format("~ts genpkey" - " -algorithm rsa" - " -out ~ts" - " -outform DER" - " -pkeyopt rsa_keygen_bits:16384", - [openssl(), KeyFile]), - Out = os:cmd(Command), - io:format(Out). - - --spec der_to_pem(KeyFile, PemFile) -> ok - when KeyFile :: file:filename(), - PemFile :: file:filename(). -%% @private -%% Format an openssl shell command that will convert the given keyfile to a pemfile. -%% The reason for this conversion is to sidestep some formatting weirdness that OpenSSL -%% injects into its generated DER formatted key output (namely, a few empty headers) -%% which Erlang's ASN.1 defintion files do not take into account. A conversion to PEM -%% then a conversion back to DER (via Erlang's ASN.1 module) resolves this in a reliable -%% way. - -der_to_pem(KeyFile, PemFile) -> - Command = - io_lib:format("~ts rsa" - " -inform DER" - " -in ~ts" - " -outform PEM" - " -pubout" - " -out ~ts", - [openssl(), KeyFile, PemFile]), - Out = os:cmd(Command), - io:format(Out). - - --spec check_key(KeyFile, PubFile) -> Result - when KeyFile :: file:filename(), - PubFile :: file:filename(), - Result :: true | false. -%% @private -%% Compare two keys for pairedness. - -check_key(KeyFile, PubFile) -> - {ok, KeyBin} = file:read_file(KeyFile), - {ok, PubBin} = file:read_file(PubFile), - Key = public_key:der_decode('RSAPrivateKey', KeyBin), - Pub = public_key:der_decode('RSAPublicKey', PubBin), - TestMessage = <<"Some test data to sign.">>, - Signature = public_key:sign(TestMessage, sha512, Key), - public_key:verify(TestMessage, sha512, Signature, Pub). - - --spec openssl() -> Executable | no_return() - when Executable :: file:filename(). -%% @private -%% Attempt to locate the installed openssl executable for use in shell commands. -%% Halts execution with an error message if the executable cannot be found. - -openssl() -> - OpenSSL = - case os:type() of - {unix, _} -> "openssl"; - {win32, _} -> "openssl.exe" - end, - ok = - case os:find_executable(OpenSSL) of - false -> - ok = log(error, "OpenSSL could not be found in this system's PATH."), - ok = log(error, "Install OpenSSL and then retry."), - error_exit("Missing system dependenct: OpenSSL", ?LINE); - Path -> - log(info, "OpenSSL executable found at: ~ts", [Path]) - end, - OpenSSL. - - --spec loadkey(Type, KeyID) -> Result - when Type :: private | public, - KeyID :: key_id(), - Result :: {ok, DecodedKey :: term()} - | {error, Reason :: term()}. -%% @private -%% Hide the details behind reading and loading DER encoded RSA key files. - -loadkey(Type, {Realm, KeyName}) -> - {DerType, Path} = - case Type of - private -> - KeyDer = KeyName ++ ".key.der", - P = filename:join([zx_lib:zomp_home(), "key", Realm, KeyDer]), - {'RSAPrivateKey', P}; - public -> - PubDer = KeyName ++ ".pub.der", - P = filename:join([zx_lib:zomp_home(), "key", Realm, PubDer]), - {'RSAPublicKey', P} - end, - ok = log(info, "Loading key from file ~ts", [Path]), - case file:read_file(Path) of - {ok, Bin} -> {ok, public_key:der_decode(DerType, Bin)}; - Error -> Error - end. @@ -1749,7 +1065,7 @@ build_plt() -> -spec default_plt() -> file:filename(). default_plt() -> - filename:join(zx_lib:zomp_home(), "basic.plt"). + filename:join(zx_lib:zomp_dir(), "basic.plt"). @@ -1768,7 +1084,7 @@ dialyze() -> true -> log(info, "Using PLT: ~tp", [PLT]); false -> build_plt() end, - TmpDir = filename:join(zx_lib:zomp_home(), "tmp"), + TmpDir = filename:join(zx_lib:zomp_dir(), "tmp"), Me = escript:script_name(), EvilTwin = filename:join(TmpDir, filename:basename(Me ++ ".erl")), ok = log(info, "Temporarily reconstructing ~tp as ~tp", [Me, EvilTwin]), @@ -1815,10 +1131,10 @@ create_realm() -> " Names can contain only lower-case letters, numbers and the underscore.~n" " Names must begin with a lower-case letter.~n", ok = io:format(Instructions), - Realm = get_input(), + Realm = zx_tty:get_input(), case zx_lib:valid_lower0_9(Realm) of true -> - RealmFile = filename:join(zx_lib:zomp_home(), Realm ++ ".realm"), + RealmFile = filename:join(zx_lib:zomp_dir(), Realm ++ ".realm"), case filelib:is_regular(RealmFile) of false -> create_realm(Realm); @@ -1846,7 +1162,7 @@ create_realm(Realm) -> prompt_external_address() -> Message = external_address_prompt(), ok = io:format(Message), - case get_input() of + case zx_tty:get_input() of "" -> ok = io:format("You need to enter an address.~n"), prompt_external_address(); @@ -1914,7 +1230,7 @@ prompt_port_number(Current) -> " A valid port is any number from 1 to 65535." " [Press enter to accept the current setting: ~tw]~n", ok = io:format(Instructions, [Current]), - case get_input() of + case zx_tty:get_input() of "" -> Current; S -> @@ -1947,7 +1263,7 @@ create_realm(Realm, ExAddress, ExPort, InPort) -> " Names can contain only lower-case letters, numbers and the underscore.~n" " Names must begin with a lower-case letter.~n", ok = io:format(Instructions), - UserName = get_input(), + UserName = zx_tty:get_input(), case zx_lib:valid_lower0_9(UserName) of true -> create_realm(Realm, ExAddress, ExPort, InPort, UserName); @@ -1972,7 +1288,7 @@ create_realm(Realm, ExAddress, ExPort, InPort, UserName) -> "minimal. Check the address you enter carefully. The only people who will " "suffer from an invalid address are your users.~n", ok = io:format(Instructions), - Email = get_input(), + Email = zx_tty:get_input(), [User, Host] = string:lexemes(Email, "@"), case {zx_lib:valid_lower0_9(User), zx_lib:valid_label(Host)} of {true, true} -> @@ -2007,7 +1323,7 @@ create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email) -> " Enter the real name (or whatever name people recognize) for the sysop.~n" " There are no rules for this one. Any valid UTF-8 printables are legal.~n", ok = io:format(Instructions), - RealName = get_input(), + RealName = zx_tty:get_input(), create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email, RealName). @@ -2022,9 +1338,9 @@ create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email) -> create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email, RealName) -> ok = io:format("~nGenerating keys. This might take a while, so settle in...~n"), - {ok, RealmKey, RealmPub} = generate_rsa({Realm, Realm ++ ".1.realm"}), - {ok, PackageKey, PackagePub} = generate_rsa({Realm, Realm ++ ".1.package"}), - {ok, SysopKey, SysopPub} = generate_rsa({Realm, UserName ++ ".1"}), + {ok, RealmKey, RealmPub} = zx_key:generate_rsa({Realm, Realm ++ ".1.realm"}), + {ok, PackageKey, PackagePub} = zx_key:generate_rsa({Realm, Realm ++ ".1.package"}), + {ok, SysopKey, SysopPub} = zx_key:generate_rsa({Realm, UserName ++ ".1"}), ok = log(info, "Generated 16k RSA pair ~ts ~ts", [RealmKey, RealmPub]), ok = log(info, "Generated 16k RSA pair ~ts ~ts", [PackageKey, PackagePub]), ok = log(info, "Generated 16k RSA pair ~ts ~ts", [SysopKey, SysopPub]), @@ -2140,7 +1456,7 @@ create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email, RealName) -> -spec create_realmfile(realm()) -> no_return(). create_realmfile(Realm) -> - RealmConf = load_realm_conf(Realm), + RealmConf = zx_lib:load_realm_conf(Realm), ok = log(info, "Realm found, creating realm file..."), {revision, Revision} = lists:keyfind(revision, 1, RealmConf), {realm_keys, RealmKeys} = lists:keyfind(realm_keys, 1, RealmConf), @@ -2158,7 +1474,7 @@ create_realmfile(Realm) -> create_realmfile(Realm, Revision, RealmKeyIDs, PackageKeyIDs) -> {ok, CWD} = file:get_cwd(), - ok = file:set_cwd(zx_lib:zomp_home()), + ok = file:set_cwd(zx_lib:zomp_dir()), KeyPath = fun({R, K}) -> filename:join(["key", R, K ++ ".pub.der"]) end, RealmKeyPaths = lists:map(KeyPath, RealmKeyIDs), PackageKeyPaths = lists:map(KeyPath, PackageKeyIDs), @@ -2169,13 +1485,6 @@ create_realmfile(Realm, Revision, RealmKeyIDs, PackageKeyIDs) -> halt(0). --spec create_sysop() -> no_return(). - -create_sysop() -> - ok = log(info, "Fo' realz, yo! We be sysoppin up in hurr!"), - halt(0). - - %%% Package utilities @@ -2184,8 +1493,8 @@ create_sysop() -> %% @private %% Install a package from the cache into the local system. %% Before calling this function it must be known that: -%% - The zrp file is in the cache -%% - The zrp file is valid +%% - The zsp file is in the cache +%% - The zsp file is valid %% - This function will only be called on startup by the launch process %% - The package is not already installed %% - If this function crashes it will completely halt the system @@ -2193,38 +1502,22 @@ create_sysop() -> install(PackageID) -> {ok, PackageString} = zx_lib:package_string(PackageID), ok = log(info, "Installing ~ts", [PackageString]), - ZrpFile = filename:join("zrp", zx_lib:namify_zrp(PackageID)), - Files = extract_zrp_or_die(ZrpFile), + ZrpFile = filename:join("zsp", zx_lib:namify_zsp(PackageID)), + Files = zx_lib:extract_zsp_or_die(ZrpFile), TgzFile = zx_lib:namify_tgz(PackageID), {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files), {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), Meta = binary_to_term(MetaBin), {KeyID, Signature} = maps:get(sig, Meta), - {ok, PubKey} = loadkey(public, KeyID), + {ok, PubKey} = zx_key:load(public, KeyID), ok = ensure_package_dirs(PackageID), PackageDir = filename:join("lib", PackageString), - ok = force_dir(PackageDir), - ok = verify(TgzData, Signature, PubKey), + ok = zx_lib:force_dir(PackageDir), + ok = zx_key:verify(TgzData, Signature, PubKey), ok = erl_tar:extract({binary, TgzData}, [compressed, {cwd, PackageDir}]), log(info, "~ts installed", [PackageString]). --spec verify(Data, Signature, PubKey) -> ok | no_return() - when Data :: binary(), - Signature :: binary(), - PubKey :: public_key:rsa_public_key(). -%% @private -%% Verify the RSA Signature of some Data against the given PubKey or halt execution. -%% This function always assumes sha512 is the algorithm being used. -%% Should only ever be called by the initial launch process. - -verify(Data, Signature, PubKey) -> - case public_key:verify(Data, sha512, Signature, PubKey) of - true -> ok; - false -> error_exit("Bad package signature!", ?LINE) - end. - - -spec build(package_id()) -> ok. %% @private %% Given an AppID, build the project from source and add it to the current lib path. @@ -2258,90 +1551,6 @@ build() -> -%%% User menu interface (terminal) - --spec get_input() -> string(). -%% @private -%% Provide a standard input prompt and newline sanitized return value. - -get_input() -> - string:trim(io:get_line("(^C to quit): ")). - - --spec select(Options) -> Selected - when Options :: [option()], - Selected :: term(). -%% @private -%% Take a list of Options to present the user, then return the indicated option to the -%% caller once the user selects something. - -select(Options) -> - Max = show(Options), - case pick(string:to_integer(io:get_line("(or ^C to quit)~n ? ")), Max) of - error -> - ok = hurr(), - select(Options); - I -> - {_, Value} = lists:nth(I, Options), - Value - end. - - --spec select_string(Strings) -> Selected - when Strings :: [string()], - Selected :: string(). -%% @private -%% @equiv select([{S, S} || S <- Strings]) - -select_string(Strings) -> - select([{S, S} || S <- Strings]). - - --spec show(Options) -> Index - when Options :: [option()], - Index :: pos_integer(). -%% @private -%% @equiv show(Options, 0). - -show(Options) -> - show(Options, 0). - - --spec show(Options, Index) -> Count - when Options :: [option()], - Index :: non_neg_integer(), - Count :: pos_integer(). -%% @private -%% Display the list of options needed to the user, and return the option total count. - -show([], I) -> - I; -show([{Label, _} | Rest], I) -> - Z = I + 1, - ok = io:format(" ~2w - ~ts~n", [Z, Label]), - show(Rest, Z). - - --spec pick({Selection, term()}, Max) -> Result - when Selection :: error | integer(), - Max :: pos_integer(), - Result :: pos_integer() | error. -%% @private -%% Interpret a user's selection returning either a valid selection index or `error'. - -pick({error, _}, _) -> error; -pick({I, _}, Max) when 0 < I, I =< Max -> I; -pick(_, _) -> error. - - --spec hurr() -> ok. -%% @private -%% Present an appropriate response when the user derps on selection. - -hurr() -> io:format("That isn't an option.~n"). - - - %%% Directory & File Management -spec mktemp_dir(Prefix) -> Result @@ -2400,64 +1609,10 @@ ensure_package_dirs(PackageID = {Realm, Name, _}) -> PackageData = zx_lib:package_dir("var", Package), PackageConf = zx_lib:package_dir("etc", Package), Dirs = [PackageHome, PackageData, PackageConf], - ok = lists:foreach(fun force_dir/1, Dirs), + ok = lists:foreach(fun zx_lib:force_dir/1, Dirs), log(info, "Created dirs:~n\t~ts~n\t~ts~n\t~ts", Dirs). --spec force_dir(Path) -> Result - when Path :: file:filename(), - Result :: ok - | {error, file:posix()}. -%% @private -%% Guarantee a directory path is created if it is possible to create or if it already -%% exists. - -force_dir(Path) -> - case filelib:is_dir(Path) of - true -> ok; - false -> filelib:ensure_dir(filename:join(Path, "foo")) - end. - - --spec extract_zrp_or_die(FileName) -> Files | no_return() - when FileName :: file:filename(), - Files :: [{file:filename(), binary()}]. -%% @private -%% Extract a zrp archive, if possible. If not possible, halt execution with as accurate -%% an error message as can be managed. - -extract_zrp_or_die(FileName) -> - case erl_tar:extract(FileName, [memory]) of - {ok, Files} -> - Files; - {error, {FileName, enoent}} -> - Message = "Can't find file ~ts.", - error_exit(Message, [FileName], ?LINE); - {error, invalid_tar_checksum} -> - Message = "~ts is not a valid zrp archive.", - error_exit(Message, [FileName], ?LINE); - {error, Reason} -> - Message = "Extracting package file failed with: ~160tp.", - error_exit(Message, [Reason], ?LINE) - end. - - --spec load_realm_conf(Realm) -> RealmConf | no_return() - when Realm :: realm(), - RealmConf :: list(). -%% @private -%% Load the config for the given realm or halt with an error. - -load_realm_conf(Realm) -> - case zx_lib:load_realm_conf(Realm) of - {ok, C} -> - C; - {error, enoent} -> - ok = log(warning, "Realm ~tp is not configured.", [Realm]), - halt(1) - end. - - %%% Usage @@ -2503,7 +1658,7 @@ usage() -> " zx review PackageID~n" " zx approve PackageID~n" " zx reject PackageID~n" - " zx resign PackageID~n" + " zx accept PackageID~n" " zx drop dep PackageID~n" " zx drop key Realm KeyName~n" " zx drop realm Realm~n" @@ -2527,7 +1682,7 @@ usage() -> " Realm :: The name of a realm as a string [:a-z:]~n" " KeyName :: The prefix of a keypair to drop~n" " Level :: The version level, one of \"major\", \"minor\", or \"patch\"~n" - " Path :: Path to a valid project directory or .zrp file~n" + " Path :: Path to a valid project directory or .zsp file~n" "~n", io:format(T). diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_auth.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_auth.erl new file mode 100644 index 0000000..e909189 --- /dev/null +++ b/zomp/lib/otpr/zx/0.1.0/src/zx_auth.erl @@ -0,0 +1,452 @@ +%%% @doc +%%% ZX Auth +%%% +%%% This module is where all the AUTH type command code lives. AUTH commands are special +%%% because they do not involve the zx_daemon at all, though they do perform network +%%% operations. +%%% +%%% All AUTH procedures terminate the runtime once complete. +%%% @end + +-module(zx_auth). +-author("Craig Everett "). +-copyright("Craig Everett "). +-license("GPL-3.0"). + +-export([list_pending/1, list_resigns/1, + submit/1, review/1, approve/1, reject/1, accept/1, + add_packager/2, add_maintainer/2, add_sysop/1, + add_package/1]). + +-include("zx_logger.hrl"). + + + +%%% Functions + + +-spec list_pending(PackageName :: string()) -> no_return(). +%% @private +%% List the versions of a package that are pending review. The package name is input by +%% the user as a string of the form "otpr-zomp" and the output is a list of full +%% package IDs, printed one per line to stdout (like "otpr-zomp-3.2.2"). + +list_pending(PackageName) -> + Package = {Realm, Name} = + case zx_lib:package_id(PackageName) of + {ok, {R, N, {z, z, z}}} -> + {R, N}; + {error, invalid_package_string} -> + zx:error_exit("~tp is not a valid package name.", [PackageName], ?LINE) + end, + case zx_daemon:list_pending(Package) of + {ok, []} -> + Message = "Package ~ts has no versions pending.", + ok = log(info, Message, [PackageName]), + halt(0); + {ok, Versions} -> + Print = + fun(Version) -> + {ok, PackageString} = zx_lib:package_string({Realm, Name, Version}), + io:format("~ts~n", [PackageString]) + end, + ok = lists:foreach(Print, Versions), + halt(0); + {error, bad_realm} -> + zx:error_exit("Bad realm name.", ?LINE); + {error, bad_package} -> + zx:error_exit("Bad package name.", ?LINE); + {error, network} -> + Message = "Network issues are preventing connection to the realm.", + zx:error_exit(Message, ?LINE) + end. + + +-spec list_resigns(zx:realm()) -> no_return(). +%% @private +%% List the package ids of all packages waiting in the resign queue for the given realm, +%% printed to stdout one per line. + +list_resigns(Realm) -> + case zx_daemon:list_resigns(Realm) of + {ok, []} -> + Message = "No packages pending signature in ~tp.", + ok = log(info, Message, [Realm]), + halt(0); + {ok, PackageIDs} -> + Print = + fun(PackageID) -> + {ok, PackageString} = zx_lib:package_string(PackageID), + io:format("~ts~n", [PackageString]) + end, + ok = lists:foreach(Print, PackageIDs), + halt(0); + {error, bad_realm} -> + zx:error_exit("Bad realm name.", ?LINE); + {error, no_realm} -> + zx:error_exit("Realm \"~ts\" is not configured.", ?LINE); + {error, network} -> + Message = "Network issues are preventing connection to the realm.", + zx:error_exit(Message, ?LINE) + end. + + +-spec submit(PackageFile) -> no_return() + when PackageFile :: file:filename(). +%% @private +%% Submit a package to the appropriate "prime" server for the given realm. + +submit(PackageFile) -> + Files = zx_lib:extract_zsp_or_die(PackageFile), + {ok, PackageData} = file:read_file(PackageFile), + {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), + Meta = binary_to_term(MetaBin), + {Realm, Package, Version} = maps:get(package_id, Meta), + {ok, Socket} = connect_auth(Realm), + ok = send(Socket, {submit, {Realm, Package, Version}}), + ok = recv_or_die(Socket), + ok = gen_tcp:send(Socket, PackageData), + ok = log(info, "Done sending contents of ~tp", [PackageFile]), + Outcome = recv_or_die(Socket), + log(info, "Response: ~tp", [Outcome]), + ok = disconnect(Socket), + halt(0). + + +review(PackageString) -> + PackageID = {Realm, _, _} = zx_lib:package_id(PackageString), + Socket = connect_auth_or_die(Realm), + ok = send(Socket, {review, PackageID}), + {ok, ZrpBin} = recv_or_die(Socket), + ok = send(Socket, ok), + ok = disconnect(Socket), + {ok, Files} = erl_tar:extract({binary, ZrpBin}, [memory]), + {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), + Meta = binary_to_term(MetaBin, [safe]), + PackageID = maps:get(package_id, Meta), + {KeyID, Signature} = maps:get(sig, Meta), + {ok, PubKey} = zx_key:load(public, KeyID), + TgzFile = PackageString ++ ".tgz", + {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files), + ok = zx_key:verify(TgzData, Signature, PubKey), + ok = + case file:make_dir(PackageString) of + ok -> + log(info, "Will unpack to directory ./~ts", [PackageString]); + {error, Error} -> + Message = "Creating dir ./~ts failed with ~ts. Aborting.", + ok = log(error, Message, [PackageString, Error]), + halt(1) + end, + ok = erl_tar:extract({binary, TgzData}, [compressed, {cwd, PackageString}]), + ok = log(info, "Unpacked and awaiting inspection."), + halt(0). + + +approve(PackageID = {Realm, _, _}) -> + Socket = connect_auth_or_die(Realm), + ok = send(Socket, {approve, PackageID}), + ok = recv_or_die(Socket), + ok = log(info, "ok"), + halt(0). + + +reject(PackageID = {Realm, _, _}) -> + Socket = connect_auth_or_die(Realm), + ok = send(Socket, {reject, PackageID}), + ok = recv_or_die(Socket), + ok = log(info, "ok"), + halt(0). + + +accept(PackageString) -> + PackageID = {Realm, _, _} = zx_lib:package_id(PackageString), + RealmConf = zx_lib:load_realm_conf(Realm), + {package_keys, PackageKeys} = lists:keyfind(package_keys, 1, RealmConf), + KeySelection = [{K, {R, K}} || {R, K} <- [element(1, K) || K <- PackageKeys]], + PackageKeyID = zx_tty:select(KeySelection), + {ok, PackageKey} = zx_key:load(private, PackageKeyID), + Socket = connect_auth_or_die(Realm), + ok = send(Socket, {accept, PackageID}), + {ok, ZrpBin} = recv_or_die(Socket), + {ok, Files} = erl_tar:extract({binary, ZrpBin}, [memory]), + {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), + Meta = binary_to_term(MetaBin, [safe]), + PackageID = maps:get(package_id, Meta), + {KeyID, Signature} = maps:get(sig, Meta), + {ok, PubKey} = zx_key:load(public, KeyID), + TgzFile = PackageString ++ ".tgz", + {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files), + ok = zx_key:verify(TgzData, Signature, PubKey), + ReSignature = public_key:sign(TgzData, sha512, PackageKey), + FinalMeta = maps:put(sig, {PackageKeyID, ReSignature}, Meta), + NewMetaBin = term_to_binary(FinalMeta), + NewFiles = lists:keystore("zomp.meta", 1, Files, {"zomp.meta", NewMetaBin}), + ResignedZrp = PackageString ++ ".zsp.resign", + ok = erl_tar:create(ResignedZrp, NewFiles), + {ok, ResignedBin} = file:read_file(ResignedZrp), + ok = gen_tcp:send(Socket, ResignedBin), + ok = recv_or_die(Socket), + ok = file:delete(ResignedZrp), + ok = recv_or_die(Socket), + ok = disconnect(Socket), + ok = log(info, "Resigned ~ts", [PackageString]), + halt(0). + + +add_packager(Package, UserFile) -> + ok = log(info, "Would add ~ts to packagers for ~160tp now.", [UserFile, Package]), + halt(0). + + +add_maintainer(Package, UserFile) -> + ok = log(info, "Would add ~ts to maintainer for ~160tp now.", [UserFile, Package]), + halt(0). + + +add_sysop(UserFile) -> + ok = log(info, "Would add ~ts to sysop list.", [UserFile]), + halt(0). + + +-spec add_package(PackageName) -> no_return() + when PackageName :: zx:package(). +%% @private +%% A sysop command that adds a package to a realm operated by the caller. + +add_package(PackageName) -> + ok = file:set_cwd(zx_lib:zomp_dir()), + case zx_lib:package_id(PackageName) of + {ok, {Realm, Name, {z, z, z}}} -> + add_package(Realm, Name); + _ -> + zx:error_exit("~tp is not a valid package name.", [PackageName], ?LINE) + end. + + +-spec add_package(Realm, Name) -> no_return() + when Realm :: zx:realm(), + Name :: zx:name(). + +add_package(Realm, Name) -> + Socket = connect_auth_or_die(Realm), + ok = send(Socket, {add_package, {Realm, Name}}), + ok = recv_or_die(Socket), + ok = log(info, "\"~ts-~ts\" added successfully.", [Realm, Name]), + halt(0). + + + +%%% Authenticated communication with prime + +-spec send(Socket, Message) -> ok + when Socket :: gen_tcp:socket(), + Message :: term(). +%% @private +%% Wrapper for the procedure necessary to send an internal message over the wire. + +send(Socket, Message) -> + Bin = term_to_binary(Message), + gen_tcp:send(Socket, Bin). + + +-spec recv_or_die(Socket) -> Result | no_return() + when Socket :: gen_tcp:socket(), + Result :: ok | {ok, term()}. + +recv_or_die(Socket) -> + receive + {tcp, Socket, Bin} -> + case binary_to_term(Bin) of + ok -> + ok; + {ok, Response} -> + {ok, Response}; + {error, Reason} -> + zx:error_exit("Action failed with: ~tp", [Reason], ?LINE); + Unexpected -> + zx:error_exit("Unexpected message: ~tp", [Unexpected], ?LINE) + end; + {tcp_closed, Socket} -> + zx:error_exit("Lost connection to node unexpectedly.", ?LINE) + after 5000 -> + zx:error_exit("Connection timed out.", ?LINE) + end. + + +-spec connect_auth_or_die(zx:realm()) -> gen_tcp:socket() | no_return(). + +connect_auth_or_die(Realm) -> + case connect_auth(Realm) of + {ok, Socket} -> + Socket; + Error -> + M1 = "Connection failed to realm prime with ~160tp.", + ok = log(warning, M1, [Error]), + halt(1) + end. + + +-spec connect_auth(Realm) -> Result + when Realm :: zx:realm(), + Result :: {ok, gen_tcp:socket()} + | {error, Reason :: term()}. +%% @private +%% Connect to one of the servers in the realm constellation. + +connect_auth(Realm) -> + RealmConf = zx_lib:load_realm_conf(Realm), + {User, KeyID, Key} = prep_auth(Realm, RealmConf), + {prime, {Host, Port}} = lists:keyfind(prime, 1, RealmConf), + Options = [{packet, 4}, {mode, binary}, {active, true}], + case gen_tcp:connect(Host, Port, Options, 5000) of + {ok, Socket} -> + ok = log(info, "Connected to ~tp prime.", [Realm]), + connect_auth(Socket, Realm, User, KeyID, Key); + Error = {error, E} -> + ok = log(warning, "Connection problem: ~tp", [E]), + {error, Error} + end. + + +-spec connect_auth(Socket, Realm, User, KeyID, Key) -> Result + when Socket :: gen_tcp:socket(), + Realm :: zx:realm(), + User :: zx:user_id(), + KeyID :: zx:key_id(), + Key :: term(), + Result :: {ok, gen_tcp:socket()} + | {error, timeout}. +%% @private +%% Send a protocol ID string to notify the server what we're up to, disconnect +%% if it does not return an "OK" response within 5 seconds. + +connect_auth(Socket, Realm, User, KeyID, Key) -> + ok = gen_tcp:send(Socket, <<"OTPR AUTH 1">>), + receive + {tcp, Socket, Bin} -> + ok = binary_to_term(Bin, [safe]), + confirm_auth(Socket, Realm, User, KeyID, Key); + {tcp_closed, Socket} -> + ok = log(warning, "Socket closed unexpectedly."), + halt(1) + after 5000 -> + ok = log(warning, "Host realm ~160tp prime timed out.", [Realm]), + {error, auth_timeout} + end. + + +confirm_auth(Socket, Realm, User, KeyID, Key) -> + ok = send(Socket, {User, KeyID}), + receive + {tcp, Socket, Bin} -> + case binary_to_term(Bin, [safe]) of + {sign, Blob} -> + Sig = public_key:sign(Blob, sha512, Key), + ok = send(Socket, {signed, Sig}), + confirm_auth(Socket); + {error, not_prime} -> + M1 = "Connected node is not prime for realm ~160tp", + ok = log(warning, M1, [Realm]), + ok = disconnect(Socket), + {error, not_prime}; + {error, bad_user} -> + M2 = "Bad user record ~160tp", + ok = log(warning, M2, [User]), + ok = disconnect(Socket), + {error, bad_user}; + {error, unauthorized_key} -> + M3 = "Unauthorized user key ~160tp", + ok = log(warning, M3, [KeyID]), + ok = disconnect(Socket), + {error, unauthorized_key}; + {error, Reason} -> + Message = "Could not begin auth exchange. Failed with ~160tp", + ok = log(warning, Message, [Reason]), + ok = disconnect(Socket), + {error, Reason} + end; + {tcp_closed, Socket} -> + ok = log(warning, "Socket closed unexpectedly."), + halt(1) + after 5000 -> + ok = log(warning, "Host realm ~tp prime timed out.", [Realm]), + {error, auth_timeout} + end. + + +confirm_auth(Socket) -> + receive + {tcp, Socket, Bin} -> + case binary_to_term(Bin, [safe]) of + ok -> {ok, Socket}; + Other -> {error, Other} + end; + {tcp_closed, Socket} -> + ok = log(warning, "Socket closed unexpectedly."), + halt(1) + after 5000 -> + {error, timeout} + end. + + +-spec prep_auth(Realm, RealmConf) -> {User, KeyID, Key} | no_return() + when Realm :: zx:realm(), + RealmConf :: [term()], + User :: zx:user_id(), + KeyID :: zx:key_id(), + Key :: term(). +%% @private +%% Loads the appropriate User, KeyID and reads in a registered key for use in +%% connect_auth/4. + +prep_auth(Realm, RealmConf) -> + UsersFile = filename:join(zx_lib:zomp_dir(), "zomp.users"), + Users = + case file:consult(UsersFile) of + {ok, U} -> + U; + {error, enoent} -> + ok = log(warning, "You do not have any users configured."), + halt(1) + end, + {User, KeyIDs} = + case lists:keyfind(Realm, 1, Users) of + {Realm, UserName, []} -> + W = "User ~tp does not have any keys registered for realm ~tp.", + ok = log(warning, W, [UserName, Realm]), + ok = log(info, "Contact the following sysop(s) to register a key:"), + {sysops, Sysops} = lists:keyfind(sysops, 1, RealmConf), + PrintContact = + fun({_, _, Email, Name, _, _}) -> + log(info, "Sysop: ~ts Email: ~ts", [Name, Email]) + end, + ok = lists:foreach(PrintContact, Sysops), + halt(1); + {Realm, UserName, KeyNames} -> + KIDs = [{Realm, KeyName} || KeyName <- KeyNames], + {{Realm, UserName}, KIDs}; + false -> + Message = "You are not a user of the given realm: ~160tp.", + ok = log(warning, Message, [Realm]), + halt(1) + end, + KeyID = hd(KeyIDs), + true = zx_key:ensure_keypair(KeyID), + {ok, Key} = zx_key:load(private, KeyID), + {User, KeyID, Key}. + + +-spec disconnect(gen_tcp:socket()) -> ok. +%% @private +%% Gracefully shut down a socket, logging (but sidestepping) the case when the socket +%% has already been closed by the other side. + +disconnect(Socket) -> + case gen_tcp:shutdown(Socket, read_write) of + ok -> + log(info, "Disconnected from ~tp", [Socket]); + {error, Error} -> + Message = "Shutdown connection ~p failed with: ~p", + log(warning, Message, [Socket, Error]) + end. diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_conf_sys.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_conf_sys.erl index d487626..146fec8 100644 --- a/zomp/lib/otpr/zx/0.1.0/src/zx_conf_sys.erl +++ b/zomp/lib/otpr/zx/0.1.0/src/zx_conf_sys.erl @@ -23,7 +23,7 @@ retries/1, retries/2, retry/1, retries_left/1, maxconn/1, maxconn/2, managed/1, managed/2, add_managed/2, rem_managed/2, - mirrors/1, mirrors/2, add_mirror/2, rem_mirror/2, next_mirror/1, + mirrors/1, mirrors/2, add_mirror/2, rem_mirror/2, reset/0]). -export_type([data/0]). @@ -35,11 +35,11 @@ %%% Type Definitions -record(d, - {timeout = 5 :: pos_integer(), - retries = {0, 3} :: non_neg_integer(), - maxconn = 5 :: pos_integer(), - managed = sets:new() :: sets:set(zx:realm()), - mirrors = queue:new() :: queue:queue(zx:host())}). + {timeout = 5 :: pos_integer(), + retries = {3, 3} :: non_neg_integer(), + maxconn = 5 :: pos_integer(), + managed = sets:new() :: sets:set(zx:realm()), + mirrors = [] :: [zx:host()]}). -opaque data() :: #d{}. @@ -55,11 +55,12 @@ %% be called by zx_daemon and utility code. load() -> - case file:consult(path()) of + Path = path(), + case file:consult(Path) of {ok, List} -> populate_data(List); {error, Reason} -> - ok = log(error, "Load etc/sys.conf failed with: ~tp", [Reason]), + ok = log(error, "Load ~tp failed with: ~tp", [Path, Reason]), Data = #d{}, ok = save(Data), Data @@ -69,28 +70,28 @@ load() -> populate_data(List) -> Timeout = case proplists:get_value(timeout, List, 5) of - V when is_integer(V) and V > 0 -> V; - _ -> 5 + TO when is_integer(TO) and TO > 0 -> TO; + _ -> 5 end, - Retry = - case proplists:get_value(retry, List, 3) of - V when is_integer(V) and V > 0 -> V; - _ -> 3 + Retries = + case proplists:get_value(retries, List, 3) of + RT when is_integer(RT) and RT > 0 -> {RT, RT}; + _ -> 3 end, MaxConn = case proplists:get_value(maxconn, List, 5) of - V when is_integer(V) and V > 0 -> V; - _ -> 5 + MC when is_integer(MC) and MC > 0 -> MC; + _ -> 5 end, Managed = case proplists:get_value(managed, List, []) of - V when is_list(V) -> sets:from_list(V); - _ -> sets:new() + MN when is_list(MN) -> sets:from_list(MN); + _ -> sets:new() end, Mirrors = case proplists:get_value(mirrors, List, []) of - V when is_list(V) -> queue:from_list(V); - _ -> queue:new() + MR when is_list(MR) -> MR; + _ -> [] end, #d{timeout = Timeout, retries = Retries, @@ -113,7 +114,7 @@ save(#d{timeout = Timeout, {retries, Retries}, {maxconn, MaxConn}, {managed, sets:to_list(Managed)}, - {mirrors, queue:to_list(Mirrors)}], + {mirrors, Mirrors}], ok = zx_lib:write_terms(path(), Terms), log(info, "Wrote etc/sys.conf"). @@ -142,7 +143,7 @@ timeout(Data, Value) %% @doc %% Return the retries value. -retries(#d{retries = Retries}) -> +retries(#d{retries = {_, Retries}}) -> Retries. @@ -153,7 +154,7 @@ retries(#d{retries = Retries}) -> %% @doc %% Set the retries attribute to a new value. -retries(Data = #d{retries = {Remaining, _}, Value) -> +retries(Data = #d{retries = {Remaining, _}}, Value) when is_integer(Value) and Value >= 0 -> Data#d{retries = {Remaining, Value}}. @@ -170,7 +171,7 @@ retries(Data = #d{retries = {Remaining, _}, Value) -> retry(#d{retries = {0, _}}) -> no_retries; retry(Data = #d{retries = {Remaining, Setting}}) -> - NewRemaining = Current - 1, + NewRemaining = Remaining - 1, NewData = Data#d{retries = {NewRemaining, Setting}}, {ok, NewData}. @@ -220,27 +221,108 @@ managed(#d{managed = Managed}) -> %% The realms must be configured on the current realm at a minimum. managed(Data, List) -> - Scrubbed = scrub_realms(List), - NewManaged = sets:from_list(Scrubbed), + Desired = sets:from_list(List), + Configured = sets:from_list(zx_lib:list_realms()), + NewManaged = sets:intersection(Desired, Configured), Data#d{managed = NewManaged}. -scrub_realms(List) -> - %... - []. - - --spec add_managed(Data, Realm) -> {ok, +-spec add_managed(Data, Realm) -> Result when Data :: data(), Realm :: zx:realm(), + Result :: {ok, NewData} + | {error, unconfigured}, NewData :: data(). %% @doc %% Add a new realm to the list of managed realms. The new realm must be configured on -%% the current node. +%% the current node. This node will then behave as the prime node for the realm (whether +%% it is or not). add_managed(Data = #d{managed = Managed}, Realm) -> - case zx_lib:valid_lower0_9(Realm) of - + case lists:member(Realm, zx_lib:list_realms()) of + true -> + NewData = Data#d{managed = sets:add_element(Realm, Managed)}, + ok = log(info, "Now managing realm: ~tp", [Realm]), + {ok, NewData}; + false -> + ok = log(warning, "Cannot manage unconfigured realm: ~tp", [Realm]), + {error, unconfigured} + end. + + +-spec rem_managed(Data, Realm) -> Result + when Data :: data(), + Realm :: zx:realm(), + Result :: {ok, NewData} + | {error, unmanaged}, + NewData :: data(). +%% @doc +%% Stop managing a realm. + +rem_managed(Data = #d{managed = Managed}, Realm) -> + case sets:is_element(Realm, Managed) of + true -> + NewData = Data#d{managed = sets:del_element(Realm, Managed)}, + ok = log(info, "No longer managing realm: ~tp", [Realm]), + {ok, NewData}; + false -> + ok = log(warning, "Cannot stop managing unmanaged realm: ~tp", [Realm]), + {error, unmanaged} + end. + + +-spec mirrors(data()) -> [zx:host()]. +%% @doc +%% Return the list of private mirrors. + +mirrors(#d{mirrors = Mirrors}) -> + Mirrors. + + +-spec mirrors(Data, Hosts) -> NewData + when Data :: data(), + Hosts :: [zx:host()], + NewData :: data(). +%% @private +%% Reset the mirror configuration. + +mirrors(Data, Hosts) -> + Data#d{mirrors = Hosts}. + + +-spec add_mirror(Data, Host) -> NewData + when Data :: data(), + Host :: zx:host(), + NewData :: data(). +%% @doc +%% Add a mirror to the permanent configuration. + +add_mirror(Data = #d{mirrors = Mirrors}, Host) -> + case lists:member(Host, Mirrors) of + false -> Data#d{mirrors = [Host | Mirrors]}; + true -> Data + end. + + +-spec rem_mirror(Data, Host) -> NewData + when Data :: data(), + Host :: zx:host(), + NewData :: data(). +%% @private +%% Remove a host from the list of permanent mirrors. + +rem_mirror(Data = #d{mirrors = Mirrors}, Host) -> + Data#d{mirrors = lists:delete(Host, Mirrors)}. + + +-spec reset() -> data(). +%% @private +%% Reset sys.conf. + +reset() -> + Data = #d{}, + save(Data), + Data. -spec path() -> file:filename(). diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_conn.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_conn.erl index 1c84891..a302a85 100644 --- a/zomp/lib/otpr/zx/0.1.0/src/zx_conn.erl +++ b/zomp/lib/otpr/zx/0.1.0/src/zx_conn.erl @@ -352,19 +352,19 @@ interpret_response(Socket, {sub, Channel, Message}, Command) -> %% Download a package to the local cache. fetch(Socket, PackageID) -> - {ok, LatestID} = request_zrp(Socket, PackageID), - ok = receive_zrp(Socket, LatestID), + {ok, LatestID} = request_zsp(Socket, PackageID), + ok = receive_zsp(Socket, LatestID), Latest = zx_lib:package_string(LatestID), log(info, "Fetched ~ts", [Latest]). --spec request_zrp(Socket, PackageID) -> Result +-spec request_zsp(Socket, PackageID) -> Result when Socket :: gen_tcp:socket(), PackageID :: zx:package_id(), Result :: {ok, Latest :: zx:package_id()} | {error, Reason :: timeout | term()}. -request_zrp(Socket, PackageID) -> +request_zsp(Socket, PackageID) -> ok = zx_net:send(Socket, {fetch, PackageID}), receive {tcp, Socket, Bin} -> @@ -384,15 +384,15 @@ request_zrp(Socket, PackageID) -> end. --spec receive_zrp(Socket, PackageID) -> Result +-spec receive_zsp(Socket, PackageID) -> Result when Socket :: gen_tcp:socket(), PackageID :: zx:package_id(), Result :: ok | {error, timeout}. -receive_zrp(Socket, PackageID) -> +receive_zsp(Socket, PackageID) -> receive {tcp, Socket, Bin} -> - ZrpPath = filename:join("zrp", zx_lib:namify_zrp(PackageID)), + ZrpPath = filename:join("zsp", zx_lib:namify_zsp(PackageID)), ok = file:write_file(ZrpPath, Bin), ok = zx_net:send(Socket, ok), log(info, "Wrote ~ts", [ZrpPath]); @@ -516,7 +516,7 @@ terminate() -> %% sourced, but exit with an error if it cannot locate or acquire the package. % %ensure_dep(Socket, PackageID) -> -% ZrpFile = filename:join("zrp", namify_zrp(PackageID)), +% ZrpFile = filename:join("zsp", namify_zsp(PackageID)), % ok = % case filelib:is_regular(ZrpFile) of % true -> ok; diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_daemon.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_daemon.erl index 86296c1..a7dada8 100644 --- a/zomp/lib/otpr/zx/0.1.0/src/zx_daemon.erl +++ b/zomp/lib/otpr/zx/0.1.0/src/zx_daemon.erl @@ -1355,14 +1355,14 @@ cx_load() -> Reason :: no_realms | file:posix(). %% @private -%% This procedure, relying zx_lib:zomp_home() allows the system to load zomp data +%% This procedure, relying zx_lib:zomp_dir() allows the system to load zomp data %% from any arbitrary home for zomp. This has been included mostly to make testing of %% Zomp and ZX easier, but incidentally opens the possibility that an arbitrary Zomp %% home could be selected by an installer (especially on consumer systems like Windows %% where any number of wild things might be going on in the user's filesystem). cx_populate() -> - Home = zx_lib:zomp_home(), + Home = zx_lib:zomp_dir(), Pattern = filename:join(Home, "*.realm"), case filelib:wildcard(Pattern) of [] -> {error, no_realms}; @@ -1477,7 +1477,7 @@ cx_write_cache({Realm, -spec cx_cache_file(zx:realm()) -> file:filename(). cx_cache_file(Realm) -> - filename:join(zx_lib:zomp_home(), Realm ++ ".cache"). + filename:join(zx_lib:zomp_dir(), Realm ++ ".cache"). -spec cx_realms(conn_index()) -> [zx:realms()]. diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_key.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_key.erl new file mode 100644 index 0000000..2fc785d --- /dev/null +++ b/zomp/lib/otpr/zx/0.1.0/src/zx_key.erl @@ -0,0 +1,280 @@ +%%% @doc +%%% ZX Key +%%% +%%% Abstraction module for dealing with keys. +%%% +%%% "Ewwwww! Keys!" +%%% -- Bertrand Russel +%%% @end + +-module(zx_key). +-author("Craig Everett "). +-copyright("Craig Everett "). +-license("GPL-3.0"). + +-export([ensure_keypair/1, have_public_key/1, have_private_key/1, + prompt_keygen/0, create_keypair/0, generate_rsa/1, + load/2, verify/3]). + +-include("zx_logger.hrl"). + + +%%% Functions + +-spec ensure_keypair(zx:key_id()) -> true | no_return(). +%% @private +%% Check if both the public and private key based on KeyID exists. + +ensure_keypair(KeyID = {Realm, KeyName}) -> + case {have_public_key(KeyID), have_private_key(KeyID)} of + {true, true} -> + true; + {false, true} -> + Message = "Public key for ~tp/~tp cannot be found", + ok = log(error, Message, [Realm, KeyName]), + halt(1); + {true, false} -> + Message = "Private key for ~tp/~tp cannot be found", + ok = log(error, Message, [Realm, KeyName]), + halt(1); + {false, false} -> + Message = "Key pair for ~tp/~tp cannot be found", + ok = log(error, Message, [Realm, KeyName]), + halt(1) + end. + + +-spec have_public_key(zx:key_id()) -> boolean(). +%% @private +%% Determine whether the public key indicated by KeyID is in the keystore. + +have_public_key({Realm, KeyName}) -> + PublicKeyFile = KeyName ++ ".pub.der", + PublicKeyPath = filename:join([zx_lib:zomp_dir(), "key", Realm, PublicKeyFile]), + filelib:is_regular(PublicKeyPath). + + +-spec have_private_key(zx:key_id()) -> boolean(). +%% @private +%% Determine whether the private key indicated by KeyID is in the keystore. + +have_private_key({Realm, KeyName}) -> + PrivateKeyFile = KeyName ++ ".key.der", + PrivateKeyPath = filename:join([zx_lib:zomp_dir(), "key", Realm, PrivateKeyFile]), + filelib:is_regular(PrivateKeyPath). + + + +%%% Key generation + +-spec prompt_keygen() -> zx:key_id(). +%% @private +%% Prompt the user for a valid KeyPrefix to use for naming a new RSA keypair. + +prompt_keygen() -> + Message = + "~n Enter a name for your new keys.~n~n" + " Valid names must start with a lower-case letter, and can include~n" + " only lower-case letters, numbers, and periods, but no series of~n" + " consecutive periods. (That is: [a-z0-9\\.])~n~n" + " To designate the key as realm-specific, enter the realm name and~n" + " key name separated by a space.~n~n" + " Example: some.realm my.key~n", + ok = io:format(Message), + Input = zx_tty:get_input(), + {Realm, KeyName} = + case string:lexemes(Input, " ") of + [R, K] -> {R, K}; + [K] -> {"otpr", K} + end, + case {zx_lib:valid_lower0_9(Realm), zx_lib:valid_label(KeyName)} of + {true, true} -> + {Realm, KeyName}; + {false, true} -> + ok = io:format("Bad realm name ~tp. Try again.~n", [Realm]), + prompt_keygen(); + {true, false} -> + ok = io:format("Bad key name ~tp. Try again.~n", [KeyName]), + prompt_keygen(); + {false, false} -> + ok = io:format("NUTS! Both key and realm names are illegal. Try again.~n"), + prompt_keygen() + end. + + +-spec create_keypair() -> no_return(). +%% @private +%% Execute the key generation procedure for 16k RSA keys once and then terminate. + +create_keypair() -> + ok = file:set_cwd(zx_lib:zomp_dir()), + KeyID = prompt_keygen(), + case generate_rsa(KeyID) of + {ok, _, _} -> halt(0); + Error -> zx:error_exit("create_keypair/0 error: ~tp", [Error], ?LINE) + end. + + +-spec generate_rsa(KeyID) -> Result + when KeyID :: zx:key_id(), + Result :: {ok, KeyFile, PubFile} + | {error, keygen_fail}, + KeyFile :: file:filename(), + PubFile :: file:filename(). +%% @private +%% Generate an RSA keypair and write them in der format to the current directory, using +%% filenames derived from Prefix. +%% NOTE: The current version of this command is likely to only work on a unix system. + +generate_rsa({Realm, KeyName}) -> + KeyDir = filename:join([zx_lib:zomp_dir(), "key", Realm]), + ok = zx_lib:force_dir(KeyDir), + PemFile = filename:join(KeyDir, KeyName ++ ".pub.pem"), + KeyFile = filename:join(KeyDir, KeyName ++ ".key.der"), + PubFile = filename:join(KeyDir, KeyName ++ ".pub.der"), + ok = lists:foreach(fun zx_lib:halt_if_exists/1, [PemFile, KeyFile, PubFile]), + ok = log(info, "Generating ~p and ~p. Please be patient...", [KeyFile, PubFile]), + ok = gen_p_key(KeyFile), + ok = der_to_pem(KeyFile, PemFile), + {ok, PemBin} = file:read_file(PemFile), + [PemData] = public_key:pem_decode(PemBin), + Pub = public_key:pem_entry_decode(PemData), + PubDer = public_key:der_encode('RSAPublicKey', Pub), + ok = file:write_file(PubFile, PubDer), + case check_key(KeyFile, PubFile) of + true -> + ok = file:delete(PemFile), + ok = log(info, "~ts and ~ts agree", [KeyFile, PubFile]), + ok = log(info, "Wrote private key to: ~ts.", [KeyFile]), + ok = log(info, "Wrote public key to: ~ts.", [PubFile]), + {ok, KeyFile, PubFile}; + false -> + ok = lists:foreach(fun file:delete/1, [PemFile, KeyFile, PubFile]), + ok = log(error, "Something has gone wrong."), + {error, keygen_fail} + end. + + +-spec gen_p_key(KeyFile) -> ok + when KeyFile :: file:filename(). +%% @private +%% Format an openssl shell command that will generate proper 16k RSA keys. + +gen_p_key(KeyFile) -> + Command = + io_lib:format("~ts genpkey" + " -algorithm rsa" + " -out ~ts" + " -outform DER" + " -pkeyopt rsa_keygen_bits:16384", + [openssl(), KeyFile]), + Out = os:cmd(Command), + io:format(Out). + + +-spec der_to_pem(KeyFile, PemFile) -> ok + when KeyFile :: file:filename(), + PemFile :: file:filename(). +%% @private +%% Format an openssl shell command that will convert the given keyfile to a pemfile. +%% The reason for this conversion is to sidestep some formatting weirdness that OpenSSL +%% injects into its generated DER formatted key output (namely, a few empty headers) +%% which Erlang's ASN.1 defintion files do not take into account. A conversion to PEM +%% then a conversion back to DER (via Erlang's ASN.1 module) resolves this in a reliable +%% way. + +der_to_pem(KeyFile, PemFile) -> + Command = + io_lib:format("~ts rsa" + " -inform DER" + " -in ~ts" + " -outform PEM" + " -pubout" + " -out ~ts", + [openssl(), KeyFile, PemFile]), + Out = os:cmd(Command), + io:format(Out). + + +-spec check_key(KeyFile, PubFile) -> Result + when KeyFile :: file:filename(), + PubFile :: file:filename(), + Result :: true | false. +%% @private +%% Compare two keys for pairedness. + +check_key(KeyFile, PubFile) -> + {ok, KeyBin} = file:read_file(KeyFile), + {ok, PubBin} = file:read_file(PubFile), + Key = public_key:der_decode('RSAPrivateKey', KeyBin), + Pub = public_key:der_decode('RSAPublicKey', PubBin), + TestMessage = <<"Some test data to sign.">>, + Signature = public_key:sign(TestMessage, sha512, Key), + public_key:verify(TestMessage, sha512, Signature, Pub). + + +-spec openssl() -> Executable | no_return() + when Executable :: file:filename(). +%% @private +%% Attempt to locate the installed openssl executable for use in shell commands. +%% Halts execution with an error message if the executable cannot be found. + +openssl() -> + OpenSSL = + case os:type() of + {unix, _} -> "openssl"; + {win32, _} -> "openssl.exe" + end, + ok = + case os:find_executable(OpenSSL) of + false -> + ok = log(error, "OpenSSL could not be found in this system's PATH."), + ok = log(error, "Install OpenSSL and then retry."), + zx:error_exit("Missing system dependenct: OpenSSL", ?LINE); + Path -> + log(info, "OpenSSL executable found at: ~ts", [Path]) + end, + OpenSSL. + + +-spec load(Type, KeyID) -> Result + when Type :: private | public, + KeyID :: zx:key_id(), + Result :: {ok, DecodedKey :: term()} + | {error, Reason :: term()}. +%% @private +%% Hide the details behind reading and loading DER encoded RSA key files. + +load(Type, {Realm, KeyName}) -> + {DerType, Path} = + case Type of + private -> + KeyDer = KeyName ++ ".key.der", + P = filename:join([zx_lib:zomp_dir(), "key", Realm, KeyDer]), + {'RSAPrivateKey', P}; + public -> + PubDer = KeyName ++ ".pub.der", + P = filename:join([zx_lib:zomp_dir(), "key", Realm, PubDer]), + {'RSAPublicKey', P} + end, + ok = log(info, "Loading key from file ~ts", [Path]), + case file:read_file(Path) of + {ok, Bin} -> {ok, public_key:der_decode(DerType, Bin)}; + Error -> Error + end. + + +-spec verify(Data, Signature, PubKey) -> ok | no_return() + when Data :: binary(), + Signature :: binary(), + PubKey :: public_key:rsa_public_key(). +%% @private +%% Verify the RSA Signature of some Data against the given PubKey or halt execution. +%% This function always assumes sha512 is the algorithm being used. +%% Should only ever be called by the initial launch process. + +verify(Data, Signature, PubKey) -> + case public_key:verify(Data, sha512, Signature, PubKey) of + true -> ok; + false -> zx:error_exit("Bad package signature!", ?LINE) + end. diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_lib.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_lib.erl index afd1665..64ab93c 100644 --- a/zomp/lib/otpr/zx/0.1.0/src/zx_lib.erl +++ b/zomp/lib/otpr/zx/0.1.0/src/zx_lib.erl @@ -16,6 +16,8 @@ -export([zomp_dir/0, find_zomp_dir/0, path/1, path/2, path/3, + force_dir/1, + list_realms/0, hosts_cache_file/1, get_prime/1, realm_meta/1, read_project_meta/0, read_project_meta/1, read_package_meta/1, write_project_meta/1, write_project_meta/2, @@ -24,9 +26,10 @@ string_to_version/1, version_to_string/1, package_id/1, package_string/1, package_dir/1, package_dir/2, - namify_zrp/1, namify_tgz/1, + namify_zsp/1, namify_tgz/1, find_latest_compatible/2, installed/1, - realm_conf/1, load_realm_conf/1]). + realm_conf/1, load_realm_conf/1, + extract_zsp_or_die/1, halt_if_exists/1]). -include("zx_logger.hrl"). @@ -57,7 +60,7 @@ find_zomp_dir() -> case os:type() of {unix, _} -> Home = os:getenv("HOME"), - Dir = "zomp", + Dir = ".zomp", filename:join(Home, Dir); {win32, _} -> Home = os:getenv("LOCALAPPDATA"), @@ -73,7 +76,7 @@ find_zomp_dir() -> | log | lib, Result :: file:filename(). -%% @doc +%% @private %% Return the top-level path of the given type in the Zomp/ZX system. path(etc) -> filename:join(zomp_dir(), "etc"); @@ -91,7 +94,7 @@ path(lib) -> filename:join(zomp_dir(), "lib"). | lib, Realm :: zx:realm(), Result :: file:filename(). -%% @doc +%% @private %% Return the realm-level path of the given type in the Zomp/ZX system. path(Type, Realm) -> @@ -107,13 +110,28 @@ path(Type, Realm) -> Realm :: zx:realm(), Name :: zx:name(), Result :: file:filename(). -%% @doc +%% @private %% Return the package-level path of the given type in the Zomp/ZX system. path(Type, Realm, Name) -> filename:join([path(Type), Realm, Name]). +-spec force_dir(Path) -> Result + when Path :: file:filename(), + Result :: ok + | {error, file:posix()}. +%% @private +%% Guarantee a directory path is created if it is possible to create or if it already +%% exists. + +force_dir(Path) -> + case filelib:is_dir(Path) of + true -> ok; + false -> filelib:ensure_dir(filename:join(Path, "foo")) + end. + + -spec hosts_cache_file(zx:realm()) -> file:filename(). %% @private %% Given a Realm name, construct a realm's .hosts filename and return it. @@ -122,6 +140,15 @@ hosts_cache_file(Realm) -> filename:join(zomp_dir(), Realm ++ ".hosts"). +-spec list_realms() -> [zx:realm()]. +%% @private +%% Check the filesystem for etc/[Realm Name]/realm.conf files. + +list_realms() -> + Pattern = filename:join([path(etc), "*", "realm.conf"]), + [filename:basename(filename:dirname(C)) || C <- filelib:wildcard(Pattern)]. + + -spec get_prime(Realm) -> Result when Realm :: zx:realm(), Result :: {ok, zx:host()} @@ -151,7 +178,7 @@ get_prime(Realm) -> %% the file. realm_meta(Realm) -> - RealmFile = filename:join(zomp_dir(), Realm ++ ".realm"), + RealmFile = filename:join(path(etc, Realm), "realm.conf"), file:consult(RealmFile). @@ -516,13 +543,13 @@ package_dir(Prefix, {Realm, Name}) -> filename:join([zomp_dir(), Prefix, PackageString]). --spec namify_zrp(PackageID) -> ZrpFileName +-spec namify_zsp(PackageID) -> ZrpFileName when PackageID :: zx:package_id(), ZrpFileName :: file:filename(). %% @private -%% Map an PackageID to its correct .zrp package file name. +%% Map an PackageID to its correct .zsp package file name. -namify_zrp(PackageID) -> namify(PackageID, "zrp"). +namify_zsp(PackageID) -> namify(PackageID, "zsp"). -spec namify_tgz(PackageID) -> TgzFileName @@ -620,5 +647,46 @@ realm_conf(Realm) -> %% Load the config for the given realm or halt with an error. load_realm_conf(Realm) -> - Path = filename:join(zomp_dir(), realm_conf(Realm)), - file:consult(Path). + Path = filename:join(path(etc, Realm), "realm.conf"), + case file:consult(Path) of + {ok, C} -> + C; + {error, enoent} -> + ok = log(warning, "Realm ~tp is not configured.", [Realm]), + halt(1) + end. + + +-spec extract_zsp_or_die(FileName) -> Files | no_return() + when FileName :: file:filename(), + Files :: [{file:filename(), binary()}]. +%% @private +%% Extract a zsp archive, if possible. If not possible, halt execution with as accurate +%% an error message as can be managed. + +extract_zsp_or_die(FileName) -> + case erl_tar:extract(FileName, [memory]) of + {ok, Files} -> + Files; + {error, {FileName, enoent}} -> + Message = "Can't find file ~ts.", + zx:error_exit(Message, [FileName], ?LINE); + {error, invalid_tar_checksum} -> + Message = "~ts is not a valid zsp archive.", + zx:error_exit(Message, [FileName], ?LINE); + {error, Reason} -> + Message = "Extracting package file failed with: ~160tp.", + zx:error_exit(Message, [Reason], ?LINE) + end. + + +-spec halt_if_exists(file:filename()) -> ok | no_return(). +%% @private +%% A helper function to guard against overwriting an existing file. Halts execution if +%% the file is found to exist. + +halt_if_exists(Path) -> + case filelib:is_file(Path) of + true -> zx:error_exit("~ts already exists! Halting.", [Path], ?LINE); + false -> ok + end. diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_tty.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_tty.erl new file mode 100644 index 0000000..46e91e7 --- /dev/null +++ b/zomp/lib/otpr/zx/0.1.0/src/zx_tty.erl @@ -0,0 +1,101 @@ +%%% @doc +%%% ZX TTY +%%% +%%% This module lets other parts of ZX interact (very clumsily) with the user via a text +%%% interface. Hopefully this will never be called on Windows. +%%% @end + +-module(zx_tty). +-author("Craig Everett "). +-copyright("Craig Everett "). +-license("GPL-3.0"). + +-export([get_input/0, select/1, select_string/1]). + + +%%% Type Definitions + +-type option() :: {string(), term()}. + + +%%% User menu interface (terminal) + +-spec get_input() -> string(). +%% @private +%% Provide a standard input prompt and newline sanitized return value. + +get_input() -> + string:trim(io:get_line("(^C to quit): ")). + + +-spec select(Options) -> Selected + when Options :: [option()], + Selected :: term(). +%% @private +%% Take a list of Options to present the user, then return the indicated option to the +%% caller once the user selects something. + +select(Options) -> + Max = show(Options), + case pick(string:to_integer(io:get_line("(or ^C to quit)~n ? ")), Max) of + error -> + ok = hurr(), + select(Options); + I -> + {_, Value} = lists:nth(I, Options), + Value + end. + + +-spec select_string(Strings) -> Selected + when Strings :: [string()], + Selected :: string(). +%% @private +%% @equiv select([{S, S} || S <- Strings]) + +select_string(Strings) -> + select([{S, S} || S <- Strings]). + + +-spec show(Options) -> Index + when Options :: [option()], + Index :: pos_integer(). +%% @private +%% @equiv show(Options, 0). + +show(Options) -> + show(Options, 0). + + +-spec show(Options, Index) -> Count + when Options :: [option()], + Index :: non_neg_integer(), + Count :: pos_integer(). +%% @private +%% Display the list of options needed to the user, and return the option total count. + +show([], I) -> + I; +show([{Label, _} | Rest], I) -> + Z = I + 1, + ok = io:format(" ~2w - ~ts~n", [Z, Label]), + show(Rest, Z). + + +-spec pick({Selection, term()}, Max) -> Result + when Selection :: error | integer(), + Max :: pos_integer(), + Result :: pos_integer() | error. +%% @private +%% Interpret a user's selection returning either a valid selection index or `error'. + +pick({error, _}, _) -> error; +pick({I, _}, Max) when 0 < I, I =< Max -> I; +pick(_, _) -> error. + + +-spec hurr() -> ok. +%% @private +%% Present an appropriate response when the user derps on selection. + +hurr() -> io:format("That isn't an option.~n"). diff --git a/zomp/zx b/zomp/zx index 8f3cea1..96f8928 100755 --- a/zomp/zx +++ b/zomp/zx @@ -1,10 +1,10 @@ #!/bin/sh -ZOMP_DIR="$HOME/zomp" +ZOMP_DIR="$HOME/.zomp" VERSION=$(cat "$ZOMP_DIR/etc/version.txt") ZX_DIR="$ZOMP_DIR/lib/otpr/zx/$VERSION" -pushd "$ZX_DIR" +pushd "$ZX_DIR" > /dev/null ./make_zx -popd +popd > /dev/null erl -pa "$ZX_DIR/ebin" -run zx start $@ diff --git a/zx_dev b/zx_dev index 596b40b..2f4b9c2 100755 --- a/zx_dev +++ b/zx_dev @@ -1,11 +1,13 @@ #!/bin/bash -ZX_DEV_ROOT=$(dirname $BASH_SOURCE) -ZOMP_DIR="$ZX_DEV_ROOT/zomp" -VERSION=$(cat "$ZOMP_DIR/etc/version.txt") -ZX_DIR="$ZOMP_DIR/lib/otpr/zx/$VERSION" +pushd $(dirname $BASH_SOURCE) > /dev/null +export ZX_DEV_ROOT=$PWD +popd > /dev/null +export ZOMP_DIR="$ZX_DEV_ROOT/zomp" +export VERSION=$(cat "$ZOMP_DIR/etc/version.txt") +export ZX_DIR="$ZOMP_DIR/lib/otpr/zx/$VERSION" -pushd "$ZX_DIR" +pushd "$ZX_DIR" > /dev/null ./make_zx -popd +popd > /dev/null erl -pa "$ZX_DIR/ebin" -run zx start $@ From 98f4b6bdf39dd518c060d606eca73d38f76c6d75 Mon Sep 17 00:00:00 2001 From: Craig Everett Date: Tue, 29 May 2018 22:16:11 +0900 Subject: [PATCH 55/55] So much foo --- .gitignore | 1 + zomp/lib/otpr/zx/0.1.0/src/zx.erl | 1385 +++-------------------- zomp/lib/otpr/zx/0.1.0/src/zx_auth.erl | 50 +- zomp/lib/otpr/zx/0.1.0/src/zx_conn.erl | 12 +- zomp/lib/otpr/zx/0.1.0/src/zx_key.erl | 38 +- zomp/lib/otpr/zx/0.1.0/src/zx_lib.erl | 78 +- zomp/lib/otpr/zx/0.1.0/src/zx_local.erl | 1177 +++++++++++++++++++ zomp/zx | 2 +- zomp/zx.cmd | 2 +- zx_dev | 10 +- 10 files changed, 1501 insertions(+), 1254 deletions(-) create mode 100644 zomp/lib/otpr/zx/0.1.0/src/zx_local.erl diff --git a/.gitignore b/.gitignore index bbcd1d5..aa7b2ab 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .eunit deps +tester *.o *.beam *.plt diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx.erl b/zomp/lib/otpr/zx/0.1.0/src/zx.erl index 977b688..1d9fd9c 100644 --- a/zomp/lib/otpr/zx/0.1.0/src/zx.erl +++ b/zomp/lib/otpr/zx/0.1.0/src/zx.erl @@ -19,10 +19,10 @@ -license("GPL-3.0"). --export([start/1]). +-export([run/0, run/1]). -export([subscribe/1, unsubscribe/0]). -export([start/2, stop/1, stop/0]). --export([error_exit/2, error_exit/3]). +-export([usage_exit/1]). -export_type([serial/0, package_id/0, package/0, realm/0, name/0, version/0, identifier/0, @@ -69,99 +69,130 @@ %%% Command Dispatch --spec start(Args) -> no_return() +-spec run() -> no_return(). + +run() -> + run([]). + + +-spec run(Args) -> no_return() when Args :: [string()]. %% Dispatch work functions based on the nature of the input arguments. -start(["help"]) -> +run(["help"]) -> usage_exit(0); -start(["run", PackageString | Args]) -> +run(["run", PackageString | Args]) -> ok = start(), run(PackageString, Args); -start(["runlocal" | ArgV]) -> +run(["runlocal" | ArgV]) -> ok = start(), run_local(ArgV); -start(["init", "app", PackageString]) -> - initialize(app, PackageString); -start(["init", "lib", PackageString]) -> - initialize(lib, PackageString); -start(["install", PackageFile]) -> +run(["init", "app", PackageString]) -> + ok = compatibility_check([unix]), + zx_local:initialize(app, PackageString); +run(["init", "lib", PackageString]) -> + ok = compatibility_check([unix]), + zx_local:initialize(lib, PackageString); +run(["install", PackageFile]) -> + zx_local:assimilate(PackageFile); +run(["set", "dep", PackageString]) -> + zx_local:set_dep(PackageString); +run(["set", "version", VersionString]) -> + ok = compatibility_check([unix]), + zx_local:set_version(VersionString); +run(["verup", Level]) -> + ok = compatibility_check([unix]), + zx_local:verup(Level); +run(["list", "realms"]) -> + zx_loca:list_realms(); +run(["list", "packages", Realm]) -> ok = start(), - assimilate(PackageFile); -start(["set", "dep", PackageString]) -> - set_dep(PackageString); -start(["set", "version", VersionString]) -> - set_version(VersionString); -start(["list", "realms"]) -> - list_realms(); -start(["list", "packages", Realm]) -> + zx_local:list_packages(Realm); +run(["list", "versions", PackageName]) -> ok = start(), - list_packages(Realm); -start(["list", "versions", PackageName]) -> - ok = start(), - list_versions(PackageName); -start(["add", "realm", RealmFile]) -> - add_realm(RealmFile); -start(["drop", "dep", PackageString]) -> + zx_local:list_versions(PackageName); +run(["add", "realm", RealmFile]) -> + zx_local:add_realm(RealmFile); +run(["drop", "dep", PackageString]) -> PackageID = zx_lib:package_id(PackageString), - drop_dep(PackageID); -start(["drop", "key", KeyID]) -> - drop_key(KeyID); -start(["drop", "realm", Realm]) -> - drop_realm(Realm); -start(["verup", Level]) -> - verup(Level); -start(["package"]) -> + zx_local:drop_dep(PackageID); +run(["drop", "key", Realm, KeyName]) -> + zx_key:drop({Realm, KeyName}); +run(["drop", "realm", Realm]) -> + zx_local:drop_realm(Realm); +run(["package"]) -> {ok, TargetDir} = file:get_cwd(), - package(TargetDir); -start(["package", TargetDir]) -> + zx_local:package(TargetDir); +run(["package", TargetDir]) -> case filelib:is_dir(TargetDir) of true -> - package(TargetDir); + zx_local:package(TargetDir); false -> ok = log(error, "Target directory ~tp does not exist!", [TargetDir]), halt(22) end; -start(["dialyze"]) -> - dialyze(); -start(["create", "user", Realm, Name]) -> - create_user(Realm, Name); -start(["create", "keypair"]) -> - zx_key:create_keypair(); -start(["create", "plt"]) -> - create_plt(); -start(["create", "realm"]) -> - create_realm(); -start(["create", "realmfile", Realm]) -> - create_realmfile(Realm); -start(["list", "pending", PackageName]) -> +run(["dialyze"]) -> + zx_local:dialyze(); +run(["create", "user", Realm, Name]) -> + zx_local:create_user(Realm, Name); +run(["create", "keypair"]) -> + zx_key:grow_a_pair(); +run(["create", "plt"]) -> + zx_local:create_plt(); +run(["create", "realm"]) -> + zx_local:create_realm(); +run(["create", "realmfile", Realm]) -> + zx_local:create_realmfile(Realm); +run(["list", "pending", PackageName]) -> zx_auth:list_pending(PackageName); -start(["list", "resigns", Realm]) -> +run(["list", "resigns", Realm]) -> zx_auth:list_resigns(Realm); -start(["submit", PackageFile]) -> +run(["submit", PackageFile]) -> zx_auth:submit(PackageFile); -start(["review", PackageString]) -> +run(["review", PackageString]) -> zx_auth:review(PackageString); -start(["approve", PackageString]) -> +run(["approve", PackageString]) -> PackageID = zx_lib:package_id(PackageString), zx_auth:approve(PackageID); -start(["reject", PackageString]) -> +run(["reject", PackageString]) -> PackageID = zx_lib:package_id(PackageString), zx_auth:reject(PackageID); -start(["accept", PackageString]) -> +run(["accept", PackageString]) -> zx_auth:accept(PackageString); -start(["add", "packager", Package, UserName]) -> +run(["add", "packager", Package, UserName]) -> zx_auth:add_packager(Package, UserName); -start(["add", "maintainer", Package, UserName]) -> +run(["add", "maintainer", Package, UserName]) -> zx_auth:add_maintainer(Package, UserName); -start(["add", "sysop", Package, UserName]) -> +run(["add", "sysop", Package, UserName]) -> zx_auth:add_sysop(Package, UserName); -start(["add", "package", PackageName]) -> +run(["add", "package", PackageName]) -> zx_auth:add_package(PackageName); -start(_) -> +run(_) -> usage_exit(22). +-spec compatibility_check(Platforms) -> ok | no_return() + when Platforms :: unix | win32. +%% @private +%% Some commands only work on specific platforms because they leverage some specific +%% aspect on that platform, but not common to all. ATM this is mostly developer +%% commands that leverage things universal to *nix/posix shells but not Windows. +%% If equivalent procedures are written in Erlang then these restrictions can be +%% avoided -- but it is unclear whether there are any Erlang developers even using +%% Windows, so for now this is the bad version of the solution. + +compatibility_check(Platforms) -> + {Family, Name} = os:type(), + case lists:member(Family, Platforms) of + true -> + ok; + false -> + Message = "Unfortunately this command is not available on ~tp ~tp", + ok = log(error, Message, [Family, Name]), + halt(0) + end. + + %%% Application Start/Stop @@ -299,9 +330,9 @@ run(Identifier, RunArgs) -> %% and use zx commands to add or drop dependencies made available via zomp. run_local(RunArgs) -> - Meta = zx_lib:read_project_meta(), + {ok, Meta} = zx_lib:read_project_meta(), PackageID = maps:get(package_id, Meta), - ok = build(), + ok = zx_lib:build(), {ok, Dir} = file:get_cwd(), ok = file:set_cwd(zx_lib:zomp_dir()), ok = start(), @@ -388,154 +419,6 @@ end. -%%% Project initialization - --spec initialize(Type, PackageString) -> no_return() - when Type :: app | lib, - PackageString :: string(). -%% @private -%% Initialize an application in the local directory based on the PackageID provided. -%% This function does not care about the name of the current directory and leaves -%% providing a complete, proper and accurate PackageID. -%% This function will check the current `lib/' directory for zomp-style dependencies. -%% If this is not the intended function or if there are non-compliant directory names -%% in `lib/' then the project will need to be rearranged to become zomp compliant or -%% the `deps' section of the resulting meta file will need to be manually updated. - -initialize(Type, PackageString) -> - PackageID = - case zx_lib:package_id(PackageString) of - {ok, ID} -> - ID; - {error, invalid_package_string} -> - error_exit("Invalid package string.", ?LINE) - end, - ok = log(info, "Initializing ~s...", [PackageString]), - MetaList = - [{package_id, PackageID}, - {deps, []}, - {type, Type}], - Meta = maps:from_list(MetaList), - ok = zx_lib:write_project_meta(Meta), - ok = log(info, "Project ~tp initialized.", [PackageString]), - Message = - "NOTICE:~n" - " This project is currently listed as having no dependencies.~n" - " If this is not true then run `zx set dep DepID` for each current dependency.~n" - " (run `zx help` for more information on usage)~n", - ok = io:format(Message), - halt(0). - - - -%%% Add a package from a local file - --spec assimilate(PackageFile) -> PackageID - when PackageFile :: file:filename(), - PackageID :: package_id(). -%% @private -%% Receives a path to a file containing package data, examines it, and copies it to a -%% canonical location under a canonical name, returning the PackageID of the package -%% contents. - -assimilate(PackageFile) -> - Files = zx_lib:extract_zsp_or_die(PackageFile), - {ok, CWD} = file:get_cwd(), - ok = file:set_cwd(zx_lib:zomp_dir()), - {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), - Meta = binary_to_term(MetaBin), - PackageID = maps:get(package_id, Meta), - TgzFile = zx_lib:namify_tgz(PackageID), - {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files), - {KeyID, Signature} = maps:get(sig, Meta), - {ok, PubKey} = zx_key:load(public, KeyID), - ok = - case public_key:verify(TgzData, sha512, Signature, PubKey) of - true -> - ZrpPath = filename:join("zsp", zx_lib:namify_zsp(PackageID)), - file:copy(PackageFile, ZrpPath); - false -> - error_exit("Bad package signature: ~ts", [PackageFile], ?LINE) - end, - ok = file:set_cwd(CWD), - Message = "~ts is now locally available.", - {ok, PackageString} = zx_lib:package_string(PackageID), - ok = log(info, Message, [PackageString]), - halt(0). - - - -%%% Set dependency - --spec set_dep(Identifier :: string()) -> no_return(). -%% @private -%% Set a specific dependency in the current project. If the project currently has a -%% dependency on the same package then the version of that dependency is updated to -%% reflect that in the PackageString argument. The AppString is permitted to be -%% incomplete. Incomplete elements of the VersionString (if included) will default to -%% the latest version available at the indicated level. - -set_dep(Identifier) -> - {ok, {Realm, Name, FuzzyVersion}} = zx_lib:package_id(Identifier), - Version = - case FuzzyVersion of - {z, z, z} -> - ok = start(), - {ok, V} = zx_daemon:query_latest({Realm, Name}), - V; - {X, Y, Z} when is_integer(X), is_integer(Y), is_integer(Z) -> - {X, Y, Z}; - _ -> - ok = start(), - {ok, V} = zx_daemon:query_latest({Realm, Name, FuzzyVersion}), - V - end, - set_dep({Realm, Name}, Version). - - -set_dep({Realm, Name}, Version) -> - PackageID = {Realm, Name, Version}, - {ok, Meta} = zx_lib:read_project_meta(), - Deps = maps:get(deps, Meta), - case lists:member(PackageID, Deps) of - true -> - {ok, PackageString} = zx_lib:package_string(PackageID), - ok = log(info, "~ts is already a dependency", [PackageString]), - halt(0); - false -> - set_dep(PackageID, Deps, Meta) - end. - - --spec set_dep(PackageID, Deps, Meta) -> no_return() - when PackageID :: package_id(), - Deps :: [package_id()], - Meta :: [term()]. -%% @private -%% Given the PackageID, list of Deps and the current contents of the project Meta, add -%% or update Deps to include (or update) Deps to reflect a dependency on PackageID, if -%% such a dependency is not already present. Then write the project meta back to its -%% file and exit. - -set_dep(PackageID = {Realm, Name, NewVersion}, Deps, Meta) -> - ExistingPackageIDs = fun({R, N, _}) -> {R, N} == {Realm, Name} end, - NewDeps = - case lists:partition(ExistingPackageIDs, Deps) of - {[{Realm, Name, OldVersion}], Rest} -> - Message = "Updating dep ~ts to ~ts", - {ok, OldPS} = zx_lib:package_string({Realm, Name, OldVersion}), - {ok, NewPS} = zx_lib:package_string({Realm, Name, NewVersion}), - ok = log(info, Message, [OldPS, NewPS]), - [PackageID | Rest]; - {[], Deps} -> - {ok, PackageString} = zx_lib:package_string(PackageID), - ok = log(info, "Adding dep ~ts", [PackageString]), - [PackageID | Deps] - end, - NewMeta = maps:put(deps, NewDeps, Meta), - ok = zx_lib:write_project_meta(NewMeta), - halt(0). - -spec ensure_installed(PackageID) -> Result | no_return() when PackageID :: package_id(), @@ -605,887 +488,6 @@ tuplize(String, Acc) -> -%%% Set version - --spec set_version(VersionString) -> no_return() - when VersionString :: string(). -%% @private -%% Convert a version string to a new version, sanitizing it in the process and returning -%% a reasonable error message on bad input. - -set_version(VersionString) -> - NewVersion = - case zx_lib:string_to_version(VersionString) of - {ok, {_, _, z}} -> - Message = "'set version' arguments must be complete, ex: 1.2.3", - error_exit(Message, ?LINE); - {ok, Version} -> - Version; - {error, invalid_version_string} -> - Message = "Invalid version string: ~tp", - error_exit(Message, [VersionString], ?LINE) - end, - {ok, Meta} = zx_lib:read_project_meta(), - {Realm, Name, OldVersion} = maps:get(package_id, Meta), - update_version(Realm, Name, OldVersion, NewVersion, Meta). - - --spec update_version(Realm, Name, OldVersion, NewVersion, OldMeta) -> no_return() - when Realm :: realm(), - Name :: name(), - OldVersion :: version(), - NewVersion :: version(), - OldMeta :: package_meta(). -%% @private -%% Update a project's `zomp.meta' file by either incrementing the indicated component, -%% or setting the version number to the one specified in VersionString. -%% This part of the procedure updates the meta and does the final write, if the write -%% turns out to be possible. If successful it will indicate to the user what was -%% changed. - -update_version(Realm, Name, OldVersion, NewVersion, OldMeta) -> - PackageID = {Realm, Name, NewVersion}, - NewMeta = maps:put(package_id, PackageID, OldMeta), - ok = zx_lib:write_project_meta(NewMeta), - OldVS = zx_lib:version_to_string(OldVersion), - NewVS = zx_lib:version_to_string(NewVersion), - ok = log(info, "Version changed from ~s to ~s.", [OldVS, NewVS]), - halt(0). - - - -%%% List Functions - --spec list_realms() -> no_return(). -%% @private -%% List all currently configured realms. The definition of a "configured realm" is a -%% realm for which a .realm file exists in $ZOMP_HOME. The realms will be printed to -%% stdout and the program will exit. - -list_realms() -> - ok = lists:foreach(fun(R) -> io:format("~ts~n", [R]) end, zx_lib:list_realms()), - halt(0). - - --spec list_packages(realm()) -> no_return(). -%% @private -%% Contact the indicated realm and query it for a list of registered packages and print -%% them to stdout. - -list_packages(Realm) -> - ok = start(), - case zx_daemon:list_packages(Realm) of - {ok, []} -> - ok = log(info, "Realm ~tp has no packages available.", [Realm]), - halt(0); - {ok, Packages} -> - Print = fun({R, N}) -> io:format("~ts-~ts~n", [R, N]) end, - ok = lists:foreach(Print, Packages), - halt(0); - {error, bad_realm} -> - error_exit("Bad realm name.", ?LINE); - {error, no_realm} -> - error_exit("Realm \"~ts\" is not configured.", ?LINE); - {error, network} -> - Message = "Network issues are preventing connection to the realm.", - error_exit(Message, ?LINE) - end. - - --spec list_versions(PackageName :: string()) -> no_return(). -%% @private -%% List the available versions of the package indicated. The user enters a string-form -%% package name (such as "otpr-zomp") and the return values will be full package strings -%% of the form "otpr-zomp-1.2.3", one per line printed to stdout. - -list_versions(PackageName) -> - Package = {Realm, Name} = - case zx_lib:package_id(PackageName) of - {ok, {R, N, {z, z, z}}} -> - {R, N}; - {error, invalid_package_string} -> - error_exit("~tp is not a valid package name.", [PackageName], ?LINE) - end, - ok = start(), - case zx_daemon:list_versions(Package) of - {ok, []} -> - Message = "Package ~ts has no versions available.", - ok = log(info, Message, [PackageName]), - halt(0); - {ok, Versions} -> - Print = - fun(Version) -> - {ok, PackageString} = zx_lib:package_string({Realm, Name, Version}), - io:format("~ts~n", [PackageString]) - end, - ok = lists:foreach(Print, Versions), - halt(0); - {error, bad_realm} -> - error_exit("Bad realm name.", ?LINE); - {error, bad_package} -> - error_exit("Bad package name.", ?LINE); - {error, network} -> - Message = "Network issues are preventing connection to the realm.", - error_exit(Message, ?LINE) - end. - - - -%%% Add realm - --spec add_realm(Path) -> no_return() - when Path :: file:filename(). -%% @private -%% Add a .realm file to $ZOMP_HOME from a location in the filesystem. -%% Print the SHA512 of the .realm file for the user so they can verify that the file -%% is authentic. This implies, of course, that .realm maintainers are going to -%% post SHA512 sums somewhere visible. - -add_realm(Path) -> - case file:read_file(Path) of - {ok, Data} -> - Digest = crypto:hash(sha512, Data), - Text = integer_to_list(binary:decode_unsigned(Digest, big), 16), - ok = log(info, "SHA512 of ~ts: ~ts", [Path, Text]), - add_realm(Path, Data); - {error, enoent} -> - ok = log(warning, "FAILED: ~ts does not exist.", [Path]), - halt(1); - {error, eisdir} -> - ok = log(warning, "FAILED: ~ts is a directory, not a realm file.", [Path]), - halt(1) - end. - - --spec add_realm(Path, Data) -> no_return() - when Path :: file:filename(), - Data :: binary(). - -add_realm(Path, Data) -> - case erl_tar:extract({binary, Data}, [compressed, {cwd, zx_lib:zomp_dir()}]) of - ok -> - {Realm, _} = string:take(filename:basename(Path), ".", true), - ok = log(info, "Realm ~ts is now visible to this system.", [Realm]), - halt(0); - {error, invalid_tar_checksum} -> - error_exit("~ts is not a valid realm file.", [Path], ?LINE); - {error, eof} -> - error_exit("~ts is not a valid realm file.", [Path], ?LINE) - end. - - - -%%% Drop dependency - --spec drop_dep(package_id()) -> no_return(). -%% @private -%% Remove the indicate dependency from the local project's zomp.meta record. - -drop_dep(PackageID) -> - {ok, PackageString} = zx_lib:package_string(PackageID), - {ok, Meta} = zx_lib:read_project_meta(), - Deps = maps:get(deps, Meta), - case lists:member(PackageID, Deps) of - true -> - NewDeps = lists:delete(PackageID, Deps), - NewMeta = maps:put(deps, NewDeps, Meta), - ok = zx_lib:write_project_meta(NewMeta), - Message = "~ts removed from dependencies.", - ok = log(info, Message, [PackageString]), - halt(0); - false -> - ok = log(info, "~ts not found in dependencies.", [PackageString]), - halt(0) - end. - - - -%%% Drop key - --spec drop_key(key_id()) -> no_return(). -%% @private -%% Given a KeyID, remove the related public and private keys from the keystore, if they -%% exist. If not, exit with a message that no keys were found, but do not return an -%% error exit value (this instruction is idempotent if used in shell scripts). - -drop_key({Realm, KeyName}) -> - ok = file:set_cwd(zx_lib:zomp_dir()), - KeyGlob = KeyName ++ ".{key,pub},der", - Pattern = filename:join([zx_lib:zomp_dir(), "key", Realm, KeyGlob]), - case filelib:wildcard(Pattern) of - [] -> - ok = log(warning, "Key ~ts/~ts not found", [Realm, KeyName]), - halt(0); - Files -> - ok = lists:foreach(fun file:delete/1, Files), - ok = log(info, "Keyset ~ts/~ts removed", [Realm, KeyName]), - halt(0) - end. - - -%%% Drop realm - --spec drop_realm(realm()) -> no_return(). - -drop_realm(Realm) -> - ok = file:set_cwd(zx_lib:zomp_dir()), - RealmConf = zx_lib:realm_conf(Realm), - case filelib:is_regular(RealmConf) of - true -> - Message = - "~n" - " WARNING: Are you SURE you want to remove realm ~ts?~n" - " (Only \"Y\" will confirm this action.)~n", - ok = io:format(Message, [Realm]), - case zx_tty:get_input() of - "Y" -> - ok = file:delete(RealmConf), - ok = drop_prime(Realm), - ok = clear_keys(Realm), - ok = log(info, "All traces of realm ~ts have been removed."), - halt(0); - _ -> - ok = log(info, "Aborting."), - halt(0) - end; - false -> - ok = log(warning, "Realm conf ~ts not found.", [RealmConf]), - clear_keys(Realm) - end. - - --spec drop_prime(realm()) -> ok. - -drop_prime(Realm) -> - Path = "zomp.conf", - case file:consult(Path) of - {ok, Conf} -> - {managed, Primes} = lists:keyfind(managed, 1, Conf), - NewPrimes = lists:delete(Realm, Primes), - NewConf = lists:keystore(managed, 1, Primes, {managed, NewPrimes}), - ok = zx_lib:write_terms(Path, NewConf), - log(info, "Ensuring ~ts is not a prime in ~ts", [Realm, Path]); - {error, enoent} -> - ok - end. - - --spec clear_keys(realm()) -> ok. - -clear_keys(Realm) -> - KeyDir = filename:join([zx_lib:zomp_dir(), "key", Realm]), - case filelib:is_dir(KeyDir) of - true -> rm_rf(KeyDir); - false -> log(warning, "Keydir ~ts not found", [KeyDir]) - end. - - - -%%% Update version - --spec verup(Level) -> no_return() - when Level :: string(). -%% @private -%% Convert input string arguments to acceptable atoms for use in update_version/1. - -verup("major") -> version_up(major); -verup("minor") -> version_up(minor); -verup("patch") -> version_up(patch); -verup(_) -> usage_exit(22). - - --spec version_up(Level) -> no_return() - when Level :: major - | minor - | patch. -%% @private -%% Update a project's `zomp.meta' file by either incrementing the indicated component, -%% or setting the version number to the one specified in VersionString. -%% This part of the procedure guards for the case when the zomp.meta file cannot be -%% read for some reason. - -version_up(Arg) -> - {ok, Meta} = zx_lib:read_project_meta(), - PackageID = maps:get(package_id, Meta), - version_up(Arg, PackageID, Meta). - - --spec version_up(Level, PackageID, Meta) -> no_return() - when Level :: major - | minor - | patch - | version(), - PackageID :: package_id(), - Meta :: [{atom(), term()}]. -%% @private -%% Update a project's `zomp.meta' file by either incrementing the indicated component, -%% or setting the version number to the one specified in VersionString. -%% This part of the procedure does the actual update calculation, to include calling to -%% convert the VersionString (if it is passed) to a `version()' type and check its -%% validity (or halt if it is a bad string). - -version_up(major, {Realm, Name, OldVersion = {Major, _, _}}, OldMeta) -> - NewVersion = {Major + 1, 0, 0}, - update_version(Realm, Name, OldVersion, NewVersion, OldMeta); -version_up(minor, {Realm, Name, OldVersion = {Major, Minor, _}}, OldMeta) -> - NewVersion = {Major, Minor + 1, 0}, - update_version(Realm, Name, OldVersion, NewVersion, OldMeta); -version_up(patch, {Realm, Name, OldVersion = {Major, Minor, Patch}}, OldMeta) -> - NewVersion = {Major, Minor, Patch + 1}, - update_version(Realm, Name, OldVersion, NewVersion, OldMeta). - - - -%%% Package generation - --spec package(TargetDir) -> no_return() - when TargetDir :: file:filename(). -%% @private -%% Turn a target project directory into a package, prompting the user for appropriate -%% key selection or generation actions along the way. - -package(TargetDir) -> - ok = log(info, "Packaging ~ts", [TargetDir]), - {ok, Meta} = zx_lib:read_project_meta(TargetDir), - {Realm, _, _} = maps:get(package_id, Meta), - KeyDir = filename:join([zx_lib:zomp_dir(), "key", Realm]), - ok = zx_lib:force_dir(KeyDir), - Pattern = KeyDir ++ "/*.key.der", - case [filename:basename(F, ".key.der") || F <- filelib:wildcard(Pattern)] of - [] -> - ok = log(info, "Need to generate key"), - KeyID = zx_key:prompt_keygen(), - {ok, _, _} = zx_key:generate_rsa(KeyID), - package(KeyID, TargetDir); - [KeyName] -> - KeyID = {Realm, KeyName}, - ok = log(info, "Using key: ~ts/~ts", [Realm, KeyName]), - package(KeyID, TargetDir); - KeyNames -> - KeyName = zx_tty:select_string(KeyNames), - package({Realm, KeyName}, TargetDir) - end. - - --spec package(KeyID, TargetDir) -> no_return() - when KeyID :: key_id(), - TargetDir :: file:filename(). -%% @private -%% Accept a KeyPrefix for signing and a TargetDir containing a project to package and -%% build a zsp package file ready to be submitted to a repository. - -package(KeyID, TargetDir) -> - {ok, Meta} = zx_lib:read_project_meta(TargetDir), - PackageID = maps:get(package_id, Meta), - true = element(1, PackageID) == element(1, KeyID), - {ok, PackageString} = zx_lib:package_string(PackageID), - ZrpFile = PackageString ++ ".zsp", - TgzFile = PackageString ++ ".tgz", - ok = zx_lib:halt_if_exists(ZrpFile), - ok = remove_binaries(TargetDir), - {ok, Everything} = file:list_dir(TargetDir), - DotFiles = filelib:wildcard(".*", TargetDir), - Ignores = ["lib" | DotFiles], - Targets = lists:subtract(Everything, Ignores), - {ok, CWD} = file:get_cwd(), - ok = file:set_cwd(TargetDir), - ok = build(), - Modules = - [filename:basename(M, ".beam") || M <- filelib:wildcard("*.beam", "ebin")], - ok = remove_binaries("."), - ok = erl_tar:create(filename:join(CWD, TgzFile), Targets, [compressed]), - ok = file:set_cwd(CWD), - {ok, Key} = zx_key:load(private, KeyID), - {ok, TgzBin} = file:read_file(TgzFile), - Sig = public_key:sign(TgzBin, sha512, Key), - Add = fun({K, V}, M) -> maps:put(K, V, M) end, - FinalMeta = lists:foldl(Add, Meta, [{modules, Modules}, {sig, {KeyID, Sig}}]), - ok = file:write_file("zomp.meta", term_to_binary(FinalMeta)), - ok = erl_tar:create(ZrpFile, ["zomp.meta", TgzFile]), - ok = file:delete(TgzFile), - ok = file:delete("zomp.meta"), - ok = log(info, "Wrote archive ~ts", [ZrpFile]), - halt(0). - - --spec remove_binaries(TargetDir) -> ok - when TargetDir :: file:filename(). -%% @private -%% Procedure to delete all .beam and .ez files from a given directory starting at -%% TargetDir. Called as part of the pre-packaging sanitization procedure. - -remove_binaries(TargetDir) -> - Beams = filelib:wildcard("**/*.{beam,ez}", TargetDir), - case [filename:join(TargetDir, Beam) || Beam <- Beams] of - [] -> - ok; - ToDelete -> - ok = log(info, "Removing: ~tp", [ToDelete]), - lists:foreach(fun file:delete/1, ToDelete) - end. - - - -%%% Generate PLT - --spec create_plt() -> no_return(). -%% @private -%% Generate a fresh PLT file that includes most basic core applications needed to -%% make a resonable estimate of a type system, write the name of the PLT to stdout, -%% and exit. - -create_plt() -> - ok = build_plt(), - halt(0). - - --spec build_plt() -> ok. -%% @private -%% Build a general plt file for Dialyzer based on the core Erland distro. -%% TODO: Make a per-package + dependencies version of this. - -build_plt() -> - PLT = default_plt(), - Template = - "dialyzer --build_plt" - " --output_plt ~ts" - " --apps asn1 reltool wx common_test crypto erts eunit inets" - " kernel mnesia public_key sasl ssh ssl stdlib", - Command = io_lib:format(Template, [PLT]), - Message = - "Generating PLT file and writing to: ~tp~n" - " There will be a list of \"unknown functions\" in the final output.~n" - " Don't panic. This is normal. Turtles all the way down, after all...", - ok = log(info, Message, [PLT]), - ok = log(info, "This may take a while. Patience is a virtue."), - Out = os:cmd(Command), - log(info, Out). - - --spec default_plt() -> file:filename(). - -default_plt() -> - filename:join(zx_lib:zomp_dir(), "basic.plt"). - - - -%%% Dialyze - --spec dialyze() -> no_return(). -%% @private -%% Preps a copy of this script for typechecking with Dialyzer. -%% TODO: Create a package_id() based version of this to handle dialyzation of complex -%% projects. - -dialyze() -> - PLT = default_plt(), - ok = - case filelib:is_regular(PLT) of - true -> log(info, "Using PLT: ~tp", [PLT]); - false -> build_plt() - end, - TmpDir = filename:join(zx_lib:zomp_dir(), "tmp"), - Me = escript:script_name(), - EvilTwin = filename:join(TmpDir, filename:basename(Me ++ ".erl")), - ok = log(info, "Temporarily reconstructing ~tp as ~tp", [Me, EvilTwin]), - Sed = io_lib:format("sed 's/^#!.*$//' ~s > ~s", [Me, EvilTwin]), - "" = os:cmd(Sed), - ok = case dialyzer:run([{init_plt, PLT}, {from, src_code}, {files, [EvilTwin]}]) of - [] -> - io:format("Dialyzer found no errors and returned no warnings! Yay!~n"); - Warnings -> - Mine = [dialyzer:format_warning({Tag, {Me, Line}, Msg}) - || {Tag, {_, Line}, Msg} <- Warnings], - lists:foreach(fun io:format/1, Mine) - end, - ok = file:delete(EvilTwin), - halt(0). - - - -%%% Create Realm & Sysop - --spec create_user(realm(), user_name()) -> no_return(). -%% @private -%% Validate the realm and username provided, prompt the user to either select a keypair -%% to use or generate a new one, and bundle a .zuser file for conveyance of the user -%% data and his relevant keys (for import into an existing zomp server via `add' -%% command like "add packager", "add maintainer" and "add sysop". - -create_user(Realm, Username) -> - Message = "Would be generating a user file for {~160tp, ~160to}.", - ok = log(info, Message, [Realm, Username]), - halt(0). - - --spec create_realm() -> no_return(). -%% @private -%% Prompt the user to input the information necessary to create a new zomp realm, -%% package the data appropriately for the server and deliver the final keys and -%% realm file to the user. - -create_realm() -> - Instructions = - "~n" - " Enter a name for your new realm.~n" - " Names can contain only lower-case letters, numbers and the underscore.~n" - " Names must begin with a lower-case letter.~n", - ok = io:format(Instructions), - Realm = zx_tty:get_input(), - case zx_lib:valid_lower0_9(Realm) of - true -> - RealmFile = filename:join(zx_lib:zomp_dir(), Realm ++ ".realm"), - case filelib:is_regular(RealmFile) of - false -> - create_realm(Realm); - true -> - ok = io:format("That realm already exists. Be more original.~n"), - create_realm() - end; - false -> - ok = io:format("Bad realm name \"~ts\". Try again.~n", [Realm]), - create_realm() - end. - - --spec create_realm(Realm) -> no_return() - when Realm :: realm(). - -create_realm(Realm) -> - ExAddress = prompt_external_address(), - create_realm(Realm, ExAddress). - - --spec prompt_external_address() -> Result - when Result :: inet:hostname() | inet:ip_address(). - -prompt_external_address() -> - Message = external_address_prompt(), - ok = io:format(Message), - case zx_tty:get_input() of - "" -> - ok = io:format("You need to enter an address.~n"), - prompt_external_address(); - String -> - parse_address(String) - end. - - --spec external_address_prompt() -> string(). - -external_address_prompt() -> - "~n" - " Enter a static, valid hostname or IPv4 or IPv6 address at which this host " - "can be reached from the public internet (or internal network if it will never " - "need to be reached from the internet).~n" - " DO NOT INCLUDE A PORT NUMBER IN THIS STEP~n". - - --spec parse_address(string()) -> inet:hostname() | inet:ip_address(). - -parse_address(String) -> - case inet:parse_address(String) of - {ok, Address} -> Address; - {error, einval} -> String - end. - - --spec create_realm(Realm, ExAddress) -> no_return() - when Realm :: realm(), - ExAddress :: inet:hostname() | inet:ip_address(). - -create_realm(Realm, ExAddress) -> - Message = - "~n" - " Enter the public (external) port number at which this service should be " - "available. (This might be different from the local port number if you are " - "forwarding ports or have a complex network layout.)~n", - ok = io:format(Message), - ExPort = prompt_port_number(11311), - create_realm(Realm, ExAddress, ExPort). - - --spec create_realm(Realm, ExAddress, ExPort) -> no_return() - when Realm :: realm(), - ExAddress :: inet:hostname() | inet:ip_address(), - ExPort :: inet:port_number(). - -create_realm(Realm, ExAddress, ExPort) -> - Message = - "~n" - " Enter the local (internal/LAN) port number at which this service should be " - "available. (This might be different from the public port visible from the " - "internet if you are port forwarding or have a complex network layout.)~n", - ok = io:format(Message), - InPort = prompt_port_number(11311), - create_realm(Realm, ExAddress, ExPort, InPort). - - --spec prompt_port_number(Current) -> Result - when Current :: inet:port_number(), - Result :: inet:port_number(). - -prompt_port_number(Current) -> - Instructions = - " A valid port is any number from 1 to 65535." - " [Press enter to accept the current setting: ~tw]~n", - ok = io:format(Instructions, [Current]), - case zx_tty:get_input() of - "" -> - Current; - S -> - try - case list_to_integer(S) of - Port when 16#ffff >= Port, Port > 0 -> - Port; - Illegal -> - Whoops = "Whoops! ~tw is out of bounds (1~65535). Try again.~n", - ok = io:format(Whoops, [Illegal]), - prompt_port_number(Current) - end - catch error:badarg -> - ok = io:format("~tp is not a port number. Try again...", [S]), - prompt_port_number(Current) - end - end. - - --spec create_realm(Realm, ExAddress, ExPort, InPort) -> no_return() - when Realm :: realm(), - ExAddress :: inet:hostname() | inet:ip_address(), - ExPort :: inet:port_number(), - InPort :: inet:port_number(). - -create_realm(Realm, ExAddress, ExPort, InPort) -> - Instructions = - "~n" - " Enter a username for the realm sysop.~n" - " Names can contain only lower-case letters, numbers and the underscore.~n" - " Names must begin with a lower-case letter.~n", - ok = io:format(Instructions), - UserName = zx_tty:get_input(), - case zx_lib:valid_lower0_9(UserName) of - true -> - create_realm(Realm, ExAddress, ExPort, InPort, UserName); - false -> - ok = io:format("Bad username ~tp. Try again.~n", [UserName]), - create_realm(Realm, ExAddress, ExPort, InPort) - end. - - --spec create_realm(Realm, ExAddress, ExPort, InPort, UserName) -> no_return() - when Realm :: realm(), - ExAddress :: inet:hostname() | inet:ip_address(), - ExPort :: inet:port_number(), - InPort :: inet:port_number(), - UserName :: string(). - -create_realm(Realm, ExAddress, ExPort, InPort, UserName) -> - Instructions = - "~n" - " Enter an email address for the realm sysop.~n" - " Valid email address rules apply though the checking done here is quite " - "minimal. Check the address you enter carefully. The only people who will " - "suffer from an invalid address are your users.~n", - ok = io:format(Instructions), - Email = zx_tty:get_input(), - [User, Host] = string:lexemes(Email, "@"), - case {zx_lib:valid_lower0_9(User), zx_lib:valid_label(Host)} of - {true, true} -> - create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email); - {false, true} -> - Message = "The user part of the email address seems invalid. Try again.~n", - ok = io:format(Message), - create_realm(Realm, ExAddress, ExPort, InPort, UserName); - {true, false} -> - Message = "The host part of the email address seems invalid. Try again.~n", - ok = io:format(Message), - create_realm(Realm, ExAddress, ExPort, InPort, UserName); - {false, false} -> - Message = "This email address seems like its totally bonkers. Try again.~n", - ok = io:format(Message), - create_realm(Realm, ExAddress, ExPort, InPort, UserName) - end. - - --spec create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email) -> - no_return() - when Realm :: realm(), - ExAddress :: inet:hostname() | inet:ip_address(), - ExPort :: inet:port_number(), - InPort :: inet:port_number(), - UserName :: string(), - Email :: string(). - -create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email) -> - Instructions = - "~n" - " Enter the real name (or whatever name people recognize) for the sysop.~n" - " There are no rules for this one. Any valid UTF-8 printables are legal.~n", - ok = io:format(Instructions), - RealName = zx_tty:get_input(), - create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email, RealName). - - --spec create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email, RealName) -> no_return() - when Realm :: realm(), - ExAddress :: inet:hostname() | inet:ip_address(), - ExPort :: inet:port_number(), - InPort :: inet:port_number(), - UserName :: string(), - Email :: string(), - RealName :: string(). - -create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email, RealName) -> - ok = io:format("~nGenerating keys. This might take a while, so settle in...~n"), - {ok, RealmKey, RealmPub} = zx_key:generate_rsa({Realm, Realm ++ ".1.realm"}), - {ok, PackageKey, PackagePub} = zx_key:generate_rsa({Realm, Realm ++ ".1.package"}), - {ok, SysopKey, SysopPub} = zx_key:generate_rsa({Realm, UserName ++ ".1"}), - ok = log(info, "Generated 16k RSA pair ~ts ~ts", [RealmKey, RealmPub]), - ok = log(info, "Generated 16k RSA pair ~ts ~ts", [PackageKey, PackagePub]), - ok = log(info, "Generated 16k RSA pair ~ts ~ts", [SysopKey, SysopPub]), - - Timestamp = calendar:now_to_universal_time(erlang:timestamp()), - - {ok, RealmPubData} = file:read_file(RealmPub), - RealmPubRecord = - {{Realm, filename:basename(RealmPub, ".pub.der")}, - realm, - {realm, Realm}, - crypto:hash(sha512, RealmPubData), - Timestamp}, - {ok, PackagePubData} = file:read_file(PackagePub), - PackagePubRecord = - {{Realm, filename:basename(PackagePub, ".pub.der")}, - package, - {realm, Realm}, - crypto:hash(sha512, PackagePubData), - Timestamp}, - UserRecord = - {{Realm, UserName}, - [filename:basename(SysopPub, ".pub.der")], - Email, - RealName}, - RealmSettings = - [{realm, Realm}, - {revision, 0}, - {prime, {ExAddress, ExPort}}, - {private, []}, - {mirrors, []}, - {sysops, [UserRecord]}, - {realm_keys, [RealmPubRecord]}, - {package_keys, [PackagePubRecord]}], - ZompSettings = - [{managed, [Realm]}, - {external_address, ExAddress}, - {external_port, ExPort}, - {internal_port, InPort}], - - {ok, CWD} = file:get_cwd(), - {ok, TempDir} = mktemp_dir("zomp"), - ok = file:set_cwd(TempDir), - KeyDir = filename:join("key", Realm), - ok = filelib:ensure_dir(KeyDir), - ok = file:make_dir(KeyDir), - KeyCopy = - fun(K) -> - {ok, _} = file:copy(K, filename:join(KeyDir, filename:basename(K))), - ok - end, - - PublicZRF = filename:join(CWD, Realm ++ ".zrf"), - RealmFN = Realm ++ ".realm", - ok = zx_lib:write_terms(RealmFN, RealmSettings), - ok = KeyCopy(PackagePub), - ok = KeyCopy(RealmPub), - ok = erl_tar:create(PublicZRF, [RealmFN, "key"], [compressed]), - - PrimeZRF = filename:join(CWD, Realm ++ ".zpf"), - ok = KeyCopy(SysopPub), - ok = zx_lib:write_terms("zomp.conf", ZompSettings), - ok = erl_tar:create(PrimeZRF, [RealmFN, "zomp.conf", "key"], [compressed]), - - KeyBundle = filename:join(CWD, Realm ++ ".zkf"), - ok = lists:foreach(KeyCopy, [PackageKey, RealmKey, SysopKey]), - ok = erl_tar:create(KeyBundle, [KeyDir], [compressed]), - - ok = file:set_cwd(CWD), - ok = rm_rf(TempDir), - - Message = - "===========================================================================~n" - "DONE!~n" - "~n" - "The realm ~ts has been created and is accessible from the current system.~n" - "Three configuration bundles have been created in the current directory:~n" - "~n" - " 1. ~ts ~n" - "This is the PRIVATE realm file you will need to install on the realm's prime~n" - "node. It includes the your (the sysop's) public key.~n" - "~n" - " 2. ~ts ~n" - "This file is the PUBLIC realm file other zomp nodes and zx users will need~n" - "to access the realm. It does not include your (the sysop's) public key.~n" - "~n" - " 3. ~ts ~n" - "This is the bundle of ALL KEYS that are defined in this realm at the moment.~n" - "~n" - "Now you need to make copies of these three files and back them up.~n" - "~n" - "On the PRIME NODE you need to run `zx add realm ~ts` and follow the prompts~n" - "to cause it to begin serving that realm as prime. (Node restart required.)~n" - "~n" - "On all zx CLIENTS that want to access your new realm and on all subordinate~n" - "MIRROR NODES the command `zx add realm ~ts` will need to be run.~n" - "The method of public realm file distribution (~ts) is up to you.~n" - "~n" - "~n" - "Public & Private key installation (if you need to recover them or perform~n" - "sysop functions from another computer) is `zx add keybundle ~ts`.~n" - "===========================================================================~n", - Substitutions = - [Realm, - PrimeZRF, PublicZRF, KeyBundle, - PrimeZRF, - PublicZRF, PublicZRF, - KeyBundle], - ok = io:format(Message, Substitutions), - halt(0). - - --spec create_realmfile(realm()) -> no_return(). - -create_realmfile(Realm) -> - RealmConf = zx_lib:load_realm_conf(Realm), - ok = log(info, "Realm found, creating realm file..."), - {revision, Revision} = lists:keyfind(revision, 1, RealmConf), - {realm_keys, RealmKeys} = lists:keyfind(realm_keys, 1, RealmConf), - {package_keys, PackageKeys} = lists:keyfind(package_keys, 1, RealmConf), - RealmKeyIDs = [element(1, K) || K <- RealmKeys], - PackageKeyIDs = [element(1, K) || K <- PackageKeys], - create_realmfile(Realm, Revision, RealmKeyIDs, PackageKeyIDs). - - --spec create_realmfile(Realm, Revision, RealmKeyIDs, PackageKeyIDs) -> ok - when Realm :: realm(), - Revision :: non_neg_integer(), - RealmKeyIDs :: [key_id()], - PackageKeyIDs :: [key_id()]. - -create_realmfile(Realm, Revision, RealmKeyIDs, PackageKeyIDs) -> - {ok, CWD} = file:get_cwd(), - ok = file:set_cwd(zx_lib:zomp_dir()), - KeyPath = fun({R, K}) -> filename:join(["key", R, K ++ ".pub.der"]) end, - RealmKeyPaths = lists:map(KeyPath, RealmKeyIDs), - PackageKeyPaths = lists:map(KeyPath, PackageKeyIDs), - Targets = [zx_lib:realm_conf(Realm) | RealmKeyPaths ++ PackageKeyPaths], - OutFile = filename:join(CWD, Realm ++ "." ++ integer_to_list(Revision) ++ ".zrf"), - ok = erl_tar:create(OutFile, Targets, [compressed]), - ok = log(info, "Realm conf file written to ~ts", [OutFile]), - halt(0). - - - %%% Package utilities @@ -1525,78 +527,13 @@ install(PackageID) -> build(PackageID) -> {ok, CWD} = file:get_cwd(), ok = file:set_cwd(zx_lib:package_dir(PackageID)), - ok = build(), + ok = zx_lib:build(), file:set_cwd(CWD). --spec build() -> ok. -%% @private -%% Run any local `zxmake' script needed by the project for non-Erlang code (if present), -%% then add the local `ebin/' directory to the runtime search path, and finally build -%% the Erlang part of the project with make:all/0 according to the local `Emakefile'. - -build() -> - ZxMake = "zxmake", - ok = - case filelib:is_regular(ZxMake) of - true -> - Out = os:cmd(ZxMake), - log(info, Out); - false -> - ok - end, - true = code:add_patha(filename:absname("ebin")), - up_to_date = make:all(), - ok. - - %%% Directory & File Management --spec mktemp_dir(Prefix) -> Result - when Prefix :: string(), - Result :: {ok, TempDir :: file:filename()} - | {error, Reason :: file:posix()}. - -mktemp_dir(Prefix) -> - Rand = integer_to_list(binary:decode_unsigned(crypto:strong_rand_bytes(8)), 36), - TempPath = filename:basedir(user_cache, Prefix), - TempDir = filename:join(TempPath, Rand), - Result1 = filelib:ensure_dir(TempDir), - Result2 = file:make_dir(TempDir), - case {Result1, Result2} of - {ok, ok} -> {ok, TempDir}; - {ok, Error} -> Error; - {Error, _} -> Error - end. - - --spec rm_rf(file:filename()) -> ok | {error, file:posix()}. -%% @private -%% Recursively remove files and directories. Equivalent to `rm -rf'. - -rm_rf(Path) -> - case filelib:is_dir(Path) of - true -> - Pattern = filename:join(Path, "**"), - Contents = lists:reverse(lists:sort(filelib:wildcard(Pattern))), - ok = lists:foreach(fun rm/1, Contents), - file:del_dir(Path); - false -> - file:delete(Path) - end. - - --spec rm(file:filename()) -> ok | {error, file:posix()}. -%% @private -%% An omnibus delete helper. - -rm(Path) -> - case filelib:is_dir(Path) of - true -> file:del_dir(Path); - false -> file:delete(Path) -end. - -spec ensure_package_dirs(package_id()) -> ok. %% @private @@ -1633,74 +570,82 @@ usage_exit(Code) -> %% Display the zx command line usage message. usage() -> - T = "~n" - "zx~n" - "~n" - "Usage: zx [command] [object] [args]~n" - "~n" - "Examples:~n" - " zx help~n" - " zx run PackageID [Args]~n" - " zx init Type PackageID~n" - " zx install PackageID~n" - " zx set dep PackageID~n" - " zx set version Version~n" - " zx list realms~n" - " zx list packages Realm~n" - " zx list versions PackageName~n" - " zx list pending PackageName~n" - " zx list resigns Realm~n" - " zx add realm RealmFile~n" - " zx add package PackageName~n" - " zx add packager PackageName~n" - " zx add maintainer PackageName~n" - " zx add sysop UserID~n" - " zx review PackageID~n" - " zx approve PackageID~n" - " zx reject PackageID~n" - " zx accept PackageID~n" - " zx drop dep PackageID~n" - " zx drop key Realm KeyName~n" - " zx drop realm Realm~n" - " zx verup Level~n" - " zx runlocal [Args]~n" - " zx package [Path]~n" - " zx submit Path~n" - " zx create user Realm Username~n" - " zx create keypair~n" - " zx create plt~n" - " zx create realm~n" - " zx create realmfile Realm~n" - " zx create sysop~n" - "~n" - "Where~n" - " PackageID :: A string of the form Realm-Name[-Version]~n" - " Args :: Arguments to pass to the application~n" - " Type :: The project type: a standalone \"app\" or a \"lib\"~n" - " Version :: Version string X, X.Y, or X.Y.Z: \"1\", \"1.2\", \"1.2.3\"~n" - " RealmFile :: Path to a valid .zrf realm file~n" - " Realm :: The name of a realm as a string [:a-z:]~n" - " KeyName :: The prefix of a keypair to drop~n" - " Level :: The version level, one of \"major\", \"minor\", or \"patch\"~n" - " Path :: Path to a valid project directory or .zsp file~n" - "~n", + T = +"ZX usage: zx [command] [object] [args]~n" +"~n" +"User Actions:~n" +" zx help~n" +" zx run PackageID [Args]~n" +" zx runlocal [Args]~n" +" zx list realms~n" +" zx list packages Realm~n" +" zx list versions PackageID~n" +" zx latest PackageID~n" +" zx add realm RealmFile~n" +" zx drop realm Realm~n" +" zx install PackageID~n" +" zx logpath [Package [1-10]]~n" +" zx status~n" +" zx set timeout Value~n" +" zx set mirror Realm Host:Port~n" +"~n" +"Developer/Packager/Maintainer Actions:~n" +" zx create project [app | lib] PackageID~n" +" zx init Type PackageID~n" +" zx list deps [PackageID]~n" +" zx set dep PackageID~n" +" zx drop dep PackageID~n" +" zx verup Level~n" +" zx set version Version~n" +" zx update .app~n" +" zx create plt~n" +" zx dialyze~n" +" zx package Path~n" +" zx submit ZspFile~n" +" zx list pending PackageName~n" +" zx list resigns Realm~n" +" zx list packagers PackageName~n" +" zx list maintainers PackageName~n" +" zx list sysops Realm~n" +" zx review PackageID~n" +" zx approve PackageID~n" +" zx reject PackageID~n" +" zx add key Realm KeyName~n" +" zx get key Realm KeyName~n" +" zx rem key Realm KeyName~n" +" zx create user Realm~n" +" zx create userfiles Realm UserName~n" +" zx create keypair Realm~n" +" zx export user UserID~n" +" zx import user ZdufFile~n" +"~n" +"Sysop Actions:~n" +" zx add user ZpufFile~n" +" zx add package PackageName~n" +" zx add packager PackageName UserID~n" +" zx add maintainer PackageName UserID~n" +" zx add sysop UserID~n" +" zx accept PackageID~n" +" zx create realm~n" +" zx create realmfile Realm~n" +" zx create sysop~n" +"~n" +"Where~n" +" PackageID :: A string of the form Realm-Name[-Version]~n" +" Args :: Arguments to pass to the application~n" +" Type :: The project type: a standalone \"app\" or a \"lib\"~n" +" Version :: Version string X, X.Y, or X.Y.Z: \"1\", \"1.2\", \"1.2.3\"~n" +" RealmFile :: Path to a valid .zrf realm file~n" +" Realm :: The name of a realm as a string [:a-z:]~n" +" KeyName :: The prefix of a keypair to drop~n" +" Level :: The version level, one of \"major\", \"minor\", or \"patch\"~n" +" Path :: Path to a valid project directory or .zsp file~n", io:format(T). %%% Error exits - --spec error_exit(Error, Line) -> no_return() - when Error :: term(), - Line :: non_neg_integer(). -%% @private -%% Format an error message in a way that makes it easy to locate. - -error_exit(Error, Line) -> - error_exit(Error, [], Line). - - -spec error_exit(Format, Args, Line) -> no_return() when Format :: string(), Args :: [term()], diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_auth.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_auth.erl index e909189..767de5c 100644 --- a/zomp/lib/otpr/zx/0.1.0/src/zx_auth.erl +++ b/zomp/lib/otpr/zx/0.1.0/src/zx_auth.erl @@ -37,7 +37,7 @@ list_pending(PackageName) -> {ok, {R, N, {z, z, z}}} -> {R, N}; {error, invalid_package_string} -> - zx:error_exit("~tp is not a valid package name.", [PackageName], ?LINE) + error_exit("~tp is not a valid package name.", [PackageName], ?LINE) end, case zx_daemon:list_pending(Package) of {ok, []} -> @@ -53,12 +53,12 @@ list_pending(PackageName) -> ok = lists:foreach(Print, Versions), halt(0); {error, bad_realm} -> - zx:error_exit("Bad realm name.", ?LINE); + error_exit("Bad realm name.", ?LINE); {error, bad_package} -> - zx:error_exit("Bad package name.", ?LINE); + error_exit("Bad package name.", ?LINE); {error, network} -> Message = "Network issues are preventing connection to the realm.", - zx:error_exit(Message, ?LINE) + error_exit(Message, ?LINE) end. @@ -82,12 +82,12 @@ list_resigns(Realm) -> ok = lists:foreach(Print, PackageIDs), halt(0); {error, bad_realm} -> - zx:error_exit("Bad realm name.", ?LINE); + error_exit("Bad realm name.", ?LINE); {error, no_realm} -> - zx:error_exit("Realm \"~ts\" is not configured.", ?LINE); + error_exit("Realm \"~ts\" is not configured.", ?LINE); {error, network} -> Message = "Network issues are preventing connection to the realm.", - zx:error_exit(Message, ?LINE) + error_exit(Message, ?LINE) end. @@ -220,7 +220,7 @@ add_package(PackageName) -> {ok, {Realm, Name, {z, z, z}}} -> add_package(Realm, Name); _ -> - zx:error_exit("~tp is not a valid package name.", [PackageName], ?LINE) + error_exit("~tp is not a valid package name.", [PackageName], ?LINE) end. @@ -263,14 +263,14 @@ recv_or_die(Socket) -> {ok, Response} -> {ok, Response}; {error, Reason} -> - zx:error_exit("Action failed with: ~tp", [Reason], ?LINE); + error_exit("Action failed with: ~tp", [Reason], ?LINE); Unexpected -> - zx:error_exit("Unexpected message: ~tp", [Unexpected], ?LINE) + error_exit("Unexpected message: ~tp", [Unexpected], ?LINE) end; {tcp_closed, Socket} -> - zx:error_exit("Lost connection to node unexpectedly.", ?LINE) + error_exit("Lost connection to node unexpectedly.", ?LINE) after 5000 -> - zx:error_exit("Connection timed out.", ?LINE) + error_exit("Connection timed out.", ?LINE) end. @@ -450,3 +450,29 @@ disconnect(Socket) -> Message = "Shutdown connection ~p failed with: ~p", log(warning, Message, [Socket, Error]) end. + + + +%%% Error exits + +-spec error_exit(Error, Line) -> no_return() + when Error :: term(), + Line :: non_neg_integer(). +%% @private +%% Format an error message in a way that makes it easy to locate. + +error_exit(Error, Line) -> + error_exit(Error, [], Line). + + +-spec error_exit(Format, Args, Line) -> no_return() + when Format :: string(), + Args :: [term()], + Line :: non_neg_integer(). +%% @private +%% Format an error message in a way that makes it easy to locate. + +error_exit(Format, Args, Line) -> + File = filename:basename(?FILE), + ok = log(error, "~ts:~tp: " ++ Format, [File, Line | Args]), + halt(1). diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_conn.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_conn.erl index a302a85..30f5ef6 100644 --- a/zomp/lib/otpr/zx/0.1.0/src/zx_conn.erl +++ b/zomp/lib/otpr/zx/0.1.0/src/zx_conn.erl @@ -11,6 +11,9 @@ -copyright("Craig Everett "). -license("GPL-3.0"). +% FIXME +-compile(export_all). + -export([subscribe/2, unsubscribe/2, fetch/3, query/3]). -export([start/1, stop/1]). -export([start_link/1, init/2]). @@ -20,9 +23,9 @@ %%% Types --type incoming() :: ping - | {sub, Channel :: term(), Message :: term()} - | term(). +%-type incoming() :: ping +% | {sub, Channel :: term(), Message :: term()} +% | term(). %%% Interface @@ -250,7 +253,8 @@ handle_message(Socket, Bin) -> Invalid -> {ok, {Addr, Port}} = zomp:peername(Socket), Host = inet:ntoa(Addr), - ok = log(warning, "Invalid message from ~tp:~p: ", [Invalid]), + Warning = "Invalid message from ~s:~p: ~tp", + ok = log(warning, Warning, [Host, Port, Invalid]), ok = zx_net:disconnect(Socket), terminate() end. diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_key.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_key.erl index 2fc785d..e9e9ed7 100644 --- a/zomp/lib/otpr/zx/0.1.0/src/zx_key.erl +++ b/zomp/lib/otpr/zx/0.1.0/src/zx_key.erl @@ -13,7 +13,7 @@ -license("GPL-3.0"). -export([ensure_keypair/1, have_public_key/1, have_private_key/1, - prompt_keygen/0, create_keypair/0, generate_rsa/1, + prompt_keygen/0, grow_a_pair/0, generate_rsa/1, load/2, verify/3]). -include("zx_logger.hrl"). @@ -102,16 +102,16 @@ prompt_keygen() -> end. --spec create_keypair() -> no_return(). +-spec grow_a_pair() -> no_return(). %% @private %% Execute the key generation procedure for 16k RSA keys once and then terminate. -create_keypair() -> +grow_a_pair() -> ok = file:set_cwd(zx_lib:zomp_dir()), KeyID = prompt_keygen(), case generate_rsa(KeyID) of {ok, _, _} -> halt(0); - Error -> zx:error_exit("create_keypair/0 error: ~tp", [Error], ?LINE) + Error -> error_exit("grow_a_pair/0 error: ~tp", [Error], ?LINE) end. @@ -230,7 +230,7 @@ openssl() -> false -> ok = log(error, "OpenSSL could not be found in this system's PATH."), ok = log(error, "Install OpenSSL and then retry."), - zx:error_exit("Missing system dependenct: OpenSSL", ?LINE); + error_exit("Missing system dependenct: OpenSSL", ?LINE); Path -> log(info, "OpenSSL executable found at: ~ts", [Path]) end, @@ -276,5 +276,31 @@ load(Type, {Realm, KeyName}) -> verify(Data, Signature, PubKey) -> case public_key:verify(Data, sha512, Signature, PubKey) of true -> ok; - false -> zx:error_exit("Bad package signature!", ?LINE) + false -> error_exit("Bad package signature!", ?LINE) end. + + + +%%% Error exits + +-spec error_exit(Error, Line) -> no_return() + when Error :: term(), + Line :: non_neg_integer(). +%% @private +%% Format an error message in a way that makes it easy to locate. + +error_exit(Error, Line) -> + error_exit(Error, [], Line). + + +-spec error_exit(Format, Args, Line) -> no_return() + when Format :: string(), + Args :: [term()], + Line :: non_neg_integer(). +%% @private +%% Format an error message in a way that makes it easy to locate. + +error_exit(Format, Args, Line) -> + File = filename:basename(?FILE), + ok = log(error, "~ts:~tp: " ++ Format, [File, Line | Args]), + halt(1). diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_lib.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_lib.erl index 64ab93c..a95a618 100644 --- a/zomp/lib/otpr/zx/0.1.0/src/zx_lib.erl +++ b/zomp/lib/otpr/zx/0.1.0/src/zx_lib.erl @@ -29,7 +29,9 @@ namify_zsp/1, namify_tgz/1, find_latest_compatible/2, installed/1, realm_conf/1, load_realm_conf/1, - extract_zsp_or_die/1, halt_if_exists/1]). + extract_zsp_or_die/1, halt_if_exists/1, + build/0, + rm_rf/1, rm/1]). -include("zx_logger.hrl"). @@ -203,7 +205,7 @@ read_project_meta(Dir) -> Path = filename:join(Dir, "zomp.meta"), case file:consult(Path) of {ok, Meta} -> - maps:from_list(Meta); + {ok, maps:from_list(Meta)}; Error -> ok = log(error, "Failed to open \"zomp.meta\" with ~tp", [Error]), ok = log(error, "Wrong directory?"), @@ -670,13 +672,13 @@ extract_zsp_or_die(FileName) -> Files; {error, {FileName, enoent}} -> Message = "Can't find file ~ts.", - zx:error_exit(Message, [FileName], ?LINE); + error_exit(Message, [FileName], ?LINE); {error, invalid_tar_checksum} -> Message = "~ts is not a valid zsp archive.", - zx:error_exit(Message, [FileName], ?LINE); + error_exit(Message, [FileName], ?LINE); {error, Reason} -> Message = "Extracting package file failed with: ~160tp.", - zx:error_exit(Message, [Reason], ?LINE) + error_exit(Message, [Reason], ?LINE) end. @@ -687,6 +689,70 @@ extract_zsp_or_die(FileName) -> halt_if_exists(Path) -> case filelib:is_file(Path) of - true -> zx:error_exit("~ts already exists! Halting.", [Path], ?LINE); + true -> error_exit("~ts already exists! Halting.", [Path], ?LINE); false -> ok end. + + +-spec build() -> ok. +%% @private +%% Run any local `zxmake' script needed by the project for non-Erlang code (if present), +%% then add the local `ebin/' directory to the runtime search path, and finally build +%% the Erlang part of the project with make:all/0 according to the local `Emakefile'. + +build() -> + ZxMake = "zxmake", + ok = + case filelib:is_regular(ZxMake) of + true -> + Out = os:cmd(ZxMake), + log(info, Out); + false -> + ok + end, + true = code:add_patha(filename:absname("ebin")), + up_to_date = make:all(), + ok. + + +-spec rm_rf(file:filename()) -> ok | {error, file:posix()}. +%% @private +%% Recursively remove files and directories. Equivalent to `rm -rf'. + +rm_rf(Path) -> + case filelib:is_dir(Path) of + true -> + Pattern = filename:join(Path, "**"), + Contents = lists:reverse(lists:sort(filelib:wildcard(Pattern))), + ok = lists:foreach(fun rm/1, Contents), + file:del_dir(Path); + false -> + file:delete(Path) + end. + + +-spec rm(file:filename()) -> ok | {error, file:posix()}. +%% @private +%% An omnibus delete helper. + +rm(Path) -> + case filelib:is_dir(Path) of + true -> file:del_dir(Path); + false -> file:delete(Path) + end. + + + +%%% Error exits + +-spec error_exit(Format, Args, Line) -> no_return() + when Format :: string(), + Args :: [term()], + Line :: non_neg_integer(). +%% @private +%% Format an error message in a way that makes it easy to locate. + +error_exit(Format, Args, Line) -> + File = filename:basename(?FILE), + ok = log(error, "~ts:~tp: " ++ Format, [File, Line | Args]), + halt(1). diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_local.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_local.erl new file mode 100644 index 0000000..e73c872 --- /dev/null +++ b/zomp/lib/otpr/zx/0.1.0/src/zx_local.erl @@ -0,0 +1,1177 @@ +%%% @doc +%%% ZX Local +%%% +%%% This module defines procedures that affect the local host and terminate on +%%% completion. +%%% @end + +-module(zx_local). +-author("Craig Everett "). +-copyright("Craig Everett "). +-license("GPL-3.0"). + +-export([initialize/2, assimilate/1, set_dep/1, set_version/1, + list_realms/0, list_packages/1, list_versions/1, add_realm/1, + drop_dep/1, drop_key/1, drop_realm/1, verup/1, package/1, + create_plt/0, dialyze/0, + create_user/2, create_realm/0, create_realmfile/1]). + +-include("zx_logger.hrl"). + + + +%%% Functions + +-spec initialize(Type, PackageString) -> no_return() + when Type :: app | lib, + PackageString :: string(). +%% @private +%% Initialize an application in the local directory based on the PackageID provided. +%% This function does not care about the name of the current directory and leaves +%% providing a complete, proper and accurate PackageID. +%% This function will check the current `lib/' directory for zomp-style dependencies. +%% If this is not the intended function or if there are non-compliant directory names +%% in `lib/' then the project will need to be rearranged to become zomp compliant or +%% the `deps' section of the resulting meta file will need to be manually updated. + +initialize(Type, RawPackageString) -> + ok = + case filelib:is_file("zomp.meta") of + false -> ok; + true -> error_exit("This project is already Zompified.", ?LINE) + end, + PackageID = + case zx_lib:package_id(RawPackageString) of + {ok, {R, N, {z, z, z}}} -> + {R, N, {0, 1, 0}}; + {ok, {R, N, {X, z, z}}} -> + {R, N, {X, 0, 0}}; + {ok, {R, N, {X, Y, z}}} -> + {R, N, {X, Y, 0}}; + {ok, ID} -> + ID; + {error, invalid_package_string} -> + error_exit("Invalid package string: ~tp", [RawPackageString], ?LINE) + end, + {ok, PackageString} = zx_lib:package_string(PackageID), + ok = check_package_conflict(PackageID, PackageString), + ok = log(info, "Initializing ~s...", [PackageString]), + Prefix = solicit_prefix(), + ok = update_source_vsn(element(3, PackageID)), + ok = update_app_file(PackageID), + MetaList = + [{package_id, PackageID}, + {deps, []}, + {type, Type}, + {prefix, Prefix}], + Meta = maps:from_list(MetaList), + ok = zx_lib:write_project_meta(Meta), + ok = log(info, "Project ~tp initialized.", [PackageString]), + Message = + "~nNOTICE:~n" + " This project is currently listed as having no dependencies.~n" + " If this is not true then run `zx set dep DepID` for each current dependency.~n" + " (run `zx help` for more information on usage)~n", + ok = io:format(Message), + halt(0). + + +-spec check_package_conflict(zx:package_id(), string()) -> ok. +%% @private +%% Check the realm's upstream for the existence of a package that already has the same +%% name, or the name of any modules in src/ and report them to the user. Give the user +%% a chance to change their package's name or ignore the conflict, and report all module +%% naming conflicts. + +check_package_conflict(_PackageID, _PackageString) -> + log(info, "TODO: This is where the intended realm is checked for conflicts " + "and the user is given a chance to rename or ignore the conflict. " + "This check will have to wait for the network protocol fix."). + + +-spec solicit_prefix() -> ok. +%% @private +%% Most Erlang projects outside of the core distribution evolve a prefix of some sort +%% to namespace their work from other projects (or deliberately mimic another project's +%% prefix in the case that a new project is meant to augment, but not alter, an already +%% existing one). +%% A prefix is decided upon or disregarded here and stored in the meta file. The user +%% is given the option to update module names now (to include modifying call sites +%% in project code automatically -- while providing ample warnings about breaking +%% external code). +%% Just like with check_package_conflict/2, this procedure gives the user a chance to +%% ignore all warnings and just go. + +solicit_prefix() -> + ok = log(info, "Will solicit a prefix here. Just returning \"zz\" right now. Hah!"), + "zz". + + +-spec update_source_vsn(zx:version()) -> ok. +%% @private +%% Use grep to tell us which files have a `-vsn' attribute and which don't. +%% Use sed to insert a line after `-module' in the files that don't have it, +%% and update the files that do. +%% This procedure is still halfway into "works for me" territory. It will take a bit +%% of survey data to know which platforms can't work with some form of something +%% in here by default (bash may need to be called explicitly, for example, or the +%% old backtick executor terms used, etc). + +update_source_vsn(Version) -> + {ok, VersionString} = zx_lib:version_to_string(Version), + AddF = "sed -i 's/^-module(.*)\\.$/&\\n-vsn(\"~s\")./' $(grep -L '^-vsn(' src/*)", + SubF = "sed -i 's/-vsn(.*$/-vsn(\"~s\")./' $(grep -l '^-vsn(' src/*)", + Add = lists:flatten(io_lib:format(AddF, [VersionString])), + Sub = lists:flatten(io_lib:format(SubF, [VersionString])), + ok = exec_shell(Add), + ok = exec_shell(Sub), + log(info, "Source version attributes set"). + + +-spec update_app_file(zx:package_id()) -> ok. +%% @private +%% Update the app file or create it if it is missing. +%% TODO: If the app file is missing, interpret the src/*app.src file correctly. +%% Should really pull a few pages out of the rebar/erland.mk books on this, +%% as they've done all the hard pioneering work already. +%% TODO: Interactively determine whether the main module is the name, or the prefix +%% is the name, or the name is the prefix, or the name is the description, etc. +%% before writing anything out. + +update_app_file({_, Name, Version}) -> + {ok, VersionString} = zx_lib:version_to_string(Version), + AppName = list_to_atom(Name), + AppFile = filename:join("ebin", Name ++ ".app"), + {application, AppName, RawAppData} = + case filelib:is_regular(AppFile) of + true -> + {ok, [D]} = file:consult(AppFile), + D; + false -> + {application, + AppName, + [{registered, []}, + {included_applications, []}, + {applications, [stdlib, kernel]}]} + end, + Grep = "grep -oP '^-module\\(\\K[^)]+' src/* | cut -d: -f2", + Modules = [list_to_atom(M) || M <- string:lexemes(os:cmd(Grep), "\n")], + Properties = + [{vsn, VersionString}, + {modules, Modules}, + {mod, {AppName, []}}], + Store = fun(T, L) -> lists:keystore(element(1, T), 1, L, T) end, + AppData = lists:foldl(Store, RawAppData, Properties), + AppProfile = {application, AppName, AppData}, + ok = log(info, "Writing app file: ~ts~n~tp", [AppFile, AppProfile]), + zx_lib:write_terms(AppFile, [AppProfile]). + + +-spec exec_shell(CMD) -> ok | no_return() + when CMD :: string(). +%% @private +%% Print the output of an os:cmd/1 event only if there is any. + +exec_shell(CMD) -> + case os:cmd(CMD) of + "" -> + ok; + Out -> + Trimmed = string:trim(Out, trailing, "\r\n"), + log(info, "os:cmd(~tp) ->~n~ts", [CMD, Trimmed]) + end. + + +-spec assimilate(PackageFile) -> PackageID + when PackageFile :: file:filename(), + PackageID :: zx:package_id(). +%% @private +%% Receives a path to a file containing package data, examines it, and copies it to a +%% canonical location under a canonical name, returning the PackageID of the package +%% contents. + +assimilate(PackageFile) -> + Files = zx_lib:extract_zsp_or_die(PackageFile), + {ok, CWD} = file:get_cwd(), + ok = file:set_cwd(zx_lib:zomp_dir()), + {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files), + Meta = binary_to_term(MetaBin), + PackageID = maps:get(package_id, Meta), + TgzFile = zx_lib:namify_tgz(PackageID), + {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files), + {KeyID, Signature} = maps:get(sig, Meta), + {ok, PubKey} = zx_key:load(public, KeyID), + ok = + case public_key:verify(TgzData, sha512, Signature, PubKey) of + true -> + ZrpPath = filename:join("zsp", zx_lib:namify_zsp(PackageID)), + file:copy(PackageFile, ZrpPath); + false -> + error_exit("Bad package signature: ~ts", [PackageFile], ?LINE) + end, + ok = file:set_cwd(CWD), + Message = "~ts is now locally available.", + {ok, PackageString} = zx_lib:package_string(PackageID), + ok = log(info, Message, [PackageString]), + halt(0). + + +-spec set_dep(Identifier :: string()) -> no_return(). +%% @private +%% Set a specific dependency in the current project. If the project currently has a +%% dependency on the same package then the version of that dependency is updated to +%% reflect that in the PackageString argument. The AppString is permitted to be +%% incomplete. Incomplete elements of the VersionString (if included) will default to +%% the latest version available at the indicated level. + +set_dep(Identifier) -> + {ok, {Realm, Name, FuzzyVersion}} = zx_lib:package_id(Identifier), + Version = + case FuzzyVersion of + {X, Y, Z} when is_integer(X), is_integer(Y), is_integer(Z) -> + {X, Y, Z}; + _ -> + error_exit("Incomplete version tuple: ~tp", [FuzzyVersion]) + end, + set_dep({Realm, Name}, Version). + + +set_dep({Realm, Name}, Version) -> + PackageID = {Realm, Name, Version}, + {ok, Meta} = zx_lib:read_project_meta(), + Deps = maps:get(deps, Meta), + case lists:member(PackageID, Deps) of + true -> + {ok, PackageString} = zx_lib:package_string(PackageID), + ok = log(info, "~ts is already a dependency", [PackageString]), + halt(0); + false -> + set_dep(PackageID, Deps, Meta) + end. + + +-spec set_dep(PackageID, Deps, Meta) -> no_return() + when PackageID :: zx:package_id(), + Deps :: [zx:package_id()], + Meta :: [term()]. +%% @private +%% Given the PackageID, list of Deps and the current contents of the project Meta, add +%% or update Deps to include (or update) Deps to reflect a dependency on PackageID, if +%% such a dependency is not already present. Then write the project meta back to its +%% file and exit. + +set_dep(PackageID = {Realm, Name, NewVersion}, Deps, Meta) -> + ExistingPackageIDs = fun({R, N, _}) -> {R, N} == {Realm, Name} end, + NewDeps = + case lists:partition(ExistingPackageIDs, Deps) of + {[{Realm, Name, OldVersion}], Rest} -> + Message = "Updating dep ~ts to ~ts", + {ok, OldPS} = zx_lib:package_string({Realm, Name, OldVersion}), + {ok, NewPS} = zx_lib:package_string({Realm, Name, NewVersion}), + ok = log(info, Message, [OldPS, NewPS]), + [PackageID | Rest]; + {[], Deps} -> + {ok, PackageString} = zx_lib:package_string(PackageID), + ok = log(info, "Adding dep ~ts", [PackageString]), + [PackageID | Deps] + end, + NewMeta = maps:put(deps, NewDeps, Meta), + ok = zx_lib:write_project_meta(NewMeta), + halt(0). + + +-spec set_version(VersionString) -> no_return() + when VersionString :: string(). +%% @private +%% Convert a version string to a new version, sanitizing it in the process and returning +%% a reasonable error message on bad input. + +set_version(VersionString) -> + NewVersion = + case zx_lib:string_to_version(VersionString) of + {ok, {_, _, z}} -> + Message = "'set version' arguments must be complete, ex: 1.2.3", + error_exit(Message, ?LINE); + {ok, Version} -> + Version; + {error, invalid_version_string} -> + Message = "Invalid version string: ~tp", + error_exit(Message, [VersionString], ?LINE) + end, + {ok, Meta} = zx_lib:read_project_meta(), + {Realm, Name, OldVersion} = maps:get(package_id, Meta), + update_version(Realm, Name, OldVersion, NewVersion, Meta). + + +-spec update_version(Realm, Name, OldVersion, NewVersion, OldMeta) -> no_return() + when Realm :: zx:realm(), + Name :: zx:name(), + OldVersion :: zx:version(), + NewVersion :: zx:version(), + OldMeta :: zx:package_meta(). +%% @private +%% Update a project's `zomp.meta' file by either incrementing the indicated component, +%% or setting the version number to the one specified in VersionString. +%% This part of the procedure updates the meta and does the final write, if the write +%% turns out to be possible. If successful it will indicate to the user what was +%% changed. + +update_version(Realm, Name, OldVersion, NewVersion, OldMeta) -> + PackageID = {Realm, Name, NewVersion}, + NewMeta = maps:put(package_id, PackageID, OldMeta), + ok = zx_lib:write_project_meta(NewMeta), + {ok, OldVS} = zx_lib:version_to_string(OldVersion), + {ok, NewVS} = zx_lib:version_to_string(NewVersion), + ok = log(info, "Version changed from ~s to ~s.", [OldVS, NewVS]), + halt(0). + + +-spec list_realms() -> no_return(). +%% @private +%% List all currently configured realms. The definition of a "configured realm" is a +%% realm for which a .realm file exists in $ZOMP_HOME. The realms will be printed to +%% stdout and the program will exit. + +list_realms() -> + ok = lists:foreach(fun(R) -> io:format("~ts~n", [R]) end, zx_lib:list_realms()), + halt(0). + + +-spec list_packages(zx:realm()) -> no_return(). +%% @private +%% Contact the indicated realm and query it for a list of registered packages and print +%% them to stdout. + +list_packages(Realm) -> + ok = zx:start(), + case zx_daemon:list_packages(Realm) of + {ok, []} -> + ok = log(info, "Realm ~tp has no packages available.", [Realm]), + halt(0); + {ok, Packages} -> + Print = fun({R, N}) -> io:format("~ts-~ts~n", [R, N]) end, + ok = lists:foreach(Print, Packages), + halt(0); + {error, bad_realm} -> + error_exit("Bad realm name.", ?LINE); + {error, no_realm} -> + error_exit("Realm \"~ts\" is not configured.", ?LINE); + {error, network} -> + Message = "Network issues are preventing connection to the realm.", + error_exit(Message, ?LINE) + end. + + +-spec list_versions(PackageName :: string()) -> no_return(). +%% @private +%% List the available versions of the package indicated. The user enters a string-form +%% package name (such as "otpr-zomp") and the return values will be full package strings +%% of the form "otpr-zomp-1.2.3", one per line printed to stdout. + +list_versions(PackageName) -> + Package = {Realm, Name} = + case zx_lib:package_id(PackageName) of + {ok, {R, N, {z, z, z}}} -> + {R, N}; + {error, invalid_package_string} -> + error_exit("~tp is not a valid package name.", [PackageName], ?LINE) + end, + ok = zx:start(), + case zx_daemon:list_versions(Package) of + {ok, []} -> + Message = "Package ~ts has no versions available.", + ok = log(info, Message, [PackageName]), + halt(0); + {ok, Versions} -> + Print = + fun(Version) -> + {ok, PackageString} = zx_lib:package_string({Realm, Name, Version}), + io:format("~ts~n", [PackageString]) + end, + ok = lists:foreach(Print, Versions), + halt(0); + {error, bad_realm} -> + error_exit("Bad realm name.", ?LINE); + {error, bad_package} -> + error_exit("Bad package name.", ?LINE); + {error, network} -> + Message = "Network issues are preventing connection to the realm.", + error_exit(Message, ?LINE) + end. + + +-spec add_realm(Path) -> no_return() + when Path :: file:filename(). +%% @private +%% Add a .realm file to $ZOMP_HOME from a location in the filesystem. +%% Print the SHA512 of the .realm file for the user so they can verify that the file +%% is authentic. This implies, of course, that .realm maintainers are going to +%% post SHA512 sums somewhere visible. + +add_realm(Path) -> + case file:read_file(Path) of + {ok, Data} -> + Digest = crypto:hash(sha512, Data), + Text = integer_to_list(binary:decode_unsigned(Digest, big), 16), + ok = log(info, "SHA512 of ~ts: ~ts", [Path, Text]), + add_realm(Path, Data); + {error, enoent} -> + ok = log(warning, "FAILED: ~ts does not exist.", [Path]), + halt(1); + {error, eisdir} -> + ok = log(warning, "FAILED: ~ts is a directory, not a realm file.", [Path]), + halt(1) + end. + + +-spec add_realm(Path, Data) -> no_return() + when Path :: file:filename(), + Data :: binary(). + +add_realm(Path, Data) -> + case erl_tar:extract({binary, Data}, [compressed, {cwd, zx_lib:zomp_dir()}]) of + ok -> + {Realm, _} = string:take(filename:basename(Path), ".", true), + ok = log(info, "Realm ~ts is now visible to this system.", [Realm]), + halt(0); + {error, invalid_tar_checksum} -> + error_exit("~ts is not a valid realm file.", [Path], ?LINE); + {error, eof} -> + error_exit("~ts is not a valid realm file.", [Path], ?LINE) + end. + + +-spec drop_dep(zx:package_id()) -> no_return(). +%% @private +%% Remove the indicate dependency from the local project's zomp.meta record. + +drop_dep(PackageID) -> + {ok, PackageString} = zx_lib:package_string(PackageID), + {ok, Meta} = zx_lib:read_project_meta(), + Deps = maps:get(deps, Meta), + case lists:member(PackageID, Deps) of + true -> + NewDeps = lists:delete(PackageID, Deps), + NewMeta = maps:put(deps, NewDeps, Meta), + ok = zx_lib:write_project_meta(NewMeta), + Message = "~ts removed from dependencies.", + ok = log(info, Message, [PackageString]), + halt(0); + false -> + ok = log(info, "~ts not found in dependencies.", [PackageString]), + halt(0) + end. + + +-spec drop_key(zx:key_id()) -> no_return(). +%% @private +%% Given a KeyID, remove the related public and private keys from the keystore, if they +%% exist. If not, exit with a message that no keys were found, but do not return an +%% error exit value (this instruction is idempotent if used in shell scripts). + +drop_key({Realm, KeyName}) -> + ok = file:set_cwd(zx_lib:zomp_dir()), + KeyGlob = KeyName ++ ".{key,pub},der", + Pattern = filename:join([zx_lib:zomp_dir(), "key", Realm, KeyGlob]), + case filelib:wildcard(Pattern) of + [] -> + ok = log(warning, "Key ~ts/~ts not found", [Realm, KeyName]), + halt(0); + Files -> + ok = lists:foreach(fun file:delete/1, Files), + ok = log(info, "Keyset ~ts/~ts removed", [Realm, KeyName]), + halt(0) + end. + + +-spec drop_realm(zx:realm()) -> no_return(). + +drop_realm(Realm) -> + ok = file:set_cwd(zx_lib:zomp_dir()), + RealmConf = zx_lib:realm_conf(Realm), + case filelib:is_regular(RealmConf) of + true -> + Message = + "~n" + " WARNING: Are you SURE you want to remove realm ~ts?~n" + " (Only \"Y\" will confirm this action.)~n", + ok = io:format(Message, [Realm]), + case zx_tty:get_input() of + "Y" -> + ok = file:delete(RealmConf), + ok = drop_prime(Realm), + ok = clear_keys(Realm), + ok = log(info, "All traces of realm ~ts have been removed."), + halt(0); + _ -> + ok = log(info, "Aborting."), + halt(0) + end; + false -> + ok = log(warning, "Realm conf ~ts not found.", [RealmConf]), + clear_keys(Realm) + end. + + +-spec drop_prime(zx:realm()) -> ok. + +drop_prime(Realm) -> + Path = "zomp.conf", + case file:consult(Path) of + {ok, Conf} -> + {managed, Primes} = lists:keyfind(managed, 1, Conf), + NewPrimes = lists:delete(Realm, Primes), + NewConf = lists:keystore(managed, 1, Primes, {managed, NewPrimes}), + ok = zx_lib:write_terms(Path, NewConf), + log(info, "Ensuring ~ts is not a prime in ~ts", [Realm, Path]); + {error, enoent} -> + ok + end. + + +-spec clear_keys(zx:realm()) -> ok. + +clear_keys(Realm) -> + KeyDir = filename:join([zx_lib:zomp_dir(), "key", Realm]), + case filelib:is_dir(KeyDir) of + true -> zx_lib:rm_rf(KeyDir); + false -> log(warning, "Keydir ~ts not found", [KeyDir]) + end. + + +-spec verup(Level) -> no_return() + when Level :: string(). +%% @private +%% Convert input string arguments to acceptable atoms for use in update_version/1. + +verup("major") -> version_up(major); +verup("minor") -> version_up(minor); +verup("patch") -> version_up(patch); +verup(_) -> zx:usage_exit(22). + + +-spec version_up(Level) -> no_return() + when Level :: major + | minor + | patch. +%% @private +%% Update a project's `zomp.meta' file by either incrementing the indicated component, +%% or setting the version number to the one specified in VersionString. +%% This part of the procedure guards for the case when the zomp.meta file cannot be +%% read for some reason. + +version_up(Arg) -> + Meta = + case zx_lib:read_project_meta() of + {ok, M} -> M; + Error -> error_exit("verup failed with: ~tp", [Error], ?LINE) + end, + PackageID = maps:get(package_id, Meta), + version_up(Arg, PackageID, Meta). + + +-spec version_up(Level, PackageID, Meta) -> no_return() + when Level :: major + | minor + | patch + | zx:version(), + PackageID :: zx:package_id(), + Meta :: [{atom(), term()}]. +%% @private +%% Update a project's `zomp.meta' file by either incrementing the indicated component, +%% or setting the version number to the one specified in VersionString. +%% This part of the procedure does the actual update calculation, to include calling to +%% convert the VersionString (if it is passed) to a `version()' type and check its +%% validity (or halt if it is a bad string). + +version_up(major, {Realm, Name, OldVersion = {Major, _, _}}, OldMeta) -> + NewVersion = {Major + 1, 0, 0}, + update_version(Realm, Name, OldVersion, NewVersion, OldMeta); +version_up(minor, {Realm, Name, OldVersion = {Major, Minor, _}}, OldMeta) -> + NewVersion = {Major, Minor + 1, 0}, + update_version(Realm, Name, OldVersion, NewVersion, OldMeta); +version_up(patch, {Realm, Name, OldVersion = {Major, Minor, Patch}}, OldMeta) -> + NewVersion = {Major, Minor, Patch + 1}, + update_version(Realm, Name, OldVersion, NewVersion, OldMeta). + + +-spec package(TargetDir) -> no_return() + when TargetDir :: file:filename(). +%% @private +%% Turn a target project directory into a package, prompting the user for appropriate +%% key selection or generation actions along the way. + +package(TargetDir) -> + ok = log(info, "Packaging ~ts", [TargetDir]), + {ok, Meta} = zx_lib:read_project_meta(TargetDir), + {Realm, _, _} = maps:get(package_id, Meta), + KeyDir = filename:join([zx_lib:zomp_dir(), "key", Realm]), + ok = zx_lib:force_dir(KeyDir), + Pattern = KeyDir ++ "/*.key.der", + case [filename:basename(F, ".key.der") || F <- filelib:wildcard(Pattern)] of + [] -> + ok = log(info, "Need to generate key"), + KeyID = zx_key:prompt_keygen(), + {ok, _, _} = zx_key:generate_rsa(KeyID), + package(KeyID, TargetDir); + [KeyName] -> + KeyID = {Realm, KeyName}, + ok = log(info, "Using key: ~ts/~ts", [Realm, KeyName]), + package(KeyID, TargetDir); + KeyNames -> + KeyName = zx_tty:select_string(KeyNames), + package({Realm, KeyName}, TargetDir) + end. + + +-spec package(KeyID, TargetDir) -> no_return() + when KeyID :: zx:key_id(), + TargetDir :: file:filename(). +%% @private +%% Accept a KeyPrefix for signing and a TargetDir containing a project to package and +%% build a zsp package file ready to be submitted to a repository. + +package(KeyID, TargetDir) -> + {ok, Meta} = zx_lib:read_project_meta(TargetDir), + PackageID = maps:get(package_id, Meta), + true = element(1, PackageID) == element(1, KeyID), + {ok, PackageString} = zx_lib:package_string(PackageID), + ZrpFile = PackageString ++ ".zsp", + TgzFile = PackageString ++ ".tgz", + ok = zx_lib:halt_if_exists(ZrpFile), + ok = remove_binaries(TargetDir), + {ok, Everything} = file:list_dir(TargetDir), + DotFiles = filelib:wildcard(".*", TargetDir), + Ignores = ["lib" | DotFiles], + Targets = lists:subtract(Everything, Ignores), + {ok, CWD} = file:get_cwd(), + ok = file:set_cwd(TargetDir), + ok = zx_lib:build(), + Modules = + [filename:basename(M, ".beam") || M <- filelib:wildcard("*.beam", "ebin")], + ok = remove_binaries("."), + ok = erl_tar:create(filename:join(CWD, TgzFile), Targets, [compressed]), + ok = file:set_cwd(CWD), + {ok, Key} = zx_key:load(private, KeyID), + {ok, TgzBin} = file:read_file(TgzFile), + Sig = public_key:sign(TgzBin, sha512, Key), + Add = fun({K, V}, M) -> maps:put(K, V, M) end, + FinalMeta = lists:foldl(Add, Meta, [{modules, Modules}, {sig, {KeyID, Sig}}]), + ok = file:write_file("zomp.meta", term_to_binary(FinalMeta)), + ok = erl_tar:create(ZrpFile, ["zomp.meta", TgzFile]), + ok = file:delete(TgzFile), + ok = file:delete("zomp.meta"), + ok = log(info, "Wrote archive ~ts", [ZrpFile]), + halt(0). + + +-spec remove_binaries(TargetDir) -> ok + when TargetDir :: file:filename(). +%% @private +%% Procedure to delete all .beam and .ez files from a given directory starting at +%% TargetDir. Called as part of the pre-packaging sanitization procedure. + +remove_binaries(TargetDir) -> + Beams = filelib:wildcard("**/*.{beam,ez}", TargetDir), + case [filename:join(TargetDir, Beam) || Beam <- Beams] of + [] -> + ok; + ToDelete -> + ok = log(info, "Removing: ~tp", [ToDelete]), + lists:foreach(fun file:delete/1, ToDelete) + end. + + +-spec create_plt() -> no_return(). +%% @private +%% Generate a fresh PLT file that includes most basic core applications needed to +%% make a resonable estimate of a type system, write the name of the PLT to stdout, +%% and exit. + +create_plt() -> + ok = build_plt(), + halt(0). + + +-spec build_plt() -> ok. +%% @private +%% Build a general plt file for Dialyzer based on the core Erland distro. +%% TODO: Make a per-package + dependencies version of this. + +build_plt() -> + PLT = default_plt(), + Template = + "dialyzer --build_plt" + " --output_plt ~ts" + " --apps asn1 reltool wx common_test crypto erts eunit inets" + " kernel mnesia public_key sasl ssh ssl stdlib", + Command = io_lib:format(Template, [PLT]), + Message = + "Generating PLT file and writing to: ~tp~n" + " There will be a list of \"unknown functions\" in the final output.~n" + " Don't panic. This is normal. Turtles all the way down, after all...", + ok = log(info, Message, [PLT]), + ok = log(info, "This may take a while. Patience is a virtue."), + Out = os:cmd(Command), + log(info, Out). + + +-spec default_plt() -> file:filename(). + +default_plt() -> + filename:join(zx_lib:zomp_dir(), "basic.plt"). + + +-spec dialyze() -> no_return(). +%% @private +%% Preps a copy of this script for typechecking with Dialyzer. +%% TODO: Create a package_id() based version of this to handle dialyzation of complex +%% projects. + +dialyze() -> + PLT = default_plt(), + ok = + case filelib:is_regular(PLT) of + true -> log(info, "Using PLT: ~tp", [PLT]); + false -> build_plt() + end, + TmpDir = filename:join(zx_lib:zomp_dir(), "tmp"), + Me = escript:script_name(), + EvilTwin = filename:join(TmpDir, filename:basename(Me ++ ".erl")), + ok = log(info, "Temporarily reconstructing ~tp as ~tp", [Me, EvilTwin]), + Sed = io_lib:format("sed 's/^#!.*$//' ~s > ~s", [Me, EvilTwin]), + "" = os:cmd(Sed), + ok = case dialyzer:run([{init_plt, PLT}, {from, src_code}, {files, [EvilTwin]}]) of + [] -> + io:format("Dialyzer found no errors and returned no warnings! Yay!~n"); + Warnings -> + Mine = [dialyzer:format_warning({Tag, {Me, Line}, Msg}) + || {Tag, {_, Line}, Msg} <- Warnings], + lists:foreach(fun io:format/1, Mine) + end, + ok = file:delete(EvilTwin), + halt(0). + + +-spec create_user(zx:realm(), zx:user_name()) -> no_return(). +%% @private +%% Validate the realm and username provided, prompt the user to either select a keypair +%% to use or generate a new one, and bundle a .zuser file for conveyance of the user +%% data and his relevant keys (for import into an existing zomp server via `add' +%% command like "add packager", "add maintainer" and "add sysop". + +create_user(Realm, Username) -> + Message = "Would be generating a user file for {~160tp, ~160to}.", + ok = log(info, Message, [Realm, Username]), + halt(0). + + +-spec create_realm() -> no_return(). +%% @private +%% Prompt the user to input the information necessary to create a new zomp realm, +%% package the data appropriately for the server and deliver the final keys and +%% realm file to the user. + +create_realm() -> + Instructions = + "~n" + " Enter a name for your new realm.~n" + " Names can contain only lower-case letters, numbers and the underscore.~n" + " Names must begin with a lower-case letter.~n", + ok = io:format(Instructions), + Realm = zx_tty:get_input(), + case zx_lib:valid_lower0_9(Realm) of + true -> + RealmFile = filename:join(zx_lib:zomp_dir(), Realm ++ ".realm"), + case filelib:is_regular(RealmFile) of + false -> + create_realm(Realm); + true -> + ok = io:format("That realm already exists. Be more original.~n"), + create_realm() + end; + false -> + ok = io:format("Bad realm name \"~ts\". Try again.~n", [Realm]), + create_realm() + end. + + +-spec create_realm(Realm) -> no_return() + when Realm :: zx:realm(). + +create_realm(Realm) -> + ExAddress = prompt_external_address(), + create_realm(Realm, ExAddress). + + +-spec prompt_external_address() -> Result + when Result :: inet:hostname() | inet:ip_address(). + +prompt_external_address() -> + Message = external_address_prompt(), + ok = io:format(Message), + case zx_tty:get_input() of + "" -> + ok = io:format("You need to enter an address.~n"), + prompt_external_address(); + String -> + parse_address(String) + end. + + +-spec external_address_prompt() -> string(). + +external_address_prompt() -> + "~n" + " Enter a static, valid hostname or IPv4 or IPv6 address at which this host " + "can be reached from the public internet (or internal network if it will never " + "need to be reached from the internet).~n" + " DO NOT INCLUDE A PORT NUMBER IN THIS STEP~n". + + +-spec parse_address(string()) -> inet:hostname() | inet:ip_address(). + +parse_address(String) -> + case inet:parse_address(String) of + {ok, Address} -> Address; + {error, einval} -> String + end. + + +-spec create_realm(Realm, ExAddress) -> no_return() + when Realm :: zx:realm(), + ExAddress :: inet:hostname() | inet:ip_address(). + +create_realm(Realm, ExAddress) -> + Message = + "~n" + " Enter the public (external) port number at which this service should be " + "available. (This might be different from the local port number if you are " + "forwarding ports or have a complex network layout.)~n", + ok = io:format(Message), + ExPort = prompt_port_number(11311), + create_realm(Realm, ExAddress, ExPort). + + +-spec create_realm(Realm, ExAddress, ExPort) -> no_return() + when Realm :: zx:realm(), + ExAddress :: inet:hostname() | inet:ip_address(), + ExPort :: inet:port_number(). + +create_realm(Realm, ExAddress, ExPort) -> + Message = + "~n" + " Enter the local (internal/LAN) port number at which this service should be " + "available. (This might be different from the public port visible from the " + "internet if you are port forwarding or have a complex network layout.)~n", + ok = io:format(Message), + InPort = prompt_port_number(11311), + create_realm(Realm, ExAddress, ExPort, InPort). + + +-spec prompt_port_number(Current) -> Result + when Current :: inet:port_number(), + Result :: inet:port_number(). + +prompt_port_number(Current) -> + Instructions = + " A valid port is any number from 1 to 65535." + " [Press enter to accept the current setting: ~tw]~n", + ok = io:format(Instructions, [Current]), + case zx_tty:get_input() of + "" -> + Current; + S -> + try + case list_to_integer(S) of + Port when 16#ffff >= Port, Port > 0 -> + Port; + Illegal -> + Whoops = "Whoops! ~tw is out of bounds (1~65535). Try again.~n", + ok = io:format(Whoops, [Illegal]), + prompt_port_number(Current) + end + catch error:badarg -> + ok = io:format("~tp is not a port number. Try again...", [S]), + prompt_port_number(Current) + end + end. + + +-spec create_realm(Realm, ExAddress, ExPort, InPort) -> no_return() + when Realm :: zx:realm(), + ExAddress :: inet:hostname() | inet:ip_address(), + ExPort :: inet:port_number(), + InPort :: inet:port_number(). + +create_realm(Realm, ExAddress, ExPort, InPort) -> + Instructions = + "~n" + " Enter a username for the realm sysop.~n" + " Names can contain only lower-case letters, numbers and the underscore.~n" + " Names must begin with a lower-case letter.~n", + ok = io:format(Instructions), + UserName = zx_tty:get_input(), + case zx_lib:valid_lower0_9(UserName) of + true -> + create_realm(Realm, ExAddress, ExPort, InPort, UserName); + false -> + ok = io:format("Bad username ~tp. Try again.~n", [UserName]), + create_realm(Realm, ExAddress, ExPort, InPort) + end. + + +-spec create_realm(Realm, ExAddress, ExPort, InPort, UserName) -> no_return() + when Realm :: zx:realm(), + ExAddress :: inet:hostname() | inet:ip_address(), + ExPort :: inet:port_number(), + InPort :: inet:port_number(), + UserName :: string(). + +create_realm(Realm, ExAddress, ExPort, InPort, UserName) -> + Instructions = + "~n" + " Enter an email address for the realm sysop.~n" + " Valid email address rules apply though the checking done here is quite " + "minimal. Check the address you enter carefully. The only people who will " + "suffer from an invalid address are your users.~n", + ok = io:format(Instructions), + Email = zx_tty:get_input(), + [User, Host] = string:lexemes(Email, "@"), + case {zx_lib:valid_lower0_9(User), zx_lib:valid_label(Host)} of + {true, true} -> + create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email); + {false, true} -> + Message = "The user part of the email address seems invalid. Try again.~n", + ok = io:format(Message), + create_realm(Realm, ExAddress, ExPort, InPort, UserName); + {true, false} -> + Message = "The host part of the email address seems invalid. Try again.~n", + ok = io:format(Message), + create_realm(Realm, ExAddress, ExPort, InPort, UserName); + {false, false} -> + Message = "This email address seems like its totally bonkers. Try again.~n", + ok = io:format(Message), + create_realm(Realm, ExAddress, ExPort, InPort, UserName) + end. + + +-spec create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email) -> + no_return() + when Realm :: zx:realm(), + ExAddress :: inet:hostname() | inet:ip_address(), + ExPort :: inet:port_number(), + InPort :: inet:port_number(), + UserName :: string(), + Email :: string(). + +create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email) -> + Instructions = + "~n" + " Enter the real name (or whatever name people recognize) for the sysop.~n" + " There are no rules for this one. Any valid UTF-8 printables are legal.~n", + ok = io:format(Instructions), + RealName = zx_tty:get_input(), + create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email, RealName). + + +-spec create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email, RealName) -> no_return() + when Realm :: zx:realm(), + ExAddress :: inet:hostname() | inet:ip_address(), + ExPort :: inet:port_number(), + InPort :: inet:port_number(), + UserName :: string(), + Email :: string(), + RealName :: string(). + +create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email, RealName) -> + ok = io:format("~nGenerating keys. This might take a while, so settle in...~n"), + {ok, RealmKey, RealmPub} = zx_key:generate_rsa({Realm, Realm ++ ".1.realm"}), + {ok, PackageKey, PackagePub} = zx_key:generate_rsa({Realm, Realm ++ ".1.package"}), + {ok, SysopKey, SysopPub} = zx_key:generate_rsa({Realm, UserName ++ ".1"}), + ok = log(info, "Generated 16k RSA pair ~ts ~ts", [RealmKey, RealmPub]), + ok = log(info, "Generated 16k RSA pair ~ts ~ts", [PackageKey, PackagePub]), + ok = log(info, "Generated 16k RSA pair ~ts ~ts", [SysopKey, SysopPub]), + + Timestamp = calendar:now_to_universal_time(erlang:timestamp()), + + {ok, RealmPubData} = file:read_file(RealmPub), + RealmPubRecord = + {{Realm, filename:basename(RealmPub, ".pub.der")}, + realm, + {realm, Realm}, + crypto:hash(sha512, RealmPubData), + Timestamp}, + {ok, PackagePubData} = file:read_file(PackagePub), + PackagePubRecord = + {{Realm, filename:basename(PackagePub, ".pub.der")}, + package, + {realm, Realm}, + crypto:hash(sha512, PackagePubData), + Timestamp}, + UserRecord = + {{Realm, UserName}, + [filename:basename(SysopPub, ".pub.der")], + Email, + RealName}, + RealmSettings = + [{realm, Realm}, + {revision, 0}, + {prime, {ExAddress, ExPort}}, + {private, []}, + {mirrors, []}, + {sysops, [UserRecord]}, + {realm_keys, [RealmPubRecord]}, + {package_keys, [PackagePubRecord]}], + ZompSettings = + [{managed, [Realm]}, + {external_address, ExAddress}, + {external_port, ExPort}, + {internal_port, InPort}], + + {ok, CWD} = file:get_cwd(), + {ok, TempDir} = mktemp_dir("zomp"), + ok = file:set_cwd(TempDir), + KeyDir = filename:join("key", Realm), + ok = filelib:ensure_dir(KeyDir), + ok = file:make_dir(KeyDir), + KeyCopy = + fun(K) -> + {ok, _} = file:copy(K, filename:join(KeyDir, filename:basename(K))), + ok + end, + + PublicZRF = filename:join(CWD, Realm ++ ".zrf"), + RealmFN = Realm ++ ".realm", + ok = zx_lib:write_terms(RealmFN, RealmSettings), + ok = KeyCopy(PackagePub), + ok = KeyCopy(RealmPub), + ok = erl_tar:create(PublicZRF, [RealmFN, "key"], [compressed]), + + PrimeZRF = filename:join(CWD, Realm ++ ".zpf"), + ok = KeyCopy(SysopPub), + ok = zx_lib:write_terms("zomp.conf", ZompSettings), + ok = erl_tar:create(PrimeZRF, [RealmFN, "zomp.conf", "key"], [compressed]), + + KeyBundle = filename:join(CWD, Realm ++ ".zkf"), + ok = lists:foreach(KeyCopy, [PackageKey, RealmKey, SysopKey]), + ok = erl_tar:create(KeyBundle, [KeyDir], [compressed]), + + ok = file:set_cwd(CWD), + ok = zx_lib:rm_rf(TempDir), + + Message = + "===========================================================================~n" + "DONE!~n" + "~n" + "The realm ~ts has been created and is accessible from the current system.~n" + "Three configuration bundles have been created in the current directory:~n" + "~n" + " 1. ~ts ~n" + "This is the PRIVATE realm file you will need to install on the realm's prime~n" + "node. It includes the your (the sysop's) public key.~n" + "~n" + " 2. ~ts ~n" + "This file is the PUBLIC realm file other zomp nodes and zx users will need~n" + "to access the realm. It does not include your (the sysop's) public key.~n" + "~n" + " 3. ~ts ~n" + "This is the bundle of ALL KEYS that are defined in this realm at the moment.~n" + "~n" + "Now you need to make copies of these three files and back them up.~n" + "~n" + "On the PRIME NODE you need to run `zx add realm ~ts` and follow the prompts~n" + "to cause it to begin serving that realm as prime. (Node restart required.)~n" + "~n" + "On all zx CLIENTS that want to access your new realm and on all subordinate~n" + "MIRROR NODES the command `zx add realm ~ts` will need to be run.~n" + "The method of public realm file distribution (~ts) is up to you.~n" + "~n" + "~n" + "Public & Private key installation (if you need to recover them or perform~n" + "sysop functions from another computer) is `zx add keybundle ~ts`.~n" + "===========================================================================~n", + Substitutions = + [Realm, + PrimeZRF, PublicZRF, KeyBundle, + PrimeZRF, + PublicZRF, PublicZRF, + KeyBundle], + ok = io:format(Message, Substitutions), + halt(0). + + +-spec mktemp_dir(Prefix) -> Result + when Prefix :: string(), + Result :: {ok, TempDir :: file:filename()} + | {error, Reason :: file:posix()}. + +mktemp_dir(Prefix) -> + Rand = integer_to_list(binary:decode_unsigned(crypto:strong_rand_bytes(8)), 36), + TempPath = filename:basedir(user_cache, Prefix), + TempDir = filename:join(TempPath, Rand), + Result1 = filelib:ensure_dir(TempDir), + Result2 = file:make_dir(TempDir), + case {Result1, Result2} of + {ok, ok} -> {ok, TempDir}; + {ok, Error} -> Error; + {Error, _} -> Error + end. + + +-spec create_realmfile(zx:realm()) -> no_return(). + +create_realmfile(Realm) -> + RealmConf = zx_lib:load_realm_conf(Realm), + ok = log(info, "Realm found, creating realm file..."), + {revision, Revision} = lists:keyfind(revision, 1, RealmConf), + {realm_keys, RealmKeys} = lists:keyfind(realm_keys, 1, RealmConf), + {package_keys, PackageKeys} = lists:keyfind(package_keys, 1, RealmConf), + RealmKeyIDs = [element(1, K) || K <- RealmKeys], + PackageKeyIDs = [element(1, K) || K <- PackageKeys], + create_realmfile(Realm, Revision, RealmKeyIDs, PackageKeyIDs). + + +-spec create_realmfile(Realm, Revision, RealmKeyIDs, PackageKeyIDs) -> ok + when Realm :: zx:realm(), + Revision :: non_neg_integer(), + RealmKeyIDs :: [zx:key_id()], + PackageKeyIDs :: [zx:key_id()]. + +create_realmfile(Realm, Revision, RealmKeyIDs, PackageKeyIDs) -> + {ok, CWD} = file:get_cwd(), + ok = file:set_cwd(zx_lib:zomp_dir()), + KeyPath = fun({R, K}) -> filename:join(["key", R, K ++ ".pub.der"]) end, + RealmKeyPaths = lists:map(KeyPath, RealmKeyIDs), + PackageKeyPaths = lists:map(KeyPath, PackageKeyIDs), + Targets = [zx_lib:realm_conf(Realm) | RealmKeyPaths ++ PackageKeyPaths], + OutFile = filename:join(CWD, Realm ++ "." ++ integer_to_list(Revision) ++ ".zrf"), + ok = erl_tar:create(OutFile, Targets, [compressed]), + ok = log(info, "Realm conf file written to ~ts", [OutFile]), + halt(0). + + + +%%% Error exits + +-spec error_exit(Error, Line) -> no_return() + when Error :: term(), + Line :: non_neg_integer(). +%% @private +%% Format an error message in a way that makes it easy to locate. + +error_exit(Error, Line) -> + error_exit(Error, [], Line). + + +-spec error_exit(Format, Args, Line) -> no_return() + when Format :: string(), + Args :: [term()], + Line :: non_neg_integer(). +%% @private +%% Format an error message in a way that makes it easy to locate. + +error_exit(Format, Args, Line) -> + File = filename:basename(?FILE), + ok = log(error, "~ts:~tp: " ++ Format, [File, Line | Args]), + halt(1). diff --git a/zomp/zx b/zomp/zx index 96f8928..c2ebddd 100755 --- a/zomp/zx +++ b/zomp/zx @@ -7,4 +7,4 @@ ZX_DIR="$ZOMP_DIR/lib/otpr/zx/$VERSION" pushd "$ZX_DIR" > /dev/null ./make_zx popd > /dev/null -erl -pa "$ZX_DIR/ebin" -run zx start $@ +erl -pa "$ZX_DIR/ebin" -run zx run $@ diff --git a/zomp/zx.cmd b/zomp/zx.cmd index a7ed5a3..12e5aec 100644 --- a/zomp/zx.cmd +++ b/zomp/zx.cmd @@ -6,4 +6,4 @@ set ZX_DIR="%ZOMP_DIR%\lib\otpr\zx\%VERSION%" pushd "%ZX_DIR%" escript.exe make_zx popd -erl.exe -pa "%ZX_DIR%/ebin" -run zx start "%*" +erl.exe -pa "%ZX_DIR%/ebin" -run zx run "%*" diff --git a/zx_dev b/zx_dev index 2f4b9c2..a370431 100755 --- a/zx_dev +++ b/zx_dev @@ -1,13 +1,15 @@ #!/bin/bash pushd $(dirname $BASH_SOURCE) > /dev/null -export ZX_DEV_ROOT=$PWD +ZX_DEV_ROOT=$PWD popd > /dev/null -export ZOMP_DIR="$ZX_DEV_ROOT/zomp" -export VERSION=$(cat "$ZOMP_DIR/etc/version.txt") +export ZOMP_DIR="$ZX_DEV_ROOT/tester" +rm -rf "$ZOMP_DIR" +cp -r "$ZX_DEV_ROOT/zomp" "$ZOMP_DIR" +VERSION=$(cat "$ZOMP_DIR/etc/version.txt") export ZX_DIR="$ZOMP_DIR/lib/otpr/zx/$VERSION" pushd "$ZX_DIR" > /dev/null ./make_zx popd > /dev/null -erl -pa "$ZX_DIR/ebin" -run zx start $@ +erl -pa "$ZX_DIR/ebin" -run zx run $@