text,length,is_long_context,metric_val,label_metric "------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- E R R O U T -- -- -- -- S p e c -- -- -- -- Copyright (C) 1992-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT 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 distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This package contains the routines to output error messages. They are -- basically system independent, however in some environments, e.g. when the -- parser is embedded into an editor, it may be appropriate to replace the -- implementation of this package. with Err_Vars; with Erroutc; with Namet; use Namet; with Table; with Types; use Types; with Uintp; use Uintp; with System; package Errout is Current_Error_Source_File : Source_File_Index renames Err_Vars.Current_Error_Source_File; -- Id of current messages. Used to post file name when unit changes. This -- is initialized to Main_Source_File at the start of a compilation, which -- means that no file names will be output unless there are errors in -- units other than the main unit. However, if the main unit has a pragma -- Source_Reference line, then this is initialized to No_Source_File, to -- force an initial reference to the real source file name. Raise_Exception_On_Error : Nat renames Err_Vars.Raise_Exception_On_Error; -- If this value is non-zero, then any attempt to generate an error -- message raises the exception Error_Msg_Exception, and the error message -- is not output. This is used for defending against junk resulting from -- illegalities, and also for substitution of more appropriate error -- messages from higher semantic levels. It is a counter so that the -- increment/decrement protocol nests neatly. Error_Msg_Exception : exception renames Err_Vars.Error_Msg_Exception; -- Exception raised if Raise_Exception_On_Error is true Warning_Doc_Switch : Boolean renames Err_Vars.Warning_Doc_Switch; -- If this is set True, then the ??/?*?/?$?/?x?/?X? insertion sequences in -- error messages generate appropriate tags for the output error messages. -- If this switch is False, then these sequences are still recognized (for -- the purposes of implementing the pattern matching in pragmas Warnings -- (Off,..) and Warning_As_Pragma(...) but do not result in adding the -- error message tag. The -gnatw.d switch sets this flag True, -gnatw.D -- sets this flag False. Current_Node : Node_Id := Empty; -- Used by Error_Msg as a default Node_Id. -- Relevant only when Opt.Include_Subprogram_In_Messages is set. ----------------------------------- -- Suppression of Error Messages -- ----------------------------------- -- In an effort to reduce the impact of redundant error messages, the -- error output routines in this package normally suppress certain -- classes of messages as follows: -- 1. Identical messages placed at the same point in the text. Such -- duplicate error message result for example from rescanning -- sections of the text that contain lexical errors. Only one of -- such a set of duplicate messages is output, and the rest are -- suppressed. -- 2. If more than one parser message is generated for a single source -- line, then only the first message is output, the remaining -- messages on the same line are suppressed. -- 3. If a message is posted on a node for which a message has been -- previously posted, then only the first message is retained. The -- Error_Posted flag is used to detect such multiple postings. Note -- that this only applies to semantic messages, since otherwise -- for parser messages, this would be a special case of case 2. -- 4. If a message is posted on a node whose Etype or Entity -- fields reference entities on which an error message has -- already been placed, as indicated by the Error_Posted flag -- being set on these entities, then the message is suppressed. -- 5. If a message attempts to insert an Error node, or a direct -- reference to the Any_Type node, then the message is suppressed. -- 6. Note that cases 2-5 only apply to error messages, not warning -- messages. Warning messages are only suppressed for case 1, and -- when they come from other than the main extended unit. -- 7. If an error or warning references an internal name, and we have -- already placed an error (not warning) message at that location, -- then we assume this is cascaded junk and delete the message. -- This normal suppression action may be overridden in cases 2-5 (but -- not in case 1 or 7) by setting All_Errors mode, or by setting the -- unconditional message insertion character (!) as described below. --------------------------------------------------------- -- Error Message Text and Message Insertion Characters -- --------------------------------------------------------- -- Error message text strings are composed of lower case letters, digits -- and the special characters space, comma, period, colon and semicolon, -- apostrophe and parentheses. Special insertion characters can also -- appear which cause the error message circuit to modify the given -- string as follows: -- Insertion character % (Percent: insert name from Names table) -- The character % is replaced by the text for the name specified by -- the Name_Id value stored in Error_Msg_Name_1. A blank precedes the -- name if it is preceded by a non-blank character other than left -- parenthesis. The name is enclosed in quotes unless manual quotation -- mode is set. If the Name_Id is set to No_Name, then no insertion -- occurs; if the Name_Id is set to Error_Name, then the string -- is inserted. A second and third % may appear in a single -- message, similarly replaced by the names which are specified by the -- Name_Id values stored in Error_Msg_Name_2 and Error_Msg_Name_3. The -- names are decoded and cased according to the current identifier -- casing mode. Note: if a unit name ending with %b or %s is passed -- for this kind of insertion, this suffix is simply stripped. Use a -- unit name insertion ($) to process the suffix. -- -- Note: the special names _xxx (xxx = Pre/Post/Invariant) are changed -- to insert the string xxx'Class into the message. -- Insertion character %% (Double percent: insert literal name) -- The character sequence %% acts as described above for %, except -- that the name is simply obtained with Get_Name_String and is not -- decoded or cased, it is inserted literally from the names table. -- A trailing %b or %s is not treated specially. -- -- Note: the special names _xxx (xxx = Pre/Post/Invariant) are changed -- to insert the string xxx'Class into the message. -- Insertion character $ (Dollar: insert unit name from Names table) -- The character $ is treated similarly to %, except that the name is -- obtained from the Unit_Name_Type value in Error_Msg_Unit_1 and -- Error_Msg_Unit_2, as provided by Get_Unit_Name_String in package -- Uname. Note that this name includes the postfix (spec) or (body) -- strings. If this postfix is not required, use the normal % insertion -- for the unit name. -- Insertion character { (Left brace: insert file name from names table) -- The character { is treated similarly to %, except that the input -- value is a File_Name_Type value stored in Error_Msg_File_1 or -- Error_Msg_File_2 or Error_Msg_File_3. The value is output literally, -- enclosed in quotes as for %, but the case is not modified, the -- insertion is the exact string stored in the names table without -- adjusting the casing. -- Insertion character * (Asterisk: insert reserved word name) -- The insertion character * is treated exactly like % except that the -- resulting name is cased according to the default conventions for -- reserved words (see package Scans). -- Insertion character & (Ampersand: insert name from node) -- The insertion character & is treated similarly to %, except that -- the name is taken from the Chars field of the given node, and may -- refer to a child unit name, or a selected component. The casing is, -- if possible, taken from the original source reference, which is -- obtained from the Sloc field of the given node or nodes. If no Sloc -- is available (happens e.g. for nodes in package Standard), then the -- default case (see Scans spec) is used. The nodes to be used are -- stored in Error_Msg_Node_1, Error_Msg_Node_2. No insertion occurs -- for the Empty node, and the Error node results in the insertion of -- the characters . In addition, if the special global variable -- Error_Msg_Qual_Level is non-zero, then the reference will include -- up to the given number of levels of qualification, using the scope -- chain. -- -- Note: the special names _xxx (xxx = Pre/Post/Invariant) are changed -- to insert the string xxx'Class into the message. -- Insertion character # (Pound: insert line number reference) -- The character # is replaced by the string indicating the source -- position stored in Error_Msg_Sloc. There are three cases: -- -- for package Standard: in package Standard -- for locations in current file: at line nnn:ccc -- for locations in other files: at filename:nnn:ccc -- -- By convention, the # insertion character is only used at the end of -- an error message, so the above strings only appear as the last -- characters of an error message. The only exceptions to this rule -- are that an RM reference may follow in the form (RM .....) and a -- right parenthesis may immediately follow the #. In the case of -- continued messages, # can only appear at the end of a group of -- continuation messages, except that \\\\ messages which always start -- a new line end the sequence from the point of view of this rule. -- The idea is that for any use of -gnatj, it will still be the case -- that a location reference appears only at the end of a line. -- Note: the output of the string ""at "" is suppressed if the string -- "" from"" or "" from "" immediately precedes the insertion character #. -- Certain messages read better with from than at. -- Insertion character } (Right brace: insert type reference) -- The character } is replaced by a string describing the type -- referenced by the entity whose Id is stored in Error_Msg_Node_1. -- The string gives the name or description of the type, and also -- where appropriate the location of its declaration. Special cases -- like ""some integer type"" are handled appropriately. Only one } is -- allowed in a message, since there is not enough room for two (the -- insertion can be quite long, including a file name). In addition, if -- the special global variable Error_Msg_Qual_Level is non-zero, then -- the reference will include up to the given number of levels of -- qualification, using the scope chain. -- Insertion character @ (At: insert column number reference) -- The character @ is replaced by null if the RM_Column_Check mode is -- off (False). If the switch is on (True), then @ is replaced by the -- text string "" in column nnn"" where nnn is the decimal -- representation of the column number stored in Error_Msg_Col plus -- one (the plus one is because the number is stored 0-origin and -- displayed 1-origin). -- Insertion character ^ (Caret: insert integer value) -- The character ^ is replaced by the decimal conversion of the Uint -- value stored in Error_Msg_Uint_1, with a possible leading minus. -- A second ^ may occur in the message, in which case it is replaced -- by the decimal conversion of the Uint value in Error_Msg_Uint_2. -- Insertion character > (Greater Than: run time name) -- The character > is replaced by a string of the form (name) if -- Targparm scanned out a Run_Time_Name (see package Targparm for -- details). The name is enclosed in parentheses and output in mixed -- case mode (upper case after any space in the name). If no run time -- name is defined, this insertion character has no effect. -- Insertion character ! (Exclamation: unconditional message) -- The character ! appearing anywhere in the text of a message makes -- the message unconditional which means that it is output even if it -- would normally be suppressed. See section above for a description -- of the cases in which messages are normally suppressed. Note that -- in the case of warnings, the meaning is that the warning should not -- be removed in dead code (that's the only time that the use of ! -- has any effect for a warning). -- -- Note: the presence of ! is ignored in continuation messages (i.e. -- messages starting with the \\ insertion character). The effect of the -- use of ! in a parent message automatically applies to all of its -- continuation messages (since we clearly don't want any case in which -- continuations are separated from the main message). It is allowable -- to put ! in continuation messages, and the usual style is to include -- it, since it makes it clear that the continuation is part of an -- unconditional message. -- Insertion character !! (Double exclamation: unconditional warning) -- Normally warning messages issued in other than the main unit are -- suppressed. If the message contains !! then this suppression is -- avoided. This is currently used by the Compile_Time_Warning pragma -- to ensure the message for a with'ed unit is output, and for warnings -- on ineffective back-end inlining, which is detected in units that -- contain subprograms to be inlined in the main program. It is also -- used by the Compiler_Unit_Warning pragma for similar reasons. -- Insertion character ? (Question: warning message) -- The character ? appearing anywhere in a message makes the message -- warning instead of a normal error message, and the text of the -- message will be preceded by ""warning:"" in the normal case. The -- handling of warnings if further controlled by the Warning_Mode -- option (-w switch), see package Opt for further details, and also by -- the current setting from pragma Warnings. This pragma applies only -- to warnings issued from the semantic phase (not the parser), but -- currently all relevant warnings are posted by the semantic phase -- anyway. Messages starting with (style) are also treated as warning -- messages. -- -- Note: when a warning message is output, the text of the message is -- preceded by ""warning: "" in the normal case. An exception to this -- rule occurs when the text of the message starts with ""info: "" in -- which case this string is not prepended. This allows callers to -- label certain warnings as informational messages, rather than as -- warning messages requiring some action. -- -- Note: the presence of ? is ignored in continuation messages (i.e. -- messages starting with the \\ insertion character). The warning -- status of continuations is determined only by the parent message -- which is being continued. It is allowable to put ? in continuation -- messages, and the usual style is to include it, since it makes it -- clear that the continuation is part of a warning message, but it is -- not necessary to go through any computational effort to include it. -- -- Note: this usage is obsolete, use ?? ?*? ?$? ?x? ?X? to specify -- the string to be added when Warn_Doc_Switch is set to True. If this -- switch is True, then for simple ? messages it has no effect. This -- simple form is to ease transition and may be removed later except -- for GNATprove-specific messages (info and warnings) which are not -- subject to the same GNAT warning switches. -- Insertion character ?? (Two question marks: default warning) -- Like ?, but if the flag Warn_Doc_Switch is True, adds the string -- ""[enabled by default]"" at the end of the warning message. For -- continuations, use this in each continuation message. -- Insertion character ?x? (warning with switch) -- Like ?, but if the flag Warn_Doc_Switch is True, adds the string -- ""[-gnatwx]"" at the end of the warning message. x is a lower case -- letter. For continuations, use this on each continuation message. -- Insertion character ?X? (warning with dot switch) -- Like ?, but if the flag Warn_Doc_Switch is True, adds the string -- ""[-gnatw.x]"" at the end of the warning message. X is an upper case -- letter corresponding to the lower case letter x in the message. -- For continuations, use this on each continuation message. -- Insertion character ?*? (restriction warning) -- Like ?, but if the flag Warn_Doc_Switch is True, adds the string -- ""[restriction warning]"" at the end of the warning message. For -- continuations, use this on each continuation message. -- Insertion character ?$? (elaboration informational messages) -- Like ?, but if the flag Warn_Doc_Switch is True, adds the string -- ""[-gnatel]"" at the end of the info message. This is used for the -- messages generated by the switch -gnatel. For continuations, use -- this on each continuation message. -- Insertion character < (Less Than: conditional warning message) -- The character < appearing anywhere in a message is used for a -- conditional error message. If Error_Msg_Warn is True, then the -- effect is the same as ? described above, and in particular << List_Pragma_Record, Table_Index_Type => Int, Table_Low_Bound => 1, Table_Initial => 50, Table_Increment => 200, Table_Name => ""List_Pragmas""); --------------------------- -- Ignore_Errors Feature -- --------------------------- -- In certain cases, notably for optional subunits, the compiler operates -- in a mode where errors are to be ignored, and the whole unit is to be -- considered as not present. To implement this we provide the following -- flag to enable special handling, where error messages are suppressed, -- but the Fatal_Error flag will still be set in the normal manner. Ignore_Errors_Enable : Nat := 0; -- Triggering switch. If non-zero, then ignore errors mode is activated. -- This is a counter to allow convenient nesting of enable/disable. ----------------------- -- CODEFIX Facility -- ----------------------- -- The GNAT Studio and GNATBench IDE's have a codefix facility that allows -- for automatic correction of a subset of the errors and warnings issued -- by the compiler. This is done by recognizing the text of specific -- messages using appropriate matching patterns. -- The text of such messages should not be altered without coordinating -- with the codefix code. All such messages are marked by a specific -- style of comments, as shown by the following example: -- Error_Msg_N -- CODEFIX -- (parameters ....) -- Any message marked with this -- CODEFIX comment should not be modified -- without appropriate coordination. ------------------------------ -- Error Output Subprograms -- ------------------------------ procedure Initialize; -- Initializes for output of error messages. Must be called for each -- source file before using any of the other routines in the package. procedure Finalize (Last_Call : Boolean); -- Finalize processing of error message list. Includes processing for -- duplicated error messages, and other similar final adjustment of the -- list of error messages. Note that this procedure must be called before -- calling Compilation_Errors to determine if there were any errors. It -- is perfectly fine to call Finalize more than once, providing that the -- parameter Last_Call is set False for every call except the last call. -- This multiple call capability is used to do some processing that may -- generate messages. Call Finalize to eliminate duplicates and remove -- deleted warnings. Test for compilation errors using Compilation_Errors, -- then generate some more errors/warnings, call Finalize again to make -- sure that all duplicates in these new messages are dealt with, then -- finally call Output_Messages to output the final list of messages. The -- argument Last_Call must be set False on all calls except the last call, -- and must be set True on the last call (a value of True activates some -- processing that must only be done after all messages are posted). procedure Output_Messages; -- Output list of messages, including messages giving number of detected -- errors and warnings. procedure Error_Msg (Msg : String; Flag_Location : Source_Ptr); procedure Error_Msg (Msg : String; Flag_Location : Source_Ptr; N : Node_Id); -- Output a message at specified location. Can be called from the parser -- or the semantic analyzer. If N is set, points to the relevant node for -- this message. procedure Error_Msg (Msg : String; Flag_Location : Source_Ptr; Is_Compile_Time_Pragma : Boolean); -- Same as Error_Msg (String, Source_Ptr) except Is_Compile_Time_Pragma -- lets the caller specify whether this is a Compile_Time_Warning or -- Compile_Time_Error pragma. procedure Error_Msg_S (Msg : String); -- Output a message at current scan pointer location. This routine can be -- called only from the parser, since it references Scan_Ptr. procedure Error_Msg_AP (Msg : String); -- Output a message just after the previous token. This routine can be -- called only from the parser, since it references Prev_Token_Ptr. procedure Error_Msg_BC (Msg : String); -- Output a message just before the current token. Note that the important -- difference between this and the previous routine is that the BC case -- posts a flag on the current line, whereas AP can post a flag at the -- end of the preceding line. This routine can be called only from the -- parser, since it references Token_Ptr. procedure Error_Msg_SC (Msg : String); -- Output a message at the start of the current token, unless we are at -- the end of file, in which case we always output the message after the -- last real token in the file. This routine can be called only from the -- parser, since it references Token_Ptr. procedure Error_Msg_SP (Msg : String); -- Output a message at the start of the previous token. This routine can -- be called only from the parser, since it references Prev_Token_Ptr. procedure Error_Msg_N (Msg : String; N : Node_Or_Entity_Id); -- Output a message at the Sloc of the given node. This routine can be -- called from the parser or the semantic analyzer, although the call from -- the latter is much more common (and is the most usual way of generating -- error messages from the analyzer). The message text may contain a -- single & insertion, which will reference the given node. The message is -- suppressed if the node N already has a message posted, or if it is a -- warning and N is an entity node for which warnings are suppressed. -- WARNING: There is a matching C declaration of this subprogram in fe.h procedure Error_Msg_F (Msg : String; N : Node_Id); -- Similar to Error_Msg_N except that the message is placed on the first -- node of the construct N (First_Node (N)). Note that this procedure uses -- Original_Node to look at the original source tree, since that's what we -- want for placing an error message flag in the right place. procedure Error_Msg_NE (Msg : String; N : Node_Or_Entity_Id; E : Node_Or_Entity_Id); -- Output a message at the Sloc of the given node N, with an insertion of -- the name from the given entity node E. This is used by the semantic -- routines, where this is a common error message situation. The Msg text -- will contain a & or } as usual to mark the insertion point. This -- routine can be called from the parser or the analyzer. -- WARNING: There is a matching C declaration of this subprogram in fe.h procedure Error_Msg_FE (Msg : String; N : Node_Id; E : Node_Or_Entity_Id); -- Same as Error_Msg_NE, except that the message is placed on the first -- node of the construct N (First_Node (N)). procedure Error_Msg_NEL (Msg : String; N : Node_Or_Entity_Id; E : Node_Or_Entity_Id; Flag_Location : Source_Ptr); -- Exactly the same as Error_Msg_NE, except that the flag is placed at -- the specified Flag_Location instead of at Sloc (N). procedure Error_Msg_NW (Eflag : Boolean; Msg : String; N : Node_Or_Entity_Id); -- This routine is used for posting a message conditionally. The message -- is posted (with the same effect as Error_Msg_N (Msg, N) if and only -- if Eflag is True and if the node N is within the main extended source -- unit and comes from source. Typically this is a warning mode flag. -- This routine can only be called during semantic analysis. It may not -- be called during parsing. procedure Change_Error_Text (Error_Id : Error_Msg_Id; New_Msg : String); -- The error message text of the message identified by Id is replaced by -- the given text. This text may contain insertion characters in the -- usual manner, and need not be the same length as the original text. function First_Node (C : Node_Id) return Node_Id; -- Given a construct C, finds the first node in the construct, i.e. the one -- with the lowest Sloc value. This is useful in placing error msgs. Note -- that this procedure uses Original_Node to look at the original source -- tree, since that's what we want for placing an error message flag in -- the right place. function First_Sloc (N : Node_Id) return Source_Ptr; -- Given the node for an expression, return a source pointer value that -- points to the start of the first token in the expression. In the case -- where the expression is parenthesized, an attempt is made to include -- the parentheses (i.e. to return the location of the initial paren). function Get_Ignore_Errors return Boolean; -- Return True if all error calls are ignored. procedure Purge_Messages (From : Source_Ptr; To : Source_Ptr) renames Erroutc.Purge_Messages; -- All error messages whose location is in the range From .. To (not -- including the end points) will be deleted from the error listing. procedure Remove_Warning_Messages (N : Node_Id); -- Remove any warning messages corresponding to the Sloc of N or any -- of its descendant nodes. No effect if no such warnings. Note that -- style messages (identified by the fact that they start with ""(style)"") -- are not removed by this call. Basically the idea behind this procedure -- is to remove warnings about execution conditions from known dead code. procedure Remove_Warning_Messages (L : List_Id); -- Remove warnings on all elements of a list (Calls Remove_Warning_Messages -- on each element of the list, see above). procedure Reset_Warnings; -- Reset the counts related to warnings. This is used both to initialize -- these counts and to reset them after each phase of analysis for a given -- value of Opt.Warning_Mode in gnat2why. procedure Set_Ignore_Errors (To : Boolean); -- Following a call to this procedure with To=True, all error calls are -- ignored. A call with To=False restores the default treatment in which -- error calls are treated as usual (and as described in this spec). procedure Set_Warnings_Mode_Off (Loc : Source_Ptr; Reason : String_Id) renames Erroutc.Set_Warnings_Mode_Off; -- Called in response to a pragma Warnings (Off) to record the source -- location from which warnings are to be turned off. Reason is the -- Reason from the pragma, or the null string if none is given. procedure Set_Warnings_Mode_On (Loc : Source_Ptr) renames Erroutc.Set_Warnings_Mode_On; -- Called in response to a pragma Warnings (On) to record the source -- location from which warnings are to be turned back on. procedure Set_Specific_Warning_Off (Loc : Source_Ptr; Msg : String; Reason : String_Id; Config : Boolean; Used : Boolean := False) renames Erroutc.Set_Specific_Warning_Off; -- This is called in response to the two argument form of pragma Warnings -- where the first argument is OFF, and the second argument is a string -- which identifies a specific warning to be suppressed. The first argument -- is the start of the suppression range, and the second argument is the -- string from the pragma. Loc is the location of the pragma (which is the -- start of the range to suppress). Reason is the reason string from the -- pragma, or the null string if no reason is given. Config is True for the -- configuration pragma case (where there is no requirement for a matching -- OFF pragma). Used is set True to disable the check that the warning -- actually has the effect of suppressing a warning. procedure Set_Specific_Warning_On (Loc : Source_Ptr; Msg : String; Err : out Boolean) renames Erroutc.Set_Specific_Warning_On; -- This is called in response to the two argument form of pragma Warnings -- where the first argument is ON, and the second argument is the prefix -- of a specific warning to be suppressed. The first argument is the end -- of the suppression range, and the second argument is the string from -- the pragma. Err is set to True on return to report the error of no -- matching Warnings Off pragma preceding this one. function Compilation_Errors return Boolean; -- Returns True if errors have been detected, or warnings in -gnatwe (treat -- warnings as errors) mode. Note that it is mandatory to call Finalize -- before calling this routine. To account for changes to Warning_Mode in -- gnat2why between phases, the past or current presence of an error is -- recorded in a global variable at each call. procedure Error_Msg_CRT (Feature : String; N : Node_Id); -- Posts a non-fatal message on node N saying that the feature identified -- by the Feature argument is not supported in either configurable -- run-time mode or no run-time mode (as appropriate). In the former case, -- the name of the library is output if available. procedure Error_Msg_PT (E : Entity_Id; Iface_Prim : Entity_Id); -- Posts an error on protected type entry or subprogram E (referencing its -- overridden interface primitive Iface_Prim) indicating wrong mode of the -- first formal (RM 9.4(11.9/3)). procedure Error_Msg_Ada_2012_Feature (Feature : String; Loc : Source_Ptr); -- If not operating in Ada 2012 mode or higher, posts errors complaining -- that Feature is only supported in Ada 2012, with appropriate suggestions -- to fix this. Loc is the location at which the flag is to be posted. -- Feature, which appears at the start of the first generated message, may -- contain error message insertion characters in the normal manner, and in -- particular may start with | to flag a non-serious error. procedure Error_Msg_Ada_2020_Feature (Feature : String; Loc : Source_Ptr); -- Analogous to Error_Msg_Ada_2012_Feature procedure dmsg (Id : Error_Msg_Id) renames Erroutc.dmsg; -- Debugging routine to dump an error message ------------------------------------ -- SPARK Error Output Subprograms -- ------------------------------------ -- The following routines are intended to report semantic errors in SPARK -- constructs subject to aspect/pragma SPARK_Mode. Note that syntax errors -- must be reported using the Error_Msg_XXX routines. This allows for the -- partial analysis of SPARK features when they are disabled via SPARK_Mode -- set to ""off"". procedure SPARK_Msg_N (Msg : String; N : Node_Or_Entity_Id); pragma Inline (SPARK_Msg_N); -- Same as Error_Msg_N, but the error is suppressed if SPARK_Mode is Off. -- The routine is inlined because it acts as a simple wrapper. procedure SPARK_Msg_NE (Msg : String; N : Node_Or_Entity_Id; E : Node_Or_Entity_Id); pragma Inline (SPARK_Msg_NE); -- Same as Error_Msg_NE, but the error is suppressed if SPARK_Mode is Off. -- The routine is inlined because it acts as a simple wrapper. ------------------------------------------ -- Utility Interface for Casing Control -- ------------------------------------------ procedure Adjust_Name_Case (Buf : in out Bounded_String; Loc : Source_Ptr); -- Given a name stored in Buf, set proper casing. Loc is an associated -- source position, and if we can find a match between the name in Buf and -- the name at that source location, we copy the casing from the source, -- otherwise we set appropriate default casing. procedure Adjust_Name_Case (Loc : Source_Ptr); -- Uses Buf => Global_Name_Buffer. There are no calls to this in the -- compiler, but it is called in SPARK 2014. procedure Set_Identifier_Casing (Identifier_Name : System.Address; File_Name : System.Address); -- This subprogram can be used by the back end for the purposes of -- concocting error messages that are not output via Errout, e.g. -- the messages generated by the gcc back end. -- -- The identifier is a null terminated string that represents the name of -- an identifier appearing in the source program. File_Name is a null -- terminated string giving the corresponding file name for the identifier -- as obtained from the front end by the use of Full_Debug_Name to the -- source file referenced by the corresponding source location value. On -- return, the name is in Name_Buffer, null terminated with Name_Len set. -- This name is the identifier name as passed, cased according to the -- default identifier casing for the given file. -- WARNING: There is a matching C declaration of this subprogram in fe.h function Is_Size_Too_Small_Message (S : String) return Boolean; Size_Too_Small_Message : constant String := ""size for& too small, minimum allowed is ^""; -- This message is printed in Freeze and Sem_Ch13. We also test for it in -- the body of this package (see Special_Msg_Delete) ???which is somewhat -- questionable. The Is_Size_Too_Small_Message function tests for it by -- testing a prefix. The function and constant should be kept in synch. end Errout; ",12211,False,2216.3820663738775,median " -1 dilate_0_0_2160_3840_0_3_3_1_1_26 0 4 0 1 1 imgHelper2_4102 0 0 0 FIFO_SRL 0 8 0 3 0 0 0 1 2 imgHelper3_4103 0 0 0 FIFO_SRL 49 8 1 3 0 0 0 1 3 p_src_rows 0 0 0 FIFO_SRL 1769353058 32 0 3 0 0 0 1 4 p_src_cols 0 0 0 FIFO_SRL 97 32 0 3 0 0 0 6 0 0 11 p_src_rows_read /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp .. 340 dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; dilate_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 340 auto fifo srl FIFO_SRL 81 32 2 0 19 20 read 0 0 0 0 3.32 1 -1 0 12 p_src_cols_read /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp .. 341 dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; dilate_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 341 auto fifo srl FIFO_SRL 81 32 2 0 21 22 read 0 0 0 0 3.32 2 -1 0 13 trunc_ln340 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp .. 340 dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; dilate_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 340 trunc_ln340_fu_52_p1 113 16 1 0 23 trunc 0 0 0 0 0.00 3 -1 0 14 trunc_ln341 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp .. 341 dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; dilate_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 341 trunc_ln341_fu_57_p1 113 16 1 0 24 trunc 0 0 0 0 0.00 4 -1 0 15 _ln376 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp .. 376 dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; dilate_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 376 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42 113 0 5 0 26 27 28 29 30 call 0 0 0 0 0.00 5 -1 0 16 _ln0 0 0 0 113 0 0 0 ret 0 0 0 0 0.00 6 -1 1 0 2 25 xfdilate_2160_3840_1_0_1_0_3841_3_3_s 0 0 0 3409872361 0 6 <constant:xfdilate<2160, 3840, 1, 0, 1, 0, 3841, 3, 3>> 1 0 3 17 dilate<0, 0, 2160, 3840, 0, 3, 3, 1, 1>26 0 0 0 1768189039 6 0 11 12 13 14 15 16 9 0 20 1 3 11 0 22 1 4 12 0 23 1 11 13 0 24 1 12 14 0 26 1 25 15 0 27 1 1 15 0 28 1 2 15 0 29 1 13 15 0 30 1 14 15 0 1 0 1 dilate<0, 0, 2160, 3840, 0, 3, 3, 1, 1>26 dilate_0_0_2160_3840_0_3_3_1_1_26 0 0 0 1 0 17 -1 -1 -1 -1 13 8319373 0 2 0 1 5 0 11 1 1 12 1 1 13 1 1 14 1 1 15 2 2 2 8 0 5 1 1 6 1 1 7 1 1 8 1 1 9 1 1 10 1 1 15 1 2 16 1 1 1 0 1 2 -1 1 0 0 0 1 0 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42 (xfdilate_2160_3840_1_0_1_0_3841_3_3_s) 3 0 BRAM 6 FF 611 LUT 819 1 0 ap_block_state1 ( or ) 4 0 (0P0) 1 (1P1) 1 FF 0 LUT 1 0 0 0 0 6 0 ap_NS_fsm 4 0 (0Size) 3 (1Bits) 1 (2Count) 3 LUT 13 ap_done 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 imgHelper2_4102_read 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 imgHelper3_4103_write 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 p_src_cols_blk_n 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 p_src_rows_blk_n 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 5 0 ap_CS_fsm 3 0 (Bits) 2 (Consts) 0 FF 2 ap_done_reg 3 0 (Bits) 1 (Consts) 0 FF 1 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42_ap_start_reg 3 0 (Bits) 1 (Consts) 0 FF 1 trunc_ln340_reg_62 3 0 (Bits) 16 (Consts) 0 FF 16 trunc_ln341_reg_67 3 0 (Bits) 16 (Consts) 0 FF 16 1 0 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42 0 0 1 0 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42 (xfdilate_2160_3840_1_0_1_0_3841_3_3_s) 1 0 15 0 0 0 0 0 0 6 0 11 0 0 12 0 0 13 0 0 14 0 0 15 0 1 16 1 0 1 0 17 0 1 0 0 5 0 30 1 0 11 36 1 0 12 42 2 0 15 15 52 1 0 13 57 1 0 14 2 0 trunc_ln340_fu_52 1 0 13 trunc_ln341_fu_57 1 0 14 1 0 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42 2 0 15 15 2 0 p_src_cols_read_read_fu_36 1 0 12 p_src_rows_read_read_fu_30 1 0 11 0 0 0 0 2 0 62 1 0 13 67 1 0 14 2 0 trunc_ln340_reg_62 1 0 13 trunc_ln341_reg_67 1 0 14 0 0 0 0 4 0 imgHelper2_4102 1 0 call 1 0 15 imgHelper3_4103 1 0 call 1 0 15 p_src_cols 1 0 read 1 0 12 p_src_rows 1 0 read 1 0 11 4 0 1 1150 10 2 1151 10 3 1150 10 4 1150 10 3 0 11 1150 10 12 1150 10 15 -1 -1 ",12512,False,2197.564868395142,median "//// Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the ""License""); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. //// anchor:gremlin-variants[] [[gremlin-drivers-variants]] = Gremlin Drivers and Variants image::gremlin-house-of-mirrors.png[width=1024] At this point, readers should be well familiar with the <> to this Reference Documentation and will likely be thinking about implementation details specific to the graph provider they have selected as well as the programming language they intend to use. The choice of programming language could have implications to the architecture and design of the application and the choice itself may have limits imposed upon it by the chosen graph provider. For example, a <> will require the selection of a driver to interact with it. On the other hand, a graph system that is designed for embedded use, like TinkerGraph, needs the Java Virtual Machine (JVM) environment so will require <>, if using a programming language that is not on the JVM and will further require driver selection. TinkerPop provides an array of drivers in different programming languages as a way to connect to a remote Gremlin Server or Remote Gremlin Provider. Drivers allow the developer to make requests to that remote system and get back results from the TinkerPop-enabled graphs hosted within. A driver can submit Gremlin strings and Gremlin bytecode over this sub-protocol. Gremlin strings are written in the scripting language made available by the remote system that the driver is connecting to (typically, Groovy-based). This connection approach is quite similar to what developers are likely familiar with when using JDBC and SQL. While it is familiar, it is not recommended and for TinkerPop it is considered an out-dated concept and is largely still present for the purpose of supporting applications that might still be using that method of interaction. The preferred approach is to use bytecode-based requests, which essentially allows the ability to craft Gremlin directly in the programming language of choice. As Gremlin makes use of two fundamental programming constructs: link:https://en.wikipedia.org/wiki/Function_composition[function composition] and link:https://en.wikipedia.org/wiki/Nested_function[function nesting]. it is possible to embed the Gremlin language in any modern programming language. It is a far more natural way to program, because it enables IDE interaction, compile time checks, and language level checks that can help prevent errors prior to execution. The differences between these two approaches were outlined in the <> Section, which applies to Gremlin Server, but also to Remote Gremlin Providers. In addition to the languages and drivers that TinkerPop supports, there are also third-party implementations, as well as extensions to the Gremlin language that might be specific to a particular graph provider. That listing can be found on the TinkerPop link:https://tinkerpop.apache.org/#graph-systems[home page]. Their description is beyond the scope of this documentation. TIP: When possible, it is typically best to align the version of TinkerPop used on the client with the version supported on the server. While it is not impossible to have a different version between client and server, it may require additional configuration and/or a deeper knowledge of that changes introduced between versions. It's simply safer to avoid the conflict, when allowed to do so. IMPORTANT: Gremlin-Java is the canonical representation of Gremlin and any (proper) Gremlin language variant will emulate its structure as best as possible given the constructs of the host language. A strong correspondence between variants ensures that the general Gremlin reference documentation is applicable to all variants and that users moving between development languages can easily adopt the Gremlin variant for that language. image::gremlin-variant-architecture.png[width=650,float=left] NOTE: The information herein describes how to use the Gremlin language variants distributed with Apache TinkerPop. For information on how to build a Gremlin language variant, please review the link:https://tinkerpop.apache.org/docs/x.y.z/tutorials/gremlin-language-variants/[Gremlin Language Variants] tutorial. The following sections describe each language variant and driver that is officially TinkerPop a part of the project, provided more detailed information about usage, configuration and known limitations. anchor:connecting-via-remotegraph[] anchor:connecting-via-java[] [[gremlin-java]] == Gremlin-Java image:gremlin-java-drawing.png[width=130,float=right] Apache TinkerPop's Gremlin-Java implements Gremlin within the Java language and can be used by any Java Virtual Machine. Gremlin-Java is considered the canonical, reference implementation of Gremlin and serves as the foundation by which all other Gremlin language variants should emulate. As the Gremlin Traversal Machine that processes Gremlin queries is also written in Java, it can be used in all three connection methods described in the <> Section. [source,xml] ---- org.apache.tinkerpop gremlin-core x.y.z org.apache.tinkerpop gremlin-driver x.y.z ---- === Connecting The pattern for connecting is described in <> and it basically distills down to creating a `GraphTraversalSource`. For <> mode, this involves first creating a `Graph` and then spawning the `GraphTraversalSource`: [source,java] ---- Graph graph = ...; GraphTraversalSource g = graph.traversal(); ---- Using ""g"" it is then possible to start writing Gremlin. The ""g"" allows for the setting of many configuration options which affect traversal execution. The <> Section describes some of these options and some are only suitable with <> style usage. For remote options however there are some added configurations to consider and this section looks to address those. When connecting to <> or <> it is possible to configure the `DriverRemoteConnection` manually as shown in earlier examples where the host and port are provided as follows: [source,java] ---- GraphTraversalSource g = traversal().withRemote(DriverRemoteConnection.using(""localhost"",8182,""g"")); ---- It is also possible to create it from a configuration. The most basic way to do so involves the following line of code: [source,java] ---- GraphTraversalSource g = traversal().withRemote('conf/remote-graph.properties'); ---- The `remote-graph.properties` file simply provides connection information to the `GraphTraversalSource` which is used to configure a `RemoteConnection`. That file looks like this: [source,text] ---- gremlin.remote.remoteConnectionClass=org.apache.tinkerpop.gremlin.driver.remote.DriverRemoteConnection gremlin.remote.driver.clusterFile=conf/remote-objects.yaml gremlin.remote.driver.sourceName=g ---- The `RemoteConnection` is an interface that provides the transport mechanism for ""g"" and makes it possible to for that mechanism to be altered (typically by graph providers who have their own protocols). TinkerPop provides one such implementation called the `DriverRemoteConnection` which enables transport over Gremlin Server protocols using the TinkerPop driver. The driver is configured by the specified `gremlin.remote.driver.clusterFile` and the local ""g"" is bound to the `GraphTraversalSource` on the remote end with `gremlin.remote.driver.sourceName` which in this case is also ""g"". There are other ways to configure the traversal using `withRemote()` as it has other overloads. It can take an Apache Commons `Configuration` object which would have keys similar to those shown in the properties file and it can also take a `RemoteConnection` instance directly. The latter is interesting in that it means it is possible to programmatically construct all aspects of the `RemoteConnection`. For TinkerPop usage, that might mean directly constructing the `DriverRemoteConnection` and the driver instance that supplies the transport mechanism. For example, the command shown above could be re-written using programmatic construction as follows: [source,java] ---- Cluster cluster = Cluster.open(); GraphTraversalSource g = traversal().withRemote(DriverRemoteConnection.using(cluster, ""g"")); ---- Please consider the following example: [gremlin-groovy] ---- g = traversal().withRemote('conf/remote-graph.properties') g.V().elementMap() g.close() ---- [source,java] ---- GraphTraversalSource g = traversal().withRemote(""conf/remote-graph.properties""); List list = g.V().elementMap(); g.close(); ---- Note the call to `close()` above. The call to `withRemote()` internally instantiates a connection via the driver that can only be released by ""closing"" the `GraphTraversalSource`. It is important to take that step to release resources created in that step. If working with multiple remote `TraversalSource` instances it is more efficient to construct `Cluster` and `Client objects and then re-use them. [gremlin-groovy] ---- cluster = Cluster.open('conf/remote-objects.yaml') client = cluster.connect() g = traversal().withRemote(DriverRemoteConnection.using(client, ""g"")) g.V().elementMap() g.close() client.close() cluster.close() ---- If the `Client` instance is supplied externally, as is shown above, then it is not closed implicitly by the close of ""g"". Closing ""g"" will have no effect on ""client"" or ""cluster"". When supplying them externally, the `Client` and `Cluster` objects must also be closed explicitly. It's worth noting that the close of a `Cluster` will close all `Client` instances spawned by the `Cluster`. IMPORTANT: Bytecode-based traversals use the `TraversalOpProcessor` in Gremlin Server which requires a cache to enable the retrieval of side-effects (if the `Traversal` produces any). That cache can be configured (e.g. controlling eviction times and sizing) in the Gremlin Server configuration file as described <>. Some connection options can also be set on individual requests made through the Java driver using `with()` step on the `TraversalSource`. For instance to set request timeout to 500 milliseconds: [source,java] ---- GraphTraversalSource g = traversal().withRemote(conf); List vertices = g.with(Tokens.ARGS_EVAL_TIMEOUT, 500L).V().out(""knows"").toList() ---- [[java-imports]] === Common Imports There are a number of classes, functions and tokens that are typically used with Gremlin. The following imports provide most of the common functionality required to use Gremlin: [source,java] ---- import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.process.traversal.IO; import static org.apache.tinkerpop.gremlin.process.traversal.AnonymousTraversalSource.traversal; import static org.apache.tinkerpop.gremlin.process.traversal.Operator.*; import static org.apache.tinkerpop.gremlin.process.traversal.Order.*; import static org.apache.tinkerpop.gremlin.process.traversal.P.*; import static org.apache.tinkerpop.gremlin.process.traversal.Pop.*; import static org.apache.tinkerpop.gremlin.process.traversal.SackFunctions.*; import static org.apache.tinkerpop.gremlin.process.traversal.Scope.*; import static org.apache.tinkerpop.gremlin.process.traversal.TextP.*; import static org.apache.tinkerpop.gremlin.structure.Column.*; import static org.apache.tinkerpop.gremlin.structure.Direction.*; import static org.apache.tinkerpop.gremlin.structure.T.*; import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.*; ---- === Configuration The following table describes the various configuration options for the Gremlin Driver: [width=""100%"",cols=""3,10,^2"",options=""header""] |========================================================= |Key |Description |Default |connectionPool.channelizer |The fully qualified classname of the client `Channelizer` that defines how to connect to the server. |`Channelizer.WebSocketChannelizer` |connectionPool.enableSsl |Determines if SSL should be enabled or not. If enabled on the server then it must be enabled on the client. |false |connectionPool.keepAliveInterval |Length of time in milliseconds to wait on an idle connection before sending a keep-alive request. Set to zero to disable this feature. |180000 |connectionPool.keyStore |The private key in JKS or PKCS#12 format. |_none_ |connectionPool.keyStorePassword |The password of the `keyStore` if it is password-protected. |_none_ |connectionPool.keyStoreType |`JKS` (Java 8 default) or `PKCS12` (Java 9+ default)|_none_ |connectionPool.maxContentLength |The maximum length in bytes that a message can be sent to the server. This number can be no greater than the setting of the same name in the server configuration. |65536 |connectionPool.maxInProcessPerConnection |The maximum number of in-flight requests that can occur on a connection. |4 |connectionPool.maxSimultaneousUsagePerConnection |The maximum number of times that a connection can be borrowed from the pool simultaneously. |16 |connectionPool.maxSize |The maximum size of a connection pool for a host. |8 |connectionPool.maxWaitForConnection |The amount of time in milliseconds to wait for a new connection before timing out. |3000 |connectionPool.maxWaitForClose |The amount of time in milliseconds to wait for pending messages to be returned from the server before closing the connection. |3000 |connectionPool.minInProcessPerConnection |The minimum number of in-flight requests that can occur on a connection. |1 |connectionPool.minSimultaneousUsagePerConnection |The maximum number of times that a connection can be borrowed from the pool simultaneously. |8 |connectionPool.minSize |The minimum size of a connection pool for a host. |2 |connectionPool.reconnectInterval |The amount of time in milliseconds to wait before trying to reconnect to a dead host. |1000 |connectionPool.resultIterationBatchSize |The override value for the size of the result batches to be returned from the server. |64 |connectionPool.sslCipherSuites |The list of JSSE ciphers to support for SSL connections. If specified, only the ciphers that are listed and supported will be enabled. If not specified, the JVM default is used. |_none_ |connectionPool.sslEnabledProtocols |The list of SSL protocols to support for SSL connections. If specified, only the protocols that are listed and supported will be enabled. If not specified, the JVM default is used. |_none_ |connectionPool.sslSkipCertValidation |Configures the `TrustManager` to trust all certs without any validation. Should not be used in production.|false |connectionPool.trustStore |File location for a SSL Certificate Chain to use when SSL is enabled. If this value is not provided and SSL is enabled, the default `TrustManager` will be used. |_none_ |connectionPool.trustStorePassword |The password of the `trustStore` if it is password-protected |_none_ |connectionPool.validationRequest |A script that is used to test server connectivity. A good script to use is one that evaluates quickly and returns no data. The default simply returns an empty string, but if a graph is required by a particular provider, a good traversal might be `g.inject()`. |_''_ |hosts |The list of hosts that the driver will connect to. |localhost |jaasEntry |Sets the `AuthProperties.Property.JAAS_ENTRY` properties for authentication to Gremlin Server. |_none_ |nioPoolSize |Size of the pool for handling request/response operations. |available processors |password |The password to submit on requests that require authentication. |_none_ |path |The URL path to the Gremlin Server. |_/gremlin_ |port |The port of the Gremlin Server to connect to. The same port will be applied for all hosts. |8192 |protocol |Sets the `AuthProperties.Property.PROTOCOL` properties for authentication to Gremlin Server. |_none_ |serializer.className |The fully qualified class name of the `MessageSerializer` that will be used to communicate with the server. Note that the serializer configured on the client should be supported by the server configuration. |_none_ |serializer.config |A `Map` of configuration settings for the serializer. |_none_ |username |The username to submit on requests that require authentication. |_none_ |workerPoolSize |Size of the pool for handling background work. |available processors * 2 |========================================================= Please see the link:https://tinkerpop.apache.org/javadocs/x.y.z/core/org/apache/tinkerpop/gremlin/driver/Cluster.Builder.html[Cluster.Builder javadoc] to get more information on these settings. === Serialization Remote systems like Gremlin Server and Remote Gremlin Providers respond to requests made in a particular serialization format and respond by serializing results to some format to be interpreted by the client. For JVM-based languages, there are three options for serialization: Gryo, GraphSON and GraphBinary. It is important that the client and server have the same serializers configured in the same way or else one or the other will experience serialization exceptions and fail to always communicate. Discrepancy in serializer registration between client and server can happen fairly easily as different graph systems may automatically include serializers on the server-side, thus leaving the client to be configured manually. As an example: [source,java] ---- IoRegistry registry = ...; // an IoRegistry instance exposed by a specific graph provider TypeSerializerRegistry typeSerializerRegistry = TypeSerializerRegistry.build().addRegistry(registry).create(); MessageSerializer serializer = new GraphBinaryMessageSerializerV1(typeSerializerRegistry); Cluster cluster = Cluster.build(). serializer(serializer). create(); Client client = cluster.connect(); GraphTraversalSource g = traversal().withRemote(DriverRemoteConnection.using(client, ""g"")); ---- The `IoRegistry` tells the serializer what classes from the graph provider to auto-register during serialization. Gremlin Server roughly uses this same approach when it configures its serializers, so using this same model will ensure compatibility when making requests. Obviously, it is possible to switch to GraphSON or Gryo by using the appropriate `MessageSerializer` (e.g. `GraphSONMessageSerializerV3d0` or `GryoMessageSerializerV3d0` respectively) in the same way and building that into the `Cluster` object. NOTE: Gryo is no longer the preferred binary serialization format for Gremlin Server - please prefer GraphBinary. === The Lambda Solution Supporting link:https://en.wikipedia.org/wiki/Anonymous_function[anonymous functions] across languages is difficult as most languages do not support lambda introspection and thus, code analysis. In Gremlin-Java and with <> usage, lambdas can be leveraged directly: [source,java] ---- g.V().out(""knows"").map(t -> t.get().value(""name"") + "" is the friend name"") <1> g.V().out(""knows"").sideEffect(System.out::println) <2> g.V().as(""a"").out(""knows"").as(""b"").select(""b"").by((Function) v -> v.value(""name"").length()) <3> ---- <1> A Java `Function` is used to map a `Traverser` to an object `E`. <2> Gremlin steps that take consumer arguments can be passed Java method references. <3> Gremlin-Java may sometimes require explicit lambda typing when types can not be automatically inferred. When sending traversals remotely to <> or <>, the static methods of `Lambda` should be used and should denote a particular JSR-223 `ScriptEngine` that is available on the remote end (typically, this is Groovy). `Lambda` creates a string-based lambda that is then converted into a lambda/closure/anonymous-function/etc. by the respective lambda language's JSR-223 `ScriptEngine` implementation. [source,java] ---- g.V().out(""knows"").map(Lambda.function(""it.get().value('name') + ' is the friend name'"")) g.V().out(""knows"").sideEffect(Lambda.consumer(""println it"")) g.V().as(""a"").out(""knows"").as(""b"").select(""b"").by(Lambda.function(""it.value('name').length()"")) ---- Finally, Gremlin `Bytecode` that includes lambdas requires that the traversal be processed by the `ScriptEngine`. To avoid continued recompilation costs, it supports the encoding of bindings, which allow Gremlin Server to cache traversals that will be reused over and over again save that some parameterization may change. Thus, instead of translating, compiling, and then executing each submitted bytecode request, it is possible to simply execute. To express bindings in Java, use `Bindings`. [source,java] ---- b = Bindings.instance() g.V(b.of('id',1)).out('created').values('name').map{t -> ""name: "" + t.get() } g.V(b.of('id',4)).out('created').values('name').map{t -> ""name: "" + t.get() } g.V(b.of('id',4)).out('created').values('name').getBytecode() g.V(b.of('id',4)).out('created').values('name').getBytecode().getBindings() cluster.close() ---- Both traversals are abstractly defined as `g.V(id).out('created').values('name').map{t -> ""name: "" + t.get() }` and thus, the first submission can be cached for faster evaluation on the next submission. WARNING: It is generally advised to avoid lambda usage. Please consider <> for more information. === Submitting Scripts WARNING: TinkerPop does not recommend submitting script-based requests and generally continues to support this feature for legacy reasons and corner use cases which are still not completely addressed by the Gremlin language. Please consider using bytecode-based requests instead when possible. image:gremlin-java.png[width=175,float=left] TinkerPop comes equipped with a reference client for Java-based applications. It is referred to as `gremlin-driver`, which enables applications to send requests to Gremlin Server and get back results. Gremlin scripts are sent to the server from a `Client` instance. A `Client` is created as follows: [source,java] ---- Cluster cluster = Cluster.open(); <1> Client client = cluster.connect(); <2> ---- <1> Opens a reference to `localhost` - note that there are many configuration options available in defining a `Cluster` object. <2> Creates a `Client` given the configuration options of the `Cluster`. Once a `Client` instance is ready, it is possible to issue some Gremlin Groovy scripts: [source,java] ---- ResultSet results = client.submit(""[1,2,3,4]""); <1> results.stream().map(i -> i.get(Integer.class) * 2); <2> CompletableFuture> results = client.submit(""[1,2,3,4]"").all(); <3> CompletableFuture future = client.submitAsync(""[1,2,3,4]""); <4> Map params = new HashMap<>(); params.put(""x"",4); client.submit(""[1,2,3,x]"", params); <5> ---- <1> Submits a script that simply returns a `List` of integers. This method blocks until the request is written to the server and a `ResultSet` is constructed. <2> Even though the `ResultSet` is constructed, it does not mean that the server has sent back the results (or even evaluated the script potentially). The `ResultSet` is just a holder that is awaiting the results from the server. In this case, they are streamed from the server as they arrive. <3> Submit a script, get a `ResultSet`, then return a `CompletableFuture` that will be called when all results have been returned. <4> Submit a script asynchronously without waiting for the request to be written to the server. <5> Parameterized request are considered the most efficient way to send Gremlin to the server as they can be cached, which will boost performance and reduce resources required on the server. ==== Per Request Settings There are a number of overloads to `Client.submit()` that accept a `RequestOptions` object. The `RequestOptions` provide a way to include options that are specific to the request made with the call to `submit()`. A good use-case for this feature is to set a per-request override to the `evaluationTimeout` so that it only applies to the current request. [source,java] ---- Cluster cluster = Cluster.open(); Client client = cluster.connect(); RequestOptions options = RequestOptions.build().timeout(500).create(); List result = client.submit(""g.V()"", options).all().get(); ---- ==== Aliases Scripts submitted to Gremlin Server automatically have the globally configured `Graph` and `TraversalSource` instances made available to them. Therefore, if Gremlin Server configures two `TraversalSource` instances called ""g1"" and ""g2"" a script can simply reference them directly as: [source,java] ---- client.submit(""g1.V()"") client.submit(""g2.V()"") ---- While this is an acceptable way to submit scripts, it has the downside of forcing the client to encode the server-side variable name directly into the script being sent. If the server configuration ever changed such that ""g1"" became ""g100"", the client-side code might have to see a significant amount of change. Decoupling the script code from the server configuration can be managed by the `alias` method on `Client` as follows: [source,java] ---- Client g1Client = client.alias(""g1"") Client g2Client = client.alias(""g2"") g1Client.submit(""g.V()"") g2Client.submit(""g.V()"") ---- The above code demonstrates how the `alias` method can be used such that the script need only contain a reference to ""g"" and ""g1"" and ""g2"" are automatically rebound into ""g"" on the server-side. [[gremlin-java-dsl]] === Domain Specific Languages Creating a <> (DSL) in Java requires the `@GremlinDsl` Java annotation in `gremlin-core`. This annotation should be applied to a ""DSL interface"" that extends `GraphTraversal.Admin`: [source,java] ---- @GremlinDsl public interface SocialTraversalDsl extends GraphTraversal.Admin { } ---- IMPORTANT: The name of the DSL interface should be suffixed with ""TraversalDSL"". All characters in the interface name before that become the ""name"" of the DSL. In this interface, define the methods that the DSL will be composed of: [source,java] ---- @GremlinDsl public interface SocialTraversalDsl extends GraphTraversal.Admin { public default GraphTraversal knows(String personName) { return out(""knows"").hasLabel(""person"").has(""name"", personName); } public default GraphTraversal youngestFriendsAge() { return out(""knows"").hasLabel(""person"").values(""age"").min(); } public default GraphTraversal createdAtLeast(int number) { return outE(""created"").count().is(P.gte(number)); } } ---- IMPORTANT: Follow the TinkerPop convention of using `` in naming generics as those conventions are taken into account when generating the anonymous traversal class. The processor attempts to infer the appropriate type parameters when generating the anonymous traversal class. If it cannot do it correctly, it is possible to avoid the inference by using the `GremlinDsl.AnonymousMethod` annotation on the DSL method. It allows explicit specification of the types to use. The `@GremlinDsl` annotation is used by the link:https://docs.oracle.com/javase/8/docs/api/index.html?javax/annotation/processing/Processor.html[Java Annotation Processor] to generate the boilerplate class structure required to properly use the DSL within the TinkerPop framework. These classes can be generated and maintained by hand, but it would be time consuming, monotonous and error-prone to do so. Typically, the Java compilation process is automatically configured to detect annotation processors on the classpath and will automatically use them when found. If that does not happen, it may be necessary to make configuration changes to the build to allow for the compilation process to be aware of the following `javax.annotation.processing.Processor` implementation: [source,java] ---- org.apache.tinkerpop.gremlin.process.traversal.dsl.GremlinDslProcessor ---- The annotation processor will generate several classes for the DSL: * `SocialTraversal` - A `Traversal` interface that extends the `SocialTraversalDsl` proxying methods to its underlying interfaces (such as `GraphTraversal`) to instead return a `SocialTraversal` * `DefaultSocialTraversal` - A default implementation of `SocialTraversal` (typically not used directly by the user) * `SocialTraversalSource` - Spawns `DefaultSocialTraversal` instances. * `__` - Spawns anonymous `DefaultSocialTraversal` instances. Using the DSL then just involves telling the `Graph` to use it: [source,java] ---- SocialTraversalSource social = graph.traversal(SocialTraversalSource.class); social.V().has(""name"",""marko"").knows(""josh""); ---- The `SocialTraversalSource` can also be customized with DSL functions. As an additional step, include a class that extends from `GraphTraversalSource` and with a name that is suffixed with ""TraversalSourceDsl"". Include in this class, any custom methods required by the DSL: [source,java] ---- public class SocialTraversalSourceDsl extends GraphTraversalSource { public SocialTraversalSourceDsl(Graph graph, TraversalStrategies traversalStrategies) { super(graph, traversalStrategies); } public SocialTraversalSourceDsl(Graph graph) { super(graph); } public GraphTraversal persons(String... names) { GraphTraversalSource clone = this.clone(); // Manually add a ""start"" step for the traversal in this case the equivalent of V(). GraphStep is marked // as a ""start"" step by passing ""true"" in the constructor. clone.getBytecode().addStep(GraphTraversal.Symbols.V); GraphTraversal traversal = new DefaultGraphTraversal<>(clone); traversal.asAdmin().addStep(new GraphStep<>(traversal.asAdmin(), Vertex.class, true)); traversal = traversal.hasLabel(""person""); if (names.length > 0) traversal = traversal.has(""name"", P.within(names)); return traversal; } } ---- Then, back in the `SocialTraversal` interface, update the `GremlinDsl` annotation with the `traversalSource` argument to point to the fully qualified class name of the `SocialTraversalSourceDsl`: [source,java] ---- @GremlinDsl(traversalSource = ""com.company.SocialTraversalSourceDsl"") public interface SocialTraversalDsl extends GraphTraversal.Admin { ... } ---- It is then possible to use the `persons()` method to start traversals: [source,java] ---- SocialTraversalSource social = graph.traversal(SocialTraversalSource.class); social.persons(""marko"").knows(""josh""); ---- NOTE: Using Maven, as shown in the `gremlin-archetype-dsl` module, makes developing DSLs with the annotation processor straightforward in that it sets up appropriate paths to the generated code automatically. anchor:java-application-examples[] [[gremlin-archetypes]] === Application Examples The available link:https://maven.apache.org/guides/introduction/introduction-to-archetypes.html[Maven archetypes] are as follows: * `gremlin-archetype-dsl` - An example project that demonstrates how to build Domain Specific Languages with Gremlin in Java. * `gremlin-archetype-server` - An example project that demonstrates the basic structure of a <> project, how to connect with the Gremlin Driver, and how to embed Gremlin Server in a testing framework. * `gremlin-archetype-tinkergraph` - A basic example of how to structure a TinkerPop project with Maven. Use Maven to generate these example projects with a command like: [source,shell] $ mvn archetype:generate -DarchetypeGroupId=org.apache.tinkerpop -DarchetypeArtifactId=gremlin-archetype-server \\ -DarchetypeVersion=x.y.z -DgroupId=com.my -DartifactId=app -Dversion=0.1 -DinteractiveMode=false This command will generate a new Maven project in a directory called ""app"" with a `pom.xml` specifying a `groupId` of `com.my`. Please see the `README.asciidoc` in the root of each generated project for information on how to build and execute it. [[gremlin-groovy]] == Gremlin-Groovy image:gremlin-groovy-drawing.png[width=130,float=right] Apache TinkerPop's Gremlin-Groovy implements Gremlin within the link:http://groovy.apache.org[Apache Groovy] language. As a JVM-based language variant, Gremlin-Groovy is backed by Gremlin-Java constructs. Moreover, given its scripting nature, Gremlin-Groovy serves as the language of <> and <>. [source,groovy] ---- compile group: 'org.apache.tinkerpop', name: 'gremlin-core', version: '3.3.4' compile group: 'org.apache.tinkerpop', name: 'gremlin-driver', version: '3.3.4' ---- [[gremlin-groovy-differences]] === Differences In Groovy, `as`, `in`, and `not` are reserved words. Gremlin-Groovy does not allow these steps to be called statically from the anonymous traversal `+__+` and therefore, must always be prefixed with `+__.+` For instance: `+g.V().as('a').in().as('b').where(__.not(__.as('a').out().as('b')))+` [[gremlin-python]] == Gremlin-Python image:gremlin-python-drawing.png[width=130,float=right] Apache TinkerPop's Gremlin-Python implements Gremlin within the link:https://www.python.org/[Python] language and can be used on any Python virtual machine including the popular link:https://en.wikipedia.org/wiki/CPython[CPython] machine. Python's syntax has the same constructs as Java including ""dot notation"" for function chaining (`a.b.c`), round bracket function arguments (`a(b,c)`), and support for global namespaces (`a(b())` vs `a(__.b())`). As such, anyone familiar with Gremlin-Java will immediately be able to work with Gremlin-Python. Moreover, there are a few added constructs to Gremlin-Python that make traversals a bit more succinct. To install Gremlin-Python, use Python's link:https://en.wikipedia.org/wiki/Pip_(package_manager)[pip] package manager. [source,bash] ---- pip install gremlinpython ---- === Connecting The pattern for connecting is described in <> and it basically distills down to creating a `GraphTraversalSource`. A `GraphTraversalSource` is created from the anonymous `traversal()` method where the ""g"" provided to the `DriverRemoteConnection` corresponds to the name of a `GraphTraversalSource` on the remote end. [source,python] ---- g = traversal().withRemote(DriverRemoteConnection('ws://localhost:8182/gremlin','g')) ---- If you need to send additional headers in the websockets connection, you can pass an optional `headers` parameter to the `DriverRemoteConnection` constructor. [source,python] ---- g = traversal().withRemote(DriverRemoteConnection('ws://localhost:8182/gremlin','g',headers={'Header':'Value'})) ---- NOTE: If connecting from an inherently single-threaded Python process where blocking while waiting for Gremlin traversals to complete is acceptable, it might be helpful to set `pool_size` and `max_workers` parameters to 1. See the <> section just below. Examples where this could apply are serverless cloud functions or WSGI worker processes. [[python-imports]] === Common Imports There are a number of classes, functions and tokens that are typically used with Gremlin. The following imports provide most of the typical functionality required to use Gremlin: [source,python] ---- from gremlin_python import statics from gremlin_python.process.anonymous_traversal import traversal from gremlin_python.process.graph_traversal import __ from gremlin_python.process.strategies import * from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection from gremlin_python.process.traversal import T from gremlin_python.process.traversal import Order from gremlin_python.process.traversal import Cardinality from gremlin_python.process.traversal import Column from gremlin_python.process.traversal import Direction from gremlin_python.process.traversal import Operator from gremlin_python.process.traversal import P from gremlin_python.process.traversal import Pop from gremlin_python.process.traversal import Scope from gremlin_python.process.traversal import Barrier from gremlin_python.process.traversal import Bindings from gremlin_python.process.traversal import WithOptions ---- These can be used analogously to how they are used in Gremlin-Java. [source,python] ---- >>> g.V().hasLabel('person').has('age',P.gt(30)).order().by('age',Order.desc).toList() [v[6], v[4]] ---- Moreover, by importing the `statics` of Gremlin-Python, the class prefixes can be omitted. [source,python] ---- >>> statics.load_statics(globals()) ---- With statics loaded its possible to represent the above traversal as below. [source,python] ---- >>> g.V().hasLabel('person').has('age',gt(30)).order().by('age',desc).toList() [v[6], v[4]] ---- Finally, statics includes all the `+__+`-methods and thus, anonymous traversals like `+__.out()+` can be expressed as below. That is, without the `+__+`-prefix. [source,python] ---- >>> g.V().repeat(out()).times(2).name.fold().toList() [['ripple', 'lop']] ---- [[python-configuration]] === Configuration The following table describes the various configuration options for the Gremlin-Python Driver. They can be passed to the `Client` or `DriverRemoteConnection` instance as keyword arguments: [width=""100%"",cols=""3,10,^2"",options=""header""] |========================================================= |Key |Description |Default |protocol_factory |A callable that returns an instance of `AbstractBaseProtocol`. |`gremlin_python.driver.protocol.GremlinServerWSProtocol` |transport_factory |A callable that returns an instance of `AbstractBaseTransport`. |`gremlin_python.driver.tornado.transport.TornadoTransport` |pool_size |The number of connections used by the pool. |4 |max_workers |Maximum number of worker threads. |Number of CPUs * 5 |message_serializer |The message serializer implementation.|`gremlin_python.driver.serializer.GraphSONMessageSerializer` |password |The password to submit on requests that require authentication. |"""" |username |The username to submit on requests that require authentication. |"""" |session | A unique string-based identifier (typically a UUID) to enable a <>. This is not a valid configuration for `DriverRemoteConnection`. |None |========================================================= === Traversal Strategies In order to add and remove <> from a traversal source, Gremlin-Python has a `TraversalStrategy` class along with a collection of subclasses that mirror the standard Gremlin-Java strategies. [source,python] ---- >>> g = g.withStrategies(SubgraphStrategy(vertices=hasLabel('person'),edges=has('weight',gt(0.5)))) >>> g.V().name.toList() ['marko', 'vadas', 'josh', 'peter'] >>> g.V().outE().elementMap().toList() [{: 8, : 'knows', : {: 4, : 'person'}, : {: 1, : 'person'}, 'weight': 1.0}] >>> g = g.withoutStrategies(SubgraphStrategy) >>> g.V().name.toList() ['marko', 'vadas', 'lop', 'josh', 'ripple', 'peter'] >>> g.V().outE().elementMap().toList() [{: 9, : 'created', : {: 3, : 'software'}, : {: 1, : 'person'}, 'weight': 0.4}, {: 7, : 'knows', : {: 2, : 'person'}, : {: 1, : 'person'}, 'weight': 0.5}, {: 8, : 'knows', : {: 4, : 'person'}, : {: 1, : 'person'}, 'weight': 1.0}, {: 10, : 'created', : {: 5, : 'software'}, : {: 4, : 'person'}, 'weight': 1.0}, {: 11, : 'created', : {: 3, : 'software'}, : {: 4, : 'person'}, 'weight': 0.4}, {: 12, : 'created', : {: 3, : 'software'}, : {: 6, : 'person'}, 'weight': 0.2}] >>> g = g.withComputer(workers=2,vertices=has('name','marko')) >>> g.V().name.toList() ['marko'] >>> g.V().outE().valueMap().with_(WithOptions.tokens).toList() [{: 9, : 'created', 'weight': 0.4}, {: 7, : 'knows', 'weight': 0.5}, {: 8, : 'knows', 'weight': 1.0}] ---- NOTE: Many of the `TraversalStrategy` classes in Gremlin-Python are proxies to the respective strategy on Apache TinkerPop's JVM-based Gremlin traversal machine. As such, their `apply(Traversal)` method does nothing. However, the strategy is encoded in the Gremlin-Python bytecode and transmitted to the Gremlin traversal machine for re-construction machine-side. === The Lambda Solution Supporting link:https://en.wikipedia.org/wiki/Anonymous_function[anonymous functions] across languages is difficult as most languages do not support lambda introspection and thus, code analysis. In Gremlin-Python, a link:https://docs.python.org/2/reference/expressions.html#lambda[Python lambda] should be represented as a zero-arg callable that returns a string representation of a lambda. The lambda should be written as a `Gremlin-Groovy`string. When the lambda is represented in `Bytecode` its language is encoded such that the remote connection host can infer which translator and ultimate execution engine to use. [source,python] ---- >>> g.V().out().map(lambda: ""it.get().value('name').length()"").sum().toList() [24] ---- TIP: When running into situations where Groovy cannot properly discern a method signature based on the `Lambda` instance created, it will help to fully define the closure in the lambda expression - so rather than `lambda: (""it.get().value(""name')"",""gremlin-groovy"")`, prefer `lambda: (""x -> x.get().value(""name""),""gremlin-groovy"")`. Finally, Gremlin `Bytecode` that includes lambdas requires that the traversal be processed by the `ScriptEngine`. To avoid continued recompilation costs, it supports the encoding of bindings, which allow a remote engine to to cache traversals that will be reused over and over again save that some parameterization may change. Thus, instead of translating, compiling, and then executing each submitted bytecode, it is possible to simply execute. [source,python] ---- >>> g.V(Bindings.of('x',1)).out('created').map(lambda: ""it.get().value('name').length()"").sum().toList() [3] >>> g.V(Bindings.of('x',4)).out('created').map(lambda: ""it.get().value('name').length()"").sum().toList() [9] ---- WARNING: As explained throughout the documentation, when possible <> lambdas. === Submitting Scripts WARNING: TinkerPop does not recommend submitting script-based requests and generally continues to support this feature for legacy reasons and corner use cases which are still not completely addressed by the Gremlin language. Please consider using bytecode-based requests instead when possible. The `Client` class implementation/interface is based on the Java Driver, with some restrictions. Most notably, Gremlin-Python does not yet implement the `Cluster` class. Instead, `Client` is instantiated directly. Usage is as follows: [source,python] ---- from gremlin_python.driver import client <1> client = client.Client('ws://localhost:8182/gremlin', 'g') <2> ---- <1> Import the Gremlin-Python `client` module. <2> Opens a reference to `localhost` - note that there are various configuration options that can be passed to the `Client` object upon instantiation as keyword arguments. Once a `Client` instance is ready, it is possible to issue some Gremlin: [source,python] ---- result_set = client.submit(""[1,2,3,4]"") <1> future_results = result_set.all() <2> results = future_results.result() <3> assert results == [1, 2, 3, 4] <4> future_result_set = client.submitAsync(""[1,2,3,4]"") <5> result_set = future_result_set.result() <6> result = result_set.one() <7> assert results == [1, 2, 3, 4] <8> assert result_set.done.done() <9> client.close() <10> ---- <1> Submit a script that simply returns a `List` of integers. This method blocks until the request is written to the server and a `ResultSet` is constructed. <2> Even though the `ResultSet` is constructed, it does not mean that the server has sent back the results (or even evaluated the script potentially). The `ResultSet` is just a holder that is awaiting the results from the server. The `all` method returns a `concurrent.futures.Future` that resolves to a list when it is complete. <3> Block until the the script is evaluated and results are sent back by the server. <4> Verify the result. <5> Submit the same script to the server but don't block. <6> Wait until request is written to the server and `ResultSet` is constructed. <7> Read a single result off the result stream. <8> Again, verify the result. <9> Verify that the all results have been read and stream is closed. <10> Close client and underlying pool connections. [[gremlin-python-dsl]] === Domain Specific Languages Writing a Gremlin <> (DSL) in Python simply requires direct extension of several classes: * `GraphTraversal` - which exposes the various steps used in traversal writing * `__` - which spawns anonymous traversals from steps * `GraphTraversalSource` - which spawns `GraphTraversal` instances The Social DSL based on the link:https://tinkerpop.apache.org/docs/current/images/tinkerpop-modern.png[""modern"" toy graph] might look like this: [source,python] ---- class SocialTraversal(GraphTraversal): def knows(self, person_name): return self.out(""knows"").hasLabel(""person"").has(""name"", person_name) def youngestFriendsAge(self): return self.out(""knows"").hasLabel(""person"").values(""age"").min() def createdAtLeast(self, number): return self.outE(""created"").count().is_(P.gte(number)) class __(AnonymousTraversal): graph_traversal = SocialTraversal @classmethod def knows(cls, *args): return cls.graph_traversal(None, None, Bytecode()).knows(*args) @classmethod def youngestFriendsAge(cls, *args): return cls.graph_traversal(None, None, Bytecode()).youngestFriendsAge(*args) @classmethod def createdAtLeast(cls, *args): return cls.graph_traversal(None, None, Bytecode()).createdAtLeast(*args) class SocialTraversalSource(GraphTraversalSource): def __init__(self, *args, **kwargs): super(SocialTraversalSource, self).__init__(*args, **kwargs) self.graph_traversal = SocialTraversal def persons(self, *args): traversal = self.get_graph_traversal() traversal.bytecode.add_step(""V"") traversal.bytecode.add_step(""hasLabel"", ""person"") if len(args) > 0: traversal.bytecode.add_step(""has"", ""name"", P.within(args)) return traversal ---- NOTE: The `AnonymousTraversal` class above is just an alias for `+__+` as in `+from gremlin_python.process.graph_traversal import __ as AnonymousTraversal+` Using the DSL is straightforward and just requires that the graph instance know the `SocialTraversalSource` should be used: [source,python] ---- social = Graph().traversal(SocialTraversalSource).withRemote(DriverRemoteConnection('ws://localhost:8182/gremlin','g')) social.persons(""marko"").knows(""josh"") social.persons(""marko"").youngestFriendsAge() social.persons().filter(__.createdAtLeast(2)).count() ---- === Syntactic Sugar Python supports meta-programming and operator overloading. There are three uses of these techniques in Gremlin-Python that makes traversals a bit more concise. [source,python] ---- >>> g.V().both()[1:3].toList() [v[2], v[4]] >>> g.V().both()[1].toList() [v[2]] >>> g.V().both().name.toList() ['lop', 'lop', 'lop', 'vadas', 'josh', 'josh', 'josh', 'marko', 'marko', 'marko', 'peter', 'ripple'] ---- [[gremlin-python-differences]] === Differences In situations where Python reserved words and global functions overlap with standard Gremlin steps and tokens, those bits of conflicting Gremlin get an underscore appended as a suffix: *Steps* - <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <> *Tokens* - <> === Limitations * Traversals that return a `Set` *might* be coerced to a `List` in Python. In the case of Python, number equality is different from JVM languages which produces different `Set` results when those types are in use. When this case is detected during deserialization, the `Set` is coerced to a `List` so that traversals return consistent results within a collection across different languages. If a `Set` is needed then convert `List` results to `Set` manually. * Gremlin is capable of returning `Dictionary` results that use non-hashable keys (e.g. Dictionary as a key) and Python does not support that at a language level. Using GraphSON 3.0 or GraphBinary (after 3.5.0) makes it possible to return such results. In all other cases, Gremlin that returns such results will need to be re-written to avoid that sort of key. === Application Examples The TinkerPop source code contains a simple Python script that shows a basic example of how gremlinpython works. It can be found in GitHub link:https://github.com/apache/tinkerpop/tree/xx.yy.zz/gremlin-python/src/main/python/example.py[here] and is designed to work best with a running <> configured with the default `conf/gremlin-server.yaml` file as included with the standard release packaging. [source,shell] ---- pip install gremlinpython pip install tornado python example.py ---- anchor:gremlin-DotNet[] [[gremlin-dotnet]] == Gremlin.Net image:gremlin-dotnet-logo.png[width=371,float=right] Apache TinkerPop's Gremlin.Net implements Gremlin within the C# language. It targets .NET Standard and can therefore be used on different operating systems and with different .NET frameworks, such as .NET Framework and link:https://www.microsoft.com/net/core[.NET Core]. Since the C# syntax is very similar to that of Java, it should be very easy to switch between Gremlin-Java and Gremlin.Net. The only major syntactical difference is that all method names in Gremlin.Net use PascalCase as opposed to camelCase in Gremlin-Java in order to comply with .NET conventions. [source,powershell] nuget install Gremlin.Net === Connecting The pattern for connecting is described in <> and it basically distills down to creating a `GraphTraversalSource`. A `GraphTraversalSource` is created from the `AnonymousTraversalSource.traversal()` method where the ""g"" provided to the `DriverRemoteConnection` corresponds to the name of a `GraphTraversalSource` on the remote end. [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=connecting] ---- === Common Imports There are a number of classes, functions and tokens that are typically used with Gremlin. The following imports provide most of the typical functionality required to use Gremlin: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=commonImports] ---- === Configuration The connection properties for the Gremlin.Net driver can be passed to the `GremlinServer` instance as keyword arguments: [width=""100%"",cols=""3,10,^2"",options=""header""] |========================================================= |Key |Description |Default |hostname |The hostname that the driver will connect to. |localhost |port |The port on which Gremlin Server can be reached. |8182 |enableSsl |Determines if SSL should be enabled or not. If enabled on the server then it must be enabled on the client. |false |username |The username to submit on requests that require authentication. |_none_ |password |The password to submit on requests that require authentication. |_none_ |========================================================= ==== Connection Pool It is also possible to configure the `ConnectionPool` of the Gremlin.Net driver. These configuration options can be set as properties on the `ConnectionPoolSettings` instance that can be passed to the `GremlinClient`: [width=""100%"",cols=""3,10,^2"",options=""header""] |========================================================= |Key |Description |Default |PoolSize |The size of the connection pool. |4 |MaxInProcessPerConnection |The maximum number of in-flight requests that can occur on a connection. |32 |ReconnectionAttempts |The number of attempts to get an open connection from the pool to submit a request. |4 |ReconnectionBaseDelay |The base delay used for the exponential backoff for the reconnection attempts. |1 s |========================================================= A `NoConnectionAvailableException` is thrown if all connections have reached the `MaxInProcessPerConnection` limit when a new request comes in. A `ServerUnavailableException` is thrown if no connection is available to the server to submit a request after `ReconnectionAttempts` retries. ==== Serialization The Gremlin.Net driver uses by default GraphSON 3.0 but it is also possible to use GraphSON 2.0 which can be necessary when the server does not support GraphSON 3.0 yet: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=serialization] ---- === Traversal Strategies In order to add and remove traversal strategies from a traversal source, Gremlin.Net has an `AbstractTraversalStrategy` class along with a collection of subclasses that mirror the standard Gremlin-Java strategies. [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=traversalStrategies] ---- NOTE: Many of the TraversalStrategy classes in Gremlin.Net are proxies to the respective strategy on Apache TinkerPop’s JVM-based Gremlin traversal machine. As such, their `Apply(ITraversal)` method does nothing. However, the strategy is encoded in the Gremlin.Net bytecode and transmitted to the Gremlin traversal machine for re-construction machine-side. === The Lambda Solution Supporting link:https://en.wikipedia.org/wiki/Anonymous_function[anonymous functions] across languages is difficult as most languages do not support lambda introspection and thus, code analysis. While Gremlin.Net doesn't support C# lambdas, it is still able to represent lambdas in other languages. When the lambda is represented in `Bytecode` its language is encoded such that the remote connection host can infer which translator and ultimate execution engine to use. [source,csharp] ---- g.V().Out().Map(Lambda.Groovy(""it.get().value('name').length()"")).Sum().ToList(); <1> g.V().Out().Map(Lambda.Python(""lambda x: len(x.get().value('name'))"")).Sum().ToList(); <2> ---- <1> `Lambda.Groovy()` can be used to create a Groovy lambda. <2> `Lambda.Python()` can be used to create a Python lambda. The `ILambda` interface returned by these two methods inherits interfaces like `IFunction` and `IPredicate` that mirror their Java counterparts which makes it possible to use lambdas with Gremlin.Net for the same steps as in Gremlin-Java. TIP: When running into situations where Groovy cannot properly discern a method signature based on the `Lambda` instance created, it will help to fully define the closure in the lambda expression - so rather than `Lambda.Groovy(""it.get().value('name'))`, prefer `Lambda.Groovy(""x -> x.get().value('name'))`. === Submitting Scripts WARNING: TinkerPop does not recommend submitting script-based requests and generally continues to support this feature for legacy reasons and corner use cases which are still not completely addressed by the Gremlin language. Please consider using bytecode-based requests instead when possible. Gremlin scripts are sent to the server from a `IGremlinClient` instance. A `IGremlinClient` is created as follows: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=submittingScripts] ---- If the remote system has authentication and SSL enabled, then the `GremlinServer` object can be configured as follows: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=submittingScriptsWithAuthentication] ---- It is also possible to initialize the `Client` to use <>: [source,csharp] ---- var gremlinServer = new GremlinServer(""localhost"", 8182); var client = new GremlinClient(gremlinServer, sessionId: Guid.NewGuid().ToString())) ---- [[gremlin-net-dsl]] === Domain Specific Languages Developing a <> (DSL) for .Net is most easily implemented using link:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods[Extension Methods] as they don't require direct extension of classes in the TinkerPop hierarchy. Extension Method classes simply need to be constructed for the `GraphTraversal` and the `GraphTraversalSource`. Unfortunately, anonymous traversals (spawned from `+__+`) can't use the Extension Method approach as they do not work for static classes and static classes can't be extended. The only option is to re-implement the methods of `+__+` as a wrapper in the anonymous traversal for the DSL or to simply create a static class for the DSL and use the two anonymous traversals creators independently. The following example uses the latter approach as it saves a lot of boilerplate code with the minor annoyance of having a second static class to deal with when writing traversals rather than just calling `+__+` for everything. [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsDsl.cs[tags=dsl] ---- Note the creation of `__Social` as the Social DSL's ""extension"" to the available ways in which to spawn anonymous traversals. The use of the double underscore prefix in the name is just a convention to consider using and is not a requirement. To use the DSL, bring it into scope with the `using` directive: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsDslTests.cs[tags=dslUsing] ---- and then it can be called from the application as follows: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsDslTests.cs[tags=dslExamples] ---- [[gremlin-dotnet-differences]] === Differences Gremlin allows for `Map` instances to include `null` keys, but `null` keys in C# `Dictionary` instances are not allowed. It is therefore necessary to rewrite a traversal such as: [source,javascript] ---- g.V().groupCount().by('age') ---- where ""age"" is not a valid key for all vertices in a way that will remove the need for a `null` to be returned. [source,javascript] ---- g.V().has('age').groupCount().by('age') g.V().hasLabel('person').groupCount().by('age') ---- Either of the above two options accomplishes the desired goal as both prevent `groupCount()` from having to process the possibility of `null`. anchor:gremlin-dotnet-template[] [[dotnet-application-examples]] === Application Examples This link:https://docs.microsoft.com/dotnet/core/tools/custom-templates[dotnet template] helps getting started with <>. It creates a new C# console project that shows how to connect to a <> with Gremlin.Net. You can install the template with the dotnet CLI tool: [source,shell] dotnet new -i Gremlin.Net.Template After the template is installed, a new project based on this template can be installed: [source,shell] dotnet new gremlin Specify the output directory for the new project which will then also be used as the name of the created project: [source,shell] dotnet new gremlin -o MyFirstGremlinProject [[gremlin-javascript]] == Gremlin-JavaScript image:gremlin-js.png[width=130,float=right] Apache TinkerPop's Gremlin-JavaScript implements Gremlin within the JavaScript language. It targets Node.js runtime and can be used on different operating systems on any Node.js 6 or above. Since the JavaScript naming conventions are very similar to that of Java, it should be very easy to switch between Gremlin-Java and Gremlin-JavaScript. [source,bash] npm install gremlin === Connecting The pattern for connecting is described in <> and it basically distills down to creating a `GraphTraversalSource`. A `GraphTraversalSource` is created from the `AnonymousTraversalSource.traversal()` method where the ""g"" provided to the `DriverRemoteConnection` corresponds to the name of a `GraphTraversalSource` on the remote end. [source,javascript] ---- const g = traversal().withRemote(new DriverRemoteConnection('ws://localhost:8182/gremlin')); ---- Gremlin-JavaScript supports plain text SASL authentication, you can set it on the connection options. [source,javascript] ---- const authenticator = new gremlin.driver.auth.PlainTextSaslAuthenticator('myuser', 'mypassword'); const g = traversal().withRemote(new DriverRemoteConnection('ws://localhost:8182/gremlin', { authenticator }); ---- Given that I/O operations in Node.js are asynchronous by default, <> return a `Promise`: * `Traversal.toList()`: Returns a `Promise` with an `Array` as result value. * `Traversal.next()`: Returns a `Promise` with a `{ value, done }` tuple as result value, according to the link:https://github.com/tc39/proposal-async-iteration[async iterator proposal]. * `Traversal.iterate()`: Returns a `Promise` without a value. For example: [source,javascript] ---- g.V().hasLabel('person').values('name').toList() .then(names => console.log(names)); ---- When using `async` functions it is possible to `await` the promises: [source,javascript] ---- const names = await g.V().hasLabel('person').values('name').toList(); console.log(names); ---- === Common Imports There are a number of classes, functions and tokens that are typically used with Gremlin. The following imports provide most of the typical functionality required to use Gremlin: [source,javascript] ---- const gremlin = require('gremlin'); const traversal = gremlin.process.AnonymousTraversalSource.traversal; const __ = gremlin.process.statics; const DriverRemoteConnection = gremlin.driver.DriverRemoteConnection; const column = gremlin.process.column const direction = gremlin.process.direction const p = gremlin.process.P const textp = gremlin.process.TextP const pick = gremlin.process.pick const pop = gremlin.process.pop const order = gremlin.process.order const scope = gremlin.process.scope const t = gremlin.process.t ---- === Submitting Scripts WARNING: TinkerPop does not recommend submitting script-based requests and generally continues to support this feature for legacy reasons and corner use cases which are still not completely addressed by the Gremlin language. Please consider using bytecode-based requests instead when possible. It is possible to submit parametrized Gremlin scripts to the server as strings, using the `Client` class: [source,javascript] ---- const gremlin = require('gremlin'); const client = new gremlin.driver.Client('ws://localhost:8182/gremlin', { traversalSource: 'g' }); const result1 = await client.submit('g.V(vid)', { vid: 1 }); const vertex = result1.first(); const result2 = await client.submit('g.V().hasLabel(label).tail(n)', { label: 'person', n: 3 }); // ResultSet is an iterable for (const vertex of result2) { console.log(vertex.id); } ---- It is also possible to initialize the `Client` to use <>: [source,javascript] ---- const client = new gremlin.driver.Client('ws://localhost:8182/gremlin', { traversalSource: 'g', 'session': 'unique-string-id' }); ---- With this configuration, the state of variables within scripts are preserved between requests. ==== Per Request Settings Some settings can be established per request, like an override of the `scriptEvaluationTimeout` which can be helpful when it is known that particular request might need to execute longer than what the server might allow with its settings: [source,javascript] ---- const result = await client.submit('g.V().repeat(both()).times(100)', null, {""scriptEvaluationTimeout"": 60000}); ---- [[gremlin-javascript-dsl]] === Domain Specific Languages Developing Gremlin DSLs in JavaScript largely requires extension of existing core classes with use of standalone functions for anonymous traversal spawning. The pattern is demonstrated in the following example: [source,javascript] ---- class SocialTraversal extends GraphTraversal { constructor(graph, traversalStrategies, bytecode) { super(graph, traversalStrategies, bytecode); } aged(age) { return this.has('person', 'age', age); } } class SocialTraversalSource extends GraphTraversalSource { constructor(graph, traversalStrategies, bytecode) { super(graph, traversalStrategies, bytecode, SocialTraversalSource, SocialTraversal); } person(name) { return this.V().has('person', 'name', name); } } function anonymous() { return new SocialTraversal(null, null, new Bytecode()); } function aged(age) { return anonymous().aged(age); } ---- `SocialTraversal` extends the core `GraphTraversal` class and has a three argument constructor which is immediately proxied to the `GraphTraversal` constructor. New DSL steps are then added to this class using available steps to construct the underlying traversal to execute as demonstrated in the `aged()` step. The `SocialTraversal` is spawned from a `SocialTraversalSource` which is extended from `GraphTraversalSource`. Steps added here are meant to be start steps. In the above case, the `person()` start step find a ""person"" vertex to begin the traversal from. Typically, steps that are made available on a `GraphTraversal` (i.e. SocialTraversal in this example) should also be made available as spawns for anonymous traversals. The recommendation is that these steps be exposed in the module as standalone functions. In the example above, the standalone `aged()` step creates an anonymous traversal through an `anonymous()` utility function. The method for creating these standalone functions can be handled in other ways if desired. To use the DSL, simply initialize the `g` as follows: [source,javascript] ---- const g = traversal(SocialTraversalSource).withRemote(connection); g.person('marko').aged(29).values('name').toList(). then(names => console.log(names)); ---- [[gremlin-javascript-differences]] === Differences In situations where Javascript reserved words and global functions overlap with standard Gremlin steps and tokens, those bits of conflicting Gremlin get an underscore appended as a suffix: *Steps* - <>, <>, <> Gremlin allows for `Map` instances to include `null` keys, but `null` keys in Javascript have some interesting behavior as in: [source,text] ---- > var a = { null: 'something', 'b': 'else' }; > JSON.stringify(a) '{""null"":""something"",""b"":""else""}' > JSON.parse(JSON.stringify(a)) { null: 'something', b: 'else' } > a[null] 'something' > a['null'] 'something' ---- This behavior needs to be considered when using Gremlin to return such results. A typical situation where this might happen is with `group()` or `groupCount()` as in: [source,javascript] ---- g.V().groupCount().by('age') ---- where ""age"" is not a valid key for all vertices. In these cases, it will return `null` for that key and group on that. It may bet better in Javascript to filter away those vertices to avoid the return of `null` in the returned `Map`: [source,javascript] ---- g.V().has('age').groupCount().by('age') g.V().hasLabel('person').groupCount().by('age') ---- Either of the above two options accomplishes the desired goal as both prevent `groupCount()` from having to process the possibility of `null`.",16276,True,2776.83286263864,median "------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- 17 package Asis.Expressions ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- package Asis.Expressions is -- pragma Preelaborate; ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- Asis.Expressions encapsulates a set of queries that operate on -- An_Expression and An_Association elements. ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- 17.1 function Corresponding_Expression_Type ------------------------------------------------------------------------------- function Corresponding_Expression_Type (Expression : in Asis.Expression) return Asis.Declaration; ------------------------------------------------------------------------------- -- Expression - Specifies the expression to query -- -- Returns the type declaration for the type or subtype of the expression. -- This query does not ""unwind"" subtypes or derived types to get to the -- Corresponding_First_Subtype or Corresponding_Parent_Subtype declarations. -- For example, for the following program text: -- -- type Int is range -5_000 .. 5_000; -- type My_Int is new Int; -- type Good_Int is new My_Int; -- Var: Good_Int; -- -- The type declaration for Good_Int should be returned. The ""unwinding"" -- should not occur. The type declaration for either My_Int or Int should -- not be returned. -- -- Returns a Nil_Element if the argument Expression does not represent an Ada -- expression having an Ada type, including the following classes: -- -- - Naming expressions that name packages, subprograms, tasks, etc. These -- expressions do have a Corresponding_Name_Definition and a -- Corresponding_Name_Declaration. Although task objects do have -- a type, this query is limited, on purpose. Thus, when a naming -- expression is given to this query (for packages, subprograms, -- tasks, etc.), this query will return Nil_Element. As the -- Application Note below indicates, if any further information -- is needed, the element should be queried by -- Corresponding_Name_Definition or Corresponding_Name_Declaration, -- which should eventually return an A_Task_Type_Declaration element. -- -- - When An_Identifier Element representing an attribute designator is -- passed as the actual to this query. -- -- - The Actual_Parameter Expression from A_Pragma_Argument_Association for -- a Pragma may or may not have a Corresponding_Expression_Type. -- -- - An_Attribute_Reference Element also may or may not have a -- Corresponding_Expression_Type; -- -- - An enumeration_aggregate which is a part of -- enumeration_representation_clause. -- -- - A_Box_Expression returned by Component_Expression applied to an -- unnormalized record association. -- -- AASIS Note: This is necessary as the <> of an unnnormalized record -- association may represent several components of different types. If the -- record association is normalized, it has a single component and the type -- of A_Box_Expression is that of the component. Similarly, the type of -- A_Box_Expression for an array association is that of the component type. -- -- Returns a Nil_Element, if the statically determinable type of Expression -- is a class-wide type, or the Expression corresponds to an inner -- sub-aggregate in multi-dimensional array aggregates. -- -- |AN Application Note: -- |AN -- |AN If the returned declaration is Nil, an application should make its own -- |AN analysis based on Corresponding_Name_Definition or -- |AN Corresponding_Name_Declaration to get more information about the -- |AN argument, including the static type resolution for class-wide -- |AN expressions, if needed. Use Enclosing_Element to determine if -- |AN Expression is from pragma argument association. If for such an -- |AN expression, Corresponding_Name_Definition raises ASIS_Failed (with a -- |AN Status of Value_Error), this An_Expression element does not represent -- |AN a normal Ada expression at all and does not follow normal Ada semantic -- |AN rules. -- |AN For example, ""pragma Private_Part (Open => Yes);"", the ""Yes"" expression -- |AN may simply be a ""keyword"" that is specially recognized by the -- |AN implementor's compilation system and may not refer to any -- |AN declared object. -- -- Appropriate Element_Kinds: -- An_Expression -- -- Returns Element_Kinds: -- Not_An_Element -- A_Declaration -- -- |ER An_Integer_Literal - 2.4 - No child elements -- |ER A_Real_Literal - 2.4 - No child elements -- |ER A_String_Literal - 2.6 - No child elements -- |ER -- |ER A string image returned by: -- |ER function Value_Image -- ------------------------------------------------------------------------------- -- 17.2 function Value_Image ------------------------------------------------------------------------------- function Value_Image (Expression : in Asis.Expression) return Wide_String; ------------------------------------------------------------------------------- -- Expression - Specifies the expression to query -- -- Returns the string image of the value of the string, integer, or real -- literal. -- -- For string literals, Value will return the quotes around the string -- literal, these quotes are doubled, just as any quote appearing embedded in -- the string literal in the program text. -- -- The form of numbers returned by this query may vary between implementors. -- Implementors are encouraged, but not required, to return numeric literals -- using the same based or exponent form used in the original compilation -- text. -- -- Appropriate Expression_Kinds: -- An_Integer_Literal -- A_Real_Literal -- A_String_Literal -- ------------------------------------------------------------------------------- -- |ER An_Identifier - 4.1 - No child elements -- |ER An_Operator_Symbol - 4.1 - No child elements -- |ER A_Character_Literal - 4.1 - No child elements -- |ER An_Enumeration_Literal - 4.1 - No child elements -- |ER -- |ER A string image returned by: -- |ER function Name_Image -- |ER -- |ER Semantic elements returned by: -- |ER function Corresponding_Name_Definition -- |ER function Corresponding_Name_Definition_List -- |ER function Corresponding_Name_Declaration -- ------------------------------------------------------------------------------- -- 17.3 function Name_Image ------------------------------------------------------------------------------- function Name_Image (Expression : in Asis.Expression) return Program_Text; ------------------------------------------------------------------------------- -- Name - Specifies the name to query -- -- Returns the program text image of the name. -- -- An_Operator_Symbol elements have names with embedded quotes """"""abs"""""" -- (function ""abs""). -- -- A_Character_Literal elements have names with embedded apostrophes ""'x'"" -- (literal 'x'). -- -- An_Enumeration_Literal and An_Identifier elements have identifier names -- ""Blue"" (literal Blue) ""Abc"" (identifier Abc). -- -- Note: Implicit subtypes that can be encountered while traversing the -- semantic information embedded in implicit inherited subprogram declarations -- (Reference Manual 3.4 (17-22)) could have names that are unique in a -- particular scope. This is because these subtypes are Is_Part_Of_Implicit -- declarations that do not form part of the physical text of the original -- compilation units. Some applications may wish to carefully separate the -- names of declarations from the names of Is_Part_Of_Implicit declaration -- when creating symbol tables and other name-specific lookup mechanisms. -- -- The case of names returned by this query may vary between implementors. -- Implementors are encouraged, but not required, to return names in the -- same case as was used in the original compilation text. -- -- Appropriate Expression_Kinds: -- An_Identifier -- An_Operator_Symbol -- A_Character_Literal -- An_Enumeration_Literal -- ------------------------------------------------------------------------------- -- 17.4 function References ------------------------------------------------------------------------------- function References (Name : in Asis.Element; Within_Element : in Asis.Element; Implicitly : in Boolean := False) return Asis.Name_List; ------------------------------------------------------------------------------- -- Name - Specifies the entity to query -- Within_Element - Specifies the limits for the query which is limited -- to the Element and its children. -- -- If the Implicitly argument is True: -- Returns all usage references of the given entity made by both explicit -- and implicit elements within the given limits. -- -- If the Implicitly argument is False: -- Returns all usage references of the given entity made only by explicit -- elements within the given limits. -- -- Returned references are in their order of appearance. -- -- Appropriate Element_Kinds: -- A_Defining_Name -- Returns Element_Kinds: -- An_Expression -- -- May raise ASIS_Failed with a Status of Obsolete_Reference_Error if the -- argument is part of an inconsistent compilation unit. -- ------------------------------------------------------------------------------- -- 17.5 function Is_Referenced ------------------------------------------------------------------------------- function Is_Referenced (Name : in Asis.Element; Within_Element : in Asis.Element; Implicitly : in Boolean := False) return Boolean; ------------------------------------------------------------------------------- -- Name - Specifies the entity to query -- Within_Element - Specifies the limits for the query which is limited -- to the Element and its children. -- -- If the Implicitly argument is True: -- Returns True if the Name is referenced by either implicit or explicit -- elements within the given limits. -- -- If the Implicitly argument is False: -- Returns True only if the Name is referenced by explicit elements. -- -- Returns False for any unexpected Element. -- -- Expected Element_Kinds: -- A_Defining_Name -- -- May raise ASIS_Failed with a Status of Obsolete_Reference_Error if the -- argument is part of an inconsistent compilation unit. -- ------------------------------------------------------------------------------- -- 17.6 function Corresponding_Name_Definition ------------------------------------------------------------------------------- function Corresponding_Name_Definition (Reference : in Asis.Expression) return Asis.Defining_Name; ------------------------------------------------------------------------------- -- Reference - Specifies an expression to query -- -- Returns the defining_identifier, defining_character_literal, -- defining_operator_symbol, or defining_program_unit_name from the -- declaration of the referenced entity. -- -- - Record component references return the defining name of the -- record discriminant or component_declaration. For references to inherited -- declarations of derived types, the Corresponding_Name_Definition returns -- the defining name of the implicit inherited declaration. -- -- - References to implicit operators and inherited subprograms will return -- an Is_Part_Of_Implicit defining name for the operation. The -- Enclosing_Element of the name is an implicit declaration for the -- operation. The Enclosing_Element of the declaration is the associated -- derived_type_definition. -- -- - References to formal parameters given in calls to inherited subprograms -- will return an Is_Part_Of_Implicit defining name for the -- Parameter_Specification from the inherited subprogram specification. -- -- - References to visible components of instantiated generic packages will -- return a name from the expanded generic specification instance. -- -- - References, within expanded generic instances, that refer to other -- components of the same, or an enclosing, expanded generic instance, -- return a name from the appropriate expanded specification or body -- instance. -- -- In case of renaming, the function returns the new name for the entity. -- -- Returns a Nil_Element if the reference is to an implicitly declared -- element for which the implementation does not provide declarations and -- defining name elements. -- -- Returns a Nil_Element if the argument is a dispatching call. -- -- The Enclosing_Element of a non-Nil result is either a Declaration or a -- Statement. -- -- Appropriate Expression_Kinds: -- An_Identifier -- An_Operator_Symbol -- A_Character_Literal -- An_Enumeration_Literal -- -- Returns Element_Kinds: -- Not_An_Element -- A_Defining_Name -- -- |IP Implementation Permissions: -- |IP -- |IP An implementation may choose to return any part of multi-part -- |IP declarations and definitions. Multi-part declaration/definitions -- |IP can occur for: -- |IP -- |IP - Subprogram specification in package specification, package body, -- |IP and subunits (is separate); -- |IP -- |IP - Entries in package specification, package body, and subunits (is -- |IP separate); -- |IP -- |IP - Private type and full type declarations; -- |IP -- |IP - Incomplete type and full type declarations; and -- |IP -- |IP - Deferred constant and full constant declarations. -- |IP -- |IP No guarantee is made that the element will be the first part or -- |IP that the determination will be made due to any visibility rules. -- |IP An application should make its own analysis for each case based -- |IP on which part is returned. -- |IP -- |IP Some implementations do not represent all forms of implicit -- |IP declarations such that elements representing them can be easily -- |IP provided. An implementation can choose whether or not to construct -- |IP and provide artificial declarations for implicitly declared elements. -- -- |IR Implementation Requirements: -- |IR -- |IR Raises ASIS_Inappropriate_Element, with a Status of Value_Error, if -- |IR passed a reference that does not have a declaration: -- |IR -- |IR - a reference to an attribute_designator. Attributes are defined, but -- |IR have no implicit or explicit declarations; -- |IR -- |IR - an identifier which syntactically is placed before ""=>"" in a -- |IR pragma_argument_association which has the form of a named -- |IR association; such an identifier can never have a declaration; -- |IR -- |IR - an identifier specific to a pragma (Reference Manual, 2.8(10)); -- |IR -- |IR pragma Should_I_Check ( Really => Yes ); -- |IR -- |IR In this example, both the names Really and Yes have no declaration. -- |IR -- |IR Raises ASIS_Inappropriate_Element, with a Status of Value_Error, if -- |IR passed a portion of a pragma that was ""ignored"" by the compiler and -- |IR which does not have (sufficient) semantic information for a proper -- |IR return result to be computed. For example, -- |IR -- |IR pragma I_Am_Ignored (Foof); -- |IR -- |IR The ""Foof"" expression is An_Identifier but raises this exception -- |IR if passed to Corresponding_Name_Definition if the pragma was ignored -- |IR or unprocessed. -- |IR -- |IR Raises ASIS_Inappropriate_Element, with a Status of Value_Error, if -- |IR passed a portion of a pragma that is an ambiguous reference to more -- |IR than one entity. For example, -- |IR -- |IR pragma Inline (""+""); -- Inlines all ""+"" operators -- |IR -- |IR The ""+"" expression is An_Operator_Symbol but raises this -- |IR exception if it referenced more than one ""+"" operator. In this -- |IR case, the Corresponding_Name_Definition_List query can be used to -- |IR obtain a list of referenced entities. -- ------------------------------------------------------------------------------- -- 17.7 function Corresponding_Name_Definition_List ------------------------------------------------------------------------------- function Corresponding_Name_Definition_List (Reference : in Asis.Element) return Asis.Defining_Name_List; ------------------------------------------------------------------------------- -- Reference - Specifies an entity reference to query -- -- Exactly like Corresponding_Name_Definition except it returns a list. -- The list will almost always have a length of one. The exception to this -- is the case where an expression in a pragma is ambiguous and reference -- more than one entity. For example, -- -- pragma Inline (""+""); -- Inlines all ""+"" operators -- -- The ""+"" expression is An_Operator_Symbol but could reference more than one -- ""+"" operator. In this case, the resulting list includes all referenced -- entities. -- -- Appropriate Expression_Kinds: -- An_Identifier -- An_Operator_Symbol -- A_Character_Literal -- An_Enumeration_Literal -- -- Returns Element_Kinds: -- A_Defining_Name -- ------------------------------------------------------------------------------- -- 17.8 function Corresponding_Name_Declaration ------------------------------------------------------------------------------- function Corresponding_Name_Declaration (Reference : in Asis.Expression) return Asis.Element; ------------------------------------------------------------------------------- -- Reference - Specifies the entity reference to query -- -- Returns the declaration that declared the entity named by the given -- reference. The result is exactly the same as: -- -- Result := Corresponding_Name_Definition (Reference); -- if not Is_Nil (Result) then -- Result := Enclosing_Element (Result); -- end if; -- return Result; -- -- See the comments for Corresponding_Name_Definition for details. -- The result is either a Declaration or a Statement. Statements result -- from references to statement labels, loop identifiers, and block -- identifiers. -- -- Appropriate Element_Kinds: -- An_Expression -- -- Appropriate Expression_Kinds: -- An_Identifier -- An_Operator_Symbol -- A_Character_Literal -- An_Enumeration_Literal -- -- Returns Element_Kinds: -- A_Declaration -- A_Statement -- -- Predefined types, exceptions, operators in package Standard can be -- checked by testing that the enclosing Compilation_Unit is standard. -- -- |ER------------------------------------------------------------------------ -- |ER An_Explicit_Dereference - 4.1 -- |CR -- |CR Child elements returned by: function Prefix -- ------------------------------------------------------------------------------- -- 17.9 function Prefix ------------------------------------------------------------------------------- function Prefix (Expression : in Asis.Expression) return Asis.Expression; ------------------------------------------------------------------------------- -- Expression - Specifies the name expression to query -- -- Returns the prefix (the construct to the left of: the rightmost unnested -- left parenthesis in function_call elements and indexed_component elements -- or slice elements, the rightmost 'dot' for selected_component elements, -- or the rightmost tick for attribute_reference elements). -- -- Returns the operator_symbol for infix operator function calls. The infix -- form A + B is equivalent to the prefix form ""+""(A, B). -- -- Appropriate Expression_Kinds: -- An_Explicit_Dereference P.ALL -- An_Attribute_Reference Priv'Base'First -- A_Function_Call Abc(...) or Integer'Image(...) -- An_Indexed_Component An_Array(3) -- A_Selected_Component A.B.C -- A_Slice An_Array(3 .. 5) -- -- Returns Expression_Kinds: -- An_Expression -- -- |ER------------------------------------------------------------------------ -- |ER An_Indexed_Component - 4.1.1 -- |ER -- |CR -- |CR Child elements returned by: -- |CR function Prefix -- |CR function Index_Expressions -- |CR -- ------------------------------------------------------------------------------- -- 17.10 function Index_Expressions ------------------------------------------------------------------------------- function Index_Expressions (Expression : in Asis.Expression) return Asis.Expression_List; ------------------------------------------------------------------------------- -- Expression - Specifies an indexed_component to query -- -- Returns the list of expressions (possibly only one) within the parenthesis, -- in their order of appearance. -- -- Appropriate Expression_Kinds: -- An_Indexed_Component -- -- Returns Element_Kinds: -- An_Expression -- -- |ER------------------------------------------------------------------------ -- |ER A_Slice - 4.1.2 -- |CR -- |CR Child elements returned by: -- |CR function Prefix -- |CR function Slice_Range -- |CR -- ------------------------------------------------------------------------------- -- 17.11 function Slice_Range ------------------------------------------------------------------------------- function Slice_Range (Expression : in Asis.Expression) return Asis.Discrete_Range; ------------------------------------------------------------------------------- -- Expression - Specifies the slice to query -- -- Returns the discrete range of the slice. -- -- Appropriate Expression_Kinds: -- A_Slice -- -- Returns Definition_Kinds: -- A_Discrete_Range -- ------------------------------------------------------------------------------- -- 17.12 function Selector ------------------------------------------------------------------------------- function Selector (Expression : in Asis.Expression) return Asis.Expression; ------------------------------------------------------------------------------- -- Expression - Specifies the selected_component to query -- -- Returns the selector (the construct to the right of the rightmost 'dot' in -- the selected_component). -- -- Appropriate Expression_Kinds: -- A_Selected_Component -- -- Returns Expression_Kinds: -- An_Identifier -- An_Operator_Symbol -- A_Character_Literal -- An_Enumeration_Literal -- ------------------------------------------------------------------------------- -- 17.13 function Attribute_Designator_Identifier ------------------------------------------------------------------------------- function Attribute_Designator_Identifier (Expression : in Asis.Expression) return Asis.Expression; ------------------------------------------------------------------------------- -- Expression - Specifies an attribute_reference expression to query -- -- Returns the identifier of the attribute_designator (the construct to the -- right of the rightmost tick of the attribute_reference). The Prefix of -- the attribute_reference can itself be an attribute_reference as in -- T'BASE'FIRST where the prefix is T'BASE and the attribute_designator name -- is FIRST. -- -- Attribute_designator reserved words ""access"", ""delta"", and ""digits"" are -- treated as An_Identifier. -- -- Appropriate Expression_Kinds: -- An_Attribute_Reference -- -- Returns Expression_Kinds: -- An_Identifier -- ------------------------------------------------------------------------------- -- 17.14 function Attribute_Designator_Expressions ------------------------------------------------------------------------------- function Attribute_Designator_Expressions (Expression : in Asis.Expression) return Asis.Expression_List; ------------------------------------------------------------------------------- -- Expression - Specifies an attribute expression to query -- -- Returns the static expressions associated with the optional argument of -- the attribute_designator. Expected predefined attributes are A'First(N), -- A'Last(N), A'Length(N), and A'Range(N). -- -- Returns a Nil_Element_List if there are no arguments. -- -- Appropriate Expression_Kinds: -- An_Attribute_Reference -- Appropriate Attribute_Kinds: -- A_First_Attribute -- A_Last_Attribute -- A_Length_Attribute -- A_Range_Attribute -- An_Implementation_Defined_Attribute -- An_Unknown_Attribute -- -- Returns Element_Kinds: -- An_Expression -- -- |IP Implementation Permissions: -- |IP -- |IP This query returns a list to support implementation-defined attributes -- |IP that may have more than one static_expression. -- ------------------------------------------------------------------------------- -- 17.15 function Record_Component_Associations ------------------------------------------------------------------------------- function Record_Component_Associations (Expression : in Asis.Expression; Normalized : in Boolean := False) return Asis.Association_List; ------------------------------------------------------------------------------- -- Expression - Specifies an aggregate expression to query -- Normalized - Specifies whether the normalized form is desired -- -- Returns a list of the record_component_association elements of a -- record_aggregate or an extension_aggregate. -- -- Returns a Nil_Element_List if the aggregate is of the form (null record). -- -- An unnormalized list contains all needed associations ordered as they -- appear in the program text. Each unnormalized association has an optional -- list of discriminant_selector_name elements, and an explicit expression. -- -- A normalized list contains artificial associations representing all -- needed components in an order matching the declaration order of the -- needed components. -- -- Each normalized association represents a one on one mapping of a -- component to the explicit expression. A normalized association has one -- A_Defining_Name component that denotes the discriminant_specification or -- component_declaration, and one An_Expression component that is the -- expression. -- -- Appropriate Expression_Kinds: -- A_Record_Aggregate -- An_Extension_Aggregate -- -- Returns Association_Kinds: -- A_Record_Component_Association -- -- |IR Implementation Requirements: -- |IR -- |IR Normalized associations are Is_Normalized and Is_Part_Of_Implicit. -- |IR Normalized associations are never Is_Equal to unnormalized -- |IR associations. -- -- |IP Implementation Permissions: -- |IP -- |IP An implementation may choose to normalize its internal representation -- |IP to use the defining_identifier element instead of the -- |IP component_selector_name element. -- |IP -- |IP If so, this query will return Is_Normalized associations even if -- |IP Normalized is False, and the query -- |IP Record_Component_Associations_Normalized will return True. -- ------------------------------------------------------------------------------- -- 17.16 function Extension_Aggregate_Expression ------------------------------------------------------------------------------- function Extension_Aggregate_Expression (Expression : in Asis.Expression) return Asis.Expression; ------------------------------------------------------------------------------- -- Expression - Specifies an extension_aggregate expression to query -- -- Returns the ancestor_part expression preceding the reserved word with in -- the extension_aggregate. -- -- Appropriate Expression_Kinds: -- An_Extension_Aggregate -- -- Returns Element_Kinds: -- An_Expression -- ------------------------------------------------------------------------------- -- 17.17 function Array_Component_Associations ------------------------------------------------------------------------------- function Array_Component_Associations (Expression : in Asis.Expression) return Asis.Association_List; ------------------------------------------------------------------------------- -- Expression - Specifies an array aggregate expression to query -- -- Returns a list of the Array_Component_Associations in an array aggregate. -- -- Appropriate Expression_Kinds: -- A_Positional_Array_Aggregate -- A_Named_Array_Aggregate -- -- Returns Association_Kinds: -- An_Array_Component_Association -- -- |AN Application Note: -- |AN -- |AN While positional_array_aggregate elements do not have -- |AN array_component_association elements defined by Ada syntax, ASIS treats -- |AN A_Positional_Array_Aggregate as if it were A_Named_Array_Aggregate. -- |AN The An_Array_Component_Association elements returned will have -- |AN Array_Component_Choices that are a Nil_Element_List for all positional -- |AN expressions except an others choice. -- ------------------------------------------------------------------------------- -- 17.18 function Array_Component_Choices ------------------------------------------------------------------------------- function Array_Component_Choices (Association : in Asis.Association) return Asis.Expression_List; ------------------------------------------------------------------------------- -- Association - Specifies the component association to query -- -- If the Association is from a named_array_aggregate: -- -- - Returns the discrete_choice_list order of appearance. The choices are -- either An_Expression or A_Discrete_Range elements, or a single -- An_Others_Choice element. -- -- If the Association is from a positional_array_aggregate: -- -- - Returns a single An_Others_Choice if the association is an others -- choice (others => expression). -- -- - Returns a Nil_Element_List otherwise. -- -- Appropriate Association_Kinds: -- An_Array_Component_Association -- -- Returns Element_Kinds: -- A_Definition -- An_Expression -- -- Returns Definition_Kinds: -- A_Discrete_Range -- An_Others_Choice -- ------------------------------------------------------------------------------- -- 17.19 function Record_Component_Choices ------------------------------------------------------------------------------- function Record_Component_Choices (Association : in Asis.Association) return Asis.Expression_List; ------------------------------------------------------------------------------- -- Association - Specifies the component association to query -- -- If the Association argument is from an unnormalized list: -- -- - If the Association is a named component association: -- -- o Returns the component_choice_list order of appearance. The choices are -- either An_Identifier elements representing component_selector_name -- elements, or a single An_Others_Choice element. -- -- o The Enclosing_Element of the choices is the Association argument. -- -- - If the Association is a positional component association: -- -- o Returns a Nil_Element_List. -- -- If the Association argument is from a Normalized list: -- -- - Returns a list containing a single choice: -- -- o A_Defining_Name element representing the defining_identifier of -- the component_declaration. -- -- o The Enclosing_Element of the A_Defining_Name is the -- component_declaration. -- -- Normalized lists contain artificial ASIS An_Association elements that -- provide one formal A_Defining_Name => An_Expression pair per -- association. These artificial associations are Is_Normalized. Their -- component A_Defining_Name is not Is_Normalized. -- -- Appropriate Association_Kinds: -- A_Record_Component_Association -- -- Returns Element_Kinds: -- A_Defining_Name -- Is_Normalized(Association) -- An_Expression -- not Is_Normalized(Association) -- Returns Expression_Kinds: -- An_Identifier -- A_Definition -- Returns Definition_Kinds: -- An_Others_Choice -- ------------------------------------------------------------------------------- -- 17.20 function Component_Expression ------------------------------------------------------------------------------- function Component_Expression (Association : in Asis.Association) return Asis.Expression; ------------------------------------------------------------------------------- -- Association - Specifies the component association to query -- -- Returns the expression of the record_component_association or -- array_component_association. -- -- The Enclosing_Element of the expression is the Association argument. -- -- Normalized lists contain artificial ASIS An_Association elements that -- provide one formal A_Defining_Name => An_Expression pair per -- association. These artificial associations are Is_Normalized. Their -- component An_Expression elements are not Is_Normalized. -- -- For An_Array_Component_Association and non-normalized -- A_Record_Component_Association where the association contains a -- box expression, Asis.Expressions.Component_Expression -- returns A_Box_Expression. -- -- For a normalized A_Record_Component_Association, where the association -- contains a a box expression, if the corresponding record type that -- contains this component contains a default expression, -- Asis.Expressions.Component_Expression returns this default -- expression, otherwise Asis.Expressions.Component_Expression -- returns A_Box_Expression. -- -- Appropriate Association_Kinds: -- A_Record_Component_Association -- An_Array_Component_Association -- A_Box_Expression -- -- Returns Element_Kinds: -- An_Expression -- ------------------------------------------------------------------------------- -- 17.21 function Formal_Parameter ------------------------------------------------------------------------------- function Formal_Parameter (Association : in Asis.Association) return Asis.Element; ------------------------------------------------------------------------------- -- Association - Specifies the association to query -- -- If the Association argument is from an unnormalized list: -- -- - If the Association is given in named notation: -- -- Returns An_Identifier representing the formal_parameter_selector_name, -- generic_formal_parameter_selector_name, or pragma_argument_identifier. -- -- The Enclosing_Element of the An_Identifier element is the Association -- argument. -- -- - If the Association is given in positional notation: -- -- Returns a Nil_Element. -- -- - May return An_Others_Choice for A_Generic_Association argument -- -- If the Association argument is from a Normalized list: -- -- - Returns A_Defining_Name representing the defining_identifier of the -- parameter_specification or generic_formal_parameter_declaration. -- Pragma_argument_association elements are not available in normalized -- form. -- -- - The Enclosing_Element of the A_Defining_Name is the -- parameter_specification or generic_formal_parameter_declaration element. -- -- Normalized lists contain artificial ASIS An_Association elements that -- provide one formal A_Defining_Name => An_Expression pair per -- association. These artificial associations are Is_Normalized. Their -- component A_Defining_Name elements are not Is_Normalized. -- -- Appropriate Association_Kinds: -- A_Parameter_Association -- A_Generic_Association -- A_Pragma_Argument_Association -- -- Returns Element_Kinds: -- Not_An_Element -- An_Operator_Symbol -- A_Defining_Name -- Is_Normalized(Association) -- An_Expression -- not Is_Normalized(Association) -- Returns Expression_Kinds: -- An_Identifier -- Definition_Kinds -- Added by Gela for SI99-0014-1 -- Returns Definition_Kinds: -- An_Others_Choice -- ------------------------------------------------------------------------------- -- 17.22 function Actual_Parameter ------------------------------------------------------------------------------- function Actual_Parameter (Association : in Asis.Association) return Asis.Expression; ------------------------------------------------------------------------------- -- Association - Specifies the association to query -- -- If the Association argument is from an unnormalized list: -- -- - Returns An_Expression representing: -- -- o the explicit_actual_parameter of a parameter_association. -- -- o the explicit_generic_actual_parameter of a generic_association. -- -- o the name or expression of a pragma_argument_association. -- -- - The Enclosing_Element of An_Expression is the Association argument. -- -- If the Association argument is from a Normalized list: -- -- - If the Association is given explicitly: -- -- o Returns An_Expression representing: -- -- + the explicit_actual_parameter of a parameter_association. -- -- + the explicit_generic_actual_parameter of a generic_association. -- -- o The Enclosing_Element of An_Expression is the Association argument. -- -- - If the Association is given by default: -- -- o Returns An_Expression representing: -- -- + the corresponding default_expression of the Is_Normalized -- A_Parameter_Association. -- -- + the corresponding default_expression or default_name of the -- Is_Normalized A_Generic_Association. -- -- o The Enclosing_Element of the An_Expression element is the -- parameter_specification or generic_formal_parameter_declaration that -- contains the default_expression or default_name, except for the case -- when this An_Expression element is an implicit naming expression -- representing the actual subprogram selected at the place of the -- instantiation for A_Box_Default. In the latter case, the -- Enclosing_Element for such An_Expression is the instantiation. -- -- o Normalized lists contain artificial ASIS An_Association elements that -- provide one formal A_Defining_Name => An_Expression pair per -- association. These artificial associations are Is_Normalized. -- Artificial associations of default associations are -- Is_Defaulted_Association. Their component An_Expression elements are -- not Is_Normalized and are not Is_Defaulted_Association. -- -- If the argument is A_Pragma_Argument_Association, then this function may -- return any expression to support implementation-defined pragmas. -- -- Appropriate Association_Kinds: -- A_Parameter_Association -- A_Generic_Association -- A_Pragma_Argument_Association -- -- Returns Element_Kinds: -- An_Expression -- ------------------------------------------------------------------------------- -- 17.23 function Discriminant_Selector_Names ------------------------------------------------------------------------------- function Discriminant_Selector_Names (Association : in Asis.Discriminant_Association) return Asis.Expression_List; ------------------------------------------------------------------------------- -- Association - Specifies the discriminant association to query -- -- If the Association argument is from an unnormalized list: -- -- - If the Association is a named discriminant_association: -- -- o Returns a list of the An_Identifier discriminant_selector_name elements -- in order of appearance. -- -- o The Enclosing_Element of the names is the Association argument. -- -- - If the Association is a positional discriminant_association: -- -- o Returns a Nil_Element_List. -- -- If the Association argument is from a Normalized list: -- -- - Returns a list containing a single A_Defining_Name element representing -- the defining_identifier of the discriminant_specification. -- -- - The Enclosing_Element of the A_Defining_Name is the -- discriminant_specification. -- -- - Normalized lists contain artificial ASIS An_Association elements that -- provide one formal A_Defining_Name => An_Expression pair per -- association. These artificial associations are Is_Normalized. Their -- component A_Defining_Name elements are not Is_Normalized. -- -- Appropriate Association_Kinds: -- A_Discriminant_Association -- -- Returns Element_Kinds: -- A_Defining_Name -- Is_Normalized(Association) -- An_Expression -- not Is_Normalized(Association) -- Returns Expression_Kinds: -- An_Identifier -- ------------------------------------------------------------------------------- -- 17.24 function Discriminant_Expression ------------------------------------------------------------------------------- function Discriminant_Expression (Association : in Asis.Discriminant_Association) return Asis.Expression; ------------------------------------------------------------------------------- -- Association - Specifies the discriminant_association to query -- -- If the Association argument is from an unnormalized list: -- -- - Returns An_Expression representing the expression of the -- discriminant_association. -- -- - The Enclosing_Element of An_Expression is the Association argument. -- -- If the Association argument is from a Normalized list: -- -- - If the Association is given explicitly: -- -- o Returns An_Expression representing the expression of the -- discriminant_association. -- -- o The Enclosing_Element of An_Expression is the Association argument. -- -- - If the Association is given by default: -- -- o Returns An_Expression representing: -- -- + the corresponding default_expression of the Is_Normalized -- A_Discriminant_Association. -- -- o The Enclosing_Element of the An_Expression element is the -- discriminant_specification that contains the default_expression. -- -- - Normalized lists contain artificial ASIS An_Association elements that -- provide one formal A_Defining_Name => An_Expression pair per -- association. These artificial associations are Is_Normalized. -- Artificial associations of default associations are -- Is_Defaulted_Association. Their component An_Expression elements are -- not Is_Normalized and are not Is_Defaulted_Association. -- -- Appropriate Association_Kinds: -- A_Discriminant_Association -- -- Returns Element_Kinds: -- An_Expression -- ------------------------------------------------------------------------------- -- 17.25 function Is_Normalized ------------------------------------------------------------------------------- function Is_Normalized (Association : in Asis.Association) return Boolean; ------------------------------------------------------------------------------- -- Association - Specifies the association to query -- -- Returns True if the association is a normalized, artificially created -- association returned by the queries Discriminant_Associations, -- Generic_Actual_Part, Call_Statement_Parameters, -- Record_Component_Associations, or Function_Call_Parameters where -- Normalized => True (or the operation returns Is_Normalized associations -- even if Normalized => False). See the Implementation Permissions for -- these queries. -- -- Returns False for any unexpected Element. -- -- Expected Association_Kinds: -- A_Discriminant_Association -- A_Record_Component_Association -- A_Parameter_Association -- A_Generic_Association -- ------------------------------------------------------------------------------- -- 17.26 function Is_Defaulted_Association ------------------------------------------------------------------------------- function Is_Defaulted_Association (Association : in Asis.Association) return Boolean; ------------------------------------------------------------------------------- -- Association - Specifies the association to query -- -- Returns True if the association is a normalized, artificially created -- association returned by the queries Discriminant_Associations, -- Generic_Actual_Part, Record_Component_Associations, -- Call_Statement_Parameters, or Function_Call_Parameters where -- Normalized => True (or the operation returns default associations even if -- Normalized => False) and the association contains a default expression. -- A default expression is one that is implicitly supplied by the language -- semantics and that was not explicitly supplied (typed) by the user. -- -- Returns False for any unexpected Element. -- -- Expected Association_Kinds: -- A_Parameter_Association -- A_Generic_Association -- -- |AN Application Note: -- |AN -- |AN Always returns False for discriminant associations. Defaulted -- |AN discriminant associations occur only when the discriminant constraint -- |AN is completely missing from a subtype indication. Consequently, it is -- |AN not possible to obtain a (normalized) discriminant constraint list for -- |AN such subtype indications. Always returns False for component -- |AN associations. Aggregates cannot have defaulted components. -- ------------------------------------------------------------------------------- -- 17.27 function Expression_Parenthesized ------------------------------------------------------------------------------- function Expression_Parenthesized (Expression : in Asis.Expression) return Asis.Expression; ------------------------------------------------------------------------------- -- Expression - Specifies the parenthesized expression to query -- -- Returns the expression within the parenthesis. This operation unwinds -- only one set of parenthesis at a time, so the result may itself be -- A_Parenthesized_Expression. -- -- A_Parenthesized_Expression kind corresponds only to the (expression) -- alternative in the syntax notion of primary in Reference Manual 4.4. For -- example, an expression of a type_conversion is A_Parenthesized_Expression -- only if it is similar to the form subtype_mark((expression)) where it has -- at least one set of its own parenthesis. -- -- Appropriate Expression_Kinds: -- A_Parenthesized_Expression -- -- Returns Element_Kinds: -- An_Expression -- ------------------------------------------------------------------------------- -- 17.28 function Is_Prefix_Call ------------------------------------------------------------------------------- function Is_Prefix_Call (Expression : in Asis.Expression) return Boolean; ------------------------------------------------------------------------------- -- Expression - Specifies the function call expression to query -- -- Returns True if the function call is in prefix form. -- -- Returns False for any unexpected Element. -- -- For example, -- -- Foo (A, B); -- Returns TRUE -- ""<"" (A, B); -- Returns TRUE -- ... A < B ... -- Returns FALSE -- -- Expected Expression_Kinds: -- A_Function_Call -- ------------------------------------------------------------------------------- -- 17.29 function Corresponding_Called_Function ------------------------------------------------------------------------------- function Corresponding_Called_Function (Expression : in Asis.Expression) return Asis.Declaration; ------------------------------------------------------------------------------- -- Expression - Specifies the function_call to query -- -- Returns the declaration of the called function. -- -- Returns a Nil_Element if the: -- -- - function_prefix denotes a predefined operator for which the -- implementation does not provide an artificial function declaration, -- -- - prefix of the call denotes an access to a function implicit or explicit -- dereference, -- -- - argument is a dispatching call. -- -- If function_prefix denotes an attribute_reference, and if the corresponding -- attribute is (re)defined by an attribute definition clause, an -- implementation is encouraged, but not required, to return the definition -- of the corresponding subprogram whose name is used after ""use"" in this -- attribute definition clause. If an implementation cannot return such a -- subprogram definition, a Nil_Element should be returned. For an attribute -- reference which is not (re)defined by an attribute definition clause, -- a Nil_Element should be returned. -- -- Appropriate Expression_Kinds: -- A_Function_Call -- -- Returns Declaration_Kinds: -- Not_A_Declaration -- A_Function_Declaration -- A_Function_Body_Declaration -- A_Function_Body_Stub -- A_Function_Renaming_Declaration -- A_Function_Instantiation -- A_Formal_Function_Declaration -- A_Generic_Function_Declaration -- -- |IP Implementation Permissions: -- |IP -- |IP An implementation may choose to return any part of multi-part -- |IP declarations and definitions. Multi-part declaration/definitions can -- |IP occur for: -- |IP -- |IP - Subprogram specification in package specification, package body, -- |IP and subunits (is separate); -- |IP - Entries in package specification, package body, and subunits -- |IP (is separate); -- |IP - Private type and full type declarations; -- |IP - Incomplete type and full type declarations; and -- |IP - Deferred constant and full constant declarations. -- |IP -- |IP No guarantee is made that the element will be the first part or -- |IP that the determination will be made due to any visibility rules. -- |IP An application should make its own analysis for each case based -- |IP on which part is returned. -- |IP -- |IP An implementation can choose whether or not to construct and provide -- |IP artificial implicit declarations for predefined operators. -- ------------------------------------------------------------------------------- -- 17.30 function Function_Call_Parameters ------------------------------------------------------------------------------- function Function_Call_Parameters (Expression : in Asis.Expression; Normalized : in Boolean := False) return Asis.Association_List; ------------------------------------------------------------------------------- -- Expression - Specifies the function call expression to query -- Normalized - Specifies whether the normalized form is desired -- -- Returns a list of parameter_association elements of the call. -- -- Returns a Nil_Element_List if there are no parameter_association elements. -- -- An unnormalized list contains only explicit associations ordered as they -- appear in the program text. Each unnormalized association has an optional -- formal_parameter_selector_name and an explicit_actual_parameter component. -- -- A normalized list contains artificial associations representing all -- explicit and default associations. It has a length equal to the number of -- parameter_specification elements of the formal_part of the -- parameter_and_result_profile. The order of normalized associations matches -- the order of parameter_specification elements. -- -- Each normalized association represents a one on one mapping of a -- parameter_specification elements to the explicit or default expression. -- A normalized association has one A_Defining_Name component that denotes -- the parameter_specification, and one An_Expression component that is -- either the explicit_actual_parameter or a default_expression. -- -- If the prefix of the call denotes an access to a function implicit or -- explicit deference, normalized associations are constructed on the basis -- of the formal_part of the parameter_and_result_profile from the -- corresponding access_to_subprogram definition. -- Returns Nil_Element for normalized associations in the case where -- the called function can be determined only dynamically (dispatching -- calls). ASIS cannot produce any meaningful result in this case. -- The exception ASIS_Inappropriate_Element is raised when the function -- call is an attribute reference and Is_Normalized is True. -- -- Appropriate Expression_Kinds: -- A_Function_Call -- -- Returns Element_Kinds: -- A_Parameter_Association -- -- |IR Implementation Requirements: -- |IR -- |IR Normalized associations are Is_Normalized and Is_Part_Of_Implicit. -- |IR Normalized associations provided by default are -- |IR Is_Defaulted_Association. -- |IR Normalized associations are never Is_Equal to unnormalized -- |IR associations. -- -- |IP Implementation Permissions: -- |IP -- |IP An implementation may choose to always include default parameters in -- |IP its internal representation. -- |IP -- |IP An implementation may also choose to normalize its representation -- |IP to use defining_identifier elements rather than -- |IP formal_parameter_selector_name elements. -- |IP -- |IP In either case, this query will return Is_Normalized associations even -- |IP if Normalized is False, and the query -- |IP Function_Call_Parameters_Normalized will return True. -- ------------------------------------------------------------------------------- -- 17.31 function Short_Circuit_Operation_Left_Expression ------------------------------------------------------------------------------- function Short_Circuit_Operation_Left_Expression (Expression : in Asis.Expression) return Asis.Expression; ------------------------------------------------------------------------------- -- Expression - Specifies the short circuit operation to query -- -- Returns the expression preceding the reserved words ""and then"" or -- ""or else"" in the short circuit expression. -- -- Appropriate Expression_Kinds: -- An_And_Then_Short_Circuit -- An_Or_Else_Short_Circuit -- -- Returns Element_Kinds: -- An_Expression -- ------------------------------------------------------------------------------- -- 17.32 function Short_Circuit_Operation_Right_Expression ------------------------------------------------------------------------------- function Short_Circuit_Operation_Right_Expression (Expression : in Asis.Expression) return Asis.Expression; ------------------------------------------------------------------------------- -- Expression - Specifies the short circuit operation to query -- -- Returns the expression following the reserved words ""or else"" or -- ""and then"" in the short circuit expression. -- -- Appropriate Expression_Kinds: -- An_And_Then_Short_Circuit -- An_Or_Else_Short_Circuit -- -- Returns Element_Kinds: -- An_Expression -- ------------------------------------------------------------------------------- -- 17.33 function Membership_Test_Expression ------------------------------------------------------------------------------- function Membership_Test_Expression (Expression : in Asis.Expression) return Asis.Expression; ------------------------------------------------------------------------------- -- Expression - Specifies the membership test operation to query -- -- Returns the expression on the left hand side of the membership test. -- -- Appropriate Expression_Kinds: -- An_In_Range_Membership_Test -- A_Not_In_Range_Membership_Test -- An_In_Type_Membership_Test -- A_Not_In_Type_Membership_Test -- -- Returns Element_Kinds: -- An_Expression -- ------------------------------------------------------------------------------- -- 17.34 function Membership_Test_Range ------------------------------------------------------------------------------- function Membership_Test_Range (Expression : in Asis.Expression) return Asis.Range_Constraint; ------------------------------------------------------------------------------- -- Expression - Specifies the membership test operation to query -- -- Returns the range following the reserved words ""in"" or ""not in"" from the -- membership test. -- -- Appropriate Expression_Kinds: -- An_In_Range_Membership_Test -- A_Not_In_Range_Membership_Test -- -- Returns Constraint_Kinds: -- A_Range_Attribute_Reference -- A_Simple_Expression_Range -- ------------------------------------------------------------------------------- -- 17.35 function Membership_Test_Subtype_Mark ------------------------------------------------------------------------------- function Membership_Test_Subtype_Mark (Expression : in Asis.Expression) return Asis.Expression; ------------------------------------------------------------------------------- -- Expression - Specifies the membership test operation to query -- -- Returns the subtype_mark expression following the reserved words ""in"" or -- ""not in"" from the membership test. -- -- Appropriate Expression_Kinds: -- An_In_Type_Membership_Test -- A_Not_In_Type_Membership_Test -- -- Returns Expression_Kinds: -- An_Identifier -- A_Selected_Component -- An_Attribute_Reference -- ------------------------------------------------------------------------------- -- 17.36 function Converted_Or_Qualified_Subtype_Mark ------------------------------------------------------------------------------- function Converted_Or_Qualified_Subtype_Mark (Expression : in Asis.Expression) return Asis.Expression; ------------------------------------------------------------------------------- -- Expression - Specifies the type conversion or qualified expression to -- query. -- -- Returns the subtype_mark expression that converts or qualifies the -- expression. -- -- Appropriate Expression_Kinds: -- A_Type_Conversion -- A_Qualified_Expression -- -- Returns Expression_Kinds: -- An_Identifier -- A_Selected_Component -- An_Attribute_Reference -- ------------------------------------------------------------------------------- -- 17.37 function Converted_Or_Qualified_Expression ------------------------------------------------------------------------------- function Converted_Or_Qualified_Expression (Expression : in Asis.Expression) return Asis.Expression; ------------------------------------------------------------------------------- -- Expression - Specifies the type conversion or qualified expression to -- query -- -- Returns the expression being converted or qualified. -- -- Appropriate Expression_Kinds: -- A_Type_Conversion -- A_Qualified_Expression -- -- Returns Element_Kinds: -- An_Expression -- ------------------------------------------------------------------------------- -- 17.38 function Allocator_Subtype_Indication ------------------------------------------------------------------------------- function Allocator_Subtype_Indication (Expression : in Asis.Expression) return Asis.Subtype_Indication; ------------------------------------------------------------------------------- -- Expression - Specifies the allocator expression to query -- -- Returns the subtype indication for the object being allocated. -- -- Appropriate Expression_Kinds: -- An_Allocation_From_Subtype -- -- Returns Definition_Kinds: -- A_Subtype_Indication -- ------------------------------------------------------------------------------- -- 17.39 function Allocator_Qualified_Expression ------------------------------------------------------------------------------- function Allocator_Qualified_Expression (Expression : in Asis.Expression) return Asis.Expression; ------------------------------------------------------------------------------- -- Expression - Specifies the allocator expression to query -- -- Returns the qualified expression for the object being allocated. -- -- Appropriate Expression_Kinds: -- An_Allocation_From_Qualified_Expression -- -- Returns Expression_Kinds: -- A_Qualified_Expression -- ------------------------------------------------------------------------------- end Asis.Expressions; ------------------------------------------------------------------------------ -- Copyright (c) 2006-2013, Maxim Reznik -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the Maxim Reznik, IE nor the names of its -- contributors may be used to endorse or promote products derived from -- this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ ",12385,True,2680.052984604914,median "------------------------------------------------------------------------------ -- -- -- GNAT LIBRARY COMPONENTS -- -- -- -- ADA.CONTAINERS.INDEFINITE_ORDERED_MULTISETS -- -- -- -- B o d y -- -- -- -- Copyright (C) 2004-2015, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- . -- -- -- -- This unit was originally developed by Matthew J Heaney. -- ------------------------------------------------------------------------------ with Ada.Unchecked_Deallocation; with Ada.Containers.Red_Black_Trees.Generic_Operations; pragma Elaborate_All (Ada.Containers.Red_Black_Trees.Generic_Operations); with Ada.Containers.Red_Black_Trees.Generic_Keys; pragma Elaborate_All (Ada.Containers.Red_Black_Trees.Generic_Keys); with Ada.Containers.Red_Black_Trees.Generic_Set_Operations; pragma Elaborate_All (Ada.Containers.Red_Black_Trees.Generic_Set_Operations); with System; use type System.Address; package body Ada.Containers.Indefinite_Ordered_Multisets is pragma Warnings (Off, ""variable """"Busy*"""" is not referenced""); pragma Warnings (Off, ""variable """"Lock*"""" is not referenced""); -- See comment in Ada.Containers.Helpers ----------------------------- -- Node Access Subprograms -- ----------------------------- -- These subprograms provide a functional interface to access fields -- of a node, and a procedural interface for modifying these values. function Color (Node : Node_Access) return Color_Type; pragma Inline (Color); function Left (Node : Node_Access) return Node_Access; pragma Inline (Left); function Parent (Node : Node_Access) return Node_Access; pragma Inline (Parent); function Right (Node : Node_Access) return Node_Access; pragma Inline (Right); procedure Set_Parent (Node : Node_Access; Parent : Node_Access); pragma Inline (Set_Parent); procedure Set_Left (Node : Node_Access; Left : Node_Access); pragma Inline (Set_Left); procedure Set_Right (Node : Node_Access; Right : Node_Access); pragma Inline (Set_Right); procedure Set_Color (Node : Node_Access; Color : Color_Type); pragma Inline (Set_Color); ----------------------- -- Local Subprograms -- ----------------------- function Copy_Node (Source : Node_Access) return Node_Access; pragma Inline (Copy_Node); procedure Free (X : in out Node_Access); procedure Insert_Sans_Hint (Tree : in out Tree_Type; New_Item : Element_Type; Node : out Node_Access); procedure Insert_With_Hint (Dst_Tree : in out Tree_Type; Dst_Hint : Node_Access; Src_Node : Node_Access; Dst_Node : out Node_Access); function Is_Equal_Node_Node (L, R : Node_Access) return Boolean; pragma Inline (Is_Equal_Node_Node); function Is_Greater_Element_Node (Left : Element_Type; Right : Node_Access) return Boolean; pragma Inline (Is_Greater_Element_Node); function Is_Less_Element_Node (Left : Element_Type; Right : Node_Access) return Boolean; pragma Inline (Is_Less_Element_Node); function Is_Less_Node_Node (L, R : Node_Access) return Boolean; pragma Inline (Is_Less_Node_Node); procedure Replace_Element (Tree : in out Tree_Type; Node : Node_Access; Item : Element_Type); -------------------------- -- Local Instantiations -- -------------------------- package Tree_Operations is new Red_Black_Trees.Generic_Operations (Tree_Types); procedure Delete_Tree is new Tree_Operations.Generic_Delete_Tree (Free); function Copy_Tree is new Tree_Operations.Generic_Copy_Tree (Copy_Node, Delete_Tree); use Tree_Operations; procedure Free_Element is new Ada.Unchecked_Deallocation (Element_Type, Element_Access); function Is_Equal is new Tree_Operations.Generic_Equal (Is_Equal_Node_Node); package Set_Ops is new Generic_Set_Operations (Tree_Operations => Tree_Operations, Insert_With_Hint => Insert_With_Hint, Copy_Tree => Copy_Tree, Delete_Tree => Delete_Tree, Is_Less => Is_Less_Node_Node, Free => Free); package Element_Keys is new Red_Black_Trees.Generic_Keys (Tree_Operations => Tree_Operations, Key_Type => Element_Type, Is_Less_Key_Node => Is_Less_Element_Node, Is_Greater_Key_Node => Is_Greater_Element_Node); --------- -- ""<"" -- --------- function ""<"" (Left, Right : Cursor) return Boolean is begin if Left.Node = null then raise Constraint_Error with ""Left cursor equals No_Element""; end if; if Right.Node = null then raise Constraint_Error with ""Right cursor equals No_Element""; end if; if Left.Node.Element = null then raise Program_Error with ""Left cursor is bad""; end if; if Right.Node.Element = null then raise Program_Error with ""Right cursor is bad""; end if; pragma Assert (Vet (Left.Container.Tree, Left.Node), ""bad Left cursor in """"<""""""); pragma Assert (Vet (Right.Container.Tree, Right.Node), ""bad Right cursor in """"<""""""); return Left.Node.Element.all < Right.Node.Element.all; end ""<""; function ""<"" (Left : Cursor; Right : Element_Type) return Boolean is begin if Left.Node = null then raise Constraint_Error with ""Left cursor equals No_Element""; end if; if Left.Node.Element = null then raise Program_Error with ""Left cursor is bad""; end if; pragma Assert (Vet (Left.Container.Tree, Left.Node), ""bad Left cursor in """"<""""""); return Left.Node.Element.all < Right; end ""<""; function ""<"" (Left : Element_Type; Right : Cursor) return Boolean is begin if Right.Node = null then raise Constraint_Error with ""Right cursor equals No_Element""; end if; if Right.Node.Element = null then raise Program_Error with ""Right cursor is bad""; end if; pragma Assert (Vet (Right.Container.Tree, Right.Node), ""bad Right cursor in """"<""""""); return Left < Right.Node.Element.all; end ""<""; --------- -- ""="" -- --------- function ""="" (Left, Right : Set) return Boolean is begin return Is_Equal (Left.Tree, Right.Tree); end ""=""; --------- -- "">"" -- --------- function "">"" (Left, Right : Cursor) return Boolean is begin if Left.Node = null then raise Constraint_Error with ""Left cursor equals No_Element""; end if; if Right.Node = null then raise Constraint_Error with ""Right cursor equals No_Element""; end if; if Left.Node.Element = null then raise Program_Error with ""Left cursor is bad""; end if; if Right.Node.Element = null then raise Program_Error with ""Right cursor is bad""; end if; pragma Assert (Vet (Left.Container.Tree, Left.Node), ""bad Left cursor in """">""""""); pragma Assert (Vet (Right.Container.Tree, Right.Node), ""bad Right cursor in """">""""""); -- L > R same as R < L return Right.Node.Element.all < Left.Node.Element.all; end "">""; function "">"" (Left : Cursor; Right : Element_Type) return Boolean is begin if Left.Node = null then raise Constraint_Error with ""Left cursor equals No_Element""; end if; if Left.Node.Element = null then raise Program_Error with ""Left cursor is bad""; end if; pragma Assert (Vet (Left.Container.Tree, Left.Node), ""bad Left cursor in """">""""""); return Right < Left.Node.Element.all; end "">""; function "">"" (Left : Element_Type; Right : Cursor) return Boolean is begin if Right.Node = null then raise Constraint_Error with ""Right cursor equals No_Element""; end if; if Right.Node.Element = null then raise Program_Error with ""Right cursor is bad""; end if; pragma Assert (Vet (Right.Container.Tree, Right.Node), ""bad Right cursor in """">""""""); return Right.Node.Element.all < Left; end "">""; ------------ -- Adjust -- ------------ procedure Adjust is new Tree_Operations.Generic_Adjust (Copy_Tree); procedure Adjust (Container : in out Set) is begin Adjust (Container.Tree); end Adjust; ------------ -- Assign -- ------------ procedure Assign (Target : in out Set; Source : Set) is begin if Target'Address = Source'Address then return; end if; Target.Clear; Target.Union (Source); end Assign; ------------- -- Ceiling -- ------------- function Ceiling (Container : Set; Item : Element_Type) return Cursor is Node : constant Node_Access := Element_Keys.Ceiling (Container.Tree, Item); begin if Node = null then return No_Element; end if; return Cursor'(Container'Unrestricted_Access, Node); end Ceiling; ----------- -- Clear -- ----------- procedure Clear is new Tree_Operations.Generic_Clear (Delete_Tree); procedure Clear (Container : in out Set) is begin Clear (Container.Tree); end Clear; ----------- -- Color -- ----------- function Color (Node : Node_Access) return Color_Type is begin return Node.Color; end Color; ------------------------ -- Constant_Reference -- ------------------------ function Constant_Reference (Container : aliased Set; Position : Cursor) return Constant_Reference_Type is begin if Position.Container = null then raise Constraint_Error with ""Position cursor has no element""; end if; if Position.Container /= Container'Unrestricted_Access then raise Program_Error with ""Position cursor designates wrong container""; end if; pragma Assert (Vet (Position.Container.Tree, Position.Node), ""bad cursor in Constant_Reference""); -- Note: in predefined container units, the creation of a reference -- increments the busy bit of the container, and its finalization -- decrements it. In the absence of control machinery, this tampering -- protection is missing. declare T : Tree_Type renames Container.Tree'Unrestricted_Access.all; pragma Unreferenced (T); begin return R : constant Constant_Reference_Type := (Element => Position.Node.Element, Control => (Container => Container'Unrestricted_Access)) do null; end return; end; end Constant_Reference; -------------- -- Contains -- -------------- function Contains (Container : Set; Item : Element_Type) return Boolean is begin return Find (Container, Item) /= No_Element; end Contains; ---------- -- Copy -- ---------- function Copy (Source : Set) return Set is begin return Target : Set do Target.Assign (Source); end return; end Copy; --------------- -- Copy_Node -- --------------- function Copy_Node (Source : Node_Access) return Node_Access is X : Element_Access := new Element_Type'(Source.Element.all); begin return new Node_Type'(Parent => null, Left => null, Right => null, Color => Source.Color, Element => X); exception when others => Free_Element (X); raise; end Copy_Node; ------------ -- Delete -- ------------ procedure Delete (Container : in out Set; Item : Element_Type) is Tree : Tree_Type renames Container.Tree; Node : Node_Access := Element_Keys.Ceiling (Tree, Item); Done : constant Node_Access := Element_Keys.Upper_Bound (Tree, Item); X : Node_Access; begin if Node = Done then raise Constraint_Error with ""attempt to delete element not in set""; end if; loop X := Node; Node := Tree_Operations.Next (Node); Tree_Operations.Delete_Node_Sans_Free (Tree, X); Free (X); exit when Node = Done; end loop; end Delete; procedure Delete (Container : in out Set; Position : in out Cursor) is begin if Position.Node = null then raise Constraint_Error with ""Position cursor equals No_Element""; end if; if Position.Node.Element = null then raise Program_Error with ""Position cursor is bad""; end if; if Position.Container /= Container'Unrestricted_Access then raise Program_Error with ""Position cursor designates wrong set""; end if; pragma Assert (Vet (Container.Tree, Position.Node), ""bad cursor in Delete""); Tree_Operations.Delete_Node_Sans_Free (Container.Tree, Position.Node); Free (Position.Node); Position.Container := null; end Delete; ------------------ -- Delete_First -- ------------------ procedure Delete_First (Container : in out Set) is Tree : Tree_Type renames Container.Tree; X : Node_Access := Tree.First; begin if X = null then return; end if; Tree_Operations.Delete_Node_Sans_Free (Tree, X); Free (X); end Delete_First; ----------------- -- Delete_Last -- ----------------- procedure Delete_Last (Container : in out Set) is Tree : Tree_Type renames Container.Tree; X : Node_Access := Tree.Last; begin if X = null then return; end if; Tree_Operations.Delete_Node_Sans_Free (Tree, X); Free (X); end Delete_Last; ---------------- -- Difference -- ---------------- procedure Difference (Target : in out Set; Source : Set) is begin Set_Ops.Difference (Target.Tree, Source.Tree); end Difference; function Difference (Left, Right : Set) return Set is Tree : constant Tree_Type := Set_Ops.Difference (Left.Tree, Right.Tree); begin return Set'(Controlled with Tree); end Difference; ------------- -- Element -- ------------- function Element (Position : Cursor) return Element_Type is begin if Position.Node = null then raise Constraint_Error with ""Position cursor equals No_Element""; end if; if Position.Node.Element = null then raise Program_Error with ""Position cursor is bad""; end if; pragma Assert (Vet (Position.Container.Tree, Position.Node), ""bad cursor in Element""); return Position.Node.Element.all; end Element; ------------------------- -- Equivalent_Elements -- ------------------------- function Equivalent_Elements (Left, Right : Element_Type) return Boolean is begin if Left < Right or else Right < Left then return False; else return True; end if; end Equivalent_Elements; --------------------- -- Equivalent_Sets -- --------------------- function Equivalent_Sets (Left, Right : Set) return Boolean is function Is_Equivalent_Node_Node (L, R : Node_Access) return Boolean; pragma Inline (Is_Equivalent_Node_Node); function Is_Equivalent is new Tree_Operations.Generic_Equal (Is_Equivalent_Node_Node); ----------------------------- -- Is_Equivalent_Node_Node -- ----------------------------- function Is_Equivalent_Node_Node (L, R : Node_Access) return Boolean is begin if L.Element.all < R.Element.all then return False; elsif R.Element.all < L.Element.all then return False; else return True; end if; end Is_Equivalent_Node_Node; -- Start of processing for Equivalent_Sets begin return Is_Equivalent (Left.Tree, Right.Tree); end Equivalent_Sets; ------------- -- Exclude -- ------------- procedure Exclude (Container : in out Set; Item : Element_Type) is Tree : Tree_Type renames Container.Tree; Node : Node_Access := Element_Keys.Ceiling (Tree, Item); Done : constant Node_Access := Element_Keys.Upper_Bound (Tree, Item); X : Node_Access; begin while Node /= Done loop X := Node; Node := Tree_Operations.Next (Node); Tree_Operations.Delete_Node_Sans_Free (Tree, X); Free (X); end loop; end Exclude; ---------- -- Find -- ---------- function Find (Container : Set; Item : Element_Type) return Cursor is Node : constant Node_Access := Element_Keys.Find (Container.Tree, Item); begin if Node = null then return No_Element; end if; return Cursor'(Container'Unrestricted_Access, Node); end Find; -------------- -- Finalize -- -------------- procedure Finalize (Object : in out Iterator) is begin Unbusy (Object.Container.Tree.TC); end Finalize; ----------- -- First -- ----------- function First (Container : Set) return Cursor is begin if Container.Tree.First = null then return No_Element; end if; return Cursor'(Container'Unrestricted_Access, Container.Tree.First); end First; function First (Object : Iterator) return Cursor is begin -- The value of the iterator object's Node component influences the -- behavior of the First (and Last) selector function. -- When the Node component is null, this means the iterator object was -- constructed without a start expression, in which case the (forward) -- iteration starts from the (logical) beginning of the entire sequence -- of items (corresponding to Container.First, for a forward iterator). -- Otherwise, this is iteration over a partial sequence of items. When -- the Node component is non-null, the iterator object was constructed -- with a start expression, that specifies the position from which the -- (forward) partial iteration begins. if Object.Node = null then return Object.Container.First; else return Cursor'(Object.Container, Object.Node); end if; end First; ------------------- -- First_Element -- ------------------- function First_Element (Container : Set) return Element_Type is begin if Container.Tree.First = null then raise Constraint_Error with ""set is empty""; end if; pragma Assert (Container.Tree.First.Element /= null); return Container.Tree.First.Element.all; end First_Element; ----------- -- Floor -- ----------- function Floor (Container : Set; Item : Element_Type) return Cursor is Node : constant Node_Access := Element_Keys.Floor (Container.Tree, Item); begin if Node = null then return No_Element; end if; return Cursor'(Container'Unrestricted_Access, Node); end Floor; ---------- -- Free -- ---------- procedure Free (X : in out Node_Access) is procedure Deallocate is new Ada.Unchecked_Deallocation (Node_Type, Node_Access); begin if X = null then return; end if; X.Parent := X; X.Left := X; X.Right := X; begin Free_Element (X.Element); exception when others => X.Element := null; Deallocate (X); raise; end; Deallocate (X); end Free; ------------------ -- Generic_Keys -- ------------------ package body Generic_Keys is ----------------------- -- Local Subprograms -- ----------------------- function Is_Less_Key_Node (Left : Key_Type; Right : Node_Access) return Boolean; pragma Inline (Is_Less_Key_Node); function Is_Greater_Key_Node (Left : Key_Type; Right : Node_Access) return Boolean; pragma Inline (Is_Greater_Key_Node); -------------------------- -- Local Instantiations -- -------------------------- package Key_Keys is new Red_Black_Trees.Generic_Keys (Tree_Operations => Tree_Operations, Key_Type => Key_Type, Is_Less_Key_Node => Is_Less_Key_Node, Is_Greater_Key_Node => Is_Greater_Key_Node); ------------- -- Ceiling -- ------------- function Ceiling (Container : Set; Key : Key_Type) return Cursor is Node : constant Node_Access := Key_Keys.Ceiling (Container.Tree, Key); begin if Node = null then return No_Element; end if; return Cursor'(Container'Unrestricted_Access, Node); end Ceiling; -------------- -- Contains -- -------------- function Contains (Container : Set; Key : Key_Type) return Boolean is begin return Find (Container, Key) /= No_Element; end Contains; ------------ -- Delete -- ------------ procedure Delete (Container : in out Set; Key : Key_Type) is Tree : Tree_Type renames Container.Tree; Node : Node_Access := Key_Keys.Ceiling (Tree, Key); Done : constant Node_Access := Key_Keys.Upper_Bound (Tree, Key); X : Node_Access; begin if Node = Done then raise Constraint_Error with ""attempt to delete key not in set""; end if; loop X := Node; Node := Tree_Operations.Next (Node); Tree_Operations.Delete_Node_Sans_Free (Tree, X); Free (X); exit when Node = Done; end loop; end Delete; ------------- -- Element -- ------------- function Element (Container : Set; Key : Key_Type) return Element_Type is Node : constant Node_Access := Key_Keys.Find (Container.Tree, Key); begin if Node = null then raise Constraint_Error with ""key not in set""; end if; return Node.Element.all; end Element; --------------------- -- Equivalent_Keys -- --------------------- function Equivalent_Keys (Left, Right : Key_Type) return Boolean is begin if Left < Right or else Right < Left then return False; else return True; end if; end Equivalent_Keys; ------------- -- Exclude -- ------------- procedure Exclude (Container : in out Set; Key : Key_Type) is Tree : Tree_Type renames Container.Tree; Node : Node_Access := Key_Keys.Ceiling (Tree, Key); Done : constant Node_Access := Key_Keys.Upper_Bound (Tree, Key); X : Node_Access; begin while Node /= Done loop X := Node; Node := Tree_Operations.Next (Node); Tree_Operations.Delete_Node_Sans_Free (Tree, X); Free (X); end loop; end Exclude; ---------- -- Find -- ---------- function Find (Container : Set; Key : Key_Type) return Cursor is Node : constant Node_Access := Key_Keys.Find (Container.Tree, Key); begin if Node = null then return No_Element; end if; return Cursor'(Container'Unrestricted_Access, Node); end Find; ----------- -- Floor -- ----------- function Floor (Container : Set; Key : Key_Type) return Cursor is Node : constant Node_Access := Key_Keys.Floor (Container.Tree, Key); begin if Node = null then return No_Element; end if; return Cursor'(Container'Unrestricted_Access, Node); end Floor; ------------------------- -- Is_Greater_Key_Node -- ------------------------- function Is_Greater_Key_Node (Left : Key_Type; Right : Node_Access) return Boolean is begin return Key (Right.Element.all) < Left; end Is_Greater_Key_Node; ---------------------- -- Is_Less_Key_Node -- ---------------------- function Is_Less_Key_Node (Left : Key_Type; Right : Node_Access) return Boolean is begin return Left < Key (Right.Element.all); end Is_Less_Key_Node; ------------- -- Iterate -- ------------- procedure Iterate (Container : Set; Key : Key_Type; Process : not null access procedure (Position : Cursor)) is procedure Process_Node (Node : Node_Access); pragma Inline (Process_Node); procedure Local_Iterate is new Key_Keys.Generic_Iteration (Process_Node); ------------------ -- Process_Node -- ------------------ procedure Process_Node (Node : Node_Access) is begin Process (Cursor'(Container'Unrestricted_Access, Node)); end Process_Node; T : Tree_Type renames Container.Tree'Unrestricted_Access.all; Busy : With_Busy (T.TC'Unrestricted_Access); -- Start of processing for Iterate begin Local_Iterate (T, Key); end Iterate; --------- -- Key -- --------- function Key (Position : Cursor) return Key_Type is begin if Position.Node = null then raise Constraint_Error with ""Position cursor equals No_Element""; end if; if Position.Node.Element = null then raise Program_Error with ""Position cursor is bad""; end if; pragma Assert (Vet (Position.Container.Tree, Position.Node), ""bad cursor in Key""); return Key (Position.Node.Element.all); end Key; --------------------- -- Reverse_Iterate -- --------------------- procedure Reverse_Iterate (Container : Set; Key : Key_Type; Process : not null access procedure (Position : Cursor)) is procedure Process_Node (Node : Node_Access); pragma Inline (Process_Node); ------------- -- Iterate -- ------------- procedure Local_Reverse_Iterate is new Key_Keys.Generic_Reverse_Iteration (Process_Node); ------------------ -- Process_Node -- ------------------ procedure Process_Node (Node : Node_Access) is begin Process (Cursor'(Container'Unrestricted_Access, Node)); end Process_Node; T : Tree_Type renames Container.Tree'Unrestricted_Access.all; Busy : With_Busy (T.TC'Unrestricted_Access); -- Start of processing for Reverse_Iterate begin Local_Reverse_Iterate (T, Key); end Reverse_Iterate; -------------------- -- Update_Element -- -------------------- procedure Update_Element (Container : in out Set; Position : Cursor; Process : not null access procedure (Element : in out Element_Type)) is Tree : Tree_Type renames Container.Tree; Node : constant Node_Access := Position.Node; begin if Node = null then raise Constraint_Error with ""Position cursor equals No_Element""; end if; if Node.Element = null then raise Program_Error with ""Position cursor is bad""; end if; if Position.Container /= Container'Unrestricted_Access then raise Program_Error with ""Position cursor designates wrong set""; end if; pragma Assert (Vet (Tree, Node), ""bad cursor in Update_Element""); declare E : Element_Type renames Node.Element.all; K : constant Key_Type := Key (E); Lock : With_Lock (Tree.TC'Unrestricted_Access); begin Process (E); if Equivalent_Keys (Left => K, Right => Key (E)) then return; end if; end; -- Delete_Node checks busy-bit Tree_Operations.Delete_Node_Sans_Free (Tree, Node); Insert_New_Item : declare function New_Node return Node_Access; pragma Inline (New_Node); procedure Insert_Post is new Element_Keys.Generic_Insert_Post (New_Node); procedure Unconditional_Insert is new Element_Keys.Generic_Unconditional_Insert (Insert_Post); -------------- -- New_Node -- -------------- function New_Node return Node_Access is begin Node.Color := Red_Black_Trees.Red; Node.Parent := null; Node.Left := null; Node.Right := null; return Node; end New_Node; Result : Node_Access; -- Start of processing for Insert_New_Item begin Unconditional_Insert (Tree => Tree, Key => Node.Element.all, Node => Result); pragma Assert (Result = Node); end Insert_New_Item; end Update_Element; end Generic_Keys; ----------------- -- Has_Element -- ----------------- function Has_Element (Position : Cursor) return Boolean is begin return Position /= No_Element; end Has_Element; ------------ -- Insert -- ------------ procedure Insert (Container : in out Set; New_Item : Element_Type) is Position : Cursor; pragma Unreferenced (Position); begin Insert (Container, New_Item, Position); end Insert; procedure Insert (Container : in out Set; New_Item : Element_Type; Position : out Cursor) is begin Insert_Sans_Hint (Container.Tree, New_Item, Position.Node); Position.Container := Container'Unrestricted_Access; end Insert; ---------------------- -- Insert_Sans_Hint -- ---------------------- procedure Insert_Sans_Hint (Tree : in out Tree_Type; New_Item : Element_Type; Node : out Node_Access) is function New_Node return Node_Access; pragma Inline (New_Node); procedure Insert_Post is new Element_Keys.Generic_Insert_Post (New_Node); procedure Unconditional_Insert is new Element_Keys.Generic_Unconditional_Insert (Insert_Post); -------------- -- New_Node -- -------------- function New_Node return Node_Access is -- The element allocator may need an accessibility check in the case -- the actual type is class-wide or has access discriminants (see -- RM 4.8(10.1) and AI12-0035). pragma Unsuppress (Accessibility_Check); Element : Element_Access := new Element_Type'(New_Item); begin return new Node_Type'(Parent => null, Left => null, Right => null, Color => Red_Black_Trees.Red, Element => Element); exception when others => Free_Element (Element); raise; end New_Node; -- Start of processing for Insert_Sans_Hint begin Unconditional_Insert (Tree, New_Item, Node); end Insert_Sans_Hint; ---------------------- -- Insert_With_Hint -- ---------------------- procedure Insert_With_Hint (Dst_Tree : in out Tree_Type; Dst_Hint : Node_Access; Src_Node : Node_Access; Dst_Node : out Node_Access) is function New_Node return Node_Access; pragma Inline (New_Node); procedure Insert_Post is new Element_Keys.Generic_Insert_Post (New_Node); procedure Insert_Sans_Hint is new Element_Keys.Generic_Unconditional_Insert (Insert_Post); procedure Local_Insert_With_Hint is new Element_Keys.Generic_Unconditional_Insert_With_Hint (Insert_Post, Insert_Sans_Hint); -------------- -- New_Node -- -------------- function New_Node return Node_Access is X : Element_Access := new Element_Type'(Src_Node.Element.all); begin return new Node_Type'(Parent => null, Left => null, Right => null, Color => Red, Element => X); exception when others => Free_Element (X); raise; end New_Node; -- Start of processing for Insert_With_Hint begin Local_Insert_With_Hint (Dst_Tree, Dst_Hint, Src_Node.Element.all, Dst_Node); end Insert_With_Hint; ------------------ -- Intersection -- ------------------ procedure Intersection (Target : in out Set; Source : Set) is begin Set_Ops.Intersection (Target.Tree, Source.Tree); end Intersection; function Intersection (Left, Right : Set) return Set is Tree : constant Tree_Type := Set_Ops.Intersection (Left.Tree, Right.Tree); begin return Set'(Controlled with Tree); end Intersection; -------------- -- Is_Empty -- -------------- function Is_Empty (Container : Set) return Boolean is begin return Container.Tree.Length = 0; end Is_Empty; ------------------------ -- Is_Equal_Node_Node -- ------------------------ function Is_Equal_Node_Node (L, R : Node_Access) return Boolean is begin return L.Element.all = R.Element.all; end Is_Equal_Node_Node; ----------------------------- -- Is_Greater_Element_Node -- ----------------------------- function Is_Greater_Element_Node (Left : Element_Type; Right : Node_Access) return Boolean is begin -- e > node same as node < e return Right.Element.all < Left; end Is_Greater_Element_Node; -------------------------- -- Is_Less_Element_Node -- -------------------------- function Is_Less_Element_Node (Left : Element_Type; Right : Node_Access) return Boolean is begin return Left < Right.Element.all; end Is_Less_Element_Node; ----------------------- -- Is_Less_Node_Node -- ----------------------- function Is_Less_Node_Node (L, R : Node_Access) return Boolean is begin return L.Element.all < R.Element.all; end Is_Less_Node_Node; --------------- -- Is_Subset -- --------------- function Is_Subset (Subset : Set; Of_Set : Set) return Boolean is begin return Set_Ops.Is_Subset (Subset => Subset.Tree, Of_Set => Of_Set.Tree); end Is_Subset; ------------- -- Iterate -- ------------- procedure Iterate (Container : Set; Item : Element_Type; Process : not null access procedure (Position : Cursor)) is procedure Process_Node (Node : Node_Access); pragma Inline (Process_Node); procedure Local_Iterate is new Element_Keys.Generic_Iteration (Process_Node); ------------------ -- Process_Node -- ------------------ procedure Process_Node (Node : Node_Access) is begin Process (Cursor'(Container'Unrestricted_Access, Node)); end Process_Node; T : Tree_Type renames Container.Tree'Unrestricted_Access.all; Busy : With_Busy (T.TC'Unrestricted_Access); -- Start of processing for Iterate begin Local_Iterate (T, Item); end Iterate; procedure Iterate (Container : Set; Process : not null access procedure (Position : Cursor)) is procedure Process_Node (Node : Node_Access); pragma Inline (Process_Node); procedure Local_Iterate is new Tree_Operations.Generic_Iteration (Process_Node); ------------------ -- Process_Node -- ------------------ procedure Process_Node (Node : Node_Access) is begin Process (Cursor'(Container'Unrestricted_Access, Node)); end Process_Node; T : Tree_Type renames Container.Tree'Unrestricted_Access.all; Busy : With_Busy (T.TC'Unrestricted_Access); -- Start of processing for Iterate begin Local_Iterate (T); end Iterate; function Iterate (Container : Set) return Set_Iterator_Interfaces.Reversible_Iterator'Class is S : constant Set_Access := Container'Unrestricted_Access; begin -- The value of the Node component influences the behavior of the First -- and Last selector functions of the iterator object. When the Node -- component is null (as is the case here), this means the iterator -- object was constructed without a start expression. This is a complete -- iterator, meaning that the iteration starts from the (logical) -- beginning of the sequence of items. -- Note: For a forward iterator, Container.First is the beginning, and -- for a reverse iterator, Container.Last is the beginning. return It : constant Iterator := (Limited_Controlled with S, null) do Busy (S.Tree.TC); end return; end Iterate; function Iterate (Container : Set; Start : Cursor) return Set_Iterator_Interfaces.Reversible_Iterator'Class is S : constant Set_Access := Container'Unrestricted_Access; begin -- It was formerly the case that when Start = No_Element, the partial -- iterator was defined to behave the same as for a complete iterator, -- and iterate over the entire sequence of items. However, those -- semantics were unintuitive and arguably error-prone (it is too easy -- to accidentally create an endless loop), and so they were changed, -- per the ARG meeting in Denver on 2011/11. However, there was no -- consensus about what positive meaning this corner case should have, -- and so it was decided to simply raise an exception. This does imply, -- however, that it is not possible to use a partial iterator to specify -- an empty sequence of items. if Start = No_Element then raise Constraint_Error with ""Start position for iterator equals No_Element""; end if; if Start.Container /= Container'Unrestricted_Access then raise Program_Error with ""Start cursor of Iterate designates wrong set""; end if; pragma Assert (Vet (Container.Tree, Start.Node), ""Start cursor of Iterate is bad""); -- The value of the Node component influences the behavior of the First -- and Last selector functions of the iterator object. When the Node -- component is non-null (as is the case here), it means that this is a -- partial iteration, over a subset of the complete sequence of -- items. The iterator object was constructed with a start expression, -- indicating the position from which the iteration begins. Note that -- the start position has the same value irrespective of whether this is -- a forward or reverse iteration. return It : constant Iterator := (Limited_Controlled with S, Start.Node) do Busy (S.Tree.TC); end return; end Iterate; ---------- -- Last -- ---------- function Last (Container : Set) return Cursor is begin if Container.Tree.Last = null then return No_Element; end if; return Cursor'(Container'Unrestricted_Access, Container.Tree.Last); end Last; function Last (Object : Iterator) return Cursor is begin -- The value of the iterator object's Node component influences the -- behavior of the Last (and First) selector function. -- When the Node component is null, this means the iterator object was -- constructed without a start expression, in which case the (reverse) -- iteration starts from the (logical) beginning of the entire sequence -- (corresponding to Container.Last, for a reverse iterator). -- Otherwise, this is iteration over a partial sequence of items. When -- the Node component is non-null, the iterator object was constructed -- with a start expression, that specifies the position from which the -- (reverse) partial iteration begins. if Object.Node = null then return Object.Container.Last; else return Cursor'(Object.Container, Object.Node); end if; end Last; ------------------ -- Last_Element -- ------------------ function Last_Element (Container : Set) return Element_Type is begin if Container.Tree.Last = null then raise Constraint_Error with ""set is empty""; end if; pragma Assert (Container.Tree.Last.Element /= null); return Container.Tree.Last.Element.all; end Last_Element; ---------- -- Left -- ---------- function Left (Node : Node_Access) return Node_Access is begin return Node.Left; end Left; ------------ -- Length -- ------------ function Length (Container : Set) return Count_Type is begin return Container.Tree.Length; end Length; ---------- -- Move -- ---------- procedure Move is new Tree_Operations.Generic_Move (Clear); procedure Move (Target : in out Set; Source : in out Set) is begin Move (Target => Target.Tree, Source => Source.Tree); end Move; ---------- -- Next -- ---------- function Next (Position : Cursor) return Cursor is begin if Position = No_Element then return No_Element; end if; pragma Assert (Vet (Position.Container.Tree, Position.Node), ""bad cursor in Next""); declare Node : constant Node_Access := Tree_Operations.Next (Position.Node); begin if Node = null then return No_Element; end if; return Cursor'(Position.Container, Node); end; end Next; procedure Next (Position : in out Cursor) is begin Position := Next (Position); end Next; function Next (Object : Iterator; Position : Cursor) return Cursor is begin if Position.Container = null then return No_Element; end if; if Position.Container /= Object.Container then raise Program_Error with ""Position cursor of Next designates wrong set""; end if; return Next (Position); end Next; ------------- -- Overlap -- ------------- function Overlap (Left, Right : Set) return Boolean is begin return Set_Ops.Overlap (Left.Tree, Right.Tree); end Overlap; ------------ -- Parent -- ------------ function Parent (Node : Node_Access) return Node_Access is begin return Node.Parent; end Parent; -------------- -- Previous -- -------------- function Previous (Position : Cursor) return Cursor is begin if Position = No_Element then return No_Element; end if; pragma Assert (Vet (Position.Container.Tree, Position.Node), ""bad cursor in Previous""); declare Node : constant Node_Access := Tree_Operations.Previous (Position.Node); begin if Node = null then return No_Element; end if; return Cursor'(Position.Container, Node); end; end Previous; procedure Previous (Position : in out Cursor) is begin Position := Previous (Position); end Previous; function Previous (Object : Iterator; Position : Cursor) return Cursor is begin if Position.Container = null then return No_Element; end if; if Position.Container /= Object.Container then raise Program_Error with ""Position cursor of Previous designates wrong set""; end if; return Previous (Position); end Previous; ------------------- -- Query_Element -- ------------------- procedure Query_Element (Position : Cursor; Process : not null access procedure (Element : Element_Type)) is begin if Position.Node = null then raise Constraint_Error with ""Position cursor equals No_Element""; end if; if Position.Node.Element = null then raise Program_Error with ""Position cursor is bad""; end if; pragma Assert (Vet (Position.Container.Tree, Position.Node), ""bad cursor in Query_Element""); declare T : Tree_Type renames Position.Container.Tree; Lock : With_Lock (T.TC'Unrestricted_Access); begin Process (Position.Node.Element.all); end; end Query_Element; ---------- -- Read -- ---------- procedure Read (Stream : not null access Root_Stream_Type'Class; Container : out Set) is function Read_Node (Stream : not null access Root_Stream_Type'Class) return Node_Access; pragma Inline (Read_Node); procedure Read is new Tree_Operations.Generic_Read (Clear, Read_Node); --------------- -- Read_Node -- --------------- function Read_Node (Stream : not null access Root_Stream_Type'Class) return Node_Access is Node : Node_Access := new Node_Type; begin Node.Element := new Element_Type'(Element_Type'Input (Stream)); return Node; exception when others => Free (Node); -- Note that Free deallocates elem too raise; end Read_Node; -- Start of processing for Read begin Read (Stream, Container.Tree); end Read; procedure Read (Stream : not null access Root_Stream_Type'Class; Item : out Cursor) is begin raise Program_Error with ""attempt to stream set cursor""; end Read; procedure Read (Stream : not null access Root_Stream_Type'Class; Item : out Constant_Reference_Type) is begin raise Program_Error with ""attempt to stream reference""; end Read; --------------------- -- Replace_Element -- --------------------- procedure Replace_Element (Tree : in out Tree_Type; Node : Node_Access; Item : Element_Type) is begin if Item < Node.Element.all or else Node.Element.all < Item then null; else TE_Check (Tree.TC); declare X : Element_Access := Node.Element; -- The element allocator may need an accessibility check in the -- case the actual type is class-wide or has access discriminants -- (see RM 4.8(10.1) and AI12-0035). pragma Unsuppress (Accessibility_Check); begin Node.Element := new Element_Type'(Item); Free_Element (X); end; return; end if; Tree_Operations.Delete_Node_Sans_Free (Tree, Node); -- Checks busy-bit Insert_New_Item : declare function New_Node return Node_Access; pragma Inline (New_Node); procedure Insert_Post is new Element_Keys.Generic_Insert_Post (New_Node); procedure Unconditional_Insert is new Element_Keys.Generic_Unconditional_Insert (Insert_Post); -------------- -- New_Node -- -------------- function New_Node return Node_Access is -- The element allocator may need an accessibility check in the -- case the actual type is class-wide or has access discriminants -- (see RM 4.8(10.1) and AI12-0035). pragma Unsuppress (Accessibility_Check); begin Node.Element := new Element_Type'(Item); -- OK if fails Node.Color := Red_Black_Trees.Red; Node.Parent := null; Node.Left := null; Node.Right := null; return Node; end New_Node; Result : Node_Access; X : Element_Access := Node.Element; -- Start of processing for Insert_New_Item begin Unconditional_Insert (Tree => Tree, Key => Item, Node => Result); pragma Assert (Result = Node); Free_Element (X); -- OK if fails end Insert_New_Item; end Replace_Element; procedure Replace_Element (Container : in out Set; Position : Cursor; New_Item : Element_Type) is begin if Position.Node = null then raise Constraint_Error with ""Position cursor equals No_Element""; end if; if Position.Node.Element = null then raise Program_Error with ""Position cursor is bad""; end if; if Position.Container /= Container'Unrestricted_Access then raise Program_Error with ""Position cursor designates wrong set""; end if; pragma Assert (Vet (Container.Tree, Position.Node), ""bad cursor in Replace_Element""); Replace_Element (Container.Tree, Position.Node, New_Item); end Replace_Element; --------------------- -- Reverse_Iterate -- --------------------- procedure Reverse_Iterate (Container : Set; Item : Element_Type; Process : not null access procedure (Position : Cursor)) is procedure Process_Node (Node : Node_Access); pragma Inline (Process_Node); procedure Local_Reverse_Iterate is new Element_Keys.Generic_Reverse_Iteration (Process_Node); ------------------ -- Process_Node -- ------------------ procedure Process_Node (Node : Node_Access) is begin Process (Cursor'(Container'Unrestricted_Access, Node)); end Process_Node; T : Tree_Type renames Container.Tree'Unrestricted_Access.all; Busy : With_Busy (T.TC'Unrestricted_Access); -- Start of processing for Reverse_Iterate begin Local_Reverse_Iterate (T, Item); end Reverse_Iterate; procedure Reverse_Iterate (Container : Set; Process : not null access procedure (Position : Cursor)) is procedure Process_Node (Node : Node_Access); pragma Inline (Process_Node); procedure Local_Reverse_Iterate is new Tree_Operations.Generic_Reverse_Iteration (Process_Node); ------------------ -- Process_Node -- ------------------ procedure Process_Node (Node : Node_Access) is begin Process (Cursor'(Container'Unrestricted_Access, Node)); end Process_Node; T : Tree_Type renames Container.Tree'Unrestricted_Access.all; Busy : With_Busy (T.TC'Unrestricted_Access); -- Start of processing for Reverse_Iterate begin Local_Reverse_Iterate (T); end Reverse_Iterate; ----------- -- Right -- ----------- function Right (Node : Node_Access) return Node_Access is begin return Node.Right; end Right; --------------- -- Set_Color -- --------------- procedure Set_Color (Node : Node_Access; Color : Color_Type) is begin Node.Color := Color; end Set_Color; -------------- -- Set_Left -- -------------- procedure Set_Left (Node : Node_Access; Left : Node_Access) is begin Node.Left := Left; end Set_Left; ---------------- -- Set_Parent -- ---------------- procedure Set_Parent (Node : Node_Access; Parent : Node_Access) is begin Node.Parent := Parent; end Set_Parent; --------------- -- Set_Right -- --------------- procedure Set_Right (Node : Node_Access; Right : Node_Access) is begin Node.Right := Right; end Set_Right; -------------------------- -- Symmetric_Difference -- -------------------------- procedure Symmetric_Difference (Target : in out Set; Source : Set) is begin Set_Ops.Symmetric_Difference (Target.Tree, Source.Tree); end Symmetric_Difference; function Symmetric_Difference (Left, Right : Set) return Set is Tree : constant Tree_Type := Set_Ops.Symmetric_Difference (Left.Tree, Right.Tree); begin return Set'(Controlled with Tree); end Symmetric_Difference; ------------ -- To_Set -- ------------ function To_Set (New_Item : Element_Type) return Set is Tree : Tree_Type; Node : Node_Access; pragma Unreferenced (Node); begin Insert_Sans_Hint (Tree, New_Item, Node); return Set'(Controlled with Tree); end To_Set; ----------- -- Union -- ----------- procedure Union (Target : in out Set; Source : Set) is begin Set_Ops.Union (Target.Tree, Source.Tree); end Union; function Union (Left, Right : Set) return Set is Tree : constant Tree_Type := Set_Ops.Union (Left.Tree, Right.Tree); begin return Set'(Controlled with Tree); end Union; ----------- -- Write -- ----------- procedure Write (Stream : not null access Root_Stream_Type'Class; Container : Set) is procedure Write_Node (Stream : not null access Root_Stream_Type'Class; Node : Node_Access); pragma Inline (Write_Node); procedure Write is new Tree_Operations.Generic_Write (Write_Node); ---------------- -- Write_Node -- ---------------- procedure Write_Node (Stream : not null access Root_Stream_Type'Class; Node : Node_Access) is begin Element_Type'Output (Stream, Node.Element.all); end Write_Node; -- Start of processing for Write begin Write (Stream, Container.Tree); end Write; procedure Write (Stream : not null access Root_Stream_Type'Class; Item : Cursor) is begin raise Program_Error with ""attempt to stream set cursor""; end Write; procedure Write (Stream : not null access Root_Stream_Type'Class; Item : Constant_Reference_Type) is begin raise Program_Error with ""attempt to stream reference""; end Write; end Ada.Containers.Indefinite_Ordered_Multisets; ",12176,True,2701.7912088663466,median ":author: hhaim :email: ifndef::backend-docbook[] ++++++++++++++










++++++++++++++ include::trex_ga.asciidoc[] :github_stl_path: https://github.com/cisco-system-traffic-generator/trex-core/tree/master/scripts/stl :github_stl_examples_path: https://github.com/cisco-system-traffic-generator/trex-core/tree/master/scripts/automation/trex_control_plane/interactive/trex/examples/stl == TRex release notes == endif::backend-docbook[] ifdef::backend-docbook[] == TRex release notes == :numbered: endif::backend-docbook[] == Release 2.47 == * ASTF: supports interactive mode. STL and ASTF works with the same framework. common features are: ** L2 emulation (arp/ipv6/l3/ping/vlan/scan6 etc) ** Port management (e.g. link attribute) ** Network namespace ** Capture/service mode ** Plugin services ** Console/TUI/API ** Not supported yet: cluster mode * The ASTF batch mode is planned to be deprecated .Start ASTF in interactive mode [source,bash] ------------------- sudo ./t-rex-64 -i --astf ------------------- .Console [source,bash] ------------------- ./trex-console -s [server-ip] ----------------- .From Console [source,bash] ------------------- trex>start -f astf/http_simple.py -m 1000 -d 1000 -l 1000 trex>tui trex>[press] t/l for astf statistics and latency trex>stop ------------------ * ASTF API docomentation is here link:cp_astf_docs/api/client_code.html[python_astf_api] link:trex_astf.html#_tutorial_python_automation_v2_47_and_up[automation] * STL: add stream pinning to core see link:trex_stateless.html#_tutorial_core_pinning[core_pinning] === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-540[trex-540] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-538[trex-538] == Release 2.46 == * ASTF: add per_core_distribution field see link:cp_astf_docs/_modules/trex/astf/trex_astf_profile.html#ASTFIPGenDist[per_core_distribution] * Extend astf-sim to replay pcap file for STF mode link:https://github.com/cisco-system-traffic-generator/trex-core/issues/156[github-256] * Amazon DPDK ENA driver fix * Stateless GUI can build trex_cfg.yaml file * Support Python ZMQ 32bit binding for x86-32bit platforms * fix scapy igmp3 for python-3 * eWLC plugin for AP scale tests === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-536[trex-536] * link:https://github.com/cisco-system-traffic-generator/trex-core/issues/150[github-150] * link:https://github.com/cisco-system-traffic-generator/trex-core/issues/123[github-123] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-192[trex-192] == Release 2.45 == * Upgrade to DPDK 18.08 * Latency dummy stream does not consume pgid * Server/Python client use the same C-ZMQ share object. * Simplified Python ZMQ binding * Speedup service mode using server side ZMQ IPC == Release 2.44 == * Upgrade to DPDK 18.05 * Stateless: allow ""start"" when port is unresolved and all streams have explicit dest MAC. * mlx5 can compile with Ubuntu distro === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-533[trex-533] == Release 2.43 == * Client Python library consolidation STL/ASTF ** New code should use: + ---- from trex.stl.api import * ---- ** For backward compatability old code still works: + ---- from trex_stl_lib.api import * ---- ** Interactive ASTF connects to the console, sending traffic/collecting stats via new lib is WIP. * Mellanox with OFED 4.3.1 offers newer FW with significantly better RX speed (due to faster dropping). + Bidirectional 64B packets RX is \\~132MPPS from 2 ports (compared to ~38MPPS with older OFED/FW) * TODO: describe FE instruction ""list"" === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-531[trex-531] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-532[trex-532] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-510[trex-510] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-528[trex-528] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-529[trex-529] == Release 2.41 == * ASTF ** Add support for non-blocking `send`, for better eflow performance (30Gb/sec per one flow) see http_eflow2.py profile ** Fix TCP fast recovery. dupack counter wasn't cleard * minor bug fixes == Release 2.41 == * ASTF ** Add support for non-blocking `send`, for better eflow performance (30Gb/sec per one flow) see http_eflow2.py profile ** Fix TCP fast recovery. dupack counter wasn't cleard * minor bug fixes == Release 2.40 == * Search for Python2/3 in start-up scripts * Add Amazon ENA DPDK driver - there are reports that the performance is not that good. * Fix STL Console history issue * ARM compilation issue fix (BPF) * Add ASTF example profiles (e.g elephant flow) === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-526[trex-526] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-525[trex-525] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-524[trex-524] == Release 2.39 == * ASTF multi-core support see link:trex_astf.html#_multi_core_support[astf] can reach 200gb/sec with TCP/UDP stack === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-428[trex-428] == Release 2.38 == * Dummy port support. (more info in link:trex_manual.html#_dummy_ports[manual]) + They can solve 2 issues: ** Odd number of interfaces (e.g. single port) ** Performance degradation when adjacent interfaces belong to different NUMAs. * Advance Stateful (ASTF) ** Support L7 emulation on top of UDP (e.g. DNS/RTP Video) ** Faster script to convert to JSON (Scapy->dpkt) * Napatech benchmark on UCS240 link:trex_appendix_napatech.html#_performance_benchmark[napatech_benchmark] === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-500[trex-500] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-521[trex-521] == Release 2.37 == * Low footprint support. Resource require with this mode 1 thread and ~500MB RAM. More info in link:trex_manual.html#_low_end_machines[manual] * Option to work with Linux interfaces (raw socket mode,--vdev/af_packet). More info in link:trex_manual.html#_linux_interfaces[manual] Example [source,bash] ---- - port_limit : 2 version : 2 low_end : true #<1> interfaces : [""veth0"", ""veth1""] #<2> port_info : # set eh mac addr - ip : 1.1.1.1 default_gw : 2.2.2.2 - ip : 2.2.2.2 default_gw : 1.1.1.1 ---- <1> low footprint <2> Linux interfaces * Above options introduced for supporting Cisco VIRL and Cisco IOx. * Docker hub image for simple tutorials using veth/low footprint link:trex_vm_manual.html[Docker] * ARM build support (works with virio for now) * ASTF, simulator can have `-e` option to debug the emulation layer == Release 2.36 == * ASTF ** Remove ASTFTCPInfo object from the profile (*NOT* backward compatible) ** Add support for scheduler.rampup_sec tunable ** Add support for scheduler.accurate tunable - accurate traffic generation for low rates(<20gbps) important for ASA ** Add --lro-disable CLI ** Add profiles that are Spirent compatible * ASTF/STF - add promiscuous mode using ""--prom"" CLI * Support CX-3 Mellanox cards * Update Napatech driver * STL ** HLTAPI bug fixes ** fix XL710 VF counters crash ** Add IPV6 ND service === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-278[trex-278] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-514[trex-514] == Release 2.35 == * ASTF L7 emulation enhancements. ** Ability to control the L7 application with more commands (e.g. random delay in the server,elephant flow, syn-ack-rst flow) see link:trex_astf.html#_tutorial_l7_emulation_fin_ack_fin_ack[l7-emulation-example] and link:cp_astf_docs/api/profile_code.html#astfprogram-class[l7-program] ** Ability to limit the total number of generated flows using `limit` directive. For example, to create a limited number of elephant flows. ** profile-tunable: ability to tune the profile using key-val input see link: trex_astf.html#_tutorial_profile_cli_tunable[l7-cli-tunable] ** Refactor the code for ASTF interactive support ** Fix TCP crash in case of corrupted packet * Napatech support for DPDK 17.11 * Stateless, Fix ipv6.scan6 crash in case of ""ff02::1"" addr (VPP use case) == Release 2.34 == * Mellanox Cx-4/5 ** Fix stability issue link:https://trex-tgn.cisco.com/youtrack/issue/trex-507[trex-507] ** Workaround to link:https://trex-tgn.cisco.com/youtrack/issue/trex-481[trex-481] * Stateless ** Add support for update/pause/resume per stream-id see link:trex_stateless.html#_per_stream_operations[per stream operation] ** Fix core pinning with latency stream. link:https://trex-tgn.cisco.com/youtrack/issue/trex-428[trex-428] * Advance Stateful - add client cluster mode support === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-428[trex-428] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-507[trex-507] thanks to Mellanox DPDK team == Release 2.33 == * Upgrade to DPDK 17.11 ** Better XXV710 support ** Mellanox CX-4/CX-5 big performance improvement (CX-5, Tx=149MPPS/Rx=120MPPS at 64B). ** A small degradation in XL710 Stateless performance WARNING: For Mellanox CX-5/4 there is a need to upgrade the distro to CentOs 7.4 and OFED to 4.2.1. This new OFED version does *not* work with older TRex versions see link:trex_manual.html#ofed_upgrade[ofed upgrade procedure] === Known issues: === * Mellanox CX-4/CX-5 stability issues see link:https://trex-tgn.cisco.com/youtrack/issue/trex-507[trex-507] == Release 2.32 == * Advance Stateful (ASTF) ** Tunables support. Tunables is a mechanism to tune the behavior of ASTF traffic profile see here link:trex_astf.html#tunable_tcp_mss[tunables] ** Cisco VIC support TSO now * Support gcc 7.x/6.x and sanitizer * Stateless ** Improve performance (mbuf-refcnt locality) == Release 2.31 == * Stateless ** Console - added option to save loaded streams as Python profile (stream command from the Console) ** Console - ability to load JSON/YAML from start command (e.g. `start -f stl/gui_example.yaml -m 100kpps --port 0`) * TCP some performance improvements (up to 5MPPS/core) ** Tune TCP timers for traffic generation case (e.g. 2MSL/keepalive is shorter) ** Add support to RFC6928 (add support for initwnd and set it by default to 10). A way to tune all the TCP parameters (including this one) will be given from the traffic profile. ** Protect TRex ASTF resource (e.g. overflow in active flows) ** General hardening ** Support client or server mode see link:trex_astf.html#_client_server_only_mode[client_server_only_mode] * Refactor the code to support ASTF in interactive mode (both STL and STF will work with the same RPC framework) * Increase the TX queue for all drivers by default - less probability for queue_full in high rates === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-495[trex-495] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-491[trex-491] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-486[trex-486] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-492[trex-492] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-485[trex-485] == Release 2.30 == * Advance Stateful (ASTF) with scalable TCP support ** Support all SFR profile with TCP flows ** Mellanox driver issue workaround see here link:https://trex-tgn.cisco.com/youtrack/issue/trex-481[trex-481] ** Hardening ** Add full simulation support using `./astf-sim --full` see here link:trex_astf.html[ASTF mode] * Wireless AP/Station emulation plugin for WLC testing. ** Improve performance considerably ** Update documentation link:trex_stateless_wlc_bench.html[WLC] * Support Napatech NIC (100Gb@64B line-rate) * Stateless ** Full Stream object are return from the client ** Old YAML profile support was removed === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-483[trex-483] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-480[trex-480] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-472[trex-472] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-475[trex-475] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-461[trex-461] == Release 2.29 == * Preliminary version with Advance Stateful (ASTF) with scalable TCP support see here link:trex_astf.html[ASTF mode] * Wireless AP/Station emulation plugin for WLC testing see link:trex_stateless_wlc_bench.html[WLC] * General ** IPv4 software checksum was wrong for 0.01% of the cases - found by link:https://wiki.fd.io/view/CSIT[CSIT group] === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-469[trex-469] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-464[trex-464] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-463[trex-463] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-462[trex-462] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-460[trex-460] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-457[trex-457] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-435[trex-435] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-453[trex-453] == Release 2.28 == * Cisco FirePOWER/ASA Stateful friendly ** Fix TCP/UDP by default in case DPDK driver support it (--checksum-offload is deprecated, new switch to disable this) ** start client source port is random- better distribution to queues ** Stateful performance degradation 5-9% due to checksum offload * Stateless ** Add capture mode information in JSON ** Fix behaviour of clear_flow_stats and clear_latency_stats args in stateless clear_stats API ** BPF-JIT filter support for traffic capture ** services are using BPF filter for better performance ** Report 0 rate immediately after stopping the flow stat stream ** Fix HLTAPI per-stream stats (keys of line utilization in pg_id stats got removed) ** Add openssl share object for DTLS/CAPWAP services * General ** Fix dpdk_setup_ports.py fails with Python 3 ** Fix latency in case cluster configuration === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-451[trex-451] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-447[trex-447] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-439[trex-439] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-446[trex-446] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-445[trex-445] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-443[trex-443] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-440[trex-440] == Release 2.27 == * Support 802.1Q and 802.1AD (QinQ) for Stateless services and port config see link:cp_stl_docs/api/client_code.html#trex_stl_lib.trex_stl_client.STLClient.set_l3_mode[l3 configuration with vlan] and link:{github_stl_examples_path}/stl_multiple_arps.py[stl_ndr_bench_tool.py example] * Remove async RPC flow-stats support. Only new sync RPC API is supported from this version. The implication is that only new GUI version (>v3.2 will work) ** refactor Python client side and fix some multi-user crash/bugs WARNING: Only GUI with version greater than v3. 2 will work with this version === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-432[trex-432] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-431[trex-431] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-427[trex-427] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-376[trex-376] == Release 2.26 == * get_pgid RPC command - change the JSON format. v2.25 client will not work with v2.26 server. Done for better JSON compatibility == Release 2.25 == * Added new stateless Python API, link:cp_stl_docs/api/client_code.html#get-pgid-stats[""get_pgid_stats""]. New API brings flow statistics and latency info for given list of packet group IDs by doing synchronous call to the server. This is opposed to the old API ""get_stats"" which brings information saved in the client, and updated every 0.5 second by asynchronous message from the server. This way, we can scale the number of pgids and the client can consume only the information it really needs, when it needs it, so statistics for more flows can be supported. **Notice** that in some future release, pgid info will not be supported using the old ""get_stats"" any more. Example for using the new API can be found in link:{github_stl_examples_path}/stl_flow_latency_stats.py[stl_flow_latency_stats.py] WARNING: In some future release, per stream statistics will not be reported using the old `get_stats` API due to scale issue, please move to the new API * Fix mlx5 driver crash/corruption (bug exits from version v2.18) * Fix Python client race condition in case of fast connect/disconnect * Remove Enum from Python packages for Python 3.5 backward compatibility * Preliminary RFC 2544 example link:{github_stl_examples_path}/stl_ndr_bench_tool.py[stl_ndr_bench_tool.py] === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-420[trex-420] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-405[trex-405] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-415[trex-415] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-416[trex-416] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-413[trex-413] == Release 2.24 == * Add support for Mellanox CX-3 VF * Better way to map DPDK ports to TRex ports [source,python] ---- * In order interfaces : [""03:00.0"",""03:00.1"",""82:00.0"",""82:00.1""] * Out order interfaces : [""03:00.1"",""03:00.0"",""82:00.1"",""82:00.0""] * Out order interfaces : [""03:00.1"",""82:00.0""] * CX3 example : each PCI has 2 ports /1 is sub interface interfaces : [""03:00.0/1"",""03:00.0/0""] ---- * L2 emulation plugins framework see here link:trex_stateless.html#_services[services framework] example for DHCP/ARP/ICMP * 2K mbuf in Rx side --> less memory is needed * Fix Docker uid issue * Better errors in case of slow RTC network === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-449[trex-449] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-448[trex-448] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-295[trex-295] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-413[trex-413] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-408[trex-408] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-398[trex-398] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-372[trex-372] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-402[trex-402] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-400[trex-400] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-371[trex-371] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-397[trex-397] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-393[trex-393] == Release 2.23 == * Support up to 1023 per stream statistics ids in software mode and with mlx5 driver * Service mode works better with multi-user * i40e - disable LLDP === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-381[trex-381] == Release 2.22 == * hotfix for software mode == Release 2.21 == * New command line arguments. `--no-hw-flow-stat`, and `--software`, for changing behavior of stateless per stream flow statistics and latency features. See detail link:trex_manual.html#_command_line_options[here]. * Support for QinQ packets in stateless per port statistics (if using new `--software` command line arg). * Support for all types of VIC cards (including ones will old firmware), using `--software`. Since we do not have all cards in our lab, we could not test all of them. Will be glad for feedback on this (good or bad). * GUI : packet builder scapy server fix for cases of packets with variable length fields (e.g. DNS) * ConnectX-4/5 support VF mode * Stateless STLVmFlowVarRepeatableRandom instruction - fix typo, add another instruction with the right name * Support vfio-pci in case it exists in the kernel (instead of igb_uio) to support Docker container without the need to compile the kernel module * Capture TRex internal generated packets (e.g. ARP/Ping) * Support older Linux distribution for Python Client code (ZMQ share object can be loaded on older machine) * Performance trend report information is taken from ElasticSearch instead of Google analytics === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-370[trex-370] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-373[trex-373] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-375[trex-375] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-377[trex-377] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-378[trex-378] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-369[trex-369] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-368[trex-368] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-366[trex-366] == Release 2.20 == * hotfix release add mlx-dpdk share objects to the package == Release 2.19 == * mlx5 dpdk driver works only with OFED 4.0 (OFED 3.4 will not be supported) ** ConnectX-5 should work now * VirtualBox with E1000 (Our Tutorial OVA) get latency packets correctly * fix NAT randomization mode * Ability to build without mlx5-dpdk driver using ./configure `--no-mlx` * RX thread CPU% is not 100% all the time from this version * Better handling of latency packets (case of fast start/stop) === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-295[trex-295] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-364[trex-364] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-361[trex-361] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-361[trex-361] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-362[trex-362] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-360[trex-360] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-359[trex-359] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-358[trex-358] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-354[trex-354] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-350[trex-350] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-355[trex-355] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-352[trex-352] WARNING: you must upgrade to OFED 4.0 even with ConnectX-4 cards == Release 2.18 == * DPDK 17.02 ** Should supports ConnectX-5 but has an OFED issue see link:https://trex-tgn.cisco.com/youtrack/issue/trex-353[trex-353] ** ixgbe SR-IOV works * Ability to add VLAN per direction link:trex_manual.html#_vlan_dot1q_support[vlan_dot1q_support] * Stateless packet capture - ability to capture tx side * mlx5 dpdk driver is share object. Reduce image OFED libs dependency === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-344[trex-344] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-269[trex-269] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-339[trex-339] == Release 2.17 == * hotfix release === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-342[trex-342] == Release 2.16 == * IPv6 console basic support (link:trex_stateless.html#_ipv6_nd_client[ipv6]): ** scan6 function to search for IPv6-enabled neighbors ** ping can be used with IPv6 addresses to ping nearby devices * Stateless Rx capturing mode support link:trex_stateless.html#_packet_capturing[capturing] * Stateless support functional testing / send packet /expect RX packet etc link:trex_stateless.html#_functional_tutorials[functional] === Video Tutorials (Beta) : === Our first video tutorial on YouTube: ifdef::backend-xhtml11[] ++++++++++++++++++ ++++++++++++++++++ endif::backend-xhtml11[] The Tutorial shows a little bit of our new packet capture ability which was released on v2.16 === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-258[trex-258] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-337[trex-337] == Release 2.15 == * XL710/X710 VF (SR-IOV) mode works better * 599 VF mode is *not* supported === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-333[trex-333] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-331[trex-331] == Release 2.14 == * Another performance improvement in Stateful case with high active flows. There is less burstiness * Scapy server - warning in case of permissions errors * Maximum supported ports are 16 (instead of 12) * ConnectX-4 DPDK driver is based on 16.11 (from 16.07) - better performance is some cases * Early support for Intel XL710/X710/599 VF support link:trex_manual.html#_configure_linux_to_use_vf_on_intel_x710_and_82599_nics[sr_iov] * Fix Cluster mode breakage (v2.12-v2.13) * Stateless GUI v3.0 works with this version === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-319[trex-319] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-322[trex-322] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-326[trex-326] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-330[trex-330] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-329[trex-329] == Release 2.13 == * Significantly improve performance and scale for stateful case with high active flows (70%-300% better) see here link:trex_manual.html#_more_active_flows[More active flows] * Stateful with low active repeatable flows - an optimization was removed, for example `cap2/imix_fast_1g.yaml`. users that want to get this in high performance are adviced to move to Stateles mode. Removing this support improved the common case. * Support NAT without IPv4.option and UDP flows- for ASA link:https://trex-tgn.cisco.com/youtrack/issue/trex-274[trex-274] * Scapy server is restart automatically - for future Stateless GUI link:https://trex-tgn.cisco.com/youtrack/issue/trex-291[trex-291] * Add minimum ipg for remote pcap link:https://trex-tgn.cisco.com/youtrack/issue/trex-281[trex-281] * Console port commands works on VIC and ConnectX-4 * RPC API version is 3.0 - New stateless GUI is required === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-317[trex-317] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-282[trex-282] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-190[trex-190] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-279[trex-279] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-313[trex-313] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-312[trex-312] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-310[trex-310] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-191[trex-191] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-306[trex-306] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-234[trex-234] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-308[trex-308] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-283[trex-283] == Release 2.12 == * Improve support for Mellanox ConnectX-4 cards (100/50/25GbE) ** Only CentOs/RedHat 7.2 and up is supported due to OFED issues ** Improve 64Byte Stateleess performance * Cisco VIC is fully supported * Stateless L2/L3 configuration mode for ports - link:trex_stateless.html#_port_layer_mode_configuration[Port Layer Mode Configuration] * Stateless neighboring protocols infra and first protocols support/Python API - link:trex_stateless.html#_neighboring_protocols[Neighboring Protocols] * Stateful - ARP support for Client clustering mode (a.k.a APIC-EM) see here link:trex_manual.html#_client_clustering_configuration[Client Clustering] * Added Stateless performance trend document link:trex_analytics.html[trex performance trend] [IMPORTANT] ===================================== Change of behavior - trex config file (/trex/cfg.yaml) should include a distinct MAC address or distinct IP address. Not setting the port information : before v2.12 : src MAC addr == 00:00:00:01:00:00 v2.12 and up : src MAC addr == HW MAC address =========================== === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-257[trex-257] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-265[trex-265] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-280[trex-280] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-277[trex-277] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-278[trex-278] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-199[trex-199] == Release 2.11 == * Early support for Mellanox ConnectX-4 cards (100/50/25GbE) - based on contributions from Mellanox DPDK team see here for more info link:trex_manual.html#_mellanox_connectx_4_support[Mellanox ConnectX-4 Support] * Add support for Cisco VIC 1300 series adapter (40GbE)- based on Cisco VIC DPDK team see link:trex_manual.html#_cisco_vic_support[Cisco VIC Support] === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-268[trex-268] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-267[trex-267] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-195[trex-195] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-271[trex-271] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-255[trex-255] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-249[trex-249] == Release 2.10 == * Added support for IP based configuration files (As opposed to MAC based used until now), with the ability of TRex to send ARP requests for default gateway, and gratitues ARP for its own addresses. See link:trex_manual.html#_configuration_yaml_parameter_of_cfg_option[here] and link:trex_config_guide.html[here] for details. * Added commands/API to Stateless client/console: ** Getting extended counters of port for improved debug purposes. See example: link:trex_stateless.html#_stats[stats] ** Changing of port attributes and getting async feedback on the changed status. See example: link:trex_stateless.html#_portattr[portattr] * For developers - added/updated RPC commands (which can be used for GUI etc.): ** Getting system info added new options, for example description of interface: link:trex_rpc_server_spec.html#_get_system_info[get_system_info] ** Setting port attributes added new options: link:trex_rpc_server_spec.html#_setting_port_attributes[set_port_attr] ** Getting xstats names (can be polled once and then combined with updated values): link:trex_rpc_server_spec.html#_get_xstat_names[get_port_xstats_names] ** Getting xstats values: link:trex_rpc_server_spec.html#_get_xstat_values[get_port_xstats_values] === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-253[trex-253] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-212[trex-212] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-251[trex-251] == Release 2.09 == * Stateless, split to core algorithm is more accurate and simple see link:trex_stateless.html#_tutorial_field_engine_split_to_core[split_to_core] * Add repeatable random instruction see an example link:https://github.com/cisco-system-traffic-generator/trex-core/tree/master/scripts/stl/udp_1pkt_repeat_random.py[stl/udp_1pkt_repeat_random.py] link:cp_stl_docs/api/field_engine.html#stlvmflowvarrepetablerandom[repetable_random] and link:trex_rpc_server_spec.html#_repetable_random[repetable_random_spec] * Add TCP/UDP checksum fix instruction see an example link:https://github.com/cisco-system-traffic-generator/trex-core/tree/master/scripts/stl/syn_attack_fix_cs_hw.py[stl/syn_attack_fix_cs_hw.py] link:cp_stl_docs/api/field_engine.html#stlvmfixchecksumhw[fix checksum] and link:trex_rpc_server_spec.html#_fix_checksum_hw[fix_checksum_hw_spec] * Improve Stateless Field Engine (FE) performance * Support dual mode for push pcap/remote Python API. see here link:cp_stl_docs/api/client_code.html#trex_stl_lib.trex_stl_client.STLClient.push_remote[push_remote] and link:cp_stl_docs/api/client_code.html#trex_stl_lib.trex_stl_client.STLClient.push_pcap[push_pcap] Using this feature pcap can be splited to client/server ports * Add infra for L2 emulation support === Fixed issues: === * link:http://trex-tgn.cisco.com/youtrack/issue/trex-243[trex-243] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-247[trex-247] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-244[trex-244] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-249[trex-249] == Release 2.08 == * Scapy JSON-RPC server for GUI packet crafting, see link:trex_scapy_rpc_server.html[trex_scapy_rpc_server] * Client.start Python API supports Core mask - significantly improve the Stateless performance. link:cp_stl_docs/_modules/trex_stl_lib/trex_stl_client.html#STLClient.start[start API], and link:trex_stateless.html#_core_masking_per_interface[core_masking] * Upgrade the ./dpdk_setup_ports.py script. It simplifies the way to create first time *optimized* config file (/etc/trex_cfg.yaml). More info at the manual: link:trex_manual.html#_script_for_creating_config_file[Script for creating config file] [source,bash] ---- [bash]>sudo ./dpdk_setup_ports.py -t # show the list of ports [bash]>sudo ./dpdk_setup_ports.py -l # return DPDK interfaces to Linux (if there is proper Linux driver) [bash]>sudo ./dpdk_setup_ports.py -i # interactive creation of config file [bash]>sudo ./dpdk_setup_ports.py -c 03:00.0 03:00.1 -o /etc/trex_cfg.yaml # create optimum /etc/trex_cfg.yaml file ---- * Preliminary Cisco VIC support. Advanced Stateless/Stateful functionality is still not supported. * Enforce latest firmware for XL710/X710 (5.04) * Add a way to stop/close NICS at TRex termination (link would be down) `-close-at-end` * IPv6 XL710 ICMP packets are supported now === Fixed issues: === * link:http://trex-tgn.cisco.com/youtrack/issue/trex-240[trex-240] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-242[trex-242] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-246[trex-246] == Release 2.07 == * DPDK 16.07 * ASYNC ZMQ is compressed by default. It improves response time see link:http://trex-tgn.cisco.com/youtrack/issue/trex-232[trex-232] ** You will need to update the GUI * Support Ubuntu 16.01 - Stateful serverr is Python 3.0 and Python 3.5 for ZMQ library * XL710/X710 low latency was improved - see link:http://trex-tgn.cisco.com/youtrack/issue/trex-214[trex-214] * Support graceful shutdown command * Console - support L1 BPS using `-m 10bpsl1` see link:http://trex-tgn.cisco.com/youtrack/issue/trex-230[trex-230] * Improve TUI refresh time * Support IPV6 latency streams (support is available for all interface types except 82599) see link:trex_stateless.html#_tutorial_per_stream_latency_jitter_packet_errors[IPV6 latency] [IMPORTANT] ===================================== For XL710/X710 there is a need to upgrade the firmware to 5.04 (or later) ===================================== === Fixed issues: === * link:http://trex-tgn.cisco.com/youtrack/issue/trex-214[trex-214] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-223[trex-223] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-226[trex-226] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-224[trex-224] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-235[trex-235] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-236[trex-236] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-238[trex-238] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-233[trex-233] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-231[trex-231] == Release 2.06 == * Support APIC-EM scale Stateful VLAN/IP/MAC mapping. * TCP SYN Randomization learning support for advanced ASA stateful testing - link:trex_manual.html#_nat_support[here] and link:trex_manual.html#_trex_with_asa_5585[here] * Advanced to latest DPDK 16.07RC3 - fix some XL710 driver performance issues === Fixed issues: === * link:http://trex-tgn.cisco.com/youtrack/issue/trex-229[trex-229] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-227[trex-227] == Release 2.05 == === Fixed issues: === * link:http://trex-tgn.cisco.com/youtrack/issue/trex-221[trex-221] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-220[trex-220] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-219[trex-219] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-218[trex-218] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-217[trex-217] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-216[trex-216] == Release 2.04 == * Watchdog support * Ability to export core file * Optimized the case of Latency stream, Field Engine and 9K template packets === Fixed issues: === * XL710/X710 present high latency with 9K packets link:http://trex-tgn.cisco.com/youtrack/issue/trex-214[trex-214] * The latency seq number gets out of sync link:http://trex-tgn.cisco.com/youtrack/issue/trex-215[trex-215] * Port/Latency stats should be with FCS link:http://trex-tgn.cisco.com/youtrack/issue/trex-213[trex-213] * Stateless Unicode is not accepted for multiplier API see link:https://github.com/cisco-system-traffic-generator/trex-core/issues/15[github-issue15] == Release 2.03 == * More accurate stateless latency/more TUI support * Speedup DPDK XL710 fdir driver === Fixed issues: === * Disconnect issue link:http://trex-tgn.cisco.com/youtrack/issue/trex-210[trex-210] == Release 2.02 == * The python latency statistic is compatible to JSON for easy manipulation * Add latency minimum value Python API taken from histogram === Fixed issues: === * Fix corruption of mbuf in case of with high rate latency stream. == Release 2.01 == * First release of latency/jitter per stream see link:trex_stateless.html#_tutorial_per_stream_latency_jitter_packet_errors[here] * Ability to send server side pcap file - unlimited pcap file size see link:/cp_stl_docs/_modules/trex_stl_lib/trex_stl_client.html#STLClient.push_remote[here] and link:trex_stateless.html#_pcap_based_traffic_tutorials[PCAP tutorial] * Significatly improve performance for both Stateful and Stateless - in some cases up to x2 due to Scheduler/CPU utilization rewrite * CPU utilization estimation is done differently * Ability to significatly improve performance for Stateless profile with Field engine (up to x5, 22MPPS) see link:trex_stateless.html#_tutorial_field_engine_significantly_improve_performance[here] * Add documentation index link:index.html[index] * Fix documentation Table of Content javascript * Update Stateless presentation link:http://www.slideshare.net/HanochHaim/trex-realistic-traffic-generator-stateless-support[Statelss presenation] * Stateful Python server API - Add support for iterator of remote file for Stateful GUI === Fixed issues: === * Performance issue, link:http://trex-tgn.cisco.com/youtrack/issue/trex-207[trex-207] * Sporadic timeout on wait_on_traffic() API see link:http://trex-tgn.cisco.com/youtrack/issue/trex-209[trex-209] == Release 2.00 == * Console ** Support partial port acquire using new CLI switch `-a ACQUIRE` (first phase) ** Add tx/rx graphs * Python API: add an API for reading events as warning/errors * HLTAPI support for per stream stats * support VALN mode for per stream stats for 82599 using `--vlan` switch at server invocation * A peek into TRex stateless GUI version for evaluation still without many features like packet builder, advance packet builder, per stream stats link:https://www.dropbox.com/s/vs9gojtdc5ewv05/setupCiscoTrex1.96-SNAPSHOT.exe?dl=0[TRex Stateless GUI Download] ** Only pcap file packet builder is supported in this version image::images/trex_stl_gui.png[title=""TRex Stateless GUI"",align=""left"",width=600, link=""images/trex_stl_gui.png""] === Fixed issues: === * X710/XL710 per stream hardware stats ** link:http://trex-tgn.cisco.com/youtrack/issue/trex-199[trex-199] ** Fix issue of RX bytes ** Fix issue with mbuf leak * Packet Memory shortage fix link:http://trex-tgn.cisco.com/youtrack/issue/trex-197[trex-197] * Python Examples - move all examples to be 16.0.0.x/48.0.0.x for some refactor == Release 1.99 == * The Client package includes Console/examples * Client API verification mechanism. The client should match the server version range === Fixed issues: === * link:http://trex-tgn.cisco.com/youtrack/issue/trex-193[trex-193] * Python2/Python3 client API hardening * Per stream statistics in software hardening - add support for wait on rx packets == Release 1.98 == * Minor Console issue * [red]*Image is broken* see link:http://trex-tgn.cisco.com/youtrack/issue/trex-193[trex-193] == Release 1.97 == * Support pyATS with Python 3/32bit * Per stream statistic supported by software for I350/82559/VXNET3 * [red]*Image is broken* see link:http://trex-tgn.cisco.com/youtrack/issue/trex-193[trex-193] == Release 1.96 == * Support pyATS/32bit/Python2.x for TCL * Traffic profile direction/port directive works see link:draft_trex_stateless.html#_tutorial_advance_traffic_profile[here] * Documentation ** Add Python API documentation link:cp_stl_docs/index.html[here] ** Add pyATS2.0 support link:cp_stl_docs/index.html[here] ** Update per stream statistic documentation see link:draft_trex_stateless.html#_tutorial_per_stream_statistics[per stream statistic] ** Update HLTAPI arguments link:draft_trex_stateless.html#_hlt_supported_arguments_a_id_altapi_support_a[HLTAPI] === Fixed issues: === * Per stream statistic - Fix High speed of start/stop of giving zero in statistics * Fix E1000 DPDK driver prints with ESXi == Release 1.95 == * TUI support per stream stats (press s to get to this window) * per stream statistic API examples * Add Python API automatic documentation scripts * Fix issue with a packet smaller than 64 bytes === Known issue * High speed of start/stop of per stream stats give zero in statistics == Release 1.94 == * Fix Python API stop/sync issue. Now TX counters are synced in case of stop API * Improve performance of Python API, ~2000 cycles/sec of load/start/stop * Add per stream Tx/Rx statistics for XL710/X710 NICS work in flow-director hardware [source,python] ---- class STLS1(object): def get_streams (self, direction = 0): return [STLStream(packet = STLPktBuilder( pkt =""stl/yaml/udp_64B_no_crc.pcap""), mode = STLTXCont(pps=10), rx_stats = STLRxStats(user_id = 7)) <1> ] ---- <1> Configure this stream to be count on all RX ports as user_id=7 * Add HTLAPI full example (examples `examples/hlt_udp_simple.py`) * Add user manual draft for Stateless functionality link:draft_trex_stateless.html[here] == Release 1.93 == * Support port attribute API and Console command. See `$portattr -a --prom` * Support random seed per Stream attribute - see specification for more info * Add more sample/profiles (stl/hlt) from real use cases * Enhance Field Engine with new instructions * TUI now shows L1 and L2 bandwidth. Console support L1 and L2 and %% * Stream rate can be configured with PPS/bps_L1/bps_L2/port_percentage * Update Stateless JSON-RPC specification * HLT fixes and support split_by variable * First phase of per stream rx/tx statistic - XL710/X710 hardware support === Fixed issues: === * Fix some typo in Python API stl/example folder * Fix Field Engine IPv4 checksum issue with big packet size * Fix Field Engine issue with random variables * Fix `streams -a` crash * Fix X710 issue. Now return speed of 10gb instead of 40gb for Stateless port speed == Release 1.92 == ** Stream can set static Source/Destination MAC-Address as oppose to the default (TRex port from /etc/trex_config.yaml) [source,python] ---- def create_stream (self): base_pkt = Ether(src=""00:00:dd:dd:00:01"")/IP()/UDP() pad = max(0, size - len(base_pkt)) * 'x' ---- ** Stream support action_count. Loop of streams can end after action_count number. The push command uses this new feature to import pcap to streams and stop after x iteration. [source,python] ---- STLStream( self_start = False, name ='S2', packet = STLPktBuilder(pkt = base_pkt2/pad), mode = STLTXSingleBurst( pps = 10, total_pkts = 3 ), action_count = 2, # loop 2 times next = 'S0' ) ---- ** Support new Field-Engine instructions (variable with step and write with mask). See new sample folder and specification for more info [source,python] ---- def create_stream (self): # 2 MPLS label the internal with s=1 (last one) pkt = Ether()/MPLS(label=17,cos=1,s=0,ttl=255)/MPLS(label=0,cos=1,s=1,ttl=12)/IP()/UDP()/('x'*20) vm = CTRexScRaw( [ STLVmFlowVar(name=""mlabel"", min_value=1, max_value=2000, size=2, op=""inc""), STLVmWrMaskFlowVar(fv_name=""mlabel"", pkt_offset= ""MPLS:1.label"",pkt_cast_size=4, mask=0xFFFFF000,shift=12) # write mask ] ) ---- [source,python] ---- vm = CTRexScRaw( [ STLVmFlowVar(name=""mac_src"", min_value=1, max_value=30, size=1, op=""dec"",step=7), # step STLVmWrFlowVar(fv_name=""mac_src"", pkt_offset= 11) ] ) ---- ** More profile samples (native/hlt) == Release 1.91 == * Convert Stateless traffic profile to Scapy see `stl/*.py` sample folder * Add HLTAPI tests and profile `stl/hlt/*.py` * Fix simulator path issue fix * The Stateless python library is not self-contained. in `automation/trex_control_plane/stl/` library is `automation/trex_control_plane/stl/trex_stl_lib/` (import trex_stl_lib) How to run the simulator [source,bash] ---- ./stl-sim -f stl/udp_1pkt_range_clients_split.py -o b.pcap -l 100 -c 2 ---- * Add push command to convert pcap to streams ------------------- TRex > push --help usage: push [-h] -f FILE [--port PORTS [PORTS ...] | -a] [-d TIME] [-i IPG_USEC] [-s SPEEDUP] [--force] optional arguments: -h, --help show this help message and exit -f FILE File path to load --port PORTS [PORTS ...] A list of ports on which to apply the command -a Set this flag to apply the command on all available ports -d TIME Set duration time for job. -i IPG_USEC, --ipg IPG_USEC IPG value in usec between packets. default will be from the pcap -s SPEEDUP, --speedup SPEEDUP Factor to accelerate the injection. effectively means IPG = IPG / SPEEDUP --force Set if you want to stop active ports before appyling command. TRex >push -f cap2/dns.pcap --port 0 -i 10 ------------------- == Release 1.90 == * Missing file in the pkg == Release 1.89 == * Integrate Scapy as a packet builder see `stl/profiles` folder * Improve Python API, samples can be seen link:https://github.com/cisco-system-traffic-generator/trex-core/tree/master/scripts/api/stl/examples[here] * Add Stateless simulator into the package Example how to run [source,bash] ---- ./stl-sim -f stl/profiles/udp_1pkt.py -l 10 -o a.pcap #<1> ./stl-sim -f stl/profiles/udp_1pkt_tuple_gen.py -l 20 -o a.pcap #<2> ./stl-sim -f stl/profiles/imix.py -l 100 -o a.pcap --json #<3> ---- <1> Limit the number of packets to 10 <2> Tuple generator example <3> imix The simulator takes Stateless profile,YAML or Py and output pcap file or json * Console can load the new Python profile [source,bash] ---- TRex > start -f stl/profiles/udp_1pkt.py -a -m 1mbps ---- * Basic Python HLTAPI support === Fixed issues: === * Dependent streams (e.g. `stl/burst_1000_pkt.yaml`) can be loaded == Release 1.88 == * Add the Python API to the package * Remove mock support == Release 1.87 == * Fix some 82599 ierror in case of high rate * First Stateless API examples under api folder (not part of the package) == Release 1.86 == * NAT Cisco ASA support ** Add support for learning using TCP-ACK field see more here link:trex_manual.html#_nat_support[here] and link:trex_manual.html#_trex_with_asa_5585[here] * More stateless support == Release 1.85 == * Upgrade to DPDK 2.2.0 ** Some XL710/X710 NIC phy issues solved ** VMXNET3 driver is optimized ** Cisco VIC should be supported, not tested yet * Jumbo packet size is supported for 1/10/40 Intel NIC up to 9K for both stateless and stateful * youTrack is public now, can be seen here link:http://trex-tgn.cisco.com/youtrack[here] * More stateless support ** Support random packet size trim instruction - see stl/udp_rand_size_9k.yaml for an example ** Move Python Regression to trex-core ** Add Coverity scripts ** Console/Python API can be call from Cisco CEL now (ZMQ Python library is compiled to an old glibc) ** Add simulator for stateless === Fixed issues: === * The infamous DPDK error is not seen in case of a wrong core argument see here link:http://trex-tgn.cisco.com/youtrack/issue/trex-147[trex-147] == Release 1.84 == * more stateless support ** Add splitter range support see ""split_by_var"" in style/imix_1pkt_vm. yaml ** Add more samples see stl/syn_attack_sample.yaml. Improve random performance ** more improvement with TUI window == Release 1.83 == * more stateless support ** Add basic Packet Field engine see stl/imin_1pkt_vm.yaml ** some improvement with TUI window. Can be run in parallel with --tui option == Release 1.82 == * more stateless support ** console stats/tui function works now ** R/W support. only one client has R/W capability * XL710/X710 support ICMP filter === Fixed issues: === * link:http://trex-tgn.cisco.com/youtrack/trex-110[trex-110] == Release 1.81 == * more stateless support and fixes ** change the JSON-RPC result format * Support for specifying different modes for the packets used for latency measurement. Details link:trex_manual.html#_measure_jitter_latency[here]. === Fixed issues: === * link:http://trex-tgn.cisco.com/youtrack/issue/trex-149[trex-149] == Release 1.80 == * more stateless support ** All type of streams are supported (Continues/Burst/Multi-burst) ** Stream can call to other streams ** start/stop/pause/resume work from the Console ** -m[rate] is supported for example -m10gbps or -m10kpps from console ** update XL710 installation support == Release 1.79 == * Initial support for stateless ** Only continues streams are supported ** more info how to enable the interactive shell link:trex_console.html[here] == Release 1.78 == * some clean up in tuple generator * trex stateles console works with trex-mock === Fixed issues: === Python API fixup see here * link:http://trex-tgn.cisco.com/youtrack/issue/trex-126[trex-126] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-123[trex-122] Check for 64bit Kernel * link:http://trex-tgn.cisco.com/youtrack/issue/trex-123[trex-123] == Release 1.77 == * improve tuple generator capability now it is more flexiable see more link:trex_manual.html#_clients_servers_ip_allocation_scheme[here] == Release 1.76 == === Fixed issues: === * minor pcap loader issues * plugin cleanup == Release 1.75 == === fix issues: === * First version that works from GitHub/Git - init script are in the output package == Release 1.72 == ",16300,True,3775.656588755017,median " //// /** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * ""License""); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //// :doctype: book :numbered: :toc: left :icons: font :experimental: [[hbase_default_configurations]] === HBase Default Configuration The documentation below is generated using the default hbase configuration file, _hbase-default.xml_, as source. [[hbase.tmp.dir]] *`hbase.tmp.dir`*:: + .Description Temporary directory on the local filesystem. Change this setting to point to a location more permanent than '/tmp', the usual resolve for java.io.tmpdir, as the '/tmp' directory is cleared on machine restart. + .Default `${java.io.tmpdir}/hbase-${user.name}` [[hbase.rootdir]] *`hbase.rootdir`*:: + .Description The directory shared by region servers and into which HBase persists. The URL should be 'fully-qualified' to include the filesystem scheme. For example, to specify the HDFS directory '/hbase' where the HDFS instance's namenode is running at namenode.example.org on port 9000, set this value to: hdfs://namenode.example.org:9000/hbase. By default, we write to whatever ${hbase.tmp.dir} is set to -- usually /tmp -- so change this configuration or else all data will be lost on machine restart. + .Default `${hbase.tmp.dir}/hbase` [[hbase.cluster.distributed]] *`hbase.cluster.distributed`*:: + .Description The mode the cluster will be in. Possible values are false for standalone mode and true for distributed mode. If false, startup will run all HBase and ZooKeeper daemons together in one JVM. + .Default `false` [[hbase.zookeeper.quorum]] *`hbase.zookeeper.quorum`*:: + .Description Comma separated list of servers in the ZooKeeper ensemble (This config. should have been named hbase.zookeeper.ensemble). For example, ""host1.mydomain.com,host2.mydomain.com,host3.mydomain.com"". By default this is set to localhost for local and pseudo-distributed modes of operation. For a fully-distributed setup, this should be set to a full list of ZooKeeper ensemble servers. If HBASE_MANAGES_ZK is set in hbase-env.sh, this is the list of servers which hbase will start/stop ZooKeeper on as part of cluster start/stop. Client-side, we will take this list of ensemble members and put it together with the hbase.zookeeper.clientPort config and pass it into zookeeper constructor as the connectString parameter. + .Default `localhost` [[hbase.local.dir]] *`hbase.local.dir`*:: + .Description Directory on the local filesystem to be used as a local storage. + .Default `${hbase.tmp.dir}/local/` [[hbase.master.info.port]] *`hbase.master.info.port`*:: + .Description The port for the HBase Master web UI. Set to -1 if you do not want a UI instance run. + .Default `16010` [[hbase.master.info.bindAddress]] *`hbase.master.info.bindAddress`*:: + .Description The bind address for the HBase Master web UI + .Default `0.0.0.0` [[hbase.master.logcleaner.plugins]] *`hbase.master.logcleaner.plugins`*:: + .Description A comma-separated list of BaseLogCleanerDelegate invoked by the LogsCleaner service. These WAL cleaners are called in order, so put the cleaner that prunes the most files in front. To implement your own BaseLogCleanerDelegate, just put it in HBase's classpath and add the fully qualified class name here. Always add the above default log cleaners in the list. + .Default `org.apache.hadoop.hbase.master.cleaner.TimeToLiveLogCleaner` [[hbase.master.logcleaner.ttl]] *`hbase.master.logcleaner.ttl`*:: + .Description Maximum time a WAL can stay in the oldWALs directory, after which it will be cleaned by a Master thread. + .Default `600000` [[hbase.master.hfilecleaner.plugins]] *`hbase.master.hfilecleaner.plugins`*:: + .Description A comma-separated list of BaseHFileCleanerDelegate invoked by the HFileCleaner service. These HFiles cleaners are called in order, so put the cleaner that prunes the most files in front. To implement your own BaseHFileCleanerDelegate, just put it in HBase's classpath and add the fully qualified class name here. Always add the above default log cleaners in the list as they will be overwritten in hbase-site.xml. + .Default `org.apache.hadoop.hbase.master.cleaner.TimeToLiveHFileCleaner` [[hbase.master.infoserver.redirect]] *`hbase.master.infoserver.redirect`*:: + .Description Whether or not the Master listens to the Master web UI port (hbase.master.info.port) and redirects requests to the web UI server shared by the Master and RegionServer. + .Default `true` [[hbase.regionserver.port]] *`hbase.regionserver.port`*:: + .Description The port the HBase RegionServer binds to. + .Default `16020` [[hbase.regionserver.info.port]] *`hbase.regionserver.info.port`*:: + .Description The port for the HBase RegionServer web UI Set to -1 if you do not want the RegionServer UI to run. + .Default `16030` [[hbase.regionserver.info.bindAddress]] *`hbase.regionserver.info.bindAddress`*:: + .Description The address for the HBase RegionServer web UI + .Default `0.0.0.0` [[hbase.regionserver.info.port.auto]] *`hbase.regionserver.info.port.auto`*:: + .Description Whether or not the Master or RegionServer UI should search for a port to bind to. Enables automatic port search if hbase.regionserver.info.port is already in use. Useful for testing, turned off by default. + .Default `false` [[hbase.regionserver.handler.count]] *`hbase.regionserver.handler.count`*:: + .Description Count of RPC Listener instances spun up on RegionServers. Same property is used by the Master for count of master handlers. + .Default `30` [[hbase.ipc.server.callqueue.handler.factor]] *`hbase.ipc.server.callqueue.handler.factor`*:: + .Description Factor to determine the number of call queues. A value of 0 means a single queue shared between all the handlers. A value of 1 means that each handler has its own queue. + .Default `0.1` [[hbase.ipc.server.callqueue.read.ratio]] *`hbase.ipc.server.callqueue.read.ratio`*:: + .Description Split the call queues into read and write queues. The specified interval (which should be between 0.0 and 1.0) will be multiplied by the number of call queues. A value of 0 indicates to not split the call queues, meaning that both read and write requests will be pushed to the same set of queues. A value lower than 0.5 means that there will be less read queues than write queues. A value of 0.5 means there will be the same number of read and write queues. A value greater than 0.5 means that there will be more read queues than write queues. A value of 1.0 means that all the queues except one are used to dispatch read requests. Example: Given the total number of call queues being 10 a read.ratio of 0 means that: the 10 queues will contain both read/write requests. a read.ratio of 0.3 means that: 3 queues will contain only read requests and 7 queues will contain only write requests. a read.ratio of 0.5 means that: 5 queues will contain only read requests and 5 queues will contain only write requests. a read.ratio of 0.8 means that: 8 queues will contain only read requests and 2 queues will contain only write requests. a read.ratio of 1 means that: 9 queues will contain only read requests and 1 queues will contain only write requests. + .Default `0` [[hbase.ipc.server.callqueue.scan.ratio]] *`hbase.ipc.server.callqueue.scan.ratio`*:: + .Description Given the number of read call queues, calculated from the total number of call queues multiplied by the callqueue.read.ratio, the scan.ratio property will split the read call queues into small-read and long-read queues. A value lower than 0.5 means that there will be less long-read queues than short-read queues. A value of 0.5 means that there will be the same number of short-read and long-read queues. A value greater than 0.5 means that there will be more long-read queues than short-read queues A value of 0 or 1 indicates to use the same set of queues for gets and scans. Example: Given the total number of read call queues being 8 a scan.ratio of 0 or 1 means that: 8 queues will contain both long and short read requests. a scan.ratio of 0.3 means that: 2 queues will contain only long-read requests and 6 queues will contain only short-read requests. a scan.ratio of 0.5 means that: 4 queues will contain only long-read requests and 4 queues will contain only short-read requests. a scan.ratio of 0.8 means that: 6 queues will contain only long-read requests and 2 queues will contain only short-read requests. + .Default `0` [[hbase.regionserver.msginterval]] *`hbase.regionserver.msginterval`*:: + .Description Interval between messages from the RegionServer to Master in milliseconds. + .Default `3000` [[hbase.regionserver.regionSplitLimit]] *`hbase.regionserver.regionSplitLimit`*:: + .Description Limit for the number of regions after which no more region splitting should take place. This is not a hard limit for the number of regions but acts as a guideline for the regionserver to stop splitting after a certain limit. Default is MAX_INT; i.e. do not block splitting. + .Default `2147483647` [[hbase.regionserver.logroll.period]] *`hbase.regionserver.logroll.period`*:: + .Description Period at which we will roll the commit log regardless of how many edits it has. + .Default `3600000` [[hbase.regionserver.logroll.errors.tolerated]] *`hbase.regionserver.logroll.errors.tolerated`*:: + .Description The number of consecutive WAL close errors we will allow before triggering a server abort. A setting of 0 will cause the region server to abort if closing the current WAL writer fails during log rolling. Even a small value (2 or 3) will allow a region server to ride over transient HDFS errors. + .Default `2` [[hbase.regionserver.hlog.reader.impl]] *`hbase.regionserver.hlog.reader.impl`*:: + .Description The WAL file reader implementation. + .Default `org.apache.hadoop.hbase.regionserver.wal.ProtobufLogReader` [[hbase.regionserver.hlog.writer.impl]] *`hbase.regionserver.hlog.writer.impl`*:: + .Description The WAL file writer implementation. + .Default `org.apache.hadoop.hbase.regionserver.wal.ProtobufLogWriter` [[hbase.regionserver.global.memstore.size]] *`hbase.regionserver.global.memstore.size`*:: + .Description Maximum size of all memstores in a region server before new updates are blocked and flushes are forced. Defaults to 40% of heap. Updates are blocked and flushes are forced until size of all memstores in a region server hits hbase.regionserver.global.memstore.size.lower.limit. + .Default `0.4` [[hbase.regionserver.global.memstore.size.lower.limit]] *`hbase.regionserver.global.memstore.size.lower.limit`*:: + .Description Maximum size of all memstores in a region server before flushes are forced. Defaults to 95% of hbase.regionserver.global.memstore.size. A 100% value for this property causes the minimum possible flushing to occur when updates are blocked due to memstore limiting. + .Default `0.95` [[hbase.regionserver.optionalcacheflushinterval]] *`hbase.regionserver.optionalcacheflushinterval`*:: + .Description Maximum amount of time an edit lives in memory before being automatically flushed. Default 1 hour. Set it to 0 to disable automatic flushing. + .Default `3600000` [[hbase.regionserver.dns.interface]] *`hbase.regionserver.dns.interface`*:: + .Description The name of the Network Interface from which a region server should report its IP address. + .Default `default` [[hbase.regionserver.dns.nameserver]] *`hbase.regionserver.dns.nameserver`*:: + .Description The host name or IP address of the name server (DNS) which a region server should use to determine the host name used by the master for communication and display purposes. + .Default `default` [[hbase.regionserver.region.split.policy]] *`hbase.regionserver.region.split.policy`*:: + .Description A split policy determines when a region should be split. The various other split policies that are available currently are ConstantSizeRegionSplitPolicy, DisabledRegionSplitPolicy, DelimitedKeyPrefixRegionSplitPolicy, KeyPrefixRegionSplitPolicy, BusyRegionSplitPolicy, SteppingSplitPolicy etc. + .Default `org.apache.hadoop.hbase.regionserver.SteppingSplitPolicy` [[zookeeper.session.timeout]] *`zookeeper.session.timeout`*:: + .Description ZooKeeper session timeout in milliseconds. It is used in two different ways. First, this value is used in the ZK client that HBase uses to connect to the ensemble. It is also used by HBase when it starts a ZK server and it is passed as the 'maxSessionTimeout'. See https://zookeeper.apache.org/doc/current/zookeeperProgrammers.html#ch_zkSessions. For example, if an HBase region server connects to a ZK ensemble that's also managed by HBase, then the session timeout will be the one specified by this configuration. But, a region server that connects to an ensemble managed with a different configuration will be subjected that ensemble's maxSessionTimeout. So, even though HBase might propose using 90 seconds, the ensemble can have a max timeout lower than this and it will take precedence. The current default maxSessionTimeout that ZK ships with is 40 seconds, which is lower than HBase's. + .Default `90000` [[zookeeper.znode.parent]] *`zookeeper.znode.parent`*:: + .Description Root ZNode for HBase in ZooKeeper. All of HBase's ZooKeeper files that are configured with a relative path will go under this node. By default, all of HBase's ZooKeeper file path are configured with a relative path, so they will all go under this directory unless changed. + .Default `/hbase` [[zookeeper.znode.acl.parent]] *`zookeeper.znode.acl.parent`*:: + .Description Root ZNode for access control lists. + .Default `acl` [[hbase.zookeeper.dns.interface]] *`hbase.zookeeper.dns.interface`*:: + .Description The name of the Network Interface from which a ZooKeeper server should report its IP address. + .Default `default` [[hbase.zookeeper.dns.nameserver]] *`hbase.zookeeper.dns.nameserver`*:: + .Description The host name or IP address of the name server (DNS) which a ZooKeeper server should use to determine the host name used by the master for communication and display purposes. + .Default `default` [[hbase.zookeeper.peerport]] *`hbase.zookeeper.peerport`*:: + .Description Port used by ZooKeeper peers to talk to each other. See https://zookeeper.apache.org/doc/r3.4.10/zookeeperStarted.html#sc_RunningReplicatedZooKeeper for more information. + .Default `2888` [[hbase.zookeeper.leaderport]] *`hbase.zookeeper.leaderport`*:: + .Description Port used by ZooKeeper for leader election. See https://zookeeper.apache.org/doc/r3.4.10/zookeeperStarted.html#sc_RunningReplicatedZooKeeper for more information. + .Default `3888` [[hbase.zookeeper.useMulti]] *`hbase.zookeeper.useMulti`*:: + .Description Instructs HBase to make use of ZooKeeper's multi-update functionality. This allows certain ZooKeeper operations to complete more quickly and prevents some issues with rare Replication failure scenarios (see the release note of HBASE-2611 for an example). IMPORTANT: only set this to true if all ZooKeeper servers in the cluster are on version 3.4+ and will not be downgraded. ZooKeeper versions before 3.4 do not support multi-update and will not fail gracefully if multi-update is invoked (see ZOOKEEPER-1495). + .Default `true` [[hbase.zookeeper.property.initLimit]] *`hbase.zookeeper.property.initLimit`*:: + .Description Property from ZooKeeper's config zoo.cfg. The number of ticks that the initial synchronization phase can take. + .Default `10` [[hbase.zookeeper.property.syncLimit]] *`hbase.zookeeper.property.syncLimit`*:: + .Description Property from ZooKeeper's config zoo.cfg. The number of ticks that can pass between sending a request and getting an acknowledgment. + .Default `5` [[hbase.zookeeper.property.dataDir]] *`hbase.zookeeper.property.dataDir`*:: + .Description Property from ZooKeeper's config zoo.cfg. The directory where the snapshot is stored. + .Default `${hbase.tmp.dir}/zookeeper` [[hbase.zookeeper.property.clientPort]] *`hbase.zookeeper.property.clientPort`*:: + .Description Property from ZooKeeper's config zoo.cfg. The port at which the clients will connect. + .Default `2181` [[hbase.zookeeper.property.maxClientCnxns]] *`hbase.zookeeper.property.maxClientCnxns`*:: + .Description Property from ZooKeeper's config zoo.cfg. Limit on number of concurrent connections (at the socket level) that a single client, identified by IP address, may make to a single member of the ZooKeeper ensemble. Set high to avoid zk connection issues running standalone and pseudo-distributed. + .Default `300` [[hbase.client.write.buffer]] *`hbase.client.write.buffer`*:: + .Description Default size of the BufferedMutator write buffer in bytes. A bigger buffer takes more memory -- on both the client and server side since server instantiates the passed write buffer to process it -- but a larger buffer size reduces the number of RPCs made. For an estimate of server-side memory-used, evaluate hbase.client.write.buffer * hbase.regionserver.handler.count + .Default `2097152` [[hbase.client.pause]] *`hbase.client.pause`*:: + .Description General client pause value. Used mostly as value to wait before running a retry of a failed get, region lookup, etc. See hbase.client.retries.number for description of how we backoff from this initial pause amount and how this pause works w/ retries. + .Default `100` [[hbase.client.retries.number]] *`hbase.client.retries.number`*:: + .Description Maximum retries. Used as maximum for all retryable operations such as the getting of a cell's value, starting a row update, etc. Retry interval is a rough function based on hbase.client.pause. At first we retry at this interval but then with backoff, we pretty quickly reach retrying every ten seconds. See HConstants#RETRY_BACKOFF for how the backup ramps up. Change this setting and hbase.client.pause to suit your workload. + .Default `35` [[hbase.client.max.total.tasks]] *`hbase.client.max.total.tasks`*:: + .Description The maximum number of concurrent tasks a single HTable instance will send to the cluster. + .Default `100` [[hbase.client.max.perserver.tasks]] *`hbase.client.max.perserver.tasks`*:: + .Description The maximum number of concurrent tasks a single HTable instance will send to a single region server. + .Default `2` [[hbase.client.max.perregion.tasks]] *`hbase.client.max.perregion.tasks`*:: + .Description The maximum number of concurrent connections the client will maintain to a single Region. That is, if there is already hbase.client.max.perregion.tasks writes in progress for this region, new puts won't be sent to this region until some writes finish. + .Default `1` [[hbase.client.scanner.caching]] *`hbase.client.scanner.caching`*:: + .Description Number of rows that will be fetched when calling next on a scanner if it is not served from (local, client) memory. Higher caching values will enable faster scanners but will eat up more memory and some calls of next may take longer and longer times when the cache is empty. Do not set this value such that the time between invocations is greater than the scanner timeout; i.e. hbase.client.scanner.timeout.period + .Default `100` [[hbase.client.keyvalue.maxsize]] *`hbase.client.keyvalue.maxsize`*:: + .Description Specifies the combined maximum allowed size of a KeyValue instance. This is to set an upper boundary for a single entry saved in a storage file. Since they cannot be split it helps avoiding that a region cannot be split any further because the data is too large. It seems wise to set this to a fraction of the maximum region size. Setting it to zero or less disables the check. + .Default `10485760` [[hbase.client.scanner.timeout.period]] *`hbase.client.scanner.timeout.period`*:: + .Description Client scanner lease period in milliseconds. + .Default `60000` [[hbase.client.localityCheck.threadPoolSize]] *`hbase.client.localityCheck.threadPoolSize`*:: + .Description + .Default `2` [[hbase.bulkload.retries.number]] *`hbase.bulkload.retries.number`*:: + .Description Maximum retries. This is a maximum number of iterations atomic bulk loads are attempted in the face of splitting operations, 0 means never give up. + .Default `10` [[hbase.balancer.period ]] *`hbase.balancer.period `*:: + .Description Period at which the region balancer runs in the Master. + .Default `300000` [[hbase.regions.slop]] *`hbase.regions.slop`*:: + .Description Rebalance if any regionserver has average + (average * slop) regions. + .Default `0.2` [[hbase.server.thread.wakefrequency]] *`hbase.server.thread.wakefrequency`*:: + .Description Time to sleep in between searches for work (in milliseconds). Used as sleep interval by service threads such as log roller. + .Default `10000` [[hbase.server.versionfile.writeattempts]] *`hbase.server.versionfile.writeattempts`*:: + .Description How many time to retry attempting to write a version file before just aborting. Each attempt is separated by the hbase.server.thread.wakefrequency milliseconds. + .Default `3` [[hbase.hregion.memstore.flush.size]] *`hbase.hregion.memstore.flush.size`*:: + .Description Memstore will be flushed to disk if size of the memstore exceeds this number of bytes. Value is checked by a thread that runs every hbase.server.thread.wakefrequency. + .Default `134217728` [[hbase.hregion.percolumnfamilyflush.size.lower.bound]] *`hbase.hregion.percolumnfamilyflush.size.lower.bound`*:: + .Description If FlushLargeStoresPolicy is used, then every time that we hit the total memstore limit, we find out all the column families whose memstores exceed this value, and only flush them, while retaining the others whose memstores are lower than this limit. If none of the families have their memstore size more than this, all the memstores will be flushed (just as usual). This value should be less than half of the total memstore threshold (hbase.hregion.memstore.flush.size). + .Default `16777216` [[hbase.hregion.preclose.flush.size]] *`hbase.hregion.preclose.flush.size`*:: + .Description If the memstores in a region are this size or larger when we go to close, run a ""pre-flush"" to clear out memstores before we put up the region closed flag and take the region offline. On close, a flush is run under the close flag to empty memory. During this time the region is offline and we are not taking on any writes. If the memstore content is large, this flush could take a long time to complete. The preflush is meant to clean out the bulk of the memstore before putting up the close flag and taking the region offline so the flush that runs under the close flag has little to do. + .Default `5242880` [[hbase.hregion.memstore.block.multiplier]] *`hbase.hregion.memstore.block.multiplier`*:: + .Description Block updates if memstore has hbase.hregion.memstore.block.multiplier times hbase.hregion.memstore.flush.size bytes. Useful preventing runaway memstore during spikes in update traffic. Without an upper-bound, memstore fills such that when it flushes the resultant flush files take a long time to compact or split, or worse, we OOME. + .Default `4` [[hbase.hregion.memstore.mslab.enabled]] *`hbase.hregion.memstore.mslab.enabled`*:: + .Description Enables the MemStore-Local Allocation Buffer, a feature which works to prevent heap fragmentation under heavy write loads. This can reduce the frequency of stop-the-world GC pauses on large heaps. + .Default `true` [[hbase.hregion.max.filesize]] *`hbase.hregion.max.filesize`*:: + .Description Maximum file size. If the sum of the sizes of a region's HFiles has grown to exceed this value, the region is split in two. There are two choices of how this option works, the first is when any store's size exceed the threshold then split, and the other is overall region's size exceed the threshold then split, it can be configed by hbase.hregion.split.overallfiles. + .Default `10737418240` [[hbase.hregion.split.overallfiles]] *`hbase.hregion.split.overallfiles`*:: + .Description If we should sum overall region files size when check to split. + .Default `true` [[hbase.hregion.majorcompaction]] *`hbase.hregion.majorcompaction`*:: + .Description Time between major compactions, expressed in milliseconds. Set to 0 to disable time-based automatic major compactions. User-requested and size-based major compactions will still run. This value is multiplied by hbase.hregion.majorcompaction.jitter to cause compaction to start at a somewhat-random time during a given window of time. The default value is 7 days, expressed in milliseconds. If major compactions are causing disruption in your environment, you can configure them to run at off-peak times for your deployment, or disable time-based major compactions by setting this parameter to 0, and run major compactions in a cron job or by another external mechanism. + .Default `604800000` [[hbase.hregion.majorcompaction.jitter]] *`hbase.hregion.majorcompaction.jitter`*:: + .Description A multiplier applied to hbase.hregion.majorcompaction to cause compaction to occur a given amount of time either side of hbase.hregion.majorcompaction. The smaller the number, the closer the compactions will happen to the hbase.hregion.majorcompaction interval. + .Default `0.50` [[hbase.hstore.compactionThreshold]] *`hbase.hstore.compactionThreshold`*:: + .Description If more than this number of StoreFiles exist in any one Store (one StoreFile is written per flush of MemStore), a compaction is run to rewrite all StoreFiles into a single StoreFile. Larger values delay compaction, but when compaction does occur, it takes longer to complete. + .Default `3` [[hbase.hstore.flusher.count]] *`hbase.hstore.flusher.count`*:: + .Description The number of flush threads. With fewer threads, the MemStore flushes will be queued. With more threads, the flushes will be executed in parallel, increasing the load on HDFS, and potentially causing more compactions. + .Default `2` [[hbase.hstore.blockingStoreFiles]] *`hbase.hstore.blockingStoreFiles`*:: + .Description If more than this number of StoreFiles exist in any one Store (one StoreFile is written per flush of MemStore), updates are blocked for this region until a compaction is completed, or until hbase.hstore.blockingWaitTime has been exceeded. + .Default `10` [[hbase.hstore.blockingWaitTime]] *`hbase.hstore.blockingWaitTime`*:: + .Description The time for which a region will block updates after reaching the StoreFile limit defined by hbase.hstore.blockingStoreFiles. After this time has elapsed, the region will stop blocking updates even if a compaction has not been completed. + .Default `90000` [[hbase.hstore.compaction.min]] *`hbase.hstore.compaction.min`*:: + .Description The minimum number of StoreFiles which must be eligible for compaction before compaction can run. The goal of tuning hbase.hstore.compaction.min is to avoid ending up with too many tiny StoreFiles to compact. Setting this value to 2 would cause a minor compaction each time you have two StoreFiles in a Store, and this is probably not appropriate. If you set this value too high, all the other values will need to be adjusted accordingly. For most cases, the default value is appropriate. In previous versions of HBase, the parameter hbase.hstore.compaction.min was named hbase.hstore.compactionThreshold. + .Default `3` [[hbase.hstore.compaction.max]] *`hbase.hstore.compaction.max`*:: + .Description The maximum number of StoreFiles which will be selected for a single minor compaction, regardless of the number of eligible StoreFiles. Effectively, the value of hbase.hstore.compaction.max controls the length of time it takes a single compaction to complete. Setting it larger means that more StoreFiles are included in a compaction. For most cases, the default value is appropriate. + .Default `10` [[hbase.hstore.compaction.min.size]] *`hbase.hstore.compaction.min.size`*:: + .Description A StoreFile smaller than this size will always be eligible for minor compaction. HFiles this size or larger are evaluated by hbase.hstore.compaction.ratio to determine if they are eligible. Because this limit represents the ""automatic include""limit for all StoreFiles smaller than this value, this value may need to be reduced in write-heavy environments where many StoreFiles in the 1-2 MB range are being flushed, because every StoreFile will be targeted for compaction and the resulting StoreFiles may still be under the minimum size and require further compaction. If this parameter is lowered, the ratio check is triggered more quickly. This addressed some issues seen in earlier versions of HBase but changing this parameter is no longer necessary in most situations. Default: 128 MB expressed in bytes. + .Default `134217728` [[hbase.hstore.compaction.max.size]] *`hbase.hstore.compaction.max.size`*:: + .Description A StoreFile larger than this size will be excluded from compaction. The effect of raising hbase.hstore.compaction.max.size is fewer, larger StoreFiles that do not get compacted often. If you feel that compaction is happening too often without much benefit, you can try raising this value. Default: the value of LONG.MAX_VALUE, expressed in bytes. + .Default `9223372036854775807` [[hbase.hstore.compaction.ratio]] *`hbase.hstore.compaction.ratio`*:: + .Description For minor compaction, this ratio is used to determine whether a given StoreFile which is larger than hbase.hstore.compaction.min.size is eligible for compaction. Its effect is to limit compaction of large StoreFiles. The value of hbase.hstore.compaction.ratio is expressed as a floating-point decimal. A large ratio, such as 10, will produce a single giant StoreFile. Conversely, a low value, such as .25, will produce behavior similar to the BigTable compaction algorithm, producing four StoreFiles. A moderate value of between 1.0 and 1.4 is recommended. When tuning this value, you are balancing write costs with read costs. Raising the value (to something like 1.4) will have more write costs, because you will compact larger StoreFiles. However, during reads, HBase will need to seek through fewer StoreFiles to accomplish the read. Consider this approach if you cannot take advantage of Bloom filters. Otherwise, you can lower this value to something like 1.0 to reduce the background cost of writes, and use Bloom filters to control the number of StoreFiles touched during reads. For most cases, the default value is appropriate. + .Default `1.2F` [[hbase.hstore.compaction.ratio.offpeak]] *`hbase.hstore.compaction.ratio.offpeak`*:: + .Description Allows you to set a different (by default, more aggressive) ratio for determining whether larger StoreFiles are included in compactions during off-peak hours. Works in the same way as hbase.hstore.compaction.ratio. Only applies if hbase.offpeak.start.hour and hbase.offpeak.end.hour are also enabled. + .Default `5.0F` [[hbase.hstore.time.to.purge.deletes]] *`hbase.hstore.time.to.purge.deletes`*:: + .Description The amount of time to delay purging of delete markers with future timestamps. If unset, or set to 0, all delete markers, including those with future timestamps, are purged during the next major compaction. Otherwise, a delete marker is kept until the major compaction which occurs after the marker's timestamp plus the value of this setting, in milliseconds. + .Default `0` [[hbase.offpeak.start.hour]] *`hbase.offpeak.start.hour`*:: + .Description The start of off-peak hours, expressed as an integer between 0 and 23, inclusive. Set to -1 to disable off-peak. + .Default `-1` [[hbase.offpeak.end.hour]] *`hbase.offpeak.end.hour`*:: + .Description The end of off-peak hours, expressed as an integer between 0 and 23, inclusive. Set to -1 to disable off-peak. + .Default `-1` [[hbase.regionserver.thread.compaction.throttle]] *`hbase.regionserver.thread.compaction.throttle`*:: + .Description There are two different thread pools for compactions, one for large compactions and the other for small compactions. This helps to keep compaction of lean tables (such as hbase:meta) fast. If a compaction is larger than this threshold, it goes into the large compaction pool. In most cases, the default value is appropriate. Default: 2 x hbase.hstore.compaction.max x hbase.hregion.memstore.flush.size (which defaults to 128MB). The value field assumes that the value of hbase.hregion.memstore.flush.size is unchanged from the default. + .Default `2684354560` [[hbase.hstore.compaction.kv.max]] *`hbase.hstore.compaction.kv.max`*:: + .Description The maximum number of KeyValues to read and then write in a batch when flushing or compacting. Set this lower if you have big KeyValues and problems with Out Of Memory Exceptions Set this higher if you have wide, small rows. + .Default `10` [[hbase.storescanner.parallel.seek.enable]] *`hbase.storescanner.parallel.seek.enable`*:: + .Description Enables StoreFileScanner parallel-seeking in StoreScanner, a feature which can reduce response latency under special conditions. + .Default `false` [[hbase.storescanner.parallel.seek.threads]] *`hbase.storescanner.parallel.seek.threads`*:: + .Description The default thread pool size if parallel-seeking feature enabled. + .Default `10` [[hfile.block.cache.size]] *`hfile.block.cache.size`*:: + .Description Percentage of maximum heap (-Xmx setting) to allocate to block cache used by a StoreFile. Default of 0.4 means allocate 40%. Set to 0 to disable but it's not recommended; you need at least enough cache to hold the storefile indices. + .Default `0.4` [[hfile.block.index.cacheonwrite]] *`hfile.block.index.cacheonwrite`*:: + .Description This allows to put non-root multi-level index blocks into the block cache at the time the index is being written. + .Default `false` [[hfile.index.block.max.size]] *`hfile.index.block.max.size`*:: + .Description When the size of a leaf-level, intermediate-level, or root-level index block in a multi-level block index grows to this size, the block is written out and a new block is started. + .Default `131072` [[hbase.bucketcache.ioengine]] *`hbase.bucketcache.ioengine`*:: + .Description Where to store the contents of the bucketcache. One of: offheap, file, files, mmap or pmem. If a file or files, set it to file(s):PATH_TO_FILE. mmap means the content will be in an mmaped file. Use mmap:PATH_TO_FILE. 'pmem' is bucket cache over a file on the persistent memory device. Use pmem:PATH_TO_FILE. See https://hbase.apache.org/devapidocs/org/apache/hadoop/hbase/io/hfile/CacheConfig.html for more information. + .Default `` [[hbase.bucketcache.combinedcache.enabled]] *`hbase.bucketcache.combinedcache.enabled`*:: + .Description Whether or not the bucketcache is used in league with the LRU on-heap block cache. In this mode, indices and blooms are kept in the LRU blockcache and the data blocks are kept in the bucketcache. + .Default `true` [[hbase.bucketcache.size]] *`hbase.bucketcache.size`*:: + .Description Used along with bucket cache, this is a float that EITHER represents a percentage of total heap memory size to give to the cache (if < 1.0) OR, it is the capacity in megabytes of the cache. (After HBase-2.0, ""hbase.bucketcache.size"" cannot be between 0-1) + .Default `0` when specified as a float [[hbase.bucketcache.bucket.sizes]] *`hbase.bucketcache.bucket.sizes`*:: + .Description A comma-separated list of sizes for buckets for the bucketcache if you use multiple sizes. Should be a list of block sizes in order from smallest to largest. The sizes you use will depend on your data access patterns. + .Default `` [[hfile.format.version]] *`hfile.format.version`*:: + .Description The HFile format version to use for new files. Version 3 adds support for tags in hfiles (See https://hbase.apache.org/book.html#hbase.tags). Also see the configuration 'hbase.replication.rpc.codec'. + .Default `3` [[hfile.block.bloom.cacheonwrite]] *`hfile.block.bloom.cacheonwrite`*:: + .Description Enables cache-on-write for inline blocks of a compound Bloom filter. + .Default `false` [[io.storefile.bloom.block.size]] *`io.storefile.bloom.block.size`*:: + .Description The size in bytes of a single block (""chunk"") of a compound Bloom filter. This size is approximate, because Bloom blocks can only be inserted at data block boundaries, and the number of keys per data block varies. + .Default `131072` [[hbase.rs.cacheblocksonwrite]] *`hbase.rs.cacheblocksonwrite`*:: + .Description Whether an HFile block should be added to the block cache when the block is finished. + .Default `false` [[hbase.rpc.timeout]] *`hbase.rpc.timeout`*:: + .Description This is for the RPC layer to define how long HBase client applications take for a remote call to time out. It uses pings to check connections but will eventually throw a TimeoutException. + .Default `60000` [[hbase.rpc.shortoperation.timeout]] *`hbase.rpc.shortoperation.timeout`*:: + .Description This is another version of ""hbase.rpc.timeout"". For those RPC operations within cluster, we rely on this configuration to set a short timeout limitation for short operations. For example, short rpc timeout for region server trying to report to active master can benefit from quicker master failover process. + .Default `10000` [[hbase.ipc.client.tcpnodelay]] *`hbase.ipc.client.tcpnodelay`*:: + .Description Set no delay on rpc socket connections. See http://docs.oracle.com/javase/8/docs/api/java/net/Socket.html#getTcpNoDelay-- + .Default `true` [[hbase.master.keytab.file]] *`hbase.master.keytab.file`*:: + .Description Full path to the kerberos keytab file to use for logging in the configured HMaster server principal. + .Default `` [[hbase.master.kerberos.principal]] *`hbase.master.kerberos.principal`*:: + .Description Ex. ""hbase/_HOST@EXAMPLE.COM"". The kerberos principal name that should be used to run the HMaster process. The principal name should be in the form: user/hostname@DOMAIN. If ""_HOST"" is used as the hostname portion, it will be replaced with the actual hostname of the running instance. + .Default `` [[hbase.regionserver.keytab.file]] *`hbase.regionserver.keytab.file`*:: + .Description Full path to the kerberos keytab file to use for logging in the configured HRegionServer server principal. + .Default `` [[hbase.regionserver.kerberos.principal]] *`hbase.regionserver.kerberos.principal`*:: + .Description Ex. ""hbase/_HOST@EXAMPLE.COM"". The kerberos principal name that should be used to run the HRegionServer process. The principal name should be in the form: user/hostname@DOMAIN. If ""_HOST"" is used as the hostname portion, it will be replaced with the actual hostname of the running instance. An entry for this principal must exist in the file specified in hbase.regionserver.keytab.file + .Default `` [[hadoop.policy.file]] *`hadoop.policy.file`*:: + .Description The policy configuration file used by RPC servers to make authorization decisions on client requests. Only used when HBase security is enabled. + .Default `hbase-policy.xml` [[hbase.superuser]] *`hbase.superuser`*:: + .Description List of users or groups (comma-separated), who are allowed full privileges, regardless of stored ACLs, across the cluster. Only used when HBase security is enabled. + .Default `` [[hbase.auth.key.update.interval]] *`hbase.auth.key.update.interval`*:: + .Description The update interval for master key for authentication tokens in servers in milliseconds. Only used when HBase security is enabled. + .Default `86400000` [[hbase.auth.token.max.lifetime]] *`hbase.auth.token.max.lifetime`*:: + .Description The maximum lifetime in milliseconds after which an authentication token expires. Only used when HBase security is enabled. + .Default `604800000` [[hbase.ipc.client.fallback-to-simple-auth-allowed]] *`hbase.ipc.client.fallback-to-simple-auth-allowed`*:: + .Description When a client is configured to attempt a secure connection, but attempts to connect to an insecure server, that server may instruct the client to switch to SASL SIMPLE (unsecure) authentication. This setting controls whether or not the client will accept this instruction from the server. When false (the default), the client will not allow the fallback to SIMPLE authentication, and will abort the connection. + .Default `false` [[hbase.display.keys]] *`hbase.display.keys`*:: + .Description When this is set to true the webUI and such will display all start/end keys as part of the table details, region names, etc. When this is set to false, the keys are hidden. + .Default `true` [[hbase.coprocessor.region.classes]] *`hbase.coprocessor.region.classes`*:: + .Description A comma-separated list of Coprocessors that are loaded by default on all tables. For any override coprocessor method, these classes will be called in order. After implementing your own Coprocessor, just put it in HBase's classpath and add the fully qualified class name here. A coprocessor can also be loaded on demand by setting HTableDescriptor. + .Default `` [[hbase.rest.port]] *`hbase.rest.port`*:: + .Description The port for the HBase REST server. + .Default `8080` [[hbase.rest.readonly]] *`hbase.rest.readonly`*:: + .Description Defines the mode the REST server will be started in. Possible values are: false: All HTTP methods are permitted - GET/PUT/POST/DELETE. true: Only the GET method is permitted. + .Default `false` [[hbase.rest.threads.max]] *`hbase.rest.threads.max`*:: + .Description The maximum number of threads of the REST server thread pool. Threads in the pool are reused to process REST requests. This controls the maximum number of requests processed concurrently. It may help to control the memory used by the REST server to avoid OOM issues. If the thread pool is full, incoming requests will be queued up and wait for some free threads. + .Default `100` [[hbase.rest.threads.min]] *`hbase.rest.threads.min`*:: + .Description The minimum number of threads of the REST server thread pool. The thread pool always has at least these number of threads so the REST server is ready to serve incoming requests. + .Default `2` [[hbase.rest.support.proxyuser]] *`hbase.rest.support.proxyuser`*:: + .Description Enables running the REST server to support proxy-user mode. + .Default `false` [[hbase.defaults.for.version.skip]] *`hbase.defaults.for.version.skip`*:: + .Description Set to true to skip the 'hbase.defaults.for.version' check. Setting this to true can be useful in contexts other than the other side of a maven generation; i.e. running in an ide. You'll want to set this boolean to true to avoid seeing the RuntimeException complaint: ""hbase-default.xml file seems to be for and old version of HBase (\\${hbase.version}), this version is X.X.X-SNAPSHOT"" + .Default `false` [[hbase.coprocessor.master.classes]] *`hbase.coprocessor.master.classes`*:: + .Description A comma-separated list of org.apache.hadoop.hbase.coprocessor.MasterObserver coprocessors that are loaded by default on the active HMaster process. For any implemented coprocessor methods, the listed classes will be called in order. After implementing your own MasterObserver, just put it in HBase's classpath and add the fully qualified class name here. + .Default `` [[hbase.coprocessor.abortonerror]] *`hbase.coprocessor.abortonerror`*:: + .Description Set to true to cause the hosting server (master or regionserver) to abort if a coprocessor fails to load, fails to initialize, or throws an unexpected Throwable object. Setting this to false will allow the server to continue execution but the system wide state of the coprocessor in question will become inconsistent as it will be properly executing in only a subset of servers, so this is most useful for debugging only. + .Default `true` [[hbase.table.lock.enable]] *`hbase.table.lock.enable`*:: + .Description Set to true to enable locking the table in zookeeper for schema change operations. Table locking from master prevents concurrent schema modifications to corrupt table state. + .Default `true` [[hbase.table.max.rowsize]] *`hbase.table.max.rowsize`*:: + .Description Maximum size of single row in bytes (default is 1 Gb) for Get'ting or Scan'ning without in-row scan flag set. If row size exceeds this limit RowTooBigException is thrown to client. + .Default `1073741824` [[hbase.thrift.minWorkerThreads]] *`hbase.thrift.minWorkerThreads`*:: + .Description The ""core size"" of the thread pool. New threads are created on every connection until this many threads are created. + .Default `16` [[hbase.thrift.maxWorkerThreads]] *`hbase.thrift.maxWorkerThreads`*:: + .Description The maximum size of the thread pool. When the pending request queue overflows, new threads are created until their number reaches this number. After that, the server starts dropping connections. + .Default `1000` [[hbase.thrift.maxQueuedRequests]] *`hbase.thrift.maxQueuedRequests`*:: + .Description The maximum number of pending Thrift connections waiting in the queue. If there are no idle threads in the pool, the server queues requests. Only when the queue overflows, new threads are added, up to hbase.thrift.maxQueuedRequests threads. + .Default `1000` [[hbase.regionserver.thrift.framed]] *`hbase.regionserver.thrift.framed`*:: + .Description Use Thrift TFramedTransport on the server side. This is the recommended transport for thrift servers and requires a similar setting on the client side. Changing this to false will select the default transport, vulnerable to DoS when malformed requests are issued due to THRIFT-601. + .Default `false` [[hbase.regionserver.thrift.framed.max_frame_size_in_mb]] *`hbase.regionserver.thrift.framed.max_frame_size_in_mb`*:: + .Description Default frame size when using framed transport + .Default `2` [[hbase.regionserver.thrift.compact]] *`hbase.regionserver.thrift.compact`*:: + .Description Use Thrift TCompactProtocol binary serialization protocol. + .Default `false` [[hbase.data.umask.enable]] *`hbase.data.umask.enable`*:: + .Description Enable, if true, that file permissions should be assigned to the files written by the regionserver + .Default `false` [[hbase.data.umask]] *`hbase.data.umask`*:: + .Description File permissions that should be used to write data files when hbase.data.umask.enable is true + .Default `000` [[hbase.snapshot.enabled]] *`hbase.snapshot.enabled`*:: + .Description Set to true to allow snapshots to be taken / restored / cloned. + .Default `true` [[hbase.snapshot.restore.take.failsafe.snapshot]] *`hbase.snapshot.restore.take.failsafe.snapshot`*:: + .Description Set to true to take a snapshot before the restore operation. The snapshot taken will be used in case of failure, to restore the previous state. At the end of the restore operation this snapshot will be deleted + .Default `true` [[hbase.snapshot.restore.failsafe.name]] *`hbase.snapshot.restore.failsafe.name`*:: + .Description Name of the failsafe snapshot taken by the restore operation. You can use the {snapshot.name}, {table.name} and {restore.timestamp} variables to create a name based on what you are restoring. + .Default `hbase-failsafe-{snapshot.name}-{restore.timestamp}` [[hbase.server.compactchecker.interval.multiplier]] *`hbase.server.compactchecker.interval.multiplier`*:: + .Description The number that determines how often we scan to see if compaction is necessary. Normally, compactions are done after some events (such as memstore flush), but if region didn't receive a lot of writes for some time, or due to different compaction policies, it may be necessary to check it periodically. The interval between checks is hbase.server.compactchecker.interval.multiplier multiplied by hbase.server.thread.wakefrequency. + .Default `1000` [[hbase.lease.recovery.timeout]] *`hbase.lease.recovery.timeout`*:: + .Description How long we wait on dfs lease recovery in total before giving up. + .Default `900000` [[hbase.lease.recovery.dfs.timeout]] *`hbase.lease.recovery.dfs.timeout`*:: + .Description How long between dfs recovery lease invocations. Should be larger than the sum of the time it takes for the namenode to issue a block recovery command as part of datanode dfs.heartbeat.interval and the time it takes for the primary datanode performing block recovery to timeout on a dead datanode, usually dfs.client.socket-timeout. See the end of HBASE-8389 for more. + .Default `64000` [[hbase.column.max.version]] *`hbase.column.max.version`*:: + .Description New column family descriptors will use this value as the default number of versions to keep. + .Default `1` [[hbase.dfs.client.read.shortcircuit.buffer.size]] *`hbase.dfs.client.read.shortcircuit.buffer.size`*:: + .Description If the DFSClient configuration dfs.client.read.shortcircuit.buffer.size is unset, we will use what is configured here as the short circuit read default direct byte buffer size. DFSClient native default is 1MB; HBase keeps its HDFS files open so number of file blocks * 1MB soon starts to add up and threaten OOME because of a shortage of direct memory. So, we set it down from the default. Make it > the default hbase block size set in the HColumnDescriptor which is usually 64k. + .Default `131072` [[hbase.regionserver.checksum.verify]] *`hbase.regionserver.checksum.verify`*:: + .Description If set to true (the default), HBase verifies the checksums for hfile blocks. HBase writes checksums inline with the data when it writes out hfiles. HDFS (as of this writing) writes checksums to a separate file than the data file necessitating extra seeks. Setting this flag saves some on i/o. Checksum verification by HDFS will be internally disabled on hfile streams when this flag is set. If the hbase-checksum verification fails, we will switch back to using HDFS checksums (so do not disable HDFS checksums! And besides this feature applies to hfiles only, not to WALs). If this parameter is set to false, then hbase will not verify any checksums, instead it will depend on checksum verification being done in the HDFS client. + .Default `true` [[hbase.hstore.bytes.per.checksum]] *`hbase.hstore.bytes.per.checksum`*:: + .Description Number of bytes in a newly created checksum chunk for HBase-level checksums in hfile blocks. + .Default `16384` [[hbase.hstore.checksum.algorithm]] *`hbase.hstore.checksum.algorithm`*:: + .Description Name of an algorithm that is used to compute checksums. Possible values are NULL, CRC32, CRC32C. + .Default `CRC32` [[hbase.status.published]] *`hbase.status.published`*:: + .Description This setting activates the publication by the master of the status of the region server. When a region server dies and its recovery starts, the master will push this information to the client application, to let them cut the connection immediately instead of waiting for a timeout. + .Default `false` [[hbase.status.publisher.class]] *`hbase.status.publisher.class`*:: + .Description Implementation of the status publication with a multicast message. + .Default `org.apache.hadoop.hbase.master.ClusterStatusPublisher$MulticastPublisher` [[hbase.status.listener.class]] *`hbase.status.listener.class`*:: + .Description Implementation of the status listener with a multicast message. + .Default `org.apache.hadoop.hbase.client.ClusterStatusListener$MulticastListener` [[hbase.status.multicast.address.ip]] *`hbase.status.multicast.address.ip`*:: + .Description Multicast address to use for the status publication by multicast. + .Default `226.1.1.3` [[hbase.status.multicast.address.port]] *`hbase.status.multicast.address.port`*:: + .Description Multicast port to use for the status publication by multicast. + .Default `16100` [[hbase.dynamic.jars.dir]] *`hbase.dynamic.jars.dir`*:: + .Description The directory from which the custom filter/co-processor jars can be loaded dynamically by the region server without the need to restart. However, an already loaded filter/co-processor class would not be un-loaded. See HBASE-1936 for more details. + .Default `${hbase.rootdir}/lib` [[hbase.security.authentication]] *`hbase.security.authentication`*:: + .Description Controls whether or not secure authentication is enabled for HBase. Possible values are 'simple' (no authentication), and 'kerberos'. + .Default `simple` [[hbase.rest.filter.classes]] *`hbase.rest.filter.classes`*:: + .Description Servlet filters for REST service. + .Default `org.apache.hadoop.hbase.rest.filter.GzipFilter` [[hbase.master.loadbalancer.class]] *`hbase.master.loadbalancer.class`*:: + .Description Class used to execute the regions balancing when the period occurs. See the class comment for more on how it works https://hbase.apache.org/devapidocs/org/apache/hadoop/hbase/master/balancer/StochasticLoadBalancer.html It replaces the DefaultLoadBalancer as the default (since renamed as the SimpleLoadBalancer). + .Default `org.apache.hadoop.hbase.master.balancer.StochasticLoadBalancer` [[hbase.security.exec.permission.checks]] *`hbase.security.exec.permission.checks`*:: + .Description If this setting is enabled and ACL based access control is active (the AccessController coprocessor is installed either as a system coprocessor or on a table as a table coprocessor) then you must grant all relevant users EXEC privilege if they require the ability to execute coprocessor endpoint calls. EXEC privilege, like any other permission, can be granted globally to a user, or to a user on a per table or per namespace basis. For more information on coprocessor endpoints, see the coprocessor section of the HBase online manual. For more information on granting or revoking permissions using the AccessController, see the security section of the HBase online manual. + .Default `false` [[hbase.procedure.regionserver.classes]] *`hbase.procedure.regionserver.classes`*:: + .Description A comma-separated list of org.apache.hadoop.hbase.procedure.RegionServerProcedureManager procedure managers that are loaded by default on the active HRegionServer process. The lifecycle methods (init/start/stop) will be called by the active HRegionServer process to perform the specific globally barriered procedure. After implementing your own RegionServerProcedureManager, just put it in HBase's classpath and add the fully qualified class name here. + .Default `` [[hbase.procedure.master.classes]] *`hbase.procedure.master.classes`*:: + .Description A comma-separated list of org.apache.hadoop.hbase.procedure.MasterProcedureManager procedure managers that are loaded by default on the active HMaster process. A procedure is identified by its signature and users can use the signature and an instant name to trigger an execution of a globally barriered procedure. After implementing your own MasterProcedureManager, just put it in HBase's classpath and add the fully qualified class name here. + .Default `` [[hbase.regionserver.storefile.refresh.period]] *`hbase.regionserver.storefile.refresh.period`*:: + .Description The period (in milliseconds) for refreshing the store files for the secondary regions. 0 means this feature is disabled. Secondary regions sees new files (from flushes and compactions) from primary once the secondary region refreshes the list of files in the region (there is no notification mechanism). But too frequent refreshes might cause extra Namenode pressure. If the files cannot be refreshed for longer than HFile TTL (hbase.master.hfilecleaner.ttl) the requests are rejected. Configuring HFile TTL to a larger value is also recommended with this setting. + .Default `0` [[hbase.region.replica.replication.enabled]] *`hbase.region.replica.replication.enabled`*:: + .Description Whether asynchronous WAL replication to the secondary region replicas is enabled or not. If this is enabled, a replication peer named ""region_replica_replication"" will be created which will tail the logs and replicate the mutations to region replicas for tables that have region replication > 1. If this is enabled once, disabling this replication also requires disabling the replication peer using shell or Admin java class. Replication to secondary region replicas works over standard inter-cluster replication. + .Default `false` [[hbase.http.filter.initializers]] *`hbase.http.filter.initializers`*:: + .Description A comma separated list of class names. Each class in the list must extend org.apache.hadoop.hbase.http.FilterInitializer. The corresponding Filter will be initialized. Then, the Filter will be applied to all user facing jsp and servlet web pages. The ordering of the list defines the ordering of the filters. The default StaticUserWebFilter adds a user principal as defined by the hbase.http.staticuser.user property. + .Default `org.apache.hadoop.hbase.http.lib.StaticUserWebFilter` [[hbase.security.visibility.mutations.checkauths]] *`hbase.security.visibility.mutations.checkauths`*:: + .Description This property if enabled, will check whether the labels in the visibility expression are associated with the user issuing the mutation + .Default `false` [[hbase.http.max.threads]] *`hbase.http.max.threads`*:: + .Description The maximum number of threads that the HTTP Server will create in its ThreadPool. + .Default `16` [[hbase.replication.rpc.codec]] *`hbase.replication.rpc.codec`*:: + .Description The codec that is to be used when replication is enabled so that the tags are also replicated. This is used along with HFileV3 which supports tags in them. If tags are not used or if the hfile version used is HFileV2 then KeyValueCodec can be used as the replication codec. Note that using KeyValueCodecWithTags for replication when there are no tags causes no harm. + .Default `org.apache.hadoop.hbase.codec.KeyValueCodecWithTags` [[hbase.http.staticuser.user]] *`hbase.http.staticuser.user`*:: + .Description The user name to filter as on static web filters while rendering content. For example, the HDFS web UI (user to be used for browsing files). + .Default `dr.stack` [[hbase.regionserver.handler.abort.on.error.percent]] *`hbase.regionserver.handler.abort.on.error.percent`*:: + .Description The percent of region server RPC threads failed to abort RS. -1 Disable aborting; 0 Abort if even a single handler has died; 0.x Abort only when this percent of handlers have died; 1 Abort only all of the handlers have died. + .Default `0.5` [[hbase.master.cleaner.snapshot.interval]] *`hbase.master.cleaner.snapshot.interval`*:: + .Description Snapshot Cleanup chore interval in milliseconds. The cleanup thread keeps running at this interval to find all snapshots that are expired based on TTL and delete them. + .Default `1800000` [[hbase.master.snapshot.ttl]] *`hbase.master.snapshot.ttl`*:: + .Description Default Snapshot TTL to be considered when the user does not specify TTL while creating snapshot. Default value 0 indicates FOREVERE - snapshot should not be automatically deleted until it is manually deleted + .Default `0` [[hbase.master.regions.recovery.check.interval]] *`hbase.master.regions.recovery.check.interval`*:: + .Description Regions Recovery Chore interval in milliseconds. This chore keeps running at this interval to find all regions with configurable max store file ref count and reopens them. + .Default `1200000` [[hbase.regions.recovery.store.file.ref.count]] *`hbase.regions.recovery.store.file.ref.count`*:: + .Description Very large number of ref count on a compacted store file indicates that it is a ref leak on that object(compacted store file). Such files can not be removed after it is invalidated via compaction. Only way to recover in such scenario is to reopen the region which can release all resources, like the refcount, leases, etc. This config represents Store files Ref Count threshold value considered for reopening regions. Any region with compacted store files ref count > this value would be eligible for reopening by master. Here, we get the max refCount among all refCounts on all compacted away store files that belong to a particular region. Default value -1 indicates this feature is turned off. Only positive integer value should be provided to enable this feature. + .Default `-1` [[hbase.regionserver.slowlog.ringbuffer.size]] *`hbase.regionserver.slowlog.ringbuffer.size`*:: + .Description Default size of ringbuffer to be maintained by each RegionServer in order to store online slowlog responses. This is an in-memory ring buffer of requests that were judged to be too slow in addition to the responseTooSlow logging. The in-memory representation would be complete. For more details, please look into Doc Section: <> + .Default `256` [[hbase.regionserver.slowlog.buffer.enabled]] *`hbase.regionserver.slowlog.buffer.enabled`*:: + .Description Indicates whether RegionServers have ring buffer running for storing Online Slow logs in FIFO manner with limited entries. The size of the ring buffer is indicated by config: hbase.regionserver.slowlog.ringbuffer.size The default value is false, turn this on and get latest slowlog responses with complete data. For more details, please look into Doc Section: <> + .Default `false` [[hbase.regionserver.slowlog.systable.enabled]] *`hbase.regionserver.slowlog.systable.enabled`*:: + .Description Should be enabled only if hbase.regionserver.slowlog.buffer.enabled is enabled. If enabled (true), all slow/large RPC logs would be persisted to system table hbase:slowlog (in addition to in-memory ring buffer at each RegionServer). The records are stored in increasing order of time. Operators can scan the table with various combination of ColumnValueFilter and time range. More details are provided in the doc section: ""Get Slow/Large Response Logs from System table hbase:slowlog"" + .Default `false` [[hbase.master.metafixer.max.merge.count]] *`hbase.master.metafixer.max.merge.count`*:: + .Description Maximum regions to merge at a time when we fix overlaps noted in CJ consistency report, but avoid merging 100 regions in one go! + .Default `64` [[hbase.rpc.rows.size.threshold.reject]] *`hbase.rpc.rows.size.threshold.reject`*:: + .Description If value is true, RegionServer will abort batch requests of Put/Delete with number of rows in a batch operation exceeding threshold defined by value of config: hbase.rpc.rows.warning.threshold. The default value is false and hence, by default, only warning will be logged. This config should be turned on to prevent RegionServer from serving very large batch size of rows and this way we can improve CPU usages by discarding too large batch request. + .Default `false` [[hbase.master.balancer.decision.buffer.enabled]] *`hbase.master.balancer.decision.buffer.enabled`*:: + .Description Indicates whether active HMaster has ring buffer running for storing balancer decisions in FIFO manner with limited entries. The size of the ring buffer is indicated by config: hbase.master.balancer.decision.queue.size + .Default `false` ",16160,True,3022.9729458627976,median "-- This spec has been automatically generated from STM32L5x2.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package STM32_SVD.USART is pragma Preelaborate; --------------- -- Registers -- --------------- subtype CR1_DEDT_Field is HAL.UInt5; subtype CR1_DEAT_Field is HAL.UInt5; -- Control register 1 type CR1_Register is record -- USART enable UE : Boolean := False; -- USART enable in Stop mode UESM : Boolean := False; -- Receiver enable RE : Boolean := False; -- Transmitter enable TE : Boolean := False; -- IDLE interrupt enable IDLEIE : Boolean := False; -- RXNE interrupt enable RXNEIE : Boolean := False; -- Transmission complete interrupt enable TCIE : Boolean := False; -- interrupt enable TXEIE : Boolean := False; -- PE interrupt enable PEIE : Boolean := False; -- Parity selection PS : Boolean := False; -- Parity control enable PCE : Boolean := False; -- Receiver wakeup method WAKE : Boolean := False; -- Word length M0 : Boolean := False; -- Mute mode enable MME : Boolean := False; -- Character match interrupt enable CMIE : Boolean := False; -- unspecified Reserved_15_15 : HAL.Bit := 16#0#; -- DEDT DEDT : CR1_DEDT_Field := 16#0#; -- DEAT DEAT : CR1_DEAT_Field := 16#0#; -- unspecified Reserved_26_27 : HAL.UInt2 := 16#0#; -- Word length M1 : Boolean := False; -- FIFOEN FIFOEN : Boolean := False; -- TXFEIE TXFEIE : Boolean := False; -- RXFFIE RXFFIE : Boolean := False; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CR1_Register use record UE at 0 range 0 .. 0; UESM at 0 range 1 .. 1; RE at 0 range 2 .. 2; TE at 0 range 3 .. 3; IDLEIE at 0 range 4 .. 4; RXNEIE at 0 range 5 .. 5; TCIE at 0 range 6 .. 6; TXEIE at 0 range 7 .. 7; PEIE at 0 range 8 .. 8; PS at 0 range 9 .. 9; PCE at 0 range 10 .. 10; WAKE at 0 range 11 .. 11; M0 at 0 range 12 .. 12; MME at 0 range 13 .. 13; CMIE at 0 range 14 .. 14; Reserved_15_15 at 0 range 15 .. 15; DEDT at 0 range 16 .. 20; DEAT at 0 range 21 .. 25; Reserved_26_27 at 0 range 26 .. 27; M1 at 0 range 28 .. 28; FIFOEN at 0 range 29 .. 29; TXFEIE at 0 range 30 .. 30; RXFFIE at 0 range 31 .. 31; end record; subtype CR2_STOP_Field is HAL.UInt2; subtype CR2_ADD0_3_Field is HAL.UInt4; subtype CR2_ADD4_7_Field is HAL.UInt4; -- Control register 2 type CR2_Register is record -- unspecified Reserved_0_3 : HAL.UInt4 := 16#0#; -- 7-bit Address Detection/4-bit Address Detection ADDM7 : Boolean := False; -- unspecified Reserved_5_11 : HAL.UInt7 := 16#0#; -- STOP bits STOP : CR2_STOP_Field := 16#0#; -- unspecified Reserved_14_14 : HAL.Bit := 16#0#; -- Swap TX/RX pins SWAP : Boolean := False; -- RX pin active level inversion RXINV : Boolean := False; -- TX pin active level inversion TXINV : Boolean := False; -- Binary data inversion TAINV : Boolean := False; -- Most significant bit first MSBFIRST : Boolean := False; -- unspecified Reserved_20_23 : HAL.UInt4 := 16#0#; -- Address of the USART node ADD0_3 : CR2_ADD0_3_Field := 16#0#; -- Address of the USART node ADD4_7 : CR2_ADD4_7_Field := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CR2_Register use record Reserved_0_3 at 0 range 0 .. 3; ADDM7 at 0 range 4 .. 4; Reserved_5_11 at 0 range 5 .. 11; STOP at 0 range 12 .. 13; Reserved_14_14 at 0 range 14 .. 14; SWAP at 0 range 15 .. 15; RXINV at 0 range 16 .. 16; TXINV at 0 range 17 .. 17; TAINV at 0 range 18 .. 18; MSBFIRST at 0 range 19 .. 19; Reserved_20_23 at 0 range 20 .. 23; ADD0_3 at 0 range 24 .. 27; ADD4_7 at 0 range 28 .. 31; end record; subtype CR3_WUS_Field is HAL.UInt2; subtype CR3_RXFTCFG_Field is HAL.UInt3; subtype CR3_TXFTCFG_Field is HAL.UInt3; -- Control register 3 type CR3_Register is record -- Error interrupt enable EIE : Boolean := False; -- unspecified Reserved_1_2 : HAL.UInt2 := 16#0#; -- Half-duplex selection HDSEL : Boolean := False; -- unspecified Reserved_4_5 : HAL.UInt2 := 16#0#; -- DMA enable receiver DMAR : Boolean := False; -- DMA enable transmitter DMAT : Boolean := False; -- RTS enable RTSE : Boolean := False; -- CTS enable CTSE : Boolean := False; -- CTS interrupt enable CTSIE : Boolean := False; -- unspecified Reserved_11_11 : HAL.Bit := 16#0#; -- Overrun Disable OVRDIS : Boolean := False; -- DMA Disable on Reception Error DDRE : Boolean := False; -- Driver enable mode DEM : Boolean := False; -- Driver enable polarity selection DEP : Boolean := False; -- unspecified Reserved_16_19 : HAL.UInt4 := 16#0#; -- Wakeup from Stop mode interrupt flag selection WUS : CR3_WUS_Field := 16#0#; -- Wakeup from Stop mode interrupt enable WUFIE : Boolean := False; -- TXFTIE TXFTIE : Boolean := False; -- unspecified Reserved_24_24 : HAL.Bit := 16#0#; -- RXFTCFG RXFTCFG : CR3_RXFTCFG_Field := 16#0#; -- RXFTIE RXFTIE : Boolean := False; -- TXFTCFG TXFTCFG : CR3_TXFTCFG_Field := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CR3_Register use record EIE at 0 range 0 .. 0; Reserved_1_2 at 0 range 1 .. 2; HDSEL at 0 range 3 .. 3; Reserved_4_5 at 0 range 4 .. 5; DMAR at 0 range 6 .. 6; DMAT at 0 range 7 .. 7; RTSE at 0 range 8 .. 8; CTSE at 0 range 9 .. 9; CTSIE at 0 range 10 .. 10; Reserved_11_11 at 0 range 11 .. 11; OVRDIS at 0 range 12 .. 12; DDRE at 0 range 13 .. 13; DEM at 0 range 14 .. 14; DEP at 0 range 15 .. 15; Reserved_16_19 at 0 range 16 .. 19; WUS at 0 range 20 .. 21; WUFIE at 0 range 22 .. 22; TXFTIE at 0 range 23 .. 23; Reserved_24_24 at 0 range 24 .. 24; RXFTCFG at 0 range 25 .. 27; RXFTIE at 0 range 28 .. 28; TXFTCFG at 0 range 29 .. 31; end record; subtype BRR_BRR_Field is HAL.UInt20; -- Baud rate register type BRR_Register is record -- BRR BRR : BRR_BRR_Field := 16#0#; -- unspecified Reserved_20_31 : HAL.UInt12 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for BRR_Register use record BRR at 0 range 0 .. 19; Reserved_20_31 at 0 range 20 .. 31; end record; -- Request register type RQR_Register is record -- unspecified Reserved_0_0 : HAL.Bit := 16#0#; -- Write-only. Send break request SBKRQ : Boolean := False; -- Write-only. Mute mode request MMRQ : Boolean := False; -- Write-only. Receive data flush request RXFRQ : Boolean := False; -- Write-only. TXFRQ TXFRQ : Boolean := False; -- unspecified Reserved_5_31 : HAL.UInt27 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for RQR_Register use record Reserved_0_0 at 0 range 0 .. 0; SBKRQ at 0 range 1 .. 1; MMRQ at 0 range 2 .. 2; RXFRQ at 0 range 3 .. 3; TXFRQ at 0 range 4 .. 4; Reserved_5_31 at 0 range 5 .. 31; end record; -- Interrupt & status register type ISR_Register is record -- Read-only. PE PE : Boolean; -- Read-only. FE FE : Boolean; -- Read-only. NF NF : Boolean; -- Read-only. ORE ORE : Boolean; -- Read-only. IDLE IDLE : Boolean; -- Read-only. RXNE RXNE : Boolean; -- Read-only. TC TC : Boolean; -- Read-only. TXE TXE : Boolean; -- unspecified Reserved_8_8 : HAL.Bit; -- Read-only. CTSIF CTSIF : Boolean; -- Read-only. CTS CTS : Boolean; -- unspecified Reserved_11_15 : HAL.UInt5; -- Read-only. BUSY BUSY : Boolean; -- Read-only. CMF CMF : Boolean; -- Read-only. SBKF SBKF : Boolean; -- Read-only. RWU RWU : Boolean; -- Read-only. WUF WUF : Boolean; -- Read-only. TEACK TEACK : Boolean; -- Read-only. REACK REACK : Boolean; -- Read-only. TXFE TXFE : Boolean; -- Read-only. RXFF RXFF : Boolean; -- unspecified Reserved_25_25 : HAL.Bit; -- Read-only. RXFT RXFT : Boolean; -- Read-only. TXFT TXFT : Boolean; -- unspecified Reserved_28_31 : HAL.UInt4; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for ISR_Register use record PE at 0 range 0 .. 0; FE at 0 range 1 .. 1; NF at 0 range 2 .. 2; ORE at 0 range 3 .. 3; IDLE at 0 range 4 .. 4; RXNE at 0 range 5 .. 5; TC at 0 range 6 .. 6; TXE at 0 range 7 .. 7; Reserved_8_8 at 0 range 8 .. 8; CTSIF at 0 range 9 .. 9; CTS at 0 range 10 .. 10; Reserved_11_15 at 0 range 11 .. 15; BUSY at 0 range 16 .. 16; CMF at 0 range 17 .. 17; SBKF at 0 range 18 .. 18; RWU at 0 range 19 .. 19; WUF at 0 range 20 .. 20; TEACK at 0 range 21 .. 21; REACK at 0 range 22 .. 22; TXFE at 0 range 23 .. 23; RXFF at 0 range 24 .. 24; Reserved_25_25 at 0 range 25 .. 25; RXFT at 0 range 26 .. 26; TXFT at 0 range 27 .. 27; Reserved_28_31 at 0 range 28 .. 31; end record; -- Interrupt flag clear register type ICR_Register is record -- Write-only. Parity error clear flag PECF : Boolean := False; -- Write-only. Framing error clear flag FECF : Boolean := False; -- Write-only. Noise detected clear flag NCF : Boolean := False; -- Write-only. Overrun error clear flag ORECF : Boolean := False; -- Write-only. Idle line detected clear flag IDLECF : Boolean := False; -- unspecified Reserved_5_5 : HAL.Bit := 16#0#; -- Write-only. Transmission complete clear flag TCCF : Boolean := False; -- unspecified Reserved_7_8 : HAL.UInt2 := 16#0#; -- Write-only. CTS clear flag CTSCF : Boolean := False; -- unspecified Reserved_10_16 : HAL.UInt7 := 16#0#; -- Write-only. Character match clear flag CMCF : Boolean := False; -- unspecified Reserved_18_19 : HAL.UInt2 := 16#0#; -- Write-only. Wakeup from Stop mode clear flag WUCF : Boolean := False; -- unspecified Reserved_21_31 : HAL.UInt11 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for ICR_Register use record PECF at 0 range 0 .. 0; FECF at 0 range 1 .. 1; NCF at 0 range 2 .. 2; ORECF at 0 range 3 .. 3; IDLECF at 0 range 4 .. 4; Reserved_5_5 at 0 range 5 .. 5; TCCF at 0 range 6 .. 6; Reserved_7_8 at 0 range 7 .. 8; CTSCF at 0 range 9 .. 9; Reserved_10_16 at 0 range 10 .. 16; CMCF at 0 range 17 .. 17; Reserved_18_19 at 0 range 18 .. 19; WUCF at 0 range 20 .. 20; Reserved_21_31 at 0 range 21 .. 31; end record; subtype RDR_RDR_Field is HAL.UInt9; -- Receive data register type RDR_Register is record -- Read-only. Receive data value RDR : RDR_RDR_Field; -- unspecified Reserved_9_31 : HAL.UInt23; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for RDR_Register use record RDR at 0 range 0 .. 8; Reserved_9_31 at 0 range 9 .. 31; end record; subtype TDR_TDR_Field is HAL.UInt9; -- Transmit data register type TDR_Register is record -- Transmit data value TDR : TDR_TDR_Field := 16#0#; -- unspecified Reserved_9_31 : HAL.UInt23 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for TDR_Register use record TDR at 0 range 0 .. 8; Reserved_9_31 at 0 range 9 .. 31; end record; subtype PRESC_PRESCALER_Field is HAL.UInt4; -- PRESC type PRESC_Register is record -- PRESCALER PRESCALER : PRESC_PRESCALER_Field := 16#0#; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for PRESC_Register use record PRESCALER at 0 range 0 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; -- CR1_DEDT array type CR1_DEDT_Field_Array is array (0 .. 4) of Boolean with Component_Size => 1, Size => 5; -- Type definition for CR1_DEDT type CR1_DEDT_Field_1 (As_Array : Boolean := False) is record case As_Array is when False => -- DEDT as a value Val : HAL.UInt5; when True => -- DEDT as an array Arr : CR1_DEDT_Field_Array; end case; end record with Unchecked_Union, Size => 5; for CR1_DEDT_Field_1 use record Val at 0 range 0 .. 4; Arr at 0 range 0 .. 4; end record; -- CR1_DEAT array type CR1_DEAT_Field_Array is array (0 .. 4) of Boolean with Component_Size => 1, Size => 5; -- Type definition for CR1_DEAT type CR1_DEAT_Field_1 (As_Array : Boolean := False) is record case As_Array is when False => -- DEAT as a value Val : HAL.UInt5; when True => -- DEAT as an array Arr : CR1_DEAT_Field_Array; end case; end record with Unchecked_Union, Size => 5; for CR1_DEAT_Field_1 use record Val at 0 range 0 .. 4; Arr at 0 range 0 .. 4; end record; -- Control register 1 type CR1_Register_1 is record -- USART enable UE : Boolean := False; -- USART enable in Stop mode UESM : Boolean := False; -- Receiver enable RE : Boolean := False; -- Transmitter enable TE : Boolean := False; -- IDLE interrupt enable IDLEIE : Boolean := False; -- RXNE interrupt enable RXNEIE : Boolean := False; -- Transmission complete interrupt enable TCIE : Boolean := False; -- interrupt enable TXEIE : Boolean := False; -- PE interrupt enable PEIE : Boolean := False; -- Parity selection PS : Boolean := False; -- Parity control enable PCE : Boolean := False; -- Receiver wakeup method WAKE : Boolean := False; -- Word length M0 : Boolean := False; -- Mute mode enable MME : Boolean := False; -- Character match interrupt enable CMIE : Boolean := False; -- Oversampling mode OVER8 : Boolean := False; -- DEDT0 DEDT : CR1_DEDT_Field_1 := (As_Array => False, Val => 16#0#); -- DEAT0 DEAT : CR1_DEAT_Field_1 := (As_Array => False, Val => 16#0#); -- Receiver timeout interrupt enable RTOIE : Boolean := False; -- End of Block interrupt enable EOBIE : Boolean := False; -- Word length M1 : Boolean := False; -- FIFOEN FIFOEN : Boolean := False; -- TXFEIE TXFEIE : Boolean := False; -- RXFFIE RXFFIE : Boolean := False; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CR1_Register_1 use record UE at 0 range 0 .. 0; UESM at 0 range 1 .. 1; RE at 0 range 2 .. 2; TE at 0 range 3 .. 3; IDLEIE at 0 range 4 .. 4; RXNEIE at 0 range 5 .. 5; TCIE at 0 range 6 .. 6; TXEIE at 0 range 7 .. 7; PEIE at 0 range 8 .. 8; PS at 0 range 9 .. 9; PCE at 0 range 10 .. 10; WAKE at 0 range 11 .. 11; M0 at 0 range 12 .. 12; MME at 0 range 13 .. 13; CMIE at 0 range 14 .. 14; OVER8 at 0 range 15 .. 15; DEDT at 0 range 16 .. 20; DEAT at 0 range 21 .. 25; RTOIE at 0 range 26 .. 26; EOBIE at 0 range 27 .. 27; M1 at 0 range 28 .. 28; FIFOEN at 0 range 29 .. 29; TXFEIE at 0 range 30 .. 30; RXFFIE at 0 range 31 .. 31; end record; -- CR2_ABRMOD array type CR2_ABRMOD_Field_Array is array (0 .. 1) of Boolean with Component_Size => 1, Size => 2; -- Type definition for CR2_ABRMOD type CR2_ABRMOD_Field (As_Array : Boolean := False) is record case As_Array is when False => -- ABRMOD as a value Val : HAL.UInt2; when True => -- ABRMOD as an array Arr : CR2_ABRMOD_Field_Array; end case; end record with Unchecked_Union, Size => 2; for CR2_ABRMOD_Field use record Val at 0 range 0 .. 1; Arr at 0 range 0 .. 1; end record; -- Control register 2 type CR2_Register_1 is record -- SLVEN SLVEN : Boolean := False; -- unspecified Reserved_1_2 : HAL.UInt2 := 16#0#; -- DIS_NSS DIS_NSS : Boolean := False; -- 7-bit Address Detection/4-bit Address Detection ADDM7 : Boolean := False; -- LIN break detection length LBDL : Boolean := False; -- LIN break detection interrupt enable LBDIE : Boolean := False; -- unspecified Reserved_7_7 : HAL.Bit := 16#0#; -- Last bit clock pulse LBCL : Boolean := False; -- Clock phase CPHA : Boolean := False; -- Clock polarity CPOL : Boolean := False; -- Clock enable CLKEN : Boolean := False; -- STOP bits STOP : CR2_STOP_Field := 16#0#; -- LIN mode enable LINEN : Boolean := False; -- Swap TX/RX pins SWAP : Boolean := False; -- RX pin active level inversion RXINV : Boolean := False; -- TX pin active level inversion TXINV : Boolean := False; -- Binary data inversion DATAINV : Boolean := False; -- Most significant bit first MSBFIRST : Boolean := False; -- Auto baud rate enable ABREN : Boolean := False; -- ABRMOD0 ABRMOD : CR2_ABRMOD_Field := (As_Array => False, Val => 16#0#); -- Receiver timeout enable RTOEN : Boolean := False; -- Address of the USART node ADD0_3 : CR2_ADD0_3_Field := 16#0#; -- Address of the USART node ADD4_7 : CR2_ADD4_7_Field := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CR2_Register_1 use record SLVEN at 0 range 0 .. 0; Reserved_1_2 at 0 range 1 .. 2; DIS_NSS at 0 range 3 .. 3; ADDM7 at 0 range 4 .. 4; LBDL at 0 range 5 .. 5; LBDIE at 0 range 6 .. 6; Reserved_7_7 at 0 range 7 .. 7; LBCL at 0 range 8 .. 8; CPHA at 0 range 9 .. 9; CPOL at 0 range 10 .. 10; CLKEN at 0 range 11 .. 11; STOP at 0 range 12 .. 13; LINEN at 0 range 14 .. 14; SWAP at 0 range 15 .. 15; RXINV at 0 range 16 .. 16; TXINV at 0 range 17 .. 17; DATAINV at 0 range 18 .. 18; MSBFIRST at 0 range 19 .. 19; ABREN at 0 range 20 .. 20; ABRMOD at 0 range 21 .. 22; RTOEN at 0 range 23 .. 23; ADD0_3 at 0 range 24 .. 27; ADD4_7 at 0 range 28 .. 31; end record; subtype CR3_SCARCNT_Field is HAL.UInt3; -- Control register 3 type CR3_Register_1 is record -- Error interrupt enable EIE : Boolean := False; -- Ir mode enable IREN : Boolean := False; -- Ir low-power IRLP : Boolean := False; -- Half-duplex selection HDSEL : Boolean := False; -- Smartcard NACK enable NACK : Boolean := False; -- Smartcard mode enable SCEN : Boolean := False; -- DMA enable receiver DMAR : Boolean := False; -- DMA enable transmitter DMAT : Boolean := False; -- RTS enable RTSE : Boolean := False; -- CTS enable CTSE : Boolean := False; -- CTS interrupt enable CTSIE : Boolean := False; -- One sample bit method enable ONEBIT : Boolean := False; -- Overrun Disable OVRDIS : Boolean := False; -- DMA Disable on Reception Error DDRE : Boolean := False; -- Driver enable mode DEM : Boolean := False; -- Driver enable polarity selection DEP : Boolean := False; -- unspecified Reserved_16_16 : HAL.Bit := 16#0#; -- Smartcard auto-retry count SCARCNT : CR3_SCARCNT_Field := 16#0#; -- Wakeup from Stop mode interrupt flag selection WUS : CR3_WUS_Field := 16#0#; -- Wakeup from Stop mode interrupt enable WUFIE : Boolean := False; -- TXFTIE TXFTIE : Boolean := False; -- TCBGTIE TCBGTIE : Boolean := False; -- RXFTCFG RXFTCFG : CR3_RXFTCFG_Field := 16#0#; -- RXFTIE RXFTIE : Boolean := False; -- TXFTCFG TXFTCFG : CR3_TXFTCFG_Field := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CR3_Register_1 use record EIE at 0 range 0 .. 0; IREN at 0 range 1 .. 1; IRLP at 0 range 2 .. 2; HDSEL at 0 range 3 .. 3; NACK at 0 range 4 .. 4; SCEN at 0 range 5 .. 5; DMAR at 0 range 6 .. 6; DMAT at 0 range 7 .. 7; RTSE at 0 range 8 .. 8; CTSE at 0 range 9 .. 9; CTSIE at 0 range 10 .. 10; ONEBIT at 0 range 11 .. 11; OVRDIS at 0 range 12 .. 12; DDRE at 0 range 13 .. 13; DEM at 0 range 14 .. 14; DEP at 0 range 15 .. 15; Reserved_16_16 at 0 range 16 .. 16; SCARCNT at 0 range 17 .. 19; WUS at 0 range 20 .. 21; WUFIE at 0 range 22 .. 22; TXFTIE at 0 range 23 .. 23; TCBGTIE at 0 range 24 .. 24; RXFTCFG at 0 range 25 .. 27; RXFTIE at 0 range 28 .. 28; TXFTCFG at 0 range 29 .. 31; end record; subtype BRR_BRR_Field_1 is HAL.UInt16; -- Baud rate register type BRR_Register_1 is record -- BRR BRR : BRR_BRR_Field_1 := 16#0#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for BRR_Register_1 use record BRR at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype GTPR_PSC_Field is HAL.UInt8; subtype GTPR_GT_Field is HAL.UInt8; -- Guard time and prescaler register type GTPR_Register is record -- Prescaler value PSC : GTPR_PSC_Field := 16#0#; -- Guard time value GT : GTPR_GT_Field := 16#0#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for GTPR_Register use record PSC at 0 range 0 .. 7; GT at 0 range 8 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype RTOR_RTO_Field is HAL.UInt24; subtype RTOR_BLEN_Field is HAL.UInt8; -- Receiver timeout register type RTOR_Register is record -- Receiver timeout value RTO : RTOR_RTO_Field := 16#0#; -- Block Length BLEN : RTOR_BLEN_Field := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for RTOR_Register use record RTO at 0 range 0 .. 23; BLEN at 0 range 24 .. 31; end record; -- Request register type RQR_Register_1 is record -- Write-only. Auto baud rate request ABRRQ : Boolean := False; -- Write-only. Send break request SBKRQ : Boolean := False; -- Write-only. Mute mode request MMRQ : Boolean := False; -- Write-only. Receive data flush request RXFRQ : Boolean := False; -- Write-only. Transmit data flush request TXFRQ : Boolean := False; -- unspecified Reserved_5_31 : HAL.UInt27 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for RQR_Register_1 use record ABRRQ at 0 range 0 .. 0; SBKRQ at 0 range 1 .. 1; MMRQ at 0 range 2 .. 2; RXFRQ at 0 range 3 .. 3; TXFRQ at 0 range 4 .. 4; Reserved_5_31 at 0 range 5 .. 31; end record; -- Interrupt & status register type ISR_Register_1 is record -- Read-only. PE PE : Boolean; -- Read-only. FE FE : Boolean; -- Read-only. NF NF : Boolean; -- Read-only. ORE ORE : Boolean; -- Read-only. IDLE IDLE : Boolean; -- Read-only. RXNE RXNE : Boolean; -- Read-only. TC TC : Boolean; -- Read-only. TXE TXE : Boolean; -- Read-only. LBDF LBDF : Boolean; -- Read-only. CTSIF CTSIF : Boolean; -- Read-only. CTS CTS : Boolean; -- Read-only. RTOF RTOF : Boolean; -- Read-only. EOBF EOBF : Boolean; -- unspecified Reserved_13_13 : HAL.Bit; -- Read-only. ABRE ABRE : Boolean; -- Read-only. ABRF ABRF : Boolean; -- Read-only. BUSY BUSY : Boolean; -- Read-only. CMF CMF : Boolean; -- Read-only. SBKF SBKF : Boolean; -- Read-only. RWU RWU : Boolean; -- Read-only. WUF WUF : Boolean; -- Read-only. TEACK TEACK : Boolean; -- Read-only. REACK REACK : Boolean; -- Read-only. TXFE TXFE : Boolean; -- Read-only. RXFF RXFF : Boolean; -- Read-only. TCBGT TCBGT : Boolean; -- Read-only. RXFT RXFT : Boolean; -- Read-only. TXFT TXFT : Boolean; -- unspecified Reserved_28_31 : HAL.UInt4; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for ISR_Register_1 use record PE at 0 range 0 .. 0; FE at 0 range 1 .. 1; NF at 0 range 2 .. 2; ORE at 0 range 3 .. 3; IDLE at 0 range 4 .. 4; RXNE at 0 range 5 .. 5; TC at 0 range 6 .. 6; TXE at 0 range 7 .. 7; LBDF at 0 range 8 .. 8; CTSIF at 0 range 9 .. 9; CTS at 0 range 10 .. 10; RTOF at 0 range 11 .. 11; EOBF at 0 range 12 .. 12; Reserved_13_13 at 0 range 13 .. 13; ABRE at 0 range 14 .. 14; ABRF at 0 range 15 .. 15; BUSY at 0 range 16 .. 16; CMF at 0 range 17 .. 17; SBKF at 0 range 18 .. 18; RWU at 0 range 19 .. 19; WUF at 0 range 20 .. 20; TEACK at 0 range 21 .. 21; REACK at 0 range 22 .. 22; TXFE at 0 range 23 .. 23; RXFF at 0 range 24 .. 24; TCBGT at 0 range 25 .. 25; RXFT at 0 range 26 .. 26; TXFT at 0 range 27 .. 27; Reserved_28_31 at 0 range 28 .. 31; end record; -- Interrupt flag clear register type ICR_Register_1 is record -- Write-only. Parity error clear flag PECF : Boolean := False; -- Write-only. Framing error clear flag FECF : Boolean := False; -- Write-only. Noise detected clear flag NCF : Boolean := False; -- Write-only. Overrun error clear flag ORECF : Boolean := False; -- Write-only. Idle line detected clear flag IDLECF : Boolean := False; -- Write-only. TXFECF TXFECF : Boolean := False; -- Write-only. Transmission complete clear flag TCCF : Boolean := False; -- Write-only. TCBGTCF TCBGTCF : Boolean := False; -- Write-only. LIN break detection clear flag LBDCF : Boolean := False; -- Write-only. CTS clear flag CTSCF : Boolean := False; -- unspecified Reserved_10_10 : HAL.Bit := 16#0#; -- Write-only. Receiver timeout clear flag RTOCF : Boolean := False; -- Write-only. End of block clear flag EOBCF : Boolean := False; -- Write-only. UDRCF UDRCF : Boolean := False; -- unspecified Reserved_14_16 : HAL.UInt3 := 16#0#; -- Write-only. Character match clear flag CMCF : Boolean := False; -- unspecified Reserved_18_19 : HAL.UInt2 := 16#0#; -- Write-only. Wakeup from Stop mode clear flag WUCF : Boolean := False; -- unspecified Reserved_21_31 : HAL.UInt11 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for ICR_Register_1 use record PECF at 0 range 0 .. 0; FECF at 0 range 1 .. 1; NCF at 0 range 2 .. 2; ORECF at 0 range 3 .. 3; IDLECF at 0 range 4 .. 4; TXFECF at 0 range 5 .. 5; TCCF at 0 range 6 .. 6; TCBGTCF at 0 range 7 .. 7; LBDCF at 0 range 8 .. 8; CTSCF at 0 range 9 .. 9; Reserved_10_10 at 0 range 10 .. 10; RTOCF at 0 range 11 .. 11; EOBCF at 0 range 12 .. 12; UDRCF at 0 range 13 .. 13; Reserved_14_16 at 0 range 14 .. 16; CMCF at 0 range 17 .. 17; Reserved_18_19 at 0 range 18 .. 19; WUCF at 0 range 20 .. 20; Reserved_21_31 at 0 range 21 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Universal synchronous asynchronous receiver transmitter type LPUART1_Peripheral is record -- Control register 1 CR1 : aliased CR1_Register; -- Control register 2 CR2 : aliased CR2_Register; -- Control register 3 CR3 : aliased CR3_Register; -- Baud rate register BRR : aliased BRR_Register; -- Request register RQR : aliased RQR_Register; -- Interrupt & status register ISR : aliased ISR_Register; -- Interrupt flag clear register ICR : aliased ICR_Register; -- Receive data register RDR : aliased RDR_Register; -- Transmit data register TDR : aliased TDR_Register; -- PRESC PRESC : aliased PRESC_Register; end record with Volatile; for LPUART1_Peripheral use record CR1 at 16#0# range 0 .. 31; CR2 at 16#4# range 0 .. 31; CR3 at 16#8# range 0 .. 31; BRR at 16#C# range 0 .. 31; RQR at 16#18# range 0 .. 31; ISR at 16#1C# range 0 .. 31; ICR at 16#20# range 0 .. 31; RDR at 16#24# range 0 .. 31; TDR at 16#28# range 0 .. 31; PRESC at 16#2C# range 0 .. 31; end record; -- Universal synchronous asynchronous receiver transmitter LPUART1_Periph : aliased LPUART1_Peripheral with Import, Address => System'To_Address (16#40008000#); -- Universal synchronous asynchronous receiver transmitter SEC_LPUART1_Periph : aliased LPUART1_Peripheral with Import, Address => System'To_Address (16#50008000#); -- Universal synchronous asynchronous receiver transmitter type SEC_UART4_Peripheral is record -- Control register 1 CR1 : aliased CR1_Register_1; -- Control register 2 CR2 : aliased CR2_Register_1; -- Control register 3 CR3 : aliased CR3_Register_1; -- Baud rate register BRR : aliased BRR_Register_1; -- Guard time and prescaler register GTPR : aliased GTPR_Register; -- Receiver timeout register RTOR : aliased RTOR_Register; -- Request register RQR : aliased RQR_Register_1; -- Interrupt & status register ISR : aliased ISR_Register_1; -- Interrupt flag clear register ICR : aliased ICR_Register_1; -- Receive data register RDR : aliased RDR_Register; -- Transmit data register TDR : aliased TDR_Register; -- PRESC PRESC : aliased PRESC_Register; end record with Volatile; for SEC_UART4_Peripheral use record CR1 at 16#0# range 0 .. 31; CR2 at 16#4# range 0 .. 31; CR3 at 16#8# range 0 .. 31; BRR at 16#C# range 0 .. 31; GTPR at 16#10# range 0 .. 31; RTOR at 16#14# range 0 .. 31; RQR at 16#18# range 0 .. 31; ISR at 16#1C# range 0 .. 31; ICR at 16#20# range 0 .. 31; RDR at 16#24# range 0 .. 31; TDR at 16#28# range 0 .. 31; PRESC at 16#2C# range 0 .. 31; end record; -- Universal synchronous asynchronous receiver transmitter SEC_UART4_Periph : aliased SEC_UART4_Peripheral with Import, Address => System'To_Address (16#50004C00#); -- Universal synchronous asynchronous receiver transmitter SEC_UART5_Periph : aliased SEC_UART4_Peripheral with Import, Address => System'To_Address (16#50005000#); -- Universal synchronous asynchronous receiver transmitter SEC_USART1_Periph : aliased SEC_UART4_Peripheral with Import, Address => System'To_Address (16#50013800#); -- Universal synchronous asynchronous receiver transmitter SEC_USART2_Periph : aliased SEC_UART4_Peripheral with Import, Address => System'To_Address (16#50004400#); -- Universal synchronous asynchronous receiver transmitter SEC_USART3_Periph : aliased SEC_UART4_Peripheral with Import, Address => System'To_Address (16#50004800#); -- Universal synchronous asynchronous receiver transmitter UART4_Periph : aliased SEC_UART4_Peripheral with Import, Address => System'To_Address (16#40004C00#); -- Universal synchronous asynchronous receiver transmitter UART5_Periph : aliased SEC_UART4_Peripheral with Import, Address => System'To_Address (16#40005000#); -- Universal synchronous asynchronous receiver transmitter USART1_Periph : aliased SEC_UART4_Peripheral with Import, Address => System'To_Address (16#40013800#); -- Universal synchronous asynchronous receiver transmitter USART2_Periph : aliased SEC_UART4_Peripheral with Import, Address => System'To_Address (16#40004400#); -- Universal synchronous asynchronous receiver transmitter USART3_Periph : aliased SEC_UART4_Peripheral with Import, Address => System'To_Address (16#40004800#); end STM32_SVD.USART; ",12102,True,3097.7250578256694,median "with ada.text_io; with ada.command_line; with gnat.os_lib; with ada.strings; with ada.strings.bounded; with ada.containers.vectors; with ada.containers.indefinite_ordered_maps; with ada.containers.ordered_maps; with ada.containers.doubly_linked_lists; with interfaces; with ada.exceptions; with ada.containers; with ada.io_exceptions; with ada.finalization; with getter; with getter.file; with getter.for_loop; with getter.macros; with numbers; use numbers; with strings; use strings; with address; use address; with labels; use labels; with env; use env; procedure a0xfa is use type byte; use type word; parse_error : exception; programm_address : pos_addr_t := create(0); ff : constant word := 16#ffff#; r_pc : constant word := 0; r_sp : constant word := 1; r_sr : constant word := 2; procedure error (s : string) is begin print(s); gnat.os_lib.os_exit(1); end error; procedure error_parse (s : string) is begin raise parse_error with s; end error_parse; procedure warning (msg : string) is begin print(""[warning]: "" & msg); end warning; type record_handler_type; type handler_type is access function (s : string) return record_handler_type; type record_handler_type is record ptr : handler_type; end record; type operation_access is access function (a, b : word) return word; parse_def_cursor : environment_t.cursor := environment_t.no_element; package operands_t is new ada.containers.doubly_linked_lists(word, ""=""); type operation_t is record operation_ptr : operation_access := words_add'access; priority : positive := 1; operand_cur : operands_t.cursor; end record; package operations_t is new ada.containers.vectors( element_type => operation_t, index_type => natural); function "">"" (a, b : operation_t) return boolean is begin return a.priority > b.priority; end; procedure insert_sorted (ops : in out operations_t.vector; op : operation_t) is tmp_cursor : operations_t.cursor := ops.first; begin while operations_t.has_element(tmp_cursor) loop if op > operations_t.element(tmp_cursor) then operations_t.insert(ops, tmp_cursor, op); return; end if; operations_t.next(tmp_cursor); end loop; operations_t.append(ops, op); end insert_sorted; procedure environment_repr is tmp_cursor : environment_t.cursor := environment.first; begin while environment_t.has_element(tmp_cursor) loop print(environment_t.key(tmp_cursor) & "" : "" & environment_t.element(tmp_cursor)'img); environment_t.next(tmp_cursor); end loop; end environment_repr; type commands is ( f_rrc, f_swpb, f_rra, f_sxt, f_push, f_call, f_reti, f_jne, f_jeq, f_jnc, f_jc, f_jn, f_jge, f_jl, f_jmp, f_mov, f_add, f_addc, f_subc, f_sub, f_cmp, f_dadd, f_bit, f_bic, f_bis, f_xor, f_and, f_jnz, f_jz, f_jlo, f_jhs, f_clrc, f_clrn, f_clrz, f_dint, f_eint, f_nop, f_ret, f_setc, f_setn, f_setz, f_adc, f_br, f_clr, f_dadc, f_dec, f_decd, f_inc, f_incd, f_inv, f_pop, f_rla, f_rlc, f_sbc, f_tst, f_raw); subtype single_commands is commands range f_rrc..f_reti; subtype jump_commands is commands range f_jne..f_jmp; subtype alternatives_jump_commands is commands range f_jnz..f_jhs; subtype two_commands is commands range f_mov..f_and; subtype emulated_commands is commands range f_jnz..f_tst; subtype zero_emulated_commands is commands range f_clrc..f_setz; subtype single_emulated_commands is commands range f_adc..f_tst; type addressing_modes is ( m_constant, m_immediate, m_indexed, m_symbolic, m_absolute, m_indirect_register, m_indirect_autoincrement, m_register); type operand_t is record mode : addressing_modes := m_constant; value : word := 0; register : word := 0; label : label_t := null_label; end record; null_operand : constant operand_t := (m_register, 0, ff, null_label); type command_t is record command : commands; source, destination : operand_t := null_operand; num_operands : byte := 0; bw : boolean := true; end record; package programm_t is new ada.containers.ordered_maps( element_type => command_t, key_type => pos_addr_t); programm : programm_t.map; null_command : command_t := (f_raw, null_operand, null_operand, 0, true); type words_t is array (word range <>) of word; command : command_t := null_command; procedure void (r : record_handler_type) is begin null; end void; function parse_main (s : string) return record_handler_type; -- procedure from_file (path : string); function parse_word (s : string) return word is begin return value(s); exception when constraint_error => error_parse(""bad value "" & s); return 0; end parse_word; function validate_register (s : string) return boolean is begin return car(s) = 'r' and then natural'value(cdr(s)) in 0..15; exception when constraint_error => return false; end validate_register; procedure validate_variable_assert (s : string) is begin if not validate_variable(s) then error_parse(""error var name "" & s); end if; end validate_variable_assert; function parse_def (s : string) return record_handler_type is use type environment_t.cursor; tb : boolean; begin if parse_def_cursor = environment_t.no_element then validate_variable_assert(s); environment.insert(s, 0, parse_def_cursor, tb); if not tb then warning(""variable """""" & s & """""" redefined""); end if; return (ptr => parse_def'access); end if; environment.replace_element(parse_def_cursor, parse_word(s)); parse_def_cursor := environment_t.no_element; return (ptr => parse_main'access); end parse_def; function parse_defs (s : string) return record_handler_type is begin if s = "".end_defs"" then return (ptr => parse_main'access); end if; void(parse_def(s)); return (ptr => parse_defs'access); end parse_defs; function parse_undef (s : string) return record_handler_type is begin validate_variable_assert(s); if not environment_t.contains(environment, s) then warning(""variable name """""" & s & """""" not defined""); else environment.delete(s); end if; return (ptr => parse_main'access); end parse_undef; function parse_set (s : string) return record_handler_type is begin validate_variable_assert(s); if not environment_t.contains(environment, s) then error_parse(""variable name """""" & s & """""" not defined""); end if; void(parse_undef(s)); return parse_def(s); end parse_set; function parse_include (s : string) return record_handler_type is begin if first_element(s) /= '""' or last_element(s) /= '""' then error_parse(""error .include format""); end if; getter.file.open(trim(s((s'first + 1)..(s'last - 1)))); return (ptr => parse_main'access); end parse_include; type for_loop_step_t is (for_loop_var, for_loop_mode, for_loop_range); for_loop_step : for_loop_step_t := for_loop_var; tmp_for_loop_cursor : environment_t.cursor; function parse_for_loop (s : string) return record_handler_type is tb : boolean; dots_pos : natural; begin if for_loop_step = for_loop_var then validate_variable_assert(s); environment.insert(s, 0, tmp_for_loop_cursor, tb); if not tb then error_parse(""variable name """""" & s & """""" already defined""); end if; for_loop_step := for_loop_mode; elsif for_loop_step = for_loop_mode then if s /= ""in"" then error_parse(""error format for: "" & s); end if; for_loop_step := for_loop_range; elsif for_loop_step = for_loop_range then dots_pos := fix.index(s, ""..""); if dots_pos < 2 or (dots_pos + 1) >= s'last then error_parse(""error range: "" & s); end if; getter.for_loop.create( parse_word(s(s'first..(dots_pos - 1))), parse_word(s((dots_pos + 2)..s'last)), tmp_for_loop_cursor); for_loop_step := for_loop_var; return (ptr => parse_main'access); end if; return (ptr => parse_for_loop'access); end parse_for_loop; macro_name : unb.unbounded_string := unb.null_unbounded_string; macro_params : unb.unbounded_string := unb.null_unbounded_string; macro_wait_open : boolean := false; function get_macros_name_params (s : string) return boolean is use type unb.unbounded_string; open_pos : natural := 1; procedure set_macro_name (name : string) is begin if not validate_variable(name) then error_parse(""error macros name: "" & name); end if; macro_name := unb.to_unbounded_string(name); end set_macro_name; procedure append_param (s : string) is begin if s'length = 0 then return; end if; unb.append(macro_params, s & ' '); end append_param; begin if macro_name = unb.null_unbounded_string then macro_wait_open := true; open_pos := fix.index(s, ""(""); if open_pos > 0 then set_macro_name(s(s'first..(open_pos - 1))); else set_macro_name(s); return false; end if; end if; if macro_wait_open then if s(open_pos) /= '(' then error_parse(""wait '(' but: "" & s); end if; macro_wait_open := false; inc(open_pos); end if; if endswith(s, ')') then if s'length > 1 then append_param(s(open_pos..(s'last - 1))); end if; return true; else append_param(s(open_pos..s'last)); end if; return false; end get_macros_name_params; function parse_macros (s : string) return record_handler_type is begin if get_macros_name_params(s) then getter.macros.define(unb.to_string(macro_name), unb.to_string(macro_params)); macro_name := unb.null_unbounded_string; macro_params := unb.null_unbounded_string; return (ptr => parse_main'access); end if; return (ptr => parse_macros'access); end parse_macros; function parse_instruction (s : string) return record_handler_type is begin if s = "".def"" then return (ptr => parse_def'access); elsif s = "".undef"" then return (ptr => parse_undef'access); elsif s = "".set"" then return (ptr => parse_set'access); elsif s = "".include"" then return (ptr => parse_include'access); elsif s = "".for"" then return (ptr => parse_for_loop'access); elsif s = "".macro"" then return (ptr => parse_macros'access); elsif s = "".defs"" then return (ptr => parse_defs'access); end if; error_parse(""unknown instruction "" & s); return (ptr => parse_main'access); end parse_instruction; function in_labels (s : string) return boolean is begin return get_by_name(s) /= null_label; end in_labels; function validate_command (s : string) return boolean is begin return commands'value(""f_"" & s(s'first..(s'last - to_natural(endswith(s, "".b""), 2) - to_natural(endswith(s, "".w""), 2)))) >= commands'first; exception when others => return false; end validate_command; function parse_label (s : string) return record_handler_type is tmp_word : word; label : label_t; begin if first_element(s) in '0'..'9' then tmp_word := parse_word(s); if not valid_value_for_pos_addr(tmp_word) then error_parse(""bad value address "" & s); end if; if last_label /= null_label and then programm_address = get(last_label) then error_parse(""set address must be before define label""); end if; programm_address := create(tmp_word); elsif first_element(s) in 'a'..'z' then validate_variable_assert(s); if validate_register(s) then error_parse(s & "" label can not be r0..15""); elsif validate_command(s) then error_parse(s & "" label can not be command""); end if; label := get_by_name(s); if label /= null_label then if get(label) = null_pos_addr then label.set(programm_address); else error_parse(""label "" & s & "" already defined""); end if; else create(s, programm_address); end if; else error_parse(""invalid data "" & s); end if; return (ptr => parse_main'access); end parse_label; function get_var_val (s : string) return word is tmp_cursor : environment_t.cursor; begin tmp_cursor := environment_t.find(environment, s); -- environment_repr; if environment_t.has_element(tmp_cursor) then return environment_t.element(tmp_cursor); end if; error_parse(""variable "" & s & "" undefined""); return 0; end get_var_val; function parse_precompile (s : string) return string is use type ada.containers.count_type; start_pos, end_pos : natural := 0; value : word := 0; operation : operation_access := words_add'access; i : natural := s'first; priority : positive; operations : operations_t.vector; operands : operands_t.list; tmp_operation : operation_t; k_priority : natural := 0; begin while i < s'last + 1 loop if s(i) in '0'..'9'|'a'..'z'|'_' then if start_pos = end_pos then start_pos := i; end_pos := i + 1; else if i /= end_pos then error_parse(""error "" & s(start_pos..i)); end if; inc(end_pos); end if; else if s(i) = ' ' then null; elsif s(i) = '(' then k_priority := k_priority + 10; elsif s(i) = ')' then if k_priority = 0 then error_parse(s & "" ')' > '('""); end if; k_priority := k_priority - 10; elsif start_pos /= end_pos then if s(start_pos) in 'a'..'z' then -- print(s(start_pos..(end_pos - 1)) & get_var_val(s(start_pos..(end_pos - 1)))'img); operands.append(get_var_val(s(start_pos..(end_pos - 1)))); else -- print(s(start_pos..(end_pos - 1))); operands.append(parse_word(s(start_pos..(end_pos - 1)))); end if; if s(i) = ';' then exit; elsif s(i) = '<' then if s(i + 1) /= '<' then error_parse(s & "" unknown operation. maybe << ?""); end if; inc(i); operation := words_sl'access; priority := k_priority + 4; elsif s(i) = '>' then if s(i + 1) /= '>' then error_parse(s & "" unknown operation. maybe >> ?""); end if; inc(i); operation := words_sr'access; priority := k_priority + 4; elsif s(i) = '+' then operation := words_add'access; priority := k_priority + 5; elsif s(i) = '-' then operation := words_sub'access; priority := k_priority + 5; elsif s(i) = '*' then if s(i + 1) = '*' then operation := words_pow'access; priority := k_priority + 7; inc(i); else operation := words_mul'access; priority := k_priority + 6; end if; elsif s(i) = '/' then operation := words_div'access; priority := k_priority + 6; elsif s(i) = '%' then operation := words_mod'access; priority := k_priority + 6; elsif s(i) = '|' then operation := words_or'access; priority := k_priority + 1; elsif s(i) = '&' then operation := words_and'access; priority := k_priority + 3; elsif s(i) = '^' then operation := words_xor'access; priority := k_priority + 2; else error_parse(s & "" unknown operation""); end if; -- print("" = "" & operands_t.element(operands, operands.last_index)'img); insert_sorted(operations, (operation, priority, operands.last)); start_pos := end_pos; else error_parse(s & "" error""); end if; end if; inc(i); end loop; if k_priority /= 0 then error_parse(s & "" '(' > ')'""); end if; if operations_t.length(operations) = 0 and operands_t.length(operands) = 1 then return ltrim(operands_t.first_element(operands)'img); end if; while not operations_t.is_empty(operations) loop tmp_operation := operations_t.first_element(operations); value := tmp_operation.operation_ptr.all( operands_t.element(tmp_operation.operand_cur), operands_t.element(operands_t.next(tmp_operation.operand_cur))); operands_t.replace_element(operands, operands_t.next(tmp_operation.operand_cur), value); operands.delete(tmp_operation.operand_cur); operations_t.delete_first(operations); end loop; return ltrim(value'img); end parse_precompile; function operand_has_ext_word (operand : operand_t) return boolean is begin return operand.mode in m_symbolic|m_absolute|m_immediate|m_indexed; end operand_has_ext_word; procedure command_to_programm (cmd : in out command_t) is tmp_cursor : programm_t.cursor; inserted : boolean; prev_addr : pos_addr_t; prev_cursor : programm_t.cursor; procedure inc_addr_by_mode (operand : operand_t; addr : in out pos_addr_t) is begin if operand /= null_operand then if operand_has_ext_word(operand) then inc(addr); end if; end if; end inc_addr_by_mode; begin if cmd.command in emulated_commands then case cmd.command is when f_adc => cmd.command := f_addc; cmd.destination := cmd.source; cmd.source.mode := m_constant; cmd.source.value := 0; when f_br => cmd.command := f_mov; cmd.destination.mode := m_register; cmd.destination.register := r_pc; when f_clr => cmd.command := f_mov; cmd.destination := cmd.source; cmd.source.mode := m_constant; cmd.source.value := 0; when f_clrc => cmd.command := f_bic; cmd.source.mode := m_constant; cmd.source.value := 1; cmd.destination.mode := m_register; cmd.destination.register := r_sr; when f_clrn => cmd.command := f_bic; cmd.source.mode := m_constant; cmd.source.value := 4; cmd.destination.mode := m_register; cmd.destination.register := r_sr; when f_clrz => cmd.command := f_bic; cmd.source.mode := m_constant; cmd.source.value := 2; cmd.destination.mode := m_register; cmd.destination.register := r_sr; when f_dadc => cmd.command := f_dadd; cmd.destination := cmd.source; cmd.source.mode := m_constant; cmd.source.value := 0; when f_dec => cmd.command := f_sub; cmd.destination := cmd.source; cmd.source.mode := m_constant; cmd.source.value := 1; when f_decd => cmd.command := f_sub; cmd.destination := cmd.source; cmd.source.mode := m_constant; cmd.source.value := 2; when f_dint => cmd.command := f_bic; cmd.source.mode := m_constant; cmd.source.value := 8; cmd.destination.mode := m_register; cmd.destination.register := r_sr; when f_eint => cmd.command := f_bis; cmd.source.mode := m_constant; cmd.source.value := 8; cmd.destination.mode := m_register; cmd.destination.register := r_sr; when f_inc => cmd.command := f_add; cmd.destination := cmd.source; cmd.source.mode := m_constant; cmd.source.value := 1; when f_incd => cmd.command := f_add; cmd.destination := cmd.source; cmd.source.mode := m_constant; cmd.source.value := 2; when f_inv => cmd.command := f_xor; cmd.destination := cmd.source; cmd.source.mode := m_constant; cmd.source.value := 16#ffff#; when f_nop => cmd.command := f_mov; cmd.source.mode := m_constant; cmd.source.value := 0; cmd.destination.mode := m_register; cmd.destination.register := 3; when f_pop => cmd.command := f_mov; cmd.destination := cmd.source; cmd.source.mode := m_indirect_autoincrement; cmd.source.register := r_sp; when f_ret => cmd.command := f_mov; cmd.source.mode := m_indirect_autoincrement; cmd.source.register := r_sp; cmd.destination.mode := m_register; cmd.destination.register := r_pc; when f_rla => cmd.command := f_add; cmd.destination := cmd.source; when f_rlc => cmd.command := f_addc; cmd.destination := cmd.source; when f_sbc => cmd.command := f_subc; cmd.destination := cmd.source; cmd.source.mode := m_constant; cmd.source.value := 0; when f_setc => cmd.command := f_bis; cmd.source.mode := m_constant; cmd.source.value := 1; cmd.destination.mode := m_register; cmd.destination.register := r_sr; when f_setn => cmd.command := f_bis; cmd.source.mode := m_constant; cmd.source.value := 4; cmd.destination.mode := m_register; cmd.destination.register := r_sr; when f_setz => cmd.command := f_bis; cmd.source.mode := m_constant; cmd.source.value := 2; cmd.destination.mode := m_register; cmd.destination.register := r_sr; when f_tst => cmd.command := f_cmp; cmd.destination := cmd.source; cmd.source.mode := m_constant; cmd.source.value := 0; when f_jnz => cmd.command := f_jne; when f_jz => cmd.command := f_jeq; when f_jlo => cmd.command := f_jnc; when f_jhs => cmd.command := f_jc; when others => null; end case; elsif cmd.command = f_reti then cmd.source.mode := m_register; cmd.source.register := 0; end if; programm_t.insert(programm, programm_address, cmd, tmp_cursor, inserted); if not inserted then error_parse(""rewrite command: "" & hex(get(programm_address))); end if; prev_cursor := programm_t.previous(tmp_cursor); if programm_t.has_element(prev_cursor) then prev_addr := programm_t.key(prev_cursor); if programm_t.element(prev_cursor).command not in jump_commands|alternatives_jump_commands|f_raw then inc_addr_by_mode(programm_t.element(prev_cursor).source, prev_addr); inc_addr_by_mode(programm_t.element(prev_cursor).destination, prev_addr); end if; if prev_addr >= programm_address and programm_t.key(prev_cursor) < programm_address then error_parse(""rewrite previous command: "" & hex(get(programm_address))); end if; end if; inc(programm_address); if cmd.command not in jump_commands|alternatives_jump_commands|f_raw then inc_addr_by_mode(cmd.source, programm_address); inc_addr_by_mode(cmd.destination, programm_address); end if; tmp_cursor := programm_t.next(tmp_cursor); if programm_t.has_element(tmp_cursor) then if programm_t.key(tmp_cursor) < programm_address then error_parse(""rewrite next command: "" & hex(get(programm_address))); end if; end if; end command_to_programm; function parse_register (s : string) return word is begin if not validate_register(s) then error_parse(s & "" is not register""); end if; return word'value(cdr(s)); end parse_register; procedure parse_operand (addr : in out operand_t; s : string) is open_pos, close_pos : natural; begin if first_element(s) = '#' then addr.mode := m_immediate; if s(s'first + 1) in '0'..'9'|'-' then addr.value := parse_word(cdr(s)); if addr.value in 0..2|4|8|ff then addr.mode := m_constant; end if; elsif in_labels(cdr(s)) then addr.label := get_by_name(cdr(s)); else addr.label := create(cdr(s)); end if; elsif first_element(s) = ''' and s'length = 3 then addr.mode := m_immediate; addr.value := character'pos(s(s'first + 1)); elsif first_element(s) = '@' then if last_element(s) = '+' then addr.mode := m_indirect_autoincrement; addr.register := parse_register(s((s'first + 1)..(s'last - 1))); else addr.mode := m_indirect_register; addr.register := parse_register(cdr(s)); end if; elsif validate_register(s) then addr.mode := m_register; addr.register := parse_register(s); elsif first_element(s) = '&' and then s'length > 1 then addr.mode := m_absolute; if s(s'first + 1) in '0'..'9'|'-' then addr.value := parse_word(cdr(s)); addr.label := null_label; elsif in_labels(cdr(s)) then addr.label := get_by_name(cdr(s)); else addr.label := create(cdr(s)); end if; elsif first_element(s) in '0'..'9' and last_element(s) /= ')' then addr.mode := m_symbolic; addr.value := parse_word(s); addr.label := null_label; elsif in_labels(s) then addr.mode := m_symbolic; addr.label := get_by_name(s); elsif validate_variable(s) then addr.mode := m_symbolic; addr.label := create(s); else open_pos := fix.index(s, ""(""); close_pos := fix.index(s, "")""); if open_pos > s'first and close_pos > (open_pos + 1) then addr.mode := m_indexed; addr.value := parse_word(s(s'first..(open_pos - 1))); addr.register := parse_register(s((open_pos + 1)..(close_pos - 1))); else error_parse(s & "" error parse operand""); end if; end if; end parse_operand; function parse_operation (s : string) return record_handler_type is begin if command = null_command then if not validate_command(s) then error_parse(s & "" unknown operation""); end if; if endswith(s, "".b"") then command.command := commands'value(""f_"" & s(s'first..(s'last - 2))); command.bw := false; elsif endswith(s, "".w"") then command.command := commands'value(""f_"" & s(s'first..(s'last - 2))); else command.command := commands'value(""f_"" & s); end if; if command.command in two_commands then command.num_operands := 2; return (ptr => parse_operation'access); elsif command.command in zero_emulated_commands|f_reti then null; else command.num_operands := 1; return (ptr => parse_operation'access); end if; elsif command.source = null_operand then parse_operand(command.source, s); if command.num_operands = 2 then return (ptr => parse_operation'access); end if; else parse_operand(command.destination, s); end if; command_to_programm(command); command := null_command; return (ptr => parse_main'access); end parse_operation; function parse_raw (s : string) return record_handler_type is begin if car(s) in 'a'..'z' then if in_labels(s) then command.source.value := get(get(get_by_name(s))); elsif not validate_variable(s) then error_parse(s & "" bad name""); else command.source.value := get_var_val(s); end if; else command.source.value := parse_word(s); end if; -- command.source.value := swpb(command.source.value); command.source.mode := m_constant; command.command := f_raw; command.num_operands := 0; command_to_programm(command); command := null_command; return (ptr => parse_main'access); end parse_raw; function parse_string (s : string) return record_handler_type is i : natural := s'first; begin if s'length < 3 then error_parse(s & "" error string""); end if; command.source.label := null_label; command.source.mode := m_constant; command.command := f_raw; command.num_operands := 0; while i /= s'last + 1 loop if s(i) = '""' then if i /= s'last then error_parse(""end of string before end""); end if; command := null_command; return (ptr => parse_main'access); end if; if s(i) = '\\' then if i = s'last then error_parse("" \\ end of string""); end if; inc(i); end if; command.source.value := character'pos(s(i)); command_to_programm(command); inc(i); end loop; command := null_command; return (ptr => parse_string'access); end parse_string; function parse_call_macros (s : string) return record_handler_type is begin if get_macros_name_params(s) then getter.macros.call(unb.to_string(macro_name), unb.to_string(macro_params)); macro_name := unb.null_unbounded_string; macro_params := unb.null_unbounded_string; return (ptr => parse_main'access); end if; return (ptr => parse_call_macros'access); end parse_call_macros; function parse_main (s : string) return record_handler_type is begin if first_element(s) = '.' then return parse_instruction(s); elsif last_element(s) = ':' then return parse_label(s(s'first..(s'last - 1))); elsif first_element(s) in 'a'..'z' then if fix.index(s, ""("") > 1 then return parse_call_macros(s); elsif validate_command(s) then return parse_operation(s); else return parse_raw(s); end if; elsif first_element(s) in '0'..'9' then return parse_raw(s); elsif first_element(s) = '""' then return parse_string(s((s'first + 1)..s'last)); else error_parse(""error "" & s); end if; return (ptr => parse_main'access); end parse_main; -- function preparse (s : string) return string is -- start_pos, end_pos, comment_pos : natural; -- begin -- comment_pos := fix.index(s, "";"", ada.strings.forward); -- start_pos := fix.index(s, ""{"", ada.strings.backward); -- if start_pos > 0 and start_pos < comment_pos then -- end_pos := fix.index(s, ""}"", start_pos, ada.strings.forward); -- if end_pos < start_pos or end_pos > comment_pos then -- error_parse(""error """""" & s & """""" no closed brackets""); -- end if; -- return preparse( -- s(s'first..(start_pos-1)) & -- parse_precompile(s((start_pos + 1)..(end_pos - 1)) & ';') & -- s((end_pos + 1)..s'last)); -- end if; -- return s; -- end preparse; -- вынести в модуль и сделать через финализе type code_t is access all unb.unbounded_string; type pre_code_t is record start_pos, end_pos : natural; code : code_t; end record; result : aliased unb.unbounded_string; -- type for_loop_t is record -- start_i, end_i, cur_i : natural; -- cursor : environment_t.cursor := environment_t.no_element; -- code : unb.unbounded_string; -- last : positive := 1; -- end record; -- for_loop_status : natural := 0; -- package for_loops_t is new ada.containers.vectors(element_type => for_loop_t, index_type => natural); -- for_loops : for_loops_t.vector; -- tmp_for_loop, last_for_loop : for_loop_t; -- for_end_offset : natural := 0; function pre_code_cmp (a, b : pre_code_t) return boolean is begin return false; end pre_code_cmp; package pre_codes_t is new ada.containers.doubly_linked_lists(pre_code_t, pre_code_cmp); pre_codes : pre_codes_t.list; end_asm : boolean := false; -- type record_getter_type; -- type getter_type is access function (getter : in out record_getter_type) return character; -- type record_getter_type is record -- ptr : getter_type; -- end record; -- current_file : ada.text_io.file_type; -- function get_from_file (getter : in out record_getter_type) return character is -- begin -- if ada.text_io.end_of_file(current_file) then -- return ascii.nul; -- end if; -- end get_from_file; function get_line return string is use type unb.unbounded_string; use type ada.containers.count_type; -- start_for : constant unb.unbounded_string := unb.to_unbounded_string("".for""); -- end_for : constant unb.unbounded_string := unb.to_unbounded_string("".end_for""); -- in_for : constant unb.unbounded_string := unb.to_unbounded_string(""in""); last_code : code_t := result'access; c : character; -- tb : boolean; -- dots_pos : natural; begin loop result := unb.null_unbounded_string; loop -- -- if not for_loops_t.is_empty(for_loops) then -- c := ' '; -- if unb.length(last_for_loop.code) < last_for_loop.last then -- inc(last_for_loop.cur_i); -- last_for_loop.last := 1; -- environment.replace_element(last_for_loop.cursor, word(last_for_loop.cur_i)); -- else -- c := unb.element(last_for_loop.code, last_for_loop.last); -- inc(last_for_loop.last); -- end if; -- if last_for_loop.cur_i > last_for_loop.end_i then -- for_loop_status := 0; -- environment.delete(last_for_loop.cursor); -- for_loops.delete_last; -- if for_loops_t.length(for_loops) > 0 then -- last_for_loop := for_loops_t.last_element(for_loops); -- end if; -- end if; -- -- elsif ada.text_io.end_of_file(file) then -- -- c := ' '; -- -- end_asm := true; -- else c := getter.get; if c = ascii.nul then end_asm := true; return """"; end if; -- end if; -- if for_loop_status = 4 then -- unb.append(tmp_for_loop.code, c); -- -- if ada.text_io.end_of_line(file) and for_loops_t.is_empty(for_loops) then -- -- unb.append(tmp_for_loop.code, ' '); -- -- end if; -- end if; -- \\; \\{ \\} \\ \\, \\\\ \\. -- if c = ';' then -- if not ada.text_io.end_of_line(file) then -- ada.text_io.skip_line(file); -- end if; -- exit when pre_codes_t.is_empty(pre_codes); if c = '{' then pre_codes.append((0, 0, new unb.unbounded_string)); last_code := pre_codes_t.last_element(pre_codes).code; elsif c = '}' then if pre_codes_t.is_empty(pre_codes) then error_parse(""""""}"""" without start""); end if; if pre_codes_t.has_element(pre_codes_t.previous(pre_codes_t.last(pre_codes))) then unb.append(pre_codes_t.element(pre_codes_t.previous(pre_codes_t.last(pre_codes))).code.all, parse_precompile(unb.to_string(last_code.all) & ';')); else unb.append(result, parse_precompile(unb.to_string(last_code.all) & ';')); end if; -- free(last_code); pre_codes.delete_last; if pre_codes_t.is_empty(pre_codes) then last_code := result'access; else last_code := pre_codes_t.last_element(pre_codes).code; end if; elsif pre_codes_t.is_empty(pre_codes) and c in ' '|',' then exit; else unb.append(last_code.all, c); end if; -- if ada.text_io.end_of_line(file) and for_loop_status /= 5 and for_loops_t.is_empty(for_loops) then -- exit when pre_codes_t.is_empty(pre_codes); -- unb.append(last_code.all, ' '); -- end if; end loop; -- if for_loop_status = 1 then -- validate_variable_assert(unb.to_string(result)); -- environment.insert(unb.to_string(result), 0, tmp_for_loop.cursor, tb); -- if not tb then -- error_parse(""variable name """""" & unb.to_string(result & """""" already defined"")); -- end if; -- inc(for_loop_status); -- elsif for_loop_status = 2 then -- if result /= in_for then -- error_parse(""error format for""); -- end if; -- inc(for_loop_status); -- elsif for_loop_status = 3 then -- dots_pos := unb.index(result, ""..""); -- if dots_pos < 2 or (dots_pos + 1) >= unb.length(result) then -- error_parse(""error range: "" & unb.to_string(result)); -- end if; -- tmp_for_loop.start_i := natural(parse_word(unb.slice(result, 1, dots_pos - 1))); -- tmp_for_loop.cur_i := tmp_for_loop.start_i; -- tmp_for_loop.end_i := natural(parse_word(unb.slice(result, dots_pos + 2, unb.length(result)))); -- environment.replace_element(tmp_for_loop.cursor, word(tmp_for_loop.cur_i)); -- inc(for_loop_status); -- elsif result = start_for then -- if for_loop_status = 4 then -- inc(for_end_offset); -- else -- for_loop_status := 1; -- tmp_for_loop.code := unb.null_unbounded_string; -- tmp_for_loop.last := 1; -- end if; -- elsif for_loop_status = 4 then -- if result = end_for then -- if for_end_offset /= 0 then -- dec(for_end_offset); -- else -- unb.replace_slice(tmp_for_loop.code, unb.length(tmp_for_loop.code) - 8, unb.length(tmp_for_loop.code), "" ""); -- if for_loops_t.length(for_loops) > 0 then -- for_loops.replace_element(for_loops_t.last(for_loops), last_for_loop); -- end if; -- last_for_loop := tmp_for_loop; -- for_loops.append(last_for_loop); -- for_loop_status := 5; -- end if; -- end if; -- else return unb.to_string(result); -- end if; end loop; return """"; end get_line; procedure from_file is -- file : ada.text_io.file_type; -- tmp_ustr : unb.unbounded_string; handler_ptr : handler_type := parse_main'access; -- cur_pos : natural := 0; -- last_space : natural := 0; begin -- getter.file.open(path); while not end_asm loop -- print(end_asm'img & path); declare l : constant string := get_line; begin -- print(l & end_asm'img); if l /= """" then handler_ptr := handler_ptr(l).ptr; end if; end; end loop; end_asm := false; -- ada.text_io.open(file, ada.text_io.in_file, path); -- while not end_asm loop -- declare -- l : constant string := get_line(file); -- begin -- if l /= """" then -- handler_ptr := handler_ptr(l).ptr; -- end if; -- end; -- end loop; -- end_asm := false; -- ada.text_io.close(file); exception when this_error: parse_error => if ada.exceptions.exception_message(this_error) /= """" then print('[' & ltrim(getter.get_line'img) & ""]: "" & ada.exceptions.exception_message(this_error)); end if; -- ada.text_io.close(file); raise parse_error with """"; when ada.io_exceptions.name_error => -- error_parse(""no such file "" & path); raise; when others => -- if ada.text_io.is_open(file) then -- ada.text_io.close(file); -- end if; raise; end from_file; procedure update_checksum (var : in out word; val : word) is begin var := var + (val and 255); var := var + sr(val, 8); end update_checksum; function word_to_str_revers (val : word) return string is begin return image(sr(val, 8) or sl(val, 8), 16); end word_to_str_revers; out_text : unb.unbounded_string; cur : programm_t.cursor; line_addr : pos_addr_t; package line_t is new ada.strings.bounded.generic_bounded_length(max => 40); out_file : ada.text_io.file_type; words : words_t(0..18); size : word := 0; procedure command_to_words (cmd : command_t; addr : pos_addr_t) is operation : word := 0; offset : word := 0; procedure set_bits (pos, length : natural; val : word) is begin operation := (operation and (sl(((2 ** length) - 1), pos - length) xor ff)) or sl(val and ((2 ** length) - 1), pos - length); end set_bits; procedure repr_ext_word (op : operand_t) is begin if operand_has_ext_word(op) then inc(words(0)); incd(offset); if op.label /= null_label and then get(op.label) = null_pos_addr then error_parse(""label "" & name(op.label) & "" used but not defined""); end if; if op.mode = m_absolute then if op.label /= null_label then words(words(0)) := get(get(op.label)); else words(words(0)) := op.value; end if; elsif op.mode = m_immediate then if op.label /= null_label then words(words(0)) := get(get(op.label)); else words(words(0)) := op.value; end if; elsif op.mode = m_symbolic then if op.label /= null_label then words(words(0)) := get(get(op.label) - addr) - offset; else words(words(0)) := op.value - get(addr) - offset; end if; else words(words(0)) := op.value; end if; end if; end repr_ext_word; procedure repr_destination is begin if cmd.command not in two_commands then return; end if; case cmd.destination.mode is when m_register => set_bits(8, 1, 0); set_bits(4, 4, cmd.destination.register); when m_indexed => set_bits(8, 1, 1); set_bits(4, 4, cmd.destination.register); when m_symbolic => set_bits(8, 1, 1); set_bits(4, 4, r_pc); when m_absolute => set_bits(8, 1, 1); set_bits(4, 4, r_sr); when others => error_parse(cdr(cmd.destination.mode'img, 2) & "" not be used for destination""); end case; repr_ext_word(cmd.destination); end repr_destination; procedure source_to_operation (pos : natural) is begin case cmd.source.mode is when m_register|m_indexed|m_indirect_register|m_indirect_autoincrement => set_bits(pos, 4, cmd.source.register); when m_symbolic|m_immediate => set_bits(pos, 4, r_pc); when m_absolute => set_bits(pos, 4, r_sr); when m_constant => if cmd.source.value = 0 then set_bits(6, 2, 0); set_bits(pos, 4, 3); elsif cmd.source.value = 1 then set_bits(6, 2, 1); set_bits(pos, 4, 3); elsif cmd.source.value = 2 then set_bits(6, 2, 2); set_bits(pos, 4, 3); elsif cmd.source.value = 4 then set_bits(6, 2, 2); set_bits(pos, 4, r_sr); elsif cmd.source.value = 8 then set_bits(6, 2, 3); set_bits(pos, 4, r_sr); elsif cmd.source.value = -1 then set_bits(6, 2, 3); set_bits(pos, 4, 3); else error_parse(""constant not constant""); end if; end case; end source_to_operation; procedure repr_operands is begin if cmd.command in jump_commands|f_raw then return; end if; if cmd.source.mode = m_register then set_bits(6, 2, 0); elsif cmd.source.mode in m_indexed|m_symbolic|m_absolute then set_bits(6, 2, 1); elsif cmd.source.mode = m_indirect_register then set_bits(6, 2, 2); elsif cmd.source.mode in m_indirect_autoincrement|m_immediate then set_bits(6, 2, 3); end if; set_bits(7, 1, to_word(not cmd.bw)); if cmd.command in single_commands then source_to_operation(4); set_bits(13, 6, commands'pos(cmd.command) - commands'pos(single_commands'first) + 32); elsif cmd.command in two_commands then source_to_operation(12); set_bits(16, 4, commands'pos(cmd.command) - commands'pos(two_commands'first) + 4); end if; repr_ext_word(cmd.source); repr_destination; end repr_operands; w : word := 0; begin if cmd.command = f_raw then set_bits(16, 16, cmd.source.value); elsif cmd.command in jump_commands then set_bits(16, 3, 1); set_bits(13, 3, commands'pos(cmd.command) - commands'pos(jump_commands'first)); if cmd.source.mode /= m_symbolic then error_parse(""jump operand must be symbolic""); end if; if cmd.source.label = null_label then if odd(cmd.source.value) then error_parse(""jump addres ["" & cmd.source.value'img & "" ] must be even""); end if; w := sr((cmd.source.value - get(addr) - 2), 1); elsif get(cmd.source.label) = null_pos_addr then error_parse(""label "" & name(cmd.source.label) & "" used but not defined""); else w := sr(get(get(cmd.source.label) - addr - create(2)), 1); end if; if w in 16#200#..16#7dff# then if cmd.source.label /= null_label then error_parse(""jump to "" & name(cmd.source.label) & "" address > 10bit""); else error_parse(""jump to "" & cmd.source.value'img & "" address > 10bit""); end if; end if; set_bits(10, 10, w); end if; inc(words(0)); w := words(0); repr_operands; words(w) := operation; end command_to_words; procedure append_line is l : word := word'min(words(0), 8); checksum : word; begin if l = 0 then return; end if; size := size + l * 2; checksum := l * 2; update_checksum(checksum, get(line_addr)); unb.append(out_text, ':' & cdr(image(l * 2, 16), 2) & image(get(line_addr), 16) & ""00""); for i in 1..l loop update_checksum(checksum, words(i)); unb.append(out_text, word_to_str_revers(words(i))); end loop; unb.append(out_text, cdr(image(256 - (checksum and 255), 16), 2) & ascii.cr & ascii.lf); if words(0) > 8 then for i in 9..words(0) loop words(i - 8) := words(i); end loop; words(0) := words(0) - 8; line_addr := line_addr + word(16); else if programm_t.has_element(cur) then line_addr := programm_t.key(cur); end if; words(0) := 0; end if; end append_line; reti_inserted : boolean := false; reti_cursor : programm_t.cursor; reti_address : pos_addr_t; begin print("" 0xfa [http://0xfa.space]""); print(""a0xfa v0.1.0 - msp430 assembler (ihex format [https://wikipedia.org/wiki/Intel_HEX])""); print(""""); if word'size > ada.containers.hash_type'size then error(""hash type error""); end if; if word'size > natural'size then error(""integer size error""); end if; if ada.command_line.argument_count /= 2 then error(""format: a0xfa input_file_path output_file_path""); end if; getter.file.open(ada.command_line.argument(1)); from_file; reti_address := create(get_var_val(""mem_code_end"") - 1); loop programm_t.insert(programm, reti_address, (f_reti, null_operand, null_operand, 0, true), reti_cursor, reti_inserted); exit when reti_inserted; dec(reti_address); end loop; for i in 32736..32767 loop programm_t.insert(programm, address.create(word(i * 2)), (f_raw, (m_constant, get(reti_address), 0, null_label), null_operand, 0, true), reti_cursor, reti_inserted); end loop; cur := programm.first; line_addr := programm.first_key; words(0) := 0; while programm_t.has_element(cur) loop command_to_words(programm_t.element(cur), programm_t.key(cur)); programm_t.next(cur); if words(0) >= 8 then append_line; end if; if not programm_t.has_element(cur) or else programm_t.key(cur) /= (line_addr + words(0) * 2) then append_line; end if; end loop; unb.append(out_text, "":00000001FF""); ada.text_io.create(out_file, name => ada.command_line.argument(2)); ada.text_io.put(out_file, unb.to_string(out_text)); ada.text_io.close(out_file); print(""done. size:"" & size'img & ""b""); exception when this_error: parse_error => error(ada.exceptions.exception_message(this_error)); when this_error: ada.io_exceptions.use_error => error(""Error: "" & ada.exceptions.exception_message(this_error)); end a0xfa; ",12376,False,2314.4735387093274,median "// tag::HeaderFullDisplayName[] = reference.usp_RepoObject_update_SysObjectQueryPlan - P // end::HeaderFullDisplayName[] == existing_properties // tag::existing_properties[] :ExistsProperty--antorareferencedlist: :ExistsProperty--antorareferencinglist: :ExistsProperty--is_repo_managed: :ExistsProperty--is_ssas: :ExistsProperty--referencedobjectlist: :ExistsProperty--sql_modules_definition: :ExistsProperty--AntoraParameterList: // end::existing_properties[] == RepoObject_guid // tag::RepoObject_guid[] 9D90291C-9D61-EB11-84DC-A81E8446D5B0 // end::RepoObject_guid[] == RepoObject_FullDisplayName2 // tag::RepoObject_FullDisplayName2[] reference.usp_RepoObject_update_SysObjectQueryPlan // end::RepoObject_FullDisplayName2[] == SysObject_type // tag::SysObject_type[] P // end::SysObject_type[] == SysObject_type_name // tag::SysObject_type_name[] stored procedure // end::SysObject_type_name[] == SysObject_id // tag::SysObject_id[] 1858105660 // end::SysObject_id[] == SysObject_modify_date // tag::SysObject_modify_date[] 2021-10-02 13:23:35 // end::SysObject_modify_date[] == AntoraColumnDetails // tag::AntoraColumnDetails[] // end::AntoraColumnDetails[] == AntoraPkColumnTableRows // tag::AntoraPkColumnTableRows[] // end::AntoraPkColumnTableRows[] == AntoraNonPkColumnTableRows // tag::AntoraNonPkColumnTableRows[] // end::AntoraNonPkColumnTableRows[] == AntoraIndexList // tag::AntoraIndexList[] // end::AntoraIndexList[] == AntoraMeasureDetails // tag::AntoraMeasureDetails[] // end::AntoraMeasureDetails[] == AntoraMeasureDescriptions == AntoraParameterList // tag::AntoraParameterList[] * @execution_instance_guid (uniqueidentifier) * @ssis_execution_id (bigint) * @sub_execution_id (int) * @parent_execution_log_id (bigint) // end::AntoraParameterList[] == AntoraXrefCulturesList // tag::AntoraXrefCulturesList[] * xref:dhw:sqldb:reference.usp_repoobject_update_sysobjectqueryplan.adoc[] - // end::AntoraXrefCulturesList[] == cultures_count // tag::cultures_count[] 1 // end::cultures_count[] == Other tags source: property.RepoObjectProperty_cross As rop_cross === additional_reference_csv // tag::additional_reference_csv[] // end::additional_reference_csv[] === AdocUspSteps // tag::adocuspsteps[] // end::adocuspsteps[] === AntoraReferencedList // tag::antorareferencedlist[] * xref:dhw:sqldb:logs.usp_executionlog_insert.adoc[] * xref:dhw:sqldb:reference.repoobject_queryplan.adoc[] * xref:dhw:sqldb:repo.repoobject.adoc[] * xref:dhw:sqldb:repo.repoobject_gross.adoc[] // end::antorareferencedlist[] === AntoraReferencingList // tag::antorareferencinglist[] * xref:dhw:sqldb:repo.usp_main.adoc[] // end::antorareferencinglist[] === Description // tag::description[] // end::description[] === exampleUsage // tag::exampleusage[] // end::exampleusage[] === exampleUsage_2 // tag::exampleusage_2[] // end::exampleusage_2[] === exampleUsage_3 // tag::exampleusage_3[] // end::exampleusage_3[] === exampleUsage_4 // tag::exampleusage_4[] // end::exampleusage_4[] === exampleUsage_5 // tag::exampleusage_5[] // end::exampleusage_5[] === exampleWrong_Usage // tag::examplewrong_usage[] // end::examplewrong_usage[] === has_execution_plan_issue // tag::has_execution_plan_issue[] // end::has_execution_plan_issue[] === has_get_referenced_issue // tag::has_get_referenced_issue[] // end::has_get_referenced_issue[] === has_history // tag::has_history[] // end::has_history[] === has_history_columns // tag::has_history_columns[] // end::has_history_columns[] === InheritanceType // tag::inheritancetype[] // end::inheritancetype[] === is_persistence // tag::is_persistence[] // end::is_persistence[] === is_persistence_check_duplicate_per_pk // tag::is_persistence_check_duplicate_per_pk[] // end::is_persistence_check_duplicate_per_pk[] === is_persistence_check_for_empty_source // tag::is_persistence_check_for_empty_source[] // end::is_persistence_check_for_empty_source[] === is_persistence_delete_changed // tag::is_persistence_delete_changed[] // end::is_persistence_delete_changed[] === is_persistence_delete_missing // tag::is_persistence_delete_missing[] // end::is_persistence_delete_missing[] === is_persistence_insert // tag::is_persistence_insert[] // end::is_persistence_insert[] === is_persistence_truncate // tag::is_persistence_truncate[] // end::is_persistence_truncate[] === is_persistence_update_changed // tag::is_persistence_update_changed[] // end::is_persistence_update_changed[] === is_repo_managed // tag::is_repo_managed[] 0 // end::is_repo_managed[] === is_ssas // tag::is_ssas[] 0 // end::is_ssas[] === microsoft_database_tools_support // tag::microsoft_database_tools_support[] // end::microsoft_database_tools_support[] === MS_Description // tag::ms_description[] // end::ms_description[] === persistence_source_RepoObject_fullname // tag::persistence_source_repoobject_fullname[] // end::persistence_source_repoobject_fullname[] === persistence_source_RepoObject_fullname2 // tag::persistence_source_repoobject_fullname2[] // end::persistence_source_repoobject_fullname2[] === persistence_source_RepoObject_guid // tag::persistence_source_repoobject_guid[] // end::persistence_source_repoobject_guid[] === persistence_source_RepoObject_xref // tag::persistence_source_repoobject_xref[] // end::persistence_source_repoobject_xref[] === pk_index_guid // tag::pk_index_guid[] // end::pk_index_guid[] === pk_IndexPatternColumnDatatype // tag::pk_indexpatterncolumndatatype[] // end::pk_indexpatterncolumndatatype[] === pk_IndexPatternColumnName // tag::pk_indexpatterncolumnname[] // end::pk_indexpatterncolumnname[] === pk_IndexSemanticGroup // tag::pk_indexsemanticgroup[] // end::pk_indexsemanticgroup[] === ReferencedObjectList // tag::referencedobjectlist[] * [logs].[usp_ExecutionLog_insert] * [reference].[RepoObject_QueryPlan] * [repo].[RepoObject] * [repo].[RepoObject_gross] // end::referencedobjectlist[] === usp_persistence_RepoObject_guid // tag::usp_persistence_repoobject_guid[] // end::usp_persistence_repoobject_guid[] === UspExamples // tag::uspexamples[] // end::uspexamples[] === uspgenerator_usp_id // tag::uspgenerator_usp_id[] // end::uspgenerator_usp_id[] === UspParameters // tag::uspparameters[] // end::uspparameters[] == Boolean Attributes source: property.RepoObjectProperty WHERE property_int = 1 // tag::boolean_attributes[] // end::boolean_attributes[] == PlantUML diagrams === PlantUML Entity // tag::puml_entity[] [plantuml, entity-{docname}, svg, subs=macros] .... 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:reference.usp_repoobject_update_sysobjectqueryplan.adoc[]"" as reference.usp_RepoObject_update_SysObjectQueryPlan << P >> { -- } .... // end::puml_entity[] === PlantUML Entity 1 1 FK // tag::puml_entity_1_1_fk[] [plantuml, entity_1_1_fk-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_fk[] === PlantUML 1 1 ObjectRef // tag::puml_entity_1_1_objectref[] [plantuml, entity_1_1_objectref-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:logs.usp_executionlog_insert.adoc[]"" as logs.usp_ExecutionLog_insert << P >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobject_queryplan.adoc[]"" as reference.RepoObject_QueryPlan << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.usp_repoobject_update_sysobjectqueryplan.adoc[]"" as reference.usp_RepoObject_update_SysObjectQueryPlan << P >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobject.adoc[]"" as repo.RepoObject << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_gross.adoc[]"" as repo.RepoObject_gross << V >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_main.adoc[]"" as repo.usp_main << P >> { -- } logs.usp_ExecutionLog_insert <.. reference.usp_RepoObject_update_SysObjectQueryPlan reference.RepoObject_QueryPlan <.. reference.usp_RepoObject_update_SysObjectQueryPlan reference.usp_RepoObject_update_SysObjectQueryPlan <.. repo.usp_main repo.RepoObject <.. reference.usp_RepoObject_update_SysObjectQueryPlan repo.RepoObject_gross <.. reference.usp_RepoObject_update_SysObjectQueryPlan footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_objectref[] === PlantUML 30 0 ObjectRef // tag::puml_entity_30_0_objectref[] [plantuml, entity_30_0_objectref-{docname}, svg, subs=macros] .... @startuml 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:config.ftv_dwh_database.adoc[]"" as config.ftv_dwh_database << IF >> { -- } entity ""puml-link:dhw:sqldb:config.ftv_get_parameter_value.adoc[]"" as config.ftv_get_parameter_value << IF >> { -- } entity ""puml-link:dhw:sqldb:config.parameter.adoc[]"" as config.Parameter << U >> { - **Parameter_name** : (varchar(100)) - **sub_Parameter** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:configt.parameter_default.adoc[]"" as configT.Parameter_default << V >> { - **Parameter_name** : (varchar(52)) - **sub_Parameter** : (nvarchar(26)) -- } entity ""puml-link:dhw:sqldb:configt.spt_values.adoc[]"" as configT.spt_values << U >> { -- } entity ""puml-link:dhw:sqldb:configt.type.adoc[]"" as configT.type << V >> { **type** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:docs.fs_cleanstringforfilename.adoc[]"" as docs.fs_cleanStringForFilename << FN >> { -- } entity ""puml-link:dhw:sqldb:logs.executionlog.adoc[]"" as logs.ExecutionLog << U >> { - **id** : (bigint) -- } entity ""puml-link:dhw:sqldb:logs.usp_executionlog_insert.adoc[]"" as logs.usp_ExecutionLog_insert << P >> { -- } entity ""puml-link:dhw:sqldb:property.external_repoobjectproperty.adoc[]"" as property.external_RepoObjectProperty << U >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.fs_get_repoobjectproperty_nvarchar.adoc[]"" as property.fs_get_RepoObjectProperty_nvarchar << FN >> { -- } entity ""puml-link:dhw:sqldb:property.propertyname_repoobject.adoc[]"" as property.PropertyName_RepoObject << V >> { **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.propertyname_repoobject_t.adoc[]"" as property.PropertyName_RepoObject_T << U >> { **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty.adoc[]"" as property.RepoObjectProperty << U >> { - **RepoObjectProperty_id** : (int) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_external_src.adoc[]"" as property.RepoObjectProperty_external_src << V >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_external_tgt.adoc[]"" as property.RepoObjectProperty_external_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_selectedpropertyname_split.adoc[]"" as property.RepoObjectProperty_SelectedPropertyName_split << V >> { -- } entity ""puml-link:dhw:sqldb:reference.additional_reference.adoc[]"" as reference.additional_Reference << U >> { - **Id** : (int) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_database.adoc[]"" as reference.additional_Reference_database << V >> { - **AntoraComponent** : (nvarchar(128)) - **AntoraModule** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_database_t.adoc[]"" as reference.additional_Reference_database_T << U >> { - **AntoraComponent** : (nvarchar(128)) - **AntoraModule** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_properties_src.adoc[]"" as reference.additional_Reference_from_properties_src << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) **referencing_Column** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_properties_tgt.adoc[]"" as reference.additional_Reference_from_properties_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) **referencing_Column** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_ssas_src.adoc[]"" as reference.additional_Reference_from_ssas_src << V >> { **referenced_AntoraComponent** : (nvarchar(128)) **referenced_AntoraModule** : (nvarchar(128)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(500)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) - **referencing_Schema** : (nvarchar(128)) - **referencing_Object** : (nvarchar(128)) **referencing_Column** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_ssas_tgt.adoc[]"" as reference.additional_Reference_from_ssas_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(128)) **referenced_AntoraModule** : (nvarchar(128)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(500)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) - **referencing_Schema** : (nvarchar(128)) - **referencing_Object** : (nvarchar(128)) **referencing_Column** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_guid.adoc[]"" as reference.additional_Reference_guid << V >> { -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_is_external.adoc[]"" as reference.additional_Reference_is_external << V >> { -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_object.adoc[]"" as reference.additional_Reference_Object << V >> { - **AntoraComponent** : (nvarchar(128)) - **AntoraModule** : (nvarchar(128)) - **SchemaName** : (nvarchar(128)) - **ObjectName** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_object_t.adoc[]"" as reference.additional_Reference_Object_T << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_objectcolumn.adoc[]"" as reference.additional_Reference_ObjectColumn << V >> { - **AntoraComponent** : (nvarchar(128)) - **AntoraModule** : (nvarchar(128)) - **SchemaName** : (nvarchar(128)) - **ObjectName** : (nvarchar(128)) **ColumnName** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_objectcolumn_t.adoc[]"" as reference.additional_Reference_ObjectColumn_T << U >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_wo_columns_from_properties_src.adoc[]"" as reference.additional_Reference_wo_columns_from_properties_src << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_wo_columns_from_properties_tgt.adoc[]"" as reference.additional_Reference_wo_columns_from_properties_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.repoobject_queryplan.adoc[]"" as reference.RepoObject_QueryPlan << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.repoobject_reference.adoc[]"" as reference.RepoObject_reference << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobject_reference_additional.adoc[]"" as reference.RepoObject_reference_additional << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobject_reference_persistence.adoc[]"" as reference.RepoObject_reference_persistence << V >> { **referenced_RepoObject_guid** : (uniqueidentifier) - **referencing_RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.repoobject_reference_persistence_target_as_source.adoc[]"" as reference.RepoObject_reference_persistence_target_as_source << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobject_reference_sqlexpressiondependencies.adoc[]"" as reference.RepoObject_reference_SqlExpressionDependencies << V >> { **referenced_RepoObject_guid** : (uniqueidentifier) **referencing_RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.repoobject_reference_t.adoc[]"" as reference.RepoObject_reference_T << U >> { **referenced_RepoObject_guid** : (uniqueidentifier) **referencing_RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.repoobject_reference_union.adoc[]"" as reference.RepoObject_reference_union << V >> { **referenced_RepoObject_guid** : (uniqueidentifier) **referencing_RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.repoobject_reference_virtual.adoc[]"" as reference.RepoObject_reference_virtual << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobject_referencedreferencing.adoc[]"" as reference.RepoObject_ReferencedReferencing << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobjectsource_virtual.adoc[]"" as reference.RepoObjectSource_virtual << U >> { - **RepoObject_guid** : (uniqueidentifier) - **Source_RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.usp_repoobject_update_sysobjectqueryplan.adoc[]"" as reference.usp_RepoObject_update_SysObjectQueryPlan << P >> { -- } entity ""puml-link:dhw:sqldb:repo.index_settings.adoc[]"" as repo.Index_Settings << U >> { - **index_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject.adoc[]"" as repo.RepoObject << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_external_src.adoc[]"" as repo.RepoObject_external_src << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_external_tgt.adoc[]"" as repo.RepoObject_external_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_gross.adoc[]"" as repo.RepoObject_gross << V >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobject_gross_persistence.adoc[]"" as repo.RepoObject_gross_persistence << V >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobject_persistence.adoc[]"" as repo.RepoObject_persistence << U >> { - **target_RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_ssas_src.adoc[]"" as repo.RepoObject_SSAS_src << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_ssas_tgt.adoc[]"" as repo.RepoObject_SSAS_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn.adoc[]"" as repo.RepoObjectColumn << U >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_external_src.adoc[]"" as repo.RepoObjectColumn_external_src << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_external_tgt.adoc[]"" as repo.RepoObjectColumn_external_tgt << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_ssas_src.adoc[]"" as repo.RepoObjectColumn_SSAS_src << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_ssas_tgt.adoc[]"" as repo.RepoObjectColumn_SSAS_tgt << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.reposchema.adoc[]"" as repo.RepoSchema << U >> { - **RepoSchema_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.reposchema_ssas_src.adoc[]"" as repo.RepoSchema_ssas_src << V >> { - **RepoSchema_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:repo.reposchema_ssas_tgt.adoc[]"" as repo.RepoSchema_ssas_tgt << V >> { - **RepoSchema_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.syscolumn_repoobjectcolumn_via_name.adoc[]"" as repo.SysColumn_RepoObjectColumn_via_name << V >> { -- } entity ""puml-link:dhw:sqldb:repo.sysobject_repoobject_via_name.adoc[]"" as repo.SysObject_RepoObject_via_name << V >> { -- } entity ""puml-link:dhw:sqldb:repo_sys.extendedproperties.adoc[]"" as repo_sys.ExtendedProperties << V >> { -- } entity ""puml-link:dhw:sqldb:repo_sys.sql_expression_dependencies.adoc[]"" as repo_sys.sql_expression_dependencies << V >> { -- } entity ""puml-link:dhw:sqldb:repo_sys.syscolumn.adoc[]"" as repo_sys.SysColumn << V >> { -- } entity ""puml-link:dhw:sqldb:repo_sys.sysobject.adoc[]"" as repo_sys.SysObject << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.additional_reference_step1.adoc[]"" as ssas.additional_Reference_step1 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json.adoc[]"" as ssas.model_json << U >> { - **databasename** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_10.adoc[]"" as ssas.model_json_10 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_20.adoc[]"" as ssas.model_json_20 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_201_descriptions_multiline.adoc[]"" as ssas.model_json_201_descriptions_multiline << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_2011_descriptions_stragg.adoc[]"" as ssas.model_json_2011_descriptions_StrAgg << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31_tables.adoc[]"" as ssas.model_json_31_tables << V >> { - **databasename** : (nvarchar(128)) **tables_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31_tables_t.adoc[]"" as ssas.model_json_31_tables_T << U >> { - **databasename** : (nvarchar(128)) **tables_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_311_tables_columns.adoc[]"" as ssas.model_json_311_tables_columns << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_columns_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_311_tables_columns_t.adoc[]"" as ssas.model_json_311_tables_columns_T << U >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_columns_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_313_tables_partitions.adoc[]"" as ssas.model_json_313_tables_partitions << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_partitions_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_3131_tables_partitions_source.adoc[]"" as ssas.model_json_3131_tables_partitions_source << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_partitions_name** : (nvarchar(500)) **tables_partitions_source_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31311_tables_partitions_source_posfrom.adoc[]"" as ssas.model_json_31311_tables_partitions_source_PosFrom << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_313111_tables_partitions_source_stringfrom.adoc[]"" as ssas.model_json_313111_tables_partitions_source_StringFrom << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_3131111_tables_partitions_source_posdot.adoc[]"" as ssas.model_json_3131111_tables_partitions_source_PosDot << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31311111_tables_partitions_source_part123.adoc[]"" as ssas.model_json_31311111_tables_partitions_source_Part123 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_316_tables_descriptions_multiline.adoc[]"" as ssas.model_json_316_tables_descriptions_multiline << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_3161_tables_descriptions_stragg.adoc[]"" as ssas.model_json_3161_tables_descriptions_StrAgg << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_33_datasources.adoc[]"" as ssas.model_json_33_dataSources << V >> { - **databasename** : (nvarchar(128)) **dataSources_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_33_datasources_t.adoc[]"" as ssas.model_json_33_dataSources_T << U >> { - **databasename** : (nvarchar(128)) **dataSources_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:sys_dwh.columns.adoc[]"" as sys_dwh.columns << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.computed_columns.adoc[]"" as sys_dwh.computed_columns << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.default_constraints.adoc[]"" as sys_dwh.default_constraints << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.extended_properties.adoc[]"" as sys_dwh.extended_properties << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.identity_columns.adoc[]"" as sys_dwh.identity_columns << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.indexes.adoc[]"" as sys_dwh.indexes << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.objects.adoc[]"" as sys_dwh.objects << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.parameters.adoc[]"" as sys_dwh.parameters << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.schemas.adoc[]"" as sys_dwh.schemas << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.sql_expression_dependencies.adoc[]"" as sys_dwh.sql_expression_dependencies << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.sql_modules.adoc[]"" as sys_dwh.sql_modules << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.tables.adoc[]"" as sys_dwh.tables << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.types.adoc[]"" as sys_dwh.types << SN >> { -- } entity ""puml-link:dhw:sqldb:uspgenerator.generatorusp.adoc[]"" as uspgenerator.GeneratorUsp << U >> { - **id** : (int) -- } config.ftv_dwh_database <.. repo_sys.sql_expression_dependencies config.ftv_dwh_database <.. repo_sys.ExtendedProperties config.ftv_dwh_database <.. repo_sys.SysColumn config.ftv_get_parameter_value <.. repo.RepoObject_external_src config.ftv_get_parameter_value <.. repo.RepoObject_gross config.ftv_get_parameter_value <.. ssas.additional_Reference_step1 config.ftv_get_parameter_value <.. reference.additional_Reference_is_external config.Parameter <.. property.PropertyName_RepoObject config.Parameter <.. config.ftv_dwh_database config.Parameter <.. config.ftv_get_parameter_value configT.Parameter_default <.. config.Parameter configT.spt_values <.. configT.type configT.type <.. repo.RepoObject_gross_persistence configT.type <.. reference.RepoObject_ReferencedReferencing configT.type <.. repo.RepoObject_gross docs.fs_cleanStringForFilename <.. repo.RepoObject_gross_persistence docs.fs_cleanStringForFilename <.. reference.RepoObject_ReferencedReferencing docs.fs_cleanStringForFilename <.. repo.RepoObject_gross logs.ExecutionLog <.. logs.usp_ExecutionLog_insert logs.usp_ExecutionLog_insert <.. reference.usp_RepoObject_update_SysObjectQueryPlan property.external_RepoObjectProperty <.. property.RepoObjectProperty_external_src property.fs_get_RepoObjectProperty_nvarchar <.. repo.RepoObject_gross property.PropertyName_RepoObject <.. property.PropertyName_RepoObject_T property.PropertyName_RepoObject_T <.. property.RepoObjectProperty_external_tgt property.RepoObjectProperty <.. property.fs_get_RepoObjectProperty_nvarchar property.RepoObjectProperty <.. property.RepoObjectProperty_SelectedPropertyName_split property.RepoObjectProperty <.. property.PropertyName_RepoObject property.RepoObjectProperty_external_src <.. property.RepoObjectProperty_external_tgt property.RepoObjectProperty_external_tgt <.. property.RepoObjectProperty property.RepoObjectProperty_SelectedPropertyName_split <.. reference.additional_Reference_from_properties_src property.RepoObjectProperty_SelectedPropertyName_split <.. reference.additional_Reference_wo_columns_from_properties_src reference.additional_Reference <.. reference.additional_Reference_guid reference.additional_Reference <.. reference.additional_Reference_is_external reference.additional_Reference_database <.. reference.additional_Reference_database_T reference.additional_Reference_database_T <.. repo.RepoObject_gross reference.additional_Reference_from_properties_src <.. reference.additional_Reference_from_properties_tgt reference.additional_Reference_from_properties_tgt <.. reference.additional_Reference reference.additional_Reference_from_ssas_src <.. reference.additional_Reference_from_ssas_tgt reference.additional_Reference_from_ssas_tgt <.. reference.additional_Reference reference.additional_Reference_guid <.. reference.RepoObject_reference_additional reference.additional_Reference_is_external <.. reference.additional_Reference_ObjectColumn reference.additional_Reference_is_external <.. reference.additional_Reference_database reference.additional_Reference_is_external <.. reference.additional_Reference_Object reference.additional_Reference_Object <.. reference.additional_Reference_Object_T reference.additional_Reference_Object_T <.. repo.RepoObject_external_src reference.additional_Reference_Object_T <.. repo.RepoObjectColumn_external_src reference.additional_Reference_ObjectColumn <.. reference.additional_Reference_ObjectColumn_T reference.additional_Reference_ObjectColumn_T <.. repo.RepoObjectColumn_external_src reference.additional_Reference_wo_columns_from_properties_src <.. reference.additional_Reference_wo_columns_from_properties_tgt reference.additional_Reference_wo_columns_from_properties_tgt <.. reference.additional_Reference reference.RepoObject_QueryPlan <.. repo.RepoObject_gross reference.RepoObject_QueryPlan <.. reference.usp_RepoObject_update_SysObjectQueryPlan reference.RepoObject_reference <.. reference.RepoObject_reference_T reference.RepoObject_reference_additional <.. reference.RepoObject_reference_union reference.RepoObject_reference_persistence <.. reference.RepoObject_reference_union reference.RepoObject_reference_persistence_target_as_source <.. reference.RepoObject_reference_union reference.RepoObject_reference_persistence_target_as_source <.. reference.RepoObject_reference reference.RepoObject_reference_SqlExpressionDependencies <.. reference.RepoObject_reference_persistence_target_as_source reference.RepoObject_reference_SqlExpressionDependencies <.. reference.RepoObject_reference_union reference.RepoObject_reference_T <.. reference.RepoObject_ReferencedReferencing reference.RepoObject_reference_union <.. reference.RepoObject_reference reference.RepoObject_reference_virtual <.. reference.RepoObject_reference_union reference.RepoObject_ReferencedReferencing <.. repo.RepoObject_gross reference.RepoObjectSource_virtual <.. reference.RepoObject_reference_virtual repo.Index_Settings <.. repo.RepoObject_gross repo.RepoObject <.. reference.RepoObject_reference_persistence repo.RepoObject <.. repo.SysObject_RepoObject_via_name repo.RepoObject <.. repo.SysColumn_RepoObjectColumn_via_name repo.RepoObject <.. repo.RepoObject_gross_persistence repo.RepoObject <.. repo.RepoObjectColumn_external_src repo.RepoObject <.. property.RepoObjectProperty_external_tgt repo.RepoObject <.. repo.RepoObject_external_src repo.RepoObject <.. reference.additional_Reference_guid repo.RepoObject <.. reference.RepoObject_reference_virtual repo.RepoObject <.. reference.RepoObject_reference_SqlExpressionDependencies repo.RepoObject <.. repo.RepoObject_gross repo.RepoObject <.. reference.usp_RepoObject_update_SysObjectQueryPlan repo.RepoObject_external_src <.. repo.RepoObject_external_tgt repo.RepoObject_external_tgt <.. repo.RepoObject repo.RepoObject_external_tgt <.. repo.RepoObjectColumn_external_tgt repo.RepoObject_gross <.. reference.usp_RepoObject_update_SysObjectQueryPlan repo.RepoObject_gross_persistence <.. reference.RepoObject_reference_persistence_target_as_source repo.RepoObject_persistence <.. repo.RepoObject_gross repo.RepoObject_persistence <.. repo.RepoObject_gross_persistence repo.RepoObject_persistence <.. reference.RepoObject_reference_persistence repo.RepoObject_SSAS_src <.. repo.RepoObject_SSAS_tgt repo.RepoObject_SSAS_tgt <.. repo.RepoObjectColumn_SSAS_tgt repo.RepoObject_SSAS_tgt <.. repo.RepoObject repo.RepoObjectColumn <.. repo.SysColumn_RepoObjectColumn_via_name repo.RepoObjectColumn <.. reference.additional_Reference_guid repo.RepoObjectColumn_external_src <.. repo.RepoObjectColumn_external_tgt repo.RepoObjectColumn_external_tgt <.. repo.RepoObjectColumn repo.RepoObjectColumn_SSAS_src <.. repo.RepoObjectColumn_SSAS_tgt repo.RepoObjectColumn_SSAS_tgt <.. repo.RepoObjectColumn repo.RepoSchema <.. repo.RepoObject_SSAS_src repo.RepoSchema_ssas_src <.. repo.RepoSchema_ssas_tgt repo.RepoSchema_ssas_tgt <.. repo.RepoSchema repo.SysColumn_RepoObjectColumn_via_name <.. repo_sys.sql_expression_dependencies repo.SysObject_RepoObject_via_name <.. repo_sys.sql_expression_dependencies repo_sys.ExtendedProperties <.. repo_sys.SysObject repo_sys.ExtendedProperties <.. repo_sys.SysColumn repo_sys.sql_expression_dependencies <.. reference.RepoObject_reference_SqlExpressionDependencies repo_sys.SysColumn <.. repo.SysColumn_RepoObjectColumn_via_name repo_sys.SysObject <.. repo.SysObject_RepoObject_via_name repo_sys.SysObject <.. repo_sys.SysColumn ssas.additional_Reference_step1 <.. reference.additional_Reference_from_ssas_src ssas.model_json <.. ssas.model_json_10 ssas.model_json_10 <.. ssas.model_json_20 ssas.model_json_20 <.. repo.RepoSchema_ssas_src ssas.model_json_20 <.. ssas.model_json_201_descriptions_multiline ssas.model_json_20 <.. ssas.model_json_33_dataSources ssas.model_json_20 <.. ssas.model_json_31_tables ssas.model_json_201_descriptions_multiline <.. ssas.model_json_2011_descriptions_StrAgg ssas.model_json_2011_descriptions_StrAgg <.. repo.RepoSchema_ssas_src ssas.model_json_31_tables <.. ssas.model_json_31_tables_T ssas.model_json_31_tables_T <.. ssas.model_json_311_tables_columns ssas.model_json_31_tables_T <.. repo.RepoObject_SSAS_src ssas.model_json_31_tables_T <.. ssas.model_json_313_tables_partitions ssas.model_json_31_tables_T <.. repo.RepoObject_gross ssas.model_json_31_tables_T <.. ssas.model_json_316_tables_descriptions_multiline ssas.model_json_311_tables_columns <.. ssas.model_json_311_tables_columns_T ssas.model_json_311_tables_columns_T <.. repo.RepoObjectColumn_SSAS_src ssas.model_json_311_tables_columns_T <.. ssas.additional_Reference_step1 ssas.model_json_313_tables_partitions <.. ssas.model_json_3131_tables_partitions_source ssas.model_json_3131_tables_partitions_source <.. ssas.model_json_31311_tables_partitions_source_PosFrom ssas.model_json_31311_tables_partitions_source_PosFrom <.. ssas.model_json_313111_tables_partitions_source_StringFrom ssas.model_json_313111_tables_partitions_source_StringFrom <.. ssas.model_json_3131111_tables_partitions_source_PosDot ssas.model_json_3131111_tables_partitions_source_PosDot <.. ssas.model_json_31311111_tables_partitions_source_Part123 ssas.model_json_31311111_tables_partitions_source_Part123 <.. ssas.additional_Reference_step1 ssas.model_json_316_tables_descriptions_multiline <.. ssas.model_json_3161_tables_descriptions_StrAgg ssas.model_json_3161_tables_descriptions_StrAgg <.. repo.RepoObject_gross ssas.model_json_33_dataSources <.. ssas.model_json_33_dataSources_T ssas.model_json_33_dataSources_T <.. ssas.additional_Reference_step1 sys_dwh.columns <.. repo_sys.ExtendedProperties sys_dwh.columns <.. repo_sys.SysColumn sys_dwh.computed_columns <.. repo_sys.SysColumn sys_dwh.default_constraints <.. repo_sys.SysColumn sys_dwh.extended_properties <.. repo_sys.ExtendedProperties sys_dwh.identity_columns <.. repo_sys.SysColumn sys_dwh.indexes <.. repo_sys.ExtendedProperties sys_dwh.objects <.. repo_sys.ExtendedProperties sys_dwh.objects <.. repo_sys.SysObject sys_dwh.parameters <.. repo_sys.ExtendedProperties sys_dwh.schemas <.. repo_sys.SysObject sys_dwh.schemas <.. repo_sys.ExtendedProperties sys_dwh.sql_expression_dependencies <.. repo_sys.sql_expression_dependencies sys_dwh.sql_modules <.. repo_sys.SysObject sys_dwh.tables <.. repo_sys.SysObject sys_dwh.types <.. repo_sys.SysColumn uspgenerator.GeneratorUsp <.. repo.RepoObject_gross footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_30_0_objectref[] === PlantUML 0 30 ObjectRef // tag::puml_entity_0_30_objectref[] [plantuml, entity_0_30_objectref-{docname}, svg, subs=macros] .... @startuml 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:reference.usp_repoobject_update_sysobjectqueryplan.adoc[]"" as reference.usp_RepoObject_update_SysObjectQueryPlan << P >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_main.adoc[]"" as repo.usp_main << P >> { -- } reference.usp_RepoObject_update_SysObjectQueryPlan <.. repo.usp_main footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_0_30_objectref[] === PlantUML 1 1 ColumnRef // tag::puml_entity_1_1_colref[] [plantuml, entity_1_1_colref-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:logs.usp_executionlog_insert.adoc[]"" as logs.usp_ExecutionLog_insert << P >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobject_queryplan.adoc[]"" as reference.RepoObject_QueryPlan << U >> { - **RepoObject_guid** : (uniqueidentifier) SysObject_query_executed_dt : (datetime) SysObject_query_plan : (xml) -- } entity ""puml-link:dhw:sqldb:reference.usp_repoobject_update_sysobjectqueryplan.adoc[]"" as reference.usp_RepoObject_update_SysObjectQueryPlan << P >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobject.adoc[]"" as repo.RepoObject << U >> { - **RepoObject_guid** : (uniqueidentifier) external_AntoraComponent : (nvarchar(128)) external_AntoraModule : (nvarchar(128)) has_execution_plan_issue : (bit) has_get_referenced_issue : (bit) indent_sql_modules_definition : (tinyint) Inheritance_Source_fullname : (nvarchar(261)) Inheritance_StringAggSeparatorSql : (nvarchar(4000)) InheritanceDefinition : (nvarchar(4000)) InheritanceType : (tinyint) - is_DocsExclude : (bit) - is_external : (bit) is_repo_managed : (bit) is_required_ObjectMerge : (bit) - is_ssas : (bit) is_SysObject_missing : (bit) - modify_dt : (datetime) pk_index_guid : (uniqueidentifier) pk_IndexPatternColumnName_new : (nvarchar(4000)) Repo_history_table_guid : (uniqueidentifier) Repo_temporal_type : (tinyint) - RepoObject_name : (nvarchar(128)) RepoObject_Referencing_Count : (int) - RepoObject_schema_name : (nvarchar(128)) - RepoObject_type : (char(2)) SysObject_id : (int) SysObject_modify_date : (datetime) - SysObject_name : (nvarchar(128)) - SysObject_parent_object_id : (int) - SysObject_schema_name : (nvarchar(128)) SysObject_type : (char(2)) ~ has_different_sys_names : (bit) # is_RepoObject_name_uniqueidentifier : (int) # is_SysObject_name_uniqueidentifier : (int) ~ node_id : (bigint) # RepoObject_fullname : (nvarchar(261)) # RepoObject_fullname2 : (nvarchar(257)) # SysObject_fullname : (nvarchar(261)) # SysObject_fullname2 : (nvarchar(257)) ~ SysObject_query_sql : (nvarchar(406)) ~ usp_persistence_fullname : (nvarchar(273)) # usp_persistence_fullname2 : (nvarchar(269)) # usp_persistence_name : (nvarchar(140)) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_gross.adoc[]"" as repo.RepoObject_gross << V >> { AntoraComponent : (nvarchar(max)) AntoraModule : (nvarchar(max)) Description : (nvarchar(max)) external_AntoraComponent : (nvarchar(128)) external_AntoraModule : (nvarchar(128)) external_DatabaseName : (nvarchar(128)) external_RepoDatabaseName : (nvarchar(128)) has_different_sys_names : (bit) has_execution_plan_issue : (bit) has_get_referenced_issue : (bit) has_history : (bit) has_history_columns : (bit) history_schema_name : (nvarchar(128)) history_table_name : (nvarchar(128)) indent_sql_modules_definition : (tinyint) Inheritance_StringAggSeparatorSql : (nvarchar(4000)) InheritanceDefinition : (nvarchar(4000)) InheritanceType : (tinyint) - is_DocsExclude : (bit) is_DocsOutput : (int) - is_external : (bit) - is_in_reference : (int) is_persistence : (bit) is_persistence_check_duplicate_per_pk : (bit) is_persistence_check_for_empty_source : (bit) is_persistence_delete_changed : (bit) is_persistence_delete_missing : (bit) is_persistence_insert : (bit) is_persistence_merge_delete_missing : (bit) is_persistence_merge_insert : (bit) is_persistence_merge_update_changed : (bit) is_persistence_persist_source : (bit) is_persistence_truncate : (bit) is_persistence_update_changed : (bit) is_repo_managed : (bit) - is_RepoObject_name_uniqueidentifier : (int) is_required_ObjectMerge : (bit) - is_ssas : (bit) is_SysObject_missing : (bit) - is_SysObject_name_uniqueidentifier : (int) - modify_dt : (datetime) node_id : (bigint) persistence_source_RepoObject_fullname : (nvarchar(261)) persistence_source_RepoObject_fullname2 : (nvarchar(257)) persistence_source_RepoObject_guid : (uniqueidentifier) persistence_source_RepoObject_xref : (nvarchar(4000)) persistence_source_SysObject_fullname : (nvarchar(261)) persistence_source_SysObject_fullname_or_tempsource : (nvarchar(261)) persistence_source_SysObject_fullname2 : (nvarchar(257)) persistence_source_SysObject_xref : (nvarchar(4000)) pk_index_guid : (uniqueidentifier) pk_IndexPatternColumnDatatype : (nvarchar(4000)) pk_IndexPatternColumnName : (nvarchar(4000)) pk_IndexPatternColumnName_new : (nvarchar(4000)) pk_IndexSemanticGroup : (nvarchar(512)) postscript : (nvarchar(max)) prescript : (nvarchar(max)) Property_ms_description : (nvarchar(4000)) Repo_history_table_guid : (uniqueidentifier) Repo_temporal_type : (tinyint) - RepoObject_fullname : (nvarchar(261)) - RepoObject_fullname2 : (nvarchar(257)) - RepoObject_guid : (uniqueidentifier) - RepoObject_name : (nvarchar(128)) RepoObject_Referencing_Count : (int) - RepoObject_schema_name : (nvarchar(128)) - RepoObject_type : (char(2)) RepoObject_type_name : (nvarchar(128)) - SysObject_fullname : (nvarchar(261)) - SysObject_fullname2 : (nvarchar(257)) SysObject_id : (int) SysObject_modify_date : (datetime) - SysObject_name : (nvarchar(128)) - SysObject_parent_object_id : (int) SysObject_query_executed_dt : (datetime) SysObject_query_plan : (xml) - SysObject_query_sql : (nvarchar(406)) - SysObject_schema_name : (nvarchar(128)) SysObject_type : (char(2)) SysObject_type_name : (nvarchar(128)) tables_dataCategory : (nvarchar(500)) tables_description : (nvarchar(max)) tables_isHidden : (bit) temporal_type : (tinyint) - usp_persistence_name : (nvarchar(140)) usp_persistence_RepoObject_guid : (uniqueidentifier) uspgenerator_usp_id : (int) -- } entity ""puml-link:dhw:sqldb:repo.usp_main.adoc[]"" as repo.usp_main << P >> { -- } logs.usp_ExecutionLog_insert <.. reference.usp_RepoObject_update_SysObjectQueryPlan reference.RepoObject_QueryPlan <.. reference.usp_RepoObject_update_SysObjectQueryPlan reference.usp_RepoObject_update_SysObjectQueryPlan <.. repo.usp_main repo.RepoObject <.. reference.usp_RepoObject_update_SysObjectQueryPlan repo.RepoObject_gross <.. reference.usp_RepoObject_update_SysObjectQueryPlan footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_colref[] == sql_modules_definition // tag::sql_modules_definition[] [%collapsible] ======= [source,sql,numbered,indent=0] ---- /* references on column level target: repo.RepoObjectSource_from_query_plan source: query plan analysis of the execution of a query like `Vselect top (1) * into #foo from (SELECT * FROM sss.aaa)` First update query plan and write them into repo.RepoObject then analyse the query plans and update results into EXEC [repo_sys].[usp_RepoObject_update_SysObjectQueryPlan] EXEC [repo].[usp_RepoObjectSource_QueryPlan] some query plans can't be extracted, some can be extracted but not analyzed in this case mark the RepoObject in repo.RepoObject SET [has_execution_plan_issue] = 1 */ CREATE Procedure [reference].[usp_RepoObject_update_SysObjectQueryPlan] -- some optional parameters, used for logging @execution_instance_guid UniqueIdentifier = Null --SSIS system variable ExecutionInstanceGUID could be used, but other any other guid , @ssis_execution_id BigInt = Null --only SSIS system variable ServerExecutionID should be used, or any other consistent number system, do not mix , @sub_execution_id Int = Null , @parent_execution_log_id BigInt = Null As Declare @current_execution_log_id BigInt , @current_execution_guid UniqueIdentifier = NewId () , @source_object NVarchar(261) = Null , @target_object NVarchar(261) = Null , @proc_id Int = @@ProcId , @proc_schema_name NVarchar(128) = Object_Schema_Name ( @@ProcId ) , @proc_name NVarchar(128) = Object_Name ( @@ProcId ) , @event_info NVarchar(Max) , @step_id Int = 0 , @step_name NVarchar(1000) = Null , @rows Int; Set @event_info = ( Select event_info From sys.dm_exec_input_buffer ( @@Spid, Current_Request_Id ()) ); If @execution_instance_guid Is Null Set @execution_instance_guid = NewId (); --SET @rows = @@ROWCOUNT; Set @step_id = @step_id + 1; Set @step_name = N'start'; --SET @source_object = NULL --SET @target_object = NULL Exec logs.usp_ExecutionLog_insert @execution_instance_guid = @execution_instance_guid , @ssis_execution_id = @ssis_execution_id , @sub_execution_id = @sub_execution_id , @parent_execution_log_id = @parent_execution_log_id , @current_execution_guid = @current_execution_guid , @proc_id = @proc_id , @proc_schema_name = @proc_schema_name , @proc_name = @proc_name , @event_info = @event_info , @step_id = @step_id , @step_name = @step_name , @source_object = @source_object , @target_object = @target_object , @inserted = Null , @updated = Null , @deleted = Null , @info_01 = Null , @info_02 = Null , @info_03 = Null , @info_04 = Null , @info_05 = Null , @info_06 = Null , @info_07 = Null , @info_08 = Null , @info_09 = Null , @execution_log_id = @current_execution_log_id Output; -- ----START -- Declare @RepoObject_guid UniqueIdentifier , @SysObject_query_sql NVarchar(4000) , @SysObject_query_plan Xml , @SysObject_query_executed_dt DateTime , @select_into_query As Varchar(4000); Declare view_cursor Cursor Local Fast_Forward For -- Select ro.RepoObject_guid , ro.SysObject_query_sql , ro.SysObject_query_plan , ro.SysObject_query_executed_dt --, ro.[SysObject_modify_date] From repo.RepoObject_gross As ro Where -- --only views and tables (for calculated columns) ----we don't need tables, references for calculated columns we have in [repo].[RepoObjectColumn_reference__sql_expression_dependencies] -- [ro].[SysObject_type] IN -- ( -- 'V' , 'U' -- ) --only views ro.SysObject_type = 'V' And ro.SysObject_query_sql <> '' And ( ro.SysObject_query_plan Is Null Or ro.SysObject_query_executed_dt Is Null --query plan could be outdated Or ro.SysObject_query_executed_dt < ro.SysObject_modify_date ) --we can't catch some issues with sys.dm_exec_query_stats --thats why as an workaround we exclude them And IsNull ( ro.has_execution_plan_issue, 0 ) = 0 Order By ro.RepoObject_guid; --FOR UPDATE OF [SysObject_query_plan] -- , [SysObject_query_executed_dt] Open view_cursor; Fetch Next From view_cursor Into @RepoObject_guid , @SysObject_query_sql , @SysObject_query_plan , @SysObject_query_executed_dt; While @@Fetch_Status <> -1 Begin If @@Fetch_Status <> -2 Begin Set @select_into_query = 'select top (1) * into #foo from (' + @SysObject_query_sql + ') as src'; --information about the current RepoObject in case of error --some query plans can't be extracted, some can be extracted but not analyzed --in this case mark the RepoObject in repo.RepoObject --SET [has_execution_plan_issue] = 1 Print Concat ( @RepoObject_guid, ' ', @SysObject_query_sql ); Print 'if you get issues and TRY CATCH doesn''t solve them, then execute this:'; Print Concat ( 'UPDATE [repo].[RepoObject] SET [has_execution_plan_issue] = 1 WHERE [RepoObject_guid] = ''' , @RepoObject_guid , '''' ); Declare @xml_plan As Xml = Null , @xml_generation_tries As TinyInt = 10; While @xml_plan Is Null And @xml_generation_tries > 0 -- There is no guaranty that plan will be cached. Begin Print @select_into_query; Execute ( @select_into_query ); --most time TRY CATCH doesn't work --sometimes any select from sys.dm_exec_query_stats results in an error: --Msg 681, Level 16, State 3, Line 1 --Attempting to set a non-NULL-able column's value to NULL. --sometimes we get other errors Begin Try Select @xml_plan = pln.query_plan From sys.dm_exec_query_stats As qry Cross Apply sys.dm_exec_sql_text ( qry.sql_handle ) As txt Cross Apply sys.dm_exec_query_plan ( qry.plan_handle ) As pln Where txt.text = @select_into_query; End Try Begin Catch Print 'Can''t get query_plan'; Update ro Set has_execution_plan_issue = 1 From repo.RepoObject As ro Where ro.RepoObject_guid = @RepoObject_guid; End Catch; Set @xml_generation_tries = @xml_generation_tries - 1; End; --PRINT 'IF @xml_plan IS NULL'; --IF @xml_plan IS NULL -- BEGIN -- --RAISERROR(N'Can''t extract XML query plan from cache.' , 15 , 0); -- RAISERROR(N'Can''t extract XML query plan from cache.' , 10 , 0); -- RETURN; --END; Merge Into [reference].RepoObject_QueryPlan T Using ( Select @RepoObject_guid , @xml_plan ) As S ( RepoObject_guid, SysObject_query_plan ) On S.RepoObject_guid = T.RepoObject_guid When Matched Then Update Set SysObject_query_plan = S.SysObject_query_plan , SysObject_query_executed_dt = GetDate () When Not Matched Then Insert ( RepoObject_guid , SysObject_query_plan , SysObject_query_executed_dt ) Values ( S.RepoObject_guid , S.SysObject_query_plan , GetDate () ); --UPDATE repo.RepoObject --SET [SysObject_query_plan] = @xml_plan -- , [SysObject_query_executed_dt] = GETDATE() --WHERE [RepoObject_guid] = @RepoObject_guid Set @rows = @@RowCount; Set @step_id = @step_id + 1; Set @step_name = N'UPDATE SET [SysObject_query_plan] = @xml_plan, [SysObject_query_executed_dt] = GETDATE()'; Set @source_object = N'[repo].[RepoObject]'; Set @target_object = N'[repo].[RepoObject]'; Exec logs.usp_ExecutionLog_insert @execution_instance_guid = @execution_instance_guid , @ssis_execution_id = @ssis_execution_id , @sub_execution_id = @sub_execution_id , @parent_execution_log_id = @parent_execution_log_id , @current_execution_guid = @current_execution_guid , @proc_id = @proc_id , @proc_schema_name = @proc_schema_name , @proc_name = @proc_name , @event_info = @event_info , @step_id = @step_id , @step_name = @step_name , @source_object = @source_object , @target_object = @target_object , @inserted = Null , @updated = @rows , @deleted = Null , @info_01 = @RepoObject_guid , @info_02 = @SysObject_query_sql , @info_03 = Null , @info_04 = Null , @info_05 = Null , @info_06 = Null , @info_07 = Null , @info_08 = Null , @info_09 = Null; End; Fetch Next From view_cursor Into @RepoObject_guid , @SysObject_query_sql , @SysObject_query_plan , @SysObject_query_executed_dt; End; Close view_cursor; Deallocate view_cursor; -- --END -- --SET @rows = @@ROWCOUNT; Set @step_id = @step_id + 1; Set @step_name = N'end'; Set @source_object = Null; Set @target_object = Null; Exec logs.usp_ExecutionLog_insert @execution_instance_guid = @execution_instance_guid , @ssis_execution_id = @ssis_execution_id , @sub_execution_id = @sub_execution_id , @parent_execution_log_id = @parent_execution_log_id , @current_execution_guid = @current_execution_guid , @proc_id = @proc_id , @proc_schema_name = @proc_schema_name , @proc_name = @proc_name , @event_info = @event_info , @step_id = @step_id , @step_name = @step_name , @source_object = @source_object , @target_object = @target_object , @inserted = Null , @updated = Null , @deleted = Null , @info_01 = Null , @info_02 = Null , @info_03 = Null , @info_04 = Null , @info_05 = Null , @info_06 = Null , @info_07 = Null , @info_08 = Null , @info_09 = Null; ---- ======= // end::sql_modules_definition[] ",16150,True,3024.7948172624315,median "------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- D E B U G -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2015, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- . -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ package body Debug is --------------------------------- -- Summary of Debug Flag Usage -- --------------------------------- -- Debug flags for compiler (GNAT1) -- da Generate messages tracking semantic analyzer progress -- db Show encoding of type names for debug output -- dc List names of units as they are compiled -- dd Dynamic allocation of tables messages generated -- de List the entity table -- df Full tree/source print (includes withed units) -- dg Print source from tree (generated code only) -- dh Generate listing showing loading of name table hash chains -- di Generate messages for visibility linking/delinking -- dj Suppress ""junk null check"" for access parameter values -- dk Generate GNATBUG message on abort, even if previous errors -- dl Generate unit load trace messages -- dm -- dn Generate messages for node/list allocation -- do Print source from tree (original code only) -- dp Generate messages for parser scope stack push/pops -- dq No auto-alignment of small records -- dr Generate parser resynchronization messages -- ds Print source from tree (including original and generated stuff) -- dt Print full tree -- du Uncheck categorization pragmas -- dv Output trace of overload resolution -- dw Print trace of semantic scope stack -- dx Force expansion on, even if no code being generated -- dy Print tree of package Standard -- dz Print source of package Standard -- dA All entities included in representation information output -- dB Output debug encoding of type names and variants -- dC Output debugging information on check suppression -- dD Delete elaboration checks in inner level routines -- dE Apply elaboration checks to predefined units -- dF Front end data layout enabled -- dG Generate all warnings including those normally suppressed -- dH Hold (kill) call to gigi -- dI Inhibit internal name numbering in gnatG listing -- dJ Output debugging trace info for JGNAT (Java VM version of GNAT) -- dK Kill all error messages -- dL Output trace information on elaboration checking -- dM Assume all variables are modified (no current values) -- dN No file name information in exception messages -- dO Output immediate error messages -- dP Do not check for controlled objects in preelaborable packages -- dQ -- dR Bypass check for correct version of s-rpc -- dS Never convert numbers to machine numbers in Sem_Eval -- dT Convert to machine numbers only for constant declarations -- dU Enable garbage collection of unreachable entities -- dV Enable viewing of all symbols in debugger -- dW Disable warnings on calls for IN OUT parameters -- dX Display messages on reads of potentially uninitialized scalars -- dY Enable configurable run-time mode -- dZ Generate listing showing the contents of the dispatch tables -- d.a Force Target_Strict_Alignment mode to True -- d.b Dump backend types -- d.c Generate inline concatenation, do not call procedure -- d.d Disable atomic synchronization -- d.e Enable atomic synchronization -- d.f Inhibit folding of static expressions -- d.g Enable conversion of raise into goto -- d.h Minimize the creation of public internal symbols for concatenation -- d.i Ignore Warnings pragmas -- d.j Generate listing of frontend inlined calls -- d.k -- d.l Use Ada 95 semantics for limited function returns -- d.m For -gnatl, print full source only for main unit -- d.n Print source file names -- d.o Generate .NET listing of CIL code -- d.p Enable the .NET CIL verifier -- d.q -- d.r Enable OK_To_Reorder_Components in non-variant records -- d.s Disable expansion of slice move, use memmove -- d.t Disable static allocation of library level dispatch tables -- d.u Enable Modify_Tree_For_C (update tree for c) -- d.v Enable OK_To_Reorder_Components in variant records -- d.w Do not check for infinite loops -- d.x No exception handlers -- d.y -- d.z Restore previous support for frontend handling of Inline_Always -- d.A Read/write Aspect_Specifications hash table to tree -- d.B -- d.C Generate concatenation call, do not generate inline code -- d.D Disable errors on use of overriding keyword in Ada 95 mode -- d.E Turn selected errors into warnings -- d.F Debug mode for GNATprove -- d.G Ignore calls through generic formal parameters for elaboration -- d.H -- d.I Do not ignore enum representation clauses in CodePeer mode -- d.J Disable parallel SCIL generation mode -- d.K -- d.L Depend on back end for limited types in if and case expressions -- d.M Relaxed RM semantics -- d.N Add node to all entities -- d.O Dump internal SCO tables -- d.P Previous (non-optimized) handling of length comparisons -- d.Q Previous (incomplete) style check for binary operators -- d.R Restrictions in ali files in positional form -- d.S Force Optimize_Alignment (Space) -- d.T Force Optimize_Alignment (Time) -- d.U Ignore indirect calls for static elaboration -- d.V -- d.W Print out debugging information for Walk_Library_Items -- d.X Old treatment of indexing aspects -- d.Y -- d.Z Do not enable expansion in configurable run-time mode -- d1 Error msgs have node numbers where possible -- d2 Eliminate error flags in verbose form error messages -- d3 Dump bad node in Comperr on an abort -- d4 Inhibit automatic krunch of predefined library unit files -- d5 Debug output for tree read/write -- d6 Default access unconstrained to thin pointers -- d7 Suppress version/source stamp/compilation time for -gnatv/-gnatl -- d8 Force opposite endianness in packed stuff -- d9 Allow lock free implementation -- d.1 Enable unnesting of nested procedures -- d.2 Allow statements in declarative part -- d.3 -- d.4 -- d.5 -- d.6 -- d.7 -- d.8 -- d.9 -- Debug flags for binder (GNATBIND) -- da All links (including internal units) listed if there is a cycle -- db Output information from Better_Choice -- dc List units as they are chosen -- dd -- de Elaboration dependencies including system units -- df -- dg -- dh -- di Ignore_Errors mode for reading ali files -- dj -- dk -- dl -- dm -- dn List details of manipulation of Num_Pred values -- do Use old preference for elaboration order -- dp -- dq -- dr -- ds -- dt -- du List units as they are acquired -- dv -- dw -- dx Force binder to read xref information from ali files -- dy -- dz -- Debug flags used in package Make and its clients (e.g. GNATMAKE) -- da -- db -- dc -- dd -- de -- df Only output file names, not path names, in log -- dg -- dh Generate listing showing loading of name table hash chains -- di -- dj -- dk -- dl -- dm Display the number of maximum simultaneous compilations -- dn Do not delete temp files created by gnatmake -- do -- dp Prints the contents of the Q used by Make.Compile_Sources -- dq Prints source files as they are enqueued and dequeued -- dr -- ds -- dt Display time stamps when there is a mismatch -- du List units as their ali files are acquired -- dv -- dw Prints the list of units withed by the unit currently explored -- dx -- dy -- dz -------------------------------------------- -- Documentation for Compiler Debug Flags -- -------------------------------------------- -- da Generate messages tracking semantic analyzer progress. A message -- is output showing each node as it gets analyzed, expanded, -- resolved, or evaluated. This option is useful for finding out -- exactly where a bomb during semantic analysis is occurring. -- db In Exp_Dbug, certain type names are encoded to include debugging -- information. This debug switch causes lines to be output showing -- the encodings used. -- dc List names of units as they are compiled. One line of output will -- be generated at the start of compiling each unit (package or -- subprogram). -- dd Dynamic allocation of tables messages generated. Each time a -- table is reallocated, a line is output indicating the expansion. -- de List the entity table -- df Full tree/source print (includes withed units). Normally the tree -- output (dt) or recreated source output (dg,do,ds) includes only -- the main unit. If df is set, then the output in either case -- includes all compiled units (see also dg,do,ds,dt). Note that to -- be effective, this switch must be used in combination with one or -- more of dt, dg, do or ds. -- dg Print the source recreated from the generated tree. In the case -- where the tree has been rewritten this output includes only the -- generated code, not the original code (see also df,do,ds,dz). -- This flag differs from -gnatG in that the output also includes -- non-source generated null statements, and freeze nodes, which -- are normally omitted in -gnatG mode. -- dh Generates a table at the end of a compilation showing how the hash -- table chains built by the Namet package are loaded. This is useful -- in ensuring that the hashing algorithm (in Namet.Hash) is working -- effectively with typical sets of program identifiers. -- di Generate messages for visibility linking/delinking -- dj Suppress ""junk null check"" for access parameters. This flag permits -- Ada programs to pass null parameters to access parameters, and to -- explicitly check such access values against the null literal. -- Neither of these is valid Ada, but both were allowed in versions of -- GNAT before 3.10, so this switch can ease the transition process. -- dk Immediate kill on abort. Normally on an abort (i.e. a call to -- Comperr.Compiler_Abort), the GNATBUG message is not given if -- there is a previous error. This debug switch bypasses this test -- and gives the message unconditionally (useful for debugging). -- dl Generate unit load trace messages. A line of traceback output is -- generated each time a request is made to the library manager to -- load a new unit. -- dn Generate messages for node/list allocation. Each time a node or -- list header is allocated, a line of output is generated. Certain -- other basic tree operations also cause a line of output to be -- generated. This option is useful in seeing where the parser is -- blowing up. -- do Print the source recreated from the generated tree. In the case -- where the tree has been rewritten, this output includes only the -- original code, not the generated code (see also df,dg,ds,dz). -- dp Generate messages for parser scope stack push/pops. A line of -- output by the parser each time the parser scope stack is either -- pushed or popped. Useful in debugging situations where the -- parser scope stack ends up incorrectly synchronized -- dq In layout version 1.38, 2002/01/12, a circuit was implemented -- to give decent default alignment to short records that had no -- specific alignment set. This debug option restores the previous -- behavior of giving such records poor alignments, typically 1. -- This may be useful in dealing with transition. -- dr Generate parser resynchronization messages. Normally the parser -- resynchronizes quietly. With this debug option, two messages -- are generated, one when the parser starts a resynchronization -- skip, and another when it resumes parsing. Useful in debugging -- inadequate error recovery situations. -- ds Print the source recreated from the generated tree. In the case -- where the tree has been rewritten this output includes both the -- generated code and the original code with the generated code -- being enlosed in curly brackets (see also df,do,ds,dz) -- dt Print full tree. The generated tree is output (see also df,dy) -- du Uncheck categorization pragmas. This debug switch causes the -- categorization pragmas (Pure, Preelaborate etc) to be ignored -- so that normal checks are not made (this is particularly useful -- for adding temporary debugging code to units that have pragmas -- that are inconsistent with the debugging code added. -- dv Output trace of overload resolution. Outputs messages for -- overload attempts that involve cascaded errors, or where -- an interepretation is incompatible with the context. -- dw Write semantic scope stack messages. Each time a scope is created -- or removed, a message is output (see the Sem_Ch8.Push_Scope and -- Sem_Ch8.Pop_Scope subprograms). -- dx Force expansion on, even if no code being generated. Normally the -- expander is inhibited if no code is generated. This switch forces -- expansion to proceed normally even if the backend is not being -- called. This is particularly useful for debugging purposes when -- using the front-end only version of the compiler (which normally -- would never do any expansion). -- dy Print tree of package Standard. Normally the tree print out does -- not include package Standard, even if the -df switch is set. This -- switch forces output of the internal tree built for Standard. -- dz Print source of package Standard. Normally the source print out -- does not include package Standard, even if the -df switch is set. -- This switch forces output of the source recreated from the internal -- tree built for Standard. Note that this differs from -gnatS in -- that it prints from the actual tree using the normal Sprint -- circuitry for printing trees. -- dA Forces output of representation information, including full -- information for all internal type and object entities, as well -- as all user defined type and object entities including private -- and incomplete types. This debug switch also automatically sets -- the equivalent of -gnatR3m. -- dB Output debug encodings for types and variants. See Exp_Dbug for -- exact form of the generated output. -- dC Output trace information showing the decisions made during -- check suppression activity in unit Checks. -- dD Delete new elaboration checks. This flag causes GNAT to return -- to the 3.13a elaboration semantics, and to suppress the fixing -- of two bugs. The first is in the context of inner routines in -- dynamic elaboration mode, when the subprogram we are in was -- called at elaboration time by a unit that was also compiled with -- dynamic elaboration checks. In this case, if A calls B calls C, -- and all are in different units, we need an elaboration check at -- each call. These nested checks were only put in recently (see -- version 1.80 of Sem_Elab) and we provide this debug flag to -- revert to the previous behavior in case of regressions. The -- other behavior reverted by this flag is the treatment of the -- Elaborate_Body pragma in static elaboration mode. This used to -- be treated as not needing elaboration checking, but in fact in -- general Elaborate_All is still required because of nested calls. -- dE Apply compile time elaboration checking for with relations between -- predefined units. Normally no checks are made (it seems that at -- least on the SGI, such checks run into trouble). -- dF Front end data layout enabled. Normally front end data layout -- is only enabled if the target parameter Backend_Layout is False. -- This debugging switch enables it unconditionally. -- dG Generate all warnings. Normally Errout suppresses warnings on -- units that are not part of the main extended source, and also -- suppresses warnings on instantiations in the main extended -- source that duplicate warnings already posted on the template. -- This switch stops both kinds of deletion and causes Errout to -- post all warnings sent to it. -- dH Inhibit call to gigi. This is useful for testing front end data -- layout, and may be useful in other debugging situations where -- you do not want gigi to intefere with the testing. -- dI Inhibit internal name numbering in gnatDG listing. Any sequence of -- the form appearing in -- a name is replaced by .... This -- is used in the fixed bugs run to minimize system and version -- dependency in filed -gnatD or -gnatG output. -- dJ Generate debugging trace output for the JGNAT back end. This -- consists of symbolic Java Byte Code sequences for all generated -- classes plus additional information to indicate local variables -- and methods. -- dK Kill all error messages. This debug flag suppresses the output -- of all error messages. It is used in regression tests where the -- error messages are target dependent and irrelevant. -- dL Output trace information on elaboration checking. This debug -- switch causes output to be generated showing each call or -- instantiation as it is checked, and the progress of the recursive -- trace through calls at elaboration time. -- dM Assume all variables have been modified, and ignore current value -- indications. This debug flag disconnects the tracking of constant -- values (see Exp_Ch2.Expand_Current_Value). -- dN Do not generate file name information in exception messages -- dO Output immediate error messages. This causes error messages to -- be output as soon as they are generated (disconnecting several -- circuits for improvement of messages, deletion of duplicate -- messages etc). Useful to diagnose compiler bombs caused by -- erroneous handling of error situations -- dP Do not check for controlled objects in preelaborable packages. -- RM 10.2.1(9) forbids the use of library level controlled objects -- in preelaborable packages, but this restriction is a huge pain, -- especially in the predefined library units. -- dR Bypass the check for a proper version of s-rpc being present -- to use the -gnatz? switch. This allows debugging of the use -- of stubs generation without needing to have GLADE (or some -- other PCS installed). -- dS Omit conversion of fpt numbers to exact machine numbers in -- non-static evaluation contexts (see Check_Non_Static_Context). -- This is intended for testing out timing problems with this -- conversion circuit. -- dT Similar to dS, but omits the conversions only in the case where -- the parent is not a constant declaration. -- dU Enable garbage collection of unreachable entities. This enables -- both the reachability analysis and changing the Is_Public and -- Is_Eliminated flags. -- dV Enable viewing of all symbols in debugger. Causes debug information -- to be generated for all symbols, including internal symbols. This -- is enabled by default for -gnatD, but this switch allows this to -- be enabled without generating modified source files. Note that the -- use of -gnatdV ensures in the dwarf/elf case that all symbols that -- are present in the elf tables are also in the dwarf tables (which -- seems to be required by some tools). Another effect of dV is to -- generate full qualified names, including internal names generated -- for blocks and loops. -- dW Disable warnings when a possibly uninitialized scalar value is -- passed to an IN OUT parameter of a procedure. This usage is a -- quite improper bounded error [erroneous in Ada 83] situation, -- and would normally generate a warning. However, to ease the -- task of transitioning incorrect legacy code, we provide this -- undocumented feature for suppressing these warnings. -- dY Enable configurable run-time mode, just as though the System file -- had Configurable_Run_Time_Mode set to True. This is useful in -- testing high integrity mode. -- dZ Generate listing showing the contents of the dispatch tables. Each -- line has an internally generated number used for references between -- tagged types and primitives. For each primitive the output has the -- following fields: -- -- - Letter 'P' or letter 's': The former indicates that this -- primitive will be located in a primary dispatch table. The -- latter indicates that it will be located in a secondary -- dispatch table. -- -- - Name of the primitive. In case of predefined Ada primitives -- the text ""(predefined)"" is added before the name, and these -- acronyms are used: SR (Stream_Read), SW (Stream_Write), SI -- (Stream_Input), SO (Stream_Output), DA (Deep_Adjust), DF -- (Deep_Finalize). In addition Oeq identifies the equality -- operator, and ""_assign"" the assignment. -- -- - If the primitive covers interface types, two extra fields -- referencing other primitives are generated: ""Alias"" references -- the primitive of the tagged type that covers an interface -- primitive, and ""AI_Alias"" references the covered interface -- primitive. -- -- - The expression ""at #xx"" indicates the slot of the dispatch -- table occupied by such primitive in its corresponding primary -- or secondary dispatch table. -- -- - In case of abstract subprograms the text ""is abstract"" is -- added at the end of the line. -- d.a Force Target_Strict_Alignment to True, even on targets where it -- would normally be false. Can be used for testing strict alignment -- circuitry in the compiler. -- d.b Dump back end types. During Create_Standard, the back end is -- queried for all available types. This option shows them. -- d.c Generate inline concatenation, instead of calling one of the -- System.Concat_n.Str_Concat_n routines in cases where the latter -- routines would normally be called. -- d.d Disable atomic synchronization for all atomic variable references. -- Pragma Enable_Atomic_Synchronization is ignored. -- d.e Enable atomic synchronization for all atomic variable references. -- Pragma Disable_Atomic_Synchronization is ignored, and also the -- compiler switch -gnated is ignored. -- d.f Suppress folding of static expressions. This of course results -- in seriously non-conforming behavior, but is useful sometimes -- when tracking down handling of complex expressions. -- d.g Enables conversion of a raise statement into a goto when the -- relevant handler is statically determinable. For now we only try -- this if this debug flag is set. Later we will enable this more -- generally by default. -- d.h Minimize the creation of public internal symbols for concatenation -- by enforcing a secondary stack-like handling of the final result. -- The target of the concatenation is thus constrained in place and -- initialized with the result instead of acting as its alias. -- d.i Ignore all occurrences of pragma Warnings in the sources. This can -- be used in particular to disable Warnings (Off) to check if any of -- these statements are inappropriate. -- d.j Generate listing of frontend inlined calls and inline calls passed -- to the backend. This is useful to locate skipped calls that must be -- inlined by the frontend. -- d.l Use Ada 95 semantics for limited function returns. This may be -- used to work around the incompatibility introduced by AI-318-2. -- It is useful only in -gnat05 mode. -- d.m When -gnatl is used, the normal output includes full listings of -- all files in the extended main source (body/spec/subunits). If this -- debug switch is used, then the full listing is given only for the -- main source (this corresponds to a previous behavior of -gnatl and -- is used for running the ACATS tests). -- d.n Print source file names as they are loaded. This is useful if the -- compiler has a bug -- these are the files that need to be included -- in a bug report. -- d.o Generate listing showing the IL instructions generated by the .NET -- compiler for each subprogram. -- d.p Enable the .NET CIL verifier. During development the verifier is -- disabled by default and this flag is used to enable it. In the -- future we will reverse this functionality. -- d.r Forces the flag OK_To_Reorder_Components to be set in all record -- base types that have no discriminants. -- d.s Normally the compiler expands slice moves into loops if overlap -- might be possible. This debug flag inhibits that expansion, and -- the back end is expected to use an appropriate routine to handle -- overlap, based on Forward_OK and Backwards_OK flags. -- d.t The compiler has been modified (a fairly extensive modification) -- to generate static dispatch tables for library level tagged types. -- This debug switch disables this modification and reverts to the -- previous dynamic construction of tables. It is there as a possible -- work around if we run into trouble with the new implementation. -- d.u Sets Modify_Tree_For_C mode in which tree is modified to make it -- easier to generate code using a C compiler. -- d.v Forces the flag OK_To_Reorder_Components to be set in all record -- base types that have at least one discriminant (v = variant). -- d.w This flag turns off the scanning of loops to detect possible -- infinite loops. -- d.x No exception handlers in generated code. This causes exception -- handlers to be eliminated from the generated code. They are still -- fully compiled and analyzed, they just get eliminated from the -- code generation step. -- d.z Restore previous front-end support for Inline_Always. In default -- mode, for targets that use the GCC back end (i.e. currently all -- targets except AAMP, .NET, JVM, and GNATprove), Inline_Always is -- handled by the back end. Use of this switch restores the previous -- handling of Inline_Always by the front end on such targets. For the -- targets that do not use the GCC back end, this switch is ignored. -- d.A There seems to be a problem with ASIS if we activate the circuit -- for reading and writing the aspect specification hash table, so -- for now, this is controlled by the debug flag d.A. The hash table -- is only written and read if this flag is set. -- d.C Generate call to System.Concat_n.Str_Concat_n routines in cases -- where we would normally generate inline concatenation code. -- d.D For compatibility with some Ada 95 compilers implementing only -- one feature of Ada 2005 (overriding keyword), disable errors on use -- of overriding keyword in Ada 95 mode. -- d.E Turn selected errors into warnings. This debug switch causes a -- specific set of error messages into warnings. Setting this switch -- causes Opt.Error_To_Warning to be set to True. The intention is -- that this be used for messages representing upwards incompatible -- changes to Ada 2012 that cause previously correct programs to be -- treated as illegal now. The following cases are affected: -- -- Errors relating to overlapping subprogram parameters for cases -- other than IN OUT parameters to functions. -- -- Errors relating to the new rules about not defining equality -- too late so that composition of equality can be assured. -- -- Errors relating to overriding indicators on protected subprogram -- bodies (not an Ada 2012 incompatibility, but might cause errors -- for existing programs assuming they were legal because GNAT -- formerly allowed them). -- d.F Sets GNATprove_Mode to True. This allows debugging the frontend in -- the special mode used by GNATprove. -- d.G Previously the compiler ignored calls via generic formal parameters -- when doing the analysis for the static elaboration model. This is -- now fixed, but we provide this debug flag to revert to the previous -- situation of ignoring such calls to aid in transition. -- d.I Do not ignore enum representation clauses in CodePeer mode. -- The default of ignoring representation clauses for enumeration -- types in CodePeer is good for the majority of Ada code, but in some -- cases being able to change this default might be useful to remove -- some false positives. -- d.J Disable parallel SCIL generation. Normally SCIL file generation is -- done in parallel to speed processing. This switch disables this -- behavior. -- d.L Normally the front end generates special expansion for conditional -- expressions of a limited type. This debug flag removes this special -- case expansion, leaving it up to the back end to handle conditional -- expressions correctly. -- d.M Relaxed RM semantics. This flag sets Opt.Relaxed_RM_Semantics -- See Opt.Relaxed_RM_Semantics for more details. -- d.N Enlarge entities by one node (but don't attempt to use this extra -- node for storage of any flags or fields). This can be used to do -- experiments on the impact of increasing entity sizes. -- d.O Dump internal SCO tables. Before outputting the SCO information to -- the ALI file, the internal SCO tables (SCO_Table/SCO_Unit_Table) -- are dumped for debugging purposes. -- d.P Previous non-optimized handling of length comparisons. Setting this -- flag inhibits the effect of Optimize_Length_Comparison in Exp_Ch4. -- This is there in case we find a situation where the optimization -- malfunctions, to provide a work around. -- d.Q Previous incomplete style checks for binary operators. Style checks -- for token separation rules were incomplete and have been made -- compliant with the documentation. For example, no warning was -- issued for expressions such as 16-One or ""A""&""B"". Setting this flag -- inhibits these new checks. -- d.R As documented in lib-writ.ads, restrictions in the ali file can -- have two forms, positional and named. The named notation is the -- current preferred form, but the use of this debug switch will force -- the use of the obsolescent positional form. -- d.S Force Optimize_Alignment (Space) mode as the default -- d.T Force Optimize_Alignment (Time) mode as the default -- d.U Ignore indirect calls for static elaboration. The static -- elaboration model is conservative, especially regarding indirect -- calls. If you say Proc'Access, it will assume you might call -- Proc. This can cause elaboration cycles at bind time. This flag -- reverts to the behavior of earlier compilers, which ignored -- indirect calls. -- d.W Print out debugging information for Walk_Library_Items, including -- the order in which units are walked. This is primarily for use in -- debugging CodePeer mode. -- d.X A previous version of GNAT allowed indexing aspects to be -- redefined on derived container types, while the default iterator -- was inherited from the aprent type. This non-standard extension -- is preserved temporarily for use by the modelling project under -- debug flag d.X. -- d.Z Normally we always enable expansion in configurable run-time mode -- to make sure we get error messages about unsupported features even -- when compiling in -gnatc mode. But expansion is turned off in this -- case if debug flag -gnatd.Z is used. This is to deal with the case -- where we discover difficulties in this new processing. -- d1 Error messages have node numbers where possible. Normally error -- messages have only source locations. This option is useful when -- debugging errors caused by expanded code, where the source location -- does not give enough information. -- d2 Suppress output of the error position flags for verbose form error -- messages. The messages are still interspersed in the listing, but -- without any error flags or extra blank lines. Also causes an extra -- <<< to be output at the right margin. This is intended to be the -- easiest format for checking conformance of ACATS B tests. This -- flag also suppresses the additional messages explaining why a -- non-static expression is non-static (see Sem_Eval.Why_Not_Static). -- This avoids having to worry about these messages in ACATS testing. -- d3 Causes Comperr to dump the contents of the node for which an abort -- was detected (normally only the Node_Id of the node is output). -- d4 Inhibits automatic krunching of predefined library unit file names. -- Normally, as described in the spec of package Krunch, such files -- are automatically krunched to 8 characters, with special treatment -- of the prefixes Ada, System, and Interfaces. Setting this debug -- switch disables this special treatment. -- d5 Causes the tree read/write circuit to output detailed information -- tracking the data that is read and written element by element. -- d6 Normally access-to-unconstrained-array types are represented -- using fat (double) pointers. Using this debug flag causes them -- to default to thin. This can be used to test the performance -- implications of using thin pointers, and also to test that the -- compiler functions correctly with this choice. -- d7 Normally a -gnatl or -gnatv listing includes the time stamp of the -- source file and the time of the compilation. This debug flag can -- be used to suppress this output, and also suppresses the message -- with the version of the compiler. This is useful for regression -- tests which need to have consistent output. -- d8 This forces the packed stuff to generate code assuming the -- opposite endianness from the actual correct value. Useful in -- testing out code generation from the packed routines. -- d9 This allows lock free implementation for protected objects -- (see Exp_Ch9). -- d.1 Sets Opt.Unnest_Subprogram_Mode to enable unnesting of subprograms. -- This special pass does not actually unnest things, but it ensures -- that a nested procedure does not contain any uplevel references. -- See spec of Exp_Unst for full details. -- d.2 Allow statements within declarative parts. This is not usually -- allowed, but in some debugging contexts (e.g. testing the circuit -- for unnesting of procedures), it is useful to allow this. ------------------------------------------ -- Documentation for Binder Debug Flags -- ------------------------------------------ -- da Normally if there is an elaboration circularity, then in describing -- the cycle, links involving internal units are omitted, since they -- are irrelevant and confusing. This debug flag causes all links to -- be listed, and is useful when diagnosing circularities introduced -- by incorrect changes to the run-time library itself. -- db Output debug information from Better_Choice in Binde, which uses -- various heuristics to determine elaboration order in cases where -- multiple orders are valid. -- dc List units as they are chosen. As units are selected for addition to -- the elaboration order, a line of output is generated showing which -- unit has been selected. -- de Similar to the effect of -e (output complete list of elaboration -- dependencies) except that internal units are included in the -- listing. -- di Normally gnatbind calls Read_Ali with Ignore_Errors set to -- False, since the binder really needs correct version ALI -- files to do its job. This debug flag causes Ignore_Errors -- mode to be set for the binder (and is particularly useful -- for testing ignore errors mode). -- dn List details of manipulation of Num_Pred values during execution of -- the algorithm used to determine a correct order of elaboration. This -- is useful in diagnosing any problems in its behavior. -- do Use old elaboration order preference. The new preference rules -- prefer specs with no bodies to specs with bodies, and between two -- specs with bodies, prefers the one whose body is closer to being -- able to be elaborated. This is a clear improvement, but we provide -- this debug flag in case of regressions. -- du List unit name and file name for each unit as it is read in -- dx Force the binder to read (and then ignore) the xref information -- in ali files (used to check that read circuit is working OK). -------------------------------------------- -- Documentation for gnatmake Debug Flags -- -------------------------------------------- -- df Only output file names, not path names, in log -- dh Generate listing showing loading of name table hash chains, -- same as for the compiler. -- dm Issue a message indicating the maximum number of simultaneous -- compilations. -- dn Do not delete temporary files created by gnatmake at the end -- of execution, such as temporary config pragma files, mapping -- files or project path files. This debug switch is equivalent to -- the standard switch --keep-temp-files. We retain the debug switch -- for back compatibility with past usage. -- dp Prints the Q used by routine Make.Compile_Sources every time -- we go around the main compile loop of Make.Compile_Sources -- dq Prints source files as they are enqueued and dequeued in the Q -- used by routine Make.Compile_Sources. Useful to figure out the -- order in which sources are recompiled. -- dt When a time stamp mismatch has been found for an ALI file, -- display the source file name, the time stamp expected and -- the time stamp found. -- du List unit name and file name for each unit as it is read in -- dw Prints the list of units withed by the unit currently explored -- during the main loop of Make.Compile_Sources. --------------------------------------------- -- Documentation for gprbuild Debug Flags -- --------------------------------------------- -- dm Display the maximum number of simultaneous compilations. -- dn Do not delete temporary files created by gprbuild at the end -- of execution, such as temporary config pragma files, mapping -- files or project path files. This debug switch is equivalent to -- the standard switch --keep-temp-files. We retain the debug switch -- for back compatibility with past usage. -- dt When a time stamp mismatch has been found for an ALI file, -- display the source file name, the time stamp expected and -- the time stamp found. -------------------- -- Set_Debug_Flag -- -------------------- procedure Set_Debug_Flag (C : Character; Val : Boolean := True) is subtype Dig is Character range '1' .. '9'; subtype LLet is Character range 'a' .. 'z'; subtype ULet is Character range 'A' .. 'Z'; begin if C in Dig then case Dig (C) is when '1' => Debug_Flag_1 := Val; when '2' => Debug_Flag_2 := Val; when '3' => Debug_Flag_3 := Val; when '4' => Debug_Flag_4 := Val; when '5' => Debug_Flag_5 := Val; when '6' => Debug_Flag_6 := Val; when '7' => Debug_Flag_7 := Val; when '8' => Debug_Flag_8 := Val; when '9' => Debug_Flag_9 := Val; end case; elsif C in ULet then case ULet (C) is when 'A' => Debug_Flag_AA := Val; when 'B' => Debug_Flag_BB := Val; when 'C' => Debug_Flag_CC := Val; when 'D' => Debug_Flag_DD := Val; when 'E' => Debug_Flag_EE := Val; when 'F' => Debug_Flag_FF := Val; when 'G' => Debug_Flag_GG := Val; when 'H' => Debug_Flag_HH := Val; when 'I' => Debug_Flag_II := Val; when 'J' => Debug_Flag_JJ := Val; when 'K' => Debug_Flag_KK := Val; when 'L' => Debug_Flag_LL := Val; when 'M' => Debug_Flag_MM := Val; when 'N' => Debug_Flag_NN := Val; when 'O' => Debug_Flag_OO := Val; when 'P' => Debug_Flag_PP := Val; when 'Q' => Debug_Flag_QQ := Val; when 'R' => Debug_Flag_RR := Val; when 'S' => Debug_Flag_SS := Val; when 'T' => Debug_Flag_TT := Val; when 'U' => Debug_Flag_UU := Val; when 'V' => Debug_Flag_VV := Val; when 'W' => Debug_Flag_WW := Val; when 'X' => Debug_Flag_XX := Val; when 'Y' => Debug_Flag_YY := Val; when 'Z' => Debug_Flag_ZZ := Val; end case; else case LLet (C) is when 'a' => Debug_Flag_A := Val; when 'b' => Debug_Flag_B := Val; when 'c' => Debug_Flag_C := Val; when 'd' => Debug_Flag_D := Val; when 'e' => Debug_Flag_E := Val; when 'f' => Debug_Flag_F := Val; when 'g' => Debug_Flag_G := Val; when 'h' => Debug_Flag_H := Val; when 'i' => Debug_Flag_I := Val; when 'j' => Debug_Flag_J := Val; when 'k' => Debug_Flag_K := Val; when 'l' => Debug_Flag_L := Val; when 'm' => Debug_Flag_M := Val; when 'n' => Debug_Flag_N := Val; when 'o' => Debug_Flag_O := Val; when 'p' => Debug_Flag_P := Val; when 'q' => Debug_Flag_Q := Val; when 'r' => Debug_Flag_R := Val; when 's' => Debug_Flag_S := Val; when 't' => Debug_Flag_T := Val; when 'u' => Debug_Flag_U := Val; when 'v' => Debug_Flag_V := Val; when 'w' => Debug_Flag_W := Val; when 'x' => Debug_Flag_X := Val; when 'y' => Debug_Flag_Y := Val; when 'z' => Debug_Flag_Z := Val; end case; end if; end Set_Debug_Flag; --------------------------- -- Set_Dotted_Debug_Flag -- --------------------------- procedure Set_Dotted_Debug_Flag (C : Character; Val : Boolean := True) is subtype Dig is Character range '1' .. '9'; subtype LLet is Character range 'a' .. 'z'; subtype ULet is Character range 'A' .. 'Z'; begin if C in Dig then case Dig (C) is when '1' => Debug_Flag_Dot_1 := Val; when '2' => Debug_Flag_Dot_2 := Val; when '3' => Debug_Flag_Dot_3 := Val; when '4' => Debug_Flag_Dot_4 := Val; when '5' => Debug_Flag_Dot_5 := Val; when '6' => Debug_Flag_Dot_6 := Val; when '7' => Debug_Flag_Dot_7 := Val; when '8' => Debug_Flag_Dot_8 := Val; when '9' => Debug_Flag_Dot_9 := Val; end case; elsif C in ULet then case ULet (C) is when 'A' => Debug_Flag_Dot_AA := Val; when 'B' => Debug_Flag_Dot_BB := Val; when 'C' => Debug_Flag_Dot_CC := Val; when 'D' => Debug_Flag_Dot_DD := Val; when 'E' => Debug_Flag_Dot_EE := Val; when 'F' => Debug_Flag_Dot_FF := Val; when 'G' => Debug_Flag_Dot_GG := Val; when 'H' => Debug_Flag_Dot_HH := Val; when 'I' => Debug_Flag_Dot_II := Val; when 'J' => Debug_Flag_Dot_JJ := Val; when 'K' => Debug_Flag_Dot_KK := Val; when 'L' => Debug_Flag_Dot_LL := Val; when 'M' => Debug_Flag_Dot_MM := Val; when 'N' => Debug_Flag_Dot_NN := Val; when 'O' => Debug_Flag_Dot_OO := Val; when 'P' => Debug_Flag_Dot_PP := Val; when 'Q' => Debug_Flag_Dot_QQ := Val; when 'R' => Debug_Flag_Dot_RR := Val; when 'S' => Debug_Flag_Dot_SS := Val; when 'T' => Debug_Flag_Dot_TT := Val; when 'U' => Debug_Flag_Dot_UU := Val; when 'V' => Debug_Flag_Dot_VV := Val; when 'W' => Debug_Flag_Dot_WW := Val; when 'X' => Debug_Flag_Dot_XX := Val; when 'Y' => Debug_Flag_Dot_YY := Val; when 'Z' => Debug_Flag_Dot_ZZ := Val; end case; else case LLet (C) is when 'a' => Debug_Flag_Dot_A := Val; when 'b' => Debug_Flag_Dot_B := Val; when 'c' => Debug_Flag_Dot_C := Val; when 'd' => Debug_Flag_Dot_D := Val; when 'e' => Debug_Flag_Dot_E := Val; when 'f' => Debug_Flag_Dot_F := Val; when 'g' => Debug_Flag_Dot_G := Val; when 'h' => Debug_Flag_Dot_H := Val; when 'i' => Debug_Flag_Dot_I := Val; when 'j' => Debug_Flag_Dot_J := Val; when 'k' => Debug_Flag_Dot_K := Val; when 'l' => Debug_Flag_Dot_L := Val; when 'm' => Debug_Flag_Dot_M := Val; when 'n' => Debug_Flag_Dot_N := Val; when 'o' => Debug_Flag_Dot_O := Val; when 'p' => Debug_Flag_Dot_P := Val; when 'q' => Debug_Flag_Dot_Q := Val; when 'r' => Debug_Flag_Dot_R := Val; when 's' => Debug_Flag_Dot_S := Val; when 't' => Debug_Flag_Dot_T := Val; when 'u' => Debug_Flag_Dot_U := Val; when 'v' => Debug_Flag_Dot_V := Val; when 'w' => Debug_Flag_Dot_W := Val; when 'x' => Debug_Flag_Dot_X := Val; when 'y' => Debug_Flag_Dot_Y := Val; when 'z' => Debug_Flag_Dot_Z := Val; end case; end if; end Set_Dotted_Debug_Flag; end Debug; ",12075,False,2270.7414249458543,median "# Instaclustr Esop image:https://img.shields.io/maven-central/v/com.instaclustr/esop.svg?label=Maven%20Central[link=https://search.maven.org/search?q=g:%22com.instaclustr%22%20AND%20a:%22esop%22] image:https://circleci.com/gh/instaclustr/esop.svg?style=svg[""Instaclustr"",link=""https://circleci.com/gh/instaclustr/esop""] _Swiss knife for Apache Cassandra backup and restore_ image::Esop.png[Esop,width=50%] - Website: https://www.instaclustr.com/ - Documentation: https://www.instaclustr.com/support/documentation/ This repository is home of backup and restoration tools from Instaclustr for Cassandra called https://en.wikipedia.org/wiki/Aesop[Esop] Esop is able to perform these operations and has these features: * Backup and restore of SSTables * Backup and restore of commit logs * Restoration of data into a Cassandra schema or diffrent table schema * Backing-up to and restoring from S3 (Oracle and Ceph via Object Gateway too), Azure, or GCP, or into any local destination or other storage providing they are easily implementable * listing of local backups and their removal, global removal of backups across all nodes in cluster * periodic removal of backups (e.g. after 10 days) * Effective upload and download—it will upload only SSTables which are not present remotely so any subsequent backups will upload and restores will download only the difference * When used in connection with https://github.com/instaclustr/icarus[Instaclustr Icarus] it is possible to backup **simultaneously** so there might be more concurrent backups which may overlap what they backup * Used as backup/restore solution in https://github.com/instaclustr/cassandra-operator[Instaclustr Cassandra Operator] for Kubernetes * Possible to restore whole node _from scratch_ (or whole cluster from scratch in cases where Kubernetes Operator is used) * In connection with Icarus, it is possible to **restore on a running cluster** so no downtime is necessary * It takes care of details such as initial tokens, auto bootstrapping, and so on... * Ability to throttle the bandwidth used for backup * Point-in-time restoration of commit logs * verification of downloaded data - computes hases upon upload and download and it has to match otherwise restoration fails * it is possible to restore tables under different names so they do not clash with your current tables ideal when you want to investigate / check data before you restore the original tables, to see what data you will have once you restore it * retry of failed operations against s3 when uploading / downloading failure happens This tool is used as a command line utility and it is meant to be executed from a shell or from scripts. However, this tooling is also embedded seamlessly into Instaclustr Icarus. The advantage of using Icarus is that you may backup and restore your node (or whole cluster) remotely by calling a respective REST endpoint so Icarus can execute respective backup or restore _operation_. Icarus is designed to be run alongside a node and it talks to Cassandra via JMX (no need to expose JMX publicly). In addition, this tool has to be run in the very same context/environment as a Cassandra node—it needs to see the whole directory structure of a node (data dir etc.) as it will upload these files during a backup and download them on a restore. If you want to be able to restore and backup remotely, use Icarus which embeds this project. ## Supporter Cassandra Versions Since we are talking to Cassandra via JMX, almost any Cassandra version is supported. We are testing this tool with Cassandra 3.11.8, 4.0-beta3, and 2.2.18. ## Usage Released artifact is on https://search.maven.org/artifact/com.instaclustr/esop[Maven Central]. You may want to build it on your own by standard Maven targets. After this project is built by `mvn clean install` (refer to <> for more details), the binary is in `target` and it is called `instaclustr-esop.jar`. This binary is all you need to backup/restore. It is the command line application, invoke it without any arguments to see help. You can invoke `help backup` for `backup` command, for example. ---- $ java -jar target/instaclustr-esop.jar Missing required subcommand. Usage:

[-V] COMMAND -V, --version print version information and exit Commands: backup Take a snapshot of this nodes Cassandra data and upload it to remote storage. Defaults to a snapshot of all keyspaces and their column families, but may be restricted to specific keyspaces or a single column-family. restore Restore the Cassandra data on this node to a specified point-in-time. commitlog-backup Upload archived commit logs to remote storage. commitlog-restore Restores archived commit logs to node. ---- ### Connecting to Cassandra Node As already mentioned, this tool expects to be invoked alongside a node—it needs to be able to read/write into Cassandra data directories. For other operations such as knowing tokens etc., it connects to respective node via JMX. By default, it will try to connect to `service:jmx:rmi:///jndi/rmi://127.0.0.1:7199/jmxrmi`. It is possible to override this and other related settings via the command line arguments. It is also possible to connect to such nodes securely if it is necessary, and this tool also supports specifying keystore, truststore, user name and password etc. For brevity, please consult the command line `help`. Not all sub-commands require the connection to Cassandra to exist. As of now, a JMX connection is necessary for: . backup of tables/keyspaces . restore of tables/keyspaces (hard linking and importing strategies) The next release of this tool might relax these requirements so it would be possible to backup and restore a node which is offline. For backup and restore of commit logs, it is not necessary to have a node up as well in case you need to restore a node _from scratch_ or if you use <>. ### Storage Location Data to backup and restore from, are located in a remote storage. This setting is controlled by flag `--storage-location`. The storage location flag has very specific structure which also indicates where data will be uploaded. Locations consist of a storage _protocol_ and path. Please keep in mind that the protocol we are using is not a _real_ protocol. It is merely a mnemonic. Use either `s3`, `gcp`, `azure`, `oracle`, `minio`, `ceph` or `file`. The format is: `protocol://bucket/cluster/datacenter/node` * `protocol` is either `s3`,`azure`,'gcp`, or `file. * `bucket` is name of the bucket data will be uploaded to/downloaded from, for example `my-bucket` * `cluster` is name of the cluster, for example, `test-cluster` * `datacenter` is name of the datacenter a node belongs to, for example `datacenter1` * `node` is identified of a node. It might be e.g. `1`, or it might be equal to node id (uuid) The structure of a storage location is validated upon every request. If we want to backup to S3, it would look like: `s3://cassandra-backups/test-cluster/datacenter1/1` In S3, data for that node will be stored under key `test-cluster/datacenter1/1`. The same mechanism works for other clouds. For `file` protocol, use `file:///data/backups/test-cluster/dc1/node1`. In every case, `file` has to start with full path (`file:///`, three slashes). File location does not have a notion of a _bucket_, but we are using it here regardless—in the following examples, the _bucket_ will be _a_. It does not matter you put slash at the end of whole location, it will be removed. .file path resolution |=== |storage location |path |file:///tmp/some/path/a/b/c/d |/tmp/some/path/a |file:///tmp/a/b/c/d |/tmp/a |=== ### Authentication Against a Cloud In order to be able to download from and upload to a remote bucket, this tool needs to pick up security credentials to do so. This varies across clouds. `file` protocol does not need any authentication. #### S3 The resolution of credentials for S3 uses the same resolution mechanism as the official AWS S3 client uses. The most notable fact is that if no credentials are set explicitly, it will try to resolve them from environment properties of the node it runs on. If that node runs in AWS EC2, it will resolve them by help of that particular instance. S3 connectors will expect to find environment properties `AWS_ACCESS_KEY_ID` and `AWS_SECRET_KEY`. They will also accept `AWS_REGION` and `AWS_ENDPOINT` environment properties—however they are not required. If `AWS_ENDPOINT` is set, `AWS_REGION` has to be set too. The communication with S3 might be insecure, this is controlled by `--insecure-http` flag on the command line. By default, it uses HTTPS. It is possible to connect to S3 via proxy; please consult ""--use-proxy"" flag and ""--proxy-*"" family of settings on command line. #### Azure Azure module expects `AZURE_STORAGE_ACCOUNT` and `AZURE_STORAGE_KEY` environment variables to be set. #### GCP GCP module expects `GOOGLE_APPLICATION_CREDENTIALS` environment property or `google.application.credentials` to be set with the path to service account credentials. #### Oracle Oracle module behaves same way as S3 when it comes to credentials. #### Ceph CEPH module uses https://docs.ceph.com/en/latest/radosgw/s3/java/[Amazon S3 driver] for https://docs.ceph.com/en/latest/radosgw/[Ceph Object Gateway]. Credentials-wise, it behaves same way as ""normal"" S3. **You are required to set endpoint to AmazonS3 client.** In that case, be sure `AWS_ENDPOINT` environment property is set or `awsendpoint` property in Kubernetes secret is specified. You need to provide typical access key and secret key too. Please consult the following section to know more about Kubernetes-related authentication properties resolution. Setting protocol to HTTP might be achieved similarly as for normal S3 module, by specifying `--insecure-http` flag. #### Minio `minio` is alias of `oracle`. Oracle nor Minio uses path-style requests which S3 module does not. #### Authentication in Kubernetes If this tooling is run in the context of Kubernetes, we need to inject these credentials dynamically upon every request. If these credentials are not set statically, e.g. as environment or system properties, we may have an application like Cassandra Sidecar which resolves these credentials on every backup or restore request so they may change over time by Kubernetes operators (as person). By dynamic injecting, we are separating the lifecycle of a credential from the lifecycle of a backup/restore/Sidecar application. Credentials are stored as a secret. Namespace to read that secret from is specified by flag `--k8s-namespace` and the secret to read credentials from is specified by flag `--k8s-secret-name`. If namespace flag is not used, it defaults to `default`. If the secret name is not used, it is resolved as `cassandra-backup-restore-secret-cluster-\\{cluterId\\}` where `clusterId` is taken from cluster name in `--storage-location`. The secret has to contain these fields: ``` apiVersion: v1 kind: Secret metadata: name: cassandra-backup-restore-secret-cluster-my-cluster type: Opaque stringData: awssecretaccesskey: _AWS secret key_ awsaccesskeyid: _AWS access id_ awsregion: e.g. eu-central-1 awsendpoint: endpoint azurestorageaccount: _Azure storage account_ azurestoragekey: _Azure storage key_ gcp: 'whole json with service account' ``` Of course, if we do not plan to use other storage providers, feel free to omit the properties for them. For S3, only the secret key and access key are required. The fact that the code is running in the context of Kubernetes is derived from two facts: * there are environment properties `KUBERNETES_SERVICE_HOST` and `KUBERNETES_SERVICE_PORT` in a respective container this tool is invoked in * This tool runs outside of Kubernetes but as _a client_ meaning it will resolve credentials from there but it does not run in any container. This is helpful for example during tests where we do not run it inside Kubernetes but we want to be sure that the logic dealing with the credentials resolution works properly. This is controlled by system property `kubernetes.client` which is by default false. There might be the third (rather special) case—we want to run this tool in Kubernetes (so env properties would be there) but we want to run it as a client. Normally, the first condition would be fulfilled. There is a property called `pretend.not.running.in.kubernetes`, defaults to `false`. If set to true, even we run our tool in Kubernetes, it will act as a client, so it will not retrieve credentials from Kubernetes secret but from system and environment variables. ### Directory Structure of a Remote Destination Cassandra data files as well as some meta-data needed for successful restoration are uploaded into a bucket of a supported cloud provider (e.g. S3, Azure, or GCP) or they are copied to a local directory. Let's say we are in a bucket called `my-cassandra-backups` in Azure, and we did a backup with storage location set to `azure://test-cluster/dc1/1e519de1-58bb-40c5-8fc7-3f0a5b0ae7ee`. Snapshot name we set via `--snapshot-tag` was `snapshot3` and schema version of that node was `f1159959-593d-33d1-9ade-712ea55b31ef`. The content of that hypothetical bucket with same data will look like this: ``` . ├── topology │ └── snapshot3-f1159959-593d-33d1-9ade-712ea55b31ef-1600645759830.json (1) └── test-cluster └── dc1 ├── 1e519de1-58bb-40c5-8fc7-3f0a5b0ae7ee (2) │ ├── data │ │ ├── system │ │ | // data for this keyspace │ │ ├── system_auth │ │ | // data for this keyspace │ │ ├── system_schema │ │ | // data for this keyspace │ │ ├── test1 │ │ │ ├── testtable1-52d74870fb9911eaa75583ff20369112 │ │ │ │ ├── 1-2620247400 (3) │ │ │ │ │ ├── na-1-big-CompressionInfo.db │ │ │ │ │ ├── na-1-big-Data.db │ │ │ │ │ ├── na-1-big-Digest.crc32 │ │ │ │ │ ├── na-1-big-Filter.db │ │ │ │ │ ├── na-1-big-Index.db │ │ │ │ │ ├── na-1-big-Statistics.db │ │ │ │ │ ├── na-1-big-Summary.db │ │ │ │ │ └── na-1-big-TOC.txt │ │ │ │ ├── 1-4234234234 │ │ │ │ │ ├── // other SSTable │ │ │ │ └── schema.cql (4) │ │ │ ├── testtable2-545c13b0fb9911eaadb9b998490b71f5 │ │ │ │ // other table │ │ │ └── testtable3-55e8a720fb9911eaa2026b6b285d5a8a │ │ │ // other table │ │ └── test2 │ └── manifests (5) │ └── snapshot1-f1159959-593d-33d1-9ade-712ea55b31ef-1600645216879.json ├── 55d39d99-a9e1-44da-941c-3a46efed66b3 │ // other node ├── 59b5e477-df39-4126-acd4-726c937fe8fc │ // other node └── e8fd8bca-e6cb-4a1a-82db-192e2b4b77a5 ``` . When this tool is used in connection with Instaclustr Cassandra Sidecar, it also creates a _topology_ file. Topology file is needed for restoration into a Kubernetes cluster. . Data for each node are stored under that very node, here we used UUID identifier which is host ID as Cassandra sees it, and it is unique. Hence, it is impossible to accidentally store data for a different node as each node will have unique UUID. It may happen that over time we will have a cluster of same name and data center of same name but the node id would be still different so no clash would occur. . Each SSTable is stored in a directory . `schema.cql` contains a CQL ""create"" statement of that table as it looked upon a respective snapshot. It is there for diagnostic purposes so we might as well import data by other means than this tool as we would have to create that table in the first place before importing any data to it. . `manifests` directory holds JSON files which contain all files related to a snapshot as well other meta information. Its content will be discussed later. The directory where SSTable files are found, in our example for `test1.testtable1`, is `1-2620247400`. `1` means the generation, `2620247400` is crc checksum from `na-1-big-Digest.crc32`. Through this technique, every SSTable is totally unique and it ensures that they would not clash, even if they were named the same. This crc is inherently the part of the path where all files are, and a manifest file is pointing to them so we have a unique match. #### Manifest A manifest file is uploaded with all data. It contains all information necessary to restore that snapshot. Manifest name has this format: `snapshot3-f1159959-593d-33d1-9ade-712ea55b31ef-1600645759830.json` * `snapshot3`—name of snapshot used during a backup * `f1159959-593d-33d1-9ade-712ea55b31ef` schema version of Cassandra * `1600645759830` timestamp when that snapshot/backup was taken The content of a manifest file looks like this: ``` { ""snapshot"" : { ""name"" : ""snapshot3"", ""keyspaces"" : { ""ks1"" : { ""tables"" : { ""ks1t1"" : { ""entries"" : [ { ""objectKey"" : ""path-to/1-1146970048/na-1-big-CompressionInfo.db"", ""type"" : ""FILE"", ""size"" : 47 }, { ""objectKey"" : ""path-to/1-1146970048/na-1-big-Data.db"", ""type"" : ""FILE"", ""size"" : 53 }, { ""objectKey"" : ""path-to/schema.cql"", ""type"" : ""CQL_SCHEMA"", ""size"" : 934 } ], ""id"" : ""e17ff4b0e89211eab4313d37e7f4ac07"", ""schemaContent"" : ""CREATE TABLE IF NOT EXISTS ks1.ks1t1 ..."" }, ""ks1t2"" : { // other table } } } ""ks2"": { // other keyspace } } }, ""tokens"" : [ ""-1025679257793152318"", ""-126823146888567559"", .... ], ""schemaVersion"" : ""f1159959-593d-33d1-9ade-712ea55b31ef"" } ``` A manifest maps all resources related to a snapshot, their size as well as type (`FILE` or `CQL_SCHEMA`). It holds all schema content in a respective file too, so we do not need to read/parse the schema file as it is already a part of the manifest. Upon restore, this file is read into its Java model and _enriched_ by setting a path where each _manifest entry_ should be physically located on disk as we need to remove part of the file where a hash is specified. It is also possible to filter this manifest in such a way that we might backup 5 tables, but we want to restore only 2 of them so the other three tables would not be downloaded at all. #### Topology File Topology file is uploaded during a backup as well. It is uploaded into a bucket's `topology` directory in root. A topology file is provided not only as a reference to see what the topology was upon backup, but it also helps Instaclustr Cassandra operator to resolve which node it should download data for. If we are restoring a cluster from scratch and all we have is its former hostname, we need to know what was the node's id (`nodeId` below) because that id signifies which directory its data is stored in. When Instaclustr Cassandra operator restores a cluster from scratch, it knows a name of a pod (its hostname) but it does not know the id to load data from. The storage location upon a restore looks like `s3://bucket/test-cluster/dc1/cassandra-test-cluster-dc1-west1-b-0`. Internally, based on a snapshot and schema, we resolve the correct topology file and we filter its content to see which node starts on that hostname so we use, in this case, `nodeId` 8619f3e2-756b-4cb1-9b5a-4f1c1aa49af6 upon restoration. Storage location flag is then updated to use this node, so it will look like `s3://bucket/test-cluster/dc1/8619f3e2-756b-4cb1-9b5a-4f1c1aa49af6`. ``` { ""timestamp"" : 1600645216879, ""clusterName"" : ""test-cluster"", ""schemaVersion"" : ""f1159959-593d-33d1-9ade-712ea55b31ef"", ""topology"" : [ { ""hostname"" : ""cassandra-test-cluster-dc1-west1-b-0"", ""cluster"" : ""test-cluster"", ""dc"" : ""dc1"", ""rack"" : ""west1-b"", ""nodeId"" : ""8619f3e2-756b-4cb1-9b5a-4f1c1aa49af6"", ""ipAddress"" : ""10.244.2.82"" }, { ""hostname"" : ""cassandra-test-cluster-dc1-west1-a-0"", ""cluster"" : ""test-cluster"", ""dc"" : ""dc1"", ""rack"" : ""west1-a"", ""nodeId"" : ""b7952bdc-ccae-4443-9521-908820d067c1"", ""ipAddress"" : ""10.244.1.194"" }, { ""hostname"" : ""cassandra-test-cluster-dc1-west1-c-0"", ""cluster"" : ""test-cluster"", ""dc"" : ""dc1"", ""rack"" : ""west1-c"", ""nodeId"" : ""1e519de1-58bb-40c5-8fc7-3f0a5b0ae7ee"", ""ipAddress"" : ""10.244.2.83"" } ] } ``` A name of a topology file has this format `clusterName-snapshotName-schemaVersion-timestamp`. This uniquely identifies a topology in time. #### Resolving Manifest and Topology File From Backup Request Lets say we have done a backup against a node, multiple times, where some snapshot names were the same and schema version was the same too, for some cases we will have these manifests in a bucket: ``` ├── snapshot3-f1159959-593d-33d1-9ade-712ea55b31ef-1600645759830.json └── test-cluster └── dc1 └── 1e519de1-58bb-40c5-8fc7-3f0a5b0ae7ee └── manifests (5) ├─ snapshot1-f1159959-593d-33d1-9ade-712ea55b31ef-1600645216000.json ├─ snapshot1-f1159959-593d-33d1-9ade-712ea55b31ef-1600645217000.json ├─ snapshot1-b555c56d-a89f-4002-9f9c-0d4c78d3eca9-1600645217800.json ├─ snapshot2-f1159959-593d-33d1-9ade-712ea55b31ef-1600645218000.json ├─ snapshot3-f1159959-593d-33d1-9ade-712ea55b31ef-1600645219000.json └─ snapshot4-f1159959-593d-33d1-9ade-712ea55b31ef-1600645220000.json ``` Which manifest will be resolved when we use `snapshot1` as `--snapshot-tag`? If there are multiple manifests starting with same snapshot tag and having same schema version, in this particular case, it will pick the one with timestamp `1600645217800` as the latest manifest wins. You may specify `--snapshot-tag` as `snapshot1-f1159959-593d-33d1-9ade-712ea55b31ef` or even full version with timestamp. The longest prefix wins and when there are multiple manifests resolved, the latest wins. In case we have the same snapshot but different schema, only the snapshot name and schema version will be enough, not the snapshot name alone. By this logic, we are preventing the situation where two operators (as a person) will do two backups with the same snapshots against a node on the same schema version—the only information which makes these two requests unique is the timestamp. However, we may use just the same snapshot name (for practical reasons not recommended) and all would work just fine. The same resolution logic holds for topology file resolution—the longest prefix wins and it has to be uniquely filtered. Upon backup, the schema version is determined by calling respective JMX method. The user does not have to provide it on his own. On the other hand, the second way how to resolve the problems above during restoration is to specify `--exactSchemaVersion` flag. When set, it will try to filter only manifests which were done on the same schema version as a current node runs on. The last option is to use `--schema-version` option (in connection with `--exact-schema-version`) with the schema version manually. #### Backup The anatomy of a backup is quite simple. The successful invocation of `backup` sub-command will do the following: . Checks if a remote bucket for whatever storage provider exists, and will optionally create it if it doesn't (consult command line for help on how to achieve that). If a bucket does not exist and we are not allowed to create it automatically—the backup will fail. . Takes tokens of a respective node via JMX. Tokens are necessary for cases when we want to restore into a completely empty node. If we downloaded all data but tokens would be autogenerated, the data that node is supposed to serve would not match tokens that node is using. . Takes a snapshot of respective _entities_—either keyspaces or tables. It is not possible to mix keyspaces and some tables, it is _either_ keyspace(s) _or_ tables. This is inherited from the fact that Cassandra JMX API is designed that way. `nodetool snapshot` also permits us to specify entities to backup either as `ks1,ks2,ks3` or `ks1.t1,ks1.t2,ks2.t3` and we copy this behaviour here. The name of snapshot is auto generated when not specified via command line. . Creates internal mapping of snapshot to files it should upload. . Uploads SSTables and helper files to remote storage—only files which are not uploaded. By doing this, we will not ""over-upload"" as an SSTable is an immutable construct, so there is no need to upload what is already there. The backup procedure will check if a remote file is not there and uploads only in case it is not. Backup is doing a ""hash"" of an SSTable and it is uploaded under such key so it is not possible that two SSTables would be overwritten even if they are named the same as their hashes do not necessarily match. . The actual downloading/uploading is done in parallel—the number of simultaneous uploadings/downloadings is controlled by `concurrent-connections` setting which defaults to 10. It is possible to throttle the bandwidth so we do not use all available bandwidth for backups/restores so the node which might still be in operation would suffer performance-wise. . Writes meta-files to a remote storage—manifest and topology file (when Sidecar is used). . Clears taken snapshot. As of now, a node to be backed-up has to be online because we need tokens, we need to take a snapshot, etc. and this is done via JMX. In theory we do not need a node to be online if we take a snapshot beforehand and tokens are somehow provided externally, however the current version of the tool does require it. #### Restore This tool is seamlessly integrated into https://github.com/instaclustr/icarus[Icarus] which is able to do backup and restore in a distributed manner—cluster wide. Please refer to documentation of Icarus to understand what restoration phases are and what restoration strategies one might use. The very same restoration flow might be executed from CLI, Icarus just accepts a JSON payload which is a different representation of the very same data structure as the one used from command like but the functionality is completely the same. CLI tool is not responsive to `globalRequest` flag in restoration/backup requests—only Sidecar can coordinate cluster-wide restoration and backup. A restoration is a relatively more complex procedure than a backup. We have provided three _strategies_. You may control which strategy is used via command line. In general, the restoration is about: . Downloading data from remote location . Making Cassandra use these files While the first step is quite straightforward, the second depends on various factors we guide a reader through. Restoration strategy is determined by flag `--restoration-strategy-type` which might be `IN_PLACE`, `IMPORT`, or `HARDLINKS`, case-insensitive. #### In-Place Restoration Strategy In-place strategy must be used only in case a Cassandra node is _down_— Cassandra process does not run. This strategy will download only SSTables (and related files) which are not present locally, and it will directly download them to their respective data directories of a node. Then it will remove SSTables (and related files) which should not be there. As a backup is done against a _snapshot_; restore is also done from a snapshot. Use this strategy if you want to: * restore from an older snapshot and your node does not run * restore from a snapshot and your node is completely empty—it was never run/its `data` dir is empty * restore a cluster/node by Cassandra Operator. This feature is already fully embedded into our operator offering so one can restore whole clusters very conveniently. In more detail, in-place strategy does the following: . Checks that a remote bucket to download data from exists and errors out if it does not . In case `--resolve-host-id-from-topology` flag is used, it will resolve a host to restore from topology file. This is handy for cases we want to restore e.g. in the context of Kubernetes by our operator. . Downloads a manifest—manifest contains the list of files which are logically related to a snapshot. . Filters out the files which need to be downloaded, as some files which are present locally might be also a part of a taken snapshot so we would download them unnecessarily. . Downloads files directly into Cassandra `data` dir. . Deletes files from `data` dir which should not be there. . Cleans data in other directories—hints, saved caches, commit logs. . Updates `cassandra.yaml` if present with `auto_bootstrap: false` and `initial_token` with tokens from manifest. It is possible to restore not only user keyspaces and tables but system keyspaces too. This is necessary for the successful restoration of a cluster/node exactly as it was before as all system tables would be same. Normally, system keyspaces are not restored and one has to set this explicitly by `--restore-system-keyspace` flag. In-place strategy uses also `--restore-into-new-cluster` flag. If specified, it will restore only system keyspaces needed for successful restoring (`system_schema`) but it will not attempt to restore anything else. In an environment like Kubernetes, we do not want to restore _everything_ because system keyspaces contain details like tokens, peers with ips, etc. and this information is very specific to each one so we do not restore them. However, if we did not restore `system_schema`, the newly started node would not see the restored data as there would not be any schema. By restoring `system_schema`, Cassandra will detect these keyspaces and tables on the very first start. In-place restoration might update `cassandra.yaml` file if found. This is done automatically upon restoration in Cassandra operator but it might be required to be done manually for other cases. By default, `cassandra.yaml` is not updated. The updating is enabled by setting `--update-cassandra-yaml` flag upon restore. It is expected that `cassandra.yaml` is located in a directory `\\{cassandraConfigDirectory\\}/` (by default `/etc/cassandra`). The Cassandra configuration directory with `cassandra.yaml` might be changed via `--config-directory` flag. There are two options which are automatically changed when `cassanra.yaml` if found, in connection with this strategy: * `auto_bootstrap` - if not found, it will be appended and set to `false`. If found and set to `true`, it will be replaced by `false`. If `auto_bootstrap: false` is already present, nothing happens. * `initial_token`—set only in case it is not present `cassandra.yaml`. Tokens are set in order to have the node we are restoring to on the same tokens as the node we took a snapshot from. #### Hard-Linking Strategy This strategy is supposed to be executed against a _running_ node. Hard-linking strategy downloads data from a bucket to a node's local directory and it will make hardlinks from these files to Cassandra data dir for that keyspace/table. After hardlinks are done, it will _refresh_ a respective table / keyspace via JMX so Cassandra will start to read from them. Afterwards, the original files are deleted. This strategy works for Cassandra version 3 as well as for Cassandra 4. #### Importing Strategy This strategy is similar to hardlinking strategy — the node upon restoration can still run and serve other requests so a restoration process is not disruptive. _Importing_ means that it will import downloaded SSTables via JMX directly so no hardlinks and refresh are necessary. Importing of SSTables by calling respecting JMX method was introduced in Cassandra 4 only, so this does not work against a node of version 3 or below. Keep in mind that imported SSTables are physically deleted from download directory and moved to live Cassandra data directory. #### Restoration Phases for Hardlinking and Importing Strategy Hardlinking and importing strategy consists of _phases_. Each phase is done _per node_. . Cluster health check—this phase ensures that we are restoring into a healthy cluster, if any of this check is violated the restore will not proceed. We check that: .. A node under the restoration is in `NORMAL` state .. Each node in a cluster is `UP—the failure detector (as seen from that node) does not detect any node as failed .. All nodes are not in _joining_, _leaving_, _moving_ state and all are reachable .. All nodes are on same schema version . Downloading phase—this phase will download all data necessary for the restore to happen. . Truncate phase—this phase will truncate all respective tables we want to restore. . Importing phase—for hardlinking strategy. It will do hardlinks from download directory to live Cassandra data dir; for importing strategy, it will call JMX method to import them. . Cleaning phase—this phase will cleanup a directory where Cassandra put truncated data; it will also delete the directory where downloaded SSTables are. In a situation where we are restoring into a cluster of multiple nodes, the truncate operation should be executed only once against a particular node, as Cassandra will internally distribute the truncating operation to all nodes in a cluster. In other words, it is enough to truncate at one node only as data from all other nodes will be truncated too. Downloading phase is proceeding all other phases because we want to be sure that we are truncating the data if and only if we have all data to restore from. If we truncated all data and download fails, we can not restore and the node does not contain any data to serve, rendering it useless (for that table) with some complicated procedure to recover the truncated data. If any phases fail, all other phases fail too. Hence if we fail to download data, from an operational point of view nothing happens, as nothing was truncated and data on a running cluster were not touched. If we fail to truncate, we are still good. Once we truncate and we have all data, it is straightforward to import/hard-link data. This is the least invasive operation with a high probability of success. It can be decided if we want to delete downloaded as well as truncated data after a restore is finished. If we plan to restore multiple times with the same data—for whatever reason— and to return back to the same snapshot, it is not desired to download all data all over again. We might just reuse them. This is controlled by flags `--restoration-no-download-data` and `--restoration-no-delete-downloads` respectively. #### Restoring Into Different Schemas When a cluster we made a backup for is on the same schema at the time we want to do a restore, all is fine. However, a database schema evolves over time, columns are added or removed and we still want to be able to restore. Let's look at this scenario: . create keyspace `ks1` with table `table1` . insert data . make backup . alter table, **add** a column . insert data . restore into snapshot made in the 3rd step Clearly, the schema we are on differs from the schema back then—there is a new column which is not present in uploaded SSTables. However, this will work, resulting in a column which is new to have all values for that column as `null`. This tool does not try to modify a schema itself. An operator would have to take care of this manually and such column would have to be dropped. The opposite situation works as well: . create keyspace `ks1` with table `table1` . insert data . make backup . alter table, **drop** a column . insert data . restore into snapshot made in the 3rd step If we want to restore, we have one column less from snapshot, data will be imported but that column will just not be there. As of now, the restore is only ""forward-compatible"" on a table level. If we dropped whole table and we want to restore it, this is not possible—the table has to be there already. You may recreate them by applying respective CQL create statements from the manifest before proceeding. The tool might try to create these tables beforehand as we have that CQL schema at hand, but currently it is not implemented. ### Simultaneous Backups Backups are non-blocking. It means that multiple backups might be in progress. However, no file is uploaded in one particular moment more than once. Each backup request forms a _session_. A session contains _units_ to upload, referencing an entry in a manifest. If the second backup wants to upload the same file as the first one which is already uploading, it will just wait until the first backup is complete. The simultaneous restore is not finished yet. The power of simultaneous backups is fully understood in connection with Instaclustr Cassandra Sidecar as that is a server-like application running for a long period of time where an operator can submit backup requests which might happen at the same time (uploading of files is happening concurrently). CLI application does not profit from this feature. ### Resolution of Entities to Backup/Restore The flag `--entities` commands which database tables/keyspaces should be backed- up or restored. |=== |--entities |backup |restore |empty |all keyspaces and tables |all keyspaces and tables except `system*` |`ks1` |all tables in keyspace ks1 |all tables in keyspace ks1, except system keyspace |`ks1.t1,ks2.t2` |tables `t1` in `ks1` and table `t2` in `ks2` |tables `t1` in `ks1` and table `t2` in `ks2` |=== Moreover, if `--restore-system-keyspace` is set upon restore, it is possible to restore system keyspaces only in case `--restoration-strategy-type` is `IN_PLACE`. Logically, we can not restore system keyspaces on a running cluster in case we use hardlinking or importing strategy. System keyspaces are filtered out from entities automatically for these strategy types. However, if `IN_PLACE` strategy is used and flag `--restore-into-new-cluster` is specified, such strategy will pick only system keyspaces necessary for successful bootstrapping, as it restores `system_schema` only from all system schemas. `system_schema` needs to already contain the keyspaces and tables we are restoring. If we started a completely new node without restoring `system_schema`, it would not detect these imported keyspaces. Keep in mind that if system keyspace (`system_schema`) is not specified upon backup, it will not be uploaded; `--entities` need to enumerate all entities explicitly (or if it is empty, absolutely everything will be uploaded). ### Backup and Restore of Commit Logs It is possible to backup and restore commit logs too. There is a dedicated sub-command for this task. Please refer to examples how to invoke it. The commit logs are simply uploaded to a remote storage under node keys of the users choosing as specified in storage location property. The respective command does not derive the storage path on its own out of the box as commit logs might be uploaded even if a node is offline. So there might be no means to retrieve its host id via JMX, for example, but this might be turned on on demand. The example of backup (for brevity, we are showing just the sub-command): ---- $ commitlog-backup \\ --storage-location=s3://myBucket/mycluster/dc1/node1, \\ --data-directory=/my/installation/of/cassandra/data ---- Note that in this example, there is not any need to specify `--jmx-service` because it is not needed. JMX is needed for taking snapshots, for example, but here we do not take any. This command will expect `commitlog` directory under `--data-directory`. It is possible to override this by specifying `--cl-archive` with the path to the commit logs instead of expecting them to be under `--data-directory`. This plays nicely especially with the commit log archiving procedure of Cassandra. Let's say you have this in `commitlog_archiving.properties` file: ---- archive_command=/bin/ln %path /backup/%name ---- where `%path` is a fully qualified path of the segment to archive and `%name` is name of the commit log (these variables will be automatically expanded by Cassandra). Then you might archive your commit logs like this: ---- $ commitlog-backup \\ --storage-location=s3://myBucket/mycluster/dc1/node1 \\ --cl-archive=/backup ---- The backup logic will iterate over all commit logs in `/backup` and it will try to refresh them in the remote store, if they are refreshed, it means they are already uploaded. If refreshing fails, that commit log is not there so it will be uploaded. You might as well script this in such a way that a commit log would be automatically uploaded as part of Cassandra archiving procedure, like this: ---- archive_command=/bin/bash /path/to/my/backup-script.sh %path %name ---- The content of `backup-script.sh` might look like: ---- $!/bin/bash java -jar instaclustr-esop.jar commitlog-backup \\ --storage-location=s3://myBucket/mycluster/dc1/node1 \\ --commit-log=$1 ---- There is one improvement to do here, even if we do not know what the host id or dc or name of a cluster is, this can be found out dynamically as part of the backup by specifying `--online` flag (if a Cassandra node is online it just archived a commit log for us). ---- $!/bin/bash # specifying --online will update s3://myBucket/mycluster/dc1/node1 to # s3://myBucket/real-dc/real-dc-name/68fcbda0-442f-4ca4-86ec-ec46f2a00a71 where uuid is host id. java -jar instaclustr-backup-restore.jar commitlog-backup \\ --storage-location=s3://myBucket/mycluster/dc1/node1 \\ --commit-log=$1 \\ --online ---- ### Examples of Command Line Invocation Each example shown here should be prepended with `java -jar instaclustr-esop.jar`. We are showing here just respective commands. This command will copy over all SSTables to the remote location. It is also possible to choose a location in a cloud. For backup, a node has to be up to back it up. ---- backup \\ --jmx-service 127.0.0.1:7199 \\ --storage-location=s3://myBucket/mycluster/dc1/node1 \\ --data-directory=/my/installation/of/cassandra \\ --entities=ks1,ks2 \\ --snapshot-tag=mysnapshot ---- If you want to upload SSTables into AWS, GCP, or Azure, just change protocol to either `s3`, `gcp`, or `azure`. The first part of the path is the bucket you want to upload files to, for `s3`, it would be like `s3://bucket-for-my-cluster/cluster-name/dc-name/node-id`. If you want to use a different cloud, just change the protocol respectively. We also support https://docs.cloud.oracle.com/en-us/iaas/Content/Object/Tasks/s3compatibleapi.htm[Oracle cloud]; use `oracle://` protocol for your backup and restores. We also support CEPH S3 Gateway, use `ceph://` protocol for your backup and restores. If a bucket does not exist, it will be created only when `--create-missing-bucket` is specified. The verification of a bucket might be skipped by flag `--skip-bucket-verification`. If the verification is not skipped (which is default) and we detect that a bucket does not exist, the operation fails if we do not specify `--create-missing-bucket` flag. ### Example of `commitlog-backup` You can backup commit logs as well. An example of a commit log backup is like the following: ---- $ commitlog-backup \\ --storage-location=s3://myBucket/mycluster/dc1/node1 \\ --data-directory=/my/installation/of/cassandra ---- Note that there is no need to specify jmx-service. JMX is needed for taking snapshots, but here we do not take any. ### Example of in-place `restore` The restoration of a node is achieved by following parameters: ---- $ restore --data-directory=/my/installation/of/restored-cassandra/data \\ --config-directory=/my/installation/of/restored-cassandra/conf \\ --snapshot-tag=stefansnapshot"" \\ --storage-location=s3://bucket-name/cluster-name/dc-name/node-id \\ --restore-system-keyspace \\ --update-cassandra-yaml=true"" ---- Notice a few things here: * there is implicity used `--restoration-strategy-type=IN_PLACE` * `--snapshot-tag` is specified. Normally, when snapshot name is not used upon backup, there is a snapshot taken of some generated name. You would have to check the name of a snapshot in a backup location to specify it yourself, so it is better to specify that beforehand and just reference it. * `--update-cassandra-yaml` is set to true, this will automatically set `initial_tokens` in `cassandra.yaml` for the restored node. If it is false, you will have to set it up yourself, copying the content of tokens file in backup directory, under `tokens` directory. * `--restore-system-keyspace` is specified, which means it will restore system keyspaces too, which is not normally done. This might be specified only for IN_PLACE strategy as that strategy requires a node to be down and we can manipulate system keyspaces only on such a node. ### Example of Hardlinking and Importing Restoration Hardlinking as well as importing restoration consists of phases. These strategies expect a Cassandra node to be up and fully operational. The primary goal of these strategies is to restore on a _running node_, so the restoration procedure does not require a node to be offline which greatly increases the availablity of the whole cluster. Backup and restore will look like the following: ---- backup \\ --jmx-service 127.0.0.1:7199 \\ --storage-location=s3://myBucket/mycluster/dc1/node1 \\ --data-directory=/my/installation/of/cassandra \\ --entities=ks1,ks2 \\ --snapshot-tag=mysnapshot ---- The first restoration phase is DOWNLOAD as we need to download remote SSTables: ---- restore \\ --data-directory=/path/to/cassandra/data \\ --snapshot-tag=my-snapshot \\ --storage-location=s3://myBucket/mycluster/dc1/node1 \\ --entities=ks1,ks2 \\ --restoration-strategy-type=hardlinks \\ --restoration-phase-type=download, /// IMPORTANT --import-source-dir=/where/to/put/downloaded/sstables ---- Then we need to truncate `ks1` and `ks2`: ---- restore, --data-directory=/path/to/cassandra/data \\ --snapshot-tag=my-snapshot \\ --storage-location=s3://myBucket/mycluster/dc1/node1 \\ --entities=ks1,ks2 \\ --restoration-strategy-type=hardlinks \\ --restoration-phase-type=truncate \\ /// IMPORTANT --import-source-dir=/where/to/put/downloaded/sstables ---- Once we truncate keyspaces, we can make hardlinks from directory where we downloaded SSTables to the Cassandra data directory: ---- restore, --data-directory=/path/to/cassandra/data \\ --snapshot-tag=my-snapshot \\ --storage-location=s3://myBucket/mycluster/dc1/node1 \\ --entities=ks1,ks2 \\ --restoration-strategy-type=hardlinks \\ --restoration-phase-type=import \\ /// IMPORTANT --import-source-dir=/where/to/put/downloaded/sstables ---- Lastly we can cleanup downloaded data as well as truncated as they are not needed anymore: ---- restore, --data-directory=/path/to/cassandra/data \\ --snapshot-tag=my-snapshot \\ --storage-location=s3://myBucket/mycluster/dc1/node1 \\ --entities=ks1,ks2 \\ --restoration-strategy-type=hardlinks \\ --restoration-phase-type=cleanup \\ /// IMPORTANT --import-source-dir=/where/to/put/downloaded/sstables ---- If you check this closely you see that the only flag we have changed is `--restoration-phase-type` and that is correct. All commands will look exactly the same but they will just differ on `--restoration-phase-type`. If we wanted to do a restore via Cassandra JMX _importing_, our `--restoration-strategy-type` would be `import`. ### Renaming of a table to restore to It is possible to restore to a different table you backed up. This feature is very handy for cases when you want to examine data before you actually restore them - you might put them temporarily to a different table to see if all is right etc. From Esop CLI, you drive this feature by flag called `--rename`. This flag might repeat as many times as many times you need to rename. This feature might be used only for hardlinks or importing strategy, not for in-place. A table has to exist before a restore action is taken. Esop does **not** create this table for you automatically and it is left for a user to ensure such table exists before proceeding. Let's say you have backed up a table called `tb1` in a keyspace called `ks1` but you want to restore it into table `tb2` in the same keyspace. Hence you need to specify `--rename=ks1.tb1=ks1.tb2`. `--rename` options is meant to be used along with `--entities`. It is a valid scenario to do this: These examples show invalid cases for the combination of `--entities` and `--renamed` ---- --entities="""" --rename=whatever non empty -> invalid --entities=ks1 --rename=whatever non empty -> invalid, you can not use only a keyspace in --entities --entities=ks1.tb1 --rename=ks1.tb2=ks1.tb2 -> invalid as ""from"" is not in entities --entities=ks1.tb1 --rename=ks1.tb2=ks1.tb1 -> invalid as ""to"" is in entities (and from is not in entities) --entities=ks1.tb1 --rename=ks1.tb1=ks1.tb2 -> truncate ks1.tb2 and process just ks1.tb2, k1.tb1 is not touched ---- Valid cases: ---- --entities=ks1.tb1 --rename=ks1.tb1=ks1.tb2 --entities=ks1.tb1 --rename=ks1.tb1=ks2.tb1 --entities=ks1.tb1,ks2.tb2,ks3.tb4 --rename=ks1.tb1=ks1.tb2,ks2.tb2=ks3.tb3 ---- * entities in ""to"" have to be unique across all renaming pairs, ""ks1.tb1=ks1.tb2,ks1.tb3=ks1.tb2"" is invalid * please keep in mind that if you are doing cross-keyspace renaming, as of now you are completely on your own when it comes to e.g. replication factors etc, Esop currently does not check that replication factor and replication strategy in source and target keyspace match. This might be addressed in the future versions. From Icarus point of view, you need to add a map under ""rename"" field: ---- { ""rename"": { ""ks1.tb1"": ""ks1.tb2"", ""ks2.tb3"": ""ks2.tb4"", ""ks3.tb5"": ""ks3.tb6"" } } ---- ### Skipping refreshment of remote objects By default, Esop ""refreshes"" remote objects. Refreshment means that the last modification date of a remote object will be updated to the time the backup was done. This is done because we need to somehow detect if a remote file already exists or not. If it does, we do not upload it. If it does not exist, we upload it. However, if it does exist, we need to update the modification date because there might be, for example, a retention policy on remote objects in a bucket to be set for some period of time (for example, 14 days) and if a particular files not touched for 14 days, it would be removed. This way you might automatically implement the deletion of older backups because if there is a newer backup consisting of a set of SSTables, all SSTables which were previously a part of the older backup but they are not a part of the current backup would not be touched - hence no modification date would be refreshed - so they would expire. For cases there is a versioning enabled (currently known to be an issue for S3 backups only), our attempt to refresh it would create new, versioned, file. This is not desired. Hence we have the possibility to skip refreshment and we just detect if a file is there or not, but you would lose the ability to expire objects as described above. This behavior is controlled by flag called `--skip-refreshing` on backup command. By default, when not specified, it is evaluated to `false`, so skipping would not happen. ### Retry of upload / download operations Imagine there is a restore happening which is downloading 100 GB of data and your connectivity to the Internet is disrupted when it is almost done, on 80%. If you restart whole restoration process, you do not want to download all 80 GB again. Hence, we want that if a restore is stopped in the middle, it will not start from scratch next time we run it and it will download what is necessary. As a result of these errors, a file might be corrupted, it may be incomplete on the disk so its loading or hard linking into Cassandra would fail. To be sure that data are not corrupted, there is a hash (sha512) of that file made and it is uploaded as part of the manifest. Upon restore, if that file already exists locally, it computes the has and it compares it withe the one in the manifest and they have to match. If they do not match, such corrupted file is deleted and whole operation as such (download phase in case of import or hardlinks strategy) fails. On the next restore attempt, it will skip files which are in download directory already present and donwloads ony missing ones, computing their hashes etc ... On backup path, if a communication error happens, this is also detected and operation fails as such but some files might be already uploaded. On next upload, Esop checks if such file is already present remotely and it will skip it from uploading if it does. If upload of a file fails, Esop can _retry_. The mechanism how this happens is controlled by the family of ""--retry-*"" switches on the command line. In a nutshell, your retry might be exponential or linear. The exponential retry will execute the same operation (e.g. uploading of a file) every time exponentially it terms of the pause between retries. Linear retry has the retry period constant. ### Explanation of Global Requests It looks like the phases are an unnecessary hassle to go through, but the granularity is required in case we are executing a so called _global request_. A global request is used in the context of Cassandra Sidecar and it does not have any usage during CLI executions. ### Example of `commitlog-restore` The restoration of commit logs can be done like this: ---- $ commitlog-restore --data-directory=/my/installation/of/restored-cassandra/data --config-directory=/my/installation/of/restored-cassandra/conf --storage-location=s3://bucket-name/cluster-name/dc-name/node-id --commitlog-download-dir=/dir/where/commitlogs/are/downloaded --timestamp-end=unix_timestamp_of_last_transaction_to_replay ---- The commit log restorations are driven by Cassandra's `commitlog_archiving.properties` file. This tool will generate such files into the node's `conf` directory so it will be read upon node start. After a node is restored in this manner, one has to *delete* `commitlog_archiving.properties` file in order to prevent commitlog replay by accident again if a node is restarted. ---- restore_directories=/home/smiklosovic/dev/instaclustr-esop/target/commitlog_download_dir restore_point_in_time=2020\\:01\\:13 11\\:32\\:51 restore_command=cp -f %from %to ---- ## Listing of backups This feature is for now only available for `file://`-based backups. Listing of a bucket provides a better visibility into what backups there are, how may files they are consisting of and how much space they occupy as well as how many space we would reclaim by their deletion. ---- $ java -jar ~/esop.jar list \\ --storage-location=file:///backup1/cluster/datacenter1/node1 \\ --skip-node-resolution \\ --human-units Timestamp Name Files Occupied space Reclaimable space 2021-04-27T15:38:40.284 name-of-backup-1 154 113.1 kB 10.1 kB 2021-04-27T15:38:20.259 name-of-backup-2 138 103.0 kB 0 B 154 113.1 kB ---- Listing of a backup will read all manifests there are for a respective node and it will compute the statistics above. It is important to understand that the figure representing the number of files for a specific backup does not represent the unique files. Since a backup can have SSTables present in more than one backup, the sum of files per backup does not need to match the global number of files. Above we see that backup1 has 154 files and backup2 has 138 files but in total there is 154 files. This means that backup2 is logically consisting of SSTables which are all in backup1 and backup1 contains all SSTables in backup2 plus some new ones. Same holds for occupied space. The figure of reclaimable space represents the number of bytes (or any human readable size) which would be freed by deleting that particular backup. For example, from the above we see that by deleting backup-2, we would get no free space. Why? Because all SSTables in backup-2 also belongs to backup-1. So we can not just physically remove it because backup-1 would just be corrupted. On the other hand, by deletion of backup-1, we would gain 10.1 kB. Why? Because we just can not go and delete all SSTables belonging to backup-1, because backup-2 would be corrupted - it would miss SStables. We can safely delete only these files from backup-1 which are not in backup-2 - and that difference occupies just 10 kB. However, we see that in total, our data occupy 113 kB at disk even though the sum of occupied space of all backups does not match the total - because there are SSTables logically belonging to multiple backups. Please keep in mind that this table reflects the reality as long as you do not add nor delete any backup. |=== |flag |explanation |--skip-node-resolution |Skips the resolution of cluster name, data center and host id of a node Esop is connected to, otherwise it will try to connect to that node and retrieve this information and it will replace respective placeholders in --storage-location property. |--simple-format |prints out just names of backups instead of all statistics |--json |prints out a json instead of a table |--human-units |prints human-friendly sizes, e.g 5 kB, 1 GB etc instead of just number of bytes |--to-file |path to file to redirect the output of the command to, file is created when it does not exist |--from-timestamp |expects unix timestamp (also present in backup's name at the end), once set, it will only process backups taken since then, including. |--last-n |expects a postive integer to process only last (the oldest) n backups. |=== All `--json`, `--simple-format` and `--to-file` might be freely turned on / off on demand. By default, it will print a table in complex format to the standard output. `list` command is receptive to all family of `--jmx-*` settings in order to connect to a running Cassandra node if necessary. ## Removal of a backup Since we are storing each SSTable only once, ever, a deletion of a backup is not so straightforward. We might delete only SSTable which is present only in one backup. If some particular SSTable is present in multiple backups, we might delete that backup _logically_, but we can not delete that SSTable. The underlying logic computes how may backups a particular file is present it by scanning all manifests there are and if we specify we want to delete so and so backup, it will physically remove only files which are part of that very backup and they are not present anywhere else. By doing this, we are not forced to remove only the last backup (for example looking at its timestamp) but we can in general remove any backup. The general workflow is to either list all backups and remove only the one you want, or you can specify `--oldest` to delete the oldest one and you can do this repeatedly. If you want to remove all backups older than some time, you might get this information from listing the backups by specifying `--from-timestamp` and then you can delete these backups one by one. ---- $ java -jar ~/esop.jar remove-backup \\ --storage-location=file:///backup1/cluster/datacenter1/node1 \\ --skip-node-resolution \\ --backup-name=full-backup-name-from-listing-with-timestamp-etc ---- All flags: |=== |flag |explanation |--backup-name |name of manifest file to delete a backup for (minus .json) |--oldest |removes oldest backup there is, backup names does not need to be specified then |--dry |it will not delete files for real, good for evaluation to see what it would do before shooting |--skip-node-resolution |consult list command, same logic |=== ## Global removal of backups From the previous section, you know how to delete an individual backup. However, it would be nice to be able to delete, for example, all backups older than 14 days, globaly. ""Globally"" means that it will scan whole local backup destination of all nodes (all dcs). You have the option to either do individual removal or global removal. For global removal of backups older than 14 days: [source,bash] ---- $ esop remove-backup \\ --global-request \\ --skip-node-resolution \\ --storage-location=file:///submit/backup/Test-Cluster/dc1/ab3f1d62-1a61-4f84-a2e2-97a626940d8d \\ --older-than=14day ---- It is enough to specify one node, all other nodes will be resolved automatically. `--older-than` accepts a format like ""number+unit"", for example ""1h"", ""1minute"". If you want to run this in a daemon mode - meaning this operation would be run repeatedly, you need to execute it like this: [source,bash] ---- $ esop remove-backup \\ --global-request \\ --skip-node-resolution \\ --storage-location=file:///submit/backup/Test-Cluster/dc1/ab3f1d62-1a61-4f84-a2e2-97a626940d8d \\ --older-than=5minute \\ --rate=1minute ---- This means it will execute a backup removal every 1 minute and it will delete all backups older than 5 minutes. For more real scenarios you might specify `--older-than=14day` and `--rate=1day`. The time for the next execution will count down from the time this command was firstly executed. You have also possibility to specify datacenters to remove by `--dcs` flag (might be specified multiple times for each dc separately) ## Logging We are using logback. There is already `logback.xml` embedded in the built JAR. However if you want to configure it, feel free to provide your own `logback.xml` and configure it like this: ---- java -Dlogback.configurationFile=my-custom-logback.xml \\ -jar instaclustr-backup-restore.jar backup ---- You can find the original file in `src/main/resources/logback.xml`. ## Build and Test There are end-to-end tests which can test all GCP, Azure, and S3 integrations as well as integrations with Kubernetes when it comes to credential fetching. Here are the test groups/profiles: * azureTests * googleTest * s3Tests * cloudTest—runs tests which will be using cloud ""buckets"" for backup / restore * k8sTest—same as `cloudTest` above, but credentials will be fetched from Kubernetes. There is no need to create buckets in a cloud beforehand as they will be created and deleted as part of a test automatically, per cloud provider. If a test is ""Kubernetes-aware"", before every test credentials are created as a Secret which will be used by backup/restore tooling during a test. We are simulating here how this tooling can be easily embedded into for example Cassandra Sidecar (part of Cassandra operator). We are avoiding the need to specify credentials upfront when a Kubernetes pod is starting as a part of that spec, by dynamically fetching all credentials from a Secret whose name is passed to a backup request and is read every time. The side-effect of this is that we can change our credentials without restarting a pod to re-read them because they will be read dynamically upon every backup request. Cloud tests are executed like this: ---- $ mvn clean install -PcloudTests ---- Kubernetes tests are executed like this: ---- $ mvn clean install -Pk8sTests ---- By default, `mvn install` is invoked with `noCloudTests` which will skip all tests dealing with storage provides but `file://`. You have to specify these system properties to run these tests successfully: ---- -Dawsaccesskeyid={your aws access key id} -Dawssecretaccesskey={your aws secret access key} -Dgoogle.application.credentials={path to google application credentials file on local disk} -Dazurestorageaccount={your azure storage account} -Dazurestoragekey={your azure storage key} ---- In order to skip tests altogether, invoke the build like `mvn clean install -DskipTests`. User can use a Maven wrapper script so all Maven will be downloaded automatically. The build in that case is run as `./mvnw clean install`. If you want to build rpm or deb package, you need to enable `rpm` and/or `deb` Maven profile. ## Further Information - Please see https://www.instaclustr.com/support/documentation/announcements/instaclustr-open-source-project-status/ for Instaclustr support status of this project - See Data Backup Documentation (https://www.instaclustr.com/support/documentation/cassandra/cassandra-cluster-operations/cluster-data-backups/) ",16199,True,2677.7761187387514,median "------------------------------------------------------------------------------ -- -- -- GNAT RUNTIME COMPONENTS -- -- -- -- A D A . S T R I N G S . W I D E _ B O U N D E D -- -- -- -- B o d y -- -- -- -- $Revision$ -- -- -- Copyright (C) 1992-2001 Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT 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 distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Ada.Strings.Wide_Maps; use Ada.Strings.Wide_Maps; with Ada.Strings.Wide_Search; package body Ada.Strings.Wide_Bounded is package body Generic_Bounded_Length is --------- -- ""&"" -- --------- function ""&"" (Left : in Bounded_Wide_String; Right : in Bounded_Wide_String) return Bounded_Wide_String is Result : Bounded_Wide_String; Llen : constant Length_Range := Left.Length; Rlen : constant Length_Range := Right.Length; Nlen : constant Natural := Llen + Rlen; begin if Nlen > Max_Length then raise Ada.Strings.Length_Error; else Result.Length := Nlen; Result.Data (1 .. Llen) := Left.Data (1 .. Llen); Result.Data (Llen + 1 .. Nlen) := Right.Data (1 .. Rlen); end if; return Result; end ""&""; function ""&"" (Left : in Bounded_Wide_String; Right : in Wide_String) return Bounded_Wide_String is Result : Bounded_Wide_String; Llen : constant Length_Range := Left.Length; Nlen : constant Natural := Llen + Right'Length; begin if Nlen > Max_Length then raise Ada.Strings.Length_Error; else Result.Length := Nlen; Result.Data (1 .. Llen) := Left.Data (1 .. Llen); Result.Data (Llen + 1 .. Nlen) := Right; end if; return Result; end ""&""; function ""&"" (Left : in Wide_String; Right : in Bounded_Wide_String) return Bounded_Wide_String is Result : Bounded_Wide_String; Llen : constant Length_Range := Left'Length; Rlen : constant Length_Range := Right.Length; Nlen : constant Natural := Llen + Rlen; begin if Nlen > Max_Length then raise Ada.Strings.Length_Error; else Result.Length := Nlen; Result.Data (1 .. Llen) := Left; Result.Data (Llen + 1 .. Nlen) := Right.Data (1 .. Rlen); end if; return Result; end ""&""; function ""&"" (Left : in Bounded_Wide_String; Right : in Wide_Character) return Bounded_Wide_String is Result : Bounded_Wide_String; Llen : constant Length_Range := Left.Length; begin if Llen = Max_Length then raise Ada.Strings.Length_Error; else Result.Length := Llen + 1; Result.Data (1 .. Llen) := Left.Data (1 .. Llen); Result.Data (Result.Length) := Right; end if; return Result; end ""&""; function ""&"" (Left : in Wide_Character; Right : in Bounded_Wide_String) return Bounded_Wide_String is Result : Bounded_Wide_String; Rlen : Length_Range := Right.Length; begin if Rlen = Max_Length then raise Ada.Strings.Length_Error; else Result.Length := Rlen + 1; Result.Data (1) := Left; Result.Data (2 .. Result.Length) := Right.Data (1 .. Rlen); end if; return Result; end ""&""; --------- -- ""*"" -- --------- function ""*"" (Left : in Natural; Right : in Wide_Character) return Bounded_Wide_String is Result : Bounded_Wide_String; begin if Left > Max_Length then raise Ada.Strings.Length_Error; else Result.Length := Left; for J in 1 .. Left loop Result.Data (J) := Right; end loop; end if; return Result; end ""*""; function ""*"" (Left : in Natural; Right : in Wide_String) return Bounded_Wide_String is Result : Bounded_Wide_String; Pos : Positive := 1; Rlen : constant Natural := Right'Length; Nlen : constant Natural := Left * Rlen; begin if Nlen > Max_Length then raise Ada.Strings.Index_Error; else Result.Length := Nlen; if Nlen > 0 then for J in 1 .. Left loop Result.Data (Pos .. Pos + Rlen - 1) := Right; Pos := Pos + Rlen; end loop; end if; end if; return Result; end ""*""; function ""*"" (Left : in Natural; Right : in Bounded_Wide_String) return Bounded_Wide_String is Result : Bounded_Wide_String; Pos : Positive := 1; Rlen : constant Length_Range := Right.Length; Nlen : constant Natural := Left * Rlen; begin if Nlen > Max_Length then raise Ada.Strings.Length_Error; else Result.Length := Nlen; if Nlen > 0 then for J in 1 .. Left loop Result.Data (Pos .. Pos + Rlen - 1) := Right.Data (1 .. Rlen); Pos := Pos + Rlen; end loop; end if; end if; return Result; end ""*""; --------- -- ""<"" -- --------- function ""<"" (Left : in Bounded_Wide_String; Right : in Bounded_Wide_String) return Boolean is begin return Left.Data (1 .. Left.Length) < Right.Data (1 .. Right.Length); end ""<""; function ""<"" (Left : in Bounded_Wide_String; Right : in Wide_String) return Boolean is begin return Left.Data (1 .. Left.Length) < Right; end ""<""; function ""<"" (Left : in Wide_String; Right : in Bounded_Wide_String) return Boolean is begin return Left < Right.Data (1 .. Right.Length); end ""<""; ---------- -- ""<="" -- ---------- function ""<="" (Left : in Bounded_Wide_String; Right : in Bounded_Wide_String) return Boolean is begin return Left.Data (1 .. Left.Length) <= Right.Data (1 .. Right.Length); end ""<=""; function ""<="" (Left : in Bounded_Wide_String; Right : in Wide_String) return Boolean is begin return Left.Data (1 .. Left.Length) <= Right; end ""<=""; function ""<="" (Left : in Wide_String; Right : in Bounded_Wide_String) return Boolean is begin return Left <= Right.Data (1 .. Right.Length); end ""<=""; --------- -- ""="" -- --------- function ""="" (Left : in Bounded_Wide_String; Right : in Bounded_Wide_String) return Boolean is begin return Left.Length = Right.Length and then Left.Data (1 .. Left.Length) = Right.Data (1 .. Right.Length); end ""=""; function ""="" (Left : in Bounded_Wide_String; Right : in Wide_String) return Boolean is begin return Left.Length = Right'Length and then Left.Data (1 .. Left.Length) = Right; end ""=""; function ""="" (Left : in Wide_String; Right : in Bounded_Wide_String) return Boolean is begin return Left'Length = Right.Length and then Left = Right.Data (1 .. Right.Length); end ""=""; --------- -- "">"" -- --------- function "">"" (Left : in Bounded_Wide_String; Right : in Bounded_Wide_String) return Boolean is begin return Left.Data (1 .. Left.Length) > Right.Data (1 .. Right.Length); end "">""; function "">"" (Left : in Bounded_Wide_String; Right : in Wide_String) return Boolean is begin return Left.Data (1 .. Left.Length) > Right; end "">""; function "">"" (Left : in Wide_String; Right : in Bounded_Wide_String) return Boolean is begin return Left > Right.Data (1 .. Right.Length); end "">""; ---------- -- "">="" -- ---------- function "">="" (Left : in Bounded_Wide_String; Right : in Bounded_Wide_String) return Boolean is begin return Left.Data (1 .. Left.Length) >= Right.Data (1 .. Right.Length); end "">=""; function "">="" (Left : in Bounded_Wide_String; Right : in Wide_String) return Boolean is begin return Left.Data (1 .. Left.Length) >= Right; end "">=""; function "">="" (Left : in Wide_String; Right : in Bounded_Wide_String) return Boolean is begin return Left >= Right.Data (1 .. Right.Length); end "">=""; ------------ -- Append -- ------------ -- Case of Bounded_Wide_String and Bounded_Wide_String function Append (Left, Right : in Bounded_Wide_String; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Result : Bounded_Wide_String; Llen : constant Length_Range := Left.Length; Rlen : constant Length_Range := Right.Length; Nlen : constant Natural := Llen + Rlen; begin if Nlen <= Max_Length then Result.Length := Nlen; Result.Data (1 .. Llen) := Left.Data (1 .. Llen); Result.Data (Llen + 1 .. Nlen) := Right.Data (1 .. Rlen); else Result.Length := Max_Length; case Drop is when Strings.Right => if Llen >= Max_Length then -- only case is Llen = Max_Length Result.Data := Right.Data; else Result.Data (1 .. Llen) := Left.Data (1 .. Llen); Result.Data (Llen + 1 .. Max_Length) := Right.Data (1 .. Max_Length - Llen); end if; when Strings.Left => if Rlen >= Max_Length then -- only case is Rlen = Max_Length Result.Data := Right.Data; else Result.Data (1 .. Max_Length - Rlen) := Left.Data (Llen - (Max_Length - Rlen - 1) .. Llen); Result.Data (Max_Length - Rlen + 1 .. Max_Length) := Right.Data (1 .. Rlen); end if; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; return Result; end Append; procedure Append (Source : in out Bounded_Wide_String; New_Item : in Bounded_Wide_String; Drop : in Truncation := Error) is Llen : constant Length_Range := Source.Length; Rlen : constant Length_Range := New_Item.Length; Nlen : constant Natural := Llen + Rlen; begin if Nlen <= Max_Length then Source.Length := Nlen; Source.Data (Llen + 1 .. Nlen) := New_Item.Data (1 .. Rlen); else Source.Length := Max_Length; case Drop is when Strings.Right => if Llen < Max_Length then Source.Data (Llen + 1 .. Max_Length) := New_Item.Data (1 .. Max_Length - Llen); end if; when Strings.Left => if Rlen >= Max_Length then -- only case is Rlen = Max_Length Source.Data := New_Item.Data; else Source.Data (1 .. Max_Length - Rlen) := Source.Data (Llen - (Max_Length - Rlen - 1) .. Llen); Source.Data (Max_Length - Rlen + 1 .. Max_Length) := New_Item.Data (1 .. Rlen); end if; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; end Append; -- Case of Bounded_Wide_String and Wide_String function Append (Left : in Bounded_Wide_String; Right : in Wide_String; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Result : Bounded_Wide_String; Llen : constant Length_Range := Left.Length; Rlen : constant Length_Range := Right'Length; Nlen : constant Natural := Llen + Rlen; begin if Nlen <= Max_Length then Result.Length := Nlen; Result.Data (1 .. Llen) := Left.Data (1 .. Llen); Result.Data (Llen + 1 .. Nlen) := Right; else Result.Length := Max_Length; case Drop is when Strings.Right => if Llen >= Max_Length then -- only case is Llen = Max_Length Result.Data := Left.Data; else Result.Data (1 .. Llen) := Left.Data (1 .. Llen); Result.Data (Llen + 1 .. Max_Length) := Right (Right'First .. Right'First - 1 + Max_Length - Llen); end if; when Strings.Left => if Rlen >= Max_Length then Result.Data (1 .. Max_Length) := Right (Right'Last - (Max_Length - 1) .. Right'Last); else Result.Data (1 .. Max_Length - Rlen) := Left.Data (Llen - (Max_Length - Rlen - 1) .. Llen); Result.Data (Max_Length - Rlen + 1 .. Max_Length) := Right; end if; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; return Result; end Append; procedure Append (Source : in out Bounded_Wide_String; New_Item : in Wide_String; Drop : in Truncation := Error) is Llen : constant Length_Range := Source.Length; Rlen : constant Length_Range := New_Item'Length; Nlen : constant Natural := Llen + Rlen; begin if Nlen <= Max_Length then Source.Length := Nlen; Source.Data (Llen + 1 .. Nlen) := New_Item; else Source.Length := Max_Length; case Drop is when Strings.Right => if Llen < Max_Length then Source.Data (Llen + 1 .. Max_Length) := New_Item (New_Item'First .. New_Item'First - 1 + Max_Length - Llen); end if; when Strings.Left => if Rlen >= Max_Length then Source.Data (1 .. Max_Length) := New_Item (New_Item'Last - (Max_Length - 1) .. New_Item'Last); else Source.Data (1 .. Max_Length - Rlen) := Source.Data (Llen - (Max_Length - Rlen - 1) .. Llen); Source.Data (Max_Length - Rlen + 1 .. Max_Length) := New_Item; end if; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; end Append; -- Case of Wide_String and Bounded_Wide_String function Append (Left : in Wide_String; Right : in Bounded_Wide_String; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Result : Bounded_Wide_String; Llen : constant Length_Range := Left'Length; Rlen : constant Length_Range := Right.Length; Nlen : constant Natural := Llen + Rlen; begin if Nlen <= Max_Length then Result.Length := Nlen; Result.Data (1 .. Llen) := Left; Result.Data (Llen + 1 .. Llen + Rlen) := Right.Data (1 .. Rlen); else Result.Length := Max_Length; case Drop is when Strings.Right => if Llen >= Max_Length then Result.Data (1 .. Max_Length) := Left (Left'First .. Left'First + (Max_Length - 1)); else Result.Data (1 .. Llen) := Left; Result.Data (Llen + 1 .. Max_Length) := Right.Data (1 .. Max_Length - Llen); end if; when Strings.Left => if Rlen >= Max_Length then Result.Data (1 .. Max_Length) := Right.Data (Rlen - (Max_Length - 1) .. Rlen); else Result.Data (1 .. Max_Length - Rlen) := Left (Left'Last - (Max_Length - Rlen - 1) .. Left'Last); Result.Data (Max_Length - Rlen + 1 .. Max_Length) := Right.Data (1 .. Rlen); end if; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; return Result; end Append; -- Case of Bounded_Wide_String and Wide_Character function Append (Left : in Bounded_Wide_String; Right : in Wide_Character; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Result : Bounded_Wide_String; Llen : constant Length_Range := Left.Length; begin if Llen < Max_Length then Result.Length := Llen + 1; Result.Data (1 .. Llen) := Left.Data (1 .. Llen); Result.Data (Llen + 1) := Right; return Result; else case Drop is when Strings.Right => return Left; when Strings.Left => Result.Length := Max_Length; Result.Data (1 .. Max_Length - 1) := Left.Data (2 .. Max_Length); Result.Data (Max_Length) := Right; return Result; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; end Append; procedure Append (Source : in out Bounded_Wide_String; New_Item : in Wide_Character; Drop : in Truncation := Error) is Llen : constant Length_Range := Source.Length; begin if Llen < Max_Length then Source.Length := Llen + 1; Source.Data (Llen + 1) := New_Item; else Source.Length := Max_Length; case Drop is when Strings.Right => null; when Strings.Left => Source.Data (1 .. Max_Length - 1) := Source.Data (2 .. Max_Length); Source.Data (Max_Length) := New_Item; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; end Append; -- Case of Wide_Character and Bounded_Wide_String function Append (Left : in Wide_Character; Right : in Bounded_Wide_String; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Result : Bounded_Wide_String; Rlen : constant Length_Range := Right.Length; begin if Rlen < Max_Length then Result.Length := Rlen + 1; Result.Data (1) := Left; Result.Data (2 .. Rlen + 1) := Right.Data (1 .. Rlen); return Result; else case Drop is when Strings.Right => Result.Length := Max_Length; Result.Data (1) := Left; Result.Data (2 .. Max_Length) := Right.Data (1 .. Max_Length - 1); return Result; when Strings.Left => return Right; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; end Append; ----------- -- Count -- ----------- function Count (Source : in Bounded_Wide_String; Pattern : in Wide_String; Mapping : in Wide_Maps.Wide_Character_Mapping := Wide_Maps.Identity) return Natural is begin return Wide_Search.Count (Source.Data (1 .. Source.Length), Pattern, Mapping); end Count; function Count (Source : in Bounded_Wide_String; Pattern : in Wide_String; Mapping : in Wide_Maps.Wide_Character_Mapping_Function) return Natural is begin return Wide_Search.Count (Source.Data (1 .. Source.Length), Pattern, Mapping); end Count; function Count (Source : in Bounded_Wide_String; Set : in Wide_Maps.Wide_Character_Set) return Natural is begin return Wide_Search.Count (Source.Data (1 .. Source.Length), Set); end Count; ------------ -- Delete -- ------------ function Delete (Source : in Bounded_Wide_String; From : in Positive; Through : in Natural) return Bounded_Wide_String is Slen : constant Natural := Source.Length; Num_Delete : constant Integer := Through - From + 1; Result : Bounded_Wide_String; begin if Num_Delete <= 0 then return Source; elsif From > Slen + 1 then raise Ada.Strings.Index_Error; elsif Through >= Slen then Result.Length := From - 1; Result.Data (1 .. From - 1) := Source.Data (1 .. From - 1); return Result; else Result.Length := Slen - Num_Delete; Result.Data (1 .. From - 1) := Source.Data (1 .. From - 1); Result.Data (From .. Result.Length) := Source.Data (Through + 1 .. Slen); return Result; end if; end Delete; procedure Delete (Source : in out Bounded_Wide_String; From : in Positive; Through : in Natural) is Slen : constant Natural := Source.Length; Num_Delete : constant Integer := Through - From + 1; begin if Num_Delete <= 0 then return; elsif From > Slen + 1 then raise Ada.Strings.Index_Error; elsif Through >= Slen then Source.Length := From - 1; else Source.Length := Slen - Num_Delete; Source.Data (From .. Source.Length) := Source.Data (Through + 1 .. Slen); end if; end Delete; ------------- -- Element -- ------------- function Element (Source : in Bounded_Wide_String; Index : in Positive) return Wide_Character is begin if Index in 1 .. Source.Length then return Source.Data (Index); else raise Strings.Index_Error; end if; end Element; ---------------- -- Find_Token -- ---------------- procedure Find_Token (Source : in Bounded_Wide_String; Set : in Wide_Maps.Wide_Character_Set; Test : in Strings.Membership; First : out Positive; Last : out Natural) is begin Wide_Search.Find_Token (Source.Data (1 .. Source.Length), Set, Test, First, Last); end Find_Token; ---------- -- Head -- ---------- function Head (Source : in Bounded_Wide_String; Count : in Natural; Pad : in Wide_Character := Wide_Space; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Result : Bounded_Wide_String; Slen : constant Natural := Source.Length; Npad : constant Integer := Count - Slen; begin if Npad <= 0 then Result.Length := Count; Result.Data (1 .. Count) := Source.Data (1 .. Count); elsif Count <= Max_Length then Result.Length := Count; Result.Data (1 .. Slen) := Source.Data (1 .. Slen); Result.Data (Slen + 1 .. Count) := (others => Pad); else Result.Length := Max_Length; case Drop is when Strings.Right => Result.Data (1 .. Slen) := Source.Data (1 .. Slen); Result.Data (Slen + 1 .. Max_Length) := (others => Pad); when Strings.Left => if Npad >= Max_Length then Result.Data := (others => Pad); else Result.Data (1 .. Max_Length - Npad) := Source.Data (Count - Max_Length + 1 .. Slen); Result.Data (Max_Length - Npad + 1 .. Max_Length) := (others => Pad); end if; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; return Result; end Head; procedure Head (Source : in out Bounded_Wide_String; Count : in Natural; Pad : in Wide_Character := Wide_Space; Drop : in Truncation := Error) is Slen : constant Natural := Source.Length; Npad : constant Integer := Count - Slen; Temp : Wide_String (1 .. Max_Length); begin if Npad <= 0 then Source.Length := Count; elsif Count <= Max_Length then Source.Length := Count; Source.Data (Slen + 1 .. Count) := (others => Pad); else Source.Length := Max_Length; case Drop is when Strings.Right => Source.Data (Slen + 1 .. Max_Length) := (others => Pad); when Strings.Left => if Npad > Max_Length then Source.Data := (others => Pad); else Temp := Source.Data; Source.Data (1 .. Max_Length - Npad) := Temp (Count - Max_Length + 1 .. Slen); for J in Max_Length - Npad + 1 .. Max_Length loop Source.Data (J) := Pad; end loop; end if; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; end Head; ----------- -- Index -- ----------- function Index (Source : in Bounded_Wide_String; Pattern : in Wide_String; Going : in Strings.Direction := Strings.Forward; Mapping : in Wide_Maps.Wide_Character_Mapping := Wide_Maps.Identity) return Natural is begin return Wide_Search.Index (Source.Data (1 .. Source.Length), Pattern, Going, Mapping); end Index; function Index (Source : in Bounded_Wide_String; Pattern : in Wide_String; Going : in Direction := Forward; Mapping : in Wide_Maps.Wide_Character_Mapping_Function) return Natural is begin return Wide_Search.Index (Source.Data (1 .. Source.Length), Pattern, Going, Mapping); end Index; function Index (Source : in Bounded_Wide_String; Set : in Wide_Maps.Wide_Character_Set; Test : in Strings.Membership := Strings.Inside; Going : in Strings.Direction := Strings.Forward) return Natural is begin return Wide_Search.Index (Source.Data (1 .. Source.Length), Set, Test, Going); end Index; --------------------- -- Index_Non_Blank -- --------------------- function Index_Non_Blank (Source : in Bounded_Wide_String; Going : in Strings.Direction := Strings.Forward) return Natural is begin return Wide_Search.Index_Non_Blank (Source.Data (1 .. Source.Length), Going); end Index_Non_Blank; ------------ -- Insert -- ------------ function Insert (Source : in Bounded_Wide_String; Before : in Positive; New_Item : in Wide_String; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Slen : constant Natural := Source.Length; Nlen : constant Natural := New_Item'Length; Tlen : constant Natural := Slen + Nlen; Blen : constant Natural := Before - 1; Alen : constant Integer := Slen - Blen; Droplen : constant Integer := Tlen - Max_Length; Result : Bounded_Wide_String; -- Tlen is the length of the total string before possible truncation. -- Blen, Alen are the lengths of the before and after pieces of the -- source string. begin if Alen < 0 then raise Ada.Strings.Index_Error; elsif Droplen <= 0 then Result.Length := Tlen; Result.Data (1 .. Blen) := Source.Data (1 .. Blen); Result.Data (Before .. Before + Nlen - 1) := New_Item; Result.Data (Before + Nlen .. Tlen) := Source.Data (Before .. Slen); else Result.Length := Max_Length; case Drop is when Strings.Right => Result.Data (1 .. Blen) := Source.Data (1 .. Blen); if Droplen > Alen then Result.Data (Before .. Max_Length) := New_Item (New_Item'First .. New_Item'First + Max_Length - Before); else Result.Data (Before .. Before + Nlen - 1) := New_Item; Result.Data (Before + Nlen .. Max_Length) := Source.Data (Before .. Slen - Droplen); end if; when Strings.Left => Result.Data (Max_Length - (Alen - 1) .. Max_Length) := Source.Data (Before .. Slen); if Droplen >= Blen then Result.Data (1 .. Max_Length - Alen) := New_Item (New_Item'Last - (Max_Length - Alen) + 1 .. New_Item'Last); else Result.Data (Blen - Droplen + 1 .. Max_Length - Alen) := New_Item; Result.Data (1 .. Blen - Droplen) := Source.Data (Droplen + 1 .. Blen); end if; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; return Result; end Insert; procedure Insert (Source : in out Bounded_Wide_String; Before : in Positive; New_Item : in Wide_String; Drop : in Strings.Truncation := Strings.Error) is begin -- We do a double copy here because this is one of the situations -- in which we move data to the right, and at least at the moment, -- GNAT is not handling such cases correctly ??? Source := Insert (Source, Before, New_Item, Drop); end Insert; ------------ -- Length -- ------------ function Length (Source : in Bounded_Wide_String) return Length_Range is begin return Source.Length; end Length; --------------- -- Overwrite -- --------------- function Overwrite (Source : in Bounded_Wide_String; Position : in Positive; New_Item : in Wide_String; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Result : Bounded_Wide_String; Endpos : constant Natural := Position + New_Item'Length - 1; Slen : constant Natural := Source.Length; Droplen : Natural; begin if Position > Slen + 1 then raise Ada.Strings.Index_Error; elsif New_Item'Length = 0 then return Source; elsif Endpos <= Slen then Result.Length := Source.Length; Result.Data (1 .. Slen) := Source.Data (1 .. Slen); Result.Data (Position .. Endpos) := New_Item; return Result; elsif Endpos <= Max_Length then Result.Length := Endpos; Result.Data (1 .. Position - 1) := Source.Data (1 .. Position - 1); Result.Data (Position .. Endpos) := New_Item; return Result; else Result.Length := Max_Length; Droplen := Endpos - Max_Length; case Drop is when Strings.Right => Result.Data (1 .. Position - 1) := Source.Data (1 .. Position - 1); Result.Data (Position .. Max_Length) := New_Item (New_Item'First .. New_Item'Last - Droplen); return Result; when Strings.Left => if New_Item'Length >= Max_Length then Result.Data (1 .. Max_Length) := New_Item (New_Item'Last - Max_Length + 1 .. New_Item'Last); return Result; else Result.Data (1 .. Max_Length - New_Item'Length) := Source.Data (Droplen + 1 .. Position - 1); Result.Data (Max_Length - New_Item'Length + 1 .. Max_Length) := New_Item; return Result; end if; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; end Overwrite; procedure Overwrite (Source : in out Bounded_Wide_String; Position : in Positive; New_Item : in Wide_String; Drop : in Strings.Truncation := Strings.Error) is Endpos : constant Positive := Position + New_Item'Length - 1; Slen : constant Natural := Source.Length; Droplen : Natural; begin if Position > Slen + 1 then raise Ada.Strings.Index_Error; elsif Endpos <= Slen then Source.Data (Position .. Endpos) := New_Item; elsif Endpos <= Max_Length then Source.Data (Position .. Endpos) := New_Item; Source.Length := Endpos; else Source.Length := Max_Length; Droplen := Endpos - Max_Length; case Drop is when Strings.Right => Source.Data (Position .. Max_Length) := New_Item (New_Item'First .. New_Item'Last - Droplen); when Strings.Left => if New_Item'Length > Max_Length then Source.Data (1 .. Max_Length) := New_Item (New_Item'Last - Max_Length + 1 .. New_Item'Last); else Source.Data (1 .. Max_Length - New_Item'Length) := Source.Data (Droplen + 1 .. Position - 1); Source.Data (Max_Length - New_Item'Length + 1 .. Max_Length) := New_Item; end if; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; end Overwrite; --------------------- -- Replace_Element -- --------------------- procedure Replace_Element (Source : in out Bounded_Wide_String; Index : in Positive; By : in Wide_Character) is begin if Index <= Source.Length then Source.Data (Index) := By; else raise Ada.Strings.Index_Error; end if; end Replace_Element; ------------------- -- Replace_Slice -- ------------------- function Replace_Slice (Source : in Bounded_Wide_String; Low : in Positive; High : in Natural; By : in Wide_String; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Slen : constant Natural := Source.Length; begin if Low > Slen + 1 then raise Strings.Index_Error; elsif High < Low then return Insert (Source, Low, By, Drop); else declare Blen : constant Natural := Natural'Max (0, Low - 1); Alen : constant Natural := Natural'Max (0, Slen - High); Tlen : constant Natural := Blen + By'Length + Alen; Droplen : constant Integer := Tlen - Max_Length; Result : Bounded_Wide_String; -- Tlen is the total length of the result string before any -- truncation. Blen and Alen are the lengths of the pieces -- of the original string that end up in the result string -- before and after the replaced slice. begin if Droplen <= 0 then Result.Length := Tlen; Result.Data (1 .. Blen) := Source.Data (1 .. Blen); Result.Data (Low .. Low + By'Length - 1) := By; Result.Data (Low + By'Length .. Tlen) := Source.Data (High + 1 .. Slen); else Result.Length := Max_Length; case Drop is when Strings.Right => Result.Data (1 .. Blen) := Source.Data (1 .. Blen); if Droplen > Alen then Result.Data (Low .. Max_Length) := By (By'First .. By'First + Max_Length - Low); else Result.Data (Low .. Low + By'Length - 1) := By; Result.Data (Low + By'Length .. Max_Length) := Source.Data (High + 1 .. Slen - Droplen); end if; when Strings.Left => Result.Data (Max_Length - (Alen - 1) .. Max_Length) := Source.Data (High + 1 .. Slen); if Droplen >= Blen then Result.Data (1 .. Max_Length - Alen) := By (By'Last - (Max_Length - Alen) + 1 .. By'Last); else Result.Data (Blen - Droplen + 1 .. Max_Length - Alen) := By; Result.Data (1 .. Blen - Droplen) := Source.Data (Droplen + 1 .. Blen); end if; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; return Result; end; end if; end Replace_Slice; procedure Replace_Slice (Source : in out Bounded_Wide_String; Low : in Positive; High : in Natural; By : in Wide_String; Drop : in Strings.Truncation := Strings.Error) is begin -- We do a double copy here because this is one of the situations -- in which we move data to the right, and at least at the moment, -- GNAT is not handling such cases correctly ??? Source := Replace_Slice (Source, Low, High, By, Drop); end Replace_Slice; --------------- -- Replicate -- --------------- function Replicate (Count : in Natural; Item : in Wide_Character; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Result : Bounded_Wide_String; begin if Count <= Max_Length then Result.Length := Count; elsif Drop = Strings.Error then raise Ada.Strings.Length_Error; else Result.Length := Max_Length; end if; Result.Data (1 .. Result.Length) := (others => Item); return Result; end Replicate; function Replicate (Count : in Natural; Item : in Wide_String; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Length : constant Integer := Count * Item'Length; Result : Bounded_Wide_String; Indx : Positive; begin if Length <= Max_Length then Result.Length := Length; if Length > 0 then Indx := 1; for J in 1 .. Count loop Result.Data (Indx .. Indx + Item'Length - 1) := Item; Indx := Indx + Item'Length; end loop; end if; else Result.Length := Max_Length; case Drop is when Strings.Right => Indx := 1; while Indx + Item'Length <= Max_Length + 1 loop Result.Data (Indx .. Indx + Item'Length - 1) := Item; Indx := Indx + Item'Length; end loop; Result.Data (Indx .. Max_Length) := Item (Item'First .. Item'First + Max_Length - Indx); when Strings.Left => Indx := Max_Length; while Indx - Item'Length >= 1 loop Result.Data (Indx - (Item'Length - 1) .. Indx) := Item; Indx := Indx - Item'Length; end loop; Result.Data (1 .. Indx) := Item (Item'Last - Indx + 1 .. Item'Last); when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; return Result; end Replicate; function Replicate (Count : in Natural; Item : in Bounded_Wide_String; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is begin return Replicate (Count, Item.Data (1 .. Item.Length), Drop); end Replicate; ----------- -- Slice -- ----------- function Slice (Source : Bounded_Wide_String; Low : Positive; High : Natural) return Wide_String is begin -- Note: test of High > Length is in accordance with AI95-00128 if Low > Source.Length + 1 or else High > Source.Length then raise Index_Error; else declare Result : Wide_String (1 .. High - Low + 1); begin Result := Source.Data (Low .. High); return Result; end; end if; end Slice; ---------- -- Tail -- ---------- function Tail (Source : in Bounded_Wide_String; Count : in Natural; Pad : in Wide_Character := Wide_Space; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Result : Bounded_Wide_String; Slen : constant Natural := Source.Length; Npad : constant Integer := Count - Slen; begin if Npad <= 0 then Result.Length := Count; Result.Data (1 .. Count) := Source.Data (Slen - (Count - 1) .. Slen); elsif Count <= Max_Length then Result.Length := Count; Result.Data (1 .. Npad) := (others => Pad); Result.Data (Npad + 1 .. Count) := Source.Data (1 .. Slen); else Result.Length := Max_Length; case Drop is when Strings.Right => if Npad >= Max_Length then Result.Data := (others => Pad); else Result.Data (1 .. Npad) := (others => Pad); Result.Data (Npad + 1 .. Max_Length) := Source.Data (1 .. Max_Length - Npad); end if; when Strings.Left => Result.Data (1 .. Max_Length - Slen) := (others => Pad); Result.Data (Max_Length - Slen + 1 .. Max_Length) := Source.Data (1 .. Slen); when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; return Result; end Tail; procedure Tail (Source : in out Bounded_Wide_String; Count : in Natural; Pad : in Wide_Character := Wide_Space; Drop : in Truncation := Error) is Slen : constant Natural := Source.Length; Npad : constant Integer := Count - Slen; Temp : Wide_String (1 .. Max_Length) := Source.Data; begin if Npad <= 0 then Source.Length := Count; Source.Data (1 .. Count) := Temp (Slen - (Count - 1) .. Slen); elsif Count <= Max_Length then Source.Length := Count; Source.Data (1 .. Npad) := (others => Pad); Source.Data (Npad + 1 .. Count) := Temp (1 .. Slen); else Source.Length := Max_Length; case Drop is when Strings.Right => if Npad >= Max_Length then Source.Data := (others => Pad); else Source.Data (1 .. Npad) := (others => Pad); Source.Data (Npad + 1 .. Max_Length) := Temp (1 .. Max_Length - Npad); end if; when Strings.Left => for J in 1 .. Max_Length - Slen loop Source.Data (J) := Pad; end loop; Source.Data (Max_Length - Slen + 1 .. Max_Length) := Temp (1 .. Slen); when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; end Tail; ---------------------------- -- To_Bounded_Wide_String -- ---------------------------- function To_Bounded_Wide_String (Source : in Wide_String; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Slen : constant Natural := Source'Length; Result : Bounded_Wide_String; begin if Slen <= Max_Length then Result.Length := Slen; Result.Data (1 .. Slen) := Source; else case Drop is when Strings.Right => Result.Length := Max_Length; Result.Data (1 .. Max_Length) := Source (Source'First .. Source'First - 1 + Max_Length); when Strings.Left => Result.Length := Max_Length; Result.Data (1 .. Max_Length) := Source (Source'Last - (Max_Length - 1) .. Source'Last); when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; return Result; end To_Bounded_Wide_String; -------------------- -- To_Wide_String -- -------------------- function To_Wide_String (Source : in Bounded_Wide_String) return Wide_String is begin return Source.Data (1 .. Source.Length); end To_Wide_String; --------------- -- Translate -- --------------- function Translate (Source : in Bounded_Wide_String; Mapping : in Wide_Maps.Wide_Character_Mapping) return Bounded_Wide_String is Result : Bounded_Wide_String; begin Result.Length := Source.Length; for J in 1 .. Source.Length loop Result.Data (J) := Value (Mapping, Source.Data (J)); end loop; return Result; end Translate; procedure Translate (Source : in out Bounded_Wide_String; Mapping : in Wide_Maps.Wide_Character_Mapping) is begin for J in 1 .. Source.Length loop Source.Data (J) := Value (Mapping, Source.Data (J)); end loop; end Translate; function Translate (Source : in Bounded_Wide_String; Mapping : in Wide_Maps.Wide_Character_Mapping_Function) return Bounded_Wide_String is Result : Bounded_Wide_String; begin Result.Length := Source.Length; for J in 1 .. Source.Length loop Result.Data (J) := Mapping.all (Source.Data (J)); end loop; return Result; end Translate; procedure Translate (Source : in out Bounded_Wide_String; Mapping : in Wide_Maps.Wide_Character_Mapping_Function) is begin for J in 1 .. Source.Length loop Source.Data (J) := Mapping.all (Source.Data (J)); end loop; end Translate; ---------- -- Trim -- ---------- function Trim (Source : in Bounded_Wide_String; Side : in Trim_End) return Bounded_Wide_String is Result : Bounded_Wide_String; Last : Natural := Source.Length; First : Positive := 1; begin if Side = Left or else Side = Both then while First <= Last and then Source.Data (First) = ' ' loop First := First + 1; end loop; end if; if Side = Right or else Side = Both then while Last >= First and then Source.Data (Last) = ' ' loop Last := Last - 1; end loop; end if; Result.Length := Last - First + 1; Result.Data (1 .. Result.Length) := Source.Data (First .. Last); return Result; end Trim; procedure Trim (Source : in out Bounded_Wide_String; Side : in Trim_End) is Last : Length_Range := Source.Length; First : Positive := 1; Temp : Wide_String (1 .. Max_Length); begin Temp (1 .. Last) := Source.Data (1 .. Last); if Side = Left or else Side = Both then while First <= Last and then Temp (First) = ' ' loop First := First + 1; end loop; end if; if Side = Right or else Side = Both then while Last >= First and then Temp (Last) = ' ' loop Last := Last - 1; end loop; end if; Source.Length := Last - First + 1; Source.Data (1 .. Source.Length) := Temp (First .. Last); end Trim; function Trim (Source : in Bounded_Wide_String; Left : in Wide_Maps.Wide_Character_Set; Right : in Wide_Maps.Wide_Character_Set) return Bounded_Wide_String is Result : Bounded_Wide_String; begin for First in 1 .. Source.Length loop if not Is_In (Source.Data (First), Left) then for Last in reverse First .. Source.Length loop if not Is_In (Source.Data (Last), Right) then Result.Length := Last - First + 1; Result.Data (1 .. Result.Length) := Source.Data (First .. Last); return Result; end if; end loop; end if; end loop; Result.Length := 0; return Result; end Trim; procedure Trim (Source : in out Bounded_Wide_String; Left : in Wide_Maps.Wide_Character_Set; Right : in Wide_Maps.Wide_Character_Set) is begin for First in 1 .. Source.Length loop if not Is_In (Source.Data (First), Left) then for Last in reverse First .. Source.Length loop if not Is_In (Source.Data (Last), Right) then if First = 1 then Source.Length := Last; return; else Source.Length := Last - First + 1; Source.Data (1 .. Source.Length) := Source.Data (First .. Last); return; end if; end if; end loop; Source.Length := 0; return; end if; end loop; Source.Length := 0; end Trim; end Generic_Bounded_Length; end Ada.Strings.Wide_Bounded; ",12159,False,2489.490427124152,median "[[plannerConfiguration]] = OptaPlanner configuration :doctype: book :imagesdir: .. :sectnums: :toc: left :icons: font :experimental: [[plannerConfigurationOverview]] == Overview Solving a planning problem with OptaPlanner consists of the following steps: . *Model your planning problem* as a class annotated with the ``@PlanningSolution`` annotation, for example the ``NQueens`` class. . **Configure a ``**Solver**``**, for example a First Fit and Tabu Search solver for any `NQueens` instance. . *Load a problem data set* from your data layer, for example a Four Queens instance. That is the planning problem. . *Solve it* with `Solver.solve(problem)` which returns the best solution found. image::PlannerConfiguration/inputOutputOverview.png[align=""center""] [[solverConfiguration]] == Solver configuration [[solverConfigurationByXML]] === Solver configuration by XML Build a `Solver` instance with the ``SolverFactory``. Configure the `SolverFactory` with a solver configuration XML file, provided as a classpath resource (as defined by ``ClassLoader.getResource()``): [source,java,options=""nowrap""] ---- SolverFactory solverFactory = SolverFactory.createFromXmlResource( ""org/optaplanner/examples/nqueens/solver/nqueensSolverConfig.xml""); Solver solver = solverFactory.buildSolver(); ---- In a typical project (following the Maven directory structure), that solverConfig XML file would be located at ``$PROJECT_DIR/src/main/resources/org/optaplanner/examples/nqueens/solver/nqueensSolverConfig.xml``. Alternatively, a `SolverFactory` can be created from a ``File`` with ``SolverFactory.createFromXmlFile()``. However, for portability reasons, a classpath resource is recommended. [NOTE] ==== On some environments (<>, <>, ...), classpath resources (such as the solver config, score DRLs and domain classes) in your jars might not be available to the default `ClassLoader` of the `optaplanner-core` jar. In those cases, provide the `ClassLoader` of your classes as a parameter: [source,java,options=""nowrap""] ---- SolverFactory solverFactory = SolverFactory.createFromXmlResource( "".../nqueensSolverConfig.xml"", getClass().getClassLoader()); ---- ==== Both a `Solver` and a `SolverFactory` have a generic type called ``Solution_``, which is the class representing a <>. A solver configuration XML file looks like this: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.nqueens.domain.NQueens org.optaplanner.examples.nqueens.domain.Queen org/optaplanner/examples/nqueens/solver/nQueensConstraints.drl ... ... ... ---- Notice the three parts in it: * Define the model. * Define the score function. * Optionally configure the optimization algorithm(s). These various parts of a configuration are explained further in this manual. *OptaPlanner makes it relatively easy to switch optimization algorithm(s) just by changing the configuration.* There is even a <> which allows you to play out different configurations against each other and report the most appropriate configuration for your use case. [[solverConfigurationByJavaAPI]] === Solver configuration by Java API A solver configuration can also be configured with the `SolverConfig` API. This is especially useful to change some values dynamically at runtime. For example, to change the running time based on system property, before building the ``Solver``: [source,java,options=""nowrap""] ---- SolverConfig solverConfig = SolverConfig.createFromXmlResource( ""org/optaplanner/examples/nqueens/solver/nqueensSolverConfig.xml""); solverConfig.withTerminationConfig(new TerminationConfig() .withMinutesSpentLimit(userInput)); SolverFactory solverFactory = SolverFactory.create(solverConfig); Solver solver = solverFactory.buildSolver(); ---- Every element in the solver configuration XML is available as a `$$*$$Config` class or a property on a `$$*$$Config` class in the package namespace ``org.optaplanner.core.config``. These `$$*$$Config` classes are the Java representation of the XML format. They build the runtime components (of the package namespace ``org.optaplanner.core.impl``) and assemble them into an efficient ``Solver``. [NOTE] ==== To configure a `SolverFactory` dynamically for each user request, build a template `SolverConfig` during initialization and copy it with the copy constructor for each user request: [source,java,options=""nowrap""] ---- private SolverConfig template; public void init() { template = SolverConfig.createFromXmlResource( ""org/optaplanner/examples/nqueens/solver/nqueensSolverConfig.xml""); template.setTerminationConfig(new TerminationConfig()); } // Called concurrently from different threads public void userRequest(..., long userInput) { SolverConfig solverConfig = new SolverConfig(template); // Copy it solverConfig.getTerminationConfig().setMinutesSpentLimit(userInput); SolverFactory solverFactory = SolverFactory.create(solverConfig); Solver solver = solverFactory.buildSolver(); ... } ---- ==== [[annotationAlternatives]] === Annotation alternatives OptaPlanner needs to be told which classes in your domain model are planning entities, which properties are planning variables, etc. There are several ways to deliver this information: * Add class annotations and JavaBean property annotations on the domain model (recommended). The property annotations must be on the getter method, not on the setter method. Such a getter does not need to be public. * Add class annotations and field annotations on the domain model. Such a field does not need to be public. * No annotations: externalize the domain configuration in an XML file. This is https://issues.redhat.com/browse/PLANNER-151[not yet supported]. This manual focuses on the first manner, but every feature supports all three manners, even if it's not explicitly mentioned. [[domainAccess]] === Domain access OptaPlanner by default accesses your domain using reflection, which will always work, but is slow compared to direct access. Alternatively, you can configure OptaPlanner to access your domain using Gizmo, which will generate bytecode that directly access the fields/methods of your domain without reflection. However, it comes with some restrictions: * The planning annotations can only be on public fields and public getters. * io.quarkus.gizmo:gizmo must be on the classpath. These restrictions do not apply when using OptaPlanner with Quarkus, where Gizmo is the default domain access type. To use Gizmo outside of Quarkus, set the `domainAccessType` in the Solver Configuration: [source,xml,options=""nowrap""] ---- GIZMO ---- [[customPropertiesConfiguration]] === Custom properties configuration Solver configuration elements, that instantiate classes and explicitly mention it, support custom properties. Custom properties are useful to tweak dynamic values through the <>. For example, presume your `EasyScoreCalculator` has heavy calculations (which are cached) and you want to increase the cache size in one benchmark: [source,xml,options=""nowrap""] ---- ...MyEasyScoreCalculator ---- Add a public setter for each custom property, which is called when a `Solver` is built. [source,java,options=""nowrap""] ---- public class MyEasyScoreCalculator extends EasyScoreCalculator { private int myCacheSize = 500; // Default value @SuppressWarnings(""unused"") public void setMyCacheSize(int myCacheSize) { this.myCacheSize = myCacheSize; } ... } ---- Most value types are supported (including `boolean`, `int`, `double`, `BigDecimal`, `String` and enums). [[modelAPlanningProblem]] == Model a planning problem [[isThisClassAProblemFactOrPlanningEntity]] === Is this class a problem fact or planning entity? Look at a dataset of your planning problem. You will recognize domain classes in there, each of which can be categorized as one of the following: * An unrelated class: not used by any of the score constraints. From a planning standpoint, this data is obsolete. * A *problem fact* class: used by the score constraints, but does NOT change during planning (as long as the problem stays the same). For example: ``Bed``, ``Room``, ``Shift``, ``Employee``, ``Topic``, ``Period``, ... All the properties of a problem fact class are problem properties. * A *planning entity* class: used by the score constraints and changes during planning. For example: ``BedDesignation``, ``ShiftAssignment``, ``Exam``, ... The properties that change during planning are planning variables. The other properties are problem properties. Ask yourself: __What class changes during planning?__ __Which class has variables that I want the ``__Solver__`` to change for me?__ That class is a planning entity. Most use cases have only one planning entity class. Most use cases also have only one planning variable per planning entity class. [NOTE] ==== In <>, even though the problem itself changes, problem facts do not really change during planning, instead they change between planning (because the Solver temporarily stops to apply the problem fact changes). ==== To create a good domain model, read the <>. *In OptaPlanner, all problem facts and planning entities are plain old JavaBeans (POJOs).* Load them from a database, an XML file, a data repository, a REST service, a noSQL cloud, ... (see <>): it doesn't matter. [[problemFact]] === Problem fact A problem fact is any JavaBean (POJO) with getters that does not change during planning. For example in n queens, the columns and rows are problem facts: [source,java,options=""nowrap""] ---- public class Column { private int index; // ... getters } ---- [source,java,options=""nowrap""] ---- public class Row { private int index; // ... getters } ---- A problem fact can reference other problem facts of course: [source,java,options=""nowrap""] ---- public class Course { private String code; private Teacher teacher; // Other problem fact private int lectureSize; private int minWorkingDaySize; private List curriculumList; // Other problem facts private int studentSize; // ... getters } ---- A problem fact class does _not_ require any OptaPlanner specific code. For example, you can reuse your domain classes, which might have JPA annotations. [NOTE] ==== Generally, better designed domain classes lead to simpler and more efficient score constraints. Therefore, when dealing with a messy (denormalized) legacy system, it can sometimes be worthwhile to convert the messy domain model into a OptaPlanner specific model first. For example: if your domain model has two `Teacher` instances for the same teacher that teaches at two different departments, it is harder to write a correct score constraint that constrains a teacher's spare time on the original model than on an adjusted model. Alternatively, you can sometimes also introduce <> to enrich the domain model for planning only. ==== [[planningEntity]] === Planning entity [[planningEntityAnnotation]] ==== Planning entity annotation A planning entity is a JavaBean (POJO) that changes during solving, for example a `Queen` that changes to another row. A planning problem has multiple planning entities, for example for a single n queens problem, each `Queen` is a planning entity. But there is usually only one planning entity class, for example the `Queen` class. A planning entity class needs to be annotated with the `@PlanningEntity` annotation. Each planning entity class has one or more _planning variables_ (which can be <> or <>). It should also have one or more _defining_ properties. For example in n queens, a `Queen` is defined by its `Column` and has a planning variable ``Row``. This means that a Queen's column never changes during solving, while its row does change. [source,java,options=""nowrap""] ---- @PlanningEntity public class Queen { private Column column; // Planning variables: changes during planning, between score calculations. private Row row; // ... getters and setters } ---- A planning entity class can have multiple planning variables. For example, a `Lecture` is defined by its `Course` and its index in that course (because one course has multiple lectures). Each `Lecture` needs to be scheduled into a `Period` and a `Room` so it has two planning variables (period and room). For example: the course Mathematics has eight lectures per week, of which the first lecture is Monday morning at 08:00 in room 212. [source,java,options=""nowrap""] ---- @PlanningEntity public class Lecture { private Course course; private int lectureIndexInCourse; // Planning variables: changes during planning, between score calculations. private Period period; private Room room; // ... } ---- The solver configuration needs to declare each planning entity class: [source,java,options=""nowrap""] ---- ... org.optaplanner.examples.nqueens.domain.Queen ... ---- Some uses cases have multiple planning entity classes. For example: route freight and trains into railway network arcs, where each freight can use multiple trains over its journey and each train can carry multiple freights per arc. Having multiple planning entity classes directly raises the implementation complexity of your use case. [NOTE] ==== _Do not create unnecessary planning entity classes._ This leads to difficult `Move` implementations and slower score calculation. For example, do not create a planning entity class to hold the total free time of a teacher, which needs to be kept up to date as the `Lecture` planning entities change. Instead, calculate the free time in the score constraints (or as a <>) and put the result per teacher into a logically inserted score object. If historic data needs to be considered too, then create problem fact to hold the total of the historic assignments up to, but __not including__, the planning window (so that it does not change when a planning entity changes) and let the score constraints take it into account. ==== [NOTE] ==== Planning entity `hashCode()` implementations must remain constant. Therefore entity `hashCode()` must not depend on any planning variables. Pay special attention when using data structures with auto-generated `hashCode()` as entities, such as Java records or Kotlin data classes. ==== [[planningEntityDifficulty]] ==== Planning entity difficulty Some optimization algorithms work more efficiently if they have an estimation of which planning entities are more difficult to plan. For example: in bin packing bigger items are harder to fit, in course scheduling lectures with more students are more difficult to schedule, and in n queens the middle queens are more difficult to fit on the board. [NOTE] ==== *Do not try to use planning entity difficulty to implement a business constraint.* It will not affect the score function: if we have infinite solving time, the returned solution will be the same. To attain a schedule in which certain entities are scheduled earlier in the schedule, <> to change the score function so it prefers such solutions. Only consider adding planning entity difficulty too if it can make the solver more efficient. ==== To allow the heuristics to take advantage of that domain specific information, set a `difficultyComparatorClass` to the `@PlanningEntity` annotation: [source,java,options=""nowrap""] ---- @PlanningEntity(difficultyComparatorClass = CloudProcessDifficultyComparator.class) public class CloudProcess { // ... } ---- [source,java,options=""nowrap""] ---- public class CloudProcessDifficultyComparator implements Comparator { public int compare(CloudProcess a, CloudProcess b) { return new CompareToBuilder() .append(a.getRequiredMultiplicand(), b.getRequiredMultiplicand()) .append(a.getId(), b.getId()) .toComparison(); } } ---- Alternatively, you can also set a `difficultyWeightFactoryClass` to the `@PlanningEntity` annotation, so that you have access to the rest of the problem facts from the solution too: [source,java,options=""nowrap""] ---- @PlanningEntity(difficultyWeightFactoryClass = QueenDifficultyWeightFactory.class) public class Queen { // ... } ---- See <> for more information. [IMPORTANT] ==== Difficulty should be implemented ascending: easy entities are lower, difficult entities are higher. For example, in bin packing: small item < medium item < big item. Although most algorithms start with the more difficult entities first, they just reverse the ordering. ==== _None of the current planning variable states should be used to compare planning entity difficulty._ During Construction Heuristics, those variables are likely to be `null` anyway. For example, a ``Queen``'s `row` variable should not be used. [[planningVariable]] === Planning variable (genuine) [[planningVariableAnnotation]] ==== Planning variable annotation A planning variable is a JavaBean property (so a getter and setter) on a planning entity. It points to a planning value, which changes during planning. For example, a ``Queen``'s `row` property is a genuine planning variable. Note that even though a ``Queen``'s `row` property changes to another `Row` during planning, no `Row` instance itself is changed. Normally planning variables are genuine, but advanced cases can also have <>. A genuine planning variable getter needs to be annotated with the `@PlanningVariable` annotation, which needs a non-empty `valueRangeProviderRefs` property. [source,java,options=""nowrap""] ---- @PlanningEntity public class Queen { ... private Row row; @PlanningVariable(valueRangeProviderRefs = {""rowRange""}) public Row getRow() { return row; } public void setRow(Row row) { this.row = row; } } ---- The `valueRangeProviderRefs` property defines what are the possible planning values for this planning variable. It references one or more ``@ValueRangeProvider`` ``id``'s. [NOTE] ==== A @PlanningVariable annotation needs to be on a member in a class with a @PlanningEntity annotation. It is ignored on parent classes or subclasses without that annotation. ==== <> instead of the property works too: [source,java,options=""nowrap""] ---- @PlanningEntity public class Queen { ... @PlanningVariable(valueRangeProviderRefs = {""rowRange""}) private Row row; } ---- [[nullablePlanningVariable]] ==== Nullable planning variable By default, an initialized planning variable cannot be ``null``, so an initialized solution will never use `null` for any of its planning variables. In an over-constrained use case, this can be counterproductive. For example: in task assignment with too many tasks for the workforce, we would rather leave low priority tasks unassigned instead of assigning them to an overloaded worker. To allow an initialized planning variable to be ``null``, set `nullable` to ``true``: [source,java,options=""nowrap""] ---- @PlanningVariable(..., nullable = true) public Worker getWorker() { return worker; } ---- [NOTE] ==== Constraint Streams filter out planning entities with a `null` planning variable by default. Use <> to avoid such unwanted behaviour. ==== OptaPlanner will automatically add the value `null` to the value range. There is no need to add `null` in a collection provided by a ``ValueRangeProvider``. [NOTE] ==== Using a nullable planning variable implies that your score calculation is responsible for punishing (or even rewarding) variables with a `null` value. ==== [WARNING] ==== Currently <> planning variables are not compatible with `nullable`. ==== <> (especially <>) does not mix well with a nullable planning variable. Every time the Solver starts or a problem fact change is made, the <> will try to initialize all the `null` variables again, which can be a huge waste of time. One way to deal with this is to filter the entity selector of the placer in the construction heuristic. [source,xml,options=""nowrap""] ---- ... ... ... ... ... ---- [[whenIsAPlanningVariableInitialized]] ==== When is a planning variable considered initialized? A planning variable is considered initialized if its value is not `null` or if the variable is ``nullable``. So a nullable variable is always considered initialized. A planning entity is initialized if all of its planning variables are initialized. A solution is initialized if all of its planning entities are initialized. [[planningValueAndPlanningValueRange]] === Planning value and planning value range [[planningValue]] ==== Planning value A planning value is a possible value for a genuine planning variable. Usually, a planning value is a problem fact, but it can also be any object, for example a ``double``. It can even be another planning entity or even an interface implemented by both a planning entity and a problem fact. A planning value range is the set of possible planning values for a planning variable. This set can be a countable (for example row ``1``, ``2``, `3` or ``4``) or uncountable (for example any `double` between `0.0` and ``1.0``). [[planningValueRangeProvider]] ==== Planning value range provider [[planningValueRangeProviderOverview]] ===== Overview The value range of a planning variable is defined with the `@ValueRangeProvider` annotation. A `@ValueRangeProvider` annotation always has a property ``id``, which is referenced by the ``@PlanningVariable``'s property ``valueRangeProviderRefs``. This annotation can be located on two types of methods: * On the Solution: All planning entities share the same value range. * On the planning entity: The value range differs per planning entity. This is less common. [NOTE] ==== A @ValueRangeProvider annotation needs to be on a member in a class with a @PlanningSolution or a @PlanningEntity annotation. It is ignored on parent classes or subclasses without those annotations. ==== The return type of that method can be three types: * ``Collection``: The value range is defined by a `Collection` (usually a ``List``) of its possible values. * Array: The value range is defined by an array of its possible values. * ``ValueRange``: The value range is defined by its bounds. This is less common. [[valueRangeProviderOnSolution]] ===== `ValueRangeProvider` on the solution All instances of the same planning entity class share the same set of possible planning values for that planning variable. This is the most common way to configure a value range. The `@PlanningSolution` implementation has method that returns a `Collection` (or a ``ValueRange``). Any value from that `Collection` is a possible planning value for this planning variable. [source,java,options=""nowrap""] ---- @PlanningVariable(valueRangeProviderRefs = {""rowRange""}) public Row getRow() { return row; } ---- [source,java,options=""nowrap""] ---- @PlanningSolution public class NQueens { ... @ValueRangeProvider(id = ""rowRange"") public List getRowList() { return rowList; } } ---- [IMPORTANT] ==== That `Collection` (or ``ValueRange``) must not contain the value ``null``, not even for a <>. ==== <> instead of the property works too: [source,java,options=""nowrap""] ---- @PlanningSolution public class NQueens { ... @ValueRangeProvider(id = ""rowRange"") private List rowList; } ---- [[valueRangeProviderOnPlanningEntity]] ===== `ValueRangeProvider` on the Planning Entity Each planning entity has its own value range (a set of possible planning values) for the planning variable. For example, if a teacher can *never* teach in a room that does not belong to his department, lectures of that teacher can limit their room value range to the rooms of his department. [source,java,options=""nowrap""] ---- @PlanningVariable(valueRangeProviderRefs = {""departmentRoomRange""}) public Room getRoom() { return room; } @ValueRangeProvider(id = ""departmentRoomRange"") public List getPossibleRoomList() { return getCourse().getTeacher().getDepartment().getRoomList(); } ---- Never use this to enforce a soft constraint (or even a hard constraint when the problem might not have a feasible solution). For example: __Unless there is no other way__, a teacher cannot teach in a room that does not belong to his department. In this case, the teacher should _not_ be limited in his room value range (because sometimes there is no other way). [NOTE] ==== By limiting the value range specifically of one planning entity, you are effectively creating a __built-in hard constraint__. This can have the benefit of severely lowering the number of possible solutions; however, it can also take away the freedom of the optimization algorithms to temporarily break that constraint in order to escape from a local optimum. ==== A planning entity should _not_ use other planning entities to determine its value range. That would only try to make the planning entity solve the planning problem itself and interfere with the optimization algorithms. Every entity has its own `List` instance, unless multiple entities have the same value range. For example, if teacher A and B belong to the same department, they use the same `List` instance. Furthermore, each `List` contains a subset of the same set of planning value instances. For example, if department A and B can both use room X, then their `List` instances contain the same `Room` instance. [NOTE] ==== A `ValueRangeProvider` on the planning entity consumes more memory than `ValueRangeProvider` on the Solution and disables certain automatic performance optimizations. ==== [WARNING] ==== A `ValueRangeProvider` on the planning entity is not currently compatible with a <> variable. ==== [[valueRangeFactory]] ===== `ValueRangeFactory` Instead of a ``Collection``, you can also return a `ValueRange` or ``CountableValueRange``, build by the ``ValueRangeFactory``: [source,java,options=""nowrap""] ---- @ValueRangeProvider(id = ""delayRange"") public CountableValueRange getDelayRange() { return ValueRangeFactory.createIntValueRange(0, 5000); } ---- A `ValueRange` uses far less memory, because it only holds the bounds. In the example above, a `Collection` would need to hold all `5000` ints, instead of just the two bounds. Furthermore, an `incrementUnit` can be specified, for example if you have to buy stocks in units of 200 pieces: [source,java,options=""nowrap""] ---- @ValueRangeProvider(id = ""stockAmountRange"") public CountableValueRange getStockAmountRange() { // Range: 0, 200, 400, 600, ..., 9999600, 9999800, 10000000 return ValueRangeFactory.createIntValueRange(0, 10000000, 200); } ---- [NOTE] ==== Return `CountableValueRange` instead of `ValueRange` whenever possible (so OptaPlanner knows that it's countable). ==== The `ValueRangeFactory` has creation methods for several value class types: * ``boolean``: A boolean range. * ``int``: A 32bit integer range. * ``long``: A 64bit integer range. * ``double``: A 64bit floating point range which only supports random selection (because it does not implement ``CountableValueRange``). * ``BigInteger``: An arbitrary-precision integer range. * ``BigDecimal``: A decimal point range. By default, the increment unit is the lowest non-zero value in the scale of the bounds. * `Temporal` (such as ``LocalDate``, ``LocalDateTime``, ...): A time range. [[combineValueRangeProviders]] ===== Combine `ValueRangeProviders` Value range providers can be combined, for example: [source,java,options=""nowrap""] ---- @PlanningVariable(valueRangeProviderRefs = {""companyCarRange"", ""personalCarRange""}) public Car getCar() { return car; } ---- [source,java,options=""nowrap""] ---- @ValueRangeProvider(id = ""companyCarRange"") public List getCompanyCarList() { return companyCarList; } @ValueRangeProvider(id = ""personalCarRange"") public List getPersonalCarList() { return personalCarList; } ---- [[planningValueStrength]] ==== Planning value strength Some optimization algorithms work a bit more efficiently if they have an estimation of which planning values are stronger, which means they are more likely to satisfy a planning entity. For example: in bin packing bigger containers are more likely to fit an item and in course scheduling bigger rooms are less likely to break the student capacity constraint. Usually, the efficiency gain of planning value strength is far less than that of <>. [NOTE] ==== *Do not try to use planning value strength to implement a business constraint.* It will not affect the score function: if we have infinite solving time, the returned solution will be the same. To affect the score function, <>. Only consider adding planning value strength too if it can make the solver more efficient. ==== To allow the heuristics to take advantage of that domain specific information, set a `strengthComparatorClass` to the `@PlanningVariable` annotation: [source,java,options=""nowrap""] ---- @PlanningVariable(..., strengthComparatorClass = CloudComputerStrengthComparator.class) public CloudComputer getComputer() { return computer; } ---- [source,java,options=""nowrap""] ---- public class CloudComputerStrengthComparator implements Comparator { public int compare(CloudComputer a, CloudComputer b) { return new CompareToBuilder() .append(a.getMultiplicand(), b.getMultiplicand()) .append(b.getCost(), a.getCost()) // Descending (but this is debatable) .append(a.getId(), b.getId()) .toComparison(); } } ---- [NOTE] ==== If you have multiple planning value classes in the _same_ value range, the `strengthComparatorClass` needs to implement a `Comparator` of a common superclass (for example ``Comparator``) and be able to handle comparing instances of those different classes. ==== Alternatively, you can also set a `strengthWeightFactoryClass` to the `@PlanningVariable` annotation, so you have access to the rest of the problem facts from the solution too: [source,java,options=""nowrap""] ---- @PlanningVariable(..., strengthWeightFactoryClass = RowStrengthWeightFactory.class) public Row getRow() { return row; } ---- See <> for more information. [IMPORTANT] ==== Strength should be implemented ascending: weaker values are lower, stronger values are higher. For example in bin packing: small container < medium container < big container. ==== _None of the current planning variable state in any of the planning entities should be used to compare planning values._ During construction heuristics, those variables are likely to be ``null``. For example, none of the `row` variables of any `Queen` may be used to determine the strength of a ``Row``. [[chainedPlanningVariable]] ==== Chained planning variable (TSP, VRP, ...) Some use cases, such as TSP and Vehicle Routing, require __chaining__. This means the planning entities point to each other and form a chain. By modeling the problem as a set of chains (instead of a set of trees/loops), the search space is heavily reduced. A planning variable that is chained either: * Directly points to a problem fact (or planning entity), which is called an __anchor__. * Points to another planning entity with the same planning variable, which recursively points to an anchor. Here are some examples of valid and invalid chains: image::PlannerConfiguration/chainPrinciples.png[align=""center""] *Every initialized planning entity is part of an open-ended chain that begins from an anchor.* A valid model means that: * A chain is never a loop. The tail is always open. * Every chain always has exactly one anchor. The anchor is never an instance of the planning entity class that contains the chained planning variable. * A chain is never a tree, it is always a line. Every anchor or planning entity has at most one trailing planning entity. * Every initialized planning entity is part of a chain. * An anchor with no planning entities pointing to it, is also considered a chain. [WARNING] ==== A planning problem instance given to the `Solver` must be valid. ==== [NOTE] ==== If your constraints dictate a closed chain, model it as an open-ended chain (which is easier to persist in a database) and implement a score constraint for the last entity back to the anchor. ==== The optimization algorithms and built-in ``Move``s do chain correction to guarantee that the model stays valid: image::PlannerConfiguration/chainCorrection.png[align=""center""] [WARNING] ==== A custom `Move` implementation must leave the model in a valid state. ==== For example, in TSP the anchor is a `Domicile` (in vehicle routing it is ``Vehicle``): [source,java,options=""nowrap""] ---- public class Domicile ... implements Standstill { ... public City getCity() {...} } ---- The anchor (which is a problem fact) and the planning entity implement a common interface, for example TSP's ``Standstill``: [source,java,options=""nowrap""] ---- public interface Standstill { City getCity(); } ---- That interface is the return type of the planning variable. Furthermore, the planning variable is chained. For example TSP's `Visit` (in vehicle routing it is ``Customer``): [source,java,options=""nowrap""] ---- @PlanningEntity public class Visit ... implements Standstill { ... public City getCity() {...} @PlanningVariable(graphType = PlanningVariableGraphType.CHAINED, valueRangeProviderRefs = {""domicileRange"", ""visitRange""}) public Standstill getPreviousStandstill() { return previousStandstill; } public void setPreviousStandstill(Standstill previousStandstill) { this.previousStandstill = previousStandstill; } } ---- Notice how two value range providers are usually combined: * The value range provider that holds the anchors, for example ``domicileList``. * The value range provider that holds the initialized planning entities, for example ``visitList``. [[planningProblemAndPlanningSolution]] === Planning problem and planning solution [[planningProblemInstance]] ==== Planning problem instance A dataset for a planning problem needs to be wrapped in a class for the `Solver` to solve. That solution class represents both the planning problem and (if solved) a solution. It is annotated with a `@PlanningSolution` annotation. For example in n queens, the solution class is the `NQueens` class, which contains a `Column` list, a `Row` list, and a `Queen` list. A planning problem is actually an unsolved planning solution or - stated differently - an uninitialized solution. For example in n queens, that `NQueens` class has the `@PlanningSolution` annotation, yet every `Queen` in an unsolved `NQueens` class is not yet assigned to a `Row` (their `row` property is ``null``). That's not a feasible solution. It's not even a possible solution. It's an uninitialized solution. [[solutionClass]] ==== Solution class A solution class holds all problem facts, planning entities and a score. It is annotated with a `@PlanningSolution` annotation. For example, an `NQueens` instance holds a list of all columns, all rows and all `Queen` instances: [source,java,options=""nowrap""] ---- @PlanningSolution public class NQueens { // Problem facts private int n; private List columnList; private List rowList; // Planning entities private List queenList; private SimpleScore score; ... } ---- The solver configuration needs to declare the planning solution class: [source,java,options=""nowrap""] ---- ... org.optaplanner.examples.nqueens.domain.NQueens ... ---- [[planningEntitiesOfASolution]] ==== Planning entities of a solution (`@PlanningEntityCollectionProperty`) OptaPlanner needs to extract the entity instances from the solution instance. It gets those collection(s) by calling every getter (or field) that is annotated with ``@PlanningEntityCollectionProperty``: [source,java,options=""nowrap""] ---- @PlanningSolution public class NQueens { ... private List queenList; @PlanningEntityCollectionProperty public List getQueenList() { return queenList; } } ---- There can be multiple `@PlanningEntityCollectionProperty` annotated members. Those can even return a `Collection` with the same entity class type. Instead of `Collection`, it can also return an array. [NOTE] ==== A `@PlanningEntityCollectionProperty` annotation needs to be on a member in a class with a `@PlanningSolution` annotation. It is ignored on parent classes or subclasses without that annotation. ==== In rare cases, a planning entity might be a singleton: use `@PlanningEntityProperty` on its getter (or field) instead. Both annotations can also be <> if enabled. [[scoreOfASolution]] ==== `Score` of asSolution (`@PlanningScore`) A `@PlanningSolution` class requires a score property (or field), which is annotated with a `@PlanningScore` annotation. The score property is `null` if the score hasn't been calculated yet. The `score` property is typed to the specific `Score` implementation of your use case. For example, `NQueens` uses a <>: [source,java,options=""nowrap""] ---- @PlanningSolution public class NQueens { ... private SimpleScore score; @PlanningScore public SimpleScore getScore() { return score; } public void setScore(SimpleScore score) { this.score = score; } } ---- Most use cases use a <> instead: [source,java,options=""nowrap""] ---- @PlanningSolution public class CloudBalance { ... private HardSoftScore score; @PlanningScore public HardSoftScore getScore() { return score; } public void setScore(HardSoftScore score) { this.score = score; } } ---- Some use cases use <>. This annotation can also be <> if enabled. [[problemFacts]] ==== Problem facts of a solution (`@ProblemFactCollectionProperty`) For <> and <>, OptaPlanner needs to extract the problem fact instances from the solution instance. It gets those collection(s) by calling every method (or field) that is annotated with ``@ProblemFactCollectionProperty``. All objects returned by those methods are available to use by the constraint streams or Drools rules. For example in `NQueens` all `Column` and `Row` instances are problem facts. [source,java,options=""nowrap""] ---- @PlanningSolution public class NQueens { ... private List columnList; private List rowList; @ProblemFactCollectionProperty public List getColumnList() { return columnList; } @ProblemFactCollectionProperty public List getRowList() { return rowList; } } ---- All planning entities are automatically inserted into the Drools working memory. Do note add an annotation on their properties. [NOTE] ==== The problem facts methods are not called often: at most only once per solver phase per solver thread. ==== There can be multiple `@ProblemFactCollectionProperty` annotated members. Those can even return a `Collection` with the same class type, but they shouldn't return the same instance twice. Instead of `Collection`, it can also return an array. [NOTE] ==== A @ProblemFactCollectionProperty annotation needs to be on a member in a class with a @PlanningSolution annotation. It is ignored on parent classes or subclasses without that annotation. ==== In rare cases, a problem fact might be a singleton: use `@ProblemFactProperty` on its method (or field) instead. Both annotations can also be <> if enabled. [[cachedProblemFact]] ===== Cached problem fact A cached problem fact is a problem fact that does not exist in the real domain model, but is calculated before the `Solver` really starts solving. The problem facts methods have the opportunity to enrich the domain model with such cached problem facts, which can lead to simpler and faster score constraints. For example in examination, a cached problem fact `TopicConflict` is created for every two ``Topic``s which share at least one ``Student``. [source,java,options=""nowrap""] ---- @ProblemFactCollectionProperty private List calculateTopicConflictList() { List topicConflictList = new ArrayList(); for (Topic leftTopic : topicList) { for (Topic rightTopic : topicList) { if (leftTopic.getId() < rightTopic.getId()) { int studentSize = 0; for (Student student : leftTopic.getStudentList()) { if (rightTopic.getStudentList().contains(student)) { studentSize++; } } if (studentSize > 0) { topicConflictList.add(new TopicConflict(leftTopic, rightTopic, studentSize)); } } } } return topicConflictList; } ---- Where a score constraint needs to check that no two exams with a topic that shares a student are scheduled close together (depending on the constraint: at the same time, in a row, or in the same day), the `TopicConflict` instance can be used as a problem fact, rather than having to combine every two `Student` instances. [[autoDiscoverSolutionProperties]] ==== Auto discover solution properties Instead of configuring each property (or field) annotation explicitly, some can also be deduced automatically by OptaPlanner. For example, on the cloud balancing example: [source,java,options=""nowrap""] ---- @PlanningSolution(autoDiscoverMemberType = AutoDiscoverMemberType.FIELD) public class CloudBalance { // Auto discovered as @ProblemFactCollectionProperty @ValueRangeProvider(id = ""computerRange"") // Not (yet) auto discovered private List computerList; // Auto discovered as @PlanningEntityCollectionProperty private List processList; // Auto discovered as @PlanningScore private HardSoftScore score; ... } ---- The `AutoDiscoverMemberType` can be: * `NONE`: No auto discovery. * `FIELD`: Auto discover all fields on the `@PlanningSolution` class * `GETTER`: Auto discover all getters on the `@PlanningSolution` class The automatic annotation is based on the field type (or getter return type): * `@ProblemFactProperty`: when it isn't a `Collection`, an array, a `@PlanningEntity` class or a `Score` * `@ProblemFactCollectionProperty`: when it's a `Collection` (or array) of a type that isn't a `@PlanningEntity` class * `@PlanningEntityProperty`: when it is a configured `@PlanningEntity` class or subclass * `@PlanningEntityCollectionProperty`: when it's a `Collection` (or array) of a type that is a configured `@PlanningEntity` class or subclass * `@PlanningScore`: when it is a `Score` or subclass These automatic annotation can still be overwritten per field (or getter). Specifically, a <> always needs to override with an explicit `@PlanningScore` annotation to define the number of hard and soft levels. [[cloningASolution]] ==== Cloning a solution Most (if not all) optimization algorithms clone the solution each time they encounter a new best solution (so they can recall it later) or to work with multiple solutions in parallel. [NOTE] ==== There are many ways to clone, such as a shallow clone, deep clone, ... This context focuses on __a planning clone__. ==== A planning clone of a solution must fulfill these requirements: * The clone must represent the same planning problem. Usually it reuses the same instances of the problem facts and problem fact collections as the original. * The clone must use different, cloned instances of the entities and entity collections. Changes to an original solution entity's variables must not affect its clone. image::PlannerConfiguration/solutionCloning.png[align=""center""] *Implementing a planning clone method is hard, therefore you do not need to implement it.* [[fieldAccessingSolutionCloner]] ===== `FieldAccessingSolutionCloner` This `SolutionCloner` is used by default. It works well for most use cases. [WARNING] ==== When the `FieldAccessingSolutionCloner` clones one of your collections or maps, it may not recognize the implementation and replace it with `ArrayList`, `LinkedHashSet`, `TreeSet`, `LinkedHashMap` or `TreeMap` (whichever is more applicable) . It recognizes most of the common JDK collection and map implementations. ==== The `FieldAccessingSolutionCloner` does not clone problem facts by default. If any of your problem facts needs to be deep cloned for a planning clone, for example if the problem fact references a planning entity or the planning solution, mark its class with a `@DeepPlanningClone` annotation: [source,java,options=""nowrap""] ---- @DeepPlanningClone public class SeatDesignationDependency { private SeatDesignation leftSeatDesignation; // planning entity private SeatDesignation rightSeatDesignation; // planning entity ... } ---- In the example above, because `SeatDesignationDependency` references the planning entity `SeatDesignation` (which is deep planning cloned automatically), it should also be deep planning cloned. Alternatively, the `@DeepPlanningClone` annotation also works on a getter method or a field to planning clone it. If that property is a `Collection` or a `Map`, it will shallow clone it and deep planning clone any element thereof that is an instance of a class that has a `@DeepPlanningClone` annotation. [[customCloning]] ===== Custom cloning with a `SolutionCloner` To use a custom cloner, configure it on the planning solution: [source,java,options=""nowrap""] ---- @PlanningSolution(solutionCloner = NQueensSolutionCloner.class) public class NQueens { ... } ---- For example, a `NQueens` planning clone only deep clones all `Queen` instances. So when the original solution changes (later on during planning) and one or more ``Queen`` instances change, the planning clone isn't affected. [source,java,options=""nowrap""] ---- public class NQueensSolutionCloner implements SolutionCloner { @Override public NQueens cloneSolution(CloneLedger ledger, NQueens original) { NQueens clone = new NQueens(); ledger.registerClone(original, clone); clone.setId(original.getId()); clone.setN(original.getN()); clone.setColumnList(original.getColumnList()); clone.setRowList(original.getRowList()); List queenList = original.getQueenList(); List clonedQueenList = new ArrayList(queenList.size()); for (Queen originalQueen : queenList) { Queen cloneQueen = new Queen(); ledger.registerClone(originalQueen, cloneQueen); cloneQueen.setId(originalQueen.getId()); cloneQueen.setColumn(originalQueen.getColumn()); cloneQueen.setRow(originalQueen.getRow()); clonedQueenList.add(cloneQueen); } clone.setQueenList(clonedQueenList); clone.setScore(original.getScore()); return clone; } } ---- _The `cloneSolution()` method should only deep clone the planning entities._ Notice that the problem facts, such as `Column` and `Row` are normally _not_ cloned: even their `List` instances are _not_ cloned. If the problem facts were cloned too, then you would have to make sure that the new planning entity clones also refer to the new problem facts clones used by the cloned solution. For example, if you were to clone all `Row` instances, then each `Queen` clone and the `NQueens` clone itself should refer to those new `Row` clones. [WARNING] ==== Cloning an entity with a <> variable is devious: a variable of an entity A might point to another entity B. If A is cloned, then its variable must point to the clone of B, not the original B. ==== [[createAnUninitializedSolution]] ==== Create an uninitialized solution Create a `@PlanningSolution` instance to represent your planning problem's dataset, so it can be set on the `Solver` as the planning problem to solve. For example in n queens, an `NQueens` instance is created with the required `Column` and `Row` instances and every `Queen` set to a different `column` and every `row` set to ``null``. [source,java,options=""nowrap""] ---- private NQueens createNQueens(int n) { NQueens nQueens = new NQueens(); nQueens.setId(0L); nQueens.setN(n); nQueens.setColumnList(createColumnList(nQueens)); nQueens.setRowList(createRowList(nQueens)); nQueens.setQueenList(createQueenList(nQueens)); return nQueens; } private List createQueenList(NQueens nQueens) { int n = nQueens.getN(); List queenList = new ArrayList(n); long id = 0L; for (Column column : nQueens.getColumnList()) { Queen queen = new Queen(); queen.setId(id); id++; queen.setColumn(column); // Notice that we leave the PlanningVariable properties on null queenList.add(queen); } return queenList; } ---- .Uninitialized Solution for the Four Queens Puzzle image::PlannerConfiguration/uninitializedNQueens04.png[align=""left""] Usually, most of this data comes from your data layer, and your solution implementation just aggregates that data and creates the uninitialized planning entity instances to plan: [source,java,options=""nowrap""] ---- private void createLectureList(CourseSchedule schedule) { List courseList = schedule.getCourseList(); List lectureList = new ArrayList(courseList.size()); long id = 0L; for (Course course : courseList) { for (int i = 0; i < course.getLectureSize(); i++) { Lecture lecture = new Lecture(); lecture.setId(id); id++; lecture.setCourse(course); lecture.setLectureIndexInCourse(i); // Notice that we leave the PlanningVariable properties (period and room) on null lectureList.add(lecture); } } schedule.setLectureList(lectureList); } ---- [[useTheSolver]] == Use the `Solver` [[theSolverInterface]] === The `Solver` interface A `Solver` solves your planning problem. [source,java,options=""nowrap""] ---- public interface Solver { Solution_ solve(Solution_ problem); ... } ---- A `Solver` can only solve one planning problem instance at a time. It is built with a ``SolverFactory``, there is no need to implement it yourself. A `Solver` should only be accessed from a single thread, except for the methods that are specifically documented in javadoc as being thread-safe. The `solve()` method hogs the current thread. This can cause HTTP timeouts for REST services and it requires extra code to solve multiple datasets in parallel. To avoid such issues, use a <> instead. [[solvingAProblem]] === Solving a problem Solving a problem is quite easy once you have: * A `Solver` built from a solver configuration * A `@PlanningSolution` that represents the planning problem instance Just provide the planning problem as argument to the `solve()` method and it will return the best solution found: [source,java,options=""nowrap""] ---- NQueens problem = ...; NQueens bestSolution = solver.solve(problem); ---- For example in n queens, the `solve()` method will return an `NQueens` instance with every `Queen` assigned to a ``Row``. .Best Solution for the Four Queens Puzzle in 8ms (Also an Optimal Solution) image::PlannerConfiguration/solvedNQueens04.png[align=""left""] The `solve(Solution)` method can take a long time (depending on the problem size and the solver configuration). The `Solver` intelligently wades through <> of possible solutions and remembers the best solution it encounters during solving. Depending on a number of factors (including problem size, how much time the `Solver` has, the solver configuration, ...), <>. [NOTE] ==== The solution instance given to the method `solve(solution)` is changed by the ``Solver``, but do not mistake it for the best solution. The solution instance returned by the methods `solve(solution)` or `getBestSolution()` is most likely <> of the instance given to the method ``solve(solution)``, which implies it is a different instance. ==== [NOTE] ==== The solution instance given to the `solve(Solution)` method does not need to be uninitialized. It can be partially or fully initialized, which is often the case in <>. ==== [[environmentMode]] === Environment mode: are there bugs in my code? The environment mode allows you to detect common bugs in your implementation. It does not affect the <>. You can set the environment mode in the solver configuration XML file: [source,xml,options=""nowrap""] ---- FAST_ASSERT ... ---- A solver has a single `Random` instance. Some solver configurations use the `Random` instance a lot more than others. For example, Simulated Annealing depends highly on random numbers, while Tabu Search only depends on it to deal with score ties. The environment mode influences the seed of that `Random` instance. These are the environment modes: [[environmentModeFullAssert]] ==== `FULL_ASSERT` The FULL_ASSERT mode turns on all assertions (such as assert that the incremental score calculation is uncorrupted for each move) to fail-fast on a bug in a Move implementation, a constraint, the engine itself, ... This mode is reproducible (see the reproducible mode). It is also intrusive because it calls the method `calculateScore()` more frequently than a non-assert mode. The FULL_ASSERT mode is horribly slow (because it does not rely on incremental score calculation). [[environmentModeNonIntrusiveFullAssert]] ==== `NON_INTRUSIVE_FULL_ASSERT` The NON_INTRUSIVE_FULL_ASSERT turns on several assertions to fail-fast on a bug in a Move implementation, a constraint, the engine itself, ... This mode is reproducible (see the reproducible mode). It is non-intrusive because it does not call the method `calculateScore()` more frequently than a non assert mode. The NON_INTRUSIVE_FULL_ASSERT mode is horribly slow (because it does not rely on incremental score calculation). [[environmentModeFastAssert]] ==== `FAST_ASSERT` The FAST_ASSERT mode turns on most assertions (such as assert that an undoMove's score is the same as before the Move) to fail-fast on a bug in a Move implementation, a constraint, the engine itself, ... This mode is reproducible (see the reproducible mode). It is also intrusive because it calls the method `calculateScore()` more frequently than a non assert mode. The FAST_ASSERT mode is slow. It is recommended to write a test case that does a short run of your planning problem with the FAST_ASSERT mode on. [[environmentModeReproducible]] ==== `REPRODUCIBLE` (default) The reproducible mode is the default mode because it is recommended during development. In this mode, two runs in the same OptaPlanner version will execute the same code in the same order. **Those two runs will have the same result at every step**, except if the note below applies. This enables you to reproduce bugs consistently. It also allows you to benchmark certain refactorings (such as a score constraint performance optimization) fairly across runs. [NOTE] ==== Despite the reproducible mode, your application might still not be fully reproducible because of: * Use of `HashSet` (or another `Collection` which has an inconsistent order between JVM runs) for collections of planning entities or planning values (but not normal problem facts), especially in the solution implementation. Replace it with ``LinkedHashSet``. * Combining a time gradient dependent algorithms (most notably Simulated Annealing) together with time spent termination. A sufficiently large difference in allocated CPU time will influence the time gradient values. Replace Simulated Annealing with Late Acceptance. Or instead, replace time spent termination with step count termination. ==== The reproducible mode can be slightly slower than the non-reproducible mode. If your production environment can benefit from reproducibility, use this mode in production. In practice, this mode uses the default, fixed <> if no seed is specified, and it also disables certain concurrency optimizations (such as work stealing). [[environmentModeProduction]] ==== `NON_REPRODUCIBLE` The non-reproducible mode can be slightly faster than the reproducible mode. Avoid using it during development as it makes debugging and bug fixing painful. If your production environment doesn't care about reproducibility, use this mode in production. In practice, this mode uses no fixed <> if no seed is specified. [[logging]] === Logging level: what is the `Solver` doing? The best way to illuminate the black box that is a ``Solver``, is to play with the logging level: * **error**: Log errors, except those that are thrown to the calling code as a ``RuntimeException``. + [NOTE] ==== **If an error happens, OptaPlanner normally fails fast**: it throws a subclass of `RuntimeException` with a detailed message to the calling code. It does not log it as an error itself to avoid duplicate log messages. Except if the calling code explicitly catches and eats that ``RuntimeException``, a ``Thread``'s default `ExceptionHandler` will log it as an error anyway. Meanwhile, the code is disrupted from doing further harm or obfuscating the error. ==== * **warn**: Log suspicious circumstances. * **info**: Log every phase and the solver itself. See <>. * **debug**: Log every step of every phase. See <>. * **trace**: Log every move of every step of every phase. See <>. [NOTE] ==== Turning on `trace` logging, will slow down performance considerably: it is often four times slower. However, it is invaluable during development to discover a bottleneck. Even `debug` logging can slow down performance considerably for fast stepping algorithms (such as Late Acceptance and Simulated Annealing), but not for slow stepping algorithms (such as Tabu Search). Both cause congestion in <> with most appenders, see below. In Eclipse, `debug` logging to the console tends to cause congestion with a score calculation speeds above 10 000 per second. Nor IntelliJ, nor the Maven command line suffer from this problem. ==== For example, set it to `debug` logging, to see when the phases end and how fast steps are taken: [source,options=""nowrap""] ---- INFO Solving started: time spent (3), best score (-4init/0), random (JDK with seed 0). DEBUG CH step (0), time spent (5), score (-3init/0), selected move count (1), picked move (Queen-2 {null -> Row-0}). DEBUG CH step (1), time spent (7), score (-2init/0), selected move count (3), picked move (Queen-1 {null -> Row-2}). DEBUG CH step (2), time spent (10), score (-1init/0), selected move count (4), picked move (Queen-3 {null -> Row-3}). DEBUG CH step (3), time spent (12), score (-1), selected move count (4), picked move (Queen-0 {null -> Row-1}). INFO Construction Heuristic phase (0) ended: time spent (12), best score (-1), score calculation speed (9000/sec), step total (4). DEBUG LS step (0), time spent (19), score (-1), best score (-1), accepted/selected move count (12/12), picked move (Queen-1 {Row-2 -> Row-3}). DEBUG LS step (1), time spent (24), score (0), new best score (0), accepted/selected move count (9/12), picked move (Queen-3 {Row-3 -> Row-2}). INFO Local Search phase (1) ended: time spent (24), best score (0), score calculation speed (4000/sec), step total (2). INFO Solving ended: time spent (24), best score (0), score calculation speed (7000/sec), phase total (2), environment mode (REPRODUCIBLE). ---- All time spent values are in milliseconds. Everything is logged to http://www.slf4j.org/[SLF4J], which is a simple logging facade which delegates every log message to Logback, Apache Commons Logging, Log4j or java.util.logging. Add a dependency to the logging adaptor for your logging framework of choice. If you are not using any logging framework yet, use Logback by adding this Maven dependency (there is no need to add an extra bridge dependency): [source,xml,options=""nowrap""] ---- ch.qos.logback logback-classic 1.x ---- Configure the logging level on the `org.optaplanner` package in your `logback.xml` file: [source,xml,options=""nowrap""] ---- ... ---- If it isn't picked up, temporarily add the system property `-Dlogback.debug=true` to figure out why. [NOTE] ==== When running multiple solvers or one <>, most appenders (including the console) cause congestion with `debug` and `trace` logging. Switch to an async appender to avoid this problem or turn off `debug` logging. ==== If instead, you are still using Log4J 1.x (and you do not want to switch to its faster successor, Logback), add the bridge dependency: [source,xml,options=""nowrap""] ---- org.slf4j slf4j-log4j12 1.x ---- And configure the logging level on the package `org.optaplanner` in your `log4j.xml` file: [source,xml,options=""nowrap""] ---- ... ---- [NOTE] ==== In a multitenant application, multiple `Solver` instances might be running at the same time. To separate their logging into distinct files, surround the `solve()` call with an http://logback.qos.ch/manual/mdc.html[MDC]: [source,java,options=""nowrap""] ---- MDC.put(""tenant.name"",tenantName); MySolution bestSolution = solver.solve(problem); MDC.remove(""tenant.name""); ---- Then configure your logger to use different files for each ``${tenant.name}``. For example in Logback, use a `SiftingAppender` in ``logback.xml``: [source,xml,options=""nowrap""] ---- tenant.name unknown local/log/optaplanner-${tenant.name}.log ... ---- ==== [[randomNumberGenerator]] === Random number generator Many heuristics and metaheuristics depend on a pseudorandom number generator for move selection, to resolve score ties, probability based move acceptance, ... During solving, the same `Random` instance is reused to improve reproducibility, performance and uniform distribution of random values. To change the random seed of that `Random` instance, specify a ``randomSeed``: [source,xml,options=""nowrap""] ---- 0 ... ---- To change the pseudorandom number generator implementation, specify a ``randomType``: [source,xml,options=""nowrap""] ---- MERSENNE_TWISTER ... ---- The following types are supported: * `JDK` (default): Standard implementation (``java.util.Random``). * ``MERSENNE_TWISTER``: Implementation by http://commons.apache.org/proper/commons-math/userguide/random.html[Commons Math]. * ``WELL512A``, ``WELL1024A``, ``WELL19937A``, ``WELL19937C``, `WELL44497A` and ``WELL44497B``: Implementation by http://commons.apache.org/proper/commons-math/userguide/random.html[Commons Math]. For most use cases, the randomType has no significant impact on the average quality of the best solution on multiple datasets. If you want to confirm this on your use case, use the <>. [[solverManager]] == SolverManager A `SolverManager` is a facade for one or more `Solver` instances to simplify solving planning problems in REST and other enterprise services. Unlike the `Solver.solve(...)` method: * *`SolverManager.solve(...)` returns immediately*: it schedules a problem for asynchronous solving without blocking the calling thread. This avoids timeout issues of HTTP and other technologies. * *`SolverManager.solve(...)` solves multiple planning problems* of the same domain, in parallel. Internally a `SolverManager` manages a thread pool of solver threads, which call `Solver.solve(...)`, and a thread pool of consumer threads, which handle best solution changed events. In <> and <>, the `SolverManager` instance is automatically injected in your code. Otherwise, build a `SolverManager` instance with the `create(...)` method: [source,java,options=""nowrap""] ---- SolverConfig solverConfig = SolverConfig.createFromXmlResource("".../cloudBalancingSolverConfig.xml""); SolverManager solverManager = SolverManager.create(solverConfig, new SolverManagerConfig()); ---- Each problem submitted to the `SolverManager.solve(...)` methods needs a unique problem ID. Later calls to `getSolverStatus(problemId)` or `terminateEarly(problemId)` use that problem ID to distinguish between the planning problems. The problem ID must be an immutable class, such as `Long`, `String` or `java.util.UUID`. The `SolverManagerConfig` class has a `parallelSolverCount` property, that controls how many solvers are run in parallel. For example, if set to `4`, submitting five problems has four problems solving immediately, and the fifth one starts when another one ends. If those problems solve for 5 minutes each, the fifth problem takes 10 minutes to finish. By default, `parallelSolverCount` is set to `AUTO`, which resolves to half the CPU cores, regardless of the <> of the solvers. To retrieve the best solution, after solving terminates normally, use `SolverJob.getFinalBestSolution()`: [source,java,options=""nowrap""] ---- CloudBalance problem1 = ...; UUID problemId = UUID.randomUUID(); // Returns immediately SolverJob solverJob = solverManager.solve(problemId, problem1); ... CloudBalance solution1; try { // Returns only after solving terminates solution1 = solverJob.getFinalBestSolution(); } catch (InterruptedException | ExecutionException e) { throw ...; } ---- However, there are better approaches, both for solving batch problems before an end-user needs the solution as well as for live solving while an end-user is actively waiting for the solution, as explained below. The current `SolverManager` implementation runs on a single computer node, but future work aims to distribute solver loads across a cloud. [[solverManagerSolveBatch]] === Solve batch problems At night, batch solving is a great approach to deliver solid plans by breakfast, because: * There are typically few or no problem changes in the middle of the night. Some organizations even enforce a deadline, for example, _submit all day off requests before midnight_. * The solvers can run for much longer, often hours, because nobody's waiting for it and CPU resources are often cheaper. To solve a multiple datasets in parallel (limited by `parallelSolverCount`), call `solve(...)` for each dataset: [source,java,options=""nowrap""] ---- public class TimeTableService { private SolverManager solverManager; // Returns immediately, call it for every dataset public void solveBatch(Long timeTableId) { solverManager.solve(timeTableId, // Called once, when solving starts this::findById, // Called once, when solving ends this::save); } public TimeTable findById(Long timeTableId) {...} public void save(TimeTable timeTable) {...} } ---- A solid plan delivered by breakfast is great, even if you need to react on problem changes during the day. [[solverManagerSolveAndListen]] === Solve and listen to show progress to the end-user When a solver is running while an end-user is waiting for that solution, the user might need to wait for several minutes or hours before receiving a result. To assure the user that everything is going well, show progress by displaying the best solution and best score attained so far. To handle intermediate best solutions, use `solveAndListen(...)`: [source,java,options=""nowrap""] ---- public class TimeTableService { private SolverManager solverManager; // Returns immediately public void solveLive(Long timeTableId) { solverManager.solveAndListen(timeTableId, // Called once, when solving starts this::findById, // Called multiple times, for every best solution change this::save); } public TimeTable findById(Long timeTableId) {...} public void save(TimeTable timeTable) {...} public void stopSolving(Long timeTableId) { solverManager.terminateEarly(timeTableId); } } ---- This implementation is using the database to communicate with the UI, which polls the database. More advanced implementations push the best solutions directly to the UI or a messaging queue. If the user is satisfied with the intermediate best solution and does not want to wait any longer for a better one, call `SolverManager.terminateEarly(problemId)`. ",16328,True,2821.7032569756598,median "------------------------------------------------------------------------------ -- -- -- GNAT LIBRARY COMPONENTS -- -- -- -- G N A T . S P I T B O L . P A T T E R N S -- -- -- -- S p e c -- -- -- -- Copyright (C) 1997-2005, AdaCore -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT 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 distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, -- -- Boston, MA 02110-1301, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- SPITBOL-like pattern construction and matching -- This child package of GNAT.SPITBOL provides a complete implementation -- of the SPITBOL-like pattern construction and matching operations. This -- package is based on Macro-SPITBOL created by Robert Dewar. ------------------------------------------------------------ -- Summary of Pattern Matching Packages in GNAT Hierarchy -- ------------------------------------------------------------ -- There are three related packages that perform pattern maching functions. -- the following is an outline of these packages, to help you determine -- which is best for your needs. -- GNAT.Regexp (files g-regexp.ads/g-regexp.adb) -- This is a simple package providing Unix-style regular expression -- matching with the restriction that it matches entire strings. It -- is particularly useful for file name matching, and in particular -- it provides ""globbing patterns"" that are useful in implementing -- unix or DOS style wild card matching for file names. -- GNAT.Regpat (files g-regpat.ads/g-regpat.adb) -- This is a more complete implementation of Unix-style regular -- expressions, copied from the original V7 style regular expression -- library written in C by Henry Spencer. It is functionally the -- same as this library, and uses the same internal data structures -- stored in a binary compatible manner. -- GNAT.Spitbol.Patterns (files g-spipat.ads/g-spipat.adb) -- This is a completely general patterm matching package based on the -- pattern language of SNOBOL4, as implemented in SPITBOL. The pattern -- language is modeled on context free grammars, with context sensitive -- extensions that provide full (type 0) computational capabilities. with Ada.Strings.Maps; use Ada.Strings.Maps; with Ada.Text_IO; use Ada.Text_IO; package GNAT.Spitbol.Patterns is pragma Elaborate_Body; ------------------------------- -- Pattern Matching Tutorial -- ------------------------------- -- A pattern matching operation (a call to one of the Match subprograms) -- takes a subject string and a pattern, and optionally a replacement -- string. The replacement string option is only allowed if the subject -- is a variable. -- The pattern is matched against the subject string, and either the -- match fails, or it succeeds matching a contiguous substring. If a -- replacement string is specified, then the subject string is modified -- by replacing the matched substring with the given replacement. -- Concatenation and Alternation -- ============================= -- A pattern consists of a series of pattern elements. The pattern is -- built up using either the concatenation operator: -- A & B -- which means match A followed immediately by matching B, or the -- alternation operator: -- A or B -- which means first attempt to match A, and then if that does not -- succeed, match B. -- There is full backtracking, which means that if a given pattern -- element fails to match, then previous alternatives are matched. -- For example if we have the pattern: -- (A or B) & (C or D) & (E or F) -- First we attempt to match A, if that succeeds, then we go on to try -- to match C, and if that succeeds, we go on to try to match E. If E -- fails, then we try F. If F fails, then we go back and try matching -- D instead of C. Let's make this explicit using a specific example, -- and introducing the simplest kind of pattern element, which is a -- literal string. The meaning of this pattern element is simply to -- match the characters that correspond to the string characters. Now -- let's rewrite the above pattern form with specific string literals -- as the pattern elements: -- (""ABC"" or ""AB"") & (""DEF"" or ""CDE"") & (""GH"" or ""IJ"") -- The following strings will be attempted in sequence: -- ABC . DEF . GH -- ABC . DEF . IJ -- ABC . CDE . GH -- ABC . CDE . IJ -- AB . DEF . GH -- AB . DEF . IJ -- AB . CDE . GH -- AB . CDE . IJ -- Here we use the dot simply to separate the pieces of the string -- matched by the three separate elements. -- Moving the Start Point -- ====================== -- A pattern is not required to match starting at the first character -- of the string, and is not required to match to the end of the string. -- The first attempt does indeed attempt to match starting at the first -- character of the string, trying all the possible alternatives. But -- if all alternatives fail, then the starting point of the match is -- moved one character, and all possible alternatives are attempted at -- the new anchor point. -- The entire match fails only when every possible starting point has -- been attempted. As an example, suppose that we had the subject -- string -- ""ABABCDEIJKL"" -- matched using the pattern in the previous example: -- (""ABC"" or ""AB"") & (""DEF"" or ""CDE"") & (""GH"" or ""IJ"") -- would succeed, afer two anchor point moves: -- ""ABABCDEIJKL"" -- ^^^^^^^ -- matched -- section -- This mode of pattern matching is called the unanchored mode. It is -- also possible to put the pattern matcher into anchored mode by -- setting the global variable Anchored_Mode to True. This will cause -- all subsequent matches to be performed in anchored mode, where the -- match is required to start at the first character. -- We will also see later how the effect of an anchored match can be -- obtained for a single specified anchor point if this is desired. -- Other Pattern Elements -- ====================== -- In addition to strings (or single characters), there are many special -- pattern elements that correspond to special predefined alternations: -- Arb Matches any string. First it matches the null string, and -- then on a subsequent failure, matches one character, and -- then two characters, and so on. It only fails if the -- entire remaining string is matched. -- Bal Matches a non-empty string that is parentheses balanced -- with respect to ordinary () characters. Examples of -- balanced strings are ""ABC"", ""A((B)C)"", and ""A(B)C(D)E"". -- Bal matches the shortest possible balanced string on the -- first attempt, and if there is a subsequent failure, -- attempts to extend the string. -- Cancel Immediately aborts the entire pattern match, signalling -- failure. This is a specialized pattern element, which is -- useful in conjunction with some of the special pattern -- elements that have side effects. -- Fail The null alternation. Matches no possible strings, so it -- always signals failure. This is a specialized pattern -- element, which is useful in conjunction with some of the -- special pattern elements that have side effects. -- Fence Matches the null string at first, and then if a failure -- causes alternatives to be sought, aborts the match (like -- a Cancel). Note that using Fence at the start of a pattern -- has the same effect as matching in anchored mode. -- Rest Matches from the current point to the last character in -- the string. This is a specialized pattern element, which -- is useful in conjunction with some of the special pattern -- elements that have side effects. -- Succeed Repeatedly matches the null string (it is equivalent to -- the alternation ("""" or """" or """" ....). This is a special -- pattern element, which is useful in conjunction with some -- of the special pattern elements that have side effects. -- Pattern Construction Functions -- ============================== -- The following functions construct additional pattern elements -- Any(S) Where S is a string, matches a single character that is -- any one of the characters in S. Fails if the current -- character is not one of the given set of characters. -- Arbno(P) Where P is any pattern, matches any number of instances -- of the pattern, starting with zero occurrences. It is -- thus equivalent to ("""" or (P & ("""" or (P & ("""" ....)))). -- The pattern P may contain any number of pattern elements -- including the use of alternatiion and concatenation. -- Break(S) Where S is a string, matches a string of zero or more -- characters up to but not including a break character -- that is one of the characters given in the string S. -- Can match the null string, but cannot match the last -- character in the string, since a break character is -- required to be present. -- BreakX(S) Where S is a string, behaves exactly like Break(S) when -- it first matches, but if a string is successfully matched, -- then a susequent failure causes an attempt to extend the -- matched string. -- Fence(P) Where P is a pattern, attempts to match the pattern P -- including trying all possible alternatives of P. If none -- of these alternatives succeeds, then the Fence pattern -- fails. If one alternative succeeds, then the pattern -- match proceeds, but on a subsequent failure, no attempt -- is made to search for alternative matches of P. The -- pattern P may contain any number of pattern elements -- including the use of alternatiion and concatenation. -- Len(N) Where N is a natural number, matches the given number of -- characters. For example, Len(10) matches any string that -- is exactly ten characters long. -- NotAny(S) Where S is a string, matches a single character that is -- not one of the characters of S. Fails if the current -- characer is one of the given set of characters. -- NSpan(S) Where S is a string, matches a string of zero or more -- characters that is among the characters given in the -- string. Always matches the longest possible such string. -- Always succeeds, since it can match the null string. -- Pos(N) Where N is a natural number, matches the null string -- if exactly N characters have been matched so far, and -- otherwise fails. -- Rpos(N) Where N is a natural number, matches the null string -- if exactly N characters remain to be matched, and -- otherwise fails. -- Rtab(N) Where N is a natural number, matches characters from -- the current position until exactly N characters remain -- to be matched in the string. Fails if fewer than N -- unmatched characters remain in the string. -- Tab(N) Where N is a natural number, matches characters from -- the current position until exactly N characters have -- been matched in all. Fails if more than N characters -- have already been matched. -- Span(S) Where S is a string, matches a string of one or more -- characters that is among the characters given in the -- string. Always matches the longest possible such string. -- Fails if the current character is not one of the given -- set of characters. -- Recursive Pattern Matching -- ========================== -- The plus operator (+P) where P is a pattern variable, creates -- a recursive pattern that will, at pattern matching time, follow -- the pointer to obtain the referenced pattern, and then match this -- pattern. This may be used to construct recursive patterns. Consider -- for example: -- P := (""A"" or (""B"" & (+P))) -- On the first attempt, this pattern attempts to match the string ""A"". -- If this fails, then the alternative matches a ""B"", followed by an -- attempt to match P again. This second attempt first attempts to -- match ""A"", and so on. The result is a pattern that will match a -- string of B's followed by a single A. -- This particular example could simply be written as NSpan('B') & 'A', -- but the use of recursive patterns in the general case can construct -- complex patterns which could not otherwise be built. -- Pattern Assignment Operations -- ============================= -- In addition to the overall result of a pattern match, which indicates -- success or failure, it is often useful to be able to keep track of -- the pieces of the subject string that are matched by individual -- pattern elements, or subsections of the pattern. -- The pattern assignment operators allow this capability. The first -- form is the immediate assignment: -- P * S -- Here P is an arbitrary pattern, and S is a variable of type VString -- that will be set to the substring matched by P. This assignment -- happens during pattern matching, so if P matches more than once, -- then the assignment happens more than once. -- The deferred assignment operation: -- P ** S -- avoids these multiple assignments by deferring the assignment to the -- end of the match. If the entire match is successful, and if the -- pattern P was part of the successful match, then at the end of the -- matching operation the assignment to S of the string matching P is -- performed. -- The cursor assignment operation: -- Setcur(N'Access) -- assigns the current cursor position to the natural variable N. The -- cursor position is defined as the count of characters that have been -- matched so far (including any start point moves). -- Finally the operations * and ** may be used with values of type -- Text_IO.File_Access. The effect is to do a Put_Line operation of -- the matched substring. These are particularly useful in debugging -- pattern matches. -- Deferred Matching -- ================= -- The pattern construction functions (such as Len and Any) all permit -- the use of pointers to natural or string values, or functions that -- return natural or string values. These forms cause the actual value -- to be obtained at pattern matching time. This allows interesting -- possibilities for constructing dynamic patterns as illustrated in -- the examples section. -- In addition the (+S) operator may be used where S is a pointer to -- string or function returning string, with a similar deferred effect. -- A special use of deferred matching is the construction of predicate -- functions. The element (+P) where P is an access to a function that -- returns a Boolean value, causes the function to be called at the -- time the element is matched. If the function returns True, then the -- null string is matched, if the function returns False, then failure -- is signalled and previous alternatives are sought. -- Deferred Replacement -- ==================== -- The simple model given for pattern replacement (where the matched -- substring is replaced by the string given as the third argument to -- Match) works fine in simple cases, but this approach does not work -- in the case where the expression used as the replacement string is -- dependent on values set by the match. -- For example, suppose we want to find an instance of a parenthesized -- character, and replace the parentheses with square brackets. At first -- glance it would seem that: -- Match (Subject, '(' & Len (1) * Char & ')', '[' & Char & ']'); -- would do the trick, but that does not work, because the third -- argument to Match gets evaluated too early, before the call to -- Match, and before the pattern match has had a chance to set Char. -- To solve this problem we provide the deferred replacement capability. -- With this approach, which of course is only needed if the pattern -- involved has side effects, is to do the match in two stages. The -- call to Match sets a pattern result in a variable of the private -- type Match_Result, and then a subsequent Replace operation uses -- this Match_Result object to perform the required replacement. -- Using this approach, we can now write the above operation properly -- in a manner that will work: -- M : Match_Result; -- ... -- Match (Subject, '(' & Len (1) * Char & ')', M); -- Replace (M, '[' & Char & ']'); -- As with other Match cases, there is a function and procedure form -- of this match call. A call to Replace after a failed match has no -- effect. Note that Subject should not be modified between the calls. -- Examples of Pattern Matching -- ============================ -- First a simple example of the use of pattern replacement to remove -- a line number from the start of a string. We assume that the line -- number has the form of a string of decimal digits followed by a -- period, followed by one or more spaces. -- Digs : constant Pattern := Span(""0123456789""); -- Lnum : constant Pattern := Pos(0) & Digs & '.' & Span(' '); -- Now to use this pattern we simply do a match with a replacement: -- Match (Line, Lnum, """"); -- which replaces the line number by the null string. Note that it is -- also possible to use an Ada.Strings.Maps.Character_Set value as an -- argument to Span and similar functions, and in particular all the -- useful constants 'in Ada.Strings.Maps.Constants are available. This -- means that we could define Digs as: -- Digs : constant Pattern := Span(Decimal_Digit_Set); -- The style we use here, of defining constant patterns and then using -- them is typical. It is possible to build up patterns dynamically, -- but it is usually more efficient to build them in pieces in advance -- using constant declarations. Note in particular that although it is -- possible to construct a pattern directly as an argument for the -- Match routine, it is much more efficient to preconstruct the pattern -- as we did in this example. -- Now let's look at the use of pattern assignment to break a -- string into sections. Suppose that the input string has two -- unsigned decimal integers, separated by spaces or a comma, -- with spaces allowed anywhere. Then we can isolate the two -- numbers with the following pattern: -- Num1, Num2 : aliased VString; -- B : constant Pattern := NSpan(' '); -- N : constant Pattern := Span(""0123456789""); -- T : constant Pattern := -- NSpan(' ') & N * Num1 & Span("" ,"") & N * Num2; -- The match operation Match ("" 124, 257 "", T) would assign the -- string 124 to Num1 and the string 257 to Num2. -- Now let's see how more complex elements can be built from the -- set of primitive elements. The following pattern matches strings -- that have the syntax of Ada 95 based literals: -- Digs : constant Pattern := Span(Decimal_Digit_Set); -- UDigs : constant Pattern := Digs & Arbno('_' & Digs); -- Edig : constant Pattern := Span(Hexadecimal_Digit_Set); -- UEdig : constant Pattern := Edig & Arbno('_' & Edig); -- Bnum : constant Pattern := Udigs & '#' & UEdig & '#'; -- A match against Bnum will now match the desired strings, e.g. -- it will match 16#123_abc#, but not a#b#. However, this pattern -- is not quite complete, since it does not allow colons to replace -- the pound signs. The following is more complete: -- Bchar : constant Pattern := Any(""#:""); -- Bnum : constant Pattern := Udigs & Bchar & UEdig & Bchar; -- but that is still not quite right, since it allows # and : to be -- mixed, and they are supposed to be used consistently. We solve -- this by using a deferred match. -- Temp : aliased VString; -- Bnum : constant Pattern := -- Udigs & Bchar * Temp & UEdig & (+Temp) -- Here the first instance of the base character is stored in Temp, and -- then later in the pattern we rematch the value that was assigned. -- For an example of a recursive pattern, let's define a pattern -- that is like the built in Bal, but the string matched is balanced -- with respect to square brackets or curly brackets. -- The language for such strings might be defined in extended BNF as -- ELEMENT ::= -- | '[' BALANCED_STRING ']' -- | '{' BALANCED_STRING '}' -- BALANCED_STRING ::= ELEMENT {ELEMENT} -- Here we use {} to indicate zero or more occurrences of a term, as -- is common practice in extended BNF. Now we can translate the above -- BNF into recursive patterns as follows: -- Element, Balanced_String : aliased Pattern; -- . -- . -- . -- Element := NotAny (""[]{}"") -- or -- ('[' & (+Balanced_String) & ']') -- or -- ('{' & (+Balanced_String) & '}'); -- Balanced_String := Element & Arbno (Element); -- Note the important use of + here to refer to a pattern not yet -- defined. Note also that we use assignments precisely because we -- cannot refer to as yet undeclared variables in initializations. -- Now that this pattern is constructed, we can use it as though it -- were a new primitive pattern element, and for example, the match: -- Match (""xy[ab{cd}]"", Balanced_String * Current_Output & Fail); -- will generate the output: -- x -- xy -- xy[ab{cd}] -- y -- y[ab{cd}] -- [ab{cd}] -- a -- ab -- ab{cd} -- b -- b{cd} -- {cd} -- c -- cd -- d -- Note that the function of the fail here is simply to force the -- pattern Balanced_String to match all possible alternatives. Studying -- the operation of this pattern in detail is highly instructive. -- Finally we give a rather elaborate example of the use of deferred -- matching. The following declarations build up a pattern which will -- find the longest string of decimal digits in the subject string. -- Max, Cur : VString; -- Loc : Natural; -- function GtS return Boolean is -- begin -- return Length (Cur) > Length (Max); -- end GtS; -- Digit : constant Character_Set := Decimal_Digit_Set; -- Digs : constant Pattern := Span(Digit); -- Find : constant Pattern := -- """" * Max & Fence & -- initialize Max to null -- BreakX (Digit) & -- scan looking for digits -- ((Span(Digit) * Cur & -- assign next string to Cur -- (+GtS'Unrestricted_Access) & -- check size(Cur) > Size(Max) -- Setcur(Loc'Access)) -- if so, save location -- * Max) & -- and assign to Max -- Fail; -- seek all alternatives -- As we see from the comments here, complex patterns like this take -- on aspects of sequential programs. In fact they are sequential -- programs with general backtracking. In this pattern, we first use -- a pattern assignment that matches null and assigns it to Max, so -- that it is initialized for the new match. Now BreakX scans to the -- next digit. Arb would do here, but BreakX will be more efficient. -- Once we have found a digit, we scan out the longest string of -- digits with Span, and assign it to Cur. The deferred call to GtS -- tests if the string we assigned to Cur is the longest so far. If -- not, then failure is signalled, and we seek alternatives (this -- means that BreakX will extend and look for the next digit string). -- If the call to GtS succeeds then the matched string is assigned -- as the largest string so far into Max and its location is saved -- in Loc. Finally Fail forces the match to fail and seek alternatives, -- so that the entire string is searched. -- If the pattern Find is matched against a string, the variable Max -- at the end of the pattern will have the longest string of digits, -- and Loc will be the starting character location of the string. For -- example, Match(""ab123cd4657ef23"", Find) will assign ""4657"" to Max -- and 11 to Loc (indicating that the string ends with the eleventh -- character of the string). -- Note: the use of Unrestricted_Access to reference GtS will not -- be needed if GtS is defined at the outer level, but definitely -- will be necessary if GtS is a nested function (in which case of -- course the scope of the pattern Find will be restricted to this -- nested scope, and this cannot be checked, i.e. use of the pattern -- outside this scope is erroneous). Generally it is a good idea to -- define patterns and the functions they call at the outer level -- where possible, to avoid such problems. -- Correspondence with Pattern Matching in SPITBOL -- =============================================== -- Generally the Ada syntax and names correspond closely to SPITBOL -- syntax for pattern matching construction. -- The basic pattern construction operators are renamed as follows: -- Spitbol Ada -- (space) & -- | or -- $ * -- . ** -- The Ada operators were chosen so that the relative precedences of -- these operators corresponds to that of the Spitbol operators, but -- as always, the use of parentheses is advisable to clarify. -- The pattern construction operators all have similar names except for -- Spitbol Ada -- Abort Cancel -- Rem Rest -- where we have clashes with Ada reserved names -- Ada requires the use of 'Access to refer to functions used in the -- pattern match, and often the use of 'Unrestricted_Access may be -- necessary to get around the scope restrictions if the functions -- are not declared at the outer level. -- The actual pattern matching syntax is modified in Ada as follows: -- Spitbol Ada -- X Y Match (X, Y); -- X Y = Z Match (X, Y, Z); -- and pattern failure is indicated by returning a Boolean result from -- the Match function (True for success, False for failure). ----------------------- -- Type Declarations -- ----------------------- type Pattern is private; -- Type representing a pattern. This package provides a complete set of -- operations for constructing patterns that can be used in the pattern -- matching operations provided. type Boolean_Func is access function return Boolean; -- General Boolean function type. When this type is used as a formal -- parameter type in this package, it indicates a deferred predicate -- pattern. The function will be called when the pattern element is -- matched and failure signalled if False is returned. type Natural_Func is access function return Natural; -- General Natural function type. When this type is used as a formal -- parameter type in this package, it indicates a deferred pattern. -- The function will be called when the pattern element is matched -- to obtain the currently referenced Natural value. type VString_Func is access function return VString; -- General VString function type. When this type is used as a formal -- parameter type in this package, it indicates a deferred pattern. -- The function will be called when the pattern element is matched -- to obtain the currently referenced string value. subtype PString is String; -- This subtype is used in the remainder of the package to indicate a -- formal parameter that is converted to its corresponding pattern, -- i.e. a pattern that matches the characters of the string. subtype PChar is Character; -- Similarly, this subtype is used in the remainder of the package to -- indicate a formal parameter that is converted to its corresponding -- pattern, i.e. a pattern that matches this one character. subtype VString_Var is VString; subtype Pattern_Var is Pattern; -- These synonyms are used as formal parameter types to a function where, -- if the language allowed, we would use in out parameters, but we are -- not allowed to have in out parameters for functions. Instead we pass -- actuals which must be variables, and with a bit of trickery in the -- body, manage to interprete them properly as though they were indeed -- in out parameters. -------------------------------- -- Basic Pattern Construction -- -------------------------------- function ""&"" (L : Pattern; R : Pattern) return Pattern; function ""&"" (L : PString; R : Pattern) return Pattern; function ""&"" (L : Pattern; R : PString) return Pattern; function ""&"" (L : PChar; R : Pattern) return Pattern; function ""&"" (L : Pattern; R : PChar) return Pattern; -- Pattern concatenation. Matches L followed by R function ""or"" (L : Pattern; R : Pattern) return Pattern; function ""or"" (L : PString; R : Pattern) return Pattern; function ""or"" (L : Pattern; R : PString) return Pattern; function ""or"" (L : PString; R : PString) return Pattern; function ""or"" (L : PChar; R : Pattern) return Pattern; function ""or"" (L : Pattern; R : PChar) return Pattern; function ""or"" (L : PChar; R : PChar) return Pattern; function ""or"" (L : PString; R : PChar) return Pattern; function ""or"" (L : PChar; R : PString) return Pattern; -- Pattern alternation. Creates a pattern that will first try to match -- L and then on a subsequent failure, attempts to match R instead. ---------------------------------- -- Pattern Assignment Functions -- ---------------------------------- function ""*"" (P : Pattern; Var : VString_Var) return Pattern; function ""*"" (P : PString; Var : VString_Var) return Pattern; function ""*"" (P : PChar; Var : VString_Var) return Pattern; -- Matches P, and if the match succeeds, assigns the matched substring -- to the given VString variable S. This assignment happens as soon as -- the substring is matched, and if the pattern P1 is matched more than -- once during the course of the match, then the assignment will occur -- more than once. function ""**"" (P : Pattern; Var : VString_Var) return Pattern; function ""**"" (P : PString; Var : VString_Var) return Pattern; function ""**"" (P : PChar; Var : VString_Var) return Pattern; -- Like ""*"" above, except that the assignment happens at most once -- after the entire match is completed successfully. If the match -- fails, then no assignment takes place. ---------------------------------- -- Deferred Matching Operations -- ---------------------------------- function ""+"" (Str : VString_Var) return Pattern; -- Here Str must be a VString variable. This function constructs a -- pattern which at pattern matching time will access the current -- value of this variable, and match against these characters. function ""+"" (Str : VString_Func) return Pattern; -- Constructs a pattern which at pattern matching time calls the given -- function, and then matches against the string or character value -- that is returned by the call. function ""+"" (P : Pattern_Var) return Pattern; -- Here P must be a Pattern variable. This function constructs a -- pattern which at pattern matching time will access the current -- value of this variable, and match against the pattern value. function ""+"" (P : Boolean_Func) return Pattern; -- Constructs a predicate pattern function that at pattern matching time -- calls the given function. If True is returned, then the pattern matches. -- If False is returned, then failure is signalled. -------------------------------- -- Pattern Building Functions -- -------------------------------- function Arb return Pattern; -- Constructs a pattern that will match any string. On the first attempt, -- the pattern matches a null string, then on each successive failure, it -- matches one more character, and only fails if matching the entire rest -- of the string. function Arbno (P : Pattern) return Pattern; function Arbno (P : PString) return Pattern; function Arbno (P : PChar) return Pattern; -- Pattern repetition. First matches null, then on a subsequent failure -- attempts to match an additional instance of the given pattern. -- Equivalent to (but more efficient than) P & ("""" or (P & ("""" or ... function Any (Str : String) return Pattern; function Any (Str : VString) return Pattern; function Any (Str : Character) return Pattern; function Any (Str : Character_Set) return Pattern; function Any (Str : access VString) return Pattern; function Any (Str : VString_Func) return Pattern; -- Constructs a pattern that matches a single character that is one of -- the characters in the given argument. The pattern fails if the current -- character is not in Str. function Bal return Pattern; -- Constructs a pattern that will match any non-empty string that is -- parentheses balanced with respect to the normal parentheses characters. -- Attempts to extend the string if a subsequent failure occurs. function Break (Str : String) return Pattern; function Break (Str : VString) return Pattern; function Break (Str : Character) return Pattern; function Break (Str : Character_Set) return Pattern; function Break (Str : access VString) return Pattern; function Break (Str : VString_Func) return Pattern; -- Constructs a pattern that matches a (possibly null) string which -- is immediately followed by a character in the given argument. This -- character is not part of the matched string. The pattern fails if -- the remaining characters to be matched do not include any of the -- characters in Str. function BreakX (Str : String) return Pattern; function BreakX (Str : VString) return Pattern; function BreakX (Str : Character) return Pattern; function BreakX (Str : Character_Set) return Pattern; function BreakX (Str : access VString) return Pattern; function BreakX (Str : VString_Func) return Pattern; -- Like Break, but the pattern attempts to extend on a failure to find -- the next occurrence of a character in Str, and only fails when the -- last such instance causes a failure. function Cancel return Pattern; -- Constructs a pattern that immediately aborts the entire match function Fail return Pattern; -- Constructs a pattern that always fails function Fence return Pattern; -- Constructs a pattern that matches null on the first attempt, and then -- causes the entire match to be aborted if a subsequent failure occurs. function Fence (P : Pattern) return Pattern; -- Constructs a pattern that first matches P. if P fails, then the -- constructed pattern fails. If P succeeds, then the match proceeds, -- but if subsequent failure occurs, alternatives in P are not sought. -- The idea of Fence is that each time the pattern is matched, just -- one attempt is made to match P, without trying alternatives. function Len (Count : Natural) return Pattern; function Len (Count : access Natural) return Pattern; function Len (Count : Natural_Func) return Pattern; -- Constructs a pattern that matches exactly the given number of -- characters. The pattern fails if fewer than this number of characters -- remain to be matched in the string. function NotAny (Str : String) return Pattern; function NotAny (Str : VString) return Pattern; function NotAny (Str : Character) return Pattern; function NotAny (Str : Character_Set) return Pattern; function NotAny (Str : access VString) return Pattern; function NotAny (Str : VString_Func) return Pattern; -- Constructs a pattern that matches a single character that is not -- one of the characters in the given argument. The pattern Fails if -- the current character is in Str. function NSpan (Str : String) return Pattern; function NSpan (Str : VString) return Pattern; function NSpan (Str : Character) return Pattern; function NSpan (Str : Character_Set) return Pattern; function NSpan (Str : access VString) return Pattern; function NSpan (Str : VString_Func) return Pattern; -- Constructs a pattern that matches the longest possible string -- consisting entirely of characters from the given argument. The -- string may be empty, so this pattern always succeeds. function Pos (Count : Natural) return Pattern; function Pos (Count : access Natural) return Pattern; function Pos (Count : Natural_Func) return Pattern; -- Constructs a pattern that matches the null string if exactly Count -- characters have already been matched, and otherwise fails. function Rest return Pattern; -- Constructs a pattern that always succeeds, matching the remaining -- unmatched characters in the pattern. function Rpos (Count : Natural) return Pattern; function Rpos (Count : access Natural) return Pattern; function Rpos (Count : Natural_Func) return Pattern; -- Constructs a pattern that matches the null string if exactly Count -- characters remain to be matched in the string, and otherwise fails. function Rtab (Count : Natural) return Pattern; function Rtab (Count : access Natural) return Pattern; function Rtab (Count : Natural_Func) return Pattern; -- Constructs a pattern that matches from the current location until -- exactly Count characters remain to be matched in the string. The -- pattern fails if fewer than Count characters remain to be matched. function Setcur (Var : access Natural) return Pattern; -- Constructs a pattern that matches the null string, and assigns the -- current cursor position in the string. This value is the number of -- characters matched so far. So it is zero at the start of the match. function Span (Str : String) return Pattern; function Span (Str : VString) return Pattern; function Span (Str : Character) return Pattern; function Span (Str : Character_Set) return Pattern; function Span (Str : access VString) return Pattern; function Span (Str : VString_Func) return Pattern; -- Constructs a pattern that matches the longest possible string -- consisting entirely of characters from the given argument. The -- string cannot be empty , so the pattern fails if the current -- character is not one of the characters in Str. function Succeed return Pattern; -- Constructs a pattern that succeeds matching null, both on the first -- attempt, and on any rematch attempt, i.e. it is equivalent to an -- infinite alternation of null strings. function Tab (Count : Natural) return Pattern; function Tab (Count : access Natural) return Pattern; function Tab (Count : Natural_Func) return Pattern; -- Constructs a pattern that from the current location until Count -- characters have been matched. The pattern fails if more than Count -- characters have already been matched. --------------------------------- -- Pattern Matching Operations -- --------------------------------- -- The Match function performs an actual pattern matching operation. -- The versions with three parameters perform a match without modifying -- the subject string and return a Boolean result indicating if the -- match is successful or not. The Anchor parameter is set to True to -- obtain an anchored match in which the pattern is required to match -- the first character of the string. In an unanchored match, which is -- the default, successive attempts are made to match the given pattern -- at each character of the subject string until a match succeeds, or -- until all possibilities have failed. -- Note that pattern assignment functions in the pattern may generate -- side effects, so these functions are not necessarily pure. Anchored_Mode : Boolean := False; -- This global variable can be set True to cause all subsequent pattern -- matches to operate in anchored mode. In anchored mode, no attempt is -- made to move the anchor point, so that if the match succeeds it must -- succeed starting at the first character. Note that the effect of -- anchored mode may be achieved in individual pattern matches by using -- Fence or Pos(0) at the start of the pattern. Pattern_Stack_Overflow : exception; -- Exception raised if internal pattern matching stack overflows. This -- is typically the result of runaway pattern recursion. If there is a -- genuine case of stack overflow, then either the match must be broken -- down into simpler steps, or the stack limit must be reset. Stack_Size : constant Positive := 2000; -- Size used for internal pattern matching stack. Increase this size if -- complex patterns cause Pattern_Stack_Overflow to be raised. -- Simple match functions. The subject is matched against the pattern. -- Any immediate or deferred assignments or writes are executed, and -- the returned value indicates whether or not the match succeeded. function Match (Subject : VString; Pat : Pattern) return Boolean; function Match (Subject : VString; Pat : PString) return Boolean; function Match (Subject : String; Pat : Pattern) return Boolean; function Match (Subject : String; Pat : PString) return Boolean; -- Replacement functions. The subject is matched against the pattern. -- Any immediate or deferred assignments or writes are executed, and -- the returned value indicates whether or not the match succeeded. -- If the match succeeds, then the matched part of the subject string -- is replaced by the given Replace string. function Match (Subject : VString_Var; Pat : Pattern; Replace : VString) return Boolean; function Match (Subject : VString_Var; Pat : PString; Replace : VString) return Boolean; function Match (Subject : VString_Var; Pat : Pattern; Replace : String) return Boolean; function Match (Subject : VString_Var; Pat : PString; Replace : String) return Boolean; -- Simple match procedures. The subject is matched against the pattern. -- Any immediate or deferred assignments or writes are executed. No -- indication of success or failure is returned. procedure Match (Subject : VString; Pat : Pattern); procedure Match (Subject : VString; Pat : PString); procedure Match (Subject : String; Pat : Pattern); procedure Match (Subject : String; Pat : PString); -- Replacement procedures. The subject is matched against the pattern. -- Any immediate or deferred assignments or writes are executed. No -- indication of success or failure is returned. If the match succeeds, -- then the matched part of the subject string is replaced by the given -- Replace string. procedure Match (Subject : in out VString; Pat : Pattern; Replace : VString); procedure Match (Subject : in out VString; Pat : PString; Replace : VString); procedure Match (Subject : in out VString; Pat : Pattern; Replace : String); procedure Match (Subject : in out VString; Pat : PString; Replace : String); -- Deferred Replacement type Match_Result is private; -- Type used to record result of pattern match subtype Match_Result_Var is Match_Result; -- This synonyms is used as a formal parameter type to a function where, -- if the language allowed, we would use an in out parameter, but we are -- not allowed to have in out parameters for functions. Instead we pass -- actuals which must be variables, and with a bit of trickery in the -- body, manage to interprete them properly as though they were indeed -- in out parameters. function Match (Subject : VString_Var; Pat : Pattern; Result : Match_Result_Var) return Boolean; procedure Match (Subject : in out VString; Pat : Pattern; Result : out Match_Result); procedure Replace (Result : in out Match_Result; Replace : VString); -- Given a previous call to Match which set Result, performs a pattern -- replacement if the match was successful. Has no effect if the match -- failed. This call should immediately follow the Match call. ------------------------ -- Debugging Routines -- ------------------------ -- Debugging pattern matching operations can often be quite complex, -- since there is no obvious way to trace the progress of the match. -- The declarations in this section provide some debugging assistance. Debug_Mode : Boolean := False; -- This global variable can be set True to generate debugging on all -- subsequent calls to Match. The debugging output is a full trace of -- the actions of the pattern matcher, written to Standard_Output. The -- level of this information is intended to be comprehensible at the -- abstract level of this package declaration. However, note that the -- use of this switch often generates large amounts of output. function ""*"" (P : Pattern; Fil : File_Access) return Pattern; function ""*"" (P : PString; Fil : File_Access) return Pattern; function ""*"" (P : PChar; Fil : File_Access) return Pattern; function ""**"" (P : Pattern; Fil : File_Access) return Pattern; function ""**"" (P : PString; Fil : File_Access) return Pattern; function ""**"" (P : PChar; Fil : File_Access) return Pattern; -- These are similar to the corresponding pattern assignment operations -- except that instead of setting the value of a variable, the matched -- substring is written to the appropriate file. This can be useful in -- following the progress of a match without generating the full amount -- of information obtained by setting Debug_Mode to True. Terminal : constant File_Access := Standard_Error; Output : constant File_Access := Standard_Output; -- Two handy synonyms for use with the above pattern write operations -- Finally we have some routines that are useful for determining what -- patterns are in use, particularly if they are constructed dynamically. function Image (P : Pattern) return String; function Image (P : Pattern) return VString; -- This procedures yield strings that corresponds to the syntax needed -- to create the given pattern using the functions in this package. The -- form of this string is such that it could actually be compiled and -- evaluated to yield the required pattern except for references to -- variables and functions, which are output using one of the following -- forms: -- -- access Natural NP(16#...#) -- access Pattern PP(16#...#) -- access VString VP(16#...#) -- -- Natural_Func NF(16#...#) -- VString_Func VF(16#...#) -- -- where 16#...# is the hex representation of the integer address that -- corresponds to the given access value procedure Dump (P : Pattern); -- This procedure writes information about the pattern to Standard_Out. -- The format of this information is keyed to the internal data structures -- used to implement patterns. The information provided by Dump is thus -- more precise than that yielded by Image, but is also a bit more obscure -- (i.e. it cannot be interpreted solely in terms of this spec, you have -- to know something about the data structures). ------------------ -- Private Part -- ------------------ private type PE; -- Pattern element, a pattern is a plex structure of PE's. This type -- is defined and sdescribed in the body of this package. type PE_Ptr is access all PE; -- Pattern reference. PE's use PE_Ptr values to reference other PE's type Pattern is new Controlled with record Stk : Natural := 0; -- Maximum number of stack entries required for matching this -- pattern. See description of pattern history stack in body. P : PE_Ptr := null; -- Pointer to initial pattern element for pattern end record; pragma Finalize_Storage_Only (Pattern); procedure Adjust (Object : in out Pattern); -- Adjust routine used to copy pattern objects procedure Finalize (Object : in out Pattern); -- Finalization routine used to release storage allocated for a pattern type VString_Ptr is access all VString; type Match_Result is record Var : VString_Ptr; -- Pointer to subject string. Set to null if match failed Start : Natural := 1; -- Starting index position (1's origin) of matched section of -- subject string. Only valid if Var is non-null. Stop : Natural := 0; -- Ending index position (1's origin) of matched section of -- subject string. Only valid if Var is non-null. end record; pragma Volatile (Match_Result); -- This ensures that the Result parameter is passed by reference, so -- that we can play our games with the bogus Match_Result_Var parameter -- in the function case to treat it as though it were an in out parameter. end GNAT.Spitbol.Patterns; ",12366,False,2337.9948296949756,median "------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- A D A . T A G S -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2006, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT 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 distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, -- -- Boston, MA 02110-1301, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Ada.Exceptions; with System.HTable; with System.Storage_Elements; use System.Storage_Elements; with System.WCh_Con; use System.WCh_Con; with System.WCh_StW; use System.WCh_StW; pragma Elaborate_All (System.HTable); package body Ada.Tags is -- Structure of the GNAT Primary Dispatch Table -- +----------------------+ -- | table of | -- : predefined primitive : -- | ops pointers | -- +----------------------+ -- | Signature | -- +----------------------+ -- | Tagged_Kind | -- +----------------------+ -- | Offset_To_Top | -- +----------------------+ -- | Typeinfo_Ptr/TSD_Ptr ---> Type Specific Data -- Tag ---> +----------------------+ +-------------------+ -- | table of | | inheritance depth | -- : primitive ops : +-------------------+ -- | pointers | | access level | -- +----------------------+ +-------------------+ -- | expanded name | -- +-------------------+ -- | external tag | -- +-------------------+ -- | hash table link | -- +-------------------+ -- | remotely callable | -- +-------------------+ -- | rec ctrler offset | -- +-------------------+ -- | num prim ops | -- +-------------------+ -- | Ifaces_Table_Ptr --> Interface Data -- +-------------------+ +------------+ -- Select Specific Data <---- SSD_Ptr | | table | -- +--------------------+ +-------------------+ : of : -- | table of primitive | | table of | | interfaces | -- : operation : : ancestor : +------------+ -- | kinds | | tags | -- +--------------------+ +-------------------+ -- | table of | -- : entry : -- | indices | -- +--------------------+ -- Structure of the GNAT Secondary Dispatch Table -- +-----------------------+ -- | table of | -- : predefined primitive : -- | ops pointers | -- +-----------------------+ -- | Signature | -- +-----------------------+ -- | Tagged_Kind | -- +-----------------------+ -- | Offset_To_Top | -- +-----------------------+ -- | OSD_Ptr |---> Object Specific Data -- Tag ---> +-----------------------+ +---------------+ -- | table of | | num prim ops | -- : primitive op : +---------------+ -- | thunk pointers | | table of | -- +-----------------------+ + primitive | -- | op offsets | -- +---------------+ ---------------------------------- -- GNAT Dispatch Table Prologue -- ---------------------------------- -- GNAT's Dispatch Table prologue contains several fields which are hidden -- in order to preserve compatibility with C++. These fields are accessed -- by address calculations performed in the following manner: -- Field : Field_Type := -- (To_Address (Tag) - Sum_Of_Preceding_Field_Sizes).all; -- The bracketed subtraction shifts the pointer (Tag) from the table of -- primitive operations (or thunks) to the field in question. Since the -- result of the subtraction is an address, dereferencing it will obtain -- the actual value of the field. -- Guidelines for addition of new hidden fields -- Define a Field_Type and Field_Type_Ptr (access to Field_Type) in -- A-Tags.ads for the newly introduced field. -- Defined the size of the new field as a constant Field_Name_Size -- Introduce an Unchecked_Conversion from System.Address to -- Field_Type_Ptr in A-Tags.ads. -- Define the specifications of Get_ and Set_ -- in a-tags.ads. -- Update the GNAT Dispatch Table structure in a-tags.adb -- Provide bodies to the Get_ and Set_ routines. -- The profile of a Get_ routine should resemble: -- function Get_ (T : Tag; ...) return Field_Type is -- Field : constant System.Address := -- To_Address (T) - ; -- begin -- pragma Assert (Check_Signature (T, )); -- -- return To_Field_Type_Ptr (Field).all; -- end Get_; -- The profile of a Set_ routine should resemble: -- procedure Set_ (T : Tag; ..., Value : Field_Type) is -- Field : constant System.Address := -- To_Address (T) - ; -- begin -- pragma Assert (Check_Signature (T, )); -- -- To_Field_Type_Ptr (Field).all := Value; -- end Set_; -- NOTE: For each field in the prologue which precedes the newly added -- one, find and update its respective Sum_Of_Previous_Field_Sizes by -- subtractind Field_Name_Size from it. Falure to do so will clobber the -- previous prologue field. K_Typeinfo : constant SSE.Storage_Count := DT_Typeinfo_Ptr_Size; K_Offset_To_Top : constant SSE.Storage_Count := K_Typeinfo + DT_Offset_To_Top_Size; K_Tagged_Kind : constant SSE.Storage_Count := K_Offset_To_Top + DT_Tagged_Kind_Size; K_Signature : constant SSE.Storage_Count := K_Tagged_Kind + DT_Signature_Size; subtype Cstring is String (Positive); type Cstring_Ptr is access all Cstring; -- We suppress index checks because the declared size in the record below -- is a dummy size of one (see below). type Tag_Table is array (Natural range <>) of Tag; pragma Suppress_Initialization (Tag_Table); pragma Suppress (Index_Check, On => Tag_Table); -- Declarations for the table of interfaces type Interface_Data_Element is record Iface_Tag : Tag; Static_Offset_To_Top : Boolean; Offset_To_Top_Value : System.Storage_Elements.Storage_Offset; Offset_To_Top_Func : System.Address; end record; -- If some ancestor of the tagged type has discriminants the field -- Static_Offset_To_Top is False and the field Offset_To_Top_Func -- is used to store the address of the function generated by the -- expander which provides this value; otherwise Static_Offset_To_Top -- is True and such value is stored in the Offset_To_Top_Value field. type Interfaces_Array is array (Natural range <>) of Interface_Data_Element; type Interface_Data (Nb_Ifaces : Positive) is record Table : Interfaces_Array (1 .. Nb_Ifaces); end record; -- Object specific data types type Object_Specific_Data_Array is array (Positive range <>) of Positive; type Object_Specific_Data (Nb_Prim : Positive) is record Num_Prim_Ops : Natural; -- Number of primitive operations of the dispatch table. This field is -- used by the run-time check routines that are activated when the -- run-time is compiled with assertions enabled. OSD_Table : Object_Specific_Data_Array (1 .. Nb_Prim); -- Table used in secondary DT to reference their counterpart in the -- select specific data (in the TSD of the primary DT). This construct -- is used in the handling of dispatching triggers in select statements. -- Nb_Prim is the number of non-predefined primitive operations. end record; -- Select specific data types type Select_Specific_Data_Element is record Index : Positive; Kind : Prim_Op_Kind; end record; type Select_Specific_Data_Array is array (Positive range <>) of Select_Specific_Data_Element; type Select_Specific_Data (Nb_Prim : Positive) is record SSD_Table : Select_Specific_Data_Array (1 .. Nb_Prim); -- NOTE: Nb_Prim is the number of non-predefined primitive operations end record; -- Type specific data types type Type_Specific_Data is record Idepth : Natural; -- Inheritance Depth Level: Used to implement the membership test -- associated with single inheritance of tagged types in constant-time. -- In addition it also indicates the size of the first table stored in -- the Tags_Table component (see comment below). Access_Level : Natural; -- Accessibility level required to give support to Ada 2005 nested type -- extensions. This feature allows safe nested type extensions by -- shifting the accessibility checks to certain operations, rather than -- being enforced at the type declaration. In particular, by performing -- run-time accessibility checks on class-wide allocators, class-wide -- function return, and class-wide stream I/O, the danger of objects -- outliving their type declaration can be eliminated (Ada 2005: AI-344) Expanded_Name : Cstring_Ptr; External_Tag : Cstring_Ptr; HT_Link : Tag; -- Components used to give support to the Ada.Tags subprograms described -- in ARM 3.9 Remotely_Callable : Boolean; -- Used to check ARM E.4 (18) RC_Offset : SSE.Storage_Offset; -- Controller Offset: Used to give support to tagged controlled objects -- (see Get_Deep_Controller at s-finimp) Ifaces_Table_Ptr : System.Address; -- Pointer to the table of interface tags. It is used to implement the -- membership test associated with interfaces and also for backward -- abstract interface type conversions (Ada 2005:AI-251) Num_Prim_Ops : Natural; -- Number of primitive operations of the dispatch table. This field is -- used for additional run-time checks when the run-time is compiled -- with assertions enabled. SSD_Ptr : System.Address; -- Pointer to a table of records used in dispatching selects. This -- field has a meaningful value for all tagged types that implement -- a limited, protected, synchronized or task interfaces and have -- non-predefined primitive operations. Tags_Table : Tag_Table (0 .. 1); -- The size of the Tags_Table array actually depends on the tagged type -- to which it applies. The compiler ensures that has enough space to -- store all the entries of the two tables phisically stored there: the -- ""table of ancestor tags"" and the ""table of interface tags"". For this -- purpose we are using the same mechanism as for the Prims_Ptr array in -- the Dispatch_Table record. See comments below on Prims_Ptr for -- further details. end record; type Dispatch_Table is record -- According to the C++ ABI the components Offset_To_Top and -- Typeinfo_Ptr are stored just ""before"" the dispatch table (that is, -- the Prims_Ptr table), and they are referenced with negative offsets -- referring to the base of the dispatch table. The _Tag (or the -- VTable_Ptr in C++ terminology) must point to the base of the virtual -- table, just after these components, to point to the Prims_Ptr table. -- For this purpose the expander generates a Prims_Ptr table that has -- enough space for these additional components, and generates code that -- displaces the _Tag to point after these components. -- Signature : Signature_Kind; -- Tagged_Kind : Tagged_Kind; -- Offset_To_Top : Natural; -- Typeinfo_Ptr : System.Address; Prims_Ptr : Address_Array (1 .. 1); -- The size of the Prims_Ptr array actually depends on the tagged type -- to which it applies. For each tagged type, the expander computes the -- actual array size, allocates the Dispatch_Table record accordingly, -- and generates code that displaces the base of the record after the -- Typeinfo_Ptr component. For this reason the first two components have -- been commented in the previous declaration. The access to these -- components is done by means of local functions. -- -- To avoid the use of discriminants to define the actual size of the -- dispatch table, we used to declare the tag as a pointer to a record -- that contains an arbitrary array of addresses, using Positive as its -- index. This ensures that there are never range checks when accessing -- the dispatch table, but it prevents GDB from displaying tagged types -- properly. A better approach is to declare this record type as holding -- small number of addresses, and to explicitly suppress checks on it. -- -- Note that in both cases, this type is never allocated, and serves -- only to declare the corresponding access type. end record; type Signature_Type is (Must_Be_Primary_DT, Must_Be_Secondary_DT, Must_Be_Primary_Or_Secondary_DT, Must_Be_Interface, Must_Be_Primary_Or_Interface); -- Type of signature accepted by primitives in this package that are called -- during the elaboration of tagged types. This type is used by the routine -- Check_Signature that is called only when the run-time is compiled with -- assertions enabled. --------------------------------------------- -- Unchecked Conversions for String Fields -- --------------------------------------------- function To_Address is new Unchecked_Conversion (Cstring_Ptr, System.Address); function To_Cstring_Ptr is new Unchecked_Conversion (System.Address, Cstring_Ptr); ------------------------------------------------ -- Unchecked Conversions for other components -- ------------------------------------------------ type Acc_Size is access function (A : System.Address) return Long_Long_Integer; function To_Acc_Size is new Unchecked_Conversion (System.Address, Acc_Size); -- The profile of the implicitly defined _size primitive type Offset_To_Top_Function_Ptr is access function (This : System.Address) return System.Storage_Elements.Storage_Offset; -- Type definition used to call the function that is generated by the -- expander in case of tagged types with discriminants that have secondary -- dispatch tables. This function provides the Offset_To_Top value in this -- specific case. function To_Offset_To_Top_Function_Ptr is new Unchecked_Conversion (System.Address, Offset_To_Top_Function_Ptr); type Storage_Offset_Ptr is access System.Storage_Elements.Storage_Offset; function To_Storage_Offset_Ptr is new Unchecked_Conversion (System.Address, Storage_Offset_Ptr); ----------------------- -- Local Subprograms -- ----------------------- function Check_Signature (T : Tag; Kind : Signature_Type) return Boolean; -- Check that the signature of T is valid and corresponds with the subset -- specified by the signature Kind. function Check_Size (Old_T : Tag; New_T : Tag; Entry_Count : Natural) return Boolean; -- Verify that Old_T and New_T have at least Entry_Count entries function Get_Num_Prim_Ops (T : Tag) return Natural; -- Retrieve the number of primitive operations in the dispatch table of T function Is_Primary_DT (T : Tag) return Boolean; pragma Inline_Always (Is_Primary_DT); -- Given a tag returns True if it has the signature of a primary dispatch -- table. This is Inline_Always since it is called from other Inline_ -- Always subprograms where we want no out of line code to be generated. function Length (Str : Cstring_Ptr) return Natural; -- Length of string represented by the given pointer (treating the string -- as a C-style string, which is Nul terminated). function Typeinfo_Ptr (T : Tag) return System.Address; -- Returns the current value of the typeinfo_ptr component available in -- the prologue of the dispatch table. pragma Unreferenced (Typeinfo_Ptr); -- These functions will be used for full compatibility with the C++ ABI ------------------------- -- External_Tag_HTable -- ------------------------- type HTable_Headers is range 1 .. 64; -- The following internal package defines the routines used for the -- instantiation of a new System.HTable.Static_HTable (see below). See -- spec in g-htable.ads for details of usage. package HTable_Subprograms is procedure Set_HT_Link (T : Tag; Next : Tag); function Get_HT_Link (T : Tag) return Tag; function Hash (F : System.Address) return HTable_Headers; function Equal (A, B : System.Address) return Boolean; end HTable_Subprograms; package External_Tag_HTable is new System.HTable.Static_HTable ( Header_Num => HTable_Headers, Element => Dispatch_Table, Elmt_Ptr => Tag, Null_Ptr => null, Set_Next => HTable_Subprograms.Set_HT_Link, Next => HTable_Subprograms.Get_HT_Link, Key => System.Address, Get_Key => Get_External_Tag, Hash => HTable_Subprograms.Hash, Equal => HTable_Subprograms.Equal); ------------------------ -- HTable_Subprograms -- ------------------------ -- Bodies of routines for hash table instantiation package body HTable_Subprograms is ----------- -- Equal -- ----------- function Equal (A, B : System.Address) return Boolean is Str1 : constant Cstring_Ptr := To_Cstring_Ptr (A); Str2 : constant Cstring_Ptr := To_Cstring_Ptr (B); J : Integer := 1; begin loop if Str1 (J) /= Str2 (J) then return False; elsif Str1 (J) = ASCII.NUL then return True; else J := J + 1; end if; end loop; end Equal; ----------------- -- Get_HT_Link -- ----------------- function Get_HT_Link (T : Tag) return Tag is begin return TSD (T).HT_Link; end Get_HT_Link; ---------- -- Hash -- ---------- function Hash (F : System.Address) return HTable_Headers is function H is new System.HTable.Hash (HTable_Headers); Str : constant Cstring_Ptr := To_Cstring_Ptr (F); Res : constant HTable_Headers := H (Str (1 .. Length (Str))); begin return Res; end Hash; ----------------- -- Set_HT_Link -- ----------------- procedure Set_HT_Link (T : Tag; Next : Tag) is begin TSD (T).HT_Link := Next; end Set_HT_Link; end HTable_Subprograms; --------------------- -- Check_Signature -- --------------------- function Check_Signature (T : Tag; Kind : Signature_Type) return Boolean is Signature : constant Storage_Offset_Ptr := To_Storage_Offset_Ptr (To_Address (T) - K_Signature); Sig_Values : constant Signature_Values := To_Signature_Values (Signature.all); Signature_Id : Signature_Kind; begin if Sig_Values (1) /= Valid_Signature then Signature_Id := Unknown; elsif Sig_Values (2) in Primary_DT .. Abstract_Interface then Signature_Id := Sig_Values (2); else Signature_Id := Unknown; end if; case Signature_Id is when Primary_DT => if Kind = Must_Be_Secondary_DT or else Kind = Must_Be_Interface then return False; end if; when Secondary_DT => if Kind = Must_Be_Primary_DT or else Kind = Must_Be_Interface then return False; end if; when Abstract_Interface => if Kind = Must_Be_Primary_DT or else Kind = Must_Be_Secondary_DT or else Kind = Must_Be_Primary_Or_Secondary_DT then return False; end if; when others => return False; end case; return True; end Check_Signature; ---------------- -- Check_Size -- ---------------- function Check_Size (Old_T : Tag; New_T : Tag; Entry_Count : Natural) return Boolean is Max_Entries_Old : constant Natural := Get_Num_Prim_Ops (Old_T); Max_Entries_New : constant Natural := Get_Num_Prim_Ops (New_T); begin return Entry_Count <= Max_Entries_Old and then Entry_Count <= Max_Entries_New; end Check_Size; ------------------- -- CW_Membership -- ------------------- -- Canonical implementation of Classwide Membership corresponding to: -- Obj in Typ'Class -- Each dispatch table contains a reference to a table of ancestors (stored -- in the first part of the Tags_Table) and a count of the level of -- inheritance ""Idepth"". -- Obj is in Typ'Class if Typ'Tag is in the table of ancestors that are -- contained in the dispatch table referenced by Obj'Tag . Knowing the -- level of inheritance of both types, this can be computed in constant -- time by the formula: -- Obj'tag.TSD.Ancestor_Tags (Obj'tag.TSD.Idepth - Typ'tag.TSD.Idepth) -- = Typ'tag function CW_Membership (Obj_Tag : Tag; Typ_Tag : Tag) return Boolean is Pos : Integer; begin pragma Assert (Check_Signature (Obj_Tag, Must_Be_Primary_DT)); pragma Assert (Check_Signature (Typ_Tag, Must_Be_Primary_DT)); Pos := TSD (Obj_Tag).Idepth - TSD (Typ_Tag).Idepth; return Pos >= 0 and then TSD (Obj_Tag).Tags_Table (Pos) = Typ_Tag; end CW_Membership; -------------- -- Displace -- -------------- function Displace (This : System.Address; T : Tag) return System.Address is Curr_DT : constant Tag := To_Tag_Ptr (This).all; Iface_Table : Interface_Data_Ptr; Obj_Base : System.Address; Obj_DT : Tag; Obj_TSD : Type_Specific_Data_Ptr; begin pragma Assert (Check_Signature (Curr_DT, Must_Be_Primary_Or_Secondary_DT)); pragma Assert (Check_Signature (T, Must_Be_Interface)); Obj_Base := This - Offset_To_Top (This); Obj_DT := To_Tag_Ptr (Obj_Base).all; pragma Assert (Check_Signature (Obj_DT, Must_Be_Primary_DT)); Obj_TSD := TSD (Obj_DT); Iface_Table := To_Interface_Data_Ptr (Obj_TSD.Ifaces_Table_Ptr); if Iface_Table /= null then for Id in 1 .. Iface_Table.Nb_Ifaces loop if Iface_Table.Table (Id).Iface_Tag = T then -- Case of Static value of Offset_To_Top if Iface_Table.Table (Id).Static_Offset_To_Top then Obj_Base := Obj_Base + Iface_Table.Table (Id).Offset_To_Top_Value; -- Otherwise we call the function generated by the expander -- to provide us with this value else Obj_Base := Obj_Base + To_Offset_To_Top_Function_Ptr (Iface_Table.Table (Id).Offset_To_Top_Func).all (Obj_Base); end if; Obj_DT := To_Tag_Ptr (Obj_Base).all; pragma Assert (Check_Signature (Obj_DT, Must_Be_Secondary_DT)); return Obj_Base; end if; end loop; end if; -- If the object does not implement the interface we must raise CE raise Constraint_Error; end Displace; ------------------- -- IW_Membership -- ------------------- -- Canonical implementation of Classwide Membership corresponding to: -- Obj in Iface'Class -- Each dispatch table contains a table with the tags of all the -- implemented interfaces. -- Obj is in Iface'Class if Iface'Tag is found in the table of interfaces -- that are contained in the dispatch table referenced by Obj'Tag. function IW_Membership (This : System.Address; T : Tag) return Boolean is Curr_DT : constant Tag := To_Tag_Ptr (This).all; Iface_Table : Interface_Data_Ptr; Last_Id : Natural; Obj_Base : System.Address; Obj_DT : Tag; Obj_TSD : Type_Specific_Data_Ptr; begin pragma Assert (Check_Signature (Curr_DT, Must_Be_Primary_Or_Secondary_DT)); pragma Assert (Check_Signature (T, Must_Be_Primary_Or_Interface)); Obj_Base := This - Offset_To_Top (This); Obj_DT := To_Tag_Ptr (Obj_Base).all; pragma Assert (Check_Signature (Obj_DT, Must_Be_Primary_DT)); Obj_TSD := TSD (Obj_DT); Last_Id := Obj_TSD.Idepth; -- Look for the tag in the table of interfaces Iface_Table := To_Interface_Data_Ptr (Obj_TSD.Ifaces_Table_Ptr); if Iface_Table /= null then for Id in 1 .. Iface_Table.Nb_Ifaces loop if Iface_Table.Table (Id).Iface_Tag = T then return True; end if; end loop; end if; -- Look for the tag in the ancestor tags table. This is required for: -- Iface_CW in Typ'Class for Id in 0 .. Last_Id loop if Obj_TSD.Tags_Table (Id) = T then return True; end if; end loop; return False; end IW_Membership; -------------------- -- Descendant_Tag -- -------------------- function Descendant_Tag (External : String; Ancestor : Tag) return Tag is Int_Tag : Tag; begin pragma Assert (Check_Signature (Ancestor, Must_Be_Primary_DT)); Int_Tag := Internal_Tag (External); pragma Assert (Check_Signature (Int_Tag, Must_Be_Primary_DT)); if not Is_Descendant_At_Same_Level (Int_Tag, Ancestor) then raise Tag_Error; end if; return Int_Tag; end Descendant_Tag; ------------------- -- Expanded_Name -- ------------------- function Expanded_Name (T : Tag) return String is Result : Cstring_Ptr; begin if T = No_Tag then raise Tag_Error; end if; pragma Assert (Check_Signature (T, Must_Be_Primary_Or_Interface)); Result := TSD (T).Expanded_Name; return Result (1 .. Length (Result)); end Expanded_Name; ------------------ -- External_Tag -- ------------------ function External_Tag (T : Tag) return String is Result : Cstring_Ptr; begin if T = No_Tag then raise Tag_Error; end if; pragma Assert (Check_Signature (T, Must_Be_Primary_Or_Interface)); Result := TSD (T).External_Tag; return Result (1 .. Length (Result)); end External_Tag; ---------------------- -- Get_Access_Level -- ---------------------- function Get_Access_Level (T : Tag) return Natural is begin pragma Assert (Check_Signature (T, Must_Be_Primary_DT)); return TSD (T).Access_Level; end Get_Access_Level; --------------------- -- Get_Entry_Index -- --------------------- function Get_Entry_Index (T : Tag; Position : Positive) return Positive is begin pragma Assert (Check_Signature (T, Must_Be_Primary_DT)); pragma Assert (Position <= Get_Num_Prim_Ops (T)); return SSD (T).SSD_Table (Position).Index; end Get_Entry_Index; ---------------------- -- Get_External_Tag -- ---------------------- function Get_External_Tag (T : Tag) return System.Address is begin pragma Assert (Check_Signature (T, Must_Be_Primary_DT)); return To_Address (TSD (T).External_Tag); end Get_External_Tag; ---------------------- -- Get_Num_Prim_Ops -- ---------------------- function Get_Num_Prim_Ops (T : Tag) return Natural is begin pragma Assert (Check_Signature (T, Must_Be_Primary_Or_Secondary_DT)); if Is_Primary_DT (T) then return TSD (T).Num_Prim_Ops; else return OSD (T).Num_Prim_Ops; end if; end Get_Num_Prim_Ops; -------------------------------- -- Get_Predef_Prim_Op_Address -- -------------------------------- function Get_Predefined_Prim_Op_Address (T : Tag; Position : Positive) return System.Address is Prim_Ops_DT : constant Tag := To_Tag (To_Address (T) - DT_Prologue_Size); begin pragma Assert (Check_Signature (T, Must_Be_Primary_Or_Secondary_DT)); pragma Assert (Position <= Default_Prim_Op_Count); return Prim_Ops_DT.Prims_Ptr (Position); end Get_Predefined_Prim_Op_Address; ------------------------- -- Get_Prim_Op_Address -- ------------------------- function Get_Prim_Op_Address (T : Tag; Position : Positive) return System.Address is begin pragma Assert (Check_Signature (T, Must_Be_Primary_Or_Secondary_DT)); pragma Assert (Position <= Get_Num_Prim_Ops (T)); return T.Prims_Ptr (Position); end Get_Prim_Op_Address; ---------------------- -- Get_Prim_Op_Kind -- ---------------------- function Get_Prim_Op_Kind (T : Tag; Position : Positive) return Prim_Op_Kind is begin pragma Assert (Check_Signature (T, Must_Be_Primary_DT)); pragma Assert (Position <= Get_Num_Prim_Ops (T)); return SSD (T).SSD_Table (Position).Kind; end Get_Prim_Op_Kind; ---------------------- -- Get_Offset_Index -- ---------------------- function Get_Offset_Index (T : Tag; Position : Positive) return Positive is begin pragma Assert (Check_Signature (T, Must_Be_Secondary_DT)); pragma Assert (Position <= Get_Num_Prim_Ops (T)); return OSD (T).OSD_Table (Position); end Get_Offset_Index; ------------------- -- Get_RC_Offset -- ------------------- function Get_RC_Offset (T : Tag) return SSE.Storage_Offset is begin pragma Assert (Check_Signature (T, Must_Be_Primary_DT)); return TSD (T).RC_Offset; end Get_RC_Offset; --------------------------- -- Get_Remotely_Callable -- --------------------------- function Get_Remotely_Callable (T : Tag) return Boolean is begin pragma Assert (Check_Signature (T, Must_Be_Primary_DT)); return TSD (T).Remotely_Callable; end Get_Remotely_Callable; --------------------- -- Get_Tagged_Kind -- --------------------- function Get_Tagged_Kind (T : Tag) return Tagged_Kind is Tagged_Kind_Ptr : constant System.Address := To_Address (T) - K_Tagged_Kind; begin pragma Assert (Check_Signature (T, Must_Be_Primary_Or_Secondary_DT)); return To_Tagged_Kind_Ptr (Tagged_Kind_Ptr).all; end Get_Tagged_Kind; ---------------- -- Inherit_DT -- ---------------- procedure Inherit_DT (Old_T : Tag; New_T : Tag; Entry_Count : Natural) is Old_T_Prim_Ops : Tag; New_T_Prim_Ops : Tag; Size : Positive; begin pragma Assert (Check_Signature (Old_T, Must_Be_Primary_Or_Secondary_DT)); pragma Assert (Check_Signature (New_T, Must_Be_Primary_Or_Secondary_DT)); pragma Assert (Check_Size (Old_T, New_T, Entry_Count)); if Old_T /= null then New_T.Prims_Ptr (1 .. Entry_Count) := Old_T.Prims_Ptr (1 .. Entry_Count); Old_T_Prim_Ops := To_Tag (To_Address (Old_T) - DT_Prologue_Size); New_T_Prim_Ops := To_Tag (To_Address (New_T) - DT_Prologue_Size); Size := Default_Prim_Op_Count; New_T_Prim_Ops.Prims_Ptr (1 .. Size) := Old_T_Prim_Ops.Prims_Ptr (1 .. Size); end if; end Inherit_DT; ----------------- -- Inherit_TSD -- ----------------- procedure Inherit_TSD (Old_Tag : Tag; New_Tag : Tag) is New_TSD_Ptr : Type_Specific_Data_Ptr; New_Iface_Table_Ptr : Interface_Data_Ptr; Old_TSD_Ptr : Type_Specific_Data_Ptr; Old_Iface_Table_Ptr : Interface_Data_Ptr; begin pragma Assert (Check_Signature (New_Tag, Must_Be_Primary_Or_Interface)); New_TSD_Ptr := TSD (New_Tag); if Old_Tag /= null then pragma Assert (Check_Signature (Old_Tag, Must_Be_Primary_Or_Interface)); Old_TSD_Ptr := TSD (Old_Tag); New_TSD_Ptr.Idepth := Old_TSD_Ptr.Idepth + 1; -- Copy the ""table of ancestor tags"" plus the ""table of interfaces"" -- of the parent. New_TSD_Ptr.Tags_Table (1 .. New_TSD_Ptr.Idepth) := Old_TSD_Ptr.Tags_Table (0 .. Old_TSD_Ptr.Idepth); -- Copy the table of interfaces of the parent if not System.""="" (Old_TSD_Ptr.Ifaces_Table_Ptr, System.Null_Address) then Old_Iface_Table_Ptr := To_Interface_Data_Ptr (Old_TSD_Ptr.Ifaces_Table_Ptr); New_Iface_Table_Ptr := To_Interface_Data_Ptr (New_TSD_Ptr.Ifaces_Table_Ptr); New_Iface_Table_Ptr.Table (1 .. Old_Iface_Table_Ptr.Nb_Ifaces) := Old_Iface_Table_Ptr.Table (1 .. Old_Iface_Table_Ptr.Nb_Ifaces); end if; else New_TSD_Ptr.Idepth := 0; end if; New_TSD_Ptr.Tags_Table (0) := New_Tag; end Inherit_TSD; ------------------ -- Internal_Tag -- ------------------ function Internal_Tag (External : String) return Tag is Ext_Copy : aliased String (External'First .. External'Last + 1); Res : Tag; begin -- Make a copy of the string representing the external tag with -- a null at the end. Ext_Copy (External'Range) := External; Ext_Copy (Ext_Copy'Last) := ASCII.NUL; Res := External_Tag_HTable.Get (Ext_Copy'Address); if Res = null then declare Msg1 : constant String := ""unknown tagged type: ""; Msg2 : String (1 .. Msg1'Length + External'Length); begin Msg2 (1 .. Msg1'Length) := Msg1; Msg2 (Msg1'Length + 1 .. Msg1'Length + External'Length) := External; Ada.Exceptions.Raise_Exception (Tag_Error'Identity, Msg2); end; end if; return Res; end Internal_Tag; --------------------------------- -- Is_Descendant_At_Same_Level -- --------------------------------- function Is_Descendant_At_Same_Level (Descendant : Tag; Ancestor : Tag) return Boolean is begin return CW_Membership (Descendant, Ancestor) and then TSD (Descendant).Access_Level = TSD (Ancestor).Access_Level; end Is_Descendant_At_Same_Level; ------------------- -- Is_Primary_DT -- ------------------- function Is_Primary_DT (T : Tag) return Boolean is Signature : constant Storage_Offset_Ptr := To_Storage_Offset_Ptr (To_Address (T) - K_Signature); Sig_Values : constant Signature_Values := To_Signature_Values (Signature.all); begin return Sig_Values (2) = Primary_DT; end Is_Primary_DT; ------------ -- Length -- ------------ function Length (Str : Cstring_Ptr) return Natural is Len : Integer := 1; begin while Str (Len) /= ASCII.Nul loop Len := Len + 1; end loop; return Len - 1; end Length; ------------------- -- Offset_To_Top -- ------------------- function Offset_To_Top (This : System.Address) return System.Storage_Elements.Storage_Offset is Curr_DT : constant Tag := To_Tag_Ptr (This).all; Offset_To_Top : Storage_Offset_Ptr; begin Offset_To_Top := To_Storage_Offset_Ptr (To_Address (Curr_DT) - K_Offset_To_Top); if Offset_To_Top.all = SSE.Storage_Offset'Last then Offset_To_Top := To_Storage_Offset_Ptr (This + Tag_Size); end if; return Offset_To_Top.all; end Offset_To_Top; --------- -- OSD -- --------- function OSD (T : Tag) return Object_Specific_Data_Ptr is OSD_Ptr : constant Addr_Ptr := To_Addr_Ptr (To_Address (T) - K_Typeinfo); begin pragma Assert (Check_Signature (T, Must_Be_Secondary_DT)); return To_Object_Specific_Data_Ptr (OSD_Ptr.all); end OSD; ----------------- -- Parent_Size -- ----------------- function Parent_Size (Obj : System.Address; T : Tag) return SSE.Storage_Count is Parent_Tag : Tag; -- The tag of the parent type through the dispatch table Prim_Ops_DT : Tag; -- The table of primitive operations of the parent F : Acc_Size; -- Access to the _size primitive of the parent. We assume that it is -- always in the first slot of the dispatch table. begin pragma Assert (Check_Signature (T, Must_Be_Primary_DT)); Parent_Tag := TSD (T).Tags_Table (1); Prim_Ops_DT := To_Tag (To_Address (Parent_Tag) - DT_Prologue_Size); F := To_Acc_Size (Prim_Ops_DT.Prims_Ptr (1)); -- Here we compute the size of the _parent field of the object return SSE.Storage_Count (F.all (Obj)); end Parent_Size; ---------------- -- Parent_Tag -- ---------------- function Parent_Tag (T : Tag) return Tag is begin if T = No_Tag then raise Tag_Error; end if; pragma Assert (Check_Signature (T, Must_Be_Primary_DT)); -- The Parent_Tag of a root-level tagged type is defined to be No_Tag. -- The first entry in the Ancestors_Tags array will be null for such -- a type, but it's better to be explicit about returning No_Tag in -- this case. if TSD (T).Idepth = 0 then return No_Tag; else return TSD (T).Tags_Table (1); end if; end Parent_Tag; ---------------------------- -- Register_Interface_Tag -- ---------------------------- procedure Register_Interface_Tag (T : Tag; Interface_T : Tag; Position : Positive) is New_T_TSD : Type_Specific_Data_Ptr; Iface_Table : Interface_Data_Ptr; begin pragma Assert (Check_Signature (T, Must_Be_Primary_DT)); pragma Assert (Check_Signature (Interface_T, Must_Be_Interface)); New_T_TSD := TSD (T); Iface_Table := To_Interface_Data_Ptr (New_T_TSD.Ifaces_Table_Ptr); pragma Assert (Position <= Iface_Table.Nb_Ifaces); Iface_Table.Table (Position).Iface_Tag := Interface_T; end Register_Interface_Tag; ------------------ -- Register_Tag -- ------------------ procedure Register_Tag (T : Tag) is begin External_Tag_HTable.Set (T); end Register_Tag; ---------------------- -- Set_Access_Level -- ---------------------- procedure Set_Access_Level (T : Tag; Value : Natural) is begin pragma Assert (Check_Signature (T, Must_Be_Primary_DT)); TSD (T).Access_Level := Value; end Set_Access_Level; --------------------- -- Set_Entry_Index -- --------------------- procedure Set_Entry_Index (T : Tag; Position : Positive; Value : Positive) is begin pragma Assert (Check_Signature (T, Must_Be_Primary_DT)); pragma Assert (Position <= Get_Num_Prim_Ops (T)); SSD (T).SSD_Table (Position).Index := Value; end Set_Entry_Index; ----------------------- -- Set_Expanded_Name -- ----------------------- procedure Set_Expanded_Name (T : Tag; Value : System.Address) is begin pragma Assert (Check_Signature (T, Must_Be_Primary_Or_Interface)); TSD (T).Expanded_Name := To_Cstring_Ptr (Value); end Set_Expanded_Name; ---------------------- -- Set_External_Tag -- ---------------------- procedure Set_External_Tag (T : Tag; Value : System.Address) is begin pragma Assert (Check_Signature (T, Must_Be_Primary_Or_Interface)); TSD (T).External_Tag := To_Cstring_Ptr (Value); end Set_External_Tag; ------------------------- -- Set_Interface_Table -- ------------------------- procedure Set_Interface_Table (T : Tag; Value : System.Address) is begin pragma Assert (Check_Signature (T, Must_Be_Primary_DT)); TSD (T).Ifaces_Table_Ptr := Value; end Set_Interface_Table; ---------------------- -- Set_Num_Prim_Ops -- ---------------------- procedure Set_Num_Prim_Ops (T : Tag; Value : Natural) is begin pragma Assert (Check_Signature (T, Must_Be_Primary_Or_Secondary_DT)); if Is_Primary_DT (T) then TSD (T).Num_Prim_Ops := Value; else OSD (T).Num_Prim_Ops := Value; end if; end Set_Num_Prim_Ops; ---------------------- -- Set_Offset_Index -- ---------------------- procedure Set_Offset_Index (T : Tag; Position : Positive; Value : Positive) is begin pragma Assert (Check_Signature (T, Must_Be_Secondary_DT)); pragma Assert (Position <= Get_Num_Prim_Ops (T)); OSD (T).OSD_Table (Position) := Value; end Set_Offset_Index; ----------------------- -- Set_Offset_To_Top -- ----------------------- procedure Set_Offset_To_Top (This : System.Address; Interface_T : Tag; Is_Static : Boolean; Offset_Value : System.Storage_Elements.Storage_Offset; Offset_Func : System.Address) is Prim_DT : Tag; Sec_Base : System.Address; Sec_DT : Tag; Offset_To_Top : Storage_Offset_Ptr; Iface_Table : Interface_Data_Ptr; Obj_TSD : Type_Specific_Data_Ptr; begin if System.""="" (This, System.Null_Address) then pragma Assert (Check_Signature (Interface_T, Must_Be_Primary_DT)); pragma Assert (Offset_Value = 0); Offset_To_Top := To_Storage_Offset_Ptr (To_Address (Interface_T) - K_Offset_To_Top); Offset_To_Top.all := Offset_Value; return; end if; -- ""This"" points to the primary DT and we must save Offset_Value in the -- Offset_To_Top field of the corresponding secondary dispatch table. Prim_DT := To_Tag_Ptr (This).all; pragma Assert (Check_Signature (Prim_DT, Must_Be_Primary_DT)); Sec_Base := This + Offset_Value; Sec_DT := To_Tag_Ptr (Sec_Base).all; Offset_To_Top := To_Storage_Offset_Ptr (To_Address (Sec_DT) - K_Offset_To_Top); pragma Assert (Check_Signature (Sec_DT, Must_Be_Secondary_DT)); if Is_Static then Offset_To_Top.all := Offset_Value; else Offset_To_Top.all := SSE.Storage_Offset'Last; end if; -- Save Offset_Value in the table of interfaces of the primary DT. This -- data will be used by the subprogram ""Displace"" to give support to -- backward abstract interface type conversions. Obj_TSD := TSD (Prim_DT); Iface_Table := To_Interface_Data_Ptr (Obj_TSD.Ifaces_Table_Ptr); -- Register the offset in the table of interfaces if Iface_Table /= null then for Id in 1 .. Iface_Table.Nb_Ifaces loop if Iface_Table.Table (Id).Iface_Tag = Interface_T then Iface_Table.Table (Id).Static_Offset_To_Top := Is_Static; if Is_Static then Iface_Table.Table (Id).Offset_To_Top_Value := Offset_Value; else Iface_Table.Table (Id).Offset_To_Top_Func := Offset_Func; end if; return; end if; end loop; end if; -- If we arrive here there is some error in the run-time data structure raise Program_Error; end Set_Offset_To_Top; ------------- -- Set_OSD -- ------------- procedure Set_OSD (T : Tag; Value : System.Address) is OSD_Ptr : constant Addr_Ptr := To_Addr_Ptr (To_Address (T) - K_Typeinfo); begin pragma Assert (Check_Signature (T, Must_Be_Secondary_DT)); OSD_Ptr.all := Value; end Set_OSD; ------------------------------------ -- Set_Predefined_Prim_Op_Address -- ------------------------------------ procedure Set_Predefined_Prim_Op_Address (T : Tag; Position : Positive; Value : System.Address) is Prim_Ops_DT : constant Tag := To_Tag (To_Address (T) - DT_Prologue_Size); begin pragma Assert (Check_Signature (T, Must_Be_Primary_Or_Secondary_DT)); pragma Assert (Position >= 1 and then Position <= Default_Prim_Op_Count); Prim_Ops_DT.Prims_Ptr (Position) := Value; end Set_Predefined_Prim_Op_Address; ------------------------- -- Set_Prim_Op_Address -- ------------------------- procedure Set_Prim_Op_Address (T : Tag; Position : Positive; Value : System.Address) is begin pragma Assert (Check_Signature (T, Must_Be_Primary_Or_Secondary_DT)); pragma Assert (Position <= Get_Num_Prim_Ops (T)); T.Prims_Ptr (Position) := Value; end Set_Prim_Op_Address; ---------------------- -- Set_Prim_Op_Kind -- ---------------------- procedure Set_Prim_Op_Kind (T : Tag; Position : Positive; Value : Prim_Op_Kind) is begin pragma Assert (Check_Signature (T, Must_Be_Primary_DT)); pragma Assert (Position <= Get_Num_Prim_Ops (T)); SSD (T).SSD_Table (Position).Kind := Value; end Set_Prim_Op_Kind; ------------------- -- Set_RC_Offset -- ------------------- procedure Set_RC_Offset (T : Tag; Value : SSE.Storage_Offset) is begin pragma Assert (Check_Signature (T, Must_Be_Primary_DT)); TSD (T).RC_Offset := Value; end Set_RC_Offset; --------------------------- -- Set_Remotely_Callable -- --------------------------- procedure Set_Remotely_Callable (T : Tag; Value : Boolean) is begin pragma Assert (Check_Signature (T, Must_Be_Primary_DT)); TSD (T).Remotely_Callable := Value; end Set_Remotely_Callable; ------------------- -- Set_Signature -- ------------------- procedure Set_Signature (T : Tag; Value : Signature_Kind) is Signature : constant System.Address := To_Address (T) - K_Signature; Sig_Ptr : constant Signature_Values_Ptr := To_Signature_Values_Ptr (Signature); begin Sig_Ptr.all (1) := Valid_Signature; Sig_Ptr.all (2) := Value; end Set_Signature; ------------- -- Set_SSD -- ------------- procedure Set_SSD (T : Tag; Value : System.Address) is begin pragma Assert (Check_Signature (T, Must_Be_Primary_DT)); TSD (T).SSD_Ptr := Value; end Set_SSD; --------------------- -- Set_Tagged_Kind -- --------------------- procedure Set_Tagged_Kind (T : Tag; Value : Tagged_Kind) is Tagged_Kind_Ptr : constant System.Address := To_Address (T) - K_Tagged_Kind; begin pragma Assert (Check_Signature (T, Must_Be_Primary_Or_Secondary_DT)); To_Tagged_Kind_Ptr (Tagged_Kind_Ptr).all := Value; end Set_Tagged_Kind; ------------- -- Set_TSD -- ------------- procedure Set_TSD (T : Tag; Value : System.Address) is TSD_Ptr : Addr_Ptr; begin pragma Assert (Check_Signature (T, Must_Be_Primary_Or_Interface)); TSD_Ptr := To_Addr_Ptr (To_Address (T) - K_Typeinfo); TSD_Ptr.all := Value; end Set_TSD; --------- -- SSD -- --------- function SSD (T : Tag) return Select_Specific_Data_Ptr is begin pragma Assert (Check_Signature (T, Must_Be_Primary_DT)); return To_Select_Specific_Data_Ptr (TSD (T).SSD_Ptr); end SSD; ------------------ -- Typeinfo_Ptr -- ------------------ function Typeinfo_Ptr (T : Tag) return System.Address is TSD_Ptr : constant Addr_Ptr := To_Addr_Ptr (To_Address (T) - K_Typeinfo); begin return TSD_Ptr.all; end Typeinfo_Ptr; --------- -- TSD -- --------- function TSD (T : Tag) return Type_Specific_Data_Ptr is TSD_Ptr : constant Addr_Ptr := To_Addr_Ptr (To_Address (T) - K_Typeinfo); begin pragma Assert (Check_Signature (T, Must_Be_Primary_Or_Interface)); return To_Type_Specific_Data_Ptr (TSD_Ptr.all); end TSD; ------------------------ -- Wide_Expanded_Name -- ------------------------ WC_Encoding : Character; pragma Import (C, WC_Encoding, ""__gl_wc_encoding""); -- Encoding method for source, as exported by binder function Wide_Expanded_Name (T : Tag) return Wide_String is begin return String_To_Wide_String (Expanded_Name (T), Get_WC_Encoding_Method (WC_Encoding)); end Wide_Expanded_Name; ----------------------------- -- Wide_Wide_Expanded_Name -- ----------------------------- function Wide_Wide_Expanded_Name (T : Tag) return Wide_Wide_String is begin return String_To_Wide_Wide_String (Expanded_Name (T), Get_WC_Encoding_Method (WC_Encoding)); end Wide_Wide_Expanded_Name; end Ada.Tags; ",12312,False,2269.5814941002154,median "[[kafka-component]] = Kafka Component :page-source: components/camel-kafka/src/main/docs/kafka-component.adoc *Since Camel 2.13* The Kafka component is used for communicating with http://kafka.apache.org/[Apache Kafka] message broker. Maven users will need to add the following dependency to their `pom.xml` for this component. [source,xml] ------------------------------------------------------------ org.apache.camel camel-kafka x.x.x ------------------------------------------------------------ == URI format [source,java] --------------------------- kafka:topic[?options] --------------------------- == Options // component options: START The Kafka component supports 8 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *configuration* (common) | Allows to pre-configure the Kafka component with common options that the endpoints will reuse. | | KafkaConfiguration | *brokers* (common) | URL of the Kafka brokers to use. The format is host1:port1,host2:port2, and the list can be a subset of brokers or a VIP pointing to a subset of brokers. This option is known as bootstrap.servers in the Kafka documentation. | | String | *workerPool* (advanced) | To use a shared custom worker pool for continue routing Exchange after kafka server has acknowledge the message that was sent to it from KafkaProducer using asynchronous non-blocking processing. If using this option then you must handle the lifecycle of the thread pool to shut the pool down when no longer needed. | | ExecutorService | *useGlobalSslContext Parameters* (security) | Enable usage of global SSL context parameters. | false | boolean | *breakOnFirstError* (consumer) | This options controls what happens when a consumer is processing an exchange and it fails. If the option is false then the consumer continues to the next message and processes it. If the option is true then the consumer breaks out, and will seek back to offset of the message that caused a failure, and then re-attempt to process this message. However this can lead to endless processing of the same message if its bound to fail every time, eg a poison message. Therefore its recommended to deal with that for example by using Camel's error handler. | false | boolean | *allowManualCommit* (consumer) | Whether to allow doing manual commits via KafkaManualCommit. If this option is enabled then an instance of KafkaManualCommit is stored on the Exchange message header, which allows end users to access this API and perform manual offset commits via the Kafka consumer. | false | boolean | *kafkaManualCommit Factory* (consumer) | Factory to use for creating KafkaManualCommit instances. This allows to plugin a custom factory to create custom KafkaManualCommit instances in case special logic is needed when doing manual commits that deviates from the default implementation that comes out of the box. | | KafkaManualCommitFactory | *basicPropertyBinding* (advanced) | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean |=== // component options: END // endpoint options: START The Kafka endpoint is configured using URI syntax: ---- kafka:topic ---- with the following path and query parameters: === Path Parameters (1 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *topic* | *Required* Name of the topic to use. On the consumer you can use comma to separate multiple topics. A producer can only send a message to a single topic. | | String |=== === Query Parameters (95 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *brokers* (common) | URL of the Kafka brokers to use. The format is host1:port1,host2:port2, and the list can be a subset of brokers or a VIP pointing to a subset of brokers. This option is known as bootstrap.servers in the Kafka documentation. | | String | *clientId* (common) | The client id is a user-specified string sent in each request to help trace calls. It should logically identify the application making the request. | | String | *headerFilterStrategy* (common) | To use a custom HeaderFilterStrategy to filter header to and from Camel message. | | HeaderFilterStrategy | *reconnectBackoffMaxMs* (common) | The maximum amount of time in milliseconds to wait when reconnecting to a broker that has repeatedly failed to connect. If provided, the backoff per host will increase exponentially for each consecutive connection failure, up to this maximum. After calculating the backoff increase, 20% random jitter is added to avoid connection storms. | 1000 | Integer | *allowManualCommit* (consumer) | Whether to allow doing manual commits via KafkaManualCommit. If this option is enabled then an instance of KafkaManualCommit is stored on the Exchange message header, which allows end users to access this API and perform manual offset commits via the Kafka consumer. | false | boolean | *autoCommitEnable* (consumer) | If true, periodically commit to ZooKeeper the offset of messages already fetched by the consumer. This committed offset will be used when the process fails as the position from which the new consumer will begin. | true | Boolean | *autoCommitIntervalMs* (consumer) | The frequency in ms that the consumer offsets are committed to zookeeper. | 5000 | Integer | *autoCommitOnStop* (consumer) | Whether to perform an explicit auto commit when the consumer stops to ensure the broker has a commit from the last consumed message. This requires the option autoCommitEnable is turned on. The possible values are: sync, async, or none. And sync is the default value. | sync | String | *autoOffsetReset* (consumer) | What to do when there is no initial offset in ZooKeeper or if an offset is out of range: earliest : automatically reset the offset to the earliest offset latest : automatically reset the offset to the latest offset fail: throw exception to the consumer | latest | String | *breakOnFirstError* (consumer) | This options controls what happens when a consumer is processing an exchange and it fails. If the option is false then the consumer continues to the next message and processes it. If the option is true then the consumer breaks out, and will seek back to offset of the message that caused a failure, and then re-attempt to process this message. However this can lead to endless processing of the same message if its bound to fail every time, eg a poison message. Therefore its recommended to deal with that for example by using Camel's error handler. | false | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *checkCrcs* (consumer) | Automatically check the CRC32 of the records consumed. This ensures no on-the-wire or on-disk corruption to the messages occurred. This check adds some overhead, so it may be disabled in cases seeking extreme performance. | true | Boolean | *consumerRequestTimeoutMs* (consumer) | The configuration controls the maximum amount of time the client will wait for the response of a request. If the response is not received before the timeout elapses the client will resend the request if necessary or fail the request if retries are exhausted. | 40000 | Integer | *consumersCount* (consumer) | The number of consumers that connect to kafka server | 1 | int | *consumerStreams* (consumer) | Number of concurrent consumers on the consumer | 10 | int | *fetchMaxBytes* (consumer) | The maximum amount of data the server should return for a fetch request This is not an absolute maximum, if the first message in the first non-empty partition of the fetch is larger than this value, the message will still be returned to ensure that the consumer can make progress. The maximum message size accepted by the broker is defined via message.max.bytes (broker config) or max.message.bytes (topic config). Note that the consumer performs multiple fetches in parallel. | 52428800 | Integer | *fetchMinBytes* (consumer) | The minimum amount of data the server should return for a fetch request. If insufficient data is available the request will wait for that much data to accumulate before answering the request. | 1 | Integer | *fetchWaitMaxMs* (consumer) | The maximum amount of time the server will block before answering the fetch request if there isn't sufficient data to immediately satisfy fetch.min.bytes | 500 | Integer | *groupId* (consumer) | A string that uniquely identifies the group of consumer processes to which this consumer belongs. By setting the same group id multiple processes indicate that they are all part of the same consumer group. This option is required for consumers. | | String | *heartbeatIntervalMs* (consumer) | The expected time between heartbeats to the consumer coordinator when using Kafka's group management facilities. Heartbeats are used to ensure that the consumer's session stays active and to facilitate rebalancing when new consumers join or leave the group. The value must be set lower than session.timeout.ms, but typically should be set no higher than 1/3 of that value. It can be adjusted even lower to control the expected time for normal rebalances. | 3000 | Integer | *kafkaHeaderDeserializer* (consumer) | Sets custom KafkaHeaderDeserializer for deserialization kafka headers values to camel headers values. | | KafkaHeaderDeserializer | *keyDeserializer* (consumer) | Deserializer class for key that implements the Deserializer interface. | org.apache.kafka.common.serialization.StringDeserializer | String | *maxPartitionFetchBytes* (consumer) | The maximum amount of data per-partition the server will return. The maximum total memory used for a request will be #partitions max.partition.fetch.bytes. This size must be at least as large as the maximum message size the server allows or else it is possible for the producer to send messages larger than the consumer can fetch. If that happens, the consumer can get stuck trying to fetch a large message on a certain partition. | 1048576 | Integer | *maxPollIntervalMs* (consumer) | The maximum delay between invocations of poll() when using consumer group management. This places an upper bound on the amount of time that the consumer can be idle before fetching more records. If poll() is not called before expiration of this timeout, then the consumer is considered failed and the group will rebalance in order to reassign the partitions to another member. | | Long | *maxPollRecords* (consumer) | The maximum number of records returned in a single call to poll() | 500 | Integer | *offsetRepository* (consumer) | The offset repository to use in order to locally store the offset of each partition of the topic. Defining one will disable the autocommit. | | StateRepository | *partitionAssignor* (consumer) | The class name of the partition assignment strategy that the client will use to distribute partition ownership amongst consumer instances when group management is used | org.apache.kafka.clients.consumer.RangeAssignor | String | *pollTimeoutMs* (consumer) | The timeout used when polling the KafkaConsumer. | 5000 | Long | *seekTo* (consumer) | Set if KafkaConsumer will read from beginning or end on startup: beginning : read from beginning end : read from end This is replacing the earlier property seekToBeginning | | String | *sessionTimeoutMs* (consumer) | The timeout used to detect failures when using Kafka's group management facilities. | 10000 | Integer | *specificAvroReader* (consumer) | This enables the use of a specific Avro reader for use with the Confluent Platform schema registry and the io.confluent.kafka.serializers.KafkaAvroDeserializer. This option is only available in the Confluent Platform (not standard Apache Kafka) | false | boolean | *topicIsPattern* (consumer) | Whether the topic is a pattern (regular expression). This can be used to subscribe to dynamic number of topics matching the pattern. | false | boolean | *valueDeserializer* (consumer) | Deserializer class for value that implements the Deserializer interface. | org.apache.kafka.common.serialization.StringDeserializer | String | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. | | ExchangePattern | *bufferMemorySize* (producer) | The total bytes of memory the producer can use to buffer records waiting to be sent to the server. If records are sent faster than they can be delivered to the server the producer will either block or throw an exception based on the preference specified by block.on.buffer.full.This setting should correspond roughly to the total memory the producer will use, but is not a hard bound since not all memory the producer uses is used for buffering. Some additional memory will be used for compression (if compression is enabled) as well as for maintaining in-flight requests. | 33554432 | Integer | *compressionCodec* (producer) | This parameter allows you to specify the compression codec for all data generated by this producer. Valid values are none, gzip and snappy. | none | String | *connectionMaxIdleMs* (producer) | Close idle connections after the number of milliseconds specified by this config. | 540000 | Integer | *enableIdempotence* (producer) | If set to 'true' the producer will ensure that exactly one copy of each message is written in the stream. If 'false', producer retries may write duplicates of the retried message in the stream. If set to true this option will require max.in.flight.requests.per.connection to be set to 1 and retries cannot be zero and additionally acks must be set to 'all'. | false | boolean | *kafkaHeaderSerializer* (producer) | Sets custom KafkaHeaderDeserializer for serialization camel headers values to kafka headers values. | | KafkaHeaderSerializer | *key* (producer) | The record key (or null if no key is specified). If this option has been configured then it take precedence over header KafkaConstants#KEY | | String | *keySerializerClass* (producer) | The serializer class for keys (defaults to the same as for messages if nothing is given). | org.apache.kafka.common.serialization.StringSerializer | String | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *lingerMs* (producer) | The producer groups together any records that arrive in between request transmissions into a single batched request. Normally this occurs only under load when records arrive faster than they can be sent out. However in some circumstances the client may want to reduce the number of requests even under moderate load. This setting accomplishes this by adding a small amount of artificial delaythat is, rather than immediately sending out a record the producer will wait for up to the given delay to allow other records to be sent so that the sends can be batched together. This can be thought of as analogous to Nagle's algorithm in TCP. This setting gives the upper bound on the delay for batching: once we get batch.size worth of records for a partition it will be sent immediately regardless of this setting, however if we have fewer than this many bytes accumulated for this partition we will 'linger' for the specified time waiting for more records to show up. This setting defaults to 0 (i.e. no delay). Setting linger.ms=5, for example, would have the effect of reducing the number of requests sent but would add up to 5ms of latency to records sent in the absense of load. | 0 | Integer | *maxBlockMs* (producer) | The configuration controls how long sending to kafka will block. These methods can be blocked for multiple reasons. For e.g: buffer full, metadata unavailable.This configuration imposes maximum limit on the total time spent in fetching metadata, serialization of key and value, partitioning and allocation of buffer memory when doing a send(). In case of partitionsFor(), this configuration imposes a maximum time threshold on waiting for metadata | 60000 | Integer | *maxInFlightRequest* (producer) | The maximum number of unacknowledged requests the client will send on a single connection before blocking. Note that if this setting is set to be greater than 1 and there are failed sends, there is a risk of message re-ordering due to retries (i.e., if retries are enabled). | 5 | Integer | *maxRequestSize* (producer) | The maximum size of a request. This is also effectively a cap on the maximum record size. Note that the server has its own cap on record size which may be different from this. This setting will limit the number of record batches the producer will send in a single request to avoid sending huge requests. | 1048576 | Integer | *metadataMaxAgeMs* (producer) | The period of time in milliseconds after which we force a refresh of metadata even if we haven't seen any partition leadership changes to proactively discover any new brokers or partitions. | 300000 | Integer | *metricReporters* (producer) | A list of classes to use as metrics reporters. Implementing the MetricReporter interface allows plugging in classes that will be notified of new metric creation. The JmxReporter is always included to register JMX statistics. | | String | *metricsSampleWindowMs* (producer) | The number of samples maintained to compute metrics. | 30000 | Integer | *noOfMetricsSample* (producer) | The number of samples maintained to compute metrics. | 2 | Integer | *partitioner* (producer) | The partitioner class for partitioning messages amongst sub-topics. The default partitioner is based on the hash of the key. | org.apache.kafka.clients.producer.internals.DefaultPartitioner | String | *partitionKey* (producer) | The partition to which the record will be sent (or null if no partition was specified). If this option has been configured then it take precedence over header KafkaConstants#PARTITION_KEY | | Integer | *producerBatchSize* (producer) | The producer will attempt to batch records together into fewer requests whenever multiple records are being sent to the same partition. This helps performance on both the client and the server. This configuration controls the default batch size in bytes. No attempt will be made to batch records larger than this size.Requests sent to brokers will contain multiple batches, one for each partition with data available to be sent.A small batch size will make batching less common and may reduce throughput (a batch size of zero will disable batching entirely). A very large batch size may use memory a bit more wastefully as we will always allocate a buffer of the specified batch size in anticipation of additional records. | 16384 | Integer | *queueBufferingMaxMessages* (producer) | The maximum number of unsent messages that can be queued up the producer when using async mode before either the producer must be blocked or data must be dropped. | 10000 | Integer | *receiveBufferBytes* (producer) | The size of the TCP receive buffer (SO_RCVBUF) to use when reading data. | 65536 | Integer | *reconnectBackoffMs* (producer) | The amount of time to wait before attempting to reconnect to a given host. This avoids repeatedly connecting to a host in a tight loop. This backoff applies to all requests sent by the consumer to the broker. | 50 | Integer | *recordMetadata* (producer) | Whether the producer should store the RecordMetadata results from sending to Kafka. The results are stored in a List containing the RecordMetadata metadata's. The list is stored on a header with the key KafkaConstants#KAFKA_RECORDMETA | true | boolean | *requestRequiredAcks* (producer) | The number of acknowledgments the producer requires the leader to have received before considering a request complete. This controls the durability of records that are sent. The following settings are common: acks=0 If set to zero then the producer will not wait for any acknowledgment from the server at all. The record will be immediately added to the socket buffer and considered sent. No guarantee can be made that the server has received the record in this case, and the retries configuration will not take effect (as the client won't generally know of any failures). The offset given back for each record will always be set to -1. acks=1 This will mean the leader will write the record to its local log but will respond without awaiting full acknowledgement from all followers. In this case should the leader fail immediately after acknowledging the record but before the followers have replicated it then the record will be lost. acks=all This means the leader will wait for the full set of in-sync replicas to acknowledge the record. This guarantees that the record will not be lost as long as at least one in-sync replica remains alive. This is the strongest available guarantee. | 1 | String | *requestTimeoutMs* (producer) | The amount of time the broker will wait trying to meet the request.required.acks requirement before sending back an error to the client. | 305000 | Integer | *retries* (producer) | Setting a value greater than zero will cause the client to resend any record whose send fails with a potentially transient error. Note that this retry is no different than if the client resent the record upon receiving the error. Allowing retries will potentially change the ordering of records because if two records are sent to a single partition, and the first fails and is retried but the second succeeds, then the second record may appear first. | 0 | Integer | *retryBackoffMs* (producer) | Before each retry, the producer refreshes the metadata of relevant topics to see if a new leader has been elected. Since leader election takes a bit of time, this property specifies the amount of time that the producer waits before refreshing the metadata. | 100 | Integer | *sendBufferBytes* (producer) | Socket write buffer size | 131072 | Integer | *serializerClass* (producer) | The serializer class for messages. | org.apache.kafka.common.serialization.StringSerializer | String | *workerPool* (producer) | To use a custom worker pool for continue routing Exchange after kafka server has acknowledge the message that was sent to it from KafkaProducer using asynchronous non-blocking processing. | | ExecutorService | *workerPoolCoreSize* (producer) | Number of core threads for the worker pool for continue routing Exchange after kafka server has acknowledge the message that was sent to it from KafkaProducer using asynchronous non-blocking processing. | 10 | Integer | *workerPoolMaxSize* (producer) | Maximum number of threads for the worker pool for continue routing Exchange after kafka server has acknowledge the message that was sent to it from KafkaProducer using asynchronous non-blocking processing. | 20 | Integer | *basicPropertyBinding* (advanced) | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *interceptorClasses* (monitoring) | Sets interceptors for producer or consumers. Producer interceptors have to be classes implementing org.apache.kafka.clients.producer.ProducerInterceptor Consumer interceptors have to be classes implementing org.apache.kafka.clients.consumer.ConsumerInterceptor Note that if you use Producer interceptor on a consumer it will throw a class cast exception in runtime | | String | *kerberosBeforeReloginMin Time* (security) | Login thread sleep time between refresh attempts. | 60000 | Integer | *kerberosInitCmd* (security) | Kerberos kinit command path. Default is /usr/bin/kinit | /usr/bin/kinit | String | *kerberosPrincipalToLocal Rules* (security) | A list of rules for mapping from principal names to short names (typically operating system usernames). The rules are evaluated in order and the first rule that matches a principal name is used to map it to a short name. Any later rules in the list are ignored. By default, principal names of the form \\{username\\}/\\{hostname\\}\\{REALM\\} are mapped to \\{username\\}. For more details on the format please see the security authorization and acls documentation.. Multiple values can be separated by comma | DEFAULT | String | *kerberosRenewJitter* (security) | Percentage of random jitter added to the renewal time. | 0.05 | Double | *kerberosRenewWindowFactor* (security) | Login thread will sleep until the specified window factor of time from last refresh to ticket's expiry has been reached, at which time it will try to renew the ticket. | 0.8 | Double | *saslJaasConfig* (security) | Expose the kafka sasl.jaas.config parameter Example: org.apache.kafka.common.security.plain.PlainLoginModule required username=USERNAME password=PASSWORD; | | String | *saslKerberosServiceName* (security) | The Kerberos principal name that Kafka runs as. This can be defined either in Kafka's JAAS config or in Kafka's config. | | String | *saslMechanism* (security) | The Simple Authentication and Security Layer (SASL) Mechanism used. For the valid values see a href= \\http://www.iana.org/assignments/sasl-mechanisms/sasl-mechanisms.xhtml\\http://www.iana.org/assignments/sasl-mechanisms/sasl-mechanisms.xhtml | GSSAPI | String | *securityProtocol* (security) | Protocol used to communicate with brokers. SASL_PLAINTEXT, PLAINTEXT and SSL are supported | PLAINTEXT | String | *sslCipherSuites* (security) | A list of cipher suites. This is a named combination of authentication, encryption, MAC and key exchange algorithm used to negotiate the security settings for a network connection using TLS or SSL network protocol.By default all the available cipher suites are supported. | | String | *sslContextParameters* (security) | SSL configuration using a Camel SSLContextParameters object. If configured it's applied before the other SSL endpoint parameters. | | SSLContextParameters | *sslEnabledProtocols* (security) | The list of protocols enabled for SSL connections. TLSv1.2, TLSv1.1 and TLSv1 are enabled by default. | TLSv1.2,TLSv1.1,TLSv1 | String | *sslEndpointAlgorithm* (security) | The endpoint identification algorithm to validate server hostname using server certificate. | | String | *sslKeymanagerAlgorithm* (security) | The algorithm used by key manager factory for SSL connections. Default value is the key manager factory algorithm configured for the Java Virtual Machine. | SunX509 | String | *sslKeyPassword* (security) | The password of the private key in the key store file. This is optional for client. | | String | *sslKeystoreLocation* (security) | The location of the key store file. This is optional for client and can be used for two-way authentication for client. | | String | *sslKeystorePassword* (security) | The store password for the key store file.This is optional for client and only needed if ssl.keystore.location is configured. | | String | *sslKeystoreType* (security) | The file format of the key store file. This is optional for client. Default value is JKS | JKS | String | *sslProtocol* (security) | The SSL protocol used to generate the SSLContext. Default setting is TLS, which is fine for most cases. Allowed values in recent JVMs are TLS, TLSv1.1 and TLSv1.2. SSL, SSLv2 and SSLv3 may be supported in older JVMs, but their usage is discouraged due to known security vulnerabilities. | TLS | String | *sslProvider* (security) | The name of the security provider used for SSL connections. Default value is the default security provider of the JVM. | | String | *sslTrustmanagerAlgorithm* (security) | The algorithm used by trust manager factory for SSL connections. Default value is the trust manager factory algorithm configured for the Java Virtual Machine. | PKIX | String | *sslTruststoreLocation* (security) | The location of the trust store file. | | String | *sslTruststoreType* (security) | The file format of the trust store file. Default value is JKS. | JKS | String | *schemaRegistryURL* (confluent) | URL of the Confluent Platform schema registry servers to use. The format is host1:port1,host2:port2. This is known as schema.registry.url in the Confluent Platform documentation. This option is only available in the Confluent Platform (not standard Apache Kafka) | | String | *sslTruststorePassword* (security) | The password for the trust store file. | | String |=== // endpoint options: END // spring-boot-auto-configure options: START == Spring Boot Auto-Configuration When using Spring Boot make sure to use the following Maven dependency to have support for auto configuration: [source,xml] ---- org.apache.camel camel-kafka-starter x.x.x ---- The component supports 98 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.component.kafka.allow-manual-commit* | Whether to allow doing manual commits via KafkaManualCommit. If this option is enabled then an instance of KafkaManualCommit is stored on the Exchange message header, which allows end users to access this API and perform manual offset commits via the Kafka consumer. | false | Boolean | *camel.component.kafka.basic-property-binding* | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | Boolean | *camel.component.kafka.break-on-first-error* | This options controls what happens when a consumer is processing an exchange and it fails. If the option is false then the consumer continues to the next message and processes it. If the option is true then the consumer breaks out, and will seek back to offset of the message that caused a failure, and then re-attempt to process this message. However this can lead to endless processing of the same message if its bound to fail every time, eg a poison message. Therefore its recommended to deal with that for example by using Camel's error handler. | false | Boolean | *camel.component.kafka.brokers* | URL of the Kafka brokers to use. The format is host1:port1,host2:port2, and the list can be a subset of brokers or a VIP pointing to a subset of brokers. This option is known as bootstrap.servers in the Kafka documentation. | | String | *camel.component.kafka.configuration.allow-manual-commit* | Whether to allow doing manual commits via {@link KafkaManualCommit}.

If this option is enabled then an instance of {@link KafkaManualCommit} is stored on the {@link Exchange} message header, which allows end users to access this API and perform manual offset commits via the Kafka consumer. | false | Boolean | *camel.component.kafka.configuration.auto-commit-enable* | If true, periodically commit to ZooKeeper the offset of messages already fetched by the consumer. This committed offset will be used when the process fails as the position from which the new consumer will begin. | true | Boolean | *camel.component.kafka.configuration.auto-commit-interval-ms* | The frequency in ms that the consumer offsets are committed to zookeeper. | 5000 | Integer | *camel.component.kafka.configuration.auto-commit-on-stop* | Whether to perform an explicit auto commit when the consumer stops to ensure the broker has a commit from the last consumed message. This requires the option autoCommitEnable is turned on. The possible values are: sync, async, or none. And sync is the default value. | sync | String | *camel.component.kafka.configuration.auto-offset-reset* | What to do when there is no initial offset in ZooKeeper or if an offset is out of range: earliest : automatically reset the offset to the earliest offset latest : automatically reset the offset to the latest offset fail: throw exception to the consumer | latest | String | *camel.component.kafka.configuration.break-on-first-error* | This options controls what happens when a consumer is processing an exchange and it fails. If the option is false then the consumer continues to the next message and processes it. If the option is true then the consumer breaks out, and will seek back to offset of the message that caused a failure, and then re-attempt to process this message. However this can lead to endless processing of the same message if its bound to fail every time, eg a poison message. Therefore its recommended to deal with that for example by using Camel's error handler. | false | Boolean | *camel.component.kafka.configuration.brokers* | URL of the Kafka brokers to use. The format is host1:port1,host2:port2, and the list can be a subset of brokers or a VIP pointing to a subset of brokers.

This option is known as bootstrap.servers in the Kafka documentation. | | String | *camel.component.kafka.configuration.buffer-memory-size* | The total bytes of memory the producer can use to buffer records waiting to be sent to the server. If records are sent faster than they can be delivered to the server the producer will either block or throw an exception based on the preference specified by block.on.buffer.full.This setting should correspond roughly to the total memory the producer will use, but is not a hard bound since not all memory the producer uses is used for buffering. Some additional memory will be used for compression (if compression is enabled) as well as for maintaining in-flight requests. | 33554432 | Integer | *camel.component.kafka.configuration.check-crcs* | Automatically check the CRC32 of the records consumed. This ensures no on-the-wire or on-disk corruption to the messages occurred. This check adds some overhead, so it may be disabled in cases seeking extreme performance. | true | Boolean | *camel.component.kafka.configuration.client-id* | The client id is a user-specified string sent in each request to help trace calls. It should logically identify the application making the request. | | String | *camel.component.kafka.configuration.compression-codec* | This parameter allows you to specify the compression codec for all data generated by this producer. Valid values are ""none"", ""gzip"" and ""snappy"". | none | String | *camel.component.kafka.configuration.connection-max-idle-ms* | Close idle connections after the number of milliseconds specified by this config. | 540000 | Integer | *camel.component.kafka.configuration.consumer-request-timeout-ms* | The configuration controls the maximum amount of time the client will wait for the response of a request. If the response is not received before the timeout elapses the client will resend the request if necessary or fail the request if retries are exhausted. | 40000 | Integer | *camel.component.kafka.configuration.consumer-streams* | Number of concurrent consumers on the consumer | 10 | Integer | *camel.component.kafka.configuration.consumers-count* | The number of consumers that connect to kafka server | 1 | Integer | *camel.component.kafka.configuration.enable-idempotence* | If set to 'true' the producer will ensure that exactly one copy of each message is written in the stream. If 'false', producer retries may write duplicates of the retried message in the stream. If set to true this option will require max.in.flight.requests.per.connection to be set to 1 and retries cannot be zero and additionally acks must be set to 'all'. | false | Boolean | *camel.component.kafka.configuration.fetch-max-bytes* | The maximum amount of data the server should return for a fetch request This is not an absolute maximum, if the first message in the first non-empty partition of the fetch is larger than this value, the message will still be returned to ensure that the consumer can make progress. The maximum message size accepted by the broker is defined via message.max.bytes (broker config) or max.message.bytes (topic config). Note that the consumer performs multiple fetches in parallel. | 52428800 | Integer | *camel.component.kafka.configuration.fetch-min-bytes* | The minimum amount of data the server should return for a fetch request. If insufficient data is available the request will wait for that much data to accumulate before answering the request. | 1 | Integer | *camel.component.kafka.configuration.fetch-wait-max-ms* | The maximum amount of time the server will block before answering the fetch request if there isn't sufficient data to immediately satisfy fetch.min.bytes | 500 | Integer | *camel.component.kafka.configuration.group-id* | A string that uniquely identifies the group of consumer processes to which this consumer belongs. By setting the same group id multiple processes indicate that they are all part of the same consumer group. This option is required for consumers. | | String | *camel.component.kafka.configuration.header-filter-strategy* | To use a custom HeaderFilterStrategy to filter header to and from Camel message. | | HeaderFilterStrategy | *camel.component.kafka.configuration.heartbeat-interval-ms* | The expected time between heartbeats to the consumer coordinator when using Kafka's group management facilities. Heartbeats are used to ensure that the consumer's session stays active and to facilitate rebalancing when new consumers join or leave the group. The value must be set lower than session.timeout.ms, but typically should be set no higher than 1/3 of that value. It can be adjusted even lower to control the expected time for normal rebalances. | 3000 | Integer | *camel.component.kafka.configuration.interceptor-classes* | Sets interceptors for producer or consumers. Producer interceptors have to be classes implementing {@link org.apache.kafka.clients.producer.ProducerInterceptor} Consumer interceptors have to be classes implementing {@link org.apache.kafka.clients.consumer.ConsumerInterceptor} Note that if you use Producer interceptor on a consumer it will throw a class cast exception in runtime | | String | *camel.component.kafka.configuration.kafka-header-deserializer* | Sets custom KafkaHeaderDeserializer for deserialization kafka headers values to camel headers values. | | KafkaHeaderDeserializer | *camel.component.kafka.configuration.kafka-header-serializer* | Sets custom KafkaHeaderDeserializer for serialization camel headers values to kafka headers values. | | KafkaHeaderSerializer | *camel.component.kafka.configuration.kerberos-before-relogin-min-time* | Login thread sleep time between refresh attempts. | 60000 | Integer | *camel.component.kafka.configuration.kerberos-init-cmd* | Kerberos kinit command path. Default is /usr/bin/kinit | /usr/bin/kinit | String | *camel.component.kafka.configuration.kerberos-principal-to-local-rules* | A list of rules for mapping from principal names to short names (typically operating system usernames). The rules are evaluated in order and the first rule that matches a principal name is used to map it to a short name. Any later rules in the list are ignored. By default, principal names of the form \\{username\\}/\\{hostname\\}@\\{REALM\\} are mapped to \\{username\\}. For more details on the format please see the security authorization and acls documentation..

Multiple values can be separated by comma | DEFAULT | String | *camel.component.kafka.configuration.kerberos-renew-jitter* | Percentage of random jitter added to the renewal time. | 0.05 | Double | *camel.component.kafka.configuration.kerberos-renew-window-factor* | Login thread will sleep until the specified window factor of time from last refresh to ticket's expiry has been reached, at which time it will try to renew the ticket. | 0.8 | Double | *camel.component.kafka.configuration.key* | The record key (or null if no key is specified). If this option has been configured then it take precedence over header {@link KafkaConstants#KEY} | | String | *camel.component.kafka.configuration.key-deserializer* | Deserializer class for key that implements the Deserializer interface. | org.apache.kafka.common.serialization.StringDeserializer | String | *camel.component.kafka.configuration.key-serializer-class* | The serializer class for keys (defaults to the same as for messages if nothing is given). | org.apache.kafka.common.serialization.StringSerializer | String | *camel.component.kafka.configuration.linger-ms* | The producer groups together any records that arrive in between request transmissions into a single batched request. Normally this occurs only under load when records arrive faster than they can be sent out. However in some circumstances the client may want to reduce the number of requests even under moderate load. This setting accomplishes this by adding a small amount of artificial delay—that is, rather than immediately sending out a record the producer will wait for up to the given delay to allow other records to be sent so that the sends can be batched together. This can be thought of as analogous to Nagle's algorithm in TCP. This setting gives the upper bound on the delay for batching: once we get batch.size worth of records for a partition it will be sent immediately regardless of this setting, however if we have fewer than this many bytes accumulated for this partition we will 'linger' for the specified time waiting for more records to show up. This setting defaults to 0 (i.e. no delay). Setting linger.ms=5, for example, would have the effect of reducing the number of requests sent but would add up to 5ms of latency to records sent in the absense of load. | 0 | Integer | *camel.component.kafka.configuration.max-block-ms* | The configuration controls how long sending to kafka will block. These methods can be blocked for multiple reasons. For e.g: buffer full, metadata unavailable.This configuration imposes maximum limit on the total time spent in fetching metadata, serialization of key and value, partitioning and allocation of buffer memory when doing a send(). In case of partitionsFor(), this configuration imposes a maximum time threshold on waiting for metadata | 60000 | Integer | *camel.component.kafka.configuration.max-in-flight-request* | The maximum number of unacknowledged requests the client will send on a single connection before blocking. Note that if this setting is set to be greater than 1 and there are failed sends, there is a risk of message re-ordering due to retries (i.e., if retries are enabled). | 5 | Integer | *camel.component.kafka.configuration.max-partition-fetch-bytes* | The maximum amount of data per-partition the server will return. The maximum total memory used for a request will be #partitions * max.partition.fetch.bytes. This size must be at least as large as the maximum message size the server allows or else it is possible for the producer to send messages larger than the consumer can fetch. If that happens, the consumer can get stuck trying to fetch a large message on a certain partition. | 1048576 | Integer | *camel.component.kafka.configuration.max-poll-interval-ms* | The maximum delay between invocations of poll() when using consumer group management. This places an upper bound on the amount of time that the consumer can be idle before fetching more records. If poll() is not called before expiration of this timeout, then the consumer is considered failed and the group will rebalance in order to reassign the partitions to another member. | | Long | *camel.component.kafka.configuration.max-poll-records* | The maximum number of records returned in a single call to poll() | 500 | Integer | *camel.component.kafka.configuration.max-request-size* | The maximum size of a request. This is also effectively a cap on the maximum record size. Note that the server has its own cap on record size which may be different from this. This setting will limit the number of record batches the producer will send in a single request to avoid sending huge requests. | 1048576 | Integer | *camel.component.kafka.configuration.metadata-max-age-ms* | The period of time in milliseconds after which we force a refresh of metadata even if we haven't seen any partition leadership changes to proactively discover any new brokers or partitions. | 300000 | Integer | *camel.component.kafka.configuration.metric-reporters* | A list of classes to use as metrics reporters. Implementing the MetricReporter interface allows plugging in classes that will be notified of new metric creation. The JmxReporter is always included to register JMX statistics. | | String | *camel.component.kafka.configuration.metrics-sample-window-ms* | The number of samples maintained to compute metrics. | 30000 | Integer | *camel.component.kafka.configuration.no-of-metrics-sample* | The number of samples maintained to compute metrics. | 2 | Integer | *camel.component.kafka.configuration.offset-repository* | The offset repository to use in order to locally store the offset of each partition of the topic. Defining one will disable the autocommit. | | StateRepository | *camel.component.kafka.configuration.partition-assignor* | The class name of the partition assignment strategy that the client will use to distribute partition ownership amongst consumer instances when group management is used | org.apache.kafka.clients.consumer.RangeAssignor | String | *camel.component.kafka.configuration.partition-key* | The partition to which the record will be sent (or null if no partition was specified). If this option has been configured then it take precedence over header {@link KafkaConstants#PARTITION_KEY} | | Integer | *camel.component.kafka.configuration.partitioner* | The partitioner class for partitioning messages amongst sub-topics. The default partitioner is based on the hash of the key. | org.apache.kafka.clients.producer.internals.DefaultPartitioner | String | *camel.component.kafka.configuration.poll-timeout-ms* | The timeout used when polling the KafkaConsumer. | 5000 | Long | *camel.component.kafka.configuration.producer-batch-size* | The producer will attempt to batch records together into fewer requests whenever multiple records are being sent to the same partition. This helps performance on both the client and the server. This configuration controls the default batch size in bytes. No attempt will be made to batch records larger than this size.Requests sent to brokers will contain multiple batches, one for each partition with data available to be sent.A small batch size will make batching less common and may reduce throughput (a batch size of zero will disable batching entirely). A very large batch size may use memory a bit more wastefully as we will always allocate a buffer of the specified batch size in anticipation of additional records. | 16384 | Integer | *camel.component.kafka.configuration.queue-buffering-max-messages* | The maximum number of unsent messages that can be queued up the producer when using async mode before either the producer must be blocked or data must be dropped. | 10000 | Integer | *camel.component.kafka.configuration.receive-buffer-bytes* | The size of the TCP receive buffer (SO_RCVBUF) to use when reading data. | 65536 | Integer | *camel.component.kafka.configuration.reconnect-backoff-max-ms* | The maximum amount of time in milliseconds to wait when reconnecting to a broker that has repeatedly failed to connect. If provided, the backoff per host will increase exponentially for each consecutive connection failure, up to this maximum. After calculating the backoff increase, 20% random jitter is added to avoid connection storms. | 1000 | Integer | *camel.component.kafka.configuration.reconnect-backoff-ms* | The amount of time to wait before attempting to reconnect to a given host. This avoids repeatedly connecting to a host in a tight loop. This backoff applies to all requests sent by the consumer to the broker. | 50 | Integer | *camel.component.kafka.configuration.record-metadata* | Whether the producer should store the {@link RecordMetadata} results from sending to Kafka. The results are stored in a {@link List} containing the {@link RecordMetadata} metadata's. The list is stored on a header with the key {@link KafkaConstants#KAFKA_RECORDMETA} | true | Boolean | *camel.component.kafka.configuration.request-required-acks* | The number of acknowledgments the producer requires the leader to have received before considering a request complete. This controls the durability of records that are sent. The following settings are common: acks=0 If set to zero then the producer will not wait for any acknowledgment from the server at all. The record will be immediately added to the socket buffer and considered sent. No guarantee can be made that the server has received the record in this case, and the retries configuration will not take effect (as the client won't generally know of any failures). The offset given back for each record will always be set to -1. acks=1 This will mean the leader will write the record to its local log but will respond without awaiting full acknowledgement from all followers. In this case should the leader fail immediately after acknowledging the record but before the followers have replicated it then the record will be lost. acks=all This means the leader will wait for the full set of in-sync replicas to acknowledge the record. This guarantees that the record will not be lost as long as at least one in-sync replica remains alive. This is the strongest available guarantee. | 1 | String | *camel.component.kafka.configuration.request-timeout-ms* | The amount of time the broker will wait trying to meet the request.required.acks requirement before sending back an error to the client. | 305000 | Integer | *camel.component.kafka.configuration.retries* | Setting a value greater than zero will cause the client to resend any record whose send fails with a potentially transient error. Note that this retry is no different than if the client resent the record upon receiving the error. Allowing retries will potentially change the ordering of records because if two records are sent to a single partition, and the first fails and is retried but the second succeeds, then the second record may appear first. | 0 | Integer | *camel.component.kafka.configuration.retry-backoff-ms* | Before each retry, the producer refreshes the metadata of relevant topics to see if a new leader has been elected. Since leader election takes a bit of time, this property specifies the amount of time that the producer waits before refreshing the metadata. | 100 | Integer | *camel.component.kafka.configuration.sasl-jaas-config* | Expose the kafka sasl.jaas.config parameter Example: org.apache.kafka.common.security.plain.PlainLoginModule required username=""USERNAME"" password=""PASSWORD""; | | String | *camel.component.kafka.configuration.sasl-kerberos-service-name* | The Kerberos principal name that Kafka runs as. This can be defined either in Kafka's JAAS config or in Kafka's config. | | String | *camel.component.kafka.configuration.sasl-mechanism* | The Simple Authentication and Security Layer (SASL) Mechanism used. For the valid values see \\http://www.iana.org/assignments/sasl-mechanisms/sasl-mechanisms.xhtml | GSSAPI | String | *camel.component.kafka.configuration.schema-registry-u-r-l* | URL of the Confluent Platform schema registry servers to use. The format is host1:port1,host2:port2. This is known as schema.registry.url in the Confluent Platform documentation. This option is only available in the Confluent Platform (not standard Apache Kafka) | | String | *camel.component.kafka.configuration.security-protocol* | Protocol used to communicate with brokers. SASL_PLAINTEXT, PLAINTEXT and SSL are supported | PLAINTEXT | String | *camel.component.kafka.configuration.seek-to* | Set if KafkaConsumer will read from beginning or end on startup: beginning : read from beginning end : read from end This is replacing the earlier property seekToBeginning | | String | *camel.component.kafka.configuration.send-buffer-bytes* | Socket write buffer size | 131072 | Integer | *camel.component.kafka.configuration.serializer-class* | The serializer class for messages. | org.apache.kafka.common.serialization.StringSerializer | String | *camel.component.kafka.configuration.session-timeout-ms* | The timeout used to detect failures when using Kafka's group management facilities. | 10000 | Integer | *camel.component.kafka.configuration.specific-avro-reader* | This enables the use of a specific Avro reader for use with the Confluent Platform schema registry and the io.confluent.kafka.serializers.KafkaAvroDeserializer. This option is only available in the Confluent Platform (not standard Apache Kafka) | false | Boolean | *camel.component.kafka.configuration.ssl-cipher-suites* | A list of cipher suites. This is a named combination of authentication, encryption, MAC and key exchange algorithm used to negotiate the security settings for a network connection using TLS or SSL network protocol.By default all the available cipher suites are supported. | | String | *camel.component.kafka.configuration.ssl-context-parameters* | SSL configuration using a Camel {@link SSLContextParameters} object. If configured it's applied before the other SSL endpoint parameters. | | SSLContextParameters | *camel.component.kafka.configuration.ssl-enabled-protocols* | The list of protocols enabled for SSL connections. TLSv1.2, TLSv1.1 and TLSv1 are enabled by default. | TLSv1.2,TLSv1.1,TLSv1 | String | *camel.component.kafka.configuration.ssl-endpoint-algorithm* | The endpoint identification algorithm to validate server hostname using server certificate. | | String | *camel.component.kafka.configuration.ssl-key-password* | The password of the private key in the key store file. This is optional for client. | | String | *camel.component.kafka.configuration.ssl-keymanager-algorithm* | The algorithm used by key manager factory for SSL connections. Default value is the key manager factory algorithm configured for the Java Virtual Machine. | SunX509 | String | *camel.component.kafka.configuration.ssl-keystore-location* | The location of the key store file. This is optional for client and can be used for two-way authentication for client. | | String | *camel.component.kafka.configuration.ssl-keystore-password* | The store password for the key store file.This is optional for client and only needed if ssl.keystore.location is configured. | | String | *camel.component.kafka.configuration.ssl-keystore-type* | The file format of the key store file. This is optional for client. Default value is JKS | JKS | String | *camel.component.kafka.configuration.ssl-protocol* | The SSL protocol used to generate the SSLContext. Default setting is TLS, which is fine for most cases. Allowed values in recent JVMs are TLS, TLSv1.1 and TLSv1.2. SSL, SSLv2 and SSLv3 may be supported in older JVMs, but their usage is discouraged due to known security vulnerabilities. | TLS | String | *camel.component.kafka.configuration.ssl-provider* | The name of the security provider used for SSL connections. Default value is the default security provider of the JVM. | | String | *camel.component.kafka.configuration.ssl-trustmanager-algorithm* | The algorithm used by trust manager factory for SSL connections. Default value is the trust manager factory algorithm configured for the Java Virtual Machine. | PKIX | String | *camel.component.kafka.configuration.ssl-truststore-location* | The location of the trust store file. | | String | *camel.component.kafka.configuration.ssl-truststore-password* | The password for the trust store file. | | String | *camel.component.kafka.configuration.ssl-truststore-type* | The file format of the trust store file. Default value is JKS. | JKS | String | *camel.component.kafka.configuration.topic* | Name of the topic to use. On the consumer you can use comma to separate multiple topics. A producer can only send a message to a single topic. | | String | *camel.component.kafka.configuration.topic-is-pattern* | Whether the topic is a pattern (regular expression). This can be used to subscribe to dynamic number of topics matching the pattern. | false | Boolean | *camel.component.kafka.configuration.value-deserializer* | Deserializer class for value that implements the Deserializer interface. | org.apache.kafka.common.serialization.StringDeserializer | String | *camel.component.kafka.configuration.worker-pool* | To use a custom worker pool for continue routing {@link Exchange} after kafka server has acknowledge the message that was sent to it from {@link KafkaProducer} using asynchronous non-blocking processing. | | ExecutorService | *camel.component.kafka.configuration.worker-pool-core-size* | Number of core threads for the worker pool for continue routing {@link Exchange} after kafka server has acknowledge the message that was sent to it from {@link KafkaProducer} using asynchronous non-blocking processing. | 10 | Integer | *camel.component.kafka.configuration.worker-pool-max-size* | Maximum number of threads for the worker pool for continue routing {@link Exchange} after kafka server has acknowledge the message that was sent to it from {@link KafkaProducer} using asynchronous non-blocking processing. | 20 | Integer | *camel.component.kafka.enabled* | Enable kafka component | true | Boolean | *camel.component.kafka.kafka-manual-commit-factory* | Factory to use for creating KafkaManualCommit instances. This allows to plugin a custom factory to create custom KafkaManualCommit instances in case special logic is needed when doing manual commits that deviates from the default implementation that comes out of the box. The option is a org.apache.camel.component.kafka.KafkaManualCommitFactory type. | | String | *camel.component.kafka.use-global-ssl-context-parameters* | Enable usage of global SSL context parameters. | false | Boolean | *camel.component.kafka.worker-pool* | To use a shared custom worker pool for continue routing Exchange after kafka server has acknowledge the message that was sent to it from KafkaProducer using asynchronous non-blocking processing. If using this option then you must handle the lifecycle of the thread pool to shut the pool down when no longer needed. The option is a java.util.concurrent.ExecutorService type. | | String |=== // spring-boot-auto-configure options: END For more information about Producer/Consumer configuration: http://kafka.apache.org/documentation.html#newconsumerconfigs[http://kafka.apache.org/documentation.html#newconsumerconfigs] http://kafka.apache.org/documentation.html#producerconfigs[http://kafka.apache.org/documentation.html#producerconfigs] == Message headers === Consumer headers The following headers are available when consuming messages from Kafka. [width=""100%"",cols=""2m,2m,1m,5"",options=""header""] |=== | Header constant | Header value | Type | Description | KafkaConstants.TOPIC | ""kafka.TOPIC"" | String | The topic from where the message originated | KafkaConstants.PARTITION | ""kafka.PARTITION"" | Integer | The partition where the message was stored | KafkaConstants.OFFSET | ""kafka.OFFSET"" | Long | The offset of the message | KafkaConstants.KEY | ""kafka.KEY"" | Object | The key of the message if configured | KafkaConstants.HEADERS | ""kafka.HEADERS"" | org.apache.kafka.common.header.Headers | The record headers | KafkaConstants.LAST_RECORD_BEFORE_COMMIT | ""kafka.LAST_RECORD_BEFORE_COMMIT"" | Boolean | Whether or not it's the last record before commit (only available if `autoCommitEnable` endpoint parameter is `false`) | KafkaConstants.MANUAL_COMMIT | ""CamelKafkaManualCommit"" | KafkaManualCommit | Can be used for forcing manual offset commit when using Kafka consumer. | |=== === Producer headers Before sending a message to Kafka you can configure the following headers. [width=""100%"",cols=""2m,2m,1m,5"",options=""header""] |=== | Header constant | Header value | Type | Description | KafkaConstants.KEY | ""kafka.KEY"" | Object | *Required* The key of the message in order to ensure that all related message goes in the same partition | KafkaConstants.OVERRIDE_TOPIC | ""kafka.OVERRIDE_TOPIC"" | String | The topic to which send the message (override and takes precedence), and the header is not preserved. | | KafkaConstants.PARTITION_KEY | ""kafka.PARTITION_KEY"" | Integer | Explicitly specify the partition (only used if the `KafkaConstants.KEY` header is defined) |=== If you want to send a message to a dynamic topic then use `KafkaConstants.OVERRIDE_TOPIC` as its used as a one-time header that are not send along the message, as its removed in the producer. After the message is sent to Kafka, the following headers are available [width=""100%"",cols=""2m,2m,1m,5"",options=""header""] |=== | Header constant | Header value | Type | Description | KafkaConstants.KAFKA_RECORDMETA | ""org.apache.kafka.clients.producer.RecordMetadata"" | List | The metadata (only configured if `recordMetadata` endpoint parameter is `true` |=== == Samples === Consuming messages from Kafka Here is the minimal route you need in order to read messages from Kafka. [source,java] ---- from(""kafka:test?brokers=localhost:9092"") .log(""Message received from Kafka : ${body}"") .log("" on the topic ${headers[kafka.TOPIC]}"") .log("" on the partition ${headers[kafka.PARTITION]}"") .log("" with the offset ${headers[kafka.OFFSET]}"") .log("" with the key ${headers[kafka.KEY]}"") ---- If you need to consume messages from multiple topics you can use a comma separated list of topic names [source,java] ---- from(""kafka:test,test1,test2?brokers=localhost:9092"") .log(""Message received from Kafka : ${body}"") .log("" on the topic ${headers[kafka.TOPIC]}"") .log("" on the partition ${headers[kafka.PARTITION]}"") .log("" with the offset ${headers[kafka.OFFSET]}"") .log("" with the key ${headers[kafka.KEY]}"") ---- When consuming messages from Kafka you can use your own offset management and not delegate this management to Kafka. In order to keep the offsets the component needs a `StateRepository` implementation such as `FileStateRepository`. This bean should be available in the registry. Here how to use it : [source,java] ---- // Create the repository in which the Kafka offsets will be persisted FileStateRepository repository = FileStateRepository.fileStateRepository(new File(""/path/to/repo.dat"")); // Bind this repository into the Camel registry Registry registry = createCamelRegistry(); registry.bind(""offsetRepo"", repository); // Configure the camel context DefaultCamelContext camelContext = new DefaultCamelContext(registry); camelContext.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from(""kafka:"" + TOPIC + ""?brokers=localhost:{{kafkaPort}}"" + // Setup the topic and broker address ""&groupId=A"" + // The consumer processor group ID ""&autoOffsetReset=earliest"" + // Ask to start from the beginning if we have unknown offset ""&offsetRepository=#offsetRepo"") // Keep the offsets in the previously configured repository .to(""mock:result""); } }); ---- === Producing messages to Kafka Here is the minimal route you need in order to write messages to Kafka. [source,java] ---- from(""direct:start"") .setBody(constant(""Message from Camel"")) // Message to send .setHeader(KafkaConstants.KEY, constant(""Camel"")) // Key of the message .to(""kafka:test?brokers=localhost:9092""); ---- == SSL configuration You have 2 different ways to configure the SSL communication on the Kafka` component. The first way is through the many SSL endpoint parameters [source,java] ---- from(""kafka:"" + TOPIC + ""?brokers=localhost:{{kafkaPort}}"" + ""&groupId=A"" + ""&sslKeystoreLocation=/path/to/keystore.jks"" + ""&sslKeystorePassword=changeit"" + ""&sslKeyPassword=changeit"" + ""&securityProtocol=SSL"") .to(""mock:result""); ---- The second way is to use the `sslContextParameters` endpoint parameter. [source,java] ---- // Configure the SSLContextParameters object KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource(""/path/to/keystore.jks""); ksp.setPassword(""changeit""); KeyManagersParameters kmp = new KeyManagersParameters(); kmp.setKeyStore(ksp); kmp.setKeyPassword(""changeit""); SSLContextParameters scp = new SSLContextParameters(); scp.setKeyManagers(kmp); // Bind this SSLContextParameters into the Camel registry Registry registry = createCamelRegistry(); registry.bind(""ssl"", scp); // Configure the camel context DefaultCamelContext camelContext = new DefaultCamelContext(registry); camelContext.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from(""kafka:"" + TOPIC + ""?brokers=localhost:{{kafkaPort}}"" + // Setup the topic and broker address ""&groupId=A"" + // The consumer processor group ID ""&sslContextParameters=#ssl"" + // The security protocol ""&securityProtocol=SSL) // Reference the SSL configuration .to(""mock:result""); } }); ---- == Using the Kafka idempotent repository *Available from Camel 2.19* The `camel-kafka` library provides a Kafka topic-based idempotent repository. This repository stores broadcasts all changes to idempotent state (add/remove) in a Kafka topic, and populates a local in-memory cache for each repository's process instance through event sourcing. The topic used must be unique per idempotent repository instance. The mechanism does not have any requirements about the number of topic partitions; as the repository consumes from all partitions at the same time. It also does not have any requirements about the replication factor of the topic. Each repository instance that uses the topic (e.g. typically on different machines running in parallel) controls its own consumer group, so in a cluster of 10 Camel processes using the same topic each will control its own offset. On startup, the instance subscribes to the topic and rewinds the offset to the beginning, rebuilding the cache to the latest state. The cache will not be considered warmed up until one poll of `pollDurationMs` in length returns 0 records. Startup will not be completed until either the cache has warmed up, or 30 seconds go by; if the latter happens the idempotent repository may be in an inconsistent state until its consumer catches up to the end of the topic. A `KafkaIdempotentRepository` has the following properties: [width=""100%"",cols=""2m,5"",options=""header""] |=== | Property | Description | topic | The name of the Kafka topic to use to broadcast changes. (required) | bootstrapServers | The `bootstrap.servers` property on the internal Kafka producer and consumer. Use this as shorthand if not setting `consumerConfig` and `producerConfig`. If used, this component will apply sensible default configurations for the producer and consumer. | producerConfig | Sets the properties that will be used by the Kafka producer that broadcasts changes. Overrides `bootstrapServers`, so must define the Kafka `bootstrap.servers` property itself | consumerConfig | Sets the properties that will be used by the Kafka consumer that populates the cache from the topic. Overrides `bootstrapServers`, so must define the Kafka `bootstrap.servers` property itself | maxCacheSize | How many of the most recently used keys should be stored in memory (default 1000). | pollDurationMs | The poll duration of the Kafka consumer. The local caches are updated immediately. This value will affect how far behind other peers that update their caches from the topic are relative to the idempotent consumer instance that sent the cache action message. The default value of this is 100 ms. + If setting this value explicitly, be aware that there is a tradeoff between the remote cache liveness and the volume of network traffic between this repository's consumer and the Kafka brokers. The cache warmup process also depends on there being one poll that fetches nothing - this indicates that the stream has been consumed up to the current point. If the poll duration is excessively long for the rate at which messages are sent on the topic, there exists a possibility that the cache cannot be warmed up and will operate in an inconsistent state relative to its peers until it catches up. |=== The repository can be instantiated by defining the `topic` and `bootstrapServers`, or the `producerConfig` and `consumerConfig` property sets can be explicitly defined to enable features such as SSL/SASL. To use, this repository must be placed in the Camel registry, either manually or by registration as a bean in Spring/Blueprint, as it is `CamelContext` aware. Sample usage is as follows: [source,java] ---- KafkaIdempotentRepository kafkaIdempotentRepository = new KafkaIdempotentRepository(""idempotent-db-inserts"", ""localhost:9091""); SimpleRegistry registry = new SimpleRegistry(); registry.put(""insertDbIdemRepo"", kafkaIdempotentRepository); // must be registered in the registry, to enable access to the CamelContext CamelContext context = new CamelContext(registry); // later in RouteBuilder... from(""direct:performInsert"") .idempotentConsumer(header(""id"")).messageIdRepositoryRef(""insertDbIdemRepo"") // once-only insert into database .end() ---- In XML: [source,xml] ---- localhost:9091 localhost:9091 ---- == Using manual commit with Kafka consumer *Available as of Camel 2.21* By default the Kafka consumer will use auto commit, where the offset will be committed automatically in the background using a given interval. In case you want to force manual commits, you can use `KafkaManualCommit` API from the Camel Exchange, stored on the message header. This requires to turn on manual commits by either setting the option `allowManualCommit` to `true` on the `KafkaComponent` or on the endpoint, for example: [source,java] ---- KafkaComponent kafka = new KafkaComponent(); kafka.setAllowManualCommit(true); ... camelContext.addComponent(""kafka"", kafka); ---- You can then use the `KafkaManualCommit` from Java code such as a Camel `Processor`: [source,java] ---- public void process(Exchange exchange) { KafkaManualCommit manual = exchange.getIn().getHeader(KafkaConstants.MANUAL_COMMIT, KafkaManualCommit.class); manual.commitSync(); } ---- This will force a synchronous commit which will block until the commit is acknowledge on Kafka, or if it fails an exception is thrown. If you want to use a custom implementation of `KafkaManualCommit` then you can configure a custom `KafkaManualCommitFactory` on the `KafkaComponent` that creates instances of your custom implementation. == Kafka Headers propagation *Available as of Camel 2.22* When consuming messages from Kafka, headers will be propagated to camel exchange headers automatically. Producing flow backed by same behaviour - camel headers of particular exchange will be propagated to kafka message headers. Since kafka headers allows only `byte[]` values, in order camel exchnage header to be propagated its value should be serialized to `bytes[]`, otherwise header will be skipped. Following header value types are supported: `String`, `Integer`, `Long`, `Double`, `Boolean`, `byte[]`. Note: all headers propagated *from* kafka *to* camel exchange will contain `byte[]` value by default. In order to override default functionality uri parameters can be set: `kafkaHeaderDeserializer` for `from` route and `kafkaHeaderSerializer` for `to` route. Example: ``` from(""kafka:my_topic?kafkaHeaderDeserializer=#myDeserializer"") ... .to(""kafka:my_topic?kafkaHeaderSerializer=#mySerializer"") ``` By default all headers are being filtered by `KafkaHeaderFilterStrategy`. Strategy filters out headers which start with `Camel` or `org.apache.camel` prefixes. Default strategy can be overridden by using `headerFilterStrategy` uri parameter in both `to` and `from` routes: ``` from(""kafka:my_topic?headerFilterStrategy=#myStrategy"") ... .to(""kafka:my_topic?headerFilterStrategy=#myStrategy"") ``` `myStrategy` object should be subclass of `HeaderFilterStrategy` and must be placed in the Camel registry, either manually or by registration as a bean in Spring/Blueprint, as it is `CamelContext` aware. ",16160,True,3416.1023513108476,median "-- *********** -- -- Version with an alternative ""Inflater"" based on simple -- Huffman tree types. Unfortunately -- the same ""wrong filter"" errors, which appeared with -- the UnZip decoder for some pictures, appear too, at the same -- places. This leads think the bug is actually not with -- this part of decompression. And other pictures fail, seemingly on -- fixed ""deflate"" blocks, with that alternative. 5-Jun-2010. -- -- A PNG stream is made of several ""chunks"" (see type PNG_Chunk_tag). -- The image itself is contained in the IDAT chunk(s). -- -- Steps for decoding an image (step numbers are from the ISO standard): -- -- 10: Inflate deflated data; at each output buffer (slide), -- process with step 9. -- 9: Read filter code (row begin), or unfilter bytes, go with step 8 -- 8: Display pixels these bytes represent; -- eventually, locate the interlaced image current point -- with GID.Buffering, GID.Decoding_PNG.Huffman; with Ada.Text_IO, Ada.Exceptions, Interfaces; package body GID.Decoding_PNG is generic type Number is mod <>; procedure Big_endian_number( from : in out Input_buffer; n : out Number ); pragma Inline(Big_endian_number); procedure Big_endian_number( from : in out Input_buffer; n : out Number ) is b: U8; begin n:= 0; for i in 1..Number'Size/8 loop Buffering.Get_Byte(from, b); n:= n * 256 + Number(b); end loop; end Big_endian_number; procedure Big_endian is new Big_endian_number( U32 ); use Ada.Exceptions; ---------- -- Read -- ---------- procedure Read (image: in out image_descriptor; ch: out Chunk_head) is str4: String(1..4); b: U8; begin Big_endian(image.buffer, ch.length); for i in str4'Range loop Buffering.Get_Byte(image.buffer, b); str4(i):= Character'Val(b); end loop; begin ch.kind:= PNG_Chunk_tag'Value(str4); if some_trace then Ada.Text_IO.Put_Line('[' & str4 & ""], length:"" & U32'Image(ch.length)); end if; exception when Constraint_Error => Raise_exception( error_in_image_data'Identity, ""PNG chunk: "" & Integer'Image(Character'Pos(str4(1))) & Integer'Image(Character'Pos(str4(2))) & Integer'Image(Character'Pos(str4(3))) & Integer'Image(Character'Pos(str4(4))) ); end; end Read; package CRC32 is use Interfaces; procedure Init( CRC: out Unsigned_32 ); function Final( CRC: Unsigned_32 ) return Unsigned_32; procedure Update( CRC: in out Unsigned_32; InBuf: Byte_array ); pragma Inline( Update ); end CRC32; package body CRC32 is CRC32_Table : array( Unsigned_32'(0)..255 ) of Unsigned_32; procedure Prepare_table is -- CRC-32 algorithm, ISO-3309 Seed: constant:= 16#EDB88320#; l: Unsigned_32; begin for i in CRC32_Table'Range loop l:= i; for bit in 0..7 loop if (l and 1) = 0 then l:= Shift_Right(l,1); else l:= Shift_Right(l,1) xor Seed; end if; end loop; CRC32_Table(i):= l; end loop; end Prepare_table; procedure Update( CRC: in out Unsigned_32; InBuf: Byte_array ) is local_CRC: Unsigned_32; begin local_CRC:= CRC ; for i in InBuf'Range loop local_CRC := CRC32_Table( 16#FF# and ( local_CRC xor Unsigned_32( InBuf(i) ) ) ) xor Shift_Right( local_CRC , 8 ); end loop; CRC:= local_CRC; end Update; table_empty: Boolean:= True; procedure Init( CRC: out Unsigned_32 ) is begin if table_empty then Prepare_table; table_empty:= False; end if; CRC:= 16#FFFF_FFFF#; end Init; function Final( CRC: Unsigned_32 ) return Unsigned_32 is begin return not CRC; end Final; end CRC32; ---------- -- Load -- ---------- procedure Load (image: in out Image_descriptor) is -- !! these constants can be made generic parameters bits_per_pixel: constant Positive:= image.bits_per_pixel; subformat_id : constant Natural := image.subformat_id; interlaced : constant Boolean := image.interlaced; use GID.Buffering; subtype Mem_row_bytes_array is Byte_array(0..image.width*8); -- mem_row_bytes: array(0..1) of Mem_row_bytes_array; -- We need to memorize two image rows, for un-filtering curr_row: Natural:= 1; -- either current is 1 and old is 0, or the reverse subtype X_range is Integer range -1..image.width-1; subtype Y_range is Integer range 0..image.height-1; -- X position -1 is for the row's filter methode code x: X_range:= X_range'First; y: Y_range:= Y_range'First; x_max: X_range; -- for non-interlaced images: = X_range'Last y_max: Y_range; -- for non-interlaced images: = Y_range'Last pass: Positive range 1..7:= 1; -- Amount of bytes to unfilter at a time bytes_to_unfilter: constant Integer:= Integer'Max(1, bits_per_pixel / 8); -------------------------- -- ** 9: Unfiltering ** -- -------------------------- type Filter_method_0 is (None, Sub, Up, Average, Paeth); current_filter: Filter_method_0; procedure Unfilter_bytes( f: in Byte_array; -- filtered u: out Byte_array -- unfiltered ) is pragma Inline(Unfilter_bytes); -- c b -- a f a,b,c,p,pa,pb,pc,pr: Integer; j: Integer:= 0; begin if full_trace and then x = 0 then Ada.Text_IO.Put_Line( Integer'Image(y) & "": "" & Filter_method_0'Image(current_filter) ); end if; case current_filter is when None => -- Recon(x) = Filt(x) u:= f; when Sub => -- Recon(x) = Filt(x) + Recon(a) if x > 0 then for i in f'Range loop u(u'First+j):= f(i) + mem_row_bytes(curr_row)((x-1)*bytes_to_unfilter+j); j:= j + 1; end loop; else u:= f; end if; when Up => -- Recon(x) = Filt(x) + Recon(b) if y > 0 then for i in f'Range loop u(u'First+j):= f(i) + mem_row_bytes(1-curr_row)(x*bytes_to_unfilter+j); j:= j + 1; end loop; else u:= f; end if; when Average => -- Recon(x) = Filt(x) + floor((Recon(a) + Recon(b)) / 2) for i in f'Range loop if x > 0 then a:= Integer(mem_row_bytes(curr_row)((x-1)*bytes_to_unfilter+j)); else a:= 0; end if; if y > 0 then b:= Integer(mem_row_bytes(1-curr_row)(x*bytes_to_unfilter+j)); else b:= 0; end if; u(u'First+j):= f(i) + U8((a+b)/2); j:= j + 1; end loop; when Paeth => -- Recon(x) = Filt(x) + PaethPredictor(Recon(a), Recon(b), Recon(c)) for i in f'Range loop if x > 0 then a:= Integer(mem_row_bytes(curr_row)((x-1)*bytes_to_unfilter+j)); else a:= 0; end if; if y > 0 then b:= Integer(mem_row_bytes(1-curr_row)(x*bytes_to_unfilter+j)); else b:= 0; end if; if x > 0 and y > 0 then c:= Integer(mem_row_bytes(1-curr_row)((x-1)*bytes_to_unfilter+j)); else c:= 0; end if; p := a + b - c; pa:= abs(p - a); pb:= abs(p - b); pc:= abs(p - c); if pa <= pb and pa <= pc then pr:= a; elsif pb <= pc then pr:= b; else pr:= c; end if; u(u'First+j):= f(i) + U8(pr); j:= j + 1; end loop; end case; j:= 0; for i in u'Range loop mem_row_bytes(curr_row)(x*bytes_to_unfilter+j):= u(i); j:= j + 1; end loop; if u'Length /= bytes_to_unfilter then raise constraint_error;-- with ""filter mismatch!""; end if; -- !! end Unfilter_bytes; filter_stat: array(Filter_method_0) of Natural:= (others => 0); -- Output bytes from decompression -- procedure Output_uncompressed( data : in Byte_array; reject: out Natural -- amount of bytes to be resent here next time, -- in order to have a full multi-byte pixel ) is -- Display of pixels coded on 8 bits per channel in the PNG stream procedure Out_Pixel_8(br, bg, bb, ba: U8) is pragma Inline(Out_Pixel_8); begin case Primary_color_range'Modulus is when 256 => Put_Pixel( Primary_color_range(br), Primary_color_range(bg), Primary_color_range(bb), Primary_color_range(ba) ); when 65_536 => Put_Pixel( 16#101# * Primary_color_range(br), 16#101# * Primary_color_range(bg), 16#101# * Primary_color_range(bb), 16#101# * Primary_color_range(ba) -- 16#101# because max intensity FF goes to FFFF ); when others => raise invalid_primary_color_range; end case; end Out_Pixel_8; procedure Out_Pixel_Palette(ix: U8) is pragma Inline(Out_Pixel_Palette); color_idx: constant Natural:= Integer(ix); begin Out_Pixel_8( image.palette(color_idx).red, image.palette(color_idx).green, image.palette(color_idx).blue, 255 ); end Out_Pixel_Palette; -- Display of pixels coded on 16 bits per channel in the PNG stream procedure Out_Pixel_16(br, bg, bb, ba: U16) is pragma Inline(Out_Pixel_16); begin case Primary_color_range'Modulus is when 256 => Put_Pixel( Primary_color_range(br / 256), Primary_color_range(bg / 256), Primary_color_range(bb / 256), Primary_color_range(ba / 256) ); when 65_536 => Put_Pixel( Primary_color_range(br), Primary_color_range(bg), Primary_color_range(bb), Primary_color_range(ba) ); when others => raise invalid_primary_color_range; end case; end Out_Pixel_16; procedure Inc_XY is pragma Inline(Inc_XY); begin if x < x_max then x:= x + 1; if interlaced then -- Position of pixels depending on pass: -- -- 1 6 4 6 2 6 4 6 -- 7 7 7 7 7 7 7 7 -- 5 6 5 6 5 6 5 6 -- 7 7 7 7 7 7 7 7 -- 3 6 4 6 3 6 4 6 -- 7 7 7 7 7 7 7 7 -- 5 6 5 6 5 6 5 6 -- 7 7 7 7 7 7 7 7 case pass is when 1 => Set_X_Y( x*8, Y_range'Last - y*8); when 2 => Set_X_Y(4 + x*8, Y_range'Last - y*8); when 3 => Set_X_Y( x*4, Y_range'Last - 4 - y*8); when 4 => Set_X_Y(2 + x*4, Y_range'Last - y*4); when 5 => Set_X_Y( x*2, Y_range'Last - 2 - y*4); when 6 => Set_X_Y(1 + x*2, Y_range'Last - y*2); when 7 => null; -- nothing to to, pixel are contiguous end case; end if; else x:= X_range'First; -- New row if y < y_max then y:= y + 1; curr_row:= 1-curr_row; -- swap row index for filtering if not interlaced then Feedback((y*100)/image.height); end if; elsif interlaced then -- last row has beed displayed if pass < 7 then pass:= pass + 1; y:= 0; case pass is when 1 => null; when 2 => x_max:= (image.width+3)/8 - 1; y_max:= (image.height+7)/8 - 1; when 3 => x_max:= (image.width+3)/4 - 1; y_max:= (image.height+3)/8 - 1; when 4 => x_max:= (image.width+1)/4 - 1; y_max:= (image.height+3)/4 - 1; when 5 => x_max:= (image.width+1)/2 - 1; y_max:= (image.height+1)/4 - 1; when 6 => x_max:= (image.width )/2 - 1; y_max:= (image.height+1)/2 - 1; when 7 => x_max:= image.width - 1; y_max:= image.height/2 - 1; end case; end if; end if; end if; end Inc_XY; uf: Byte_array(0..15); -- unfiltered bytes for a pixel w1, w2: U16; i: Integer; begin if some_trace then Ada.Text_IO.Put(""[UO]""); end if; -- Depending on the row size, bpp, etc., we can have -- several rows, or less than one, being displayed -- with the present uncompressed data batch. -- i:= data'First; if i > data'Last then reject:= 0; return; -- data is empty, do nothing end if; -- -- Main loop over data -- loop if x = X_range'First then -- pseudo-column for filter method exit when i > data'Last; begin current_filter:= Filter_method_0'Val(data(i)); if some_trace then filter_stat(current_filter):= filter_stat(current_filter) + 1; end if; exception when Constraint_Error => Raise_exception( error_in_image_data'Identity, ""PNG: wrong filter code, row #"" & Integer'Image(y) & "" code:"" & U8'Image(data(i)) ); end; if interlaced then case pass is when 1..6 => null; -- Set_X_Y for each pixel when 7 => Set_X_Y(0, Y_range'Last - 1 - y*2); end case; else Set_X_Y(0, Y_range'Last - y); end if; i:= i + 1; else -- normal pixel -- -- We quit the loop if all data has been used (except for an -- eventual incomplete pixel) exit when i > data'Last - (bytes_to_unfilter - 1); -- NB, for per-channel bpp < 8: -- 7.2 Scanlines - some low-order bits of the -- last byte of a scanline may go unused. case subformat_id is when 0 => ----------------------- -- Type 0: Greyscale -- ----------------------- case bits_per_pixel is when 1 | 2 | 4 => Unfilter_bytes(data(i..i), uf(0..0)); i:= i + 1; declare b: U8; shift: Integer:= 8 - bits_per_pixel; use Interfaces; max: constant U8:= U8(Shift_Left(Unsigned_32'(1), bits_per_pixel)-1); -- Scaling factor to obtain the correct color value on a 0..255 range. -- The division is exact in all cases (bpp=8,4,2,1), -- since 255 = 3 * 5 * 17 and max = 255, 15, 3 or 1. -- This factor ensures: 0 -> 0, max -> 255 factor: constant U8:= 255 / max; begin -- loop through the number of pixels in this byte: for k in reverse 1..8/bits_per_pixel loop b:= (max and U8(Shift_Right(Unsigned_8(uf(0)), shift))) * factor; shift:= shift - bits_per_pixel; Out_Pixel_8(b, b, b, 255); exit when x >= x_max or k = 1; x:= x + 1; end loop; end; when 8 => -- !! with bpp as generic param, this case can be merged -- into the general 1,2,4[,8] case without loss of performance -- if the compiler is smart enough. To be tested first... Unfilter_bytes(data(i..i), uf(0..0)); i:= i + 1; Out_Pixel_8(uf(0), uf(0), uf(0), 255); when 16 => Unfilter_bytes(data(i..i+1), uf(0..1)); i:= i + 2; w1:= U16(uf(0)) * 256 + U16(uf(1)); Out_Pixel_16(w1, w1, w1, 65535); when others => null; -- undefined in PNG standard end case; when 2 => ----------------- -- Type 2: RGB -- ----------------- case bits_per_pixel is when 24 => Unfilter_bytes(data(i..i+2), uf(0..2)); i:= i + 3; Out_Pixel_8(uf(0), uf(1), uf(2), 255); when 48 => Unfilter_bytes(data(i..i+5), uf(0..5)); i:= i + 6; Out_Pixel_16( U16(uf(0)) * 256 + U16(uf(1)), U16(uf(2)) * 256 + U16(uf(3)), U16(uf(4)) * 256 + U16(uf(5)), 65_535 ); when others => null; end case; when 3 => ------------------------------ -- Type 3: RGB with palette -- ------------------------------ Unfilter_bytes(data(i..i), uf(0..0)); i:= i + 1; case bits_per_pixel is when 1 | 2 | 4 => declare shift: Integer:= 8 - bits_per_pixel; use Interfaces; max: constant U8:= U8(Shift_Left(Unsigned_32'(1), bits_per_pixel)-1); begin -- loop through the number of pixels in this byte: for k in reverse 1..8/bits_per_pixel loop Out_Pixel_Palette(max and U8(Shift_Right(Unsigned_8(uf(0)), shift))); shift:= shift - bits_per_pixel; exit when x >= x_max or k = 1; x:= x + 1; end loop; end; when 8 => -- !! with bpp as generic param, this case can be merged -- into the general 1,2,4[,8] case without loss of performance -- if the compiler is smart enough. To be tested first... Out_Pixel_Palette(uf(0)); when others => null; end case; when 4 => ------------------------------- -- Type 4: Greyscale & Alpha -- ------------------------------- case bits_per_pixel is when 16 => Unfilter_bytes(data(i..i+1), uf(0..1)); i:= i + 2; Out_Pixel_8(uf(0), uf(0), uf(0), uf(1)); when 32 => Unfilter_bytes(data(i..i+3), uf(0..3)); i:= i + 4; w1:= U16(uf(0)) * 256 + U16(uf(1)); w2:= U16(uf(2)) * 256 + U16(uf(3)); Out_Pixel_16(w1, w1, w1, w2); when others => null; -- undefined in PNG standard end case; when 6 => ------------------ -- Type 5: RGBA -- ------------------ case bits_per_pixel is when 32 => Unfilter_bytes(data(i..i+3), uf(0..3)); i:= i + 4; Out_Pixel_8(uf(0), uf(1), uf(2), uf(3)); when 64 => Unfilter_bytes(data(i..i+7), uf(0..7)); i:= i + 6; Out_Pixel_16( U16(uf(0)) * 256 + U16(uf(1)), U16(uf(2)) * 256 + U16(uf(3)), U16(uf(4)) * 256 + U16(uf(5)), U16(uf(6)) * 256 + U16(uf(7)) ); when others => null; end case; when others => null; -- Unknown - exception already raised at header level end case; end if; Inc_XY; end loop; -- i is between data'Last-(bytes_to_unfilter-2) and data'Last+1 reject:= (data'Last + 1) - i; if reject > 0 then if some_trace then Ada.Text_IO.Put(""[rj"" & Integer'Image(reject) & ']'); end if; end if; end Output_uncompressed; --------------------------------------------------------------------- -- ** 10: Decompression ** -- -- Excerpt and simplification from UnZip.Decompress (Inflate only) -- --------------------------------------------------------------------- -- Size of sliding dictionary and output buffer wsize: constant:= 16#10000#; -------------------------------------- -- Specifications of UnZ_* packages -- -------------------------------------- use Interfaces; package UnZ_Glob is -- I/O Buffers -- > Sliding dictionary for unzipping, and output buffer as well slide: Byte_Array( 0..wsize ); slide_index: Integer:= 0; -- Current Position in slide IDAT_reserve: Natural; Zip_EOF : constant Boolean:= False; crc32val : Unsigned_32; -- crc calculated from data end UnZ_Glob; package UnZ_IO is procedure Init_Buffers(IDAT_reserve: Natural); procedure Read_raw_byte ( bt : out U8 ); pragma Inline(Read_raw_byte); package Bit_buffer is procedure Init; -- Read at least n bits into the bit buffer, returns the n first bits function Read ( n: Natural ) return Integer; pragma Inline(Read); function Read_U32 ( n: Natural ) return Unsigned_32; pragma Inline(Read_U32); -- Dump n bits no longer needed from the bit buffer procedure Dump ( n: Natural ); pragma Inline(Dump); procedure Dump_to_byte_boundary; function Read_and_dump( n: Natural ) return Integer; pragma Inline(Read_and_dump); function Read_and_dump_U32( n: Natural ) return Unsigned_32; pragma Inline(Read_and_dump_U32); end Bit_buffer; procedure Flush ( x: Natural ); -- directly from slide to output stream procedure Flush_if_full(W: in out Integer); pragma Inline(Flush_if_full); procedure Copy( distance, length: Natural; index : in out Natural ); pragma Inline(Copy); end UnZ_IO; package UnZ_Meth is deflate_e_mode: constant Boolean:= False; procedure Inflate; end UnZ_Meth; ------------------------------ -- Bodies of UnZ_* packages -- ------------------------------ package body UnZ_IO is procedure Init_Buffers(IDAT_reserve: Natural) is begin UnZ_Glob.slide_index := 0; Bit_buffer.Init; CRC32.Init( UnZ_Glob.crc32val ); UnZ_Glob.IDAT_reserve:= IDAT_reserve; end Init_Buffers; procedure Read_raw_byte ( bt : out U8 ) is ch: Chunk_head; dummy: U32; begin if UnZ_Glob.IDAT_reserve = 0 then -- We hit the end of a PNG 'IDAT' chunk, so we go to the next one -- (in petto, it's strange design, but well...). -- This ""feature"" has taken some time (and nerves) to be addressed. -- Incidentally, I have reprogrammed the whole Huffman -- decoding, and looked at many other wrong places to solve -- the mystery. Big_endian(image.buffer, dummy); -- ending chunk's CRC -- New chunk begins here. Read(image, ch); if ch.kind /= IDAT then Raise_exception( error_in_image_data'Identity, ""PNG additional data chunk must be an IDAT"" ); end if; UnZ_Glob.IDAT_reserve:= Natural(ch.length); end if; Buffering.Get_Byte(image.buffer, bt); UnZ_Glob.IDAT_reserve:= UnZ_Glob.IDAT_reserve - 1; end Read_raw_byte; package body Bit_buffer is B : Unsigned_32; K : Integer; procedure Init is begin B := 0; K := 0; end Init; procedure Need( n : Natural ) is pragma Inline(Need); bt: U8; begin while K < n loop Read_raw_byte( bt ); B:= B or Shift_Left( Unsigned_32( bt ), K ); K:= K + 8; end loop; end Need; procedure Dump ( n : Natural ) is begin B := Shift_Right(B, n ); K := K - n; end Dump; procedure Dump_to_byte_boundary is begin Dump ( K mod 8 ); end Dump_to_byte_boundary; function Read_U32 ( n: Natural ) return Unsigned_32 is begin Need(n); return B and (Shift_Left(1,n) - 1); end Read_U32; function Read ( n: Natural ) return Integer is begin return Integer(Read_U32(n)); end Read; function Read_and_dump( n: Natural ) return Integer is res: Integer; begin res:= Read(n); Dump(n); return res; end Read_and_dump; function Read_and_dump_U32( n: Natural ) return Unsigned_32 is res: Unsigned_32; begin res:= Read_U32(n); Dump(n); return res; end Read_and_dump_U32; end Bit_buffer; old_bytes: Natural:= 0; -- how many bytes to be resent from last Inflate output byte_mem: Byte_array(1..8); procedure Flush ( x: Natural ) is use Ada.Streams; begin if full_trace then Ada.Text_IO.Put(""[Flush..."" & Integer'Image(x)); end if; CRC32.Update( UnZ_Glob.crc32val, UnZ_Glob.slide( 0..x-1 ) ); if old_bytes > 0 then declare app: constant Byte_array:= byte_mem(1..old_bytes) & UnZ_Glob.slide(0..x-1); begin Output_uncompressed(app, old_bytes); -- In extreme cases (x very small), we might have some of -- the rejected bytes from byte_mem. if old_bytes > 0 then byte_mem(1..old_bytes):= app(app'Last-(old_bytes-1)..app'Last); end if; end; else Output_uncompressed(UnZ_Glob.slide(0..x-1), old_bytes); if old_bytes > 0 then byte_mem(1..old_bytes):= UnZ_Glob.slide(x-old_bytes..x-1); end if; end if; if full_trace then Ada.Text_IO.Put_Line(""finished]""); end if; end Flush; procedure Flush_if_full(W: in out Integer) is begin if W = wsize then Flush(wsize); W:= 0; end if; end Flush_if_full; ---------------------------------------------------- -- Reproduction of sequences in the output slide. -- ---------------------------------------------------- -- Internal: procedure Adjust_to_Slide( source : in out Integer; remain : in out Natural; part : out Integer; index: Integer) is pragma Inline(Adjust_to_Slide); begin source:= source mod wsize; -- source and index are now in 0..WSize-1 if source > index then part:= wsize-source; else part:= wsize-index; end if; -- NB: part is in 1..WSize (part cannot be 0) if part > remain then part:= remain; end if; -- Now part <= remain remain:= remain - part; -- NB: remain cannot be < 0 end Adjust_to_Slide; procedure Copy_range(source, index: in out Natural; amount: Positive) is pragma Inline(Copy_range); begin if abs (index - source) < amount then -- if source >= index, the effect of copy is -- just like the non-overlapping case for count in reverse 1..amount loop UnZ_Glob.slide(index):= UnZ_Glob.slide(source); index := index + 1; source:= source + 1; end loop; else -- non-overlapping -> copy slice UnZ_Glob.slide( index .. index+amount-1 ):= UnZ_Glob.slide( source..source+amount-1 ); index := index + amount; source:= source + amount; end if; end Copy_range; -- The copying routines: procedure Copy( distance, length: Natural; index : in out Natural ) is source,part,remain: Integer; begin source:= index - distance; remain:= length; loop Adjust_to_Slide(source,remain,part, index); Copy_range(source, index, part); Flush_if_full(index); exit when remain = 0; end loop; end Copy; end UnZ_IO; package body UnZ_Meth is use GID.Decoding_PNG.Huffman; --------[ Method: Inflate ]-------- procedure Inflate_Codes ( huf_dis, huf_lit_len: Huff_tree ) is dis_idx, lit_len_idx: Natural; -- indices in both trees val, val_dis, val_len : Natural; use Interfaces; procedure Get_length is v32, base, offset, extra: Unsigned_32; begin if val <= 264 then val_len:= 3 + (val-257); elsif val >= 285 then val_len:= 258; else v32:= Unsigned_32(val); extra := 1 + (v32-265)/4; base := Shift_Left(8, ((val-265)/4)) + 3; offset:= ((v32-265) and 3) * Shift_Left(2, ((val-265)/4)); val_len:= UnZ_IO.Bit_buffer.Read_and_dump(Natural(extra)) + Natural(base + offset); end if; end Get_length; procedure Get_distance is v32, base, offset, extra: Unsigned_32; begin if val_dis <= 3 then val_dis:= val_dis + 1; else v32:= Unsigned_32(val_dis); base:= Shift_Left(4, ((val_dis-4)/2))+1; offset:= (v32 and 1) * Shift_Left(2, ((val_dis-4)/2)); extra:= (v32-2)/2; val_dis:= UnZ_IO.Bit_buffer.Read_and_dump(Natural(extra)) + Natural(base + offset); end if; end Get_distance; w : Integer:= UnZ_Glob.slide_index; -- more local variable for slide index begin if full_trace then Ada.Text_IO.Put_Line(""Begin Inflate_codes""); end if; if huf_lit_len.last = nil then return; end if; lit_len_idx:= root; -- inflate the coded data main_loop: while not UnZ_Glob.Zip_EOF loop if UnZ_IO.Bit_buffer.Read_and_dump(1) = 0 then lit_len_idx:= huf_lit_len.node(lit_len_idx).zero; else lit_len_idx:= huf_lit_len.node(lit_len_idx).one; end if; if lit_len_idx = nil then raise error_in_image_data; end if; if huf_lit_len.node(lit_len_idx).zero = nil and then huf_lit_len.node(lit_len_idx).one = nil then -- tree node val:= huf_lit_len.node(lit_len_idx).n; case val is when 0 .. 255 => -- It is a litteral UnZ_Glob.slide ( w ) := U8( val ); w:= w + 1; UnZ_IO.Flush_if_full(w); when 256 => -- End of block (EOB) if full_trace then Ada.Text_IO.Put_Line(""Exit Inflate_codes, EOB""); end if; exit main_loop; when 257 .. 285 => -- We have a LZ length/distance code Get_length; if huf_dis.last = nil then -- Empty tree for distances (""fixed""), then read directly val_dis:= UnZ_IO.Bit_buffer.Read_and_dump(5); else dis_idx:= root; while huf_dis.node(dis_idx).zero /= nil or else huf_dis.node(dis_idx).one /= nil loop if UnZ_IO.Bit_buffer.Read_and_dump(1) = 0 then dis_idx:= huf_dis.node(dis_idx).zero; else dis_idx:= huf_dis.node(dis_idx).one; end if; end loop; val_dis:= huf_dis.node(dis_idx).n; end if; Get_distance; UnZ_IO.Copy( distance => val_dis, length => val_len, index => w ); when others => raise error_in_image_data; end case; lit_len_idx:= root; end if; end loop main_loop; UnZ_Glob.slide_index:= w; if full_trace then Ada.Text_IO.Put_Line(""End Inflate_codes""); end if; end Inflate_Codes; procedure Inflate_stored_block is -- Actually, nothing to inflate N : Integer; begin if full_trace then Ada.Text_IO.Put_Line(""Begin Inflate_stored_block""); end if; UnZ_IO.Bit_buffer.Dump_to_byte_boundary; -- Get the block length and its complement N:= UnZ_IO.Bit_buffer.Read_and_dump( 16 ); if N /= Integer( (not UnZ_IO.Bit_buffer.Read_and_dump_U32(16)) and 16#ffff#) then raise error_in_image_data; end if; while N > 0 and then not UnZ_Glob.Zip_EOF loop -- Read and output the non-compressed data N:= N - 1; UnZ_Glob.slide ( UnZ_Glob.slide_index ) := U8( UnZ_IO.Bit_buffer.Read_and_dump(8) ); UnZ_Glob.slide_index:= UnZ_Glob.slide_index + 1; UnZ_IO.Flush_if_full(UnZ_Glob.slide_index); end loop; if full_trace then Ada.Text_IO.Put_Line(""End Inflate_stored_block""); end if; end Inflate_stored_block; -- Copy lengths for literal codes 257..285 copy_lengths_literal : Length_array( 0..30 ) := ( 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 ); -- Extra bits for literal codes 257..285 extra_bits_literal : Length_array( 0..30 ) := ( 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, invalid, invalid ); -- Copy offsets for distance codes 0..29 (30..31: deflate_e) copy_offset_distance : constant Length_array( 0..31 ) := ( 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 32769, 49153 ); -- Extra bits for distance codes extra_bits_distance : constant Length_array( 0..31 ) := ( 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14 ); max_dist: Integer:= 29; -- changed to 31 for deflate_e procedure Inflate_fixed_block is huf_dis, huf_lit_len: Huff_tree; descr_lit_len: Huff_descriptor(0..287); begin if full_trace then Ada.Text_IO.Put_Line(""Begin Inflate_fixed_block""); end if; -- Make the tree descriptor for LZ distances for i in 0 .. 143 loop descr_lit_len(i):= (length => 8, code => 16#30#+i); end loop; for i in 144 .. 255 loop descr_lit_len(i):= (length => 9, code => 16#190#+(i-144)); end loop; for i in 256 .. 279 loop descr_lit_len(i):= (length => 7, code => i-256); end loop; for i in 280 .. 287 loop descr_lit_len(i):= (length => 8, code => 16#C0#+(i-280)); end loop; -- Build the tree according to the descriptor Build(huf_lit_len, descr_lit_len); huf_dis.last:= nil; Inflate_Codes ( huf_dis, huf_lit_len ); if full_trace then Ada.Text_IO.Put_Line(""End Inflate_fixed_block""); end if; end Inflate_fixed_block; procedure Inflate_dynamic_block is type H_vector is array(Natural range <>) of Natural; procedure Make_dynamic_descriptor(h: out Huff_descriptor; lng: in H_vector) is maxLng, code, len: Natural; begin for i in h'Range loop h(i):= (length => lng(i), code => 0); end loop; maxLng:= 0; for i in h'Range loop if maxLng < lng(i) then maxLng:= lng(i); end if; end loop; declare bl_count, next_code: H_vector(0..maxLng):= (others => 0); begin for i in h'Range loop bl_count(lng(i)):= bl_count(lng(i)) + 1; end loop; code:= 0; bl_count(0):= 0; for bits in 1 .. maxLng loop code:= (code + bl_count(bits-1)) * 2; next_code(bits):= code; end loop; for n in h'Range loop len:= lng(n); if len > 0 then h(n).code:= next_code(len); next_code(len):= next_code(len) + 1; -- !! before or after (++) end if; end loop; end; end Make_dynamic_descriptor; huf_dis, huf_lit: Huff_tree; procedure Decode_dynamic_compression_structure is huf_len: Huff_tree; len_idx: Natural; hLit: Natural; hDist: Natural; hCLen: Natural; nExtr: Natural; codeLengthOrder : constant H_vector( 0..18 ) := ( 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ); codeLengthCode: H_vector( codeLengthOrder'Range ):= (others => 0); value,copyLength: Natural; begin hLit := UnZ_IO.Bit_buffer.Read_and_dump(5); hDist:= UnZ_IO.Bit_buffer.Read_and_dump(5); hCLen:= UnZ_IO.Bit_buffer.Read_and_dump(4); for i in 0 .. hCLen+3 loop codeLengthCode(codeLengthOrder(i)):= UnZ_IO.Bit_buffer.Read_and_dump(3); end loop; declare descr_code: Huff_descriptor(codeLengthCode'Range); begin Make_dynamic_descriptor(descr_code, codeLengthCode); Build(huf_len, descr_code); end; declare cl_lit: H_vector(0..(hLit+257)-1); cl_dis: H_vector(0..(hDist+1)-1); cl_combined: H_vector(0..(hLit+257+hDist+1)-1); -- max 321 descr_lit: Huff_descriptor( cl_lit'Range ); descr_dis: Huff_descriptor( cl_dis'Range ); begin nExtr:= 0; len_idx:= root; while nExtr <= hLit+257+hDist loop if UnZ_IO.Bit_buffer.Read_and_dump(1) = 0 then len_idx:= huf_len.node(len_idx).zero; else len_idx:= huf_len.node(len_idx).one; end if; if len_idx = nil then raise error_in_image_data; end if; if huf_len.node(len_idx).zero = nil and then huf_len.node(len_idx).one = nil then value:= huf_len.node(len_idx).n; case value is when 0..15 => -- length of code in bits (0..15) cl_combined(nExtr):= value; nExtr:= nExtr + 1; -- !! ++ when 16 => -- repeat last length 3 to 6 times for copy in 1 .. 3 + UnZ_IO.Bit_buffer.Read_and_dump(2) loop cl_combined(nExtr):= cl_combined(nExtr-1); nExtr:= nExtr + 1; end loop; when 17 => -- 3 to 10 zero length codes for copy in 1 .. 3 + UnZ_IO.Bit_buffer.Read_and_dump(3) loop cl_combined(nExtr):= 0; nExtr:= nExtr + 1; end loop; when 18 => -- 11 to 138 zero length codes for copy in 1 .. 11 + UnZ_IO.Bit_buffer.Read_and_dump(7) loop cl_combined(nExtr):= 0; nExtr:= nExtr + 1; end loop; when others => null; -- or error...!! end case; len_idx:= root; end if; end loop; cl_lit:= cl_combined(cl_lit'Range); cl_dis:= cl_combined(hLit+257..cl_combined'Last); -- NB: we could use only cl_combined if Make_dynamic_descriptor uses lng'First Make_dynamic_descriptor(descr_lit, cl_lit); Build(huf_lit, descr_lit); Make_dynamic_descriptor(descr_dis, cl_dis); Build(huf_dis, descr_dis); end; end Decode_dynamic_compression_structure; begin if full_trace then Ada.Text_IO.Put_Line(""Begin Inflate_dynamic_block""); end if; Decode_dynamic_compression_structure; Inflate_Codes( huf_dis, huf_lit ); if full_trace then Ada.Text_IO.Put_Line(""End Inflate_dynamic_block""); end if; end Inflate_dynamic_block; procedure Inflate_Block( last_block: out Boolean ) is begin last_block:= Boolean'Val(UnZ_IO.Bit_buffer.Read_and_dump(1)); case UnZ_IO.Bit_buffer.Read_and_dump(2) is -- Block type = 0,1,2,3 when 0 => Inflate_stored_block; when 1 => Inflate_fixed_block; when 2 => Inflate_dynamic_block; when others => raise error_in_image_data; -- Bad block type (3) end case; end Inflate_Block; procedure Inflate is is_last_block: Boolean; blocks: Positive:= 1; begin if deflate_e_mode then copy_lengths_literal(28):= 3; -- instead of 258 extra_bits_literal(28):= 16; -- instead of 0 max_dist:= 31; end if; loop Inflate_Block ( is_last_block ); exit when is_last_block; blocks:= blocks+1; end loop; UnZ_IO.Flush( UnZ_Glob.slide_index ); UnZ_Glob.slide_index:= 0; if some_trace then Ada.Text_IO.Put(""# blocks:"" & Integer'Image(blocks)); end if; UnZ_Glob.crc32val := CRC32.Final( UnZ_Glob.crc32val ); end Inflate; end UnZ_Meth; -------------------------------------------------------------------- -- End of the Decompression part, and of UnZip.Decompress excerpt -- -------------------------------------------------------------------- ch: Chunk_head; b: U8; z_crc, dummy: U32; begin -- Load if interlaced then x_max:= (image.width+7)/8 - 1; y_max:= (image.height+7)/8 - 1; else x_max:= X_range'Last; y_max:= Y_range'Last; end if; loop Read(image, ch); case ch.kind is when IEND => -- 11.2.5 IEND Image trailer exit; when IDAT => -- 11.2.4 IDAT Image data -- -- NB: the compressed data may hold on several IDAT chunks. -- It means that right in the middle of compressed data, you -- can have a chunk crc, and a new IDAT header!... -- Get_Byte(image.buffer, b); -- zlib compression method/flags code Get_Byte(image.buffer, b); -- Additional flags/check bits -- UnZ_IO.Init_Buffers(IDAT_reserve => Natural(ch.length) - 2); -- ^ we indicate that we have a byte reserve of chunk's length, -- minus both zlib header bytes. UnZ_Meth.Inflate; Big_endian(image.buffer, z_crc); -- zlib Check value -- if z_crc /= U32(UnZ_Glob.crc32val) then -- ada.text_io.put(z_crc 'img & UnZ_Glob.crc32val'img); -- Raise_exception( -- error_in_image_data'Identity, -- ""PNG: deflate stream corrupt"" -- ); -- end if; -- ** Mystery: this check fail even with images which decompress perfectly -- ** Is CRC init value different between zip and zlib ? Is it Adler32 ? Big_endian(image.buffer, dummy); -- last IDAT chunk's CRC (then, on compressed data) -- when tEXt => -- 11.3.4.3 tEXt Textual data for i in 1..ch.length loop Get_Byte(image.buffer, b); if some_trace then if b=0 then -- separates keyword from message Ada.Text_IO.New_Line; else Ada.Text_IO.Put(Character'Val(b)); end if; end if; end loop; Big_endian(image.buffer, dummy); -- chunk's CRC when others => -- Skip chunk data and CRC for i in 1..ch.length + 4 loop Get_Byte(image.buffer, b); end loop; end case; end loop; if some_trace then for f in Filter_method_0 loop Ada.Text_IO.Put_Line( ""Filter: "" & Filter_method_0'Image(f) & Integer'Image(filter_stat(f)) ); end loop; end if; Feedback(100); end Load; end GID.Decoding_PNG; ",12257,False,2158.173997929609,median "-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Utilities; with Parameters; with Ada.Characters.Latin_1; package body Port_Specification.Makefile is package UTL renames Utilities; package PM renames Parameters; package LAT renames Ada.Characters.Latin_1; -------------------------------------------------------------------------------------------- -- generator -------------------------------------------------------------------------------------------- procedure generator (specs : Portspecs; variant : String; opsys : supported_opsys; arch : supported_arch; output_file : String ) is procedure send (data : String; use_put : Boolean := False); procedure send (varname, value : String); procedure send (varname : String; value : HT.Text); procedure send (varname : String; crate : string_crate.Vector; flavor : Positive); procedure send (varname : String; crate : list_crate.Map; flavor : Positive); procedure send (varname : String; value : Boolean; dummy : Boolean); procedure send (varname : String; value, default : Integer); procedure print_item (position : string_crate.Cursor); procedure print_module (position : string_crate.Cursor); procedure print_verbation (position : string_crate.Cursor); procedure print_if_defined (varname, value : String); procedure dump_list (position : list_crate.Cursor); procedure dump_variant_index (position : list_crate.Cursor); procedure dump_distfiles (position : string_crate.Cursor); procedure dump_makesum (position : string_crate.Cursor); procedure dump_ext_zip (position : string_crate.Cursor); procedure dump_ext_7z (position : string_crate.Cursor); procedure dump_ext_lha (position : string_crate.Cursor); procedure dump_ext_deb (position : string_crate.Cursor); procedure dump_line (position : string_crate.Cursor); procedure dump_extract_head_tail (position : list_crate.Cursor); procedure dump_dirty_extract (position : string_crate.Cursor); procedure dump_standard_target (target : String); procedure dump_opsys_target (target : String); procedure dump_option_target (target : String); procedure dump_broken; procedure dump_catchall; procedure dump_has_configure (value : HT.Text); procedure dump_distname; procedure dump_license; procedure dump_subr; procedure dump_info; procedure dump_conditional_vars; write_to_file : constant Boolean := (output_file /= """"); makefile_handle : TIO.File_Type; varname_prefix : HT.Text; procedure send (data : String; use_put : Boolean := False) is begin if write_to_file then if use_put then TIO.Put (makefile_handle, data); else TIO.Put_Line (makefile_handle, data); end if; else if use_put then TIO.Put (data); else TIO.Put_Line (data); end if; end if; end send; procedure print_if_defined (varname, value : String) is begin if value /= """" then send (varname & LAT.Equals_Sign & value); end if; end print_if_defined; procedure send (varname, value : String) is begin send (varname & LAT.Equals_Sign & value); end send; procedure send (varname : String; value : HT.Text) is begin if not HT.IsBlank (value) then send (varname & LAT.Equals_Sign & HT.USS (value)); end if; end send; procedure send (varname : String; value : Boolean; dummy : Boolean) is begin if value then send (varname & LAT.Equals_Sign & ""yes""); end if; end send; procedure send (varname : String; value, default : Integer) is begin if value /= default then send (varname & LAT.Equals_Sign & HT.int2str (value)); end if; end send; procedure send (varname : String; crate : string_crate.Vector; flavor : Positive) is begin if crate.Is_Empty then return; end if; case flavor is when 1 => send (varname & ""="", True); crate.Iterate (Process => print_item'Access); send (""""); when 2 => varname_prefix := HT.SUS (varname); crate.Iterate (Process => dump_distfiles'Access); when 3 => crate.Iterate (Process => dump_ext_zip'Access); when 4 => crate.Iterate (Process => dump_ext_7z'Access); when 5 => crate.Iterate (Process => dump_ext_lha'Access); when 7 => crate.Iterate (Process => dump_dirty_extract'Access); when 9 => send (varname & ""="", True); crate.Iterate (Process => dump_makesum'Access); send (""""); when 10 => send (varname & ""="", True); crate.Iterate (Process => print_module'Access); send (""""); when 11 => crate.Iterate (Process => dump_ext_deb'Access); when others => raise dev_error; end case; end send; procedure send (varname : String; crate : list_crate.Map; flavor : Positive) is begin varname_prefix := HT.SUS (varname); case flavor is when 1 => crate.Iterate (Process => dump_list'Access); when 6 => crate.Iterate (Process => dump_extract_head_tail'Access); when 8 => crate.Iterate (Process => dump_variant_index'Access); when others => raise dev_error; end case; end send; procedure dump_list (position : list_crate.Cursor) is NDX : String := HT.USS (varname_prefix) & ""_"" & HT.USS (list_crate.Element (position).group) & LAT.Equals_Sign; begin send (NDX, True); list_crate.Element (position).list.Iterate (Process => print_item'Access); send (""""); end dump_list; procedure dump_variant_index (position : list_crate.Cursor) is index : String := HT.USS (list_crate.Element (position).group); begin if index = variant then send (HT.USS (varname_prefix) & LAT.Equals_Sign, True); list_crate.Element (position).list.Iterate (Process => print_item'Access); send (""""); end if; end dump_variant_index; procedure dump_extract_head_tail (position : list_crate.Cursor) is NDX : String := HT.USS (varname_prefix) & ""_"" & HT.USS (list_crate.Element (position).group) & LAT.Equals_Sign; begin if not list_crate.Element (position).list.Is_Empty then send (NDX, True); list_crate.Element (position).list.Iterate (Process => print_item'Access); send (""""); end if; end dump_extract_head_tail; procedure print_item (position : string_crate.Cursor) is index : Natural := string_crate.To_Index (position); begin if index > 1 then send ("" "", True); end if; send (HT.USS (string_crate.Element (position)), True); end print_item; procedure print_module (position : string_crate.Cursor) is module_w_args : String := HT.USS (string_crate.Element (position)); module : String := HT.part_1 (module_w_args); begin if not passive_uses_module (module) then send (module_w_args & "" "", True); end if; end print_module; procedure dump_line (position : string_crate.Cursor) is begin send (HT.USS (string_crate.Element (position))); end dump_line; procedure dump_distfiles (position : string_crate.Cursor) is index : String := HT.int2str (string_crate.To_Index (position)); pload : String := HT.USS (string_crate.Element (position)); NDX : String := HT.USS (varname_prefix) & ""_"" & index & LAT.Equals_Sign; begin if HT.leads (pload, ""generated:"") then declare group : String := HT.part_2 (pload, "":""); dlsite : String := HT.USS (specs.dl_sites.Element (HT.SUS (group)).list.First_Element); begin if HT.leads (dlsite, ""GITHUB/"") or else HT.leads (dlsite, ""GITHUB_PRIVATE/"") or else HT.leads (dlsite, ""GHPRIV/"") then send (NDX & generate_github_distfile (dlsite) & "":"" & group); return; elsif HT.leads (dlsite, ""GITLAB/"") then send (NDX & generate_gitlab_distfile (dlsite) & "":"" & group); return; elsif HT.leads (dlsite, ""CRATES/"") then send (NDX & generate_crates_distfile (dlsite) & "":"" & group); return; else -- seems like a mistake, fall through null; end if; end; end if; send (NDX & pload); end dump_distfiles; procedure dump_distname is begin if not HT.IsBlank (specs.distname) then send (""DISTNAME"", specs.distname); else if HT.equivalent (list_crate.Element (specs.dl_sites.First).group, dlgroup_none) then return; end if; declare first_dlsite : constant String := HT.USS (specs.dl_sites.Element (HT.SUS (dlgroup_main)).list.First_Element); begin if HT.leads (first_dlsite, ""GITHUB/"") or else HT.leads (first_dlsite, ""GITHUB_PRIVATE/"") or else HT.leads (first_dlsite, ""GHPRIV/"") then send (""DISTNAME"", generate_github_distname (first_dlsite)); elsif HT.leads (first_dlsite, ""GITLAB/"") then send (""DISTNAME"", generate_gitlab_distname (first_dlsite)); elsif HT.leads (first_dlsite, ""CRATES/"") then send (""DISTNAME"", generate_crates_distname (first_dlsite)); end if; end; end if; end dump_distname; procedure dump_makesum (position : string_crate.Cursor) is index : Natural := string_crate.To_Index (position); begin send (HT.int2str (index) & "" "", True); end dump_makesum; procedure dump_ext_zip (position : string_crate.Cursor) is N : String := HT.USS (string_crate.Element (position)); begin send (""EXTRACT_HEAD_"" & N & ""=/usr/bin/unzip -qo""); send (""EXTRACT_TAIL_"" & N & ""=-d ${EXTRACT_WRKDIR_"" & N & ""}""); end dump_ext_zip; procedure dump_ext_7z (position : string_crate.Cursor) is N : String := HT.USS (string_crate.Element (position)); begin send (""EXTRACT_HEAD_"" & N & ""=7z x -y -o${EXTRACT_WRKDIR_"" & N & ""} >/dev/null""); send (""EXTRACT_TAIL_"" & N & ""=# empty""); end dump_ext_7z; procedure dump_ext_lha (position : string_crate.Cursor) is N : String := HT.USS (string_crate.Element (position)); begin send (""EXTRACT_HEAD_"" & N & ""=lha xfpw=${EXTRACT_WRKDIR_"" & N & ""}""); send (""EXTRACT_TAIL_"" & N & ""=# empty""); end dump_ext_lha; procedure dump_ext_deb (position : string_crate.Cursor) is N : String := HT.USS (string_crate.Element (position)); begin send (""EXTRACT_HEAD_"" & N & ""=ar -x""); send (""EXTRACT_TAIL_"" & N & ""=&& ${TAR} -xf data.tar.*""); end dump_ext_deb; procedure dump_dirty_extract (position : string_crate.Cursor) is N : String := HT.USS (string_crate.Element (position)); begin send (""DIRTY_EXTRACT_"" & N & ""=yes""); end dump_dirty_extract; procedure dump_standard_target (target : String) is target_text : HT.Text := HT.SUS (target); begin if specs.make_targets.Contains (target_text) then send (""""); send (target & LAT.Colon); specs.make_targets.Element (target_text).list.Iterate (Process => dump_line'Access); end if; end dump_standard_target; procedure dump_opsys_target (target : String) is os_target : HT.Text := HT.SUS (target & LAT.Hyphen & UTL.lower_opsys (opsys)); std_target : String := target & ""-opsys""; begin if specs.make_targets.Contains (os_target) then send (""""); send (std_target & LAT.Colon); send (LAT.HT & ""# "" & UTL.mixed_opsys (opsys) & ""-specific""); specs.make_targets.Element (os_target).list.Iterate (Process => dump_line'Access); end if; end dump_opsys_target; procedure dump_option_target (target : String) is procedure precheck (position : string_crate.Cursor); procedure check (position : string_crate.Cursor); -- Logic: considered ""used"" if option is OFF and -