diff
stringlengths 41
2.03M
| msg
stringlengths 1
1.5k
⌀ | repo
stringlengths 5
40
| sha
stringlengths 40
40
| time
stringlengths 20
20
|
---|---|---|---|---|
mmm a / hphp / hack / src / search / namespaceSearchService . ml <nl> ppp b / hphp / hack / src / search / namespaceSearchService . ml <nl> let find_exact_match ( namespace : string ) : nss_node = <nl> ) <nl> end <nl> <nl> + ( * Produce a list of results for the current node * ) <nl> + let get_matches_for_node ( node : nss_node ) : si_results = <nl> + Hashtbl . fold ( fun _key value acc - > <nl> + { <nl> + si_name = value . nss_name ; <nl> + si_kind = SI_Namespace ; <nl> + si_filehash = 0L ; <nl> + } : : acc <nl> + ) node . nss_children [ ] <nl> + <nl> ( * Find all namespaces that match this prefix * ) <nl> let find_matching_namespaces ( query_text : string ) : si_results = <nl> <nl> ( * Trivial case * ) <nl> if query_text = " " then begin <nl> [ ] <nl> + <nl> ( * Special case - just give root namespace only * ) <nl> end else if query_text = " \ \ " then begin <nl> - <nl> - ( * Play that fun _key music * ) <nl> - Hashtbl . fold ( fun _key value acc - > <nl> - { <nl> - si_name = value . nss_name ; <nl> - si_kind = SI_Namespace ; <nl> - si_filehash = 0L ; <nl> - } : : acc <nl> - ) root_namespace . nss_children [ ] <nl> + get_matches_for_node root_namespace <nl> <nl> ( * Normal case , search for matches * ) <nl> end else begin <nl> let find_matching_namespaces ( query_text : string ) : si_results = <nl> match Hashtbl . find_opt ! current_node . nss_children leaf_name with <nl> | Some matching_leaf - > <nl> current_node : = matching_leaf ; <nl> + matches : = get_matches_for_node matching_leaf ; <nl> | None - > <nl> + matches : = [ ] ; <nl> Hashtbl . iter ( fun key _ - > <nl> if Core_kernel . String . is_substring key ~ substring : leaf_name then begin <nl> let node = Hashtbl . find ! current_node . nss_children key in <nl> mmm a / hphp / hack / test / integration / symbol_index_test . ml <nl> ppp b / hphp / hack / test / integration / symbol_index_test . ml <nl> let test_namespace_map ( harness : Test_harness . t ) : bool = <nl> let matches = find_matching_namespaces " " in <nl> IA . assert_equals 0 ( List . length matches ) " Empty string / zero matches " ; <nl> <nl> - ( * Special case : single backslash should show root namespaces * ) <nl> + ( * Special case : single backslash should show at least these root namespaces * ) <nl> let matches = find_matching_namespaces " \ \ " in <nl> assert_ns_matches " Str " matches ; <nl> assert_ns_matches " StrFb " matches ; <nl> assert_ns_matches " HH " matches ; <nl> - IA . assert_equals 3 ( List . length matches ) " Special case root namespace " ; <nl> - true <nl> <nl> + ( * Normal use case * ) <nl> + Hh_logger . log " Reached the hh section " ; <nl> + let matches = find_matching_namespaces " hh " in <nl> + assert_ns_matches " Lib " matches ; <nl> + let matches = find_matching_namespaces " \ \ HH \ \ " in <nl> + assert_ns_matches " Lib " matches ; <nl> + <nl> + true <nl> ; ; <nl> <nl> ( * Main test suite * ) <nl> | Fix values at the beginning of a namespace | facebook/hhvm | 2814bb2b38f688b3a77fce61993a165b9879ea38 | 2019-06-10T19:57:06Z |
mmm a / CMakeLists . txt <nl> ppp b / CMakeLists . txt <nl> set ( SEED " 0x $ { SEED_ } " CACHE STRING " Random seed for testing " ) <nl> # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # <nl> <nl> include ( CompileBoost ) <nl> - if ( WITH_TLS ) <nl> - add_subdirectory ( FDBLibTLS ) <nl> - endif ( ) <nl> add_subdirectory ( flow ) <nl> add_subdirectory ( fdbrpc ) <nl> add_subdirectory ( fdbclient ) <nl> mmm a / Makefile <nl> ppp b / Makefile <nl> ifeq ( $ ( PLATFORM ) , Linux ) <nl> CXXFLAGS + = - std = c + + 17 <nl> <nl> BOOST_BASEDIR ? = / opt <nl> - TLS_LIBDIR ? = / usr / local / lib <nl> + TLS_LIBDIR ? = / usr / local / lib64 <nl> DLEXT : = so <nl> java_DLEXT : = so <nl> TARGET_LIBC_VERSION ? = 2 . 11 <nl> else ifeq ( $ ( PLATFORM ) , Darwin ) <nl> . LIBPATTERNS : = lib % . dylib lib % . a <nl> <nl> BOOST_BASEDIR ? = $ { HOME } <nl> - TLS_LIBDIR ? = / usr / local / lib <nl> + TLS_LIBDIR ? = / usr / local / lib64 <nl> DLEXT : = dylib <nl> java_DLEXT : = jnilib <nl> else <nl> CFLAGS + = - DTLS_DISABLED <nl> FDB_TLS_LIB : = <nl> TLS_LIBS : = <nl> else <nl> - FDB_TLS_LIB : = lib / libFDBLibTLS . a <nl> - TLS_LIBS + = $ ( addprefix $ ( TLS_LIBDIR ) / , libtls . a libssl . a libcrypto . a ) <nl> + FDB_TLS_LIB : = <nl> + TLS_LIBS + = $ ( addprefix $ ( TLS_LIBDIR ) / , libssl . a libcrypto . a ) <nl> endif <nl> <nl> CXXFLAGS + = - Wno - deprecated - DBOOST_ERROR_CODE_HEADER_ONLY - DBOOST_SYSTEM_NO_DEPRECATED <nl> VPATH + = $ ( addprefix : , $ ( filter - out lib , $ ( patsubst - L % , % , $ ( filter - L % , $ ( LDFLAGS ) <nl> <nl> CS_PROJECTS : = flow / actorcompiler flow / coveragetool fdbclient / vexillographer <nl> CPP_PROJECTS : = flow fdbrpc fdbclient fdbbackup fdbserver fdbcli bindings / c bindings / java fdbmonitor bindings / flow / tester bindings / flow <nl> - ifndef TLS_DISABLED <nl> - CPP_PROJECTS + = FDBLibTLS <nl> - endif <nl> OTHER_PROJECTS : = bindings / python bindings / ruby bindings / go <nl> <nl> CS_MK_GENERATED : = $ ( CS_PROJECTS : = / generated . mk ) <nl> mmm a / README . md <nl> ppp b / README . md <nl> If you want to create a package you have to tell cmake what platform it is for . <nl> And then you can build by simply calling ` cpack ` . So for debian , call : <nl> <nl> ` ` ` <nl> - cmake - DINSTALL_LAYOUT = DEB < FDB_SOURCE_DIR > <nl> + cmake < FDB_SOURCE_DIR > <nl> make <nl> - cpack <nl> + cpack - G DEB <nl> ` ` ` <nl> <nl> For RPM simply replace ` DEB ` with ` RPM ` . <nl> To generate a installable package , you have to call CMake with the corresponding <nl> arguments and then use cpack to generate the package : <nl> <nl> ` ` ` sh <nl> - cmake - DINSTALL_LAYOUT = OSX < FDB_SOURCE_DIR > <nl> + cmake < FDB_SOURCE_DIR > <nl> make <nl> - cpack <nl> + cpack - G productbuild <nl> ` ` ` <nl> <nl> # # # Windows <nl> mmm a / bindings / c / CMakeLists . txt <nl> ppp b / bindings / c / CMakeLists . txt <nl> else ( ) <nl> endif ( ) <nl> add_dependencies ( fdb_c fdb_c_generated fdb_c_options ) <nl> target_link_libraries ( fdb_c PUBLIC $ < BUILD_INTERFACE : fdbclient > ) <nl> + if ( APPLE ) <nl> + set ( symbols $ { CMAKE_CURRENT_BINARY_DIR } / fdb_c . symbols ) <nl> + add_custom_command ( OUTPUT $ { symbols } <nl> + COMMAND $ < TARGET_FILE : Python : : Interpreter > $ { CMAKE_CURRENT_SOURCE_DIR } / symbolify . py <nl> + $ { CMAKE_CURRENT_SOURCE_DIR } / foundationdb / fdb_c . h <nl> + $ { symbols } <nl> + DEPENDS $ { CMAKE_CURRENT_SOURCE_DIR } / symbolify . py $ { CMAKE_CURRENT_SOURCE_DIR } / foundationdb / fdb_c . h <nl> + COMMENT " Generate exported_symbols_list " ) <nl> + add_custom_target ( exported_symbols_list DEPENDS $ { symbols } ) <nl> + add_dependencies ( fdb_c exported_symbols_list ) <nl> + target_link_options ( fdb_c PRIVATE " LINKER : - no_weak_exports , - exported_symbols_list , $ { symbols } " ) <nl> + elseif ( WIN32 ) <nl> + else ( ) <nl> + target_link_options ( fdb_c PRIVATE " LINKER : - - version - script = $ { CMAKE_CURRENT_SOURCE_DIR } / fdb_c . map , - z , nodelete " ) <nl> + endif ( ) <nl> target_include_directories ( fdb_c PUBLIC <nl> $ < BUILD_INTERFACE : $ { CMAKE_CURRENT_BINARY_DIR } > <nl> $ < BUILD_INTERFACE : $ { CMAKE_CURRENT_SOURCE_DIR } > <nl> mmm a / bindings / c / fdb_c . cpp <nl> ppp b / bindings / c / fdb_c . cpp <nl> fdb_error_t fdb_network_set_option ( FDBNetworkOption option , <nl> } <nl> <nl> fdb_error_t fdb_setup_network_impl ( ) { <nl> - CATCH_AND_RETURN ( API - > setupNetwork ( ) ; ) ; <nl> + CATCH_AND_RETURN ( <nl> + try { <nl> + API - > setupNetwork ( ) ; <nl> + } catch ( boost : : system : : system_error & e ) { <nl> + return error_code_tls_error ; <nl> + } ) ; <nl> } <nl> <nl> fdb_error_t fdb_setup_network_v13 ( const char * localAddress ) { <nl> new file mode 100644 <nl> index 0000000000 . . 55d8dc81fd <nl> mmm / dev / null <nl> ppp b / bindings / c / symbolify . py <nl> <nl> + if __name__ = = ' __main__ ' : <nl> + import re <nl> + import sys <nl> + r = re . compile ( ' DLLEXPORT [ ^ ( ] * ( fdb_ [ ^ ( ] * ) [ ( ] ' ) <nl> + ( fdb_c_h , symbols_file ) = sys . argv [ 1 : ] <nl> + with open ( fdb_c_h , ' r ' ) as f : <nl> + symbols = sorted ( set ( ' _ ' + m . group ( 1 ) for m in r . finditer ( f . read ( ) ) ) ) <nl> + with open ( symbols_file , ' w ' ) as f : <nl> + f . write ( ' \ n ' . join ( symbols ) ) <nl> + f . write ( ' \ n ' ) <nl> mmm a / bindings / flow / fdb_flow . actor . cpp <nl> ppp b / bindings / flow / fdb_flow . actor . cpp <nl> void fdb_flow_test ( ) { <nl> fdb - > setupNetwork ( ) ; <nl> startThread ( networkThread , fdb ) ; <nl> <nl> - g_network = newNet2 ( false ) ; <nl> + g_network = newNet2 ( false ) ; <nl> <nl> openTraceFile ( NetworkAddress ( ) , 1000000 , 1000000 , " . " ) ; <nl> systemMonitor ( ) ; <nl> mmm a / bindings / flow / tester / local . mk <nl> ppp b / bindings / flow / tester / local . mk <nl> <nl> fdb_flow_tester_CFLAGS : = - Ibindings / c $ ( fdbrpc_CFLAGS ) <nl> fdb_flow_tester_LDFLAGS : = - Llib $ ( fdbrpc_LDFLAGS ) - lfdb_c <nl> fdb_flow_tester_LIBS : = lib / libfdb_flow . a lib / libflow . a lib / libfdb_c . $ ( DLEXT ) <nl> + fdb_flow_tester_STATIC_LIBS : = $ ( TLS_LIBS ) <nl> <nl> fdb_flow_tester : lib / libfdb_c . $ ( DLEXT ) <nl> @ mkdir - p bindings / flow / bin <nl> mmm a / bindings / go / src / fdb / generated . go <nl> ppp b / bindings / go / src / fdb / generated . go <nl> func ( o NetworkOptions ) SetTraceFormat ( param string ) error { <nl> return o . setOpt ( 34 , [ ] byte ( param ) ) <nl> } <nl> <nl> + / / Select clock source for trace files . now ( default ) or realtime are supported . <nl> + / / <nl> + / / Parameter : Trace clock source <nl> + func ( o NetworkOptions ) SetTraceClockSource ( param string ) error { <nl> + return o . setOpt ( 35 , [ ] byte ( param ) ) <nl> + } <nl> + <nl> / / Set internal tuning or debugging knobs <nl> / / <nl> / / Parameter : knob_name = knob_value <nl> mmm a / bindings / go / src / fdb / range . go <nl> ppp b / bindings / go / src / fdb / range . go <nl> type RangeOptions struct { <nl> / / Reverse indicates that the read should be performed in lexicographic <nl> / / ( false ) or reverse lexicographic ( true ) order . When Reverse is true and <nl> / / Limit is non - zero , the last Limit key - value pairs in the range are <nl> - / / returned . <nl> + / / returned . Reading ranges in reverse is supported natively by the <nl> + / / database and should have minimal extra cost . <nl> Reverse bool <nl> } <nl> <nl> mmm a / bindings / java / JavaWorkload . cpp <nl> ppp b / bindings / java / JavaWorkload . cpp <nl> struct JVM { <nl> { { " send " , " ( JZ ) V " , reinterpret_cast < void * > ( & promiseSend ) } } ) ; <nl> auto fdbClass = getClass ( " com / apple / foundationdb / FDB " ) ; <nl> jmethodID selectMethod = <nl> - env - > GetStaticMethodID ( fdbClass , " selectAPIVersion " , " ( IZ ) Lcom / apple / foundationdb / FDB ; " ) ; <nl> + env - > GetStaticMethodID ( fdbClass , " selectAPIVersion " , " ( I ) Lcom / apple / foundationdb / FDB ; " ) ; <nl> checkException ( ) ; <nl> - env - > CallStaticObjectMethod ( fdbClass , selectMethod , jint ( 700 ) , jboolean ( false ) ) ; <nl> + auto fdbInstance = env - > CallStaticObjectMethod ( fdbClass , selectMethod , jint ( 700 ) ) ; <nl> + checkException ( ) ; <nl> + env - > CallObjectMethod ( fdbInstance , getMethod ( fdbClass , " disableShutdownHook " , " ( ) V " ) ) ; <nl> checkException ( ) ; <nl> } <nl> <nl> mmm a / bindings / java / src / main / com / apple / foundationdb / FDB . java <nl> ppp b / bindings / java / src / main / com / apple / foundationdb / FDB . java <nl> public Thread newThread ( Runnable r ) { <nl> private volatile boolean netStarted = false ; <nl> private volatile boolean netStopped = false ; <nl> volatile boolean warnOnUnclosed = true ; <nl> + private boolean useShutdownHook = true ; <nl> + private Thread shutdownHook ; <nl> private final Semaphore netRunning = new Semaphore ( 1 ) ; <nl> private final NetworkOptions options ; <nl> <nl> public Thread newThread ( Runnable r ) { <nl> * Called only once to create the FDB singleton . <nl> * / <nl> private FDB ( int apiVersion ) { <nl> - this ( apiVersion , true ) ; <nl> - } <nl> - <nl> - private FDB ( int apiVersion , boolean controlRuntime ) { <nl> this . apiVersion = apiVersion ; <nl> options = new NetworkOptions ( this : : Network_setOption ) ; <nl> - if ( controlRuntime ) { <nl> - Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( this : : stopNetwork ) ) ; <nl> - } <nl> } <nl> <nl> / * * <nl> public static FDB instance ( ) throws FDBException { <nl> * object . < br > < br > <nl> * <nl> * Warning : When using the multi - version client API , setting an API version that <nl> - * is not supported by a particular client library will prevent that client from <nl> + * is not supported by a particular client library will prevent that client from <nl> * being used to connect to the cluster . In particular , you should not advance <nl> - * the API version of your application after upgrading your client until the <nl> + * the API version of your application after upgrading your client until the <nl> * cluster has also been upgraded . <nl> * <nl> * @ param version the API version required <nl> public static FDB instance ( ) throws FDBException { <nl> * @ return the FoundationDB API object <nl> * / <nl> public static FDB selectAPIVersion ( final int version ) throws FDBException { <nl> - return selectAPIVersion ( version , true ) ; <nl> - } <nl> - <nl> - / * * <nl> - This function is called from C + + if the VM is controlled directly from FDB <nl> - * / <nl> - private static synchronized FDB selectAPIVersion ( final int version , boolean controlRuntime ) throws FDBException { <nl> if ( singleton ! = null ) { <nl> if ( version ! = singleton . getAPIVersion ( ) ) { <nl> throw new IllegalArgumentException ( <nl> private static synchronized FDB selectAPIVersion ( final int version , boolean cont <nl> throw new IllegalArgumentException ( " API version not supported ( maximum 700 ) " ) ; <nl> <nl> Select_API_version ( version ) ; <nl> - FDB fdb = new FDB ( version , controlRuntime ) ; <nl> + singleton = new FDB ( version ) ; <nl> <nl> - return singleton = fdb ; <nl> + return singleton ; <nl> + } <nl> + <nl> + / * * <nl> + * Disables shutdown hook that stops network thread upon process shutdown . This is useful if you need to run <nl> + * your own shutdown hook that uses the FDB instance and you need to avoid race conditions <nl> + * with the default shutdown hook . Replacement shutdown hook should stop the network thread manually <nl> + * by calling { @ link # stopNetwork } . <nl> + * / <nl> + public synchronized void disableShutdownHook ( ) { <nl> + useShutdownHook = false ; <nl> + if ( shutdownHook ! = null ) { <nl> + / / If this method was called after network thread started and shutdown hook was installed , <nl> + / / remove this hook <nl> + Runtime . getRuntime ( ) . removeShutdownHook ( shutdownHook ) ; <nl> + / / Release thread reference for GC <nl> + shutdownHook = null ; <nl> + } <nl> } <nl> <nl> / * * <nl> public synchronized void startNetwork ( Executor e ) throws FDBException , IllegalSt <nl> if ( netStarted ) { <nl> return ; <nl> } <nl> + if ( useShutdownHook ) { <nl> + / / Register shutdown hook that stops network thread if user did not opt out <nl> + shutdownHook = new Thread ( this : : stopNetwork , " fdb - shutdown - hook " ) ; <nl> + Runtime . getRuntime ( ) . addShutdownHook ( shutdownHook ) ; <nl> + } <nl> Network_setup ( ) ; <nl> netStarted = true ; <nl> <nl> protected static boolean evalErrorPredicate ( int predicate , int code ) { <nl> private native boolean Error_predicate ( int predicate , int code ) ; <nl> <nl> private native long Database_create ( String clusterFilePath ) throws FDBException ; <nl> - } <nl> + } <nl> \ No newline at end of file <nl> mmm a / bindings / java / src / main / com / apple / foundationdb / ReadTransaction . java <nl> ppp b / bindings / java / src / main / com / apple / foundationdb / ReadTransaction . java <nl> <nl> * < i > first < / i > keys in the range . Pass { @ link # ROW_LIMIT_UNLIMITED } if this query <nl> * should not limit the number of results . If { @ code reverse } is { @ code true } rows <nl> * will be limited starting at the end of the range . <nl> - * @ param reverse return results starting at the end of the range in reverse order <nl> + * @ param reverse return results starting at the end of the range in reverse order . <nl> + * Reading ranges in reverse is supported natively by the database and should <nl> + * have minimal extra cost . <nl> * <nl> * @ return a handle to access the results of the asynchronous call <nl> * / <nl> <nl> * < i > first < / i > keys in the range . Pass { @ link # ROW_LIMIT_UNLIMITED } if this query <nl> * should not limit the number of results . If { @ code reverse } is { @ code true } rows <nl> * will be limited starting at the end of the range . <nl> - * @ param reverse return results starting at the end of the range in reverse order <nl> + * @ param reverse return results starting at the end of the range in reverse order . <nl> + * Reading ranges in reverse is supported natively by the database and should <nl> + * have minimal extra cost . <nl> * @ param mode provide a hint about how the results are to be used . This <nl> * can provide speed improvements or efficiency gains based on the caller ' s <nl> * knowledge of the upcoming access pattern . <nl> <nl> * < i > first < / i > keys in the range . Pass { @ link # ROW_LIMIT_UNLIMITED } if this query <nl> * should not limit the number of results . If { @ code reverse } is { @ code true } rows <nl> * will be limited starting at the end of the range . <nl> - * @ param reverse return results starting at the end of the range in reverse order <nl> + * @ param reverse return results starting at the end of the range in reverse order . <nl> + * Reading ranges in reverse is supported natively by the database and should <nl> + * have minimal extra cost . <nl> * <nl> * @ return a handle to access the results of the asynchronous call <nl> * / <nl> <nl> * < i > first < / i > keys in the range . Pass { @ link # ROW_LIMIT_UNLIMITED } if this query <nl> * should not limit the number of results . If { @ code reverse } is { @ code true } rows <nl> * will be limited starting at the end of the range . <nl> - * @ param reverse return results starting at the end of the range in reverse order <nl> + * @ param reverse return results starting at the end of the range in reverse order . <nl> + * Reading ranges in reverse is supported natively by the database and should <nl> + * have minimal extra cost . <nl> * @ param mode provide a hint about how the results are to be used . This <nl> * can provide speed improvements or efficiency gains based on the caller ' s <nl> * knowledge of the upcoming access pattern . <nl> <nl> * < i > first < / i > keys in the range . Pass { @ link # ROW_LIMIT_UNLIMITED } if this query <nl> * should not limit the number of results . If { @ code reverse } is { @ code true } rows <nl> * will be limited starting at the end of the range . <nl> - * @ param reverse return results starting at the end of the range in reverse order <nl> + * @ param reverse return results starting at the end of the range in reverse order . <nl> + * Reading ranges in reverse is supported natively by the database and should <nl> + * have minimal extra cost . <nl> * <nl> * @ return a handle to access the results of the asynchronous call <nl> * / <nl> <nl> * < i > first < / i > keys in the range . Pass { @ link # ROW_LIMIT_UNLIMITED } if this query <nl> * should not limit the number of results . If { @ code reverse } is { @ code true } rows <nl> * will be limited starting at the end of the range . <nl> - * @ param reverse return results starting at the end of the range in reverse order <nl> + * @ param reverse return results starting at the end of the range in reverse order . <nl> + * Reading ranges in reverse is supported natively by the database and should <nl> + * have minimal extra cost . <nl> * @ param mode provide a hint about how the results are to be used . This <nl> * can provide speed improvements or efficiency gains based on the caller ' s <nl> * knowledge of the upcoming access pattern . <nl> mmm a / bindings / java / src / main / com / apple / foundationdb / directory / DirectoryLayer . java <nl> ppp b / bindings / java / src / main / com / apple / foundationdb / directory / DirectoryLayer . java <nl> else if ( path . size ( ) > 1 ) { <nl> <nl> private static long unpackLittleEndian ( byte [ ] bytes ) { <nl> assert bytes . length = = 8 ; <nl> - int value = 0 ; <nl> + long value = 0 ; <nl> for ( int i = 0 ; i < 8 ; + + i ) { <nl> - value + = ( bytes [ i ] < < ( i * 8 ) ) ; <nl> + value + = ( Byte . toUnsignedLong ( bytes [ i ] ) < < ( i * 8 ) ) ; <nl> } <nl> return value ; <nl> } <nl> mmm a / build / Dockerfile <nl> ppp b / build / Dockerfile <nl> <nl> FROM centos : 6 <nl> - LABEL version = 0 . 1 . 9 <nl> - ENV DOCKER_IMAGEVER = 0 . 1 . 9 <nl> <nl> # Install dependencies for developer tools , bindings , \ <nl> # documentation , actorcompiler , and packaging tools \ <nl> RUN yum install - y yum - utils & & \ <nl> yum - config - manager - - enable rhel - server - rhscl - 7 - rpms & & \ <nl> yum - y install centos - release - scl epel - release & & \ <nl> yum - y install devtoolset - 8 - 8 . 1 - 1 . el6 java - 1 . 8 . 0 - openjdk - devel \ <nl> + devtoolset - 8 - gcc - 8 . 3 . 1 - 3 . 1 . el6 devtoolset - 8 - gcc - c + + - 8 . 3 . 1 - 3 . 1 . el6 \ <nl> rh - python36 - python - devel devtoolset - 8 - valgrind - devel \ <nl> mono - core rh - ruby24 golang python27 rpm - build debbuild \ <nl> - python - pip npm dos2unix valgrind - devel ccache distcc devtoolset - 8 - libubsan - devel libubsan - devel & & \ <nl> + python - pip dos2unix valgrind - devel ccache distcc devtoolset - 8 - libubsan - devel libubsan - devel & & \ <nl> pip install boto3 = = 1 . 1 . 1 <nl> <nl> USER root <nl> RUN adduser - - comment ' ' fdb & & chown fdb / opt <nl> <nl> # wget of bintray without forcing UTF - 8 encoding results in 403 Forbidden <nl> RUN cd / opt / & & \ <nl> - curl - L https : / / dl . bintray . com / boostorg / release / 1 . 67 . 0 / source / boost_1_67_0 . tar . bz2 > boost_1_67_0 . tar . bz2 & & \ <nl> - echo " 2684c972994ee57fc5632e03bf044746f6eb45d4920c343937a465fd67a5adba boost_1_67_0 . tar . bz2 " > boost - sha . txt & & \ <nl> - sha256sum - c boost - sha . txt & & \ <nl> + curl - L https : / / dl . bintray . com / boostorg / release / 1 . 67 . 0 / source / boost_1_67_0 . tar . bz2 - o boost_1_67_0 . tar . bz2 & & \ <nl> + echo " 2684c972994ee57fc5632e03bf044746f6eb45d4920c343937a465fd67a5adba boost_1_67_0 . tar . bz2 " > boost - sha - 67 . txt & & \ <nl> + sha256sum - c boost - sha - 67 . txt & & \ <nl> tar - xjf boost_1_67_0 . tar . bz2 & & \ <nl> - rm - rf boost_1_67_0 . tar . bz2 boost - sha . txt boost_1_67_0 / libs <nl> + rm - rf boost_1_67_0 . tar . bz2 boost - sha - 67 . txt boost_1_67_0 / libs & & \ <nl> + curl - L https : / / dl . bintray . com / boostorg / release / 1 . 72 . 0 / source / boost_1_72_0 . tar . bz2 - o boost_1_72_0 . tar . bz2 & & \ <nl> + echo " 59c9b274bc451cf91a9ba1dd2c7fdcaf5d60b1b3aa83f2c9fa143417cc660722 boost_1_72_0 . tar . bz2 " > boost - sha - 72 . txt & & \ <nl> + sha256sum - c boost - sha - 72 . txt & & \ <nl> + tar - xjf boost_1_72_0 . tar . bz2 & & \ <nl> + rm - rf boost_1_72_0 . tar . bz2 boost - sha - 72 . txt boost_1_72_0 / libs <nl> <nl> # install cmake <nl> - RUN curl - L https : / / github . com / Kitware / CMake / releases / download / v3 . 13 . 4 / cmake - 3 . 13 . 4 - Linux - x86_64 . tar . gz > / tmp / cmake . tar . gz & & \ <nl> + RUN curl - L https : / / github . com / Kitware / CMake / releases / download / v3 . 13 . 4 / cmake - 3 . 13 . 4 - Linux - x86_64 . tar . gz - o / tmp / cmake . tar . gz & & \ <nl> echo " 563a39e0a7c7368f81bfa1c3aff8b590a0617cdfe51177ddc808f66cc0866c76 / tmp / cmake . tar . gz " > / tmp / cmake - sha . txt & & \ <nl> sha256sum - c / tmp / cmake - sha . txt & & \ <nl> cd / tmp & & tar xf cmake . tar . gz & & \ <nl> cp - r cmake - 3 . 13 . 4 - Linux - x86_64 / * / usr / local / & & \ <nl> rm - rf cmake . tar . gz cmake - 3 . 13 . 4 - Linux - x86_64 cmake - sha . txt <nl> <nl> - # install LibreSSL <nl> - RUN cd / tmp & & curl - L https : / / github . com / ninja - build / ninja / archive / v1 . 9 . 0 . zip > ninja . zip & & \ <nl> + # install Ninja <nl> + RUN cd / tmp & & curl - L https : / / github . com / ninja - build / ninja / archive / v1 . 9 . 0 . zip - o ninja . zip & & \ <nl> unzip ninja . zip & & cd ninja - 1 . 9 . 0 & & scl enable devtoolset - 8 - - . / configure . py - - bootstrap & & cp ninja / usr / bin & & \ <nl> - cd . . & & rm - rf ninja - 1 . 9 . 0 ninja . zip & & \ <nl> - curl - L https : / / ftp . openbsd . org / pub / OpenBSD / LibreSSL / libressl - 2 . 8 . 2 . tar . gz > / tmp / libressl . tar . gz & & \ <nl> - cd / tmp & & echo " b8cb31e59f1294557bfc80f2a662969bc064e83006ceef0574e2553a1c254fd5 libressl . tar . gz " > libressl - sha . txt & & \ <nl> - sha256sum - c libressl - sha . txt & & tar xf libressl . tar . gz & & \ <nl> - cd libressl - 2 . 8 . 2 & & cd / tmp / libressl - 2 . 8 . 2 & & scl enable devtoolset - 8 - - . / configure - - prefix = / usr / local / stow / libressl CFLAGS = " - fPIC - O3 " - - prefix = / usr / local & & \ <nl> - cd / tmp / libressl - 2 . 8 . 2 & & scl enable devtoolset - 8 - - make - j ` nproc ` install & & \ <nl> - rm - rf / tmp / libressl - 2 . 8 . 2 / tmp / libressl . tar . gz <nl> + cd . . & & rm - rf ninja - 1 . 9 . 0 ninja . zip <nl> <nl> + # install openssl <nl> + RUN cd / tmp & & curl - L https : / / www . openssl . org / source / openssl - 1 . 1 . 1d . tar . gz - o openssl . tar . gz & & \ <nl> + echo " 1e3a91bc1f9dfce01af26026f856e064eab4c8ee0a8f457b5ae30b40b8b711f2 openssl . tar . gz " > openssl - sha . txt & & \ <nl> + sha256sum - c openssl - sha . txt & & tar - xzf openssl . tar . gz & & \ <nl> + cd openssl - 1 . 1 . 1d & & scl enable devtoolset - 8 - - . / config CFLAGS = " - fPIC - O3 " - - prefix = / usr / local & & \ <nl> + scl enable devtoolset - 8 - - make - j ` nproc ` & & scl enable devtoolset - 8 - - make - j1 install & & \ <nl> + ln - sv / usr / local / lib64 / lib * . so . 1 . 1 / usr / lib64 / & & \ <nl> + cd / tmp / & & rm - rf / tmp / openssl - 1 . 1 . 1d / tmp / openssl . tar . gz <nl> + <nl> + LABEL version = 0 . 1 . 12 <nl> + ENV DOCKER_IMAGEVER = 0 . 1 . 12 <nl> ENV JAVA_HOME = / usr / lib / jvm / java - 1 . 8 . 0 <nl> ENV CC = / opt / rh / devtoolset - 8 / root / usr / bin / gcc <nl> ENV CXX = / opt / rh / devtoolset - 8 / root / usr / bin / g + + <nl> - CMD scl enable devtoolset - 8 python27 rh - python36 rh - ruby24 - - bash <nl> + CMD scl enable devtoolset - 8 rh - python36 rh - ruby24 - - bash <nl> mmm a / build / docker - compose . yaml <nl> ppp b / build / docker - compose . yaml <nl> version : " 3 " <nl> <nl> services : <nl> common : & common <nl> - image : foundationdb / foundationdb - build : 0 . 1 . 9 <nl> + image : foundationdb / foundationdb - build : 0 . 1 . 12 <nl> <nl> build - setup : & build - setup <nl> < < : * common <nl> services : <nl> <nl> release - packages : & release - packages <nl> < < : * release - setup <nl> - command : scl enable devtoolset - 8 python27 rh - python36 rh - ruby24 - - bash - c ' make - j " $ $ { MAKEJOBS } " packages ' <nl> + command : scl enable devtoolset - 8 rh - python36 rh - ruby24 - - bash - c ' make - j " $ $ { MAKEJOBS } " packages ' <nl> <nl> snapshot - packages : & snapshot - packages <nl> < < : * build - setup <nl> - command : scl enable devtoolset - 8 python27 rh - python36 rh - ruby24 - - bash - c ' make - j " $ $ { MAKEJOBS } " packages ' <nl> + command : scl enable devtoolset - 8 rh - python36 rh - ruby24 - - bash - c ' make - j " $ $ { MAKEJOBS } " packages ' <nl> <nl> prb - packages : <nl> < < : * snapshot - packages <nl> services : <nl> <nl> release - bindings : & release - bindings <nl> < < : * release - setup <nl> - command : scl enable devtoolset - 8 python27 rh - python36 rh - ruby24 - - bash - c ' make - j " $ $ { MAKEJOBS } " bindings ' <nl> + command : scl enable devtoolset - 8 rh - python36 rh - ruby24 - - bash - c ' make - j " $ $ { MAKEJOBS } " bindings ' <nl> <nl> snapshot - bindings : & snapshot - bindings <nl> < < : * build - setup <nl> - command : scl enable devtoolset - 8 python27 rh - python36 rh - ruby24 - - bash - c ' make - j " $ $ { MAKEJOBS } " bindings ' <nl> + command : scl enable devtoolset - 8 rh - python36 rh - ruby24 - - bash - c ' make - j " $ $ { MAKEJOBS } " bindings ' <nl> <nl> prb - bindings : <nl> < < : * snapshot - bindings <nl> services : <nl> <nl> snapshot - cmake : & snapshot - cmake <nl> < < : * build - setup <nl> - command : scl enable devtoolset - 8 python27 rh - python36 rh - ruby24 - - bash - c ' mkdir - p " $ $ { BUILD_DIR } " & & cd " $ $ { BUILD_DIR } " & & cmake - G " Ninja " - DCMAKE_COLOR_MAKEFILE = 0 - DUSE_WERROR = 1 - DFDB_RELEASE = 0 - DVALGRIND = 0 / __this_is_some_very_long_name_dir_needed_to_fix_a_bug_with_debug_rpms__ / foundationdb & & ninja - v - j " $ $ { MAKEJOBS } " " packages " " strip_targets " & & cpack ' <nl> + command : scl enable devtoolset - 8 rh - python36 rh - ruby24 - - bash - c ' mkdir - p " $ $ { BUILD_DIR } " & & cd " $ $ { BUILD_DIR } " & & cmake - G " Ninja " - DCMAKE_COLOR_MAKEFILE = 0 - DFDB_RELEASE = 0 - DVALGRIND = 0 / __this_is_some_very_long_name_dir_needed_to_fix_a_bug_with_debug_rpms__ / foundationdb & & ninja - v - j " $ $ { MAKEJOBS } " " packages " " strip_targets " & & cpack ' <nl> <nl> prb - cmake : <nl> < < : * snapshot - cmake <nl> services : <nl> <nl> snapshot - ctest : & snapshot - ctest <nl> < < : * build - setup <nl> - command : scl enable devtoolset - 8 python27 rh - python36 rh - ruby24 - - bash - c ' mkdir - p " $ $ { BUILD_DIR } " & & cd " $ $ { BUILD_DIR } " & & cmake - G " Ninja " - DCMAKE_COLOR_MAKEFILE = 0 - DUSE_WERROR = 1 - DFDB_RELEASE = 1 / __this_is_some_very_long_name_dir_needed_to_fix_a_bug_with_debug_rpms__ / foundationdb & & ninja - v - j " $ $ { MAKEJOBS } " & & ctest - L fast - j " $ $ { MAKEJOBS } " - - output - on - failure ' <nl> + command : scl enable devtoolset - 8 rh - python36 rh - ruby24 - - bash - c ' mkdir - p " $ $ { BUILD_DIR } " & & cd " $ $ { BUILD_DIR } " & & cmake - G " Ninja " - DCMAKE_COLOR_MAKEFILE = 0 - DFDB_RELEASE = 1 / __this_is_some_very_long_name_dir_needed_to_fix_a_bug_with_debug_rpms__ / foundationdb & & ninja - v - j " $ $ { MAKEJOBS } " & & ctest - L fast - j " $ $ { MAKEJOBS } " - - output - on - failure ' <nl> <nl> prb - ctest : <nl> < < : * snapshot - ctest <nl> services : <nl> <nl> snapshot - correctness : & snapshot - correctness <nl> < < : * build - setup <nl> - command : scl enable devtoolset - 8 python27 rh - python36 rh - ruby24 - - bash - c ' mkdir - p " $ $ { BUILD_DIR } " & & cd " $ $ { BUILD_DIR } " & & cmake - G " Ninja " - DCMAKE_COLOR_MAKEFILE = 0 - DUSE_WERROR = 1 - DFDB_RELEASE = 1 / __this_is_some_very_long_name_dir_needed_to_fix_a_bug_with_debug_rpms__ / foundationdb & & ninja - v - j " $ $ { MAKEJOBS } " & & ctest - j " $ $ { MAKEJOBS } " - - output - on - failure ' <nl> + command : scl enable devtoolset - 8 rh - python36 rh - ruby24 - - bash - c ' mkdir - p " $ $ { BUILD_DIR } " & & cd " $ $ { BUILD_DIR } " & & cmake - G " Ninja " - DCMAKE_COLOR_MAKEFILE = 0 - DFDB_RELEASE = 1 / __this_is_some_very_long_name_dir_needed_to_fix_a_bug_with_debug_rpms__ / foundationdb & & ninja - v - j " $ $ { MAKEJOBS } " & & ctest - j " $ $ { MAKEJOBS } " - - output - on - failure ' <nl> <nl> prb - correctness : <nl> < < : * snapshot - correctness <nl> mmm a / cmake / FDBComponents . cmake <nl> ppp b / cmake / FDBComponents . cmake <nl> if ( USE_VALGRIND ) <nl> endif ( ) <nl> <nl> # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # <nl> - # LibreSSL <nl> + # SSL <nl> # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # <nl> <nl> set ( DISABLE_TLS OFF CACHE BOOL " Don ' t try to find LibreSSL and always build without TLS support " ) <nl> if ( DISABLE_TLS ) <nl> set ( WITH_TLS OFF ) <nl> else ( ) <nl> - set ( LIBRESSL_USE_STATIC_LIBS TRUE ) <nl> - find_package ( LibreSSL ) <nl> - if ( LibreSSL_FOUND ) <nl> + set ( OPENSSL_USE_STATIC_LIBS TRUE ) <nl> + find_package ( OpenSSL ) <nl> + if ( NOT OPENSSL_FOUND ) <nl> + set ( LIBRESSL_USE_STATIC_LIBS TRUE ) <nl> + find_package ( LibreSSL ) <nl> + if ( LIBRESSL_FOUND ) <nl> + add_library ( OpenSSL : : SSL ALIAS LibreSSL ) <nl> + endif ( ) <nl> + endif ( ) <nl> + if ( OPENSSL_FOUND OR LIBRESSL_FOUND ) <nl> set ( WITH_TLS ON ) <nl> add_compile_options ( - DHAVE_OPENSSL ) <nl> else ( ) <nl> - message ( STATUS " LibreSSL NOT Found - Will compile without TLS Support " ) <nl> - message ( STATUS " You can set LibreSSL_ROOT to the LibreSSL install directory to help cmake find it " ) <nl> + message ( STATUS " Neither OpenSSL nor LibreSSL were found - Will compile without TLS Support " ) <nl> + message ( STATUS " You can set OPENSSL_ROOT_DIR or LibreSSL_ROOT to the LibreSSL install directory to help cmake find it " ) <nl> + set ( WITH_TLS OFF ) <nl> + endif ( ) <nl> + if ( WIN32 ) <nl> + message ( STATUS " TLS is temporarilty disabled on macOS while libressl - > openssl transition happens " ) <nl> set ( WITH_TLS OFF ) <nl> endif ( ) <nl> endif ( ) <nl> endif ( ) <nl> # Pip <nl> # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # <nl> <nl> - find_package ( Virtualenv ) <nl> - if ( Virtualenv_FOUND ) <nl> + find_package ( Python3 COMPONENTS Interpreter ) <nl> + if ( Python3_Interpreter_FOUND ) <nl> set ( WITH_DOCUMENTATION ON ) <nl> else ( ) <nl> set ( WITH_DOCUMENTATION OFF ) <nl> deleted file mode 100644 <nl> index ace748f672 . . 0000000000 <nl> mmm a / cmake / FindVirtualenv . cmake <nl> ppp / dev / null <nl> <nl> - find_program ( _VIRTUALENV_EXE virtualenv ) <nl> - <nl> - # get version and test that program actually works <nl> - if ( _VIRTUALENV_EXE ) <nl> - execute_process ( <nl> - COMMAND $ { _VIRTUALENV_EXE } - - version <nl> - RESULT_VARIABLE ret_code <nl> - OUTPUT_VARIABLE version_string <nl> - ERROR_VARIABLE error_output <nl> - OUTPUT_STRIP_TRAILING_WHITESPACE ) <nl> - if ( ret_code EQUAL 0 AND NOT ERROR_VARIABLE ) <nl> - # we found a working virtualenv <nl> - set ( VIRTUALENV_EXE $ { _VIRTUALENV_EXE } ) <nl> - set ( VIRTUALENV_VERSION version_string ) <nl> - endif ( ) <nl> - endif ( ) <nl> - <nl> - find_package_handle_standard_args ( Virtualenv <nl> - REQUIRED_VARS VIRTUALENV_EXE <nl> - VERSION_VAR $ { VIRTUALENV_VERSION } ) <nl> mmm a / design / backup . md <nl> ppp b / design / backup . md <nl> <nl> KV ranges { ( a - b , v0 ) , ( c - d , v1 ) , ( e - f , v2 ) . . . ( y - z , v10 ) } . With mutation log recorded all along , we can still use <nl> the simple backup - restore scheme described above on sub keyspaces seperately . Assuming we did record mutation log from <nl> v0 to vn , that allows us to restore <nl> - <nl> + <nl> * Keyspace a - b to any version between v0 and vn <nl> * Keyspace c - d to any version between v1 and vn <nl> * Keyspace y - z to any version between v10 and vn <nl> mmm a / design / recovery - internals . md <nl> ppp b / design / recovery - internals . md <nl> The transaction system state before the recovery is the starting point for the c <nl> <nl> # # Phase 2 : LOCKING_CSTATE <nl> <nl> - This phase locks the coordinated state ( cstate ) to make sure there is only one master who can change the cstate . Otherwise , we may end up with more than one master accepting commits after the recovery . To achieve that , the master needs to get currently alive tLogs ’ interfaces and sends commands to tLogs to lock their states , preventing them from accepting any further writes . <nl> + This phase locks the coordinated state ( cstate ) to make sure there is only one master who can change the cstate . Otherwise , we may end up with more than one master accepting commits after the recovery . To achieve that , the master needs to get currently alive tLogs ’ interfaces and sends commands to tLogs to lock their states , preventing them from accepting any further writes . <nl> <nl> Recall that ` ServerDBInfo ` has master ' s interface and is propogated by CC to every process in a cluster . The current running tLogs can use the master interface in its ` ServerDBInfo ` to send itself ' s interface to master . <nl> Master simply waits on receiving the ` TLogRejoinRequest ` streams : for each tLog ’ s interface received , the master compares the interface ID with the tLog ID read from cstate . Once the master collects enough old tLog interfaces , it will use the interfaces to lock those tLogs . <nl> mmm a / documentation / CMakeLists . txt <nl> ppp b / documentation / CMakeLists . txt <nl> set ( pip_command $ { venv_dir } / bin / pip $ { EXE_SUFFIX } ) <nl> set ( python_command $ { venv_dir } / bin / python $ { EXE_SUFFIX } ) <nl> <nl> add_custom_command ( OUTPUT $ { venv_dir } / venv_setup <nl> - COMMAND $ { VIRTUALENV_EXE } venv & & <nl> + COMMAND $ { Python3_EXECUTABLE } - m venv venv & & <nl> $ { CMAKE_COMMAND } - E copy $ { sphinx_dir } / . pip . conf $ { venv_dir } / pip . conf & & <nl> . $ { venv_dir } / bin / activate & & <nl> $ { pip_command } install - - upgrade pip & & <nl> else ( ) <nl> endif ( ) <nl> <nl> add_custom_target ( docpreview <nl> - COMMAND $ { python_command } - m SimpleHTTPServer $ { port } <nl> + COMMAND $ { python_command } - m http . server $ { port } <nl> WORKING_DIRECTORY $ { CMAKE_CURRENT_BINARY_DIR } / html <nl> USES_TERMINAL ) <nl> add_dependencies ( docpreview html ) <nl> mmm a / documentation / sphinx / source / administration . rst <nl> ppp b / documentation / sphinx / source / administration . rst <nl> Upgrades from 6 . 1 . x will keep all your old data and configuration settings . Data <nl> Upgrading from 6 . 0 . x <nl> mmmmmmmmmmmmmmmmmm - - <nl> <nl> - Upgrades from 6 . 0 . x will keep all your old data and configuration settings . Data distribution will slowly reorganize how data is spread across storage servers . <nl> + Upgrades from 6 . 0 . x will keep all your old data and configuration settings . <nl> <nl> Upgrading from 5 . 2 . x <nl> mmmmmmmmmmmmmmmmmm - - <nl> <nl> - Upgrades from 5 . 2 . x will keep all your old data and configuration settings . <nl> + Upgrades from 5 . 2 . x will keep all your old data and configuration settings . Some affinities that certain roles have for running on processes that haven ' t set a process class have changed , which may result in these processes running in different locations after upgrading . To avoid this , set process classes as needed . The following changes were made : <nl> + <nl> + * The proxies and master no longer prefer ` ` resolution ` ` or ` ` transaction ` ` class processes to processes with unset class . <nl> + * The resolver no longer prefers ` ` transaction ` ` class processes to processes with unset class . <nl> + * The cluster controller no longer prefers ` ` master ` ` , ` ` resolution ` ` or ` ` proxy ` ` class processes to processes with unset class . <nl> + <nl> + See : ref : ` guidelines - process - class - config ` for recommendations on setting process classes . All of the above roles will prefer ` ` stateless ` ` class processes to ones that don ' t set a class . <nl> <nl> Upgrading from 5 . 0 . x - 5 . 1 . x <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> mmm a / documentation / sphinx / source / api - c . rst <nl> ppp b / documentation / sphinx / source / api - c . rst <nl> Applications must provide error handling and an appropriate retry loop around th <nl> | snapshot | <nl> <nl> ` ` reverse ` ` <nl> - <nl> - If non - zero , key - value pairs will be returned in reverse lexicographical order beginning at the end of the range . <nl> + If non - zero , key - value pairs will be returned in reverse lexicographical order beginning at the end of the range . Reading ranges in reverse is supported natively by the database and should have minimal extra cost . <nl> <nl> . . type : : FDBStreamingMode <nl> <nl> mmm a / documentation / sphinx / source / api - common . rst . inc <nl> ppp b / documentation / sphinx / source / api - common . rst . inc <nl> <nl> . . | option - trace - format - blurb | replace : : <nl> Select the format of the trace files for this FoundationDB client . xml ( the default ) and json are supported . <nl> <nl> + . . | option - trace - clock - source - blurb | replace : : <nl> + Select clock source for trace files . now ( the default ) or realtime are supported . <nl> + <nl> . . | network - options - warning | replace : : <nl> <nl> It is an error to set these options after the first call to | open - func | anywhere in your application . <nl> mmm a / documentation / sphinx / source / api - python . rst <nl> ppp b / documentation / sphinx / source / api - python . rst <nl> After importing the ` ` fdb ` ` module and selecting an API version , you probably wa <nl> <nl> | option - trace - format - blurb | <nl> <nl> + . . method : : fdb . options . set_trace_clock_source ( source ) <nl> + <nl> + | option - trace - clock - source - blurb | <nl> + <nl> . . method : : fdb . options . set_disable_multi_version_client_api ( ) <nl> <nl> | option - disable - multi - version - client - api | <nl> A | database - blurb1 | | database - blurb2 | <nl> <nl> If ` ` limit ` ` is specified , then only the first ` ` limit ` ` keys ( and their values ) in the range will be returned . <nl> <nl> - If ` ` reverse ` ` is True , then the last ` ` limit ` ` keys in the range will be returned in reverse order . <nl> + If ` ` reverse ` ` is True , then the last ` ` limit ` ` keys in the range will be returned in reverse order . Reading ranges in reverse is supported natively by the database and should have minimal extra cost . <nl> <nl> If ` ` streaming_mode ` ` is specified , it must be a value from the : data : ` StreamingMode ` enumeration . It provides a hint to FoundationDB about how to retrieve the specified range . This option should generally not be specified , allowing FoundationDB to retrieve the full range very efficiently . <nl> <nl> Reading data <nl> <nl> If ` ` limit ` ` is specified , then only the first ` ` limit ` ` keys ( and their values ) in the range will be returned . <nl> <nl> - If ` ` reverse ` ` is True , then the last ` ` limit ` ` keys in the range will be returned in reverse order . <nl> + If ` ` reverse ` ` is True , then the last ` ` limit ` ` keys in the range will be returned in reverse order . Reading ranges in reverse is supported natively by the database and should have minimal extra cost . <nl> <nl> If ` ` streaming_mode ` ` is specified , it must be a value from the : data : ` StreamingMode ` enumeration . It provides a hint to FoundationDB about how the returned container is likely to be used . The default is : data : ` StreamingMode . iterator ` . <nl> <nl> mmm a / documentation / sphinx / source / api - ruby . rst <nl> ppp b / documentation / sphinx / source / api - ruby . rst <nl> After requiring the ` ` FDB ` ` gem and selecting an API version , you probably want <nl> <nl> | option - trace - format - blurb | <nl> <nl> + . . method : : FDB . options . set_trace_clock_source ( source ) - > nil <nl> + <nl> + | option - trace - clock - source - blurb | <nl> + <nl> . . method : : FDB . options . set_disable_multi_version_client_api ( ) - > nil <nl> <nl> | option - disable - multi - version - client - api | <nl> A | database - blurb1 | | database - blurb2 | <nl> Only the first ` ` limit ` ` keys ( and their values ) in the range will be returned . <nl> <nl> ` ` : reverse ` ` <nl> - If ` ` true ` ` , then the keys in the range will be returned in reverse order . <nl> + If ` ` true ` ` , then the keys in the range will be returned in reverse order . Reading ranges in reverse is supported natively by the database and should have minimal extra cost . <nl> <nl> If ` ` : limit ` ` is also specified , the * last * ` ` limit ` ` keys in the range will be returned in reverse order . <nl> <nl> Reading data <nl> Only the first ` ` limit ` ` keys ( and their values ) in the range will be returned . <nl> <nl> ` ` : reverse ` ` <nl> - If true , then the keys in the range will be returned in reverse order . <nl> + If ` ` true ` ` , then the keys in the range will be returned in reverse order . Reading ranges in reverse is supported natively by the database and should have minimal extra cost . <nl> <nl> If ` ` : limit ` ` is also specified , the * last * ` ` limit ` ` keys in the range will be returned in reverse order . <nl> <nl> mmm a / documentation / sphinx / source / backups . rst <nl> ppp b / documentation / sphinx / source / backups . rst <nl> While a cluster is being used as the destination for a DR operation it will be l <nl> Limitations <nl> = = = = = = = = = = = <nl> <nl> - Backup data is not encrypted on disk , in a blob store account , or in transit to a destination blob store account or database . <nl> + Backup data is not encrypted at rest on disk or in a blob store account . <nl> <nl> Tools <nl> = = = = = = = = = = = <nl> The Blob Credential File format is JSON with the following schema : <nl> } <nl> } <nl> <nl> - SSL Support <nl> + TLS Support <nl> = = = = = = = = = = = <nl> <nl> - By default , backup will communicate over https . To configure https , the following environment variables are used : <nl> + In - flight traffic for blob store or disaster recovery backups can be encrypted with the following environment variables . They are also offered as command - line flags or can be specified in ` ` foundationdb . conf ` ` for backup agents . <nl> <nl> = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> Environment Variable Purpose <nl> = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> - ` ` FDB_TLS_PLUGIN ` ` Path to the file to be loaded as the TLS plugin <nl> ` ` FDB_TLS_CERTIFICATE_FILE ` ` Path to the file from which the local certificates <nl> can be loaded , used by the plugin <nl> ` ` FDB_TLS_KEY_FILE ` ` Path to the file from which to load the private <nl> Environment Variable Purpose <nl> ` ` FDB_TLS_CA_FILE ` ` Path to the file containing the CA certificates <nl> to trust . Specify to override the default openssl <nl> location . <nl> + ` ` FDB_TLS_VERIFY_PEERS ` ` The byte - string for the verification of peer <nl> + certificates and sessions . <nl> = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> <nl> + Blob store backups can be configured to use HTTPS / TLS by setting the ` ` secure_connection ` ` or ` ` sc ` ` backup URL option to ` ` 1 ` ` , which is the default . Disaster recovery backups are secured by using TLS for both the source and target clusters and setting the TLS options for the ` ` fdbdr ` ` and ` ` dr_agent ` ` commands . <nl> <nl> ` ` fdbbackup ` ` command line tool <nl> = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> mmm a / documentation / sphinx / source / configuration . rst <nl> ppp b / documentation / sphinx / source / configuration . rst <nl> System requirements <nl> * Or , an unsupported Linux distribution with : <nl> <nl> * Kernel version between 2 . 6 . 33 and 3 . 0 . x ( inclusive ) or 3 . 7 or greater <nl> - * Works with . deb or . rpm packages <nl> + * Preferably . deb or . rpm package support <nl> <nl> * Or , macOS 10 . 7 or later <nl> <nl> - . . warning : : The macOS version of the FoundationDB server is intended for use on locally accessible development machines only . Other uses are not supported . <nl> + . . warning : : The macOS and Windows versions of the FoundationDB server are intended for use on locally accessible development machines only . Other uses are not supported . <nl> <nl> * 4GB * * ECC * * RAM ( per fdbserver process ) <nl> * Storage <nl> FoundationDB will never use processes on the same machine for the replication of <nl> <nl> FoundationDB replicates data to three machines , and at least three available machines are required to make progress . This is the recommended mode for a cluster of five or more machines in a single datacenter . <nl> <nl> + . . note : : When running in cloud environments with managed disks that are already replicated and persistent , ` ` double ` ` replication may still be considered for 5 + machine clusters . This will result in lower availability fault tolerance for planned or unplanned failures and lower total read throughput , but offers a reasonable tradeoff for cost . <nl> + <nl> ` ` three_data_hall ` ` mode <nl> FoundationDB stores data in triplicate , with one copy on a storage server in each of three data halls . The transaction logs are replicated four times , with two data halls containing two replicas apiece . Four available machines ( two in each of two data halls ) are therefore required to make progress . This configuration enables the cluster to remain available after losing a single data hall and one machine in another data hall . <nl> <nl> Region configuration is better in almost all ways than the ` ` three_datacenter ` ` <nl> Known limitations <nl> mmmmmmmmmmmmmmm - - <nl> <nl> - The 6 . 0 release still has a number of rough edges related to region configuration . This is a collection of all the issues that have been pointed out in the sections above . These issues should be significantly improved in future releases of FoundationDB : <nl> + The 6 . 2 release still has a number of rough edges related to region configuration . This is a collection of all the issues that have been pointed out in the sections above . These issues should be significantly improved in future releases of FoundationDB : <nl> <nl> * FoundationDB supports replicating data to at most two regions . <nl> <nl> * ` ` two_satellite_fast ` ` does not hide latency properly when configured with more than 4 satellite transaction logs . <nl> <nl> - * While a datacenter has failed , the maximum write throughput of the cluster will be roughly 1 / 3 of normal performance . <nl> - <nl> . . _guidelines - process - class - config : <nl> <nl> Guidelines for setting process class <nl> mmm a / documentation / sphinx / source / old - release - notes / release - notes - 600 . rst <nl> ppp b / documentation / sphinx / source / old - release - notes / release - notes - 600 . rst <nl> Other Changes <nl> <nl> * Does not support upgrades from any version older than 5 . 0 . <nl> * Normalized the capitalization of trace event names and attributes . ` ( PR # 455 ) < https : / / github . com / apple / foundationdb / pull / 455 > ` _ <nl> + * Various stateless processes now have a higher affinity for running on processes with unset process class , which may result in those roles changing location upon upgrade . See : ref : ` version - specific - upgrading ` for details . ` ( PR # 526 ) < https : / / github . com / apple / foundationdb / pull / 526 > ` _ <nl> * Increased the memory requirements of the transaction log by 400MB . [ 6 . 0 . 5 ] ` ( PR # 673 ) < https : / / github . com / apple / foundationdb / pull / 673 > ` _ <nl> <nl> Earlier release notes <nl> mmm a / fdbbackup / backup . actor . cpp <nl> ppp b / fdbbackup / backup . actor . cpp <nl> <nl> # include " fdbclient / json_spirit / json_spirit_writer_template . h " <nl> <nl> # include " fdbrpc / Platform . h " <nl> - # include " fdbrpc / TLSConnection . h " <nl> <nl> # include < stdarg . h > <nl> # include < stdio . h > <nl> ACTOR Future < Void > runFastRestoreAgent ( Database db , std : : string tagName , std : : st <nl> <nl> if ( performRestore ) { <nl> if ( dbVersion = = invalidVersion ) { <nl> + TraceEvent ( " FastRestoreAgent " ) . detail ( " TargetRestoreVersion " , " Largest restorable version " ) ; <nl> BackupDescription desc = wait ( IBackupContainer : : openContainer ( container ) - > describeBackup ( ) ) ; <nl> if ( ! desc . maxRestorableVersion . present ( ) ) { <nl> fprintf ( stderr , " The specified backup is not restorable to any version . \ n " ) ; <nl> ACTOR Future < Void > runFastRestoreAgent ( Database db , std : : string tagName , std : : st <nl> } <nl> <nl> dbVersion = desc . maxRestorableVersion . get ( ) ; <nl> + TraceEvent ( " FastRestoreAgent " ) . detail ( " TargetRestoreVersion " , dbVersion ) ; <nl> } <nl> Version _restoreVersion = wait ( fastRestore ( db , KeyRef ( tagName ) , KeyRef ( container ) , waitForDone , dbVersion , <nl> verbose , range , KeyRef ( addPrefix ) , KeyRef ( removePrefix ) ) ) ; <nl> int main ( int argc , char * argv [ ] ) { <nl> blobCredentials . push_back ( args - > OptionArg ( ) ) ; <nl> break ; <nl> # ifndef TLS_DISABLED <nl> - case TLSOptions : : OPT_TLS_PLUGIN : <nl> + case TLSParams : : OPT_TLS_PLUGIN : <nl> args - > OptionArg ( ) ; <nl> break ; <nl> - case TLSOptions : : OPT_TLS_CERTIFICATES : <nl> + case TLSParams : : OPT_TLS_CERTIFICATES : <nl> tlsCertPath = args - > OptionArg ( ) ; <nl> break ; <nl> - case TLSOptions : : OPT_TLS_PASSWORD : <nl> + case TLSParams : : OPT_TLS_PASSWORD : <nl> tlsPassword = args - > OptionArg ( ) ; <nl> break ; <nl> - case TLSOptions : : OPT_TLS_CA_FILE : <nl> + case TLSParams : : OPT_TLS_CA_FILE : <nl> tlsCAPath = args - > OptionArg ( ) ; <nl> break ; <nl> - case TLSOptions : : OPT_TLS_KEY : <nl> + case TLSParams : : OPT_TLS_KEY : <nl> tlsKeyPath = args - > OptionArg ( ) ; <nl> break ; <nl> - case TLSOptions : : OPT_TLS_VERIFY_PEERS : <nl> + case TLSParams : : OPT_TLS_VERIFY_PEERS : <nl> tlsVerifyPeers = args - > OptionArg ( ) ; <nl> break ; <nl> # endif <nl> int main ( int argc , char * argv [ ] ) { <nl> } catch ( Error & e ) { <nl> TraceEvent ( SevError , " MainError " ) . error ( e ) ; <nl> status = FDB_EXIT_MAIN_ERROR ; <nl> + } catch ( boost : : system : : system_error & e ) { <nl> + if ( g_network ) { <nl> + TraceEvent ( SevError , " MainError " ) . error ( unknown_error ( ) ) . detail ( " RootException " , e . what ( ) ) ; <nl> + } else { <nl> + fprintf ( stderr , " ERROR : % s ( % d ) \ n " , e . what ( ) , e . code ( ) . value ( ) ) ; <nl> + } <nl> + status = FDB_EXIT_MAIN_EXCEPTION ; <nl> } catch ( std : : exception & e ) { <nl> TraceEvent ( SevError , " MainError " ) . error ( unknown_error ( ) ) . detail ( " RootException " , e . what ( ) ) ; <nl> status = FDB_EXIT_MAIN_EXCEPTION ; <nl> mmm a / fdbcli / fdbcli . actor . cpp <nl> ppp b / fdbcli / fdbcli . actor . cpp <nl> <nl> # include " fdbclient / FDBOptions . g . h " <nl> <nl> # include " flow / DeterministicRandom . h " <nl> - # include " fdbrpc / TLSConnection . h " <nl> # include " fdbrpc / Platform . h " <nl> <nl> # include " flow / SimpleOpt . h " <nl> ACTOR Future < Void > timeWarning ( double when , const char * msg ) { <nl> return Void ( ) ; <nl> } <nl> <nl> - ACTOR Future < Void > checkStatus ( Future < Void > f , Reference < ClusterConnectionFile > clusterFile , bool displayDatabaseAvailable = true ) { <nl> + ACTOR Future < Void > checkStatus ( Future < Void > f , Database db , bool displayDatabaseAvailable = true ) { <nl> wait ( f ) ; <nl> - StatusObject s = wait ( StatusClient : : statusFetcher ( clusterFile ) ) ; <nl> + StatusObject s = wait ( StatusClient : : statusFetcher ( db ) ) ; <nl> printf ( " \ n " ) ; <nl> printStatus ( s , StatusClient : : MINIMAL , displayDatabaseAvailable ) ; <nl> printf ( " \ n " ) ; <nl> ACTOR Future < bool > configure ( Database db , std : : vector < StringRef > tokens , Refere <nl> <nl> state Optional < ConfigureAutoResult > conf ; <nl> if ( tokens [ startToken ] = = LiteralStringRef ( " auto " ) ) { <nl> - StatusObject s = wait ( makeInterruptable ( StatusClient : : statusFetcher ( ccf ) ) ) ; <nl> + StatusObject s = wait ( makeInterruptable ( StatusClient : : statusFetcher ( db ) ) ) ; <nl> if ( warn . isValid ( ) ) <nl> warn . cancel ( ) ; <nl> <nl> ACTOR Future < bool > configure ( Database db , std : : vector < StringRef > tokens , Refere <nl> printf ( " Configuration changed \ n " ) ; <nl> ret = false ; <nl> break ; <nl> + case ConfigurationResult : : LOCKED_NOT_NEW : <nl> + printf ( " ERROR : ` only new databases can be configured as locked ` \ n " ) ; <nl> + ret = true ; <nl> + break ; <nl> default : <nl> ASSERT ( false ) ; <nl> ret = true ; <nl> ACTOR Future < bool > exclude ( Database db , std : : vector < StringRef > tokens , Referenc <nl> return true ; <nl> } <nl> } <nl> - StatusObject status = wait ( makeInterruptable ( StatusClient : : statusFetcher ( ccf ) ) ) ; <nl> + StatusObject status = wait ( makeInterruptable ( StatusClient : : statusFetcher ( db ) ) ) ; <nl> <nl> state std : : string errorString = " ERROR : Could not calculate the impact of this exclude on the total free space in the cluster . \ n " <nl> " Please try the exclude again in 30 seconds . \ n " <nl> struct CLIOptions { <nl> <nl> # ifndef TLS_DISABLED <nl> / / TLS Options <nl> - case TLSOptions : : OPT_TLS_PLUGIN : <nl> + case TLSParams : : OPT_TLS_PLUGIN : <nl> args . OptionArg ( ) ; <nl> break ; <nl> - case TLSOptions : : OPT_TLS_CERTIFICATES : <nl> + case TLSParams : : OPT_TLS_CERTIFICATES : <nl> tlsCertPath = args . OptionArg ( ) ; <nl> break ; <nl> - case TLSOptions : : OPT_TLS_CA_FILE : <nl> + case TLSParams : : OPT_TLS_CA_FILE : <nl> tlsCAPath = args . OptionArg ( ) ; <nl> break ; <nl> - case TLSOptions : : OPT_TLS_KEY : <nl> + case TLSParams : : OPT_TLS_KEY : <nl> tlsKeyPath = args . OptionArg ( ) ; <nl> break ; <nl> - case TLSOptions : : OPT_TLS_PASSWORD : <nl> + case TLSParams : : OPT_TLS_PASSWORD : <nl> tlsPassword = args . OptionArg ( ) ; <nl> break ; <nl> - case TLSOptions : : OPT_TLS_VERIFY_PEERS : <nl> + case TLSParams : : OPT_TLS_VERIFY_PEERS : <nl> tlsVerifyPeers = args . OptionArg ( ) ; <nl> break ; <nl> # endif <nl> ACTOR Future < Void > addInterface ( std : : map < Key , std : : pair < Value , ClientLeaderRegInt <nl> ( * address_interface ) [ ip_port2 ] = std : : make_pair ( kv . value , leaderInterf ) ; <nl> } <nl> } <nl> - when ( wait ( delay ( 1 . 0 ) ) ) { } <nl> + when ( wait ( delay ( CLIENT_KNOBS - > CLI_CONNECT_TIMEOUT ) ) ) { } <nl> } <nl> return Void ( ) ; <nl> } <nl> ACTOR Future < int > cli ( CLIOptions opt , LineNoise * plinenoise ) { <nl> <nl> if ( ! opt . exec . present ( ) ) { <nl> if ( opt . initialStatusCheck ) { <nl> - Future < Void > checkStatusF = checkStatus ( Void ( ) , db - > getConnectionFile ( ) ) ; <nl> + Future < Void > checkStatusF = checkStatus ( Void ( ) , db ) ; <nl> wait ( makeInterruptable ( success ( checkStatusF ) ) ) ; <nl> } <nl> else { <nl> ACTOR Future < int > cli ( CLIOptions opt , LineNoise * plinenoise ) { <nl> linenoise . historyAdd ( line ) ; <nl> } <nl> <nl> - warn = checkStatus ( timeWarning ( 5 . 0 , " \ nWARNING : Long delay ( Ctrl - C to interrupt ) \ n " ) , db - > getConnectionFile ( ) ) ; <nl> + warn = checkStatus ( timeWarning ( 5 . 0 , " \ nWARNING : Long delay ( Ctrl - C to interrupt ) \ n " ) , db ) ; <nl> <nl> try { <nl> state UID randomID = deterministicRandom ( ) - > randomUniqueID ( ) ; <nl> ACTOR Future < int > cli ( CLIOptions opt , LineNoise * plinenoise ) { <nl> continue ; <nl> } <nl> <nl> - StatusObject s = wait ( makeInterruptable ( StatusClient : : statusFetcher ( db - > getConnectionFile ( ) ) ) ) ; <nl> + StatusObject s = wait ( makeInterruptable ( StatusClient : : statusFetcher ( db ) ) ) ; <nl> <nl> if ( ! opt . exec . present ( ) ) printf ( " \ n " ) ; <nl> printStatus ( s , level ) ; <nl> int main ( int argc , char * * argv ) { <nl> } catch ( Error & e ) { <nl> printf ( " ERROR : % s ( % d ) \ n " , e . what ( ) , e . code ( ) ) ; <nl> return 1 ; <nl> + } catch ( boost : : system : : system_error & e ) { <nl> + printf ( " ERROR : % s ( % d ) \ n " , e . what ( ) , e . code ( ) . value ( ) ) ; <nl> + return 1 ; <nl> } <nl> } <nl> mmm a / fdbclient / BackupContainer . actor . cpp <nl> ppp b / fdbclient / BackupContainer . actor . cpp <nl> class BackupContainerFileSystem : public IBackupContainer { <nl> return writeFile ( snapshotFolderString ( snapshotBeginVersion ) + format ( " / % d / " , snapshotFileCount / ( BUGGIFY ? 1 : 5000 ) ) + fileName ) ; <nl> } <nl> <nl> + / / Find what should be the filename of a path by finding whatever is after the last forward or backward slash , or failing to find those , the whole string . <nl> + static std : : string fileNameOnly ( std : : string path ) { <nl> + / / Find the last forward slash position , defaulting to 0 if not found <nl> + int pos = path . find_last_of ( ' / ' ) ; <nl> + if ( pos = = std : : string : : npos ) { <nl> + pos = 0 ; <nl> + } <nl> + / / Find the last backward slash position after pos , and update pos if found <nl> + int b = path . find_last_of ( ' \ \ ' , pos ) ; <nl> + if ( b ! = std : : string : : npos ) { <nl> + pos = b ; <nl> + } <nl> + return path . substr ( pos + 1 ) ; <nl> + } <nl> + <nl> static bool pathToRangeFile ( RangeFile & out , std : : string path , int64_t size ) { <nl> - std : : string name = basename ( path ) ; <nl> + std : : string name = fileNameOnly ( path ) ; <nl> RangeFile f ; <nl> f . fileName = path ; <nl> f . fileSize = size ; <nl> class BackupContainerFileSystem : public IBackupContainer { <nl> } <nl> <nl> static bool pathToLogFile ( LogFile & out , std : : string path , int64_t size ) { <nl> - std : : string name = basename ( path ) ; <nl> + std : : string name = fileNameOnly ( path ) ; <nl> LogFile f ; <nl> f . fileName = path ; <nl> f . fileSize = size ; <nl> class BackupContainerFileSystem : public IBackupContainer { <nl> } <nl> <nl> static bool pathToKeyspaceSnapshotFile ( KeyspaceSnapshotFile & out , std : : string path ) { <nl> - std : : string name = basename ( path ) ; <nl> + std : : string name = fileNameOnly ( path ) ; <nl> KeyspaceSnapshotFile f ; <nl> f . fileName = path ; <nl> int len ; <nl> mmm a / fdbclient / CommitTransaction . h <nl> ppp b / fdbclient / CommitTransaction . h <nl> <nl> # pragma once <nl> <nl> # include " fdbclient / FDBTypes . h " <nl> + # include " fdbserver / Knobs . h " <nl> <nl> / / The versioned message has wire format : - 1 , version , messages <nl> static const int32_t VERSION_HEADER = - 1 ; <nl> static const char * typeString [ ] = { " SetValue " , <nl> " AndV2 " , <nl> " CompareAndClear " } ; <nl> <nl> - struct MutationRef { <nl> + struct MutationRef { <nl> static const int OVERHEAD_BYTES = 12 ; / / 12 is the size of Header in MutationList entries <nl> enum Type : uint8_t { <nl> SetValue = 0 , <nl> struct MutationRef { <nl> MutationRef ( ) { } <nl> MutationRef ( Type t , StringRef a , StringRef b ) : type ( t ) , param1 ( a ) , param2 ( b ) { } <nl> MutationRef ( Arena & to , const MutationRef & from ) : type ( from . type ) , param1 ( to , from . param1 ) , param2 ( to , from . param2 ) { } <nl> - int totalSize ( ) const { return OVERHEAD_BYTES + param1 . size ( ) + param2 . size ( ) ; } <nl> + int totalSize ( ) const { return OVERHEAD_BYTES + param1 . size ( ) + param2 . size ( ) ; } <nl> int expectedSize ( ) const { return param1 . size ( ) + param2 . size ( ) ; } <nl> + int weightedTotalSize ( ) const { <nl> + / / AtomicOp can cause more workload to FDB cluster than the same - size set mutation ; <nl> + / / Amplify atomicOp size to consider such extra workload . <nl> + / / A good value for FASTRESTORE_ATOMICOP_WEIGHT needs experimental evaluations . <nl> + if ( isAtomicOp ( ) ) { <nl> + return totalSize ( ) * SERVER_KNOBS - > FASTRESTORE_ATOMICOP_WEIGHT ; <nl> + } else { <nl> + return totalSize ( ) ; <nl> + } <nl> + } <nl> <nl> std : : string toString ( ) const { <nl> if ( type < MutationRef : : MAX_ATOMIC_OP ) { <nl> struct MutationRef { <nl> } <nl> } <nl> <nl> + bool isAtomicOp ( ) const { return ( ATOMIC_MASK & ( 1 < < type ) ) ! = 0 ; } <nl> + <nl> template < class Ar > <nl> void serialize ( Ar & ar ) { <nl> serializer ( ar , type , param1 , param2 ) ; <nl> mmm a / fdbclient / DatabaseBackupAgent . actor . cpp <nl> ppp b / fdbclient / DatabaseBackupAgent . actor . cpp <nl> class DatabaseBackupAgentImpl { <nl> } <nl> <nl> if ( ! g_network - > isSimulated ( ) & & ! forceAction ) { <nl> - state StatusObject srcStatus = wait ( StatusClient : : statusFetcher ( backupAgent - > taskBucket - > src - > getConnectionFile ( ) ) ) ; <nl> - StatusObject destStatus = wait ( StatusClient : : statusFetcher ( dest - > getConnectionFile ( ) ) ) ; <nl> + state StatusObject srcStatus = wait ( StatusClient : : statusFetcher ( backupAgent - > taskBucket - > src ) ) ; <nl> + StatusObject destStatus = wait ( StatusClient : : statusFetcher ( dest ) ) ; <nl> checkAtomicSwitchOverConfig ( srcStatus , destStatus , tagName ) ; <nl> } <nl> <nl> mmm a / fdbclient / DatabaseContext . h <nl> ppp b / fdbclient / DatabaseContext . h <nl> class DatabaseContext : public ReferenceCounted < DatabaseContext > , public FastAll <nl> Future < Void > clientInfoMonitor ; <nl> Future < Void > connected ; <nl> <nl> + Reference < AsyncVar < Optional < ClusterInterface > > > statusClusterInterface ; <nl> + Future < Void > statusLeaderMon ; <nl> + double lastStatusFetch ; <nl> + <nl> int apiVersion ; <nl> <nl> int mvCacheInsertLocation ; <nl> mmm a / fdbclient / Knobs . cpp <nl> ppp b / fdbclient / Knobs . cpp <nl> ClientKnobs : : ClientKnobs ( bool randomize ) { <nl> init ( CLIENT_EXAMPLE_AMOUNT , 20 ) ; <nl> init ( MAX_CLIENT_STATUS_AGE , 1 . 0 ) ; <nl> init ( MAX_PROXY_CONNECTIONS , 5 ) ; if ( randomize & & BUGGIFY ) MAX_PROXY_CONNECTIONS = 1 ; <nl> + init ( STATUS_IDLE_TIMEOUT , 120 . 0 ) ; <nl> <nl> / / wrong_shard_server sometimes comes from the only nonfailed server , so we need to avoid a fast spin <nl> <nl> ClientKnobs : : ClientKnobs ( bool randomize ) { <nl> <nl> init ( CONSISTENCY_CHECK_RATE_LIMIT_MAX , 50e6 ) ; / / Limit in per sec <nl> init ( CONSISTENCY_CHECK_ONE_ROUND_TARGET_COMPLETION_TIME , 7 * 24 * 60 * 60 ) ; / / 7 days <nl> - <nl> - / / fdbcli <nl> - init ( CLI_CONNECT_PARALLELISM , 10 ) ; <nl> + <nl> + / / fdbcli <nl> + init ( CLI_CONNECT_PARALLELISM , 400 ) ; <nl> + init ( CLI_CONNECT_TIMEOUT , 10 . 0 ) ; <nl> } <nl> mmm a / fdbclient / Knobs . h <nl> ppp b / fdbclient / Knobs . h <nl> class ClientKnobs : public Knobs { <nl> int CLIENT_EXAMPLE_AMOUNT ; <nl> double MAX_CLIENT_STATUS_AGE ; <nl> int MAX_PROXY_CONNECTIONS ; <nl> + double STATUS_IDLE_TIMEOUT ; <nl> <nl> / / wrong_shard_server sometimes comes from the only nonfailed server , so we need to avoid a fast spin <nl> double WRONG_SHARD_SERVER_DELAY ; / / SOMEDAY : This delay can limit performance of retrieving data when the cache is mostly wrong ( e . g . dumping the database after a test ) <nl> class ClientKnobs : public Knobs { <nl> <nl> int CONSISTENCY_CHECK_RATE_LIMIT_MAX ; <nl> int CONSISTENCY_CHECK_ONE_ROUND_TARGET_COMPLETION_TIME ; <nl> - <nl> - / / fdbcli <nl> - int CLI_CONNECT_PARALLELISM ; <nl> <nl> + / / fdbcli <nl> + int CLI_CONNECT_PARALLELISM ; <nl> + double CLI_CONNECT_TIMEOUT ; <nl> + <nl> ClientKnobs ( bool randomize = false ) ; <nl> } ; <nl> <nl> mmm a / fdbclient / ManagementAPI . actor . cpp <nl> ppp b / fdbclient / ManagementAPI . actor . cpp <nl> std : : map < std : : string , std : : string > configForToken ( std : : string const & mode ) { <nl> return out ; <nl> } <nl> <nl> + if ( mode = = " locked " ) { <nl> + / / Setting this key is interpreted as an instruction to use the normal version - stamp - based mechanism for locking <nl> + / / the database . <nl> + out [ databaseLockedKey . toString ( ) ] = deterministicRandom ( ) - > randomUniqueID ( ) . toString ( ) ; <nl> + return out ; <nl> + } <nl> + <nl> size_t pos ; <nl> <nl> / / key : = value is unvalidated and unchecked <nl> ACTOR Future < ConfigurationResult : : Type > changeConfig ( Database cx , std : : map < std : <nl> / / make sure we have essential configuration options <nl> std : : string initKey = configKeysPrefix . toString ( ) + " initialized " ; <nl> state bool creating = m . count ( initKey ) ! = 0 ; <nl> + state Optional < UID > locked ; <nl> + { <nl> + auto iter = m . find ( databaseLockedKey . toString ( ) ) ; <nl> + if ( iter ! = m . end ( ) ) { <nl> + if ( ! creating ) { <nl> + return ConfigurationResult : : LOCKED_NOT_NEW ; <nl> + } <nl> + locked = UID : : fromString ( iter - > second ) ; <nl> + m . erase ( iter ) ; <nl> + } <nl> + } <nl> if ( creating ) { <nl> m [ initIdKey . toString ( ) ] = deterministicRandom ( ) - > randomUniqueID ( ) . toString ( ) ; <nl> if ( ! isCompleteConfiguration ( m ) ) { <nl> ACTOR Future < ConfigurationResult : : Type > changeConfig ( Database cx , std : : map < std : <nl> tr . addReadConflictRange ( singleKeyRange ( m . begin ( ) - > first ) ) ; <nl> } <nl> <nl> + if ( locked . present ( ) ) { <nl> + ASSERT ( creating ) ; <nl> + tr . atomicOp ( databaseLockedKey , <nl> + BinaryWriter : : toValue ( locked . get ( ) , Unversioned ( ) ) <nl> + . withPrefix ( LiteralStringRef ( " 0123456789 " ) ) <nl> + . withSuffix ( LiteralStringRef ( " \ x00 \ x00 \ x00 \ x00 " ) ) , <nl> + MutationRef : : SetVersionstampedValue ) ; <nl> + } <nl> + <nl> for ( auto i = m . begin ( ) ; i ! = m . end ( ) ; + + i ) { <nl> tr . set ( StringRef ( i - > first ) , StringRef ( i - > second ) ) ; <nl> } <nl> ACTOR Future < CoordinatorsResult : : Type > changeQuorum ( Database cx , Reference < IQuo <nl> <nl> if ( g_network - > isSimulated ( ) ) { <nl> for ( int i = 0 ; i < ( desiredCoordinators . size ( ) / 2 ) + 1 ; i + + ) { <nl> - auto address = NetworkAddress ( desiredCoordinators [ i ] . ip , desiredCoordinators [ i ] . port , true , false ) ; <nl> - g_simulator . protectedAddresses . insert ( address ) ; <nl> - TraceEvent ( " ProtectCoordinator " ) . detail ( " Address " , address ) . backtrace ( ) ; <nl> + auto addresses = g_simulator . getProcessByAddress ( desiredCoordinators [ i ] ) - > addresses ; <nl> + <nl> + g_simulator . protectedAddresses . insert ( addresses . address ) ; <nl> + if ( addresses . secondaryAddress . present ( ) ) { <nl> + g_simulator . protectedAddresses . insert ( addresses . secondaryAddress . get ( ) ) ; <nl> + } <nl> + TraceEvent ( " ProtectCoordinator " ) . detail ( " Address " , desiredCoordinators [ i ] ) . backtrace ( ) ; <nl> } <nl> } <nl> <nl> struct AutoQuorumChange : IQuorumChange { <nl> * err = CoordinatorsResult : : NOT_ENOUGH_MACHINES ; <nl> return vector < NetworkAddress > ( ) ; <nl> } <nl> - desiredCount = std : : max ( oldCoordinators . size ( ) , ( workers . size ( ) - 1 ) | 1 ) ; <nl> - chosen . resize ( desiredCount ) ; <nl> + chosen . resize ( ( chosen . size ( ) - 1 ) | 1 ) ; <nl> } <nl> <nl> return chosen ; <nl> ACTOR Future < std : : set < NetworkAddress > > checkForExcludingServers ( Database cx , vec <nl> state bool ok = true ; <nl> inProgressExclusion . clear ( ) ; <nl> for ( auto & s : serverList ) { <nl> - auto addr = decodeServerListValue ( s . value ) . address ( ) ; <nl> - if ( addressExcluded ( exclusions , addr ) ) { <nl> + auto addresses = decodeServerListValue ( s . value ) . getKeyValues . getEndpoint ( ) . addresses ; <nl> + if ( addressExcluded ( exclusions , addresses . address ) ) { <nl> + ok = false ; <nl> + inProgressExclusion . insert ( addresses . address ) ; <nl> + } <nl> + if ( addresses . secondaryAddress . present ( ) & & addressExcluded ( exclusions , addresses . secondaryAddress . get ( ) ) ) { <nl> ok = false ; <nl> - inProgressExclusion . insert ( addr ) ; <nl> + inProgressExclusion . insert ( addresses . secondaryAddress . get ( ) ) ; <nl> } <nl> } <nl> <nl> mmm a / fdbclient / ManagementAPI . actor . h <nl> ppp b / fdbclient / ManagementAPI . actor . h <nl> class ConfigurationResult { <nl> NOT_ENOUGH_WORKERS , <nl> REGION_REPLICATION_MISMATCH , <nl> DCID_MISSING , <nl> - SUCCESS <nl> + LOCKED_NOT_NEW , <nl> + SUCCESS , <nl> } ; <nl> } ; <nl> <nl> mmm a / fdbclient / MonitorLeader . actor . cpp <nl> ppp b / fdbclient / MonitorLeader . actor . cpp <nl> ACTOR Future < Void > asyncDeserializeClusterInterface ( Reference < AsyncVar < Value > > s <nl> Reference < AsyncVar < Optional < ClusterInterface > > > outKnownLeader ) { <nl> state Reference < AsyncVar < Optional < ClusterControllerClientInterface > > > knownLeader ( <nl> new AsyncVar < Optional < ClusterControllerClientInterface > > { } ) ; <nl> - state Future < Void > deserializer = asyncDeserialize ( serializedInfo , knownLeader , FLOW_KNOBS - > USE_OBJECT_SERIALIZER ) ; <nl> + state Future < Void > deserializer = asyncDeserialize ( serializedInfo , knownLeader ) ; <nl> loop { <nl> choose { <nl> when ( wait ( deserializer ) ) { UNSTOPPABLE_ASSERT ( false ) ; } <nl> ACTOR Future < Void > monitorLeaderForProxies ( Key clusterKey , vector < NetworkAddres <nl> } <nl> <nl> if ( leader . get ( ) . first . serializedInfo . size ( ) ) { <nl> - if ( FLOW_KNOBS - > USE_OBJECT_SERIALIZER ) { <nl> - ObjectReader reader ( leader . get ( ) . first . serializedInfo . begin ( ) , IncludeVersion ( ) ) ; <nl> - ClusterControllerClientInterface res ; <nl> - reader . deserialize ( res ) ; <nl> - knownLeader - > set ( res ) ; <nl> - } else { <nl> - ClusterControllerClientInterface res = BinaryReader : : fromStringRef < ClusterControllerClientInterface > ( leader . get ( ) . first . serializedInfo , IncludeVersion ( ) ) ; <nl> - knownLeader - > set ( res ) ; <nl> - } <nl> + ObjectReader reader ( leader . get ( ) . first . serializedInfo . begin ( ) , IncludeVersion ( ) ) ; <nl> + ClusterControllerClientInterface res ; <nl> + reader . deserialize ( res ) ; <nl> + knownLeader - > set ( res ) ; <nl> } <nl> } <nl> wait ( nomineeChange . onTrigger ( ) | | allActors ) ; <nl> mmm a / fdbclient / MonitorLeader . h <nl> ppp b / fdbclient / MonitorLeader . h <nl> template < class LeaderInterface > <nl> struct LeaderDeserializer { <nl> Future < Void > operator ( ) ( const Reference < AsyncVar < Value > > & serializedInfo , <nl> const Reference < AsyncVar < Optional < LeaderInterface > > > & outKnownLeader ) { <nl> - return asyncDeserialize ( serializedInfo , outKnownLeader , FLOW_KNOBS - > USE_OBJECT_SERIALIZER ) ; <nl> + return asyncDeserialize ( serializedInfo , outKnownLeader ) ; <nl> } <nl> } ; <nl> <nl> mmm a / fdbclient / NativeAPI . actor . cpp <nl> ppp b / fdbclient / NativeAPI . actor . cpp <nl> <nl> # include " fdbrpc / LoadBalance . h " <nl> # include " fdbrpc / Net2FileSystem . h " <nl> # include " fdbrpc / simulator . h " <nl> - # include " fdbrpc / TLSConnection . h " <nl> # include " flow / ActorCollection . h " <nl> # include " flow / DeterministicRandom . h " <nl> # include " flow / Knobs . h " <nl> # include " flow / Platform . h " <nl> # include " flow / SystemMonitor . h " <nl> + # include " flow / TLSPolicy . h " <nl> # include " flow / UnitTest . h " <nl> <nl> # if defined ( CMAKE_BUILD ) | | ! defined ( WIN32 ) <nl> using std : : min ; <nl> using std : : pair ; <nl> <nl> NetworkOptions networkOptions ; <nl> - Reference < TLSOptions > tlsOptions ; <nl> + TLSParams tlsParams ; <nl> + static Reference < TLSPolicy > tlsPolicy ; <nl> <nl> - static void initTLSOptions ( ) { <nl> - if ( ! tlsOptions ) { <nl> - tlsOptions = Reference < TLSOptions > ( new TLSOptions ( ) ) ; <nl> + static void initTLSPolicy ( ) { <nl> + # ifndef TLS_DISABLED <nl> + if ( ! tlsPolicy ) { <nl> + tlsPolicy = Reference < TLSPolicy > ( new TLSPolicy ( TLSPolicy : : Is : : CLIENT ) ) ; <nl> } <nl> + # endif <nl> } <nl> <nl> static const Key CLIENT_LATENCY_INFO_PREFIX = LiteralStringRef ( " client_latency / " ) ; <nl> Database Database : : createDatabase ( Reference < ClusterConnectionFile > connFile , in <nl> <nl> auto publicIP = determinePublicIPAutomatically ( connFile - > getConnectionString ( ) ) ; <nl> selectTraceFormatter ( networkOptions . traceFormat ) ; <nl> + selectTraceClockSource ( networkOptions . traceClockSource ) ; <nl> openTraceFile ( NetworkAddress ( publicIP , : : getpid ( ) ) , networkOptions . traceRollSize , networkOptions . traceMaxLogsSize , networkOptions . traceDirectory . get ( ) , " trace " , networkOptions . traceLogGroup ) ; <nl> <nl> TraceEvent ( " ClientStart " ) <nl> void setNetworkOption ( FDBNetworkOptions : : Option option , Optional < StringRef > valu <nl> throw invalid_option_value ( ) ; <nl> } <nl> break ; <nl> + case FDBNetworkOptions : : TRACE_CLOCK_SOURCE : <nl> + validateOptionValue ( value , true ) ; <nl> + networkOptions . traceClockSource = value . get ( ) . toString ( ) ; <nl> + if ( ! validateTraceClockSource ( networkOptions . traceClockSource ) ) { <nl> + fprintf ( stderr , " Unrecognized trace clock source : ` % s ' \ n " , networkOptions . traceClockSource . c_str ( ) ) ; <nl> + throw invalid_option_value ( ) ; <nl> + } <nl> + break ; <nl> case FDBNetworkOptions : : KNOB : { <nl> validateOptionValue ( value , true ) ; <nl> <nl> void setNetworkOption ( FDBNetworkOptions : : Option option , Optional < StringRef > valu <nl> break ; <nl> case FDBNetworkOptions : : TLS_CERT_PATH : <nl> validateOptionValue ( value , true ) ; <nl> - initTLSOptions ( ) ; <nl> - tlsOptions - > set_cert_file ( value . get ( ) . toString ( ) ) ; <nl> + tlsParams . tlsCertPath = value . get ( ) . toString ( ) ; <nl> break ; <nl> - case FDBNetworkOptions : : TLS_CERT_BYTES : <nl> - initTLSOptions ( ) ; <nl> - tlsOptions - > set_cert_data ( value . get ( ) . toString ( ) ) ; <nl> + case FDBNetworkOptions : : TLS_CERT_BYTES : { <nl> + validateOptionValue ( value , true ) ; <nl> + tlsParams . tlsCertBytes = value . get ( ) . toString ( ) ; <nl> break ; <nl> - case FDBNetworkOptions : : TLS_CA_PATH : <nl> + } <nl> + case FDBNetworkOptions : : TLS_CA_PATH : { <nl> validateOptionValue ( value , true ) ; <nl> - initTLSOptions ( ) ; <nl> - tlsOptions - > set_ca_file ( value . get ( ) . toString ( ) ) ; <nl> + tlsParams . tlsCAPath = value . get ( ) . toString ( ) ; <nl> break ; <nl> - case FDBNetworkOptions : : TLS_CA_BYTES : <nl> + } <nl> + case FDBNetworkOptions : : TLS_CA_BYTES : { <nl> validateOptionValue ( value , true ) ; <nl> - initTLSOptions ( ) ; <nl> - tlsOptions - > set_ca_data ( value . get ( ) . toString ( ) ) ; <nl> + tlsParams . tlsCABytes = value . get ( ) . toString ( ) ; <nl> break ; <nl> + } <nl> case FDBNetworkOptions : : TLS_PASSWORD : <nl> validateOptionValue ( value , true ) ; <nl> - initTLSOptions ( ) ; <nl> - tlsOptions - > set_key_password ( value . get ( ) . toString ( ) ) ; <nl> + tlsParams . tlsPassword = value . get ( ) . toString ( ) ; <nl> break ; <nl> case FDBNetworkOptions : : TLS_KEY_PATH : <nl> - validateOptionValue ( value , true ) ; <nl> - initTLSOptions ( ) ; <nl> - tlsOptions - > set_key_file ( value . get ( ) . toString ( ) ) ; <nl> + validateOptionValue ( value , true ) ; <nl> + tlsParams . tlsKeyPath = value . get ( ) . toString ( ) ; <nl> break ; <nl> - case FDBNetworkOptions : : TLS_KEY_BYTES : <nl> + case FDBNetworkOptions : : TLS_KEY_BYTES : { <nl> validateOptionValue ( value , true ) ; <nl> - initTLSOptions ( ) ; <nl> - tlsOptions - > set_key_data ( value . get ( ) . toString ( ) ) ; <nl> + tlsParams . tlsKeyBytes = value . get ( ) . toString ( ) ; <nl> break ; <nl> + } <nl> case FDBNetworkOptions : : TLS_VERIFY_PEERS : <nl> validateOptionValue ( value , true ) ; <nl> - initTLSOptions ( ) ; <nl> - try { <nl> - tlsOptions - > set_verify_peers ( { value . get ( ) . toString ( ) } ) ; <nl> - } catch ( Error & e ) { <nl> + initTLSPolicy ( ) ; <nl> + # ifndef TLS_DISABLED <nl> + if ( ! tlsPolicy - > set_verify_peers ( { value . get ( ) . toString ( ) } ) ) { <nl> TraceEvent ( SevWarnAlways , " TLSValidationSetError " ) <nl> - . error ( e ) <nl> . detail ( " Input " , value . get ( ) . toString ( ) ) ; <nl> throw invalid_option_value ( ) ; <nl> } <nl> + # endif <nl> break ; <nl> case FDBNetworkOptions : : CLIENT_BUGGIFY_ENABLE : <nl> enableBuggify ( true , BuggifyType : : Client ) ; <nl> void setupNetwork ( uint64_t transportId , bool useMetrics ) { <nl> if ( ! networkOptions . logClientInfo . present ( ) ) <nl> networkOptions . logClientInfo = true ; <nl> <nl> - g_network = newNet2 ( false , useMetrics | | networkOptions . traceDirectory . present ( ) ) ; <nl> + initTLSPolicy ( ) ; <nl> + <nl> + g_network = newNet2 ( false , useMetrics | | networkOptions . traceDirectory . present ( ) , tlsPolicy , tlsParams ) ; <nl> FlowTransport : : createInstance ( true , transportId ) ; <nl> Net2FileSystem : : newFileSystem ( ) ; <nl> - <nl> - initTLSOptions ( ) ; <nl> - <nl> - # ifndef TLS_DISABLED <nl> - tlsOptions - > register_network ( ) ; <nl> - # endif <nl> } <nl> <nl> void runNetwork ( ) { <nl> ACTOR void checkWrites ( Database cx , Future < Void > committed , Promise < Void > outCo <nl> } else { <nl> Optional < Value > val = wait ( tr . get ( it - > range ( ) . begin ) ) ; <nl> if ( ! val . present ( ) | | val . get ( ) ! = m . setValue ) { <nl> - TraceEvent evt = TraceEvent ( SevError , " CheckWritesFailed " ) <nl> - . detail ( " Class " , " Set " ) <nl> + TraceEvent evt ( SevError , " CheckWritesFailed " ) ; <nl> + evt . detail ( " Class " , " Set " ) <nl> . detail ( " Key " , it - > range ( ) . begin ) <nl> . detail ( " Expected " , m . setValue ) ; <nl> if ( ! val . present ( ) ) <nl> mmm a / fdbclient / NativeAPI . actor . h <nl> ppp b / fdbclient / NativeAPI . actor . h <nl> struct NetworkOptions { <nl> std : : string clusterFile ; <nl> Optional < std : : string > traceDirectory ; <nl> uint64_t traceRollSize ; <nl> - uint64_t traceMaxLogsSize ; <nl> + uint64_t traceMaxLogsSize ; <nl> std : : string traceLogGroup ; <nl> std : : string traceFormat ; <nl> + std : : string traceClockSource ; <nl> Optional < bool > logClientInfo ; <nl> Standalone < VectorRef < ClientVersionRef > > supportedVersions ; <nl> bool slowTaskProfilingEnabled ; <nl> struct NetworkOptions { <nl> NetworkOptions ( ) <nl> : localAddress ( " " ) , clusterFile ( " " ) , traceDirectory ( Optional < std : : string > ( ) ) , <nl> traceRollSize ( TRACE_DEFAULT_ROLL_SIZE ) , traceMaxLogsSize ( TRACE_DEFAULT_MAX_LOGS_SIZE ) , traceLogGroup ( " default " ) , <nl> - traceFormat ( " xml " ) , slowTaskProfilingEnabled ( false ) { } <nl> + traceFormat ( " xml " ) , traceClockSource ( " now " ) , slowTaskProfilingEnabled ( false ) { } <nl> } ; <nl> <nl> class Database { <nl> mmm a / fdbclient / ReadYourWrites . actor . cpp <nl> ppp b / fdbclient / ReadYourWrites . actor . cpp <nl> Optional < Value > getValueFromJSON ( StatusObject statusObj ) { <nl> } <nl> } <nl> <nl> - ACTOR Future < Optional < Value > > getJSON ( Reference < ClusterConnectionFile > clusterFile ) { <nl> - StatusObject statusObj = wait ( StatusClient : : statusFetcher ( clusterFile ) ) ; <nl> + ACTOR Future < Optional < Value > > getJSON ( Database db ) { <nl> + StatusObject statusObj = wait ( StatusClient : : statusFetcher ( db ) ) ; <nl> return getValueFromJSON ( statusObj ) ; <nl> } <nl> <nl> Future < Optional < Value > > ReadYourWritesTransaction : : get ( const Key & key , bool s <nl> <nl> if ( key = = LiteralStringRef ( " \ xff \ xff / status / json " ) ) { <nl> if ( tr . getDatabase ( ) . getPtr ( ) & & tr . getDatabase ( ) - > getConnectionFile ( ) ) { <nl> - return getJSON ( tr . getDatabase ( ) - > getConnectionFile ( ) ) ; <nl> + return getJSON ( tr . getDatabase ( ) ) ; <nl> } <nl> else { <nl> return Optional < Value > ( ) ; <nl> mmm a / fdbclient / RestoreWorkerInterface . actor . h <nl> ppp b / fdbclient / RestoreWorkerInterface . actor . h <nl> <nl> # define FDBCLIENT_RESTORE_WORKER_INTERFACE_ACTOR_H <nl> <nl> # include < sstream > <nl> + # include < string > <nl> # include " flow / Stats . h " <nl> # include " flow / flow . h " <nl> # include " fdbrpc / fdbrpc . h " <nl> struct RestoreSendMutationsToAppliersRequest ; <nl> struct RestoreSendVersionedMutationsRequest ; <nl> struct RestoreSysInfo ; <nl> struct RestoreApplierInterface ; <nl> + struct RestoreFinishRequest ; <nl> <nl> / / RestoreSysInfo includes information each ( type of ) restore roles should know . <nl> / / At this moment , it only include appliers . We keep the name for future extension . <nl> struct RestoreLoaderInterface : RestoreRoleInterface { <nl> RequestStream < RestoreSendMutationsToAppliersRequest > sendMutations ; <nl> RequestStream < RestoreVersionBatchRequest > initVersionBatch ; <nl> RequestStream < RestoreSimpleRequest > collectRestoreRoleInterfaces ; <nl> - RequestStream < RestoreVersionBatchRequest > finishRestore ; <nl> + RequestStream < RestoreFinishRequest > finishRestore ; <nl> <nl> bool operator = = ( RestoreWorkerInterface const & r ) const { return id ( ) = = r . id ( ) ; } <nl> bool operator ! = ( RestoreWorkerInterface const & r ) const { return id ( ) ! = r . id ( ) ; } <nl> struct RestoreApplierInterface : RestoreRoleInterface { <nl> RequestStream < RestoreVersionBatchRequest > applyToDB ; <nl> RequestStream < RestoreVersionBatchRequest > initVersionBatch ; <nl> RequestStream < RestoreSimpleRequest > collectRestoreRoleInterfaces ; <nl> - RequestStream < RestoreVersionBatchRequest > finishRestore ; <nl> + RequestStream < RestoreFinishRequest > finishRestore ; <nl> <nl> bool operator = = ( RestoreWorkerInterface const & r ) const { return id ( ) = = r . id ( ) ; } <nl> bool operator ! = ( RestoreWorkerInterface const & r ) const { return id ( ) ! = r . id ( ) ; } <nl> struct RestoreRecruitRoleRequest : TimedRequest { <nl> std : : string toString ( ) { return printable ( ) ; } <nl> } ; <nl> <nl> + / / Static info . across version batches <nl> struct RestoreSysInfoRequest : TimedRequest { <nl> constexpr static FileIdentifier file_identifier = 75960741 ; <nl> <nl> struct RestoreLoadFileReply : TimedRequest { <nl> <nl> LoadingParam param ; <nl> MutationsVec samples ; / / sampled mutations <nl> + bool isDuplicated ; / / true if loader thinks the request is a duplicated one <nl> <nl> RestoreLoadFileReply ( ) = default ; <nl> - explicit RestoreLoadFileReply ( LoadingParam param , MutationsVec samples ) : param ( param ) , samples ( samples ) { } <nl> + explicit RestoreLoadFileReply ( LoadingParam param , MutationsVec samples , bool isDuplicated ) <nl> + : param ( param ) , samples ( samples ) , isDuplicated ( isDuplicated ) { } <nl> <nl> template < class Ar > <nl> void serialize ( Ar & ar ) { <nl> - serializer ( ar , param , samples ) ; <nl> + serializer ( ar , param , samples , isDuplicated ) ; <nl> } <nl> <nl> std : : string toString ( ) { <nl> std : : stringstream ss ; <nl> - ss < < " LoadingParam : " < < param . toString ( ) < < " samples . size : " < < samples . size ( ) ; <nl> + ss < < " LoadingParam : " < < param . toString ( ) < < " samples . size : " < < samples . size ( ) <nl> + < < " isDuplicated : " < < isDuplicated ; <nl> return ss . str ( ) ; <nl> } <nl> } ; <nl> struct RestoreLoadFileReply : TimedRequest { <nl> struct RestoreLoadFileRequest : TimedRequest { <nl> constexpr static FileIdentifier file_identifier = 26557364 ; <nl> <nl> + int batchIndex ; <nl> LoadingParam param ; <nl> <nl> ReplyPromise < RestoreLoadFileReply > reply ; <nl> <nl> RestoreLoadFileRequest ( ) = default ; <nl> - explicit RestoreLoadFileRequest ( LoadingParam & param ) : param ( param ) { } ; <nl> + explicit RestoreLoadFileRequest ( int batchIndex , LoadingParam & param ) : batchIndex ( batchIndex ) , param ( param ) { } ; <nl> <nl> template < class Ar > <nl> void serialize ( Ar & ar ) { <nl> - serializer ( ar , param , reply ) ; <nl> + serializer ( ar , batchIndex , param , reply ) ; <nl> } <nl> <nl> std : : string toString ( ) { <nl> std : : stringstream ss ; <nl> - ss < < " RestoreLoadFileRequest param : " < < param . toString ( ) ; <nl> + ss < < " RestoreLoadFileRequest batchIndex : " < < batchIndex < < " param : " < < param . toString ( ) ; <nl> return ss . str ( ) ; <nl> } <nl> } ; <nl> struct RestoreLoadFileRequest : TimedRequest { <nl> struct RestoreSendMutationsToAppliersRequest : TimedRequest { <nl> constexpr static FileIdentifier file_identifier = 68827305 ; <nl> <nl> + int batchIndex ; / / version batch index <nl> std : : map < Key , UID > rangeToApplier ; <nl> bool useRangeFile ; / / Send mutations parsed from range file ? <nl> <nl> ReplyPromise < RestoreCommonReply > reply ; <nl> <nl> RestoreSendMutationsToAppliersRequest ( ) = default ; <nl> - explicit RestoreSendMutationsToAppliersRequest ( std : : map < Key , UID > rangeToApplier , bool useRangeFile ) <nl> - : rangeToApplier ( rangeToApplier ) , useRangeFile ( useRangeFile ) { } <nl> + explicit RestoreSendMutationsToAppliersRequest ( int batchIndex , std : : map < Key , UID > rangeToApplier , bool useRangeFile ) <nl> + : batchIndex ( batchIndex ) , rangeToApplier ( rangeToApplier ) , useRangeFile ( useRangeFile ) { } <nl> <nl> template < class Ar > <nl> void serialize ( Ar & ar ) { <nl> - serializer ( ar , rangeToApplier , useRangeFile , reply ) ; <nl> + serializer ( ar , batchIndex , rangeToApplier , useRangeFile , reply ) ; <nl> } <nl> <nl> std : : string toString ( ) { <nl> std : : stringstream ss ; <nl> - ss < < " RestoreSendMutationsToAppliersRequest keyToAppliers . size : " < < rangeToApplier . size ( ) <nl> - < < " useRangeFile : " < < useRangeFile ; <nl> + ss < < " RestoreSendMutationsToAppliersRequest batchIndex : " < < batchIndex <nl> + < < " keyToAppliers . size : " < < rangeToApplier . size ( ) < < " useRangeFile : " < < useRangeFile ; <nl> return ss . str ( ) ; <nl> } <nl> } ; <nl> struct RestoreSendMutationsToAppliersRequest : TimedRequest { <nl> struct RestoreSendVersionedMutationsRequest : TimedRequest { <nl> constexpr static FileIdentifier file_identifier = 69764565 ; <nl> <nl> + int batchIndex ; / / version batch index <nl> RestoreAsset asset ; / / Unique identifier for the current restore asset <nl> <nl> Version prevVersion , version ; / / version is the commitVersion of the mutation vector . <nl> struct RestoreSendVersionedMutationsRequest : TimedRequest { <nl> ReplyPromise < RestoreCommonReply > reply ; <nl> <nl> RestoreSendVersionedMutationsRequest ( ) = default ; <nl> - explicit RestoreSendVersionedMutationsRequest ( const RestoreAsset & asset , Version prevVersion , Version version , <nl> - bool isRangeFile , MutationsVec mutations ) <nl> - : asset ( asset ) , prevVersion ( prevVersion ) , version ( version ) , isRangeFile ( isRangeFile ) , mutations ( mutations ) { } <nl> + explicit RestoreSendVersionedMutationsRequest ( int batchIndex , const RestoreAsset & asset , Version prevVersion , <nl> + Version version , bool isRangeFile , MutationsVec mutations ) <nl> + : batchIndex ( batchIndex ) , asset ( asset ) , prevVersion ( prevVersion ) , version ( version ) , isRangeFile ( isRangeFile ) , <nl> + mutations ( mutations ) { } <nl> <nl> std : : string toString ( ) { <nl> std : : stringstream ss ; <nl> - ss < < " RestoreAsset : " < < asset . toString ( ) < < " prevVersion : " < < prevVersion < < " version : " < < version <nl> - < < " isRangeFile : " < < isRangeFile < < " mutations . size : " < < mutations . size ( ) ; <nl> + ss < < " VersionBatchIndex : " < < batchIndex < < " RestoreAsset : " < < asset . toString ( ) <nl> + < < " prevVersion : " < < prevVersion < < " version : " < < version < < " isRangeFile : " < < isRangeFile <nl> + < < " mutations . size : " < < mutations . size ( ) ; <nl> return ss . str ( ) ; <nl> } <nl> <nl> template < class Ar > <nl> void serialize ( Ar & ar ) { <nl> - serializer ( ar , asset , prevVersion , version , isRangeFile , mutations , reply ) ; <nl> + serializer ( ar , batchIndex , asset , prevVersion , version , isRangeFile , mutations , reply ) ; <nl> } <nl> } ; <nl> <nl> struct RestoreVersionBatchRequest : TimedRequest { <nl> - constexpr static FileIdentifier file_identifier = 13018413 ; <nl> + constexpr static FileIdentifier file_identifier = 97223537 ; <nl> <nl> - int batchID ; <nl> + int batchIndex ; <nl> <nl> ReplyPromise < RestoreCommonReply > reply ; <nl> <nl> RestoreVersionBatchRequest ( ) = default ; <nl> - explicit RestoreVersionBatchRequest ( int batchID ) : batchID ( batchID ) { } <nl> + explicit RestoreVersionBatchRequest ( int batchIndex ) : batchIndex ( batchIndex ) { } <nl> + <nl> + template < class Ar > <nl> + void serialize ( Ar & ar ) { <nl> + serializer ( ar , batchIndex , reply ) ; <nl> + } <nl> + <nl> + std : : string toString ( ) { <nl> + std : : stringstream ss ; <nl> + ss < < " RestoreVersionBatchRequest batchIndex : " < < batchIndex ; <nl> + return ss . str ( ) ; <nl> + } <nl> + } ; <nl> + <nl> + struct RestoreFinishRequest : TimedRequest { <nl> + constexpr static FileIdentifier file_identifier = 13018413 ; <nl> + <nl> + bool terminate ; / / role exits if terminate = true <nl> + <nl> + ReplyPromise < RestoreCommonReply > reply ; <nl> + <nl> + RestoreFinishRequest ( ) = default ; <nl> + explicit RestoreFinishRequest ( bool terminate ) : terminate ( terminate ) { } <nl> <nl> template < class Ar > <nl> void serialize ( Ar & ar ) { <nl> - serializer ( ar , batchID , reply ) ; <nl> + serializer ( ar , terminate , reply ) ; <nl> } <nl> <nl> std : : string toString ( ) { <nl> std : : stringstream ss ; <nl> - ss < < " RestoreVersionBatchRequest BatchID : " < < batchID ; <nl> + ss < < " RestoreFinishRequest terminate : " < < terminate ; <nl> return ss . str ( ) ; <nl> } <nl> } ; <nl> std : : string getRoleStr ( RestoreRole role ) ; <nl> <nl> / / / / mmm Interface functions <nl> ACTOR Future < Void > _restoreWorker ( Database cx , LocalityData locality ) ; <nl> - ACTOR Future < Void > restoreWorker ( Reference < ClusterConnectionFile > ccf , LocalityData locality ) ; <nl> + ACTOR Future < Void > restoreWorker ( Reference < ClusterConnectionFile > ccf , LocalityData locality , std : : string coordFolder ) ; <nl> <nl> # include " flow / unactorcompiler . h " <nl> # endif <nl> mmm a / fdbclient / StatusClient . actor . cpp <nl> ppp b / fdbclient / StatusClient . actor . cpp <nl> StatusObject getClientDatabaseStatus ( StatusObjectReader client , StatusObjectRead <nl> return databaseStatus ; <nl> } <nl> <nl> - ACTOR Future < StatusObject > statusFetcherImpl ( Reference < ClusterConnectionFile > f ) { <nl> + ACTOR Future < StatusObject > statusFetcherImpl ( Reference < ClusterConnectionFile > f , Reference < AsyncVar < Optional < ClusterInterface > > > clusterInterface ) { <nl> if ( ! g_network ) throw network_not_setup ( ) ; <nl> <nl> state StatusObject statusObj ; <nl> ACTOR Future < StatusObject > statusFetcherImpl ( Reference < ClusterConnectionFile > f <nl> / / This could be read from the JSON but doing so safely is ugly so using a real var . <nl> state bool quorum_reachable = false ; <nl> state int coordinatorsFaultTolerance = 0 ; <nl> - state Reference < AsyncVar < Optional < ClusterInterface > > > clusterInterface ( new AsyncVar < Optional < ClusterInterface > > ) ; <nl> <nl> try { <nl> state int64_t clientTime = time ( 0 ) ; <nl> <nl> - state Future < Void > leaderMon = monitorLeader < ClusterInterface > ( f , clusterInterface ) ; <nl> - <nl> StatusObject _statusObjClient = wait ( clientStatusFetcher ( f , & clientMessages , & quorum_reachable , & coordinatorsFaultTolerance ) ) ; <nl> statusObjClient = _statusObjClient ; <nl> <nl> ACTOR Future < StatusObject > statusFetcherImpl ( Reference < ClusterConnectionFile > f <nl> return statusObj ; <nl> } <nl> <nl> - Future < StatusObject > StatusClient : : statusFetcher ( Reference < ClusterConnectionFile > clusterFile ) { <nl> - return statusFetcherImpl ( clusterFile ) ; <nl> + ACTOR Future < Void > timeoutMonitorLeader ( Database db ) { <nl> + state Future < Void > leadMon = monitorLeader < ClusterInterface > ( db - > getConnectionFile ( ) , db - > statusClusterInterface ) ; <nl> + loop { <nl> + wait ( delay ( CLIENT_KNOBS - > STATUS_IDLE_TIMEOUT + 0 . 00001 + db - > lastStatusFetch - now ( ) ) ) ; <nl> + if ( now ( ) - db - > lastStatusFetch > CLIENT_KNOBS - > STATUS_IDLE_TIMEOUT ) { <nl> + db - > statusClusterInterface = Reference < AsyncVar < Optional < ClusterInterface > > > ( ) ; <nl> + return Void ( ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + Future < StatusObject > StatusClient : : statusFetcher ( Database db ) { <nl> + db - > lastStatusFetch = now ( ) ; <nl> + if ( ! db - > statusClusterInterface ) { <nl> + db - > statusClusterInterface = Reference < AsyncVar < Optional < ClusterInterface > > > ( new AsyncVar < Optional < ClusterInterface > > ) ; <nl> + db - > statusLeaderMon = timeoutMonitorLeader ( db ) ; <nl> + } <nl> + <nl> + return statusFetcherImpl ( db - > getConnectionFile ( ) , db - > statusClusterInterface ) ; <nl> } <nl> mmm a / fdbclient / StatusClient . h <nl> ppp b / fdbclient / StatusClient . h <nl> <nl> <nl> # include " flow / flow . h " <nl> # include " fdbclient / Status . h " <nl> + # include " fdbclient / DatabaseContext . h " <nl> <nl> class StatusClient { <nl> public : <nl> enum StatusLevel { MINIMAL = 0 , NORMAL = 1 , DETAILED = 2 , JSON = 3 } ; <nl> - static Future < StatusObject > statusFetcher ( Reference < ClusterConnectionFile > clusterFile ) ; <nl> + static Future < StatusObject > statusFetcher ( Database db ) ; <nl> } ; <nl> <nl> # endif <nl> \ No newline at end of file <nl> mmm a / fdbclient / StorageServerInterface . h <nl> ppp b / fdbclient / StorageServerInterface . h <nl> struct SplitMetricsRequest { <nl> struct GetStorageMetricsReply { <nl> constexpr static FileIdentifier file_identifier = 15491478 ; <nl> StorageMetrics load ; <nl> - StorageMetrics free ; <nl> + StorageMetrics available ; <nl> StorageMetrics capacity ; <nl> double bytesInputRate ; <nl> <nl> struct GetStorageMetricsReply { <nl> <nl> template < class Ar > <nl> void serialize ( Ar & ar ) { <nl> - serializer ( ar , load , free , capacity , bytesInputRate ) ; <nl> + serializer ( ar , load , available , capacity , bytesInputRate ) ; <nl> } <nl> } ; <nl> <nl> mmm a / fdbclient / SystemData . cpp <nl> ppp b / fdbclient / SystemData . cpp <nl> const KeyRangeRef restoreApplierKeys ( LiteralStringRef ( " \ xff \ x02 / restoreApplier / " <nl> const KeyRef restoreApplierTxnValue = LiteralStringRef ( " 1 " ) ; <nl> <nl> / / restoreApplierKeys : track atomic transaction progress to ensure applying atomicOp exactly once <nl> - / / Version is passed in as LittleEndian , it must be converted to BigEndian to maintain ordering in lexical order <nl> - const Key restoreApplierKeyFor ( UID const & applierID , Version version ) { <nl> + / / Version and batchIndex are passed in as LittleEndian , <nl> + / / they must be converted to BigEndian to maintain ordering in lexical order <nl> + const Key restoreApplierKeyFor ( UID const & applierID , int64_t batchIndex , Version version ) { <nl> BinaryWriter wr ( Unversioned ( ) ) ; <nl> wr . serializeBytes ( restoreApplierKeys . begin ) ; <nl> - wr < < applierID < < bigEndian64 ( version ) ; <nl> + wr < < applierID < < bigEndian64 ( batchIndex ) < < bigEndian64 ( version ) ; <nl> return wr . toValue ( ) ; <nl> } <nl> <nl> - std : : pair < UID , Version > decodeRestoreApplierKey ( ValueRef const & key ) { <nl> + std : : tuple < UID , int64_t , Version > decodeRestoreApplierKey ( ValueRef const & key ) { <nl> BinaryReader rd ( key , Unversioned ( ) ) ; <nl> UID applierID ; <nl> + int64_t batchIndex ; <nl> Version version ; <nl> - rd > > applierID > > version ; <nl> - return std : : make_pair ( applierID , bigEndian64 ( version ) ) ; <nl> + rd > > applierID > > batchIndex > > version ; <nl> + return std : : make_tuple ( applierID , bigEndian64 ( batchIndex ) , bigEndian64 ( version ) ) ; <nl> } <nl> <nl> / / Encode restore worker key for workerID <nl> mmm a / fdbclient / SystemData . h <nl> ppp b / fdbclient / SystemData . h <nl> extern const KeyRangeRef restoreRequestKeys ; <nl> extern const KeyRangeRef restoreApplierKeys ; <nl> extern const KeyRef restoreApplierTxnValue ; <nl> <nl> - const Key restoreApplierKeyFor ( UID const & applierID , Version version ) ; <nl> - std : : pair < UID , Version > decodeRestoreApplierKey ( ValueRef const & key ) ; <nl> + const Key restoreApplierKeyFor ( UID const & applierID , int64_t batchIndex , Version version ) ; <nl> + std : : tuple < UID , int64_t , Version > decodeRestoreApplierKey ( ValueRef const & key ) ; <nl> const Key restoreWorkerKeyFor ( UID const & workerID ) ; <nl> const Value restoreWorkerInterfaceValue ( RestoreWorkerInterface const & server ) ; <nl> RestoreWorkerInterface decodeRestoreWorkerInterfaceValue ( ValueRef const & value ) ; <nl> mmm a / fdbclient / md5 / md5 . c <nl> ppp b / fdbclient / md5 / md5 . c <nl> <nl> * compile - time configuration . <nl> * / <nl> <nl> - # ifndef HAVE_OPENSSL <nl> + # if ! defined ( HAVE_OPENSSL ) | | defined ( TLS_DISABLED ) <nl> <nl> # include < string . h > <nl> <nl> mmm a / fdbclient / md5 / md5 . h <nl> ppp b / fdbclient / md5 / md5 . h <nl> <nl> * See md5 . c for more information . <nl> * / <nl> <nl> - # ifdef HAVE_OPENSSL <nl> + # if defined ( HAVE_OPENSSL ) & & ! defined ( TLS_DISABLED ) <nl> # include < openssl / md5 . h > <nl> # elif ! defined ( _MD5_H ) <nl> # define _MD5_H <nl> mmm a / fdbclient / vexillographer / fdb . options <nl> ppp b / fdbclient / vexillographer / fdb . options <nl> description is not currently required but encouraged . <nl> < Option name = " trace_format " code = " 34 " <nl> paramType = " String " paramDescription = " Format of trace files " <nl> description = " Select the format of the log files . xml ( the default ) and json are supported . " / > <nl> + < Option name = " trace_clock_source " code = " 35 " <nl> + paramType = " String " paramDescription = " Trace clock source " <nl> + description = " Select clock source for trace files . now ( the default ) or realtime are supported . " / > <nl> < Option name = " knob " code = " 40 " <nl> paramType = " String " paramDescription = " knob_name = knob_value " <nl> description = " Set internal tuning or debugging knobs " / > <nl> description is not currently required but encouraged . <nl> defaultFor = " 500 " / > <nl> < Option name = " transaction_retry_limit " code = " 501 " <nl> paramType = " Int " paramDescription = " number of times to retry " <nl> - description = " Set a timeout in milliseconds which , when elapsed , will cause a transaction automatically to be cancelled . This sets the ` ` retry_limit ` ` option of each transaction created by this database . See the transaction option description for more information . " <nl> + description = " Set a maximum number of retries after which additional calls to ` ` onError ` ` will throw the most recently seen error code . This sets the ` ` retry_limit ` ` option of each transaction created by this database . See the transaction option description for more information . " <nl> defaultFor = " 501 " / > <nl> < Option name = " transaction_max_retry_delay " code = " 502 " <nl> paramType = " Int " paramDescription = " value in milliseconds of maximum delay " <nl> description is not currently required but encouraged . <nl> < Option name = " debug_transaction_identifier " code = " 403 " paramType = " String " paramDescription = " String identifier to be used when tracing or profiling this transaction . The identifier must not exceed 100 characters . " <nl> description = " Sets a client provided identifier for the transaction that will be used in scenarios like tracing or profiling . Client trace logging or transaction profiling must be separately enabled . " / > <nl> < Option name = " log_transaction " code = " 404 " <nl> - description = " Enables tracing for this transaction and logs results to the client trace logs . The DEBUG_TRANSACTION_IDENTIFIER option must be set before using this option , and client trace logging must be enabled and to get log output . " / > <nl> + description = " Enables tracing for this transaction and logs results to the client trace logs . The DEBUG_TRANSACTION_IDENTIFIER option must be set before using this option , and client trace logging must be enabled to get log output . " / > <nl> < Option name = " transaction_logging_max_field_length " code = " 405 " paramType = " Int " paramDescription = " Maximum length of escaped key and value fields . " <nl> description = " Sets the maximum escaped length of key and value fields to be logged to the trace file via the LOG_TRANSACTION option , after which the field will be truncated . A negative value disables truncation . " / > <nl> < Option name = " timeout " code = " 500 " <nl> description is not currently required but encouraged . <nl> < Option name = " snapshot_ryw_disable " code = " 601 " <nl> description = " Snapshot read operations will not see the results of writes done in the same transaction . This was the default behavior prior to API version 300 . " / > <nl> < Option name = " lock_aware " code = " 700 " <nl> - description = " The transaction can read and write to locked databases , and is resposible for checking that it took the lock . " / > <nl> + description = " The transaction can read and write to locked databases , and is responsible for checking that it took the lock . " / > <nl> < Option name = " used_during_commit_protection_disable " code = " 701 " <nl> description = " By default , operations that are performed on a transaction while it is being committed will not only fail themselves , but they will attempt to fail other in - flight operations ( such as the commit ) as well . This behavior is intended to help developers discover situations where operations could be unintentionally executed after the transaction has been reset . Setting this option removes that protection , causing only the offending operation to fail . " / > <nl> < Option name = " read_lock_aware " code = " 702 " <nl> mmm a / fdbrpc / CMakeLists . txt <nl> ppp b / fdbrpc / CMakeLists . txt <nl> set ( FDBRPC_SRCS <nl> sim2 . actor . cpp <nl> sim_validation . cpp <nl> TimedRequest . h <nl> - TLSConnection . actor . cpp <nl> TraceFileIO . cpp ) <nl> <nl> set ( FDBRPC_THIRD_PARTY_SRCS <nl> mmm a / fdbrpc / FlowTests . actor . cpp <nl> ppp b / fdbrpc / FlowTests . actor . cpp <nl> struct YieldMockNetwork : INetwork , ReferenceCounted < YieldMockNetwork > { <nl> virtual TaskPriority getCurrentTask ( ) { return baseNetwork - > getCurrentTask ( ) ; } <nl> virtual void setCurrentTask ( TaskPriority taskID ) { baseNetwork - > setCurrentTask ( taskID ) ; } <nl> virtual double now ( ) { return baseNetwork - > now ( ) ; } <nl> + virtual double timer ( ) { return baseNetwork - > timer ( ) ; } <nl> virtual void stop ( ) { return baseNetwork - > stop ( ) ; } <nl> virtual bool isSimulated ( ) const { return baseNetwork - > isSimulated ( ) ; } <nl> virtual void onMainThread ( Promise < Void > & & signal , TaskPriority taskID ) { return baseNetwork - > onMainThread ( std : : move ( signal ) , taskID ) ; } <nl> TEST_CASE ( " / fdbrpc / flow / wait_expression_after_cancel " ) <nl> return Void ( ) ; <nl> } <nl> <nl> + / / Tests for https : / / github . com / apple / foundationdb / issues / 1226 <nl> + <nl> + template < class > <nl> + struct ShouldNotGoIntoClassContextStack ; <nl> + <nl> + ACTOR static Future < Void > shouldNotHaveFriends ( ) ; <nl> + <nl> + class Foo1 { <nl> + public : <nl> + explicit Foo1 ( int x ) : x ( x ) { } <nl> + Future < int > foo ( ) { return fooActor ( this ) ; } <nl> + ACTOR static Future < int > fooActor ( Foo1 * self ) ; <nl> + <nl> + private : <nl> + int x ; <nl> + } ; <nl> + ACTOR Future < int > Foo1 : : fooActor ( Foo1 * self ) { <nl> + wait ( Future < Void > ( ) ) ; <nl> + return self - > x ; <nl> + } <nl> + <nl> + class [ [ nodiscard ] ] Foo2 { <nl> + public : <nl> + explicit Foo2 ( int x ) : x ( x ) { } <nl> + Future < int > foo ( ) { return fooActor ( this ) ; } <nl> + ACTOR static Future < int > fooActor ( Foo2 * self ) ; <nl> + <nl> + private : <nl> + int x ; <nl> + } ; <nl> + ACTOR Future < int > Foo2 : : fooActor ( Foo2 * self ) { <nl> + wait ( Future < Void > ( ) ) ; <nl> + return self - > x ; <nl> + } <nl> + <nl> + class alignas ( 4 ) Foo3 { <nl> + public : <nl> + explicit Foo3 ( int x ) : x ( x ) { } <nl> + Future < int > foo ( ) { return fooActor ( this ) ; } <nl> + ACTOR static Future < int > fooActor ( Foo3 * self ) ; <nl> + <nl> + private : <nl> + int x ; <nl> + } ; <nl> + ACTOR Future < int > Foo3 : : fooActor ( Foo3 * self ) { <nl> + wait ( Future < Void > ( ) ) ; <nl> + return self - > x ; <nl> + } <nl> + <nl> + struct Super { } ; <nl> + <nl> + class Foo4 : Super { <nl> + public : <nl> + explicit Foo4 ( int x ) : x ( x ) { } <nl> + Future < int > foo ( ) { return fooActor ( this ) ; } <nl> + ACTOR static Future < int > fooActor ( Foo4 * self ) ; <nl> + <nl> + private : <nl> + int x ; <nl> + } ; <nl> + ACTOR Future < int > Foo4 : : fooActor ( Foo4 * self ) { <nl> + wait ( Future < Void > ( ) ) ; <nl> + return self - > x ; <nl> + } <nl> + <nl> + struct Outer { <nl> + class Foo5 : Super { <nl> + public : <nl> + explicit Foo5 ( int x ) : x ( x ) { } <nl> + Future < int > foo ( ) { return fooActor ( this ) ; } <nl> + ACTOR static Future < int > fooActor ( Foo5 * self ) ; <nl> + <nl> + private : <nl> + int x ; <nl> + } ; <nl> + } ; <nl> + ACTOR Future < int > Outer : : Foo5 : : fooActor ( Outer : : Foo5 * self ) { <nl> + wait ( Future < Void > ( ) ) ; <nl> + return self - > x ; <nl> + } <nl> + <nl> + ACTOR static Future < Void > shouldNotHaveFriends2 ( ) ; <nl> + <nl> / / Meant to be run with - fsanitize = undefined <nl> TEST_CASE ( " / flow / DeterministicRandom / SignedOverflow " ) { <nl> deterministicRandom ( ) - > randomInt ( std : : numeric_limits < int > : : min ( ) , 0 ) ; <nl> mmm a / fdbrpc / FlowTransport . actor . cpp <nl> ppp b / fdbrpc / FlowTransport . actor . cpp <nl> ACTOR Future < Void > connectionMonitor ( Reference < Peer > peer ) { <nl> state double lastRefreshed = now ( ) ; <nl> state int64_t lastBytesReceived = peer - > bytesReceived ; <nl> loop { <nl> - wait ( delay ( FLOW_KNOBS - > CONNECTION_MONITOR_LOOP_TIME ) ) ; <nl> + wait ( delay ( FLOW_KNOBS - > CONNECTION_MONITOR_LOOP_TIME , TaskPriority : : ReadSocket ) ) ; <nl> if ( lastBytesReceived < peer - > bytesReceived ) { <nl> lastRefreshed = now ( ) ; <nl> lastBytesReceived = peer - > bytesReceived ; <nl> ACTOR Future < Void > connectionMonitor ( Reference < Peer > peer ) { <nl> <nl> / / We cannot let an error be thrown from connectionMonitor while still on the stack from scanPackets in connectionReader <nl> / / because then it would not call the destructor of connectionReader when connectionReader is cancelled . <nl> - wait ( delay ( 0 ) ) ; <nl> + wait ( delay ( 0 , TaskPriority : : ReadSocket ) ) ; <nl> <nl> if ( peer - > reliable . empty ( ) & & peer - > unsent . empty ( ) & & peer - > outstandingReplies = = 0 ) { <nl> if ( peer - > peerReferences = = 0 & & <nl> ACTOR Future < Void > connectionMonitor ( Reference < Peer > peer ) { <nl> } <nl> } <nl> <nl> - wait ( delayJittered ( FLOW_KNOBS - > CONNECTION_MONITOR_LOOP_TIME ) ) ; <nl> + wait ( delayJittered ( FLOW_KNOBS - > CONNECTION_MONITOR_LOOP_TIME , TaskPriority : : ReadSocket ) ) ; <nl> <nl> / / TODO : Stop monitoring and close the connection with no onDisconnect requests outstanding <nl> state ReplyPromise < Void > reply ; <nl> ACTOR Future < Void > connectionKeeper ( Reference < Peer > self , <nl> <nl> try { <nl> choose { <nl> - when ( Reference < IConnection > _conn = <nl> - wait ( INetworkConnections : : net ( ) - > connect ( self - > destination ) ) ) { <nl> + when ( Reference < IConnection > _conn = wait ( INetworkConnections : : net ( ) - > connect ( self - > destination ) ) ) { <nl> + conn = _conn ; <nl> + wait ( conn - > connectHandshake ( ) ) ; <nl> IFailureMonitor : : failureMonitor ( ) . setStatus ( self - > destination , FailureStatus ( false ) ) ; <nl> if ( self - > unsent . empty ( ) ) { <nl> - _conn - > close ( ) ; <nl> + conn - > close ( ) ; <nl> + conn = Reference < IConnection > ( ) ; <nl> continue ; <nl> } else { <nl> - conn = _conn ; <nl> TraceEvent ( " ConnectionExchangingConnectPacket " , conn - > getDebugID ( ) ) <nl> . suppressFor ( 1 . 0 ) <nl> . detail ( " PeerAddr " , self - > destination ) ; <nl> void Peer : : prependConnectPacket ( ) { <nl> <nl> pkt . connectPacketLength = sizeof ( pkt ) - sizeof ( pkt . connectPacketLength ) ; <nl> pkt . protocolVersion = currentProtocolVersion ; <nl> - if ( FLOW_KNOBS - > USE_OBJECT_SERIALIZER ) { <nl> - pkt . protocolVersion . addObjectSerializerFlag ( ) ; <nl> - } <nl> + pkt . protocolVersion . addObjectSerializerFlag ( ) ; <nl> pkt . connectionId = transport - > transportId ; <nl> <nl> PacketBuffer * pb_first = PacketBuffer : : create ( ) ; <nl> ACTOR static void deliver ( TransportData * self , Endpoint destination , ArenaReader <nl> if ( receiver ) { <nl> try { <nl> g_currentDeliveryPeerAddress = destination . addresses ; <nl> - if ( FLOW_KNOBS - > USE_OBJECT_SERIALIZER ) { <nl> - StringRef data = reader . arenaReadAll ( ) ; <nl> - ASSERT ( data . size ( ) > 8 ) ; <nl> - ArenaObjectReader objReader ( reader . arena ( ) , reader . arenaReadAll ( ) , AssumeVersion ( reader . protocolVersion ( ) ) ) ; <nl> - receiver - > receive ( objReader ) ; <nl> - } else { <nl> - receiver - > receive ( reader ) ; <nl> - } <nl> + StringRef data = reader . arenaReadAll ( ) ; <nl> + ASSERT ( data . size ( ) > 8 ) ; <nl> + ArenaObjectReader objReader ( reader . arena ( ) , reader . arenaReadAll ( ) , AssumeVersion ( reader . protocolVersion ( ) ) ) ; <nl> + receiver - > receive ( objReader ) ; <nl> g_currentDeliveryPeerAddress = { NetworkAddress ( ) } ; <nl> } catch ( Error & e ) { <nl> g_currentDeliveryPeerAddress = { NetworkAddress ( ) } ; <nl> ACTOR static Future < Void > connectionReader ( <nl> serializer ( pktReader , pkt ) ; <nl> <nl> uint64_t connectionId = pkt . connectionId ; <nl> - if ( ( FLOW_KNOBS - > USE_OBJECT_SERIALIZER ! = 0 ) ! = pkt . protocolVersion . hasObjectSerializerFlag ( ) | | <nl> - ! pkt . protocolVersion . isCompatible ( currentProtocolVersion ) ) { <nl> + if ( ! pkt . protocolVersion . hasObjectSerializerFlag ( ) | | <nl> + ! pkt . protocolVersion . isCompatible ( currentProtocolVersion ) ) { <nl> incompatibleProtocolVersionNewer = pkt . protocolVersion > currentProtocolVersion ; <nl> NetworkAddress addr = pkt . canonicalRemotePort <nl> ? NetworkAddress ( pkt . canonicalRemoteIp ( ) , pkt . canonicalRemotePort ) <nl> ACTOR static Future < Void > connectionReader ( <nl> / / Older versions expected us to hang up . It may work even if we don ' t hang up here , but it ' s safer to keep the old behavior . <nl> throw incompatible_protocol_version ( ) ; <nl> } <nl> - } <nl> - else { <nl> + } else { <nl> compatible = true ; <nl> TraceEvent ( " ConnectionEstablished " , conn - > getDebugID ( ) ) <nl> . suppressFor ( 1 . 0 ) <nl> ACTOR static Future < Void > connectionReader ( <nl> <nl> ACTOR static Future < Void > connectionIncoming ( TransportData * self , Reference < IConnection > conn ) { <nl> try { <nl> + wait ( conn - > acceptHandshake ( ) ) ; <nl> state Promise < Reference < Peer > > onConnected ; <nl> state Future < Void > reader = connectionReader ( self , conn , Reference < Peer > ( ) , onConnected ) ; <nl> choose { <nl> ACTOR static Future < Void > listen ( TransportData * self , NetworkAddress listenAddr <nl> try { <nl> loop { <nl> Reference < IConnection > conn = wait ( listener - > accept ( ) ) ; <nl> - TraceEvent ( " ConnectionFrom " , conn - > getDebugID ( ) ) . suppressFor ( 1 . 0 ) <nl> - . detail ( " FromAddress " , conn - > getPeerAddress ( ) ) <nl> - . detail ( " ListenAddress " , listenAddr . toString ( ) ) ; <nl> - incoming . add ( connectionIncoming ( self , conn ) ) ; <nl> - wait ( delay ( 0 ) | | delay ( FLOW_KNOBS - > CONNECTION_ACCEPT_DELAY , TaskPriority : : WriteSocket ) ) ; <nl> + if ( conn ) { <nl> + TraceEvent ( " ConnectionFrom " , conn - > getDebugID ( ) ) . suppressFor ( 1 . 0 ) <nl> + . detail ( " FromAddress " , conn - > getPeerAddress ( ) ) <nl> + . detail ( " ListenAddress " , listenAddr . toString ( ) ) ; <nl> + incoming . add ( connectionIncoming ( self , conn ) ) ; <nl> + } <nl> + wait ( delay ( 0 , TaskPriority : : AcceptSocket ) ) ; <nl> } <nl> } catch ( Error & e ) { <nl> TraceEvent ( SevError , " ListenError " ) . error ( e ) ; <nl> void FlowTransport : : addPeerReference ( const Endpoint & endpoint , bool isStream ) { <nl> return ; <nl> <nl> Reference < Peer > peer = self - > getOrOpenPeer ( endpoint . getPrimaryAddress ( ) ) ; <nl> - <nl> + <nl> if ( peer - > peerReferences = = - 1 ) { <nl> IFailureMonitor : : failureMonitor ( ) . setStatus ( endpoint . getPrimaryAddress ( ) , FailureStatus ( false ) ) ; <nl> peer - > peerReferences = 1 ; <nl> void FlowTransport : : removePeerReference ( const Endpoint & endpoint , bool isStream ) <nl> . detail ( " Address " , endpoint . getPrimaryAddress ( ) ) <nl> . detail ( " Token " , endpoint . token ) ; <nl> } <nl> - if ( peer - > peerReferences = = 0 & & peer - > reliable . empty ( ) & & peer - > unsent . empty ( ) & & peer - > outstandingReplies = = 0 ) { <nl> + if ( peer - > peerReferences = = 0 & & peer - > reliable . empty ( ) & & peer - > unsent . empty ( ) & & peer - > outstandingReplies = = 0 & & peer - > lastDataPacketSentTime < now ( ) - FLOW_KNOBS - > CONNECTION_MONITOR_UNREFERENCED_CLOSE_DELAY ) { <nl> peer - > resetPing . trigger ( ) ; <nl> } <nl> } <nl> static void sendLocal ( TransportData * self , ISerializeSource const & what , const <nl> / / SOMEDAY : Would it be better to avoid ( de ) serialization by doing this check in flow ? <nl> <nl> Standalone < StringRef > copy ; <nl> - if ( FLOW_KNOBS - > USE_OBJECT_SERIALIZER ) { <nl> - ObjectWriter wr ( AssumeVersion ( currentProtocolVersion ) ) ; <nl> - what . serializeObjectWriter ( wr ) ; <nl> - copy = wr . toStringRef ( ) ; <nl> - } else { <nl> - BinaryWriter wr ( AssumeVersion ( currentProtocolVersion ) ) ; <nl> - what . serializeBinaryWriter ( wr ) ; <nl> - copy = wr . toValue ( ) ; <nl> - } <nl> + ObjectWriter wr ( AssumeVersion ( currentProtocolVersion ) ) ; <nl> + what . serializeObjectWriter ( wr ) ; <nl> + copy = wr . toStringRef ( ) ; <nl> # if VALGRIND <nl> VALGRIND_CHECK_MEM_IS_DEFINED ( copy . begin ( ) , copy . size ( ) ) ; <nl> # endif <nl> static ReliablePacket * sendPacket ( TransportData * self , Reference < Peer > peer , IS <nl> <nl> wr . writeAhead ( packetInfoSize , & packetInfoBuffer ) ; <nl> wr < < destination . token ; <nl> - what . serializePacketWriter ( wr , FLOW_KNOBS - > USE_OBJECT_SERIALIZER ) ; <nl> + what . serializePacketWriter ( wr ) ; <nl> pb = wr . finish ( ) ; <nl> len = wr . size ( ) - packetInfoSize ; <nl> <nl> mmm a / fdbrpc / FlowTransport . h <nl> ppp b / fdbrpc / FlowTransport . h <nl> class Endpoint { <nl> class ArenaObjectReader ; <nl> class NetworkMessageReceiver { <nl> public : <nl> - virtual void receive ( ArenaReader & ) = 0 ; <nl> virtual void receive ( ArenaObjectReader & ) = 0 ; <nl> virtual bool isStream ( ) const { return false ; } <nl> } ; <nl> deleted file mode 100644 <nl> index 4ceeb6414d . . 0000000000 <nl> mmm a / fdbrpc / ITLSPlugin . h <nl> ppp / dev / null <nl> <nl> - / * <nl> - * ITLSPlugin . h <nl> - * <nl> - * This source file is part of the FoundationDB open source project <nl> - * <nl> - * Copyright 2013 - 2018 Apple Inc . and the FoundationDB project authors <nl> - * <nl> - * Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> - * you may not use this file except in compliance with the License . <nl> - * You may obtain a copy of the License at <nl> - * <nl> - * http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> - * <nl> - * Unless required by applicable law or agreed to in writing , software <nl> - * distributed under the License is distributed on an " AS IS " BASIS , <nl> - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> - * See the License for the specific language governing permissions and <nl> - * limitations under the License . <nl> - * / <nl> - <nl> - # ifndef FDB_ITLSPLUGIN_H <nl> - # define FDB_ITLSPLUGIN_H <nl> - <nl> - # pragma once <nl> - <nl> - # include < stdint . h > <nl> - <nl> - struct ITLSSession { <nl> - enum { SUCCESS = 0 , WANT_READ = - 1 , WANT_WRITE = - 2 , FAILED = - 3 } ; <nl> - <nl> - virtual void addref ( ) = 0 ; <nl> - virtual void delref ( ) = 0 ; <nl> - <nl> - / / handshake should return SUCCESS if the handshake is complete , <nl> - / / FAILED on fatal error , or one of WANT_READ or WANT_WRITE if the <nl> - / / handshake should be reattempted after more data can be <nl> - / / read / written on the underlying connection . <nl> - virtual int handshake ( ) = 0 ; <nl> - <nl> - / / read should return the ( non - zero ) number of bytes read , <nl> - / / WANT_READ or WANT_WRITE if the operation is blocked by the <nl> - / / underlying stream , or FAILED if there is an error ( including a <nl> - / / closed connection ) . <nl> - virtual int read ( uint8_t * data , int length ) = 0 ; <nl> - <nl> - / / write should return the ( non - zero ) number of bytes written , or <nl> - / / WANT_READ or WANT_WRITE if the operation is blocked by the <nl> - / / underlying stream , or FAILED if there is an error . <nl> - virtual int write ( const uint8_t * data , int length ) = 0 ; <nl> - } ; <nl> - <nl> - / / Returns the number of bytes sent ( possibly 0 ) , or - 1 on error <nl> - / / ( including connection close ) <nl> - typedef int ( * TLSSendCallbackFunc ) ( void * ctx , const uint8_t * buf , int len ) ; <nl> - <nl> - / / Returns the number of bytes read ( possibly 0 ) , or - 1 on error <nl> - / / ( including connection close ) <nl> - typedef int ( * TLSRecvCallbackFunc ) ( void * ctx , uint8_t * buf , int len ) ; <nl> - <nl> - struct ITLSPolicy { <nl> - virtual void addref ( ) = 0 ; <nl> - virtual void delref ( ) = 0 ; <nl> - <nl> - / / set_ca_data should import the provided certificate list and <nl> - / / associate it with this policy . cert_data will point to a PEM <nl> - / / encoded certificate list of trust roots . <nl> - / / <nl> - / / set_ca_data should return true if the operation succeeded , <nl> - / / and false otherwise . After the first call to create_session for <nl> - / / a given policy , set_ca_data should immediately return false <nl> - / / if called . <nl> - virtual bool set_ca_data ( const uint8_t * ca_data , int ca_len ) = 0 ; <nl> - <nl> - / / set_cert_data should import the provided certificate list and <nl> - / / associate it with this policy . cert_data will point to a PEM <nl> - / / encoded certificate list , ordered such that each certificate <nl> - / / certifies the one before it . <nl> - / / <nl> - / / cert_data may additionally contain key information , which must <nl> - / / be ignored . <nl> - / / <nl> - / / set_cert_data should return true if the operation succeeded , <nl> - / / and false otherwise . After the first call to create_session for <nl> - / / a given policy , set_cert_data should immediately return false <nl> - / / if called . <nl> - virtual bool set_cert_data ( const uint8_t * cert_data , int cert_len ) = 0 ; <nl> - <nl> - / / set_key_data should import the provided private key and <nl> - / / associate it with this policy . key_data will point to a PEM <nl> - / / encoded key , which may be encrypted . If encrypted the password <nl> - / / argument should be specified , otherwise it may be NULL . <nl> - / / <nl> - / / key_data may additionally contain certificate information , <nl> - / / which must be ignored . <nl> - / / <nl> - / / set_key_data should return true if the operation succeeded , and <nl> - / / false otherwise . After the first call to create_session for a <nl> - / / given policy , set_key_data should immediately return false if <nl> - / / called . <nl> - virtual bool set_key_data ( const uint8_t * key_data , int key_len , const char * password ) = 0 ; <nl> - <nl> - / / set_verify_peers should modify the validation rules for <nl> - / / verifying a peer during connection handshake . The format of <nl> - / / verify_peers is implementation specific . <nl> - / / <nl> - / / set_verify_peers should return true if the operation succeed , <nl> - / / and false otherwise . After the first call to create_session for <nl> - / / a given policy , set_verify_peers should immediately return <nl> - / / false if called . <nl> - virtual bool set_verify_peers ( int count , const uint8_t * verify_peers [ ] , int verify_peers_len [ ] ) = 0 ; <nl> - <nl> - / / create_session should return a new object that implements <nl> - / / ITLSSession , associated with this policy . After the first call <nl> - / / to create_session for a given policy , further calls to <nl> - / / ITLSPolicy : : set_ * will fail and return false . <nl> - / / <nl> - / / The newly created session should use send_func and recv_func to <nl> - / / send and receive data on the underlying transport , and must <nl> - / / provide send_ctx / recv_ctx to the callbacks . <nl> - / / <nl> - / / uid will be used to identify this session within trace events <nl> - virtual ITLSSession * create_session ( bool is_client , const char * servername , TLSSendCallbackFunc send_func , void * send_ctx , TLSRecvCallbackFunc recv_func , void * recv_ctx , void * uid ) = 0 ; <nl> - } ; <nl> - <nl> - struct ITLSPlugin { <nl> - virtual void addref ( ) = 0 ; <nl> - virtual void delref ( ) = 0 ; <nl> - <nl> - / / create_policy should return a new object that implements <nl> - / / ITLSPolicy . <nl> - virtual ITLSPolicy * create_policy ( ) = 0 ; <nl> - <nl> - static inline const char * get_plugin_type_name_and_version ( ) { return " ITLSPlugin " ; } <nl> - } ; <nl> - <nl> - # endif / * FDB_ITLSPLUGIN_H * / <nl> mmm a / fdbrpc / LoadPlugin . h <nl> ppp b / fdbrpc / LoadPlugin . h <nl> <nl> * limitations under the License . <nl> * / <nl> <nl> - # pragma once <nl> + # ifndef _FLOW_LOADPLUGIN_H_ <nl> + # define _FLOW_LOADPLUGIN_H_ <nl> <nl> - / / Specialized TLS plugin library <nl> - extern " C " void * get_tls_plugin ( const char * plugin_type_name_and_version ) ; <nl> + # pragma once <nl> <nl> - / / Name of specialized TLS Plugin <nl> - extern const char * tlsPluginName ; <nl> + # include < string > <nl> + # include " flow / flow . h " <nl> <nl> template < class T > <nl> Reference < T > loadPlugin ( std : : string const & plugin_name ) { <nl> void * ( * get_plugin ) ( const char * ) = NULL ; <nl> - # ifndef TLS_DISABLED <nl> - if ( ! plugin_name . compare ( tlsPluginName ) ) { <nl> - get_plugin = ( void * ( * ) ( const char * ) ) get_tls_plugin ; <nl> - } <nl> - else <nl> - # endif <nl> - { <nl> - void * plugin = loadLibrary ( plugin_name . c_str ( ) ) ; <nl> - if ( plugin ) <nl> - get_plugin = ( void * ( * ) ( const char * ) ) loadFunction ( plugin , " get_plugin " ) ; <nl> - } <nl> + void * plugin = loadLibrary ( plugin_name . c_str ( ) ) ; <nl> + if ( plugin ) <nl> + get_plugin = ( void * ( * ) ( const char * ) ) loadFunction ( plugin , " get_plugin " ) ; <nl> return ( get_plugin ) ? Reference < T > ( ( T * ) get_plugin ( T : : get_plugin_type_name_and_version ( ) ) ) : Reference < T > ( NULL ) ; <nl> } <nl> + <nl> + # endif <nl> mmm a / fdbrpc / Locality . h <nl> ppp b / fdbrpc / Locality . h <nl> struct ProcessClass { <nl> else if ( s = = " log " ) _class = LogClass ; <nl> else if ( s = = " router " ) _class = LogRouterClass ; <nl> else if ( s = = " cluster_controller " ) _class = ClusterControllerClass ; <nl> - else if ( s = = " fast_restore " ) _class = FastRestoreClass ; <nl> + else if ( s = = " fast_restore " ) _class = FastRestoreClass ; <nl> else if ( s = = " data_distributor " ) _class = DataDistributorClass ; <nl> else if ( s = = " coordinator " ) _class = CoordinatorClass ; <nl> else if ( s = = " ratekeeper " ) _class = RatekeeperClass ; <nl> mmm a / fdbrpc / Replication . h <nl> ppp b / fdbrpc / Replication . h <nl> struct LocalitySet : public ReferenceCounted < LocalitySet > { <nl> std : : vector < LocalityEntry > const & getEntries ( ) const <nl> { return _entryArray ; } <nl> <nl> - std : : vector < LocalityEntry > const & getMutableEntries ( ) const <nl> - { return _mutableEntryArray ; } <nl> + std : : vector < LocalityEntry > & getMutableEntries ( ) { return _mutableEntryArray ; } <nl> <nl> std : : vector < LocalityEntry > const & getGroupEntries ( ) const <nl> { return _localitygroup - > _entryArray ; } <nl> struct LocalitySet : public ReferenceCounted < LocalitySet > { <nl> <nl> while ( nRandomItems > 0 ) <nl> { <nl> - if ( nItemsLeft < = 0 ) { <nl> + if ( nRandomItems > nItemsLeft | | nItemsLeft < = 0 ) { <nl> bComplete = false ; <nl> break ; <nl> } <nl> struct LocalitySet : public ReferenceCounted < LocalitySet > { <nl> <nl> Reference < StringToIntMap > _keymap ; <nl> <nl> + virtual std : : vector < std : : vector < AttribValue > > const & getKeyValueArray ( ) const { return _keyValueArray ; } <nl> + <nl> protected : <nl> virtual Reference < StringToIntMap > & getGroupValueMap ( ) <nl> { return _localitygroup - > getGroupValueMap ( ) ; } <nl> mmm a / fdbrpc / ReplicationPolicy . h <nl> ppp b / fdbrpc / ReplicationPolicy . h <nl> struct PolicyAcross : IReplicationPolicy , public ReferenceCounted < PolicyAcross > <nl> explicit PolicyAcross ( const PolicyAcross & other ) : PolicyAcross ( other . _count , other . _attribKey , other . _policy ) { } <nl> virtual ~ PolicyAcross ( ) ; <nl> virtual std : : string name ( ) const { return " Across " ; } <nl> + std : : string embeddedPolicyName ( ) const { return _policy - > name ( ) ; } <nl> + int getCount ( ) const { return _count ; } <nl> virtual std : : string info ( ) const { return format ( " % s ^ % d x " , _attribKey . c_str ( ) , _count ) + _policy - > info ( ) ; } <nl> virtual int maxResults ( ) const { return _count * _policy - > maxResults ( ) ; } <nl> virtual int depth ( ) const { return 1 + _policy - > depth ( ) ; } <nl> mmm a / fdbrpc / ReplicationUtils . cpp <nl> ppp b / fdbrpc / ReplicationUtils . cpp <nl> double ratePolicy ( <nl> return rating ; <nl> } <nl> <nl> - bool findBestPolicySet ( <nl> - std : : vector < LocalityEntry > & bestResults , <nl> - Reference < LocalitySet > & localitySet , <nl> - Reference < IReplicationPolicy > const & policy , <nl> - unsigned int nMinItems , <nl> - unsigned int nSelectTests , <nl> - unsigned int nPolicyTests ) <nl> - { <nl> + int mostUsedZoneCount ( Reference < LocalitySet > & logServerSet , std : : vector < LocalityEntry > & bestSet ) { <nl> + AttribKey indexKey = logServerSet - > keyIndex ( " zoneid " ) ; <nl> + std : : map < AttribValue , int > entries ; <nl> + for ( int i = 0 ; i < bestSet . size ( ) ; i + + ) { <nl> + Optional < AttribValue > value = logServerSet - > getRecordViaEntry ( bestSet [ i ] ) - > getValue ( indexKey ) ; <nl> + entries [ value . get ( ) ] + + ; <nl> + } <nl> + int maxEntries = 0 ; <nl> + for ( auto it : entries ) { <nl> + maxEntries = std : : max ( maxEntries , it . second ) ; <nl> + } <nl> + return maxEntries ; <nl> + } <nl> + <nl> + bool findBestPolicySetSimple ( int targetUniqueValueCount , Reference < LocalitySet > & logServerSet , std : : vector < LocalityEntry > & bestSet , <nl> + int desired ) { <nl> + auto & mutableEntries = logServerSet - > getMutableEntries ( ) ; <nl> + deterministicRandom ( ) - > randomShuffle ( mutableEntries ) ; <nl> + / / First make sure the current localitySet is able to fulfuill the policy <nl> + AttribKey indexKey = logServerSet - > keyIndex ( " zoneid " ) ; <nl> + int uniqueValueCount = logServerSet - > getKeyValueArray ( ) [ indexKey . _id ] . size ( ) ; <nl> + <nl> + if ( uniqueValueCount < targetUniqueValueCount ) { <nl> + / / logServerSet won ' t be able to fulfill the policy <nl> + return false ; <nl> + } <nl> + <nl> + std : : map < AttribValue , std : : vector < int > > entries ; <nl> + for ( int i = 0 ; i < mutableEntries . size ( ) ; i + + ) { <nl> + Optional < AttribValue > value = logServerSet - > getRecord ( mutableEntries [ i ] . _id ) - > getValue ( indexKey ) ; <nl> + if ( value . present ( ) ) { <nl> + entries [ value . get ( ) ] . push_back ( i ) ; <nl> + } <nl> + } <nl> + <nl> + ASSERT_WE_THINK ( uniqueValueCount = = entries . size ( ) ) ; <nl> + <nl> + desired = std : : max ( desired , targetUniqueValueCount ) ; <nl> + auto it = entries . begin ( ) ; <nl> + while ( bestSet . size ( ) < desired ) { <nl> + if ( it - > second . size ( ) ) { <nl> + bestSet . push_back ( mutableEntries [ it - > second . back ( ) ] ) ; <nl> + it - > second . pop_back ( ) ; <nl> + } <nl> + <nl> + + + it ; <nl> + if ( it = = entries . end ( ) ) { <nl> + it = entries . begin ( ) ; <nl> + } <nl> + } <nl> + <nl> + return true ; <nl> + } <nl> + <nl> + bool findBestPolicySetExpensive ( std : : vector < LocalityEntry > & bestResults , Reference < LocalitySet > & localitySet , <nl> + Reference < IReplicationPolicy > const & policy , unsigned int nMinItems , <nl> + unsigned int nSelectTests , unsigned int nPolicyTests ) { <nl> bool bSucceeded = true ; <nl> Reference < LocalitySet > bestLocalitySet , testLocalitySet ; <nl> std : : vector < LocalityEntry > results ; <nl> bool findBestPolicySet ( <nl> } <nl> <nl> / / Get some additional random items , if needed <nl> - if ( ( nMinItems > results . size ( ) ) & & <nl> - ( ! localitySet - > random ( results , results , nMinItems - results . size ( ) ) ) ) <nl> - { <nl> + if ( ( nMinItems > results . size ( ) ) & & ( ! localitySet - > random ( results , results , nMinItems - results . size ( ) ) ) ) { <nl> bSucceeded = false ; <nl> break ; <nl> } <nl> bool findBestPolicySet ( <nl> return bSucceeded ; <nl> } <nl> <nl> + bool findBestPolicySet ( std : : vector < LocalityEntry > & bestResults , Reference < LocalitySet > & localitySet , <nl> + Reference < IReplicationPolicy > const & policy , unsigned int nMinItems , unsigned int nSelectTests , <nl> + unsigned int nPolicyTests ) { <nl> + <nl> + bool bestFound = false ; <nl> + <nl> + / / Specialization for policies of shape : <nl> + / / - PolicyOne ( ) <nl> + / / - PolicyAcross ( , " zoneId " , PolicyOne ( ) ) <nl> + / / - TODO : More specializations for common policies <nl> + if ( policy - > name ( ) = = " One " ) { <nl> + bestFound = true ; <nl> + int count = 0 ; <nl> + auto & mutableEntries = localitySet - > getMutableEntries ( ) ; <nl> + deterministicRandom ( ) - > randomShuffle ( mutableEntries ) ; <nl> + for ( auto const & entry : mutableEntries ) { <nl> + bestResults . push_back ( entry ) ; <nl> + if ( + + count = = nMinItems ) break ; <nl> + } <nl> + } else if ( policy - > name ( ) = = " Across " ) { <nl> + PolicyAcross * pa = ( PolicyAcross * ) policy . getPtr ( ) ; <nl> + std : : set < std : : string > attributeKeys ; <nl> + pa - > attributeKeys ( & attributeKeys ) ; <nl> + if ( pa - > embeddedPolicyName ( ) = = " One " & & attributeKeys . size ( ) = = 1 & & <nl> + * attributeKeys . begin ( ) = = " zoneid " / / This algorithm can actually apply to any field <nl> + ) { <nl> + bestFound = findBestPolicySetSimple ( pa - > getCount ( ) , localitySet , bestResults , nMinItems ) ; <nl> + if ( bestFound & & g_network - > isSimulated ( ) ) { <nl> + std : : vector < LocalityEntry > oldBest ; <nl> + auto oldBestFound = <nl> + findBestPolicySetExpensive ( oldBest , localitySet , policy , nMinItems , nSelectTests , nPolicyTests ) ; <nl> + if ( ! oldBestFound ) { <nl> + TraceEvent ( SevError , " FBPSMissmatch " ) . detail ( " Policy " , policy - > info ( ) ) ; <nl> + } else { <nl> + ASSERT ( mostUsedZoneCount ( localitySet , bestResults ) < = mostUsedZoneCount ( localitySet , oldBest ) ) ; <nl> + } <nl> + } <nl> + } else { <nl> + bestFound = <nl> + findBestPolicySetExpensive ( bestResults , localitySet , policy , nMinItems , nSelectTests , nPolicyTests ) ; <nl> + } <nl> + } else { <nl> + bestFound = findBestPolicySetExpensive ( bestResults , localitySet , policy , nMinItems , nSelectTests , nPolicyTests ) ; <nl> + } <nl> + return bestFound ; <nl> + } <nl> + <nl> bool findBestUniquePolicySet ( <nl> std : : vector < LocalityEntry > & bestResults , <nl> Reference < LocalitySet > & localitySet , <nl> deleted file mode 100644 <nl> index 7f0f65a1de . . 0000000000 <nl> mmm a / fdbrpc / TLSConnection . actor . cpp <nl> ppp / dev / null <nl> <nl> - / * <nl> - * TLSConnection . actor . cpp <nl> - * <nl> - * This source file is part of the FoundationDB open source project <nl> - * <nl> - * Copyright 2013 - 2018 Apple Inc . and the FoundationDB project authors <nl> - * <nl> - * Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> - * you may not use this file except in compliance with the License . <nl> - * You may obtain a copy of the License at <nl> - * <nl> - * http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> - * <nl> - * Unless required by applicable law or agreed to in writing , software <nl> - * distributed under the License is distributed on an " AS IS " BASIS , <nl> - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> - * See the License for the specific language governing permissions and <nl> - * limitations under the License . <nl> - * / <nl> - <nl> - # include < memory > <nl> - # include " flow / flow . h " <nl> - # include " flow / network . h " <nl> - # include " flow / Knobs . h " <nl> - # include " fdbrpc / TLSConnection . h " <nl> - # include " fdbrpc / ITLSPlugin . h " <nl> - # include " fdbrpc / LoadPlugin . h " <nl> - # include " fdbrpc / Platform . h " <nl> - # include " fdbrpc / IAsyncFile . h " <nl> - # include " flow / actorcompiler . h " / / This must be the last # include . <nl> - <nl> - / / Name of specialized TLS Plugin <nl> - const char * tlsPluginName = " fdb - libressl - plugin " ; <nl> - <nl> - / / Must not throw an exception from this function ! <nl> - static int send_func ( void * ctx , const uint8_t * buf , int len ) { <nl> - TLSConnection * conn = ( TLSConnection * ) ctx ; <nl> - <nl> - try { <nl> - SendBuffer sb ; <nl> - sb . bytes_sent = 0 ; <nl> - sb . bytes_written = len ; <nl> - sb . data = buf ; <nl> - sb . next = 0 ; <nl> - <nl> - int w = conn - > conn - > write ( & sb ) ; <nl> - return w ; <nl> - } catch ( Error & e ) { <nl> - TraceEvent ( " TLSConnectionSendError " , conn - > getDebugID ( ) ) . suppressFor ( 1 . 0 ) . detail ( " Peer " , conn - > getPeerAddress ( ) . toString ( ) ) . error ( e ) ; <nl> - return - 1 ; <nl> - } catch ( . . . ) { <nl> - TraceEvent ( " TLSConnectionSendError " , conn - > getDebugID ( ) ) . suppressFor ( 1 . 0 ) . detail ( " Peer " , conn - > getPeerAddress ( ) ) . error ( unknown_error ( ) ) ; <nl> - return - 1 ; <nl> - } <nl> - } <nl> - <nl> - / / Must not throw an exception from this function ! <nl> - static int recv_func ( void * ctx , uint8_t * buf , int len ) { <nl> - TLSConnection * conn = ( TLSConnection * ) ctx ; <nl> - <nl> - try { <nl> - int r = conn - > conn - > read ( buf , buf + len ) ; <nl> - return r ; <nl> - } catch ( Error & e ) { <nl> - TraceEvent ( " TLSConnectionRecvError " , conn - > getDebugID ( ) ) . suppressFor ( 1 . 0 ) . detail ( " Peer " , conn - > getPeerAddress ( ) ) . error ( e ) ; <nl> - return - 1 ; <nl> - } catch ( . . . ) { <nl> - TraceEvent ( " TLSConnectionRecvError " , conn - > getDebugID ( ) ) . suppressFor ( 1 . 0 ) . detail ( " Peer " , conn - > getPeerAddress ( ) ) . error ( unknown_error ( ) ) ; <nl> - return - 1 ; <nl> - } <nl> - } <nl> - <nl> - ACTOR static Future < Void > handshake ( TLSConnection * self ) { <nl> - state std : : pair < IPAddress , uint16_t > peerIP = std : : make_pair ( self - > conn - > getPeerAddress ( ) . ip , self - > is_client ? self - > conn - > getPeerAddress ( ) . port : static_cast < uint16_t > ( 0 ) ) ; <nl> - if ( ! self - > is_client ) { <nl> - auto iter ( g_network - > networkInfo . serverTLSConnectionThrottler . find ( peerIP ) ) ; <nl> - if ( iter ! = g_network - > networkInfo . serverTLSConnectionThrottler . end ( ) ) { <nl> - if ( now ( ) < iter - > second . second ) { <nl> - if ( iter - > second . first > = FLOW_KNOBS - > TLS_SERVER_CONNECTION_THROTTLE_ATTEMPTS ) { <nl> - TraceEvent ( " TLSIncomingConnectionThrottlingWarning " , self - > getDebugID ( ) ) . suppressFor ( 1 . 0 ) . detail ( " PeerIP " , peerIP . first . toString ( ) ) ; <nl> - wait ( delay ( FLOW_KNOBS - > CONNECTION_MONITOR_TIMEOUT ) ) ; <nl> - throw connection_failed ( ) ; <nl> - } <nl> - } else { <nl> - g_network - > networkInfo . serverTLSConnectionThrottler . erase ( peerIP ) ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - loop { <nl> - int r = self - > session - > handshake ( ) ; <nl> - if ( BUGGIFY_WITH_PROB ( 0 . 001 ) ) { <nl> - r = ITLSSession : : FAILED ; <nl> - } <nl> - if ( r = = ITLSSession : : SUCCESS ) break ; <nl> - if ( r = = ITLSSession : : FAILED ) { <nl> - TraceEvent ( " TLSConnectionHandshakeError " , self - > getDebugID ( ) ) . suppressFor ( 1 . 0 ) . detail ( " Peer " , self - > getPeerAddress ( ) ) ; <nl> - auto iter ( g_network - > networkInfo . serverTLSConnectionThrottler . find ( peerIP ) ) ; <nl> - if ( iter ! = g_network - > networkInfo . serverTLSConnectionThrottler . end ( ) ) { <nl> - iter - > second . first + + ; <nl> - } else { <nl> - g_network - > networkInfo . serverTLSConnectionThrottler [ peerIP ] = std : : make_pair ( 0 , now ( ) + ( self - > is_client ? FLOW_KNOBS - > TLS_CLIENT_CONNECTION_THROTTLE_TIMEOUT : FLOW_KNOBS - > TLS_SERVER_CONNECTION_THROTTLE_TIMEOUT ) ) ; <nl> - } <nl> - throw connection_failed ( ) ; <nl> - } <nl> - ASSERT ( r = = ITLSSession : : WANT_WRITE | | r = = ITLSSession : : WANT_READ ) ; <nl> - wait ( r = = ITLSSession : : WANT_WRITE ? self - > conn - > onWritable ( ) : self - > conn - > onReadable ( ) ) ; <nl> - } <nl> - <nl> - TraceEvent ( " TLSConnectionHandshakeSuccessful " , self - > getDebugID ( ) ) . suppressFor ( 1 . 0 ) . detail ( " Peer " , self - > getPeerAddress ( ) ) ; <nl> - <nl> - return Void ( ) ; <nl> - } <nl> - <nl> - TLSConnection : : TLSConnection ( Reference < IConnection > const & conn , Reference < ITLSPolicy > const & policy , bool is_client , std : : string host ) : conn ( conn ) , write_wants ( 0 ) , read_wants ( 0 ) , uid ( conn - > getDebugID ( ) ) , is_client ( is_client ) { <nl> - const char * serverName = host . empty ( ) ? NULL : host . c_str ( ) ; <nl> - session = Reference < ITLSSession > ( policy - > create_session ( is_client , serverName , send_func , this , recv_func , this , ( void * ) & uid ) ) ; <nl> - if ( ! session ) { <nl> - / / If session is NULL , we ' re trusting policy - > create_session <nl> - / / to have used its provided logging function to have logged <nl> - / / the error <nl> - throw tls_error ( ) ; <nl> - } <nl> - handshook = handshake ( this ) ; <nl> - } <nl> - <nl> - Future < Void > TLSConnection : : onWritable ( ) { <nl> - if ( ! handshook . isReady ( ) ) <nl> - return handshook ; <nl> - return <nl> - write_wants = = ITLSSession : : WANT_READ ? conn - > onReadable ( ) : <nl> - write_wants = = ITLSSession : : WANT_WRITE ? conn - > onWritable ( ) : <nl> - Void ( ) ; <nl> - } <nl> - <nl> - Future < Void > TLSConnection : : onReadable ( ) { <nl> - if ( ! handshook . isReady ( ) ) <nl> - return handshook ; <nl> - return <nl> - read_wants = = ITLSSession : : WANT_READ ? conn - > onReadable ( ) : <nl> - read_wants = = ITLSSession : : WANT_WRITE ? conn - > onWritable ( ) : <nl> - Void ( ) ; <nl> - } <nl> - <nl> - int TLSConnection : : read ( uint8_t * begin , uint8_t * end ) { <nl> - if ( ! handshook . isReady ( ) ) return 0 ; <nl> - handshook . get ( ) ; <nl> - <nl> - read_wants = 0 ; <nl> - int r = session - > read ( begin , end - begin ) ; <nl> - if ( r > 0 ) <nl> - return r ; <nl> - <nl> - if ( r = = ITLSSession : : FAILED ) throw connection_failed ( ) ; <nl> - <nl> - ASSERT ( r = = ITLSSession : : WANT_WRITE | | r = = ITLSSession : : WANT_READ ) ; <nl> - <nl> - read_wants = r ; <nl> - return 0 ; <nl> - } <nl> - <nl> - int TLSConnection : : write ( SendBuffer const * buffer , int limit ) { <nl> - ASSERT ( limit > 0 ) ; <nl> - <nl> - if ( ! handshook . isReady ( ) ) return 0 ; <nl> - handshook . get ( ) ; <nl> - <nl> - write_wants = 0 ; <nl> - int toSend = std : : min ( limit , buffer - > bytes_written - buffer - > bytes_sent ) ; <nl> - ASSERT ( toSend ) ; <nl> - int w = session - > write ( buffer - > data + buffer - > bytes_sent , toSend ) ; <nl> - if ( w > 0 ) <nl> - return w ; <nl> - <nl> - if ( w = = ITLSSession : : FAILED ) throw connection_failed ( ) ; <nl> - <nl> - ASSERT ( w = = ITLSSession : : WANT_WRITE | | w = = ITLSSession : : WANT_READ ) ; <nl> - <nl> - write_wants = w ; <nl> - return 0 ; <nl> - } <nl> - <nl> - ACTOR Future < Reference < IConnection > > wrap ( Reference < ITLSPolicy > policy , bool is_client , Future < Reference < IConnection > > c , std : : string host ) { <nl> - state Reference < IConnection > conn = wait ( c ) ; <nl> - try { <nl> - state Reference < TLSConnection > tlsConn ( new TLSConnection ( conn , policy , is_client , host ) ) ; <nl> - if ( is_client ) { <nl> - wait ( tlsConn - > handshook ) ; <nl> - } <nl> - return tlsConn ; <nl> - } catch ( Error & e ) { <nl> - conn - > close ( ) ; <nl> - throw e ; <nl> - } <nl> - } <nl> - <nl> - Future < Reference < IConnection > > TLSListener : : accept ( ) { <nl> - return wrap ( options - > get_policy ( TLSOptions : : POLICY_VERIFY_PEERS ) , false , listener - > accept ( ) , " " ) ; <nl> - } <nl> - <nl> - TLSNetworkConnections : : TLSNetworkConnections ( Reference < TLSOptions > options ) : options ( options ) { <nl> - network = INetworkConnections : : net ( ) ; <nl> - g_network - > setGlobal ( INetwork : : enumGlobal : : enNetworkConnections , ( flowGlobalType ) this ) ; <nl> - } <nl> - <nl> - ACTOR Future < Reference < IConnection > > waitAndFailConnection ( ) { <nl> - wait ( delay ( FLOW_KNOBS - > CONNECTION_MONITOR_TIMEOUT ) ) ; <nl> - throw connection_failed ( ) ; <nl> - } <nl> - <nl> - Future < Reference < IConnection > > TLSNetworkConnections : : connect ( NetworkAddress toAddr , std : : string host ) { <nl> - if ( toAddr . isTLS ( ) ) { <nl> - NetworkAddress clearAddr ( toAddr . ip , toAddr . port , toAddr . isPublic ( ) , false ) ; <nl> - std : : pair < IPAddress , uint16_t > peerIP = std : : make_pair ( toAddr . ip , toAddr . port ) ; <nl> - auto iter ( g_network - > networkInfo . serverTLSConnectionThrottler . find ( peerIP ) ) ; <nl> - if ( iter ! = g_network - > networkInfo . serverTLSConnectionThrottler . end ( ) ) { <nl> - if ( now ( ) < iter - > second . second ) { <nl> - if ( iter - > second . first > = FLOW_KNOBS - > TLS_CLIENT_CONNECTION_THROTTLE_ATTEMPTS ) { <nl> - TraceEvent ( " TLSOutgoingConnectionThrottlingWarning " ) . suppressFor ( 1 . 0 ) . detail ( " PeerIP " , toAddr ) ; <nl> - return waitAndFailConnection ( ) ; <nl> - } <nl> - } else { <nl> - g_network - > networkInfo . serverTLSConnectionThrottler . erase ( peerIP ) ; <nl> - } <nl> - } <nl> - <nl> - TraceEvent ( " TLSConnectionConnecting " ) . suppressFor ( 1 . 0 ) . detail ( " ToAddr " , toAddr ) ; <nl> - / / For FDB < - > FDB connections , we don ' t have hostnames and can ' t verify IP <nl> - / / addresses against certificates , so we have our own peer verifying logic <nl> - / / to use . For FDB < - > external system connections , we can use the standard <nl> - / / hostname - based certificate verification logic . <nl> - if ( host . empty ( ) | | host = = toAddr . ip . toString ( ) ) <nl> - return wrap ( options - > get_policy ( TLSOptions : : POLICY_VERIFY_PEERS ) , true , network - > connect ( clearAddr ) , std : : string ( " " ) ) ; <nl> - else <nl> - return wrap ( options - > get_policy ( TLSOptions : : POLICY_NO_VERIFY_PEERS ) , true , network - > connect ( clearAddr ) , host ) ; <nl> - } <nl> - return network - > connect ( toAddr ) ; <nl> - } <nl> - <nl> - Future < std : : vector < NetworkAddress > > TLSNetworkConnections : : resolveTCPEndpoint ( std : : string host , std : : string service ) { <nl> - return network - > resolveTCPEndpoint ( host , service ) ; <nl> - } <nl> - <nl> - Reference < IListener > TLSNetworkConnections : : listen ( NetworkAddress localAddr ) { <nl> - if ( localAddr . isTLS ( ) ) { <nl> - NetworkAddress clearAddr ( localAddr . ip , localAddr . port , localAddr . isPublic ( ) , false ) ; <nl> - TraceEvent ( " TLSConnectionListening " ) . detail ( " OnAddr " , localAddr ) ; <nl> - return Reference < IListener > ( new TLSListener ( options , network - > listen ( clearAddr ) ) ) ; <nl> - } <nl> - return network - > listen ( localAddr ) ; <nl> - } <nl> - <nl> - / / 5MB for loading files into memory <nl> - # define CERT_FILE_MAX_SIZE ( 5 * 1024 * 1024 ) <nl> - <nl> - void TLSOptions : : set_cert_file ( std : : string const & cert_file ) { <nl> - try { <nl> - TraceEvent ( " TLSConnectionSettingCertFile " ) . detail ( " CertFilePath " , cert_file ) ; <nl> - policyInfo . cert_path = cert_file ; <nl> - set_cert_data ( readFileBytes ( cert_file , CERT_FILE_MAX_SIZE ) ) ; <nl> - } catch ( Error & e ) { <nl> - TraceEvent ( SevError , " TLSOptionsSetCertFileError " ) . detail ( " Filename " , cert_file ) . error ( e ) . GetLastError ( ) ; <nl> - throw ; <nl> - } <nl> - } <nl> - <nl> - void TLSOptions : : set_ca_file ( std : : string const & ca_file ) { <nl> - try { <nl> - TraceEvent ( " TLSConnectionSettingCAFile " ) . detail ( " CAPath " , ca_file ) ; <nl> - policyInfo . ca_path = ca_file ; <nl> - set_ca_data ( readFileBytes ( ca_file , CERT_FILE_MAX_SIZE ) ) ; <nl> - } <nl> - catch ( Error & e ) { <nl> - TraceEvent ( SevError , " TLSOptionsSetCertAError " ) . detail ( " Filename " , ca_file ) . error ( e ) . GetLastError ( ) ; <nl> - throw ; <nl> - } <nl> - } <nl> - <nl> - void TLSOptions : : set_ca_data ( std : : string const & ca_data ) { <nl> - if ( ! policyVerifyPeersSet . get ( ) | | ! policyVerifyPeersNotSet . get ( ) ) <nl> - init_plugin ( ) ; <nl> - <nl> - TraceEvent ( " TLSConnectionSettingCAData " ) . detail ( " CADataSize " , ca_data . size ( ) ) ; <nl> - policyInfo . ca_contents = Standalone < StringRef > ( ca_data ) ; <nl> - if ( ! policyVerifyPeersSet . get ( ) - > set_ca_data ( ( const uint8_t * ) & ca_data [ 0 ] , ca_data . size ( ) ) ) <nl> - throw tls_error ( ) ; <nl> - if ( ! policyVerifyPeersNotSet . get ( ) - > set_ca_data ( ( const uint8_t * ) & ca_data [ 0 ] , ca_data . size ( ) ) ) <nl> - throw tls_error ( ) ; <nl> - <nl> - ca_set = true ; <nl> - } <nl> - <nl> - void TLSOptions : : set_cert_data ( std : : string const & cert_data ) { <nl> - if ( ! policyVerifyPeersSet . get ( ) | | ! policyVerifyPeersNotSet . get ( ) ) <nl> - init_plugin ( ) ; <nl> - <nl> - TraceEvent ( " TLSConnectionSettingCertData " ) . detail ( " CertDataSize " , cert_data . size ( ) ) ; <nl> - policyInfo . cert_contents = Standalone < StringRef > ( cert_data ) ; <nl> - if ( ! policyVerifyPeersSet . get ( ) - > set_cert_data ( ( const uint8_t * ) & cert_data [ 0 ] , cert_data . size ( ) ) ) <nl> - throw tls_error ( ) ; <nl> - if ( ! policyVerifyPeersNotSet . get ( ) - > set_cert_data ( ( const uint8_t * ) & cert_data [ 0 ] , cert_data . size ( ) ) ) <nl> - throw tls_error ( ) ; <nl> - <nl> - certs_set = true ; <nl> - } <nl> - <nl> - void TLSOptions : : set_key_password ( std : : string const & password ) { <nl> - TraceEvent ( " TLSConnectionSettingPassword " ) ; <nl> - policyInfo . keyPassword = password ; <nl> - } <nl> - <nl> - void TLSOptions : : set_key_file ( std : : string const & key_file ) { <nl> - try { <nl> - TraceEvent ( " TLSConnectionSettingKeyFile " ) . detail ( " KeyFilePath " , key_file ) ; <nl> - policyInfo . key_path = key_file ; <nl> - set_key_data ( readFileBytes ( key_file , CERT_FILE_MAX_SIZE ) ) ; <nl> - } catch ( Error & e ) { <nl> - TraceEvent ( SevError , " TLSOptionsSetKeyFileError " ) . detail ( " Filename " , key_file ) . error ( e ) . GetLastError ( ) ; <nl> - throw ; <nl> - } <nl> - } <nl> - <nl> - void TLSOptions : : set_key_data ( std : : string const & key_data ) { <nl> - if ( ! policyVerifyPeersSet . get ( ) | | ! policyVerifyPeersNotSet . get ( ) ) <nl> - init_plugin ( ) ; <nl> - const char * passphrase = policyInfo . keyPassword . empty ( ) ? NULL : policyInfo . keyPassword . c_str ( ) ; <nl> - TraceEvent ( " TLSConnectionSettingKeyData " ) . detail ( " KeyDataSize " , key_data . size ( ) ) ; <nl> - policyInfo . key_contents = Standalone < StringRef > ( key_data ) ; <nl> - if ( ! policyVerifyPeersSet . get ( ) - > set_key_data ( ( const uint8_t * ) & key_data [ 0 ] , key_data . size ( ) , passphrase ) ) <nl> - throw tls_error ( ) ; <nl> - if ( ! policyVerifyPeersNotSet . get ( ) - > set_key_data ( ( const uint8_t * ) & key_data [ 0 ] , key_data . size ( ) , passphrase ) ) <nl> - throw tls_error ( ) ; <nl> - <nl> - key_set = true ; <nl> - } <nl> - <nl> - void TLSOptions : : set_verify_peers ( std : : vector < std : : string > const & verify_peers ) { <nl> - if ( ! policyVerifyPeersSet . get ( ) ) <nl> - init_plugin ( ) ; <nl> - { <nl> - TraceEvent e ( " TLSConnectionSettingVerifyPeers " ) ; <nl> - for ( int i = 0 ; i < verify_peers . size ( ) ; i + + ) <nl> - e . detail ( std : : string ( " Value " + std : : to_string ( i ) ) . c_str ( ) , verify_peers [ i ] . c_str ( ) ) ; <nl> - } <nl> - std : : unique_ptr < const uint8_t * [ ] > verify_peers_arr ( new const uint8_t * [ verify_peers . size ( ) ] ) ; <nl> - std : : unique_ptr < int [ ] > verify_peers_len ( new int [ verify_peers . size ( ) ] ) ; <nl> - for ( int i = 0 ; i < verify_peers . size ( ) ; i + + ) { <nl> - verify_peers_arr [ i ] = ( const uint8_t * ) & verify_peers [ i ] [ 0 ] ; <nl> - verify_peers_len [ i ] = verify_peers [ i ] . size ( ) ; <nl> - } <nl> - <nl> - if ( ! policyVerifyPeersSet . get ( ) - > set_verify_peers ( verify_peers . size ( ) , verify_peers_arr . get ( ) , verify_peers_len . get ( ) ) ) <nl> - throw tls_error ( ) ; <nl> - <nl> - policyInfo . verify_peers = verify_peers ; <nl> - verify_peers_set = true ; <nl> - } <nl> - <nl> - void TLSOptions : : register_network ( ) { <nl> - / / Simulation relies upon being able to call this multiple times , and have it override g_network <nl> - / / each time it ' s called . <nl> - new TLSNetworkConnections ( Reference < TLSOptions > : : addRef ( this ) ) ; <nl> - } <nl> - <nl> - ACTOR static Future < ErrorOr < Standalone < StringRef > > > readEntireFile ( std : : string filename ) { <nl> - state Reference < IAsyncFile > file = wait ( IAsyncFileSystem : : filesystem ( ) - > open ( filename , IAsyncFile : : OPEN_READONLY | IAsyncFile : : OPEN_UNCACHED , 0 ) ) ; <nl> - state int64_t filesize = wait ( file - > size ( ) ) ; <nl> - state Standalone < StringRef > buf = makeString ( filesize ) ; <nl> - int rc = wait ( file - > read ( mutateString ( buf ) , filesize , 0 ) ) ; <nl> - if ( rc ! = filesize ) { <nl> - / / File modified during read , probably . The mtime should change , and thus we ' ll be called again . <nl> - return tls_error ( ) ; <nl> - } <nl> - return buf ; <nl> - } <nl> - <nl> - ACTOR static Future < Void > watchFileForChanges ( std : : string filename , AsyncVar < Standalone < StringRef > > * contents_var ) { <nl> - state std : : time_t lastModTime = wait ( IAsyncFileSystem : : filesystem ( ) - > lastWriteTime ( filename ) ) ; <nl> - loop { <nl> - wait ( delay ( FLOW_KNOBS - > TLS_CERT_REFRESH_DELAY_SECONDS ) ) ; <nl> - std : : time_t modtime = wait ( IAsyncFileSystem : : filesystem ( ) - > lastWriteTime ( filename ) ) ; <nl> - if ( lastModTime ! = modtime ) { <nl> - lastModTime = modtime ; <nl> - ErrorOr < Standalone < StringRef > > contents = wait ( readEntireFile ( filename ) ) ; <nl> - if ( contents . present ( ) ) { <nl> - contents_var - > set ( contents . get ( ) ) ; <nl> - } <nl> - } <nl> - } <nl> - } <nl> - <nl> - ACTOR static Future < Void > reloadConfigurationOnChange ( TLSOptions : : PolicyInfo * pci , Reference < ITLSPlugin > plugin , AsyncVar < Reference < ITLSPolicy > > * realVerifyPeersPolicy , AsyncVar < Reference < ITLSPolicy > > * realNoVerifyPeersPolicy ) { <nl> - if ( FLOW_KNOBS - > TLS_CERT_REFRESH_DELAY_SECONDS < = 0 ) { <nl> - return Void ( ) ; <nl> - } <nl> - loop { <nl> - / / Early in bootup , the filesystem might not be initialized yet . Wait until it is . <nl> - if ( IAsyncFileSystem : : filesystem ( ) ! = nullptr ) { <nl> - break ; <nl> - } <nl> - wait ( delay ( 1 . 0 ) ) ; <nl> - } <nl> - state int mismatches = 0 ; <nl> - state AsyncVar < Standalone < StringRef > > ca_var ; <nl> - state AsyncVar < Standalone < StringRef > > key_var ; <nl> - state AsyncVar < Standalone < StringRef > > cert_var ; <nl> - state std : : vector < Future < Void > > lifetimes ; <nl> - if ( ! pci - > ca_path . empty ( ) ) lifetimes . push_back ( watchFileForChanges ( pci - > ca_path , & ca_var ) ) ; <nl> - if ( ! pci - > key_path . empty ( ) ) lifetimes . push_back ( watchFileForChanges ( pci - > key_path , & key_var ) ) ; <nl> - if ( ! pci - > cert_path . empty ( ) ) lifetimes . push_back ( watchFileForChanges ( pci - > cert_path , & cert_var ) ) ; <nl> - loop { <nl> - state Future < Void > ca_changed = ca_var . onChange ( ) ; <nl> - state Future < Void > key_changed = key_var . onChange ( ) ; <nl> - state Future < Void > cert_changed = cert_var . onChange ( ) ; <nl> - wait ( ca_changed | | key_changed | | cert_changed ) ; <nl> - if ( ca_changed . isReady ( ) ) { <nl> - TraceEvent ( SevInfo , " TLSRefreshCAChanged " ) . detail ( " path " , pci - > ca_path ) . detail ( " length " , ca_var . get ( ) . size ( ) ) ; <nl> - pci - > ca_contents = ca_var . get ( ) ; <nl> - } <nl> - if ( key_changed . isReady ( ) ) { <nl> - TraceEvent ( SevInfo , " TLSRefreshKeyChanged " ) . detail ( " path " , pci - > key_path ) . detail ( " length " , key_var . get ( ) . size ( ) ) ; <nl> - pci - > key_contents = key_var . get ( ) ; <nl> - } <nl> - if ( cert_changed . isReady ( ) ) { <nl> - TraceEvent ( SevInfo , " TLSRefreshCertChanged " ) . detail ( " path " , pci - > cert_path ) . detail ( " length " , cert_var . get ( ) . size ( ) ) ; <nl> - pci - > cert_contents = cert_var . get ( ) ; <nl> - } <nl> - bool rc = true ; <nl> - Reference < ITLSPolicy > verifypeers = Reference < ITLSPolicy > ( plugin - > create_policy ( ) ) ; <nl> - Reference < ITLSPolicy > noverifypeers = Reference < ITLSPolicy > ( plugin - > create_policy ( ) ) ; <nl> - loop { <nl> - / / Don ' t actually loop . We ' re just using loop / break as a ` goto err ` . <nl> - / / This loop always ends with an unconditional break . <nl> - rc = verifypeers - > set_ca_data ( pci - > ca_contents . begin ( ) , pci - > ca_contents . size ( ) ) ; <nl> - if ( ! rc ) break ; <nl> - rc = verifypeers - > set_key_data ( pci - > key_contents . begin ( ) , pci - > key_contents . size ( ) , pci - > keyPassword . c_str ( ) ) ; <nl> - if ( ! rc ) break ; <nl> - rc = verifypeers - > set_cert_data ( pci - > cert_contents . begin ( ) , pci - > cert_contents . size ( ) ) ; <nl> - if ( ! rc ) break ; <nl> - { <nl> - std : : unique_ptr < const uint8_t * [ ] > verify_peers_arr ( new const uint8_t * [ pci - > verify_peers . size ( ) ] ) ; <nl> - std : : unique_ptr < int [ ] > verify_peers_len ( new int [ pci - > verify_peers . size ( ) ] ) ; <nl> - for ( int i = 0 ; i < pci - > verify_peers . size ( ) ; i + + ) { <nl> - verify_peers_arr [ i ] = ( const uint8_t * ) & pci - > verify_peers [ i ] [ 0 ] ; <nl> - verify_peers_len [ i ] = pci - > verify_peers [ i ] . size ( ) ; <nl> - } <nl> - rc = verifypeers - > set_verify_peers ( pci - > verify_peers . size ( ) , verify_peers_arr . get ( ) , verify_peers_len . get ( ) ) ; <nl> - if ( ! rc ) break ; <nl> - } <nl> - rc = noverifypeers - > set_ca_data ( pci - > ca_contents . begin ( ) , pci - > ca_contents . size ( ) ) ; <nl> - if ( ! rc ) break ; <nl> - rc = noverifypeers - > set_key_data ( pci - > key_contents . begin ( ) , pci - > key_contents . size ( ) , pci - > keyPassword . c_str ( ) ) ; <nl> - if ( ! rc ) break ; <nl> - rc = noverifypeers - > set_cert_data ( pci - > cert_contents . begin ( ) , pci - > cert_contents . size ( ) ) ; <nl> - if ( ! rc ) break ; <nl> - break ; <nl> - } <nl> - <nl> - if ( rc ) { <nl> - TraceEvent ( SevInfo , " TLSCertificateRefreshSucceeded " ) ; <nl> - realVerifyPeersPolicy - > set ( verifypeers ) ; <nl> - realNoVerifyPeersPolicy - > set ( noverifypeers ) ; <nl> - mismatches = 0 ; <nl> - } else { <nl> - / / Some files didn ' t match up , they should in the future , and we ' ll retry then . <nl> - mismatches + + ; <nl> - TraceEvent ( SevWarn , " TLSCertificateRefreshMismatch " ) . detail ( " mismatches " , mismatches ) ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - const char * defaultCertFileName = " fdb . pem " ; <nl> - <nl> - Reference < ITLSPolicy > TLSOptions : : get_policy ( PolicyType type ) { <nl> - if ( ! certs_set ) { <nl> - if ( ! platform : : getEnvironmentVar ( " FDB_TLS_CERTIFICATE_FILE " , policyInfo . cert_path ) ) <nl> - policyInfo . cert_path = fileExists ( defaultCertFileName ) ? defaultCertFileName : joinPath ( platform : : getDefaultConfigPath ( ) , defaultCertFileName ) ; <nl> - set_cert_file ( policyInfo . cert_path ) ; <nl> - } <nl> - if ( ! key_set ) { <nl> - if ( policyInfo . keyPassword . empty ( ) ) <nl> - platform : : getEnvironmentVar ( " FDB_TLS_PASSWORD " , policyInfo . keyPassword ) ; <nl> - if ( ! platform : : getEnvironmentVar ( " FDB_TLS_KEY_FILE " , policyInfo . key_path ) ) <nl> - policyInfo . key_path = fileExists ( defaultCertFileName ) ? defaultCertFileName : joinPath ( platform : : getDefaultConfigPath ( ) , defaultCertFileName ) ; <nl> - set_key_file ( policyInfo . key_path ) ; <nl> - } <nl> - if ( ! verify_peers_set ) { <nl> - std : : string verify_peers ; <nl> - if ( platform : : getEnvironmentVar ( " FDB_TLS_VERIFY_PEERS " , verify_peers ) ) <nl> - set_verify_peers ( { verify_peers } ) ; <nl> - else <nl> - set_verify_peers ( { std : : string ( " Check . Valid = 1 " ) } ) ; <nl> - } <nl> - if ( ! ca_set ) { <nl> - if ( platform : : getEnvironmentVar ( " FDB_TLS_CA_FILE " , policyInfo . ca_path ) ) <nl> - set_ca_file ( policyInfo . ca_path ) ; <nl> - } <nl> - <nl> - if ( ! configurationReloader . present ( ) ) { <nl> - configurationReloader = reloadConfigurationOnChange ( & policyInfo , plugin , & policyVerifyPeersSet , & policyVerifyPeersNotSet ) ; <nl> - } <nl> - <nl> - Reference < ITLSPolicy > policy ; <nl> - switch ( type ) { <nl> - case POLICY_VERIFY_PEERS : <nl> - policy = policyVerifyPeersSet . get ( ) ; <nl> - break ; <nl> - case POLICY_NO_VERIFY_PEERS : <nl> - policy = policyVerifyPeersNotSet . get ( ) ; <nl> - break ; <nl> - default : <nl> - ASSERT_ABORT ( 0 ) ; <nl> - } <nl> - return policy ; <nl> - } <nl> - <nl> - void TLSOptions : : init_plugin ( ) { <nl> - <nl> - TraceEvent ( " TLSConnectionLoadingPlugin " ) . detail ( " Plugin " , tlsPluginName ) ; <nl> - <nl> - plugin = loadPlugin < ITLSPlugin > ( tlsPluginName ) ; <nl> - <nl> - if ( ! plugin ) { <nl> - TraceEvent ( SevError , " TLSConnectionPluginInitError " ) . detail ( " Plugin " , tlsPluginName ) . GetLastError ( ) ; <nl> - throw tls_error ( ) ; <nl> - } <nl> - <nl> - policyVerifyPeersSet = AsyncVar < Reference < ITLSPolicy > > ( Reference < ITLSPolicy > ( plugin - > create_policy ( ) ) ) ; <nl> - if ( ! policyVerifyPeersSet . get ( ) ) { <nl> - / / Hopefully create_policy logged something with the log func <nl> - TraceEvent ( SevError , " TLSConnectionCreatePolicyVerifyPeersSetError " ) ; <nl> - throw tls_error ( ) ; <nl> - } <nl> - <nl> - policyVerifyPeersNotSet = AsyncVar < Reference < ITLSPolicy > > ( Reference < ITLSPolicy > ( plugin - > create_policy ( ) ) ) ; <nl> - if ( ! policyVerifyPeersNotSet . get ( ) ) { <nl> - / / Hopefully create_policy logged something with the log func <nl> - TraceEvent ( SevError , " TLSConnectionCreatePolicyVerifyPeersNotSetError " ) ; <nl> - throw tls_error ( ) ; <nl> - } <nl> - } <nl> - <nl> - bool TLSOptions : : enabled ( ) { <nl> - return policyVerifyPeersSet . get ( ) . isValid ( ) & & policyVerifyPeersNotSet . get ( ) . isValid ( ) ; <nl> - } <nl> deleted file mode 100644 <nl> index 7e8bb38fd8 . . 0000000000 <nl> mmm a / fdbrpc / TLSConnection . h <nl> ppp / dev / null <nl> <nl> - / * <nl> - * TLSConnection . h <nl> - * <nl> - * This source file is part of the FoundationDB open source project <nl> - * <nl> - * Copyright 2013 - 2018 Apple Inc . and the FoundationDB project authors <nl> - * <nl> - * Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> - * you may not use this file except in compliance with the License . <nl> - * You may obtain a copy of the License at <nl> - * <nl> - * http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> - * <nl> - * Unless required by applicable law or agreed to in writing , software <nl> - * distributed under the License is distributed on an " AS IS " BASIS , <nl> - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> - * See the License for the specific language governing permissions and <nl> - * limitations under the License . <nl> - * / <nl> - <nl> - # ifndef FLOW_TLSCONNECTION_H <nl> - # define FLOW_TLSCONNECTION_H <nl> - <nl> - # pragma once <nl> - <nl> - # include " flow / Platform . h " <nl> - <nl> - # include " fdbrpc / ITLSPlugin . h " <nl> - <nl> - struct TLSConnection : IConnection , ReferenceCounted < TLSConnection > { <nl> - Reference < IConnection > conn ; <nl> - Reference < ITLSSession > session ; <nl> - <nl> - Future < Void > handshook ; <nl> - <nl> - int write_wants , read_wants ; <nl> - <nl> - UID uid ; <nl> - bool is_client ; <nl> - <nl> - virtual void addref ( ) { ReferenceCounted < TLSConnection > : : addref ( ) ; } <nl> - virtual void delref ( ) { ReferenceCounted < TLSConnection > : : delref ( ) ; } <nl> - <nl> - TLSConnection ( Reference < IConnection > const & conn , Reference < ITLSPolicy > const & policy , bool is_client , std : : string host ) ; <nl> - ~ TLSConnection ( ) { <nl> - / / Here for ordering to make sure we delref the ITLSSession <nl> - / / which has a pointer to this object <nl> - session . clear ( ) ; <nl> - } <nl> - <nl> - virtual void close ( ) { conn - > close ( ) ; } <nl> - <nl> - virtual Future < Void > onWritable ( ) ; <nl> - <nl> - virtual Future < Void > onReadable ( ) ; <nl> - <nl> - virtual int read ( uint8_t * begin , uint8_t * end ) ; <nl> - <nl> - virtual int write ( SendBuffer const * buffer , int limit ) ; <nl> - <nl> - virtual NetworkAddress getPeerAddress ( ) { <nl> - NetworkAddress a = conn - > getPeerAddress ( ) ; <nl> - return NetworkAddress ( a . ip , a . port , a . isPublic ( ) , true ) ; <nl> - } <nl> - <nl> - virtual UID getDebugID ( ) { return uid ; } <nl> - } ; <nl> - <nl> - struct TLSOptions : ReferenceCounted < TLSOptions > { <nl> - enum { OPT_TLS = 100000 , OPT_TLS_PLUGIN , OPT_TLS_CERTIFICATES , OPT_TLS_KEY , OPT_TLS_VERIFY_PEERS , OPT_TLS_CA_FILE , OPT_TLS_PASSWORD } ; <nl> - enum PolicyType { POLICY_VERIFY_PEERS = 1 , POLICY_NO_VERIFY_PEERS } ; <nl> - TLSOptions ( ) : certs_set ( false ) , key_set ( false ) , verify_peers_set ( false ) , ca_set ( false ) { <nl> - # ifndef TLS_DISABLED <nl> - init_plugin ( ) ; <nl> - # endif <nl> - } <nl> - <nl> - void set_cert_file ( std : : string const & cert_file ) ; <nl> - void set_cert_data ( std : : string const & cert_data ) ; <nl> - void set_ca_file ( std : : string const & ca_file ) ; <nl> - void set_ca_data ( std : : string const & ca_data ) ; <nl> - / / If there is a passphrase , this api should be called prior to setting key for the passphrase to be used <nl> - void set_key_password ( std : : string const & password ) ; <nl> - void set_key_file ( std : : string const & key_file ) ; <nl> - void set_key_data ( std : : string const & key_data ) ; <nl> - void set_verify_peers ( std : : vector < std : : string > const & verify_peers ) ; <nl> - <nl> - void register_network ( ) ; <nl> - <nl> - Reference < ITLSPolicy > get_policy ( PolicyType type ) ; <nl> - bool enabled ( ) ; <nl> - <nl> - struct PolicyInfo { <nl> - std : : string ca_path ; <nl> - Standalone < StringRef > ca_contents ; <nl> - std : : string key_path ; <nl> - std : : string keyPassword ; <nl> - Standalone < StringRef > key_contents ; <nl> - std : : string cert_path ; <nl> - Standalone < StringRef > cert_contents ; <nl> - std : : vector < std : : string > verify_peers ; <nl> - } ; <nl> - <nl> - private : <nl> - void init_plugin ( ) ; <nl> - <nl> - Reference < ITLSPlugin > plugin ; <nl> - PolicyInfo policyInfo ; <nl> - AsyncVar < Reference < ITLSPolicy > > policyVerifyPeersSet ; <nl> - AsyncVar < Reference < ITLSPolicy > > policyVerifyPeersNotSet ; <nl> - Optional < Future < Void > > configurationReloader ; <nl> - <nl> - bool certs_set , key_set , verify_peers_set , ca_set ; <nl> - } ; <nl> - <nl> - struct TLSListener : IListener , ReferenceCounted < TLSListener > { <nl> - Reference < IListener > listener ; <nl> - Reference < TLSOptions > options ; <nl> - <nl> - TLSListener ( Reference < TLSOptions > options , Reference < IListener > listener ) : options ( options ) , listener ( listener ) { } <nl> - <nl> - virtual void addref ( ) { ReferenceCounted < TLSListener > : : addref ( ) ; } <nl> - virtual void delref ( ) { ReferenceCounted < TLSListener > : : delref ( ) ; } <nl> - <nl> - virtual Future < Reference < IConnection > > accept ( ) ; <nl> - <nl> - virtual NetworkAddress getListenAddress ( ) { return listener - > getListenAddress ( ) ; } <nl> - } ; <nl> - <nl> - struct TLSNetworkConnections : INetworkConnections { <nl> - INetworkConnections * network ; <nl> - <nl> - explicit TLSNetworkConnections ( Reference < TLSOptions > options ) ; <nl> - <nl> - virtual Future < Reference < IConnection > > connect ( NetworkAddress toAddr , std : : string host ) ; <nl> - virtual Future < std : : vector < NetworkAddress > > resolveTCPEndpoint ( std : : string host , std : : string service ) ; <nl> - <nl> - virtual Reference < IListener > listen ( NetworkAddress localAddr ) ; <nl> - <nl> - private : <nl> - Reference < TLSOptions > options ; <nl> - } ; <nl> - <nl> - # define TLS_PLUGIN_FLAG " - - tls_plugin " <nl> - # define TLS_CERTIFICATE_FILE_FLAG " - - tls_certificate_file " <nl> - # define TLS_KEY_FILE_FLAG " - - tls_key_file " <nl> - # define TLS_VERIFY_PEERS_FLAG " - - tls_verify_peers " <nl> - # define TLS_CA_FILE_FLAG " - - tls_ca_file " <nl> - # define TLS_PASSWORD_FLAG " - - tls_password " <nl> - <nl> - # define TLS_OPTION_FLAGS \ <nl> - { TLSOptions : : OPT_TLS_PLUGIN , TLS_PLUGIN_FLAG , SO_REQ_SEP } , \ <nl> - { TLSOptions : : OPT_TLS_CERTIFICATES , TLS_CERTIFICATE_FILE_FLAG , SO_REQ_SEP } , \ <nl> - { TLSOptions : : OPT_TLS_KEY , TLS_KEY_FILE_FLAG , SO_REQ_SEP } , \ <nl> - { TLSOptions : : OPT_TLS_VERIFY_PEERS , TLS_VERIFY_PEERS_FLAG , SO_REQ_SEP } , \ <nl> - { TLSOptions : : OPT_TLS_PASSWORD , TLS_PASSWORD_FLAG , SO_REQ_SEP } , \ <nl> - { TLSOptions : : OPT_TLS_CA_FILE , TLS_CA_FILE_FLAG , SO_REQ_SEP } , <nl> - <nl> - # define TLS_HELP \ <nl> - " " TLS_CERTIFICATE_FILE_FLAG " CERTFILE \ n " \ <nl> - " The path of a file containing the TLS certificate and CA \ n " \ <nl> - " chain . \ n " \ <nl> - " " TLS_CA_FILE_FLAG " CERTAUTHFILE \ n " \ <nl> - " The path of a file containing the CA certificates chain . \ n " \ <nl> - " " TLS_KEY_FILE_FLAG " KEYFILE \ n " \ <nl> - " The path of a file containing the private key corresponding \ n " \ <nl> - " to the TLS certificate . \ n " \ <nl> - " " TLS_PASSWORD_FLAG " PASSCODE \ n " \ <nl> - " The passphrase of encrypted private key \ n " \ <nl> - " " TLS_VERIFY_PEERS_FLAG " CONSTRAINTS \ n " \ <nl> - " The constraints by which to validate TLS peers . The contents \ n " \ <nl> - " and format of CONSTRAINTS are plugin - specific . \ n " <nl> - <nl> - # endif / * FLOW_TLSCONNECTION_H * / <nl> mmm a / fdbrpc / fdbrpc . h <nl> ppp b / fdbrpc / fdbrpc . h <nl> struct NetSAV : SAV < T > , FlowReceiver , FastAllocated < NetSAV < T > > { <nl> } <nl> <nl> virtual void destroy ( ) { delete this ; } <nl> - virtual void receive ( ArenaReader & reader ) { <nl> - if ( ! SAV < T > : : canBeSet ( ) ) return ; / / load balancing and retries can result in the same request being answered twice <nl> - this - > addPromiseRef ( ) ; <nl> - bool ok ; <nl> - reader > > ok ; <nl> - if ( ok ) { <nl> - T message ; <nl> - reader > > message ; <nl> - SAV < T > : : sendAndDelPromiseRef ( message ) ; <nl> - } <nl> - else { <nl> - Error error ; <nl> - reader > > error ; <nl> - SAV < T > : : sendErrorAndDelPromiseRef ( error ) ; <nl> - } <nl> - } <nl> virtual void receive ( ArenaObjectReader & reader ) { <nl> if ( ! SAV < T > : : canBeSet ( ) ) return ; <nl> this - > addPromiseRef ( ) ; <nl> struct NetNotifiedQueue : NotifiedQueue < T > , FlowReceiver , FastAllocated < NetNotif <nl> : NotifiedQueue < T > ( futures , promises ) , FlowReceiver ( remoteEndpoint , true ) { } <nl> <nl> virtual void destroy ( ) { delete this ; } <nl> - virtual void receive ( ArenaReader & reader ) { <nl> - this - > addPromiseRef ( ) ; <nl> - T message ; <nl> - reader > > message ; <nl> - this - > send ( std : : move ( message ) ) ; <nl> - this - > delPromiseRef ( ) ; <nl> - } <nl> virtual void receive ( ArenaObjectReader & reader ) { <nl> this - > addPromiseRef ( ) ; <nl> T message ; <nl> mmm a / fdbrpc / fdbrpc . vcxproj <nl> ppp b / fdbrpc / fdbrpc . vcxproj <nl> <nl> < ClCompile Include = " ReplicationTypes . cpp " / > <nl> < ClCompile Include = " ReplicationPolicy . cpp " / > <nl> < ClCompile Include = " sim_validation . cpp " / > <nl> - < ActorCompiler Include = " TLSConnection . actor . cpp " / > <nl> < ClCompile Include = " TraceFileIO . cpp " / > <nl> < ClCompile Include = " zlib \ gzwrite . c " / > <nl> < ClCompile Include = " zlib \ gzclose . c " / > <nl> <nl> < ClInclude Include = " Platform . h " / > <nl> < ClInclude Include = " fdbrpc . h " / > <nl> < ClInclude Include = " FlowTransport . h " / > <nl> - < ClInclude Include = " ITLSPlugin . h " / > <nl> < ClInclude Include = " libcoroutine \ Base . h " / > <nl> < ClInclude Include = " libcoroutine \ Common . h " / > <nl> < ClInclude Include = " libcoroutine \ Coro . h " / > <nl> <nl> < ClInclude Include = " sim_validation . h " / > <nl> < ClInclude Include = " Smoother . h " / > <nl> < ClInclude Include = " TimedRequest . h " / > <nl> - < ClInclude Include = " TLSConnection . h " / > <nl> < ClInclude Include = " TraceFileIO . h " / > <nl> < ClInclude Include = " zlib \ zlib . h " / > <nl> < ClInclude Include = " zlib \ deflate . h " / > <nl> mmm a / fdbrpc / fdbrpc . vcxproj . filters <nl> ppp b / fdbrpc / fdbrpc . vcxproj . filters <nl> <nl> < ActorCompiler Include = " AsyncFileCached . actor . cpp " / > <nl> < ActorCompiler Include = " AsyncFileNonDurable . actor . h " / > <nl> < ActorCompiler Include = " AsyncFileNonDurable . actor . cpp " / > <nl> - < ActorCompiler Include = " TLSConnection . actor . cpp " / > <nl> < ActorCompiler Include = " dsltest . actor . cpp " / > <nl> < ActorCompiler Include = " FlowTests . actor . cpp " / > <nl> < ActorCompiler Include = " genericactors . actor . cpp " / > <nl> <nl> < ClInclude Include = " zlib \ inftrees . h " > <nl> < Filter > zlib < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " ITLSPlugin . h " / > <nl> < ClInclude Include = " FailureMonitor . h " / > <nl> < ClInclude Include = " FlowTransport . h " / > <nl> < ClInclude Include = " IAsyncFile . h " / > <nl> <nl> < ClInclude Include = " RangeMap . h " / > <nl> < ClInclude Include = " Smoother . h " / > <nl> < ClInclude Include = " TraceFileIO . h " / > <nl> - < ClInclude Include = " TLSConnection . h " / > <nl> < ClInclude Include = " IRateControl . h " / > <nl> < ClInclude Include = " Replication . h " / > <nl> < ClInclude Include = " ReplicationTypes . h " / > <nl> mmm a / fdbrpc / networksender . actor . h <nl> ppp b / fdbrpc / networksender . actor . h <nl> ACTOR template < class T > <nl> void networkSender ( Future < T > input , Endpoint endpoint ) { <nl> try { <nl> T value = wait ( input ) ; <nl> - if ( FLOW_KNOBS - > USE_OBJECT_SERIALIZER ) { <nl> - FlowTransport : : transport ( ) . sendUnreliable ( SerializeSource < ErrorOr < EnsureTable < T > > > ( value ) , endpoint , false ) ; <nl> - } else { <nl> - FlowTransport : : transport ( ) . sendUnreliable ( SerializeBoolAnd < T > ( true , value ) , endpoint , false ) ; <nl> - } <nl> + FlowTransport : : transport ( ) . sendUnreliable ( SerializeSource < ErrorOr < EnsureTable < T > > > ( value ) , endpoint , false ) ; <nl> } catch ( Error & err ) { <nl> / / if ( err . code ( ) = = error_code_broken_promise ) return ; <nl> ASSERT ( err . code ( ) ! = error_code_actor_cancelled ) ; <nl> - if ( FLOW_KNOBS - > USE_OBJECT_SERIALIZER ) { <nl> - FlowTransport : : transport ( ) . sendUnreliable ( SerializeSource < ErrorOr < EnsureTable < T > > > ( err ) , endpoint , false ) ; <nl> - } else { <nl> - FlowTransport : : transport ( ) . sendUnreliable ( SerializeBoolAnd < Error > ( false , err ) , endpoint , false ) ; <nl> - } <nl> + FlowTransport : : transport ( ) . sendUnreliable ( SerializeSource < ErrorOr < EnsureTable < T > > > ( err ) , endpoint , false ) ; <nl> } <nl> } <nl> # include " flow / unactorcompiler . h " <nl> mmm a / fdbrpc / sim2 . actor . cpp <nl> ppp b / fdbrpc / sim2 . actor . cpp <nl> struct Sim2Conn : IConnection , ReferenceCounted < Sim2Conn > { <nl> virtual void delref ( ) { ReferenceCounted < Sim2Conn > : : delref ( ) ; } <nl> virtual void close ( ) { closedByCaller = true ; closeInternal ( ) ; } <nl> <nl> + virtual Future < Void > acceptHandshake ( ) { return delay ( 0 . 01 * deterministicRandom ( ) - > random01 ( ) ) ; } <nl> + virtual Future < Void > connectHandshake ( ) { return delay ( 0 . 01 * deterministicRandom ( ) - > random01 ( ) ) ; } <nl> + <nl> virtual Future < Void > onWritable ( ) { return whenWritable ( this ) ; } <nl> virtual Future < Void > onReadable ( ) { return whenReadable ( this ) ; } <nl> <nl> class Sim2 : public ISimulator , public INetworkConnections { <nl> / / Everything actually network related is delegated to the Sim2Net class ; Sim2 is only concerned with simulating machines and time <nl> virtual double now ( ) { return time ; } <nl> <nl> + / / timer ( ) can be up to one second ahead of now ( ) <nl> + virtual double timer ( ) { <nl> + timerTime + = deterministicRandom ( ) - > random01 ( ) * ( time + 1 . 0 - timerTime ) / 2 . 0 ; <nl> + return timerTime ; <nl> + } <nl> + <nl> virtual Future < class Void > delay ( double seconds , TaskPriority taskID ) { <nl> ASSERT ( taskID > = TaskPriority : : Min & & taskID < = TaskPriority : : Max ) ; <nl> return delay ( seconds , taskID , currentProcess ) ; <nl> class Sim2 : public ISimulator , public INetworkConnections { <nl> } <nl> / / Sets the taskID / priority of the current task , without yielding <nl> virtual Future < Reference < IConnection > > connect ( NetworkAddress toAddr , std : : string host ) { <nl> - ASSERT ( ! toAddr . isTLS ( ) & & host . empty ( ) ) ; <nl> + ASSERT ( host . empty ( ) ) ; <nl> if ( ! addressMap . count ( toAddr ) ) { <nl> return waitForProcessAndConnect ( toAddr , this ) ; <nl> } <nl> class Sim2 : public ISimulator , public INetworkConnections { <nl> } else { <nl> localIp = IPAddress ( getCurrentProcess ( ) - > address . ip . toV4 ( ) + deterministicRandom ( ) - > randomInt ( 0 , 256 ) ) ; <nl> } <nl> - peerc - > connect ( myc , NetworkAddress ( localIp , deterministicRandom ( ) - > randomInt ( 40000 , 60000 ) ) ) ; <nl> + peerc - > connect ( myc , NetworkAddress ( localIp , deterministicRandom ( ) - > randomInt ( 40000 , 60000 ) , false , toAddr . isTLS ( ) ) ) ; <nl> <nl> ( ( Sim2Listener * ) peerp - > getListener ( toAddr ) . getPtr ( ) ) - > incomingConnection ( 0 . 5 * deterministicRandom ( ) - > random01 ( ) , Reference < IConnection > ( peerc ) ) ; <nl> return onConnect ( : : delay ( 0 . 5 * deterministicRandom ( ) - > random01 ( ) ) , myc ) ; <nl> class Sim2 : public ISimulator , public INetworkConnections { <nl> return conn ; <nl> } <nl> virtual Reference < IListener > listen ( NetworkAddress localAddr ) { <nl> - ASSERT ( ! localAddr . isTLS ( ) ) ; <nl> Reference < IListener > listener ( getCurrentProcess ( ) - > getListener ( localAddr ) ) ; <nl> ASSERT ( listener ) ; <nl> return listener ; <nl> class Sim2 : public ISimulator , public INetworkConnections { <nl> Future < Void > loopFuture = runLoop ( this ) ; <nl> net2 - > run ( ) ; <nl> } <nl> - virtual ProcessInfo * newProcess ( const char * name , IPAddress ip , uint16_t port , uint16_t listenPerProcess , <nl> + virtual ProcessInfo * newProcess ( const char * name , IPAddress ip , uint16_t port , bool sslEnabled , uint16_t listenPerProcess , <nl> LocalityData locality , ProcessClass startingClass , const char * dataFolder , <nl> const char * coordinationFolder ) { <nl> ASSERT ( locality . machineId ( ) . present ( ) ) ; <nl> class Sim2 : public ISimulator , public INetworkConnections { <nl> } <nl> <nl> NetworkAddressList addresses ; <nl> - addresses . address = NetworkAddress ( ip , port , true , false ) ; <nl> + addresses . address = NetworkAddress ( ip , port , true , sslEnabled ) ; <nl> if ( listenPerProcess = = 2 ) { <nl> addresses . secondaryAddress = NetworkAddress ( ip , port + 1 , true , false ) ; <nl> } <nl> <nl> ProcessInfo * m = new ProcessInfo ( name , locality , startingClass , addresses , this , dataFolder , coordinationFolder ) ; <nl> for ( int processPort = port ; processPort < port + listenPerProcess ; + + processPort ) { <nl> - NetworkAddress address ( ip , processPort , true , false ) ; / / SOMEDAY see above about becoming SSL ! <nl> + NetworkAddress address ( ip , processPort , true , sslEnabled & & processPort = = port ) ; <nl> m - > listenerMap [ address ] = Reference < IListener > ( new Sim2Listener ( m , address ) ) ; <nl> addressMap [ address ] = m ; <nl> } <nl> class Sim2 : public ISimulator , public INetworkConnections { <nl> return processes ; <nl> } <nl> virtual ProcessInfo * getProcessByAddress ( NetworkAddress const & address ) { <nl> - NetworkAddress normalizedAddress ( address . ip , address . port , true , false ) ; <nl> + NetworkAddress normalizedAddress ( address . ip , address . port , true , address . isTLS ( ) ) ; <nl> ASSERT ( addressMap . count ( normalizedAddress ) ) ; <nl> return addressMap [ normalizedAddress ] ; <nl> } <nl> class Sim2 : public ISimulator , public INetworkConnections { <nl> machines . erase ( machineId ) ; <nl> } <nl> <nl> - Sim2 ( ) : time ( 0 . 0 ) , taskCount ( 0 ) , yielded ( false ) , yield_limit ( 0 ) , currentTaskID ( TaskPriority : : Zero ) { <nl> + Sim2 ( ) : time ( 0 . 0 ) , timerTime ( 0 . 0 ) , taskCount ( 0 ) , yielded ( false ) , yield_limit ( 0 ) , currentTaskID ( TaskPriority : : Zero ) { <nl> / / Not letting currentProcess be NULL eliminates some annoying special cases <nl> currentProcess = new ProcessInfo ( " NoMachine " , LocalityData ( Optional < Standalone < StringRef > > ( ) , StringRef ( ) , StringRef ( ) , StringRef ( ) ) , ProcessClass ( ) , { NetworkAddress ( ) } , this , " " , " " ) ; <nl> g_network = net2 = newNet2 ( false , true ) ; <nl> class Sim2 : public ISimulator , public INetworkConnections { <nl> else { <nl> mutex . enter ( ) ; <nl> this - > time = t . time ; <nl> + this - > timerTime = std : : max ( this - > timerTime , this - > time ) ; <nl> mutex . leave ( ) ; <nl> <nl> this - > currentProcess = t . machine ; <nl> class Sim2 : public ISimulator , public INetworkConnections { <nl> / / time is guarded by ISimulator : : mutex . It is not necessary to guard reads on the main thread because <nl> / / time should only be modified from the main thread . <nl> double time ; <nl> + double timerTime ; <nl> TaskPriority currentTaskID ; <nl> <nl> / / taskCount is guarded by ISimulator : : mutex <nl> ACTOR void doReboot ( ISimulator : : ProcessInfo * p , ISimulator : : KillType kt ) { <nl> TEST ( kt = = ISimulator : : RebootAndDelete ) ; / / Simulated machine rebooted with data and coordination state deletion <nl> TEST ( kt = = ISimulator : : RebootProcessAndDelete ) ; / / Simulated process rebooted with data and coordination state deletion <nl> <nl> - if ( p - > rebooting ) <nl> + if ( p - > rebooting | | ! p - > isReliable ( ) ) <nl> return ; <nl> TraceEvent ( " RebootingProcess " ) . detail ( " KillType " , kt ) . detail ( " Address " , p - > address ) . detail ( " ZoneId " , p - > locality . zoneId ( ) ) . detail ( " DataHall " , p - > locality . dataHallId ( ) ) . detail ( " Locality " , p - > locality . toString ( ) ) . detail ( " Failed " , p - > failed ) . detail ( " Excluded " , p - > excluded ) . detail ( " Cleared " , p - > cleared ) . backtrace ( ) ; <nl> p - > rebooting = true ; <nl> mmm a / fdbrpc / simulator . h <nl> ppp b / fdbrpc / simulator . h <nl> class ISimulator : public INetwork { <nl> virtual Future < Void > onProcess ( ISimulator : : ProcessInfo * process , TaskPriority taskID = TaskPriority : : Zero ) = 0 ; <nl> virtual Future < Void > onMachine ( ISimulator : : ProcessInfo * process , TaskPriority taskID = TaskPriority : : Zero ) = 0 ; <nl> <nl> - virtual ProcessInfo * newProcess ( const char * name , IPAddress ip , uint16_t port , uint16_t listenPerProcess , <nl> + virtual ProcessInfo * newProcess ( const char * name , IPAddress ip , uint16_t port , bool sslEnabled , uint16_t listenPerProcess , <nl> LocalityData locality , ProcessClass startingClass , const char * dataFolder , <nl> const char * coordinationFolder ) = 0 ; <nl> virtual void killProcess ( ProcessInfo * machine , KillType ) = 0 ; <nl> mmm a / fdbserver / BackupWorker . actor . cpp <nl> ppp b / fdbserver / BackupWorker . actor . cpp <nl> struct BackupData { <nl> BackupData * self = nullptr ; <nl> Version startVersion = invalidVersion ; <nl> Version lastSavedVersion = invalidVersion ; <nl> - Future < Reference < IBackupContainer > > container ; <nl> + Future < Optional < Reference < IBackupContainer > > > container ; <nl> Future < Optional < std : : vector < KeyRange > > > ranges ; / / Key ranges of this backup <nl> bool allWorkerStarted = false ; / / Only worker with Tag ( - 2 , 0 ) uses & sets this field <nl> bool stopped = false ; / / Is the backup stopped ? <nl> struct BackupData { <nl> <nl> / / Open the container and get key ranges <nl> BackupConfig config ( uid ) ; <nl> - inserted . first - > second . container = config . backupContainer ( ) . getOrThrow ( cx ) ; <nl> + inserted . first - > second . container = config . backupContainer ( ) . get ( cx ) ; <nl> inserted . first - > second . ranges = config . backupRanges ( ) . get ( cx ) ; <nl> } else { <nl> stopList . erase ( uid ) ; <nl> ACTOR Future < Void > saveMutationsToFile ( BackupData * self , Version popVersion , int <nl> for ( auto it = self - > backups . begin ( ) ; it ! = self - > backups . end ( ) ; ) { <nl> if ( ! it - > second . isRunning ( ) ) { <nl> if ( it - > second . stopped ) { <nl> + TraceEvent ( " BackupWorkerRemoveStoppedContainer " , self - > myId ) . detail ( " BackupId " , it - > first ) ; <nl> it = self - > backups . erase ( it ) ; <nl> } else { <nl> it + + ; <nl> } <nl> continue ; <nl> } <nl> + if ( ! it - > second . container . get ( ) . present ( ) ) { <nl> + TraceEvent ( " BackupWorkerNoContainer " , self - > myId ) . detail ( " BackupId " , it - > first ) ; <nl> + it = self - > backups . erase ( it ) ; <nl> + continue ; <nl> + } <nl> const int index = logFileFutures . size ( ) ; <nl> activeUids . insert ( it - > first ) ; <nl> self - > insertRanges ( keyRangeMap , it - > second . ranges . get ( ) , index ) ; <nl> if ( it - > second . lastSavedVersion = = invalidVersion ) { <nl> it - > second . lastSavedVersion = self - > messages [ 0 ] . getVersion ( ) ; <nl> } <nl> - logFileFutures . push_back ( it - > second . container . get ( ) - > writeTaggedLogFile ( <nl> + logFileFutures . push_back ( it - > second . container . get ( ) . get ( ) - > writeTaggedLogFile ( <nl> it - > second . lastSavedVersion , popVersion + 1 , blockSize , self - > tag . id ) ) ; <nl> it + + ; <nl> } <nl> mmm a / fdbserver / ClusterController . actor . cpp <nl> ppp b / fdbserver / ClusterController . actor . cpp <nl> struct WorkerInfo : NonCopyable { <nl> ReplyPromise < RegisterWorkerReply > reply ; <nl> Generation gen ; <nl> int reboots ; <nl> - double lastAvailableTime ; <nl> ProcessClass initialClass ; <nl> ClusterControllerPriorityInfo priorityInfo ; <nl> WorkerDetails details ; <nl> struct WorkerInfo : NonCopyable { <nl> Future < Void > haltDistributor ; <nl> Optional < uint16_t > storageCacheInfo ; <nl> <nl> - WorkerInfo ( ) : gen ( - 1 ) , reboots ( 0 ) , lastAvailableTime ( now ( ) ) , priorityInfo ( ProcessClass : : UnsetFit , false , ClusterControllerPriorityInfo : : FitnessUnknown ) { } <nl> + WorkerInfo ( ) : gen ( - 1 ) , reboots ( 0 ) , priorityInfo ( ProcessClass : : UnsetFit , false , ClusterControllerPriorityInfo : : FitnessUnknown ) { } <nl> WorkerInfo ( Future < Void > watcher , ReplyPromise < RegisterWorkerReply > reply , Generation gen , WorkerInterface interf , ProcessClass initialClass , ProcessClass processClass , ClusterControllerPriorityInfo priorityInfo , bool degraded ) : <nl> - watcher ( watcher ) , reply ( reply ) , gen ( gen ) , reboots ( 0 ) , lastAvailableTime ( now ( ) ) , initialClass ( initialClass ) , priorityInfo ( priorityInfo ) , details ( interf , processClass , degraded ) { } <nl> + watcher ( watcher ) , reply ( reply ) , gen ( gen ) , reboots ( 0 ) , initialClass ( initialClass ) , priorityInfo ( priorityInfo ) , details ( interf , processClass , degraded ) { } <nl> <nl> WorkerInfo ( WorkerInfo & & r ) BOOST_NOEXCEPT : watcher ( std : : move ( r . watcher ) ) , reply ( std : : move ( r . reply ) ) , gen ( r . gen ) , <nl> - reboots ( r . reboots ) , lastAvailableTime ( r . lastAvailableTime ) , initialClass ( r . initialClass ) , priorityInfo ( r . priorityInfo ) , details ( std : : move ( r . details ) ) , <nl> + reboots ( r . reboots ) , initialClass ( r . initialClass ) , priorityInfo ( r . priorityInfo ) , details ( std : : move ( r . details ) ) , <nl> haltRatekeeper ( r . haltRatekeeper ) , haltDistributor ( r . haltDistributor ) , storageCacheInfo ( r . storageCacheInfo ) { } <nl> void operator = ( WorkerInfo & & r ) BOOST_NOEXCEPT { <nl> watcher = std : : move ( r . watcher ) ; <nl> reply = std : : move ( r . reply ) ; <nl> gen = r . gen ; <nl> reboots = r . reboots ; <nl> - lastAvailableTime = r . lastAvailableTime ; <nl> initialClass = r . initialClass ; <nl> priorityInfo = r . priorityInfo ; <nl> details = std : : move ( r . details ) ; <nl> class ClusterControllerData { <nl> std : : vector < LocalityData > tLocalities ; <nl> <nl> / / Try to find the best team of servers to fulfill the policy <nl> - if ( findBestPolicySet ( bestSet , logServerSet , policy , desired , SERVER_KNOBS - > POLICY_RATING_TESTS , SERVER_KNOBS - > POLICY_GENERATIONS ) ) { <nl> + if ( findBestPolicySet ( bestSet , logServerSet , policy , desired , SERVER_KNOBS - > POLICY_RATING_TESTS , <nl> + SERVER_KNOBS - > POLICY_GENERATIONS ) ) { <nl> results . reserve ( results . size ( ) + bestSet . size ( ) ) ; <nl> for ( auto & entry : bestSet ) { <nl> auto object = logServerMap - > getObject ( entry ) ; <nl> class ClusterControllerData { <nl> TraceEvent ( " GetTLogTeamDone " ) . detail ( " Completed " , bCompleted ) . detail ( " Policy " , policy - > info ( ) ) . detail ( " Results " , results . size ( ) ) . detail ( " Processes " , logServerSet - > size ( ) ) . detail ( " Workers " , id_worker . size ( ) ) <nl> . detail ( " Required " , required ) . detail ( " Desired " , desired ) . detail ( " RatingTests " , SERVER_KNOBS - > POLICY_RATING_TESTS ) . detail ( " PolicyGenerations " , SERVER_KNOBS - > POLICY_GENERATIONS ) ; <nl> <nl> - logServerSet - > clear ( ) ; <nl> - logServerSet . clear ( ) ; <nl> <nl> return results ; <nl> } <nl> class ClusterControllerData { <nl> if ( satelliteFallback | | region . satelliteTLogUsableDcsFallback = = 0 ) { <nl> throw no_more_servers ( ) ; <nl> } else { <nl> - if ( now ( ) - startTime < SERVER_KNOBS - > WAIT_FOR_GOOD_RECRUITMENT_DELAY ) { <nl> + if ( ! goodRecruitmentTime . isReady ( ) ) { <nl> throw operation_failed ( ) ; <nl> } <nl> satelliteFallback = true ; <nl> class ClusterControllerData { <nl> result . logRouters . push_back ( logRouters [ i ] . interf ) ; <nl> } <nl> <nl> - if ( ! remoteStartTime . present ( ) ) { <nl> - double maxAvailableTime = 0 ; <nl> - for ( auto & it : result . remoteTLogs ) { <nl> - maxAvailableTime = std : : max ( maxAvailableTime , id_worker [ it . locality . processId ( ) ] . lastAvailableTime ) ; <nl> - } <nl> - for ( auto & it : result . logRouters ) { <nl> - maxAvailableTime = std : : max ( maxAvailableTime , id_worker [ it . locality . processId ( ) ] . lastAvailableTime ) ; <nl> - } <nl> - remoteStartTime = maxAvailableTime ; <nl> - } <nl> <nl> - if ( now ( ) - remoteStartTime . get ( ) < SERVER_KNOBS - > WAIT_FOR_GOOD_REMOTE_RECRUITMENT_DELAY & & <nl> + if ( ! goodRemoteRecruitmentTime . isReady ( ) & & <nl> ( ( RoleFitness ( SERVER_KNOBS - > EXPECTED_TLOG_FITNESS , req . configuration . getDesiredRemoteLogs ( ) , ProcessClass : : TLog ) . betterCount ( RoleFitness ( remoteLogs , ProcessClass : : TLog ) ) ) | | <nl> ( RoleFitness ( SERVER_KNOBS - > EXPECTED_LOG_ROUTER_FITNESS , req . logRouterCount , ProcessClass : : LogRouter ) . betterCount ( RoleFitness ( logRouters , ProcessClass : : LogRouter ) ) ) ) ) { <nl> throw operation_failed ( ) ; <nl> class ClusterControllerData { <nl> [ ] ( const WorkerDetails & w ) { return w . interf ; } ) ; <nl> } <nl> <nl> - if ( now ( ) - startTime < SERVER_KNOBS - > WAIT_FOR_GOOD_RECRUITMENT_DELAY & & <nl> + if ( ! goodRecruitmentTime . isReady ( ) & & <nl> ( RoleFitness ( SERVER_KNOBS - > EXPECTED_TLOG_FITNESS , req . configuration . getDesiredLogs ( ) , ProcessClass : : TLog ) . betterCount ( RoleFitness ( tlogs , ProcessClass : : TLog ) ) | | <nl> ( region . satelliteTLogReplicationFactor > 0 & & RoleFitness ( SERVER_KNOBS - > EXPECTED_TLOG_FITNESS , req . configuration . getDesiredSatelliteLogs ( dcId ) , ProcessClass : : TLog ) . betterCount ( RoleFitness ( satelliteLogs , ProcessClass : : TLog ) ) ) | | <nl> RoleFitness ( SERVER_KNOBS - > EXPECTED_PROXY_FITNESS , req . configuration . getDesiredProxies ( ) , ProcessClass : : Proxy ) . betterCount ( RoleFitness ( proxies , ProcessClass : : Proxy ) ) | | <nl> class ClusterControllerData { <nl> } <nl> throw no_more_servers ( ) ; <nl> } catch ( Error & e ) { <nl> - if ( now ( ) - startTime < SERVER_KNOBS - > WAIT_FOR_GOOD_REMOTE_RECRUITMENT_DELAY & & regions [ 1 ] . dcId ! = clusterControllerDcId . get ( ) ) { <nl> + if ( ! goodRemoteRecruitmentTime . isReady ( ) & & regions [ 1 ] . dcId ! = clusterControllerDcId . get ( ) ) { <nl> throw operation_failed ( ) ; <nl> } <nl> <nl> class ClusterControllerData { <nl> . detail ( " DesiredProxies " , req . configuration . getDesiredProxies ( ) ) . detail ( " ActualProxies " , result . proxies . size ( ) ) <nl> . detail ( " DesiredResolvers " , req . configuration . getDesiredResolvers ( ) ) . detail ( " ActualResolvers " , result . resolvers . size ( ) ) ; <nl> <nl> - if ( now ( ) - startTime < SERVER_KNOBS - > WAIT_FOR_GOOD_RECRUITMENT_DELAY & & <nl> + if ( ! goodRecruitmentTime . isReady ( ) & & <nl> ( RoleFitness ( SERVER_KNOBS - > EXPECTED_TLOG_FITNESS , req . configuration . getDesiredLogs ( ) , ProcessClass : : TLog ) . betterCount ( RoleFitness ( tlogs , ProcessClass : : TLog ) ) | | <nl> RoleFitness ( SERVER_KNOBS - > EXPECTED_PROXY_FITNESS , req . configuration . getDesiredProxies ( ) , ProcessClass : : Proxy ) . betterCount ( bestFitness . proxy ) | | <nl> RoleFitness ( SERVER_KNOBS - > EXPECTED_RESOLVER_FITNESS , req . configuration . getDesiredResolvers ( ) , ProcessClass : : Resolver ) . betterCount ( bestFitness . resolver ) ) ) { <nl> class ClusterControllerData { <nl> ActorCollection ac ; <nl> UpdateWorkerList updateWorkerList ; <nl> Future < Void > outstandingRequestChecker ; <nl> + Future < Void > outstandingRemoteRequestChecker ; <nl> <nl> DBInfo db ; <nl> Database cx ; <nl> double startTime ; <nl> - Optional < double > remoteStartTime ; <nl> + Future < Void > goodRecruitmentTime ; <nl> + Future < Void > goodRemoteRecruitmentTime ; <nl> Version datacenterVersionDifference ; <nl> PromiseStream < Future < Void > > addActor ; <nl> bool versionDifferenceUpdated ; <nl> class ClusterControllerData { <nl> <nl> ClusterControllerData ( ClusterControllerFullInterface const & ccInterface , LocalityData const & locality ) <nl> : clusterControllerProcessId ( locality . processId ( ) ) , clusterControllerDcId ( locality . dcId ( ) ) , <nl> - id ( ccInterface . id ( ) ) , ac ( false ) , outstandingRequestChecker ( Void ( ) ) , gotProcessClasses ( false ) , <nl> - gotFullyRecoveredConfig ( false ) , startTime ( now ( ) ) , datacenterVersionDifference ( 0 ) , <nl> + id ( ccInterface . id ( ) ) , ac ( false ) , outstandingRequestChecker ( Void ( ) ) , outstandingRemoteRequestChecker ( Void ( ) ) , gotProcessClasses ( false ) , <nl> + gotFullyRecoveredConfig ( false ) , startTime ( now ( ) ) , goodRecruitmentTime ( Never ( ) ) , <nl> + goodRemoteRecruitmentTime ( Never ( ) ) , datacenterVersionDifference ( 0 ) , <nl> versionDifferenceUpdated ( false ) , recruitingDistributor ( false ) , recruitRatekeeper ( false ) , <nl> clusterControllerMetrics ( " ClusterController " , id . toString ( ) ) , <nl> openDatabaseRequests ( " OpenDatabaseRequests " , clusterControllerMetrics ) , <nl> ACTOR Future < Void > clusterWatchDatabase ( ClusterControllerData * cluster , Cluster <nl> id_used [ cluster - > clusterControllerProcessId ] + + ; <nl> state WorkerFitnessInfo masterWorker = cluster - > getWorkerForRoleInDatacenter ( cluster - > clusterControllerDcId , ProcessClass : : Master , ProcessClass : : NeverAssign , db - > config , id_used ) ; <nl> if ( ( masterWorker . worker . processClass . machineClassFitness ( ProcessClass : : Master ) > SERVER_KNOBS - > EXPECTED_MASTER_FITNESS | | masterWorker . worker . interf . locality . processId ( ) = = cluster - > clusterControllerProcessId ) <nl> - & & now ( ) - cluster - > startTime < SERVER_KNOBS - > WAIT_FOR_GOOD_RECRUITMENT_DELAY ) { <nl> + & & ! cluster - > goodRecruitmentTime . isReady ( ) ) { <nl> TraceEvent ( " CCWDB " , cluster - > id ) . detail ( " Fitness " , masterWorker . worker . processClass . machineClassFitness ( ProcessClass : : Master ) ) ; <nl> wait ( delay ( SERVER_KNOBS - > ATTEMPT_RECRUITMENT_DELAY ) ) ; <nl> continue ; <nl> void checkBetterDDOrRK ( ClusterControllerData * self ) { <nl> ACTOR Future < Void > doCheckOutstandingRequests ( ClusterControllerData * self ) { <nl> try { <nl> wait ( delay ( SERVER_KNOBS - > CHECK_OUTSTANDING_INTERVAL ) ) ; <nl> + while ( ! self - > goodRecruitmentTime . isReady ( ) ) { <nl> + wait ( self - > goodRecruitmentTime ) ; <nl> + } <nl> <nl> checkOutstandingRecruitmentRequests ( self ) ; <nl> - checkOutstandingRemoteRecruitmentRequests ( self ) ; <nl> checkOutstandingStorageRequests ( self ) ; <nl> checkBetterDDOrRK ( self ) ; <nl> <nl> ACTOR Future < Void > doCheckOutstandingRequests ( ClusterControllerData * self ) { <nl> TraceEvent ( " MasterRegistrationKill " , self - > id ) . detail ( " MasterId " , self - > db . serverInfo - > get ( ) . read ( ) . master . id ( ) ) ; <nl> } <nl> } catch ( Error & e ) { <nl> - if ( e . code ( ) ! = error_code_operation_failed & & e . code ( ) ! = error_code_no_more_servers ) { <nl> + if ( e . code ( ) ! = error_code_no_more_servers ) { <nl> + TraceEvent ( SevError , " CheckOutstandingError " ) . error ( e ) ; <nl> + } <nl> + } <nl> + return Void ( ) ; <nl> + } <nl> + <nl> + ACTOR Future < Void > doCheckOutstandingRemoteRequests ( ClusterControllerData * self ) { <nl> + try { <nl> + wait ( delay ( SERVER_KNOBS - > CHECK_OUTSTANDING_INTERVAL ) ) ; <nl> + while ( ! self - > goodRemoteRecruitmentTime . isReady ( ) ) { <nl> + wait ( self - > goodRemoteRecruitmentTime ) ; <nl> + } <nl> + <nl> + checkOutstandingRemoteRecruitmentRequests ( self ) ; <nl> + } catch ( Error & e ) { <nl> + if ( e . code ( ) ! = error_code_no_more_servers ) { <nl> TraceEvent ( SevError , " CheckOutstandingError " ) . error ( e ) ; <nl> } <nl> } <nl> ACTOR Future < Void > doCheckOutstandingRequests ( ClusterControllerData * self ) { <nl> } <nl> <nl> void checkOutstandingRequests ( ClusterControllerData * self ) { <nl> - if ( ! self - > outstandingRequestChecker . isReady ( ) ) <nl> - return ; <nl> + if ( self - > outstandingRemoteRequestChecker . isReady ( ) ) { <nl> + self - > outstandingRemoteRequestChecker = doCheckOutstandingRemoteRequests ( self ) ; <nl> + } <nl> <nl> - self - > outstandingRequestChecker = doCheckOutstandingRequests ( self ) ; <nl> + if ( self - > outstandingRequestChecker . isReady ( ) ) { <nl> + self - > outstandingRequestChecker = doCheckOutstandingRequests ( self ) ; <nl> + } <nl> } <nl> <nl> ACTOR Future < Void > rebootAndCheck ( ClusterControllerData * cluster , Optional < Standalone < StringRef > > processID ) { <nl> ACTOR Future < Void > rebootAndCheck ( ClusterControllerData * cluster , Optional < Stan <nl> auto watcher = cluster - > id_worker . find ( processID ) ; <nl> ASSERT ( watcher ! = cluster - > id_worker . end ( ) ) ; <nl> <nl> - watcher - > second . lastAvailableTime = now ( ) ; <nl> watcher - > second . reboots + + ; <nl> wait ( delay ( g_network - > isSimulated ( ) ? SERVER_KNOBS - > SIM_SHUTDOWN_TIMEOUT : SERVER_KNOBS - > SHUTDOWN_TIMEOUT ) ) ; <nl> } <nl> ACTOR Future < Void > clusterRecruitFromConfiguration ( ClusterControllerData * self , <nl> req . reply . send ( rep ) ; <nl> return Void ( ) ; <nl> } catch ( Error & e ) { <nl> - if ( e . code ( ) = = error_code_no_more_servers & & now ( ) - self - > startTime > = SERVER_KNOBS - > WAIT_FOR_GOOD_RECRUITMENT_DELAY ) { <nl> + if ( e . code ( ) = = error_code_no_more_servers & & self - > goodRecruitmentTime . isReady ( ) ) { <nl> self - > outstandingRecruitmentRequests . push_back ( req ) ; <nl> TraceEvent ( SevWarn , " RecruitFromConfigurationNotAvailable " , self - > id ) . error ( e ) ; <nl> return Void ( ) ; <nl> ACTOR Future < Void > clusterRecruitFromConfiguration ( ClusterControllerData * self , <nl> throw ; / / goodbye , cluster controller <nl> } <nl> } <nl> - wait ( delay ( SERVER_KNOBS - > ATTEMPT_RECRUITMENT_DELAY ) ) ; <nl> + wait ( lowPriorityDelay ( SERVER_KNOBS - > ATTEMPT_RECRUITMENT_DELAY ) ) ; <nl> } <nl> } <nl> <nl> ACTOR Future < Void > clusterRecruitRemoteFromConfiguration ( ClusterControllerData * <nl> req . reply . send ( rep ) ; <nl> return Void ( ) ; <nl> } catch ( Error & e ) { <nl> - if ( e . code ( ) = = error_code_no_more_servers & & self - > remoteStartTime . present ( ) & & now ( ) - self - > remoteStartTime . get ( ) > = SERVER_KNOBS - > WAIT_FOR_GOOD_REMOTE_RECRUITMENT_DELAY ) { <nl> + if ( e . code ( ) = = error_code_no_more_servers & & self - > goodRemoteRecruitmentTime . isReady ( ) ) { <nl> self - > outstandingRemoteRecruitmentRequests . push_back ( req ) ; <nl> TraceEvent ( SevWarn , " RecruitRemoteFromConfigurationNotAvailable " , self - > id ) . error ( e ) ; <nl> return Void ( ) ; <nl> ACTOR Future < Void > clusterRecruitRemoteFromConfiguration ( ClusterControllerData * <nl> throw ; / / goodbye , cluster controller <nl> } <nl> } <nl> - wait ( delay ( SERVER_KNOBS - > ATTEMPT_RECRUITMENT_DELAY ) ) ; <nl> + wait ( lowPriorityDelay ( SERVER_KNOBS - > ATTEMPT_RECRUITMENT_DELAY ) ) ; <nl> } <nl> } <nl> <nl> void registerWorker ( RegisterWorkerRequest req , ClusterControllerData * self ) { <nl> <nl> if ( info = = self - > id_worker . end ( ) ) { <nl> TraceEvent ( " ClusterControllerActualWorkers " , self - > id ) . detail ( " WorkerId " , w . id ( ) ) . detail ( " ProcessId " , w . locality . processId ( ) ) . detail ( " ZoneId " , w . locality . zoneId ( ) ) . detail ( " DataHall " , w . locality . dataHallId ( ) ) . detail ( " PClass " , req . processClass . toString ( ) ) . detail ( " Workers " , self - > id_worker . size ( ) ) ; <nl> + self - > goodRecruitmentTime = lowPriorityDelay ( SERVER_KNOBS - > WAIT_FOR_GOOD_RECRUITMENT_DELAY ) ; <nl> + self - > goodRemoteRecruitmentTime = lowPriorityDelay ( SERVER_KNOBS - > WAIT_FOR_GOOD_REMOTE_RECRUITMENT_DELAY ) ; <nl> } else { <nl> TraceEvent ( " ClusterControllerWorkerAlreadyRegistered " , self - > id ) . suppressFor ( 1 . 0 ) . detail ( " WorkerId " , w . id ( ) ) . detail ( " ProcessId " , w . locality . processId ( ) ) . detail ( " ZoneId " , w . locality . zoneId ( ) ) . detail ( " DataHall " , w . locality . dataHallId ( ) ) . detail ( " PClass " , req . processClass . toString ( ) ) . detail ( " Workers " , self - > id_worker . size ( ) ) ; <nl> } <nl> ACTOR Future < DataDistributorInterface > startDataDistributor ( ClusterControllerDa <nl> throw ; <nl> } <nl> } <nl> - wait ( delay ( SERVER_KNOBS - > ATTEMPT_RECRUITMENT_DELAY ) ) ; <nl> + wait ( lowPriorityDelay ( SERVER_KNOBS - > ATTEMPT_RECRUITMENT_DELAY ) ) ; <nl> } <nl> } <nl> <nl> ACTOR Future < Void > startRatekeeper ( ClusterControllerData * self ) { <nl> throw ; <nl> } <nl> } <nl> - wait ( delay ( SERVER_KNOBS - > ATTEMPT_RECRUITMENT_DELAY ) ) ; <nl> + wait ( lowPriorityDelay ( SERVER_KNOBS - > ATTEMPT_RECRUITMENT_DELAY ) ) ; <nl> } <nl> } <nl> <nl> mmm a / fdbserver / Coordination . actor . cpp <nl> ppp b / fdbserver / Coordination . actor . cpp <nl> struct LeaderRegisterCollection { <nl> if ( ! self - > pStore - > exists ( ) ) <nl> return Void ( ) ; <nl> OnDemandStore & store = * self - > pStore ; <nl> - Standalone < VectorRef < KeyValueRef > > forwardingInfo = wait ( store - > readRange ( fwdKeys ) ) ; <nl> + Standalone < RangeResultRef > forwardingInfo = wait ( store - > readRange ( fwdKeys ) ) ; <nl> for ( int i = 0 ; i < forwardingInfo . size ( ) ; i + + ) { <nl> LeaderInfo forwardInfo ; <nl> forwardInfo . forward = true ; <nl> mmm a / fdbserver / CoordinationInterface . h <nl> ppp b / fdbserver / CoordinationInterface . h <nl> struct GenerationRegInterface { <nl> / / If gen > 0 and there was no prior write ( _ , _ , 0 ) or a data loss fault , throws not_created ( ) ? <nl> / / ( gen1 = = gen is considered a " successful " write ) <nl> / / There is some earlier or concurrent read ( key , gen1 ) or write ( key , _ , gen1 ) . ( In the successful case , the concurrent write is this one ) <nl> - <nl> + <nl> / / All instances of the pattern <nl> / / read ( key , g ) = > v1 and write ( key , v2 , g ) = > true <nl> / / thus form a totally ordered sequence of modifications , in which <nl> mmm a / fdbserver / DataDistribution . actor . cpp <nl> ppp b / fdbserver / DataDistribution . actor . cpp <nl> class TCTeamInfo : public ReferenceCounted < TCTeamInfo > , public IDataDistribution <nl> <nl> virtual int64_t getLoadBytes ( bool includeInFlight = true , double inflightPenalty = 1 . 0 ) { <nl> int64_t physicalBytes = getLoadAverage ( ) ; <nl> - double minFreeSpaceRatio = getMinFreeSpaceRatio ( includeInFlight ) ; <nl> + double minAvailableSpaceRatio = getMinAvailableSpaceRatio ( includeInFlight ) ; <nl> int64_t inFlightBytes = includeInFlight ? getDataInFlightToTeam ( ) / servers . size ( ) : 0 ; <nl> - double freeSpaceMultiplier = SERVER_KNOBS - > FREE_SPACE_RATIO_CUTOFF / ( std : : max ( std : : min ( SERVER_KNOBS - > FREE_SPACE_RATIO_CUTOFF , minFreeSpaceRatio ) , 0 . 000001 ) ) ; <nl> + double availableSpaceMultiplier = SERVER_KNOBS - > FREE_SPACE_RATIO_CUTOFF / ( std : : max ( std : : min ( SERVER_KNOBS - > FREE_SPACE_RATIO_CUTOFF , minAvailableSpaceRatio ) , 0 . 000001 ) ) ; <nl> + if ( servers . size ( ) > 2 ) { <nl> + / / make sure in triple replication the penalty is high enough that you will always avoid a team with a member at 20 % free space <nl> + availableSpaceMultiplier = availableSpaceMultiplier * availableSpaceMultiplier ; <nl> + } <nl> <nl> - if ( freeSpaceMultiplier > 1 & & deterministicRandom ( ) - > random01 ( ) < 0 . 001 ) <nl> - TraceEvent ( SevWarn , " DiskNearCapacity " ) . detail ( " FreeSpaceRatio " , minFreeSpaceRatio ) ; <nl> + if ( minAvailableSpaceRatio < SERVER_KNOBS - > TARGET_AVAILABLE_SPACE_RATIO ) { <nl> + TraceEvent ( SevWarn , " DiskNearCapacity " ) . suppressFor ( 1 . 0 ) . detail ( " AvailableSpaceRatio " , minAvailableSpaceRatio ) ; <nl> + } <nl> <nl> - return ( physicalBytes + ( inflightPenalty * inFlightBytes ) ) * freeSpaceMultiplier ; <nl> + return ( physicalBytes + ( inflightPenalty * inFlightBytes ) ) * availableSpaceMultiplier ; <nl> } <nl> <nl> - virtual int64_t getMinFreeSpace ( bool includeInFlight = true ) { <nl> - int64_t minFreeSpace = std : : numeric_limits < int64_t > : : max ( ) ; <nl> + virtual int64_t getMinAvailableSpace ( bool includeInFlight = true ) { <nl> + int64_t minAvailableSpace = std : : numeric_limits < int64_t > : : max ( ) ; <nl> for ( int i = 0 ; i < servers . size ( ) ; i + + ) { <nl> if ( servers [ i ] - > serverMetrics . present ( ) ) { <nl> auto & replyValue = servers [ i ] - > serverMetrics . get ( ) ; <nl> <nl> - ASSERT ( replyValue . free . bytes > = 0 ) ; <nl> + ASSERT ( replyValue . available . bytes > = 0 ) ; <nl> ASSERT ( replyValue . capacity . bytes > = 0 ) ; <nl> <nl> - int64_t bytesFree = replyValue . free . bytes ; <nl> + int64_t bytesAvailable = replyValue . available . bytes ; <nl> if ( includeInFlight ) { <nl> - bytesFree - = servers [ i ] - > dataInFlightToServer ; <nl> + bytesAvailable - = servers [ i ] - > dataInFlightToServer ; <nl> } <nl> <nl> - minFreeSpace = std : : min ( bytesFree , minFreeSpace ) ; <nl> + minAvailableSpace = std : : min ( bytesAvailable , minAvailableSpace ) ; <nl> } <nl> } <nl> <nl> - return minFreeSpace ; / / Could be negative <nl> + return minAvailableSpace ; / / Could be negative <nl> } <nl> <nl> - virtual double getMinFreeSpaceRatio ( bool includeInFlight = true ) { <nl> + virtual double getMinAvailableSpaceRatio ( bool includeInFlight = true ) { <nl> double minRatio = 1 . 0 ; <nl> for ( int i = 0 ; i < servers . size ( ) ; i + + ) { <nl> if ( servers [ i ] - > serverMetrics . present ( ) ) { <nl> auto & replyValue = servers [ i ] - > serverMetrics . get ( ) ; <nl> <nl> - ASSERT ( replyValue . free . bytes > = 0 ) ; <nl> + ASSERT ( replyValue . available . bytes > = 0 ) ; <nl> ASSERT ( replyValue . capacity . bytes > = 0 ) ; <nl> <nl> - int64_t bytesFree = replyValue . free . bytes ; <nl> + int64_t bytesAvailable = replyValue . available . bytes ; <nl> if ( includeInFlight ) { <nl> - bytesFree = std : : max ( ( int64_t ) 0 , bytesFree - servers [ i ] - > dataInFlightToServer ) ; <nl> + bytesAvailable = std : : max ( ( int64_t ) 0 , bytesAvailable - servers [ i ] - > dataInFlightToServer ) ; <nl> } <nl> <nl> if ( replyValue . capacity . bytes = = 0 ) <nl> minRatio = 0 ; <nl> else <nl> - minRatio = std : : min ( minRatio , ( ( double ) bytesFree ) / replyValue . capacity . bytes ) ; <nl> + minRatio = std : : min ( minRatio , ( ( double ) bytesAvailable ) / replyValue . capacity . bytes ) ; <nl> } <nl> } <nl> <nl> return minRatio ; <nl> } <nl> <nl> - virtual bool hasHealthyFreeSpace ( ) { <nl> - return getMinFreeSpaceRatio ( ) > SERVER_KNOBS - > MIN_FREE_SPACE_RATIO & & getMinFreeSpace ( ) > SERVER_KNOBS - > MIN_FREE_SPACE ; <nl> + virtual bool hasHealthyAvailableSpace ( double minRatio ) { <nl> + return getMinAvailableSpaceRatio ( ) > = minRatio & & getMinAvailableSpace ( ) > SERVER_KNOBS - > MIN_AVAILABLE_SPACE ; <nl> } <nl> <nl> virtual Future < Void > updateStorageMetrics ( ) { <nl> struct DDTeamCollection : ReferenceCounted < DDTeamCollection > { <nl> std : : vector < DDTeamCollection * > teamCollections ; <nl> AsyncVar < Optional < Key > > healthyZone ; <nl> Future < bool > clearHealthyZoneFuture ; <nl> + double medianAvailableSpace ; <nl> + double lastMedianAvailableSpaceUpdate ; <nl> / / clang - format on <nl> <nl> void resetLocalitySet ( ) { <nl> struct DDTeamCollection : ReferenceCounted < DDTeamCollection > { <nl> initializationDoneActor ( logOnCompletion ( readyToStart & & initialFailureReactionDelay , this ) ) , <nl> optimalTeamCount ( 0 ) , recruitingStream ( 0 ) , restartRecruiting ( SERVER_KNOBS - > DEBOUNCE_RECRUITING_DELAY ) , <nl> unhealthyServers ( 0 ) , includedDCs ( includedDCs ) , otherTrackedDCs ( otherTrackedDCs ) , <nl> - zeroHealthyTeams ( zeroHealthyTeams ) , zeroOptimalTeams ( true ) , primary ( primary ) , <nl> - processingUnhealthy ( processingUnhealthy ) { <nl> + zeroHealthyTeams ( zeroHealthyTeams ) , zeroOptimalTeams ( true ) , primary ( primary ) , medianAvailableSpace ( SERVER_KNOBS - > MIN_AVAILABLE_SPACE_RATIO ) , <nl> + lastMedianAvailableSpaceUpdate ( 0 ) , processingUnhealthy ( processingUnhealthy ) { <nl> if ( ! primary | | configuration . usableRegions = = 1 ) { <nl> TraceEvent ( " DDTrackerStarting " , distributorId ) <nl> . detail ( " State " , " Inactive " ) <nl> struct DDTeamCollection : ReferenceCounted < DDTeamCollection > { <nl> ACTOR static Future < Void > getTeam ( DDTeamCollection * self , GetTeamRequest req ) { <nl> try { <nl> wait ( self - > checkBuildTeams ( self ) ) ; <nl> + if ( now ( ) - self - > lastMedianAvailableSpaceUpdate > SERVER_KNOBS - > AVAILABLE_SPACE_UPDATE_DELAY ) { <nl> + self - > lastMedianAvailableSpaceUpdate = now ( ) ; <nl> + std : : vector < double > teamAvailableSpace ; <nl> + teamAvailableSpace . reserve ( self - > teams . size ( ) ) ; <nl> + for ( int i = 0 ; i < self - > teams . size ( ) ; i + + ) { <nl> + if ( self - > teams [ i ] - > isHealthy ( ) ) { <nl> + teamAvailableSpace . push_back ( self - > teams [ i ] - > getMinAvailableSpaceRatio ( ) ) ; <nl> + } <nl> + } <nl> + <nl> + size_t pivot = teamAvailableSpace . size ( ) / 2 ; <nl> + if ( teamAvailableSpace . size ( ) > 1 ) { <nl> + std : : nth_element ( teamAvailableSpace . begin ( ) , teamAvailableSpace . begin ( ) + pivot , teamAvailableSpace . end ( ) ) ; <nl> + self - > medianAvailableSpace = std : : max ( SERVER_KNOBS - > MIN_AVAILABLE_SPACE_RATIO , std : : min ( SERVER_KNOBS - > TARGET_AVAILABLE_SPACE_RATIO , teamAvailableSpace [ pivot ] ) ) ; <nl> + } else { <nl> + self - > medianAvailableSpace = SERVER_KNOBS - > MIN_AVAILABLE_SPACE_RATIO ; <nl> + } <nl> + } <nl> <nl> / / Select the best team <nl> / / Currently the metric is minimum used disk space ( adjusted for data in flight ) <nl> struct DDTeamCollection : ReferenceCounted < DDTeamCollection > { <nl> std : : vector < Reference < IDataDistributionTeam > > randomTeams ; <nl> const std : : set < UID > completeSources ( req . completeSources . begin ( ) , req . completeSources . end ( ) ) ; <nl> <nl> + / / Note : this block does not apply any filters from the request <nl> if ( ! req . wantsNewServers ) { <nl> for ( int i = 0 ; i < req . completeSources . size ( ) ; i + + ) { <nl> if ( ! self - > server_info . count ( req . completeSources [ i ] ) ) { <nl> struct DDTeamCollection : ReferenceCounted < DDTeamCollection > { <nl> if ( req . wantsTrueBest ) { <nl> ASSERT ( ! bestOption . present ( ) ) ; <nl> for ( int i = 0 ; i < self - > teams . size ( ) ; i + + ) { <nl> - if ( self - > teams [ i ] - > isHealthy ( ) & & ( ! req . preferLowerUtilization | | self - > teams [ i ] - > hasHealthyFreeSpace ( ) ) ) { <nl> + if ( self - > teams [ i ] - > isHealthy ( ) & & <nl> + ( ! req . preferLowerUtilization | | self - > teams [ i ] - > hasHealthyAvailableSpace ( self - > medianAvailableSpace ) ) & & <nl> + ( ! req . teamMustHaveShards | | self - > shardsAffectedByTeamFailure - > getShardsFor ( ShardsAffectedByTeamFailure : : Team ( self - > teams [ i ] - > getServerIDs ( ) , self - > primary ) ) . size ( ) > 0 ) ) <nl> + { <nl> int64_t loadBytes = self - > teams [ i ] - > getLoadBytes ( true , req . inflightPenalty ) ; <nl> if ( ! bestOption . present ( ) | | ( req . preferLowerUtilization & & loadBytes < bestLoadBytes ) | | ( ! req . preferLowerUtilization & & loadBytes > bestLoadBytes ) ) { <nl> bestLoadBytes = loadBytes ; <nl> struct DDTeamCollection : ReferenceCounted < DDTeamCollection > { <nl> / / If unhealthy team is majority , we may not find an ok dest in this while loop <nl> Reference < IDataDistributionTeam > dest = deterministicRandom ( ) - > randomChoice ( self - > teams ) ; <nl> <nl> - bool ok = dest - > isHealthy ( ) & & ( ! req . preferLowerUtilization | | dest - > hasHealthyFreeSpace ( ) ) ; <nl> + bool ok = dest - > isHealthy ( ) & & <nl> + ( ! req . preferLowerUtilization | | dest - > hasHealthyAvailableSpace ( self - > medianAvailableSpace ) ) & & <nl> + ( ! req . teamMustHaveShards | | self - > shardsAffectedByTeamFailure - > getShardsFor ( ShardsAffectedByTeamFailure : : Team ( dest - > getServerIDs ( ) , self - > primary ) ) . size ( ) > 0 ) ; <nl> + <nl> for ( int i = 0 ; ok & & i < randomTeams . size ( ) ; i + + ) { <nl> if ( randomTeams [ i ] - > getServerIDs ( ) = = dest - > getServerIDs ( ) ) { <nl> ok = false ; <nl> struct DDTeamCollection : ReferenceCounted < DDTeamCollection > { <nl> <nl> / / Note : req . completeSources can be empty and all servers ( and server teams ) can be unhealthy . <nl> / / We will get stuck at this ! This only happens when a DC fails . No need to consider it right now . <nl> + / / Note : this block does not apply any filters from the request <nl> if ( ! bestOption . present ( ) & & self - > zeroHealthyTeams - > get ( ) ) { <nl> / / Attempt to find the unhealthy source server team and return it <nl> for ( int i = 0 ; i < req . completeSources . size ( ) ; i + + ) { <nl> struct DDTeamCollection : ReferenceCounted < DDTeamCollection > { <nl> TraceEvent ( " ServerTeamInfo " , distributorId ) <nl> . detail ( " TeamIndex " , i + + ) <nl> . detail ( " Healthy " , team - > isHealthy ( ) ) <nl> - . detail ( " HasHealthyFreeSpace " , team - > hasHealthyFreeSpace ( ) ) <nl> . detail ( " TeamSize " , team - > size ( ) ) <nl> . detail ( " MemberIDs " , team - > getServerIDsStr ( ) ) ; <nl> } <nl> mmm a / fdbserver / DataDistribution . actor . h <nl> ppp b / fdbserver / DataDistribution . actor . h <nl> struct IDataDistributionTeam { <nl> virtual void addDataInFlightToTeam ( int64_t delta ) = 0 ; <nl> virtual int64_t getDataInFlightToTeam ( ) = 0 ; <nl> virtual int64_t getLoadBytes ( bool includeInFlight = true , double inflightPenalty = 1 . 0 ) = 0 ; <nl> - virtual int64_t getMinFreeSpace ( bool includeInFlight = true ) = 0 ; <nl> - virtual double getMinFreeSpaceRatio ( bool includeInFlight = true ) = 0 ; <nl> - virtual bool hasHealthyFreeSpace ( ) = 0 ; <nl> + virtual int64_t getMinAvailableSpace ( bool includeInFlight = true ) = 0 ; <nl> + virtual double getMinAvailableSpaceRatio ( bool includeInFlight = true ) = 0 ; <nl> + virtual bool hasHealthyAvailableSpace ( double minRatio ) = 0 ; <nl> virtual Future < Void > updateStorageMetrics ( ) = 0 ; <nl> virtual void addref ( ) = 0 ; <nl> virtual void delref ( ) = 0 ; <nl> struct GetTeamRequest { <nl> bool wantsNewServers ; <nl> bool wantsTrueBest ; <nl> bool preferLowerUtilization ; <nl> + bool teamMustHaveShards ; <nl> double inflightPenalty ; <nl> std : : vector < UID > completeSources ; <nl> Promise < Optional < Reference < IDataDistributionTeam > > > reply ; <nl> <nl> GetTeamRequest ( ) { } <nl> - GetTeamRequest ( bool wantsNewServers , bool wantsTrueBest , bool preferLowerUtilization , double inflightPenalty = 1 . 0 ) : wantsNewServers ( wantsNewServers ) , wantsTrueBest ( wantsTrueBest ) , preferLowerUtilization ( preferLowerUtilization ) , inflightPenalty ( inflightPenalty ) { } <nl> - <nl> + GetTeamRequest ( bool wantsNewServers , bool wantsTrueBest , bool preferLowerUtilization , bool teamMustHaveShards , double inflightPenalty = 1 . 0 ) <nl> + : wantsNewServers ( wantsNewServers ) , wantsTrueBest ( wantsTrueBest ) , preferLowerUtilization ( preferLowerUtilization ) , teamMustHaveShards ( teamMustHaveShards ) , inflightPenalty ( inflightPenalty ) { } <nl> + <nl> std : : string getDesc ( ) { <nl> std : : stringstream ss ; <nl> <nl> ss < < " WantsNewServers : " < < wantsNewServers < < " WantsTrueBest : " < < wantsTrueBest <nl> - < < " PreferLowerUtilization : " < < preferLowerUtilization < < " inflightPenalty : " < < inflightPenalty < < " ; " ; <nl> + < < " PreferLowerUtilization : " < < preferLowerUtilization <nl> + < < " teamMustHaveShards : " < < teamMustHaveShards <nl> + < < " inflightPenalty : " < < inflightPenalty < < " ; " ; <nl> ss < < " CompleteSources : " ; <nl> for ( auto & cs : completeSources ) { <nl> ss < < cs . toString ( ) < < " , " ; <nl> mmm a / fdbserver / DataDistributionQueue . actor . cpp <nl> ppp b / fdbserver / DataDistributionQueue . actor . cpp <nl> class ParallelTCInfo : public ReferenceCounted < ParallelTCInfo > , public IDataDist <nl> } ) ; <nl> } <nl> <nl> - virtual int64_t getMinFreeSpace ( bool includeInFlight = true ) { <nl> + virtual int64_t getMinAvailableSpace ( bool includeInFlight = true ) { <nl> int64_t result = std : : numeric_limits < int64_t > : : max ( ) ; <nl> for ( auto it = teams . begin ( ) ; it ! = teams . end ( ) ; it + + ) { <nl> - result = std : : min ( result , ( * it ) - > getMinFreeSpace ( includeInFlight ) ) ; <nl> + result = std : : min ( result , ( * it ) - > getMinAvailableSpace ( includeInFlight ) ) ; <nl> } <nl> return result ; <nl> } <nl> <nl> - virtual double getMinFreeSpaceRatio ( bool includeInFlight = true ) { <nl> + virtual double getMinAvailableSpaceRatio ( bool includeInFlight = true ) { <nl> double result = std : : numeric_limits < double > : : max ( ) ; <nl> for ( auto it = teams . begin ( ) ; it ! = teams . end ( ) ; it + + ) { <nl> - result = std : : min ( result , ( * it ) - > getMinFreeSpaceRatio ( includeInFlight ) ) ; <nl> + result = std : : min ( result , ( * it ) - > getMinAvailableSpaceRatio ( includeInFlight ) ) ; <nl> } <nl> return result ; <nl> } <nl> <nl> - virtual bool hasHealthyFreeSpace ( ) { <nl> - return all ( [ ] ( Reference < IDataDistributionTeam > team ) { <nl> - return team - > hasHealthyFreeSpace ( ) ; <nl> + virtual bool hasHealthyAvailableSpace ( double minRatio ) { <nl> + return all ( [ minRatio ] ( Reference < IDataDistributionTeam > team ) { <nl> + return team - > hasHealthyAvailableSpace ( minRatio ) ; <nl> } ) ; <nl> } <nl> <nl> ACTOR Future < Void > dataDistributionRelocator ( DDQueueData * self , RelocateData rd <nl> if ( rd . healthPriority = = SERVER_KNOBS - > PRIORITY_TEAM_UNHEALTHY | | rd . healthPriority = = SERVER_KNOBS - > PRIORITY_TEAM_2_LEFT ) inflightPenalty = SERVER_KNOBS - > INFLIGHT_PENALTY_UNHEALTHY ; <nl> if ( rd . healthPriority = = SERVER_KNOBS - > PRIORITY_TEAM_1_LEFT | | rd . healthPriority = = SERVER_KNOBS - > PRIORITY_TEAM_0_LEFT ) inflightPenalty = SERVER_KNOBS - > INFLIGHT_PENALTY_ONE_LEFT ; <nl> <nl> - auto req = GetTeamRequest ( rd . wantsNewServers , rd . priority = = SERVER_KNOBS - > PRIORITY_REBALANCE_UNDERUTILIZED_TEAM , true , inflightPenalty ) ; <nl> + auto req = GetTeamRequest ( rd . wantsNewServers , rd . priority = = SERVER_KNOBS - > PRIORITY_REBALANCE_UNDERUTILIZED_TEAM , true , false , inflightPenalty ) ; <nl> req . completeSources = rd . completeSources ; <nl> Optional < Reference < IDataDistributionTeam > > bestTeam = wait ( brokenPromiseToNever ( self - > teamCollections [ tciIndex ] . getTeam . getReply ( req ) ) ) ; <nl> / / If a DC has no healthy team , we stop checking the other DCs until <nl> ACTOR Future < Void > dataDistributionRelocator ( DDQueueData * self , RelocateData rd <nl> } <nl> <nl> / / Move a random shard of sourceTeam ' s to destTeam if sourceTeam has much more data than destTeam <nl> - ACTOR Future < bool > rebalanceTeams ( DDQueueData * self , int priority , Reference < IDataDistributionTeam > sourceTeam , Reference < IDataDistributionTeam > destTeam , bool primary ) { <nl> + ACTOR Future < bool > rebalanceTeams ( DDQueueData * self , int priority , Reference < IDataDistributionTeam > sourceTeam , <nl> + Reference < IDataDistributionTeam > destTeam , bool primary , TraceEvent * traceEvent ) { <nl> if ( g_network - > isSimulated ( ) & & g_simulator . speedUpSimulation ) { <nl> + traceEvent - > detail ( " CancelingDueToSimulationSpeedup " , true ) ; <nl> return false ; <nl> } <nl> <nl> ACTOR Future < bool > rebalanceTeams ( DDQueueData * self , int priority , Reference < ID <nl> state int64_t averageShardBytes = wait ( req . getFuture ( ) ) ; <nl> state std : : vector < KeyRange > shards = self - > shardsAffectedByTeamFailure - > getShardsFor ( ShardsAffectedByTeamFailure : : Team ( sourceTeam - > getServerIDs ( ) , primary ) ) ; <nl> <nl> + traceEvent - > detail ( " AverageShardBytes " , averageShardBytes ) <nl> + . detail ( " ShardsInSource " , shards . size ( ) ) ; <nl> + <nl> if ( ! shards . size ( ) ) <nl> return false ; <nl> <nl> ACTOR Future < bool > rebalanceTeams ( DDQueueData * self , int priority , Reference < ID <nl> <nl> int64_t sourceBytes = sourceTeam - > getLoadBytes ( false ) ; <nl> int64_t destBytes = destTeam - > getLoadBytes ( ) ; <nl> - if ( sourceBytes - destBytes < = 3 * std : : max < int64_t > ( SERVER_KNOBS - > MIN_SHARD_BYTES , metrics . bytes ) | | metrics . bytes = = 0 ) <nl> + <nl> + bool sourceAndDestTooSimilar = sourceBytes - destBytes < = 3 * std : : max < int64_t > ( SERVER_KNOBS - > MIN_SHARD_BYTES , metrics . bytes ) ; <nl> + traceEvent - > detail ( " SourceBytes " , sourceBytes ) <nl> + . detail ( " DestBytes " , destBytes ) <nl> + . detail ( " ShardBytes " , metrics . bytes ) <nl> + . detail ( " SourceAndDestTooSimilar " , sourceAndDestTooSimilar ) ; <nl> + <nl> + if ( sourceAndDestTooSimilar | | metrics . bytes = = 0 ) { <nl> return false ; <nl> + } <nl> <nl> - { <nl> - / / verify the shard is still in sabtf <nl> - std : : vector < KeyRange > shards = self - > shardsAffectedByTeamFailure - > getShardsFor ( ShardsAffectedByTeamFailure : : Team ( sourceTeam - > getServerIDs ( ) , primary ) ) ; <nl> - for ( int i = 0 ; i < shards . size ( ) ; i + + ) { <nl> - if ( moveShard = = shards [ i ] ) { <nl> - TraceEvent ( priority = = SERVER_KNOBS - > PRIORITY_REBALANCE_OVERUTILIZED_TEAM ? " BgDDMountainChopper " : " BgDDValleyFiller " , self - > distributorId ) <nl> - . detail ( " SourceBytes " , sourceBytes ) <nl> - . detail ( " DestBytes " , destBytes ) <nl> - . detail ( " ShardBytes " , metrics . bytes ) <nl> - . detail ( " AverageShardBytes " , averageShardBytes ) <nl> - . detail ( " SourceTeam " , sourceTeam - > getDesc ( ) ) <nl> - . detail ( " DestTeam " , destTeam - > getDesc ( ) ) ; <nl> - <nl> - self - > output . send ( RelocateShard ( moveShard , priority ) ) ; <nl> - return true ; <nl> - } <nl> + / / verify the shard is still in sabtf <nl> + shards = self - > shardsAffectedByTeamFailure - > getShardsFor ( ShardsAffectedByTeamFailure : : Team ( sourceTeam - > getServerIDs ( ) , primary ) ) ; <nl> + for ( int i = 0 ; i < shards . size ( ) ; i + + ) { <nl> + if ( moveShard = = shards [ i ] ) { <nl> + traceEvent - > detail ( " ShardStillPresent " , true ) ; <nl> + self - > output . send ( RelocateShard ( moveShard , priority ) ) ; <nl> + return true ; <nl> } <nl> } <nl> <nl> + traceEvent - > detail ( " ShardStillPresent " , false ) ; <nl> return false ; <nl> } <nl> <nl> ACTOR Future < Void > BgDDMountainChopper ( DDQueueData * self , int teamCollectionInd <nl> state double lastRead = 0 ; <nl> state bool skipCurrentLoop = false ; <nl> loop { <nl> + state bool moved = false ; <nl> + state TraceEvent traceEvent ( " BgDDMountainChopper " , self - > distributorId ) ; <nl> + traceEvent . suppressFor ( 5 . 0 ) <nl> + . detail ( " PollingInterval " , rebalancePollingInterval ) ; <nl> + <nl> + if ( * self - > lastLimited > 0 ) { <nl> + traceEvent . detail ( " SecondsSinceLastLimited " , now ( ) - * self - > lastLimited ) ; <nl> + } <nl> + <nl> try { <nl> state Future < Void > delayF = delay ( rebalancePollingInterval , TaskPriority : : DataDistributionLaunch ) ; <nl> if ( ( now ( ) - lastRead ) > SERVER_KNOBS - > BG_REBALANCE_SWITCH_CHECK_INTERVAL ) { <nl> ACTOR Future < Void > BgDDMountainChopper ( DDQueueData * self , int teamCollectionInd <nl> } <nl> skipCurrentLoop = val . present ( ) ; <nl> } <nl> + <nl> + traceEvent . detail ( " Enabled " , ! skipCurrentLoop ) ; <nl> + <nl> wait ( delayF ) ; <nl> if ( skipCurrentLoop ) { <nl> / / set loop interval to avoid busy wait here . <nl> ACTOR Future < Void > BgDDMountainChopper ( DDQueueData * self , int teamCollectionInd <nl> std : : max ( rebalancePollingInterval , SERVER_KNOBS - > BG_REBALANCE_SWITCH_CHECK_INTERVAL ) ; <nl> continue ; <nl> } <nl> + <nl> + traceEvent . detail ( " QueuedRelocations " , self - > priority_relocations [ SERVER_KNOBS - > PRIORITY_REBALANCE_OVERUTILIZED_TEAM ] ) ; <nl> if ( self - > priority_relocations [ SERVER_KNOBS - > PRIORITY_REBALANCE_OVERUTILIZED_TEAM ] < <nl> SERVER_KNOBS - > DD_REBALANCE_PARALLELISM ) { <nl> state Optional < Reference < IDataDistributionTeam > > randomTeam = wait ( brokenPromiseToNever ( <nl> - self - > teamCollections [ teamCollectionIndex ] . getTeam . getReply ( GetTeamRequest ( true , false , true ) ) ) ) ; <nl> + self - > teamCollections [ teamCollectionIndex ] . getTeam . getReply ( GetTeamRequest ( true , false , true , false ) ) ) ) ; <nl> + <nl> + traceEvent . detail ( " DestTeam " , printable ( randomTeam . map < std : : string > ( [ ] ( const Reference < IDataDistributionTeam > & team ) { <nl> + return team - > getDesc ( ) ; <nl> + } ) ) ) ; <nl> + <nl> if ( randomTeam . present ( ) ) { <nl> - / / Destination team must be healthy and have healthyFreeSpace , otherwise , BestTeamStuck may occur <nl> - if ( randomTeam . get ( ) - > getMinFreeSpaceRatio ( ) > SERVER_KNOBS - > FREE_SPACE_RATIO_DD_CUTOFF & & <nl> - randomTeam . get ( ) - > hasHealthyFreeSpace ( ) ) { <nl> - state Optional < Reference < IDataDistributionTeam > > loadedTeam = <nl> - wait ( brokenPromiseToNever ( self - > teamCollections [ teamCollectionIndex ] . getTeam . getReply ( <nl> - GetTeamRequest ( true , true , false ) ) ) ) ; <nl> - if ( loadedTeam . present ( ) ) { <nl> - bool moved = <nl> - wait ( rebalanceTeams ( self , SERVER_KNOBS - > PRIORITY_REBALANCE_OVERUTILIZED_TEAM , loadedTeam . get ( ) , <nl> - randomTeam . get ( ) , teamCollectionIndex = = 0 ) ) ; <nl> - if ( moved ) { <nl> - resetCount = 0 ; <nl> - } else { <nl> - resetCount + + ; <nl> - } <nl> + state Optional < Reference < IDataDistributionTeam > > loadedTeam = <nl> + wait ( brokenPromiseToNever ( self - > teamCollections [ teamCollectionIndex ] . getTeam . getReply ( <nl> + GetTeamRequest ( true , true , false , true ) ) ) ) ; <nl> + <nl> + traceEvent . detail ( " SourceTeam " , printable ( loadedTeam . map < std : : string > ( [ ] ( const Reference < IDataDistributionTeam > & team ) { <nl> + return team - > getDesc ( ) ; <nl> + } ) ) ) ; <nl> + <nl> + if ( loadedTeam . present ( ) ) { <nl> + bool _moved = <nl> + wait ( rebalanceTeams ( self , SERVER_KNOBS - > PRIORITY_REBALANCE_OVERUTILIZED_TEAM , loadedTeam . get ( ) , <nl> + randomTeam . get ( ) , teamCollectionIndex = = 0 , & traceEvent ) ) ; <nl> + moved = _moved ; <nl> + if ( moved ) { <nl> + resetCount = 0 ; <nl> + } else { <nl> + resetCount + + ; <nl> } <nl> } <nl> } <nl> ACTOR Future < Void > BgDDMountainChopper ( DDQueueData * self , int teamCollectionInd <nl> rebalancePollingInterval = SERVER_KNOBS - > BG_REBALANCE_POLLING_INTERVAL ; <nl> resetCount = SERVER_KNOBS - > DD_REBALANCE_RESET_AMOUNT ; <nl> } <nl> + <nl> + traceEvent . detail ( " ResetCount " , resetCount ) ; <nl> tr . reset ( ) ; <nl> } catch ( Error & e ) { <nl> + traceEvent . error ( e , true ) ; / / Log actor_cancelled because it ' s not legal to suppress an event that ' s initialized <nl> wait ( tr . onError ( e ) ) ; <nl> } <nl> + <nl> + traceEvent . detail ( " Moved " , moved ) ; <nl> + traceEvent . log ( ) ; <nl> } <nl> } <nl> <nl> ACTOR Future < Void > BgDDValleyFiller ( DDQueueData * self , int teamCollectionIndex ) <nl> state double lastRead = 0 ; <nl> state bool skipCurrentLoop = false ; <nl> loop { <nl> + state bool moved = false ; <nl> + state TraceEvent traceEvent ( " BgDDValleyFiller " , self - > distributorId ) ; <nl> + traceEvent . suppressFor ( 5 . 0 ) <nl> + . detail ( " PollingInterval " , rebalancePollingInterval ) ; <nl> + <nl> + if ( * self - > lastLimited > 0 ) { <nl> + traceEvent . detail ( " SecondsSinceLastLimited " , now ( ) - * self - > lastLimited ) ; <nl> + } <nl> + <nl> try { <nl> state Future < Void > delayF = delay ( rebalancePollingInterval , TaskPriority : : DataDistributionLaunch ) ; <nl> if ( ( now ( ) - lastRead ) > SERVER_KNOBS - > BG_REBALANCE_SWITCH_CHECK_INTERVAL ) { <nl> ACTOR Future < Void > BgDDValleyFiller ( DDQueueData * self , int teamCollectionIndex ) <nl> } <nl> skipCurrentLoop = val . present ( ) ; <nl> } <nl> + <nl> + traceEvent . detail ( " Enabled " , ! skipCurrentLoop ) ; <nl> + <nl> wait ( delayF ) ; <nl> if ( skipCurrentLoop ) { <nl> / / set loop interval to avoid busy wait here . <nl> ACTOR Future < Void > BgDDValleyFiller ( DDQueueData * self , int teamCollectionIndex ) <nl> std : : max ( rebalancePollingInterval , SERVER_KNOBS - > BG_REBALANCE_SWITCH_CHECK_INTERVAL ) ; <nl> continue ; <nl> } <nl> + <nl> + traceEvent . detail ( " QueuedRelocations " , self - > priority_relocations [ SERVER_KNOBS - > PRIORITY_REBALANCE_UNDERUTILIZED_TEAM ] ) ; <nl> if ( self - > priority_relocations [ SERVER_KNOBS - > PRIORITY_REBALANCE_UNDERUTILIZED_TEAM ] < <nl> SERVER_KNOBS - > DD_REBALANCE_PARALLELISM ) { <nl> state Optional < Reference < IDataDistributionTeam > > randomTeam = wait ( brokenPromiseToNever ( <nl> - self - > teamCollections [ teamCollectionIndex ] . getTeam . getReply ( GetTeamRequest ( true , false , false ) ) ) ) ; <nl> + self - > teamCollections [ teamCollectionIndex ] . getTeam . getReply ( GetTeamRequest ( true , false , false , true ) ) ) ) ; <nl> + <nl> + traceEvent . detail ( " SourceTeam " , printable ( randomTeam . map < std : : string > ( [ ] ( const Reference < IDataDistributionTeam > & team ) { <nl> + return team - > getDesc ( ) ; <nl> + } ) ) ) ; <nl> + <nl> if ( randomTeam . present ( ) ) { <nl> state Optional < Reference < IDataDistributionTeam > > unloadedTeam = wait ( brokenPromiseToNever ( <nl> - self - > teamCollections [ teamCollectionIndex ] . getTeam . getReply ( GetTeamRequest ( true , true , true ) ) ) ) ; <nl> + self - > teamCollections [ teamCollectionIndex ] . getTeam . getReply ( GetTeamRequest ( true , true , true , false ) ) ) ) ; <nl> + <nl> + traceEvent . detail ( " DestTeam " , printable ( unloadedTeam . map < std : : string > ( [ ] ( const Reference < IDataDistributionTeam > & team ) { <nl> + return team - > getDesc ( ) ; <nl> + } ) ) ) ; <nl> + <nl> if ( unloadedTeam . present ( ) ) { <nl> - / / Destination team must be healthy and healthyFreeSpace , otherwise , BestTeamStuck may occur <nl> - if ( unloadedTeam . get ( ) - > getMinFreeSpaceRatio ( ) > SERVER_KNOBS - > FREE_SPACE_RATIO_DD_CUTOFF & & <nl> - unloadedTeam . get ( ) - > hasHealthyFreeSpace ( ) ) { <nl> - bool moved = <nl> - wait ( rebalanceTeams ( self , SERVER_KNOBS - > PRIORITY_REBALANCE_UNDERUTILIZED_TEAM , randomTeam . get ( ) , <nl> - unloadedTeam . get ( ) , teamCollectionIndex = = 0 ) ) ; <nl> - if ( moved ) { <nl> - resetCount = 0 ; <nl> - } else { <nl> - resetCount + + ; <nl> - } <nl> + bool _moved = <nl> + wait ( rebalanceTeams ( self , SERVER_KNOBS - > PRIORITY_REBALANCE_UNDERUTILIZED_TEAM , randomTeam . get ( ) , <nl> + unloadedTeam . get ( ) , teamCollectionIndex = = 0 , & traceEvent ) ) ; <nl> + moved = _moved ; <nl> + if ( moved ) { <nl> + resetCount = 0 ; <nl> + } else { <nl> + resetCount + + ; <nl> } <nl> } <nl> } <nl> ACTOR Future < Void > BgDDValleyFiller ( DDQueueData * self , int teamCollectionIndex ) <nl> rebalancePollingInterval = SERVER_KNOBS - > BG_REBALANCE_POLLING_INTERVAL ; <nl> resetCount = SERVER_KNOBS - > DD_REBALANCE_RESET_AMOUNT ; <nl> } <nl> + <nl> + traceEvent . detail ( " ResetCount " , resetCount ) ; <nl> tr . reset ( ) ; <nl> } catch ( Error & e ) { <nl> + traceEvent . error ( e , true ) ; / / Log actor_cancelled because it ' s not legal to suppress an event that ' s initialized <nl> wait ( tr . onError ( e ) ) ; <nl> } <nl> + <nl> + traceEvent . detail ( " Moved " , moved ) ; <nl> + traceEvent . log ( ) ; <nl> } <nl> } <nl> <nl> mmm a / fdbserver / IKeyValueStore . h <nl> ppp b / fdbserver / IKeyValueStore . h <nl> class IKeyValueStore : public IClosable { <nl> <nl> / / If rowLimit > = 0 , reads first rows sorted ascending , otherwise reads last rows sorted descending <nl> / / The total size of the returned value ( less the last entry ) will be less than byteLimit <nl> - virtual Future < Standalone < VectorRef < KeyValueRef > > > readRange ( KeyRangeRef keys , int rowLimit = 1 < < 30 , int byteLimit = 1 < < 30 ) = 0 ; <nl> + virtual Future < Standalone < RangeResultRef > > readRange ( KeyRangeRef keys , int rowLimit = 1 < < 30 , int byteLimit = 1 < < 30 ) = 0 ; <nl> <nl> / / To debug MEMORY_RADIXTREE type ONLY <nl> / / Returns ( 1 ) how many key & value pairs have been inserted ( 2 ) how many nodes have been created ( 3 ) how many <nl> mmm a / fdbserver / KeyValueStoreCompressTestData . actor . cpp <nl> ppp b / fdbserver / KeyValueStoreCompressTestData . actor . cpp <nl> struct KeyValueStoreCompressTestData : IKeyValueStore { <nl> <nl> / / If rowLimit > = 0 , reads first rows sorted ascending , otherwise reads last rows sorted descending <nl> / / The total size of the returned value ( less the last entry ) will be less than byteLimit <nl> - virtual Future < Standalone < VectorRef < KeyValueRef > > > readRange ( KeyRangeRef keys , int rowLimit = 1 < < 30 , int byteLimit = 1 < < 30 ) { <nl> + virtual Future < Standalone < RangeResultRef > > readRange ( KeyRangeRef keys , int rowLimit = 1 < < 30 , int byteLimit = 1 < < 30 ) { <nl> return doReadRange ( store , keys , rowLimit , byteLimit ) ; <nl> } <nl> - ACTOR Future < Standalone < VectorRef < KeyValueRef > > > doReadRange ( IKeyValueStore * store , KeyRangeRef keys , int rowLimit , int byteLimit ) { <nl> - Standalone < VectorRef < KeyValueRef > > _vs = wait ( store - > readRange ( keys , rowLimit , byteLimit ) ) ; <nl> - Standalone < VectorRef < KeyValueRef > > vs = _vs ; / / Get rid of implicit const & from wait statement <nl> + ACTOR Future < Standalone < RangeResultRef > > doReadRange ( IKeyValueStore * store , KeyRangeRef keys , int rowLimit , int byteLimit ) { <nl> + Standalone < RangeResultRef > _vs = wait ( store - > readRange ( keys , rowLimit , byteLimit ) ) ; <nl> + Standalone < RangeResultRef > vs = _vs ; / / Get rid of implicit const & from wait statement <nl> Arena & a = vs . arena ( ) ; <nl> for ( int i = 0 ; i < vs . size ( ) ; i + + ) <nl> vs [ i ] . value = ValueRef ( a , ( ValueRef const & ) unpack ( vs [ i ] . value ) ) ; <nl> mmm a / fdbserver / KeyValueStoreMemory . actor . cpp <nl> ppp b / fdbserver / KeyValueStoreMemory . actor . cpp <nl> class KeyValueStoreMemory : public IKeyValueStore , NonCopyable { <nl> <nl> / / If rowLimit > = 0 , reads first rows sorted ascending , otherwise reads last rows sorted descending <nl> / / The total size of the returned value ( less the last entry ) will be less than byteLimit <nl> - virtual Future < Standalone < VectorRef < KeyValueRef > > > readRange ( KeyRangeRef keys , int rowLimit = 1 < < 30 , <nl> - int byteLimit = 1 < < 30 ) { <nl> - if ( recovering . isError ( ) ) throw recovering . getError ( ) ; <nl> + virtual Future < Standalone < RangeResultRef > > readRange ( KeyRangeRef keys , int rowLimit = 1 < < 30 , int byteLimit = 1 < < 30 ) { <nl> + if ( recovering . isError ( ) ) throw recovering . getError ( ) ; <nl> if ( ! recovering . isReady ( ) ) return waitAndReadRange ( this , keys , rowLimit , byteLimit ) ; <nl> <nl> - Standalone < VectorRef < KeyValueRef > > result ; <nl> - if ( rowLimit > = 0 ) { <nl> + Standalone < RangeResultRef > result ; <nl> + if ( rowLimit = = 0 ) { <nl> + return result ; <nl> + } <nl> + <nl> + if ( rowLimit > 0 ) { <nl> auto it = data . lower_bound ( keys . begin ) ; <nl> - while ( it ! = data . end ( ) & & rowLimit & & byteLimit > = 0 ) { <nl> + while ( it ! = data . end ( ) & & rowLimit & & byteLimit > 0 ) { <nl> StringRef tempKey = it . getKey ( reserved_buffer ) ; <nl> if ( tempKey > = keys . end ) break ; <nl> <nl> class KeyValueStoreMemory : public IKeyValueStore , NonCopyable { <nl> } else { <nl> rowLimit = - rowLimit ; <nl> auto it = data . previous ( data . lower_bound ( keys . end ) ) ; <nl> - while ( it ! = data . end ( ) & & rowLimit & & byteLimit > = 0 ) { <nl> + while ( it ! = data . end ( ) & & rowLimit & & byteLimit > 0 ) { <nl> StringRef tempKey = it . getKey ( reserved_buffer ) ; <nl> if ( tempKey < keys . begin ) break ; <nl> <nl> class KeyValueStoreMemory : public IKeyValueStore , NonCopyable { <nl> - - rowLimit ; <nl> } <nl> } <nl> + <nl> + result . more = rowLimit = = 0 | | byteLimit < = 0 ; <nl> + if ( result . more ) { <nl> + ASSERT ( result . size ( ) > 0 ) ; <nl> + result . readThrough = result [ result . size ( ) - 1 ] . key ; <nl> + } <nl> return result ; <nl> } <nl> <nl> class KeyValueStoreMemory : public IKeyValueStore , NonCopyable { <nl> wait ( self - > recovering ) ; <nl> return self - > readValuePrefix ( key , maxLength ) . get ( ) ; <nl> } <nl> - ACTOR static Future < Standalone < VectorRef < KeyValueRef > > > waitAndReadRange ( KeyValueStoreMemory * self , KeyRange keys , int rowLimit , int byteLimit ) { <nl> + ACTOR static Future < Standalone < RangeResultRef > > waitAndReadRange ( KeyValueStoreMemory * self , KeyRange keys , int rowLimit , int byteLimit ) { <nl> wait ( self - > recovering ) ; <nl> return self - > readRange ( keys , rowLimit , byteLimit ) . get ( ) ; <nl> } <nl> mmm a / fdbserver / KeyValueStoreSQLite . actor . cpp <nl> ppp b / fdbserver / KeyValueStoreSQLite . actor . cpp <nl> struct RawCursor { <nl> } <nl> return Optional < Value > ( ) ; <nl> } <nl> - Standalone < VectorRef < KeyValueRef > > getRange ( KeyRangeRef keys , int rowLimit , int byteLimit ) { <nl> - Standalone < VectorRef < KeyValueRef > > result ; <nl> + Standalone < RangeResultRef > getRange ( KeyRangeRef keys , int rowLimit , int byteLimit ) { <nl> + Standalone < RangeResultRef > result ; <nl> int accumulatedBytes = 0 ; <nl> ASSERT ( byteLimit > 0 ) ; <nl> + if ( rowLimit = = 0 ) { <nl> + return result ; <nl> + } <nl> + <nl> if ( db . fragment_values ) { <nl> - if ( rowLimit > = 0 ) { <nl> + if ( rowLimit > 0 ) { <nl> int r = moveTo ( keys . begin ) ; <nl> if ( r < 0 ) <nl> moveNext ( ) ; <nl> <nl> DefragmentingReader i ( * this , result . arena ( ) , true ) ; <nl> Optional < KeyRef > nextKey = i . peek ( ) ; <nl> - while ( nextKey . present ( ) & & nextKey . get ( ) < keys . end & & rowLimit - - & & accumulatedBytes < byteLimit ) { <nl> + while ( nextKey . present ( ) & & nextKey . get ( ) < keys . end & & rowLimit ! = 0 & & accumulatedBytes < byteLimit ) { <nl> Optional < KeyValueRef > kv = i . getNext ( ) ; <nl> result . push_back ( result . arena ( ) , kv . get ( ) ) ; <nl> + - - rowLimit ; <nl> accumulatedBytes + = sizeof ( KeyValueRef ) + kv . get ( ) . expectedSize ( ) ; <nl> nextKey = i . peek ( ) ; <nl> } <nl> struct RawCursor { <nl> movePrevious ( ) ; <nl> DefragmentingReader i ( * this , result . arena ( ) , false ) ; <nl> Optional < KeyRef > nextKey = i . peek ( ) ; <nl> - while ( nextKey . present ( ) & & nextKey . get ( ) > = keys . begin & & rowLimit + + & & accumulatedBytes < byteLimit ) { <nl> + while ( nextKey . present ( ) & & nextKey . get ( ) > = keys . begin & & rowLimit ! = 0 & & accumulatedBytes < byteLimit ) { <nl> Optional < KeyValueRef > kv = i . getNext ( ) ; <nl> result . push_back ( result . arena ( ) , kv . get ( ) ) ; <nl> + + + rowLimit ; <nl> accumulatedBytes + = sizeof ( KeyValueRef ) + kv . get ( ) . expectedSize ( ) ; <nl> nextKey = i . peek ( ) ; <nl> } <nl> } <nl> } <nl> else { <nl> - if ( rowLimit > = 0 ) { <nl> + if ( rowLimit > 0 ) { <nl> int r = moveTo ( keys . begin ) ; <nl> if ( r < 0 ) moveNext ( ) ; <nl> - while ( this - > valid & & rowLimit - - & & accumulatedBytes < byteLimit ) { <nl> + while ( this - > valid & & rowLimit ! = 0 & & accumulatedBytes < byteLimit ) { <nl> KeyValueRef kv = decodeKV ( getEncodedRow ( result . arena ( ) ) ) ; <nl> - accumulatedBytes + = sizeof ( KeyValueRef ) + kv . expectedSize ( ) ; <nl> if ( kv . key > = keys . end ) break ; <nl> + - - rowLimit ; <nl> + accumulatedBytes + = sizeof ( KeyValueRef ) + kv . expectedSize ( ) ; <nl> result . push_back ( result . arena ( ) , kv ) ; <nl> moveNext ( ) ; <nl> } <nl> } else { <nl> int r = moveTo ( keys . end ) ; <nl> if ( r > = 0 ) movePrevious ( ) ; <nl> - while ( this - > valid & & rowLimit + + & & accumulatedBytes < byteLimit ) { <nl> + while ( this - > valid & & rowLimit ! = 0 & & accumulatedBytes < byteLimit ) { <nl> KeyValueRef kv = decodeKV ( getEncodedRow ( result . arena ( ) ) ) ; <nl> - accumulatedBytes + = sizeof ( KeyValueRef ) + kv . expectedSize ( ) ; <nl> if ( kv . key < keys . begin ) break ; <nl> + + + rowLimit ; <nl> + accumulatedBytes + = sizeof ( KeyValueRef ) + kv . expectedSize ( ) ; <nl> result . push_back ( result . arena ( ) , kv ) ; <nl> movePrevious ( ) ; <nl> } <nl> } <nl> } <nl> + result . more = rowLimit = = 0 | | accumulatedBytes > = byteLimit ; <nl> + if ( result . more ) { <nl> + ASSERT ( result . size ( ) > 0 ) ; <nl> + result . readThrough = result [ result . size ( ) - 1 ] . key ; <nl> + } <nl> return result ; <nl> } <nl> <nl> class KeyValueStoreSQLite : public IKeyValueStore { <nl> <nl> virtual Future < Optional < Value > > readValue ( KeyRef key , Optional < UID > debugID ) ; <nl> virtual Future < Optional < Value > > readValuePrefix ( KeyRef key , int maxLength , Optional < UID > debugID ) ; <nl> - virtual Future < Standalone < VectorRef < KeyValueRef > > > readRange ( KeyRangeRef keys , int rowLimit = 1 < < 30 , int byteLimit = 1 < < 30 ) ; <nl> + virtual Future < Standalone < RangeResultRef > > readRange ( KeyRangeRef keys , int rowLimit = 1 < < 30 , int byteLimit = 1 < < 30 ) ; <nl> <nl> KeyValueStoreSQLite ( std : : string const & filename , UID logID , KeyValueStoreType type , bool checkChecksums , bool checkIntegrity ) ; <nl> ~ KeyValueStoreSQLite ( ) ; <nl> class KeyValueStoreSQLite : public IKeyValueStore { <nl> struct ReadRangeAction : TypedAction < Reader , ReadRangeAction > , FastAllocated < ReadRangeAction > { <nl> KeyRange keys ; <nl> int rowLimit , byteLimit ; <nl> - ThreadReturnPromise < Standalone < VectorRef < KeyValueRef > > > result ; <nl> + ThreadReturnPromise < Standalone < RangeResultRef > > result ; <nl> ReadRangeAction ( KeyRange keys , int rowLimit , int byteLimit ) : keys ( keys ) , rowLimit ( rowLimit ) , byteLimit ( byteLimit ) { } <nl> virtual double getTimeEstimate ( ) { return SERVER_KNOBS - > READ_RANGE_TIME_ESTIMATE ; } <nl> } ; <nl> Future < Optional < Value > > KeyValueStoreSQLite : : readValuePrefix ( KeyRef key , int ma <nl> readThreads - > post ( p ) ; <nl> return f ; <nl> } <nl> - Future < Standalone < VectorRef < KeyValueRef > > > KeyValueStoreSQLite : : readRange ( KeyRangeRef keys , int rowLimit , int byteLimit ) { <nl> + Future < Standalone < RangeResultRef > > KeyValueStoreSQLite : : readRange ( KeyRangeRef keys , int rowLimit , int byteLimit ) { <nl> + + readsRequested ; <nl> auto p = new Reader : : ReadRangeAction ( keys , rowLimit , byteLimit ) ; <nl> auto f = p - > result . getFuture ( ) ; <nl> mmm a / fdbserver / Knobs . cpp <nl> ppp b / fdbserver / Knobs . cpp <nl> ServerKnobs : : ServerKnobs ( bool randomize , ClientKnobs * clientKnobs , bool isSimula <nl> init ( DISK_QUEUE_FILE_EXTENSION_BYTES , 10 < < 20 ) ; / / BUGGIFYd per file within the DiskQueue <nl> init ( DISK_QUEUE_FILE_SHRINK_BYTES , 100 < < 20 ) ; / / BUGGIFYd per file within the DiskQueue <nl> init ( DISK_QUEUE_MAX_TRUNCATE_BYTES , 2 < < 30 ) ; if ( randomize & & BUGGIFY ) DISK_QUEUE_MAX_TRUNCATE_BYTES = 0 ; <nl> - init ( TLOG_DEGRADED_DELAY_COUNT , 5 ) ; <nl> init ( TLOG_DEGRADED_DURATION , 5 . 0 ) ; <nl> init ( MAX_CACHE_VERSIONS , 10e6 ) ; <nl> init ( TLOG_IGNORE_POP_AUTO_ENABLE_DELAY , 300 . 0 ) ; <nl> ServerKnobs : : ServerKnobs ( bool randomize , ClientKnobs * clientKnobs , bool isSimula <nl> / / Data distribution queue <nl> init ( HEALTH_POLL_TIME , 1 . 0 ) ; <nl> init ( BEST_TEAM_STUCK_DELAY , 1 . 0 ) ; <nl> - init ( BG_REBALANCE_POLLING_INTERVAL , 10 . 0 ) ; <nl> - init ( BG_REBALANCE_SWITCH_CHECK_INTERVAL , 5 . 0 ) ; if ( randomize & & BUGGIFY ) BG_REBALANCE_SWITCH_CHECK_INTERVAL = 1 . 0 ; <nl> + init ( BG_REBALANCE_POLLING_INTERVAL , 10 . 0 ) ; <nl> + init ( BG_REBALANCE_SWITCH_CHECK_INTERVAL , 5 . 0 ) ; if ( randomize & & BUGGIFY ) BG_REBALANCE_SWITCH_CHECK_INTERVAL = 1 . 0 ; <nl> init ( DD_QUEUE_LOGGING_INTERVAL , 5 . 0 ) ; <nl> init ( RELOCATION_PARALLELISM_PER_SOURCE_SERVER , 2 ) ; if ( randomize & & BUGGIFY ) RELOCATION_PARALLELISM_PER_SOURCE_SERVER = 1 ; <nl> init ( DD_QUEUE_MAX_KEY_SERVERS , 100 ) ; if ( randomize & & BUGGIFY ) DD_QUEUE_MAX_KEY_SERVERS = 1 ; <nl> ServerKnobs : : ServerKnobs ( bool randomize , ClientKnobs * clientKnobs , bool isSimula <nl> init ( BG_DD_DECREASE_RATE , 1 . 02 ) ; <nl> init ( BG_DD_SATURATION_DELAY , 1 . 0 ) ; <nl> init ( INFLIGHT_PENALTY_HEALTHY , 1 . 0 ) ; <nl> - init ( INFLIGHT_PENALTY_UNHEALTHY , 10 . 0 ) ; <nl> + init ( INFLIGHT_PENALTY_UNHEALTHY , 500 . 0 ) ; <nl> init ( INFLIGHT_PENALTY_ONE_LEFT , 1000 . 0 ) ; <nl> - <nl> + <nl> init ( PRIORITY_RECOVER_MOVE , 110 ) ; <nl> init ( PRIORITY_REBALANCE_UNDERUTILIZED_TEAM , 120 ) ; <nl> init ( PRIORITY_REBALANCE_OVERUTILIZED_TEAM , 121 ) ; <nl> ServerKnobs : : ServerKnobs ( bool randomize , ClientKnobs * clientKnobs , bool isSimula <nl> If this value is too small relative to SHARD_MIN_BYTES_PER_KSEC immediate merging work will be generated . <nl> * / <nl> <nl> - init ( STORAGE_METRIC_TIMEOUT , 600 . 0 ) ; if ( randomize & & BUGGIFY ) STORAGE_METRIC_TIMEOUT = deterministicRandom ( ) - > coinflip ( ) ? 10 . 0 : 60 . 0 ; <nl> + init ( STORAGE_METRIC_TIMEOUT , isSimulated ? 60 . 0 : 600 . 0 ) ; if ( randomize & & BUGGIFY ) STORAGE_METRIC_TIMEOUT = deterministicRandom ( ) - > coinflip ( ) ? 10 . 0 : 30 . 0 ; <nl> init ( METRIC_DELAY , 0 . 1 ) ; if ( randomize & & BUGGIFY ) METRIC_DELAY = 1 . 0 ; <nl> init ( ALL_DATA_REMOVED_DELAY , 1 . 0 ) ; <nl> init ( INITIAL_FAILURE_REACTION_DELAY , 30 . 0 ) ; if ( randomize & & BUGGIFY ) INITIAL_FAILURE_REACTION_DELAY = 0 . 0 ; <nl> ServerKnobs : : ServerKnobs ( bool randomize , ClientKnobs * clientKnobs , bool isSimula <nl> init ( DATA_DISTRIBUTION_LOGGING_INTERVAL , 5 . 0 ) ; <nl> init ( DD_ENABLED_CHECK_DELAY , 1 . 0 ) ; <nl> init ( DD_STALL_CHECK_DELAY , 0 . 4 ) ; / / Must be larger than 2 * MAX_BUGGIFIED_DELAY <nl> - init ( DD_LOW_BANDWIDTH_DELAY , isSimulated ? 90 . 0 : 240 . 0 ) ; if ( randomize & & BUGGIFY ) DD_LOW_BANDWIDTH_DELAY = 0 ; / / Because of delayJitter , this should be less than 0 . 9 * DD_MERGE_COALESCE_DELAY <nl> - init ( DD_MERGE_COALESCE_DELAY , isSimulated ? 120 . 0 : 300 . 0 ) ; if ( randomize & & BUGGIFY ) DD_MERGE_COALESCE_DELAY = 0 . 001 ; <nl> + init ( DD_LOW_BANDWIDTH_DELAY , isSimulated ? 15 . 0 : 240 . 0 ) ; if ( randomize & & BUGGIFY ) DD_LOW_BANDWIDTH_DELAY = 0 ; / / Because of delayJitter , this should be less than 0 . 9 * DD_MERGE_COALESCE_DELAY <nl> + init ( DD_MERGE_COALESCE_DELAY , isSimulated ? 30 . 0 : 300 . 0 ) ; if ( randomize & & BUGGIFY ) DD_MERGE_COALESCE_DELAY = 0 . 001 ; <nl> init ( STORAGE_METRICS_POLLING_DELAY , 2 . 0 ) ; if ( randomize & & BUGGIFY ) STORAGE_METRICS_POLLING_DELAY = 15 . 0 ; <nl> init ( STORAGE_METRICS_RANDOM_DELAY , 0 . 2 ) ; <nl> - init ( FREE_SPACE_RATIO_CUTOFF , 0 . 1 ) ; <nl> - init ( FREE_SPACE_RATIO_DD_CUTOFF , 0 . 2 ) ; <nl> + init ( FREE_SPACE_RATIO_CUTOFF , 0 . 35 ) ; <nl> init ( DESIRED_TEAMS_PER_SERVER , 5 ) ; if ( randomize & & BUGGIFY ) DESIRED_TEAMS_PER_SERVER = 1 ; <nl> init ( MAX_TEAMS_PER_SERVER , 5 * DESIRED_TEAMS_PER_SERVER ) ; <nl> init ( DD_SHARD_SIZE_GRANULARITY , 5000000 ) ; <nl> ServerKnobs : : ServerKnobs ( bool randomize , ClientKnobs * clientKnobs , bool isSimula <nl> init ( DD_CHECK_INVALID_LOCALITY_DELAY , 60 ) ; if ( randomize & & BUGGIFY ) DD_CHECK_INVALID_LOCALITY_DELAY = 1 + deterministicRandom ( ) - > random01 ( ) * 600 ; <nl> <nl> / / TeamRemover <nl> - TR_FLAG_DISABLE_MACHINE_TEAM_REMOVER = false ; if ( randomize & & BUGGIFY ) TR_FLAG_DISABLE_MACHINE_TEAM_REMOVER = deterministicRandom ( ) - > random01 ( ) < 0 . 1 ? true : false ; / / false by default . disable the consistency check when it ' s true <nl> + init ( TR_FLAG_DISABLE_MACHINE_TEAM_REMOVER , false ) ; if ( randomize & & BUGGIFY ) TR_FLAG_DISABLE_MACHINE_TEAM_REMOVER = deterministicRandom ( ) - > random01 ( ) < 0 . 1 ? true : false ; / / false by default . disable the consistency check when it ' s true <nl> init ( TR_REMOVE_MACHINE_TEAM_DELAY , 60 . 0 ) ; if ( randomize & & BUGGIFY ) TR_REMOVE_MACHINE_TEAM_DELAY = deterministicRandom ( ) - > random01 ( ) * 60 . 0 ; <nl> - TR_FLAG_REMOVE_MT_WITH_MOST_TEAMS = true ; if ( randomize & & BUGGIFY ) TR_FLAG_REMOVE_MT_WITH_MOST_TEAMS = deterministicRandom ( ) - > random01 ( ) < 0 . 1 ? true : false ; <nl> - TR_FLAG_DISABLE_SERVER_TEAM_REMOVER = false ; if ( randomize & & BUGGIFY ) TR_FLAG_DISABLE_SERVER_TEAM_REMOVER = deterministicRandom ( ) - > random01 ( ) < 0 . 1 ? true : false ; / / false by default . disable the consistency check when it ' s true <nl> + init ( TR_FLAG_REMOVE_MT_WITH_MOST_TEAMS , true ) ; if ( randomize & & BUGGIFY ) TR_FLAG_REMOVE_MT_WITH_MOST_TEAMS = deterministicRandom ( ) - > random01 ( ) < 0 . 1 ? true : false ; <nl> + init ( TR_FLAG_DISABLE_SERVER_TEAM_REMOVER , false ) ; if ( randomize & & BUGGIFY ) TR_FLAG_DISABLE_SERVER_TEAM_REMOVER = deterministicRandom ( ) - > random01 ( ) < 0 . 1 ? true : false ; / / false by default . disable the consistency check when it ' s true <nl> init ( TR_REMOVE_SERVER_TEAM_DELAY , 60 . 0 ) ; if ( randomize & & BUGGIFY ) TR_REMOVE_SERVER_TEAM_DELAY = deterministicRandom ( ) - > random01 ( ) * 60 . 0 ; <nl> init ( TR_REMOVE_SERVER_TEAM_EXTRA_DELAY , 5 . 0 ) ; if ( randomize & & BUGGIFY ) TR_REMOVE_SERVER_TEAM_EXTRA_DELAY = deterministicRandom ( ) - > random01 ( ) * 10 . 0 ; <nl> <nl> ServerKnobs : : ServerKnobs ( bool randomize , ClientKnobs * clientKnobs , bool isSimula <nl> <nl> / / Redwood Storage Engine <nl> init ( PREFIX_TREE_IMMEDIATE_KEY_SIZE_LIMIT , 30 ) ; <nl> - init ( PREFIX_TREE_IMMEDIATE_KEY_SIZE_MIN , 0 ) ; <nl> + init ( PREFIX_TREE_IMMEDIATE_KEY_SIZE_MIN , 0 ) ; <nl> <nl> / / KeyValueStore SQLITE <nl> init ( CLEAR_BUFFER_SIZE , 20000 ) ; <nl> ServerKnobs : : ServerKnobs ( bool randomize , ClientKnobs * clientKnobs , bool isSimula <nl> init ( REQUIRED_MIN_RECOVERY_DURATION , 0 . 080 ) ; if ( shortRecoveryDuration ) REQUIRED_MIN_RECOVERY_DURATION = 0 . 01 ; <nl> init ( ALWAYS_CAUSAL_READ_RISKY , false ) ; <nl> init ( MAX_COMMIT_UPDATES , 2000 ) ; if ( randomize & & BUGGIFY ) MAX_COMMIT_UPDATES = 1 ; <nl> + init ( MIN_PROXY_COMPUTE , 0 . 001 ) ; <nl> + init ( PROXY_COMPUTE_BUCKETS , 5000 ) ; <nl> + init ( PROXY_COMPUTE_GROWTH_RATE , 0 . 01 ) ; <nl> <nl> / / Master Server <nl> / / masterCommitter ( ) in the master server will allow lower priority tasks ( e . g . DataDistibution ) <nl> ServerKnobs : : ServerKnobs ( bool randomize , ClientKnobs * clientKnobs , bool isSimula <nl> init ( CLIENT_REGISTER_INTERVAL , 600 . 0 ) ; <nl> <nl> init ( INCOMPATIBLE_PEERS_LOGGING_INTERVAL , 600 ) ; if ( randomize & & BUGGIFY ) INCOMPATIBLE_PEERS_LOGGING_INTERVAL = 60 . 0 ; <nl> - init ( EXPECTED_MASTER_FITNESS , ProcessClass : : UnsetFit ) ; <nl> - init ( EXPECTED_TLOG_FITNESS , ProcessClass : : UnsetFit ) ; <nl> - init ( EXPECTED_LOG_ROUTER_FITNESS , ProcessClass : : UnsetFit ) ; <nl> - init ( EXPECTED_PROXY_FITNESS , ProcessClass : : UnsetFit ) ; <nl> - init ( EXPECTED_RESOLVER_FITNESS , ProcessClass : : UnsetFit ) ; <nl> + init ( EXPECTED_MASTER_FITNESS , ProcessClass : : UnsetFit ) ; <nl> + init ( EXPECTED_TLOG_FITNESS , ProcessClass : : UnsetFit ) ; <nl> + init ( EXPECTED_LOG_ROUTER_FITNESS , ProcessClass : : UnsetFit ) ; <nl> + init ( EXPECTED_PROXY_FITNESS , ProcessClass : : UnsetFit ) ; <nl> + init ( EXPECTED_RESOLVER_FITNESS , ProcessClass : : UnsetFit ) ; <nl> init ( RECRUITMENT_TIMEOUT , 600 ) ; if ( randomize & & BUGGIFY ) RECRUITMENT_TIMEOUT = deterministicRandom ( ) - > coinflip ( ) ? 60 . 0 : 1 . 0 ; <nl> <nl> init ( POLICY_RATING_TESTS , 200 ) ; if ( randomize & & BUGGIFY ) POLICY_RATING_TESTS = 20 ; <nl> ServerKnobs : : ServerKnobs ( bool randomize , ClientKnobs * clientKnobs , bool isSimula <nl> init ( MIN_REBOOT_TIME , 4 . 0 ) ; if ( longReboots ) MIN_REBOOT_TIME = 10 . 0 ; <nl> init ( MAX_REBOOT_TIME , 5 . 0 ) ; if ( longReboots ) MAX_REBOOT_TIME = 20 . 0 ; <nl> init ( LOG_DIRECTORY , " . " ) ; / / Will be set to the command line flag . <nl> - init ( SERVER_MEM_LIMIT , 8LL < < 30 ) ; <nl> + init ( SERVER_MEM_LIMIT , 8LL < < 30 ) ; <nl> <nl> / / Ratekeeper <nl> bool slowRatekeeper = randomize & & BUGGIFY ; <nl> ServerKnobs : : ServerKnobs ( bool randomize , ClientKnobs * clientKnobs , bool isSimula <nl> <nl> init ( MAX_TRANSACTIONS_PER_BYTE , 1000 ) ; <nl> <nl> - init ( MIN_FREE_SPACE , 1e8 ) ; <nl> - init ( MIN_FREE_SPACE_RATIO , 0 . 05 ) ; <nl> + init ( MIN_AVAILABLE_SPACE , 1e8 ) ; <nl> + init ( MIN_AVAILABLE_SPACE_RATIO , 0 . 05 ) ; <nl> + init ( TARGET_AVAILABLE_SPACE_RATIO , 0 . 30 ) ; <nl> + init ( AVAILABLE_SPACE_UPDATE_DELAY , 5 . 0 ) ; <nl> <nl> init ( MAX_TL_SS_VERSION_DIFFERENCE , 1e99 ) ; / / if ( randomize & & BUGGIFY ) MAX_TL_SS_VERSION_DIFFERENCE = std : : max ( 1 . 0 , 0 . 25 * VERSIONS_PER_SECOND ) ; / / spring starts at half this value / / FIXME : this knob causes ratekeeper to clamp on idle cluster in simulation that have a large number of logs <nl> init ( MAX_TL_SS_VERSION_DIFFERENCE_BATCH , 1e99 ) ; <nl> ServerKnobs : : ServerKnobs ( bool randomize , ClientKnobs * clientKnobs , bool isSimula <nl> init ( BEHIND_CHECK_DELAY , 2 . 0 ) ; <nl> init ( BEHIND_CHECK_COUNT , 2 ) ; <nl> init ( BEHIND_CHECK_VERSIONS , 5 * VERSIONS_PER_SECOND ) ; <nl> - init ( WAIT_METRICS_WRONG_SHARD_CHANCE , 0 . 1 ) ; <nl> + init ( WAIT_METRICS_WRONG_SHARD_CHANCE , isSimulated ? 1 . 0 : 0 . 1 ) ; <nl> <nl> / / Wait Failure <nl> init ( MAX_OUTSTANDING_WAIT_FAILURE_REQUESTS , 250 ) ; if ( randomize & & BUGGIFY ) MAX_OUTSTANDING_WAIT_FAILURE_REQUESTS = 2 ; <nl> ServerKnobs : : ServerKnobs ( bool randomize , ClientKnobs * clientKnobs , bool isSimula <nl> <nl> / / Buggification <nl> init ( BUGGIFIED_EVENTUAL_CONSISTENCY , 1 . 0 ) ; <nl> - BUGGIFY_ALL_COORDINATION = false ; if ( randomize & & BUGGIFY ) BUGGIFY_ALL_COORDINATION = true ; <nl> + init ( BUGGIFY_ALL_COORDINATION , false ) ; if ( randomize & & BUGGIFY ) BUGGIFY_ALL_COORDINATION = true ; <nl> <nl> / / Status <nl> init ( STATUS_MIN_TIME_BETWEEN_REQUESTS , 0 . 0 ) ; <nl> ServerKnobs : : ServerKnobs ( bool randomize , ClientKnobs * clientKnobs , bool isSimula <nl> <nl> / / Timekeeper <nl> init ( TIME_KEEPER_DELAY , 10 ) ; <nl> - init ( TIME_KEEPER_MAX_ENTRIES , 3600 * 24 * 30 * 6 ) ; if ( randomize & & BUGGIFY ) { TIME_KEEPER_MAX_ENTRIES = 2 ; } <nl> + init ( TIME_KEEPER_MAX_ENTRIES , 3600 * 24 * 30 * 6 ) ; if ( randomize & & BUGGIFY ) { TIME_KEEPER_MAX_ENTRIES = 2 ; } <nl> <nl> / / Fast Restore <nl> init ( FASTRESTORE_FAILURE_TIMEOUT , 3600 ) ; <nl> init ( FASTRESTORE_HEARTBEAT_INTERVAL , 60 ) ; <nl> - init ( FASTRESTORE_SAMPLING_PERCENT , 1 ) ; if ( randomize & & BUGGIFY ) { FASTRESTORE_SAMPLING_PERCENT = deterministicRandom ( ) - > random01 ( ) * 100 ; } <nl> + init ( FASTRESTORE_SAMPLING_PERCENT , 1 ) ; if ( randomize ) { FASTRESTORE_SAMPLING_PERCENT = deterministicRandom ( ) - > random01 ( ) * 100 ; } <nl> + init ( FASTRESTORE_NUM_LOADERS , 3 ) ; if ( randomize ) { FASTRESTORE_NUM_LOADERS = deterministicRandom ( ) - > random01 ( ) * 10 + 1 ; } <nl> + init ( FASTRESTORE_NUM_APPLIERS , 3 ) ; if ( randomize ) { FASTRESTORE_NUM_APPLIERS = deterministicRandom ( ) - > random01 ( ) * 10 + 1 ; } <nl> + init ( FASTRESTORE_TXN_BATCH_MAX_BYTES , 512 . 0 ) ; if ( randomize ) { FASTRESTORE_TXN_BATCH_MAX_BYTES = deterministicRandom ( ) - > random01 ( ) * 1024 . 0 * 1024 . 0 + 1 . 0 ; } <nl> + init ( FASTRESTORE_VERSIONBATCH_MAX_BYTES , 10 . 0 * 1024 . 0 * 1024 . 0 ) ; if ( randomize ) { FASTRESTORE_VERSIONBATCH_MAX_BYTES = deterministicRandom ( ) - > random01 ( ) * 10 . 0 * 1024 . 0 * 1024 . 0 * 1024 . 0 ; } <nl> + init ( FASTRESTORE_VB_PARALLELISM , 3 ) ; if ( randomize ) { FASTRESTORE_VB_PARALLELISM = deterministicRandom ( ) - > random01 ( ) * 20 + 1 ; } <nl> + init ( FASTRESTORE_VB_MONITOR_DELAY , 5 ) ; if ( randomize ) { FASTRESTORE_VB_MONITOR_DELAY = deterministicRandom ( ) - > random01 ( ) * 20 + 1 ; } <nl> + init ( FASTRESTORE_VB_LAUNCH_DELAY , 5 ) ; if ( randomize ) { FASTRESTORE_VB_LAUNCH_DELAY = deterministicRandom ( ) - > random01 ( ) * 60 + 1 ; } <nl> + init ( FASTRESTORE_ROLE_LOGGING_DELAY , 5 ) ; if ( randomize ) { FASTRESTORE_ROLE_LOGGING_DELAY = deterministicRandom ( ) - > random01 ( ) * 60 + 1 ; } <nl> + init ( FASTRESTORE_UPDATE_PROCESS_STATS_INTERVAL , 5 ) ; if ( randomize ) { FASTRESTORE_UPDATE_PROCESS_STATS_INTERVAL = deterministicRandom ( ) - > random01 ( ) * 60 + 1 ; } <nl> + init ( FASTRESTORE_ATOMICOP_WEIGHT , 100 ) ; if ( randomize ) { FASTRESTORE_ATOMICOP_WEIGHT = deterministicRandom ( ) - > random01 ( ) * 200 + 1 ; } <nl> + init ( FASTRESTORE_APPLYING_PARALLELISM , 100 ) ; if ( randomize ) { FASTRESTORE_APPLYING_PARALLELISM = deterministicRandom ( ) - > random01 ( ) * 10 + 1 ; } <nl> + init ( FASTRESTORE_MONITOR_LEADER_DELAY , 5 ) ; if ( randomize ) { FASTRESTORE_MONITOR_LEADER_DELAY = deterministicRandom ( ) - > random01 ( ) * 100 ; } <nl> <nl> / / clang - format on <nl> <nl> mmm a / fdbserver / Knobs . h <nl> ppp b / fdbserver / Knobs . h <nl> class ServerKnobs : public Knobs { <nl> int64_t DISK_QUEUE_FILE_EXTENSION_BYTES ; / / When we grow the disk queue , by how many bytes should it grow ? <nl> int64_t DISK_QUEUE_FILE_SHRINK_BYTES ; / / When we shrink the disk queue , by how many bytes should it shrink ? <nl> int DISK_QUEUE_MAX_TRUNCATE_BYTES ; / / A truncate larger than this will cause the file to be replaced instead . <nl> - int TLOG_DEGRADED_DELAY_COUNT ; <nl> double TLOG_DEGRADED_DURATION ; <nl> int64_t MAX_CACHE_VERSIONS ; <nl> double TXS_POPPED_MAX_DELAY ; <nl> class ServerKnobs : public Knobs { <nl> double INFLIGHT_PENALTY_REDUNDANT ; <nl> double INFLIGHT_PENALTY_UNHEALTHY ; <nl> double INFLIGHT_PENALTY_ONE_LEFT ; <nl> - <nl> + <nl> / / Higher priorities are executed first <nl> / / Priority / 100 is the " priority group " / " superpriority " . Priority inversion <nl> / / is possible within but not between priority groups ; fewer priority groups <nl> class ServerKnobs : public Knobs { <nl> double STORAGE_METRICS_POLLING_DELAY ; <nl> double STORAGE_METRICS_RANDOM_DELAY ; <nl> double FREE_SPACE_RATIO_CUTOFF ; <nl> - double FREE_SPACE_RATIO_DD_CUTOFF ; <nl> + double FREE_SPACE_CUTOFF_PENALTY ; <nl> int DESIRED_TEAMS_PER_SERVER ; <nl> int MAX_TEAMS_PER_SERVER ; <nl> int64_t DD_SHARD_SIZE_GRANULARITY ; <nl> class ServerKnobs : public Knobs { <nl> double REQUIRED_MIN_RECOVERY_DURATION ; <nl> bool ALWAYS_CAUSAL_READ_RISKY ; <nl> int MAX_COMMIT_UPDATES ; <nl> + double MIN_PROXY_COMPUTE ; <nl> + int PROXY_COMPUTE_BUCKETS ; <nl> + double PROXY_COMPUTE_GROWTH_RATE ; <nl> <nl> / / Master Server <nl> double COMMIT_SLEEP_TIME ; <nl> class ServerKnobs : public Knobs { <nl> <nl> double MAX_TRANSACTIONS_PER_BYTE ; <nl> <nl> - int64_t MIN_FREE_SPACE ; <nl> - double MIN_FREE_SPACE_RATIO ; <nl> + int64_t MIN_AVAILABLE_SPACE ; <nl> + double MIN_AVAILABLE_SPACE_RATIO ; <nl> + double TARGET_AVAILABLE_SPACE_RATIO ; <nl> + double AVAILABLE_SPACE_UPDATE_DELAY ; <nl> <nl> double MAX_TL_SS_VERSION_DIFFERENCE ; / / spring starts at half this value <nl> double MAX_TL_SS_VERSION_DIFFERENCE_BATCH ; <nl> class ServerKnobs : public Knobs { <nl> int64_t FASTRESTORE_FAILURE_TIMEOUT ; <nl> int64_t FASTRESTORE_HEARTBEAT_INTERVAL ; <nl> double FASTRESTORE_SAMPLING_PERCENT ; <nl> + int64_t FASTRESTORE_NUM_LOADERS ; <nl> + int64_t FASTRESTORE_NUM_APPLIERS ; <nl> + / / FASTRESTORE_TXN_BATCH_MAX_BYTES is target txn size used by appliers to apply mutations <nl> + double FASTRESTORE_TXN_BATCH_MAX_BYTES ; <nl> + / / FASTRESTORE_VERSIONBATCH_MAX_BYTES is the maximum data size in each version batch <nl> + double FASTRESTORE_VERSIONBATCH_MAX_BYTES ; <nl> + / / FASTRESTORE_VB_PARALLELISM is the number of concurrently running version batches <nl> + int64_t FASTRESTORE_VB_PARALLELISM ; <nl> + int64_t FASTRESTORE_VB_MONITOR_DELAY ; / / How quickly monitor finished version batch <nl> + int64_t FASTRESTORE_VB_LAUNCH_DELAY ; <nl> + int64_t FASTRESTORE_ROLE_LOGGING_DELAY ; <nl> + int64_t FASTRESTORE_UPDATE_PROCESS_STATS_INTERVAL ; / / How quickly to update process metrics for restore <nl> + int64_t FASTRESTORE_ATOMICOP_WEIGHT ; / / workload amplication factor for atomic op <nl> + int64_t FASTRESTORE_APPLYING_PARALLELISM ; / / number of outstanding txns writing to dest . DB <nl> + int64_t FASTRESTORE_MONITOR_LEADER_DELAY ; <nl> <nl> ServerKnobs ( bool randomize = false , ClientKnobs * clientKnobs = NULL , bool isSimulated = false ) ; <nl> } ; <nl> mmm a / fdbserver / LeaderElection . h <nl> ppp b / fdbserver / LeaderElection . h <nl> Future < Void > tryBecomeLeader ( ServerCoordinators const & coordinators , <nl> Reference < AsyncVar < ClusterControllerPriorityInfo > > const & asyncPriorityInfo ) <nl> { <nl> Reference < AsyncVar < Value > > serializedInfo ( new AsyncVar < Value > ) ; <nl> - Future < Void > m = tryBecomeLeaderInternal ( <nl> - coordinators , <nl> - FLOW_KNOBS - > USE_OBJECT_SERIALIZER ? ObjectWriter : : toValue ( proposedInterface , IncludeVersion ( ) ) : BinaryWriter : : toValue ( proposedInterface , IncludeVersion ( ) ) , <nl> - serializedInfo , hasConnected , asyncPriorityInfo ) ; <nl> - return m | | asyncDeserialize ( serializedInfo , outKnownLeader , FLOW_KNOBS - > USE_OBJECT_SERIALIZER ) ; <nl> + Future < Void > m = tryBecomeLeaderInternal ( coordinators , ObjectWriter : : toValue ( proposedInterface , IncludeVersion ( ) ) , <nl> + serializedInfo , hasConnected , asyncPriorityInfo ) ; <nl> + return m | | asyncDeserialize ( serializedInfo , outKnownLeader ) ; <nl> } <nl> <nl> # ifndef __INTEL_COMPILER <nl> mmm a / fdbserver / LogSystemPeekCursor . actor . cpp <nl> ppp b / fdbserver / LogSystemPeekCursor . actor . cpp <nl> ACTOR Future < Void > bufferedGetMore ( ILogSystem : : BufferedCursor * self , TaskPriori <nl> loop { <nl> wait ( allLoaders | | delay ( SERVER_KNOBS - > DESIRED_GET_MORE_DELAY , taskID ) ) ; <nl> minVersion = self - > end ; <nl> - for ( auto cursor : self - > cursors ) { <nl> + for ( int i = 0 ; i < self - > cursors . size ( ) ; i + + ) { <nl> + auto cursor = self - > cursors [ i ] ; <nl> + while ( cursor - > hasMessage ( ) ) { <nl> + self - > cursorMessages [ i ] . push_back ( ILogSystem : : BufferedCursor : : BufferedMessage ( cursor - > arena ( ) , ( ! self - > withTags | | self - > collectTags ) ? cursor - > getMessage ( ) : cursor - > getMessageWithTags ( ) , ! self - > withTags ? VectorRef < Tag > ( ) : cursor - > getTags ( ) , cursor - > version ( ) ) ) ; <nl> + cursor - > nextMessage ( ) ; <nl> + } <nl> minVersion = std : : min ( minVersion , cursor - > version ( ) . version ) ; <nl> } <nl> if ( minVersion > self - > messageVersion . version ) { <nl> mmm a / fdbserver / MasterProxyServer . actor . cpp <nl> ppp b / fdbserver / MasterProxyServer . actor . cpp <nl> struct ProxyCommitData { <nl> int updateCommitRequests = 0 ; <nl> NotifiedDouble lastCommitTime ; <nl> <nl> + vector < double > commitComputePerOperation ; <nl> + <nl> / / The tag related to a storage server rarely change , so we keep a vector of tags for each key range to be slightly more CPU efficient . <nl> / / When a tag related to a storage server does change , we empty out all of these vectors to signify they must be repopulated . <nl> / / We do not repopulate them immediately to avoid a slow task . <nl> struct ProxyCommitData { <nl> localCommitBatchesStarted ( 0 ) , locked ( false ) , commitBatchInterval ( SERVER_KNOBS - > COMMIT_TRANSACTION_BATCH_INTERVAL_MIN ) , <nl> firstProxy ( firstProxy ) , cx ( openDBOnServer ( db , TaskPriority : : DefaultEndpoint , true , true ) ) , db ( db ) , <nl> singleKeyMutationEvent ( LiteralStringRef ( " SingleKeyMutation " ) ) , commitBatchesMemBytesCount ( 0 ) , lastTxsPop ( 0 ) , lastStartCommit ( 0 ) , lastCommitLatency ( SERVER_KNOBS - > REQUIRED_MIN_RECOVERY_DURATION ) , lastCommitTime ( 0 ) <nl> - { } <nl> + { <nl> + commitComputePerOperation . resize ( SERVER_KNOBS - > PROXY_COMPUTE_BUCKETS , 0 . 0 ) ; <nl> + } <nl> } ; <nl> <nl> struct ResolutionRequestBuilder { <nl> bool isWhitelisted ( const vector < Standalone < StringRef > > & binPathVec , StringRef bi <nl> } <nl> <nl> ACTOR Future < Void > addBackupMutations ( ProxyCommitData * self , std : : map < Key , MutationListRef > * logRangeMutations , <nl> - LogPushData * toCommit , Version commitVersion ) { <nl> + LogPushData * toCommit , Version commitVersion , double * computeDuration , double * computeStart ) { <nl> state std : : map < Key , MutationListRef > : : iterator logRangeMutation = logRangeMutations - > begin ( ) ; <nl> state int32_t version = commitVersion / CLIENT_KNOBS - > LOG_RANGE_BLOCK_SIZE ; <nl> state int yieldBytes = 0 ; <nl> ACTOR Future < Void > addBackupMutations ( ProxyCommitData * self , std : : map < Key , Mutat <nl> while ( blobIter ) { <nl> if ( yieldBytes > SERVER_KNOBS - > DESIRED_TOTAL_BYTES ) { <nl> yieldBytes = 0 ; <nl> - wait ( yield ( TaskPriority : : ProxyCommitYield2 ) ) ; <nl> + if ( g_network - > check_yield ( TaskPriority : : ProxyCommitYield1 ) ) { <nl> + * computeDuration + = g_network - > timer ( ) - * computeStart ; <nl> + wait ( delay ( 0 , TaskPriority : : ProxyCommitYield1 ) ) ; <nl> + * computeStart = g_network - > timer ( ) ; <nl> + } <nl> } <nl> valueWriter . serializeBytes ( blobIter - > data ) ; <nl> yieldBytes + = blobIter - > data . size ( ) ; <nl> ACTOR Future < Void > addBackupMutations ( ProxyCommitData * self , std : : map < Key , Mutat <nl> return Void ( ) ; <nl> } <nl> <nl> + ACTOR Future < Void > releaseResolvingAfter ( ProxyCommitData * self , Future < Void > releaseDelay , int64_t localBatchNumber ) { <nl> + wait ( releaseDelay ) ; <nl> + ASSERT ( self - > latestLocalCommitBatchResolving . get ( ) = = localBatchNumber - 1 ) ; <nl> + self - > latestLocalCommitBatchResolving . set ( localBatchNumber ) ; <nl> + return Void ( ) ; <nl> + } <nl> + <nl> ACTOR Future < Void > commitBatch ( <nl> ProxyCommitData * self , <nl> vector < CommitTransactionRequest > trs , <nl> ACTOR Future < Void > commitBatch ( <nl> state double t1 = now ( ) ; <nl> state Optional < UID > debugID ; <nl> state bool forceRecovery = false ; <nl> + state int batchOperations = 0 ; <nl> + int64_t batchBytes = 0 ; <nl> + for ( int t = 0 ; t < trs . size ( ) ; t + + ) { <nl> + batchOperations + = trs [ t ] . transaction . mutations . size ( ) ; <nl> + batchBytes + = trs [ t ] . transaction . mutations . expectedSize ( ) ; <nl> + } <nl> + state int latencyBucket = batchOperations = = 0 ? 0 : std : : min < int > ( SERVER_KNOBS - > PROXY_COMPUTE_BUCKETS - 1 , SERVER_KNOBS - > PROXY_COMPUTE_BUCKETS * batchBytes / ( batchOperations * ( CLIENT_KNOBS - > VALUE_SIZE_LIMIT + CLIENT_KNOBS - > KEY_SIZE_LIMIT ) ) ) ; <nl> <nl> ASSERT ( SERVER_KNOBS - > MAX_READ_TRANSACTION_LIFE_VERSIONS < = SERVER_KNOBS - > MAX_VERSIONS_IN_FLIGHT ) ; / / since we are using just the former to limit the number of versions actually in flight ! <nl> <nl> ACTOR Future < Void > commitBatch ( <nl> / / Queuing pre - resolution commit processing <nl> TEST ( self - > latestLocalCommitBatchResolving . get ( ) < localBatchNumber - 1 ) ; <nl> wait ( self - > latestLocalCommitBatchResolving . whenAtLeast ( localBatchNumber - 1 ) ) ; <nl> - wait ( yield ( TaskPriority : : ProxyCommitYield1 ) ) ; <nl> + state Future < Void > releaseDelay = delay ( batchOperations * self - > commitComputePerOperation [ latencyBucket ] , TaskPriority : : ProxyMasterVersionReply ) ; <nl> <nl> if ( debugID . present ( ) ) <nl> g_traceBatch . addEvent ( " CommitDebug " , debugID . get ( ) . first ( ) , " MasterProxyServer . commitBatch . GettingCommitVersion " ) ; <nl> ACTOR Future < Void > commitBatch ( <nl> } <nl> <nl> state vector < vector < int > > transactionResolverMap = std : : move ( requests . transactionResolverMap ) ; <nl> - <nl> - ASSERT ( self - > latestLocalCommitBatchResolving . get ( ) = = localBatchNumber - 1 ) ; <nl> - self - > latestLocalCommitBatchResolving . set ( localBatchNumber ) ; <nl> + state Future < Void > releaseFuture = releaseResolvingAfter ( self , releaseDelay , localBatchNumber ) ; <nl> <nl> / / / / / / / Phase 2 : Resolution ( waiting on the network ; pipelined ) <nl> state vector < ResolveTransactionBatchReply > resolution = wait ( getAll ( replies ) ) ; <nl> ACTOR Future < Void > commitBatch ( <nl> / / / / / / Phase 3 : Post - resolution processing ( CPU bound except for very rare situations ; ordered ; currently atomic but doesn ' t need to be ) <nl> TEST ( self - > latestLocalCommitBatchLogging . get ( ) < localBatchNumber - 1 ) ; / / Queuing post - resolution commit processing <nl> wait ( self - > latestLocalCommitBatchLogging . whenAtLeast ( localBatchNumber - 1 ) ) ; <nl> - wait ( yield ( TaskPriority : : ProxyCommitYield2 ) ) ; <nl> + wait ( yield ( TaskPriority : : ProxyCommitYield1 ) ) ; <nl> <nl> + state double computeStart = g_network - > timer ( ) ; <nl> + state double computeDuration = 0 ; <nl> self - > stats . txnCommitResolved + = trs . size ( ) ; <nl> <nl> if ( debugID . present ( ) ) <nl> ACTOR Future < Void > commitBatch ( <nl> for ( ; mutationNum < pMutations - > size ( ) ; mutationNum + + ) { <nl> if ( yieldBytes > SERVER_KNOBS - > DESIRED_TOTAL_BYTES ) { <nl> yieldBytes = 0 ; <nl> - wait ( yield ( TaskPriority : : ProxyCommitYield2 ) ) ; <nl> + if ( g_network - > check_yield ( TaskPriority : : ProxyCommitYield1 ) ) { <nl> + computeDuration + = g_network - > timer ( ) - computeStart ; <nl> + wait ( delay ( 0 , TaskPriority : : ProxyCommitYield1 ) ) ; <nl> + computeStart = g_network - > timer ( ) ; <nl> + } <nl> } <nl> <nl> auto & m = ( * pMutations ) [ mutationNum ] ; <nl> ACTOR Future < Void > commitBatch ( <nl> <nl> / / Serialize and backup the mutations as a single mutation <nl> if ( ( self - > vecBackupKeys . size ( ) > 1 ) & & logRangeMutations . size ( ) ) { <nl> - wait ( addBackupMutations ( self , & logRangeMutations , & toCommit , commitVersion ) ) ; <nl> + wait ( addBackupMutations ( self , & logRangeMutations , & toCommit , commitVersion , & computeDuration , & computeStart ) ) ; <nl> } <nl> <nl> self - > stats . mutations + = mutationCount ; <nl> ACTOR Future < Void > commitBatch ( <nl> <nl> / / Storage servers mustn ' t make durable versions which are not fully committed ( because then they are impossible to roll back ) <nl> / / We prevent this by limiting the number of versions which are semi - committed but not fully committed to be less than the MVCC window <nl> - while ( self - > committedVersion . get ( ) < commitVersion - SERVER_KNOBS - > MAX_READ_TRANSACTION_LIFE_VERSIONS ) { <nl> - / / This should be * extremely * rare in the real world , but knob buggification should make it happen in simulation <nl> - TEST ( true ) ; / / Semi - committed pipeline limited by MVCC window <nl> - / / TraceEvent ( " ProxyWaitingForCommitted " , self - > dbgid ) . detail ( " CommittedVersion " , self - > committedVersion . get ( ) ) . detail ( " NeedToCommit " , commitVersion ) ; <nl> - choose { <nl> - when ( wait ( self - > committedVersion . whenAtLeast ( commitVersion - SERVER_KNOBS - > MAX_READ_TRANSACTION_LIFE_VERSIONS ) ) ) { <nl> - wait ( yield ( ) ) ; <nl> - break ; <nl> - } <nl> - when ( GetReadVersionReply v = wait ( self - > getConsistentReadVersion . getReply ( GetReadVersionRequest ( 0 , GetReadVersionRequest : : PRIORITY_SYSTEM_IMMEDIATE | GetReadVersionRequest : : FLAG_CAUSAL_READ_RISKY ) ) ) ) { <nl> - if ( v . version > self - > committedVersion . get ( ) ) { <nl> - self - > locked = v . locked ; <nl> - self - > metadataVersion = v . metadataVersion ; <nl> - self - > committedVersion . set ( v . version ) ; <nl> + if ( self - > committedVersion . get ( ) < commitVersion - SERVER_KNOBS - > MAX_READ_TRANSACTION_LIFE_VERSIONS ) { <nl> + computeDuration + = g_network - > timer ( ) - computeStart ; <nl> + while ( self - > committedVersion . get ( ) < commitVersion - SERVER_KNOBS - > MAX_READ_TRANSACTION_LIFE_VERSIONS ) { <nl> + / / This should be * extremely * rare in the real world , but knob buggification should make it happen in simulation <nl> + TEST ( true ) ; / / Semi - committed pipeline limited by MVCC window <nl> + / / TraceEvent ( " ProxyWaitingForCommitted " , self - > dbgid ) . detail ( " CommittedVersion " , self - > committedVersion . get ( ) ) . detail ( " NeedToCommit " , commitVersion ) ; <nl> + choose { <nl> + when ( wait ( self - > committedVersion . whenAtLeast ( commitVersion - SERVER_KNOBS - > MAX_READ_TRANSACTION_LIFE_VERSIONS ) ) ) { <nl> + wait ( yield ( ) ) ; <nl> + break ; <nl> + } <nl> + when ( GetReadVersionReply v = wait ( self - > getConsistentReadVersion . getReply ( GetReadVersionRequest ( 0 , GetReadVersionRequest : : PRIORITY_SYSTEM_IMMEDIATE | GetReadVersionRequest : : FLAG_CAUSAL_READ_RISKY ) ) ) ) { <nl> + if ( v . version > self - > committedVersion . get ( ) ) { <nl> + self - > locked = v . locked ; <nl> + self - > metadataVersion = v . metadataVersion ; <nl> + self - > committedVersion . set ( v . version ) ; <nl> + } <nl> + <nl> + if ( self - > committedVersion . get ( ) < commitVersion - SERVER_KNOBS - > MAX_READ_TRANSACTION_LIFE_VERSIONS ) <nl> + wait ( delay ( SERVER_KNOBS - > PROXY_SPIN_DELAY ) ) ; <nl> } <nl> - <nl> - if ( self - > committedVersion . get ( ) < commitVersion - SERVER_KNOBS - > MAX_READ_TRANSACTION_LIFE_VERSIONS ) <nl> - wait ( delay ( SERVER_KNOBS - > PROXY_SPIN_DELAY ) ) ; <nl> } <nl> } <nl> + computeStart = g_network - > timer ( ) ; <nl> } <nl> <nl> - state LogSystemDiskQueueAdapter : : CommitMessage msg = wait ( storeCommits . back ( ) . first ) ; / / Should just be doing yields <nl> + state LogSystemDiskQueueAdapter : : CommitMessage msg = storeCommits . back ( ) . first . get ( ) ; <nl> <nl> if ( debugID . present ( ) ) <nl> g_traceBatch . addEvent ( " CommitDebug " , debugID . get ( ) . first ( ) , " MasterProxyServer . commitBatch . AfterStoreCommits " ) ; <nl> ACTOR Future < Void > commitBatch ( <nl> self - > latestLocalCommitBatchLogging . set ( localBatchNumber ) ; <nl> } <nl> <nl> + computeDuration + = g_network - > timer ( ) - computeStart ; <nl> + if ( computeDuration > SERVER_KNOBS - > MIN_PROXY_COMPUTE & & batchOperations > 0 ) { <nl> + double computePerOperation = computeDuration / batchOperations ; <nl> + if ( computePerOperation < = self - > commitComputePerOperation [ latencyBucket ] | | self - > commitComputePerOperation [ latencyBucket ] = = 0 . 0 ) { <nl> + self - > commitComputePerOperation [ latencyBucket ] = computePerOperation ; <nl> + } else { <nl> + self - > commitComputePerOperation [ latencyBucket ] = SERVER_KNOBS - > PROXY_COMPUTE_GROWTH_RATE * computePerOperation + ( ( 1 . 0 - SERVER_KNOBS - > PROXY_COMPUTE_GROWTH_RATE ) * self - > commitComputePerOperation [ latencyBucket ] ) ; <nl> + } <nl> + } <nl> + <nl> / / / / / / / Phase 4 : Logging ( network bound ; pipelined up to MAX_READ_TRANSACTION_LIFE_VERSIONS ( limited by loop above ) ) <nl> <nl> try { <nl> ACTOR Future < Void > commitBatch ( <nl> } <nl> self - > lastCommitLatency = now ( ) - commitStartTime ; <nl> self - > lastCommitTime = std : : max ( self - > lastCommitTime . get ( ) , commitStartTime ) ; <nl> - wait ( yield ( TaskPriority : : ProxyCommitYield3 ) ) ; <nl> + wait ( yield ( TaskPriority : : ProxyCommitYield2 ) ) ; <nl> <nl> if ( self - > popRemoteTxs & & msg . popTo > ( self - > txsPopVersions . size ( ) ? self - > txsPopVersions . back ( ) . second : self - > lastTxsPop ) ) { <nl> if ( self - > txsPopVersions . size ( ) > = SERVER_KNOBS - > MAX_TXS_POP_VERSION_HISTORY ) { <nl> ACTOR Future < Void > commitBatch ( <nl> } <nl> <nl> / / Send replies to clients <nl> - double endTime = timer ( ) ; <nl> + double endTime = g_network - > timer ( ) ; <nl> for ( int t = 0 ; t < trs . size ( ) ; t + + ) { <nl> if ( committed [ t ] = = ConflictBatch : : TransactionCommitted & & ( ! locked | | trs [ t ] . isLockAware ( ) ) ) { <nl> ASSERT_WE_THINK ( commitVersion ! = invalidVersion ) ; <nl> ACTOR Future < Void > commitBatch ( <nl> <nl> self - > commitBatchesMemBytesCount - = currentBatchMemBytesCount ; <nl> ASSERT_ABORT ( self - > commitBatchesMemBytesCount > = 0 ) ; <nl> + wait ( releaseFuture ) ; <nl> return Void ( ) ; <nl> } <nl> <nl> ACTOR Future < GetReadVersionReply > getLiveCommittedVersion ( ProxyCommitData * commi <nl> ACTOR Future < Void > sendGrvReplies ( Future < GetReadVersionReply > replyFuture , std : : vector < GetReadVersionRequest > requests , <nl> ProxyStats * stats , Version minKnownCommittedVersion ) { <nl> GetReadVersionReply reply = wait ( replyFuture ) ; <nl> - <nl> - double end = timer ( ) ; <nl> + double end = g_network - > timer ( ) ; <nl> for ( GetReadVersionRequest const & request : requests ) { <nl> if ( request . priority ( ) > = GetReadVersionRequest : : PRIORITY_DEFAULT ) { <nl> stats - > grvLatencyBands . addMeasurement ( end - request . requestTime ( ) ) ; <nl> ACTOR static Future < Void > rejoinServer ( MasterProxyInterface proxy , ProxyCommitD <nl> GetStorageServerRejoinInfoReply rep ; <nl> rep . version = commitData - > version ; <nl> rep . tag = decodeServerTagValue ( commitData - > txnStateStore - > readValue ( serverTagKeyFor ( req . id ) ) . get ( ) . get ( ) ) ; <nl> - Standalone < VectorRef < KeyValueRef > > history = commitData - > txnStateStore - > readRange ( serverTagHistoryRangeFor ( req . id ) ) . get ( ) ; <nl> + Standalone < RangeResultRef > history = commitData - > txnStateStore - > readRange ( serverTagHistoryRangeFor ( req . id ) ) . get ( ) ; <nl> for ( int i = history . size ( ) - 1 ; i > = 0 ; i - - ) { <nl> rep . history . push_back ( std : : make_pair ( decodeServerTagHistoryKey ( history [ i ] . key ) , decodeServerTagValue ( history [ i ] . value ) ) ) ; <nl> } <nl> ACTOR Future < Void > masterProxyServerCore ( <nl> state KeyRange txnKeys = allKeys ; <nl> loop { <nl> wait ( yield ( ) ) ; <nl> - Standalone < VectorRef < KeyValueRef > > data = commitData . txnStateStore - > readRange ( txnKeys , SERVER_KNOBS - > BUGGIFIED_ROW_LIMIT , SERVER_KNOBS - > APPLY_MUTATION_BYTES ) . get ( ) ; <nl> + Standalone < RangeResultRef > data = commitData . txnStateStore - > readRange ( txnKeys , SERVER_KNOBS - > BUGGIFIED_ROW_LIMIT , SERVER_KNOBS - > APPLY_MUTATION_BYTES ) . get ( ) ; <nl> if ( ! data . size ( ) ) break ; <nl> ( ( KeyRangeRef & ) txnKeys ) = KeyRangeRef ( keyAfter ( data . back ( ) . key , txnKeys . arena ( ) ) , txnKeys . end ) ; <nl> <nl> mmm a / fdbserver / OldTLogServer_4_6 . actor . cpp <nl> ppp b / fdbserver / OldTLogServer_4_6 . actor . cpp <nl> namespace oldTLog_4_6 { <nl> std : : map < UID , Reference < struct LogData > > id_data ; <nl> <nl> UID dbgid ; <nl> + UID workerID ; <nl> <nl> IKeyValueStore * persistentData ; <nl> IDiskQueue * rawPersistentQueue ; <nl> namespace oldTLog_4_6 { <nl> PromiseStream < Future < Void > > sharedActors ; <nl> bool terminated ; <nl> <nl> - TLogData ( UID dbgid , IKeyValueStore * persistentData , IDiskQueue * persistentQueue , Reference < AsyncVar < ServerDBInfo > > const & dbInfo ) <nl> - : dbgid ( dbgid ) , instanceID ( deterministicRandom ( ) - > randomUniqueID ( ) . first ( ) ) , <nl> + TLogData ( UID dbgid , UID workerID , IKeyValueStore * persistentData , IDiskQueue * persistentQueue , Reference < AsyncVar < ServerDBInfo > > const & dbInfo ) <nl> + : dbgid ( dbgid ) , workerID ( workerID ) , instanceID ( deterministicRandom ( ) - > randomUniqueID ( ) . first ( ) ) , <nl> persistentData ( persistentData ) , rawPersistentQueue ( persistentQueue ) , persistentQueue ( new TLogQueue ( persistentQueue , dbgid ) ) , <nl> dbInfo ( dbInfo ) , queueCommitBegin ( 0 ) , queueCommitEnd ( 0 ) , prevVersion ( 0 ) , <nl> diskQueueCommitBytes ( 0 ) , largeDiskQueueCommitBytes ( false ) , <nl> namespace oldTLog_4_6 { <nl> / / These are initialized differently on init ( ) or recovery <nl> recoveryCount ( ) , stopped ( false ) , initialized ( false ) , queueCommittingVersion ( 0 ) , newPersistentDataVersion ( invalidVersion ) , recovery ( Void ( ) ) <nl> { <nl> - startRole ( Role : : TRANSACTION_LOG , interf . id ( ) , UID ( ) ) ; <nl> + startRole ( Role : : TRANSACTION_LOG , interf . id ( ) , tLogData - > workerID , { { " SharedTLog " , tLogData - > dbgid . shortString ( ) } } , " Restored " ) ; <nl> <nl> persistentDataVersion . init ( LiteralStringRef ( " TLog . PersistentDataVersion " ) , cc . id ) ; <nl> persistentDataDurableVersion . init ( LiteralStringRef ( " TLog . PersistentDataDurableVersion " ) , cc . id ) ; <nl> namespace oldTLog_4_6 { <nl> <nl> peekMessagesFromMemory ( logData , req , messages2 , endVersion ) ; <nl> <nl> - Standalone < VectorRef < KeyValueRef > > kvs = wait ( <nl> + Standalone < RangeResultRef > kvs = wait ( <nl> self - > persistentData - > readRange ( KeyRangeRef ( <nl> persistTagMessagesKey ( logData - > logId , oldTag , req . begin ) , <nl> persistTagMessagesKey ( logData - > logId , oldTag , logData - > persistentDataDurableVersion + 1 ) ) , SERVER_KNOBS - > DESIRED_TOTAL_BYTES , SERVER_KNOBS - > DESIRED_TOTAL_BYTES ) ) ; <nl> namespace oldTLog_4_6 { <nl> / / The TLogRejoinRequest is needed to establish communications with a new master , which doesn ' t have our TLogInterface <nl> TLogRejoinRequest req ; <nl> req . myInterface = tli ; <nl> - TraceEvent ( " TLogRejoining " , self - > dbgid ) . detail ( " Master " , self - > dbInfo - > get ( ) . master . id ( ) ) ; <nl> + TraceEvent ( " TLogRejoining " , tli . id ( ) ) . detail ( " Master " , self - > dbInfo - > get ( ) . master . id ( ) ) ; <nl> choose { <nl> when ( TLogRejoinReply rep = <nl> wait ( brokenPromiseToNever ( self - > dbInfo - > get ( ) . master . tlogRejoin . getReply ( req ) ) ) ) { <nl> namespace oldTLog_4_6 { <nl> <nl> IKeyValueStore * storage = self - > persistentData ; <nl> state Future < Optional < Value > > fFormat = storage - > readValue ( persistFormat . key ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fVers = storage - > readRange ( persistCurrentVersionKeys ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fRecoverCounts = storage - > readRange ( persistRecoveryCountKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fVers = storage - > readRange ( persistCurrentVersionKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fRecoverCounts = storage - > readRange ( persistRecoveryCountKeys ) ; <nl> <nl> / / FIXME : metadata in queue ? <nl> <nl> namespace oldTLog_4_6 { <nl> } <nl> <nl> if ( ! fFormat . get ( ) . present ( ) ) { <nl> - Standalone < VectorRef < KeyValueRef > > v = wait ( self - > persistentData - > readRange ( KeyRangeRef ( StringRef ( ) , LiteralStringRef ( " \ xff " ) ) , 1 ) ) ; <nl> + Standalone < RangeResultRef > v = wait ( self - > persistentData - > readRange ( KeyRangeRef ( StringRef ( ) , LiteralStringRef ( " \ xff " ) ) , 1 ) ) ; <nl> if ( ! v . size ( ) ) { <nl> TEST ( true ) ; / / The DB is completely empty , so it was never initialized . Delete it . <nl> throw worker_removed ( ) ; <nl> namespace oldTLog_4_6 { <nl> tagKeys = prefixRange ( rawId . withPrefix ( persistTagPoppedKeys . begin ) ) ; <nl> loop { <nl> if ( logData - > removed . isReady ( ) ) break ; <nl> - Standalone < VectorRef < KeyValueRef > > data = wait ( self - > persistentData - > readRange ( tagKeys , BUGGIFY ? 3 : 1 < < 30 , 1 < < 20 ) ) ; <nl> + Standalone < RangeResultRef > data = wait ( self - > persistentData - > readRange ( tagKeys , BUGGIFY ? 3 : 1 < < 30 , 1 < < 20 ) ) ; <nl> if ( ! data . size ( ) ) break ; <nl> ( ( KeyRangeRef & ) tagKeys ) = KeyRangeRef ( keyAfter ( data . back ( ) . key , tagKeys . arena ( ) ) , tagKeys . end ) ; <nl> <nl> namespace oldTLog_4_6 { <nl> return Void ( ) ; <nl> } <nl> <nl> - ACTOR Future < Void > tLog ( IKeyValueStore * persistentData , IDiskQueue * persistentQueue , Reference < AsyncVar < ServerDBInfo > > db , LocalityData locality , UID tlogId ) <nl> + ACTOR Future < Void > tLog ( IKeyValueStore * persistentData , IDiskQueue * persistentQueue , Reference < AsyncVar < ServerDBInfo > > db , LocalityData locality , UID tlogId , UID workerID ) <nl> { <nl> - state TLogData self ( tlogId , persistentData , persistentQueue , db ) ; <nl> + state TLogData self ( tlogId , workerID , persistentData , persistentQueue , db ) ; <nl> state Future < Void > error = actorCollection ( self . sharedActors . getFuture ( ) ) ; <nl> <nl> TraceEvent ( " SharedTlog " , tlogId ) ; <nl> mmm a / fdbserver / OldTLogServer_6_0 . actor . cpp <nl> ppp b / fdbserver / OldTLogServer_6_0 . actor . cpp <nl> struct TLogData : NonCopyable { <nl> std : : map < UID , Reference < struct LogData > > id_data ; <nl> <nl> UID dbgid ; <nl> + UID workerID ; <nl> <nl> IKeyValueStore * persistentData ; <nl> IDiskQueue * rawPersistentQueue ; <nl> struct TLogData : NonCopyable { <nl> Reference < AsyncVar < bool > > degraded ; <nl> std : : vector < TagsAndMessage > tempTagMessages ; <nl> <nl> - TLogData ( UID dbgid , IKeyValueStore * persistentData , IDiskQueue * persistentQueue , Reference < AsyncVar < ServerDBInfo > > dbInfo , Reference < AsyncVar < bool > > degraded , std : : string folder ) <nl> - : dbgid ( dbgid ) , instanceID ( deterministicRandom ( ) - > randomUniqueID ( ) . first ( ) ) , <nl> + TLogData ( UID dbgid , UID workerID , IKeyValueStore * persistentData , IDiskQueue * persistentQueue , Reference < AsyncVar < ServerDBInfo > > dbInfo , Reference < AsyncVar < bool > > degraded , std : : string folder ) <nl> + : dbgid ( dbgid ) , workerID ( workerID ) , instanceID ( deterministicRandom ( ) - > randomUniqueID ( ) . first ( ) ) , <nl> persistentData ( persistentData ) , rawPersistentQueue ( persistentQueue ) , persistentQueue ( new TLogQueue ( persistentQueue , dbgid ) ) , <nl> dbInfo ( dbInfo ) , degraded ( degraded ) , queueCommitBegin ( 0 ) , queueCommitEnd ( 0 ) , <nl> diskQueueCommitBytes ( 0 ) , largeDiskQueueCommitBytes ( false ) , bytesInput ( 0 ) , bytesDurable ( 0 ) , targetVolatileBytes ( SERVER_KNOBS - > TLOG_SPILL_THRESHOLD ) , overheadBytesInput ( 0 ) , overheadBytesDurable ( 0 ) , <nl> struct LogData : NonCopyable , public ReferenceCounted < LogData > { <nl> bool execOpCommitInProgress ; <nl> int txsTags ; <nl> <nl> - explicit LogData ( TLogData * tLogData , TLogInterface interf , Tag remoteTag , bool isPrimary , int logRouterTags , int txsTags , UID recruitmentID , std : : vector < Tag > tags ) : tLogData ( tLogData ) , knownCommittedVersion ( 0 ) , logId ( interf . id ( ) ) , <nl> - cc ( " TLog " , interf . id ( ) . toString ( ) ) , bytesInput ( " BytesInput " , cc ) , bytesDurable ( " BytesDurable " , cc ) , remoteTag ( remoteTag ) , isPrimary ( isPrimary ) , logRouterTags ( logRouterTags ) , txsTags ( txsTags ) , recruitmentID ( recruitmentID ) , <nl> - logSystem ( new AsyncVar < Reference < ILogSystem > > ( ) ) , logRouterPoppedVersion ( 0 ) , durableKnownCommittedVersion ( 0 ) , minKnownCommittedVersion ( 0 ) , allTags ( tags . begin ( ) , tags . end ( ) ) , terminated ( tLogData - > terminated . getFuture ( ) ) , <nl> - / / These are initialized differently on init ( ) or recovery <nl> - recoveryCount ( ) , stopped ( false ) , initialized ( false ) , queueCommittingVersion ( 0 ) , newPersistentDataVersion ( invalidVersion ) , unrecoveredBefore ( 1 ) , recoveredAt ( 1 ) , unpoppedRecoveredTags ( 0 ) , <nl> - logRouterPopToVersion ( 0 ) , locality ( tagLocalityInvalid ) , execOpCommitInProgress ( false ) <nl> + explicit LogData ( TLogData * tLogData , TLogInterface interf , Tag remoteTag , bool isPrimary , int logRouterTags , int txsTags , UID recruitmentID , std : : vector < Tag > tags , std : : string context ) <nl> + : tLogData ( tLogData ) , knownCommittedVersion ( 0 ) , logId ( interf . id ( ) ) , <nl> + cc ( " TLog " , interf . id ( ) . toString ( ) ) , bytesInput ( " BytesInput " , cc ) , bytesDurable ( " BytesDurable " , cc ) , remoteTag ( remoteTag ) , isPrimary ( isPrimary ) , logRouterTags ( logRouterTags ) , txsTags ( txsTags ) , recruitmentID ( recruitmentID ) , <nl> + logSystem ( new AsyncVar < Reference < ILogSystem > > ( ) ) , logRouterPoppedVersion ( 0 ) , durableKnownCommittedVersion ( 0 ) , minKnownCommittedVersion ( 0 ) , allTags ( tags . begin ( ) , tags . end ( ) ) , terminated ( tLogData - > terminated . getFuture ( ) ) , <nl> + / / These are initialized differently on init ( ) or recovery <nl> + recoveryCount ( ) , stopped ( false ) , initialized ( false ) , queueCommittingVersion ( 0 ) , newPersistentDataVersion ( invalidVersion ) , unrecoveredBefore ( 1 ) , recoveredAt ( 1 ) , unpoppedRecoveredTags ( 0 ) , <nl> + logRouterPopToVersion ( 0 ) , locality ( tagLocalityInvalid ) , execOpCommitInProgress ( false ) <nl> { <nl> - startRole ( Role : : TRANSACTION_LOG , interf . id ( ) , UID ( ) ) ; <nl> + startRole ( Role : : TRANSACTION_LOG , interf . id ( ) , tLogData - > workerID , { { " SharedTLog " , tLogData - > dbgid . shortString ( ) } } , context ) ; <nl> <nl> persistentDataVersion . init ( LiteralStringRef ( " TLog . PersistentDataVersion " ) , cc . id ) ; <nl> persistentDataDurableVersion . init ( LiteralStringRef ( " TLog . PersistentDataDurableVersion " ) , cc . id ) ; <nl> ACTOR Future < Void > tLogPeekMessages ( TLogData * self , TLogPeekRequest req , Refere <nl> peekMessagesFromMemory ( logData , req , messages2 , endVersion ) ; <nl> } <nl> <nl> - Standalone < VectorRef < KeyValueRef > > kvs = wait ( <nl> + Standalone < RangeResultRef > kvs = wait ( <nl> self - > persistentData - > readRange ( KeyRangeRef ( <nl> persistTagMessagesKey ( logData - > logId , req . tag , req . begin ) , <nl> persistTagMessagesKey ( logData - > logId , req . tag , logData - > persistentDataDurableVersion + 1 ) ) , SERVER_KNOBS - > DESIRED_TOTAL_BYTES , SERVER_KNOBS - > DESIRED_TOTAL_BYTES ) ) ; <nl> ACTOR Future < Void > watchDegraded ( TLogData * self ) { <nl> return Void ( ) ; <nl> } <nl> <nl> - / / This delay is divided into multiple delays to avoid marking the tlog as degraded because of a single SlowTask <nl> - state int loopCount = 0 ; <nl> - while ( loopCount < SERVER_KNOBS - > TLOG_DEGRADED_DELAY_COUNT ) { <nl> - wait ( delay ( SERVER_KNOBS - > TLOG_DEGRADED_DURATION / SERVER_KNOBS - > TLOG_DEGRADED_DELAY_COUNT , TaskPriority : : Low ) ) ; <nl> - loopCount + + ; <nl> - } <nl> + wait ( lowPriorityDelay ( SERVER_KNOBS - > TLOG_DEGRADED_DURATION ) ) ; <nl> + <nl> TraceEvent ( SevWarnAlways , " TLogDegraded " , self - > dbgid ) ; <nl> TEST ( true ) ; / / 6 . 0 TLog degraded <nl> self - > degraded - > set ( true ) ; <nl> ACTOR Future < Void > rejoinMasters ( TLogData * self , TLogInterface tli , DBRecoveryC <nl> if ( self - > dbInfo - > get ( ) . master . id ( ) ! = lastMasterID ) { <nl> / / The TLogRejoinRequest is needed to establish communications with a new master , which doesn ' t have our TLogInterface <nl> TLogRejoinRequest req ( tli ) ; <nl> - TraceEvent ( " TLogRejoining " , self - > dbgid ) . detail ( " Master " , self - > dbInfo - > get ( ) . master . id ( ) ) ; <nl> + TraceEvent ( " TLogRejoining " , tli . id ( ) ) . detail ( " Master " , self - > dbInfo - > get ( ) . master . id ( ) ) ; <nl> choose { <nl> when ( TLogRejoinReply rep = <nl> wait ( brokenPromiseToNever ( self - > dbInfo - > get ( ) . master . tlogRejoin . getReply ( req ) ) ) ) { <nl> ACTOR Future < Void > restorePersistentState ( TLogData * self , LocalityData locality <nl> state IKeyValueStore * storage = self - > persistentData ; <nl> wait ( storage - > init ( ) ) ; <nl> state Future < Optional < Value > > fFormat = storage - > readValue ( persistFormat . key ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fVers = storage - > readRange ( persistCurrentVersionKeys ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fKnownCommitted = storage - > readRange ( persistKnownCommittedVersionKeys ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fLocality = storage - > readRange ( persistLocalityKeys ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fLogRouterTags = storage - > readRange ( persistLogRouterTagsKeys ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fTxsTags = storage - > readRange ( persistTxsTagsKeys ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fRecoverCounts = storage - > readRange ( persistRecoveryCountKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fVers = storage - > readRange ( persistCurrentVersionKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fKnownCommitted = storage - > readRange ( persistKnownCommittedVersionKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fLocality = storage - > readRange ( persistLocalityKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fLogRouterTags = storage - > readRange ( persistLogRouterTagsKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fTxsTags = storage - > readRange ( persistTxsTagsKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fRecoverCounts = storage - > readRange ( persistRecoveryCountKeys ) ; <nl> <nl> / / FIXME : metadata in queue ? <nl> <nl> ACTOR Future < Void > restorePersistentState ( TLogData * self , LocalityData locality <nl> } <nl> <nl> if ( ! fFormat . get ( ) . present ( ) ) { <nl> - Standalone < VectorRef < KeyValueRef > > v = wait ( self - > persistentData - > readRange ( KeyRangeRef ( StringRef ( ) , LiteralStringRef ( " \ xff " ) ) , 1 ) ) ; <nl> + Standalone < RangeResultRef > v = wait ( self - > persistentData - > readRange ( KeyRangeRef ( StringRef ( ) , LiteralStringRef ( " \ xff " ) ) , 1 ) ) ; <nl> if ( ! v . size ( ) ) { <nl> TEST ( true ) ; / / The DB is completely empty , so it was never initialized . Delete it . <nl> throw worker_removed ( ) ; <nl> ACTOR Future < Void > restorePersistentState ( TLogData * self , LocalityData locality <nl> tlogRequests . getFuture ( ) . pop ( ) . reply . sendError ( recruitment_failed ( ) ) ; <nl> } <nl> <nl> - wait ( oldTLog_4_6 : : tLog ( self - > persistentData , self - > rawPersistentQueue , self - > dbInfo , locality , self - > dbgid ) ) ; <nl> + wait ( oldTLog_4_6 : : tLog ( self - > persistentData , self - > rawPersistentQueue , self - > dbInfo , locality , self - > dbgid , self - > workerID ) ) ; <nl> throw internal_error ( ) ; <nl> } <nl> <nl> ACTOR Future < Void > restorePersistentState ( TLogData * self , LocalityData locality <nl> DUMPTOKEN ( recruited . confirmRunning ) ; <nl> <nl> / / We do not need the remoteTag , because we will not be loading any additional data <nl> - logData = Reference < LogData > ( new LogData ( self , recruited , Tag ( ) , true , id_logRouterTags [ id1 ] , id_txsTags [ id1 ] , UID ( ) , std : : vector < Tag > ( ) ) ) ; <nl> + logData = Reference < LogData > ( new LogData ( self , recruited , Tag ( ) , true , id_logRouterTags [ id1 ] , id_txsTags [ id1 ] , UID ( ) , std : : vector < Tag > ( ) , " Restored " ) ) ; <nl> logData - > locality = id_locality [ id1 ] ; <nl> logData - > stopped = true ; <nl> self - > id_data [ id1 ] = logData ; <nl> ACTOR Future < Void > restorePersistentState ( TLogData * self , LocalityData locality <nl> tagKeys = prefixRange ( rawId . withPrefix ( persistTagPoppedKeys . begin ) ) ; <nl> loop { <nl> if ( logData - > removed . isReady ( ) ) break ; <nl> - Standalone < VectorRef < KeyValueRef > > data = wait ( self - > persistentData - > readRange ( tagKeys , BUGGIFY ? 3 : 1 < < 30 , 1 < < 20 ) ) ; <nl> + Standalone < RangeResultRef > data = wait ( self - > persistentData - > readRange ( tagKeys , BUGGIFY ? 3 : 1 < < 30 , 1 < < 20 ) ) ; <nl> if ( ! data . size ( ) ) break ; <nl> ( ( KeyRangeRef & ) tagKeys ) = KeyRangeRef ( keyAfter ( data . back ( ) . key , tagKeys . arena ( ) ) , tagKeys . end ) ; <nl> <nl> ACTOR Future < Void > tLogStart ( TLogData * self , InitializeTLogRequest req , Localit <nl> it . second - > stopCommit . trigger ( ) ; <nl> } <nl> <nl> - state Reference < LogData > logData = Reference < LogData > ( new LogData ( self , recruited , req . remoteTag , req . isPrimary , req . logRouterTags , req . txsTags , req . recruitmentID , req . allTags ) ) ; <nl> + bool recovering = ( req . recoverFrom . logSystemType = = LogSystemType : : tagPartitioned ) ; <nl> + state Reference < LogData > logData = Reference < LogData > ( new LogData ( self , recruited , req . remoteTag , req . isPrimary , req . logRouterTags , req . txsTags , req . recruitmentID , req . allTags , recovering ? " Recovered " : " Recruited " ) ) ; <nl> self - > id_data [ recruited . id ( ) ] = logData ; <nl> logData - > locality = req . locality ; <nl> logData - > recoveryCount = req . epoch ; <nl> ACTOR Future < Void > tLogStart ( TLogData * self , InitializeTLogRequest req , Localit <nl> throw logData - > removed . getError ( ) ; <nl> } <nl> <nl> - if ( req . recoverFrom . logSystemType = = LogSystemType : : tagPartitioned ) { <nl> + if ( recovering ) { <nl> logData - > unrecoveredBefore = req . startVersion ; <nl> logData - > recoveredAt = req . recoverAt ; <nl> logData - > knownCommittedVersion = req . startVersion - 1 ; <nl> ACTOR Future < Void > startSpillingInTenSeconds ( TLogData * self , UID tlogId , Referen <nl> } <nl> <nl> / / New tLog ( if ! recoverFrom . size ( ) ) or restore from network <nl> - ACTOR Future < Void > tLog ( IKeyValueStore * persistentData , IDiskQueue * persistentQueue , Reference < AsyncVar < ServerDBInfo > > db , LocalityData locality , PromiseStream < InitializeTLogRequest > tlogRequests , UID tlogId , bool restoreFromDisk , Promise < Void > oldLog , Promise < Void > recovered , std : : string folder , Reference < AsyncVar < bool > > degraded , Reference < AsyncVar < UID > > activeSharedTLog ) { <nl> - state TLogData self ( tlogId , persistentData , persistentQueue , db , degraded , folder ) ; <nl> + ACTOR Future < Void > tLog ( IKeyValueStore * persistentData , IDiskQueue * persistentQueue , Reference < AsyncVar < ServerDBInfo > > db , LocalityData locality , PromiseStream < InitializeTLogRequest > tlogRequests , UID tlogId , UID workerID , bool restoreFromDisk , Promise < Void > oldLog , Promise < Void > recovered , std : : string folder , Reference < AsyncVar < bool > > degraded , Reference < AsyncVar < UID > > activeSharedTLog ) { <nl> + state TLogData self ( tlogId , workerID , persistentData , persistentQueue , db , degraded , folder ) ; <nl> state Future < Void > error = actorCollection ( self . sharedActors . getFuture ( ) ) ; <nl> <nl> TraceEvent ( " SharedTlog " , tlogId ) ; <nl> - / / FIXME : Pass the worker id instead of stubbing it <nl> - startRole ( Role : : SHARED_TRANSACTION_LOG , tlogId , UID ( ) ) ; <nl> try { <nl> if ( restoreFromDisk ) { <nl> wait ( restorePersistentState ( & self , locality , oldLog , recovered , tlogRequests ) ) ; <nl> ACTOR Future < Void > tLog ( IKeyValueStore * persistentData , IDiskQueue * persistentQ <nl> } catch ( Error & e ) { <nl> self . terminated . send ( Void ( ) ) ; <nl> TraceEvent ( " TLogError " , tlogId ) . error ( e , true ) ; <nl> - endRole ( Role : : SHARED_TRANSACTION_LOG , tlogId , " Error " , true ) ; <nl> if ( recovered . canBeSet ( ) ) recovered . send ( Void ( ) ) ; <nl> <nl> while ( ! tlogRequests . isEmpty ( ) ) { <nl> mmm a / fdbserver / OldTLogServer_6_2 . actor . cpp <nl> ppp b / fdbserver / OldTLogServer_6_2 . actor . cpp <nl> struct TLogData : NonCopyable { <nl> std : : map < UID , Reference < struct LogData > > id_data ; <nl> <nl> UID dbgid ; <nl> + UID workerID ; <nl> <nl> IKeyValueStore * persistentData ; / / Durable data on disk that were spilled . <nl> IDiskQueue * rawPersistentQueue ; / / The physical queue the persistentQueue below stores its data . Ideally , log interface should work without directly accessing rawPersistentQueue <nl> struct TLogData : NonCopyable { <nl> / / that came when ignorePopRequest was set <nl> Reference < AsyncVar < bool > > degraded ; <nl> <nl> - TLogData ( UID dbgid , IKeyValueStore * persistentData , IDiskQueue * persistentQueue , Reference < AsyncVar < ServerDBInfo > > dbInfo , Reference < AsyncVar < bool > > degraded , std : : string folder ) <nl> - : dbgid ( dbgid ) , instanceID ( deterministicRandom ( ) - > randomUniqueID ( ) . first ( ) ) , <nl> + TLogData ( UID dbgid , UID workerID , IKeyValueStore * persistentData , IDiskQueue * persistentQueue , Reference < AsyncVar < ServerDBInfo > > dbInfo , Reference < AsyncVar < bool > > degraded , std : : string folder ) <nl> + : dbgid ( dbgid ) , workerID ( workerID ) , instanceID ( deterministicRandom ( ) - > randomUniqueID ( ) . first ( ) ) , <nl> persistentData ( persistentData ) , rawPersistentQueue ( persistentQueue ) , persistentQueue ( new TLogQueue ( persistentQueue , dbgid ) ) , <nl> dbInfo ( dbInfo ) , degraded ( degraded ) , queueCommitBegin ( 0 ) , queueCommitEnd ( 0 ) , <nl> diskQueueCommitBytes ( 0 ) , largeDiskQueueCommitBytes ( false ) , bytesInput ( 0 ) , bytesDurable ( 0 ) , targetVolatileBytes ( SERVER_KNOBS - > TLOG_SPILL_THRESHOLD ) , overheadBytesInput ( 0 ) , overheadBytesDurable ( 0 ) , <nl> struct LogData : NonCopyable , public ReferenceCounted < LogData > { <nl> bool execOpCommitInProgress ; <nl> int txsTags ; <nl> <nl> - explicit LogData ( TLogData * tLogData , TLogInterface interf , Tag remoteTag , bool isPrimary , int logRouterTags , int txsTags , UID recruitmentID , ProtocolVersion protocolVersion , std : : vector < Tag > tags ) : tLogData ( tLogData ) , knownCommittedVersion ( 0 ) , logId ( interf . id ( ) ) , <nl> + explicit LogData ( TLogData * tLogData , TLogInterface interf , Tag remoteTag , bool isPrimary , int logRouterTags , int txsTags , UID recruitmentID , ProtocolVersion protocolVersion , std : : vector < Tag > tags , std : : string context ) : tLogData ( tLogData ) , knownCommittedVersion ( 0 ) , logId ( interf . id ( ) ) , <nl> cc ( " TLog " , interf . id ( ) . toString ( ) ) , bytesInput ( " BytesInput " , cc ) , bytesDurable ( " BytesDurable " , cc ) , remoteTag ( remoteTag ) , isPrimary ( isPrimary ) , logRouterTags ( logRouterTags ) , txsTags ( txsTags ) , recruitmentID ( recruitmentID ) , protocolVersion ( protocolVersion ) , <nl> logSystem ( new AsyncVar < Reference < ILogSystem > > ( ) ) , logRouterPoppedVersion ( 0 ) , durableKnownCommittedVersion ( 0 ) , minKnownCommittedVersion ( 0 ) , queuePoppedVersion ( 0 ) , allTags ( tags . begin ( ) , tags . end ( ) ) , terminated ( tLogData - > terminated . getFuture ( ) ) , <nl> minPoppedTagVersion ( 0 ) , minPoppedTag ( invalidTag ) , <nl> struct LogData : NonCopyable , public ReferenceCounted < LogData > { <nl> recoveryCount ( ) , stopped ( false ) , initialized ( false ) , queueCommittingVersion ( 0 ) , newPersistentDataVersion ( invalidVersion ) , unrecoveredBefore ( 1 ) , recoveredAt ( 1 ) , unpoppedRecoveredTags ( 0 ) , <nl> logRouterPopToVersion ( 0 ) , locality ( tagLocalityInvalid ) , execOpCommitInProgress ( false ) <nl> { <nl> - startRole ( Role : : TRANSACTION_LOG , interf . id ( ) , UID ( ) ) ; <nl> + startRole ( Role : : TRANSACTION_LOG , interf . id ( ) , tLogData - > workerID , { { " SharedTLog " , tLogData - > dbgid . shortString ( ) } } , context ) ; <nl> <nl> persistentDataVersion . init ( LiteralStringRef ( " TLog . PersistentDataVersion " ) , cc . id ) ; <nl> persistentDataDurableVersion . init ( LiteralStringRef ( " TLog . PersistentDataDurableVersion " ) , cc . id ) ; <nl> ACTOR Future < Void > updatePoppedLocation ( TLogData * self , Reference < LogData > logD <nl> / / us to remove data that still is pointed to by SpilledData in the btree . <nl> if ( data - > persistentPopped < = logData - > persistentDataVersion ) { <nl> / / Recover the next needed location in the Disk Queue from the index . <nl> - Standalone < VectorRef < KeyValueRef > > kvrefs = wait ( <nl> + Standalone < RangeResultRef > kvrefs = wait ( <nl> self - > persistentData - > readRange ( KeyRangeRef ( <nl> persistTagMessageRefsKey ( logData - > logId , data - > tag , data - > persistentPopped ) , <nl> persistTagMessageRefsKey ( logData - > logId , data - > tag , logData - > persistentDataVersion + 1 ) ) , 1 ) ) ; <nl> ACTOR Future < Void > tLogPeekMessages ( TLogData * self , TLogPeekRequest req , Refere <nl> } <nl> <nl> if ( req . tag . locality = = tagLocalityTxs | | req . tag = = txsTag ) { <nl> - Standalone < VectorRef < KeyValueRef > > kvs = wait ( <nl> + Standalone < RangeResultRef > kvs = wait ( <nl> self - > persistentData - > readRange ( KeyRangeRef ( <nl> persistTagMessagesKey ( logData - > logId , req . tag , req . begin ) , <nl> persistTagMessagesKey ( logData - > logId , req . tag , logData - > persistentDataDurableVersion + 1 ) ) , SERVER_KNOBS - > DESIRED_TOTAL_BYTES , SERVER_KNOBS - > DESIRED_TOTAL_BYTES ) ) ; <nl> ACTOR Future < Void > tLogPeekMessages ( TLogData * self , TLogPeekRequest req , Refere <nl> } <nl> } else { <nl> / / FIXME : Limit to approximately DESIRED_TOTATL_BYTES somehow . <nl> - Standalone < VectorRef < KeyValueRef > > kvrefs = wait ( <nl> + Standalone < RangeResultRef > kvrefs = wait ( <nl> self - > persistentData - > readRange ( KeyRangeRef ( <nl> persistTagMessageRefsKey ( logData - > logId , req . tag , req . begin ) , <nl> persistTagMessageRefsKey ( logData - > logId , req . tag , logData - > persistentDataDurableVersion + 1 ) ) , <nl> ACTOR Future < Void > watchDegraded ( TLogData * self ) { <nl> return Void ( ) ; <nl> } <nl> <nl> - / / This delay is divided into multiple delays to avoid marking the tlog as degraded because of a single SlowTask <nl> - state int loopCount = 0 ; <nl> - while ( loopCount < SERVER_KNOBS - > TLOG_DEGRADED_DELAY_COUNT ) { <nl> - wait ( delay ( SERVER_KNOBS - > TLOG_DEGRADED_DURATION / SERVER_KNOBS - > TLOG_DEGRADED_DELAY_COUNT , TaskPriority : : Low ) ) ; <nl> - loopCount + + ; <nl> - } <nl> + wait ( lowPriorityDelay ( SERVER_KNOBS - > TLOG_DEGRADED_DURATION ) ) ; <nl> + <nl> TraceEvent ( SevWarnAlways , " TLogDegraded " , self - > dbgid ) ; <nl> TEST ( true ) ; / / TLog degraded <nl> self - > degraded - > set ( true ) ; <nl> ACTOR Future < Void > rejoinMasters ( TLogData * self , TLogInterface tli , DBRecoveryC <nl> if ( self - > dbInfo - > get ( ) . master . id ( ) ! = lastMasterID ) { <nl> / / The TLogRejoinRequest is needed to establish communications with a new master , which doesn ' t have our TLogInterface <nl> TLogRejoinRequest req ( tli ) ; <nl> - TraceEvent ( " TLogRejoining " , self - > dbgid ) . detail ( " Master " , self - > dbInfo - > get ( ) . master . id ( ) ) ; <nl> + TraceEvent ( " TLogRejoining " , tli . id ( ) ) . detail ( " Master " , self - > dbInfo - > get ( ) . master . id ( ) ) ; <nl> choose { <nl> when ( TLogRejoinReply rep = <nl> wait ( brokenPromiseToNever ( self - > dbInfo - > get ( ) . master . tlogRejoin . getReply ( req ) ) ) ) { <nl> ACTOR Future < Void > restorePersistentState ( TLogData * self , LocalityData locality <nl> wait ( storage - > init ( ) ) ; <nl> state Future < Optional < Value > > fFormat = storage - > readValue ( persistFormat . key ) ; <nl> state Future < Optional < Value > > fRecoveryLocation = storage - > readValue ( persistRecoveryLocationKey ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fVers = storage - > readRange ( persistCurrentVersionKeys ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fKnownCommitted = storage - > readRange ( persistKnownCommittedVersionKeys ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fLocality = storage - > readRange ( persistLocalityKeys ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fLogRouterTags = storage - > readRange ( persistLogRouterTagsKeys ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fTxsTags = storage - > readRange ( persistTxsTagsKeys ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fRecoverCounts = storage - > readRange ( persistRecoveryCountKeys ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fProtocolVersions = storage - > readRange ( persistProtocolVersionKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fVers = storage - > readRange ( persistCurrentVersionKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fKnownCommitted = storage - > readRange ( persistKnownCommittedVersionKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fLocality = storage - > readRange ( persistLocalityKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fLogRouterTags = storage - > readRange ( persistLogRouterTagsKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fTxsTags = storage - > readRange ( persistTxsTagsKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fRecoverCounts = storage - > readRange ( persistRecoveryCountKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fProtocolVersions = storage - > readRange ( persistProtocolVersionKeys ) ; <nl> <nl> / / FIXME : metadata in queue ? <nl> <nl> ACTOR Future < Void > restorePersistentState ( TLogData * self , LocalityData locality <nl> } <nl> <nl> if ( ! fFormat . get ( ) . present ( ) ) { <nl> - Standalone < VectorRef < KeyValueRef > > v = wait ( self - > persistentData - > readRange ( KeyRangeRef ( StringRef ( ) , LiteralStringRef ( " \ xff " ) ) , 1 ) ) ; <nl> + Standalone < RangeResultRef > v = wait ( self - > persistentData - > readRange ( KeyRangeRef ( StringRef ( ) , LiteralStringRef ( " \ xff " ) ) , 1 ) ) ; <nl> if ( ! v . size ( ) ) { <nl> TEST ( true ) ; / / The DB is completely empty , so it was never initialized . Delete it . <nl> throw worker_removed ( ) ; <nl> ACTOR Future < Void > restorePersistentState ( TLogData * self , LocalityData locality <nl> ProtocolVersion protocolVersion = BinaryReader : : fromStringRef < ProtocolVersion > ( fProtocolVersions . get ( ) [ idx ] . value , Unversioned ( ) ) ; <nl> <nl> / / We do not need the remoteTag , because we will not be loading any additional data <nl> - logData = Reference < LogData > ( new LogData ( self , recruited , Tag ( ) , true , id_logRouterTags [ id1 ] , id_txsTags [ id1 ] , UID ( ) , protocolVersion , std : : vector < Tag > ( ) ) ) ; <nl> + logData = Reference < LogData > ( new LogData ( self , recruited , Tag ( ) , true , id_logRouterTags [ id1 ] , id_txsTags [ id1 ] , UID ( ) , protocolVersion , std : : vector < Tag > ( ) , " Restored " ) ) ; <nl> logData - > locality = id_locality [ id1 ] ; <nl> logData - > stopped = true ; <nl> self - > id_data [ id1 ] = logData ; <nl> ACTOR Future < Void > restorePersistentState ( TLogData * self , LocalityData locality <nl> tagKeys = prefixRange ( rawId . withPrefix ( persistTagPoppedKeys . begin ) ) ; <nl> loop { <nl> if ( logData - > removed . isReady ( ) ) break ; <nl> - Standalone < VectorRef < KeyValueRef > > data = wait ( self - > persistentData - > readRange ( tagKeys , BUGGIFY ? 3 : 1 < < 30 , 1 < < 20 ) ) ; <nl> + Standalone < RangeResultRef > data = wait ( self - > persistentData - > readRange ( tagKeys , BUGGIFY ? 3 : 1 < < 30 , 1 < < 20 ) ) ; <nl> if ( ! data . size ( ) ) break ; <nl> ( ( KeyRangeRef & ) tagKeys ) = KeyRangeRef ( keyAfter ( data . back ( ) . key , tagKeys . arena ( ) ) , tagKeys . end ) ; <nl> <nl> ACTOR Future < Void > tLogStart ( TLogData * self , InitializeTLogRequest req , Localit <nl> it . second - > stopCommit . trigger ( ) ; <nl> } <nl> <nl> - state Reference < LogData > logData = Reference < LogData > ( new LogData ( self , recruited , req . remoteTag , req . isPrimary , req . logRouterTags , req . txsTags , req . recruitmentID , currentProtocolVersion , req . allTags ) ) ; <nl> + bool recovering = ( req . recoverFrom . logSystemType = = LogSystemType : : tagPartitioned ) ; <nl> + <nl> + state Reference < LogData > logData = Reference < LogData > ( new LogData ( self , recruited , req . remoteTag , req . isPrimary , req . logRouterTags , req . txsTags , req . recruitmentID , currentProtocolVersion , req . allTags , recovering ? " Recovered " : " Recruited " ) ) ; <nl> self - > id_data [ recruited . id ( ) ] = logData ; <nl> logData - > locality = req . locality ; <nl> logData - > recoveryCount = req . epoch ; <nl> ACTOR Future < Void > tLogStart ( TLogData * self , InitializeTLogRequest req , Localit <nl> throw logData - > removed . getError ( ) ; <nl> } <nl> <nl> - if ( req . recoverFrom . logSystemType = = LogSystemType : : tagPartitioned ) { <nl> + if ( recovering ) { <nl> logData - > unrecoveredBefore = req . startVersion ; <nl> logData - > recoveredAt = req . recoverAt ; <nl> logData - > knownCommittedVersion = req . startVersion - 1 ; <nl> ACTOR Future < Void > startSpillingInTenSeconds ( TLogData * self , UID tlogId , Referen <nl> } <nl> <nl> / / New tLog ( if ! recoverFrom . size ( ) ) or restore from network <nl> - ACTOR Future < Void > tLog ( IKeyValueStore * persistentData , IDiskQueue * persistentQueue , Reference < AsyncVar < ServerDBInfo > > db , LocalityData locality , PromiseStream < InitializeTLogRequest > tlogRequests , UID tlogId , bool restoreFromDisk , Promise < Void > oldLog , Promise < Void > recovered , std : : string folder , Reference < AsyncVar < bool > > degraded , Reference < AsyncVar < UID > > activeSharedTLog ) { <nl> - state TLogData self ( tlogId , persistentData , persistentQueue , db , degraded , folder ) ; <nl> + ACTOR Future < Void > tLog ( IKeyValueStore * persistentData , IDiskQueue * persistentQueue , Reference < AsyncVar < ServerDBInfo > > db , LocalityData locality , PromiseStream < InitializeTLogRequest > tlogRequests , UID tlogId , UID workerID , bool restoreFromDisk , Promise < Void > oldLog , Promise < Void > recovered , std : : string folder , Reference < AsyncVar < bool > > degraded , Reference < AsyncVar < UID > > activeSharedTLog ) { <nl> + state TLogData self ( tlogId , workerID , persistentData , persistentQueue , db , degraded , folder ) ; <nl> state Future < Void > error = actorCollection ( self . sharedActors . getFuture ( ) ) ; <nl> <nl> TraceEvent ( " SharedTlog " , tlogId ) ; <nl> - / / FIXME : Pass the worker id instead of stubbing it <nl> - startRole ( Role : : SHARED_TRANSACTION_LOG , tlogId , UID ( ) ) ; <nl> try { <nl> if ( restoreFromDisk ) { <nl> wait ( restorePersistentState ( & self , locality , oldLog , recovered , tlogRequests ) ) ; <nl> ACTOR Future < Void > tLog ( IKeyValueStore * persistentData , IDiskQueue * persistentQ <nl> } catch ( Error & e ) { <nl> self . terminated . send ( Void ( ) ) ; <nl> TraceEvent ( " TLogError " , tlogId ) . error ( e , true ) ; <nl> - endRole ( Role : : SHARED_TRANSACTION_LOG , tlogId , " Error " , true ) ; <nl> if ( recovered . canBeSet ( ) ) recovered . send ( Void ( ) ) ; <nl> <nl> while ( ! tlogRequests . isEmpty ( ) ) { <nl> mmm a / fdbserver / Ratekeeper . actor . cpp <nl> ppp b / fdbserver / Ratekeeper . actor . cpp <nl> void updateRate ( RatekeeperData * self , RatekeeperLimits * limits ) { <nl> <nl> limitReason_t ssLimitReason = limitReason_t : : unlimited ; <nl> <nl> - int64_t minFreeSpace = std : : max ( SERVER_KNOBS - > MIN_FREE_SPACE , ( int64_t ) ( SERVER_KNOBS - > MIN_FREE_SPACE_RATIO * ss . smoothTotalSpace . smoothTotal ( ) ) ) ; <nl> + int64_t minFreeSpace = std : : max ( SERVER_KNOBS - > MIN_AVAILABLE_SPACE , ( int64_t ) ( SERVER_KNOBS - > MIN_AVAILABLE_SPACE_RATIO * ss . smoothTotalSpace . smoothTotal ( ) ) ) ; <nl> <nl> worstFreeSpaceStorageServer = std : : min ( worstFreeSpaceStorageServer , ( int64_t ) ss . smoothFreeSpace . smoothTotal ( ) - minFreeSpace ) ; <nl> <nl> int64_t springBytes = std : : max < int64_t > ( 1 , std : : min < int64_t > ( limits - > storageSpringBytes , ( ss . smoothFreeSpace . smoothTotal ( ) - minFreeSpace ) * 0 . 2 ) ) ; <nl> int64_t targetBytes = std : : max < int64_t > ( 1 , std : : min ( limits - > storageTargetBytes , ( int64_t ) ss . smoothFreeSpace . smoothTotal ( ) - minFreeSpace ) ) ; <nl> if ( targetBytes ! = limits - > storageTargetBytes ) { <nl> - if ( minFreeSpace = = SERVER_KNOBS - > MIN_FREE_SPACE ) { <nl> + if ( minFreeSpace = = SERVER_KNOBS - > MIN_AVAILABLE_SPACE ) { <nl> ssLimitReason = limitReason_t : : storage_server_min_free_space ; <nl> } else { <nl> ssLimitReason = limitReason_t : : storage_server_min_free_space_ratio ; <nl> void updateRate ( RatekeeperData * self , RatekeeperLimits * limits ) { <nl> <nl> limitReason_t tlogLimitReason = limitReason_t : : log_server_write_queue ; <nl> <nl> - int64_t minFreeSpace = std : : max ( SERVER_KNOBS - > MIN_FREE_SPACE , ( int64_t ) ( SERVER_KNOBS - > MIN_FREE_SPACE_RATIO * tl . smoothTotalSpace . smoothTotal ( ) ) ) ; <nl> + int64_t minFreeSpace = std : : max ( SERVER_KNOBS - > MIN_AVAILABLE_SPACE , ( int64_t ) ( SERVER_KNOBS - > MIN_AVAILABLE_SPACE_RATIO * tl . smoothTotalSpace . smoothTotal ( ) ) ) ; <nl> <nl> worstFreeSpaceTLog = std : : min ( worstFreeSpaceTLog , ( int64_t ) tl . smoothFreeSpace . smoothTotal ( ) - minFreeSpace ) ; <nl> <nl> int64_t springBytes = std : : max < int64_t > ( 1 , std : : min < int64_t > ( limits - > logSpringBytes , ( tl . smoothFreeSpace . smoothTotal ( ) - minFreeSpace ) * 0 . 2 ) ) ; <nl> int64_t targetBytes = std : : max < int64_t > ( 1 , std : : min ( limits - > logTargetBytes , ( int64_t ) tl . smoothFreeSpace . smoothTotal ( ) - minFreeSpace ) ) ; <nl> if ( targetBytes ! = limits - > logTargetBytes ) { <nl> - if ( minFreeSpace = = SERVER_KNOBS - > MIN_FREE_SPACE ) { <nl> + if ( minFreeSpace = = SERVER_KNOBS - > MIN_AVAILABLE_SPACE ) { <nl> tlogLimitReason = limitReason_t : : log_server_min_free_space ; <nl> } else { <nl> tlogLimitReason = limitReason_t : : log_server_min_free_space_ratio ; <nl> mmm a / fdbserver / Resolver . actor . cpp <nl> ppp b / fdbserver / Resolver . actor . cpp <nl> struct Resolver : ReferenceCounted < Resolver > { <nl> <nl> Version debugMinRecentStateVersion ; <nl> } ; <nl> - } <nl> + } / / namespace <nl> <nl> ACTOR Future < Void > resolveBatch ( <nl> Reference < Resolver > self , <nl> mmm a / fdbserver / RestoreApplier . actor . cpp <nl> ppp b / fdbserver / RestoreApplier . actor . cpp <nl> ACTOR static Future < Void > handleApplyToDBRequest ( RestoreVersionBatchRequest req , <nl> ACTOR Future < Void > restoreApplierCore ( RestoreApplierInterface applierInterf , int nodeIndex , Database cx ) { <nl> state Reference < RestoreApplierData > self = <nl> Reference < RestoreApplierData > ( new RestoreApplierData ( applierInterf . id ( ) , nodeIndex ) ) ; <nl> - <nl> state ActorCollection actors ( false ) ; <nl> state Future < Void > exitRole = Never ( ) ; <nl> + state Future < Void > updateProcessStatsTimer = delay ( SERVER_KNOBS - > FASTRESTORE_UPDATE_PROCESS_STATS_INTERVAL ) ; <nl> + <nl> + actors . add ( traceProcessMetrics ( self , " Applier " ) ) ; <nl> + <nl> loop { <nl> state std : : string requestTypeStr = " [ Init ] " ; <nl> <nl> ACTOR Future < Void > restoreApplierCore ( RestoreApplierInterface applierInterf , int <nl> } <nl> when ( RestoreVersionBatchRequest req = waitNext ( applierInterf . initVersionBatch . getFuture ( ) ) ) { <nl> requestTypeStr = " initVersionBatch " ; <nl> - wait ( handleInitVersionBatchRequest ( req , self ) ) ; <nl> + actors . add ( handleInitVersionBatchRequest ( req , self ) ) ; <nl> } <nl> - when ( RestoreVersionBatchRequest req = waitNext ( applierInterf . finishRestore . getFuture ( ) ) ) { <nl> + when ( RestoreFinishRequest req = waitNext ( applierInterf . finishRestore . getFuture ( ) ) ) { <nl> requestTypeStr = " finishRestore " ; <nl> handleFinishRestoreRequest ( req , self ) ; <nl> - exitRole = Void ( ) ; <nl> + if ( req . terminate ) { <nl> + exitRole = Void ( ) ; <nl> + } <nl> + } <nl> + when ( wait ( updateProcessStatsTimer ) ) { <nl> + updateProcessStats ( self ) ; <nl> + updateProcessStatsTimer = delay ( SERVER_KNOBS - > FASTRESTORE_UPDATE_PROCESS_STATS_INTERVAL ) ; <nl> } <nl> when ( wait ( exitRole ) ) { <nl> TraceEvent ( " FastRestore " ) . detail ( " RestoreApplierCore " , " ExitRole " ) . detail ( " NodeID " , self - > id ( ) ) ; <nl> ACTOR Future < Void > restoreApplierCore ( RestoreApplierInterface applierInterf , int <nl> / / Only one actor can process mutations from the same file <nl> ACTOR static Future < Void > handleSendMutationVectorRequest ( RestoreSendVersionedMutationsRequest req , <nl> Reference < RestoreApplierData > self ) { <nl> - / / Assume : self - > processedFileState [ req . asset ] will not be erased while the actor is active . <nl> + state Reference < ApplierBatchData > batchData = self - > batch [ req . batchIndex ] ; <nl> + / / Assume : processedFileState [ req . asset ] will not be erased while the actor is active . <nl> / / Note : Insert new items into processedFileState will not invalidate the reference . <nl> - state NotifiedVersion & curFilePos = self - > processedFileState [ req . asset ] ; <nl> + state NotifiedVersion & curFilePos = batchData - > processedFileState [ req . asset ] ; <nl> <nl> - TraceEvent ( " FastRestore " ) <nl> - . detail ( " ApplierNode " , self - > id ( ) ) <nl> + TraceEvent ( SevDebug , " FastRestoreApplierPhaseReceiveMutations " , self - > id ( ) ) <nl> + . detail ( " BatchIndex " , req . batchIndex ) <nl> . detail ( " RestoreAsset " , req . asset . toString ( ) ) <nl> . detail ( " ProcessedFileVersion " , curFilePos . get ( ) ) <nl> . detail ( " Request " , req . toString ( ) ) ; <nl> <nl> wait ( curFilePos . whenAtLeast ( req . prevVersion ) ) ; <nl> <nl> + state bool isDuplicated = true ; <nl> if ( curFilePos . get ( ) = = req . prevVersion ) { <nl> + isDuplicated = false ; <nl> Version commitVersion = req . version ; <nl> + uint16_t numVersionStampedKV = 0 ; <nl> MutationsVec mutations ( req . mutations ) ; <nl> / / Sanity check : mutations in range file is in [ beginVersion , endVersion ) ; <nl> / / mutations in log file is in [ beginVersion , endVersion ] , both inclusive . <nl> ASSERT_WE_THINK ( commitVersion > = req . asset . beginVersion ) ; <nl> / / Loader sends the endVersion to ensure all useful versions are sent <nl> - ASSERT_WE_THINK ( ( req . isRangeFile & & commitVersion < = req . asset . endVersion ) | | <nl> - ( ! req . isRangeFile & & commitVersion < = req . asset . endVersion ) ) ; <nl> + ASSERT_WE_THINK ( commitVersion < = req . asset . endVersion ) ; <nl> <nl> - if ( self - > kvOps . find ( commitVersion ) = = self - > kvOps . end ( ) ) { <nl> - self - > kvOps . insert ( std : : make_pair ( commitVersion , MutationsVec ( ) ) ) ; <nl> - } <nl> for ( int mIndex = 0 ; mIndex < mutations . size ( ) ; mIndex + + ) { <nl> MutationRef mutation = mutations [ mIndex ] ; <nl> - TraceEvent ( SevFRMutationInfo , " FastRestore " ) <nl> + TraceEvent ( SevFRMutationInfo , " FastRestoreApplierPhaseReceiveMutations " , self - > id ( ) ) <nl> . detail ( " ApplierNode " , self - > id ( ) ) <nl> . detail ( " RestoreAsset " , req . asset . toString ( ) ) <nl> . detail ( " Version " , commitVersion ) <nl> . detail ( " Index " , mIndex ) <nl> . detail ( " MutationReceived " , mutation . toString ( ) ) ; <nl> + batchData - > counters . receivedBytes + = mutation . totalSize ( ) ; <nl> + batchData - > counters . receivedWeightedBytes + = mutation . weightedTotalSize ( ) ; / / atomicOp will be amplified <nl> + batchData - > counters . receivedMutations + = 1 ; <nl> + batchData - > counters . receivedAtomicOps + = isAtomicOp ( ( MutationRef : : Type ) mutation . type ) ? 1 : 0 ; <nl> / / Sanity check <nl> if ( g_network - > isSimulated ( ) ) { <nl> if ( isRangeMutation ( mutation ) ) { <nl> ACTOR static Future < Void > handleSendMutationVectorRequest ( RestoreSendVersionedMu <nl> ASSERT ( mutation . param1 > = req . asset . range . begin & & mutation . param1 < req . asset . range . end ) ; <nl> } <nl> } <nl> - self - > kvOps [ commitVersion ] . push_back_deep ( self - > kvOps [ commitVersion ] . arena ( ) , mutation ) ; <nl> - / / TODO : What if log file ' s mutations are delivered out - of - order ( behind ) the range file ' s mutations ? ! <nl> + / / Note : Log and range mutations may be delivered out of order . Can we handle it ? <nl> + if ( mutation . type = = MutationRef : : SetVersionstampedKey | | <nl> + mutation . type = = MutationRef : : SetVersionstampedValue ) { <nl> + batchData - > addVersionStampedKV ( mutation , commitVersion , numVersionStampedKV ) ; <nl> + numVersionStampedKV + + ; <nl> + } else { <nl> + batchData - > addMutation ( mutation , commitVersion ) ; <nl> + } <nl> } <nl> curFilePos . set ( req . version ) ; <nl> } <nl> <nl> - req . reply . send ( RestoreCommonReply ( self - > id ( ) ) ) ; <nl> + req . reply . send ( RestoreCommonReply ( self - > id ( ) , isDuplicated ) ) ; <nl> + TraceEvent ( SevDebug , " FastRestoreApplierPhaseReceiveMutationsDone " , self - > id ( ) ) <nl> + . detail ( " BatchIndex " , req . batchIndex ) <nl> + . detail ( " RestoreAsset " , req . asset . toString ( ) ) <nl> + . detail ( " ProcessedFileVersion " , curFilePos . get ( ) ) <nl> + . detail ( " Request " , req . toString ( ) ) ; <nl> return Void ( ) ; <nl> } <nl> <nl> - / / Progress and checkpoint for applying ( atomic ) mutations in transactions to DB <nl> - struct DBApplyProgress { <nl> - / / Mutation state in the current uncommitted transaction <nl> - VersionedMutationsMap : : iterator curItInCurTxn ; <nl> - int curIndexInCurTxn ; <nl> - <nl> - / / Save the starting point for current txn to handle ( commit_unknown_result ) error in txn commit <nl> - / / startItInUncommittedTxn is starting iterator in the most recent uncommitted ( and failed ) txn <nl> - / / startIndexInUncommittedTxn is start index in the most recent uncommitted ( and failed ) txn . <nl> - / / Note : Txns have different number of mutations <nl> - VersionedMutationsMap : : iterator startItInUncommittedTxn ; <nl> - int startIndexInUncommittedTxn ; <nl> - <nl> - / / State to decide if a txn succeeds or not when txn error ( commit_unknown_result ) happens ; <nl> - / / curTxnId : The id of the current uncommitted txn , which monotonically increase for each successful transaction <nl> - / / uncommittedTxnId : The id of the most recent succeeded txn . Used to recover the failed txn id in retry <nl> - / / lastTxnHasError : Does the last txn has error . TODO : Only need to handle txn_commit_unknown error <nl> - Version curTxnId ; <nl> - Version uncommittedTxnId ; <nl> - bool lastTxnHasError ; <nl> - <nl> - / / Decide when to commit a transaction . We buffer enough mutations in a txn before commit the txn <nl> - bool startNextVersion ; / / The next txn will include mutations in next version <nl> - int numAtomicOps ; <nl> - double transactionSize ; <nl> - <nl> - Reference < RestoreApplierData > self ; <nl> - <nl> - DBApplyProgress ( ) = default ; <nl> - explicit DBApplyProgress ( Reference < RestoreApplierData > self ) <nl> - : self ( self ) , curIndexInCurTxn ( 0 ) , startIndexInUncommittedTxn ( 0 ) , curTxnId ( 0 ) , uncommittedTxnId ( 0 ) , <nl> - lastTxnHasError ( false ) , startNextVersion ( false ) , numAtomicOps ( 0 ) , transactionSize ( 0 ) { <nl> - curItInCurTxn = self - > kvOps . begin ( ) ; <nl> - while ( curItInCurTxn ! = self - > kvOps . end ( ) & & curItInCurTxn - > second . empty ( ) ) { <nl> - curItInCurTxn + + ; <nl> - } <nl> - startItInUncommittedTxn = curItInCurTxn ; <nl> - } <nl> - <nl> - / / Has all mutations been committed ? <nl> - bool isDone ( ) { return curItInCurTxn = = self - > kvOps . end ( ) ; } <nl> - <nl> - / / Set cursor for next mutation <nl> - void nextMutation ( ) { <nl> - curIndexInCurTxn + + ; <nl> - while ( curItInCurTxn ! = self - > kvOps . end ( ) & & curIndexInCurTxn > = curItInCurTxn - > second . size ( ) ) { <nl> - curIndexInCurTxn = 0 ; <nl> - curItInCurTxn + + ; <nl> - startNextVersion = true ; <nl> + / / Clear all ranges in input ranges <nl> + ACTOR static Future < Void > applyClearRangeMutations ( Standalone < VectorRef < KeyRangeRef > > ranges , Database cx ) { <nl> + state Reference < ReadYourWritesTransaction > tr ( new ReadYourWritesTransaction ( cx ) ) ; <nl> + loop { <nl> + try { <nl> + tr - > reset ( ) ; <nl> + tr - > setOption ( FDBTransactionOptions : : ACCESS_SYSTEM_KEYS ) ; <nl> + tr - > setOption ( FDBTransactionOptions : : LOCK_AWARE ) ; <nl> + for ( auto & range : ranges ) { <nl> + tr - > clear ( range ) ; <nl> + } <nl> + wait ( tr - > commit ( ) ) ; <nl> + break ; <nl> + } catch ( Error & e ) { <nl> + wait ( tr - > onError ( e ) ) ; <nl> } <nl> } <nl> + return Void ( ) ; <nl> + } <nl> <nl> - / / Setup for the next transaction ; This should be done after nextMutation ( ) <nl> - void nextTxn ( ) { <nl> - transactionSize = 0 ; <nl> - numAtomicOps = 0 ; <nl> - lastTxnHasError = false ; <nl> - startNextVersion = false ; <nl> - <nl> - curTxnId + + ; <nl> - <nl> - startIndexInUncommittedTxn = curIndexInCurTxn ; <nl> - startItInUncommittedTxn = curItInCurTxn ; <nl> - uncommittedTxnId = curTxnId ; <nl> - } <nl> - <nl> - / / Rollback to the starting point of the uncommitted - and - failed transaction to <nl> - / / re - execute uncommitted txn <nl> - void rollback ( ) { <nl> - TraceEvent ( SevWarn , " FastRestore_ApplyTxnError " ) <nl> - . detail ( " TxnStatusFailed " , curTxnId ) <nl> - . detail ( " ApplierApplyToDB " , self - > id ( ) ) <nl> - . detail ( " UncommittedTxnId " , uncommittedTxnId ) <nl> - . detail ( " CurIteratorVersion " , curItInCurTxn - > first ) <nl> - . detail ( " StartIteratorVersionInUncommittedTxn " , startItInUncommittedTxn - > first ) <nl> - . detail ( " CurrentIndexInFailedTxn " , curIndexInCurTxn ) <nl> - . detail ( " StartIndexInUncommittedTxn " , startIndexInUncommittedTxn ) <nl> - . detail ( " NumIncludedAtomicOps " , numAtomicOps ) ; <nl> - curItInCurTxn = startItInUncommittedTxn ; <nl> - curIndexInCurTxn = startIndexInUncommittedTxn ; <nl> - curTxnId = uncommittedTxnId ; <nl> - <nl> - numAtomicOps = 0 ; <nl> - transactionSize = 0 ; <nl> - startNextVersion = false ; <nl> - lastTxnHasError = false ; <nl> - } <nl> - <nl> - bool shouldCommit ( ) { <nl> - return ( ! lastTxnHasError & & ( startNextVersion | | transactionSize > = opConfig . transactionBatchSizeThreshold | | <nl> - curItInCurTxn = = self - > kvOps . end ( ) ) ) ; <nl> - } <nl> - <nl> - bool hasError ( ) { return lastTxnHasError ; } <nl> - <nl> - void setTxnError ( Error & e ) { <nl> - TraceEvent ( SevWarnAlways , " FastRestore_ApplyTxnError " ) <nl> - . detail ( " TxnStatus " , " ? " ) <nl> - . detail ( " ApplierApplyToDB " , self - > id ( ) ) <nl> - . detail ( " TxnId " , curTxnId ) <nl> - . detail ( " StartIndexInCurrentTxn " , curIndexInCurTxn ) <nl> - . detail ( " Version " , curItInCurTxn - > first ) <nl> - . error ( e , true ) ; <nl> - lastTxnHasError = true ; <nl> - } <nl> - <nl> - MutationRef getCurrentMutation ( ) { <nl> - ASSERT_WE_THINK ( curIndexInCurTxn < curItInCurTxn - > second . size ( ) ) ; <nl> - return curItInCurTxn - > second [ curIndexInCurTxn ] ; <nl> - } <nl> - } ; <nl> - <nl> - ACTOR Future < Void > applyToDB ( Reference < RestoreApplierData > self , Database cx ) { <nl> - / / state variables must be defined at the start of actor to be initialized in the actor constructor <nl> - state std : : string typeStr = " " ; <nl> + / / Get keys in imcompleteStagingKeys and precompute the stagingKey which is stored in batchData - > stagingKeys <nl> + ACTOR static Future < Void > getAndComputeStagingKeys ( <nl> + std : : map < Key , std : : map < Key , StagingKey > : : iterator > imcompleteStagingKeys , Database cx , UID applierID ) { <nl> state Reference < ReadYourWritesTransaction > tr ( new ReadYourWritesTransaction ( cx ) ) ; <nl> - state DBApplyProgress progress ( self ) ; <nl> - <nl> - / / Assume the process will not crash when it apply mutations to DB . The reply message can be lost though <nl> - if ( self - > kvOps . empty ( ) ) { <nl> - TraceEvent ( " FastRestore_ApplierTxn " ) <nl> - . detail ( " ApplierApplyToDBFinished " , self - > id ( ) ) <nl> - . detail ( " Reason " , " EmptyVersionMutation " ) ; <nl> - return Void ( ) ; <nl> - } <nl> - ASSERT_WE_THINK ( self - > kvOps . size ( ) ) ; <nl> - TraceEvent ( " FastRestore " ) <nl> - . detail ( " ApplierApplyToDB " , self - > id ( ) ) <nl> - . detail ( " FromVersion " , self - > kvOps . begin ( ) - > first ) <nl> - . detail ( " EndVersion " , self - > kvOps . rbegin ( ) - > first ) ; <nl> - <nl> - self - > sanityCheckMutationOps ( ) ; <nl> - <nl> - if ( progress . isDone ( ) ) { <nl> - TraceEvent ( " FastRestore_ApplierTxn " ) <nl> - . detail ( " ApplierApplyToDBFinished " , self - > id ( ) ) <nl> - . detail ( " Reason " , " NoMutationAtVersions " ) ; <nl> - return Void ( ) ; <nl> - } <nl> - <nl> - / / Sanity check the restoreApplierKeys , which should be empty at this point <nl> + state std : : vector < Future < Optional < Value > > > fValues ; <nl> + state int i = 0 ; <nl> + TraceEvent ( " FastRestoreApplierGetAndComputeStagingKeysStart " , applierID ) <nl> + . detail ( " GetKeys " , imcompleteStagingKeys . size ( ) ) ; <nl> loop { <nl> try { <nl> tr - > reset ( ) ; <nl> tr - > setOption ( FDBTransactionOptions : : ACCESS_SYSTEM_KEYS ) ; <nl> tr - > setOption ( FDBTransactionOptions : : LOCK_AWARE ) ; <nl> - Key begin = restoreApplierKeyFor ( self - > id ( ) , 0 ) ; <nl> - Key end = restoreApplierKeyFor ( self - > id ( ) , std : : numeric_limits < int64_t > : : max ( ) ) ; <nl> - Standalone < RangeResultRef > txnIds = wait ( tr - > getRange ( KeyRangeRef ( begin , end ) , CLIENT_KNOBS - > TOO_MANY ) ) ; <nl> - if ( txnIds . size ( ) > 0 ) { <nl> - TraceEvent ( SevError , " FastRestore_ApplyTxnStateNotClean " ) . detail ( " TxnIds " , txnIds . size ( ) ) ; <nl> - for ( auto & kv : txnIds ) { <nl> - std : : pair < UID , Version > applierInfo = decodeRestoreApplierKey ( kv . key ) ; <nl> - TraceEvent ( SevError , " FastRestore_ApplyTxnStateNotClean " ) <nl> - . detail ( " Applier " , applierInfo . first ) <nl> - . detail ( " ResidueTxnID " , applierInfo . second ) ; <nl> - } <nl> + for ( auto & key : imcompleteStagingKeys ) { <nl> + fValues . push_back ( tr - > get ( key . first ) ) ; <nl> } <nl> + wait ( waitForAll ( fValues ) ) ; <nl> break ; <nl> } catch ( Error & e ) { <nl> + TraceEvent ( SevError , " FastRestoreApplierGetAndComputeStagingKeysUnhandledError " ) <nl> + . detail ( " GetKeys " , imcompleteStagingKeys . size ( ) ) <nl> + . detail ( " Error " , e . what ( ) ) <nl> + . detail ( " ErrorCode " , e . code ( ) ) ; <nl> wait ( tr - > onError ( e ) ) ; <nl> + fValues . clear ( ) ; <nl> } <nl> } <nl> <nl> - loop { / / Transaction retry loop <nl> - try { <nl> - / / Check if the transaction succeeds <nl> - if ( progress . hasError ( ) ) { <nl> - tr - > reset ( ) ; <nl> - tr - > setOption ( FDBTransactionOptions : : ACCESS_SYSTEM_KEYS ) ; <nl> - tr - > setOption ( FDBTransactionOptions : : LOCK_AWARE ) ; <nl> - Optional < Value > txnSucceeded = wait ( tr - > get ( restoreApplierKeyFor ( self - > id ( ) , progress . curTxnId ) ) ) ; <nl> - if ( ! txnSucceeded . present ( ) ) { <nl> - progress . rollback ( ) ; <nl> - continue ; <nl> - } else { <nl> - TraceEvent ( SevWarn , " FastRestore_ApplyTxnError " ) <nl> - . detail ( " TxnStatusSucceeded " , progress . curTxnId ) <nl> - . detail ( " ApplierApplyToDB " , self - > id ( ) ) <nl> - . detail ( " CurIteratorVersion " , progress . curItInCurTxn - > first ) <nl> - . detail ( " CurrentIteratorMutations " , progress . curItInCurTxn - > second . size ( ) ) <nl> - . detail ( " CurrentIndexInSucceedTxn " , progress . curIndexInCurTxn ) <nl> - . detail ( " NumIncludedAtomicOps " , progress . numAtomicOps ) ; <nl> - / / Txn succeeded and exectue the same logic when txn succeeds <nl> + ASSERT ( fValues . size ( ) = = imcompleteStagingKeys . size ( ) ) ; <nl> + int i = 0 ; <nl> + for ( auto & key : imcompleteStagingKeys ) { <nl> + if ( ! fValues [ i ] . get ( ) . present ( ) ) { <nl> + TraceEvent ( SevWarnAlways , " FastRestoreApplierGetAndComputeStagingKeysUnhandledError " ) <nl> + . detail ( " Key " , key . first ) <nl> + . detail ( " Reason " , " Not found in DB " ) <nl> + . detail ( " PendingMutations " , key . second - > second . pendingMutations . size ( ) ) <nl> + . detail ( " StagingKeyType " , ( int ) key . second - > second . type ) ; <nl> + for ( auto & vm : key . second - > second . pendingMutations ) { <nl> + for ( auto & m : vm . second ) { <nl> + TraceEvent ( SevWarnAlways , " FastRestoreApplierGetAndComputeStagingKeysUnhandledError " ) <nl> + . detail ( " PendingMutationVersion " , vm . first ) <nl> + . detail ( " PendingMutation " , m . toString ( ) ) ; <nl> } <nl> - } else { / / ! lastTxnHasError : accumulate mutations in a txn <nl> - tr - > reset ( ) ; <nl> - tr - > setOption ( FDBTransactionOptions : : ACCESS_SYSTEM_KEYS ) ; <nl> - tr - > setOption ( FDBTransactionOptions : : LOCK_AWARE ) ; <nl> - TraceEvent ( " FastRestore_ApplierTxn " ) <nl> - . detail ( " ApplierApplyToDB " , self - > id ( ) ) <nl> - . detail ( " TxnId " , progress . curTxnId ) <nl> - . detail ( " CurrentIndexInCurrentTxn " , progress . curIndexInCurTxn ) <nl> - . detail ( " CurrentIteratorMutations " , progress . curItInCurTxn - > second . size ( ) ) <nl> - . detail ( " Version " , progress . curItInCurTxn - > first ) ; <nl> - <nl> - / / restoreApplierKeyFor ( self - > id ( ) , curTxnId ) to tell if txn succeeds at an unknown error <nl> - tr - > set ( restoreApplierKeyFor ( self - > id ( ) , progress . curTxnId ) , restoreApplierTxnValue ) ; <nl> - <nl> - while ( 1 ) { / / Loop : Accumulate mutations in a transaction <nl> - MutationRef m = progress . getCurrentMutation ( ) ; <nl> - <nl> - if ( m . type > = MutationRef : : Type : : SetValue & & m . type < = MutationRef : : Type : : MAX_ATOMIC_OP ) { <nl> - typeStr = typeString [ m . type ] ; <nl> - } else { <nl> - TraceEvent ( SevError , " FastRestore " ) . detail ( " InvalidMutationType " , m . type ) ; <nl> - } <nl> + } <nl> + key . second - > second . precomputeResult ( ) ; <nl> + i + + ; <nl> + continue ; <nl> + } else { <nl> + / / The key ' s version ideally should be the most recently committed version . <nl> + / / But as long as it is > 1 and less than the start version of the version batch , it is the same result . <nl> + MutationRef m ( MutationRef : : SetValue , key . first , fValues [ i ] . get ( ) . get ( ) ) ; <nl> + key . second - > second . add ( m , ( Version ) 1 ) ; <nl> + key . second - > second . precomputeResult ( ) ; <nl> + i + + ; <nl> + } <nl> + } <nl> <nl> - TraceEvent ( SevFRMutationInfo , " FastRestore " ) <nl> - . detail ( " ApplierApplyToDB " , self - > describeNode ( ) ) <nl> - . detail ( " Version " , progress . curItInCurTxn - > first ) <nl> - . detail ( " Index " , progress . curIndexInCurTxn ) <nl> - . detail ( " Mutation " , m . toString ( ) ) <nl> - . detail ( " MutationSize " , m . expectedSize ( ) ) <nl> - . detail ( " TxnSize " , progress . transactionSize ) ; <nl> - if ( m . type = = MutationRef : : SetValue ) { <nl> - tr - > set ( m . param1 , m . param2 ) ; <nl> - } else if ( m . type = = MutationRef : : ClearRange ) { <nl> - KeyRangeRef mutationRange ( m . param1 , m . param2 ) ; <nl> - tr - > clear ( mutationRange ) ; <nl> - } else if ( isAtomicOp ( ( MutationRef : : Type ) m . type ) ) { <nl> - tr - > atomicOp ( m . param1 , m . param2 , m . type ) ; <nl> - progress . numAtomicOps + + ; <nl> - } else { <nl> - TraceEvent ( SevError , " FastRestore " ) <nl> - . detail ( " UnhandledMutationType " , m . type ) <nl> - . detail ( " TypeName " , typeStr ) ; <nl> - } <nl> + TraceEvent ( " FastRestoreApplierGetAndComputeStagingKeysDone " , applierID ) <nl> + . detail ( " GetKeys " , imcompleteStagingKeys . size ( ) ) ; <nl> <nl> - progress . transactionSize + = m . expectedSize ( ) ; <nl> + return Void ( ) ; <nl> + } <nl> <nl> - progress . nextMutation ( ) ; / / Prepare for the next mutation <nl> - / / commit per transactionBatchSizeThreshold bytes ; and commit does not cross version boundary <nl> - if ( progress . shouldCommit ( ) ) { <nl> - break ; / / Got enough mutation in the txn <nl> - } <nl> - } <nl> - } / / ! lastTxnHasError <nl> + ACTOR static Future < Void > precomputeMutationsResult ( Reference < ApplierBatchData > batchData , UID applierID , <nl> + int64_t batchIndex , Database cx ) { <nl> + / / Apply range mutations ( i . e . , clearRange ) to database cx <nl> + TraceEvent ( " FastRestoreApplerPhasePrecomputeMutationsResult " , applierID ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " Step " , " Applying clear range mutations to DB " ) <nl> + . detail ( " ClearRanges " , batchData - > stagingKeyRanges . size ( ) ) ; <nl> + state std : : vector < Future < Void > > fClearRanges ; <nl> + std : : vector < Standalone < VectorRef < KeyRangeRef > > > clearBuf ; <nl> + clearBuf . push_back ( Standalone < VectorRef < KeyRangeRef > > ( ) ) ; <nl> + Standalone < VectorRef < KeyRangeRef > > clearRanges = clearBuf . back ( ) ; <nl> + double curTxnSize = 0 ; <nl> + for ( auto & rangeMutation : batchData - > stagingKeyRanges ) { <nl> + KeyRangeRef range ( rangeMutation . mutation . param1 , rangeMutation . mutation . param2 ) ; <nl> + clearRanges . push_back ( clearRanges . arena ( ) , range ) ; <nl> + curTxnSize + = range . expectedSize ( ) ; <nl> + if ( curTxnSize > = SERVER_KNOBS - > FASTRESTORE_TXN_BATCH_MAX_BYTES ) { <nl> + fClearRanges . push_back ( applyClearRangeMutations ( clearRanges , cx ) ) ; <nl> + clearBuf . push_back ( Standalone < VectorRef < KeyRangeRef > > ( ) ) ; <nl> + clearRanges = clearBuf . back ( ) ; <nl> + curTxnSize = 0 ; <nl> + } <nl> + } <nl> + if ( curTxnSize > 0 ) { <nl> + fClearRanges . push_back ( applyClearRangeMutations ( clearRanges , cx ) ) ; <nl> + } <nl> <nl> - / / Commit the txn and prepare the starting point for next txn <nl> - if ( progress . shouldCommit ( ) ) { <nl> - wait ( tr - > commit ( ) ) ; <nl> - } <nl> + / / Apply range mutations ( i . e . , clearRange ) to stagingKeyRanges <nl> + TraceEvent ( " FastRestoreApplerPhasePrecomputeMutationsResult " , applierID ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " Step " , " Applying clear range mutations to staging keys " ) <nl> + . detail ( " ClearRanges " , batchData - > stagingKeyRanges . size ( ) ) ; <nl> + for ( auto & rangeMutation : batchData - > stagingKeyRanges ) { <nl> + std : : map < Key , StagingKey > : : iterator lb = batchData - > stagingKeys . lower_bound ( rangeMutation . mutation . param1 ) ; <nl> + std : : map < Key , StagingKey > : : iterator ub = batchData - > stagingKeys . upper_bound ( rangeMutation . mutation . param2 ) ; <nl> + while ( lb ! = ub ) { <nl> + lb - > second . add ( rangeMutation . mutation , rangeMutation . version ) ; <nl> + lb + + ; <nl> + } <nl> + } <nl> <nl> - if ( progress . isDone ( ) ) { / / Are all mutations processed ? <nl> - break ; <nl> - } <nl> - progress . nextTxn ( ) ; <nl> - } catch ( Error & e ) { <nl> - TraceEvent ( SevWarnAlways , " FastRestore_ApplyTxnError " ) <nl> - . detail ( " TxnStatus " , " ? " ) <nl> - . detail ( " ApplierApplyToDB " , self - > id ( ) ) <nl> - . detail ( " TxnId " , progress . curTxnId ) <nl> - . detail ( " CurrentIndexInCurrentTxn " , progress . curIndexInCurTxn ) <nl> - . detail ( " Version " , progress . curItInCurTxn - > first ) <nl> - . error ( e , true ) ; <nl> - progress . lastTxnHasError = true ; <nl> - / / if ( e . code ( ) = = commit_unknown_result ) { <nl> - / / lastTxnHasError = true ; <nl> - / / } <nl> - wait ( tr - > onError ( e ) ) ; <nl> + wait ( waitForAll ( fClearRanges ) ) ; <nl> + TraceEvent ( " FastRestoreApplerPhasePrecomputeMutationsResult " , applierID ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " Step " , " Getting and computing staging keys " ) <nl> + . detail ( " StagingKeys " , batchData - > stagingKeys . size ( ) ) ; <nl> + <nl> + / / Get keys in stagingKeys which does not have a baseline key by reading database cx , and precompute the key ' s value <nl> + std : : map < Key , std : : map < Key , StagingKey > : : iterator > imcompleteStagingKeys ; <nl> + std : : map < Key , StagingKey > : : iterator stagingKeyIter = batchData - > stagingKeys . begin ( ) ; <nl> + for ( ; stagingKeyIter ! = batchData - > stagingKeys . end ( ) ; stagingKeyIter + + ) { <nl> + if ( ! stagingKeyIter - > second . hasBaseValue ( ) ) { <nl> + imcompleteStagingKeys . emplace ( stagingKeyIter - > first , stagingKeyIter ) ; <nl> + } <nl> + } <nl> + <nl> + Future < Void > fGetAndComputeKeys = getAndComputeStagingKeys ( imcompleteStagingKeys , cx , applierID ) ; <nl> + <nl> + TraceEvent ( " FastRestoreApplerPhasePrecomputeMutationsResult " , applierID ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " Step " , " Compute the other staging keys " ) <nl> + . detail ( " StagingKeys " , batchData - > stagingKeys . size ( ) ) ; <nl> + / / Pre - compute pendingMutations to other keys in stagingKeys that has base value <nl> + for ( stagingKeyIter = batchData - > stagingKeys . begin ( ) ; stagingKeyIter ! = batchData - > stagingKeys . end ( ) ; <nl> + stagingKeyIter + + ) { <nl> + if ( stagingKeyIter - > second . hasBaseValue ( ) ) { <nl> + stagingKeyIter - > second . precomputeResult ( ) ; <nl> } <nl> } <nl> <nl> - TraceEvent ( " FastRestore_ApplierTxn " ) <nl> - . detail ( " ApplierApplyToDBFinished " , self - > id ( ) ) <nl> - . detail ( " CleanupCurTxnIds " , progress . curTxnId ) ; <nl> - / / clean up txn ids <nl> + TraceEvent ( " FastRestoreApplierGetAndComputeStagingKeysWaitOn " , applierID ) ; <nl> + wait ( fGetAndComputeKeys ) ; <nl> + <nl> + / / Sanity check all stagingKeys have been precomputed <nl> + ASSERT_WE_THINK ( batchData - > allKeysPrecomputed ( ) ) ; <nl> + <nl> + TraceEvent ( " FastRestoreApplerPhasePrecomputeMutationsResultDone " , applierID ) . detail ( " BatchIndex " , batchIndex ) ; <nl> + <nl> + return Void ( ) ; <nl> + } <nl> + <nl> + / / Apply mutations in batchData - > stagingKeys [ begin , end ) . <nl> + ACTOR static Future < Void > applyStagingKeysBatch ( std : : map < Key , StagingKey > : : iterator begin , <nl> + std : : map < Key , StagingKey > : : iterator end , Database cx , <nl> + FlowLock * applyStagingKeysBatchLock , UID applierID ) { <nl> + wait ( applyStagingKeysBatchLock - > take ( TaskPriority : : RestoreApplierWriteDB ) ) ; <nl> + state FlowLock : : Releaser releaser ( * applyStagingKeysBatchLock ) ; <nl> + state Reference < ReadYourWritesTransaction > tr ( new ReadYourWritesTransaction ( cx ) ) ; <nl> + state int sets = 0 ; <nl> + state int clears = 0 ; <nl> + TraceEvent ( " FastRestoreApplierPhaseApplyStagingKeysBatch " , applierID ) . detail ( " Begin " , begin - > first ) ; <nl> loop { <nl> try { <nl> tr - > reset ( ) ; <nl> tr - > setOption ( FDBTransactionOptions : : ACCESS_SYSTEM_KEYS ) ; <nl> tr - > setOption ( FDBTransactionOptions : : LOCK_AWARE ) ; <nl> - / / Clear txnIds in [ 0 , progress . curTxnId ) . We add 100 to curTxnId just to be safe . <nl> - tr - > clear ( KeyRangeRef ( restoreApplierKeyFor ( self - > id ( ) , 0 ) , <nl> - restoreApplierKeyFor ( self - > id ( ) , progress . curTxnId + 100 ) ) ) ; <nl> + std : : map < Key , StagingKey > : : iterator iter = begin ; <nl> + while ( iter ! = end ) { <nl> + if ( iter - > second . type = = MutationRef : : SetValue ) { <nl> + tr - > set ( iter - > second . key , iter - > second . val ) ; <nl> + sets + + ; <nl> + } else if ( iter - > second . type = = MutationRef : : ClearRange ) { <nl> + tr - > clear ( KeyRangeRef ( iter - > second . key , iter - > second . val ) ) ; <nl> + clears + + ; <nl> + } else { <nl> + ASSERT ( false ) ; <nl> + } <nl> + iter + + ; <nl> + if ( sets > 10000000 | | clears > 10000000 ) { <nl> + TraceEvent ( SevError , " FastRestoreApplierPhaseApplyStagingKeysBatchInfiniteLoop " , applierID ) <nl> + . detail ( " Begin " , begin - > first ) <nl> + . detail ( " Sets " , sets ) <nl> + . detail ( " Clears " , clears ) ; <nl> + } <nl> + } <nl> + TraceEvent ( " FastRestoreApplierPhaseApplyStagingKeysBatchPrecommit " , applierID ) <nl> + . detail ( " Begin " , begin - > first ) <nl> + . detail ( " Sets " , sets ) <nl> + . detail ( " Clears " , clears ) ; <nl> wait ( tr - > commit ( ) ) ; <nl> break ; <nl> } catch ( Error & e ) { <nl> wait ( tr - > onError ( e ) ) ; <nl> } <nl> } <nl> - / / House cleaning <nl> - self - > kvOps . clear ( ) ; <nl> - TraceEvent ( " FastRestore_ApplierTxn " ) . detail ( " ApplierApplyToDBFinished " , self - > id ( ) ) ; <nl> + return Void ( ) ; <nl> + } <nl> + <nl> + / / Apply mutations in stagingKeys in batches in parallel <nl> + ACTOR static Future < Void > applyStagingKeys ( Reference < ApplierBatchData > batchData , UID applierID , int64_t batchIndex , <nl> + Database cx ) { <nl> + std : : map < Key , StagingKey > : : iterator begin = batchData - > stagingKeys . begin ( ) ; <nl> + std : : map < Key , StagingKey > : : iterator cur = begin ; <nl> + double txnSize = 0 ; <nl> + std : : vector < Future < Void > > fBatches ; <nl> + TraceEvent ( " FastRestoreApplerPhaseApplyStagingKeys " , applierID ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " StagingKeys " , batchData - > stagingKeys . size ( ) ) ; <nl> + while ( cur ! = batchData - > stagingKeys . end ( ) ) { <nl> + txnSize + = cur - > second . expectedMutationSize ( ) ; <nl> + if ( txnSize > SERVER_KNOBS - > FASTRESTORE_TXN_BATCH_MAX_BYTES ) { <nl> + fBatches . push_back ( applyStagingKeysBatch ( begin , cur , cx , & batchData - > applyStagingKeysBatchLock , applierID ) ) ; <nl> + begin = cur ; <nl> + txnSize = 0 ; <nl> + } <nl> + cur + + ; <nl> + } <nl> + if ( begin ! = batchData - > stagingKeys . end ( ) ) { <nl> + fBatches . push_back ( applyStagingKeysBatch ( begin , cur , cx , & batchData - > applyStagingKeysBatchLock , applierID ) ) ; <nl> + } <nl> + <nl> + wait ( waitForAll ( fBatches ) ) ; <nl> + <nl> + TraceEvent ( " FastRestoreApplerPhaseApplyStagingKeysDone " , applierID ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " StagingKeys " , batchData - > stagingKeys . size ( ) ) ; <nl> + return Void ( ) ; <nl> + } <nl> + <nl> + / / Write mutations to the destination DB <nl> + ACTOR Future < Void > writeMutationsToDB ( UID applierID , int64_t batchIndex , Reference < ApplierBatchData > batchData , <nl> + Database cx ) { <nl> + TraceEvent ( " FastRestoreApplerPhaseApplyTxn " , applierID ) . detail ( " BatchIndex " , batchIndex ) ; <nl> + wait ( precomputeMutationsResult ( batchData , applierID , batchIndex , cx ) ) ; <nl> + <nl> + wait ( applyStagingKeys ( batchData , applierID , batchIndex , cx ) ) ; <nl> + TraceEvent ( " FastRestoreApplerPhaseApplyTxnDone " , applierID ) . detail ( " BatchIndex " , batchIndex ) ; <nl> <nl> return Void ( ) ; <nl> } <nl> <nl> ACTOR static Future < Void > handleApplyToDBRequest ( RestoreVersionBatchRequest req , Reference < RestoreApplierData > self , <nl> Database cx ) { <nl> - TraceEvent ( " FastRestore " ) <nl> - . detail ( " ApplierApplyToDB " , self - > id ( ) ) <nl> - . detail ( " DBApplierPresent " , self - > dbApplier . present ( ) ) ; <nl> - if ( ! self - > dbApplier . present ( ) ) { <nl> - self - > dbApplier = applyToDB ( self , cx ) ; <nl> - } <nl> + / / Ensure batch ( i - 1 ) is applied before batch i <nl> + wait ( self - > finishedBatch . whenAtLeast ( req . batchIndex - 1 ) ) ; <nl> + <nl> + state bool isDuplicated = true ; <nl> + Reference < ApplierBatchData > batchData = self - > batch [ req . batchIndex ] ; <nl> + TraceEvent ( " FastRestoreApplierPhaseHandleApplyToDB " , self - > id ( ) ) <nl> + . detail ( " BatchIndex " , req . batchIndex ) <nl> + . detail ( " FinishedBatch " , self - > finishedBatch . get ( ) ) <nl> + . detail ( " HasStarted " , batchData - > dbApplier . present ( ) ) ; <nl> + if ( self - > finishedBatch . get ( ) = = req . batchIndex - 1 ) { <nl> + ASSERT ( batchData . isValid ( ) ) ; <nl> + if ( ! batchData - > dbApplier . present ( ) ) { <nl> + isDuplicated = false ; <nl> + batchData - > dbApplier = Never ( ) ; <nl> + batchData - > dbApplier = writeMutationsToDB ( self - > id ( ) , req . batchIndex , batchData , cx ) ; <nl> + } <nl> + <nl> + ASSERT ( batchData - > dbApplier . present ( ) ) ; <nl> <nl> - ASSERT ( self - > dbApplier . present ( ) ) ; <nl> + wait ( batchData - > dbApplier . get ( ) ) ; <nl> <nl> - wait ( self - > dbApplier . get ( ) ) ; <nl> - req . reply . send ( RestoreCommonReply ( self - > id ( ) ) ) ; <nl> + / / Multiple actor invokation can wait on req . batchIndex - 1 ; <nl> + / / Avoid setting finishedBatch when finishedBatch > req . batchIndex <nl> + if ( self - > finishedBatch . get ( ) = = req . batchIndex - 1 ) { <nl> + self - > finishedBatch . set ( req . batchIndex ) ; <nl> + } <nl> + } <nl> + req . reply . send ( RestoreCommonReply ( self - > id ( ) , isDuplicated ) ) ; <nl> <nl> return Void ( ) ; <nl> - } <nl> \ No newline at end of file <nl> + } <nl> + <nl> + / / Copy from WriteDuringRead . actor . cpp with small modifications <nl> + / / Not all AtomicOps are handled in this function : SetVersionstampedKey , SetVersionstampedValue , and CompareAndClear <nl> + Value applyAtomicOp ( Optional < StringRef > existingValue , Value value , MutationRef : : Type type ) { <nl> + Arena arena ; <nl> + if ( type = = MutationRef : : AddValue ) <nl> + return doLittleEndianAdd ( existingValue , value , arena ) ; <nl> + else if ( type = = MutationRef : : AppendIfFits ) <nl> + return doAppendIfFits ( existingValue , value , arena ) ; <nl> + else if ( type = = MutationRef : : And | | type = = MutationRef : : AndV2 ) <nl> + return doAndV2 ( existingValue , value , arena ) ; <nl> + else if ( type = = MutationRef : : Or ) <nl> + return doOr ( existingValue , value , arena ) ; <nl> + else if ( type = = MutationRef : : Xor ) <nl> + return doXor ( existingValue , value , arena ) ; <nl> + else if ( type = = MutationRef : : Max ) <nl> + return doMax ( existingValue , value , arena ) ; <nl> + else if ( type = = MutationRef : : Min | | type = = MutationRef : : MinV2 ) <nl> + return doMinV2 ( existingValue , value , arena ) ; <nl> + else if ( type = = MutationRef : : ByteMin ) <nl> + return doByteMin ( existingValue , value , arena ) ; <nl> + else if ( type = = MutationRef : : ByteMax ) <nl> + return doByteMax ( existingValue , value , arena ) ; <nl> + else { <nl> + TraceEvent ( SevError , " ApplyAtomicOpUnhandledType " ) <nl> + . detail ( " TypeCode " , ( int ) type ) <nl> + . detail ( " TypeName " , typeString [ type ] ) ; <nl> + ASSERT ( false ) ; <nl> + } <nl> + return Value ( ) ; <nl> + } <nl> mmm a / fdbserver / RestoreApplier . actor . h <nl> ppp b / fdbserver / RestoreApplier . actor . h <nl> <nl> <nl> # include < sstream > <nl> # include " flow / Stats . h " <nl> + # include " fdbclient / Atomic . h " <nl> # include " fdbclient / FDBTypes . h " <nl> # include " fdbclient / CommitTransaction . h " <nl> # include " fdbrpc / fdbrpc . h " <nl> <nl> <nl> # include " flow / actorcompiler . h " / / has to be last include <nl> <nl> - struct RestoreApplierData : RestoreRoleData , public ReferenceCounted < RestoreApplierData > { <nl> + Value applyAtomicOp ( Optional < StringRef > existingValue , Value value , MutationRef : : Type type ) ; <nl> + <nl> + / / Key whose mutations are buffered on applier . <nl> + / / key , value , type and version defines the parsed mutation at version . <nl> + / / pendingMutations has all versioned mutations to be applied . <nl> + / / Mutations in pendingMutations whose version is below the version in StagingKey can be ignored in applying phase . <nl> + struct StagingKey { <nl> + Key key ; / / TODO : Maybe not needed ? <nl> + Value val ; <nl> + MutationRef : : Type type ; / / set or clear <nl> + Version version ; / / largest version of set or clear for the key <nl> + std : : map < Version , MutationsVec > pendingMutations ; / / mutations not set or clear type <nl> + <nl> + explicit StagingKey ( ) : version ( 0 ) , type ( MutationRef : : MAX_ATOMIC_OP ) { } <nl> + <nl> + / / Add mutation m at newVersion to stagingKey <nl> + / / Assume : SetVersionstampedKey and SetVersionstampedValue have been converted to set <nl> + void add ( const MutationRef & m , Version newVersion ) { <nl> + ASSERT ( m . type ! = MutationRef : : SetVersionstampedKey & & m . type ! = MutationRef : : SetVersionstampedValue ) ; <nl> + if ( version < newVersion ) { <nl> + if ( m . type = = MutationRef : : SetValue | | m . type = = MutationRef : : ClearRange ) { <nl> + key = m . param1 ; <nl> + val = m . param2 ; <nl> + type = ( MutationRef : : Type ) m . type ; <nl> + version = newVersion ; <nl> + } else { <nl> + if ( pendingMutations . find ( newVersion ) = = pendingMutations . end ( ) ) { <nl> + pendingMutations . emplace ( newVersion , MutationsVec ( ) ) ; <nl> + } <nl> + / / TODO : Do we really need deep copy ? <nl> + MutationsVec & mutations = pendingMutations [ newVersion ] ; <nl> + mutations . push_back_deep ( mutations . arena ( ) , m ) ; <nl> + } <nl> + } else if ( version = = newVersion ) { / / Sanity check <nl> + TraceEvent ( " FastRestoreApplierStagingKeyMutationAtSameVersion " ) <nl> + . detail ( " Version " , newVersion ) <nl> + . detail ( " NewMutation " , m . toString ( ) ) <nl> + . detail ( " ExistingKeyType " , typeString [ type ] ) ; <nl> + if ( m . type = = MutationRef : : SetValue ) { <nl> + if ( type = = MutationRef : : SetValue ) { <nl> + if ( m . param2 ! = val ) { <nl> + TraceEvent ( SevError , " FastRestoreApplierStagingKeyMutationAtSameVersionUnhandled " ) <nl> + . detail ( " Version " , newVersion ) <nl> + . detail ( " NewMutation " , m . toString ( ) ) <nl> + . detail ( " ExistingKeyType " , typeString [ type ] ) <nl> + . detail ( " ExitingKeyValue " , val ) <nl> + . detail ( " Investigate " , <nl> + " Why would backup have two sets with different value at same version " ) ; <nl> + } / / else { } Backup has duplicate set at the same version <nl> + } else { <nl> + TraceEvent ( SevWarnAlways , " FastRestoreApplierStagingKeyMutationAtSameVersionOverride " ) <nl> + . detail ( " Version " , newVersion ) <nl> + . detail ( " NewMutation " , m . toString ( ) ) <nl> + . detail ( " ExistingKeyType " , typeString [ type ] ) <nl> + . detail ( " ExitingKeyValue " , val ) ; <nl> + type = ( MutationRef : : Type ) m . type ; <nl> + val = m . param2 ; <nl> + } <nl> + } else if ( m . type = = MutationRef : : ClearRange ) { <nl> + TraceEvent ( SevWarnAlways , " FastRestoreApplierStagingKeyMutationAtSameVersionSkipped " ) <nl> + . detail ( " Version " , newVersion ) <nl> + . detail ( " NewMutation " , m . toString ( ) ) <nl> + . detail ( " ExistingKeyType " , typeString [ type ] ) <nl> + . detail ( " ExitingKeyValue " , val ) ; <nl> + } <nl> + } / / else input mutation is old and can be ignored <nl> + } <nl> + <nl> + / / Precompute the final value of the key . <nl> + void precomputeResult ( ) { <nl> + TraceEvent ( SevDebug , " FastRestoreApplierPrecomputeResult " ) <nl> + . detail ( " Key " , key ) <nl> + . detail ( " Version " , version ) <nl> + . detail ( " LargestPendingVersion " , ( pendingMutations . empty ( ) ? - 1 : pendingMutations . rbegin ( ) - > first ) ) ; <nl> + std : : map < Version , MutationsVec > : : iterator lb = pendingMutations . lower_bound ( version ) ; <nl> + if ( lb = = pendingMutations . end ( ) ) { <nl> + return ; <nl> + } <nl> + if ( lb - > first = = version ) { <nl> + / / Sanity check mutations at version are either atomicOps which can be ignored or the same value as buffered <nl> + for ( int i = 0 ; i < lb - > second . size ( ) ; i + + ) { <nl> + MutationRef m = lb - > second [ i ] ; <nl> + if ( m . type = = MutationRef : : SetValue | | m . type = = MutationRef : : ClearRange ) { <nl> + if ( std : : tie ( type , key , val ) ! = std : : tie ( m . type , m . param1 , m . param2 ) ) { <nl> + TraceEvent ( SevError , " FastRestoreApplierPrecomputeResultUnhandledSituation " ) <nl> + . detail ( " BufferedType " , typeString [ type ] ) <nl> + . detail ( " PendingType " , typeString [ m . type ] ) <nl> + . detail ( " BufferedVal " , val . toString ( ) ) <nl> + . detail ( " PendingVal " , m . param2 . toString ( ) ) ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + while ( lb ! = pendingMutations . end ( ) ) { <nl> + if ( lb - > first = = version ) { <nl> + lb + + ; <nl> + continue ; <nl> + } <nl> + for ( auto & mutation : lb - > second ) { <nl> + if ( type = = MutationRef : : CompareAndClear ) { / / Special atomicOp <nl> + Arena arena ; <nl> + Optional < ValueRef > retVal = doCompareAndClear ( val , mutation . param2 , arena ) ; <nl> + if ( ! retVal . present ( ) ) { <nl> + val = key ; <nl> + type = MutationRef : : ClearRange ; <nl> + } / / else no - op <nl> + } else if ( isAtomicOp ( ( MutationRef : : Type ) mutation . type ) ) { <nl> + Optional < StringRef > inputVal ; <nl> + if ( hasBaseValue ( ) ) { <nl> + inputVal = val ; <nl> + } <nl> + val = applyAtomicOp ( inputVal , mutation . param2 , ( MutationRef : : Type ) mutation . type ) ; <nl> + type = MutationRef : : SetValue ; / / Precomputed result should be set to DB . <nl> + } else if ( mutation . type = = MutationRef : : SetValue | | mutation . type = = MutationRef : : ClearRange ) { <nl> + type = MutationRef : : SetValue ; / / Precomputed result should be set to DB . <nl> + TraceEvent ( SevError , " FastRestoreApplierPrecomputeResultUnexpectedSet " ) <nl> + . detail ( " Type " , typeString [ mutation . type ] ) <nl> + . detail ( " Version " , lb - > first ) ; <nl> + } else { <nl> + TraceEvent ( SevWarnAlways , " FastRestoreApplierPrecomputeResultSkipUnexpectedBackupMutation " ) <nl> + . detail ( " Type " , typeString [ mutation . type ] ) <nl> + . detail ( " Version " , lb - > first ) ; <nl> + } <nl> + } <nl> + version = lb - > first ; <nl> + lb + + ; <nl> + } <nl> + } <nl> + <nl> + / / Does the key has at least 1 set or clear mutation to get the base value <nl> + bool hasBaseValue ( ) { <nl> + if ( version > 0 ) { <nl> + ASSERT ( type = = MutationRef : : SetValue | | type = = MutationRef : : ClearRange ) ; <nl> + } <nl> + return version > 0 ; <nl> + } <nl> + <nl> + / / Has all pendingMutations been pre - applied to the val ? <nl> + bool hasPrecomputed ( ) { <nl> + ASSERT ( pendingMutations . empty ( ) | | pendingMutations . rbegin ( ) - > first > = pendingMutations . begin ( ) - > first ) ; <nl> + return pendingMutations . empty ( ) | | version > = pendingMutations . rbegin ( ) - > first ; <nl> + } <nl> + <nl> + int expectedMutationSize ( ) { return key . size ( ) + val . size ( ) ; } <nl> + } ; <nl> + <nl> + / / The range mutation received on applier . <nl> + / / Range mutations should be applied both to the destination DB and to the StagingKeys <nl> + struct StagingKeyRange { <nl> + Standalone < MutationRef > mutation ; <nl> + Version version ; <nl> + <nl> + explicit StagingKeyRange ( MutationRef m , Version newVersion ) : mutation ( m ) , version ( newVersion ) { } <nl> + <nl> + bool operator < ( const StagingKeyRange & rhs ) const { <nl> + return std : : tie ( version , mutation . type , mutation . param1 , mutation . param2 ) < <nl> + std : : tie ( rhs . version , rhs . mutation . type , rhs . mutation . param1 , rhs . mutation . param2 ) ; <nl> + } <nl> + } ; <nl> + <nl> + struct ApplierBatchData : public ReferenceCounted < ApplierBatchData > { <nl> / / processedFileState : key : RestoreAsset ; value : largest version of mutation received on the applier <nl> std : : map < RestoreAsset , NotifiedVersion > processedFileState ; <nl> Optional < Future < Void > > dbApplier ; <nl> + VersionedMutationsMap kvOps ; / / Mutations at each version <nl> + std : : map < Key , StagingKey > stagingKeys ; <nl> + std : : set < StagingKeyRange > stagingKeyRanges ; <nl> + FlowLock applyStagingKeysBatchLock ; <nl> <nl> - / / rangeToApplier is in master and loader . Loader uses it to determine which applier a mutation should be sent <nl> - / / KeyRef is the inclusive lower bound of the key range the applier ( UID ) is responsible for <nl> - std : : map < Key , UID > rangeToApplier ; <nl> - / / keyOpsCount is the number of operations per key that is used to determine the key - range boundary for appliers <nl> - std : : map < Key , int > keyOpsCount ; <nl> - <nl> - / / For master applier to hold the lower bound of key ranges for each appliers <nl> - std : : vector < Key > keyRangeLowerBounds ; <nl> - <nl> - / / TODO : This block of variables may be moved to RestoreRoleData <nl> - bool inProgressApplyToDB = false ; <nl> + Future < Void > pollMetrics ; <nl> <nl> - / / Mutations at each version <nl> - VersionedMutationsMap kvOps ; <nl> + / / Status counters <nl> + struct Counters { <nl> + CounterCollection cc ; <nl> + Counter receivedBytes , receivedWeightedBytes , receivedMutations , receivedAtomicOps ; <nl> + Counter appliedWeightedBytes , appliedMutations , appliedAtomicOps ; <nl> + Counter appliedTxns ; <nl> <nl> - void addref ( ) { return ReferenceCounted < RestoreApplierData > : : addref ( ) ; } <nl> - void delref ( ) { return ReferenceCounted < RestoreApplierData > : : delref ( ) ; } <nl> + Counters ( ApplierBatchData * self , UID applierInterfID , int batchIndex ) <nl> + : cc ( " ApplierBatch " , applierInterfID . toString ( ) + " : " + std : : to_string ( batchIndex ) ) , <nl> + receivedBytes ( " ReceivedBytes " , cc ) , receivedMutations ( " ReceivedMutations " , cc ) , <nl> + receivedAtomicOps ( " ReceivedAtomicOps " , cc ) , receivedWeightedBytes ( " ReceivedWeightedMutations " , cc ) , <nl> + appliedWeightedBytes ( " AppliedWeightedBytes " , cc ) , appliedMutations ( " AppliedMutations " , cc ) , <nl> + appliedAtomicOps ( " AppliedAtomicOps " , cc ) , appliedTxns ( " AppliedTxns " , cc ) { } <nl> + } counters ; <nl> <nl> - explicit RestoreApplierData ( UID applierInterfID , int assignedIndex ) { <nl> - nodeID = applierInterfID ; <nl> - nodeIndex = assignedIndex ; <nl> + void addref ( ) { return ReferenceCounted < ApplierBatchData > : : addref ( ) ; } <nl> + void delref ( ) { return ReferenceCounted < ApplierBatchData > : : delref ( ) ; } <nl> <nl> - / / Q : Why do we need to initMetric ? <nl> - / / version . initMetric ( LiteralStringRef ( " RestoreApplier . Version " ) , cc . id ) ; <nl> + explicit ApplierBatchData ( UID nodeID , int batchIndex ) <nl> + : counters ( this , nodeID , batchIndex ) , applyStagingKeysBatchLock ( SERVER_KNOBS - > FASTRESTORE_APPLYING_PARALLELISM ) { <nl> + pollMetrics = <nl> + traceCounters ( " FastRestoreApplierMetrics " , nodeID , SERVER_KNOBS - > FASTRESTORE_ROLE_LOGGING_DELAY , <nl> + & counters . cc , nodeID . toString ( ) + " / RestoreApplierMetrics / " + std : : to_string ( batchIndex ) ) ; <nl> + TraceEvent ( " FastRestoreApplierMetricsCreated " ) . detail ( " Node " , nodeID ) ; <nl> + } <nl> + ~ ApplierBatchData ( ) = default ; <nl> <nl> - role = RestoreRole : : Applier ; <nl> + void addMutation ( MutationRef m , Version ver ) { <nl> + if ( ! isRangeMutation ( m ) ) { <nl> + auto item = stagingKeys . emplace ( m . param1 , StagingKey ( ) ) ; <nl> + item . first - > second . add ( m , ver ) ; <nl> + } else { <nl> + stagingKeyRanges . insert ( StagingKeyRange ( m , ver ) ) ; <nl> + } <nl> } <nl> <nl> - ~ RestoreApplierData ( ) = default ; <nl> + void addVersionStampedKV ( MutationRef m , Version ver , uint16_t numVersionStampedKV ) { <nl> + if ( m . type = = MutationRef : : SetVersionstampedKey ) { <nl> + / / Assume transactionNumber = 0 does not affect result <nl> + TraceEvent ( SevDebug , " FastRestoreApplierAddMutation " ) <nl> + . detail ( " MutationType " , typeString [ m . type ] ) <nl> + . detail ( " FakedTransactionNumber " , numVersionStampedKV ) ; <nl> + transformVersionstampMutation ( m , & MutationRef : : param1 , ver , numVersionStampedKV ) ; <nl> + addMutation ( m , ver ) ; <nl> + } else if ( m . type = = MutationRef : : SetVersionstampedValue ) { <nl> + / / Assume transactionNumber = 0 does not affect result <nl> + TraceEvent ( SevDebug , " FastRestoreApplierAddMutation " ) <nl> + . detail ( " MutationType " , typeString [ m . type ] ) <nl> + . detail ( " FakedTransactionNumber " , numVersionStampedKV ) ; <nl> + transformVersionstampMutation ( m , & MutationRef : : param2 , ver , numVersionStampedKV ) ; <nl> + addMutation ( m , ver ) ; <nl> + } else { <nl> + ASSERT ( false ) ; <nl> + } <nl> + } <nl> <nl> - std : : string describeNode ( ) { <nl> - std : : stringstream ss ; <nl> - ss < < " NodeID : " < < nodeID . toString ( ) < < " nodeIndex : " < < nodeIndex ; <nl> - return ss . str ( ) ; <nl> + / / Return true if all staging keys have been precomputed <nl> + bool allKeysPrecomputed ( ) { <nl> + for ( auto & stagingKey : stagingKeys ) { <nl> + if ( ! stagingKey . second . hasPrecomputed ( ) ) { <nl> + TraceEvent ( " FastRestoreApplierAllKeysPrecomputedFalse " ) <nl> + . detail ( " Key " , stagingKey . first ) <nl> + . detail ( " BufferedVersion " , stagingKey . second . version ) <nl> + . detail ( " MaxPendingVersion " , stagingKey . second . pendingMutations . rbegin ( ) - > first ) ; <nl> + return false ; <nl> + } <nl> + } <nl> + TraceEvent ( " FastRestoreApplierAllKeysPrecomputed " ) ; <nl> + return true ; <nl> } <nl> <nl> - void resetPerVersionBatch ( ) { <nl> - TraceEvent ( " FastRestore " ) . detail ( " ResetPerVersionBatchOnApplier " , nodeID ) ; <nl> - inProgressApplyToDB = false ; <nl> + void reset ( ) { <nl> kvOps . clear ( ) ; <nl> dbApplier = Optional < Future < Void > > ( ) ; <nl> } <nl> struct RestoreApplierData : RestoreRoleData , public ReferenceCounted < RestoreAppl <nl> } <nl> } ; <nl> <nl> + struct RestoreApplierData : RestoreRoleData , public ReferenceCounted < RestoreApplierData > { <nl> + / / Buffer for uncommitted data at ongoing version batches <nl> + std : : map < int , Reference < ApplierBatchData > > batch ; <nl> + NotifiedVersion finishedBatch ; / / The version batch that has been applied to DB <nl> + <nl> + void addref ( ) { return ReferenceCounted < RestoreApplierData > : : addref ( ) ; } <nl> + void delref ( ) { return ReferenceCounted < RestoreApplierData > : : delref ( ) ; } <nl> + <nl> + explicit RestoreApplierData ( UID applierInterfID , int assignedIndex ) { <nl> + nodeID = applierInterfID ; <nl> + nodeIndex = assignedIndex ; <nl> + <nl> + / / Q : Why do we need to initMetric ? <nl> + / / version . initMetric ( LiteralStringRef ( " RestoreApplier . Version " ) , cc . id ) ; <nl> + <nl> + role = RestoreRole : : Applier ; <nl> + } <nl> + <nl> + ~ RestoreApplierData ( ) = default ; <nl> + <nl> + void initVersionBatch ( int batchIndex ) { <nl> + TraceEvent ( " FastRestoreApplierInitVersionBatch " , id ( ) ) . detail ( " BatchIndex " , batchIndex ) ; <nl> + batch [ batchIndex ] = Reference < ApplierBatchData > ( new ApplierBatchData ( nodeID , batchIndex ) ) ; <nl> + } <nl> + <nl> + void resetPerRestoreRequest ( ) { <nl> + batch . clear ( ) ; <nl> + finishedBatch = NotifiedVersion ( 0 ) ; <nl> + } <nl> + <nl> + std : : string describeNode ( ) { <nl> + std : : stringstream ss ; <nl> + ss < < " NodeID : " < < nodeID . toString ( ) < < " nodeIndex : " < < nodeIndex ; <nl> + return ss . str ( ) ; <nl> + } <nl> + } ; <nl> + <nl> ACTOR Future < Void > restoreApplierCore ( RestoreApplierInterface applierInterf , int nodeIndex , Database cx ) ; <nl> <nl> # include " flow / unactorcompiler . h " <nl> mmm a / fdbserver / RestoreCommon . actor . cpp <nl> ppp b / fdbserver / RestoreCommon . actor . cpp <nl> std : : string RestoreConfigFR : : toString ( ) { <nl> return ss . str ( ) ; <nl> } <nl> <nl> - / / typedef RestoreConfigFR : : RestoreFile RestoreFileFR ; <nl> - <nl> / / parallelFileRestore is copied from FileBackupAgent . actor . cpp for the same reason as RestoreConfigFR is copied <nl> / / The implementation of parallelFileRestore is copied from FileBackupAgent . actor . cpp <nl> / / parallelFileRestore is copied from FileBackupAgent . actor . cpp for the same reason as RestoreConfigFR is copied <nl> mmm a / fdbserver / RestoreCommon . actor . h <nl> ppp b / fdbserver / RestoreCommon . actor . h <nl> struct RestoreFileFR { <nl> } <nl> <nl> bool operator < ( const RestoreFileFR & rhs ) const { <nl> - return std : : tie ( beginVersion , endVersion , fileIndex ) < std : : tie ( rhs . beginVersion , rhs . endVersion , rhs . fileIndex ) ; <nl> + return std : : tie ( beginVersion , endVersion , fileIndex , fileName ) < <nl> + std : : tie ( rhs . beginVersion , rhs . endVersion , rhs . fileIndex , rhs . fileName ) ; <nl> } <nl> <nl> RestoreFileFR ( ) <nl> ACTOR Future < Standalone < VectorRef < KeyValueRef > > > decodeLogFileBlock ( Reference < IA <nl> / / The UID in a request is the UID of the interface to handle the request <nl> ACTOR template < class Interface , class Request > <nl> Future < Void > sendBatchRequests ( RequestStream < Request > Interface : : * channel , std : : map < UID , Interface > interfaces , <nl> - std : : vector < std : : pair < UID , Request > > requests ) { <nl> + std : : vector < std : : pair < UID , Request > > requests , TaskPriority taskID = TaskPriority : : Low ) { <nl> <nl> if ( requests . empty ( ) ) { <nl> return Void ( ) ; <nl> Future < Void > sendBatchRequests ( RequestStream < Request > Interface : : * channel , std : : <nl> std : : vector < Future < REPLY_TYPE ( Request ) > > cmdReplies ; <nl> for ( auto & request : requests ) { <nl> RequestStream < Request > const * stream = & ( interfaces [ request . first ] . * channel ) ; <nl> - cmdReplies . push_back ( stream - > getReply ( request . second ) ) ; <nl> + cmdReplies . push_back ( stream - > getReply ( request . second , taskID ) ) ; <nl> } <nl> <nl> / / Alex : Unless you want to do some action when it timeout multiple times , you should use timout . Otherwise , <nl> Future < Void > sendBatchRequests ( RequestStream < Request > Interface : : * channel , std : : <nl> / / This actor can be combined with sendBatchRequests ( . . . ) <nl> ACTOR template < class Interface , class Request > <nl> Future < Void > getBatchReplies ( RequestStream < Request > Interface : : * channel , std : : map < UID , Interface > interfaces , <nl> - std : : vector < std : : pair < UID , Request > > requests , std : : vector < REPLY_TYPE ( Request ) > * replies ) { <nl> + std : : vector < std : : pair < UID , Request > > requests , std : : vector < REPLY_TYPE ( Request ) > * replies , <nl> + TaskPriority taskID = TaskPriority : : Low ) { <nl> <nl> if ( requests . empty ( ) ) { <nl> return Void ( ) ; <nl> Future < Void > getBatchReplies ( RequestStream < Request > Interface : : * channel , std : : ma <nl> std : : vector < Future < REPLY_TYPE ( Request ) > > cmdReplies ; <nl> for ( auto & request : requests ) { <nl> RequestStream < Request > const * stream = & ( interfaces [ request . first ] . * channel ) ; <nl> - cmdReplies . push_back ( stream - > getReply ( request . second ) ) ; <nl> + cmdReplies . push_back ( stream - > getReply ( request . second , taskID ) ) ; <nl> } <nl> <nl> / / Alex : Unless you want to do some action when it timeout multiple times , you should use timout . Otherwise , <nl> mmm a / fdbserver / RestoreLoader . actor . cpp <nl> ppp b / fdbserver / RestoreLoader . actor . cpp <nl> typedef std : : map < Standalone < StringRef > , Standalone < StringRef > > SerializedMutatio <nl> / / Key has the same semantics as SerializedMutationListMap ; Value is the part number of the splitted mutation list <nl> typedef std : : map < Standalone < StringRef > , uint32_t > SerializedMutationPartMap ; <nl> <nl> - void splitMutation ( Reference < RestoreLoaderData > self , MutationRef m , Arena & mvector_arena , <nl> + std : : vector < UID > getApplierIDs ( std : : map < Key , UID > & rangeToApplier ) ; <nl> + void splitMutation ( std : : map < Key , UID > * pRangeToApplier , MutationRef m , Arena & mvector_arena , <nl> VectorRef < MutationRef > & mvector , Arena & nodeIDs_arena , VectorRef < UID > & nodeIDs ) ; <nl> void _parseSerializedMutation ( std : : map < LoadingParam , VersionedMutationsMap > : : iterator kvOpsIter , <nl> SerializedMutationListMap * mutationMap , <nl> - std : : map < LoadingParam , MutationsVec > : : iterator samplesIter , const RestoreAsset & asset ) ; <nl> + std : : map < LoadingParam , MutationsVec > : : iterator samplesIter , LoaderCounters * cc , <nl> + const RestoreAsset & asset ) ; <nl> <nl> void handleRestoreSysInfoRequest ( const RestoreSysInfoRequest & req , Reference < RestoreLoaderData > self ) ; <nl> ACTOR Future < Void > handleLoadFileRequest ( RestoreLoadFileRequest req , Reference < RestoreLoaderData > self ) ; <nl> ACTOR Future < Void > handleSendMutationsRequest ( RestoreSendMutationsToAppliersRequest req , <nl> Reference < RestoreLoaderData > self ) ; <nl> - ACTOR Future < Void > sendMutationsToApplier ( Reference < RestoreLoaderData > self , VersionedMutationsMap * kvOps , <nl> - bool isRangeFile , RestoreAsset asset ) ; <nl> + ACTOR Future < Void > sendMutationsToApplier ( VersionedMutationsMap * pkvOps , int batchIndex , RestoreAsset asset , <nl> + bool isRangeFile , std : : map < Key , UID > * pRangeToApplier , <nl> + std : : map < UID , RestoreApplierInterface > * pApplierInterfaces ) ; <nl> ACTOR static Future < Void > _parseLogFileToMutationsOnLoader ( NotifiedVersion * pProcessedFileOffset , <nl> SerializedMutationListMap * mutationMap , <nl> SerializedMutationPartMap * mutationPartMap , <nl> Reference < IBackupContainer > bc , RestoreAsset asset ) ; <nl> ACTOR static Future < Void > _parseRangeFileToMutationsOnLoader ( <nl> std : : map < LoadingParam , VersionedMutationsMap > : : iterator kvOpsIter , <nl> - std : : map < LoadingParam , MutationsVec > : : iterator samplesIter , Reference < IBackupContainer > bc , Version version , <nl> - RestoreAsset asset ) ; <nl> + std : : map < LoadingParam , MutationsVec > : : iterator samplesIter , LoaderCounters * cc , Reference < IBackupContainer > bc , <nl> + Version version , RestoreAsset asset ) ; <nl> <nl> ACTOR Future < Void > restoreLoaderCore ( RestoreLoaderInterface loaderInterf , int nodeIndex , Database cx ) { <nl> state Reference < RestoreLoaderData > self = <nl> Reference < RestoreLoaderData > ( new RestoreLoaderData ( loaderInterf . id ( ) , nodeIndex ) ) ; <nl> - <nl> state ActorCollection actors ( false ) ; <nl> state Future < Void > exitRole = Never ( ) ; <nl> + state Future < Void > updateProcessStatsTimer = delay ( SERVER_KNOBS - > FASTRESTORE_UPDATE_PROCESS_STATS_INTERVAL ) ; <nl> + <nl> + actors . add ( traceProcessMetrics ( self , " Loader " ) ) ; <nl> + <nl> loop { <nl> state std : : string requestTypeStr = " [ Init ] " ; <nl> <nl> ACTOR Future < Void > restoreLoaderCore ( RestoreLoaderInterface loaderInterf , int no <nl> } <nl> when ( RestoreVersionBatchRequest req = waitNext ( loaderInterf . initVersionBatch . getFuture ( ) ) ) { <nl> requestTypeStr = " initVersionBatch " ; <nl> - wait ( handleInitVersionBatchRequest ( req , self ) ) ; <nl> + actors . add ( handleInitVersionBatchRequest ( req , self ) ) ; <nl> } <nl> - when ( RestoreVersionBatchRequest req = waitNext ( loaderInterf . finishRestore . getFuture ( ) ) ) { <nl> + when ( RestoreFinishRequest req = waitNext ( loaderInterf . finishRestore . getFuture ( ) ) ) { <nl> requestTypeStr = " finishRestore " ; <nl> handleFinishRestoreRequest ( req , self ) ; <nl> - exitRole = Void ( ) ; <nl> + if ( req . terminate ) { <nl> + exitRole = Void ( ) ; <nl> + } <nl> + } <nl> + when ( wait ( updateProcessStatsTimer ) ) { <nl> + updateProcessStats ( self ) ; <nl> + updateProcessStatsTimer = delay ( SERVER_KNOBS - > FASTRESTORE_UPDATE_PROCESS_STATS_INTERVAL ) ; <nl> } <nl> when ( wait ( exitRole ) ) { <nl> TraceEvent ( " FastRestore " ) . detail ( " RestoreLoaderCore " , " ExitRole " ) . detail ( " NodeID " , self - > id ( ) ) ; <nl> ACTOR Future < Void > restoreLoaderCore ( RestoreLoaderInterface loaderInterf , int no <nl> <nl> / / Assume : Only update the local data if it ( applierInterf ) has not been set <nl> void handleRestoreSysInfoRequest ( const RestoreSysInfoRequest & req , Reference < RestoreLoaderData > self ) { <nl> - TraceEvent ( " FastRestore " ) . detail ( " HandleRestoreSysInfoRequest " , self - > id ( ) ) ; <nl> + TraceEvent ( " FastRestoreLoader " , self - > id ( ) ) . detail ( " HandleRestoreSysInfoRequest " , self - > id ( ) ) ; <nl> ASSERT ( self . isValid ( ) ) ; <nl> <nl> / / The loader has received the appliers interfaces <nl> void handleRestoreSysInfoRequest ( const RestoreSysInfoRequest & req , Reference < Res <nl> req . reply . send ( RestoreCommonReply ( self - > id ( ) ) ) ; <nl> } <nl> <nl> - ACTOR Future < Void > _processLoadingParam ( LoadingParam param , Reference < RestoreLoaderData > self ) { <nl> + ACTOR Future < Void > _processLoadingParam ( LoadingParam param , Reference < LoaderBatchData > batchData , UID loaderID , <nl> + Reference < IBackupContainer > bc ) { <nl> / / Temporary data structure for parsing log files into ( version , < K , V , mutationType > ) <nl> / / Must use StandAlone to save mutations , otherwise , the mutationref memory will be corrupted <nl> / / mutationMap : Key is the unique identifier for a batch of mutation logs at the same version <nl> ACTOR Future < Void > _processLoadingParam ( LoadingParam param , Reference < RestoreLoa <nl> state std : : map < Standalone < StringRef > , uint32_t > mutationPartMap ; / / Sanity check the data parsing is correct <nl> state NotifiedVersion processedFileOffset ( 0 ) ; <nl> state std : : vector < Future < Void > > fileParserFutures ; <nl> - state std : : map < LoadingParam , VersionedMutationsMap > : : iterator kvOpsPerLPIter = self - > kvOpsPerLP . end ( ) ; <nl> - state std : : map < LoadingParam , MutationsVec > : : iterator samplesIter = self - > sampleMutations . end ( ) ; <nl> + state std : : map < LoadingParam , VersionedMutationsMap > : : iterator kvOpsPerLPIter = batchData - > kvOpsPerLP . end ( ) ; <nl> + state std : : map < LoadingParam , MutationsVec > : : iterator samplesIter = batchData - > sampleMutations . end ( ) ; <nl> <nl> / / Q : How to record the param ' s fields inside LoadingParam Refer to storageMetrics <nl> - TraceEvent ( " FastRestore " ) . detail ( " Loader " , self - > id ( ) ) . detail ( " StartProcessLoadParam " , param . toString ( ) ) ; <nl> + TraceEvent ( " FastRestoreLoaderProcessLoadingParam " , loaderID ) . detail ( " LoadingParam " , param . toString ( ) ) ; <nl> ASSERT ( param . blockSize > 0 ) ; <nl> ASSERT ( param . asset . offset % param . blockSize = = 0 ) ; / / Parse file must be at block bondary . <nl> - ASSERT ( self - > kvOpsPerLP . find ( param ) = = self - > kvOpsPerLP . end ( ) ) ; <nl> + ASSERT ( batchData - > kvOpsPerLP . find ( param ) = = batchData - > kvOpsPerLP . end ( ) ) ; <nl> <nl> / / NOTE : map ' s iterator is guaranteed to be stable , but pointer may not . <nl> / / state VersionedMutationsMap * kvOps = & self - > kvOpsPerLP [ param ] ; <nl> - self - > kvOpsPerLP . emplace ( param , VersionedMutationsMap ( ) ) ; <nl> - self - > sampleMutations . emplace ( param , MutationsVec ( ) ) ; <nl> - kvOpsPerLPIter = self - > kvOpsPerLP . find ( param ) ; <nl> - samplesIter = self - > sampleMutations . find ( param ) ; <nl> + batchData - > kvOpsPerLP . emplace ( param , VersionedMutationsMap ( ) ) ; <nl> + batchData - > sampleMutations . emplace ( param , MutationsVec ( ) ) ; <nl> + kvOpsPerLPIter = batchData - > kvOpsPerLP . find ( param ) ; <nl> + samplesIter = batchData - > sampleMutations . find ( param ) ; <nl> <nl> for ( int64_t j = param . asset . offset ; j < param . asset . len ; j + = param . blockSize ) { <nl> RestoreAsset subAsset = param . asset ; <nl> subAsset . offset = j ; <nl> subAsset . len = std : : min < int64_t > ( param . blockSize , param . asset . len - j ) ; <nl> if ( param . isRangeFile ) { <nl> - fileParserFutures . push_back ( _parseRangeFileToMutationsOnLoader ( kvOpsPerLPIter , samplesIter , self - > bc , <nl> - param . rangeVersion . get ( ) , subAsset ) ) ; <nl> + fileParserFutures . push_back ( _parseRangeFileToMutationsOnLoader ( <nl> + kvOpsPerLPIter , samplesIter , & batchData - > counters , bc , param . rangeVersion . get ( ) , subAsset ) ) ; <nl> } else { <nl> / / TODO : Sanity check the log file ' s range is overlapped with the restored version range <nl> - fileParserFutures . push_back ( _parseLogFileToMutationsOnLoader ( & processedFileOffset , & mutationMap , <nl> - & mutationPartMap , self - > bc , subAsset ) ) ; <nl> + fileParserFutures . push_back ( <nl> + _parseLogFileToMutationsOnLoader ( & processedFileOffset , & mutationMap , & mutationPartMap , bc , subAsset ) ) ; <nl> } <nl> } <nl> wait ( waitForAll ( fileParserFutures ) ) ; <nl> <nl> if ( ! param . isRangeFile ) { <nl> - _parseSerializedMutation ( kvOpsPerLPIter , & mutationMap , samplesIter , param . asset ) ; <nl> + _parseSerializedMutation ( kvOpsPerLPIter , & mutationMap , samplesIter , & batchData - > counters , param . asset ) ; <nl> } <nl> <nl> - TraceEvent ( " FastRestore " ) . detail ( " Loader " , self - > id ( ) ) . detail ( " FinishLoadingFile " , param . asset . filename ) ; <nl> + TraceEvent ( " FastRestoreLoaderProcessLoadingParamDone " , loaderID ) . detail ( " LoadingParam " , param . toString ( ) ) ; <nl> <nl> return Void ( ) ; <nl> } <nl> <nl> / / A loader can process multiple RestoreLoadFileRequest in parallel . <nl> ACTOR Future < Void > handleLoadFileRequest ( RestoreLoadFileRequest req , Reference < RestoreLoaderData > self ) { <nl> - if ( self - > processedFileParams . find ( req . param ) = = self - > processedFileParams . end ( ) ) { <nl> - TraceEvent ( " FastRestore " ) . detail ( " Loader " , self - > id ( ) ) . detail ( " ProcessLoadParam " , req . param . toString ( ) ) ; <nl> - ASSERT ( self - > sampleMutations . find ( req . param ) = = self - > sampleMutations . end ( ) ) ; <nl> - self - > processedFileParams [ req . param ] = Never ( ) ; <nl> - self - > processedFileParams [ req . param ] = _processLoadingParam ( req . param , self ) ; <nl> + state Reference < LoaderBatchData > batchData = self - > batch [ req . batchIndex ] ; <nl> + state bool isDuplicated = true ; <nl> + ASSERT ( batchData . isValid ( ) ) ; <nl> + bool paramExist = batchData - > processedFileParams . find ( req . param ) ! = batchData - > processedFileParams . end ( ) ; <nl> + bool isReady = paramExist ? batchData - > processedFileParams [ req . param ] . isReady ( ) : false ; <nl> + <nl> + TraceEvent ( " FastRestoreLoaderPhaseLoadFile " , self - > id ( ) ) <nl> + . detail ( " BatchIndex " , req . batchIndex ) <nl> + . detail ( " ProcessLoadParam " , req . param . toString ( ) ) <nl> + . detail ( " NotProcessed " , ! paramExist ) <nl> + . detail ( " Processed " , isReady ) ; <nl> + if ( batchData - > processedFileParams . find ( req . param ) = = batchData - > processedFileParams . end ( ) ) { <nl> + TraceEvent ( " FastRestoreLoadFile " , self - > id ( ) ) <nl> + . detail ( " BatchIndex " , req . batchIndex ) <nl> + . detail ( " ProcessLoadParam " , req . param . toString ( ) ) ; <nl> + ASSERT ( batchData - > sampleMutations . find ( req . param ) = = batchData - > sampleMutations . end ( ) ) ; <nl> + batchData - > processedFileParams [ req . param ] = Never ( ) ; / / Ensure second exec . wait on _processLoadingParam ( ) <nl> + batchData - > processedFileParams [ req . param ] = _processLoadingParam ( req . param , batchData , self - > id ( ) , self - > bc ) ; <nl> + isDuplicated = false ; <nl> } else { <nl> - TraceEvent ( " FastRestore " ) . detail ( " Loader " , self - > id ( ) ) . detail ( " WaitOnProcessLoadParam " , req . param . toString ( ) ) ; <nl> + TraceEvent ( " FastRestoreLoadFile " , self - > id ( ) ) <nl> + . detail ( " BatchIndex " , req . batchIndex ) <nl> + . detail ( " WaitOnProcessLoadParam " , req . param . toString ( ) ) ; <nl> } <nl> - ASSERT ( self - > processedFileParams . find ( req . param ) ! = self - > processedFileParams . end ( ) ) ; <nl> - wait ( self - > processedFileParams [ req . param ] ) ; / / wait on the processing of the req . param . <nl> + ASSERT ( batchData - > processedFileParams . find ( req . param ) ! = batchData - > processedFileParams . end ( ) ) ; <nl> + wait ( batchData - > processedFileParams [ req . param ] ) ; / / wait on the processing of the req . param . <nl> <nl> - req . reply . send ( RestoreLoadFileReply ( req . param , self - > sampleMutations [ req . param ] ) ) ; <nl> + req . reply . send ( RestoreLoadFileReply ( req . param , batchData - > sampleMutations [ req . param ] , isDuplicated ) ) ; <nl> + TraceEvent ( " FastRestoreLoaderPhaseLoadFileDone " , self - > id ( ) ) <nl> + . detail ( " BatchIndex " , req . batchIndex ) <nl> + . detail ( " ProcessLoadParam " , req . param . toString ( ) ) ; <nl> / / TODO : clear self - > sampleMutations [ req . param ] memory to save memory on loader <nl> return Void ( ) ; <nl> } <nl> <nl> ACTOR Future < Void > handleSendMutationsRequest ( RestoreSendMutationsToAppliersRequest req , <nl> Reference < RestoreLoaderData > self ) { <nl> - state std : : map < LoadingParam , VersionedMutationsMap > : : iterator item = self - > kvOpsPerLP . begin ( ) ; <nl> + state Reference < LoaderBatchData > batchData = self - > batch [ req . batchIndex ] ; <nl> + state std : : map < LoadingParam , VersionedMutationsMap > : : iterator item = batchData - > kvOpsPerLP . begin ( ) ; <nl> + state Reference < LoaderBatchStatus > batchStatus = self - > status [ req . batchIndex ] ; <nl> + state bool isDuplicated = true ; <nl> + <nl> + TraceEvent ( " FastRestoreLoaderPhaseSendMutations " , self - > id ( ) ) <nl> + . detail ( " BatchIndex " , req . batchIndex ) <nl> + . detail ( " UseRangeFile " , req . useRangeFile ) <nl> + . detail ( " LoaderSendStatus " , batchStatus - > toString ( ) ) ; <nl> + <nl> + if ( ! req . useRangeFile ) { <nl> + if ( ! batchStatus - > sendAllLogs . present ( ) ) { / / Has not sent <nl> + batchStatus - > sendAllLogs = Never ( ) ; <nl> + isDuplicated = false ; <nl> + TraceEvent ( SevInfo , " FastRestoreSendMutationsProcessLogRequest " , self - > id ( ) ) <nl> + . detail ( " BatchIndex " , req . batchIndex ) <nl> + . detail ( " UseRangeFile " , req . useRangeFile ) ; <nl> + ASSERT ( ! batchStatus - > sendAllRanges . present ( ) ) ; <nl> + } else if ( ! batchStatus - > sendAllLogs . get ( ) . isReady ( ) ) { / / In the process of sending <nl> + TraceEvent ( SevDebug , " FastRestoreSendMutationsWaitDuplicateLogRequest " , self - > id ( ) ) <nl> + . detail ( " BatchIndex " , req . batchIndex ) <nl> + . detail ( " UseRangeFile " , req . useRangeFile ) ; <nl> + wait ( batchStatus - > sendAllLogs . get ( ) ) ; <nl> + } else { / / Already sent <nl> + TraceEvent ( SevDebug , " FastRestoreSendMutationsSkipDuplicateLogRequest " , self - > id ( ) ) <nl> + . detail ( " BatchIndex " , req . batchIndex ) <nl> + . detail ( " UseRangeFile " , req . useRangeFile ) ; <nl> + } <nl> + } else { <nl> + if ( ! batchStatus - > sendAllRanges . present ( ) ) { <nl> + batchStatus - > sendAllRanges = Never ( ) ; <nl> + isDuplicated = false ; <nl> + TraceEvent ( SevInfo , " FastRestoreSendMutationsProcessRangeRequest " , self - > id ( ) ) <nl> + . detail ( " BatchIndex " , req . batchIndex ) <nl> + . detail ( " UseRangeFile " , req . useRangeFile ) ; <nl> + ASSERT ( batchStatus - > sendAllLogs . get ( ) . isReady ( ) ) ; <nl> + } else if ( ! batchStatus - > sendAllRanges . get ( ) . isReady ( ) ) { <nl> + TraceEvent ( SevDebug , " FastRestoreSendMutationsWaitDuplicateRangeRequest " , self - > id ( ) ) <nl> + . detail ( " BatchIndex " , req . batchIndex ) <nl> + . detail ( " UseRangeFile " , req . useRangeFile ) ; <nl> + wait ( batchStatus - > sendAllRanges . get ( ) ) ; <nl> + } else { <nl> + TraceEvent ( SevDebug , " FastRestoreSendMutationsSkipDuplicateRangeRequest " , self - > id ( ) ) <nl> + . detail ( " BatchIndex " , req . batchIndex ) <nl> + . detail ( " UseRangeFile " , req . useRangeFile ) ; <nl> + } <nl> + } <nl> <nl> - self - > rangeToApplier = req . rangeToApplier ; <nl> - for ( ; item ! = self - > kvOpsPerLP . end ( ) ; item + + ) { <nl> - if ( item - > first . isRangeFile = = req . useRangeFile ) { <nl> - / / Send the parsed mutation to applier who will apply the mutation to DB <nl> - wait ( sendMutationsToApplier ( self , & item - > second , item - > first . isRangeFile , item - > first . asset ) ) ; <nl> + if ( ! isDuplicated ) { <nl> + vector < Future < Void > > fSendMutations ; <nl> + batchData - > rangeToApplier = req . rangeToApplier ; <nl> + for ( ; item ! = batchData - > kvOpsPerLP . end ( ) ; item + + ) { <nl> + if ( item - > first . isRangeFile = = req . useRangeFile ) { <nl> + / / Send the parsed mutation to applier who will apply the mutation to DB <nl> + fSendMutations . push_back ( sendMutationsToApplier ( & item - > second , req . batchIndex , item - > first . asset , <nl> + item - > first . isRangeFile , & batchData - > rangeToApplier , <nl> + & self - > appliersInterf ) ) ; <nl> + } <nl> + } <nl> + wait ( waitForAll ( fSendMutations ) ) ; <nl> + if ( req . useRangeFile ) { <nl> + batchStatus - > sendAllRanges = Void ( ) ; / / Finish sending kvs parsed from range files <nl> + } else { <nl> + batchStatus - > sendAllLogs = Void ( ) ; <nl> } <nl> } <nl> <nl> - req . reply . send ( RestoreCommonReply ( self - > id ( ) ) ) ; <nl> + TraceEvent ( " FastRestoreLoaderPhaseSendMutationsDone " , self - > id ( ) ) <nl> + . detail ( " BatchIndex " , req . batchIndex ) <nl> + . detail ( " UseRangeFile " , req . useRangeFile ) <nl> + . detail ( " LoaderSendStatus " , batchStatus - > toString ( ) ) ; <nl> + req . reply . send ( RestoreCommonReply ( self - > id ( ) , isDuplicated ) ) ; <nl> return Void ( ) ; <nl> } <nl> <nl> - / / TODO : This function can be revised better <nl> - / / Assume : kvOps data are from the same file . <nl> - ACTOR Future < Void > sendMutationsToApplier ( Reference < RestoreLoaderData > self , VersionedMutationsMap * pkvOps , <nl> - bool isRangeFile , RestoreAsset asset ) { <nl> + / / Assume : kvOps data are from the same RestoreAsset . <nl> + / / Input : pkvOps : versioned kv mutation for the asset in the version batch ( batchIndex ) <nl> + / / isRangeFile : is pkvOps from range file ? Let receiver ( applier ) know if the mutation is log mutation ; <nl> + / / pRangeToApplier : range to applierID mapping , deciding which applier is responsible for which range <nl> + / / pApplierInterfaces : applier interfaces to send the mutations to <nl> + ACTOR Future < Void > sendMutationsToApplier ( VersionedMutationsMap * pkvOps , int batchIndex , RestoreAsset asset , <nl> + bool isRangeFile , std : : map < Key , UID > * pRangeToApplier , <nl> + std : : map < UID , RestoreApplierInterface > * pApplierInterfaces ) { <nl> state VersionedMutationsMap & kvOps = * pkvOps ; <nl> state VersionedMutationsMap : : iterator kvOp = kvOps . begin ( ) ; <nl> state int kvCount = 0 ; <nl> state int splitMutationIndex = 0 ; <nl> - state std : : vector < UID > applierIDs = self - > getWorkingApplierIDs ( ) ; <nl> state std : : vector < std : : pair < UID , RestoreSendVersionedMutationsRequest > > requests ; <nl> state Version prevVersion = 0 ; / / startVersion <nl> + state std : : vector < UID > applierIDs = getApplierIDs ( * pRangeToApplier ) ; <nl> <nl> - TraceEvent ( " FastRestore_SendMutationToApplier " ) <nl> - . detail ( " Loader " , self - > id ( ) ) <nl> + TraceEvent ( " FastRestoreLoaderSendMutationToApplier " ) <nl> . detail ( " IsRangeFile " , isRangeFile ) <nl> . detail ( " EndVersion " , asset . endVersion ) <nl> . detail ( " RestoreAsset " , asset . toString ( ) ) ; <nl> <nl> + / / There should be no mutation at asset . endVersion version because it is exclusive <nl> + if ( kvOps . find ( asset . endVersion ) ! = kvOps . end ( ) ) { <nl> + TraceEvent ( SevError , " FastRestoreLoaderSendMutationToApplier " ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " RestoreAsset " , asset . toString ( ) ) <nl> + . detail ( " IsRangeFile " , isRangeFile ) <nl> + . detail ( " Data loss at version " , asset . endVersion ) ; <nl> + } <nl> / / Ensure there is a mutation request sent at endVersion , so that applier can advance its notifiedVersion <nl> if ( kvOps . find ( asset . endVersion ) = = kvOps . end ( ) ) { <nl> kvOps [ asset . endVersion ] = MutationsVec ( ) ; / / Empty mutation vector will be handled by applier <nl> ACTOR Future < Void > sendMutationsToApplier ( Reference < RestoreLoaderData > self , Ver <nl> / / Because using a vector of mutations causes overhead , and the range mutation should happen rarely ; <nl> / / We handle the range mutation and key mutation differently for the benefit of avoiding memory copy <nl> / / WARNING : The splitMutation ( ) may have bugs <nl> - splitMutation ( self , kvm , mvector . arena ( ) , mvector . contents ( ) , nodeIDs . arena ( ) , nodeIDs . contents ( ) ) ; <nl> + splitMutation ( pRangeToApplier , kvm , mvector . arena ( ) , mvector . contents ( ) , nodeIDs . arena ( ) , <nl> + nodeIDs . contents ( ) ) ; <nl> ASSERT ( mvector . size ( ) = = nodeIDs . size ( ) ) ; <nl> <nl> for ( splitMutationIndex = 0 ; splitMutationIndex < mvector . size ( ) ; splitMutationIndex + + ) { <nl> ACTOR Future < Void > sendMutationsToApplier ( Reference < RestoreLoaderData > self , Ver <nl> kvCount + + ; <nl> } <nl> } else { / / mutation operates on a particular key <nl> - std : : map < Key , UID > : : iterator itlow = self - > rangeToApplier . upper_bound ( kvm . param1 ) ; <nl> + std : : map < Key , UID > : : iterator itlow = pRangeToApplier - > upper_bound ( kvm . param1 ) ; <nl> - - itlow ; / / make sure itlow - > first < = m . param1 <nl> ASSERT ( itlow - > first < = kvm . param1 ) ; <nl> MutationRef mutation = kvm ; <nl> ACTOR Future < Void > sendMutationsToApplier ( Reference < RestoreLoaderData > self , Ver <nl> } <nl> } / / Mutations at the same version <nl> <nl> + / / TODO : Sanity check each asset has been received exactly once ! <nl> / / Send the mutations to appliers for each version <nl> for ( auto & applierID : applierIDs ) { <nl> requests . push_back ( std : : make_pair ( <nl> - applierID , RestoreSendVersionedMutationsRequest ( asset , prevVersion , commitVersion , isRangeFile , <nl> - applierMutationsBuffer [ applierID ] ) ) ) ; <nl> + applierID , RestoreSendVersionedMutationsRequest ( batchIndex , asset , prevVersion , commitVersion , <nl> + isRangeFile , applierMutationsBuffer [ applierID ] ) ) ) ; <nl> } <nl> TraceEvent ( SevDebug , " FastRestore_SendMutationToApplier " ) <nl> - . detail ( " Loader " , self - > id ( ) ) <nl> . detail ( " PrevVersion " , prevVersion ) <nl> . detail ( " CommitVersion " , commitVersion ) <nl> . detail ( " RestoreAsset " , asset . toString ( ) ) ; <nl> ASSERT ( prevVersion < commitVersion ) ; <nl> prevVersion = commitVersion ; <nl> - wait ( sendBatchRequests ( & RestoreApplierInterface : : sendMutationVector , self - > appliersInterf , requests ) ) ; <nl> + wait ( sendBatchRequests ( & RestoreApplierInterface : : sendMutationVector , * pApplierInterfaces , requests , <nl> + TaskPriority : : RestoreLoaderSendMutations ) ) ; <nl> <nl> requests . clear ( ) ; <nl> <nl> ACTOR Future < Void > sendMutationsToApplier ( Reference < RestoreLoaderData > self , Ver <nl> } <nl> <nl> / / TODO : Add a unit test for this function <nl> - void splitMutation ( Reference < RestoreLoaderData > self , MutationRef m , Arena & mvector_arena , <nl> + void splitMutation ( std : : map < Key , UID > * pRangeToApplier , MutationRef m , Arena & mvector_arena , <nl> VectorRef < MutationRef > & mvector , Arena & nodeIDs_arena , VectorRef < UID > & nodeIDs ) { <nl> + TraceEvent ( SevWarn , " FastRestoreSplitMutation " ) . detail ( " Mutation " , m . toString ( ) ) ; <nl> / / mvector [ i ] should be mapped to nodeID [ i ] <nl> ASSERT ( mvector . empty ( ) ) ; <nl> ASSERT ( nodeIDs . empty ( ) ) ; <nl> / / key range [ m - > param1 , m - > param2 ) <nl> std : : map < Standalone < KeyRef > , UID > : : iterator itlow , itup ; / / we will return [ itlow , itup ) <nl> - itlow = self - > rangeToApplier . lower_bound ( m . param1 ) ; / / lower_bound returns the iterator that is > = m . param1 <nl> + itlow = pRangeToApplier - > lower_bound ( m . param1 ) ; / / lower_bound returns the iterator that is > = m . param1 <nl> if ( itlow - > first > m . param1 ) { <nl> - if ( itlow ! = self - > rangeToApplier . begin ( ) ) { <nl> + if ( itlow ! = pRangeToApplier - > begin ( ) ) { <nl> - - itlow ; <nl> } <nl> } <nl> <nl> - itup = self - > rangeToApplier . upper_bound ( m . param2 ) ; / / return rmap : : end if no key is after m . param2 . <nl> - ASSERT ( itup = = self - > rangeToApplier . end ( ) | | itup - > first > m . param2 ) ; <nl> + itup = pRangeToApplier - > upper_bound ( m . param2 ) ; / / return rmap : : end if no key is after m . param2 . <nl> + ASSERT ( itup = = pRangeToApplier - > end ( ) | | itup - > first > m . param2 ) ; <nl> <nl> std : : map < Standalone < KeyRef > , UID > : : iterator itApplier ; <nl> while ( itlow ! = itup ) { <nl> bool concatenateBackupMutationForLogFile ( std : : map < Standalone < StringRef > , Standal <nl> / / Parse the kv pair ( version , serialized_mutation ) , which are the results parsed from log file , into <nl> / / ( version , < K , V , mutationType > ) pair ; <nl> / / Put the parsed versioned mutations into * pkvOps . <nl> - / / <nl> + / / <nl> / / Input key : [ commitVersion_of_the_mutation_batch : uint64_t ] ; <nl> / / Input value : [ includeVersion : uint64_t ] [ val_length : uint32_t ] [ encoded_list_of_mutations ] , where <nl> / / includeVersion is the serialized version in the batch commit . It is not the commitVersion in Input key . <nl> - / / <nl> + / / <nl> / / val_length is always equal to ( val . size ( ) - 12 ) ; otherwise , <nl> / / we may not get the entire mutation list for the version encoded_list_of_mutations : <nl> / / [ mutation1 ] [ mutation2 ] . . . [ mutationk ] , where <nl> / / a mutation is encoded as [ type : uint32_t ] [ keyLength : uint32_t ] [ valueLength : uint32_t ] [ keyContent ] [ valueContent ] <nl> void _parseSerializedMutation ( std : : map < LoadingParam , VersionedMutationsMap > : : iterator kvOpsIter , <nl> SerializedMutationListMap * pmutationMap , <nl> - std : : map < LoadingParam , MutationsVec > : : iterator samplesIter , const RestoreAsset & asset ) { <nl> + std : : map < LoadingParam , MutationsVec > : : iterator samplesIter , LoaderCounters * cc , <nl> + const RestoreAsset & asset ) { <nl> VersionedMutationsMap & kvOps = kvOpsIter - > second ; <nl> MutationsVec & samples = samplesIter - > second ; <nl> SerializedMutationListMap & mutationMap = * pmutationMap ; <nl> void _parseSerializedMutation ( std : : map < LoadingParam , VersionedMutationsMap > : : ite <nl> mutation . param2 = mutation . param2 < asset . range . end ? mutation . param2 : asset . range . end ; <nl> } <nl> <nl> + cc - > sampledLogBytes + = mutation . totalSize ( ) ; <nl> + <nl> TraceEvent ( SevFRMutationInfo , " FastRestore_VerboseDebug " ) <nl> . detail ( " CommitVersion " , commitVersion ) <nl> . detail ( " ParsedMutation " , mutation . toString ( ) ) ; <nl> void _parseSerializedMutation ( std : : map < LoadingParam , VersionedMutationsMap > : : ite <nl> / / Parsing the data blocks in a range file <nl> ACTOR static Future < Void > _parseRangeFileToMutationsOnLoader ( <nl> std : : map < LoadingParam , VersionedMutationsMap > : : iterator kvOpsIter , <nl> - std : : map < LoadingParam , MutationsVec > : : iterator samplesIter , Reference < IBackupContainer > bc , Version version , <nl> - RestoreAsset asset ) { <nl> + std : : map < LoadingParam , MutationsVec > : : iterator samplesIter , LoaderCounters * cc , Reference < IBackupContainer > bc , <nl> + Version version , RestoreAsset asset ) { <nl> state VersionedMutationsMap & kvOps = kvOpsIter - > second ; <nl> state MutationsVec & sampleMutations = samplesIter - > second ; <nl> <nl> ACTOR static Future < Void > _parseRangeFileToMutationsOnLoader ( <nl> / / Should NOT add prefix or remove surfix for the backup data ! <nl> MutationRef m ( MutationRef : : Type : : SetValue , data [ i ] . key , <nl> data [ i ] . value ) ; / / ASSUME : all operation in range file is set . <nl> + cc - > loadedRangeBytes + = m . totalSize ( ) ; <nl> <nl> / / We cache all kv operations into kvOps , and apply all kv operations later in one place <nl> kvOps . insert ( std : : make_pair ( version , MutationsVec ( ) ) ) ; <nl> ACTOR static Future < Void > _parseRangeFileToMutationsOnLoader ( <nl> kvOps [ version ] . push_back_deep ( kvOps [ version ] . arena ( ) , m ) ; <nl> / / Sampling ( FASTRESTORE_SAMPLING_PERCENT % ) data <nl> if ( deterministicRandom ( ) - > random01 ( ) * 100 < SERVER_KNOBS - > FASTRESTORE_SAMPLING_PERCENT ) { <nl> + cc - > sampledRangeBytes + = m . totalSize ( ) ; <nl> sampleMutations . push_back_deep ( sampleMutations . arena ( ) , m ) ; <nl> } <nl> } <nl> ACTOR static Future < Void > _parseLogFileToMutationsOnLoader ( NotifiedVersion * pPro <nl> <nl> return Void ( ) ; <nl> } <nl> + <nl> + / / Return applier IDs that are used to apply key - values <nl> + std : : vector < UID > getApplierIDs ( std : : map < Key , UID > & rangeToApplier ) { <nl> + std : : vector < UID > applierIDs ; <nl> + for ( auto & applier : rangeToApplier ) { <nl> + applierIDs . push_back ( applier . second ) ; <nl> + } <nl> + <nl> + ASSERT ( ! applierIDs . empty ( ) ) ; <nl> + return applierIDs ; <nl> + } <nl> \ No newline at end of file <nl> mmm a / fdbserver / RestoreLoader . actor . h <nl> ppp b / fdbserver / RestoreLoader . actor . h <nl> <nl> <nl> # include " flow / actorcompiler . h " / / has to be last include <nl> <nl> - struct RestoreLoaderData : RestoreRoleData , public ReferenceCounted < RestoreLoaderData > { <nl> + struct LoaderBatchData : public ReferenceCounted < LoaderBatchData > { <nl> std : : map < LoadingParam , Future < Void > > processedFileParams ; <nl> std : : map < LoadingParam , VersionedMutationsMap > kvOpsPerLP ; / / Buffered kvOps for each loading param <nl> <nl> struct RestoreLoaderData : RestoreRoleData , public ReferenceCounted < RestoreLoade <nl> <nl> / / Sampled mutations to be sent back to restore master <nl> std : : map < LoadingParam , MutationsVec > sampleMutations ; <nl> - / / keyOpsCount is the number of operations per key which is used to determine the key - range boundary for appliers <nl> - std : : map < Standalone < KeyRef > , int > keyOpsCount ; <nl> int numSampledMutations ; / / The total number of mutations received from sampled data . <nl> <nl> + Future < Void > pollMetrics ; <nl> + <nl> + / / Status counters <nl> + struct Counters { <nl> + CounterCollection cc ; <nl> + Counter loadedRangeBytes , loadedLogBytes , sentBytes ; <nl> + Counter sampledRangeBytes , sampledLogBytes ; <nl> + <nl> + Counters ( LoaderBatchData * self , UID loaderInterfID , int batchIndex ) <nl> + : cc ( " LoaderBatch " , loaderInterfID . toString ( ) + " : " + std : : to_string ( batchIndex ) ) , <nl> + loadedRangeBytes ( " LoadedRangeBytes " , cc ) , loadedLogBytes ( " LoadedLogBytes " , cc ) , sentBytes ( " SentBytes " , cc ) , <nl> + sampledRangeBytes ( " SampledRangeBytes " , cc ) , sampledLogBytes ( " SampledLogBytes " , cc ) { } <nl> + } counters ; <nl> + <nl> + explicit LoaderBatchData ( UID nodeID , int batchIndex ) : counters ( this , nodeID , batchIndex ) { <nl> + pollMetrics = <nl> + traceCounters ( " FastRestoreLoaderMetrics " , nodeID , SERVER_KNOBS - > FASTRESTORE_ROLE_LOGGING_DELAY , <nl> + & counters . cc , nodeID . toString ( ) + " / RestoreLoaderMetrics / " + std : : to_string ( batchIndex ) ) ; <nl> + TraceEvent ( " FastRestoreLoaderMetricsCreated " ) . detail ( " Node " , nodeID ) ; <nl> + } <nl> + <nl> + void reset ( ) { <nl> + processedFileParams . clear ( ) ; <nl> + kvOpsPerLP . clear ( ) ; <nl> + sampleMutations . clear ( ) ; <nl> + numSampledMutations = 0 ; <nl> + rangeToApplier . clear ( ) ; <nl> + } <nl> + } ; <nl> + <nl> + using LoaderCounters = LoaderBatchData : : Counters ; <nl> + <nl> + struct LoaderBatchStatus : public ReferenceCounted < LoaderBatchStatus > { <nl> + Optional < Future < Void > > sendAllRanges ; <nl> + Optional < Future < Void > > sendAllLogs ; <nl> + <nl> + void addref ( ) { return ReferenceCounted < LoaderBatchStatus > : : addref ( ) ; } <nl> + void delref ( ) { return ReferenceCounted < LoaderBatchStatus > : : delref ( ) ; } <nl> + <nl> + std : : string toString ( ) { <nl> + std : : stringstream ss ; <nl> + ss < < " sendAllRanges : " <nl> + < < ( ! sendAllRanges . present ( ) ? " invalid " : ( sendAllRanges . get ( ) . isReady ( ) ? " ready " : " notReady " ) ) <nl> + < < " sendAllLogs : " <nl> + < < ( ! sendAllLogs . present ( ) ? " invalid " : ( sendAllLogs . get ( ) . isReady ( ) ? " ready " : " notReady " ) ) ; <nl> + return ss . str ( ) ; <nl> + } <nl> + } ; <nl> + <nl> + struct RestoreLoaderData : RestoreRoleData , public ReferenceCounted < RestoreLoaderData > { <nl> + / / buffered data per version batch <nl> + std : : map < int , Reference < LoaderBatchData > > batch ; <nl> + std : : map < int , Reference < LoaderBatchStatus > > status ; <nl> + <nl> Reference < IBackupContainer > bc ; / / Backup container is used to read backup files <nl> Key bcUrl ; / / The url used to get the bc <nl> <nl> struct RestoreLoaderData : RestoreRoleData , public ReferenceCounted < RestoreLoade <nl> return ss . str ( ) ; <nl> } <nl> <nl> - void resetPerVersionBatch ( ) { <nl> - TraceEvent ( " FastRestore " ) . detail ( " ResetPerVersionBatchOnLoader " , nodeID ) ; <nl> - rangeToApplier . clear ( ) ; <nl> - keyOpsCount . clear ( ) ; <nl> - numSampledMutations = 0 ; <nl> - processedFileParams . clear ( ) ; <nl> - kvOpsPerLP . clear ( ) ; <nl> - sampleMutations . clear ( ) ; <nl> + void initVersionBatch ( int batchIndex ) { <nl> + TraceEvent ( " FastRestore " ) . detail ( " InitVersionBatchOnLoader " , nodeID ) ; <nl> + batch [ batchIndex ] = Reference < LoaderBatchData > ( new LoaderBatchData ( nodeID , batchIndex ) ) ; <nl> + status [ batchIndex ] = Reference < LoaderBatchStatus > ( new LoaderBatchStatus ( ) ) ; <nl> } <nl> <nl> - / / Only get the appliers that are responsible for a range <nl> - std : : vector < UID > getWorkingApplierIDs ( ) { <nl> - std : : vector < UID > applierIDs ; <nl> - for ( auto & applier : rangeToApplier ) { <nl> - applierIDs . push_back ( applier . second ) ; <nl> - } <nl> - <nl> - ASSERT ( ! applierIDs . empty ( ) ) ; <nl> - return applierIDs ; <nl> + void resetPerRestoreRequest ( ) { <nl> + batch . clear ( ) ; <nl> + status . clear ( ) ; <nl> } <nl> <nl> void initBackupContainer ( Key url ) { <nl> mmm a / fdbserver / RestoreMaster . actor . cpp <nl> ppp b / fdbserver / RestoreMaster . actor . cpp <nl> ACTOR static Future < Void > collectBackupFiles ( Reference < IBackupContainer > bc , std <nl> <nl> ACTOR static Future < Version > processRestoreRequest ( Reference < RestoreMasterData > self , Database cx , RestoreRequest request ) ; <nl> ACTOR static Future < Void > startProcessRestoreRequests ( Reference < RestoreMasterData > self , Database cx ) ; <nl> - ACTOR static Future < Void > distributeWorkloadPerVersionBatch ( Reference < RestoreMasterData > self , Database cx , <nl> - RestoreRequest request , VersionBatch versionBatch ) ; <nl> + ACTOR static Future < Void > distributeWorkloadPerVersionBatch ( Reference < RestoreMasterData > self , int batchIndex , <nl> + Database cx , RestoreRequest request , <nl> + VersionBatch versionBatch ) ; <nl> <nl> ACTOR static Future < Void > recruitRestoreRoles ( Reference < RestoreWorkerData > masterWorker , <nl> Reference < RestoreMasterData > masterData ) ; <nl> ACTOR static Future < Void > distributeRestoreSysInfo ( Reference < RestoreWorkerData > <nl> Reference < RestoreMasterData > masterData ) ; <nl> <nl> ACTOR static Future < Standalone < VectorRef < RestoreRequest > > > collectRestoreRequests ( Database cx ) ; <nl> - ACTOR static Future < Void > initializeVersionBatch ( Reference < RestoreMasterData > self ) ; <nl> - ACTOR static Future < Void > notifyApplierToApplyMutations ( Reference < RestoreMasterData > self ) ; <nl> - ACTOR static Future < Void > notifyRestoreCompleted ( Reference < RestoreMasterData > self , Database cx ) ; <nl> - <nl> - void splitKeyRangeForAppliers ( Reference < RestoreMasterData > self ) ; <nl> + ACTOR static Future < Void > initializeVersionBatch ( std : : map < UID , RestoreApplierInterface > appliersInterf , <nl> + std : : map < UID , RestoreLoaderInterface > loadersInterf , int batchIndex ) ; <nl> + ACTOR static Future < Void > notifyApplierToApplyMutations ( Reference < MasterBatchData > batchData , <nl> + Reference < MasterBatchStatus > batchStatus , <nl> + std : : map < UID , RestoreApplierInterface > appliersInterf , <nl> + int batchIndex , NotifiedVersion * finishedBatch ) ; <nl> + ACTOR static Future < Void > notifyRestoreCompleted ( Reference < RestoreMasterData > self , bool terminate ) ; <nl> + ACTOR static Future < Void > signalRestoreCompleted ( Reference < RestoreMasterData > self , Database cx ) ; <nl> + <nl> + void splitKeyRangeForAppliers ( Reference < MasterBatchData > batchData , <nl> + std : : map < UID , RestoreApplierInterface > appliersInterf , int batchIndex ) ; <nl> <nl> ACTOR Future < Void > startRestoreMaster ( Reference < RestoreWorkerData > masterWorker , Database cx ) { <nl> state Reference < RestoreMasterData > self = Reference < RestoreMasterData > ( new RestoreMasterData ( ) ) ; <nl> ACTOR Future < Void > recruitRestoreRoles ( Reference < RestoreWorkerData > masterWorker <nl> state int nodeIndex = 0 ; <nl> state RestoreRole role = RestoreRole : : Invalid ; <nl> <nl> - TraceEvent ( " FastRestore " ) <nl> + TraceEvent ( " FastRestoreMaster " , masterData - > id ( ) ) <nl> . detail ( " RecruitRestoreRoles " , masterWorker - > workerInterfaces . size ( ) ) <nl> - . detail ( " NumLoaders " , opConfig . num_loaders ) <nl> - . detail ( " NumAppliers " , opConfig . num_appliers ) ; <nl> + . detail ( " NumLoaders " , SERVER_KNOBS - > FASTRESTORE_NUM_LOADERS ) <nl> + . detail ( " NumAppliers " , SERVER_KNOBS - > FASTRESTORE_NUM_APPLIERS ) ; <nl> ASSERT ( masterData - > loadersInterf . empty ( ) & & masterData - > appliersInterf . empty ( ) ) ; <nl> <nl> ASSERT ( masterData . isValid ( ) ) ; <nl> - ASSERT ( opConfig . num_loaders > 0 & & opConfig . num_appliers > 0 ) ; <nl> + ASSERT ( SERVER_KNOBS - > FASTRESTORE_NUM_LOADERS > 0 & & SERVER_KNOBS - > FASTRESTORE_NUM_APPLIERS > 0 ) ; <nl> / / We assign 1 role per worker for now <nl> - ASSERT ( opConfig . num_loaders + opConfig . num_appliers < = masterWorker - > workerInterfaces . size ( ) ) ; <nl> + ASSERT ( SERVER_KNOBS - > FASTRESTORE_NUM_LOADERS + SERVER_KNOBS - > FASTRESTORE_NUM_APPLIERS < = <nl> + masterWorker - > workerInterfaces . size ( ) ) ; <nl> <nl> / / Assign a role to each worker <nl> std : : vector < std : : pair < UID , RestoreRecruitRoleRequest > > requests ; <nl> for ( auto & workerInterf : masterWorker - > workerInterfaces ) { <nl> - if ( nodeIndex > = 0 & & nodeIndex < opConfig . num_appliers ) { <nl> + if ( nodeIndex > = 0 & & nodeIndex < SERVER_KNOBS - > FASTRESTORE_NUM_APPLIERS ) { <nl> / / [ 0 , numApplier ) are appliers <nl> role = RestoreRole : : Applier ; <nl> - } else if ( nodeIndex > = opConfig . num_appliers & & nodeIndex < opConfig . num_loaders + opConfig . num_appliers ) { <nl> + } else if ( nodeIndex > = SERVER_KNOBS - > FASTRESTORE_NUM_APPLIERS & & <nl> + nodeIndex < SERVER_KNOBS - > FASTRESTORE_NUM_LOADERS + SERVER_KNOBS - > FASTRESTORE_NUM_APPLIERS ) { <nl> / / [ numApplier , numApplier + numLoader ) are loaders <nl> role = RestoreRole : : Loader ; <nl> } else { <nl> break ; <nl> } <nl> <nl> - TraceEvent ( " FastRestore " ) <nl> - . detail ( " Role " , getRoleStr ( role ) ) <nl> - . detail ( " NodeIndex " , nodeIndex ) <nl> - . detail ( " WorkerNode " , workerInterf . first ) ; <nl> + TraceEvent ( " FastRestoreMaster " , masterData - > id ( ) ) . detail ( " WorkerNode " , workerInterf . first ) ; <nl> requests . emplace_back ( workerInterf . first , RestoreRecruitRoleRequest ( role , nodeIndex ) ) ; <nl> nodeIndex + + ; <nl> } <nl> ACTOR Future < Void > recruitRestoreRoles ( Reference < RestoreWorkerData > masterWorker <nl> ASSERT_WE_THINK ( reply . loader . present ( ) ) ; <nl> masterData - > loadersInterf [ reply . loader . get ( ) . id ( ) ] = reply . loader . get ( ) ; <nl> } else { <nl> - TraceEvent ( SevError , " FastRestore " ) . detail ( " RecruitRestoreRoles_InvalidRole " , reply . role ) ; <nl> + TraceEvent ( SevError , " FastRestoreMaster " ) . detail ( " RecruitRestoreRolesInvalidRole " , reply . role ) ; <nl> } <nl> } <nl> - TraceEvent ( " FastRestore " ) . detail ( " RecruitRestoreRolesDone " , masterWorker - > workerInterfaces . size ( ) ) ; <nl> + TraceEvent ( " FastRestoreRecruitRestoreRolesDone " , masterData - > id ( ) ) <nl> + . detail ( " Workers " , masterWorker - > workerInterfaces . size ( ) ) <nl> + . detail ( " RecruitedRoles " , replies . size ( ) ) ; <nl> <nl> return Void ( ) ; <nl> } <nl> ACTOR Future < Void > distributeRestoreSysInfo ( Reference < RestoreWorkerData > masterW <nl> RestoreSysInfo sysInfo ( masterData - > appliersInterf ) ; <nl> std : : vector < std : : pair < UID , RestoreSysInfoRequest > > requests ; <nl> for ( auto & loader : masterData - > loadersInterf ) { <nl> - requests . push_back ( std : : make_pair ( loader . first , RestoreSysInfoRequest ( sysInfo ) ) ) ; <nl> + requests . emplace_back ( loader . first , RestoreSysInfoRequest ( sysInfo ) ) ; <nl> } <nl> <nl> - TraceEvent ( " FastRestore " ) . detail ( " DistributeRestoreSysInfoToLoaders " , masterData - > loadersInterf . size ( ) ) ; <nl> + TraceEvent ( " FastRestoreDistributeRestoreSysInfoToLoaders " , masterData - > id ( ) ) <nl> + . detail ( " Loaders " , masterData - > loadersInterf . size ( ) ) ; <nl> wait ( sendBatchRequests ( & RestoreLoaderInterface : : updateRestoreSysInfo , masterData - > loadersInterf , requests ) ) ; <nl> + TraceEvent ( " FastRestoreDistributeRestoreSysInfoToLoadersDone " , masterData - > id ( ) ) <nl> + . detail ( " Loaders " , masterData - > loadersInterf . size ( ) ) ; <nl> <nl> return Void ( ) ; <nl> } <nl> ACTOR Future < Void > startProcessRestoreRequests ( Reference < RestoreMasterData > self <nl> state int numTries = 0 ; <nl> state int restoreIndex = 0 ; <nl> <nl> - TraceEvent ( " FastRestore " ) . detail ( " RestoreMaster " , " WaitOnRestoreRequests " ) ; <nl> + TraceEvent ( " FastRestoreMasterWaitOnRestoreRequests " , self - > id ( ) ) ; <nl> <nl> / / lock DB for restore <nl> numTries = 0 ; <nl> ACTOR Future < Void > startProcessRestoreRequests ( Reference < RestoreMasterData > self <nl> tr - > setOption ( FDBTransactionOptions : : ACCESS_SYSTEM_KEYS ) ; <nl> tr - > setOption ( FDBTransactionOptions : : LOCK_AWARE ) ; <nl> wait ( checkDatabaseLock ( tr , randomUID ) ) ; <nl> - TraceEvent ( " FastRestore " ) . detail ( " DBIsLocked " , randomUID ) ; <nl> + TraceEvent ( " FastRestoreMasterProcessRestoreRequests " , self - > id ( ) ) . detail ( " DBIsLocked " , randomUID ) ; <nl> break ; <nl> } catch ( Error & e ) { <nl> - TraceEvent ( " FastRestore " ) . detail ( " CheckLockError " , e . what ( ) ) ; <nl> + TraceEvent ( " FastRestoreMasterProcessRestoreRequests " , self - > id ( ) ) . detail ( " CheckLockError " , e . what ( ) ) ; <nl> TraceEvent ( numTries > 50 ? SevError : SevWarnAlways , " FastRestoreMayFail " ) <nl> . detail ( " Reason " , " DB is not properly locked " ) <nl> . detail ( " ExpectedLockID " , randomUID ) ; <nl> ACTOR Future < Void > startProcessRestoreRequests ( Reference < RestoreMasterData > self <nl> try { <nl> for ( restoreIndex = 0 ; restoreIndex < restoreRequests . size ( ) ; restoreIndex + + ) { <nl> RestoreRequest & request = restoreRequests [ restoreIndex ] ; <nl> - TraceEvent ( " FastRestore " ) . detail ( " RestoreRequestInfo " , request . toString ( ) ) ; <nl> + TraceEvent ( " FastRestoreMasterProcessRestoreRequests " , self - > id ( ) ) <nl> + . detail ( " RestoreRequestInfo " , request . toString ( ) ) ; <nl> + / / TODO : Initialize MasterData and all loaders and appliers ' data for each restore request ! <nl> + self - > resetPerRestoreRequest ( ) ; <nl> wait ( success ( processRestoreRequest ( self , cx , request ) ) ) ; <nl> + wait ( notifyRestoreCompleted ( self , false ) ) ; <nl> } <nl> } catch ( Error & e ) { <nl> if ( restoreIndex < restoreRequests . size ( ) ) { <nl> - TraceEvent ( SevError , " FastRestoreFailed " ) <nl> + TraceEvent ( SevError , " FastRestoreMasterProcessRestoreRequestsFailed " , self - > id ( ) ) <nl> . detail ( " RestoreRequest " , restoreRequests [ restoreIndex ] . toString ( ) ) ; <nl> } else { <nl> - TraceEvent ( SevError , " FastRestoreFailed " ) <nl> + TraceEvent ( SevError , " FastRestoreMasterProcessRestoreRequestsFailed " , self - > id ( ) ) <nl> . detail ( " RestoreRequests " , restoreRequests . size ( ) ) <nl> . detail ( " RestoreIndex " , restoreIndex ) ; <nl> } <nl> } <nl> <nl> / / Step : Notify all restore requests have been handled by cleaning up the restore keys <nl> - wait ( notifyRestoreCompleted ( self , cx ) ) ; <nl> + wait ( signalRestoreCompleted ( self , cx ) ) ; <nl> <nl> try { <nl> wait ( unlockDatabase ( cx , randomUID ) ) ; <nl> } catch ( Error & e ) { <nl> - TraceEvent ( SevError , " UnlockDBFailed " ) . detail ( " UID " , randomUID . toString ( ) ) ; <nl> + TraceEvent ( SevError , " FastRestoreMasterUnlockDBFailed " , self - > id ( ) ) . detail ( " UID " , randomUID . toString ( ) ) ; <nl> ASSERT_WE_THINK ( false ) ; / / This unlockDatabase should always succeed , we think . <nl> } <nl> <nl> - <nl> - TraceEvent ( " FastRestore " ) . detail ( " RestoreMasterComplete " , self - > id ( ) ) ; <nl> + TraceEvent ( " FastRestoreMasterRestoreCompleted " , self - > id ( ) ) ; <nl> <nl> return Void ( ) ; <nl> } <nl> <nl> + ACTOR static Future < Void > monitorFinishedVersion ( Reference < RestoreMasterData > self , RestoreRequest request ) { <nl> + loop { <nl> + TraceEvent ( " FastRestoreMonitorFinishedVersion " , self - > id ( ) ) <nl> + . detail ( " RestoreRequest " , request . toString ( ) ) <nl> + . detail ( " BatchIndex " , self - > finishedBatch . get ( ) ) ; <nl> + wait ( delay ( SERVER_KNOBS - > FASTRESTORE_VB_MONITOR_DELAY ) ) ; <nl> + } <nl> + } <nl> + <nl> ACTOR static Future < Version > processRestoreRequest ( Reference < RestoreMasterData > self , Database cx , <nl> RestoreRequest request ) { <nl> state std : : vector < RestoreFileFR > rangeFiles ; <nl> state std : : vector < RestoreFileFR > logFiles ; <nl> state std : : vector < RestoreFileFR > allFiles ; <nl> - state std : : map < Version , VersionBatch > : : iterator versionBatch = self - > versionBatches . begin ( ) ; <nl> + state ActorCollection actors ( false ) ; <nl> <nl> self - > initBackupContainer ( request . url ) ; <nl> <nl> ACTOR static Future < Version > processRestoreRequest ( Reference < RestoreMasterData > <nl> <nl> std : : sort ( rangeFiles . begin ( ) , rangeFiles . end ( ) ) ; <nl> std : : sort ( logFiles . begin ( ) , logFiles . end ( ) , [ ] ( RestoreFileFR const & f1 , RestoreFileFR const & f2 ) - > bool { <nl> - return std : : tie ( f1 . endVersion , f1 . beginVersion , f1 . fileIndex ) < <nl> - std : : tie ( f2 . endVersion , f2 . beginVersion , f2 . fileIndex ) ; <nl> + return std : : tie ( f1 . endVersion , f1 . beginVersion , f1 . fileIndex , f1 . fileName ) < <nl> + std : : tie ( f2 . endVersion , f2 . beginVersion , f2 . fileIndex , f2 . fileName ) ; <nl> } ) ; <nl> <nl> self - > buildVersionBatches ( rangeFiles , logFiles , & self - > versionBatches ) ; / / Divide files into version batches <nl> self - > dumpVersionBatches ( self - > versionBatches ) ; <nl> <nl> - ASSERT ( self - > batchIndex = = 1 ) ; / / versionBatchIndex starts at 1 because NotifiedVersion starts at 0 <nl> - for ( versionBatch = self - > versionBatches . begin ( ) ; versionBatch ! = self - > versionBatches . end ( ) ; versionBatch + + ) { <nl> - wait ( initializeVersionBatch ( self ) ) ; <nl> - wait ( distributeWorkloadPerVersionBatch ( self , cx , request , versionBatch - > second ) ) ; <nl> - self - > batchIndex + + ; <nl> + state std : : vector < Future < Void > > fBatches ; <nl> + state std : : vector < VersionBatch > versionBatches ; / / To randomize invoking order of version batchs <nl> + for ( auto & vb : self - > versionBatches ) { <nl> + versionBatches . push_back ( vb . second ) ; <nl> } <nl> <nl> + if ( g_network - > isSimulated ( ) & & deterministicRandom ( ) - > random01 ( ) < 0 . 5 ) { <nl> + / / Randomize invoking order of version batches <nl> + int permTimes = deterministicRandom ( ) - > randomInt ( 0 , 100 ) ; <nl> + while ( permTimes - - > 0 ) { <nl> + std : : next_permutation ( versionBatches . begin ( ) , versionBatches . end ( ) ) ; <nl> + } <nl> + } <nl> + <nl> + actors . add ( monitorFinishedVersion ( self , request ) ) ; <nl> + state std : : vector < VersionBatch > : : iterator versionBatch = versionBatches . begin ( ) ; <nl> + for ( ; versionBatch ! = versionBatches . end ( ) ; versionBatch + + ) { <nl> + while ( self - > runningVersionBatches . get ( ) > = SERVER_KNOBS - > FASTRESTORE_VB_PARALLELISM ) { <nl> + / / Control how many batches can be processed in parallel . Avoid dead lock due to OOM on loaders <nl> + TraceEvent ( " FastRestoreMasterDispatchVersionBatches " ) <nl> + . detail ( " WaitOnRunningVersionBatches " , self - > runningVersionBatches . get ( ) ) ; <nl> + wait ( self - > runningVersionBatches . onChange ( ) ) ; <nl> + } <nl> + int batchIndex = versionBatch - > batchIndex ; <nl> + TraceEvent ( " FastRestoreMasterDispatchVersionBatches " ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " BatchSize " , versionBatch - > size ) <nl> + . detail ( " RunningVersionBatches " , self - > runningVersionBatches . get ( ) ) <nl> + . detail ( " Start " , now ( ) ) ; <nl> + self - > batch [ batchIndex ] = Reference < MasterBatchData > ( new MasterBatchData ( ) ) ; <nl> + self - > batchStatus [ batchIndex ] = Reference < MasterBatchStatus > ( new MasterBatchStatus ( ) ) ; <nl> + fBatches . push_back ( distributeWorkloadPerVersionBatch ( self , batchIndex , cx , request , * versionBatch ) ) ; <nl> + / / Wait a bit to give the current version batch a head start from the next version batch <nl> + wait ( delay ( SERVER_KNOBS - > FASTRESTORE_VB_LAUNCH_DELAY ) ) ; <nl> + } <nl> + <nl> + wait ( waitForAll ( fBatches ) ) ; <nl> + <nl> TraceEvent ( " FastRestore " ) . detail ( " RestoreToVersion " , request . targetVersion ) ; <nl> return request . targetVersion ; <nl> } <nl> <nl> - ACTOR static Future < Void > loadFilesOnLoaders ( Reference < RestoreMasterData > self , Database cx , RestoreRequest request , <nl> - VersionBatch versionBatch , bool isRangeFile ) { <nl> - TraceEvent ( " FastRestore " ) <nl> - . detail ( " FileTypeLoadedInVersionBatch " , isRangeFile ) <nl> - . detail ( " BeginVersion " , versionBatch . beginVersion ) <nl> - . detail ( " EndVersion " , versionBatch . endVersion ) ; <nl> - <nl> - std : : vector < RestoreFileFR > * files = nullptr ; <nl> + ACTOR static Future < Void > loadFilesOnLoaders ( Reference < MasterBatchData > batchData , <nl> + Reference < MasterBatchStatus > batchStatus , <nl> + std : : map < UID , RestoreLoaderInterface > loadersInterf , int batchIndex , <nl> + Database cx , RestoreRequest request , VersionBatch versionBatch , <nl> + bool isRangeFile ) { <nl> + / / set is internally sorted <nl> + std : : set < RestoreFileFR > * files = nullptr ; <nl> if ( isRangeFile ) { <nl> files = & versionBatch . rangeFiles ; <nl> } else { <nl> files = & versionBatch . logFiles ; <nl> } <nl> <nl> - / / sort files in increasing order of beginVersion <nl> - std : : sort ( files - > begin ( ) , files - > end ( ) ) ; <nl> + TraceEvent ( " FastRestoreMasterPhaseLoadFilesStart " ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " FileTypeLoadedInVersionBatch " , isRangeFile ) <nl> + . detail ( " BeginVersion " , versionBatch . beginVersion ) <nl> + . detail ( " EndVersion " , versionBatch . endVersion ) <nl> + . detail ( " Files " , ( files ! = nullptr ? files - > size ( ) : - 1 ) ) ; <nl> <nl> std : : vector < std : : pair < UID , RestoreLoadFileRequest > > requests ; <nl> - std : : map < UID , RestoreLoaderInterface > : : iterator loader = self - > loadersInterf . begin ( ) ; <nl> + std : : map < UID , RestoreLoaderInterface > : : iterator loader = loadersInterf . begin ( ) ; <nl> + state std : : vector < RestoreAsset > assets ; / / all assets loaded , used for sanity check restore progress <nl> <nl> + / / Balance workload on loaders for parsing range and log files across version batches <nl> + int random = deterministicRandom ( ) - > randomInt ( 0 , loadersInterf . size ( ) ) ; <nl> + while ( random - - > 0 ) { <nl> + loader + + ; <nl> + } <nl> + <nl> + int paramIdx = 0 ; <nl> for ( auto & file : * files ) { <nl> - / / NOTE : Cannot skip empty files because empty files , e . g . , log file , still need to generate dummy mutation to <nl> - / / drive applier ' s NotifiedVersion . <nl> - if ( loader = = self - > loadersInterf . end ( ) ) { <nl> - loader = self - > loadersInterf . begin ( ) ; <nl> + if ( loader = = loadersInterf . end ( ) ) { <nl> + loader = loadersInterf . begin ( ) ; <nl> } <nl> / / Prepare loading <nl> LoadingParam param ; <nl> ACTOR static Future < Void > loadFilesOnLoaders ( Reference < RestoreMasterData > self , <nl> param . asset . beginVersion = versionBatch . beginVersion ; <nl> param . asset . endVersion = versionBatch . endVersion ; <nl> <nl> - TraceEvent ( " FastRestore " ) . detail ( " LoadParam " , param . toString ( ) ) . detail ( " LoaderID " , loader - > first . toString ( ) ) ; <nl> + TraceEvent ( " FastRestoreMasterPhaseLoadFiles " ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " LoadParamIndex " , paramIdx ) <nl> + . detail ( " LoaderID " , loader - > first . toString ( ) ) <nl> + . detail ( " LoadParam " , param . toString ( ) ) ; <nl> ASSERT_WE_THINK ( param . asset . len > 0 ) ; <nl> ASSERT_WE_THINK ( param . asset . offset > = 0 ) ; <nl> ASSERT_WE_THINK ( param . asset . offset < = file . fileSize ) ; <nl> ASSERT_WE_THINK ( param . asset . beginVersion < = param . asset . endVersion ) ; <nl> <nl> - requests . emplace_back ( loader - > first , RestoreLoadFileRequest ( param ) ) ; <nl> - loader + + ; <nl> + requests . emplace_back ( loader - > first , RestoreLoadFileRequest ( batchIndex , param ) ) ; <nl> + / / Restore asset should only be loaded exactly once . <nl> + if ( batchStatus - > raStatus . find ( param . asset ) ! = batchStatus - > raStatus . end ( ) ) { <nl> + TraceEvent ( SevError , " FastRestoreMasterPhaseLoadFiles " ) <nl> + . detail ( " LoadingParam " , param . toString ( ) ) <nl> + . detail ( " RestoreAssetAlreadyProcessed " , batchStatus - > raStatus [ param . asset ] ) ; <nl> + } <nl> + batchStatus - > raStatus [ param . asset ] = RestoreAssetStatus : : Loading ; <nl> + assets . push_back ( param . asset ) ; <nl> + + + loader ; <nl> + + + paramIdx ; <nl> } <nl> + TraceEvent ( files - > size ( ) ! = paramIdx ? SevError : SevInfo , " FastRestoreMasterPhaseLoadFiles " ) <nl> + . detail ( " Files " , files - > size ( ) ) <nl> + . detail ( " LoadParams " , paramIdx ) ; <nl> <nl> state std : : vector < RestoreLoadFileReply > replies ; <nl> / / Wait on the batch of load files or log files <nl> - wait ( getBatchReplies ( & RestoreLoaderInterface : : loadFile , self - > loadersInterf , requests , & replies ) ) ; <nl> - TraceEvent ( " FastRestore " ) . detail ( " VersionBatch " , self - > batchIndex ) . detail ( " SamplingReplies " , replies . size ( ) ) ; <nl> + wait ( getBatchReplies ( & RestoreLoaderInterface : : loadFile , loadersInterf , requests , & replies , <nl> + TaskPriority : : RestoreLoaderLoadFiles ) ) ; <nl> + <nl> + TraceEvent ( " FastRestoreMasterPhaseLoadFilesReply " ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " SamplingReplies " , replies . size ( ) ) ; <nl> for ( auto & reply : replies ) { <nl> - TraceEvent ( " FastRestore " ) . detail ( " VersionBatch " , self - > batchIndex ) . detail ( " SamplingReplies " , reply . toString ( ) ) ; <nl> + / / Update and sanity check restore asset ' s status <nl> + RestoreAssetStatus status = batchStatus - > raStatus [ reply . param . asset ] ; <nl> + if ( status = = RestoreAssetStatus : : Loading & & ! reply . isDuplicated ) { <nl> + batchStatus - > raStatus [ reply . param . asset ] = RestoreAssetStatus : : Loaded ; <nl> + } else if ( status = = RestoreAssetStatus : : Loading & & reply . isDuplicated ) { <nl> + / / Duplicate request wait on the restore asset to be processed before it replies <nl> + batchStatus - > raStatus [ reply . param . asset ] = RestoreAssetStatus : : Loaded ; <nl> + TraceEvent ( SevWarn , " FastRestoreMasterPhaseLoadFilesReply " ) <nl> + . detail ( " RestoreAsset " , reply . param . asset . toString ( ) ) <nl> + . detail ( " DuplicateRequestArriveEarly " , " RestoreAsset should have been processed " ) ; <nl> + } else if ( status = = RestoreAssetStatus : : Loaded & & reply . isDuplicated ) { <nl> + TraceEvent ( SevDebug , " FastRestoreMasterPhaseLoadFilesReply " ) <nl> + . detail ( " RestoreAsset " , reply . param . asset . toString ( ) ) <nl> + . detail ( " RequestIgnored " , " Loading request was sent more than once " ) ; <nl> + } else { <nl> + TraceEvent ( SevError , " FastRestoreMasterPhaseLoadFilesReply " ) <nl> + . detail ( " RestoreAsset " , reply . param . asset . toString ( ) ) <nl> + . detail ( " UnexpectedReply " , reply . toString ( ) ) ; <nl> + } <nl> + / / Update sampled data <nl> for ( int i = 0 ; i < reply . samples . size ( ) ; + + i ) { <nl> MutationRef mutation = reply . samples [ i ] ; <nl> - self - > samples . addMetric ( mutation . param1 , mutation . totalSize ( ) ) ; <nl> - self - > samplesSize + = mutation . totalSize ( ) ; <nl> + batchData - > samples . addMetric ( mutation . param1 , mutation . weightedTotalSize ( ) ) ; <nl> + batchData - > samplesSize + = mutation . weightedTotalSize ( ) ; <nl> } <nl> } <nl> <nl> + / / Sanity check : all restore assets status should be Loaded <nl> + for ( auto & asset : assets ) { <nl> + if ( batchStatus - > raStatus [ asset ] ! = RestoreAssetStatus : : Loaded ) { <nl> + TraceEvent ( SevError , " FastRestoreMasterPhaseLoadFilesReply " ) <nl> + . detail ( " RestoreAsset " , asset . toString ( ) ) <nl> + . detail ( " UnexpectedStatus " , batchStatus - > raStatus [ asset ] ) ; <nl> + } <nl> + } <nl> + <nl> + TraceEvent ( " FastRestoreMasterPhaseLoadFilesDone " ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " FileTypeLoadedInVersionBatch " , isRangeFile ) <nl> + . detail ( " BeginVersion " , versionBatch . beginVersion ) <nl> + . detail ( " EndVersion " , versionBatch . endVersion ) ; <nl> return Void ( ) ; <nl> } <nl> <nl> / / Ask loaders to send its buffered mutations to appliers <nl> - ACTOR static Future < Void > sendMutationsFromLoaders ( Reference < RestoreMasterData > self , bool useRangeFile ) { <nl> - TraceEvent ( " FastRestore " ) <nl> - . detail ( " SendMutationsFromLoaders " , self - > batchIndex ) <nl> - . detail ( " UseRangeFiles " , useRangeFile ) ; <nl> + ACTOR static Future < Void > sendMutationsFromLoaders ( Reference < MasterBatchData > batchData , <nl> + Reference < MasterBatchStatus > batchStatus , <nl> + std : : map < UID , RestoreLoaderInterface > loadersInterf , int batchIndex , <nl> + bool useRangeFile ) { <nl> + TraceEvent ( " FastRestoreMasterPhaseSendMutationsFromLoadersStart " ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " UseRangeFiles " , useRangeFile ) <nl> + . detail ( " Loaders " , loadersInterf . size ( ) ) ; <nl> <nl> std : : vector < std : : pair < UID , RestoreSendMutationsToAppliersRequest > > requests ; <nl> - for ( auto & loader : self - > loadersInterf ) { <nl> - requests . emplace_back ( loader . first , RestoreSendMutationsToAppliersRequest ( self - > rangeToApplier , useRangeFile ) ) ; <nl> + for ( auto & loader : loadersInterf ) { <nl> + ASSERT ( batchStatus - > loadStatus . find ( loader . first ) = = batchStatus - > loadStatus . end ( ) | | <nl> + batchStatus - > loadStatus [ loader . first ] = = RestoreSendStatus : : SendedLogs ) ; <nl> + requests . emplace_back ( <nl> + loader . first , RestoreSendMutationsToAppliersRequest ( batchIndex , batchData - > rangeToApplier , useRangeFile ) ) ; <nl> + batchStatus - > loadStatus [ loader . first ] = <nl> + useRangeFile ? RestoreSendStatus : : SendingRanges : RestoreSendStatus : : SendingLogs ; <nl> + } <nl> + state std : : vector < RestoreCommonReply > replies ; <nl> + wait ( getBatchReplies ( & RestoreLoaderInterface : : sendMutations , loadersInterf , requests , & replies , <nl> + TaskPriority : : RestoreLoaderSendMutations ) ) ; <nl> + <nl> + / / Update status and sanity check <nl> + for ( auto & reply : replies ) { <nl> + RestoreSendStatus status = batchStatus - > loadStatus [ reply . id ] ; <nl> + if ( ( status = = RestoreSendStatus : : SendingRanges | | status = = RestoreSendStatus : : SendingLogs ) ) { <nl> + batchStatus - > loadStatus [ reply . id ] = ( status = = RestoreSendStatus : : SendingRanges ) <nl> + ? RestoreSendStatus : : SendedRanges <nl> + : RestoreSendStatus : : SendedLogs ; <nl> + if ( reply . isDuplicated ) { <nl> + TraceEvent ( SevWarn , " FastRestoreMasterPhaseSendMutationsFromLoaders " ) <nl> + . detail ( " Loader " , reply . id ) <nl> + . detail ( " DuplicateRequestAcked " , " Request should have been processed " ) ; <nl> + } <nl> + } else if ( ( status = = RestoreSendStatus : : SendedRanges | | status = = RestoreSendStatus : : SendedLogs ) & & <nl> + reply . isDuplicated ) { <nl> + TraceEvent ( SevDebug , " FastRestoreMasterPhaseSendMutationsFromLoaders " ) <nl> + . detail ( " Loader " , reply . id ) <nl> + . detail ( " RequestIgnored " , " Send request was sent more than once " ) ; <nl> + } else { <nl> + TraceEvent ( SevError , " FastRestoreMasterPhaseSendMutationsFromLoaders " ) <nl> + . detail ( " Loader " , reply . id ) <nl> + . detail ( " UnexpectedReply " , reply . toString ( ) ) ; <nl> + } <nl> + } <nl> + / / Sanity check all loaders have sent requests <nl> + for ( auto & loader : loadersInterf ) { <nl> + if ( ( useRangeFile & & batchStatus - > loadStatus [ loader . first ] ! = RestoreSendStatus : : SendedRanges ) | | <nl> + ( ! useRangeFile & & batchStatus - > loadStatus [ loader . first ] ! = RestoreSendStatus : : SendedLogs ) ) { <nl> + TraceEvent ( SevError , " FastRestoreMasterPhaseSendMutationsFromLoaders " ) <nl> + . detail ( " Loader " , loader . first ) <nl> + . detail ( " UseRangeFile " , useRangeFile ) <nl> + . detail ( " SendStatus " , batchStatus - > loadStatus [ loader . first ] ) ; <nl> + } <nl> } <nl> - wait ( sendBatchRequests ( & RestoreLoaderInterface : : sendMutations , self - > loadersInterf , requests ) ) ; <nl> + <nl> + TraceEvent ( " FastRestoreMasterPhaseSendMutationsFromLoadersDone " ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " UseRangeFiles " , useRangeFile ) <nl> + . detail ( " Loaders " , loadersInterf . size ( ) ) ; <nl> <nl> return Void ( ) ; <nl> } <nl> <nl> - ACTOR static Future < Void > distributeWorkloadPerVersionBatch ( Reference < RestoreMasterData > self , Database cx , <nl> - RestoreRequest request , VersionBatch versionBatch ) { <nl> + / / Process a version batch . Phases ( loading files , send mutations ) should execute in order <nl> + ACTOR static Future < Void > distributeWorkloadPerVersionBatch ( Reference < RestoreMasterData > self , int batchIndex , <nl> + Database cx , RestoreRequest request , <nl> + VersionBatch versionBatch ) { <nl> + state Reference < MasterBatchData > batchData = self - > batch [ batchIndex ] ; <nl> + state Reference < MasterBatchStatus > batchStatus = self - > batchStatus [ batchIndex ] ; <nl> + <nl> + self - > runningVersionBatches . set ( self - > runningVersionBatches . get ( ) + 1 ) ; <nl> + <nl> + wait ( initializeVersionBatch ( self - > appliersInterf , self - > loadersInterf , batchIndex ) ) ; <nl> + <nl> ASSERT ( ! versionBatch . isEmpty ( ) ) ; <nl> ASSERT ( self - > loadersInterf . size ( ) > 0 ) ; <nl> ASSERT ( self - > appliersInterf . size ( ) > 0 ) ; <nl> <nl> / / Parse log files and send mutations to appliers before we parse range files <nl> / / TODO : Allow loading both range and log files in parallel <nl> - wait ( loadFilesOnLoaders ( self , cx , request , versionBatch , false ) ) ; <nl> - wait ( loadFilesOnLoaders ( self , cx , request , versionBatch , true ) ) ; <nl> + ASSERT ( batchData - > samples . empty ( ) ) ; <nl> + ASSERT ( batchData - > samplesSize < 1 & & batchData - > samplesSize > - 1 ) ; / / samplesSize should be 0 <nl> + ASSERT ( batchStatus - > raStatus . empty ( ) ) ; <nl> + ASSERT ( batchStatus - > loadStatus . empty ( ) ) ; <nl> + ASSERT ( batchStatus - > applyStatus . empty ( ) ) ; <nl> + <nl> + wait ( loadFilesOnLoaders ( batchData , batchStatus , self - > loadersInterf , batchIndex , cx , request , versionBatch , false ) ) ; <nl> + wait ( loadFilesOnLoaders ( batchData , batchStatus , self - > loadersInterf , batchIndex , cx , request , versionBatch , true ) ) ; <nl> <nl> - splitKeyRangeForAppliers ( self ) ; <nl> + ASSERT ( batchData - > rangeToApplier . empty ( ) ) ; <nl> + splitKeyRangeForAppliers ( batchData , self - > appliersInterf , batchIndex ) ; <nl> <nl> / / Loaders should ensure log files ' mutations sent to appliers before range files ' mutations <nl> / / TODO : Let applier buffer mutations from log and range files differently so that loaders can send mutations in <nl> / / parallel <nl> - wait ( sendMutationsFromLoaders ( self , false ) ) ; <nl> - wait ( sendMutationsFromLoaders ( self , true ) ) ; <nl> + wait ( sendMutationsFromLoaders ( batchData , batchStatus , self - > loadersInterf , batchIndex , false ) ) ; <nl> + wait ( sendMutationsFromLoaders ( batchData , batchStatus , self - > loadersInterf , batchIndex , true ) ) ; <nl> <nl> - wait ( notifyApplierToApplyMutations ( self ) ) ; <nl> + wait ( notifyApplierToApplyMutations ( batchData , batchStatus , self - > appliersInterf , batchIndex , & self - > finishedBatch ) ) ; <nl> <nl> + self - > runningVersionBatches . set ( self - > runningVersionBatches . get ( ) - 1 ) ; <nl> return Void ( ) ; <nl> } <nl> <nl> / / Decide which key range should be taken by which applier <nl> - void splitKeyRangeForAppliers ( Reference < RestoreMasterData > self ) { <nl> - ASSERT ( self - > samplesSize > = 0 ) ; <nl> - int numAppliers = self - > appliersInterf . size ( ) ; <nl> - double slotSize = std : : max ( self - > samplesSize / numAppliers , 1 . 0 ) ; <nl> - std : : vector < Key > keyrangeSplitter ; <nl> - keyrangeSplitter . push_back ( normalKeys . begin ) ; / / First slot <nl> + / / Input : samples in batchData <nl> + / / Output : rangeToApplier in batchData <nl> + void splitKeyRangeForAppliers ( Reference < MasterBatchData > batchData , <nl> + std : : map < UID , RestoreApplierInterface > appliersInterf , int batchIndex ) { <nl> + ASSERT ( batchData - > samplesSize > = 0 ) ; <nl> + int numAppliers = appliersInterf . size ( ) ; <nl> + double slotSize = std : : max ( batchData - > samplesSize / numAppliers , 1 . 0 ) ; <nl> + std : : set < Key > keyrangeSplitter ; / / unique key to split key range for appliers <nl> + keyrangeSplitter . insert ( normalKeys . begin ) ; / / First slot <nl> double cumulativeSize = slotSize ; <nl> - TraceEvent ( " FastRestore " ) . detail ( " VersionBatch " , self - > batchIndex ) . detail ( " SamplingSize " , self - > samplesSize ) ; <nl> - while ( cumulativeSize < self - > samplesSize ) { <nl> - IndexedSet < Key , int64_t > : : iterator lowerBound = self - > samples . index ( cumulativeSize ) ; <nl> - if ( lowerBound = = self - > samples . end ( ) ) { <nl> + TraceEvent ( " FastRestoreMasterPhaseCalculateApplierKeyRangesStart " ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " SamplingSize " , batchData - > samplesSize ) <nl> + . detail ( " SlotSize " , slotSize ) ; <nl> + int slotIdx = 1 ; <nl> + while ( cumulativeSize < batchData - > samplesSize ) { <nl> + IndexedSet < Key , int64_t > : : iterator lowerBound = batchData - > samples . index ( cumulativeSize ) ; <nl> + if ( lowerBound = = batchData - > samples . end ( ) ) { <nl> break ; <nl> } <nl> - keyrangeSplitter . push_back ( * lowerBound ) ; <nl> - TraceEvent ( " FastRestore " ) <nl> - . detail ( " VersionBatch " , self - > batchIndex ) <nl> + keyrangeSplitter . insert ( * lowerBound ) ; <nl> + TraceEvent ( " FastRestoreMasterPhaseCalculateApplierKeyRanges " ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> . detail ( " CumulativeSize " , cumulativeSize ) <nl> - . detail ( " SlotSize " , slotSize ) ; <nl> + . detail ( " Slot " , slotIdx + + ) <nl> + . detail ( " LowerBoundKey " , lowerBound - > toString ( ) ) ; <nl> cumulativeSize + = slotSize ; <nl> } <nl> if ( keyrangeSplitter . size ( ) < numAppliers ) { <nl> - TraceEvent ( SevWarnAlways , " FastRestore " ) <nl> + TraceEvent ( SevWarnAlways , " FastRestoreMasterPhaseCalculateApplierKeyRanges " ) <nl> . detail ( " NotAllAppliersAreUsed " , keyrangeSplitter . size ( ) ) <nl> . detail ( " NumAppliers " , numAppliers ) ; <nl> } else if ( keyrangeSplitter . size ( ) > numAppliers ) { <nl> - TraceEvent ( SevError , " FastRestore " ) <nl> + bool expected = ( keyrangeSplitter . size ( ) = = numAppliers + 1 ) ; <nl> + TraceEvent ( expected ? SevWarn : SevError , " FastRestoreMasterPhaseCalculateApplierKeyRanges " ) <nl> . detail ( " TooManySlotsThanAppliers " , keyrangeSplitter . size ( ) ) <nl> - . detail ( " NumAppliers " , numAppliers ) ; <nl> + . detail ( " NumAppliers " , numAppliers ) <nl> + . detail ( " SamplingSize " , batchData - > samplesSize ) <nl> + . detail ( " PerformanceMayDegrade " , " Last applier handles more data than others " ) ; <nl> } <nl> - / / std : : sort ( keyrangeSplitter . begin ( ) , keyrangeSplitter . end ( ) ) ; <nl> + <nl> + std : : set < Key > : : iterator splitter = keyrangeSplitter . begin ( ) ; <nl> int i = 0 ; <nl> - self - > rangeToApplier . clear ( ) ; <nl> - for ( auto & applier : self - > appliersInterf ) { <nl> - if ( i > = keyrangeSplitter . size ( ) ) { <nl> + batchData - > rangeToApplier . clear ( ) ; <nl> + for ( auto & applier : appliersInterf ) { <nl> + if ( splitter = = keyrangeSplitter . end ( ) ) { <nl> break ; / / Not all appliers will be used <nl> } <nl> - self - > rangeToApplier [ keyrangeSplitter [ i ] ] = applier . first ; <nl> + batchData - > rangeToApplier [ * splitter ] = applier . first ; <nl> i + + ; <nl> + splitter + + ; <nl> } <nl> - ASSERT ( self - > rangeToApplier . size ( ) > 0 ) ; <nl> - ASSERT ( self - > sanityCheckApplierKeyRange ( ) ) ; <nl> - self - > logApplierKeyRange ( ) ; <nl> + ASSERT ( batchData - > rangeToApplier . size ( ) > 0 ) ; <nl> + ASSERT ( batchData - > sanityCheckApplierKeyRange ( ) ) ; <nl> + batchData - > logApplierKeyRange ( batchIndex ) ; <nl> + TraceEvent ( " FastRestoreMasterPhaseCalculateApplierKeyRangesDone " ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " SamplingSize " , batchData - > samplesSize ) <nl> + . detail ( " SlotSize " , slotSize ) ; <nl> } <nl> <nl> ACTOR static Future < Standalone < VectorRef < RestoreRequest > > > collectRestoreRequests ( Database cx ) { <nl> ACTOR static Future < Standalone < VectorRef < RestoreRequest > > > collectRestoreRequest <nl> / / wait for the restoreRequestTriggerKey to be set by the client / test workload <nl> loop { <nl> try { <nl> + TraceEvent ( " FastRestoreMasterPhaseCollectRestoreRequestsWait " ) ; <nl> tr . reset ( ) ; <nl> tr . setOption ( FDBTransactionOptions : : ACCESS_SYSTEM_KEYS ) ; <nl> tr . setOption ( FDBTransactionOptions : : LOCK_AWARE ) ; <nl> ACTOR static Future < Standalone < VectorRef < RestoreRequest > > > collectRestoreRequest <nl> if ( restoreRequestValues . size ( ) ) { <nl> for ( auto & it : restoreRequestValues ) { <nl> restoreRequests . push_back ( restoreRequests . arena ( ) , decodeRestoreRequestValue ( it . value ) ) ; <nl> - TraceEvent ( " FastRestore " ) . detail ( " RestoreRequest " , restoreRequests . back ( ) . toString ( ) ) ; <nl> + TraceEvent ( " FastRestoreMasterPhaseCollectRestoreRequests " ) <nl> + . detail ( " RestoreRequest " , restoreRequests . back ( ) . toString ( ) ) ; <nl> } <nl> } <nl> break ; <nl> ACTOR static Future < Void > collectBackupFiles ( Reference < IBackupContainer > bc , std <nl> <nl> / / Convert version to real time for operators to read the BackupDescription desc . <nl> wait ( desc . resolveVersionTimes ( cx ) ) ; <nl> - TraceEvent ( " FastRestore " ) . detail ( " BackupDesc " , desc . toString ( ) ) ; <nl> + TraceEvent ( " FastRestoreMasterPhaseCollectBackupFilesStart " ) . detail ( " BackupDesc " , desc . toString ( ) ) ; <nl> <nl> if ( request . targetVersion = = invalidVersion & & desc . maxRestorableVersion . present ( ) ) { <nl> request . targetVersion = desc . maxRestorableVersion . get ( ) ; <nl> ACTOR static Future < Void > collectBackupFiles ( Reference < IBackupContainer > bc , std <nl> Optional < RestorableFileSet > restorable = wait ( bc - > getRestoreSet ( request . targetVersion ) ) ; <nl> <nl> if ( ! restorable . present ( ) ) { <nl> - TraceEvent ( SevWarn , " FastRestore " ) . detail ( " NotRestorable " , request . targetVersion ) ; <nl> + TraceEvent ( SevWarn , " FastRestoreMasterPhaseCollectBackupFiles " ) . detail ( " NotRestorable " , request . targetVersion ) ; <nl> throw restore_missing_data ( ) ; <nl> } <nl> <nl> ASSERT ( rangeFiles - > empty ( ) ) ; <nl> ASSERT ( logFiles - > empty ( ) ) ; <nl> <nl> + std : : set < RestoreFileFR > uniqueRangeFiles ; <nl> + std : : set < RestoreFileFR > uniqueLogFiles ; <nl> for ( const RangeFile & f : restorable . get ( ) . ranges ) { <nl> - TraceEvent ( " FastRestore " ) . detail ( " RangeFile " , f . toString ( ) ) ; <nl> + TraceEvent ( " FastRestoreMasterPhaseCollectBackupFiles " ) . detail ( " RangeFile " , f . toString ( ) ) ; <nl> if ( f . fileSize < = 0 ) { <nl> continue ; <nl> } <nl> RestoreFileFR file ( f . version , f . fileName , true , f . blockSize , f . fileSize , f . version , f . version ) ; <nl> - TraceEvent ( " FastRestore " ) . detail ( " RangeFileFR " , file . toString ( ) ) ; <nl> - rangeFiles - > push_back ( file ) ; <nl> + TraceEvent ( " FastRestoreMasterPhaseCollectBackupFiles " ) . detail ( " RangeFileFR " , file . toString ( ) ) ; <nl> + uniqueRangeFiles . insert ( file ) ; <nl> } <nl> for ( const LogFile & f : restorable . get ( ) . logs ) { <nl> - TraceEvent ( " FastRestore " ) . detail ( " LogFile " , f . toString ( ) ) ; <nl> + TraceEvent ( " FastRestoreMasterPhaseCollectBackupFiles " ) . detail ( " LogFile " , f . toString ( ) ) ; <nl> if ( f . fileSize < = 0 ) { <nl> continue ; <nl> } <nl> RestoreFileFR file ( f . beginVersion , f . fileName , false , f . blockSize , f . fileSize , f . endVersion , f . beginVersion ) ; <nl> - TraceEvent ( " FastRestore " ) . detail ( " LogFileFR " , file . toString ( ) ) ; <nl> + TraceEvent ( " FastRestoreMasterPhaseCollectBackupFiles " ) . detail ( " LogFileFR " , file . toString ( ) ) ; <nl> logFiles - > push_back ( file ) ; <nl> + uniqueLogFiles . insert ( file ) ; <nl> } <nl> - <nl> + / / Assign unique range files and log files to output <nl> + rangeFiles - > assign ( uniqueRangeFiles . begin ( ) , uniqueRangeFiles . end ( ) ) ; <nl> + logFiles - > assign ( uniqueLogFiles . begin ( ) , uniqueLogFiles . end ( ) ) ; <nl> + <nl> + TraceEvent ( " FastRestoreMasterPhaseCollectBackupFilesDone " ) <nl> + . detail ( " BackupDesc " , desc . toString ( ) ) <nl> + . detail ( " RangeFiles " , rangeFiles - > size ( ) ) <nl> + . detail ( " LogFiles " , logFiles - > size ( ) ) ; <nl> return Void ( ) ; <nl> } <nl> <nl> ACTOR static Future < Void > clearDB ( Database cx ) { <nl> return Void ( ) ; <nl> } <nl> <nl> - ACTOR static Future < Void > initializeVersionBatch ( Reference < RestoreMasterData > self ) { <nl> - <nl> + ACTOR static Future < Void > initializeVersionBatch ( std : : map < UID , RestoreApplierInterface > appliersInterf , <nl> + std : : map < UID , RestoreLoaderInterface > loadersInterf , int batchIndex ) { <nl> + TraceEvent ( " FastRestoreMasterPhaseInitVersionBatchForAppliersStart " ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " Appliers " , appliersInterf . size ( ) ) ; <nl> std : : vector < std : : pair < UID , RestoreVersionBatchRequest > > requestsToAppliers ; <nl> - for ( auto & applier : self - > appliersInterf ) { <nl> - requestsToAppliers . push_back ( std : : make_pair ( applier . first , RestoreVersionBatchRequest ( self - > batchIndex ) ) ) ; <nl> + for ( auto & applier : appliersInterf ) { <nl> + requestsToAppliers . emplace_back ( applier . first , RestoreVersionBatchRequest ( batchIndex ) ) ; <nl> } <nl> - wait ( sendBatchRequests ( & RestoreApplierInterface : : initVersionBatch , self - > appliersInterf , requestsToAppliers ) ) ; <nl> + wait ( sendBatchRequests ( & RestoreApplierInterface : : initVersionBatch , appliersInterf , requestsToAppliers ) ) ; <nl> <nl> + TraceEvent ( " FastRestoreMasterPhaseInitVersionBatchForLoaders " ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " Loaders " , loadersInterf . size ( ) ) ; <nl> std : : vector < std : : pair < UID , RestoreVersionBatchRequest > > requestsToLoaders ; <nl> - for ( auto & loader : self - > loadersInterf ) { <nl> - requestsToLoaders . push_back ( std : : make_pair ( loader . first , RestoreVersionBatchRequest ( self - > batchIndex ) ) ) ; <nl> + for ( auto & loader : loadersInterf ) { <nl> + requestsToLoaders . emplace_back ( loader . first , RestoreVersionBatchRequest ( batchIndex ) ) ; <nl> } <nl> - wait ( sendBatchRequests ( & RestoreLoaderInterface : : initVersionBatch , self - > loadersInterf , requestsToLoaders ) ) ; <nl> - <nl> - self - > resetPerVersionBatch ( ) ; <nl> + wait ( sendBatchRequests ( & RestoreLoaderInterface : : initVersionBatch , loadersInterf , requestsToLoaders ) ) ; <nl> <nl> + TraceEvent ( " FastRestoreMasterPhaseInitVersionBatchForLoadersDone " ) . detail ( " BatchIndex " , batchIndex ) ; <nl> return Void ( ) ; <nl> } <nl> <nl> / / Ask each applier to apply its received mutations to DB <nl> - ACTOR static Future < Void > notifyApplierToApplyMutations ( Reference < RestoreMasterData > self ) { <nl> - / / Prepare the applyToDB requests <nl> - std : : vector < std : : pair < UID , RestoreVersionBatchRequest > > requests ; <nl> - for ( auto & applier : self - > appliersInterf ) { <nl> - requests . push_back ( std : : make_pair ( applier . first , RestoreVersionBatchRequest ( self - > batchIndex ) ) ) ; <nl> + / / NOTE : Master cannot start applying mutations at batchIndex until all appliers have applied for ( batchIndex - 1 ) <nl> + / / because appliers at different batchIndex may have overlapped key ranges . <nl> + ACTOR static Future < Void > notifyApplierToApplyMutations ( Reference < MasterBatchData > batchData , <nl> + Reference < MasterBatchStatus > batchStatus , <nl> + std : : map < UID , RestoreApplierInterface > appliersInterf , <nl> + int batchIndex , NotifiedVersion * finishedBatch ) { <nl> + <nl> + wait ( finishedBatch - > whenAtLeast ( batchIndex - 1 ) ) ; <nl> + TraceEvent ( " FastRestoreMasterPhaseApplyToDB " ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " FinishedBatch " , finishedBatch - > get ( ) ) ; <nl> + <nl> + if ( finishedBatch - > get ( ) = = batchIndex - 1 ) { <nl> + / / Prepare the applyToDB requests <nl> + std : : vector < std : : pair < UID , RestoreVersionBatchRequest > > requests ; <nl> + <nl> + TraceEvent ( " FastRestoreMasterPhaseApplyToDB " ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " Appliers " , appliersInterf . size ( ) ) ; <nl> + for ( auto & applier : appliersInterf ) { <nl> + ASSERT ( batchStatus - > applyStatus . find ( applier . first ) = = batchStatus - > applyStatus . end ( ) ) ; <nl> + requests . emplace_back ( applier . first , RestoreVersionBatchRequest ( batchIndex ) ) ; <nl> + batchStatus - > applyStatus [ applier . first ] = RestoreApplyStatus : : Applying ; <nl> + } <nl> + state std : : vector < RestoreCommonReply > replies ; <nl> + / / The actor at each batchIndex should only occur once . <nl> + / / Use batchData - > applyToDB just incase the actor at a batchIndex is executed more than once . <nl> + if ( ! batchData - > applyToDB . present ( ) ) { <nl> + batchData - > applyToDB = Never ( ) ; <nl> + batchData - > applyToDB = getBatchReplies ( & RestoreApplierInterface : : applyToDB , appliersInterf , requests , <nl> + & replies , TaskPriority : : RestoreApplierWriteDB ) ; <nl> + } else { <nl> + TraceEvent ( SevError , " FastRestoreMasterPhaseApplyToDB " ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " Attention " , " Actor should not be invoked twice for the same batch index " ) ; <nl> + } <nl> + <nl> + ASSERT ( batchData - > applyToDB . present ( ) ) ; <nl> + wait ( batchData - > applyToDB . get ( ) ) ; <nl> + <nl> + / / Sanity check all appliers have applied data to destination DB <nl> + for ( auto & reply : replies ) { <nl> + if ( batchStatus - > applyStatus [ reply . id ] = = RestoreApplyStatus : : Applying ) { <nl> + batchStatus - > applyStatus [ reply . id ] = RestoreApplyStatus : : Applied ; <nl> + if ( reply . isDuplicated ) { <nl> + TraceEvent ( SevWarn , " FastRestoreMasterPhaseApplyToDB " ) <nl> + . detail ( " Applier " , reply . id ) <nl> + . detail ( " DuplicateRequestReturnEarlier " , " Apply db request should have been processed " ) ; <nl> + } <nl> + } <nl> + } <nl> + for ( auto & applier : appliersInterf ) { <nl> + if ( batchStatus - > applyStatus [ applier . first ] ! = RestoreApplyStatus : : Applied ) { <nl> + TraceEvent ( SevError , " FastRestoreMasterPhaseApplyToDB " ) <nl> + . detail ( " Applier " , applier . first ) <nl> + . detail ( " ApplyStatus " , batchStatus - > applyStatus [ applier . first ] ) ; <nl> + } <nl> + } <nl> + finishedBatch - > set ( batchIndex ) ; <nl> } <nl> - wait ( sendBatchRequests ( & RestoreApplierInterface : : applyToDB , self - > appliersInterf , requests ) ) ; <nl> <nl> - TraceEvent ( " FastRestore " ) . detail ( " Master " , self - > id ( ) ) . detail ( " ApplyToDB " , " Completed " ) ; <nl> + TraceEvent ( " FastRestoreMasterPhaseApplyToDBDone " ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " FinishedBatch " , finishedBatch - > get ( ) ) ; <nl> + <nl> return Void ( ) ; <nl> } <nl> <nl> - / / Ask all loaders and appliers to perform housecleaning at the end of restore and <nl> - / / Register the restoreRequestDoneKey to signal the end of restore <nl> - ACTOR static Future < Void > notifyRestoreCompleted ( Reference < RestoreMasterData > self , Database cx ) { <nl> - state Reference < ReadYourWritesTransaction > tr ( new ReadYourWritesTransaction ( cx ) ) ; <nl> - <nl> - std : : vector < std : : pair < UID , RestoreVersionBatchRequest > > requests ; <nl> + / / Ask all loaders and appliers to perform housecleaning at the end of a restore request <nl> + / / Terminate those roles if terminate = true <nl> + ACTOR static Future < Void > notifyRestoreCompleted ( Reference < RestoreMasterData > self , bool terminate = false ) { <nl> + std : : vector < std : : pair < UID , RestoreFinishRequest > > requests ; <nl> + TraceEvent ( " FastRestoreMasterPhaseNotifyRestoreCompletedStart " ) ; <nl> for ( auto & loader : self - > loadersInterf ) { <nl> - requests . push_back ( std : : make_pair ( loader . first , RestoreVersionBatchRequest ( self - > batchIndex ) ) ) ; <nl> + requests . emplace_back ( loader . first , RestoreFinishRequest ( terminate ) ) ; <nl> } <nl> - / / A loader exits immediately after it receives the request . Master may not receive acks . <nl> + <nl> Future < Void > endLoaders = sendBatchRequests ( & RestoreLoaderInterface : : finishRestore , self - > loadersInterf , requests ) ; <nl> <nl> requests . clear ( ) ; <nl> for ( auto & applier : self - > appliersInterf ) { <nl> - requests . push_back ( std : : make_pair ( applier . first , RestoreVersionBatchRequest ( self - > batchIndex ) ) ) ; <nl> + requests . emplace_back ( applier . first , RestoreFinishRequest ( terminate ) ) ; <nl> } <nl> - Future < Void > endApplier = <nl> + Future < Void > endAppliers = <nl> sendBatchRequests ( & RestoreApplierInterface : : finishRestore , self - > appliersInterf , requests ) ; <nl> <nl> + / / If terminate = true , loaders and appliers exits immediately after it receives the request . Master may not receive <nl> + / / acks . <nl> + if ( ! terminate ) { <nl> + wait ( endLoaders & & endAppliers ) ; <nl> + } <nl> + <nl> + TraceEvent ( " FastRestoreMasterPhaseNotifyRestoreCompletedDone " ) ; <nl> + <nl> + return Void ( ) ; <nl> + } <nl> + <nl> + / / Register the restoreRequestDoneKey to signal the end of restore <nl> + ACTOR static Future < Void > signalRestoreCompleted ( Reference < RestoreMasterData > self , Database cx ) { <nl> + state Reference < ReadYourWritesTransaction > tr ( new ReadYourWritesTransaction ( cx ) ) ; <nl> + <nl> + wait ( notifyRestoreCompleted ( self , true ) ) ; <nl> + <nl> wait ( delay ( 5 . 0 ) ) ; / / Give some time for loaders and appliers to exit <nl> <nl> / / Notify tester that the restore has finished <nl> ACTOR static Future < Void > notifyRestoreCompleted ( Reference < RestoreMasterData > se <nl> } <nl> } <nl> <nl> - TraceEvent ( " FastRestore " ) . detail ( " RestoreMaster " , " RestoreCompleted " ) ; <nl> + TraceEvent ( " FastRestore " ) . detail ( " RestoreMaster " , " AllRestoreCompleted " ) ; <nl> <nl> return Void ( ) ; <nl> - } <nl> + } <nl> \ No newline at end of file <nl> mmm a / fdbserver / RestoreMaster . actor . h <nl> ppp b / fdbserver / RestoreMaster . actor . h <nl> <nl> <nl> # include " flow / actorcompiler . h " / / has to be last include <nl> <nl> - extern int restoreStatusIndex ; <nl> - <nl> struct VersionBatch { <nl> Version beginVersion ; / / Inclusive <nl> Version endVersion ; / / exclusive <nl> - std : : vector < RestoreFileFR > logFiles ; <nl> - std : : vector < RestoreFileFR > rangeFiles ; <nl> + std : : set < RestoreFileFR > logFiles ; <nl> + std : : set < RestoreFileFR > rangeFiles ; <nl> double size ; / / size of data in range and log files <nl> + int batchIndex ; / / Never reset <nl> <nl> VersionBatch ( ) : beginVersion ( 0 ) , endVersion ( 0 ) , size ( 0 ) { } ; <nl> <nl> + bool operator < ( const VersionBatch & rhs ) const { <nl> + return std : : tie ( batchIndex , beginVersion , endVersion , logFiles , rangeFiles , size ) < <nl> + std : : tie ( rhs . batchIndex , rhs . beginVersion , rhs . endVersion , rhs . logFiles , rhs . rangeFiles , rhs . size ) ; <nl> + } <nl> + <nl> bool isEmpty ( ) { return logFiles . empty ( ) & & rangeFiles . empty ( ) ; } <nl> void reset ( ) { <nl> beginVersion = 0 ; <nl> struct VersionBatch { <nl> bool isInVersionRange ( Version version ) const { return version > = beginVersion & & version < endVersion ; } <nl> } ; <nl> <nl> - struct RestoreMasterData : RestoreRoleData , public ReferenceCounted < RestoreMasterData > { <nl> + struct MasterBatchData : public ReferenceCounted < MasterBatchData > { <nl> / / rangeToApplier is in master and loader node . Loader uses this to determine which applier a mutation should be sent . <nl> / / KeyRef is the inclusive lower bound of the key range the applier ( UID ) is responsible for <nl> std : : map < Key , UID > rangeToApplier ; <nl> - std : : map < Version , VersionBatch > versionBatches ; / / key is the beginVersion of the version batch <nl> + IndexedSet < Key , int64_t > samples ; / / sample of range and log files <nl> + double samplesSize ; / / sum of the metric of all samples <nl> + Optional < Future < Void > > applyToDB ; <nl> + <nl> + MasterBatchData ( ) = default ; <nl> + ~ MasterBatchData ( ) = default ; <nl> + <nl> + / / Return true if pass the sanity check <nl> + bool sanityCheckApplierKeyRange ( ) { <nl> + bool ret = true ; <nl> + / / An applier should only appear once in rangeToApplier <nl> + std : : map < UID , Key > applierToRange ; <nl> + for ( auto & applier : rangeToApplier ) { <nl> + if ( applierToRange . find ( applier . second ) = = applierToRange . end ( ) ) { <nl> + applierToRange [ applier . second ] = applier . first ; <nl> + } else { <nl> + TraceEvent ( SevError , " FastRestore " ) <nl> + . detail ( " SanityCheckApplierKeyRange " , applierToRange . size ( ) ) <nl> + . detail ( " ApplierID " , applier . second ) <nl> + . detail ( " Key1 " , applierToRange [ applier . second ] ) <nl> + . detail ( " Key2 " , applier . first ) ; <nl> + ret = false ; <nl> + } <nl> + } <nl> + return ret ; <nl> + } <nl> + <nl> + void logApplierKeyRange ( int batchIndex ) { <nl> + TraceEvent ( " FastRestoreLogApplierKeyRange " ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " ApplierKeyRangeNum " , rangeToApplier . size ( ) ) ; <nl> + for ( auto & applier : rangeToApplier ) { <nl> + TraceEvent ( " FastRestoreLogApplierKeyRange " ) <nl> + . detail ( " BatchIndex " , batchIndex ) <nl> + . detail ( " KeyRangeLowerBound " , applier . first ) <nl> + . detail ( " Applier " , applier . second ) ; <nl> + } <nl> + } <nl> + } ; <nl> + <nl> + enum class RestoreAssetStatus { Loading , Loaded } ; <nl> + <nl> + enum class RestoreSendStatus { SendingLogs , SendedLogs , SendingRanges , SendedRanges } ; <nl> + <nl> + enum class RestoreApplyStatus { Applying , Applied } ; <nl> <nl> - int batchIndex ; <nl> + / / Track restore progress of each RestoreAsset ( RA ) and <nl> + / / Use status to sanity check restore property , e . g . , each RA should be processed exactly once . <nl> + struct MasterBatchStatus : public ReferenceCounted < MasterBatchStatus > { <nl> + std : : map < RestoreAsset , RestoreAssetStatus > raStatus ; <nl> + std : : map < UID , RestoreSendStatus > loadStatus ; <nl> + std : : map < UID , RestoreApplyStatus > applyStatus ; <nl> + <nl> + void addref ( ) { return ReferenceCounted < MasterBatchStatus > : : addref ( ) ; } <nl> + void delref ( ) { return ReferenceCounted < MasterBatchStatus > : : delref ( ) ; } <nl> + <nl> + MasterBatchStatus ( ) = default ; <nl> + ~ MasterBatchStatus ( ) = default ; <nl> + } ; <nl> + <nl> + struct RestoreMasterData : RestoreRoleData , public ReferenceCounted < RestoreMasterData > { <nl> + std : : map < Version , VersionBatch > versionBatches ; / / key is the beginVersion of the version batch <nl> <nl> Reference < IBackupContainer > bc ; / / Backup container is used to read backup files <nl> Key bcUrl ; / / The url used to get the bc <nl> <nl> - IndexedSet < Key , int64_t > samples ; / / sample of range and log files <nl> - double samplesSize ; / / sum of the metric of all samples <nl> + std : : map < int , Reference < MasterBatchData > > batch ; <nl> + std : : map < int , Reference < MasterBatchStatus > > batchStatus ; <nl> + NotifiedVersion finishedBatch ; / / The highest batch index all appliers have applied mutations <nl> + <nl> + AsyncVar < int > runningVersionBatches ; / / Currently running version batches <nl> <nl> void addref ( ) { return ReferenceCounted < RestoreMasterData > : : addref ( ) ; } <nl> void delref ( ) { return ReferenceCounted < RestoreMasterData > : : delref ( ) ; } <nl> struct RestoreMasterData : RestoreRoleData , public ReferenceCounted < RestoreMaste <nl> RestoreMasterData ( ) { <nl> role = RestoreRole : : Master ; <nl> nodeID = UID ( ) ; <nl> - batchIndex = 1 ; / / starts with 1 because batchId ( NotifiedVersion ) in loaders and appliers start with 0 <nl> + runningVersionBatches . set ( 0 ) ; <nl> } <nl> <nl> ~ RestoreMasterData ( ) = default ; <nl> <nl> - void resetPerVersionBatch ( ) { <nl> - TraceEvent ( " FastRestore " ) <nl> - . detail ( " RestoreMaster " , " ResetPerVersionBatch " ) <nl> - . detail ( " VersionBatchIndex " , batchIndex ) ; <nl> - samplesSize = 0 ; <nl> - samples . clear ( ) ; <nl> + void initVersionBatch ( int batchIndex ) { <nl> + TraceEvent ( " FastRestoreMasterInitVersionBatch " , id ( ) ) . detail ( " VersionBatchIndex " , batchIndex ) ; <nl> + } <nl> + <nl> + / / Reset master data at the beginning of each restore request <nl> + void resetPerRestoreRequest ( ) { <nl> + TraceEvent ( " FastRestoreMasterReset " ) . detail ( " OldVersionBatches " , versionBatches . size ( ) ) ; <nl> + versionBatches . clear ( ) ; <nl> + batch . clear ( ) ; <nl> + batchStatus . clear ( ) ; <nl> + finishedBatch = NotifiedVersion ( ) ; <nl> + ASSERT ( runningVersionBatches . get ( ) = = 0 ) ; <nl> } <nl> <nl> std : : string describeNode ( ) { <nl> std : : stringstream ss ; <nl> - ss < < " Master versionBatch : " < < batchIndex ; <nl> + ss < < " Master " ; <nl> return ss . str ( ) ; <nl> } <nl> <nl> void dumpVersionBatches ( const std : : map < Version , VersionBatch > & versionBatches ) { <nl> - int i = 0 ; <nl> + int i = 1 ; <nl> for ( auto & vb : versionBatches ) { <nl> TraceEvent ( " FastRestoreVersionBatches " ) <nl> - . detail ( " BatchIndex " , i ) <nl> + . detail ( " BatchIndex " , vb . second . batchIndex ) <nl> + . detail ( " ExpectedBatchIndex " , i ) <nl> . detail ( " BeginVersion " , vb . second . beginVersion ) <nl> . detail ( " EndVersion " , vb . second . endVersion ) <nl> . detail ( " Size " , vb . second . size ) ; <nl> struct RestoreMasterData : RestoreRoleData , public ReferenceCounted < RestoreMaste <nl> <nl> / / Split backup files into version batches , each of which has similar data size <nl> / / Input : sorted range files , sorted log files ; <nl> - / / Output : a set of version batches whose size is less than opConfig . batchSizeThreshold <nl> + / / Output : a set of version batches whose size is less than SERVER_KNOBS - > FASTRESTORE_VERSIONBATCH_MAX_BYTES <nl> / / and each mutation in backup files is included in the version batches exactly once . <nl> / / Assumption 1 : input files has no empty files ; <nl> - / / Assumption 2 : range files at one version < = batchSizeThreshold . <nl> - / / Note : We do not allow a versionBatch size larger than the batchSizeThreshold because the range file size at <nl> - / / a version depends on the number of backupAgents and its upper bound is hard to get . <nl> + / / Assumption 2 : range files at one version < = FASTRESTORE_VERSIONBATCH_MAX_BYTES . <nl> + / / Note : We do not allow a versionBatch size larger than the FASTRESTORE_VERSIONBATCH_MAX_BYTES because the range <nl> + / / file size at a version depends on the number of backupAgents and its upper bound is hard to get . <nl> void buildVersionBatches ( const std : : vector < RestoreFileFR > & rangeFiles , const std : : vector < RestoreFileFR > & logFiles , <nl> std : : map < Version , VersionBatch > * versionBatches ) { <nl> bool rewriteNextVersion = false ; <nl> struct RestoreMasterData : RestoreRoleData , public ReferenceCounted < RestoreMaste <nl> Version nextVersion = 0 ; / / Used to calculate the batch ' s endVersion <nl> VersionBatch vb ; <nl> vb . beginVersion = 0 ; / / Version batch range [ beginVersion , endVersion ) <nl> + vb . batchIndex = 1 ; <nl> <nl> while ( rangeIdx < rangeFiles . size ( ) | | logIdx < logFiles . size ( ) ) { <nl> if ( ! rewriteNextVersion ) { <nl> struct RestoreMasterData : RestoreRoleData , public ReferenceCounted < RestoreMaste <nl> . detail ( " RangeFiles " , rangeFiles . size ( ) ) <nl> . detail ( " LogIndex " , logIdx ) <nl> . detail ( " LogFiles " , logFiles . size ( ) ) <nl> - . detail ( " BatchSizeThreshold " , opConfig . batchSizeThreshold ) <nl> + . detail ( " VersionBatchSizeThreshold " , SERVER_KNOBS - > FASTRESTORE_VERSIONBATCH_MAX_BYTES ) <nl> . detail ( " CurrentBatchSize " , vb . size ) <nl> . detail ( " NextVersionIntervalSize " , nextVersionSize ) <nl> . detail ( " NextRangeIndex " , nextRangeIdx ) <nl> . detail ( " UsedLogFiles " , curLogFiles . size ( ) ) ; <nl> <nl> ASSERT ( prevEndVersion < nextVersion ) ; / / Ensure progress <nl> - if ( vb . size + nextVersionSize < = opConfig . batchSizeThreshold ) { <nl> + if ( vb . size + nextVersionSize < = SERVER_KNOBS - > FASTRESTORE_VERSIONBATCH_MAX_BYTES | | <nl> + ( vb . size < 1 & & prevEndVersion + 1 = = nextVersion ) ) { <nl> + / / In case the batch size at a single version > FASTRESTORE_VERSIONBATCH_MAX_BYTES , <nl> + / / the version batch should include the single version to avoid false positive in simulation . <nl> + if ( vb . size + nextVersionSize > SERVER_KNOBS - > FASTRESTORE_VERSIONBATCH_MAX_BYTES ) { <nl> + TraceEvent ( g_network - > isSimulated ( ) ? SevWarnAlways : SevError , " FastRestoreBuildVersionBatch " ) <nl> + . detail ( " NextVersion " , nextVersion ) <nl> + . detail ( " PreviousEndVersion " , prevEndVersion ) <nl> + . detail ( " NextVersionIntervalSize " , nextVersionSize ) <nl> + . detail ( " VersionBatchSizeThreshold " , SERVER_KNOBS - > FASTRESTORE_VERSIONBATCH_MAX_BYTES ) <nl> + . detail ( " SuggestedMinimumVersionBatchSizeThreshold " , nextVersionSize * 2 ) ; <nl> + } <nl> / / nextVersion should be included in this batch <nl> vb . size + = nextVersionSize ; <nl> while ( rangeIdx < nextRangeIdx & & rangeIdx < rangeFiles . size ( ) ) { <nl> ASSERT ( rangeFiles [ rangeIdx ] . fileSize > 0 ) ; <nl> - vb . rangeFiles . push_back ( rangeFiles [ rangeIdx ] ) ; <nl> + vb . rangeFiles . insert ( rangeFiles [ rangeIdx ] ) ; <nl> + + rangeIdx ; <nl> } <nl> <nl> struct RestoreMasterData : RestoreRoleData , public ReferenceCounted < RestoreMaste <nl> ASSERT ( log . beginVersion < nextVersion ) ; <nl> ASSERT ( log . endVersion > prevEndVersion ) ; <nl> ASSERT ( log . fileSize > 0 ) ; <nl> - vb . logFiles . push_back ( log ) ; <nl> + vb . logFiles . insert ( log ) ; <nl> } <nl> <nl> vb . endVersion = nextVersion ; <nl> prevEndVersion = vb . endVersion ; <nl> } else { <nl> if ( vb . size < 1 ) { <nl> - / / [ vb . endVersion , nextVersion ) > opConfig . batchSizeThreshold . We should split the version range <nl> + / / [ vb . endVersion , nextVersion ) > SERVER_KNOBS - > FASTRESTORE_VERSIONBATCH_MAX_BYTES . We should split <nl> + / / the version range <nl> if ( prevEndVersion > = nextVersion ) { <nl> - / / If range files at one version > batchSizeThreshold , DBA should increase batchSizeThreshold to <nl> - / / some value larger than nextVersion <nl> + / / If range files at one version > FASTRESTORE_VERSIONBATCH_MAX_BYTES , DBA should increase <nl> + / / FASTRESTORE_VERSIONBATCH_MAX_BYTES to some value larger than nextVersion <nl> TraceEvent ( SevError , " FastRestoreBuildVersionBatch " ) <nl> . detail ( " NextVersion " , nextVersion ) <nl> . detail ( " PreviousEndVersion " , prevEndVersion ) <nl> . detail ( " NextVersionIntervalSize " , nextVersionSize ) <nl> - . detail ( " BatchSizeThreshold " , opConfig . batchSizeThreshold ) <nl> - . detail ( " SuggestedMinimumBatchSizeThreshold " , nextVersion ) ; <nl> + . detail ( " VersionBatchSizeThreshold " , SERVER_KNOBS - > FASTRESTORE_VERSIONBATCH_MAX_BYTES ) <nl> + . detail ( " SuggestedMinimumVersionBatchSizeThreshold " , nextVersionSize * 2 ) ; <nl> / / Exit restore early if it won ' t succeed <nl> flushAndExit ( FDB_EXIT_ERROR ) ; <nl> } <nl> struct RestoreMasterData : RestoreRoleData , public ReferenceCounted < RestoreMaste <nl> vb . reset ( ) ; <nl> vb . size = 0 ; <nl> vb . beginVersion = prevEndVersion ; <nl> + vb . batchIndex + + ; <nl> } <nl> } <nl> / / The last wip version batch has some files <nl> struct RestoreMasterData : RestoreRoleData , public ReferenceCounted < RestoreMaste <nl> } <nl> } <nl> <nl> - / / Return true if pass the sanity check <nl> - bool sanityCheckApplierKeyRange ( ) { <nl> - bool ret = true ; <nl> - / / An applier should only appear once in rangeToApplier <nl> - std : : map < UID , Key > applierToRange ; <nl> - for ( auto & applier : rangeToApplier ) { <nl> - if ( applierToRange . find ( applier . second ) = = applierToRange . end ( ) ) { <nl> - applierToRange [ applier . second ] = applier . first ; <nl> - } else { <nl> - TraceEvent ( SevError , " FastRestore " ) <nl> - . detail ( " SanityCheckApplierKeyRange " , applierToRange . size ( ) ) <nl> - . detail ( " ApplierID " , applier . second ) <nl> - . detail ( " Key1 " , applierToRange [ applier . second ] ) <nl> - . detail ( " Key2 " , applier . first ) ; <nl> - ret = false ; <nl> - } <nl> - } <nl> - return ret ; <nl> - } <nl> - <nl> - void logApplierKeyRange ( ) { <nl> - TraceEvent ( " FastRestore " ) . detail ( " ApplierKeyRangeNum " , rangeToApplier . size ( ) ) ; <nl> - for ( auto & applier : rangeToApplier ) { <nl> - TraceEvent ( " FastRestore " ) . detail ( " KeyRangeLowerBound " , applier . first ) . detail ( " Applier " , applier . second ) ; <nl> - } <nl> - } <nl> - <nl> void initBackupContainer ( Key url ) { <nl> if ( bcUrl = = url & & bc . isValid ( ) ) { <nl> return ; <nl> mmm a / fdbserver / RestoreRoleCommon . actor . cpp <nl> ppp b / fdbserver / RestoreRoleCommon . actor . cpp <nl> ACTOR Future < Void > handleHeartbeat ( RestoreSimpleRequest req , UID id ) { <nl> return Void ( ) ; <nl> } <nl> <nl> - void handleFinishRestoreRequest ( const RestoreVersionBatchRequest & req , Reference < RestoreRoleData > self ) { <nl> - if ( self - > versionBatchStart ) { <nl> - self - > versionBatchStart = false ; <nl> - } <nl> - <nl> - TraceEvent ( " FastRestore " ) <nl> - . detail ( " FinishRestoreRequest " , req . batchID ) <nl> - . detail ( " Role " , getRoleStr ( self - > role ) ) <nl> - . detail ( " Node " , self - > id ( ) ) ; <nl> + void handleFinishRestoreRequest ( const RestoreFinishRequest & req , Reference < RestoreRoleData > self ) { <nl> + self - > resetPerRestoreRequest ( ) ; <nl> + TraceEvent ( " FastRestoreRolePhaseFinishRestoreRequest " , self - > id ( ) ) <nl> + . detail ( " FinishRestoreRequest " , req . terminate ) <nl> + . detail ( " Role " , getRoleStr ( self - > role ) ) ; <nl> <nl> req . reply . send ( RestoreCommonReply ( self - > id ( ) ) ) ; <nl> } <nl> <nl> + / / Multiple version batches may execute in parallel and init their version batches <nl> ACTOR Future < Void > handleInitVersionBatchRequest ( RestoreVersionBatchRequest req , Reference < RestoreRoleData > self ) { <nl> - / / batchId is continuous . ( req . batchID - 1 ) is the id of the just finished batch . <nl> - wait ( self - > versionBatchId . whenAtLeast ( req . batchID - 1 ) ) ; <nl> + TraceEvent ( " FastRestoreRolePhaseInitVersionBatch " , self - > id ( ) ) <nl> + . detail ( " BatchIndex " , req . batchIndex ) <nl> + . detail ( " Role " , getRoleStr ( self - > role ) ) <nl> + . detail ( " VersionBatchNotifiedVersion " , self - > versionBatchId . get ( ) ) ; <nl> + / / batchId is continuous . ( req . batchIndex - 1 ) is the id of the just finished batch . <nl> + wait ( self - > versionBatchId . whenAtLeast ( req . batchIndex - 1 ) ) ; <nl> <nl> - if ( self - > versionBatchId . get ( ) = = req . batchID - 1 ) { <nl> - self - > resetPerVersionBatch ( ) ; <nl> - TraceEvent ( " FastRestore " ) <nl> - . detail ( " InitVersionBatch " , req . batchID ) <nl> + if ( self - > versionBatchId . get ( ) = = req . batchIndex - 1 ) { <nl> + self - > initVersionBatch ( req . batchIndex ) ; <nl> + TraceEvent ( " FastRestoreInitVersionBatch " ) <nl> + . detail ( " BatchIndex " , req . batchIndex ) <nl> . detail ( " Role " , getRoleStr ( self - > role ) ) <nl> . detail ( " Node " , self - > id ( ) ) ; <nl> - self - > versionBatchId . set ( req . batchID ) ; <nl> + self - > versionBatchId . set ( req . batchIndex ) ; <nl> } <nl> <nl> req . reply . send ( RestoreCommonReply ( self - > id ( ) ) ) ; <nl> return Void ( ) ; <nl> } <nl> <nl> + void updateProcessStats ( Reference < RestoreRoleData > self ) { <nl> + if ( g_network - > isSimulated ( ) ) { <nl> + / / memUsage and cpuUsage are not relevant in the simulator , <nl> + / / and relying on the actual values could break seed determinism <nl> + self - > cpuUsage = 100 . 0 ; <nl> + self - > memory = 100 . 0 ; <nl> + self - > residentMemory = 100 . 0 ; <nl> + return ; <nl> + } <nl> + <nl> + SystemStatistics sysStats = getSystemStatistics ( ) ; <nl> + if ( sysStats . initialized ) { <nl> + self - > cpuUsage = 100 * sysStats . processCPUSeconds / sysStats . elapsed ; <nl> + self - > memory = sysStats . processMemory ; <nl> + self - > residentMemory = sysStats . processResidentMemory ; <nl> + } <nl> + } <nl> + <nl> + ACTOR Future < Void > traceProcessMetrics ( Reference < RestoreRoleData > self , std : : string role ) { <nl> + loop { <nl> + TraceEvent ( " FastRestoreTraceProcessMetrics " ) <nl> + . detail ( " Role " , role ) <nl> + . detail ( " Node " , self - > nodeID ) <nl> + . detail ( " CpuUsage " , self - > cpuUsage ) <nl> + . detail ( " UsedMemory " , self - > memory ) <nl> + . detail ( " ResidentMemory " , self - > residentMemory ) ; <nl> + wait ( delay ( SERVER_KNOBS - > FASTRESTORE_ROLE_LOGGING_DELAY ) ) ; <nl> + } <nl> + } <nl> + <nl> / / mmmmmm - Helper functions <nl> std : : string getHexString ( StringRef input ) { <nl> std : : stringstream ss ; <nl> mmm a / fdbserver / RestoreRoleCommon . actor . h <nl> ppp b / fdbserver / RestoreRoleCommon . actor . h <nl> <nl> <nl> # include < sstream > <nl> # include " flow / Stats . h " <nl> + # include " flow / SystemMonitor . h " <nl> # include " fdbclient / FDBTypes . h " <nl> # include " fdbclient / CommitTransaction . h " <nl> # include " fdbclient / Notified . h " <nl> <nl> <nl> # include " flow / actorcompiler . h " / / has to be last include <nl> <nl> - extern bool debug_verbose ; <nl> - <nl> struct RestoreRoleInterface ; <nl> struct RestoreLoaderInterface ; <nl> struct RestoreApplierInterface ; <nl> using VersionedMutationsMap = std : : map < Version , MutationsVec > ; <nl> <nl> ACTOR Future < Void > handleHeartbeat ( RestoreSimpleRequest req , UID id ) ; <nl> ACTOR Future < Void > handleInitVersionBatchRequest ( RestoreVersionBatchRequest req , Reference < RestoreRoleData > self ) ; <nl> - void handleFinishRestoreRequest ( const RestoreVersionBatchRequest & req , Reference < RestoreRoleData > self ) ; <nl> + void handleFinishRestoreRequest ( const RestoreFinishRequest & req , Reference < RestoreRoleData > self ) ; <nl> <nl> / / Helper class for reading restore data from a buffer and throwing the right errors . <nl> / / This struct is mostly copied from StringRefReader . We add a sanity check in this struct . <nl> struct RestoreRoleData : NonCopyable , public ReferenceCounted < RestoreRoleData > { <nl> UID nodeID ; <nl> int nodeIndex ; <nl> <nl> + double cpuUsage ; <nl> + double memory ; <nl> + double residentMemory ; <nl> + <nl> std : : map < UID , RestoreLoaderInterface > loadersInterf ; / / UID : loaderInterf ' s id <nl> std : : map < UID , RestoreApplierInterface > appliersInterf ; / / UID : applierInterf ' s id <nl> - RestoreApplierInterface masterApplierInterf ; <nl> <nl> NotifiedVersion versionBatchId ; / / Continuously increase for each versionBatch <nl> <nl> bool versionBatchStart = false ; <nl> <nl> - uint32_t inProgressFlag = 0 ; <nl> - <nl> - RestoreRoleData ( ) : role ( RestoreRole : : Invalid ) { } ; <nl> + RestoreRoleData ( ) : role ( RestoreRole : : Invalid ) , cpuUsage ( 0 . 0 ) , memory ( 0 . 0 ) , residentMemory ( 0 . 0 ) { } ; <nl> <nl> virtual ~ RestoreRoleData ( ) { } <nl> <nl> UID id ( ) const { return nodeID ; } <nl> <nl> - virtual void resetPerVersionBatch ( ) = 0 ; <nl> + virtual void initVersionBatch ( int batchIndex ) = 0 ; <nl> + <nl> + virtual void resetPerRestoreRequest ( ) = 0 ; <nl> <nl> void clearInterfaces ( ) { <nl> loadersInterf . clear ( ) ; <nl> struct RestoreRoleData : NonCopyable , public ReferenceCounted < RestoreRoleData > { <nl> virtual std : : string describeNode ( ) = 0 ; <nl> } ; <nl> <nl> + void updateProcessStats ( Reference < RestoreRoleData > self ) ; <nl> + ACTOR Future < Void > traceProcessMetrics ( Reference < RestoreRoleData > self , std : : string role ) ; <nl> + <nl> # include " flow / unactorcompiler . h " <nl> # endif <nl> mmm a / fdbserver / RestoreUtil . h <nl> ppp b / fdbserver / RestoreUtil . h <nl> <nl> # include < cstdint > <nl> # include < cstdarg > <nl> <nl> - / / # define SevFRMutationInfo SevVerbose <nl> - # define SevFRMutationInfo SevInfo <nl> + # define SevFRMutationInfo SevVerbose <nl> + / / # define SevFRMutationInfo SevInfo <nl> <nl> using MutationsVec = Standalone < VectorRef < MutationRef > > ; <nl> <nl> extern int numRoles ; <nl> <nl> std : : string getHexString ( StringRef input ) ; <nl> <nl> - / / Fast restore operation configuration <nl> - / / The initRestoreWorkerConfig function will reset the configuration params in simulation <nl> - struct FastRestoreOpConfig { <nl> - int num_loaders = 120 ; <nl> - int num_appliers = 40 ; <nl> - / / transactionBatchSizeThreshold is used when applier applies multiple mutations in a transaction to DB <nl> - double transactionBatchSizeThreshold = 512 ; / / 512 in Bytes <nl> - / / batchSizeThreshold is the maximum data size in each version batch <nl> - double batchSizeThreshold = 10 . 0 * 1024 . 0 * 1024 . 0 * 1024 . 0 ; / / 10 GB <nl> - } ; <nl> - extern FastRestoreOpConfig opConfig ; <nl> - <nl> struct RestoreCommonReply { <nl> constexpr static FileIdentifier file_identifier = 56140435 ; <nl> UID id ; / / unique ID of the server who sends the reply <nl> + bool isDuplicated ; <nl> <nl> RestoreCommonReply ( ) = default ; <nl> - explicit RestoreCommonReply ( UID id ) : id ( id ) { } <nl> + explicit RestoreCommonReply ( UID id , bool isDuplicated = false ) : id ( id ) , isDuplicated ( isDuplicated ) { } <nl> <nl> std : : string toString ( ) const { <nl> std : : stringstream ss ; <nl> - ss < < " ServerNodeID : " < < id . toString ( ) ; <nl> + ss < < " ServerNodeID : " < < id . toString ( ) < < " isDuplicated : " < < isDuplicated ; <nl> return ss . str ( ) ; <nl> } <nl> <nl> template < class Ar > <nl> void serialize ( Ar & ar ) { <nl> - serializer ( ar , id ) ; <nl> + serializer ( ar , id , isDuplicated ) ; <nl> } <nl> } ; <nl> <nl> mmm a / fdbserver / RestoreWorker . actor . cpp <nl> ppp b / fdbserver / RestoreWorker . actor . cpp <nl> <nl> <nl> # include " flow / actorcompiler . h " / / This must be the last # include . <nl> <nl> - FastRestoreOpConfig opConfig ; <nl> - <nl> - int NUM_APPLIERS = 40 ; <nl> - <nl> - int restoreStatusIndex = 0 ; <nl> - <nl> class RestoreConfigFR ; <nl> struct RestoreWorkerData ; / / Only declare the struct exist but we cannot use its field <nl> <nl> - void initRestoreWorkerConfig ( ) ; <nl> - <nl> ACTOR Future < Void > handlerTerminateWorkerRequest ( RestoreSimpleRequest req , Reference < RestoreWorkerData > self , <nl> RestoreWorkerInterface workerInterf , Database cx ) ; <nl> ACTOR Future < Void > monitorWorkerLiveness ( Reference < RestoreWorkerData > self ) ; <nl> ACTOR Future < Void > monitorWorkerLiveness ( Reference < RestoreWorkerData > self ) { <nl> } <nl> } <nl> <nl> - void initRestoreWorkerConfig ( ) { <nl> - opConfig . num_loaders = g_network - > isSimulated ( ) ? 3 : opConfig . num_loaders ; <nl> - opConfig . num_appliers = g_network - > isSimulated ( ) ? 3 : opConfig . num_appliers ; <nl> - / / TODO : Set the threshold to a random value in a range <nl> - opConfig . transactionBatchSizeThreshold = <nl> - g_network - > isSimulated ( ) ? 512 : opConfig . transactionBatchSizeThreshold ; / / Byte <nl> - opConfig . batchSizeThreshold = g_network - > isSimulated ( ) ? 10 * 1024 * 1024 : opConfig . batchSizeThreshold ; / / Byte <nl> - TraceEvent ( " FastRestore " ) <nl> - . detail ( " InitOpConfig " , " Result " ) <nl> - . detail ( " NumLoaders " , opConfig . num_loaders ) <nl> - . detail ( " NumAppliers " , opConfig . num_appliers ) <nl> - . detail ( " TxnBatchSize " , opConfig . transactionBatchSizeThreshold ) ; <nl> - } <nl> - <nl> / / RestoreWorkerLeader is the worker that runs RestoreMaster role <nl> ACTOR Future < Void > startRestoreWorkerLeader ( Reference < RestoreWorkerData > self , RestoreWorkerInterface workerInterf , <nl> Database cx ) { <nl> / / We must wait for enough time to make sure all restore workers have registered their workerInterfaces into the DB <nl> - TraceEvent ( " FastRestore " ) . detail ( " Master " , workerInterf . id ( ) ) . detail ( " WaitForRestoreWorkerInterfaces " , opConfig . num_loaders + opConfig . num_appliers ) ; <nl> + TraceEvent ( " FastRestore " ) <nl> + . detail ( " Master " , workerInterf . id ( ) ) <nl> + . detail ( " WaitForRestoreWorkerInterfaces " , <nl> + SERVER_KNOBS - > FASTRESTORE_NUM_LOADERS + SERVER_KNOBS - > FASTRESTORE_NUM_APPLIERS ) ; <nl> wait ( delay ( 10 . 0 ) ) ; <nl> - TraceEvent ( " FastRestore " ) . detail ( " Master " , workerInterf . id ( ) ) . detail ( " CollectRestoreWorkerInterfaces " , opConfig . num_loaders + opConfig . num_appliers ) ; <nl> + TraceEvent ( " FastRestore " ) <nl> + . detail ( " Master " , workerInterf . id ( ) ) <nl> + . detail ( " CollectRestoreWorkerInterfaces " , <nl> + SERVER_KNOBS - > FASTRESTORE_NUM_LOADERS + SERVER_KNOBS - > FASTRESTORE_NUM_APPLIERS ) ; <nl> <nl> - wait ( collectRestoreWorkerInterface ( self , cx , opConfig . num_loaders + opConfig . num_appliers ) ) ; <nl> + wait ( collectRestoreWorkerInterface ( self , cx , <nl> + SERVER_KNOBS - > FASTRESTORE_NUM_LOADERS + SERVER_KNOBS - > FASTRESTORE_NUM_APPLIERS ) ) ; <nl> <nl> / / TODO : Needs to keep this monitor ' s future . May use actorCollection <nl> state Future < Void > workersFailureMonitor = monitorWorkerLiveness ( self ) ; <nl> ACTOR Future < Void > startRestoreWorker ( Reference < RestoreWorkerData > self , Restore <nl> . detail ( " RestoreWorkerError " , e . what ( ) ) <nl> . detail ( " RequestType " , requestTypeStr ) ; <nl> break ; <nl> - / / if ( requestTypeStr . find ( " [ Init ] " ) ! = std : : string : : npos ) { <nl> - / / TraceEvent ( SevError , " FastRestore " ) . detail ( " RestoreWorkerUnexpectedExit " , " RequestType_Init " ) ; <nl> - / / break ; <nl> - / / } <nl> } <nl> } <nl> <nl> ACTOR Future < Void > startRestoreWorker ( Reference < RestoreWorkerData > self , Restore <nl> / / RestoreMaster is the leader <nl> ACTOR Future < Void > monitorleader ( Reference < AsyncVar < RestoreWorkerInterface > > leader , Database cx , <nl> RestoreWorkerInterface myWorkerInterf ) { <nl> - TraceEvent ( " FastRestore " ) . detail ( " MonitorLeader " , " StartLeaderElection " ) ; <nl> - state ReadYourWritesTransaction tr ( cx ) ; <nl> - / / state Future < Void > leaderWatch ; <nl> - state RestoreWorkerInterface leaderInterf ; <nl> + wait ( delay ( SERVER_KNOBS - > FASTRESTORE_MONITOR_LEADER_DELAY ) ) ; <nl> + TraceEvent ( " FastRestoreWorker " , myWorkerInterf . id ( ) ) . detail ( " MonitorLeader " , " StartLeaderElection " ) ; <nl> + state int count = 0 ; <nl> loop { <nl> try { <nl> + state RestoreWorkerInterface leaderInterf ; <nl> + state ReadYourWritesTransaction tr ( cx ) ; / / MX : Somewhere here program gets stuck <nl> + count + + ; <nl> tr . reset ( ) ; <nl> tr . setOption ( FDBTransactionOptions : : ACCESS_SYSTEM_KEYS ) ; <nl> tr . setOption ( FDBTransactionOptions : : LOCK_AWARE ) ; <nl> Optional < Value > leaderValue = wait ( tr . get ( restoreLeaderKey ) ) ; <nl> + TraceEvent ( SevInfo , " FastRestoreLeaderElection " ) <nl> + . detail ( " Round " , count ) <nl> + . detail ( " LeaderExisted " , leaderValue . present ( ) ) ; <nl> if ( leaderValue . present ( ) ) { <nl> leaderInterf = BinaryReader : : fromStringRef < RestoreWorkerInterface > ( leaderValue . get ( ) , IncludeVersion ( ) ) ; <nl> / / Register my interface as an worker if I am not the leader <nl> ACTOR Future < Void > monitorleader ( Reference < AsyncVar < RestoreWorkerInterface > > lea <nl> leader - > set ( leaderInterf ) ; <nl> break ; <nl> } catch ( Error & e ) { <nl> + TraceEvent ( SevInfo , " FastRestoreLeaderElection " ) . detail ( " ErrorCode " , e . code ( ) ) . detail ( " Error " , e . what ( ) ) ; <nl> wait ( tr . onError ( e ) ) ; <nl> } <nl> } <nl> <nl> - TraceEvent ( " FastRestore " ) . detail ( " MonitorLeader " , " FinishLeaderElection " ) . detail ( " Leader " , leaderInterf . id ( ) ) ; <nl> + TraceEvent ( " FastRestoreWorker " , myWorkerInterf . id ( ) ) <nl> + . detail ( " MonitorLeader " , " FinishLeaderElection " ) <nl> + . detail ( " Leader " , leaderInterf . id ( ) ) <nl> + . detail ( " IamLeader " , leaderInterf = = myWorkerInterf ) ; <nl> return Void ( ) ; <nl> } <nl> <nl> ACTOR Future < Void > _restoreWorker ( Database cx , LocalityData locality ) { <nl> myWorkerInterf . initEndpoints ( ) ; <nl> state Reference < RestoreWorkerData > self = Reference < RestoreWorkerData > ( new RestoreWorkerData ( ) ) ; <nl> self - > workerID = myWorkerInterf . id ( ) ; <nl> - initRestoreWorkerConfig ( ) ; <nl> + TraceEvent ( " FastRestoreWorkerKnobs " , myWorkerInterf . id ( ) ) <nl> + . detail ( " FailureTimeout " , SERVER_KNOBS - > FASTRESTORE_FAILURE_TIMEOUT ) <nl> + . detail ( " HeartBeat " , SERVER_KNOBS - > FASTRESTORE_HEARTBEAT_INTERVAL ) <nl> + . detail ( " SamplePercentage " , SERVER_KNOBS - > FASTRESTORE_SAMPLING_PERCENT ) <nl> + . detail ( " NumLoaders " , SERVER_KNOBS - > FASTRESTORE_NUM_LOADERS ) <nl> + . detail ( " NumAppliers " , SERVER_KNOBS - > FASTRESTORE_NUM_APPLIERS ) <nl> + . detail ( " TxnBatchSize " , SERVER_KNOBS - > FASTRESTORE_TXN_BATCH_MAX_BYTES ) <nl> + . detail ( " VersionBatchSize " , SERVER_KNOBS - > FASTRESTORE_VERSIONBATCH_MAX_BYTES ) ; <nl> <nl> wait ( monitorleader ( leader , cx , myWorkerInterf ) ) ; <nl> <nl> - TraceEvent ( " FastRestore " ) . detail ( " LeaderElection " , " WaitForLeader " ) ; <nl> + TraceEvent ( " FastRestoreWorker " , myWorkerInterf . id ( ) ) . detail ( " LeaderElection " , " WaitForLeader " ) ; <nl> if ( leader - > get ( ) = = myWorkerInterf ) { <nl> / / Restore master worker : doLeaderThings ( ) ; <nl> myWork = startRestoreWorkerLeader ( self , myWorkerInterf , cx ) ; <nl> ACTOR Future < Void > _restoreWorker ( Database cx , LocalityData locality ) { <nl> return Void ( ) ; <nl> } <nl> <nl> - ACTOR Future < Void > restoreWorker ( Reference < ClusterConnectionFile > ccf , LocalityData locality ) { <nl> - Database cx = Database : : createDatabase ( ccf - > getFilename ( ) , Database : : API_VERSION_LATEST , true , locality ) ; <nl> - wait ( _restoreWorker ( cx , locality ) ) ; <nl> + ACTOR Future < Void > restoreWorker ( Reference < ClusterConnectionFile > connFile , LocalityData locality , <nl> + std : : string coordFolder ) { <nl> + try { <nl> + Database cx = Database : : createDatabase ( connFile , Database : : API_VERSION_LATEST , true , locality ) ; <nl> + wait ( reportErrors ( _restoreWorker ( cx , locality ) , " RestoreWorker " ) ) ; <nl> + } catch ( Error & e ) { <nl> + TraceEvent ( " FastRestoreWorker " ) . detail ( " Error " , e . what ( ) ) ; <nl> + throw e ; <nl> + } <nl> + <nl> return Void ( ) ; <nl> } <nl> mmm a / fdbserver / RestoreWorker . actor . h <nl> ppp b / fdbserver / RestoreWorker . actor . h <nl> struct RestoreWorkerData : NonCopyable , public ReferenceCounted < RestoreWorkerDa <nl> Optional < RestoreLoaderInterface > loaderInterf ; <nl> Optional < RestoreApplierInterface > applierInterf ; <nl> <nl> - uint32_t inProgressFlag = 0 ; / / To avoid race between duplicate message delivery that invokes the same actor multiple times <nl> - <nl> UID id ( ) const { return workerID ; } ; <nl> <nl> RestoreWorkerData ( ) = default ; <nl> mmm a / fdbserver / SimulatedCluster . actor . cpp <nl> ppp b / fdbserver / SimulatedCluster . actor . cpp <nl> <nl> # include " fdbserver / CoordinationInterface . h " <nl> # include " fdbmonitor / SimpleIni . h " <nl> # include " fdbrpc / AsyncFileNonDurable . actor . h " <nl> - # include " fdbrpc / TLSConnection . h " <nl> # include " fdbclient / ManagementAPI . actor . h " <nl> # include " fdbclient / NativeAPI . actor . h " <nl> # include " fdbclient / BackupAgent . actor . h " <nl> const int MACHINE_REBOOT_TIME = 10 ; <nl> <nl> bool destructed = false ; <nl> <nl> - static const char * certBytes = <nl> - " mmm - - BEGIN CERTIFICATEmmm - - \ n " <nl> - " MIIEGzCCAwOgAwIBAgIJANUQj1rRA2XMMA0GCSqGSIb3DQEBBQUAMIGjMQswCQYD \ n " <nl> - " VQQGEwJVUzELMAkGA1UECAwCVkExDzANBgNVBAcMBlZpZW5uYTEaMBgGA1UECgwR \ n " <nl> - " Rm91bmRhdGlvbkRCLCBMTEMxGTAXBgNVBAsMEFRlc3QgZW5naW5lZXJpbmcxFTAT \ n " <nl> - " BgNVBAMMDE1yLiBCaWcgVHVuYTEoMCYGCSqGSIb3DQEJARYZYmlnLnR1bmFAZm91 \ n " <nl> - " bmRhdGlvbmRiLmNvbTAeFw0xNDEyMDUxNTEyMjFaFw0yNDEyMDIxNTEyMjFaMIGj \ n " <nl> - " MQswCQYDVQQGEwJVUzELMAkGA1UECAwCVkExDzANBgNVBAcMBlZpZW5uYTEaMBgG \ n " <nl> - " A1UECgwRRm91bmRhdGlvbkRCLCBMTEMxGTAXBgNVBAsMEFRlc3QgZW5naW5lZXJp \ n " <nl> - " bmcxFTATBgNVBAMMDE1yLiBCaWcgVHVuYTEoMCYGCSqGSIb3DQEJARYZYmlnLnR1 \ n " <nl> - " bmFAZm91bmRhdGlvbmRiLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC \ n " <nl> - " ggEBAKZTL2edDkiet4HBTZnjysn6gOVZH2MP02KVBIv / H7e + 3w7ZOIRvcPzhZe9M \ n " <nl> - " 3cGH1t / pkr9DSXvzIb42EffMVlpLD2VQn2H8VC2QSdJCIQcf802u + Taf + XtW6K1h \ n " <nl> - " p / YPL1uhdopUs3c1oon8ykKwnOfrQYgv5pUa7jQdMkltI2MQJU3uFq3Z / LHTvIKe \ n " <nl> - " FN + bqK0iYhZthwMG7Rld4 + RgKZoT4u1B6w / duEWk9KLjgs7fTf3Oe6JHCYNqwBJi \ n " <nl> - " 78sJalwXz9Wf8wmMaYSG0XNA7vBOdpTFhVPSsh6e3rkydf5HydMade / II98MWpMe \ n " <nl> - " hFg7FFMaJP6ig8p5iL + 9QP2VMCkCAwEAAaNQME4wHQYDVR0OBBYEFIXGmIcKptBP \ n " <nl> - " v3i9WS / mK78o5E / MMB8GA1UdIwQYMBaAFIXGmIcKptBPv3i9WS / mK78o5E / MMAwG \ n " <nl> - " A1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAJkVgNGOXT + ZHCNEYLjr / 6OM \ n " <nl> - " UCHvwlMeaEyqxaOmK26J2kAADPhjBZ7lZOHWb2Wzb + BiQUIFGwNIMoRvsg8skpJa \ n " <nl> - " OCqpVciHVXY / U8BiYY70DKozRza93Ab9om3pySGDJ / akdCjqbMT1Cb7Kloyw + hNh \ n " <nl> - " XD4MML0lYiUE9KK35xyK6FgTx4A7IXl4b3lWBgglqTh4 + P5J1 + xy8AYJ0VfPoP7y \ n " <nl> - " OoZgwAmkpkMnalReNkN7LALHGqMzv / qH04ODlkU / HUGgExtnINMxK9VEDIe / yLGm \ n " <nl> - " DHy7gcQMj5Hyymack / d4ZF8CSrYpGZQeZGXoxOmTDwWcXgnYA + 2o7lOYPb5Uu08 = \ n " <nl> - " mmm - - END CERTIFICATEmmm - - \ n " <nl> - " mmm - - BEGIN PRIVATE KEYmmm - - \ n " <nl> - " MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCmUy9nnQ5InreB \ n " <nl> - " wU2Z48rJ + oDlWR9jD9NilQSL / x + 3vt8O2TiEb3D84WXvTN3Bh9bf6ZK / Q0l78yG + \ n " <nl> - " NhH3zFZaSw9lUJ9h / FQtkEnSQiEHH / NNrvk2n / l7VuitYaf2Dy9boXaKVLN3NaKJ \ n " <nl> - " / MpCsJzn60GIL + aVGu40HTJJbSNjECVN7hat2fyx07yCnhTfm6itImIWbYcDBu0Z \ n " <nl> - " XePkYCmaE + LtQesP3bhFpPSi44LO3039znuiRwmDasASYu / LCWpcF8 / Vn / MJjGmE \ n " <nl> - " htFzQO7wTnaUxYVT0rIent65MnX + R8nTGnXvyCPfDFqTHoRYOxRTGiT + ooPKeYi / \ n " <nl> - " vUD9lTApAgMBAAECggEBAIYCmDtfq9aPK0P8v82yX / 4FPD2OZV + nrKXNc3BpCuE9 \ n " <nl> - " hPOtyX / LWrol0b / Rqwr3rAWVaIt6Z4bbCuD7J9cEaL8voyP6pbCJYjmj / BbQ + VOI \ n " <nl> - " Rrzcsid1Fcpu5 + JqwK3c5kdp / NzQChmOuXt8lmrNal7iilZ0YdDZdfu / WnkW2mBB \ n " <nl> - " oQHkujlnWr4PNYdwMOnBU6TwdOuz + inPVMLohOO0Vr585OxPsGzG2Ud3yQ / t34Cq \ n " <nl> - " F9nmOXQoszftGKsL1yuh / 3fGj / O86g / CRsUy05qZhDDBEYQD6qZCvD5 + yp8oOWIR \ n " <nl> - " SljM3GXDBnJqRPhP + Nyf6e6 / GoQtfVZ9MPRzDDPzIBECgYEA2kX / zAs6taOiNqCb \ n " <nl> - " 6nVGe7 / 3uQJz / CkmOSKIFKUu7lCEUjmMYpK3Xzp26RTUR9cT + g9y + cnJO1Vbaxtf \ n " <nl> - " Qidje6K + Oi1pQyUGQ6W + U8cPJHz43PVa7IB5Az5i / sS2tu0BGhvGo9G6iYQjxXeD \ n " <nl> - " 1197DRACgnm5AORQMum616XvSPMCgYEAwxKbkAzJzfZF6A3Ys + / 0kycNfDP8xZoC \ n " <nl> - " 1zV3d1b2JncsdAPCHYSKtpniRrQN9ASa3RMdkh + wrMN / KlbtU9Ddoc4NHxSTFV7F \ n " <nl> - " wypFMzLZslqkQ6uHnVVewHV7prfoKsMci2c9iHO7W8TEv4aqW8XDd8OozP3 / q2j4 \ n " <nl> - " hvL7VIAVqXMCgYEAwAFnfOQ75uBkp00tGlfDgsRhc5vWz3CbMRNRRWfxGq41V + dL \ n " <nl> - " uMJ7EAfr5ijue6uU5RmF + HkqzUjOvC894oGnn3CPibm8qNX + 5q7799JZXa2ZdTVX \ n " <nl> - " oEd7LAFLL / V3DP77Qy4 / 1Id / Ycydcu0pSuGw6tK0gnX06fXtHnxAYcaT8UUCgYAE \ n " <nl> - " MytcP5o8r / ezVlD7Fsh6PpYAvZHMo1M6VPFchWfJTjmLyeTtA8SEx + 1iPlAql8rJ \ n " <nl> - " xbaWRc5k + dSMEdEMQ + vxpuELcUL1a9PwLsHMp2SefWsZ9eB2l7bxh9YAsebyvL6p \ n " <nl> - " lbBydqNrB2KBCSIz1Z8uveytdS6C / 0CSjzqwCA3vVwKBgQDAXqjo3xrzMlHeXm5o \ n " <nl> - " qH / OjajjqbnPXHolHDitbLubyQ4E6KhMBMxfChBe / 8VptB / Gs0efVbMVGuabxY7Q \ n " <nl> - " iastGId8HyONy3UPGPxCn4b95cIxKvdpt + hvWtYHIBCfHXluQK7zsDMgvtXjYNiz \ n " <nl> - " peZRikYlwmu1K2YRTf7oLE2Ogw = = \ n " <nl> - " mmm - - END PRIVATE KEYmmm - - \ n " ; <nl> - <nl> template < class T > <nl> T simulate ( const T & in ) { <nl> BinaryWriter writer ( AssumeVersion ( currentProtocolVersion ) ) ; <nl> T simulate ( const T & in ) { <nl> return out ; <nl> } <nl> <nl> - static void simInitTLS ( Reference < TLSOptions > tlsOptions ) { <nl> - tlsOptions - > set_cert_data ( certBytes ) ; <nl> - tlsOptions - > set_key_data ( certBytes ) ; <nl> - tlsOptions - > set_verify_peers ( std : : vector < std : : string > ( 1 , " Check . Valid = 0 " ) ) ; <nl> - tlsOptions - > register_network ( ) ; <nl> - } <nl> - <nl> ACTOR Future < Void > runBackup ( Reference < ClusterConnectionFile > connFile ) { <nl> state std : : vector < Future < Void > > agentFutures ; <nl> <nl> enum AgentMode { <nl> / / a loop { } will be needed around the waiting on simulatedFDBD ( ) . For now this simply <nl> / / takes care of house - keeping such as context switching and file closing . <nl> ACTOR Future < ISimulator : : KillType > simulatedFDBDRebooter ( Reference < ClusterConnectionFile > connFile , IPAddress ip , <nl> - bool sslEnabled , Reference < TLSOptions > tlsOptions , <nl> + bool sslEnabled , <nl> uint16_t port , uint16_t listenPerProcess , <nl> LocalityData localities , ProcessClass processClass , <nl> std : : string * dataFolder , std : : string * coordFolder , <nl> ACTOR Future < ISimulator : : KillType > simulatedFDBDRebooter ( Reference < ClusterConnec <nl> wait ( delay ( waitTime ) ) ; <nl> <nl> state ISimulator : : ProcessInfo * process = <nl> - g_simulator . newProcess ( " Server " , ip , port , listenPerProcess , localities , processClass , dataFolder - > c_str ( ) , <nl> + g_simulator . newProcess ( " Server " , ip , port , sslEnabled , listenPerProcess , localities , processClass , dataFolder - > c_str ( ) , <nl> coordFolder - > c_str ( ) ) ; <nl> wait ( g_simulator . onProcess ( process , <nl> TaskPriority : : DefaultYield ) ) ; / / Now switch execution to the process on which we will run <nl> ACTOR Future < ISimulator : : KillType > simulatedFDBDRebooter ( Reference < ClusterConnec <nl> / / SOMEDAY : test lower memory limits , without making them too small and causing the database to stop making progress <nl> FlowTransport : : createInstance ( processClass = = ProcessClass : : TesterClass | | runBackupAgents = = AgentOnly , 1 ) ; <nl> Sim2FileSystem : : newFileSystem ( ) ; <nl> - if ( sslEnabled ) { <nl> - tlsOptions - > register_network ( ) ; <nl> - } <nl> <nl> vector < Future < Void > > futures ; <nl> for ( int listenPort = port ; listenPort < port + listenPerProcess ; + + listenPort ) { <nl> std : : string describe ( int const & val ) { <nl> / / Since a datacenter kill is considered to be the same as killing a machine , files cannot be swapped across datacenters <nl> std : : map < Optional < Standalone < StringRef > > , std : : vector < std : : vector < std : : string > > > availableFolders ; <nl> / / process count is no longer needed because it is now the length of the vector of ip ' s , because it was one ip per process <nl> - ACTOR Future < Void > simulatedMachine ( ClusterConnectionString connStr , std : : vector < IPAddress > ips , bool sslEnabled , <nl> - Reference < TLSOptions > tlsOptions , LocalityData localities , <nl> + ACTOR Future < Void > simulatedMachine ( ClusterConnectionString connStr , std : : vector < IPAddress > ips , bool sslEnabled , LocalityData localities , <nl> ProcessClass processClass , std : : string baseFolder , bool restarting , <nl> bool useSeedFile , AgentMode runBackupAgents , bool sslOnly , std : : string whitelistBinPaths ) { <nl> state int bootCount = 0 ; <nl> ACTOR Future < Void > simulatedMachine ( ClusterConnectionString connStr , std : : vector <nl> Reference < ClusterConnectionFile > clusterFile ( useSeedFile ? new ClusterConnectionFile ( path , connStr . toString ( ) ) : new ClusterConnectionFile ( path ) ) ; <nl> const int listenPort = i * listenPerProcess + 1 ; <nl> AgentMode agentMode = runBackupAgents = = AgentOnly ? ( i = = ips . size ( ) - 1 ? AgentOnly : AgentNone ) : runBackupAgents ; <nl> - processes . push_back ( simulatedFDBDRebooter ( clusterFile , ips [ i ] , sslEnabled , tlsOptions , listenPort , listenPerProcess , localities , processClass , & myFolders [ i ] , & coordFolders [ i ] , baseFolder , connStr , useSeedFile , agentMode , whitelistBinPaths ) ) ; <nl> + processes . push_back ( simulatedFDBDRebooter ( clusterFile , ips [ i ] , sslEnabled , listenPort , listenPerProcess , localities , processClass , & myFolders [ i ] , & coordFolders [ i ] , baseFolder , connStr , useSeedFile , agentMode , whitelistBinPaths ) ) ; <nl> TraceEvent ( " SimulatedMachineProcess " , randomId ) . detail ( " Address " , NetworkAddress ( ips [ i ] , listenPort , true , false ) ) . detail ( " ZoneId " , localities . zoneId ( ) ) . detail ( " DataHall " , localities . dataHallId ( ) ) . detail ( " Folder " , myFolders [ i ] ) ; <nl> } <nl> <nl> IPAddress makeIPAddressForSim ( bool isIPv6 , std : : array < int , 4 > parts ) { <nl> ACTOR Future < Void > restartSimulatedSystem ( vector < Future < Void > > * systemActors , std : : string baseFolder , int * pTesterCount , <nl> Optional < ClusterConnectionString > * pConnString , <nl> Standalone < StringRef > * pStartingConfiguration , <nl> - Reference < TLSOptions > tlsOptions , int extraDB , std : : string whitelistBinPaths ) { <nl> + int extraDB , std : : string whitelistBinPaths ) { <nl> CSimpleIni ini ; <nl> ini . SetUnicode ( ) ; <nl> ini . LoadFile ( joinPath ( baseFolder , " restartInfo . ini " ) . c_str ( ) ) ; <nl> ACTOR Future < Void > restartSimulatedSystem ( vector < Future < Void > > * systemActors , st <nl> <nl> / / SOMEDAY : parse backup agent from test file <nl> systemActors - > push_back ( reportErrors ( <nl> - simulatedMachine ( conn , ipAddrs , usingSSL , tlsOptions , localities , processClass , baseFolder , true , <nl> + simulatedMachine ( conn , ipAddrs , usingSSL , localities , processClass , baseFolder , true , <nl> i = = useSeedForMachine , enableExtraDB ? AgentAddition : AgentNone , <nl> usingSSL & & ( listenersPerProcess = = 1 | | processClass = = ProcessClass : : TesterClass ) , whitelistBinPaths ) , <nl> processClass = = ProcessClass : : TesterClass ? " SimulatedTesterMachine " : " SimulatedMachine " ) ) ; <nl> void SimulationConfig : : generateNormalConfig ( int minimumReplication , int minimumR <nl> <nl> void setupSimulatedSystem ( vector < Future < Void > > * systemActors , std : : string baseFolder , int * pTesterCount , <nl> Optional < ClusterConnectionString > * pConnString , Standalone < StringRef > * pStartingConfiguration , <nl> - int extraDB , int minimumReplication , int minimumRegions , Reference < TLSOptions > tlsOptions , <nl> - std : : string whitelistBinPaths ) { <nl> + int extraDB , int minimumReplication , int minimumRegions , std : : string whitelistBinPaths , bool configureLocked ) { <nl> / / SOMEDAY : this does not test multi - interface configurations <nl> SimulationConfig simconfig ( extraDB , minimumReplication , minimumRegions ) ; <nl> StatusObject startingConfigJSON = simconfig . db . toJSON ( true ) ; <nl> std : : string startingConfigString = " new " ; <nl> + if ( configureLocked ) { <nl> + startingConfigString + = " locked " ; <nl> + } <nl> for ( auto kv : startingConfigJSON ) { <nl> startingConfigString + = " " ; <nl> if ( kv . second . type ( ) = = json_spirit : : int_type ) { <nl> void setupSimulatedSystem ( vector < Future < Void > > * systemActors , std : : string baseFo <nl> bool assignClasses = machineCount - dataCenters > 4 & & deterministicRandom ( ) - > random01 ( ) < 0 . 5 ; <nl> <nl> / / Use SSL 5 % of the time <nl> - bool sslEnabled = deterministicRandom ( ) - > random01 ( ) < 0 . 10 & & tlsOptions - > enabled ( ) ; <nl> + bool sslEnabled = deterministicRandom ( ) - > random01 ( ) < 0 . 10 ; <nl> bool sslOnly = sslEnabled & & deterministicRandom ( ) - > coinflip ( ) ; <nl> g_simulator . listenersPerProcess = sslEnabled & & ! sslOnly ? 2 : 1 ; <nl> TEST ( sslEnabled ) ; / / SSL enabled <nl> void setupSimulatedSystem ( vector < Future < Void > > * systemActors , std : : string baseFo <nl> . detail ( " Address " , coordinatorAddresses [ i ] ) <nl> . detail ( " Coordinators " , describe ( coordinatorAddresses ) ) ; <nl> g_simulator . protectedAddresses . insert ( <nl> - NetworkAddress ( coordinatorAddresses [ i ] . ip , coordinatorAddresses [ i ] . port , true , false ) ) ; <nl> + NetworkAddress ( coordinatorAddresses [ i ] . ip , coordinatorAddresses [ i ] . port , true , coordinatorAddresses [ i ] . isTLS ( ) ) ) ; <nl> if ( coordinatorAddresses [ i ] . port = = 2 ) { <nl> - g_simulator . protectedAddresses . insert ( NetworkAddress ( coordinatorAddresses [ i ] . ip , 1 , true , false ) ) ; <nl> + g_simulator . protectedAddresses . insert ( NetworkAddress ( coordinatorAddresses [ i ] . ip , 1 , true , true ) ) ; <nl> } <nl> } <nl> deterministicRandom ( ) - > randomShuffle ( coordinatorAddresses ) ; <nl> void setupSimulatedSystem ( vector < Future < Void > > * systemActors , std : : string baseFo <nl> / / check the sslEnablementMap using only one ip ( <nl> LocalityData localities ( Optional < Standalone < StringRef > > ( ) , zoneId , machineId , dcUID ) ; <nl> localities . set ( LiteralStringRef ( " data_hall " ) , dcUID ) ; <nl> - systemActors - > push_back ( reportErrors ( simulatedMachine ( conn , ips , sslEnabled , tlsOptions , <nl> + systemActors - > push_back ( reportErrors ( simulatedMachine ( conn , ips , sslEnabled , <nl> localities , processClass , baseFolder , false , machine = = useSeedForMachine , requiresExtraDBMachines ? AgentOnly : AgentAddition , sslOnly , whitelistBinPaths ) , " SimulatedMachine " ) ) ; <nl> <nl> if ( requiresExtraDBMachines ) { <nl> void setupSimulatedSystem ( vector < Future < Void > > * systemActors , std : : string baseFo <nl> <nl> LocalityData localities ( Optional < Standalone < StringRef > > ( ) , newZoneId , newMachineId , dcUID ) ; <nl> localities . set ( LiteralStringRef ( " data_hall " ) , dcUID ) ; <nl> - systemActors - > push_back ( reportErrors ( simulatedMachine ( * g_simulator . extraDB , extraIps , sslEnabled , tlsOptions , <nl> + systemActors - > push_back ( reportErrors ( simulatedMachine ( * g_simulator . extraDB , extraIps , sslEnabled , <nl> localities , <nl> processClass , baseFolder , false , machine = = useSeedForMachine , AgentNone , sslOnly , whitelistBinPaths ) , " SimulatedMachine " ) ) ; <nl> } <nl> void setupSimulatedSystem ( vector < Future < Void > > * systemActors , std : : string baseFo <nl> Standalone < StringRef > newZoneId = Standalone < StringRef > ( deterministicRandom ( ) - > randomUniqueID ( ) . toString ( ) ) ; <nl> LocalityData localities ( Optional < Standalone < StringRef > > ( ) , newZoneId , newZoneId , Optional < Standalone < StringRef > > ( ) ) ; <nl> systemActors - > push_back ( reportErrors ( simulatedMachine ( <nl> - conn , ips , sslEnabled , tlsOptions , <nl> + conn , ips , sslEnabled & & sslOnly , <nl> localities , ProcessClass ( ProcessClass : : TesterClass , ProcessClass : : CommandLineSource ) , <nl> - baseFolder , false , i = = useSeedForMachine , AgentNone , sslEnabled , whitelistBinPaths ) , <nl> + baseFolder , false , i = = useSeedForMachine , AgentNone , sslEnabled & & sslOnly , whitelistBinPaths ) , <nl> " SimulatedTesterMachine " ) ) ; <nl> } <nl> * pStartingConfiguration = startingConfigString ; <nl> void setupSimulatedSystem ( vector < Future < Void > > * systemActors , std : : string baseFo <nl> . detail ( " StartingConfiguration " , pStartingConfiguration - > toString ( ) ) ; <nl> } <nl> <nl> - void checkExtraDB ( const char * testFile , int & extraDB , int & minimumReplication , int & minimumRegions ) { <nl> + void checkTestConf ( const char * testFile , int & extraDB , int & minimumReplication , int & minimumRegions , <nl> + int & configureLocked ) { <nl> std : : ifstream ifs ; <nl> ifs . open ( testFile , std : : ifstream : : in ) ; <nl> if ( ! ifs . good ( ) ) <nl> void checkExtraDB ( const char * testFile , int & extraDB , int & minimumReplication , i <nl> if ( attrib = = " minimumRegions " ) { <nl> sscanf ( value . c_str ( ) , " % d " , & minimumRegions ) ; <nl> } <nl> + <nl> + if ( attrib = = " configureLocked " ) { <nl> + sscanf ( value . c_str ( ) , " % d " , & configureLocked ) ; <nl> + } <nl> } <nl> <nl> ifs . close ( ) ; <nl> } <nl> <nl> - ACTOR void setupAndRun ( std : : string dataFolder , const char * testFile , bool rebooting , bool restoring , std : : string whitelistBinPaths , Reference < TLSOptions > tlsOptions ) { <nl> + ACTOR void setupAndRun ( std : : string dataFolder , const char * testFile , bool rebooting , bool restoring , std : : string whitelistBinPaths ) { <nl> state vector < Future < Void > > systemActors ; <nl> state Optional < ClusterConnectionString > connFile ; <nl> state Standalone < StringRef > startingConfiguration ; <nl> ACTOR void setupAndRun ( std : : string dataFolder , const char * testFile , bool reboot <nl> state int extraDB = 0 ; <nl> state int minimumReplication = 0 ; <nl> state int minimumRegions = 0 ; <nl> - checkExtraDB ( testFile , extraDB , minimumReplication , minimumRegions ) ; <nl> + state int configureLocked = 0 ; <nl> + checkTestConf ( testFile , extraDB , minimumReplication , minimumRegions , configureLocked ) ; <nl> <nl> / / TODO ( IPv6 ) Use IPv6 ? <nl> wait ( g_simulator . onProcess ( <nl> - g_simulator . newProcess ( " TestSystem " , IPAddress ( 0x01010101 ) , 1 , 1 , <nl> + g_simulator . newProcess ( " TestSystem " , IPAddress ( 0x01010101 ) , 1 , false , 1 , <nl> LocalityData ( Optional < Standalone < StringRef > > ( ) , <nl> Standalone < StringRef > ( deterministicRandom ( ) - > randomUniqueID ( ) . toString ( ) ) , <nl> Standalone < StringRef > ( deterministicRandom ( ) - > randomUniqueID ( ) . toString ( ) ) , <nl> ACTOR void setupAndRun ( std : : string dataFolder , const char * testFile , bool reboot <nl> TaskPriority : : DefaultYield ) ) ; <nl> Sim2FileSystem : : newFileSystem ( ) ; <nl> FlowTransport : : createInstance ( true , 1 ) ; <nl> - if ( tlsOptions - > enabled ( ) ) { <nl> - simInitTLS ( tlsOptions ) ; <nl> - } <nl> - <nl> TEST ( true ) ; / / Simulation start <nl> <nl> try { <nl> / / systemActors . push_back ( startSystemMonitor ( dataFolder ) ) ; <nl> if ( rebooting ) { <nl> - wait ( timeoutError ( restartSimulatedSystem ( & systemActors , dataFolder , & testerCount , & connFile , & startingConfiguration , tlsOptions , extraDB , whitelistBinPaths ) , 100 . 0 ) ) ; <nl> + wait ( timeoutError ( restartSimulatedSystem ( & systemActors , dataFolder , & testerCount , & connFile , & startingConfiguration , extraDB , whitelistBinPaths ) , 100 . 0 ) ) ; <nl> / / FIXME : snapshot restore does not support multi - region restore , hence restore it as single region always <nl> if ( restoring ) { <nl> startingConfiguration = LiteralStringRef ( " usable_regions = 1 " ) ; <nl> ACTOR void setupAndRun ( std : : string dataFolder , const char * testFile , bool reboot <nl> else { <nl> g_expect_full_pointermap = 1 ; <nl> setupSimulatedSystem ( & systemActors , dataFolder , & testerCount , & connFile , & startingConfiguration , extraDB , <nl> - minimumReplication , minimumRegions , tlsOptions , whitelistBinPaths ) ; <nl> + minimumReplication , minimumRegions , whitelistBinPaths , configureLocked ) ; <nl> wait ( delay ( 1 . 0 ) ) ; / / FIXME : WHY ! ! ! / / wait for machines to boot <nl> } <nl> std : : string clusterFileDir = joinPath ( dataFolder , deterministicRandom ( ) - > randomUniqueID ( ) . toString ( ) ) ; <nl> mmm a / fdbserver / SimulatedCluster . h <nl> ppp b / fdbserver / SimulatedCluster . h <nl> <nl> * limitations under the License . <nl> * / <nl> <nl> - # include " fdbrpc / TLSConnection . h " <nl> - <nl> # ifndef FDBSERVER_SIMULATEDCLUSTER_H <nl> # define FDBSERVER_SIMULATEDCLUSTER_H <nl> # pragma once <nl> <nl> - void setupAndRun ( std : : string const & dataFolder , const char * const & testFile , bool const & rebooting , bool const & restoring , std : : string const & whitelistBinPath , Reference < TLSOptions > const & useSSL ) ; <nl> + void setupAndRun ( std : : string const & dataFolder , const char * const & testFile , bool const & rebooting , bool const & restoring , std : : string const & whitelistBinPath ) ; <nl> <nl> # endif <nl> mmm a / fdbserver / SkipList . cpp <nl> ppp b / fdbserver / SkipList . cpp <nl> struct KeyInfo { <nl> : key ( key ) , begin ( begin ) , write ( write ) , transaction ( transaction ) , pIndex ( pIndex ) { } <nl> } ; <nl> <nl> + force_inline int extra_ordering ( const KeyInfo & ki ) { <nl> + return ki . begin * 2 + ( ki . write ^ ki . begin ) ; <nl> + } <nl> + <nl> / / returns true if done with string <nl> force_inline bool getCharacter ( const KeyInfo & ki , int character , int & outputCharacter ) { <nl> / / normal case <nl> force_inline bool getCharacter ( const KeyInfo & ki , int character , int & outputChar <nl> <nl> if ( character = = ki . key . size ( ) + 1 ) { <nl> / / end / begin + read / write relative sorting <nl> - outputCharacter = ki . begin * 2 + ( ki . write ^ ki . begin ) ; <nl> + outputCharacter = extra_ordering ( ki ) ; <nl> return false ; <nl> } <nl> <nl> bool operator < ( const KeyInfo & lhs , const KeyInfo & rhs ) { <nl> int c = memcmp ( lhs . key . begin ( ) , rhs . key . begin ( ) , i ) ; <nl> if ( c ! = 0 ) return c < 0 ; <nl> <nl> - / / SOMEDAY : This is probably not very fast . Slows D . Sort by ~ 20 % relative to previous ( incorrect ) version . <nl> - <nl> - bool lDone , rDone ; <nl> - int lc , rc ; <nl> - while ( true ) { <nl> - lDone = getCharacter ( lhs , i , lc ) ; <nl> - rDone = getCharacter ( rhs , i , rc ) ; <nl> - if ( lDone & & rDone ) return false ; / / equality <nl> - if ( lc < rc ) return true ; <nl> - if ( lc > rc ) return false ; <nl> - i + + ; <nl> + / / Always sort shorter keys before longer keys . <nl> + if ( lhs . key . size ( ) < rhs . key . size ( ) ) { <nl> + return true ; <nl> + } <nl> + if ( lhs . key . size ( ) > rhs . key . size ( ) ) { <nl> + return false ; <nl> } <nl> + <nl> + / / When the keys are the same length , use the extra ordering constraint . <nl> + return extra_ordering ( lhs ) < extra_ordering ( rhs ) ; <nl> } <nl> <nl> bool operator = = ( const KeyInfo & lhs , const KeyInfo & rhs ) { <nl> class SkipList : NonCopyable { <nl> int nPointers , valueLength ; <nl> } ; <nl> <nl> - static force_inline bool less ( const uint8_t * a , int aLen , const uint8_t * b , int bLen ) { <nl> - int len = min ( aLen , bLen ) ; <nl> - for ( int i = 0 ; i < len ; i + + ) <nl> - if ( a [ i ] < b [ i ] ) <nl> - return true ; <nl> - else if ( a [ i ] > b [ i ] ) <nl> - return false ; <nl> - <nl> + static force_inline bool less ( const uint8_t * a , int aLen , const uint8_t * b , int bLen ) { <nl> + int c = memcmp ( a , b , min ( aLen , bLen ) ) ; <nl> + if ( c < 0 ) return true ; <nl> + if ( c > 0 ) return false ; <nl> return aLen < bLen ; <nl> } <nl> <nl> void miniConflictSetTest ( ) { <nl> printf ( " miniConflictSetTest complete \ n " ) ; <nl> } <nl> <nl> + void operatorLessThanTest ( ) { <nl> + { / / Longer strings before shorter strings . <nl> + KeyInfo a ( LiteralStringRef ( " hello " ) , / * begin = * / false , / * write = * / true , 0 , nullptr ) ; <nl> + KeyInfo b ( LiteralStringRef ( " hello \ 0 " ) , / * begin = * / false , / * write = * / false , 0 , nullptr ) ; <nl> + ASSERT ( a < b ) ; <nl> + ASSERT ( ! ( b < a ) ) ; <nl> + ASSERT ( ! ( a = = b ) ) ; <nl> + } <nl> + <nl> + { / / Reads before writes . <nl> + KeyInfo a ( LiteralStringRef ( " hello " ) , / * begin = * / false , / * write = * / false , 0 , nullptr ) ; <nl> + KeyInfo b ( LiteralStringRef ( " hello " ) , / * begin = * / false , / * write = * / true , 0 , nullptr ) ; <nl> + ASSERT ( a < b ) ; <nl> + ASSERT ( ! ( b < a ) ) ; <nl> + ASSERT ( ! ( a = = b ) ) ; <nl> + } <nl> + <nl> + { / / Begin reads after writes . <nl> + KeyInfo a ( LiteralStringRef ( " hello " ) , / * begin = * / false , / * write = * / true , 0 , nullptr ) ; <nl> + KeyInfo b ( LiteralStringRef ( " hello " ) , / * begin = * / true , / * write = * / false , 0 , nullptr ) ; <nl> + ASSERT ( a < b ) ; <nl> + ASSERT ( ! ( b < a ) ) ; <nl> + ASSERT ( ! ( a = = b ) ) ; <nl> + } <nl> + <nl> + { / / Begin writes after writes . <nl> + KeyInfo a ( LiteralStringRef ( " hello " ) , / * begin = * / false , / * write = * / true , 0 , nullptr ) ; <nl> + KeyInfo b ( LiteralStringRef ( " hello " ) , / * begin = * / true , / * write = * / true , 0 , nullptr ) ; <nl> + ASSERT ( a < b ) ; <nl> + ASSERT ( ! ( b < a ) ) ; <nl> + ASSERT ( ! ( a = = b ) ) ; <nl> + } <nl> + } <nl> + <nl> void skipListTest ( ) { <nl> printf ( " Skip list test \ n " ) ; <nl> <nl> - / / A test case that breaks the old operator < <nl> - / / KeyInfo a ( LiteralStringRef ( " hello " ) , true , false , true , - 1 ) ; <nl> - / / KeyInfo b ( LiteralStringRef ( " hello \ 0 " ) , false , false , false , 0 ) ; <nl> - <nl> miniConflictSetTest ( ) ; <nl> <nl> + operatorLessThanTest ( ) ; <nl> + <nl> setAffinity ( 0 ) ; <nl> <nl> double start ; <nl> mmm a / fdbserver / Status . actor . cpp <nl> ppp b / fdbserver / Status . actor . cpp <nl> ACTOR static Future < vector < std : : pair < TLogInterface , EventMap > > > getTLogsAndMetri <nl> return results ; <nl> } <nl> <nl> - ACTOR static Future < vector < std : : pair < MasterProxyInterface , EventMap > > > getProxiesAndMetrics ( Database cx , std : : unordered_map < NetworkAddress , WorkerInterface > address_workers ) { <nl> - Reference < ProxyInfo > proxyInfo = cx - > getMasterProxies ( false ) ; <nl> - std : : vector < MasterProxyInterface > servers ; <nl> - if ( proxyInfo ) { <nl> - for ( int i = 0 ; i < proxyInfo - > size ( ) ; + + i ) { <nl> - servers . push_back ( proxyInfo - > getInterface ( i ) ) ; <nl> - } <nl> - } <nl> - <nl> + ACTOR static Future < vector < std : : pair < MasterProxyInterface , EventMap > > > getProxiesAndMetrics ( Reference < AsyncVar < CachedSerialization < ServerDBInfo > > > db , std : : unordered_map < NetworkAddress , WorkerInterface > address_workers ) { <nl> vector < std : : pair < MasterProxyInterface , EventMap > > results = wait ( getServerMetrics ( <nl> - servers , address_workers , std : : vector < std : : string > { " GRVLatencyMetrics " , " CommitLatencyMetrics " } ) ) ; <nl> + db - > get ( ) . read ( ) . client . proxies , address_workers , std : : vector < std : : string > { " GRVLatencyMetrics " , " CommitLatencyMetrics " } ) ) ; <nl> <nl> return results ; <nl> } <nl> ACTOR Future < StatusReply > clusterGetStatus ( <nl> <nl> state Future < ErrorOr < vector < std : : pair < StorageServerInterface , EventMap > > > > storageServerFuture = errorOr ( getStorageServersAndMetrics ( cx , address_workers ) ) ; <nl> state Future < ErrorOr < vector < std : : pair < TLogInterface , EventMap > > > > tLogFuture = errorOr ( getTLogsAndMetrics ( db , address_workers ) ) ; <nl> - state Future < ErrorOr < vector < std : : pair < MasterProxyInterface , EventMap > > > > proxyFuture = errorOr ( getProxiesAndMetrics ( cx , address_workers ) ) ; <nl> + state Future < ErrorOr < vector < std : : pair < MasterProxyInterface , EventMap > > > > proxyFuture = errorOr ( getProxiesAndMetrics ( db , address_workers ) ) ; <nl> <nl> state int minReplicasRemaining = - 1 ; <nl> std : : vector < Future < JsonBuilderObject > > futures2 ; <nl> mmm a / fdbserver / StorageMetrics . actor . h <nl> ppp b / fdbserver / StorageMetrics . actor . h <nl> struct StorageServerMetrics { <nl> . detail ( " Load " , rep . load . bytes ) ; <nl> } <nl> <nl> - rep . free . bytes = sb . free ; <nl> - rep . free . iosPerKSecond = 10e6 ; <nl> - rep . free . bytesPerKSecond = 100e9 ; <nl> - rep . free . bytesReadPerKSecond = 100e9 ; <nl> + rep . available . bytes = sb . available ; <nl> + rep . available . iosPerKSecond = 10e6 ; <nl> + rep . available . bytesPerKSecond = 100e9 ; <nl> + rep . available . bytesReadPerKSecond = 100e9 ; <nl> <nl> rep . capacity . bytes = sb . total ; <nl> rep . capacity . iosPerKSecond = 10e6 ; <nl> mmm a / fdbserver / TLogServer . actor . cpp <nl> ppp b / fdbserver / TLogServer . actor . cpp <nl> struct TLogData : NonCopyable { <nl> std : : map < UID , Reference < struct LogData > > id_data ; <nl> <nl> UID dbgid ; <nl> + UID workerID ; <nl> <nl> IKeyValueStore * persistentData ; / / Durable data on disk that were spilled . <nl> IDiskQueue * rawPersistentQueue ; / / The physical queue the persistentQueue below stores its data . Ideally , log interface should work without directly accessing rawPersistentQueue <nl> struct TLogData : NonCopyable { <nl> Reference < AsyncVar < bool > > degraded ; <nl> std : : vector < TagsAndMessage > tempTagMessages ; <nl> <nl> - TLogData ( UID dbgid , IKeyValueStore * persistentData , IDiskQueue * persistentQueue , Reference < AsyncVar < ServerDBInfo > > dbInfo , Reference < AsyncVar < bool > > degraded , std : : string folder ) <nl> - : dbgid ( dbgid ) , instanceID ( deterministicRandom ( ) - > randomUniqueID ( ) . first ( ) ) , <nl> + TLogData ( UID dbgid , UID workerID , IKeyValueStore * persistentData , IDiskQueue * persistentQueue , Reference < AsyncVar < ServerDBInfo > > dbInfo , Reference < AsyncVar < bool > > degraded , std : : string folder ) <nl> + : dbgid ( dbgid ) , workerID ( workerID ) , instanceID ( deterministicRandom ( ) - > randomUniqueID ( ) . first ( ) ) , <nl> persistentData ( persistentData ) , rawPersistentQueue ( persistentQueue ) , persistentQueue ( new TLogQueue ( persistentQueue , dbgid ) ) , <nl> dbInfo ( dbInfo ) , degraded ( degraded ) , queueCommitBegin ( 0 ) , queueCommitEnd ( 0 ) , <nl> diskQueueCommitBytes ( 0 ) , largeDiskQueueCommitBytes ( false ) , bytesInput ( 0 ) , bytesDurable ( 0 ) , targetVolatileBytes ( SERVER_KNOBS - > TLOG_SPILL_THRESHOLD ) , overheadBytesInput ( 0 ) , overheadBytesDurable ( 0 ) , <nl> struct LogData : NonCopyable , public ReferenceCounted < LogData > { <nl> bool execOpCommitInProgress ; <nl> int txsTags ; <nl> <nl> - explicit LogData ( TLogData * tLogData , TLogInterface interf , Tag remoteTag , bool isPrimary , int logRouterTags , int txsTags , UID recruitmentID , ProtocolVersion protocolVersion , TLogSpillType logSpillType , std : : vector < Tag > tags ) : tLogData ( tLogData ) , knownCommittedVersion ( 0 ) , logId ( interf . id ( ) ) , <nl> - cc ( " TLog " , interf . id ( ) . toString ( ) ) , bytesInput ( " BytesInput " , cc ) , bytesDurable ( " BytesDurable " , cc ) , remoteTag ( remoteTag ) , isPrimary ( isPrimary ) , logRouterTags ( logRouterTags ) , txsTags ( txsTags ) , recruitmentID ( recruitmentID ) , protocolVersion ( protocolVersion ) , logSpillType ( logSpillType ) , <nl> - logSystem ( new AsyncVar < Reference < ILogSystem > > ( ) ) , logRouterPoppedVersion ( 0 ) , durableKnownCommittedVersion ( 0 ) , minKnownCommittedVersion ( 0 ) , queuePoppedVersion ( 0 ) , allTags ( tags . begin ( ) , tags . end ( ) ) , terminated ( tLogData - > terminated . getFuture ( ) ) , <nl> - minPoppedTagVersion ( 0 ) , minPoppedTag ( invalidTag ) , <nl> + explicit LogData ( TLogData * tLogData , TLogInterface interf , Tag remoteTag , bool isPrimary , int logRouterTags , int txsTags , UID recruitmentID , ProtocolVersion protocolVersion , TLogSpillType logSpillType , std : : vector < Tag > tags , std : : string context ) <nl> + : tLogData ( tLogData ) , knownCommittedVersion ( 0 ) , logId ( interf . id ( ) ) , <nl> + cc ( " TLog " , interf . id ( ) . toString ( ) ) , bytesInput ( " BytesInput " , cc ) , bytesDurable ( " BytesDurable " , cc ) , remoteTag ( remoteTag ) , isPrimary ( isPrimary ) , logRouterTags ( logRouterTags ) , txsTags ( txsTags ) , recruitmentID ( recruitmentID ) , protocolVersion ( protocolVersion ) , logSpillType ( logSpillType ) , <nl> + logSystem ( new AsyncVar < Reference < ILogSystem > > ( ) ) , logRouterPoppedVersion ( 0 ) , durableKnownCommittedVersion ( 0 ) , minKnownCommittedVersion ( 0 ) , queuePoppedVersion ( 0 ) , allTags ( tags . begin ( ) , tags . end ( ) ) , terminated ( tLogData - > terminated . getFuture ( ) ) , <nl> + minPoppedTagVersion ( 0 ) , minPoppedTag ( invalidTag ) , <nl> / / These are initialized differently on init ( ) or recovery <nl> recoveryCount ( ) , stopped ( false ) , initialized ( false ) , queueCommittingVersion ( 0 ) , newPersistentDataVersion ( invalidVersion ) , unrecoveredBefore ( 1 ) , recoveredAt ( 1 ) , unpoppedRecoveredTags ( 0 ) , <nl> logRouterPopToVersion ( 0 ) , locality ( tagLocalityInvalid ) , execOpCommitInProgress ( false ) <nl> { <nl> - startRole ( Role : : TRANSACTION_LOG , interf . id ( ) , UID ( ) ) ; <nl> + startRole ( Role : : TRANSACTION_LOG , interf . id ( ) , tLogData - > workerID , { { " SharedTLog " , tLogData - > dbgid . shortString ( ) } } , context ) ; <nl> <nl> persistentDataVersion . init ( LiteralStringRef ( " TLog . PersistentDataVersion " ) , cc . id ) ; <nl> persistentDataDurableVersion . init ( LiteralStringRef ( " TLog . PersistentDataDurableVersion " ) , cc . id ) ; <nl> ACTOR Future < Void > updatePoppedLocation ( TLogData * self , Reference < LogData > logD <nl> / / us to remove data that still is pointed to by SpilledData in the btree . <nl> if ( data - > persistentPopped < = logData - > persistentDataVersion ) { <nl> / / Recover the next needed location in the Disk Queue from the index . <nl> - Standalone < VectorRef < KeyValueRef > > kvrefs = wait ( <nl> + Standalone < RangeResultRef > kvrefs = wait ( <nl> self - > persistentData - > readRange ( KeyRangeRef ( <nl> persistTagMessageRefsKey ( logData - > logId , data - > tag , data - > persistentPopped ) , <nl> persistTagMessageRefsKey ( logData - > logId , data - > tag , logData - > persistentDataVersion + 1 ) ) , 1 ) ) ; <nl> ACTOR Future < Void > tLogPeekMessages ( TLogData * self , TLogPeekRequest req , Refere <nl> } <nl> <nl> if ( logData - > shouldSpillByValue ( req . tag ) ) { <nl> - Standalone < VectorRef < KeyValueRef > > kvs = wait ( <nl> + Standalone < RangeResultRef > kvs = wait ( <nl> self - > persistentData - > readRange ( KeyRangeRef ( <nl> persistTagMessagesKey ( logData - > logId , req . tag , req . begin ) , <nl> persistTagMessagesKey ( logData - > logId , req . tag , logData - > persistentDataDurableVersion + 1 ) ) , SERVER_KNOBS - > DESIRED_TOTAL_BYTES , SERVER_KNOBS - > DESIRED_TOTAL_BYTES ) ) ; <nl> ACTOR Future < Void > tLogPeekMessages ( TLogData * self , TLogPeekRequest req , Refere <nl> } <nl> } else { <nl> / / FIXME : Limit to approximately DESIRED_TOTATL_BYTES somehow . <nl> - Standalone < VectorRef < KeyValueRef > > kvrefs = wait ( <nl> + Standalone < RangeResultRef > kvrefs = wait ( <nl> self - > persistentData - > readRange ( KeyRangeRef ( <nl> persistTagMessageRefsKey ( logData - > logId , req . tag , req . begin ) , <nl> persistTagMessageRefsKey ( logData - > logId , req . tag , logData - > persistentDataDurableVersion + 1 ) ) , <nl> ACTOR Future < Void > watchDegraded ( TLogData * self ) { <nl> return Void ( ) ; <nl> } <nl> <nl> - / / This delay is divided into multiple delays to avoid marking the tlog as degraded because of a single SlowTask <nl> - state int loopCount = 0 ; <nl> - while ( loopCount < SERVER_KNOBS - > TLOG_DEGRADED_DELAY_COUNT ) { <nl> - wait ( delay ( SERVER_KNOBS - > TLOG_DEGRADED_DURATION / SERVER_KNOBS - > TLOG_DEGRADED_DELAY_COUNT , TaskPriority : : Low ) ) ; <nl> - loopCount + + ; <nl> - } <nl> + wait ( lowPriorityDelay ( SERVER_KNOBS - > TLOG_DEGRADED_DURATION ) ) ; <nl> + <nl> TraceEvent ( SevWarnAlways , " TLogDegraded " , self - > dbgid ) ; <nl> TEST ( true ) ; / / TLog degraded <nl> self - > degraded - > set ( true ) ; <nl> ACTOR Future < Void > rejoinMasters ( TLogData * self , TLogInterface tli , DBRecoveryC <nl> if ( self - > dbInfo - > get ( ) . master . id ( ) ! = lastMasterID ) { <nl> / / The TLogRejoinRequest is needed to establish communications with a new master , which doesn ' t have our TLogInterface <nl> TLogRejoinRequest req ( tli ) ; <nl> - TraceEvent ( " TLogRejoining " , self - > dbgid ) . detail ( " Master " , self - > dbInfo - > get ( ) . master . id ( ) ) ; <nl> + TraceEvent ( " TLogRejoining " , tli . id ( ) ) . detail ( " Master " , self - > dbInfo - > get ( ) . master . id ( ) ) ; <nl> choose { <nl> when ( TLogRejoinReply rep = <nl> wait ( brokenPromiseToNever ( self - > dbInfo - > get ( ) . master . tlogRejoin . getReply ( req ) ) ) ) { <nl> ACTOR Future < Void > restorePersistentState ( TLogData * self , LocalityData locality <nl> wait ( storage - > init ( ) ) ; <nl> state Future < Optional < Value > > fFormat = storage - > readValue ( persistFormat . key ) ; <nl> state Future < Optional < Value > > fRecoveryLocation = storage - > readValue ( persistRecoveryLocationKey ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fVers = storage - > readRange ( persistCurrentVersionKeys ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fKnownCommitted = storage - > readRange ( persistKnownCommittedVersionKeys ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fLocality = storage - > readRange ( persistLocalityKeys ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fLogRouterTags = storage - > readRange ( persistLogRouterTagsKeys ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fTxsTags = storage - > readRange ( persistTxsTagsKeys ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fRecoverCounts = storage - > readRange ( persistRecoveryCountKeys ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fProtocolVersions = storage - > readRange ( persistProtocolVersionKeys ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fTLogSpillTypes = storage - > readRange ( persistTLogSpillTypeKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fVers = storage - > readRange ( persistCurrentVersionKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fKnownCommitted = storage - > readRange ( persistKnownCommittedVersionKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fLocality = storage - > readRange ( persistLocalityKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fLogRouterTags = storage - > readRange ( persistLogRouterTagsKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fTxsTags = storage - > readRange ( persistTxsTagsKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fRecoverCounts = storage - > readRange ( persistRecoveryCountKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fProtocolVersions = storage - > readRange ( persistProtocolVersionKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fTLogSpillTypes = storage - > readRange ( persistTLogSpillTypeKeys ) ; <nl> <nl> / / FIXME : metadata in queue ? <nl> <nl> ACTOR Future < Void > restorePersistentState ( TLogData * self , LocalityData locality <nl> } <nl> <nl> if ( ! fFormat . get ( ) . present ( ) ) { <nl> - Standalone < VectorRef < KeyValueRef > > v = wait ( self - > persistentData - > readRange ( KeyRangeRef ( StringRef ( ) , LiteralStringRef ( " \ xff " ) ) , 1 ) ) ; <nl> + Standalone < RangeResultRef > v = wait ( self - > persistentData - > readRange ( KeyRangeRef ( StringRef ( ) , LiteralStringRef ( " \ xff " ) ) , 1 ) ) ; <nl> if ( ! v . size ( ) ) { <nl> TEST ( true ) ; / / The DB is completely empty , so it was never initialized . Delete it . <nl> throw worker_removed ( ) ; <nl> ACTOR Future < Void > restorePersistentState ( TLogData * self , LocalityData locality <nl> TLogSpillType logSpillType = BinaryReader : : fromStringRef < TLogSpillType > ( fTLogSpillTypes . get ( ) [ idx ] . value , AssumeVersion ( protocolVersion ) ) ; <nl> <nl> / / We do not need the remoteTag , because we will not be loading any additional data <nl> - logData = Reference < LogData > ( new LogData ( self , recruited , Tag ( ) , true , id_logRouterTags [ id1 ] , id_txsTags [ id1 ] , UID ( ) , protocolVersion , logSpillType , std : : vector < Tag > ( ) ) ) ; <nl> + logData = Reference < LogData > ( new LogData ( self , recruited , Tag ( ) , true , id_logRouterTags [ id1 ] , id_txsTags [ id1 ] , UID ( ) , protocolVersion , logSpillType , std : : vector < Tag > ( ) , " Restored " ) ) ; <nl> logData - > locality = id_locality [ id1 ] ; <nl> logData - > stopped = true ; <nl> self - > id_data [ id1 ] = logData ; <nl> ACTOR Future < Void > restorePersistentState ( TLogData * self , LocalityData locality <nl> tagKeys = prefixRange ( rawId . withPrefix ( persistTagPoppedKeys . begin ) ) ; <nl> loop { <nl> if ( logData - > removed . isReady ( ) ) break ; <nl> - Standalone < VectorRef < KeyValueRef > > data = wait ( self - > persistentData - > readRange ( tagKeys , BUGGIFY ? 3 : 1 < < 30 , 1 < < 20 ) ) ; <nl> + Standalone < RangeResultRef > data = wait ( self - > persistentData - > readRange ( tagKeys , BUGGIFY ? 3 : 1 < < 30 , 1 < < 20 ) ) ; <nl> if ( ! data . size ( ) ) break ; <nl> ( ( KeyRangeRef & ) tagKeys ) = KeyRangeRef ( keyAfter ( data . back ( ) . key , tagKeys . arena ( ) ) , tagKeys . end ) ; <nl> <nl> ACTOR Future < Void > tLogStart ( TLogData * self , InitializeTLogRequest req , Localit <nl> <nl> stopAllTLogs ( self , recruited . id ( ) ) ; <nl> <nl> - state Reference < LogData > logData = Reference < LogData > ( new LogData ( self , recruited , req . remoteTag , req . isPrimary , req . logRouterTags , req . txsTags , req . recruitmentID , currentProtocolVersion , req . spillType , req . allTags ) ) ; <nl> + bool recovering = ( req . recoverFrom . logSystemType = = LogSystemType : : tagPartitioned ) ; <nl> + state Reference < LogData > logData = Reference < LogData > ( new LogData ( self , recruited , req . remoteTag , req . isPrimary , req . logRouterTags , req . txsTags , req . recruitmentID , currentProtocolVersion , req . spillType , req . allTags , recovering ? " Recovered " : " Recruited " ) ) ; <nl> self - > id_data [ recruited . id ( ) ] = logData ; <nl> logData - > locality = req . locality ; <nl> logData - > recoveryCount = req . epoch ; <nl> ACTOR Future < Void > tLogStart ( TLogData * self , InitializeTLogRequest req , Localit <nl> throw logData - > removed . getError ( ) ; <nl> } <nl> <nl> - if ( req . recoverFrom . logSystemType = = LogSystemType : : tagPartitioned ) { <nl> + if ( recovering ) { <nl> logData - > unrecoveredBefore = req . startVersion ; <nl> logData - > recoveredAt = req . recoverAt ; <nl> logData - > knownCommittedVersion = req . startVersion - 1 ; <nl> ACTOR Future < Void > startSpillingInTenSeconds ( TLogData * self , UID tlogId , Referen <nl> } <nl> <nl> / / New tLog ( if ! recoverFrom . size ( ) ) or restore from network <nl> - ACTOR Future < Void > tLog ( IKeyValueStore * persistentData , IDiskQueue * persistentQueue , Reference < AsyncVar < ServerDBInfo > > db , LocalityData locality , PromiseStream < InitializeTLogRequest > tlogRequests , UID tlogId , bool restoreFromDisk , Promise < Void > oldLog , Promise < Void > recovered , std : : string folder , Reference < AsyncVar < bool > > degraded , Reference < AsyncVar < UID > > activeSharedTLog ) { <nl> - state TLogData self ( tlogId , persistentData , persistentQueue , db , degraded , folder ) ; <nl> + ACTOR Future < Void > tLog ( IKeyValueStore * persistentData , IDiskQueue * persistentQueue , Reference < AsyncVar < ServerDBInfo > > db , LocalityData locality , PromiseStream < InitializeTLogRequest > tlogRequests , UID tlogId , UID workerID , bool restoreFromDisk , Promise < Void > oldLog , Promise < Void > recovered , std : : string folder , Reference < AsyncVar < bool > > degraded , Reference < AsyncVar < UID > > activeSharedTLog ) { <nl> + state TLogData self ( tlogId , workerID , persistentData , persistentQueue , db , degraded , folder ) ; <nl> state Future < Void > error = actorCollection ( self . sharedActors . getFuture ( ) ) ; <nl> <nl> TraceEvent ( " SharedTlog " , tlogId ) ; <nl> - / / FIXME : Pass the worker id instead of stubbing it <nl> - startRole ( Role : : SHARED_TRANSACTION_LOG , tlogId , UID ( ) ) ; <nl> try { <nl> if ( restoreFromDisk ) { <nl> wait ( restorePersistentState ( & self , locality , oldLog , recovered , tlogRequests ) ) ; <nl> ACTOR Future < Void > tLog ( IKeyValueStore * persistentData , IDiskQueue * persistentQ <nl> } catch ( Error & e ) { <nl> self . terminated . send ( Void ( ) ) ; <nl> TraceEvent ( " TLogError " , tlogId ) . error ( e , true ) ; <nl> - endRole ( Role : : SHARED_TRANSACTION_LOG , tlogId , " Error " , true ) ; <nl> if ( recovered . canBeSet ( ) ) recovered . send ( Void ( ) ) ; <nl> <nl> while ( ! tlogRequests . isEmpty ( ) ) { <nl> mmm a / fdbserver / VersionedBTree . actor . cpp <nl> ppp b / fdbserver / VersionedBTree . actor . cpp <nl> class DWALPager : public IPager2 { <nl> <nl> self - > remapUndoFuture = Void ( ) ; <nl> <nl> - int64_t flags = IAsyncFile : : OPEN_UNCACHED | IAsyncFile : : OPEN_READWRITE | IAsyncFile : : OPEN_LOCK ; <nl> + int64_t flags = IAsyncFile : : OPEN_UNCACHED | IAsyncFile : : OPEN_UNBUFFERED | IAsyncFile : : OPEN_READWRITE | IAsyncFile : : OPEN_LOCK ; <nl> state bool exists = fileExists ( self - > filename ) ; <nl> if ( ! exists ) { <nl> flags | = IAsyncFile : : OPEN_ATOMIC_WRITE_AND_CREATE | IAsyncFile : : OPEN_CREATE ; <nl> class KeyValueStoreRedwoodUnversioned : public IKeyValueStore { <nl> m_tree - > set ( keyValue ) ; <nl> } <nl> <nl> - Future < Standalone < VectorRef < KeyValueRef > > > readRange ( KeyRangeRef keys , int rowLimit = 1 < < 30 , int byteLimit = 1 < < 30 ) { <nl> + Future < Standalone < RangeResultRef > > readRange ( KeyRangeRef keys , int rowLimit = 1 < < 30 , int byteLimit = 1 < < 30 ) { <nl> debug_printf ( " READRANGE % s \ n " , printable ( keys ) . c_str ( ) ) ; <nl> return catchError ( readRange_impl ( this , keys , rowLimit , byteLimit ) ) ; <nl> } <nl> <nl> - ACTOR static Future < Standalone < VectorRef < KeyValueRef > > > readRange_impl ( KeyValueStoreRedwoodUnversioned * self , KeyRange keys , int rowLimit , int byteLimit ) { <nl> + ACTOR static Future < Standalone < RangeResultRef > > readRange_impl ( KeyValueStoreRedwoodUnversioned * self , KeyRange keys , int rowLimit , int byteLimit ) { <nl> self - > m_tree - > counts . getRanges + + ; <nl> - state Standalone < VectorRef < KeyValueRef > > result ; <nl> + state Standalone < RangeResultRef > result ; <nl> state int accumulatedBytes = 0 ; <nl> ASSERT ( byteLimit > 0 ) ; <nl> <nl> + if ( rowLimit = = 0 ) { <nl> + return result ; <nl> + } <nl> + <nl> state Reference < IStoreCursor > cur = self - > m_tree - > readAtVersion ( self - > m_tree - > getLastCommittedVersion ( ) ) ; <nl> / / Prefetch is currently only done in the forward direction <nl> state int prefetchBytes = rowLimit > 1 ? byteLimit : 0 ; <nl> <nl> - if ( rowLimit > = 0 ) { <nl> + if ( rowLimit > 0 ) { <nl> wait ( cur - > findFirstEqualOrGreater ( keys . begin , prefetchBytes ) ) ; <nl> while ( cur - > isValid ( ) & & cur - > getKey ( ) < keys . end ) { <nl> KeyValueRef kv ( KeyRef ( result . arena ( ) , cur - > getKey ( ) ) , ValueRef ( result . arena ( ) , cur - > getValue ( ) ) ) ; <nl> class KeyValueStoreRedwoodUnversioned : public IKeyValueStore { <nl> wait ( cur - > prev ( ) ) ; <nl> } <nl> } <nl> + <nl> + result . more = rowLimit = = 0 | | accumulatedBytes > = byteLimit ; <nl> + if ( result . more ) { <nl> + ASSERT ( result . size ( ) > 0 ) ; <nl> + result . readThrough = result [ result . size ( ) - 1 ] . key ; <nl> + } <nl> return result ; <nl> } <nl> <nl> mmm a / fdbserver / WorkerInterface . actor . h <nl> ppp b / fdbserver / WorkerInterface . actor . h <nl> struct Role { <nl> } <nl> } ; <nl> <nl> - void startRole ( const Role & role , UID roleId , UID workerId , std : : map < std : : string , std : : string > details = std : : map < std : : string , std : : string > ( ) , std : : string origination = " Recruited " ) ; <nl> + void startRole ( const Role & role , UID roleId , UID workerId , const std : : map < std : : string , std : : string > & details = std : : map < std : : string , std : : string > ( ) , const std : : string & origination = " Recruited " ) ; <nl> void endRole ( const Role & role , UID id , std : : string reason , bool ok = true , Error e = Error ( ) ) ; <nl> <nl> struct ServerDBInfo ; <nl> ACTOR Future < Void > masterProxyServer ( MasterProxyInterface proxy , InitializeMaste <nl> Reference < AsyncVar < ServerDBInfo > > db , std : : string whitelistBinPaths ) ; <nl> ACTOR Future < Void > tLog ( IKeyValueStore * persistentData , IDiskQueue * persistentQueue , <nl> Reference < AsyncVar < ServerDBInfo > > db , LocalityData locality , <nl> - PromiseStream < InitializeTLogRequest > tlogRequests , UID tlogId , bool restoreFromDisk , <nl> - Promise < Void > oldLog , Promise < Void > recovered , std : : string folder , <nl> + PromiseStream < InitializeTLogRequest > tlogRequests , UID tlogId , UID workerID , <nl> + bool restoreFromDisk , Promise < Void > oldLog , Promise < Void > recovered , std : : string folder , <nl> Reference < AsyncVar < bool > > degraded , Reference < AsyncVar < UID > > activeSharedTLog ) ; <nl> <nl> ACTOR Future < Void > monitorServerDBInfo ( Reference < AsyncVar < Optional < ClusterControllerFullInterface > > > ccInterface , <nl> void updateCpuProfiler ( ProfilerRequest req ) ; <nl> <nl> namespace oldTLog_4_6 { <nl> ACTOR Future < Void > tLog ( IKeyValueStore * persistentData , IDiskQueue * persistentQueue , <nl> - Reference < AsyncVar < ServerDBInfo > > db , LocalityData locality , UID tlogId ) ; <nl> + Reference < AsyncVar < ServerDBInfo > > db , LocalityData locality , UID tlogId , UID workerID ) ; <nl> } <nl> namespace oldTLog_6_0 { <nl> ACTOR Future < Void > tLog ( IKeyValueStore * persistentData , IDiskQueue * persistentQueue , <nl> Reference < AsyncVar < ServerDBInfo > > db , LocalityData locality , <nl> - PromiseStream < InitializeTLogRequest > tlogRequests , UID tlogId , bool restoreFromDisk , <nl> - Promise < Void > oldLog , Promise < Void > recovered , std : : string folder , <nl> + PromiseStream < InitializeTLogRequest > tlogRequests , UID tlogId , UID workerID , <nl> + bool restoreFromDisk , Promise < Void > oldLog , Promise < Void > recovered , std : : string folder , <nl> Reference < AsyncVar < bool > > degraded , Reference < AsyncVar < UID > > activeSharedTLog ) ; <nl> } <nl> namespace oldTLog_6_2 { <nl> ACTOR Future < Void > tLog ( IKeyValueStore * persistentData , IDiskQueue * persistentQueue , <nl> Reference < AsyncVar < ServerDBInfo > > db , LocalityData locality , <nl> - PromiseStream < InitializeTLogRequest > tlogRequests , UID tlogId , bool restoreFromDisk , <nl> - Promise < Void > oldLog , Promise < Void > recovered , std : : string folder , <nl> + PromiseStream < InitializeTLogRequest > tlogRequests , UID tlogId , UID workerID , <nl> + bool restoreFromDisk , Promise < Void > oldLog , Promise < Void > recovered , std : : string folder , <nl> Reference < AsyncVar < bool > > degraded , Reference < AsyncVar < UID > > activeSharedTLog ) ; <nl> } <nl> <nl> mmm a / fdbserver / fdbserver . actor . cpp <nl> ppp b / fdbserver / fdbserver . actor . cpp <nl> <nl> # include " fdbserver / workloads / workloads . actor . h " <nl> # include < time . h > <nl> # include " fdbserver / Status . h " <nl> - # include " fdbrpc / TLSConnection . h " <nl> # include " fdbrpc / Net2FileSystem . h " <nl> # include " fdbrpc / Platform . h " <nl> # include " fdbrpc / AsyncFileCached . actor . h " <nl> # include " fdbserver / CoroFlow . h " <nl> + # include " flow / TLSPolicy . h " <nl> # if defined ( CMAKE_BUILD ) | | ! defined ( WIN32 ) <nl> # include " versions . h " <nl> # endif <nl> <nl> # include " flow / SimpleOpt . h " <nl> # include " flow / actorcompiler . h " / / This must be the last # include . <nl> <nl> + / / clang - format off <nl> enum { <nl> OPT_CONNFILE , OPT_SEEDCONNFILE , OPT_SEEDCONNSTRING , OPT_ROLE , OPT_LISTEN , OPT_PUBLICADDR , OPT_DATAFOLDER , OPT_LOGFOLDER , OPT_PARENTPID , OPT_NEWCONSOLE , <nl> OPT_NOBOX , OPT_TESTFILE , OPT_RESTARTING , OPT_RESTORING , OPT_RANDOMSEED , OPT_KEY , OPT_MEMLIMIT , OPT_STORAGEMEMLIMIT , OPT_CACHEMEMLIMIT , OPT_MACHINEID , <nl> OPT_DCID , OPT_MACHINE_CLASS , OPT_BUGGIFY , OPT_VERSION , OPT_CRASHONERROR , OPT_HELP , OPT_NETWORKIMPL , OPT_NOBUFSTDOUT , OPT_BUFSTDOUTERR , OPT_TRACECLOCK , <nl> OPT_NUMTESTERS , OPT_DEVHELP , OPT_ROLLSIZE , OPT_MAXLOGS , OPT_MAXLOGSSIZE , OPT_KNOB , OPT_TESTSERVERS , OPT_TEST_ON_SERVERS , OPT_METRICSCONNFILE , <nl> OPT_METRICSPREFIX , OPT_LOGGROUP , OPT_LOCALITY , OPT_IO_TRUST_SECONDS , OPT_IO_TRUST_WARN_ONLY , OPT_FILESYSTEM , OPT_PROFILER_RSS_SIZE , OPT_KVFILE , <nl> - OPT_TRACE_FORMAT , OPT_WHITELIST_BINPATH <nl> + OPT_TRACE_FORMAT , OPT_WHITELIST_BINPATH , OPT_BLOB_CREDENTIAL_FILE <nl> } ; <nl> <nl> CSimpleOpt : : SOption g_rgOptions [ ] = { <nl> CSimpleOpt : : SOption g_rgOptions [ ] = { <nl> { OPT_IO_TRUST_WARN_ONLY , " - - io_trust_warn_only " , SO_NONE } , <nl> { OPT_TRACE_FORMAT , " - - trace_format " , SO_REQ_SEP } , <nl> { OPT_WHITELIST_BINPATH , " - - whitelist_binpath " , SO_REQ_SEP } , <nl> + { OPT_BLOB_CREDENTIAL_FILE , " - - blob_credential_file " , SO_REQ_SEP } , <nl> <nl> # ifndef TLS_DISABLED <nl> TLS_OPTION_FLAGS <nl> CSimpleOpt : : SOption g_rgOptions [ ] = { <nl> SO_END_OF_OPTIONS <nl> } ; <nl> <nl> + / / clang - format on <nl> + <nl> GlobalCounters g_counters ; <nl> <nl> extern void dsltest ( ) ; <nl> struct CLIOptions { <nl> int minTesterCount = 1 ; <nl> bool testOnServers = false ; <nl> <nl> - Reference < TLSOptions > tlsOptions = Reference < TLSOptions > ( new TLSOptions ) ; <nl> - std : : string tlsCertPath , tlsKeyPath , tlsCAPath , tlsPassword ; <nl> + Reference < TLSPolicy > tlsPolicy = Reference < TLSPolicy > ( new TLSPolicy ( TLSPolicy : : Is : : SERVER ) ) ; <nl> + TLSParams tlsParams ; <nl> std : : vector < std : : string > tlsVerifyPeers ; <nl> double fileIoTimeout = 0 . 0 ; <nl> bool fileIoWarnOnly = false ; <nl> uint64_t rsssize = - 1 ; <nl> + std : : vector < std : : string > blobCredentials ; / / used for fast restore workers <nl> + const char * blobCredsFromENV = nullptr ; <nl> <nl> Reference < ClusterConnectionFile > connectionFile ; <nl> Standalone < StringRef > machineId ; <nl> struct CLIOptions { <nl> case OPT_WHITELIST_BINPATH : <nl> whitelistBinPaths = args . OptionArg ( ) ; <nl> break ; <nl> + case OPT_BLOB_CREDENTIAL_FILE : <nl> + / / Add blob credential following backup agent example <nl> + blobCredentials . push_back ( args . OptionArg ( ) ) ; <nl> + printf ( " blob credential file : % s \ n " , blobCredentials . back ( ) . c_str ( ) ) ; <nl> + <nl> + blobCredsFromENV = getenv ( " FDB_BLOB_CREDENTIALS " ) ; <nl> + if ( blobCredsFromENV ! = nullptr ) { <nl> + fprintf ( stderr , " [ WARNING ] Set blob credetial via env variable is not tested yet \ n " ) ; <nl> + TraceEvent ( SevError , " FastRestoreGetBlobCredentialFile " ) <nl> + . detail ( " Reason " , " Set blob credetial via env variable is not tested yet " ) ; <nl> + StringRef t ( ( uint8_t * ) blobCredsFromENV , strlen ( blobCredsFromENV ) ) ; <nl> + do { <nl> + StringRef file = t . eat ( " : " ) ; <nl> + if ( file . size ( ) ! = 0 ) { <nl> + blobCredentials . push_back ( file . toString ( ) ) ; <nl> + } <nl> + } while ( t . size ( ) ! = 0 ) ; <nl> + } <nl> + break ; <nl> + <nl> # ifndef TLS_DISABLED <nl> - case TLSOptions : : OPT_TLS_PLUGIN : <nl> + case TLSParams : : OPT_TLS_PLUGIN : <nl> args . OptionArg ( ) ; <nl> break ; <nl> - case TLSOptions : : OPT_TLS_CERTIFICATES : <nl> - tlsCertPath = args . OptionArg ( ) ; <nl> + case TLSParams : : OPT_TLS_CERTIFICATES : <nl> + tlsParams . tlsCertPath = args . OptionArg ( ) ; <nl> break ; <nl> - case TLSOptions : : OPT_TLS_PASSWORD : <nl> - tlsPassword = args . OptionArg ( ) ; <nl> + case TLSParams : : OPT_TLS_PASSWORD : <nl> + tlsParams . tlsPassword = args . OptionArg ( ) ; <nl> break ; <nl> - case TLSOptions : : OPT_TLS_CA_FILE : <nl> - tlsCAPath = args . OptionArg ( ) ; <nl> + case TLSParams : : OPT_TLS_CA_FILE : <nl> + tlsParams . tlsCAPath = args . OptionArg ( ) ; <nl> break ; <nl> - case TLSOptions : : OPT_TLS_KEY : <nl> - tlsKeyPath = args . OptionArg ( ) ; <nl> + case TLSParams : : OPT_TLS_KEY : <nl> + tlsParams . tlsKeyPath = args . OptionArg ( ) ; <nl> break ; <nl> - case TLSOptions : : OPT_TLS_VERIFY_PEERS : <nl> + case TLSParams : : OPT_TLS_VERIFY_PEERS : <nl> tlsVerifyPeers . push_back ( args . OptionArg ( ) ) ; <nl> break ; <nl> # endif <nl> int main ( int argc , char * argv [ ] ) { <nl> startNewSimulator ( ) ; <nl> openTraceFile ( NetworkAddress ( ) , opts . rollsize , opts . maxLogsSize , opts . logFolder , " trace " , opts . logGroup ) ; <nl> } else { <nl> - g_network = newNet2 ( opts . useThreadPool , true ) ; <nl> + # ifndef TLS_DISABLED <nl> + if ( opts . tlsVerifyPeers . size ( ) ) { <nl> + opts . tlsPolicy - > set_verify_peers ( opts . tlsVerifyPeers ) ; <nl> + } <nl> + # endif <nl> + g_network = newNet2 ( opts . useThreadPool , true , opts . tlsPolicy , opts . tlsParams ) ; <nl> FlowTransport : : createInstance ( false , 1 ) ; <nl> <nl> const bool expectsPublicAddress = ( role = = FDBD | | role = = NetworkTestServer | | role = = Restore ) ; <nl> int main ( int argc , char * argv [ ] ) { <nl> openTraceFile ( opts . publicAddresses . address , opts . rollsize , opts . maxLogsSize , opts . logFolder , " trace " , <nl> opts . logGroup ) ; <nl> <nl> - # ifndef TLS_DISABLED <nl> - if ( opts . tlsCertPath . size ( ) ) opts . tlsOptions - > set_cert_file ( opts . tlsCertPath ) ; <nl> - if ( opts . tlsCAPath . size ( ) ) opts . tlsOptions - > set_ca_file ( opts . tlsCAPath ) ; <nl> - if ( opts . tlsKeyPath . size ( ) ) { <nl> - if ( opts . tlsPassword . size ( ) ) opts . tlsOptions - > set_key_password ( opts . tlsPassword ) ; <nl> - <nl> - opts . tlsOptions - > set_key_file ( opts . tlsKeyPath ) ; <nl> - } <nl> - if ( opts . tlsVerifyPeers . size ( ) ) opts . tlsOptions - > set_verify_peers ( opts . tlsVerifyPeers ) ; <nl> - <nl> - opts . tlsOptions - > register_network ( ) ; <nl> - # endif <nl> if ( expectsPublicAddress ) { <nl> for ( int ii = 0 ; ii < ( opts . publicAddresses . secondaryAddress . present ( ) ? 2 : 1 ) ; + + ii ) { <nl> const NetworkAddress & publicAddress = <nl> int main ( int argc , char * argv [ ] ) { <nl> } <nl> } <nl> } <nl> - setupAndRun ( dataFolder , opts . testFile , opts . restarting , ( isRestoring > = 1 ) , opts . whitelistBinPaths , <nl> - opts . tlsOptions ) ; <nl> + setupAndRun ( dataFolder , opts . testFile , opts . restarting , ( isRestoring > = 1 ) , opts . whitelistBinPaths ) ; <nl> g_simulator . run ( ) ; <nl> } else if ( role = = FDBD ) { <nl> - ASSERT ( opts . connectionFile ) ; <nl> - <nl> - setupSlowTaskProfiler ( ) ; <nl> - <nl> - auto dataFolder = opts . dataFolder ; <nl> - if ( ! dataFolder . size ( ) ) <nl> - dataFolder = format ( " fdb / % d / " , opts . publicAddresses . address . port ) ; / / SOMEDAY : Better default <nl> - <nl> - vector < Future < Void > > actors ( listenErrors . begin ( ) , listenErrors . end ( ) ) ; <nl> - actors . push_back ( fdbd ( opts . connectionFile , opts . localities , opts . processClass , dataFolder , dataFolder , <nl> - opts . storageMemLimit , opts . metricsConnFile , opts . metricsPrefix , opts . rsssize , <nl> - opts . whitelistBinPaths ) ) ; <nl> - / / actors . push_back ( recurring ( [ ] { } , . 001 ) ) ; / / for ASIO latency measurement <nl> + / / Call fast restore for the class FastRestoreClass . This is a short - cut to run fast restore in circus <nl> + if ( opts . processClass = = ProcessClass : : FastRestoreClass ) { <nl> + printf ( " Run as fast restore worker \ n " ) ; <nl> + ASSERT ( opts . connectionFile ) ; <nl> + auto dataFolder = opts . dataFolder ; <nl> + if ( ! dataFolder . size ( ) ) <nl> + dataFolder = format ( " fdb / % d / " , opts . publicAddresses . address . port ) ; / / SOMEDAY : Better default <nl> + <nl> + / / Update the global blob credential files list <nl> + std : : vector < std : : string > * pFiles = <nl> + ( std : : vector < std : : string > * ) g_network - > global ( INetwork : : enBlobCredentialFiles ) ; <nl> + if ( pFiles ! = nullptr ) { <nl> + for ( auto & f : opts . blobCredentials ) { <nl> + pFiles - > push_back ( f ) ; <nl> + } <nl> + } <nl> <nl> - f = stopAfter ( waitForAll ( actors ) ) ; <nl> - g_network - > run ( ) ; <nl> + vector < Future < Void > > actors ( listenErrors . begin ( ) , listenErrors . end ( ) ) ; <nl> + actors . push_back ( restoreWorker ( opts . connectionFile , opts . localities , dataFolder ) ) ; <nl> + f = stopAfter ( waitForAll ( actors ) ) ; <nl> + printf ( " Fast restore worker exits \ n " ) ; <nl> + g_network - > run ( ) ; <nl> + printf ( " g_network - > run ( ) done \ n " ) ; <nl> + } else { / / Call fdbd roles in conventional way <nl> + ASSERT ( opts . connectionFile ) ; <nl> + <nl> + setupSlowTaskProfiler ( ) ; <nl> + <nl> + auto dataFolder = opts . dataFolder ; <nl> + if ( ! dataFolder . size ( ) ) <nl> + dataFolder = format ( " fdb / % d / " , opts . publicAddresses . address . port ) ; / / SOMEDAY : Better default <nl> + <nl> + vector < Future < Void > > actors ( listenErrors . begin ( ) , listenErrors . end ( ) ) ; <nl> + actors . push_back ( fdbd ( opts . connectionFile , opts . localities , opts . processClass , dataFolder , dataFolder , <nl> + opts . storageMemLimit , opts . metricsConnFile , opts . metricsPrefix , opts . rsssize , <nl> + opts . whitelistBinPaths ) ) ; <nl> + / / actors . push_back ( recurring ( [ ] { } , . 001 ) ) ; / / for ASIO latency measurement <nl> + <nl> + f = stopAfter ( waitForAll ( actors ) ) ; <nl> + g_network - > run ( ) ; <nl> + } <nl> } else if ( role = = MultiTester ) { <nl> f = stopAfter ( runTests ( opts . connectionFile , TEST_TYPE_FROM_FILE , <nl> opts . testOnServers ? TEST_ON_SERVERS : TEST_ON_TESTERS , opts . minTesterCount , <nl> int main ( int argc , char * argv [ ] ) { <nl> f = stopAfter ( networkTestServer ( ) ) ; <nl> g_network - > run ( ) ; <nl> } else if ( role = = Restore ) { <nl> - f = stopAfter ( restoreWorker ( opts . connectionFile , opts . localities ) ) ; <nl> + f = stopAfter ( restoreWorker ( opts . connectionFile , opts . localities , opts . dataFolder ) ) ; <nl> g_network - > run ( ) ; <nl> } else if ( role = = KVFileIntegrityCheck ) { <nl> f = stopAfter ( KVFileCheck ( opts . kvFile , true ) ) ; <nl> int main ( int argc , char * argv [ ] ) { <nl> TraceEvent ( SevError , " MainError " ) . error ( e ) ; <nl> / / printf ( " \ n % d tests passed ; % d tests failed \ n " , passCount , failCount ) ; <nl> flushAndExit ( FDB_EXIT_MAIN_ERROR ) ; <nl> + } catch ( boost : : system : : system_error & e ) { <nl> + fprintf ( stderr , " boost : : system : : system_error : % s ( % d ) " , e . what ( ) , e . code ( ) . value ( ) ) ; <nl> + TraceEvent ( SevError , " MainError " ) . error ( unknown_error ( ) ) . detail ( " RootException " , e . what ( ) ) ; <nl> + / / printf ( " \ n % d tests passed ; % d tests failed \ n " , passCount , failCount ) ; <nl> + flushAndExit ( FDB_EXIT_MAIN_EXCEPTION ) ; <nl> } catch ( std : : exception & e ) { <nl> fprintf ( stderr , " std : : exception : % s \ n " , e . what ( ) ) ; <nl> TraceEvent ( SevError , " MainError " ) . error ( unknown_error ( ) ) . detail ( " RootException " , e . what ( ) ) ; <nl> mmm a / fdbserver / masterserver . actor . cpp <nl> ppp b / fdbserver / masterserver . actor . cpp <nl> ACTOR Future < Void > readTransactionSystemState ( Reference < MasterData > self , Refer <nl> <nl> TraceEvent ( " MasterRecovering " , self - > dbgid ) . detail ( " LastEpochEnd " , self - > lastEpochEnd ) . detail ( " RecoveryTransactionVersion " , self - > recoveryTransactionVersion ) ; <nl> <nl> - Standalone < VectorRef < KeyValueRef > > rawConf = wait ( self - > txnStateStore - > readRange ( configKeys ) ) ; <nl> - self - > configuration . fromKeyValues ( rawConf ) ; <nl> + Standalone < RangeResultRef > rawConf = wait ( self - > txnStateStore - > readRange ( configKeys ) ) ; <nl> + self - > configuration . fromKeyValues ( rawConf . castTo < VectorRef < KeyValueRef > > ( ) ) ; <nl> self - > originalConfiguration = self - > configuration ; <nl> self - > hasConfiguration = true ; <nl> <nl> ACTOR Future < Void > readTransactionSystemState ( Reference < MasterData > self , Refer <nl> . detail ( " Conf " , self - > configuration . toString ( ) ) <nl> . trackLatest ( " RecoveredConfig " ) ; <nl> <nl> - Standalone < VectorRef < KeyValueRef > > rawLocalities = wait ( self - > txnStateStore - > readRange ( tagLocalityListKeys ) ) ; <nl> + Standalone < RangeResultRef > rawLocalities = wait ( self - > txnStateStore - > readRange ( tagLocalityListKeys ) ) ; <nl> self - > dcId_locality . clear ( ) ; <nl> for ( auto & kv : rawLocalities ) { <nl> self - > dcId_locality [ decodeTagLocalityListKey ( kv . key ) ] = decodeTagLocalityListValue ( kv . value ) ; <nl> } <nl> <nl> - Standalone < VectorRef < KeyValueRef > > rawTags = wait ( self - > txnStateStore - > readRange ( serverTagKeys ) ) ; <nl> + Standalone < RangeResultRef > rawTags = wait ( self - > txnStateStore - > readRange ( serverTagKeys ) ) ; <nl> self - > allTags . clear ( ) ; <nl> if ( self - > lastEpochEnd > 0 ) { <nl> self - > allTags . push_back ( cacheTag ) ; <nl> ACTOR Future < Void > readTransactionSystemState ( Reference < MasterData > self , Refer <nl> } <nl> } <nl> <nl> - Standalone < VectorRef < KeyValueRef > > rawHistoryTags = wait ( self - > txnStateStore - > readRange ( serverTagHistoryKeys ) ) ; <nl> + Standalone < RangeResultRef > rawHistoryTags = wait ( self - > txnStateStore - > readRange ( serverTagHistoryKeys ) ) ; <nl> for ( auto & kv : rawHistoryTags ) { <nl> self - > allTags . push_back ( decodeServerTagValue ( kv . value ) ) ; <nl> } <nl> ACTOR Future < Void > sendInitialCommitToResolvers ( Reference < MasterData > self ) { <nl> state Sequence txnSequence = 0 ; <nl> ASSERT ( self - > recoveryTransactionVersion ) ; <nl> <nl> - state Standalone < VectorRef < KeyValueRef > > data = self - > txnStateStore - > readRange ( txnKeys , BUGGIFY ? 3 : SERVER_KNOBS - > DESIRED_TOTAL_BYTES , SERVER_KNOBS - > DESIRED_TOTAL_BYTES ) . get ( ) ; <nl> + state Standalone < RangeResultRef > data = self - > txnStateStore - > readRange ( txnKeys , BUGGIFY ? 3 : SERVER_KNOBS - > DESIRED_TOTAL_BYTES , SERVER_KNOBS - > DESIRED_TOTAL_BYTES ) . get ( ) ; <nl> state vector < Future < Void > > txnReplies ; <nl> state int64_t dataOutstanding = 0 ; <nl> loop { <nl> if ( ! data . size ( ) ) break ; <nl> ( ( KeyRangeRef & ) txnKeys ) = KeyRangeRef ( keyAfter ( data . back ( ) . key , txnKeys . arena ( ) ) , txnKeys . end ) ; <nl> - Standalone < VectorRef < KeyValueRef > > nextData = self - > txnStateStore - > readRange ( txnKeys , BUGGIFY ? 3 : SERVER_KNOBS - > DESIRED_TOTAL_BYTES , SERVER_KNOBS - > DESIRED_TOTAL_BYTES ) . get ( ) ; <nl> + Standalone < RangeResultRef > nextData = self - > txnStateStore - > readRange ( txnKeys , BUGGIFY ? 3 : SERVER_KNOBS - > DESIRED_TOTAL_BYTES , SERVER_KNOBS - > DESIRED_TOTAL_BYTES ) . get ( ) ; <nl> <nl> for ( auto & r : self - > proxies ) { <nl> TxnStateRequest req ; <nl> mmm a / fdbserver / networktest . actor . cpp <nl> ppp b / fdbserver / networktest . actor . cpp <nl> <nl> <nl> UID WLTOKEN_NETWORKTEST ( - 1 , 2 ) ; <nl> <nl> + struct LatencyStats { <nl> + using sample = double ; <nl> + double x = 0 ; <nl> + double x2 = 0 ; <nl> + double n = 0 ; <nl> + <nl> + sample tick ( ) { <nl> + / / now ( ) returns the timestamp when we were scheduled ; count <nl> + / / all that time against this sample . <nl> + return now ( ) ; <nl> + } <nl> + <nl> + void tock ( sample tick ) { <nl> + / / time_monotonic returns the timestamp when it was called ; <nl> + / / count the time it took us to be dispatched and invoke <nl> + / / timer_monotonic <nl> + double delta = timer_monotonic ( ) - tick ; <nl> + x + = delta ; <nl> + x2 + = ( delta * delta ) ; <nl> + n + + ; <nl> + } <nl> + <nl> + void reset ( ) { * this = LatencyStats ( ) ; } <nl> + double count ( ) { return n ; } <nl> + double mean ( ) { return x / n ; } <nl> + double stddev ( ) { return sqrt ( x2 / n - ( x / n ) * ( x / n ) ) ; } <nl> + } ; <nl> + <nl> NetworkTestInterface : : NetworkTestInterface ( NetworkAddress remote ) <nl> : test ( Endpoint ( { remote } , WLTOKEN_NETWORKTEST ) ) <nl> { <nl> ACTOR Future < Void > networkTestServer ( ) { <nl> state Future < Void > logging = delay ( 1 . 0 ) ; <nl> state double lastTime = now ( ) ; <nl> state int sent = 0 ; <nl> + state LatencyStats latency ; <nl> <nl> loop { <nl> choose { <nl> when ( NetworkTestRequest req = waitNext ( interf . test . getFuture ( ) ) ) { <nl> + LatencyStats : : sample sample = latency . tick ( ) ; <nl> req . reply . send ( NetworkTestReply ( Value ( std : : string ( req . replySize , ' . ' ) ) ) ) ; <nl> + latency . tock ( sample ) ; <nl> sent + + ; <nl> } <nl> when ( wait ( logging ) ) { <nl> auto spd = sent / ( now ( ) - lastTime ) ; <nl> - fprintf ( stderr , " responses per second : % f ( % f us ) \ n " , spd , 1e6 / spd ) ; <nl> + if ( FLOW_KNOBS - > NETWORK_TEST_SCRIPT_MODE ) { <nl> + fprintf ( stderr , " % f \ t % . 3f \ t % . 3f \ n " , spd , latency . mean ( ) * 1e6 , latency . stddev ( ) * 1e6 ) ; <nl> + } else { <nl> + fprintf ( stderr , " responses per second : % f ( % f us ) \ n " , spd , latency . mean ( ) * 1e6 ) ; <nl> + } <nl> + latency . reset ( ) ; <nl> lastTime = now ( ) ; <nl> sent = 0 ; <nl> logging = delay ( 1 . 0 ) ; <nl> ACTOR Future < Void > networkTestServer ( ) { <nl> } <nl> } <nl> <nl> - ACTOR Future < Void > testClient ( std : : vector < NetworkTestInterface > interfs , int * sent ) { <nl> - loop { <nl> - NetworkTestReply rep = wait ( retryBrokenPromise ( interfs [ deterministicRandom ( ) - > randomInt ( 0 , interfs . size ( ) ) ] . test , NetworkTestRequest ( LiteralStringRef ( " . " ) , FLOW_KNOBS - > NETWORK_TEST_REPLY_SIZE ) ) ) ; <nl> + static bool moreRequestsPending ( int count ) { <nl> + if ( count = = - 1 ) { <nl> + return false ; <nl> + } else { <nl> + int request_count = FLOW_KNOBS - > NETWORK_TEST_REQUEST_COUNT ; <nl> + return ( ! request_count ) | | count < request_count ; <nl> + } <nl> + } <nl> + <nl> + static bool moreLoggingNeeded ( int count , int iteration ) { <nl> + if ( FLOW_KNOBS - > NETWORK_TEST_SCRIPT_MODE ) { <nl> + return iteration < = 2 ; <nl> + } else { <nl> + return moreRequestsPending ( count ) ; <nl> + } <nl> + } <nl> + <nl> + ACTOR Future < Void > testClient ( std : : vector < NetworkTestInterface > interfs , int * sent , int * completed , <nl> + LatencyStats * latency ) { <nl> + state std : : string request_payload ( FLOW_KNOBS - > NETWORK_TEST_REQUEST_SIZE , ' . ' ) ; <nl> + state int count = FLOW_KNOBS - > NETWORK_TEST_REQUEST_COUNT ; <nl> + state LatencyStats : : sample sample ; <nl> + <nl> + while ( moreRequestsPending ( * sent ) ) { <nl> ( * sent ) + + ; <nl> + sample = latency - > tick ( ) ; <nl> + NetworkTestReply rep = wait ( <nl> + retryBrokenPromise ( interfs [ deterministicRandom ( ) - > randomInt ( 0 , interfs . size ( ) ) ] . test , <nl> + NetworkTestRequest ( StringRef ( request_payload ) , FLOW_KNOBS - > NETWORK_TEST_REPLY_SIZE ) ) ) ; <nl> + latency - > tock ( sample ) ; <nl> + ( * completed ) + + ; <nl> } <nl> + return Void ( ) ; <nl> } <nl> <nl> - ACTOR Future < Void > logger ( int * sent ) { <nl> + ACTOR Future < Void > logger ( int * sent , int * completed , LatencyStats * latency ) { <nl> state double lastTime = now ( ) ; <nl> - loop { <nl> + state int logged = 0 ; <nl> + state int iteration = 0 ; <nl> + while ( moreLoggingNeeded ( logged , + + iteration ) ) { <nl> wait ( delay ( 1 . 0 ) ) ; <nl> - auto spd = * sent / ( now ( ) - lastTime ) ; <nl> - fprintf ( stderr , " messages per second : % f \ n " , spd ) ; <nl> + auto spd = ( * completed - logged ) / ( now ( ) - lastTime ) ; <nl> + if ( FLOW_KNOBS - > NETWORK_TEST_SCRIPT_MODE ) { <nl> + if ( iteration = = 2 ) { <nl> + / / We don ' t report the first iteration because of warm - up effects . <nl> + printf ( " % f \ t % . 3f \ t % . 3f \ n " , spd , latency - > mean ( ) * 1e6 , latency - > stddev ( ) * 1e6 ) ; <nl> + } <nl> + } else { <nl> + fprintf ( stderr , " messages per second : % f ( % 6 . 3f us ) \ n " , spd , latency - > mean ( ) * 1e6 ) ; <nl> + } <nl> + latency - > reset ( ) ; <nl> lastTime = now ( ) ; <nl> - * sent = 0 ; <nl> + logged = * completed ; <nl> } <nl> + / / tell the clients to shut down <nl> + * sent = - 1 ; <nl> + return Void ( ) ; <nl> } <nl> <nl> static void networkTestnanosleep ( ) <nl> static void networkTestnanosleep ( ) <nl> tv . tv_nsec = 10 ; <nl> nanosleep ( & tv , NULL ) ; <nl> double after = timer_monotonic ( ) ; <nl> - <nl> printf ( " % 0 . 3lf " , ( after - before ) * 1e6 ) ; <nl> } <nl> <nl> ACTOR Future < Void > networkTestClient ( std : : string testServers ) { <nl> / / return Void ( ) ; <nl> } <nl> <nl> - <nl> state std : : vector < NetworkTestInterface > interfs ; <nl> state std : : vector < NetworkAddress > servers = NetworkAddress : : parseList ( testServers ) ; <nl> state int sent = 0 ; <nl> + state int completed = 0 ; <nl> + state LatencyStats latency ; <nl> <nl> for ( int i = 0 ; i < servers . size ( ) ; i + + ) { <nl> interfs . push_back ( NetworkTestInterface ( servers [ i ] ) ) ; <nl> } <nl> <nl> state std : : vector < Future < Void > > clients ; <nl> - for ( int i = 0 ; i < 30 ; i + + ) <nl> - clients . push_back ( testClient ( interfs , & sent ) ) ; <nl> - clients . push_back ( logger ( & sent ) ) ; <nl> + for ( int i = 0 ; i < FLOW_KNOBS - > NETWORK_TEST_CLIENT_COUNT ; i + + ) { <nl> + clients . push_back ( testClient ( interfs , & sent , & completed , & latency ) ) ; <nl> + } <nl> + clients . push_back ( logger ( & sent , & completed , & latency ) ) ; <nl> <nl> wait ( waitForAll ( clients ) ) ; <nl> return Void ( ) ; <nl> mmm a / fdbserver / storageserver . actor . cpp <nl> ppp b / fdbserver / storageserver . actor . cpp <nl> struct StorageServerDisk { <nl> Future < Key > readNextKeyInclusive ( KeyRef key ) { return readFirstKey ( storage , KeyRangeRef ( key , allKeys . end ) ) ; } <nl> Future < Optional < Value > > readValue ( KeyRef key , Optional < UID > debugID = Optional < UID > ( ) ) { return storage - > readValue ( key , debugID ) ; } <nl> Future < Optional < Value > > readValuePrefix ( KeyRef key , int maxLength , Optional < UID > debugID = Optional < UID > ( ) ) { return storage - > readValuePrefix ( key , maxLength , debugID ) ; } <nl> - Future < Standalone < VectorRef < KeyValueRef > > > readRange ( KeyRangeRef keys , int rowLimit = 1 < < 30 , int byteLimit = 1 < < 30 ) { return storage - > readRange ( keys , rowLimit , byteLimit ) ; } <nl> + Future < Standalone < RangeResultRef > > readRange ( KeyRangeRef keys , int rowLimit = 1 < < 30 , int byteLimit = 1 < < 30 ) { return storage - > readRange ( keys , rowLimit , byteLimit ) ; } <nl> <nl> KeyValueStoreType getKeyValueStoreType ( ) { return storage - > getType ( ) ; } <nl> StorageBytes getStorageBytes ( ) { return storage - > getStorageBytes ( ) ; } <nl> struct StorageServerDisk { <nl> void writeMutations ( MutationListRef mutations , Version debugVersion , const char * debugContext ) ; <nl> <nl> ACTOR static Future < Key > readFirstKey ( IKeyValueStore * storage , KeyRangeRef range ) { <nl> - Standalone < VectorRef < KeyValueRef > > r = wait ( storage - > readRange ( range , 1 ) ) ; <nl> + Standalone < RangeResultRef > r = wait ( storage - > readRange ( range , 1 ) ) ; <nl> if ( r . size ( ) ) return r [ 0 ] . key ; <nl> else return range . end ; <nl> } <nl> void merge ( Arena & arena , VectorRef < KeyValueRef , VecSerStrategy : : String > & output <nl> / / Combines data from base ( at an older version ) with sets from newer versions in [ start , end ) and appends the first ( up to ) | limit | rows to output <nl> / / If limit < 0 , base and output are in descending order , and start - > key ( ) > end - > key ( ) , but start is still inclusive and end is exclusive <nl> { <nl> - if ( limit = = 0 ) return ; <nl> - int originalLimit = abs ( limit ) + output . size ( ) ; <nl> + ASSERT ( limit ! = 0 ) ; <nl> + <nl> bool forward = limit > 0 ; <nl> if ( ! forward ) limit = - limit ; <nl> + int adjustedLimit = limit + output . size ( ) ; <nl> int accumulatedBytes = 0 ; <nl> <nl> KeyValueRef const * baseStart = base . begin ( ) ; <nl> KeyValueRef const * baseEnd = base . end ( ) ; <nl> - while ( baseStart ! = baseEnd & & start ! = end & & - - limit > = 0 & & accumulatedBytes < limitBytes ) { <nl> - if ( forward ? baseStart - > key < start . key ( ) : baseStart - > key > start . key ( ) ) <nl> + while ( baseStart ! = baseEnd & & start ! = end & & output . size ( ) < adjustedLimit & & accumulatedBytes < limitBytes ) { <nl> + if ( forward ? baseStart - > key < start . key ( ) : baseStart - > key > start . key ( ) ) { <nl> output . push_back_deep ( arena , * baseStart + + ) ; <nl> + } <nl> else { <nl> output . push_back_deep ( arena , KeyValueRef ( start . key ( ) , start - > getValue ( ) ) ) ; <nl> if ( baseStart - > key = = start . key ( ) ) + + baseStart ; <nl> void merge ( Arena & arena , VectorRef < KeyValueRef , VecSerStrategy : : String > & output <nl> } <nl> accumulatedBytes + = sizeof ( KeyValueRef ) + output . end ( ) [ - 1 ] . expectedSize ( ) ; <nl> } <nl> - while ( baseStart ! = baseEnd & & - - limit > = 0 & & accumulatedBytes < limitBytes ) { <nl> + while ( baseStart ! = baseEnd & & output . size ( ) < adjustedLimit & & accumulatedBytes < limitBytes ) { <nl> output . push_back_deep ( arena , * baseStart + + ) ; <nl> accumulatedBytes + = sizeof ( KeyValueRef ) + output . end ( ) [ - 1 ] . expectedSize ( ) ; <nl> } <nl> if ( ! stopAtEndOfBase ) { <nl> - while ( start ! = end & & - - limit > = 0 & & accumulatedBytes < limitBytes ) { <nl> + while ( start ! = end & & output . size ( ) < adjustedLimit & & accumulatedBytes < limitBytes ) { <nl> output . push_back_deep ( arena , KeyValueRef ( start . key ( ) , start - > getValue ( ) ) ) ; <nl> accumulatedBytes + = sizeof ( KeyValueRef ) + output . end ( ) [ - 1 ] . expectedSize ( ) ; <nl> if ( forward ) + + start ; else - - start ; <nl> } <nl> } <nl> - ASSERT ( output . size ( ) < = originalLimit ) ; <nl> } <nl> <nl> / / If limit > = 0 , it returns the first rows in the range ( sorted ascending ) , otherwise the last rows ( sorted descending ) . <nl> ACTOR Future < GetKeyValuesReply > readRange ( StorageServer * data , Version version , <nl> state KeyRef readEnd ; <nl> state Key readBeginTemp ; <nl> state int vCount ; <nl> - / / state UID rrid = deterministicRandom ( ) - > randomUniqueID ( ) ; <nl> - / / state int originalLimit = limit ; <nl> - / / state int originalLimitBytes = * pLimitBytes ; <nl> - / / state bool track = rrid . first ( ) = = 0x1bc134c2f752187cLL ; <nl> <nl> / / Check if the desired key - range intersects the cached key - ranges <nl> / / TODO Find a more efficient way to do it <nl> ACTOR Future < GetKeyValuesReply > readRange ( StorageServer * data , Version version , <nl> auto cached = data - > cachedRangeMap . intersectingRanges ( range ) ; <nl> result . cached = ( cached . begin ( ) ! = cached . end ( ) ) ; <nl> <nl> - / / FIXME : Review pLimitBytes behavior <nl> / / if ( limit > = 0 ) we are reading forward , else backward <nl> - <nl> if ( limit > = 0 ) { <nl> / / We might care about a clear beginning before start that <nl> / / runs into range <nl> ACTOR Future < GetKeyValuesReply > readRange ( StorageServer * data , Version version , <nl> <nl> vStart = view . lower_bound ( readBegin ) ; <nl> <nl> - / * if ( track ) { <nl> - printf ( " readRange ( % llx , @ % lld , ' % s ' - ' % s ' ) \ n " , data - > thisServerID . first ( ) , version , printable ( range . begin ) . c_str ( ) , printable ( range . end ) . c_str ( ) ) ; <nl> - printf ( " mvcc : \ n " ) ; <nl> - vEnd = view . upper_bound ( range . end ) ; <nl> - for ( auto r = vStart ; r ! = vEnd ; + + r ) { <nl> - if ( r - > isClearTo ( ) ) <nl> - printf ( " ' % s ' - ' % s ' cleared \ n " , printable ( r . key ( ) ) . c_str ( ) , printable ( r - > getEndKey ( ) ) . c_str ( ) ) ; <nl> - else <nl> - printf ( " ' % s ' : = ' % s ' \ n " , printable ( r . key ( ) ) . c_str ( ) , printable ( r - > getValue ( ) ) . c_str ( ) ) ; <nl> - } <nl> - } * / <nl> - <nl> while ( limit > 0 & & * pLimitBytes > 0 & & readBegin < range . end ) { <nl> - / / ASSERT ( vStart = = view . lower_bound ( readBegin ) ) ; <nl> ASSERT ( ! vStart | | vStart . key ( ) > = readBegin ) ; <nl> if ( vStart ) { auto b = vStart ; - - b ; ASSERT ( ! b | | b . key ( ) < readBegin ) ; } <nl> ASSERT ( data - > storageVersion ( ) < = version ) ; <nl> ACTOR Future < GetKeyValuesReply > readRange ( StorageServer * data , Version version , <nl> <nl> / / Read the data on disk up to vEnd ( or the end of the range ) <nl> readEnd = vEnd ? std : : min ( vEnd . key ( ) , range . end ) : range . end ; <nl> - Standalone < VectorRef < KeyValueRef > > atStorageVersion = wait ( <nl> + Standalone < RangeResultRef > atStorageVersion = wait ( <nl> data - > storage . readRange ( KeyRangeRef ( readBegin , readEnd ) , limit , * pLimitBytes ) ) ; <nl> <nl> - / * if ( track ) { <nl> - printf ( " read [ % s , % s ) : % d rows \ n " , printable ( readBegin ) . c_str ( ) , printable ( readEnd ) . c_str ( ) , atStorageVersion . size ( ) ) ; <nl> - for ( auto r = atStorageVersion . begin ( ) ; r ! = atStorageVersion . end ( ) ; + + r ) <nl> - printf ( " ' % s ' : = ' % s ' \ n " , printable ( r - > key ) . c_str ( ) , printable ( r - > value ) . c_str ( ) ) ; <nl> - } * / <nl> - <nl> ASSERT ( atStorageVersion . size ( ) < = limit ) ; <nl> if ( data - > storageVersion ( ) > version ) throw transaction_too_old ( ) ; <nl> <nl> - bool more = atStorageVersion . size ( ) ! = 0 ; <nl> - <nl> - / / merge the sets in [ vStart , vEnd ) with the sets on disk , stopping at the last key from disk if there is ' more ' <nl> + / / merge the sets in [ vStart , vEnd ) with the sets on disk , stopping at the last key from disk if we were limited <nl> int prevSize = result . data . size ( ) ; <nl> - merge ( result . arena , result . data , atStorageVersion , vStart , vEnd , vCount , limit , more , * pLimitBytes ) ; <nl> + merge ( result . arena , result . data , atStorageVersion , vStart , vEnd , vCount , limit , atStorageVersion . more , * pLimitBytes ) ; <nl> limit - = result . data . size ( ) - prevSize ; <nl> <nl> for ( auto i = result . data . begin ( ) + prevSize ; i ! = result . data . end ( ) ; i + + ) { <nl> * pLimitBytes - = sizeof ( KeyValueRef ) + i - > expectedSize ( ) ; <nl> } <nl> <nl> - / / Setup for the next iteration <nl> - if ( more ) { / / if there might be more data , begin reading right after what we already found to find out <nl> - / / if ( track ) printf ( " more \ n " ) ; <nl> - if ( ! ( limit < = 0 | | * pLimitBytes < = 0 | | result . data . end ( ) [ - 1 ] . key = = atStorageVersion . end ( ) [ - 1 ] . key ) ) <nl> - TraceEvent ( SevError , " ReadRangeIssue " , data - > thisServerID ) . detail ( " ReadBegin " , readBegin ) . detail ( " ReadEnd " , readEnd ) <nl> - . detail ( " VStart " , vStart ? vStart . key ( ) : LiteralStringRef ( " nil " ) ) . detail ( " VEnd " , vEnd ? vEnd . key ( ) : LiteralStringRef ( " nil " ) ) <nl> - . detail ( " AtStorageVersionBack " , atStorageVersion . end ( ) [ - 1 ] . key ) . detail ( " ResultBack " , result . data . end ( ) [ - 1 ] . key ) <nl> - . detail ( " Limit " , limit ) . detail ( " LimitBytes " , * pLimitBytes ) . detail ( " ResultSize " , result . data . size ( ) ) . detail ( " PrevSize " , prevSize ) ; <nl> - readBegin = readBeginTemp = keyAfter ( result . data . end ( ) [ - 1 ] . key ) ; <nl> - ASSERT ( limit < = 0 | | * pLimitBytes < = 0 | | result . data . end ( ) [ - 1 ] . key = = atStorageVersion . end ( ) [ - 1 ] . key ) ; <nl> - } else if ( vStart & & vStart - > isClearTo ( ) ) { / / if vStart is a clear , skip it . <nl> - / / if ( track ) printf ( " skip clear \ n " ) ; <nl> - readBegin = vStart - > getEndKey ( ) ; / / next disk read should start at the end of the clear <nl> + if ( limit < = 0 | | * pLimitBytes < = 0 ) { <nl> + break ; <nl> + } <nl> + <nl> + / / If we hit our limits reading from disk but then combining with MVCC gave us back more room <nl> + if ( atStorageVersion . more ) { <nl> + ASSERT ( result . data . end ( ) [ - 1 ] . key = = atStorageVersion . end ( ) [ - 1 ] . key ) ; <nl> + readBegin = readBeginTemp = keyAfter ( result . data . end ( ) [ - 1 ] . key ) ; <nl> + } else if ( vEnd & & vEnd - > isClearTo ( ) ) { <nl> + ASSERT ( vStart = = vEnd ) ; / / vStart will have been advanced by merge ( ) <nl> + ASSERT ( vEnd - > getEndKey ( ) > readBegin ) ; <nl> + readBegin = vEnd - > getEndKey ( ) ; <nl> + + vStart ; <nl> - } else { / / Otherwise , continue at readEnd <nl> - / / if ( track ) printf ( " continue \ n " ) ; <nl> - readBegin = readEnd ; <nl> - } <nl> - } <nl> - / / all but the last item are less than * pLimitBytes <nl> - ASSERT ( result . data . size ( ) = = 0 | | * pLimitBytes + result . data . end ( ) [ - 1 ] . expectedSize ( ) + sizeof ( KeyValueRef ) > 0 ) ; <nl> - / * if ( * pLimitBytes < = 0 ) <nl> - TraceEvent ( SevWarn , " ReadRangeLimitExceeded " ) <nl> - . detail ( " Version " , version ) <nl> - . detail ( " Begin " , range . begin ) <nl> - . detail ( " End " , range . end ) <nl> - . detail ( " LimitReamin " , limit ) <nl> - . detail ( " LimitBytesRemain " , * pLimitBytes ) ; * / <nl> - <nl> - / * GetKeyValuesReply correct = wait ( readRangeOld ( data , version , range , originalLimit , originalLimitBytes ) ) ; <nl> - bool prefix_equal = true ; <nl> - int totalsize = 0 ; <nl> - int first_difference = - 1 ; <nl> - for ( int i = 0 ; i < result . data . size ( ) & & i < correct . data . size ( ) ; i + + ) { <nl> - if ( result . data [ i ] ! = correct . data [ i ] ) { <nl> - first_difference = i ; <nl> - prefix_equal = false ; <nl> + } else { <nl> + ASSERT ( readEnd = = range . end ) ; <nl> break ; <nl> } <nl> - totalsize + = result . data [ i ] . expectedSize ( ) + sizeof ( KeyValueRef ) ; <nl> } <nl> - <nl> - / / for the following check <nl> - result . more = limit = = 0 | | * pLimitBytes < = 0 ; / / FIXME : Does this have to be exact ? <nl> - result . version = version ; <nl> - if ( ! ( totalsize > originalLimitBytes ? prefix_equal : result . data = = correct . data ) | | correct . more ! = result . more ) { <nl> - TraceEvent ( SevError , " IncorrectResult " , rrid ) . detail ( " Server " , data - > thisServerID ) . detail ( " CorrectRows " , correct . data . size ( ) ) <nl> - . detail ( " FirstDifference " , first_difference ) . detail ( " OriginalLimit " , originalLimit ) <nl> - . detail ( " ResultRows " , result . data . size ( ) ) . detail ( " Result0 " , result . data [ 0 ] . key ) . detail ( " Correct0 " , correct . data [ 0 ] . key ) <nl> - . detail ( " ResultN " , result . data . size ( ) ? result . data [ std : : min ( correct . data . size ( ) , result . data . size ( ) ) - 1 ] . key : " nil " ) <nl> - . detail ( " CorrectN " , correct . data . size ( ) ? correct . data [ std : : min ( correct . data . size ( ) , result . data . size ( ) ) - 1 ] . key : " nil " ) ; <nl> - } * / <nl> } else { <nl> - / / Reverse read - abandon hope alle ye who enter here <nl> - readEnd = range . end ; <nl> - <nl> - vStart = view . lastLess ( readEnd ) ; <nl> + vStart = view . lastLess ( range . end ) ; <nl> <nl> / / A clear might extend all the way to range . end <nl> - if ( vStart & & vStart - > isClearTo ( ) & & vStart - > getEndKey ( ) > = readEnd ) { <nl> + if ( vStart & & vStart - > isClearTo ( ) & & vStart - > getEndKey ( ) > = range . end ) { <nl> readEnd = vStart . key ( ) ; <nl> - - vStart ; <nl> + } else { <nl> + readEnd = range . end ; <nl> } <nl> <nl> while ( limit < 0 & & * pLimitBytes > 0 & & readEnd > range . begin ) { <nl> + ASSERT ( ! vStart | | vStart . key ( ) < readEnd ) ; <nl> + if ( vStart ) { <nl> + auto b = vStart ; <nl> + + + b ; <nl> + ASSERT ( ! b | | b . key ( ) > = readEnd ) ; <nl> + } <nl> + ASSERT ( data - > storageVersion ( ) < = version ) ; <nl> + <nl> vEnd = vStart ; <nl> vCount = 0 ; <nl> int vSize = 0 ; <nl> ACTOR Future < GetKeyValuesReply > readRange ( StorageServer * data , Version version , <nl> - - vEnd ; <nl> } <nl> <nl> - readBegin = range . begin ; <nl> - if ( vEnd ) <nl> - readBegin = std : : max ( readBegin , vEnd - > isClearTo ( ) ? vEnd - > getEndKey ( ) : vEnd . key ( ) ) ; <nl> + readBegin = vEnd ? std : : max ( vEnd - > isClearTo ( ) ? vEnd - > getEndKey ( ) : vEnd . key ( ) , range . begin ) : range . begin ; <nl> + Standalone < RangeResultRef > atStorageVersion = <nl> + wait ( data - > storage . readRange ( KeyRangeRef ( readBegin , readEnd ) , limit , * pLimitBytes ) ) ; <nl> <nl> - Standalone < VectorRef < KeyValueRef > > atStorageVersion = wait ( data - > storage . readRange ( KeyRangeRef ( readBegin , readEnd ) , limit ) ) ; <nl> + ASSERT ( atStorageVersion . size ( ) < = - limit ) ; <nl> if ( data - > storageVersion ( ) > version ) throw transaction_too_old ( ) ; <nl> <nl> int prevSize = result . data . size ( ) ; <nl> - merge ( result . arena , result . data , atStorageVersion , vStart , vEnd , vCount , limit , false , * pLimitBytes ) ; <nl> + merge ( result . arena , result . data , atStorageVersion , vStart , vEnd , vCount , limit , atStorageVersion . more , * pLimitBytes ) ; <nl> limit + = result . data . size ( ) - prevSize ; <nl> <nl> for ( auto i = result . data . begin ( ) + prevSize ; i ! = result . data . end ( ) ; i + + ) { <nl> * pLimitBytes - = sizeof ( KeyValueRef ) + i - > expectedSize ( ) ; <nl> } <nl> <nl> - vStart = vEnd ; <nl> - readEnd = readBegin ; <nl> - <nl> - if ( vStart & & vStart - > isClearTo ( ) ) { <nl> - ASSERT ( vStart . key ( ) < readEnd ) ; <nl> - readEnd = vStart . key ( ) ; <nl> + if ( limit > = 0 | | * pLimitBytes < = 0 ) { <nl> + break ; <nl> + } <nl> + <nl> + if ( atStorageVersion . more ) { <nl> + ASSERT ( result . data . end ( ) [ - 1 ] . key = = atStorageVersion . end ( ) [ - 1 ] . key ) ; <nl> + readEnd = result . data . end ( ) [ - 1 ] . key ; <nl> + } else if ( vEnd & & vEnd - > isClearTo ( ) ) { <nl> + ASSERT ( vStart = = vEnd ) ; <nl> + ASSERT ( vEnd . key ( ) < readEnd ) <nl> + readEnd = vEnd . key ( ) ; <nl> - - vStart ; <nl> + } else { <nl> + ASSERT ( readBegin = = range . begin ) ; <nl> + break ; <nl> } <nl> } <nl> } <nl> + <nl> + / / all but the last item are less than * pLimitBytes <nl> + ASSERT ( result . data . size ( ) = = 0 | | * pLimitBytes + result . data . end ( ) [ - 1 ] . expectedSize ( ) + sizeof ( KeyValueRef ) > 0 ) ; <nl> + <nl> result . more = limit = = 0 | | * pLimitBytes < = 0 ; / / FIXME : Does this have to be exact ? <nl> result . version = version ; <nl> return result ; <nl> ACTOR Future < Void > applyByteSampleResult ( StorageServer * data , IKeyValueStore * s <nl> state int totalKeys = 0 ; <nl> state int totalBytes = 0 ; <nl> loop { <nl> - Standalone < VectorRef < KeyValueRef > > bs = wait ( storage - > readRange ( KeyRangeRef ( begin , end ) , SERVER_KNOBS - > STORAGE_LIMIT_BYTES , SERVER_KNOBS - > STORAGE_LIMIT_BYTES ) ) ; <nl> - if ( results ) results - > push_back ( bs ) ; <nl> + Standalone < RangeResultRef > bs = wait ( storage - > readRange ( KeyRangeRef ( begin , end ) , SERVER_KNOBS - > STORAGE_LIMIT_BYTES , SERVER_KNOBS - > STORAGE_LIMIT_BYTES ) ) ; <nl> + if ( results ) results - > push_back ( bs . castTo < VectorRef < KeyValueRef > > ( ) ) ; <nl> int rangeSize = bs . expectedSize ( ) ; <nl> totalFetches + + ; <nl> totalKeys + = bs . size ( ) ; <nl> ACTOR Future < bool > restoreDurableState ( StorageServer * data , IKeyValueStore * sto <nl> state Future < Optional < Value > > fVersion = storage - > readValue ( persistVersion ) ; <nl> state Future < Optional < Value > > fLogProtocol = storage - > readValue ( persistLogProtocol ) ; <nl> state Future < Optional < Value > > fPrimaryLocality = storage - > readValue ( persistPrimaryLocality ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fShardAssigned = storage - > readRange ( persistShardAssignedKeys ) ; <nl> - state Future < Standalone < VectorRef < KeyValueRef > > > fShardAvailable = storage - > readRange ( persistShardAvailableKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fShardAssigned = storage - > readRange ( persistShardAssignedKeys ) ; <nl> + state Future < Standalone < RangeResultRef > > fShardAvailable = storage - > readRange ( persistShardAvailableKeys ) ; <nl> <nl> state Promise < Void > byteSampleSampleRecovered ; <nl> state Promise < Void > startByteSampleRestore ; <nl> ACTOR Future < bool > restoreDurableState ( StorageServer * data , IKeyValueStore * sto <nl> debug_checkRestoredVersion ( data - > thisServerID , version , " StorageServer " ) ; <nl> data - > setInitialVersion ( version ) ; <nl> <nl> - state Standalone < VectorRef < KeyValueRef > > available = fShardAvailable . get ( ) ; <nl> + state Standalone < RangeResultRef > available = fShardAvailable . get ( ) ; <nl> state int availableLoc ; <nl> for ( availableLoc = 0 ; availableLoc < available . size ( ) ; availableLoc + + ) { <nl> KeyRangeRef keys ( <nl> ACTOR Future < bool > restoreDurableState ( StorageServer * data , IKeyValueStore * sto <nl> wait ( yield ( ) ) ; <nl> } <nl> <nl> - state Standalone < VectorRef < KeyValueRef > > assigned = fShardAssigned . get ( ) ; <nl> + state Standalone < RangeResultRef > assigned = fShardAssigned . get ( ) ; <nl> state int assignedLoc ; <nl> for ( assignedLoc = 0 ; assignedLoc < assigned . size ( ) ; assignedLoc + + ) { <nl> KeyRangeRef keys ( <nl> ACTOR Future < Void > waitMetrics ( StorageServerMetrics * self , WaitMetricsRequest r <nl> <nl> if ( timedout ) { <nl> TEST ( true ) ; / / ShardWaitMetrics return on timeout <nl> + / / FIXME : instead of using random chance , send wrong_shard_server when the call in from waitMetricsMultiple ( requires additional information in the request ) <nl> if ( deterministicRandom ( ) - > random01 ( ) < SERVER_KNOBS - > WAIT_METRICS_WRONG_SHARD_CHANCE ) { <nl> req . reply . sendError ( wrong_shard_server ( ) ) ; <nl> } else { <nl> ACTOR Future < Void > storageServerCore ( StorageServer * self , StorageServerInterfac <nl> state double lastLoopTopTime = now ( ) ; <nl> state Future < Void > dbInfoChange = Void ( ) ; <nl> state Future < Void > checkLastUpdate = Void ( ) ; <nl> - state double updateProcessStatsDelay = SERVER_KNOBS - > UPDATE_STORAGE_PROCESS_STATS_INTERVAL ; <nl> - state Future < Void > updateProcessStatsTimer = delay ( updateProcessStatsDelay ) ; <nl> + state Future < Void > updateProcessStatsTimer = delay ( SERVER_KNOBS - > FASTRESTORE_UPDATE_PROCESS_STATS_INTERVAL ) ; <nl> <nl> actors . add ( updateStorage ( self ) ) ; <nl> actors . add ( waitFailureServer ( ssi . waitFailure . getFuture ( ) ) ) ; <nl> ACTOR Future < Void > storageServerCore ( StorageServer * self , StorageServerInterfac <nl> } <nl> when ( wait ( updateProcessStatsTimer ) ) { <nl> updateProcessStats ( self ) ; <nl> - updateProcessStatsTimer = delay ( updateProcessStatsDelay ) ; <nl> + updateProcessStatsTimer = delay ( SERVER_KNOBS - > FASTRESTORE_UPDATE_PROCESS_STATS_INTERVAL ) ; <nl> } <nl> when ( wait ( actors . getResult ( ) ) ) { } <nl> } <nl> mmm a / fdbserver / tester . actor . cpp <nl> ppp b / fdbserver / tester . actor . cpp <nl> ACTOR Future < Void > testerServerWorkload ( WorkloadRequest work , Reference < Cluster <nl> } <nl> <nl> wait ( test ) ; <nl> - <nl> + <nl> endRole ( Role : : TESTER , workIface . id ( ) , " Complete " ) ; <nl> } catch ( Error & e ) { <nl> if ( ! replied ) { <nl> vector < TestSpec > readTests ( ifstream & ifs ) { <nl> TraceEvent ( " TestParserTest " ) . detail ( " ParsedSimDrAgents " , spec . simDrAgents ) ; <nl> } else if ( attrib = = " extraDB " ) { <nl> TraceEvent ( " TestParserTest " ) . detail ( " ParsedExtraDB " , " " ) ; <nl> + } else if ( attrib = = " configureLocked " ) { <nl> + TraceEvent ( " TestParserTest " ) . detail ( " ParsedConfigureLocked " , " " ) ; <nl> } else if ( attrib = = " minimumReplication " ) { <nl> TraceEvent ( " TestParserTest " ) . detail ( " ParsedMinimumReplication " , " " ) ; <nl> } else if ( attrib = = " minimumRegions " ) { <nl> mmm a / fdbserver / worker . actor . cpp <nl> ppp b / fdbserver / worker . actor . cpp <nl> std : : string filenameFromSample ( KeyValueStoreType storeType , std : : string folder , <nl> return joinPath ( folder , sample_filename ) ; <nl> else if ( storeType = = KeyValueStoreType : : SSD_BTREE_V2 ) <nl> return joinPath ( folder , sample_filename ) ; <nl> - else if ( storeType = = KeyValueStoreType : : MEMORY | | KeyValueStoreType : : MEMORY_RADIXTREE ) <nl> + else if ( storeType = = KeyValueStoreType : : MEMORY | | storeType = = KeyValueStoreType : : MEMORY_RADIXTREE ) <nl> return joinPath ( folder , sample_filename . substr ( 0 , sample_filename . size ( ) - 5 ) ) ; <nl> - <nl> else if ( storeType = = KeyValueStoreType : : SSD_REDWOOD_V1 ) <nl> return joinPath ( folder , sample_filename ) ; <nl> UNREACHABLE ( ) ; <nl> Standalone < StringRef > roleString ( std : : set < std : : pair < std : : string , std : : string > > r <nl> return StringRef ( result ) ; <nl> } <nl> <nl> - void startRole ( const Role & role , UID roleId , UID workerId , std : : map < std : : string , std : : string > details , std : : string origination ) { <nl> + void startRole ( const Role & role , UID roleId , UID workerId , const std : : map < std : : string , std : : string > & details , const std : : string & origination ) { <nl> if ( role . includeInTraceRoles ) { <nl> addTraceRole ( role . abbreviation ) ; <nl> } <nl> ACTOR Future < Void > monitorServerDBInfo ( Reference < AsyncVar < Optional < ClusterContr <nl> TraceEvent ( " GotServerDBInfoChange " ) . detail ( " ChangeID " , localInfo . id ) . detail ( " MasterID " , localInfo . master . id ( ) ) <nl> . detail ( " RatekeeperID " , localInfo . ratekeeper . present ( ) ? localInfo . ratekeeper . get ( ) . id ( ) : UID ( ) ) <nl> . detail ( " DataDistributorID " , localInfo . distributor . present ( ) ? localInfo . distributor . get ( ) . id ( ) : UID ( ) ) ; <nl> - <nl> + <nl> localInfo . myLocality = locality ; <nl> dbInfo - > set ( localInfo ) ; <nl> } <nl> ACTOR Future < Void > workerServer ( <nl> auto & logData = sharedLogs [ SharedLogsKey ( s . tLogOptions , s . storeType ) ] ; <nl> / / FIXME : Shouldn ' t if logData . first isValid & & ! isReady , shouldn ' t we <nl> / / be sending a fake InitializeTLogRequest rather than calling tLog ( ) ? <nl> - Future < Void > tl = tLogFn ( kv , queue , dbInfo , locality , ! logData . actor . isValid ( ) | | logData . actor . isReady ( ) ? logData . requests : PromiseStream < InitializeTLogRequest > ( ) , s . storeID , true , oldLog , recovery , folder , degraded , activeSharedTLog ) ; <nl> + Future < Void > tl = tLogFn ( kv , queue , dbInfo , locality , ! logData . actor . isValid ( ) | | logData . actor . isReady ( ) ? logData . requests : PromiseStream < InitializeTLogRequest > ( ) , s . storeID , interf . id ( ) , true , oldLog , recovery , folder , degraded , activeSharedTLog ) ; <nl> recoveries . push_back ( recovery . getFuture ( ) ) ; <nl> activeSharedTLog - > set ( s . storeID ) ; <nl> <nl> ACTOR Future < Void > workerServer ( <nl> filesClosed . add ( data - > onClosed ( ) ) ; <nl> filesClosed . add ( queue - > onClosed ( ) ) ; <nl> <nl> - Future < Void > tLogCore = tLogFn ( data , queue , dbInfo , locality , logData . requests , logId , false , Promise < Void > ( ) , Promise < Void > ( ) , folder , degraded , activeSharedTLog ) ; <nl> + Future < Void > tLogCore = tLogFn ( data , queue , dbInfo , locality , logData . requests , logId , interf . id ( ) , false , Promise < Void > ( ) , Promise < Void > ( ) , folder , degraded , activeSharedTLog ) ; <nl> tLogCore = handleIOErrors ( tLogCore , data , logId ) ; <nl> tLogCore = handleIOErrors ( tLogCore , queue , logId ) ; <nl> errorForwarders . add ( forwardError ( errors , Role : : SHARED_TRANSACTION_LOG , logId , tLogCore ) ) ; <nl> ACTOR Future < Void > fileNotFoundToNever ( Future < Void > f ) { <nl> try { <nl> wait ( f ) ; <nl> return Void ( ) ; <nl> - } <nl> - catch ( Error & e ) { <nl> - if ( e . code ( ) = = error_code_file_not_found ) { <nl> + } catch ( Error & e ) { <nl> + if ( e . code ( ) = = error_code_file_not_found ) { <nl> TraceEvent ( SevWarn , " ClusterCoordinatorFailed " ) . error ( e ) ; <nl> return Never ( ) ; <nl> } <nl> ACTOR Future < UID > createAndLockProcessIdFile ( std : : string folder ) { <nl> state UID processIDUid ; <nl> platform : : createDirectory ( folder ) ; <nl> <nl> - try { <nl> - state std : : string lockFilePath = joinPath ( folder , " processId " ) ; <nl> - state ErrorOr < Reference < IAsyncFile > > lockFile = wait ( errorOr ( IAsyncFileSystem : : filesystem ( g_network ) - > open ( lockFilePath , IAsyncFile : : OPEN_READWRITE | IAsyncFile : : OPEN_LOCK , 0600 ) ) ) ; <nl> - <nl> - if ( lockFile . isError ( ) & & lockFile . getError ( ) . code ( ) = = error_code_file_not_found & & ! fileExists ( lockFilePath ) ) { <nl> - Reference < IAsyncFile > _lockFile = wait ( IAsyncFileSystem : : filesystem ( ) - > open ( lockFilePath , IAsyncFile : : OPEN_ATOMIC_WRITE_AND_CREATE | IAsyncFile : : OPEN_CREATE | IAsyncFile : : OPEN_LOCK | IAsyncFile : : OPEN_READWRITE , 0600 ) ) ; <nl> - lockFile = _lockFile ; <nl> - processIDUid = deterministicRandom ( ) - > randomUniqueID ( ) ; <nl> - BinaryWriter wr ( IncludeVersion ( ) ) ; <nl> - wr < < processIDUid ; <nl> - wait ( lockFile . get ( ) - > write ( wr . getData ( ) , wr . getLength ( ) , 0 ) ) ; <nl> - wait ( lockFile . get ( ) - > sync ( ) ) ; <nl> - } <nl> - else { <nl> - if ( lockFile . isError ( ) ) throw lockFile . getError ( ) ; / / If we ' ve failed to open the file , throw an exception <nl> + loop { <nl> + try { <nl> + state std : : string lockFilePath = joinPath ( folder , " processId " ) ; <nl> + state ErrorOr < Reference < IAsyncFile > > lockFile = wait ( errorOr ( IAsyncFileSystem : : filesystem ( g_network ) - > open ( lockFilePath , IAsyncFile : : OPEN_READWRITE | IAsyncFile : : OPEN_LOCK , 0600 ) ) ) ; <nl> + <nl> + if ( lockFile . isError ( ) & & lockFile . getError ( ) . code ( ) = = error_code_file_not_found & & ! fileExists ( lockFilePath ) ) { <nl> + Reference < IAsyncFile > _lockFile = wait ( IAsyncFileSystem : : filesystem ( ) - > open ( lockFilePath , IAsyncFile : : OPEN_ATOMIC_WRITE_AND_CREATE | IAsyncFile : : OPEN_CREATE | IAsyncFile : : OPEN_LOCK | IAsyncFile : : OPEN_READWRITE , 0600 ) ) ; <nl> + lockFile = _lockFile ; <nl> + processIDUid = deterministicRandom ( ) - > randomUniqueID ( ) ; <nl> + BinaryWriter wr ( IncludeVersion ( ) ) ; <nl> + wr < < processIDUid ; <nl> + wait ( lockFile . get ( ) - > write ( wr . getData ( ) , wr . getLength ( ) , 0 ) ) ; <nl> + wait ( lockFile . get ( ) - > sync ( ) ) ; <nl> + } <nl> + else { <nl> + if ( lockFile . isError ( ) ) throw lockFile . getError ( ) ; / / If we ' ve failed to open the file , throw an exception <nl> <nl> - int64_t fileSize = wait ( lockFile . get ( ) - > size ( ) ) ; <nl> - state Key fileData = makeString ( fileSize ) ; <nl> - wait ( success ( lockFile . get ( ) - > read ( mutateString ( fileData ) , fileSize , 0 ) ) ) ; <nl> - processIDUid = BinaryReader : : fromStringRef < UID > ( fileData , IncludeVersion ( ) ) ; <nl> + int64_t fileSize = wait ( lockFile . get ( ) - > size ( ) ) ; <nl> + state Key fileData = makeString ( fileSize ) ; <nl> + wait ( success ( lockFile . get ( ) - > read ( mutateString ( fileData ) , fileSize , 0 ) ) ) ; <nl> + try { <nl> + processIDUid = BinaryReader : : fromStringRef < UID > ( fileData , IncludeVersion ( ) ) ; <nl> + return processIDUid ; <nl> + } catch ( Error & e ) { <nl> + if ( ! g_network - > isSimulated ( ) ) { <nl> + throw ; <nl> + } <nl> + deleteFile ( lockFilePath ) ; <nl> + } <nl> + } <nl> } <nl> - } <nl> - catch ( Error & e ) { <nl> - if ( e . code ( ) ! = error_code_actor_cancelled ) { <nl> - if ( ! e . isInjectedFault ( ) ) <nl> + catch ( Error & e ) { <nl> + if ( e . code ( ) = = error_code_actor_cancelled ) { <nl> + throw ; <nl> + } <nl> + if ( ! e . isInjectedFault ( ) ) { <nl> fprintf ( stderr , " ERROR : error creating or opening process id file ` % s ' . \ n " , joinPath ( folder , " processId " ) . c_str ( ) ) ; <nl> + } <nl> TraceEvent ( SevError , " OpenProcessIdError " ) . error ( e ) ; <nl> + throw ; <nl> } <nl> - throw ; <nl> } <nl> - return processIDUid ; <nl> } <nl> <nl> ACTOR Future < Void > fdbd ( <nl> ACTOR Future < Void > fdbd ( <nl> TraceEvent ( " StartingFDBD " ) . detail ( " ZoneID " , localities . zoneId ( ) ) . detail ( " MachineId " , localities . machineId ( ) ) . detail ( " DiskPath " , dataFolder ) . detail ( " CoordPath " , coordFolder ) . detail ( " WhiteListBinPath " , whitelistBinPaths ) ; <nl> <nl> / / SOMEDAY : start the services on the machine in a staggered fashion in simulation ? <nl> - / / Endpoints should be registered first before any process trying to connect to it . So coordinationServer actor should be the first one executed before any other . <nl> - if ( coordFolder . size ( ) ) <nl> - actors . push_back ( fileNotFoundToNever ( coordinationServer ( coordFolder ) ) ) ; / / SOMEDAY : remove the fileNotFound wrapper and make DiskQueue construction safe from errors setting up their files <nl> - <nl> + / / Endpoints should be registered first before any process trying to connect to it . <nl> + / / So coordinationServer actor should be the first one executed before any other . <nl> + if ( coordFolder . size ( ) ) { <nl> + / / SOMEDAY : remove the fileNotFound wrapper and make DiskQueue construction safe from errors setting up <nl> + / / their files <nl> + actors . push_back ( fileNotFoundToNever ( coordinationServer ( coordFolder ) ) ) ; <nl> + } <nl> + <nl> state UID processIDUid = wait ( createAndLockProcessIdFile ( dataFolder ) ) ; <nl> localities . set ( LocalityData : : keyProcessId , processIDUid . toString ( ) ) ; <nl> / / Only one process can execute on a dataFolder from this point onwards <nl> mmm a / fdbserver / workloads / AtomicOps . actor . cpp <nl> ppp b / fdbserver / workloads / AtomicOps . actor . cpp <nl> <nl> # include " fdbserver / workloads / workloads . actor . h " <nl> # include " flow / actorcompiler . h " / / This must be the last # include . <nl> <nl> + / / # define SevAtomicOpDebug SevInfo <nl> + # define SevAtomicOpDebug SevVerbose <nl> + <nl> struct AtomicOpsWorkload : TestWorkload { <nl> int opNum , actorCount , nodeCount ; <nl> uint32_t opType ; <nl> struct AtomicOpsWorkload : TestWorkload { <nl> loop { <nl> int group = deterministicRandom ( ) - > randomInt ( 0 , 100 ) ; <nl> state uint64_t intValue = deterministicRandom ( ) - > randomInt ( 0 , 10000000 ) ; <nl> - Key val = StringRef ( ( const uint8_t * ) & intValue , sizeof ( intValue ) ) ; <nl> + state Key val = StringRef ( ( const uint8_t * ) & intValue , sizeof ( intValue ) ) ; <nl> state std : : pair < Key , Key > logDebugKey = self - > logDebugKey ( group ) ; <nl> int nodeIndex = deterministicRandom ( ) - > randomInt ( 0 , self - > nodeCount / 100 ) ; <nl> state Key opsKey ( format ( " ops % 08x % 08x " , group , nodeIndex ) ) ; <nl> struct AtomicOpsWorkload : TestWorkload { <nl> tr . set ( logDebugKey . second , opsKey ) ; / / set debug key ; one opsKey can have multiple logs key <nl> tr . atomicOp ( opsKey , val , self - > opType ) ; <nl> wait ( tr . commit ( ) ) ; <nl> + TraceEvent ( SevAtomicOpDebug , " AtomicOpWorker " ) <nl> + . detail ( " OpsKey " , opsKey ) <nl> + . detail ( " LogKey " , logDebugKey . first ) <nl> + . detail ( " Value " , val . toString ( ) ) ; <nl> if ( self - > opType = = MutationRef : : AddValue ) { <nl> self - > lbsum + = intValue ; <nl> self - > ubsum + = intValue ; <nl> struct AtomicOpsWorkload : TestWorkload { <nl> memcpy ( & intValue , kv . value . begin ( ) , kv . value . size ( ) ) ; <nl> opsVal [ kv . key ] = intValue ; <nl> if ( ! inRecord ) { <nl> - TraceEvent ( SevError , " MissingLogKey " ) . detail ( " OpsKey " , kv . key ) ; <nl> + TraceEvent ( SevWarnAlways , " MissingLogKey " ) . detail ( " OpsKey " , kv . key ) ; <nl> } <nl> if ( inRecord & & ( self - > actorCount = = 1 & & intValue ! = logVal [ records [ kv . key ] ] ) ) { <nl> / / When multiple actors exist , 1 opsKey can have multiple log keys <nl> mmm a / fdbserver / workloads / BackupAndParallelRestoreCorrectness . actor . cpp <nl> ppp b / fdbserver / workloads / BackupAndParallelRestoreCorrectness . actor . cpp <nl> <nl> # include " fdbclient / RestoreWorkerInterface . actor . h " <nl> # include " flow / actorcompiler . h " / / This must be the last # include . <nl> <nl> + # define TEST_ABORT_FASTRESTORE 0 <nl> + <nl> / / A workload which test the correctness of backup and restore process <nl> struct BackupAndParallelRestoreCorrectnessWorkload : TestWorkload { <nl> double backupAfter , restoreAfter , abortAndRestartAfter ; <nl> struct BackupAndParallelRestoreCorrectnessWorkload : TestWorkload { <nl> if ( BUGGIFY ) { <nl> state KeyBackedTag backupTag = makeBackupTag ( tag . toString ( ) ) ; <nl> TraceEvent ( " BARW_DoBackupWaitForRestorable " , randomID ) . detail ( " Tag " , backupTag . tagName ) ; <nl> - / / Wait until the backup is in a restorable state <nl> - state int resultWait = wait ( backupAgent - > waitBackup ( cx , backupTag . tagName , false ) ) ; <nl> - UidAndAbortedFlagT uidFlag = wait ( backupTag . getOrThrow ( cx ) ) ; <nl> - state UID logUid = uidFlag . first ; <nl> - state Reference < IBackupContainer > lastBackupContainer = <nl> - wait ( BackupConfig ( logUid ) . backupContainer ( ) . getD ( cx ) ) ; <nl> + / / Wait until the backup is in a restorable state and get the status , URL , and UID atomically <nl> + state Reference < IBackupContainer > lastBackupContainer ; <nl> + state UID lastBackupUID ; <nl> + state int resultWait = wait ( backupAgent - > waitBackup ( cx , backupTag . tagName , false , & lastBackupContainer , & lastBackupUID ) ) ; <nl> + <nl> + TraceEvent ( " BARW_DoBackupWaitForRestorable " , randomID ) . detail ( " Tag " , backupTag . tagName ) . detail ( " Result " , resultWait ) ; <nl> <nl> state bool restorable = false ; <nl> - if ( lastBackupContainer ) { <nl> - state BackupDescription desc = wait ( lastBackupContainer - > describeBackup ( ) ) ; <nl> - wait ( desc . resolveVersionTimes ( cx ) ) ; <nl> - printf ( " BackupDescription : \ n % s \ n " , desc . toString ( ) . c_str ( ) ) ; <nl> - restorable = desc . maxRestorableVersion . present ( ) ; <nl> + if ( lastBackupContainer ) { <nl> + state Future < BackupDescription > fdesc = lastBackupContainer - > describeBackup ( ) ; <nl> + wait ( ready ( fdesc ) ) ; <nl> + <nl> + if ( ! fdesc . isError ( ) ) { <nl> + state BackupDescription desc = fdesc . get ( ) ; <nl> + wait ( desc . resolveVersionTimes ( cx ) ) ; <nl> + printf ( " BackupDescription : \ n % s \ n " , desc . toString ( ) . c_str ( ) ) ; <nl> + restorable = desc . maxRestorableVersion . present ( ) ; <nl> + } <nl> } <nl> <nl> TraceEvent ( " BARW_LastBackupContainer " , randomID ) <nl> - . detail ( " BackupTag " , printable ( tag ) ) <nl> - . detail ( " LastBackupContainer " , lastBackupContainer ? lastBackupContainer - > getURL ( ) : " " ) <nl> - . detail ( " LogUid " , logUid ) <nl> - . detail ( " WaitStatus " , resultWait ) <nl> - . detail ( " Restorable " , restorable ) ; <nl> + . detail ( " BackupTag " , printable ( tag ) ) <nl> + . detail ( " LastBackupContainer " , lastBackupContainer ? lastBackupContainer - > getURL ( ) : " " ) <nl> + . detail ( " LastBackupUID " , lastBackupUID ) . detail ( " WaitStatus " , resultWait ) . detail ( " Restorable " , restorable ) ; <nl> <nl> / / Do not check the backup , if aborted <nl> if ( resultWait = = BackupAgentBase : : STATE_ABORTED ) { <nl> } <nl> / / Ensure that a backup container was found <nl> else if ( ! lastBackupContainer ) { <nl> - TraceEvent ( " BARW_MissingBackupContainer " , randomID ) <nl> - . detail ( " LogUid " , logUid ) <nl> - . detail ( " BackupTag " , printable ( tag ) ) <nl> - . detail ( " WaitStatus " , resultWait ) ; <nl> + TraceEvent ( SevError , " BARW_MissingBackupContainer " , randomID ) . detail ( " LastBackupUID " , lastBackupUID ) . detail ( " BackupTag " , printable ( tag ) ) . detail ( " WaitStatus " , resultWait ) ; <nl> printf ( " BackupCorrectnessMissingBackupContainer tag : % s status : % d \ n " , <nl> printable ( tag ) . c_str ( ) , resultWait ) ; <nl> } <nl> / / Check that backup is restorable <nl> - else { <nl> - if ( ! restorable ) { <nl> - TraceEvent ( " BARW_NotRestorable " , randomID ) <nl> - . detail ( " LogUid " , logUid ) <nl> - . detail ( " BackupTag " , printable ( tag ) ) <nl> - . detail ( " BackupFolder " , lastBackupContainer - > getURL ( ) ) <nl> - . detail ( " WaitStatus " , resultWait ) ; <nl> - printf ( " BackupCorrectnessNotRestorable : tag : % s \ n " , printable ( tag ) . c_str ( ) ) ; <nl> - } <nl> + else if ( ! restorable ) { <nl> + TraceEvent ( SevError , " BARW_NotRestorable " , randomID ) . detail ( " LastBackupUID " , lastBackupUID ) . detail ( " BackupTag " , printable ( tag ) ) <nl> + . detail ( " BackupFolder " , lastBackupContainer - > getURL ( ) ) . detail ( " WaitStatus " , resultWait ) ; <nl> + printf ( " BackupCorrectnessNotRestorable : tag : % s \ n " , printable ( tag ) . c_str ( ) ) ; <nl> } <nl> <nl> / / Abort the backup , if not the first backup because the second backup may have aborted the backup <nl> struct BackupAndParallelRestoreCorrectnessWorkload : TestWorkload { <nl> return Void ( ) ; <nl> } <nl> <nl> - <nl> / / This actor attempts to restore the database without clearing the keyspace . <nl> / / TODO : Enable this function in correctness test <nl> ACTOR static Future < Void > attemptDirtyRestore ( BackupAndParallelRestoreCorrectnessWorkload * self , Database cx , <nl> struct BackupAndParallelRestoreCorrectnessWorkload : TestWorkload { <nl> TraceEvent ( " FastRestore " ) . detail ( " TriggerRestore " , " Setting up restoreRequestTriggerKey " ) ; <nl> <nl> / / Sometimes kill and restart the restore <nl> - if ( BUGGIFY ) { <nl> + / / In real cluster , aborting a restore needs : <nl> + / / ( 1 ) kill restore cluster ; ( 2 ) clear dest . DB restore system keyspace . <nl> + / / TODO : Consider gracefully abort a restore and restart . <nl> + if ( BUGGIFY & & TEST_ABORT_FASTRESTORE ) { <nl> TraceEvent ( SevError , " FastRestore " ) . detail ( " Buggify " , " NotImplementedYet " ) ; <nl> wait ( delay ( deterministicRandom ( ) - > randomInt ( 0 , 10 ) ) ) ; <nl> for ( restoreIndex = 0 ; restoreIndex < restores . size ( ) ; restoreIndex + + ) { <nl> mmm a / fdbserver / workloads / BackupCorrectness . actor . cpp <nl> ppp b / fdbserver / workloads / BackupCorrectness . actor . cpp <nl> struct BackupAndRestoreCorrectnessWorkload : TestWorkload { <nl> state UID lastBackupUID ; <nl> state int resultWait = wait ( backupAgent - > waitBackup ( cx , backupTag . tagName , false , & lastBackupContainer , & lastBackupUID ) ) ; <nl> <nl> + TraceEvent ( " BARW_DoBackupWaitForRestorable " , randomID ) . detail ( " Tag " , backupTag . tagName ) . detail ( " Result " , resultWait ) ; <nl> + <nl> state bool restorable = false ; <nl> if ( lastBackupContainer ) { <nl> state Future < BackupDescription > fdesc = lastBackupContainer - > describeBackup ( ) ; <nl> mmm a / fdbserver / workloads / ConsistencyCheck . actor . cpp <nl> ppp b / fdbserver / workloads / ConsistencyCheck . actor . cpp <nl> struct ConsistencyCheckWorkload : TestWorkload <nl> std : : set < Optional < Key > > missingStorage ; <nl> <nl> for ( int i = 0 ; i < workers . size ( ) ; i + + ) { <nl> - if ( ! configuration . isExcludedServer ( workers [ i ] . interf . address ( ) ) & & <nl> + NetworkAddress addr = workers [ i ] . interf . tLog . getEndpoint ( ) . addresses . getTLSAddress ( ) ; <nl> + if ( ! configuration . isExcludedServer ( addr ) & & <nl> ( workers [ i ] . processClass = = ProcessClass : : StorageClass | | workers [ i ] . processClass = = ProcessClass : : UnsetClass ) ) { <nl> bool found = false ; <nl> for ( int j = 0 ; j < storageServers . size ( ) ; j + + ) { <nl> - if ( storageServers [ j ] . address ( ) = = workers [ i ] . interf . address ( ) ) { <nl> + if ( storageServers [ j ] . getValue . getEndpoint ( ) . addresses . getTLSAddress ( ) = = addr ) { <nl> found = true ; <nl> break ; <nl> } <nl> } <nl> if ( ! found ) { <nl> TraceEvent ( " ConsistencyCheck_NoStorage " ) <nl> - . detail ( " Address " , workers [ i ] . interf . address ( ) ) <nl> + . detail ( " Address " , addr ) <nl> . detail ( " ProcessClassEqualToStorageClass " , <nl> ( int ) ( workers [ i ] . processClass = = ProcessClass : : StorageClass ) ) ; <nl> missingStorage . insert ( workers [ i ] . interf . locality . dcId ( ) ) ; <nl> struct ConsistencyCheckWorkload : TestWorkload <nl> if ( ! statefulProcesses [ itr - > interf . address ( ) ] . count ( id ) ) { <nl> TraceEvent ( " ConsistencyCheck_ExtraDataStore " ) . detail ( " Address " , itr - > interf . address ( ) ) . detail ( " DataStoreID " , id ) ; <nl> if ( g_network - > isSimulated ( ) ) { <nl> - TraceEvent ( " ConsistencyCheck_RebootProcess " ) . detail ( " Address " , itr - > interf . address ( ) ) . detail ( " DataStoreID " , id ) ; <nl> - g_simulator . rebootProcess ( g_simulator . getProcessByAddress ( itr - > interf . address ( ) ) , ISimulator : : RebootProcess ) ; <nl> + / / FIXME : this is hiding the fact that we can recruit a new storage server on a location the has files left behind by a previous failure <nl> + / / this means that the process is wasting disk space until the process is rebooting <nl> + auto p = g_simulator . getProcessByAddress ( itr - > interf . address ( ) ) ; <nl> + TraceEvent ( " ConsistencyCheck_RebootProcess " ) . detail ( " Address " , itr - > interf . address ( ) ) . detail ( " DataStoreID " , id ) . detail ( " Reliable " , p - > isReliable ( ) ) ; <nl> + if ( p - > isReliable ( ) ) { <nl> + g_simulator . rebootProcess ( p , ISimulator : : RebootProcess ) ; <nl> + } else { <nl> + g_simulator . killProcess ( p , ISimulator : : KillInstantly ) ; <nl> + } <nl> } <nl> <nl> foundExtraDataStore = true ; <nl> struct ConsistencyCheckWorkload : TestWorkload <nl> std : : set < NetworkAddress > workerAddresses ; <nl> <nl> for ( const auto & it : workers ) { <nl> - ISimulator : : ProcessInfo * info = g_simulator . getProcessByAddress ( it . interf . address ( ) ) ; <nl> + NetworkAddress addr = it . interf . tLog . getEndpoint ( ) . addresses . getTLSAddress ( ) ; <nl> + ISimulator : : ProcessInfo * info = g_simulator . getProcessByAddress ( addr ) ; <nl> if ( ! info | | info - > failed ) { <nl> TraceEvent ( " ConsistencyCheck_FailedWorkerInList " ) . detail ( " Addr " , it . interf . address ( ) ) ; <nl> return false ; <nl> } <nl> - workerAddresses . insert ( NetworkAddress ( it . interf . address ( ) . ip , it . interf . address ( ) . port , true , false ) ) ; <nl> + workerAddresses . insert ( NetworkAddress ( addr . ip , addr . port , true , addr . isTLS ( ) ) ) ; <nl> } <nl> <nl> vector < ISimulator : : ProcessInfo * > all = g_simulator . getAllProcesses ( ) ; <nl> mmm a / fdbserver / workloads / DDMetricsExclude . actor . cpp <nl> ppp b / fdbserver / workloads / DDMetricsExclude . actor . cpp <nl> struct DDMetricsExcludeWorkload : TestWorkload { <nl> <nl> ACTOR static Future < double > getMovingDataAmount ( Database cx , DDMetricsExcludeWorkload * self ) { <nl> try { <nl> - StatusObject statusObj = wait ( StatusClient : : statusFetcher ( cx - > getConnectionFile ( ) ) ) ; <nl> + StatusObject statusObj = wait ( StatusClient : : statusFetcher ( cx ) ) ; <nl> StatusObjectReader statusObjCluster ; <nl> ( ( StatusObjectReader ) statusObj ) . get ( " cluster " , statusObjCluster ) ; <nl> StatusObjectReader statusObjData ; <nl> mmm a / fdbserver / workloads / KVStoreTest . actor . cpp <nl> ppp b / fdbserver / workloads / KVStoreTest . actor . cpp <nl> ACTOR Future < Void > testKVStoreMain ( KVStoreTestWorkload * workload , KVTest * ptest <nl> state Key k ; <nl> state double cst = timer ( ) ; <nl> while ( true ) { <nl> - Standalone < VectorRef < KeyValueRef > > kv = <nl> + Standalone < RangeResultRef > kv = <nl> wait ( test . store - > readRange ( KeyRangeRef ( k , LiteralStringRef ( " \ xff \ xff \ xff \ xff " ) ) , 1000 ) ) ; <nl> count + = kv . size ( ) ; <nl> if ( kv . size ( ) < 1000 ) break ; <nl> mmm a / fdbserver / workloads / LockDatabase . actor . cpp <nl> ppp b / fdbserver / workloads / LockDatabase . actor . cpp <nl> <nl> struct LockDatabaseWorkload : TestWorkload { <nl> double lockAfter , unlockAfter ; <nl> bool ok ; <nl> + bool onlyCheckLocked ; <nl> <nl> LockDatabaseWorkload ( WorkloadContext const & wcx ) <nl> : TestWorkload ( wcx ) , ok ( true ) <nl> { <nl> lockAfter = getOption ( options , LiteralStringRef ( " lockAfter " ) , 0 . 0 ) ; <nl> unlockAfter = getOption ( options , LiteralStringRef ( " unlockAfter " ) , 10 . 0 ) ; <nl> + onlyCheckLocked = getOption ( options , LiteralStringRef ( " onlyCheckLocked " ) , false ) ; <nl> ASSERT ( unlockAfter > lockAfter ) ; <nl> } <nl> <nl> struct LockDatabaseWorkload : TestWorkload { <nl> return Void ( ) ; <nl> } <nl> <nl> - virtual Future < Void > start ( Database const & cx ) { <nl> - if ( clientId = = 0 ) <nl> - return lockWorker ( cx , this ) ; <nl> + virtual Future < Void > start ( Database const & cx ) { <nl> + if ( clientId = = 0 ) return onlyCheckLocked ? timeout ( checkLocked ( cx , this ) , 60 , Void ( ) ) : lockWorker ( cx , this ) ; <nl> return Void ( ) ; <nl> } <nl> <nl> struct LockDatabaseWorkload : TestWorkload { <nl> self - > ok = false ; <nl> return Void ( ) ; <nl> } catch ( Error & e ) { <nl> + TEST ( e . code ( ) = = error_code_database_locked ) ; / / Database confirmed locked <nl> wait ( tr . onError ( e ) ) ; <nl> } <nl> } <nl> mmm a / fdbserver / workloads / ParallelRestore . actor . cpp <nl> ppp b / fdbserver / workloads / ParallelRestore . actor . cpp <nl> struct RunRestoreWorkerWorkload : TestWorkload { <nl> virtual Future < Void > setup ( Database const & cx ) { return Void ( ) ; } <nl> <nl> virtual Future < Void > start ( Database const & cx ) { <nl> - int num_myWorkers = 3 ; <nl> - TraceEvent ( " RunParallelRestoreWorkerWorkload " ) . detail ( " Start " , " RestoreAgentDB " ) ; <nl> + int num_myWorkers = SERVER_KNOBS - > FASTRESTORE_NUM_APPLIERS + SERVER_KNOBS - > FASTRESTORE_NUM_LOADERS + 1 ; <nl> + TraceEvent ( " RunParallelRestoreWorkerWorkload " ) . detail ( " Start " , " RestoreAgentDB " ) . detail ( " Workers " , num_myWorkers ) ; <nl> printf ( " RunParallelRestoreWorkerWorkload , we will start % d restore workers \ n " , num_myWorkers ) ; <nl> std : : vector < Future < Void > > myWorkers ; <nl> for ( int i = 0 ; i < num_myWorkers ; + + i ) { <nl> mmm a / fdbserver / workloads / RandomSelector . actor . cpp <nl> ppp b / fdbserver / workloads / RandomSelector . actor . cpp <nl> struct RandomSelectorWorkload : TestWorkload { <nl> myValue = format ( " % d " , deterministicRandom ( ) - > randomInt ( 0 , 10000000 ) ) ; <nl> / / TraceEvent ( " RYOWor " ) . detail ( " Key " , myKeyA ) . detail ( " Value " , myValue ) ; <nl> trRYOW . atomicOp ( StringRef ( clientID + " b / " + myKeyA ) , myValue , MutationRef : : Or ) ; <nl> - <nl> + <nl> loop { <nl> try { <nl> tr . set ( StringRef ( clientID + " z / " + myRandomIDKey ) , StringRef ( ) ) ; <nl> struct RandomSelectorWorkload : TestWorkload { <nl> myValue = format ( " % d " , deterministicRandom ( ) - > randomInt ( 0 , 10000000 ) ) ; <nl> / / TraceEvent ( " RYOWxor " ) . detail ( " Key " , myKeyA ) . detail ( " Value " , myValue ) ; <nl> trRYOW . atomicOp ( StringRef ( clientID + " b / " + myKeyA ) , myValue , MutationRef : : Xor ) ; <nl> - <nl> + <nl> loop { <nl> try { <nl> tr . set ( StringRef ( clientID + " z / " + myRandomIDKey ) , StringRef ( ) ) ; <nl> mmm a / fdbserver / workloads / ReadWrite . actor . cpp <nl> ppp b / fdbserver / workloads / ReadWrite . actor . cpp <nl> struct ReadWriteWorkload : KVWorkload { <nl> elapsed + = self - > periodicLoggingInterval ; <nl> wait ( delayUntil ( start + elapsed ) ) ; <nl> <nl> - TraceEvent ( ( self - > description ( ) + " _RowReadLatency " ) . c_str ( ) ) . detail ( " Mean " , self - > readLatencies . mean ( ) ) . detail ( " Median " , self - > readLatencies . median ( ) ) . detail ( " Percentile5 " , self - > readLatencies . percentile ( . 05 ) ) . detail ( " Percentile95 " , self - > readLatencies . percentile ( . 95 ) ) . detail ( " Count " , self - > readLatencyCount ) . detail ( " Elapsed " , elapsed ) ; <nl> - TraceEvent ( ( self - > description ( ) + " _GRVLatency " ) . c_str ( ) ) . detail ( " Mean " , self - > GRVLatencies . mean ( ) ) . detail ( " Median " , self - > GRVLatencies . median ( ) ) . detail ( " Percentile5 " , self - > GRVLatencies . percentile ( . 05 ) ) . detail ( " Percentile95 " , self - > GRVLatencies . percentile ( . 95 ) ) ; <nl> - TraceEvent ( ( self - > description ( ) + " _CommitLatency " ) . c_str ( ) ) . detail ( " Mean " , self - > commitLatencies . mean ( ) ) . detail ( " Median " , self - > commitLatencies . median ( ) ) . detail ( " Percentile5 " , self - > commitLatencies . percentile ( . 05 ) ) . detail ( " Percentile95 " , self - > commitLatencies . percentile ( . 95 ) ) ; <nl> - TraceEvent ( ( self - > description ( ) + " _TotalLatency " ) . c_str ( ) ) . detail ( " Mean " , self - > latencies . mean ( ) ) . detail ( " Median " , self - > latencies . median ( ) ) . detail ( " Percentile5 " , self - > latencies . percentile ( . 05 ) ) . detail ( " Percentile95 " , self - > latencies . percentile ( . 95 ) ) ; <nl> + TraceEvent ( ( self - > description ( ) + " _RowReadLatency " ) . c_str ( ) ) <nl> + . detail ( " Mean " , self - > readLatencies . mean ( ) ) <nl> + . detail ( " Median " , self - > readLatencies . median ( ) ) <nl> + . detail ( " Percentile5 " , self - > readLatencies . percentile ( . 05 ) ) <nl> + . detail ( " Percentile95 " , self - > readLatencies . percentile ( . 95 ) ) <nl> + . detail ( " Percentile99 " , self - > readLatencies . percentile ( . 99 ) ) <nl> + . detail ( " Percentile99_9 " , self - > readLatencies . percentile ( . 999 ) ) <nl> + . detail ( " Max " , self - > readLatencies . max ( ) ) <nl> + . detail ( " Count " , self - > readLatencyCount ) <nl> + . detail ( " Elapsed " , elapsed ) ; <nl> + <nl> + TraceEvent ( ( self - > description ( ) + " _GRVLatency " ) . c_str ( ) ) <nl> + . detail ( " Mean " , self - > GRVLatencies . mean ( ) ) <nl> + . detail ( " Median " , self - > GRVLatencies . median ( ) ) <nl> + . detail ( " Percentile5 " , self - > GRVLatencies . percentile ( . 05 ) ) <nl> + . detail ( " Percentile95 " , self - > GRVLatencies . percentile ( . 95 ) ) <nl> + . detail ( " Percentile99 " , self - > GRVLatencies . percentile ( . 99 ) ) <nl> + . detail ( " Percentile99_9 " , self - > GRVLatencies . percentile ( . 999 ) ) <nl> + . detail ( " Max " , self - > GRVLatencies . max ( ) ) ; <nl> + <nl> + TraceEvent ( ( self - > description ( ) + " _CommitLatency " ) . c_str ( ) ) <nl> + . detail ( " Mean " , self - > commitLatencies . mean ( ) ) <nl> + . detail ( " Median " , self - > commitLatencies . median ( ) ) <nl> + . detail ( " Percentile5 " , self - > commitLatencies . percentile ( . 05 ) ) <nl> + . detail ( " Percentile95 " , self - > commitLatencies . percentile ( . 95 ) ) <nl> + . detail ( " Percentile99 " , self - > commitLatencies . percentile ( . 99 ) ) <nl> + . detail ( " Percentile99_9 " , self - > commitLatencies . percentile ( . 999 ) ) <nl> + . detail ( " Max " , self - > commitLatencies . max ( ) ) ; <nl> + <nl> + TraceEvent ( ( self - > description ( ) + " _TotalLatency " ) . c_str ( ) ) <nl> + . detail ( " Mean " , self - > latencies . mean ( ) ) <nl> + . detail ( " Median " , self - > latencies . median ( ) ) <nl> + . detail ( " Percentile5 " , self - > latencies . percentile ( . 05 ) ) <nl> + . detail ( " Percentile95 " , self - > latencies . percentile ( . 95 ) ) <nl> + . detail ( " Percentile99 " , self - > latencies . percentile ( . 99 ) ) <nl> + . detail ( " Percentile99_9 " , self - > latencies . percentile ( . 999 ) ) <nl> + . detail ( " Max " , self - > latencies . max ( ) ) ; <nl> <nl> int64_t ops = ( self - > aTransactions . getValue ( ) * ( self - > readsPerTransactionA + self - > writesPerTransactionA ) ) + <nl> ( self - > bTransactions . getValue ( ) * ( self - > readsPerTransactionB + self - > writesPerTransactionB ) ) ; <nl> mmm a / fdbserver / workloads / StatusWorkload . actor . cpp <nl> ppp b / fdbserver / workloads / StatusWorkload . actor . cpp <nl> struct StatusWorkload : TestWorkload { <nl> if ( clientId ! = 0 ) <nl> return Void ( ) ; <nl> <nl> - return success ( timeout ( fetcher ( cx - > getConnectionFile ( ) , this ) , testDuration ) ) ; <nl> + return success ( timeout ( fetcher ( cx , this ) , testDuration ) ) ; <nl> } <nl> virtual Future < bool > check ( Database const & cx ) { <nl> return errors . getValue ( ) = = 0 ; <nl> struct StatusWorkload : TestWorkload { <nl> } <nl> } <nl> <nl> - ACTOR Future < Void > fetcher ( Reference < ClusterConnectionFile > connFile , StatusWorkload * self ) { <nl> + ACTOR Future < Void > fetcher ( Database cx , StatusWorkload * self ) { <nl> state double lastTime = now ( ) ; <nl> <nl> loop { <nl> struct StatusWorkload : TestWorkload { <nl> / / Since we count the requests that start , we could potentially never really hear back ? <nl> + + self - > requests ; <nl> state double issued = now ( ) ; <nl> - StatusObject result = wait ( StatusClient : : statusFetcher ( connFile ) ) ; <nl> + StatusObject result = wait ( StatusClient : : statusFetcher ( cx ) ) ; <nl> + + self - > replies ; <nl> BinaryWriter br ( AssumeVersion ( currentProtocolVersion ) ) ; <nl> save ( br , result ) ; <nl> mmm a / flow / Arena . h <nl> ppp b / flow / Arena . h <nl> class Standalone : private Arena , public T { <nl> } <nl> # endif <nl> <nl> + template < class U > Standalone < U > castTo ( ) const { <nl> + return Standalone < U > ( * this , arena ( ) ) ; <nl> + } <nl> + <nl> template < class Archive > <nl> void serialize ( Archive & ar ) { <nl> / / FIXME : something like BinaryReader ( ar ) > > arena > > * ( T * ) this ; to guarantee standalone arena ? ? ? <nl> mmm a / flow / CMakeLists . txt <nl> ppp b / flow / CMakeLists . txt <nl> set ( FLOW_SRCS <nl> ThreadSafeQueue . h <nl> Trace . cpp <nl> Trace . h <nl> + TLSPolicy . h <nl> + TLSPolicy . cpp <nl> UnitTest . cpp <nl> UnitTest . h <nl> XmlTraceLogFormatter . h <nl> set ( FLOW_SRCS <nl> configure_file ( $ { CMAKE_CURRENT_SOURCE_DIR } / SourceVersion . h . cmake $ { CMAKE_CURRENT_BINARY_DIR } / SourceVersion . h ) <nl> <nl> add_flow_target ( STATIC_LIBRARY NAME flow SRCS $ { FLOW_SRCS } ) <nl> + target_include_directories ( flow SYSTEM PUBLIC $ { CMAKE_THREAD_LIBS_INIT } ) <nl> target_include_directories ( flow PUBLIC $ { CMAKE_CURRENT_BINARY_DIR } $ { CMAKE_CURRENT_SOURCE_DIR } ) <nl> if ( NOT APPLE AND NOT WIN32 ) <nl> set ( FLOW_LIBS $ { FLOW_LIBS } rt ) <nl> elseif ( WIN32 ) <nl> target_link_libraries ( flow PUBLIC psapi . lib ) <nl> endif ( ) <nl> target_link_libraries ( flow PRIVATE $ { FLOW_LIBS } ) <nl> - target_link_libraries ( flow PUBLIC boost_target Threads : : Threads $ { CMAKE_DL_LIBS } ) <nl> if ( USE_VALGRIND ) <nl> target_link_libraries ( flow PUBLIC Valgrind ) <nl> endif ( ) <nl> endif ( ) <nl> if ( NOT WITH_TLS OR OPEN_FOR_IDE ) <nl> target_compile_definitions ( flow PUBLIC TLS_DISABLED ) <nl> else ( ) <nl> - target_link_libraries ( flow PUBLIC FDBLibTLS ) <nl> + target_link_libraries ( flow PUBLIC OpenSSL : : SSL ) <nl> + endif ( ) <nl> + target_link_libraries ( flow PUBLIC boost_target Threads : : Threads $ { CMAKE_DL_LIBS } ) <nl> + if ( USE_VALGRIND ) <nl> + target_link_libraries ( flow PUBLIC Valgrind ) <nl> endif ( ) <nl> <nl> if ( APPLE ) <nl> mmm a / flow / Knobs . cpp <nl> ppp b / flow / Knobs . cpp <nl> FlowKnobs : : FlowKnobs ( bool randomize , bool isSimulated ) { <nl> init ( MAX_RECONNECTION_TIME , 0 . 5 ) ; <nl> init ( RECONNECTION_TIME_GROWTH_RATE , 1 . 2 ) ; <nl> init ( RECONNECTION_RESET_TIME , 5 . 0 ) ; <nl> - init ( CONNECTION_ACCEPT_DELAY , 0 . 5 ) ; <nl> - init ( USE_OBJECT_SERIALIZER , 1 ) ; <nl> init ( TOO_MANY_CONNECTIONS_CLOSED_RESET_DELAY , 5 . 0 ) ; <nl> init ( TOO_MANY_CONNECTIONS_CLOSED_TIMEOUT , 20 . 0 ) ; <nl> init ( PEER_UNAVAILABLE_FOR_LONG_TIME_TIMEOUT , 3600 . 0 ) ; <nl> FlowKnobs : : FlowKnobs ( bool randomize , bool isSimulated ) { <nl> init ( TLS_SERVER_CONNECTION_THROTTLE_ATTEMPTS , 1 ) ; <nl> init ( TLS_CLIENT_CONNECTION_THROTTLE_ATTEMPTS , 0 ) ; <nl> <nl> + init ( NETWORK_TEST_CLIENT_COUNT , 30 ) ; <nl> init ( NETWORK_TEST_REPLY_SIZE , 600e3 ) ; <nl> + init ( NETWORK_TEST_REQUEST_COUNT , 0 ) ; / / 0 - > run forever <nl> + init ( NETWORK_TEST_REQUEST_SIZE , 1 ) ; <nl> + init ( NETWORK_TEST_SCRIPT_MODE , false ) ; <nl> <nl> / / AsyncFileCached <nl> init ( PAGE_CACHE_4K , 2LL < < 30 ) ; <nl> FlowKnobs : : FlowKnobs ( bool randomize , bool isSimulated ) { <nl> <nl> / / GenericActors <nl> init ( BUGGIFY_FLOW_LOCK_RELEASE_DELAY , 1 . 0 ) ; <nl> + init ( LOW_PRIORITY_DELAY_COUNT , 5 ) ; <nl> <nl> / / IAsyncFile <nl> init ( INCREMENTAL_DELETE_TRUNCATE_AMOUNT , 5e8 ) ; / / 500MB <nl> FlowKnobs : : FlowKnobs ( bool randomize , bool isSimulated ) { <nl> init ( SLOW_LOOP_CUTOFF , 15 . 0 / 1000 . 0 ) ; <nl> init ( SLOW_LOOP_SAMPLING_RATE , 0 . 1 ) ; <nl> init ( TSC_YIELD_TIME , 1000000 ) ; <nl> + init ( CERT_FILE_MAX_SIZE , 5 * 1024 * 1024 ) ; <nl> <nl> / / Network <nl> init ( PACKET_LIMIT , 100LL < < 20 ) ; <nl> FlowKnobs : : FlowKnobs ( bool randomize , bool isSimulated ) { <nl> init ( MIN_PACKET_BUFFER_FREE_BYTES , 256 ) ; <nl> init ( FLOW_TCP_NODELAY , 1 ) ; <nl> init ( FLOW_TCP_QUICKACK , 0 ) ; <nl> + init ( UNRESTRICTED_HANDSHAKE_LIMIT , 15 ) ; <nl> + init ( BOUNDED_HANDSHAKE_LIMIT , 400 ) ; <nl> <nl> / / Sim2 <nl> init ( MIN_OPEN_TIME , 0 . 0002 ) ; <nl> mmm a / flow / Knobs . h <nl> ppp b / flow / Knobs . h <nl> class FlowKnobs : public Knobs { <nl> double MAX_RECONNECTION_TIME ; <nl> double RECONNECTION_TIME_GROWTH_RATE ; <nl> double RECONNECTION_RESET_TIME ; <nl> - double CONNECTION_ACCEPT_DELAY ; <nl> - int USE_OBJECT_SERIALIZER ; <nl> <nl> int TLS_CERT_REFRESH_DELAY_SECONDS ; <nl> double TLS_SERVER_CONNECTION_THROTTLE_TIMEOUT ; <nl> class FlowKnobs : public Knobs { <nl> int TLS_SERVER_CONNECTION_THROTTLE_ATTEMPTS ; <nl> int TLS_CLIENT_CONNECTION_THROTTLE_ATTEMPTS ; <nl> <nl> + int NETWORK_TEST_CLIENT_COUNT ; <nl> int NETWORK_TEST_REPLY_SIZE ; <nl> - <nl> + int NETWORK_TEST_REQUEST_COUNT ; <nl> + int NETWORK_TEST_REQUEST_SIZE ; <nl> + bool NETWORK_TEST_SCRIPT_MODE ; <nl> + <nl> / / AsyncFileCached <nl> int64_t PAGE_CACHE_4K ; <nl> int64_t PAGE_CACHE_64K ; <nl> class FlowKnobs : public Knobs { <nl> <nl> / / GenericActors <nl> double BUGGIFY_FLOW_LOCK_RELEASE_DELAY ; <nl> + int LOW_PRIORITY_DELAY_COUNT ; <nl> <nl> / / IAsyncFile <nl> int64_t INCREMENTAL_DELETE_TRUNCATE_AMOUNT ; <nl> class FlowKnobs : public Knobs { <nl> double SLOW_LOOP_SAMPLING_RATE ; <nl> int64_t TSC_YIELD_TIME ; <nl> int64_t REACTOR_FLAGS ; <nl> + int CERT_FILE_MAX_SIZE ; <nl> <nl> / / Network <nl> int64_t PACKET_LIMIT ; <nl> class FlowKnobs : public Knobs { <nl> int MIN_PACKET_BUFFER_FREE_BYTES ; <nl> int FLOW_TCP_NODELAY ; <nl> int FLOW_TCP_QUICKACK ; <nl> + int UNRESTRICTED_HANDSHAKE_LIMIT ; <nl> + int BOUNDED_HANDSHAKE_LIMIT ; <nl> <nl> / / Sim2 <nl> / / FIMXE : more parameters could be factored out <nl> mmm a / flow / Net2 . actor . cpp <nl> ppp b / flow / Net2 . actor . cpp <nl> <nl> # include " flow / AsioReactor . h " <nl> # include " flow / Profiler . h " <nl> # include " flow / ProtocolVersion . h " <nl> + # include " flow / TLSPolicy . h " <nl> <nl> # ifdef WIN32 <nl> # include < mmsystem . h > <nl> intptr_t g_stackYieldLimit = 0 ; <nl> <nl> using namespace boost : : asio : : ip ; <nl> <nl> - <nl> # if defined ( __linux__ ) <nl> # include < execinfo . h > <nl> <nl> thread_local INetwork * thread_network = 0 ; <nl> class Net2 sealed : public INetwork , public INetworkConnections { <nl> <nl> public : <nl> - Net2 ( bool useThreadPool , bool useMetrics ) ; <nl> + Net2 ( bool useThreadPool , bool useMetrics , Reference < TLSPolicy > policy , const TLSParams & tlsParams ) ; <nl> void run ( ) ; <nl> void initMetrics ( ) ; <nl> <nl> class Net2 sealed : public INetwork , public INetworkConnections { <nl> <nl> / / INetwork interface <nl> virtual double now ( ) { return currentTime ; } ; <nl> + virtual double timer ( ) { return : : timer ( ) ; } ; <nl> virtual Future < Void > delay ( double seconds , TaskPriority taskId ) ; <nl> virtual Future < class Void > yield ( TaskPriority taskID ) ; <nl> virtual bool check_yield ( TaskPriority taskId ) ; <nl> class Net2 sealed : public INetwork , public INetworkConnections { <nl> / / private : <nl> <nl> ASIOReactor reactor ; <nl> + # ifndef TLS_DISABLED <nl> + boost : : asio : : ssl : : context sslContext ; <nl> + # endif <nl> + std : : string tlsPassword ; <nl> + <nl> + std : : string get_password ( ) const { <nl> + return tlsPassword ; <nl> + } <nl> + <nl> INetworkConnections * network ; / / initially this , but can be changed <nl> <nl> int64_t tsc_begin , tsc_end ; <nl> class BindPromise { <nl> try { <nl> if ( error ) { <nl> / / Log the error . . . <nl> - TraceEvent ( SevWarn , errContext , errID ) . suppressFor ( 1 . 0 ) . detail ( " ErrorCode " , error . value ( ) ) . detail ( " Message " , error . message ( ) ) ; <nl> + TraceEvent ( SevWarn , errContext , errID ) . suppressFor ( 1 . 0 ) . detail ( " ErrorCode " , error . value ( ) ) . detail ( " Message " , error . message ( ) ) <nl> + # ifndef TLS_DISABLED <nl> + . detail ( " WhichMeans " , TLSPolicy : : ErrorString ( error ) ) <nl> + # endif <nl> + ; <nl> p . sendError ( connection_failed ( ) ) ; <nl> } else <nl> p . send ( Void ( ) ) ; <nl> class Connection : public IConnection , ReferenceCounted < Connection > { <nl> init ( ) ; <nl> } <nl> <nl> + virtual Future < Void > acceptHandshake ( ) { return Void ( ) ; } <nl> + <nl> + virtual Future < Void > connectHandshake ( ) { return Void ( ) ; } <nl> + <nl> / / returns when write ( ) can write at least one byte <nl> virtual Future < Void > onWritable ( ) { <nl> + + g_net2 - > countWriteProbes ; <nl> class Listener : public IListener , ReferenceCounted < Listener > { <nl> } <nl> } ; <nl> <nl> + # ifndef TLS_DISABLED <nl> + typedef boost : : asio : : ssl : : stream < boost : : asio : : ip : : tcp : : socket & > ssl_socket ; <nl> + <nl> + class SSLConnection : public IConnection , ReferenceCounted < SSLConnection > { <nl> + public : <nl> + virtual void addref ( ) { ReferenceCounted < SSLConnection > : : addref ( ) ; } <nl> + virtual void delref ( ) { ReferenceCounted < SSLConnection > : : delref ( ) ; } <nl> + <nl> + virtual void close ( ) { <nl> + closeSocket ( ) ; <nl> + } <nl> + <nl> + explicit SSLConnection ( boost : : asio : : io_service & io_service , boost : : asio : : ssl : : context & context ) <nl> + : id ( nondeterministicRandom ( ) - > randomUniqueID ( ) ) , socket ( io_service ) , ssl_sock ( socket , context ) <nl> + { <nl> + } <nl> + <nl> + / / This is not part of the IConnection interface , because it is wrapped by INetwork : : connect ( ) <nl> + ACTOR static Future < Reference < IConnection > > connect ( boost : : asio : : io_service * ios , boost : : asio : : ssl : : context * context , NetworkAddress addr ) { <nl> + std : : pair < IPAddress , uint16_t > peerIP = std : : make_pair ( addr . ip , addr . port ) ; <nl> + auto iter ( g_network - > networkInfo . serverTLSConnectionThrottler . find ( peerIP ) ) ; <nl> + if ( iter ! = g_network - > networkInfo . serverTLSConnectionThrottler . end ( ) ) { <nl> + if ( now ( ) < iter - > second . second ) { <nl> + if ( iter - > second . first > = FLOW_KNOBS - > TLS_CLIENT_CONNECTION_THROTTLE_ATTEMPTS ) { <nl> + TraceEvent ( " TLSOutgoingConnectionThrottlingWarning " ) . suppressFor ( 1 . 0 ) . detail ( " PeerIP " , addr ) ; <nl> + wait ( delay ( FLOW_KNOBS - > CONNECTION_MONITOR_TIMEOUT ) ) ; <nl> + throw connection_failed ( ) ; <nl> + } <nl> + } else { <nl> + g_network - > networkInfo . serverTLSConnectionThrottler . erase ( peerIP ) ; <nl> + } <nl> + } <nl> + <nl> + state Reference < SSLConnection > self ( new SSLConnection ( * ios , * context ) ) ; <nl> + self - > peer_address = addr ; <nl> + <nl> + try { <nl> + auto to = tcpEndpoint ( self - > peer_address ) ; <nl> + BindPromise p ( " N2_ConnectError " , self - > id ) ; <nl> + Future < Void > onConnected = p . getFuture ( ) ; <nl> + self - > socket . async_connect ( to , std : : move ( p ) ) ; <nl> + <nl> + wait ( onConnected ) ; <nl> + self - > init ( ) ; <nl> + return self ; <nl> + } catch ( Error & e ) { <nl> + / / Either the connection failed , or was cancelled by the caller <nl> + self - > closeSocket ( ) ; <nl> + throw ; <nl> + } <nl> + } <nl> + <nl> + / / This is not part of the IConnection interface , because it is wrapped by IListener : : accept ( ) <nl> + void accept ( NetworkAddress peerAddr ) { <nl> + this - > peer_address = peerAddr ; <nl> + init ( ) ; <nl> + } <nl> + <nl> + ACTOR static void doAcceptHandshake ( Reference < SSLConnection > self , Promise < Void > connected ) { <nl> + try { <nl> + state std : : pair < IPAddress , uint16_t > peerIP = std : : make_pair ( self - > getPeerAddress ( ) . ip , static_cast < uint16_t > ( 0 ) ) ; <nl> + auto iter ( g_network - > networkInfo . serverTLSConnectionThrottler . find ( peerIP ) ) ; <nl> + if ( iter ! = g_network - > networkInfo . serverTLSConnectionThrottler . end ( ) ) { <nl> + if ( now ( ) < iter - > second . second ) { <nl> + if ( iter - > second . first > = FLOW_KNOBS - > TLS_SERVER_CONNECTION_THROTTLE_ATTEMPTS ) { <nl> + TraceEvent ( " TLSIncomingConnectionThrottlingWarning " ) . suppressFor ( 1 . 0 ) . detail ( " PeerIP " , peerIP . first . toString ( ) ) ; <nl> + wait ( delay ( FLOW_KNOBS - > CONNECTION_MONITOR_TIMEOUT ) ) ; <nl> + self - > closeSocket ( ) ; <nl> + connected . sendError ( connection_failed ( ) ) ; <nl> + return ; <nl> + } <nl> + } else { <nl> + g_network - > networkInfo . serverTLSConnectionThrottler . erase ( peerIP ) ; <nl> + } <nl> + } <nl> + <nl> + int64_t permitNumber = wait ( g_network - > networkInfo . handshakeLock - > take ( ) ) ; <nl> + state BoundedFlowLock : : Releaser releaser ( g_network - > networkInfo . handshakeLock , permitNumber ) ; <nl> + <nl> + BindPromise p ( " N2_AcceptHandshakeError " , UID ( ) ) ; <nl> + auto onHandshook = p . getFuture ( ) ; <nl> + self - > getSSLSocket ( ) . async_handshake ( boost : : asio : : ssl : : stream_base : : server , std : : move ( p ) ) ; <nl> + wait ( onHandshook ) ; <nl> + wait ( delay ( 0 , TaskPriority : : Handshake ) ) ; <nl> + connected . send ( Void ( ) ) ; <nl> + } catch ( . . . ) { <nl> + auto iter ( g_network - > networkInfo . serverTLSConnectionThrottler . find ( peerIP ) ) ; <nl> + if ( iter ! = g_network - > networkInfo . serverTLSConnectionThrottler . end ( ) ) { <nl> + iter - > second . first + + ; <nl> + } else { <nl> + g_network - > networkInfo . serverTLSConnectionThrottler [ peerIP ] = std : : make_pair ( 0 , now ( ) + FLOW_KNOBS - > TLS_SERVER_CONNECTION_THROTTLE_TIMEOUT ) ; <nl> + } <nl> + self - > closeSocket ( ) ; <nl> + connected . sendError ( connection_failed ( ) ) ; <nl> + } <nl> + } <nl> + <nl> + ACTOR static Future < Void > acceptHandshakeWrapper ( Reference < SSLConnection > self ) { <nl> + Promise < Void > connected ; <nl> + doAcceptHandshake ( self , connected ) ; <nl> + try { <nl> + wait ( connected . getFuture ( ) ) ; <nl> + return Void ( ) ; <nl> + } catch ( Error & e ) { <nl> + / / Either the connection failed , or was cancelled by the caller <nl> + self - > closeSocket ( ) ; <nl> + throw ; <nl> + } <nl> + } <nl> + <nl> + virtual Future < Void > acceptHandshake ( ) { <nl> + return acceptHandshakeWrapper ( Reference < SSLConnection > : : addRef ( this ) ) ; <nl> + } <nl> + <nl> + ACTOR static void doConnectHandshake ( Reference < SSLConnection > self , Promise < Void > connected ) { <nl> + try { <nl> + int64_t permitNumber = wait ( g_network - > networkInfo . handshakeLock - > take ( ) ) ; <nl> + state BoundedFlowLock : : Releaser releaser ( g_network - > networkInfo . handshakeLock , permitNumber ) ; <nl> + <nl> + BindPromise p ( " N2_ConnectHandshakeError " , self - > id ) ; <nl> + Future < Void > onHandshook = p . getFuture ( ) ; <nl> + self - > ssl_sock . async_handshake ( boost : : asio : : ssl : : stream_base : : client , std : : move ( p ) ) ; <nl> + wait ( onHandshook ) ; <nl> + wait ( delay ( 0 , TaskPriority : : Handshake ) ) ; <nl> + connected . send ( Void ( ) ) ; <nl> + } catch ( . . . ) { <nl> + std : : pair < IPAddress , uint16_t > peerIP = std : : make_pair ( self - > peer_address . ip , self - > peer_address . port ) ; <nl> + auto iter ( g_network - > networkInfo . serverTLSConnectionThrottler . find ( peerIP ) ) ; <nl> + if ( iter ! = g_network - > networkInfo . serverTLSConnectionThrottler . end ( ) ) { <nl> + iter - > second . first + + ; <nl> + } else { <nl> + g_network - > networkInfo . serverTLSConnectionThrottler [ peerIP ] = std : : make_pair ( 0 , now ( ) + FLOW_KNOBS - > TLS_CLIENT_CONNECTION_THROTTLE_TIMEOUT ) ; <nl> + } <nl> + self - > closeSocket ( ) ; <nl> + connected . sendError ( connection_failed ( ) ) ; <nl> + } <nl> + } <nl> + <nl> + ACTOR static Future < Void > connectHandshakeWrapper ( Reference < SSLConnection > self ) { <nl> + Promise < Void > connected ; <nl> + doConnectHandshake ( self , connected ) ; <nl> + try { <nl> + wait ( connected . getFuture ( ) ) ; <nl> + return Void ( ) ; <nl> + } catch ( Error & e ) { <nl> + / / Either the connection failed , or was cancelled by the caller <nl> + self - > closeSocket ( ) ; <nl> + throw ; <nl> + } <nl> + } <nl> + <nl> + virtual Future < Void > connectHandshake ( ) { <nl> + return connectHandshakeWrapper ( Reference < SSLConnection > : : addRef ( this ) ) ; <nl> + } <nl> + <nl> + / / returns when write ( ) can write at least one byte <nl> + virtual Future < Void > onWritable ( ) { <nl> + + + g_net2 - > countWriteProbes ; <nl> + BindPromise p ( " N2_WriteProbeError " , id ) ; <nl> + auto f = p . getFuture ( ) ; <nl> + socket . async_write_some ( boost : : asio : : null_buffers ( ) , std : : move ( p ) ) ; <nl> + return f ; <nl> + } <nl> + <nl> + / / returns when read ( ) can read at least one byte <nl> + virtual Future < Void > onReadable ( ) { <nl> + + + g_net2 - > countReadProbes ; <nl> + BindPromise p ( " N2_ReadProbeError " , id ) ; <nl> + auto f = p . getFuture ( ) ; <nl> + socket . async_read_some ( boost : : asio : : null_buffers ( ) , std : : move ( p ) ) ; <nl> + return f ; <nl> + } <nl> + <nl> + / / Reads as many bytes as possible from the read buffer into [ begin , end ) and returns the number of bytes read ( might be 0 ) <nl> + virtual int read ( uint8_t * begin , uint8_t * end ) { <nl> + boost : : system : : error_code err ; <nl> + + + g_net2 - > countReads ; <nl> + size_t toRead = end - begin ; <nl> + size_t size = ssl_sock . read_some ( boost : : asio : : mutable_buffers_1 ( begin , toRead ) , err ) ; <nl> + g_net2 - > bytesReceived + = size ; <nl> + / / TraceEvent ( " ConnRead " , this - > id ) . detail ( " Bytes " , size ) ; <nl> + if ( err ) { <nl> + if ( err = = boost : : asio : : error : : would_block ) { <nl> + + + g_net2 - > countWouldBlock ; <nl> + return 0 ; <nl> + } <nl> + onReadError ( err ) ; <nl> + throw connection_failed ( ) ; <nl> + } <nl> + ASSERT ( size ) ; / / If the socket is closed , we expect an ' eof ' error , not a zero return value <nl> + <nl> + return size ; <nl> + } <nl> + <nl> + / / Writes as many bytes as possible from the given SendBuffer chain into the write buffer and returns the number of bytes written ( might be 0 ) <nl> + virtual int write ( SendBuffer const * data , int limit ) { <nl> + boost : : system : : error_code err ; <nl> + + + g_net2 - > countWrites ; <nl> + <nl> + size_t sent = ssl_sock . write_some ( boost : : iterator_range < SendBufferIterator > ( SendBufferIterator ( data , limit ) , SendBufferIterator ( ) ) , err ) ; <nl> + <nl> + if ( err ) { <nl> + / / Since there was an error , sent ' s value can ' t be used to infer that the buffer has data and the limit is positive so check explicitly . <nl> + ASSERT ( limit > 0 ) ; <nl> + bool notEmpty = false ; <nl> + for ( auto p = data ; p ; p = p - > next ) <nl> + if ( p - > bytes_written - p - > bytes_sent > 0 ) { <nl> + notEmpty = true ; <nl> + break ; <nl> + } <nl> + ASSERT ( notEmpty ) ; <nl> + <nl> + if ( err = = boost : : asio : : error : : would_block ) { <nl> + + + g_net2 - > countWouldBlock ; <nl> + return 0 ; <nl> + } <nl> + onWriteError ( err ) ; <nl> + throw connection_failed ( ) ; <nl> + } <nl> + <nl> + ASSERT ( sent ) ; / / Make sure data was sent , and also this check will fail if the buffer chain was empty or the limit was not > 0 . <nl> + return sent ; <nl> + } <nl> + <nl> + virtual NetworkAddress getPeerAddress ( ) { return peer_address ; } <nl> + <nl> + virtual UID getDebugID ( ) { return id ; } <nl> + <nl> + tcp : : socket & getSocket ( ) { return socket ; } <nl> + <nl> + ssl_socket & getSSLSocket ( ) { return ssl_sock ; } <nl> + private : <nl> + UID id ; <nl> + tcp : : socket socket ; <nl> + ssl_socket ssl_sock ; <nl> + NetworkAddress peer_address ; <nl> + <nl> + struct SendBufferIterator { <nl> + typedef boost : : asio : : const_buffer value_type ; <nl> + typedef std : : forward_iterator_tag iterator_category ; <nl> + typedef size_t difference_type ; <nl> + typedef boost : : asio : : const_buffer * pointer ; <nl> + typedef boost : : asio : : const_buffer & reference ; <nl> + <nl> + SendBuffer const * p ; <nl> + int limit ; <nl> + <nl> + SendBufferIterator ( SendBuffer const * p = 0 , int limit = std : : numeric_limits < int > : : max ( ) ) : p ( p ) , limit ( limit ) { <nl> + ASSERT ( limit > 0 ) ; <nl> + } <nl> + <nl> + bool operator = = ( SendBufferIterator const & r ) const { return p = = r . p ; } <nl> + bool operator ! = ( SendBufferIterator const & r ) const { return p ! = r . p ; } <nl> + void operator + + ( ) { <nl> + limit - = p - > bytes_written - p - > bytes_sent ; <nl> + if ( limit > 0 ) <nl> + p = p - > next ; <nl> + else <nl> + p = NULL ; <nl> + } <nl> + <nl> + boost : : asio : : const_buffer operator * ( ) const { <nl> + return boost : : asio : : const_buffer ( p - > data + p - > bytes_sent , std : : min ( limit , p - > bytes_written - p - > bytes_sent ) ) ; <nl> + } <nl> + } ; <nl> + <nl> + void init ( ) { <nl> + / / Socket settings that have to be set after connect or accept succeeds <nl> + socket . non_blocking ( true ) ; <nl> + socket . set_option ( boost : : asio : : ip : : tcp : : no_delay ( true ) ) ; <nl> + platform : : setCloseOnExec ( socket . native_handle ( ) ) ; <nl> + } <nl> + <nl> + void closeSocket ( ) { <nl> + boost : : system : : error_code cancelError ; <nl> + socket . cancel ( cancelError ) ; <nl> + boost : : system : : error_code closeError ; <nl> + socket . close ( closeError ) ; <nl> + boost : : system : : error_code shutdownError ; <nl> + ssl_sock . shutdown ( shutdownError ) ; <nl> + } <nl> + <nl> + void onReadError ( const boost : : system : : error_code & error ) { <nl> + TraceEvent ( SevWarn , " N2_ReadError " , id ) . suppressFor ( 1 . 0 ) . detail ( " Message " , error . value ( ) ) ; <nl> + closeSocket ( ) ; <nl> + } <nl> + void onWriteError ( const boost : : system : : error_code & error ) { <nl> + TraceEvent ( SevWarn , " N2_WriteError " , id ) . suppressFor ( 1 . 0 ) . detail ( " Message " , error . value ( ) ) ; <nl> + closeSocket ( ) ; <nl> + } <nl> + } ; <nl> + <nl> + class SSLListener : public IListener , ReferenceCounted < SSLListener > { <nl> + NetworkAddress listenAddress ; <nl> + tcp : : acceptor acceptor ; <nl> + boost : : asio : : ssl : : context * context ; <nl> + <nl> + public : <nl> + SSLListener ( boost : : asio : : io_service & io_service , boost : : asio : : ssl : : context * context , NetworkAddress listenAddress ) <nl> + : listenAddress ( listenAddress ) , acceptor ( io_service , tcpEndpoint ( listenAddress ) ) , context ( context ) <nl> + { <nl> + platform : : setCloseOnExec ( acceptor . native_handle ( ) ) ; <nl> + } <nl> + <nl> + virtual void addref ( ) { ReferenceCounted < SSLListener > : : addref ( ) ; } <nl> + virtual void delref ( ) { ReferenceCounted < SSLListener > : : delref ( ) ; } <nl> + <nl> + / / Returns one incoming connection when it is available <nl> + virtual Future < Reference < IConnection > > accept ( ) { <nl> + return doAccept ( this ) ; <nl> + } <nl> + <nl> + virtual NetworkAddress getListenAddress ( ) { return listenAddress ; } <nl> + <nl> + private : <nl> + ACTOR static Future < Reference < IConnection > > doAccept ( SSLListener * self ) { <nl> + state Reference < SSLConnection > conn ( new SSLConnection ( self - > acceptor . get_io_service ( ) , * self - > context ) ) ; <nl> + state tcp : : acceptor : : endpoint_type peer_endpoint ; <nl> + try { <nl> + BindPromise p ( " N2_AcceptError " , UID ( ) ) ; <nl> + auto f = p . getFuture ( ) ; <nl> + self - > acceptor . async_accept ( conn - > getSocket ( ) , peer_endpoint , std : : move ( p ) ) ; <nl> + wait ( f ) ; <nl> + auto peer_address = peer_endpoint . address ( ) . is_v6 ( ) ? IPAddress ( peer_endpoint . address ( ) . to_v6 ( ) . to_bytes ( ) ) : IPAddress ( peer_endpoint . address ( ) . to_v4 ( ) . to_ulong ( ) ) ; <nl> + <nl> + conn - > accept ( NetworkAddress ( peer_address , peer_endpoint . port ( ) , false , true ) ) ; <nl> + <nl> + return conn ; <nl> + } catch ( . . . ) { <nl> + conn - > close ( ) ; <nl> + throw ; <nl> + } <nl> + } <nl> + } ; <nl> + # endif <nl> + <nl> struct PromiseTask : public Task , public FastAllocated < PromiseTask > { <nl> Promise < Void > promise ; <nl> PromiseTask ( ) { } <nl> struct PromiseTask : public Task , public FastAllocated < PromiseTask > { <nl> } <nl> } ; <nl> <nl> - Net2 : : Net2 ( bool useThreadPool , bool useMetrics ) <nl> + / / 5MB for loading files into memory <nl> + <nl> + # ifndef TLS_DISABLED <nl> + bool insecurely_always_accept ( bool _1 , boost : : asio : : ssl : : verify_context & _2 ) { <nl> + return true ; <nl> + } <nl> + # endif <nl> + <nl> + Net2 : : Net2 ( bool useThreadPool , bool useMetrics , Reference < TLSPolicy > policy , const TLSParams & tlsParams ) <nl> : useThreadPool ( useThreadPool ) , <nl> network ( this ) , <nl> reactor ( this ) , <nl> Net2 : : Net2 ( bool useThreadPool , bool useMetrics ) <nl> / / Until run ( ) is called , yield ( ) will always yield <nl> tsc_begin ( 0 ) , tsc_end ( 0 ) , taskBegin ( 0 ) , currentTaskID ( TaskPriority : : DefaultYield ) , <nl> lastMinTaskID ( TaskPriority : : Zero ) , <nl> - numYields ( 0 ) <nl> + numYields ( 0 ) , <nl> + tlsPassword ( tlsParams . tlsPassword ) <nl> + # ifndef TLS_DISABLED <nl> + , sslContext ( boost : : asio : : ssl : : context ( boost : : asio : : ssl : : context : : tlsv12 ) ) <nl> + # endif <nl> + <nl> { <nl> TraceEvent ( " Net2Starting " ) ; <nl> <nl> + # ifndef TLS_DISABLED <nl> + sslContext . set_options ( boost : : asio : : ssl : : context : : default_workarounds ) ; <nl> + sslContext . set_verify_mode ( boost : : asio : : ssl : : context : : verify_peer | boost : : asio : : ssl : : verify_fail_if_no_peer_cert ) ; <nl> + if ( policy ) { <nl> + sslContext . set_verify_callback ( [ policy ] ( bool preverified , boost : : asio : : ssl : : verify_context & ctx ) { <nl> + return policy - > verify_peer ( preverified , ctx . native_handle ( ) ) ; <nl> + } ) ; <nl> + } else { <nl> + sslContext . set_verify_callback ( boost : : bind ( & insecurely_always_accept , _1 , _2 ) ) ; <nl> + } <nl> + <nl> + sslContext . set_password_callback ( std : : bind ( & Net2 : : get_password , this ) ) ; <nl> + <nl> + if ( tlsParams . tlsCertPath . size ( ) ) { <nl> + sslContext . use_certificate_chain_file ( tlsParams . tlsCertPath ) ; <nl> + } <nl> + if ( tlsParams . tlsCertBytes . size ( ) ) { <nl> + sslContext . use_certificate ( boost : : asio : : buffer ( tlsParams . tlsCertBytes . data ( ) , tlsParams . tlsCertBytes . size ( ) ) , boost : : asio : : ssl : : context : : pem ) ; <nl> + } <nl> + if ( tlsParams . tlsCAPath . size ( ) ) { <nl> + std : : string cert = readFileBytes ( tlsParams . tlsCAPath , FLOW_KNOBS - > CERT_FILE_MAX_SIZE ) ; <nl> + sslContext . add_certificate_authority ( boost : : asio : : buffer ( cert . data ( ) , cert . size ( ) ) ) ; <nl> + } <nl> + if ( tlsParams . tlsCABytes . size ( ) ) { <nl> + sslContext . add_certificate_authority ( boost : : asio : : buffer ( tlsParams . tlsCABytes . data ( ) , tlsParams . tlsCABytes . size ( ) ) ) ; <nl> + } <nl> + if ( tlsParams . tlsKeyPath . size ( ) ) { <nl> + sslContext . use_private_key_file ( tlsParams . tlsKeyPath , boost : : asio : : ssl : : context : : pem ) ; <nl> + } <nl> + if ( tlsParams . tlsKeyBytes . size ( ) ) { <nl> + sslContext . use_private_key ( boost : : asio : : buffer ( tlsParams . tlsKeyBytes . data ( ) , tlsParams . tlsKeyBytes . size ( ) ) , boost : : asio : : ssl : : context : : pem ) ; <nl> + } <nl> + # endif <nl> + <nl> / / Set the global members <nl> if ( useMetrics ) { <nl> setGlobal ( INetwork : : enTDMetrics , ( flowGlobalType ) & tdmetrics ) ; <nl> THREAD_HANDLE Net2 : : startThread ( THREAD_FUNC_RETURN ( * func ) ( void * ) , void * arg ) <nl> return : : startThread ( func , arg ) ; <nl> } <nl> <nl> - <nl> Future < Reference < IConnection > > Net2 : : connect ( NetworkAddress toAddr , std : : string host ) { <nl> + # ifndef TLS_DISABLED <nl> + if ( toAddr . isTLS ( ) ) { <nl> + return SSLConnection : : connect ( & this - > reactor . ios , & this - > sslContext , toAddr ) ; <nl> + } <nl> + # endif <nl> + <nl> return Connection : : connect ( & this - > reactor . ios , toAddr ) ; <nl> } <nl> <nl> bool Net2 : : isAddressOnThisHost ( NetworkAddress const & addr ) { <nl> <nl> Reference < IListener > Net2 : : listen ( NetworkAddress localAddr ) { <nl> try { <nl> + # ifndef TLS_DISABLED <nl> + if ( localAddr . isTLS ( ) ) { <nl> + return Reference < IListener > ( new SSLListener ( reactor . ios , & this - > sslContext , localAddr ) ) ; <nl> + } <nl> + # endif <nl> return Reference < IListener > ( new Listener ( reactor . ios , localAddr ) ) ; <nl> } catch ( boost : : system : : system_error const & e ) { <nl> Error x ; <nl> void ASIOReactor : : wake ( ) { <nl> <nl> } / / namespace net2 <nl> <nl> - INetwork * newNet2 ( bool useThreadPool , bool useMetrics ) { <nl> + INetwork * newNet2 ( bool useThreadPool , bool useMetrics , Reference < TLSPolicy > policy , const TLSParams & tlsParams ) { <nl> try { <nl> - N2 : : g_net2 = new N2 : : Net2 ( useThreadPool , useMetrics ) ; <nl> + N2 : : g_net2 = new N2 : : Net2 ( useThreadPool , useMetrics , policy , tlsParams ) ; <nl> } <nl> catch ( boost : : system : : system_error e ) { <nl> TraceEvent ( " Net2InitError " ) . detail ( " Message " , e . what ( ) ) ; <nl> - throw unknown_error ( ) ; <nl> + throw ; <nl> } <nl> catch ( std : : exception const & e ) { <nl> TraceEvent ( " Net2InitError " ) . detail ( " Message " , e . what ( ) ) ; <nl> new file mode 100644 <nl> index 0000000000 . . c3a71abe1e <nl> mmm / dev / null <nl> ppp b / flow / TLSPolicy . cpp <nl> <nl> + / * <nl> + * TLSPolicy . cpp <nl> + * <nl> + * This source file is part of the FoundationDB open source project <nl> + * <nl> + * Copyright 2013 - 2020 Apple Inc . and the FoundationDB project authors <nl> + * <nl> + * Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + * you may not use this file except in compliance with the License . <nl> + * You may obtain a copy of the License at <nl> + * <nl> + * http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + * <nl> + * Unless required by applicable law or agreed to in writing , software <nl> + * distributed under the License is distributed on an " AS IS " BASIS , <nl> + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + * See the License for the specific language governing permissions and <nl> + * limitations under the License . <nl> + * / <nl> + <nl> + # include " flow / TLSPolicy . h " <nl> + <nl> + TLSPolicy : : ~ TLSPolicy ( ) { } <nl> + <nl> + # ifndef TLS_DISABLED <nl> + # include < algorithm > <nl> + # include < cstring > <nl> + # include < exception > <nl> + # include < map > <nl> + # include < set > <nl> + # include < openssl / objects . h > <nl> + # include < openssl / bio . h > <nl> + # include < openssl / err . h > <nl> + # include < openssl / pem . h > <nl> + # include < openssl / x509 . h > <nl> + # include < openssl / x509v3 . h > <nl> + # include < openssl / x509_vfy . h > <nl> + # include < stdint . h > <nl> + # include < string > <nl> + # include < sstream > <nl> + # include < utility > <nl> + <nl> + # include " flow / FastRef . h " <nl> + # include " flow / Trace . h " <nl> + <nl> + std : : string TLSPolicy : : ErrorString ( boost : : system : : error_code e ) { <nl> + char * str = ERR_error_string ( e . value ( ) , NULL ) ; <nl> + return std : : string ( str ) ; <nl> + } <nl> + <nl> + / / To force typeinfo to only be emitted once . <nl> + <nl> + <nl> + std : : string TLSPolicy : : toString ( ) const { <nl> + std : : stringstream ss ; <nl> + ss < < " TLSPolicy { Rules = [ " ; <nl> + for ( const auto & r : rules ) { <nl> + ss < < " " < < r . toString ( ) < < " , " ; <nl> + } <nl> + ss < < " ] } " ; <nl> + return ss . str ( ) ; <nl> + } <nl> + <nl> + std : : string TLSPolicy : : Rule : : toString ( ) const { <nl> + std : : stringstream ss ; <nl> + <nl> + ss < < " Rule { verify_cert = " < < verify_cert <nl> + < < " , verify_time = " < < verify_time ; <nl> + ss < < " , Subject = [ " ; <nl> + for ( const auto & s : subject_criteria ) { <nl> + ss < < " { NID = " < < s . first < < " , Criteria = " < < s . second . criteria < < " } , " ; <nl> + } <nl> + ss < < " ] , Issuer = [ " ; <nl> + for ( const auto & s : issuer_criteria ) { <nl> + ss < < " { NID = " < < s . first < < " , Criteria = " < < s . second . criteria < < " } , " ; <nl> + } <nl> + ss < < " ] , Root = [ " ; <nl> + for ( const auto & s : root_criteria ) { <nl> + ss < < " { NID = " < < s . first < < " , Criteria = " < < s . second . criteria < < " } , " ; <nl> + } <nl> + ss < < " ] } " ; <nl> + <nl> + return ss . str ( ) ; <nl> + } <nl> + <nl> + static int hexValue ( char c ) { <nl> + static char const digits [ ] = " 0123456789ABCDEF " ; <nl> + <nl> + if ( c > = ' a ' & & c < = ' f ' ) <nl> + c - = ( ' a ' - ' A ' ) ; <nl> + <nl> + int value = std : : find ( digits , digits + 16 , c ) - digits ; <nl> + if ( value > = 16 ) { <nl> + throw std : : runtime_error ( " hexValue " ) ; <nl> + } <nl> + return value ; <nl> + } <nl> + <nl> + / / Does not handle " raw " form ( e . g . # 28C4D1 ) , only escaped text <nl> + static std : : string de4514 ( std : : string const & input , int start , int & out_end ) { <nl> + std : : string output ; <nl> + <nl> + if ( input [ start ] = = ' # ' | | input [ start ] = = ' ' ) { <nl> + out_end = start ; <nl> + return output ; <nl> + } <nl> + <nl> + int space_count = 0 ; <nl> + <nl> + for ( int p = start ; p < input . size ( ) ; ) { <nl> + switch ( input [ p ] ) { <nl> + case ' \ \ ' : / / Handle escaped sequence <nl> + <nl> + / / Backslash escaping nothing ! <nl> + if ( p = = input . size ( ) - 1 ) { <nl> + out_end = p ; <nl> + goto FIN ; <nl> + } <nl> + <nl> + switch ( input [ p + 1 ] ) { <nl> + case ' ' : <nl> + case ' " ' : <nl> + case ' # ' : <nl> + case ' + ' : <nl> + case ' , ' : <nl> + case ' ; ' : <nl> + case ' < ' : <nl> + case ' = ' : <nl> + case ' > ' : <nl> + case ' | ' : <nl> + case ' \ \ ' : <nl> + output + = input [ p + 1 ] ; <nl> + p + = 2 ; <nl> + space_count = 0 ; <nl> + continue ; <nl> + <nl> + default : <nl> + / / Backslash escaping pair of hex digits requires two characters <nl> + if ( p = = input . size ( ) - 2 ) { <nl> + out_end = p ; <nl> + goto FIN ; <nl> + } <nl> + <nl> + try { <nl> + output + = hexValue ( input [ p + 1 ] ) * 16 + hexValue ( input [ p + 2 ] ) ; <nl> + p + = 3 ; <nl> + space_count = 0 ; <nl> + continue ; <nl> + } catch ( . . . ) { <nl> + out_end = p ; <nl> + goto FIN ; <nl> + } <nl> + } <nl> + <nl> + case ' " ' : <nl> + case ' + ' : <nl> + case ' , ' : <nl> + case ' ; ' : <nl> + case ' < ' : <nl> + case ' > ' : <nl> + case 0 : <nl> + / / All of these must have been escaped <nl> + out_end = p ; <nl> + goto FIN ; <nl> + <nl> + default : <nl> + / / Character is what it is <nl> + output + = input [ p ] ; <nl> + if ( input [ p ] = = ' ' ) <nl> + space_count + + ; <nl> + else <nl> + space_count = 0 ; <nl> + p + + ; <nl> + } <nl> + } <nl> + <nl> + out_end = input . size ( ) ; <nl> + <nl> + FIN : <nl> + out_end - = space_count ; <nl> + output . resize ( output . size ( ) - space_count ) ; <nl> + <nl> + return output ; <nl> + } <nl> + <nl> + static std : : pair < std : : string , std : : string > splitPair ( std : : string const & input , char c ) { <nl> + int p = input . find_first_of ( c ) ; <nl> + if ( p = = input . npos ) { <nl> + throw std : : runtime_error ( " splitPair " ) ; <nl> + } <nl> + return std : : make_pair ( input . substr ( 0 , p ) , input . substr ( p + 1 , input . size ( ) ) ) ; <nl> + } <nl> + <nl> + static NID abbrevToNID ( std : : string const & sn ) { <nl> + NID nid = NID_undef ; <nl> + <nl> + if ( sn = = " C " | | sn = = " CN " | | sn = = " L " | | sn = = " ST " | | sn = = " O " | | sn = = " OU " | | sn = = " UID " | | sn = = " DC " | | sn = = " subjectAltName " ) <nl> + nid = OBJ_sn2nid ( sn . c_str ( ) ) ; <nl> + if ( nid = = NID_undef ) <nl> + throw std : : runtime_error ( " abbrevToNID " ) ; <nl> + <nl> + return nid ; <nl> + } <nl> + <nl> + static X509Location locationForNID ( NID nid ) { <nl> + const char * name = OBJ_nid2ln ( nid ) ; <nl> + if ( name = = NULL ) { <nl> + throw std : : runtime_error ( " locationForNID " ) ; <nl> + } <nl> + if ( strncmp ( name , " X509v3 " , 6 ) = = 0 ) { <nl> + return X509Location : : EXTENSION ; <nl> + } else { <nl> + / / It probably isn ' t true that all other NIDs live in the NAME , but it is for now . . . <nl> + return X509Location : : NAME ; <nl> + } <nl> + } <nl> + <nl> + bool TLSPolicy : : set_verify_peers ( std : : vector < std : : string > verify_peers ) { <nl> + for ( int i = 0 ; i < verify_peers . size ( ) ; i + + ) { <nl> + try { <nl> + std : : string & verifyString = verify_peers [ i ] ; <nl> + int start = 0 ; <nl> + while ( start < verifyString . size ( ) ) { <nl> + int split = verifyString . find ( ' | ' , start ) ; <nl> + if ( split = = std : : string : : npos ) { <nl> + break ; <nl> + } <nl> + if ( split = = start | | verifyString [ split - 1 ] ! = ' \ \ ' ) { <nl> + rules . emplace_back ( verifyString . substr ( start , split - start ) ) ; <nl> + start = split + 1 ; <nl> + } <nl> + } <nl> + rules . emplace_back ( verifyString . substr ( start ) ) ; <nl> + } catch ( const std : : runtime_error & e ) { <nl> + rules . clear ( ) ; <nl> + std : : string & verifyString = verify_peers [ i ] ; <nl> + TraceEvent ( SevError , " FDBLibTLSVerifyPeersParseError " ) . detail ( " Config " , verifyString ) ; <nl> + return false ; <nl> + } <nl> + } <nl> + return true ; <nl> + } <nl> + <nl> + TLSPolicy : : Rule : : Rule ( std : : string input ) { <nl> + int s = 0 ; <nl> + <nl> + while ( s < input . size ( ) ) { <nl> + int eq = input . find ( ' = ' , s ) ; <nl> + <nl> + if ( eq = = input . npos ) <nl> + throw std : : runtime_error ( " parse_verify " ) ; <nl> + <nl> + MatchType mt = MatchType : : EXACT ; <nl> + if ( input [ eq - 1 ] = = ' > ' ) mt = MatchType : : PREFIX ; <nl> + if ( input [ eq - 1 ] = = ' < ' ) mt = MatchType : : SUFFIX ; <nl> + std : : string term = input . substr ( s , eq - s - ( mt = = MatchType : : EXACT ? 0 : 1 ) ) ; <nl> + <nl> + if ( term . find ( " Check . " ) = = 0 ) { <nl> + if ( eq + 2 > input . size ( ) ) <nl> + throw std : : runtime_error ( " parse_verify " ) ; <nl> + if ( eq + 2 ! = input . size ( ) & & input [ eq + 2 ] ! = ' , ' ) <nl> + throw std : : runtime_error ( " parse_verify " ) ; <nl> + if ( mt ! = MatchType : : EXACT ) <nl> + throw std : : runtime_error ( " parse_verify : cannot prefix match Check " ) ; <nl> + <nl> + bool * flag ; <nl> + <nl> + if ( term = = " Check . Valid " ) <nl> + flag = & verify_cert ; <nl> + else if ( term = = " Check . Unexpired " ) <nl> + flag = & verify_time ; <nl> + else <nl> + throw std : : runtime_error ( " parse_verify " ) ; <nl> + <nl> + if ( input [ eq + 1 ] = = ' 0 ' ) <nl> + * flag = false ; <nl> + else if ( input [ eq + 1 ] = = ' 1 ' ) <nl> + * flag = true ; <nl> + else <nl> + throw std : : runtime_error ( " parse_verify " ) ; <nl> + <nl> + s = eq + 3 ; <nl> + } else { <nl> + std : : map < int , Criteria > * criteria = & subject_criteria ; <nl> + <nl> + if ( term . find ( ' . ' ) ! = term . npos ) { <nl> + auto scoped = splitPair ( term , ' . ' ) ; <nl> + <nl> + if ( scoped . first = = " S " | | scoped . first = = " Subject " ) <nl> + criteria = & subject_criteria ; <nl> + else if ( scoped . first = = " I " | | scoped . first = = " Issuer " ) <nl> + criteria = & issuer_criteria ; <nl> + else if ( scoped . first = = " R " | | scoped . first = = " Root " ) <nl> + criteria = & root_criteria ; <nl> + else <nl> + throw std : : runtime_error ( " parse_verify " ) ; <nl> + <nl> + term = scoped . second ; <nl> + } <nl> + <nl> + int remain ; <nl> + auto unesc = de4514 ( input , eq + 1 , remain ) ; <nl> + <nl> + if ( remain = = eq + 1 ) <nl> + throw std : : runtime_error ( " parse_verify " ) ; <nl> + <nl> + NID termNID = abbrevToNID ( term ) ; <nl> + const X509Location loc = locationForNID ( termNID ) ; <nl> + criteria - > insert ( std : : make_pair ( termNID , Criteria ( unesc , mt , loc ) ) ) ; <nl> + <nl> + if ( remain ! = input . size ( ) & & input [ remain ] ! = ' , ' ) <nl> + throw std : : runtime_error ( " parse_verify " ) ; <nl> + <nl> + s = remain + 1 ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + bool match_criteria_entry ( const std : : string & criteria , ASN1_STRING * entry , MatchType mt ) { <nl> + bool rc = false ; <nl> + ASN1_STRING * asn_criteria = NULL ; <nl> + unsigned char * criteria_utf8 = NULL ; <nl> + int criteria_utf8_len = 0 ; <nl> + unsigned char * entry_utf8 = NULL ; <nl> + int entry_utf8_len = 0 ; <nl> + <nl> + if ( ( asn_criteria = ASN1_IA5STRING_new ( ) ) = = NULL ) <nl> + goto err ; <nl> + if ( ASN1_STRING_set ( asn_criteria , criteria . c_str ( ) , criteria . size ( ) ) ! = 1 ) <nl> + goto err ; <nl> + if ( ( criteria_utf8_len = ASN1_STRING_to_UTF8 ( & criteria_utf8 , asn_criteria ) ) < 1 ) <nl> + goto err ; <nl> + if ( ( entry_utf8_len = ASN1_STRING_to_UTF8 ( & entry_utf8 , entry ) ) < 1 ) <nl> + goto err ; <nl> + if ( mt = = MatchType : : EXACT ) { <nl> + if ( criteria_utf8_len = = entry_utf8_len & & <nl> + memcmp ( criteria_utf8 , entry_utf8 , criteria_utf8_len ) = = 0 ) <nl> + rc = true ; <nl> + } else if ( mt = = MatchType : : PREFIX ) { <nl> + if ( criteria_utf8_len < = entry_utf8_len & & <nl> + memcmp ( criteria_utf8 , entry_utf8 , criteria_utf8_len ) = = 0 ) <nl> + rc = true ; <nl> + } else if ( mt = = MatchType : : SUFFIX ) { <nl> + if ( criteria_utf8_len < = entry_utf8_len & & <nl> + memcmp ( criteria_utf8 , entry_utf8 + ( entry_utf8_len - criteria_utf8_len ) , criteria_utf8_len ) = = 0 ) <nl> + rc = true ; <nl> + } <nl> + <nl> + err : <nl> + ASN1_STRING_free ( asn_criteria ) ; <nl> + free ( criteria_utf8 ) ; <nl> + free ( entry_utf8 ) ; <nl> + return rc ; <nl> + } <nl> + <nl> + bool match_name_criteria ( X509_NAME * name , NID nid , const std : : string & criteria , MatchType mt ) { <nl> + X509_NAME_ENTRY * name_entry ; <nl> + int idx ; <nl> + <nl> + / / If name does not exist , or has multiple of this RDN , refuse to proceed . <nl> + if ( ( idx = X509_NAME_get_index_by_NID ( name , nid , - 1 ) ) < 0 ) <nl> + return false ; <nl> + if ( X509_NAME_get_index_by_NID ( name , nid , idx ) ! = - 1 ) <nl> + return false ; <nl> + if ( ( name_entry = X509_NAME_get_entry ( name , idx ) ) = = NULL ) <nl> + return false ; <nl> + <nl> + return match_criteria_entry ( criteria , X509_NAME_ENTRY_get_data ( name_entry ) , mt ) ; <nl> + } <nl> + <nl> + bool match_extension_criteria ( X509 * cert , NID nid , const std : : string & value , MatchType mt ) { <nl> + if ( nid ! = NID_subject_alt_name & & nid ! = NID_issuer_alt_name ) { <nl> + / / I have no idea how other extensions work . <nl> + return false ; <nl> + } <nl> + auto pos = value . find ( ' : ' ) ; <nl> + if ( pos = = value . npos ) { <nl> + return false ; <nl> + } <nl> + std : : string value_gen = value . substr ( 0 , pos ) ; <nl> + std : : string value_val = value . substr ( pos + 1 , value . npos ) ; <nl> + STACK_OF ( GENERAL_NAME ) * sans = reinterpret_cast < STACK_OF ( GENERAL_NAME ) * > ( X509_get_ext_d2i ( cert , nid , NULL , NULL ) ) ; <nl> + if ( sans = = NULL ) { <nl> + return false ; <nl> + } <nl> + int num_sans = sk_GENERAL_NAME_num ( sans ) ; <nl> + bool rc = false ; <nl> + for ( int i = 0 ; i < num_sans & & ! rc ; + + i ) { <nl> + GENERAL_NAME * altname = sk_GENERAL_NAME_value ( sans , i ) ; <nl> + std : : string matchable ; <nl> + switch ( altname - > type ) { <nl> + case GEN_OTHERNAME : <nl> + break ; <nl> + case GEN_EMAIL : <nl> + if ( value_gen = = " EMAIL " & & <nl> + match_criteria_entry ( value_val , altname - > d . rfc822Name , mt ) ) { <nl> + rc = true ; <nl> + break ; <nl> + } <nl> + case GEN_DNS : <nl> + if ( value_gen = = " DNS " & & <nl> + match_criteria_entry ( value_val , altname - > d . dNSName , mt ) ) { <nl> + rc = true ; <nl> + break ; <nl> + } <nl> + case GEN_X400 : <nl> + case GEN_DIRNAME : <nl> + case GEN_EDIPARTY : <nl> + break ; <nl> + case GEN_URI : <nl> + if ( value_gen = = " URI " & & <nl> + match_criteria_entry ( value_val , altname - > d . uniformResourceIdentifier , mt ) ) { <nl> + rc = true ; <nl> + break ; <nl> + } <nl> + case GEN_IPADD : <nl> + if ( value_gen = = " IP " & & <nl> + match_criteria_entry ( value_val , altname - > d . iPAddress , mt ) ) { <nl> + rc = true ; <nl> + break ; <nl> + } <nl> + case GEN_RID : <nl> + break ; <nl> + } <nl> + } <nl> + sk_GENERAL_NAME_pop_free ( sans , GENERAL_NAME_free ) ; <nl> + return rc ; <nl> + } <nl> + <nl> + bool match_criteria ( X509 * cert , X509_NAME * subject , NID nid , const std : : string & criteria , MatchType mt , X509Location loc ) { <nl> + switch ( loc ) { <nl> + case X509Location : : NAME : { <nl> + return match_name_criteria ( subject , nid , criteria , mt ) ; <nl> + } <nl> + case X509Location : : EXTENSION : { <nl> + return match_extension_criteria ( cert , nid , criteria , mt ) ; <nl> + } <nl> + } <nl> + / / Should never be reachable . <nl> + return false ; <nl> + } <nl> + <nl> + std : : tuple < bool , std : : string > check_verify ( const TLSPolicy : : Rule * verify , X509_STORE_CTX * store_ctx , bool is_client ) { <nl> + X509_NAME * subject , * issuer ; <nl> + bool rc = false ; <nl> + X509 * cert = NULL ; <nl> + / / if returning false , give a reason string <nl> + std : : string reason = " " ; <nl> + <nl> + / / Check subject criteria . <nl> + cert = sk_X509_value ( X509_STORE_CTX_get0_chain ( store_ctx ) , 0 ) ; <nl> + if ( ( subject = X509_get_subject_name ( cert ) ) = = NULL ) { <nl> + reason = " Cert subject error " ; <nl> + goto err ; <nl> + } <nl> + for ( auto & pair : verify - > subject_criteria ) { <nl> + if ( ! match_criteria ( cert , subject , pair . first , pair . second . criteria , pair . second . match_type , pair . second . location ) ) { <nl> + reason = " Cert subject match failure " ; <nl> + goto err ; <nl> + } <nl> + } <nl> + <nl> + / / Check issuer criteria . <nl> + if ( ( issuer = X509_get_issuer_name ( cert ) ) = = NULL ) { <nl> + reason = " Cert issuer error " ; <nl> + goto err ; <nl> + } <nl> + for ( auto & pair : verify - > issuer_criteria ) { <nl> + if ( ! match_criteria ( cert , issuer , pair . first , pair . second . criteria , pair . second . match_type , pair . second . location ) ) { <nl> + reason = " Cert issuer match failure " ; <nl> + goto err ; <nl> + } <nl> + } <nl> + <nl> + / / Check root criteria - this is the subject of the final certificate in the stack . <nl> + cert = sk_X509_value ( X509_STORE_CTX_get0_chain ( store_ctx ) , sk_X509_num ( X509_STORE_CTX_get0_chain ( store_ctx ) ) - 1 ) ; <nl> + if ( ( subject = X509_get_subject_name ( cert ) ) = = NULL ) { <nl> + reason = " Root subject error " ; <nl> + goto err ; <nl> + } <nl> + for ( auto & pair : verify - > root_criteria ) { <nl> + if ( ! match_criteria ( cert , subject , pair . first , pair . second . criteria , pair . second . match_type , pair . second . location ) ) { <nl> + reason = " Root subject match failure " ; <nl> + goto err ; <nl> + } <nl> + } <nl> + <nl> + / / If we got this far , everything checked out . . . <nl> + rc = true ; <nl> + <nl> + err : <nl> + return std : : make_tuple ( rc , reason ) ; <nl> + } <nl> + <nl> + bool TLSPolicy : : verify_peer ( bool preverified , X509_STORE_CTX * store_ctx ) { <nl> + bool rc = false ; <nl> + std : : set < std : : string > verify_failure_reasons ; <nl> + bool verify_success ; <nl> + std : : string verify_failure_reason ; <nl> + <nl> + / / If certificate verification is disabled , there ' s nothing more to do . <nl> + if ( std : : any_of ( rules . begin ( ) , rules . end ( ) , [ ] ( const Rule & r ) { return ! r . verify_cert ; } ) ) { <nl> + return true ; <nl> + } <nl> + <nl> + if ( ! preverified ) { <nl> + TraceEvent ( " TLSPolicyFailure " ) . suppressFor ( 1 . 0 ) . detail ( " Reason " , " preverification failed " ) . detail ( " VerifyError " , X509_verify_cert_error_string ( X509_STORE_CTX_get_error ( store_ctx ) ) ) ; <nl> + return false ; <nl> + } <nl> + <nl> + if ( ! rules . size ( ) ) { <nl> + return true ; <nl> + } <nl> + <nl> + / / Any matching rule is sufficient . <nl> + for ( auto & verify_rule : rules ) { <nl> + std : : tie ( verify_success , verify_failure_reason ) = check_verify ( & verify_rule , store_ctx , is_client ) ; <nl> + if ( verify_success ) { <nl> + rc = true ; <nl> + break ; <nl> + } else { <nl> + if ( verify_failure_reason . length ( ) > 0 ) <nl> + verify_failure_reasons . insert ( verify_failure_reason ) ; <nl> + } <nl> + } <nl> + <nl> + if ( ! rc ) { <nl> + / / log the various failure reasons <nl> + for ( std : : string reason : verify_failure_reasons ) { <nl> + TraceEvent ( " TLSPolicyFailure " ) . suppressFor ( 1 . 0 ) . detail ( " Reason " , reason ) ; <nl> + } <nl> + } <nl> + return rc ; <nl> + } <nl> + # endif <nl> new file mode 100644 <nl> index 0000000000 . . 1af5abfb73 <nl> mmm / dev / null <nl> ppp b / flow / TLSPolicy . h <nl> <nl> + / * <nl> + * TLSPolicy . h <nl> + * <nl> + * This source file is part of the FoundationDB open source project <nl> + * <nl> + * Copyright 2013 - 2020 Apple Inc . and the FoundationDB project authors <nl> + * <nl> + * Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + * you may not use this file except in compliance with the License . <nl> + * You may obtain a copy of the License at <nl> + * <nl> + * http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + * <nl> + * Unless required by applicable law or agreed to in writing , software <nl> + * distributed under the License is distributed on an " AS IS " BASIS , <nl> + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + * See the License for the specific language governing permissions and <nl> + * limitations under the License . <nl> + * / <nl> + <nl> + # ifndef _FLOW_TLSPOLICY_H_ <nl> + # define _FLOW_TLSPOLICY_H_ <nl> + # pragma once <nl> + <nl> + # include < map > <nl> + # include < string > <nl> + # include < vector > <nl> + # include < boost / system / system_error . hpp > <nl> + # include " flow / FastRef . h " <nl> + <nl> + # ifndef TLS_DISABLED <nl> + <nl> + # include < openssl / x509 . h > <nl> + typedef int NID ; <nl> + <nl> + enum class MatchType { <nl> + EXACT , <nl> + PREFIX , <nl> + SUFFIX , <nl> + } ; <nl> + <nl> + enum class X509Location { <nl> + / / This NID is located within a X509_NAME <nl> + NAME , <nl> + / / This NID is an X509 extension , and should be parsed accordingly <nl> + EXTENSION , <nl> + } ; <nl> + <nl> + struct Criteria { <nl> + Criteria ( const std : : string & s ) <nl> + : criteria ( s ) , match_type ( MatchType : : EXACT ) , location ( X509Location : : NAME ) { } <nl> + Criteria ( const std : : string & s , MatchType mt ) <nl> + : criteria ( s ) , match_type ( mt ) , location ( X509Location : : NAME ) { } <nl> + Criteria ( const std : : string & s , X509Location loc ) <nl> + : criteria ( s ) , match_type ( MatchType : : EXACT ) , location ( loc ) { } <nl> + Criteria ( const std : : string & s , MatchType mt , X509Location loc ) <nl> + : criteria ( s ) , match_type ( mt ) , location ( loc ) { } <nl> + <nl> + std : : string criteria ; <nl> + MatchType match_type ; <nl> + X509Location location ; <nl> + <nl> + bool operator = = ( const Criteria & c ) const { <nl> + return criteria = = c . criteria & & match_type = = c . match_type & & location = = c . location ; <nl> + } <nl> + } ; <nl> + # endif <nl> + <nl> + struct TLSParams { <nl> + enum { OPT_TLS = 100000 , OPT_TLS_PLUGIN , OPT_TLS_CERTIFICATES , OPT_TLS_KEY , OPT_TLS_VERIFY_PEERS , OPT_TLS_CA_FILE , OPT_TLS_PASSWORD } ; <nl> + <nl> + std : : string tlsCertPath , tlsKeyPath , tlsCAPath , tlsPassword ; <nl> + std : : string tlsCertBytes , tlsKeyBytes , tlsCABytes ; <nl> + } ; <nl> + <nl> + class TLSPolicy : ReferenceCounted < TLSPolicy > { <nl> + public : <nl> + enum class Is { <nl> + CLIENT , <nl> + SERVER <nl> + } ; <nl> + <nl> + TLSPolicy ( Is client ) : is_client ( client = = Is : : CLIENT ) { } <nl> + virtual ~ TLSPolicy ( ) ; <nl> + <nl> + virtual void addref ( ) { ReferenceCounted < TLSPolicy > : : addref ( ) ; } <nl> + virtual void delref ( ) { ReferenceCounted < TLSPolicy > : : delref ( ) ; } <nl> + <nl> + # ifndef TLS_DISABLED <nl> + static std : : string ErrorString ( boost : : system : : error_code e ) ; <nl> + <nl> + bool set_verify_peers ( std : : vector < std : : string > verify_peers ) ; <nl> + bool verify_peer ( bool preverified , X509_STORE_CTX * store_ctx ) ; <nl> + <nl> + std : : string toString ( ) const ; <nl> + <nl> + struct Rule { <nl> + explicit Rule ( std : : string input ) ; <nl> + <nl> + std : : string toString ( ) const ; <nl> + <nl> + std : : map < NID , Criteria > subject_criteria ; <nl> + std : : map < NID , Criteria > issuer_criteria ; <nl> + std : : map < NID , Criteria > root_criteria ; <nl> + <nl> + bool verify_cert = true ; <nl> + bool verify_time = true ; <nl> + } ; <nl> + <nl> + std : : vector < Rule > rules ; <nl> + # endif <nl> + bool is_client ; <nl> + } ; <nl> + <nl> + # define TLS_PLUGIN_FLAG " - - tls_plugin " <nl> + # define TLS_CERTIFICATE_FILE_FLAG " - - tls_certificate_file " <nl> + # define TLS_KEY_FILE_FLAG " - - tls_key_file " <nl> + # define TLS_VERIFY_PEERS_FLAG " - - tls_verify_peers " <nl> + # define TLS_CA_FILE_FLAG " - - tls_ca_file " <nl> + # define TLS_PASSWORD_FLAG " - - tls_password " <nl> + <nl> + # define TLS_OPTION_FLAGS \ <nl> + { TLSParams : : OPT_TLS_PLUGIN , TLS_PLUGIN_FLAG , SO_REQ_SEP } , \ <nl> + { TLSParams : : OPT_TLS_CERTIFICATES , TLS_CERTIFICATE_FILE_FLAG , SO_REQ_SEP } , \ <nl> + { TLSParams : : OPT_TLS_KEY , TLS_KEY_FILE_FLAG , SO_REQ_SEP } , \ <nl> + { TLSParams : : OPT_TLS_VERIFY_PEERS , TLS_VERIFY_PEERS_FLAG , SO_REQ_SEP } , \ <nl> + { TLSParams : : OPT_TLS_PASSWORD , TLS_PASSWORD_FLAG , SO_REQ_SEP } , \ <nl> + { TLSParams : : OPT_TLS_CA_FILE , TLS_CA_FILE_FLAG , SO_REQ_SEP } , <nl> + <nl> + # define TLS_HELP \ <nl> + " " TLS_CERTIFICATE_FILE_FLAG " CERTFILE \ n " \ <nl> + " The path of a file containing the TLS certificate and CA \ n " \ <nl> + " chain . \ n " \ <nl> + " " TLS_CA_FILE_FLAG " CERTAUTHFILE \ n " \ <nl> + " The path of a file containing the CA certificates chain . \ n " \ <nl> + " " TLS_KEY_FILE_FLAG " KEYFILE \ n " \ <nl> + " The path of a file containing the private key corresponding \ n " \ <nl> + " to the TLS certificate . \ n " \ <nl> + " " TLS_PASSWORD_FLAG " PASSCODE \ n " \ <nl> + " The passphrase of encrypted private key \ n " \ <nl> + " " TLS_VERIFY_PEERS_FLAG " CONSTRAINTS \ n " \ <nl> + " The constraints by which to validate TLS peers . The contents \ n " \ <nl> + " and format of CONSTRAINTS are plugin - specific . \ n " <nl> + <nl> + # endif <nl> mmm a / flow / Trace . cpp <nl> ppp b / flow / Trace . cpp <nl> bool traceFormatImpl ( std : : string & format ) { <nl> return false ; <nl> } <nl> } <nl> + <nl> + template < bool validate > <nl> + bool traceClockSource ( std : : string & source ) { <nl> + std : : transform ( source . begin ( ) , source . end ( ) , source . begin ( ) , : : tolower ) ; <nl> + if ( source = = " now " ) { <nl> + if ( ! validate ) { <nl> + g_trace_clock . store ( TRACE_CLOCK_NOW ) ; <nl> + } <nl> + return true ; <nl> + } else if ( source = = " realtime " ) { <nl> + if ( ! validate ) { <nl> + g_trace_clock . store ( TRACE_CLOCK_REALTIME ) ; <nl> + } <nl> + return true ; <nl> + } else { <nl> + return false ; <nl> + } <nl> + } <nl> } / / namespace <nl> <nl> bool selectTraceFormatter ( std : : string format ) { <nl> bool validateTraceFormat ( std : : string format ) { <nl> return traceFormatImpl < / * validate * / true > ( format ) ; <nl> } <nl> <nl> + bool selectTraceClockSource ( std : : string source ) { <nl> + ASSERT ( ! g_traceLog . isOpen ( ) ) ; <nl> + bool recognized = traceClockSource < / * validate * / false > ( source ) ; <nl> + if ( ! recognized ) { <nl> + TraceEvent ( SevWarnAlways , " UnrecognizedTraceClockSource " ) . detail ( " source " , source ) ; <nl> + } <nl> + return recognized ; <nl> + } <nl> + <nl> + bool validateTraceClockSource ( std : : string source ) { <nl> + return traceClockSource < / * validate * / true > ( source ) ; <nl> + } <nl> + <nl> ThreadFuture < Void > flushTraceFile ( ) { <nl> if ( ! g_traceLog . isOpen ( ) ) <nl> return Void ( ) ; <nl> void removeTraceRole ( std : : string role ) { <nl> g_traceLog . removeRole ( role ) ; <nl> } <nl> <nl> + TraceEvent : : TraceEvent ( ) : initialized ( true ) , enabled ( false ) , logged ( true ) { } <nl> + <nl> + TraceEvent : : TraceEvent ( TraceEvent & & ev ) { <nl> + enabled = ev . enabled ; <nl> + err = ev . err ; <nl> + fields = std : : move ( ev . fields ) ; <nl> + id = ev . id ; <nl> + initialized = ev . initialized ; <nl> + logged = ev . logged ; <nl> + maxEventLength = ev . maxEventLength ; <nl> + maxFieldLength = ev . maxFieldLength ; <nl> + severity = ev . severity ; <nl> + tmpEventMetric = ev . tmpEventMetric ; <nl> + trackingKey = ev . trackingKey ; <nl> + type = ev . type ; <nl> + <nl> + ev . initialized = true ; <nl> + ev . enabled = false ; <nl> + ev . logged = true ; <nl> + ev . tmpEventMetric = nullptr ; <nl> + } <nl> + <nl> + TraceEvent & TraceEvent : : operator = ( TraceEvent & & ev ) { <nl> + enabled = ev . enabled ; <nl> + err = ev . err ; <nl> + fields = std : : move ( ev . fields ) ; <nl> + id = ev . id ; <nl> + initialized = ev . initialized ; <nl> + logged = ev . logged ; <nl> + maxEventLength = ev . maxEventLength ; <nl> + maxFieldLength = ev . maxFieldLength ; <nl> + severity = ev . severity ; <nl> + tmpEventMetric = ev . tmpEventMetric ; <nl> + trackingKey = ev . trackingKey ; <nl> + type = ev . type ; <nl> + <nl> + ev . initialized = true ; <nl> + ev . enabled = false ; <nl> + ev . logged = true ; <nl> + ev . tmpEventMetric = nullptr ; <nl> + <nl> + return * this ; <nl> + } <nl> + <nl> TraceEvent : : TraceEvent ( const char * type , UID id ) : id ( id ) , type ( type ) , severity ( SevInfo ) , initialized ( false ) , enabled ( true ) , logged ( false ) { <nl> g_trace_depth + + ; <nl> setMaxFieldLength ( 0 ) ; <nl> bool TraceEvent : : init ( ) { <nl> } <nl> <nl> detail ( " Severity " , int ( severity ) ) ; <nl> - detailf ( " Time " , " % . 6f " , getCurrentTime ( ) ) ; <nl> + detail ( " Time " , " 0 . 000000 " ) ; <nl> + timeIndex = fields . size ( ) - 1 ; <nl> + <nl> detail ( " Type " , type ) ; <nl> if ( g_network & & g_network - > isSimulated ( ) ) { <nl> NetworkAddress local = g_network - > getLocalAddress ( ) ; <nl> void TraceEvent : : log ( ) { <nl> init ( ) ; <nl> try { <nl> if ( enabled ) { <nl> + fields . mutate ( timeIndex ) . second = format ( " % . 6f " , TraceEvent : : getCurrentTime ( ) ) ; <nl> + <nl> if ( this - > severity = = SevError ) { <nl> severity = SevInfo ; <nl> backtrace ( ) ; <nl> std : : string TraceEventFields : : getValue ( std : : string key ) const { <nl> } <nl> } <nl> <nl> + TraceEventFields : : Field & TraceEventFields : : mutate ( int index ) { <nl> + return fields . at ( index ) ; <nl> + } <nl> + <nl> namespace { <nl> void parseNumericValue ( std : : string const & s , double & outValue , bool permissive = false ) { <nl> double d = 0 ; <nl> void TraceEventFields : : validateFormat ( ) const { <nl> } <nl> <nl> std : : string traceableStringToString ( const char * value , size_t S ) { <nl> - ASSERT_WE_THINK ( S > 0 & & value [ S - 1 ] = = ' \ 0 ' ) ; <nl> + if ( g_network ) { <nl> + ASSERT_WE_THINK ( S > 0 & & value [ S - 1 ] = = ' \ 0 ' ) ; <nl> + } <nl> + <nl> return std : : string ( value , S - 1 ) ; / / Exclude trailing \ 0 byte <nl> } <nl> mmm a / flow / Trace . h <nl> ppp b / flow / Trace . h <nl> class TraceEventFields { <nl> int64_t getInt64 ( std : : string key , bool permissive = false ) const ; <nl> double getDouble ( std : : string key , bool permissive = false ) const ; <nl> <nl> + Field & mutate ( int index ) ; <nl> + <nl> std : : string toString ( ) const ; <nl> void validateFormat ( ) const ; <nl> template < class Archiver > <nl> struct SpecialTraceMetricType <nl> TRACE_METRIC_TYPE ( double , double ) ; <nl> <nl> struct TraceEvent { <nl> + TraceEvent ( ) ; <nl> TraceEvent ( const char * type , UID id = UID ( ) ) ; / / Assumes SevInfo severity <nl> TraceEvent ( Severity , const char * type , UID id = UID ( ) ) ; <nl> TraceEvent ( struct TraceInterval & , UID id = UID ( ) ) ; <nl> TraceEvent ( Severity severity , struct TraceInterval & interval , UID id = UID ( ) ) ; <nl> <nl> + TraceEvent ( TraceEvent & & ev ) ; <nl> + TraceEvent & operator = ( TraceEvent & & ev ) ; <nl> + <nl> static void setNetworkThread ( ) ; <nl> static bool isNetworkThread ( ) ; <nl> <nl> struct TraceEvent { <nl> <nl> int maxFieldLength ; <nl> int maxEventLength ; <nl> + int timeIndex ; <nl> <nl> void setSizeLimits ( ) ; <nl> <nl> bool selectTraceFormatter ( std : : string format ) ; <nl> / / Returns true iff format is recognized . <nl> bool validateTraceFormat ( std : : string format ) ; <nl> <nl> + / / Select the clock source for trace files . Returns false if the format is unrecognized . No longer safe to call after a call <nl> + / / to openTraceFile . <nl> + bool selectTraceClockSource ( std : : string source ) ; <nl> + / / Returns true iff source is recognized . <nl> + bool validateTraceClockSource ( std : : string source ) ; <nl> + <nl> void addTraceRole ( std : : string role ) ; <nl> void removeTraceRole ( std : : string role ) ; <nl> <nl> mmm a / flow / actorcompiler / ActorCompiler . cs <nl> ppp b / flow / actorcompiler / ActorCompiler . cs <nl> public DescrCompiler ( Descr descr , int braceDepth ) <nl> public void Write ( TextWriter writer , out int lines ) <nl> { <nl> lines = 0 ; <nl> - / / if ( isTopLevel ) writer . WriteLine ( " namespace { " ) ; <nl> <nl> writer . WriteLine ( memberIndentStr + " template < > struct Descriptor < struct { 0 } > { { " , descr . name ) ; <nl> writer . WriteLine ( memberIndentStr + " \ tstatic StringRef typeName ( ) { { return LiteralStringRef ( \ " { 0 } \ " ) ; } } " , descr . name ) ; <nl> public void Write ( TextWriter writer , out int lines ) <nl> lines + + ; <nl> } <nl> <nl> - / / if ( isTopLevel ) writer . WriteLine ( " } " ) ; / / namespace <nl> } <nl> } <nl> <nl> public void Write ( TextWriter writer ) <nl> string fullReturnType = <nl> actor . returnType ! = null ? string . Format ( " Future < { 0 } > " , actor . returnType ) <nl> : " void " ; <nl> - if ( actor . isForwardDeclaration ) { <nl> - foreach ( string attribute in actor . attributes ) { <nl> - writer . Write ( attribute + " " ) ; <nl> - } <nl> - if ( actor . isStatic ) writer . Write ( " static " ) ; <nl> - writer . WriteLine ( " { 0 } { 3 } { 1 } ( { 2 } ) ; " , fullReturnType , actor . name , string . Join ( " , " , ParameterList ( ) ) , actor . nameSpace = = null ? " " : actor . nameSpace + " : : " ) ; <nl> - return ; <nl> - } <nl> for ( int i = 0 ; ; i + + ) <nl> { <nl> - className = string . Format ( " { 0 } { 1 } Actor { 2 } " , <nl> + className = string . Format ( " { 3 } { 0 } { 1 } Actor { 2 } " , <nl> actor . name . Substring ( 0 , 1 ) . ToUpper ( ) , <nl> actor . name . Substring ( 1 ) , <nl> - i ! = 0 ? i . ToString ( ) : " " ) ; <nl> - if ( usedClassNames . Add ( className ) ) <nl> + i ! = 0 ? i . ToString ( ) : " " , <nl> + actor . enclosingClass ! = null & & actor . isForwardDeclaration ? actor . enclosingClass . Replace ( " : : " , " _ " ) + " _ " <nl> + : actor . nameSpace ! = null ? actor . nameSpace . Replace ( " : : " , " _ " ) + " _ " <nl> + : " " ) ; <nl> + if ( actor . isForwardDeclaration | | usedClassNames . Add ( className ) ) <nl> break ; <nl> } <nl> <nl> public void Write ( TextWriter writer ) <nl> stateClassName = className + " State " ; <nl> var fullStateClassName = stateClassName + GetTemplateActuals ( new VarDeclaration { type = " class " , name = fullClassName } ) ; <nl> <nl> + if ( actor . isForwardDeclaration ) { <nl> + foreach ( string attribute in actor . attributes ) { <nl> + writer . Write ( attribute + " " ) ; <nl> + } <nl> + if ( actor . isStatic ) writer . Write ( " static " ) ; <nl> + writer . WriteLine ( " { 0 } { 3 } { 1 } ( { 2 } ) ; " , fullReturnType , actor . name , string . Join ( " , " , ParameterList ( ) ) , actor . nameSpace = = null ? " " : actor . nameSpace + " : : " ) ; <nl> + if ( actor . enclosingClass ! = null ) { <nl> + writer . WriteLine ( " template < class > friend class { 0 } ; " , stateClassName ) ; <nl> + } <nl> + return ; <nl> + } <nl> + <nl> var body = getFunction ( " " , " body " , loopDepth0 ) ; <nl> var bodyContext = new Context { <nl> target = body , <nl> public void Write ( TextWriter writer ) <nl> } <nl> bodyContext . catchFErr . WriteLine ( " loopDepth = 0 ; " ) ; <nl> <nl> - if ( isTopLevel ) writer . WriteLine ( " namespace { " ) ; <nl> + if ( isTopLevel & & actor . nameSpace = = null ) writer . WriteLine ( " namespace { " ) ; <nl> <nl> / / The " State " class contains all state and user code , to make sure that state names are accessible to user code but <nl> / / inherited members of Actor , Callback etc are not . <nl> public void Write ( TextWriter writer ) <nl> / / WriteStartFunc ( body , writer ) ; <nl> WriteCancelFunc ( writer ) ; <nl> writer . WriteLine ( " } ; " ) ; <nl> - if ( isTopLevel ) writer . WriteLine ( " } " ) ; / / namespace <nl> + if ( isTopLevel & & actor . nameSpace = = null ) writer . WriteLine ( " } " ) ; / / namespace <nl> WriteTemplate ( writer ) ; <nl> LineNumber ( writer , actor . SourceLine ) ; <nl> foreach ( string attribute in actor . attributes ) { <nl> mmm a / flow / actorcompiler / ActorParser . cs <nl> ppp b / flow / actorcompiler / ActorParser . cs <nl> public ActorParser ( string text , string sourceFile , ErrorMessagePolicy errorMessa <nl> / / showTokens ( ) ; <nl> } <nl> <nl> + class ClassContext { <nl> + public string name ; <nl> + public int inBlocks ; <nl> + } <nl> + <nl> + private bool ParseClassContext ( TokenRange toks , out string name ) <nl> + { <nl> + name = " " ; <nl> + if ( toks . Begin = = toks . End ) <nl> + { <nl> + return false ; <nl> + } <nl> + <nl> + / / http : / / nongnu . org / hcb / # attribute - specifier - seq <nl> + Token first ; <nl> + while ( true ) <nl> + { <nl> + first = toks . First ( NonWhitespace ) ; <nl> + if ( first . Value = = " [ " ) <nl> + { <nl> + var contents = first . GetMatchingRangeIn ( toks ) ; <nl> + toks = range ( contents . End + 1 , toks . End ) ; <nl> + } <nl> + else if ( first . Value = = " alignas " ) <nl> + { <nl> + toks = range ( first . Position + 1 , toks . End ) ; <nl> + first = toks . First ( NonWhitespace ) ; <nl> + first . Assert ( " Expected ( after alignas " , t = > t . Value = = " ( " ) ; <nl> + var contents = first . GetMatchingRangeIn ( toks ) ; <nl> + toks = range ( contents . End + 1 , toks . End ) ; <nl> + } <nl> + else <nl> + { <nl> + break ; <nl> + } <nl> + } <nl> + <nl> + / / http : / / nongnu . org / hcb / # class - head - name <nl> + first = toks . First ( NonWhitespace ) ; <nl> + if ( ! identifierPattern . Match ( first . Value ) . Success ) { <nl> + return false ; <nl> + } <nl> + while ( true ) { <nl> + first . Assert ( " Expected identifier " , t = > identifierPattern . Match ( t . Value ) . Success ) ; <nl> + name + = first . Value ; <nl> + toks = range ( first . Position + 1 , toks . End ) ; <nl> + if ( toks . First ( NonWhitespace ) . Value = = " : : " ) { <nl> + name + = " : : " ; <nl> + toks = toks . SkipWhile ( Whitespace ) . Skip ( 1 ) ; <nl> + } else { <nl> + break ; <nl> + } <nl> + first = toks . First ( NonWhitespace ) ; <nl> + } <nl> + / / http : / / nongnu . org / hcb / # class - virt - specifier - seq <nl> + toks = toks . SkipWhile ( t = > Whitespace ( t ) | | t . Value = = " final " | | t . Value = = " explicit " | | t . Value = = " sealed " ) ; <nl> + <nl> + first = toks . First ( NonWhitespace ) ; <nl> + if ( first . Value = = " : " | | first . Value = = " { " ) { <nl> + / / At this point we ' ve confirmed that this is a class . <nl> + return true ; <nl> + } <nl> + return false ; <nl> + } <nl> + <nl> public void Write ( System . IO . TextWriter writer , string destFileName ) <nl> { <nl> writer . NewLine = " \ n " ; <nl> public void Write ( System . IO . TextWriter writer , string destFileName ) <nl> outLine + + ; <nl> } <nl> int inBlocks = 0 ; <nl> + Stack < ClassContext > classContextStack = new Stack < ClassContext > ( ) ; <nl> for ( int i = 0 ; i < tokens . Length ; i + + ) <nl> { <nl> if ( tokens [ 0 ] . SourceLine = = 0 ) <nl> public void Write ( System . IO . TextWriter writer , string destFileName ) <nl> { <nl> int end ; <nl> var actor = ParseActor ( i , out end ) ; <nl> + if ( classContextStack . Count > 0 ) <nl> + { <nl> + actor . enclosingClass = String . Join ( " : : " , classContextStack . Reverse ( ) . Select ( t = > t . name ) ) ; <nl> + } <nl> var actorWriter = new System . IO . StringWriter ( ) ; <nl> actorWriter . NewLine = " \ n " ; <nl> - new ActorCompiler ( actor , sourceFile , inBlocks = = 0 , LineNumbersEnabled , generateProbes ) . Write ( actorWriter ) ; <nl> + new ActorCompiler ( actor , sourceFile , inBlocks = = 0 , LineNumbersEnabled , generateProbes ) . Write ( actorWriter ) ; <nl> string [ ] actorLines = actorWriter . ToString ( ) . Split ( ' \ n ' ) ; <nl> <nl> bool hasLineNumber = false ; <nl> public void Write ( System . IO . TextWriter writer , string destFileName ) <nl> outLine + + ; <nl> } <nl> } <nl> + else if ( tokens [ i ] . Value = = " class " | | tokens [ i ] . Value = = " struct " | | tokens [ i ] . Value = = " union " ) <nl> + { <nl> + writer . Write ( tokens [ i ] . Value ) ; <nl> + string name ; <nl> + if ( ParseClassContext ( range ( i + 1 , tokens . Length ) , out name ) ) <nl> + { <nl> + classContextStack . Push ( new ClassContext { name = name , inBlocks = inBlocks } ) ; <nl> + } <nl> + } <nl> else <nl> { <nl> - if ( tokens [ i ] . Value = = " { " ) inBlocks + + ; <nl> - else if ( tokens [ i ] . Value = = " } " ) inBlocks - - ; <nl> + if ( tokens [ i ] . Value = = " { " ) <nl> + { <nl> + inBlocks + + ; <nl> + } <nl> + else if ( tokens [ i ] . Value = = " } " ) <nl> + { <nl> + inBlocks - - ; <nl> + if ( classContextStack . Count > 0 & & classContextStack . Peek ( ) . inBlocks = = inBlocks ) <nl> + { <nl> + classContextStack . Pop ( ) ; <nl> + } <nl> + } <nl> writer . Write ( tokens [ i ] . Value ) ; <nl> outLine + = tokens [ i ] . Value . Count ( c = > c = = ' \ n ' ) ; <nl> } <nl> void showTokens ( ) <nl> } <nl> } <nl> <nl> + readonly Regex identifierPattern = new Regex ( @ " \ G [ a - zA - Z_ ] [ a - zA - Z_0 - 9 ] * " , RegexOptions . Singleline ) ; <nl> + <nl> readonly Regex [ ] tokenExpressions = ( new string [ ] { <nl> @ " \ { " , <nl> @ " \ } " , <nl> void showTokens ( ) <nl> @ " \ r \ n " , <nl> @ " \ n " , <nl> @ " : : " , <nl> + @ " : " , <nl> @ " . " <nl> } ) . Select ( x = > new Regex ( @ " \ G " + x , RegexOptions . Singleline ) ) . ToArray ( ) ; <nl> <nl> mmm a / flow / actorcompiler / ParseTree . cs <nl> ppp b / flow / actorcompiler / ParseTree . cs <nl> class Actor <nl> public List < string > attributes = new List < string > ( ) ; <nl> public string returnType ; <nl> public string name ; <nl> + public string enclosingClass = null ; <nl> public VarDeclaration [ ] parameters ; <nl> public VarDeclaration [ ] templateFormals ; / / < null if not a template <nl> public CodeBlock body ; <nl> mmm a / flow / flow . vcxproj <nl> ppp b / flow / flow . vcxproj <nl> <nl> < ClCompile Include = " version . cpp " / > <nl> < ClCompile Include = " SignalSafeUnwind . cpp " / > <nl> < ClCompile Include = " serialize . cpp " / > <nl> + < ClCompile Include = " TLSPolicy . cpp " / > <nl> < / ItemGroup > <nl> < ItemGroup > <nl> < ClInclude Include = " CompressedInt . h " / > <nl> <nl> < ClInclude Include = " Platform . h " / > <nl> < ClInclude Include = " ThreadSafeQueue . h " / > <nl> < ClInclude Include = " Trace . h " / > <nl> + < ClInclude Include = " TLSPolicy . h " / > <nl> < ClInclude Include = " SignalSafeUnwind . h " / > <nl> < ClInclude Include = " UnitTest . h " / > <nl> < ActorCompiler Include = " ThreadHelper . actor . h " > <nl> mmm a / flow / genericactors . actor . cpp <nl> ppp b / flow / genericactors . actor . cpp <nl> ACTOR Future < Void > returnIfTrue ( Future < bool > f ) <nl> wait ( Never ( ) ) ; <nl> throw internal_error ( ) ; <nl> } <nl> + <nl> + ACTOR Future < Void > lowPriorityDelay ( double waitTime ) { <nl> + state int loopCount = 0 ; <nl> + while ( loopCount < FLOW_KNOBS - > LOW_PRIORITY_DELAY_COUNT ) { <nl> + wait ( delay ( waitTime / FLOW_KNOBS - > LOW_PRIORITY_DELAY_COUNT , TaskPriority : : Low ) ) ; <nl> + loopCount + + ; <nl> + } <nl> + return Void ( ) ; <nl> + } <nl> mmm a / flow / genericactors . actor . h <nl> ppp b / flow / genericactors . actor . h <nl> <nl> # include " flow / flow . h " <nl> # include " flow / Knobs . h " <nl> # include " flow / Util . h " <nl> + # include " flow / IndexedSet . h " <nl> # include " flow / actorcompiler . h " / / This must be the last # include . <nl> # pragma warning ( disable : 4355 ) / / ' this ' : used in base member initializer list <nl> <nl> class Debouncer : NonCopyable { <nl> } <nl> } ; <nl> <nl> - ACTOR template < class T > Future < Void > asyncDeserialize ( Reference < AsyncVar < Standalone < StringRef > > > input , Reference < AsyncVar < Optional < T > > > output , bool useObjSerializer ) { <nl> + ACTOR template < class T > <nl> + Future < Void > asyncDeserialize ( Reference < AsyncVar < Standalone < StringRef > > > input , <nl> + Reference < AsyncVar < Optional < T > > > output ) { <nl> loop { <nl> if ( input - > get ( ) . size ( ) ) { <nl> - if ( useObjSerializer ) { <nl> - ObjectReader reader ( input - > get ( ) . begin ( ) , IncludeVersion ( ) ) ; <nl> - T res ; <nl> - reader . deserialize ( res ) ; <nl> - output - > set ( res ) ; <nl> - } else { <nl> - output - > set ( BinaryReader : : fromStringRef < T > ( input - > get ( ) , IncludeVersion ( ) ) ) ; <nl> - } <nl> + ObjectReader reader ( input - > get ( ) . begin ( ) , IncludeVersion ( ) ) ; <nl> + T res ; <nl> + reader . deserialize ( res ) ; <nl> + output - > set ( res ) ; <nl> } else <nl> output - > set ( Optional < T > ( ) ) ; <nl> wait ( input - > onChange ( ) ) ; <nl> Future < Void > anyTrue ( std : : vector < Reference < AsyncVar < bool > > > const & input , Refer <nl> Future < Void > cancelOnly ( std : : vector < Future < Void > > const & futures ) ; <nl> Future < Void > timeoutWarningCollector ( FutureStream < Void > const & input , double const & logDelay , const char * const & context , UID const & id ) ; <nl> Future < bool > quorumEqualsTrue ( std : : vector < Future < bool > > const & futures , int const & required ) ; <nl> + Future < Void > lowPriorityDelay ( double const & waitTime ) ; <nl> <nl> ACTOR template < class T > <nl> Future < Void > streamHelper ( PromiseStream < T > output , PromiseStream < Error > errors , Future < T > input ) { <nl> struct FlowLock : NonCopyable , public ReferenceCounted < FlowLock > { <nl> } <nl> } ; <nl> <nl> + struct NotifiedInt { <nl> + NotifiedInt ( int64_t val = 0 ) : val ( val ) { } <nl> + <nl> + Future < Void > whenAtLeast ( int64_t limit ) { <nl> + if ( val > = limit ) <nl> + return Void ( ) ; <nl> + Promise < Void > p ; <nl> + waiting . push ( std : : make_pair ( limit , p ) ) ; <nl> + return p . getFuture ( ) ; <nl> + } <nl> + <nl> + int64_t get ( ) const { return val ; } <nl> + <nl> + void set ( int64_t v ) { <nl> + ASSERT ( v > = val ) ; <nl> + if ( v ! = val ) { <nl> + val = v ; <nl> + <nl> + std : : vector < Promise < Void > > toSend ; <nl> + while ( waiting . size ( ) & & v > = waiting . top ( ) . first ) { <nl> + Promise < Void > p = std : : move ( waiting . top ( ) . second ) ; <nl> + waiting . pop ( ) ; <nl> + toSend . push_back ( p ) ; <nl> + } <nl> + for ( auto & p : toSend ) { <nl> + p . send ( Void ( ) ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + void operator = ( int64_t v ) { <nl> + set ( v ) ; <nl> + } <nl> + <nl> + NotifiedInt ( NotifiedInt & & r ) BOOST_NOEXCEPT : waiting ( std : : move ( r . waiting ) ) , val ( r . val ) { } <nl> + void operator = ( NotifiedInt & & r ) BOOST_NOEXCEPT { waiting = std : : move ( r . waiting ) ; val = r . val ; } <nl> + <nl> + private : <nl> + typedef std : : pair < int64_t , Promise < Void > > Item ; <nl> + struct ItemCompare { <nl> + bool operator ( ) ( const Item & a , const Item & b ) { return a . first > b . first ; } <nl> + } ; <nl> + std : : priority_queue < Item , std : : vector < Item > , ItemCompare > waiting ; <nl> + int64_t val ; <nl> + } ; <nl> + <nl> + struct BoundedFlowLock : NonCopyable , public ReferenceCounted < BoundedFlowLock > { <nl> + / / BoundedFlowLock is different from a FlowLock in that it has a bound on how many locks can be taken from the oldest outstanding lock . <nl> + / / For instance , with a FlowLock that has two permits , if one permit is taken but never released , the other permit can be reused an unlimited <nl> + / / amount of times , but with a BoundedFlowLock , it can only be reused a fixed number of times . <nl> + <nl> + struct Releaser : NonCopyable { <nl> + BoundedFlowLock * lock ; <nl> + int64_t permitNumber ; <nl> + Releaser ( ) : lock ( nullptr ) , permitNumber ( 0 ) { } <nl> + Releaser ( BoundedFlowLock * lock , int64_t permitNumber ) : lock ( lock ) , permitNumber ( permitNumber ) { } <nl> + Releaser ( Releaser & & r ) BOOST_NOEXCEPT : lock ( r . lock ) , permitNumber ( r . permitNumber ) { r . permitNumber = 0 ; } <nl> + void operator = ( Releaser & & r ) { if ( permitNumber ) lock - > release ( permitNumber ) ; lock = r . lock ; permitNumber = r . permitNumber ; r . permitNumber = 0 ; } <nl> + <nl> + void release ( ) { <nl> + if ( permitNumber ) { <nl> + lock - > release ( permitNumber ) ; <nl> + } <nl> + permitNumber = 0 ; <nl> + } <nl> + <nl> + ~ Releaser ( ) { if ( permitNumber ) lock - > release ( permitNumber ) ; } <nl> + } ; <nl> + <nl> + BoundedFlowLock ( ) : unrestrictedPermits ( 1 ) , boundedPermits ( 0 ) , nextPermitNumber ( 0 ) , minOutstanding ( 0 ) { } <nl> + explicit BoundedFlowLock ( int64_t unrestrictedPermits , int64_t boundedPermits ) : unrestrictedPermits ( unrestrictedPermits ) , boundedPermits ( boundedPermits ) , nextPermitNumber ( 0 ) , minOutstanding ( 0 ) { } <nl> + <nl> + Future < int64_t > take ( ) { <nl> + return takeActor ( this ) ; <nl> + } <nl> + void release ( int64_t permitNumber ) { <nl> + outstanding . erase ( permitNumber ) ; <nl> + updateMinOutstanding ( ) ; <nl> + } <nl> + private : <nl> + IndexedSet < int64_t , int64_t > outstanding ; <nl> + NotifiedInt minOutstanding ; <nl> + int64_t nextPermitNumber ; <nl> + const int64_t unrestrictedPermits ; <nl> + const int64_t boundedPermits ; <nl> + <nl> + void updateMinOutstanding ( ) { <nl> + auto it = outstanding . index ( unrestrictedPermits - 1 ) ; <nl> + if ( it = = outstanding . end ( ) ) { <nl> + minOutstanding . set ( nextPermitNumber ) ; <nl> + } else { <nl> + minOutstanding . set ( * it ) ; <nl> + } <nl> + } <nl> + <nl> + ACTOR static Future < int64_t > takeActor ( BoundedFlowLock * lock ) { <nl> + state int64_t permitNumber = + + lock - > nextPermitNumber ; <nl> + lock - > outstanding . insert ( permitNumber , 1 ) ; <nl> + lock - > updateMinOutstanding ( ) ; <nl> + wait ( lock - > minOutstanding . whenAtLeast ( std : : max < int64_t > ( 0 , permitNumber - lock - > boundedPermits ) ) ) ; <nl> + return permitNumber ; <nl> + } <nl> + } ; <nl> + <nl> ACTOR template < class T > <nl> Future < Void > yieldPromiseStream ( FutureStream < T > input , PromiseStream < T > output , TaskPriority taskID = TaskPriority : : DefaultYield ) { <nl> loop { <nl> mmm a / flow / network . cpp <nl> ppp b / flow / network . cpp <nl> TEST_CASE ( " / flow / network / ipaddress " ) { <nl> <nl> return Void ( ) ; <nl> } <nl> + <nl> + NetworkInfo : : NetworkInfo ( ) : handshakeLock ( new BoundedFlowLock ( FLOW_KNOBS - > UNRESTRICTED_HANDSHAKE_LIMIT , FLOW_KNOBS - > BOUNDED_HANDSHAKE_LIMIT ) ) { } <nl> mmm a / flow / network . h <nl> ppp b / flow / network . h <nl> <nl> # include < stdint . h > <nl> # include < variant > <nl> # include " boost / asio . hpp " <nl> + # ifndef TLS_DISABLED <nl> + # include " boost / asio / ssl . hpp " <nl> + # endif <nl> # include " flow / serialize . h " <nl> # include " flow / IRandom . h " <nl> + # include " flow / TLSPolicy . h " <nl> <nl> enum class TaskPriority { <nl> Max = 1000000 , <nl> enum class TaskPriority { <nl> DiskIOComplete = 9150 , <nl> LoadBalancedEndpoint = 9000 , <nl> ReadSocket = 9000 , <nl> + AcceptSocket = 8950 , <nl> + Handshake = 8900 , <nl> CoordinationReply = 8810 , <nl> Coordination = 8800 , <nl> FailureMonitor = 8700 , <nl> enum class TaskPriority { <nl> TLogCommitReply = 8580 , <nl> TLogCommit = 8570 , <nl> ProxyGetRawCommittedVersion = 8565 , <nl> - ProxyCommitYield3 = 8562 , <nl> - ProxyTLogCommitReply = 8560 , <nl> + ProxyMasterVersionReply = 8560 , <nl> ProxyCommitYield2 = 8557 , <nl> - ProxyResolverReply = 8555 , <nl> - ProxyMasterVersionReply = 8550 , <nl> - ProxyCommitYield1 = 8547 , <nl> + ProxyTLogCommitReply = 8555 , <nl> + ProxyCommitYield1 = 8550 , <nl> + ProxyResolverReply = 8547 , <nl> ProxyCommit = 8545 , <nl> ProxyCommitBatcher = 8540 , <nl> TLogConfirmRunningReply = 8530 , <nl> enum class TaskPriority { <nl> CompactCache = 2900 , <nl> TLogSpilledPeekReply = 2800 , <nl> FetchKeys = 2500 , <nl> + RestoreApplierWriteDB = 2400 , <nl> + RestoreApplierReceiveMutations = 2310 , <nl> + RestoreLoaderSendMutations = 2300 , <nl> + RestoreLoaderLoadFiles = 2200 , <nl> Low = 2000 , <nl> <nl> Min = 1000 , <nl> struct NetworkAddressList { <nl> return secondaryAddress < r . secondaryAddress ; <nl> } <nl> <nl> + NetworkAddress getTLSAddress ( ) const { <nl> + if ( ! secondaryAddress . present ( ) | | address . isTLS ( ) ) { <nl> + return address ; <nl> + } <nl> + return secondaryAddress . get ( ) ; <nl> + } <nl> + <nl> std : : string toString ( ) const { <nl> if ( ! secondaryAddress . present ( ) ) { <nl> return address . toString ( ) ; <nl> struct NetworkMetrics { <nl> NetworkMetrics ( ) { } <nl> } ; <nl> <nl> + struct BoundedFlowLock ; <nl> + <nl> struct NetworkInfo { <nl> NetworkMetrics metrics ; <nl> double oldestAlternativesFailure = 0 ; <nl> struct NetworkInfo { <nl> double lastAlternativesFailureSkipDelay = 0 ; <nl> <nl> std : : map < std : : pair < IPAddress , uint16_t > , std : : pair < int , double > > serverTLSConnectionThrottler ; <nl> + BoundedFlowLock * handshakeLock ; <nl> <nl> - NetworkInfo ( ) { } <nl> + NetworkInfo ( ) ; <nl> } ; <nl> <nl> class IEventFD : public ReferenceCounted < IEventFD > { <nl> class IConnection { <nl> / / Closes the underlying connection eventually if it is not already closed . <nl> virtual void close ( ) = 0 ; <nl> <nl> + virtual Future < Void > acceptHandshake ( ) = 0 ; <nl> + <nl> + virtual Future < Void > connectHandshake ( ) = 0 ; <nl> + <nl> / / returns when write ( ) can write at least one byte ( or may throw an error if the connection dies ) <nl> virtual Future < Void > onWritable ( ) = 0 ; <nl> <nl> typedef NetworkAddressList ( * NetworkAddressesFuncPtr ) ( ) ; <nl> <nl> class INetwork ; <nl> extern INetwork * g_network ; <nl> - extern INetwork * newNet2 ( bool useThreadPool = false , bool useMetrics = false ) ; <nl> + extern INetwork * newNet2 ( bool useThreadPool = false , bool useMetrics = false , Reference < TLSPolicy > policy = Reference < TLSPolicy > ( ) , const TLSParams & tlsParams = TLSParams ( ) ) ; <nl> <nl> class INetwork { <nl> public : <nl> class INetwork { <nl> / / Provides a clock that advances at a similar rate on all connected endpoints <nl> / / FIXME : Return a fixed point Time class <nl> <nl> + virtual double timer ( ) = 0 ; <nl> + / / A wrapper for directly getting the system time . The time returned by now ( ) only updates in the run loop , <nl> + / / so it cannot be used to measure times of functions that do not have wait statements . <nl> + <nl> virtual Future < class Void > delay ( double seconds , TaskPriority taskID ) = 0 ; <nl> / / The given future will be set after seconds have elapsed <nl> <nl> mmm a / flow / serialize . h <nl> ppp b / flow / serialize . h <nl> struct _IncludeVersion { <nl> ar > > v ; <nl> if ( ! v . isValid ( ) ) { <nl> auto err = incompatible_protocol_version ( ) ; <nl> - TraceEvent ( SevError , " InvalidSerializationVersion " ) . error ( err ) . detailf ( " Version " , " % llx " , v . versionWithFlags ( ) ) ; <nl> + TraceEvent ( SevWarnAlways , " InvalidSerializationVersion " ) . error ( err ) . detailf ( " Version " , " % llx " , v . versionWithFlags ( ) ) ; <nl> throw err ; <nl> } <nl> if ( v > currentProtocolVersion ) { <nl> struct PacketWriter { <nl> } ; <nl> <nl> struct ISerializeSource { <nl> - virtual void serializePacketWriter ( PacketWriter & , bool useObjectSerializer ) const = 0 ; <nl> - virtual void serializeBinaryWriter ( BinaryWriter & ) const = 0 ; <nl> + virtual void serializePacketWriter ( PacketWriter & ) const = 0 ; <nl> virtual void serializeObjectWriter ( ObjectWriter & ) const = 0 ; <nl> } ; <nl> <nl> template < class T , class V > <nl> struct MakeSerializeSource : ISerializeSource { <nl> using value_type = V ; <nl> - virtual void serializePacketWriter ( PacketWriter & w , bool useObjectSerializer ) const { <nl> - if ( useObjectSerializer ) { <nl> - ObjectWriter writer ( [ & ] ( size_t size ) { return w . writeBytes ( size ) ; } , AssumeVersion ( w . protocolVersion ( ) ) ) ; <nl> - writer . serialize ( get ( ) ) ; / / Writes directly into buffer supplied by | w | <nl> - } else { <nl> - static_cast < T const * > ( this ) - > serialize ( w ) ; <nl> - } <nl> + virtual void serializePacketWriter ( PacketWriter & w ) const { <nl> + ObjectWriter writer ( [ & ] ( size_t size ) { return w . writeBytes ( size ) ; } , AssumeVersion ( w . protocolVersion ( ) ) ) ; <nl> + writer . serialize ( get ( ) ) ; / / Writes directly into buffer supplied by | w | <nl> } <nl> - virtual void serializeBinaryWriter ( BinaryWriter & w ) const { static_cast < T const * > ( this ) - > serialize ( w ) ; } <nl> virtual value_type const & get ( ) const = 0 ; <nl> } ; <nl> <nl> struct SerializeSource : MakeSerializeSource < SerializeSource < T > , T > { <nl> virtual void serializeObjectWriter ( ObjectWriter & w ) const { <nl> w . serialize ( value ) ; <nl> } <nl> - template < class Ar > void serialize ( Ar & ar ) const { <nl> - ar < < value ; <nl> - } <nl> virtual T const & get ( ) const { return value ; } <nl> } ; <nl> <nl> - template < class T > <nl> - struct SerializeBoolAnd : MakeSerializeSource < SerializeBoolAnd < T > , T > { <nl> - using value_type = T ; <nl> - bool b ; <nl> - T const & value ; <nl> - SerializeBoolAnd ( bool b , T const & value ) : b ( b ) , value ( value ) { } <nl> - template < class Ar > void serialize ( Ar & ar ) const { ar < < b < < value ; } <nl> - virtual void serializeObjectWriter ( ObjectWriter & w ) const { <nl> - ASSERT ( false ) ; <nl> - } <nl> - virtual T const & get ( ) const { <nl> - / / This is only used for the streaming serializer <nl> - ASSERT ( false ) ; <nl> - return value ; <nl> - } <nl> - } ; <nl> - <nl> # endif <nl> mmm a / packaging / docker / samples / python / README . md <nl> ppp b / packaging / docker / samples / python / README . md <nl> FDB_CLUSTER_FILE = . / docker . cluster fdbcli <nl> <nl> ` ` ` <nl> docker - compose down <nl> - ` ` ` <nl> \ No newline at end of file <nl> + ` ` ` <nl> + <nl> + # # Use outside of docker - compose <nl> + <nl> + The client application is also available as a standalone image : ` foundationdb / foundationdb - sample - python - app : latest ` . <nl> \ No newline at end of file <nl> mmm a / packaging / docker / samples / python / app / Dockerfile <nl> ppp b / packaging / docker / samples / python / app / Dockerfile <nl> COPY - - from = fdb / usr / lib / libfdb_c . so / usr / lib <nl> COPY - - from = fdb / usr / bin / fdbcli / usr / bin / <nl> COPY - - from = fdb / var / fdb / scripts / create_cluster_file . bash / app <nl> <nl> + ARG FDB_WEBSITE = https : / / foundationdb . org <nl> + ARG FDB_OLDER_VERSIONS = " " <nl> + ENV FDB_NETWORK_OPTION_EXTERNAL_CLIENT_DIRECTORY = / usr / lib / fdb - multiversion <nl> + RUN \ <nl> + mkdir / usr / lib / fdb - multiversion ; \ <nl> + for version in $ { FDB_OLDER_VERSIONS } ; do \ <nl> + wget $ { FDB_WEBSITE } / downloads / $ version / linux / libfdb_c_ $ version . so - O / usr / lib / fdb - multiversion / libfdb_c_ $ version . so ; \ <nl> + done <nl> + <nl> COPY requirements . txt / app <nl> RUN pip install - r requirements . txt <nl> <nl> mmm a / packaging / docker / samples / python / app / requirements . txt <nl> ppp b / packaging / docker / samples / python / app / requirements . txt <nl> <nl> # <nl> <nl> Flask = = 1 . 1 . 1 <nl> - foundationdb = = 6 . 2 . 10 <nl> \ No newline at end of file <nl> + foundationdb = = 6 . 1 . 11 <nl> \ No newline at end of file <nl> mmm a / packaging / docker / samples / python / app / start . bash <nl> ppp b / packaging / docker / samples / python / app / start . bash <nl> <nl> <nl> set - xe ; <nl> <nl> - / app / create_cluster_file . bash <nl> - FDB_CLUSTER_FILE = " $ { FDB_CLUSTER_FILE : - / etc / foundationdb / fdb . cluster } " <nl> + if [ [ ! - n " $ { FDB_CLUSTER_FILE : - } " | | ! - s " $ { FDB_CLUSTER_FILE } " ] ] ; then <nl> + / app / create_cluster_file . bash <nl> + FDB_CLUSTER_FILE = " $ { FDB_CLUSTER_FILE : - / etc / foundationdb / fdb . cluster } " <nl> <nl> - # Attempt to connect . Configure the database if necessary . <nl> - if ! / usr / bin / fdbcli - C $ FDB_CLUSTER_FILE - - exec status - - timeout 3 ; then <nl> - echo " creating the database " <nl> - if ! fdbcli - C $ FDB_CLUSTER_FILE - - exec " configure new single memory ; status " - - timeout 10 ; then <nl> - echo " Unable to configure new FDB cluster . " <nl> - exit 1 <nl> + # Attempt to connect . Configure the database if necessary . <nl> + if ! / usr / bin / fdbcli - C $ FDB_CLUSTER_FILE - - exec status - - timeout 3 ; then <nl> + echo " creating the database " <nl> + if ! fdbcli - C $ FDB_CLUSTER_FILE - - exec " configure new single memory ; status " - - timeout 10 ; then <nl> + echo " Unable to configure new FDB cluster . " <nl> + exit 1 <nl> + fi <nl> fi <nl> fi <nl> <nl> mmm a / packaging / rpm / foundationdb . service <nl> ppp b / packaging / rpm / foundationdb . service <nl> <nl> [ Unit ] <nl> Description = FoundationDB Key - Value Store <nl> - After = syslog . target network . target <nl> + After = syslog . target network - online . target <nl> + Wants = network - online . target <nl> <nl> [ Service ] <nl> Type = forking <nl> mmm a / packaging / rpm / foundationdb . spec . in <nl> ppp b / packaging / rpm / foundationdb . spec . in <nl> Requires : foundationdb - clients = % { version } - % { release } <nl> Conflicts : foundationdb < 0 . 1 . 4 <nl> ifdef ( ` RHEL6 ' , ` Requires ( post ) : chkconfig > = 0 . 9 , / sbin / service ' ) <nl> Requires ( pre ) : / usr / sbin / useradd , / usr / sbin / groupadd , / usr / bin / getent <nl> + # This is a heavy hammer , to remove / usr / bin / python as a dependency , <nl> + # as it also removes dependencies like glibc . However , none of the <nl> + # other strategies ( __requires_exclude ) seem to work . <nl> + AutoReq : 0 <nl> <nl> % package clients <nl> Summary : FoundationDB clients and library <nl> mmm a / tests / CMakeLists . txt <nl> ppp b / tests / CMakeLists . txt <nl> if ( WITH_PYTHON ) <nl> add_fdb_test ( TEST_FILES fast / BackupToDBCorrectness . txt ) <nl> add_fdb_test ( TEST_FILES fast / BackupToDBCorrectnessClean . txt ) <nl> add_fdb_test ( TEST_FILES fast / CloggedSideband . txt ) <nl> + add_fdb_test ( TEST_FILES fast / ConfigureLocked . txt ) <nl> add_fdb_test ( TEST_FILES fast / ConstrainedRandomSelector . txt ) <nl> add_fdb_test ( TEST_FILES fast / CycleAndLock . txt ) <nl> add_fdb_test ( TEST_FILES fast / CycleTest . txt ) <nl> new file mode 100644 <nl> index 0000000000 . . 90be170716 <nl> mmm / dev / null <nl> ppp b / tests / fast / ConfigureLocked . txt <nl> <nl> + testTitle = ConfigureLocked <nl> + testName = LockDatabase <nl> + configureLocked = 1 <nl> + onlyCheckLocked = true <nl> + runConsistencyCheck = false <nl> + clearAfterTest = false <nl> mmm a / tests / slow / ParallelRestoreCorrectnessAtomicOpTinyData . txt <nl> ppp b / tests / slow / ParallelRestoreCorrectnessAtomicOpTinyData . txt <nl> testTitle = BackupAndParallelRestoreWithAtomicOp <nl> <nl> testName = RandomClogging <nl> testDuration = 90 . 0 <nl> - <nl> + <nl> ; testName = Rollback <nl> ; meanDelay = 90 . 0 <nl> ; testDuration = 90 . 0 <nl> testTitle = BackupAndParallelRestoreWithAtomicOp <nl> ; testDuration = 90 . 0 <nl> <nl> ; Disable buggify for parallel restore <nl> - buggify = off <nl> + ; buggify = on <nl> ; testDuration = 360000 ; not work <nl> ; timeout is in seconds <nl> timeout = 360000 <nl> mmm a / tests / slow / ParallelRestoreCorrectnessCycle . txt <nl> ppp b / tests / slow / ParallelRestoreCorrectnessCycle . txt <nl> testTitle = BackupAndRestore <nl> ; testDuration = 90 . 0 <nl> <nl> ; Disable buggify for parallel restore <nl> - buggify = off <nl> + ; buggify = off <nl> ; testDuration = 360000 ; not work <nl> ; timeout is in seconds <nl> timeout = 360000 <nl> | Merge remote - tracking branch ' upstream / master ' | apple/foundationdb | 45a8bbf1a7a892cbbe5ce037c01c0c7aca34500e | 2020-02-25T22:37:17Z |
mmm a / tensorflow / g3doc / how_tos / image_retraining / index . md <nl> ppp b / tensorflow / g3doc / how_tos / image_retraining / index . md <nl> and compact summary of the images , since it has to contain enough information <nl> for the classifier to make a good choice in a very small set of values . The <nl> reason our final layer retraining can work on new classes is that it turns out <nl> the kind of information needed to distinguish between all the 1 , 000 classes in <nl> - ImageNet is often also useful to chose between new kinds of objects . <nl> + ImageNet is often also useful to distinguish between new kinds of objects . <nl> <nl> Because every image is reused multiple times during training and calculating <nl> each bottleneck takes a significant amount of time , it speeds things up to <nl> part again . <nl> Once the bottlenecks are complete , the actual training of the top layer of the <nl> network begins . You ' ll see a series of step outputs , each one showing training <nl> accuracy , validation accuracy , and the cross entropy . The training accuracy <nl> - shows how many of the images used in the current training batch were labeled <nl> - with the correct class . The validation accuracy is the precision on a <nl> + shows what percent of the images used in the current training batch were <nl> + labeled with the correct class . The validation accuracy is the precision on a <nl> randomly - selected group of images from a different set . The key difference is <nl> that the training accuracy is based on images that the network has been able <nl> to learn from so the network can overfit to the noise in the training data . A <nl> true measure of the performance of the network is to measure its performance on <nl> a data set not contained in the training data - - this is measured by the <nl> - validation accuracy . If the test accuracy is high but the validation remains <nl> - low , that means the network is overfitting and memorizing particular features <nl> - in the training images that aren ' t helpful more generally . Cross entropy is a <nl> - loss function which gives a glimpse into how well the learning process is <nl> - progressing . The training ' s objective is to make the loss as small as possible , <nl> - so you can tell if the learning is working by keeping an eye on whether the loss <nl> - keeps trending downwards , ignoring the short - term noise . <nl> + validation accuracy . If the train accuracy is high but the validation accuracy <nl> + remains low , that means the network is overfitting and memorizing particular <nl> + features in the training images that aren ' t helpful more generally . Cross <nl> + entropy is a loss function which gives a glimpse into how well the learning <nl> + process is progressing . The training ' s objective is to make the loss as small as <nl> + possible , so you can tell if the learning is working by keeping an eye on <nl> + whether the loss keeps trending downwards , ignoring the short - term noise . <nl> <nl> By default this script will run 4 , 000 training steps . Each step chooses ten <nl> images at random from the training set , finds their bottlenecks from the cache , <nl> and validation pictures . This test evaluation is the best estimate of how the <nl> trained model will perform on the classification task . You should see an <nl> accuracy value of between 90 % and 95 % , though the exact value will vary from run <nl> to run since there ' s randomness in the training process . This number is based on <nl> - how many of the images in the test set are given the correct label after the <nl> - model is fully trained . <nl> + the percent of the images in the test set that are given the correct label <nl> + after the model is fully trained . <nl> <nl> # # Using the Retrained Model <nl> <nl> memorized unimportant details of the training images . <nl> <nl> This problem is known as overfitting , and to avoid it we keep some of our data <nl> out of the training process , so that the model can ' t memorize them . We then use <nl> - those images as a check to make sure that overfitting isn ' t occuring , since if <nl> + those images as a check to make sure that overfitting isn ' t occurring , since if <nl> we see good accuracy on them it ' s a good sign the network isn ' t overfitting . The <nl> usual split is to put 80 % of the images into the main training set , keep 10 % <nl> aside to run as validation frequently during training , and then have a final 10 % <nl> | Fix typos in image_retraining how - to | tensorflow/tensorflow | f0b09bdcc58ab82726e597a0799d9d3e1ebf4ae4 | 2016-03-03T22:43:03Z |
mmm a / src / rdb_protocol / err . hpp <nl> ppp b / src / rdb_protocol / err . hpp <nl> struct backtrace_t { <nl> RDB_MAKE_ME_SERIALIZABLE_1 ( frames ) ; <nl> <nl> void push_front ( frame_t f ) { <nl> - debugf ( " PUSHING % s \ n " , f . toproto ( ) . DebugString ( ) . c_str ( ) ) ; <nl> + r_sanity_check ( f . is_valid ( ) ) ; <nl> + / / debugf ( " PUSHING % s \ n " , f . toproto ( ) . DebugString ( ) . c_str ( ) ) ; <nl> frames . push_front ( f ) ; <nl> } <nl> private : <nl> void fill_error ( Response2 * res , Response2_ResponseType type , std : : string msg , <nl> try { \ <nl> cmd ; \ <nl> } catch ( exc_t & e ) { \ <nl> - debugf ( " WITH_BT \ n " ) ; \ <nl> e . backtrace . push_front ( N ) ; \ <nl> throw ; \ <nl> } <nl> <nl> # define CATCH_WITH_BT ( N ) catch ( exc_t & e ) { \ <nl> - debugf ( " CATCH_WITH_BT \ n " ) ; \ <nl> e . backtrace . push_front ( N ) ; \ <nl> throw ; \ <nl> } <nl> mmm a / src / rdb_protocol / term . cc <nl> ppp b / src / rdb_protocol / term . cc <nl> term_t : : term_t ( env_t * _env ) : use_cached_val ( false ) , env ( _env ) , cached_val ( 0 ) { <nl> } <nl> term_t : : ~ term_t ( ) { } <nl> <nl> - # define INSTRUMENT 1 <nl> + / / # define INSTRUMENT 1 <nl> # ifdef INSTRUMENT <nl> __thread int __depth = 0 ; <nl> # define DBG ( s , args . . . ) { \ <nl> mmm a / src / rdb_protocol / terms / writes . hpp <nl> ppp b / src / rdb_protocol / terms / writes . hpp <nl> class insert_term_t : public op_term_t { <nl> bool done = false ; <nl> const datum_t * stats = env - > add_ptr ( new datum_t ( datum_t : : R_OBJECT ) ) ; ; <nl> std : : vector < std : : string > generated_keys ; <nl> - if ( arg ( 1 ) - > get_type ( ) . is_convertible ( val_t : : type_t : : DATUM ) ) { <nl> - const datum_t * d = arg ( 1 ) - > as_datum ( ) ; <nl> + val_t * v1 = arg ( 1 ) ; <nl> + if ( v1 - > get_type ( ) . is_convertible ( val_t : : type_t : : DATUM ) ) { <nl> + const datum_t * d = v1 - > as_datum ( ) ; <nl> if ( d - > get_type ( ) = = datum_t : : R_OBJECT ) { <nl> maybe_generate_key ( t , & generated_keys , & d ) ; <nl> stats = stats - > merge ( env , t - > replace ( d , d , upsert ) , stats_merge ) ; <nl> class insert_term_t : public op_term_t { <nl> } <nl> <nl> if ( ! done ) { <nl> - datum_stream_t * ds = arg ( 1 ) - > as_seq ( ) ; <nl> + datum_stream_t * ds = v1 - > as_seq ( ) ; <nl> while ( const datum_t * d = ds - > next ( ) ) { <nl> try { <nl> maybe_generate_key ( t , & generated_keys , & d ) ; <nl> class replace_term_t : public op_term_t { <nl> " Could not prove function deterministic . " <nl> " Maybe you want to use the non_atomic flag ? " ) ; <nl> <nl> - if ( arg ( 0 ) - > get_type ( ) . is_convertible ( val_t : : type_t : : SINGLE_SELECTION ) ) { <nl> - std : : pair < table_t * , const datum_t * > tblrow = arg ( 0 ) - > as_single_selection ( ) ; <nl> + val_t * v0 = arg ( 0 ) ; <nl> + if ( v0 - > get_type ( ) . is_convertible ( val_t : : type_t : : SINGLE_SELECTION ) ) { <nl> + std : : pair < table_t * , const datum_t * > tblrow = v0 - > as_single_selection ( ) ; <nl> return new_val ( tblrow . first - > replace ( tblrow . second , f , nondet_ok ) ) ; <nl> } <nl> - std : : pair < table_t * , datum_stream_t * > tblrows = arg ( 0 ) - > as_selection ( ) ; <nl> + std : : pair < table_t * , datum_stream_t * > tblrows = v0 - > as_selection ( ) ; <nl> table_t * tbl = tblrows . first ; <nl> datum_stream_t * ds = tblrows . second ; <nl> const datum_t * stats = env - > add_ptr ( new datum_t ( datum_t : : R_OBJECT ) ) ; <nl> | removed debugfs | rethinkdb/rethinkdb | 05edfe15e8b26eb8eeb292ac3c695949b3b0ea56 | 2013-02-07T21:43:37Z |
mmm a / Telegram / SourceFiles / history / history . cpp <nl> ppp b / Telegram / SourceFiles / history / history . cpp <nl> HistoryItem * History : : addNewToLastBlock ( <nl> applyMessageChanges ( item , msg ) ; <nl> } <nl> const auto result = addNewItem ( item , newUnreadMessage ) ; <nl> + checkForLoadedAtTop ( result ) ; <nl> if ( type = = NewMessageLast ) { <nl> / / When we add just one last item , like we do while loading dialogs , <nl> / / we want to remove a single added grouped media , otherwise it will <nl> HistoryItem * History : : addNewToLastBlock ( <nl> return result ; <nl> } <nl> <nl> + void History : : checkForLoadedAtTop ( not_null < HistoryItem * > added ) { <nl> + if ( peer - > isChat ( ) ) { <nl> + if ( added - > isGroupEssential ( ) & & ! added - > isGroupMigrate ( ) ) { <nl> + / / We added the first message about group creation . <nl> + _loadedAtTop = true ; <nl> + addEdgesToSharedMedia ( ) ; <nl> + } <nl> + } else if ( peer - > isChannel ( ) ) { <nl> + if ( added - > id = = 1 ) { <nl> + _loadedAtTop = true ; <nl> + checkJoinedMessage ( ) ; <nl> + addEdgesToSharedMedia ( ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> HistoryItem * History : : addToHistory ( const MTPMessage & msg ) { <nl> const auto detachExistingItem = false ; <nl> return createItem ( msg , detachExistingItem ) ; <nl> auto History : : computeChatListMessageFromLast ( ) const <nl> / / about migration in the chats list and display the last <nl> / / non - migration message from the original legacy group . <nl> const auto last = lastMessage ( ) ; <nl> - if ( ! last | | ! last - > isGroupEssential ( ) | | ! last - > isEmpty ( ) ) { <nl> + if ( ! last | | ! last - > isGroupMigrate ( ) ) { <nl> return _lastMessage ; <nl> } <nl> if ( const auto chat = peer - > asChat ( ) ) { <nl> void History : : setFakeChatListMessageFrom ( const MTPmessages_Messages & data ) { <nl> } <nl> } ) ; <nl> const auto last = lastMessage ( ) ; <nl> - if ( ! last | | ! last - > isGroupEssential ( ) | | ! last - > isEmpty ( ) ) { <nl> + if ( ! last | | ! last - > isGroupMigrate ( ) ) { <nl> / / Last message is good enough . <nl> return ; <nl> } <nl> void History : : setFakeChatListMessageFrom ( const MTPmessages_Messages & data ) { <nl> return ; <nl> } <nl> const auto item = owner ( ) . addNewMessage ( * other , NewMessageExisting ) ; <nl> - if ( ! item | | ( item - > isGroupEssential ( ) & & item - > isEmpty ( ) ) ) { <nl> + if ( ! item | | item - > isGroupMigrate ( ) ) { <nl> / / Not better than the last one . <nl> return ; <nl> } <nl> bool History : : isEmpty ( ) const { <nl> } <nl> <nl> bool History : : isDisplayedEmpty ( ) const { <nl> + if ( ! loadedAtTop ( ) | | ! loadedAtBottom ( ) ) { <nl> + return false ; <nl> + } <nl> const auto first = findFirstNonEmpty ( ) ; <nl> if ( ! first ) { <nl> return true ; <nl> - } else if ( ! first - > data ( ) - > isGroupEssential ( ) ) { <nl> + } <nl> + const auto chat = peer - > asChat ( ) ; <nl> + if ( ! chat | | ! chat - > amCreator ( ) ) { <nl> return false ; <nl> - } else if ( const auto chat = peer - > asChat ( ) ) { <nl> - / / For legacy chats we want to show the chat with only first <nl> - / / message about you creating the group as an empty chat with <nl> - / / a nice information about the group features . <nl> - return chat - > amCreator ( ) & & ( findLastNonEmpty ( ) = = first ) ; <nl> - } else { <nl> + } <nl> + <nl> + / / For legacy chats we want to show the chat with only <nl> + / / messages about you creating the group and maybe about you <nl> + / / changing the group photo as an empty chat with <nl> + / / a nice information about the group features . <nl> + if ( nonEmptyCountMoreThan ( 2 ) ) { <nl> return false ; <nl> } <nl> + const auto isChangePhoto = [ ] ( not_null < HistoryItem * > item ) { <nl> + if ( const auto media = item - > media ( ) ) { <nl> + return ( media - > photo ( ) ! = nullptr ) & & ! item - > toHistoryMessage ( ) ; <nl> + } <nl> + return false ; <nl> + } ; <nl> + const auto last = findLastNonEmpty ( ) ; <nl> + if ( first = = last ) { <nl> + return first - > data ( ) - > isGroupEssential ( ) <nl> + | | isChangePhoto ( first - > data ( ) ) ; <nl> + } <nl> + return first - > data ( ) - > isGroupEssential ( ) & & isChangePhoto ( last - > data ( ) ) ; <nl> } <nl> <nl> auto History : : findFirstNonEmpty ( ) const - > Element * { <nl> auto History : : findLastNonEmpty ( ) const - > Element * { <nl> return nullptr ; <nl> } <nl> <nl> + bool History : : nonEmptyCountMoreThan ( int count ) const { <nl> + Expects ( count > = 0 ) ; <nl> + <nl> + for ( const auto & block : blocks ) { <nl> + for ( const auto & element : block - > messages ) { <nl> + if ( ! element - > data ( ) - > isEmpty ( ) ) { <nl> + if ( ! count - - ) { <nl> + return true ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + return false ; <nl> + } <nl> + <nl> bool History : : hasOrphanMediaGroupPart ( ) const { <nl> if ( loadedAtTop ( ) | | ! loadedAtBottom ( ) ) { <nl> return false ; <nl> mmm a / Telegram / SourceFiles / history / history . h <nl> ppp b / Telegram / SourceFiles / history / history . h <nl> class History final : public Dialogs : : Entry { <nl> return _buildingFrontBlock ! = nullptr ; <nl> } <nl> <nl> + void checkForLoadedAtTop ( not_null < HistoryItem * > added ) ; <nl> void mainViewRemoved ( <nl> not_null < HistoryBlock * > block , <nl> not_null < Element * > view ) ; <nl> class History final : public Dialogs : : Entry { <nl> <nl> HistoryItem * lastAvailableMessage ( ) const ; <nl> void getNextFirstUnreadMessage ( ) ; <nl> + bool nonEmptyCountMoreThan ( int count ) const ; <nl> <nl> / / Creates if necessary a new block for adding item . <nl> / / Depending on isBuildingFrontBlock ( ) gets front or back block . <nl> mmm a / Telegram / SourceFiles / history / history_inner_widget . cpp <nl> ppp b / Telegram / SourceFiles / history / history_inner_widget . cpp <nl> void HistoryInner : : paintEvent ( QPaintEvent * e ) { <nl> auto clip = e - > rect ( ) ; <nl> auto ms = getms ( ) ; <nl> <nl> - bool historyDisplayedEmpty = ( _history - > isDisplayedEmpty ( ) & & ( ! _migrated | | _migrated - > isDisplayedEmpty ( ) ) ) ; <nl> + const auto historyDisplayedEmpty = _history - > isDisplayedEmpty ( ) <nl> + & & ( ! _migrated | | _migrated - > isDisplayedEmpty ( ) ) ; <nl> bool noHistoryDisplayed = _firstLoading | | historyDisplayedEmpty ; <nl> if ( ! _firstLoading & & _botAbout & & ! _botAbout - > info - > text . isEmpty ( ) & & _botAbout - > height > 0 ) { <nl> if ( clip . y ( ) < _botAbout - > rect . y ( ) + _botAbout - > rect . height ( ) & & clip . y ( ) + clip . height ( ) > _botAbout - > rect . y ( ) ) { <nl> void HistoryInner : : paintEvent ( QPaintEvent * e ) { <nl> } <nl> } else if ( historyDisplayedEmpty ) { <nl> paintEmpty ( p , width ( ) , height ( ) ) ; <nl> + } else { <nl> + _emptyPainter = nullptr ; <nl> } <nl> if ( ! noHistoryDisplayed ) { <nl> auto readMentions = base : : flat_set < not_null < HistoryItem * > > ( ) ; <nl> mmm a / Telegram / SourceFiles / history / history_inner_widget . h <nl> ppp b / Telegram / SourceFiles / history / history_inner_widget . h <nl> class HistoryInner <nl> void messagesReceivedDown ( PeerData * peer , const QVector < MTPMessage > & messages ) ; <nl> <nl> TextWithEntities getSelectedText ( ) const ; <nl> - void paintEmpty ( Painter & p , int width , int height ) ; <nl> <nl> void touchScrollUpdated ( const QPoint & screenPos ) ; <nl> <nl> public slots : <nl> std : : unique_ptr < QMimeData > prepareDrag ( ) ; <nl> void performDrag ( ) ; <nl> <nl> + void paintEmpty ( Painter & p , int width , int height ) ; <nl> + <nl> QPoint mapPointToItem ( QPoint p , const Element * view ) const ; <nl> QPoint mapPointToItem ( QPoint p , const HistoryItem * item ) const ; <nl> <nl> mmm a / Telegram / SourceFiles / history / history_item . cpp <nl> ppp b / Telegram / SourceFiles / history / history_item . cpp <nl> bool HistoryItem : : canDelete ( ) const { <nl> } <nl> auto channel = _history - > peer - > asChannel ( ) ; <nl> if ( ! channel ) { <nl> - return ! ( _flags & MTPDmessage_ClientFlag : : f_is_group_essential ) ; <nl> + return ! isGroupMigrate ( ) ; <nl> } <nl> <nl> if ( id = = 1 ) { <nl> mmm a / Telegram / SourceFiles / history / history_item . h <nl> ppp b / Telegram / SourceFiles / history / history_item . h <nl> class HistoryItem : public RuntimeComposer < HistoryItem > { <nl> bool isGroupEssential ( ) const { <nl> return _flags & MTPDmessage_ClientFlag : : f_is_group_essential ; <nl> } <nl> + bool isGroupMigrate ( ) const { <nl> + return isGroupEssential ( ) & & isEmpty ( ) ; <nl> + } <nl> bool hasViews ( ) const { <nl> return _flags & MTPDmessage : : Flag : : f_views ; <nl> } <nl> mmm a / Telegram / SourceFiles / history / history_widget . cpp <nl> ppp b / Telegram / SourceFiles / history / history_widget . cpp <nl> void HistoryWidget : : paintEvent ( QPaintEvent * e ) { <nl> if ( _pinnedBar & & ! _pinnedBar - > cancel - > isHidden ( ) ) { <nl> drawPinnedBar ( p ) ; <nl> } <nl> - if ( _scroll - > isHidden ( ) & & _history ) { <nl> - p . setClipRect ( _scroll - > geometry ( ) ) ; <nl> - _list - > paintEmpty ( <nl> - p , <nl> - width ( ) , <nl> - height ( ) - _field - > height ( ) - 2 * st : : historySendPadding ) ; <nl> - } <nl> } else { <nl> const auto w = st : : msgServiceFont - > width ( lang ( lng_willbe_history ) ) <nl> + st : : msgPadding . left ( ) <nl> mmm a / Telegram / SourceFiles / history / view / history_view_service_message . cpp <nl> ppp b / Telegram / SourceFiles / history / view / history_view_service_message . cpp <nl> void EmptyPainter : : fillAboutGroup ( ) { <nl> text . setText ( <nl> st : : serviceTextStyle , <nl> content , <nl> - Ui : : ItemTextServiceOptions ( ) ) ; <nl> + Ui : : NameTextOptions ( ) ) ; <nl> } ; <nl> setText ( _header , lang ( lng_group_about_header ) ) ; <nl> setText ( _text , lang ( lng_group_about_text ) ) ; <nl> void EmptyPainter : : paint ( Painter & p , int width , int height ) { <nl> + st : : historyGroupAboutSkip * int ( _phrases . size ( ) - 1 ) <nl> + padding . bottom ( ) ; <nl> const auto bubbleLeft = ( width - bubbleWidth ) / 2 ; <nl> - const auto bubbleTop = ( height - bubbleHeight ) / 3 ; <nl> + const auto bubbleTop = ( height - bubbleHeight ) / 2 ; <nl> <nl> ServiceMessagePainter : : paintBubble ( <nl> p , <nl> | Improve empty group display . | telegramdesktop/tdesktop | ebc20430555d7ea9f17b9fc3fdda8c2d27b52f58 | 2019-01-22T07:50:21Z |
mmm a / tensorflow / core / graph / mkl_layout_pass_test . cc <nl> ppp b / tensorflow / core / graph / mkl_layout_pass_test . cc <nl> BENCHMARK ( BM_MklLayoutRewritePass ) - > Arg ( 1000 ) - > Arg ( 10000 ) ; <nl> <nl> # else / / INTEL_MKL_ML <nl> <nl> + / / NOTE : Unit tests in this file rely on a topological sorted graph for <nl> + / / printing . But since sibling nodes of a node in the topologically sorted graph <nl> + / / can be printed in different orders , tests may fail if the order in which <nl> + / / sibling nodes are visited is changed . <nl> + <nl> namespace { <nl> <nl> const char kCPUDevice [ ] = " / job : a / replica : 0 / task : 0 / device : CPU : 0 " ; <nl> TEST_F ( MklLayoutPassTest , NodeRewrite_Concat_Input_Mkl ) { <nl> " A ( Input ) ; B ( Input ) ; C ( Input ) ; D ( Input ) ; DMT / _0 ( Const ) ; DMT / _1 ( Const ) ; " <nl> " DMT / _2 ( Const ) ; DMT / _3 ( Const ) ; DMT / _4 ( Const ) ; E ( _MklConv2D ) ; " <nl> " F ( _MklConv2D ) ; G ( Const ) ; H ( _MklConcat ) ; I ( Zeta ) | A - > E ; A - > I ; " <nl> - " A : control - > DMT / _2 : control ; A : control - > DMT / _3 : control ; " <nl> - " B - > E : 1 ; C - > F ; C : control - > DMT / _0 : control ; C : control - > DMT / _1 : control ; " <nl> - " D - > F : 1 ; DMT / _0 - > F : 2 ; DMT / _1 - > F : 3 ; DMT / _2 - > E : 2 ; DMT / _3 - > E : 3 ; " <nl> + " A : control - > DMT / _0 : control ; A : control - > DMT / _1 : control ; " <nl> + " B - > E : 1 ; C - > F ; C : control - > DMT / _2 : control ; C : control - > DMT / _3 : control ; " <nl> + " D - > F : 1 ; DMT / _0 - > E : 2 ; DMT / _1 - > E : 3 ; DMT / _2 - > F : 2 ; DMT / _3 - > F : 3 ; " <nl> " DMT / _4 - > H : 3 ; E - > H : 1 ; E : 2 - > H : 4 ; F - > H : 2 ; F : 2 - > H : 5 ; G - > H ; " <nl> " G : control - > DMT / _4 : control ; H - > I : 1 " ) ; <nl> } <nl> TEST_F ( MklLayoutPassTest , NodeRewrite_ConcatV2_Input_Mkl ) { <nl> " A ( Input ) ; B ( Input ) ; C ( Input ) ; D ( Input ) ; DMT / _0 ( Const ) ; DMT / _1 ( Const ) ; " <nl> " DMT / _2 ( Const ) ; DMT / _3 ( Const ) ; DMT / _4 ( Const ) ; E ( _MklConv2D ) ; " <nl> " F ( _MklConv2D ) ; G ( Const ) ; H ( _MklConcatV2 ) ; I ( Zeta ) | A - > E ; A - > I ; " <nl> - " A : control - > DMT / _2 : control ; A : control - > DMT / _3 : control ; B - > E : 1 ; C - > F ; " <nl> - " C : control - > DMT / _0 : control ; C : control - > DMT / _1 : control ; " <nl> - " D - > F : 1 ; DMT / _0 - > F : 2 ; DMT / _1 - > F : 3 ; DMT / _2 - > E : 2 ; DMT / _3 - > E : 3 ; " <nl> + " A : control - > DMT / _0 : control ; A : control - > DMT / _1 : control ; B - > E : 1 ; C - > F ; " <nl> + " C : control - > DMT / _2 : control ; C : control - > DMT / _3 : control ; " <nl> + " D - > F : 1 ; DMT / _0 - > E : 2 ; DMT / _1 - > E : 3 ; DMT / _2 - > F : 2 ; DMT / _3 - > F : 3 ; " <nl> " DMT / _4 - > H : 5 ; E - > H ; E : 2 - > H : 3 ; E : control - > DMT / _4 : control ; F - > H : 1 ; " <nl> " F : 2 - > H : 4 ; G - > H : 2 ; H - > I : 1 " ) ; <nl> } <nl> TEST_F ( MklLayoutPassTest , LRN_Negative3 ) { <nl> " C : control - > DMT / _1 : control ; C : control - > DMT / _2 : control ; " <nl> " C : control - > DMT / _3 : control ; C : control - > DMT / _4 : control ; " <nl> " C : control - > DMT / _5 : control ; C : control - > DMT / _6 : control ; " <nl> - " D - > E : 1 ; D - > F : 2 ; DMT / _0 - > B : 1 ; DMT / _1 - > F : 3 ; DMT / _2 - > F : 7 ; DMT / _3 - > F : 4 ; " <nl> - " DMT / _4 - > F : 6 ; DMT / _5 - > E : 4 ; DMT / _6 - > E : 5 ; E - > G ; F - > G : 1 " ) ; <nl> + " D - > E : 1 ; D - > F : 2 ; DMT / _0 - > B : 1 ; DMT / _1 - > E : 4 ; DMT / _2 - > E : 5 ; DMT / _3 - > F : 3 ; " <nl> + " DMT / _4 - > F : 7 ; DMT / _5 - > F : 4 ; DMT / _6 - > F : 6 ; E - > G ; F - > G : 1 " ) ; <nl> } <nl> <nl> / * Test MaxPool - > MaxPoolGrad replacement by workspace + rewrite nodes . * / <nl> | [ Intel MKL ] Fixing MKL graph layout pass test ( ) | tensorflow/tensorflow | ff7e6399443615675a3f1182c4f2e1850008da04 | 2018-06-18T16:25:00Z |
new file mode 100644 <nl> index 000000000000 . . fd9a7328080f <nl> mmm / dev / null <nl> ppp b / jstests / replsets / state_change_errors_return_topology_version . js <nl> <nl> + / * * <nl> + * This tests that state change errors include a TopologyVersion field . <nl> + * <nl> + * @ tags : [ requires_fcv_44 ] <nl> + * / <nl> + <nl> + ( function ( ) { <nl> + " use strict " ; <nl> + <nl> + const rst = new ReplSetTest ( { nodes : 1 } ) ; <nl> + rst . startSet ( ) ; <nl> + rst . initiate ( ) ; <nl> + <nl> + const dbName = " test " ; <nl> + const collName = " state_change_errors_return_topology_version " ; <nl> + const primary = rst . getPrimary ( ) ; <nl> + const primaryDB = primary . getDB ( dbName ) ; <nl> + <nl> + const stateChangeErrorCodes = [ <nl> + ErrorCodes . InterruptedAtShutdown , <nl> + ErrorCodes . InterruptedDueToReplStateChange , <nl> + ErrorCodes . ShutdownInProgress , <nl> + ErrorCodes . NotMaster , <nl> + ErrorCodes . NotMasterNoSlaveOk , <nl> + ErrorCodes . NotMasterOrSecondary , <nl> + ErrorCodes . PrimarySteppedDown <nl> + ] ; <nl> + <nl> + function runFailInCommandDispatch ( errorCode , isWCError ) { <nl> + jsTestLog ( ` Testing with errorCode : $ { <nl> + errorCode } with failPoint : failWithErrorCodeInCommandDispatch , isWCError : $ { isWCError } . ` ) ; <nl> + <nl> + if ( isWCError ) { <nl> + assert . commandWorked ( primary . adminCommand ( { <nl> + configureFailPoint : " failCommand " , <nl> + mode : " alwaysOn " , <nl> + data : { <nl> + writeConcernError : { code : NumberInt ( errorCode ) , errmsg : " dummy " } , <nl> + failCommands : [ " insert " ] , <nl> + } <nl> + } ) ) ; <nl> + } else { <nl> + assert . commandWorked ( primary . adminCommand ( { <nl> + configureFailPoint : " failCommand " , <nl> + mode : " alwaysOn " , <nl> + data : { <nl> + errorCode : NumberInt ( errorCode ) , <nl> + failCommands : [ " insert " ] , <nl> + } <nl> + } ) ) ; <nl> + } <nl> + <nl> + const res = primaryDB . runCommand ( { insert : collName , documents : [ { x : 1 } ] } ) ; <nl> + assert . commandFailedWithCode ( res , errorCode ) ; <nl> + / / Only StateChangeErrors should return TopologyVersion in the response . <nl> + if ( stateChangeErrorCodes . includes ( errorCode ) ) { <nl> + assert ( res . hasOwnProperty ( " topologyVersion " ) , tojson ( res ) ) ; <nl> + } else { <nl> + assert ( ! res . hasOwnProperty ( " topologyVersion " ) , tojson ( res ) ) ; <nl> + } <nl> + assert . commandWorked ( primary . adminCommand ( { configureFailPoint : " failCommand " , mode : " off " } ) ) ; <nl> + } <nl> + <nl> + function runFailInRunCommand ( errorCode ) { <nl> + jsTestLog ( <nl> + ` Testing with errorCode : $ { errorCode } with failPoint : failWithErrorCodeInRunCommand . ` ) ; <nl> + <nl> + assert . commandWorked ( primary . adminCommand ( { <nl> + configureFailPoint : " failWithErrorCodeInRunCommand " , <nl> + mode : " alwaysOn " , <nl> + data : { <nl> + errorCode : NumberInt ( errorCode ) , <nl> + } <nl> + } ) ) ; <nl> + <nl> + const res = primaryDB . runCommand ( { insert : collName , documents : [ { x : 1 } ] } ) ; <nl> + assert . commandFailedWithCode ( res , errorCode ) ; <nl> + / / Only StateChangeErrors should return TopologyVersion in the response . <nl> + if ( stateChangeErrorCodes . includes ( errorCode ) ) { <nl> + assert ( res . hasOwnProperty ( " topologyVersion " ) , tojson ( res ) ) ; <nl> + } else { <nl> + assert ( ! res . hasOwnProperty ( " topologyVersion " ) , tojson ( res ) ) ; <nl> + } <nl> + / / We expect ' configureFailPoint ' to succeed here since the ' failWithErrorCodeInRunCommand ' fail <nl> + / / point only affects commands that support writeConcern . <nl> + assert . commandWorked ( <nl> + primary . adminCommand ( { configureFailPoint : " failWithErrorCodeInRunCommand " , mode : " off " } ) ) ; <nl> + } <nl> + <nl> + stateChangeErrorCodes . forEach ( function ( code ) { <nl> + runFailInCommandDispatch ( code , true / * isWCError * / ) ; <nl> + runFailInCommandDispatch ( code , false / * isWCError * / ) ; <nl> + } ) ; <nl> + <nl> + / / Test that errors that are not state change errors will not return a TopologyVersion . <nl> + runFailInCommandDispatch ( ErrorCodes . InternalError , true / * isWCError * / ) ; <nl> + runFailInCommandDispatch ( ErrorCodes . InternalError , false / * isWCError * / ) ; <nl> + <nl> + stateChangeErrorCodes . forEach ( function ( code ) { <nl> + runFailInRunCommand ( code ) ; <nl> + } ) ; <nl> + runFailInRunCommand ( ErrorCodes . InternalError ) ; <nl> + rst . stopSet ( ) ; <nl> + } ) ( ) ; <nl> mmm a / src / mongo / db / SConscript <nl> ppp b / src / mongo / db / SConscript <nl> env . Library ( <nl> ' $ BUILD_DIR / mongo / db / storage / storage_engine_lock_file ' , <nl> ' $ BUILD_DIR / mongo / db / storage / storage_engine_metadata ' , <nl> ' commands / server_status_core ' , <nl> + ' repl / replica_set_messages ' , <nl> ] , <nl> ) <nl> <nl> mmm a / src / mongo / db / repl / SConscript <nl> ppp b / src / mongo / db / repl / SConscript <nl> env . Library ( ' topology_coordinator ' , <nl> ' $ BUILD_DIR / mongo / db / audit ' , <nl> ' $ BUILD_DIR / mongo / rpc / metadata ' , <nl> ' $ BUILD_DIR / mongo / util / fail_point ' , <nl> + ' isself ' , <nl> ' replica_set_messages ' , <nl> ' repl_settings ' , <nl> ' rslog ' , <nl> env . Library ( ' topology_coordinator ' , <nl> LIBDEPS_PRIVATE = [ <nl> ' $ BUILD_DIR / mongo / db / catalog / commit_quorum_options ' , <nl> ' $ BUILD_DIR / mongo / idl / server_parameter ' , <nl> - ' isself ' , <nl> ] ) <nl> <nl> env . Library ( <nl> mmm a / src / mongo / db / repl / replication_coordinator . h <nl> ppp b / src / mongo / db / repl / replication_coordinator . h <nl> class ReplicationCoordinator : public SyncSourceSelector { <nl> * / <nl> virtual long long getTerm ( ) const = 0 ; <nl> <nl> + / * * <nl> + * Returns the TopologyVersion . It is possible to return a stale value . This is safe because <nl> + * we expect the ' processId ' field to never change and ' counter ' should always be increasing . <nl> + * / <nl> + virtual TopologyVersion getTopologyVersion ( ) const = 0 ; <nl> + <nl> / * * <nl> * Attempts to update the current term for the V1 election protocol . If the term changes and <nl> * this node is primary , relinquishes primary . <nl> mmm a / src / mongo / db / repl / replication_coordinator_impl . cpp <nl> ppp b / src / mongo / db / repl / replication_coordinator_impl . cpp <nl> <nl> # include " mongo / db / repl / check_quorum_for_config_change . h " <nl> # include " mongo / db / repl / data_replicator_external_state_initial_sync . h " <nl> # include " mongo / db / repl / is_master_response . h " <nl> + # include " mongo / db / repl / isself . h " <nl> # include " mongo / db / repl / last_vote . h " <nl> # include " mongo / db / repl / local_oplog_info . h " <nl> # include " mongo / db / repl / read_concern_args . h " <nl> void ReplicationCoordinatorImpl : : _setConfigState_inlock ( ConfigState newState ) { <nl> void ReplicationCoordinatorImpl : : _fulfillTopologyChangePromise ( OperationContext * opCtx , <nl> WithLock lock ) { <nl> _topCoord - > incrementTopologyVersion ( ) ; <nl> + _cachedTopologyVersionCounter . store ( _topCoord - > getTopologyVersion ( ) . getCounter ( ) ) ; <nl> / / Create an isMaster response for each horizon the server is knowledgeable about . <nl> for ( auto iter = _horizonToPromiseMap . begin ( ) ; iter ! = _horizonToPromiseMap . end ( ) ; iter + + ) { <nl> auto response = _makeIsMasterResponse ( iter - > first , lock ) ; <nl> long long ReplicationCoordinatorImpl : : getTerm ( ) const { <nl> return _termShadow . load ( ) ; <nl> } <nl> <nl> + TopologyVersion ReplicationCoordinatorImpl : : getTopologyVersion ( ) const { <nl> + return TopologyVersion ( repl : : instanceId , _cachedTopologyVersionCounter . load ( ) ) ; <nl> + } <nl> + <nl> EventHandle ReplicationCoordinatorImpl : : updateTerm_forTest ( <nl> long long term , TopologyCoordinator : : UpdateTermResult * updateResult ) { <nl> stdx : : lock_guard < Latch > lock ( _mutex ) ; <nl> mmm a / src / mongo / db / repl / replication_coordinator_impl . h <nl> ppp b / src / mongo / db / repl / replication_coordinator_impl . h <nl> class ReplicationCoordinatorImpl : public ReplicationCoordinator { <nl> const size_t numOpsKilled , <nl> const size_t numOpsRunning ) const override ; <nl> <nl> + virtual TopologyVersion getTopologyVersion ( ) const override ; <nl> + <nl> virtual std : : shared_ptr < const IsMasterResponse > awaitIsMasterResponse ( <nl> OperationContext * opCtx , <nl> const SplitHorizon : : Parameters & horizonParams , <nl> class ReplicationCoordinatorImpl : public ReplicationCoordinator { <nl> <nl> / / If we ' re in terminal shutdown . If true , we ' ll refuse to vote in elections . <nl> bool _inTerminalShutdown = false ; / / ( M ) <nl> + <nl> + / / The cached value of the ' counter ' field in the server ' s TopologyVersion . <nl> + AtomicWord < int64_t > _cachedTopologyVersionCounter ; / / ( S ) <nl> } ; <nl> <nl> } / / namespace repl <nl> mmm a / src / mongo / db / repl / replication_coordinator_mock . cpp <nl> ppp b / src / mongo / db / repl / replication_coordinator_mock . cpp <nl> void ReplicationCoordinatorMock : : updateAndLogStateTransitionMetrics ( <nl> return ; <nl> } <nl> <nl> + TopologyVersion ReplicationCoordinatorMock : : getTopologyVersion ( ) const { <nl> + return TopologyVersion ( repl : : instanceId , 0 ) ; <nl> + } <nl> + <nl> std : : shared_ptr < const IsMasterResponse > ReplicationCoordinatorMock : : awaitIsMasterResponse ( <nl> OperationContext * opCtx , <nl> const SplitHorizon : : Parameters & horizonParams , <nl> mmm a / src / mongo / db / repl / replication_coordinator_mock . h <nl> ppp b / src / mongo / db / repl / replication_coordinator_mock . h <nl> class ReplicationCoordinatorMock : public ReplicationCoordinator { <nl> <nl> virtual void setCanAcceptNonLocalWrites ( bool canAcceptNonLocalWrites ) ; <nl> <nl> + virtual TopologyVersion getTopologyVersion ( ) const ; <nl> + <nl> virtual std : : shared_ptr < const IsMasterResponse > awaitIsMasterResponse ( <nl> OperationContext * opCtx , <nl> const SplitHorizon : : Parameters & horizonParams , <nl> mmm a / src / mongo / db / repl / replication_coordinator_noop . cpp <nl> ppp b / src / mongo / db / repl / replication_coordinator_noop . cpp <nl> void ReplicationCoordinatorNoOp : : updateAndLogStateTransitionMetrics ( <nl> MONGO_UNREACHABLE ; <nl> } <nl> <nl> + TopologyVersion ReplicationCoordinatorNoOp : : getTopologyVersion ( ) const { <nl> + MONGO_UNREACHABLE ; <nl> + } <nl> + <nl> std : : shared_ptr < const IsMasterResponse > ReplicationCoordinatorNoOp : : awaitIsMasterResponse ( <nl> OperationContext * opCtx , <nl> const SplitHorizon : : Parameters & horizonParams , <nl> mmm a / src / mongo / db / repl / replication_coordinator_noop . h <nl> ppp b / src / mongo / db / repl / replication_coordinator_noop . h <nl> class ReplicationCoordinatorNoOp final : public ReplicationCoordinator { <nl> const size_t numOpsKilled , <nl> const size_t numOpsRunning ) const final ; <nl> <nl> + TopologyVersion getTopologyVersion ( ) const final ; <nl> + <nl> std : : shared_ptr < const IsMasterResponse > awaitIsMasterResponse ( <nl> OperationContext * opCtx , <nl> const SplitHorizon : : Parameters & horizonParams , <nl> mmm a / src / mongo / db / service_entry_point_common . cpp <nl> ppp b / src / mongo / db / service_entry_point_common . cpp <nl> MONGO_FAIL_POINT_DEFINE ( skipCheckingForNotMasterInCommandDispatch ) ; <nl> MONGO_FAIL_POINT_DEFINE ( sleepMillisAfterCommandExecutionBegins ) ; <nl> MONGO_FAIL_POINT_DEFINE ( waitAfterNewStatementBlocksBehindPrepare ) ; <nl> MONGO_FAIL_POINT_DEFINE ( waitAfterCommandFinishesExecution ) ; <nl> + MONGO_FAIL_POINT_DEFINE ( failWithErrorCodeInRunCommand ) ; <nl> <nl> / / Tracks the number of times a legacy unacknowledged write failed due to <nl> / / not master error resulted in network disconnection . <nl> void appendClusterAndOperationTime ( OperationContext * opCtx , <nl> operationTime . appendAsOperationTime ( commandBodyFieldsBob ) ; <nl> } <nl> <nl> + void appendErrorLabelsAndTopologyVersion ( OperationContext * opCtx , <nl> + BSONObjBuilder * commandBodyFieldsBob , <nl> + const OperationSessionInfoFromClient & sessionOptions , <nl> + const std : : string & commandName , <nl> + boost : : optional < ErrorCodes : : Error > code , <nl> + boost : : optional < ErrorCodes : : Error > wcCode , <nl> + bool isInternalClient ) { <nl> + auto errorLabels = <nl> + getErrorLabels ( opCtx , sessionOptions , commandName , code , wcCode , isInternalClient ) ; <nl> + commandBodyFieldsBob - > appendElements ( errorLabels ) ; <nl> + <nl> + auto isStateChangeError = false ; <nl> + if ( code ) { <nl> + isStateChangeError = ErrorCodes : : isA < ErrorCategory : : NotMasterError > ( * code ) | | <nl> + ErrorCodes : : isA < ErrorCategory : : ShutdownError > ( * code ) ; <nl> + } <nl> + <nl> + if ( ! isStateChangeError & & wcCode ) { <nl> + isStateChangeError = ErrorCodes : : isA < ErrorCategory : : NotMasterError > ( * wcCode ) | | <nl> + ErrorCodes : : isA < ErrorCategory : : ShutdownError > ( * wcCode ) ; <nl> + } <nl> + <nl> + const auto replCoord = repl : : ReplicationCoordinator : : get ( opCtx ) ; <nl> + if ( replCoord - > getReplicationMode ( ) ! = repl : : ReplicationCoordinator : : modeReplSet | | <nl> + ! isStateChangeError ) { <nl> + return ; <nl> + } <nl> + const auto topologyVersion = replCoord - > getTopologyVersion ( ) ; <nl> + BSONObjBuilder topologyVersionBuilder ( commandBodyFieldsBob - > subobjStart ( " topologyVersion " ) ) ; <nl> + topologyVersion . serialize ( & topologyVersionBuilder ) ; <nl> + } <nl> + <nl> namespace { <nl> void _abortUnpreparedOrStashPreparedTransaction ( <nl> OperationContext * opCtx , TransactionParticipant : : Participant * txnParticipant ) { <nl> bool runCommandImpl ( OperationContext * opCtx , <nl> } ; <nl> <nl> try { <nl> - if ( shouldCheckOutSession ) { <nl> + if ( MONGO_unlikely ( failWithErrorCodeInRunCommand . shouldFail ( ) ) ) { <nl> + auto scoped = failWithErrorCodeInRunCommand . scoped ( ) ; <nl> + const auto errorCode = scoped . getData ( ) [ " errorCode " ] . numberInt ( ) ; <nl> + log ( ) < < " failWithErrorCodeInRunCommand enabled - failing command with error " <nl> + " code : " <nl> + < < errorCode ; <nl> + BSONObjBuilder errorBuilder ; <nl> + errorBuilder . append ( " ok " , 0 . 0 ) ; <nl> + errorBuilder . append ( " code " , errorCode ) ; <nl> + errorBuilder . append ( " errmsg " , " failWithErrorCodeInRunCommand enabled . " ) ; <nl> + replyBuilder - > setCommandReply ( errorBuilder . obj ( ) ) ; <nl> + } else if ( shouldCheckOutSession ) { <nl> invokeWithSessionCheckedOut ( opCtx , invocation , sessionOptions , replyBuilder ) ; <nl> } else { <nl> invocation - > run ( opCtx , replyBuilder ) ; <nl> bool runCommandImpl ( OperationContext * opCtx , <nl> behaviors . attachCurOpErrInfo ( opCtx , replyBuilder - > getBodyBuilder ( ) . asTempObj ( ) ) ; <nl> <nl> { <nl> - boost : : optional < ErrorCodes : : Error > wcCode ; <nl> boost : : optional < ErrorCodes : : Error > code ; <nl> - auto response = replyBuilder - > getBodyBuilder ( ) . asTempObj ( ) ; <nl> + boost : : optional < ErrorCodes : : Error > wcCode ; <nl> + auto body = replyBuilder - > getBodyBuilder ( ) ; <nl> + auto response = body . asTempObj ( ) ; <nl> auto codeField = response [ " code " ] ; <nl> if ( ! ok & & codeField . isNumber ( ) ) { <nl> code = ErrorCodes : : Error ( codeField . numberInt ( ) ) ; <nl> bool runCommandImpl ( OperationContext * opCtx , <nl> } <nl> auto isInternalClient = opCtx - > getClient ( ) - > session ( ) & & <nl> ( opCtx - > getClient ( ) - > session ( ) - > getTags ( ) & transport : : Session : : kInternalClient ) ; <nl> - auto errorLabels = getErrorLabels ( <nl> - opCtx , sessionOptions , command - > getName ( ) , code , wcCode , isInternalClient ) ; <nl> - replyBuilder - > getBodyBuilder ( ) . appendElements ( errorLabels ) ; <nl> + appendErrorLabelsAndTopologyVersion ( <nl> + opCtx , & body , sessionOptions , command - > getName ( ) , code , wcCode , isInternalClient ) ; <nl> } <nl> <nl> auto commandBodyBob = replyBuilder - > getBodyBuilder ( ) ; <nl> behaviors . appendReplyMetadata ( opCtx , request , & commandBodyBob ) ; <nl> appendClusterAndOperationTime ( opCtx , & commandBodyBob , & commandBodyBob , startOperationTime ) ; <nl> - <nl> return ok ; <nl> } <nl> <nl> void execCommandDatabase ( OperationContext * opCtx , <nl> } <nl> auto isInternalClient = opCtx - > getClient ( ) - > session ( ) & & <nl> ( opCtx - > getClient ( ) - > session ( ) - > getTags ( ) & transport : : Session : : kInternalClient ) ; <nl> - auto errorLabels = getErrorLabels ( <nl> - opCtx , sessionOptions , command - > getName ( ) , e . code ( ) , wcCode , isInternalClient ) ; <nl> - extraFieldsBuilder . appendElements ( errorLabels ) ; <nl> + appendErrorLabelsAndTopologyVersion ( opCtx , <nl> + & extraFieldsBuilder , <nl> + sessionOptions , <nl> + command - > getName ( ) , <nl> + e . code ( ) , <nl> + wcCode , <nl> + isInternalClient ) ; <nl> <nl> BSONObjBuilder metadataBob ; <nl> behaviors . appendReplyMetadata ( opCtx , request , & metadataBob ) ; <nl> mmm a / src / mongo / embedded / replication_coordinator_embedded . cpp <nl> ppp b / src / mongo / embedded / replication_coordinator_embedded . cpp <nl> void ReplicationCoordinatorEmbedded : : updateAndLogStateTransitionMetrics ( <nl> UASSERT_NOT_IMPLEMENTED ; <nl> } <nl> <nl> + TopologyVersion ReplicationCoordinatorEmbedded : : getTopologyVersion ( ) const { <nl> + UASSERT_NOT_IMPLEMENTED ; <nl> + } <nl> + <nl> std : : shared_ptr < const repl : : IsMasterResponse > ReplicationCoordinatorEmbedded : : awaitIsMasterResponse ( <nl> OperationContext * opCtx , <nl> const repl : : SplitHorizon : : Parameters & horizonParams , <nl> mmm a / src / mongo / embedded / replication_coordinator_embedded . h <nl> ppp b / src / mongo / embedded / replication_coordinator_embedded . h <nl> class ReplicationCoordinatorEmbedded final : public repl : : ReplicationCoordinator <nl> const size_t numOpsKilled , <nl> const size_t numOpsRunning ) const override ; <nl> <nl> + TopologyVersion getTopologyVersion ( ) const override ; <nl> + <nl> std : : shared_ptr < const repl : : IsMasterResponse > awaitIsMasterResponse ( <nl> OperationContext * opCtx , <nl> const repl : : SplitHorizon : : Parameters & horizonParams , <nl> | SERVER - 44518 Add TopologyVersion to State Change Errors . | mongodb/mongo | 30b8a9ee82306012a1a344c684932df1b15f1be8 | 2020-01-21T22:07:40Z |
mmm a / lib / Sema / TypeCheckConstraintsGen . cpp <nl> ppp b / lib / Sema / TypeCheckConstraintsGen . cpp <nl> namespace { <nl> Type ty = CS . createTypeVariable ( CS . getConstraintLocator ( locator ) , <nl> / * canBindToLValue * / forFunctionParam ) ; <nl> <nl> - var - > setType ( ty ) ; <nl> + / / We want to set the variable ' s type here when type - checking <nl> + / / a function ' s parameter clauses because we ' re going to <nl> + / / type - check the entire function body within the context of <nl> + / / the constraint system . In contrast , when type - checking a <nl> + / / variable binding , we really don ' t want to set the <nl> + / / variable ' s type because it can easily escape the constraint <nl> + / / system and become a dangling type reference . <nl> + if ( forFunctionParam ) <nl> + var - > setType ( ty ) ; <nl> return ty ; <nl> } <nl> <nl> mmm a / lib / Sema / TypeCheckDecl . cpp <nl> ppp b / lib / Sema / TypeCheckDecl . cpp <nl> class DeclChecker : public DeclVisitor < DeclChecker > { <nl> llvm_unreachable ( " bad pattern kind ! " ) ; <nl> } <nl> <nl> + / / / Set ErrorType as the type of any variables bound by this pattern <nl> + / / / that don ' t yet have types . <nl> + / / / <nl> + / / / This method is called when some kind of further checking has <nl> + / / / failed , e . g . when the initializer didn ' t type - check . We may <nl> + / / / encounter references to the bound variables later , so for <nl> + / / / sanity ' s sake , we need to make sure that every variable has a <nl> + / / / type . At the same time , some of the variables may have explicit <nl> + / / / type annotations , and we don ' t want to lose those annotations <nl> + / / / unnecessarily because that would impede downstream type - checking <nl> + / / / and code completion . <nl> void setBoundVarsTypeError ( Pattern * pattern ) { <nl> switch ( pattern - > getKind ( ) ) { <nl> case PatternKind : : Tuple : <nl> class DeclChecker : public DeclVisitor < DeclChecker > { <nl> <nl> / / Handle vars . <nl> case PatternKind : : Named : { <nl> + / / Don ' t change the type of a variable that we ' ve been able to <nl> + / / compute a type for . <nl> VarDecl * var = cast < NamedPattern > ( pattern ) - > getDecl ( ) ; <nl> - var - > overwriteType ( ErrorType : : get ( TC . Context ) ) ; <nl> - var - > setInvalid ( ) ; <nl> + if ( var - > hasType ( ) ) { <nl> + if ( var - > getType ( ) - > is < ErrorType > ( ) ) <nl> + var - > setInvalid ( ) ; <nl> + } else { <nl> + var - > setType ( ErrorType : : get ( TC . Context ) ) ; <nl> + var - > setInvalid ( ) ; <nl> + } <nl> return ; <nl> } <nl> <nl> mmm a / lib / Sema / TypeChecker . h <nl> ppp b / lib / Sema / TypeChecker . h <nl> class TypeChecker : public ASTMutationListener , public LazyResolver { <nl> bool typeCheckExprPattern ( ExprPattern * EP , DeclContext * DC , <nl> Type type ) ; <nl> <nl> + / / / Type - check an initialized variable pattern declaration . <nl> bool typeCheckBinding ( PatternBindingDecl * D ) ; <nl> <nl> / / / \ brief Compute the set of captures for the given function or closure . <nl> | Don ' t overwrite a fully - annotated variable ' s type just because | apple/swift | 53f3ab9f4798d3cfdafea1392c522253c04fa658 | 2013-09-19T05:44:17Z |
mmm a / folly / experimental / coro / tests / CoroTest . cpp <nl> ppp b / folly / experimental / coro / tests / CoroTest . cpp <nl> <nl> * limitations under the License . <nl> * / <nl> <nl> + # include < folly / Portability . h > <nl> + <nl> # if FOLLY_HAS_COROUTINES <nl> <nl> # include < folly / executors / ManualExecutor . h > <nl> | Include Portability . h before using FOLLY_HAS_COROUTINES | facebook/folly | 7f696fbd87e7bf22936930611a413e29c95f6df7 | 2018-03-17T18:34:18Z |
mmm a / tensorflow / compiler / xla / service / buffer_assignment . cc <nl> ppp b / tensorflow / compiler / xla / service / buffer_assignment . cc <nl> Status BufferAssigner : : AssignBuffersForComputations ( <nl> } ; <nl> const HloValue * a_min = * absl : : c_min_element ( a - > values ( ) , compare ) ; <nl> const HloValue * b_min = * absl : : c_min_element ( b - > values ( ) , compare ) ; <nl> - return post_order_position . at ( a_min - > instruction ( ) ) < <nl> - post_order_position . at ( b_min - > instruction ( ) ) ; <nl> + return compare ( a_min , b_min ) ; <nl> } ) ; <nl> <nl> std : : vector < BufferAllocation : : Index > allocation_indices ; <nl> | [ XLA ] Use an already defined function instead of duplicating comparison logic | tensorflow/tensorflow | 41cb57976b198957f53cc4d54e2437928d9f1093 | 2019-09-11T01:58:03Z |
mmm a / tensorflow / core / ops / parsing_ops . cc <nl> ppp b / tensorflow / core / ops / parsing_ops . cc <nl> output : A Tensor with one more dimension than the input ` bytes ` . The <nl> of ` bytes ` divided by the number of bytes to represent ` out_type ` . <nl> ) doc " ) ; <nl> <nl> + REGISTER_OP ( " DecodeCompressed " ) <nl> + . Input ( " bytes : string " ) <nl> + . Output ( " output : string " ) <nl> + . Attr ( " compression_type : string = ' ' " ) <nl> + . SetShapeFn ( shape_inference : : UnchangedShape ) <nl> + . Doc ( R " doc ( <nl> + Reinterpret the bytes of a string as a vector of numbers . <nl> + <nl> + bytes : All the elements must have the same length . <nl> + compression_type : A scalar containing either ( i ) the empty string ( no <nl> + compression ) , ( ii ) " ZLIB " , or ( iii ) " GZIP " . <nl> + output : A Tensor with the same shape as input ` bytes ` . <nl> + ) doc " ) ; <nl> + <nl> REGISTER_OP ( " ParseExample " ) <nl> . Input ( " serialized : string " ) <nl> . Input ( " names : string " ) <nl> | Add DecodeCompressed ops to parsing_ops . cc | tensorflow/tensorflow | 5f65cc6648be94adf55b9e6b2589ffc669a82c5a | 2017-12-19T03:11:04Z |
mmm a / lib / browser / api / menu - item - roles . js <nl> ppp b / lib / browser / api / menu - item - roles . js <nl> const roles = { <nl> } ) <nl> } <nl> } , <nl> - / / submenu Edit ( should fit both Mac & Windows ) <nl> + / / Edit submenu ( should fit both Mac & Windows ) <nl> editMenu : { <nl> label : ' Edit ' , <nl> submenu : [ <nl> const roles = { <nl> ] <nl> } , <nl> <nl> - / / submenu Window should be used for Mac only <nl> + / / Window submenu should be used for Mac only <nl> windowMenu : { <nl> label : ' Window ' , <nl> submenu : [ <nl> exports . getDefaultAccelerator = ( role ) = > { <nl> } <nl> <nl> exports . getDefaultSubmenu = ( role ) = > { <nl> - if ( roles . hasOwnProperty ( role ) ) { <nl> - let submenu = roles [ role ] . submenu <nl> + if ( ! roles . hasOwnProperty ( role ) ) return <nl> <nl> - / / remove empty objects from within the submenu <nl> - if ( Array . isArray ( submenu ) ) { <nl> - submenu = submenu . filter ( function ( n ) { <nl> - return n ! = null <nl> - } ) <nl> - } <nl> + let { submenu } = roles [ role ] <nl> <nl> - return submenu <nl> + / / remove null items from within the submenu <nl> + if ( Array . isArray ( submenu ) ) { <nl> + submenu = submenu . filter ( ( item ) = > item ! = null ) <nl> } <nl> + <nl> + return submenu <nl> } <nl> <nl> exports . execute = ( role , focusedWindow , focusedWebContents ) = > { <nl> mmm a / spec / api - menu - spec . js <nl> ppp b / spec / api - menu - spec . js <nl> describe ( ' menu module ' , function ( ) { <nl> assert . equal ( item . submenu . items [ 3 ] . role , ' cut ' ) <nl> assert . equal ( item . submenu . items [ 4 ] . role , ' copy ' ) <nl> assert . equal ( item . submenu . items [ 5 ] . role , ' paste ' ) <nl> + <nl> if ( process . platform = = = ' darwin ' ) { <nl> assert . equal ( item . submenu . items [ 6 ] . role , ' pasteandmatchstyle ' ) <nl> assert . equal ( item . submenu . items [ 7 ] . role , ' delete ' ) <nl> assert . equal ( item . submenu . items [ 8 ] . role , ' selectall ' ) <nl> } <nl> + <nl> if ( process . platform = = = ' win32 ' ) { <nl> assert . equal ( item . submenu . items [ 6 ] . role , ' delete ' ) <nl> assert . equal ( item . submenu . items [ 7 ] . type , ' separator ' ) <nl> assert . equal ( item . submenu . items [ 8 ] . role , ' selectall ' ) <nl> } <nl> } ) <nl> + <nl> it ( ' overrides default layout when submenu is specified ' , function ( ) { <nl> var item = new MenuItem ( { role : ' editMenu ' , submenu : [ { role : ' close ' } ] } ) <nl> assert . equal ( item . label , ' Edit ' ) <nl> describe ( ' menu module ' , function ( ) { <nl> assert . equal ( item . label , ' Window ' ) <nl> assert . equal ( item . submenu . items [ 0 ] . role , ' minimize ' ) <nl> assert . equal ( item . submenu . items [ 1 ] . role , ' close ' ) <nl> + <nl> if ( process . platform = = = ' darwin ' ) { <nl> assert . equal ( item . submenu . items [ 2 ] . type , ' separator ' ) <nl> assert . equal ( item . submenu . items [ 3 ] . role , ' front ' ) <nl> } <nl> } ) <nl> + <nl> it ( ' overrides default layout when submenu is specified ' , function ( ) { <nl> var item = new MenuItem ( { role : ' windowMenu ' , submenu : [ { role : ' copy ' } ] } ) <nl> assert . equal ( item . label , ' Window ' ) <nl> | : art : | electron/electron | 8b4bf1f29ed5629037c93525beabab246e9eda92 | 2017-03-29T19:29:36Z |
mmm a / arangod / V8Server / v8 - collection . cpp <nl> ppp b / arangod / V8Server / v8 - collection . cpp <nl> static void JS_RotateVocbaseCol ( <nl> TRI_V8_THROW_EXCEPTION ( res ) ; <nl> } <nl> <nl> - res = collection - > rotateActiveJournal ( ) ; <nl> + res = collection - > getPhysical ( ) - > rotateActiveJournal ( ) ; <nl> <nl> trx . finish ( res ) ; <nl> <nl> mmm a / arangod / VocBase / LogicalCollection . cpp <nl> ppp b / arangod / VocBase / LogicalCollection . cpp <nl> int LogicalCollection : : close ( ) { <nl> return getPhysical ( ) - > close ( ) ; <nl> } <nl> <nl> - int LogicalCollection : : rotateActiveJournal ( ) { <nl> - return getPhysical ( ) - > rotateActiveJournal ( ) ; <nl> - } <nl> - <nl> bool LogicalCollection : : applyForTickRange ( <nl> TRI_voc_tick_t dataMin , TRI_voc_tick_t dataMax , <nl> std : : function < bool ( TRI_voc_tick_t foundTick , <nl> mmm a / arangod / VocBase / LogicalCollection . h <nl> ppp b / arangod / VocBase / LogicalCollection . h <nl> class LogicalCollection { <nl> <nl> / / / datafile management <nl> <nl> - / / / @ brief rotate the active journal - will do nothing if there is no journal <nl> - int rotateActiveJournal ( ) ; <nl> - <nl> bool applyForTickRange ( <nl> TRI_voc_tick_t dataMin , TRI_voc_tick_t dataMax , <nl> std : : function < bool ( TRI_voc_tick_t foundTick , <nl> mmm a / arangod / VocBase / PhysicalCollection . h <nl> ppp b / arangod / VocBase / PhysicalCollection . h <nl> class PhysicalCollection { <nl> virtual int close ( ) = 0 ; <nl> <nl> / / / @ brief rotate the active journal - will do nothing if there is no journal <nl> + / / / REVIEW - MOVE INTO MMFILES ? ? - used in v8 - collection <nl> virtual int rotateActiveJournal ( ) = 0 ; <nl> <nl> virtual bool applyForTickRange ( TRI_voc_tick_t dataMin , TRI_voc_tick_t dataMax , <nl> | remove rotateJournals from LogicalCollection | arangodb/arangodb | e9555e4b10f0131bc16af4478e754e766a4f9749 | 2017-02-21T10:06:53Z |
mmm a / xbmc / guilib / GUITexture . h <nl> ppp b / xbmc / guilib / GUITexture . h <nl> class CGUITextureBase <nl> void LoadDiffuseImage ( ) ; <nl> bool AllocateOnDemand ( ) ; <nl> bool UpdateAnimFrame ( unsigned int currentTime ) ; <nl> - void Render ( float left , float top , float bottom , float right , float u1 , float v1 , float u2 , float v2 , float u3 , float v3 ) ; <nl> + void Render ( float left , <nl> + float top , <nl> + float right , <nl> + float bottom , <nl> + float u1 , <nl> + float v1 , <nl> + float u2 , <nl> + float v2 , <nl> + float u3 , <nl> + float v3 ) ; <nl> static void OrientateTexture ( CRect & rect , float width , float height , int orientation ) ; <nl> void ResetAnimState ( ) ; <nl> <nl> | [ guilib / guitexture ] fix warning - func arg order different | xbmc/xbmc | 19f5dac75ebf2ce1a9d6b5594c5dc9b6c730a14f | 2020-10-06T06:39:45Z |
mmm a / include / v8 . h <nl> ppp b / include / v8 . h <nl> typedef void ( * FailedAccessCheckCallback ) ( Local < Object > target , <nl> * / <nl> typedef bool ( * AllowCodeGenerationFromStringsCallback ) ( Local < Context > context ) ; <nl> <nl> - / / mmm WASM compilation callbacks mmm <nl> - <nl> - / * * <nl> - * Callback to check if a buffer source may be compiled to WASM , given <nl> - * the compilation is attempted as a promise or not . <nl> - * / <nl> - <nl> - typedef bool ( * AllowWasmCompileCallback ) ( Local < Value > source , bool as_promise ) ; <nl> - <nl> - typedef bool ( * AllowWasmInstantiateCallback ) ( Local < WasmCompiledModule > module , <nl> - Local < Value > ffi , bool as_promise ) ; <nl> - <nl> / / mmm Garbage Collection Callbacks mmm <nl> <nl> / * * <nl> class V8_EXPORT Isolate { <nl> void SetAllowCodeGenerationFromStringsCallback ( <nl> AllowCodeGenerationFromStringsCallback callback ) ; <nl> <nl> - / * * <nl> - * Set the callback to invoke to check if wasm compilation from <nl> - * the specified object is allowed . By default , wasm compilation <nl> - * is allowed . <nl> - * <nl> - * Similar for instantiate . <nl> - * / <nl> - void SetAllowWasmCompileCallback ( AllowWasmCompileCallback callback ) ; <nl> - void SetAllowWasmInstantiateCallback ( AllowWasmInstantiateCallback callback ) ; <nl> - <nl> / * * <nl> * Check if V8 is dead and therefore unusable . This is the case after <nl> * fatal errors such as out - of - memory situations . <nl> mmm a / src / api . cc <nl> ppp b / src / api . cc <nl> void Isolate : : SetAllowCodeGenerationFromStringsCallback ( <nl> isolate - > set_allow_code_gen_callback ( callback ) ; <nl> } <nl> <nl> - void Isolate : : SetAllowWasmCompileCallback ( AllowWasmCompileCallback callback ) { <nl> - i : : Isolate * isolate = reinterpret_cast < i : : Isolate * > ( this ) ; <nl> - isolate - > set_allow_wasm_compile_callback ( callback ) ; <nl> - } <nl> - <nl> - void Isolate : : SetAllowWasmInstantiateCallback ( <nl> - AllowWasmInstantiateCallback callback ) { <nl> - i : : Isolate * isolate = reinterpret_cast < i : : Isolate * > ( this ) ; <nl> - isolate - > set_allow_wasm_instantiate_callback ( callback ) ; <nl> - } <nl> <nl> bool Isolate : : IsDead ( ) { <nl> i : : Isolate * isolate = reinterpret_cast < i : : Isolate * > ( this ) ; <nl> mmm a / src / isolate . h <nl> ppp b / src / isolate . h <nl> typedef List < HeapObject * > DebugObjectCache ; <nl> V ( OOMErrorCallback , oom_behavior , nullptr ) \ <nl> V ( LogEventCallback , event_logger , nullptr ) \ <nl> V ( AllowCodeGenerationFromStringsCallback , allow_code_gen_callback , nullptr ) \ <nl> - V ( AllowWasmCompileCallback , allow_wasm_compile_callback , nullptr ) \ <nl> - V ( AllowWasmInstantiateCallback , allow_wasm_instantiate_callback , nullptr ) \ <nl> V ( ExternalReferenceRedirectorPointer * , external_reference_redirector , \ <nl> nullptr ) \ <nl> / * State for Relocatable . * / \ <nl> mmm a / src / runtime / runtime - test . cc <nl> ppp b / src / runtime / runtime - test . cc <nl> <nl> # include " src / wasm / wasm - module . h " <nl> # include " src / wasm / wasm - objects . h " <nl> <nl> - namespace { <nl> - struct WasmCompileControls { <nl> - uint32_t MaxWasmBufferSize = std : : numeric_limits < uint32_t > : : max ( ) ; <nl> - bool AllowAnySizeForAsync = true ; <nl> - } g_WasmCompileControls ; <nl> - <nl> - bool IsWasmCompileAllowed ( v8 : : Local < v8 : : Value > value , bool is_async ) { <nl> - return ( is_async & & g_WasmCompileControls . AllowAnySizeForAsync ) | | <nl> - ( v8 : : Local < v8 : : ArrayBuffer > : : Cast ( value ) - > ByteLength ( ) < = <nl> - g_WasmCompileControls . MaxWasmBufferSize ) ; <nl> - } <nl> - <nl> - / / Use the compile controls for instantiation , too <nl> - bool IsWasmInstantiateAllowed ( v8 : : Local < v8 : : WasmCompiledModule > module , <nl> - v8 : : Local < v8 : : Value > ffi , bool is_async ) { <nl> - return ( is_async & & g_WasmCompileControls . AllowAnySizeForAsync ) | | <nl> - ( static_cast < uint32_t > ( module - > GetWasmWireBytes ( ) - > Length ( ) ) < = <nl> - g_WasmCompileControls . MaxWasmBufferSize ) ; <nl> - } <nl> - } / / namespace <nl> - <nl> namespace v8 { <nl> namespace internal { <nl> <nl> RUNTIME_FUNCTION ( Runtime_CheckWasmWrapperElision ) { <nl> return isolate - > heap ( ) - > ToBoolean ( count = = 1 ) ; <nl> } <nl> <nl> - RUNTIME_FUNCTION ( Runtime_SetWasmCompileControls ) { <nl> - HandleScope scope ( isolate ) ; <nl> - CHECK ( args . length ( ) = = 2 ) ; <nl> - CONVERT_ARG_HANDLE_CHECKED ( Smi , block_size , 0 ) ; <nl> - CONVERT_BOOLEAN_ARG_CHECKED ( allow_async , 1 ) ; <nl> - g_WasmCompileControls . AllowAnySizeForAsync = allow_async ; <nl> - g_WasmCompileControls . MaxWasmBufferSize = <nl> - static_cast < uint32_t > ( block_size - > value ( ) ) ; <nl> - isolate - > set_allow_wasm_compile_callback ( IsWasmCompileAllowed ) ; <nl> - return isolate - > heap ( ) - > undefined_value ( ) ; <nl> - } <nl> - <nl> - RUNTIME_FUNCTION ( Runtime_SetWasmInstantiateControls ) { <nl> - HandleScope scope ( isolate ) ; <nl> - CHECK ( args . length ( ) = = 0 ) ; <nl> - isolate - > set_allow_wasm_instantiate_callback ( IsWasmInstantiateAllowed ) ; <nl> - return isolate - > heap ( ) - > undefined_value ( ) ; <nl> - } <nl> - <nl> RUNTIME_FUNCTION ( Runtime_NotifyContextDisposed ) { <nl> HandleScope scope ( isolate ) ; <nl> DCHECK_EQ ( 0 , args . length ( ) ) ; <nl> mmm a / src / runtime / runtime . h <nl> ppp b / src / runtime / runtime . h <nl> namespace internal { <nl> F ( ValidateWasmInstancesChain , 2 , 1 ) \ <nl> F ( ValidateWasmModuleState , 1 , 1 ) \ <nl> F ( ValidateWasmOrphanedInstance , 1 , 1 ) \ <nl> - F ( SetWasmCompileControls , 2 , 1 ) \ <nl> - F ( SetWasmInstantiateControls , 0 , 1 ) \ <nl> F ( Verify , 1 , 1 ) <nl> <nl> # define FOR_EACH_INTRINSIC_TYPEDARRAY ( F ) \ <nl> mmm a / src / wasm / wasm - js . cc <nl> ppp b / src / wasm / wasm - js . cc <nl> RawBuffer GetRawBufferSource ( <nl> <nl> static i : : MaybeHandle < i : : WasmModuleObject > CreateModuleObject ( <nl> v8 : : Isolate * isolate , const v8 : : Local < v8 : : Value > source , <nl> - ErrorThrower * thrower , bool async ) { <nl> + ErrorThrower * thrower ) { <nl> i : : Isolate * i_isolate = reinterpret_cast < i : : Isolate * > ( isolate ) ; <nl> - i : : MaybeHandle < i : : WasmModuleObject > nothing ; <nl> - <nl> - AllowWasmCompileCallback callback = <nl> - reinterpret_cast < i : : Isolate * > ( isolate ) - > allow_wasm_compile_callback ( ) ; <nl> - if ( callback ! = nullptr & & ! callback ( source , async ) ) { <nl> - thrower - > RangeError ( <nl> - " Wasm compilation exceeds internal limits in this context for provided " <nl> - " arguments " ) ; <nl> - return nothing ; <nl> - } <nl> + i : : MaybeHandle < i : : JSObject > nothing ; <nl> <nl> RawBuffer buffer = GetRawBufferSource ( source , thrower ) ; <nl> if ( buffer . start = = nullptr ) return i : : MaybeHandle < i : : WasmModuleObject > ( ) ; <nl> void WebAssemblyCompile ( const v8 : : FunctionCallbackInfo < v8 : : Value > & args ) { <nl> return ; <nl> } <nl> i : : MaybeHandle < i : : JSObject > module_obj = <nl> - CreateModuleObject ( isolate , args [ 0 ] , & thrower , true ) ; <nl> + CreateModuleObject ( isolate , args [ 0 ] , & thrower ) ; <nl> <nl> if ( thrower . error ( ) ) { <nl> resolver - > Reject ( context , Utils : : ToLocal ( thrower . Reify ( ) ) ) ; <nl> void WebAssemblyModule ( const v8 : : FunctionCallbackInfo < v8 : : Value > & args ) { <nl> } <nl> <nl> i : : MaybeHandle < i : : JSObject > module_obj = <nl> - CreateModuleObject ( isolate , args [ 0 ] , & thrower , false ) ; <nl> + CreateModuleObject ( isolate , args [ 0 ] , & thrower ) ; <nl> if ( module_obj . is_null ( ) ) return ; <nl> <nl> v8 : : ReturnValue < v8 : : Value > return_value = args . GetReturnValue ( ) ; <nl> void WebAssemblyModule ( const v8 : : FunctionCallbackInfo < v8 : : Value > & args ) { <nl> <nl> MaybeLocal < Value > InstantiateModuleImpl ( <nl> i : : Isolate * i_isolate , i : : Handle < i : : WasmModuleObject > i_module_obj , <nl> - const v8 : : FunctionCallbackInfo < v8 : : Value > & args , ErrorThrower * thrower , <nl> - bool as_promise ) { <nl> + const v8 : : FunctionCallbackInfo < v8 : : Value > & args , ErrorThrower * thrower ) { <nl> / / It so happens that in both the WebAssembly . instantiate , as well as <nl> / / WebAssembly . Instance ctor , the positions of the ffi object and memory <nl> / / are the same . If that changes later , we refactor the consts into <nl> MaybeLocal < Value > InstantiateModuleImpl ( <nl> Local < Object > obj = Local < Object > : : Cast ( args [ kFfiOffset ] ) ; <nl> ffi = i : : Handle < i : : JSReceiver > : : cast ( v8 : : Utils : : OpenHandle ( * obj ) ) ; <nl> } <nl> - AllowWasmInstantiateCallback allow_instantiate = <nl> - i_isolate - > allow_wasm_instantiate_callback ( ) ; <nl> - if ( allow_instantiate ! = nullptr & & <nl> - ! allow_instantiate ( Local < WasmCompiledModule > : : Cast ( Utils : : ToLocal ( <nl> - i : : Handle < i : : JSObject > : : cast ( i_module_obj ) ) ) , <nl> - Utils : : ToLocal ( ffi ) , as_promise ) ) { <nl> - thrower - > RangeError ( <nl> - " Wasm instantiation exceeds internal limits in this context for " <nl> - " provided arguments " ) ; <nl> - return nothing ; <nl> - } <nl> <nl> i : : MaybeHandle < i : : JSObject > instance = <nl> i : : wasm : : WasmModule : : Instantiate ( i_isolate , thrower , i_module_obj , ffi ) ; <nl> void WebAssemblyInstance ( const v8 : : FunctionCallbackInfo < v8 : : Value > & args ) { <nl> <nl> if ( ! maybe_module . is_null ( ) ) { <nl> MaybeLocal < Value > instance = InstantiateModuleImpl ( <nl> - i_isolate , maybe_module . ToHandleChecked ( ) , args , & thrower , false ) ; <nl> + i_isolate , maybe_module . ToHandleChecked ( ) , args , & thrower ) ; <nl> <nl> if ( instance . IsEmpty ( ) ) { <nl> DCHECK ( thrower . error ( ) ) ; <nl> void WebAssemblyInstantiate ( const v8 : : FunctionCallbackInfo < v8 : : Value > & args ) { <nl> i : : Handle < i : : WasmModuleObject > module_obj ; <nl> if ( want_pair ) { <nl> i : : MaybeHandle < i : : WasmModuleObject > maybe_module_obj = <nl> - CreateModuleObject ( isolate , args [ 0 ] , & thrower , true ) ; <nl> + CreateModuleObject ( isolate , args [ 0 ] , & thrower ) ; <nl> if ( ! maybe_module_obj . ToHandle ( & module_obj ) ) { <nl> DCHECK ( thrower . error ( ) ) ; <nl> resolver - > Reject ( context , Utils : : ToLocal ( thrower . Reify ( ) ) ) ; <nl> void WebAssemblyInstantiate ( const v8 : : FunctionCallbackInfo < v8 : : Value > & args ) { <nl> } <nl> DCHECK ( ! module_obj . is_null ( ) ) ; <nl> MaybeLocal < Value > instance = <nl> - InstantiateModuleImpl ( i_isolate , module_obj , args , & thrower , true ) ; <nl> + InstantiateModuleImpl ( i_isolate , module_obj , args , & thrower ) ; <nl> if ( instance . IsEmpty ( ) ) { <nl> DCHECK ( thrower . error ( ) ) ; <nl> resolver - > Reject ( context , Utils : : ToLocal ( thrower . Reify ( ) ) ) ; <nl> deleted file mode 100644 <nl> index 5d244947f9a . . 00000000000 <nl> mmm a / test / mjsunit / wasm / test - wasm - compilation - control . js <nl> ppp / dev / null <nl> <nl> - / / Copyright 2017 the V8 project authors . All rights reserved . <nl> - / / Use of this source code is governed by a BSD - style license that can be <nl> - / / found in the LICENSE file . <nl> - <nl> - / / Flags : - - allow - natives - syntax - - validate - asm <nl> - <nl> - load ( " test / mjsunit / wasm / wasm - constants . js " ) ; <nl> - load ( " test / mjsunit / wasm / wasm - module - builder . js " ) ; <nl> - <nl> - let buffer = ( ( ) = > { <nl> - var builder = new WasmModuleBuilder ( ) ; <nl> - builder . addFunction ( " f " , kSig_i_v ) <nl> - . addBody ( [ kExprI32Const , 42 ] ) <nl> - . exportAs ( " f " ) ; <nl> - return builder . toBuffer ( ) ; <nl> - } ) ( ) ; <nl> - <nl> - / / allow up to the buffer size <nl> - % SetWasmCompileControls ( buffer . byteLength , true ) ; <nl> - % SetWasmInstantiateControls ( ) ; <nl> - var m = new WebAssembly . Module ( buffer ) ; <nl> - var i = new WebAssembly . Instance ( m ) ; <nl> - assertEquals ( i . exports . f ( ) , 42 ) ; <nl> - <nl> - / / the buffer can ' t compile synchronously , but we allow async compile <nl> - % SetWasmCompileControls ( buffer . byteLength - 1 , true ) ; <nl> - / / test first that we can ' t sync - instantiate this module anymore <nl> - try { <nl> - i = new WebAssembly . Instance ( m ) ; <nl> - } catch ( e ) { <nl> - assertTrue ( e instanceof RangeError ) ; <nl> - } <nl> - <nl> - / / . . . but we can async - instantiate it <nl> - <nl> - WebAssembly . instantiate ( m ) <nl> - . then ( instance = > i = instance , <nl> - assertUnreachable ) ; <nl> - % RunMicrotasks ( ) ; <nl> - assertTrue ( i instanceof WebAssembly . Instance ) ; <nl> - <nl> - try { <nl> - m = new WebAssembly . Module ( buffer ) ; <nl> - assertUnreachable ( ) ; <nl> - } catch ( e ) { <nl> - assertTrue ( e instanceof RangeError ) ; <nl> - } <nl> - <nl> - WebAssembly . compile ( buffer ) <nl> - . then ( res = > m = res , <nl> - m = null ) ; <nl> - <nl> - % RunMicrotasks ( ) ; <nl> - assertTrue ( m instanceof WebAssembly . Module ) <nl> - <nl> - WebAssembly . instantiate ( buffer ) <nl> - . then ( res = > m = res . module , <nl> - m = null ) ; <nl> - <nl> - % RunMicrotasks ( ) ; <nl> - assertTrue ( m instanceof WebAssembly . Module ) ; <nl> - <nl> - / / not even async compile works . <nl> - var ex ; <nl> - % SetWasmCompileControls ( buffer . byteLength - 1 , false ) ; <nl> - WebAssembly . compile ( buffer ) <nl> - . then ( ex = null , <nl> - e = > ex = e ) ; <nl> - <nl> - % RunMicrotasks ( ) ; <nl> - assertTrue ( ex instanceof RangeError ) ; <nl> - <nl> - WebAssembly . instantiate ( buffer ) <nl> - . then ( ex = null , <nl> - e = > ex = e ) ; <nl> - % RunMicrotasks ( ) ; <nl> - assertTrue ( ex instanceof RangeError ) ; <nl> - <nl> - <nl> - / / For asm - wasm , these controls are ignored . <nl> - % SetWasmCompileControls ( 0 , false ) ; <nl> - function assertValidAsm ( func ) { <nl> - assertTrue ( % IsAsmWasmCode ( func ) ) ; <nl> - } <nl> - <nl> - function assertWasm ( expected , func ) { <nl> - assertEquals ( <nl> - expected , func ( undefined , undefined , new ArrayBuffer ( 1024 ) ) . caller ( ) ) ; <nl> - assertValidAsm ( func ) ; <nl> - } <nl> - <nl> - function TestAsmWasmIsUnaffected ( ) { <nl> - " use asm " ; <nl> - function caller ( ) { <nl> - return 43 ; <nl> - } <nl> - <nl> - return { caller : caller } ; <nl> - } <nl> - <nl> - assertWasm ( 43 , TestAsmWasmIsUnaffected ) ; <nl> | Revert of [ wasm ] Embedder can control what buffers wasm compilation works on . ( patchset id : 60001 of https : / / codereview . chromium . org / 2699843003 / ) | v8/v8 | 1bbbfb42d5e439596c8cae7d12b2896d1f5c01df | 2017-02-20T08:01:01Z |
mmm a / ChangeLog <nl> ppp b / ChangeLog <nl> <nl> + 2009 - 05 - 04 Tatsuhiro Tsujikawa < t - tujikawa @ users . sourceforge . net > <nl> + <nl> + Now the constructor of AbstractDiskWriter takes filename as an <nl> + argument and filename argument is removed from openFile ( ) , <nl> + initAndOpenFile ( ) , openExistingFile ( ) interface . storeDir member <nl> + and its accessor functions are removed from DiskAdaptor because it <nl> + is not used anymore . size ( ) member function of DefaultDiskWriter , <nl> + DirectDiskAdaptor and MultiDiskAdaptor now can be called without <nl> + opening file . <nl> + * src / AbstractDiskWriter . cc <nl> + * src / AbstractDiskWriter . h <nl> + * src / AbstractSingleDiskAdaptor . cc <nl> + * src / AbstractSingleDiskAdaptor . h <nl> + * src / ByteArrayDiskWriter . cc <nl> + * src / ByteArrayDiskWriter . h <nl> + * src / ByteArrayDiskWriterFactory . cc <nl> + * src / ByteArrayDiskWriterFactory . h <nl> + * src / DefaultDiskWriter . cc <nl> + * src / DefaultDiskWriter . h <nl> + * src / DefaultDiskWriterFactory . cc <nl> + * src / DefaultDiskWriterFactory . h <nl> + * src / DefaultPieceStorage . cc <nl> + * src / DirectDiskAdaptor . cc <nl> + * src / DirectDiskAdaptor . h <nl> + * src / DiskAdaptor . h <nl> + * src / DiskWriter . h <nl> + * src / DiskWriterFactory . h <nl> + * src / MessageDigestHelper . cc <nl> + * src / MultiDiskAdaptor . cc <nl> + * src / RequestGroup . cc <nl> + * src / UnknownLengthPieceStorage . cc <nl> + * src / Util . cc <nl> + * test / DefaultDiskWriterTest . cc <nl> + * test / DirectDiskAdaptorTest . cc <nl> + * test / FallocFileAllocationIteratorTest . cc <nl> + * test / MessageDigestHelperTest . cc <nl> + * test / MetalinkProcessorTest . cc <nl> + * test / MultiDiskAdaptorTest . cc <nl> + * test / MultiFileAllocationIteratorTest . cc <nl> + * test / SingleFileAllocationIteratorTest . cc <nl> + * test / UtilTest . cc <nl> + <nl> 2009 - 05 - 04 Tatsuhiro Tsujikawa < t - tujikawa @ users . sourceforge . net > <nl> <nl> Fixed the bug that aria2 aborts when - - select - file is used . This <nl> mmm a / src / AbstractDiskWriter . cc <nl> ppp b / src / AbstractDiskWriter . cc <nl> <nl> <nl> namespace aria2 { <nl> <nl> - AbstractDiskWriter : : AbstractDiskWriter ( ) : <nl> + AbstractDiskWriter : : AbstractDiskWriter ( const std : : string & filename ) : <nl> + _filename ( filename ) , <nl> fd ( - 1 ) , <nl> _readOnly ( false ) , <nl> logger ( LogFactory : : getInstance ( ) ) { } <nl> AbstractDiskWriter : : ~ AbstractDiskWriter ( ) <nl> closeFile ( ) ; <nl> } <nl> <nl> - void AbstractDiskWriter : : openFile ( const std : : string & filename , uint64_t totalLength ) <nl> + void AbstractDiskWriter : : openFile ( uint64_t totalLength ) <nl> { <nl> - File f ( filename ) ; <nl> - if ( f . exists ( ) ) { <nl> - openExistingFile ( filename , totalLength ) ; <nl> + if ( File ( _filename ) . exists ( ) ) { <nl> + openExistingFile ( totalLength ) ; <nl> } else { <nl> - initAndOpenFile ( filename , totalLength ) ; <nl> + initAndOpenFile ( totalLength ) ; <nl> } <nl> } <nl> <nl> void AbstractDiskWriter : : closeFile ( ) <nl> } <nl> } <nl> <nl> - void AbstractDiskWriter : : openExistingFile ( const std : : string & filename , <nl> - uint64_t totalLength ) <nl> + void AbstractDiskWriter : : openExistingFile ( uint64_t totalLength ) <nl> { <nl> - this - > filename = filename ; <nl> - File f ( filename ) ; <nl> - if ( ! f . exists ( ) ) { <nl> + if ( ! File ( _filename ) . exists ( ) ) { <nl> throw DlAbortEx <nl> - ( StringFormat ( EX_FILE_OPEN , filename . c_str ( ) , MSG_FILE_NOT_FOUND ) . str ( ) ) ; <nl> + ( StringFormat ( EX_FILE_OPEN , _filename . c_str ( ) , MSG_FILE_NOT_FOUND ) . str ( ) ) ; <nl> } <nl> <nl> int flags = O_BINARY ; <nl> void AbstractDiskWriter : : openExistingFile ( const std : : string & filename , <nl> flags | = O_RDWR ; <nl> } <nl> <nl> - if ( ( fd = open ( filename . c_str ( ) , flags , OPEN_MODE ) ) < 0 ) { <nl> + if ( ( fd = open ( _filename . c_str ( ) , flags , OPEN_MODE ) ) < 0 ) { <nl> throw DlAbortEx <nl> - ( StringFormat ( EX_FILE_OPEN , filename . c_str ( ) , strerror ( errno ) ) . str ( ) ) ; <nl> + ( StringFormat ( EX_FILE_OPEN , _filename . c_str ( ) , strerror ( errno ) ) . str ( ) ) ; <nl> } <nl> } <nl> <nl> - void AbstractDiskWriter : : createFile ( const std : : string & filename , int addFlags ) <nl> + void AbstractDiskWriter : : createFile ( int addFlags ) <nl> { <nl> - this - > filename = filename ; <nl> - assert ( filename . size ( ) ) ; <nl> - Util : : mkdirs ( File ( filename ) . getDirname ( ) ) ; <nl> - if ( ( fd = open ( filename . c_str ( ) , O_CREAT | O_RDWR | O_TRUNC | O_BINARY | addFlags , OPEN_MODE ) ) < 0 ) { <nl> - throw DlAbortEx ( StringFormat ( EX_FILE_OPEN , filename . c_str ( ) , strerror ( errno ) ) . str ( ) ) ; <nl> + assert ( ! _filename . empty ( ) ) ; <nl> + Util : : mkdirs ( File ( _filename ) . getDirname ( ) ) ; <nl> + if ( ( fd = open ( _filename . c_str ( ) , O_CREAT | O_RDWR | O_TRUNC | O_BINARY | addFlags , <nl> + OPEN_MODE ) ) < 0 ) { <nl> + throw DlAbortEx ( StringFormat ( EX_FILE_OPEN , <nl> + _filename . c_str ( ) , strerror ( errno ) ) . str ( ) ) ; <nl> } <nl> } <nl> <nl> void AbstractDiskWriter : : seek ( off_t offset ) <nl> { <nl> if ( lseek ( fd , offset , SEEK_SET ) = = ( off_t ) - 1 ) { <nl> throw DlAbortEx <nl> - ( StringFormat ( EX_FILE_SEEK , filename . c_str ( ) , strerror ( errno ) ) . str ( ) ) ; <nl> + ( StringFormat ( EX_FILE_SEEK , _filename . c_str ( ) , strerror ( errno ) ) . str ( ) ) ; <nl> } <nl> } <nl> <nl> void AbstractDiskWriter : : writeData ( const unsigned char * data , size_t len , off_t <nl> / / DownloadFailureException and abort download instantly . <nl> if ( errno = = ENOSPC ) { <nl> throw DownloadFailureException <nl> - ( StringFormat ( EX_FILE_WRITE , filename . c_str ( ) , strerror ( errno ) ) . str ( ) ) ; <nl> + ( StringFormat ( EX_FILE_WRITE , _filename . c_str ( ) , strerror ( errno ) ) . str ( ) ) ; <nl> } <nl> - throw DlAbortEx ( StringFormat ( EX_FILE_WRITE , filename . c_str ( ) , strerror ( errno ) ) . str ( ) ) ; <nl> + throw DlAbortEx ( StringFormat ( EX_FILE_WRITE , <nl> + _filename . c_str ( ) , strerror ( errno ) ) . str ( ) ) ; <nl> } <nl> } <nl> <nl> ssize_t AbstractDiskWriter : : readData ( unsigned char * data , size_t len , off_t offs <nl> ssize_t ret ; <nl> seek ( offset ) ; <nl> if ( ( ret = readDataInternal ( data , len ) ) < 0 ) { <nl> - throw DlAbortEx ( StringFormat ( EX_FILE_READ , filename . c_str ( ) , strerror ( errno ) ) . str ( ) ) ; <nl> + throw DlAbortEx ( StringFormat ( EX_FILE_READ , <nl> + _filename . c_str ( ) , strerror ( errno ) ) . str ( ) ) ; <nl> } <nl> return ret ; <nl> } <nl> void AbstractDiskWriter : : allocate ( off_t offset , uint64_t length ) <nl> } <nl> # endif / / HAVE_POSIX_FALLOCATE <nl> <nl> - / / TODO the file descriptor fd must be opened before calling this function . <nl> uint64_t AbstractDiskWriter : : size ( ) <nl> { <nl> - if ( fd = = - 1 ) { <nl> - throw DlAbortEx ( " File not opened . " ) ; <nl> - } <nl> - a2_struct_stat fileStat ; <nl> - if ( fstat ( fd , & fileStat ) < 0 ) { <nl> - return 0 ; <nl> - } <nl> - return fileStat . st_size ; <nl> + return File ( _filename ) . size ( ) ; <nl> } <nl> <nl> void AbstractDiskWriter : : enableDirectIO ( ) <nl> mmm a / src / AbstractDiskWriter . h <nl> ppp b / src / AbstractDiskWriter . h <nl> class Logger ; <nl> <nl> class AbstractDiskWriter : public DiskWriter { <nl> protected : <nl> - std : : string filename ; <nl> + std : : string _filename ; <nl> int fd ; <nl> <nl> bool _readOnly ; <nl> <nl> Logger * logger ; <nl> <nl> - void createFile ( const std : : string & filename , int addFlags = 0 ) ; <nl> + void createFile ( int addFlags = 0 ) ; <nl> <nl> private : <nl> ssize_t writeDataInternal ( const unsigned char * data , size_t len ) ; <nl> class AbstractDiskWriter : public DiskWriter { <nl> <nl> void seek ( off_t offset ) ; <nl> public : <nl> - AbstractDiskWriter ( ) ; <nl> + AbstractDiskWriter ( const std : : string & filename ) ; <nl> virtual ~ AbstractDiskWriter ( ) ; <nl> <nl> - virtual void openFile ( const std : : string & filename , uint64_t totalLength = 0 ) ; <nl> + virtual void openFile ( uint64_t totalLength = 0 ) ; <nl> <nl> virtual void closeFile ( ) ; <nl> <nl> - virtual void openExistingFile ( const std : : string & filename , uint64_t totalLength = 0 ) ; <nl> + virtual void openExistingFile ( uint64_t totalLength = 0 ) ; <nl> <nl> virtual void writeData ( const unsigned char * data , size_t len , off_t offset ) ; <nl> <nl> mmm a / src / AbstractSingleDiskAdaptor . cc <nl> ppp b / src / AbstractSingleDiskAdaptor . cc <nl> AbstractSingleDiskAdaptor : : ~ AbstractSingleDiskAdaptor ( ) { } <nl> <nl> void AbstractSingleDiskAdaptor : : initAndOpenFile ( ) <nl> { <nl> - diskWriter - > initAndOpenFile ( getFilePath ( ) , totalLength ) ; <nl> + diskWriter - > initAndOpenFile ( totalLength ) ; <nl> } <nl> <nl> void AbstractSingleDiskAdaptor : : openFile ( ) <nl> { <nl> - diskWriter - > openFile ( getFilePath ( ) , totalLength ) ; <nl> + diskWriter - > openFile ( totalLength ) ; <nl> } <nl> <nl> void AbstractSingleDiskAdaptor : : closeFile ( ) <nl> void AbstractSingleDiskAdaptor : : closeFile ( ) <nl> <nl> void AbstractSingleDiskAdaptor : : openExistingFile ( ) <nl> { <nl> - diskWriter - > openExistingFile ( getFilePath ( ) , totalLength ) ; <nl> + diskWriter - > openExistingFile ( totalLength ) ; <nl> } <nl> <nl> void AbstractSingleDiskAdaptor : : writeData ( const unsigned char * data , size_t len , off_t offset ) <nl> bool AbstractSingleDiskAdaptor : : fileExists ( ) <nl> <nl> uint64_t AbstractSingleDiskAdaptor : : size ( ) <nl> { <nl> - return diskWriter - > size ( ) ; <nl> + return File ( getFilePath ( ) ) . size ( ) ; <nl> } <nl> <nl> void AbstractSingleDiskAdaptor : : truncate ( uint64_t length ) <nl> mmm a / src / AbstractSingleDiskAdaptor . h <nl> ppp b / src / AbstractSingleDiskAdaptor . h <nl> class AbstractSingleDiskAdaptor : public DiskAdaptor { <nl> <nl> virtual void cutTrailingGarbage ( ) ; <nl> <nl> - virtual std : : string getFilePath ( ) = 0 ; <nl> + virtual const std : : string & getFilePath ( ) = 0 ; <nl> <nl> void setDiskWriter ( const SharedHandle < DiskWriter > & diskWriter ) ; <nl> <nl> mmm a / src / ByteArrayDiskWriter . cc <nl> ppp b / src / ByteArrayDiskWriter . cc <nl> void ByteArrayDiskWriter : : clear ( ) <nl> buf . str ( A2STR : : NIL ) ; <nl> } <nl> <nl> - void ByteArrayDiskWriter : : initAndOpenFile ( const std : : string & filename , <nl> - uint64_t totalLength ) <nl> + void ByteArrayDiskWriter : : initAndOpenFile ( uint64_t totalLength ) <nl> { <nl> clear ( ) ; <nl> } <nl> <nl> - void ByteArrayDiskWriter : : openFile ( const std : : string & filename , <nl> - uint64_t totalLength ) { } <nl> + void ByteArrayDiskWriter : : openFile ( uint64_t totalLength ) { } <nl> <nl> void ByteArrayDiskWriter : : closeFile ( ) { } <nl> <nl> - void ByteArrayDiskWriter : : openExistingFile ( const std : : string & filename , <nl> - uint64_t totalLength ) <nl> + void ByteArrayDiskWriter : : openExistingFile ( uint64_t totalLength ) <nl> { <nl> - openFile ( filename ) ; <nl> + openFile ( ) ; <nl> } <nl> <nl> void ByteArrayDiskWriter : : writeData ( const unsigned char * data , size_t dataLength , off_t position ) <nl> mmm a / src / ByteArrayDiskWriter . h <nl> ppp b / src / ByteArrayDiskWriter . h <nl> class ByteArrayDiskWriter : public DiskWriter { <nl> ByteArrayDiskWriter ( ) ; <nl> virtual ~ ByteArrayDiskWriter ( ) ; <nl> <nl> - virtual void initAndOpenFile ( const std : : string & filename , uint64_t totalLength = 0 ) ; <nl> + virtual void initAndOpenFile ( uint64_t totalLength = 0 ) ; <nl> <nl> - virtual void openFile ( const std : : string & filename , uint64_t totalLength = 0 ) ; <nl> + virtual void openFile ( uint64_t totalLength = 0 ) ; <nl> <nl> virtual void closeFile ( ) ; <nl> <nl> - virtual void openExistingFile ( const std : : string & filename , uint64_t totalLength = 0 ) ; <nl> + virtual void openExistingFile ( uint64_t totalLength = 0 ) ; <nl> <nl> virtual void writeData ( const unsigned char * data , size_t len , off_t position ) ; <nl> virtual ssize_t readData ( unsigned char * data , size_t len , off_t position ) ; <nl> mmm a / src / ByteArrayDiskWriterFactory . cc <nl> ppp b / src / ByteArrayDiskWriterFactory . cc <nl> <nl> <nl> namespace aria2 { <nl> <nl> - DiskWriterHandle ByteArrayDiskWriterFactory : : newDiskWriter ( ) <nl> + DiskWriterHandle ByteArrayDiskWriterFactory : : newDiskWriter <nl> + ( const std : : string & filename ) <nl> { <nl> return SharedHandle < DiskWriter > ( new ByteArrayDiskWriter ( ) ) ; <nl> } <nl> mmm a / src / ByteArrayDiskWriterFactory . h <nl> ppp b / src / ByteArrayDiskWriterFactory . h <nl> class ByteArrayDiskWriter ; <nl> class ByteArrayDiskWriterFactory : public DiskWriterFactory <nl> { <nl> public : <nl> - SharedHandle < DiskWriter > newDiskWriter ( ) ; <nl> + SharedHandle < DiskWriter > newDiskWriter ( const std : : string & filename ) ; <nl> } ; <nl> <nl> typedef SharedHandle < ByteArrayDiskWriterFactory > ByteArrayDiskWriterFactoryHandle ; <nl> mmm a / src / DefaultDiskWriter . cc <nl> ppp b / src / DefaultDiskWriter . cc <nl> <nl> <nl> namespace aria2 { <nl> <nl> - DefaultDiskWriter : : DefaultDiskWriter ( ) : AbstractDiskWriter ( ) { } <nl> + DefaultDiskWriter : : DefaultDiskWriter ( const std : : string & filename ) : <nl> + AbstractDiskWriter ( filename ) { } <nl> <nl> DefaultDiskWriter : : ~ DefaultDiskWriter ( ) { } <nl> <nl> - void DefaultDiskWriter : : initAndOpenFile ( const std : : string & filename , <nl> - uint64_t totalLength ) <nl> + void DefaultDiskWriter : : initAndOpenFile ( uint64_t totalLength ) <nl> { <nl> - createFile ( filename ) ; <nl> + createFile ( ) ; <nl> } <nl> <nl> } / / namespace aria2 <nl> mmm a / src / DefaultDiskWriter . h <nl> ppp b / src / DefaultDiskWriter . h <nl> namespace aria2 { <nl> <nl> class DefaultDiskWriter : public AbstractDiskWriter { <nl> public : <nl> - DefaultDiskWriter ( ) ; <nl> + DefaultDiskWriter ( const std : : string & filename ) ; <nl> <nl> virtual ~ DefaultDiskWriter ( ) ; <nl> <nl> - virtual void initAndOpenFile ( const std : : string & filename , uint64_t totalLength = 0 ) ; <nl> + virtual void initAndOpenFile ( uint64_t totalLength = 0 ) ; <nl> } ; <nl> <nl> typedef SharedHandle < DefaultDiskWriter > DefaultDiskWriterHandle ; <nl> mmm a / src / DefaultDiskWriterFactory . cc <nl> ppp b / src / DefaultDiskWriterFactory . cc <nl> <nl> <nl> namespace aria2 { <nl> <nl> - SharedHandle < DiskWriter > DefaultDiskWriterFactory : : newDiskWriter ( ) <nl> + SharedHandle < DiskWriter > DefaultDiskWriterFactory : : newDiskWriter <nl> + ( const std : : string & filename ) <nl> { <nl> - return SharedHandle < DiskWriter > ( new DefaultDiskWriter ( ) ) ; <nl> + return SharedHandle < DiskWriter > ( new DefaultDiskWriter ( filename ) ) ; <nl> } <nl> <nl> } / / namespace aria2 <nl> mmm a / src / DefaultDiskWriterFactory . h <nl> ppp b / src / DefaultDiskWriterFactory . h <nl> class DiskWriter ; <nl> class DefaultDiskWriterFactory : public DiskWriterFactory <nl> { <nl> public : <nl> - virtual SharedHandle < DiskWriter > newDiskWriter ( ) ; <nl> + virtual SharedHandle < DiskWriter > newDiskWriter ( const std : : string & filename ) ; <nl> } ; <nl> <nl> typedef SharedHandle < DefaultDiskWriterFactory > DefaultDiskWriterFactoryHandle ; <nl> mmm a / src / DefaultPieceStorage . cc <nl> ppp b / src / DefaultPieceStorage . cc <nl> void DefaultPieceStorage : : initStorage ( ) <nl> { <nl> if ( downloadContext - > getFileMode ( ) = = DownloadContext : : SINGLE ) { <nl> logger - > debug ( " Instantiating DirectDiskAdaptor " ) ; <nl> - DiskWriterHandle writer = _diskWriterFactory - > newDiskWriter ( ) ; <nl> - writer - > setDirectIOAllowed ( option - > getAsBool ( PREF_ENABLE_DIRECT_IO ) ) ; <nl> DirectDiskAdaptorHandle directDiskAdaptor ( new DirectDiskAdaptor ( ) ) ; <nl> - directDiskAdaptor - > setDiskWriter ( writer ) ; <nl> directDiskAdaptor - > setTotalLength ( downloadContext - > getTotalLength ( ) ) ; <nl> + directDiskAdaptor - > setFileEntries ( downloadContext - > getFileEntries ( ) ) ; <nl> + <nl> + DiskWriterHandle writer = <nl> + _diskWriterFactory - > newDiskWriter ( directDiskAdaptor - > getFilePath ( ) ) ; <nl> + writer - > setDirectIOAllowed ( option - > getAsBool ( PREF_ENABLE_DIRECT_IO ) ) ; <nl> + <nl> + directDiskAdaptor - > setDiskWriter ( writer ) ; <nl> this - > diskAdaptor = directDiskAdaptor ; <nl> } else { <nl> / / file mode = = DownloadContext : : MULTI <nl> logger - > debug ( " Instantiating MultiDiskAdaptor " ) ; <nl> MultiDiskAdaptorHandle multiDiskAdaptor ( new MultiDiskAdaptor ( ) ) ; <nl> + multiDiskAdaptor - > setFileEntries ( downloadContext - > getFileEntries ( ) ) ; <nl> multiDiskAdaptor - > setDirectIOAllowed ( option - > getAsBool ( PREF_ENABLE_DIRECT_IO ) ) ; <nl> multiDiskAdaptor - > setPieceLength ( downloadContext - > getPieceLength ( ) ) ; <nl> multiDiskAdaptor - > setMaxOpenFiles ( option - > getAsInt ( PREF_BT_MAX_OPEN_FILES ) ) ; <nl> this - > diskAdaptor = multiDiskAdaptor ; <nl> } <nl> - diskAdaptor - > setStoreDir ( downloadContext - > getDir ( ) ) ; <nl> - diskAdaptor - > setFileEntries ( downloadContext - > getFileEntries ( ) ) ; <nl> # ifdef HAVE_POSIX_FALLOCATE <nl> if ( option - > get ( PREF_FILE_ALLOCATION ) = = V_FALLOC ) { <nl> diskAdaptor - > enableFallocate ( ) ; <nl> mmm a / src / DirectDiskAdaptor . cc <nl> ppp b / src / DirectDiskAdaptor . cc <nl> <nl> <nl> namespace aria2 { <nl> <nl> - std : : string DirectDiskAdaptor : : getFilePath ( ) <nl> + const std : : string & DirectDiskAdaptor : : getFilePath ( ) <nl> { <nl> return fileEntries . front ( ) - > getPath ( ) ; <nl> } <nl> mmm a / src / DirectDiskAdaptor . h <nl> ppp b / src / DirectDiskAdaptor . h <nl> class DirectDiskAdaptor : public AbstractSingleDiskAdaptor { <nl> DirectDiskAdaptor ( ) { } ; <nl> virtual ~ DirectDiskAdaptor ( ) { } ; <nl> <nl> - virtual std : : string getFilePath ( ) ; <nl> + virtual const std : : string & getFilePath ( ) ; <nl> <nl> virtual void onDownloadComplete ( ) ; <nl> <nl> mmm a / src / DiskAdaptor . h <nl> ppp b / src / DiskAdaptor . h <nl> class FileAllocationIterator ; <nl> <nl> class DiskAdaptor : public BinaryStream { <nl> protected : <nl> - std : : string storeDir ; <nl> std : : deque < SharedHandle < FileEntry > > fileEntries ; <nl> # ifdef HAVE_POSIX_FALLOCATE <nl> bool _fallocate ; <nl> class DiskAdaptor : public BinaryStream { <nl> <nl> void removeAllDownloadEntry ( ) ; <nl> <nl> - void setStoreDir ( const std : : string & storeDir ) { this - > storeDir = storeDir ; } <nl> - <nl> - const std : : string & getStoreDir ( ) const { return this - > storeDir ; } <nl> - <nl> virtual SharedHandle < FileAllocationIterator > fileAllocationIterator ( ) = 0 ; <nl> <nl> virtual void enableDirectIO ( ) { } <nl> mmm a / src / DiskWriter . h <nl> ppp b / src / DiskWriter . h <nl> class DiskWriter : public BinaryStream { <nl> <nl> virtual ~ DiskWriter ( ) { } <nl> / * * <nl> - * Creates a file output stream to write to the file with the specified name . <nl> - * If the file exists , then it is truncated to 0 length . <nl> - * @ param filename the file name to be opened . <nl> + * Opens file . If the file exists , then it is truncated to 0 length . <nl> * / <nl> - virtual void initAndOpenFile ( const std : : string & filename , uint64_t totalLength = 0 ) = 0 ; <nl> + virtual void initAndOpenFile ( uint64_t totalLength = 0 ) = 0 ; <nl> <nl> - virtual void openFile ( const std : : string & filename , uint64_t totalLength = 0 ) = 0 ; <nl> + virtual void openFile ( uint64_t totalLength = 0 ) = 0 ; <nl> <nl> / * * <nl> * Closes this output stream . <nl> class DiskWriter : public BinaryStream { <nl> virtual void closeFile ( ) = 0 ; <nl> <nl> / * * <nl> - * Opens a file output stream to write to the file with the specified name . <nl> - * If the file doesnot exists , an exception may be throwed . <nl> - * <nl> - * @ param filename the file name to be opened . <nl> + * Opens a file . If the file doesnot exists , an exception may be <nl> + * thrown . <nl> * / <nl> - virtual void openExistingFile ( const std : : string & filename , uint64_t totalLength = 0 ) = 0 ; <nl> + virtual void openExistingFile ( uint64_t totalLength = 0 ) = 0 ; <nl> <nl> / / Returns file length <nl> virtual uint64_t size ( ) = 0 ; <nl> mmm a / src / DiskWriterFactory . h <nl> ppp b / src / DiskWriterFactory . h <nl> class DiskWriterFactory { <nl> public : <nl> virtual ~ DiskWriterFactory ( ) { } <nl> <nl> - virtual SharedHandle < DiskWriter > newDiskWriter ( ) = 0 ; <nl> + virtual SharedHandle < DiskWriter > newDiskWriter ( const std : : string & filename ) = 0 ; <nl> } ; <nl> <nl> typedef SharedHandle < DiskWriterFactory > DiskWriterFactoryHandle ; <nl> mmm a / src / MessageDigestHelper . cc <nl> ppp b / src / MessageDigestHelper . cc <nl> std : : string MessageDigestHelper : : digest ( MessageDigestContext * ctx , <nl> <nl> std : : string MessageDigestHelper : : digest ( const std : : string & algo , const std : : string & filename ) <nl> { <nl> - DiskWriterHandle writer ( new DefaultDiskWriter ( ) ) ; <nl> - writer - > openExistingFile ( filename ) ; <nl> + DiskWriterHandle writer ( new DefaultDiskWriter ( filename ) ) ; <nl> + writer - > openExistingFile ( ) ; <nl> return digest ( algo , writer , 0 , writer - > size ( ) ) ; <nl> } <nl> <nl> mmm a / src / MultiDiskAdaptor . cc <nl> ppp b / src / MultiDiskAdaptor . cc <nl> const std : : string & DiskWriterEntry : : getFilePath ( ) const <nl> void DiskWriterEntry : : initAndOpenFile ( ) <nl> { <nl> if ( ! diskWriter . isNull ( ) ) { <nl> - diskWriter - > initAndOpenFile ( getFilePath ( ) , fileEntry - > getLength ( ) ) ; <nl> + diskWriter - > initAndOpenFile ( fileEntry - > getLength ( ) ) ; <nl> if ( _directIO ) { <nl> diskWriter - > enableDirectIO ( ) ; <nl> } <nl> void DiskWriterEntry : : initAndOpenFile ( ) <nl> void DiskWriterEntry : : openFile ( ) <nl> { <nl> if ( ! diskWriter . isNull ( ) ) { <nl> - diskWriter - > openFile ( getFilePath ( ) , fileEntry - > getLength ( ) ) ; <nl> + diskWriter - > openFile ( fileEntry - > getLength ( ) ) ; <nl> if ( _directIO ) { <nl> diskWriter - > enableDirectIO ( ) ; <nl> } <nl> void DiskWriterEntry : : openFile ( ) <nl> void DiskWriterEntry : : openExistingFile ( ) <nl> { <nl> if ( ! diskWriter . isNull ( ) ) { <nl> - diskWriter - > openExistingFile ( getFilePath ( ) , fileEntry - > getLength ( ) ) ; <nl> + diskWriter - > openExistingFile ( fileEntry - > getLength ( ) ) ; <nl> if ( _directIO ) { <nl> diskWriter - > enableDirectIO ( ) ; <nl> } <nl> bool DiskWriterEntry : : fileExists ( ) <nl> <nl> uint64_t DiskWriterEntry : : size ( ) const <nl> { <nl> - if ( diskWriter . isNull ( ) ) { <nl> - return File ( getFilePath ( ) ) . size ( ) ; <nl> - } else { <nl> - return diskWriter - > size ( ) ; <nl> - } <nl> + return File ( getFilePath ( ) ) . size ( ) ; <nl> } <nl> <nl> SharedHandle < FileEntry > DiskWriterEntry : : getFileEntry ( ) const <nl> void MultiDiskAdaptor : : resetDiskWriterEntries ( ) <nl> ( * i ) - > fileExists ( ) ) { <nl> logger - > debug ( " Creating DiskWriter for filename = % s " , <nl> ( * i ) - > getFilePath ( ) . c_str ( ) ) ; <nl> - ( * i ) - > setDiskWriter ( dwFactory . newDiskWriter ( ) ) ; <nl> + ( * i ) - > setDiskWriter ( dwFactory . newDiskWriter ( ( * i ) - > getFilePath ( ) ) ) ; <nl> ( * i ) - > getDiskWriter ( ) - > setDirectIOAllowed ( _directIOAllowed ) ; <nl> if ( _readOnly ) { <nl> ( * i ) - > getDiskWriter ( ) - > enableReadOnly ( ) ; <nl> bool MultiDiskAdaptor : : fileExists ( ) <nl> return false ; <nl> } <nl> <nl> - / / TODO call DiskWriter : : openFile ( ) before calling this function . <nl> uint64_t MultiDiskAdaptor : : size ( ) <nl> { <nl> uint64_t size = 0 ; <nl> mmm a / src / RequestGroup . cc <nl> ppp b / src / RequestGroup . cc <nl> void RequestGroup : : createInitialCommand ( std : : deque < Command * > & commands , <nl> progressInfoFile - > getFilename ( ) . c_str ( ) , <nl> getFilePath ( ) . c_str ( ) ) ; <nl> } <nl> - / / First , make DiskAdaptor read - only mode . <nl> - _pieceStorage - > getDiskAdaptor ( ) - > enableReadOnly ( ) ; <nl> - <nl> + { <nl> + uint64_t actualFileSize = _pieceStorage - > getDiskAdaptor ( ) - > size ( ) ; <nl> + if ( actualFileSize = = btContext - > getTotalLength ( ) ) { <nl> + / / First , make DiskAdaptor read - only mode to allow the <nl> + / / program to seed file in read - only media . <nl> + _pieceStorage - > getDiskAdaptor ( ) - > enableReadOnly ( ) ; <nl> + } else { <nl> + / / Open file in writable mode to allow the program <nl> + / / truncate the file to btContext - > getTotalLength ( ) <nl> + _logger - > debug ( " File size not match . File is opened in writable mode . " <nl> + " Expected : % s Actual : % s " , <nl> + Util : : uitos ( btContext - > getTotalLength ( ) ) . c_str ( ) , <nl> + Util : : uitos ( actualFileSize ) . c_str ( ) ) ; <nl> + } <nl> + } <nl> / / Call Load , Save and file allocation command here <nl> if ( progressInfoFile - > exists ( ) ) { <nl> / / load . aria2 file if it exists . <nl> void RequestGroup : : createInitialCommand ( std : : deque < Command * > & commands , <nl> } <nl> } <nl> _progressInfoFile = progressInfoFile ; <nl> - { <nl> - uint64_t actualFileSize = _pieceStorage - > getDiskAdaptor ( ) - > size ( ) ; <nl> - if ( actualFileSize ! = btContext - > getTotalLength ( ) ) { <nl> - / / Re - open file in writable mode to allow the program <nl> - / / truncate the file to the specified length <nl> - _logger - > debug ( " File size not match . Re - open file in writable mode . " <nl> - " Expected : % s Actual : % s " , <nl> - Util : : uitos ( btContext - > getTotalLength ( ) ) . c_str ( ) , <nl> - Util : : uitos ( actualFileSize ) . c_str ( ) ) ; <nl> - _pieceStorage - > getDiskAdaptor ( ) - > closeFile ( ) ; <nl> - _pieceStorage - > getDiskAdaptor ( ) - > disableReadOnly ( ) ; <nl> - _pieceStorage - > getDiskAdaptor ( ) - > openFile ( ) ; <nl> - } <nl> - } <nl> + <nl> if ( ! btContext - > isPrivate ( ) & & _option - > getAsBool ( PREF_ENABLE_DHT ) ) { <nl> std : : deque < Command * > commands ; <nl> DHTSetup ( ) . setup ( commands , e , _option ) ; <nl> mmm a / src / UnknownLengthPieceStorage . cc <nl> ppp b / src / UnknownLengthPieceStorage . cc <nl> UnknownLengthPieceStorage : : ~ UnknownLengthPieceStorage ( ) { } <nl> <nl> void UnknownLengthPieceStorage : : initStorage ( ) <nl> { <nl> - DiskWriterHandle writer = _diskWriterFactory - > newDiskWriter ( ) ; <nl> DirectDiskAdaptorHandle directDiskAdaptor ( new DirectDiskAdaptor ( ) ) ; <nl> - directDiskAdaptor - > setDiskWriter ( writer ) ; <nl> directDiskAdaptor - > setTotalLength ( _downloadContext - > getTotalLength ( ) ) ; <nl> + directDiskAdaptor - > setFileEntries ( _downloadContext - > getFileEntries ( ) ) ; <nl> + <nl> + DiskWriterHandle writer = <nl> + _diskWriterFactory - > newDiskWriter ( directDiskAdaptor - > getFilePath ( ) ) ; <nl> + directDiskAdaptor - > setDiskWriter ( writer ) ; <nl> + <nl> _diskAdaptor = directDiskAdaptor ; <nl> - std : : string storeDir = _downloadContext - > getDir ( ) ; <nl> - / / if ( storeDir = = " " ) { <nl> - / / storeDir = " . " ; <nl> - / / } <nl> - _diskAdaptor - > setStoreDir ( storeDir ) ; <nl> - _diskAdaptor - > setFileEntries ( _downloadContext - > getFileEntries ( ) ) ; <nl> } <nl> <nl> bool UnknownLengthPieceStorage : : hasMissingPiece ( const SharedHandle < Peer > & peer ) <nl> mmm a / src / Util . cc <nl> ppp b / src / Util . cc <nl> void Util : : rangedFileCopy ( const std : : string & dest , const std : : string & src , off_t <nl> { <nl> size_t bufSize = 4096 ; <nl> unsigned char buf [ bufSize ] ; <nl> - DefaultDiskWriter srcdw ; <nl> - DefaultDiskWriter destdw ; <nl> + DefaultDiskWriter srcdw ( src ) ; <nl> + DefaultDiskWriter destdw ( dest ) ; <nl> <nl> - srcdw . openExistingFile ( src ) ; <nl> - destdw . initAndOpenFile ( dest ) ; <nl> + srcdw . openExistingFile ( ) ; <nl> + destdw . initAndOpenFile ( ) ; <nl> <nl> lldiv_t res = lldiv ( length , bufSize ) ; <nl> unsigned int x = res . quot ; <nl> mmm a / test / DefaultDiskWriterTest . cc <nl> ppp b / test / DefaultDiskWriterTest . cc <nl> CPPUNIT_TEST_SUITE_REGISTRATION ( DefaultDiskWriterTest ) ; <nl> <nl> void DefaultDiskWriterTest : : testSize ( ) <nl> { <nl> - DefaultDiskWriter dw ; <nl> - dw . openExistingFile ( " 4096chunk . txt " ) ; <nl> + DefaultDiskWriter dw ( " 4096chunk . txt " ) ; <nl> + dw . openExistingFile ( ) ; <nl> CPPUNIT_ASSERT_EQUAL ( ( uint64_t ) 4096ULL , dw . size ( ) ) ; <nl> } <nl> <nl> mmm a / test / DirectDiskAdaptorTest . cc <nl> ppp b / test / DirectDiskAdaptorTest . cc <nl> void DirectDiskAdaptorTest : : testCutTrailingGarbage ( ) <nl> fileEntries . push_back ( entry ) ; <nl> <nl> DirectDiskAdaptor adaptor ; <nl> - adaptor . setDiskWriter ( SharedHandle < DiskWriter > ( new DefaultDiskWriter ( ) ) ) ; <nl> + adaptor . setDiskWriter <nl> + ( SharedHandle < DiskWriter > ( new DefaultDiskWriter ( entry - > getPath ( ) ) ) ) ; <nl> adaptor . setTotalLength ( entry - > getLength ( ) ) ; <nl> - adaptor . setStoreDir ( dir ) ; <nl> adaptor . setFileEntries ( fileEntries ) ; <nl> adaptor . openFile ( ) ; <nl> <nl> mmm a / test / FallocFileAllocationIteratorTest . cc <nl> ppp b / test / FallocFileAllocationIteratorTest . cc <nl> void FallocFileAllocationIteratorTest : : testAllocate ( ) <nl> File f ( fn ) ; <nl> CPPUNIT_ASSERT_EQUAL ( ( uint64_t ) 10 , f . size ( ) ) ; <nl> <nl> - DefaultDiskWriter writer ; <nl> + DefaultDiskWriter writer ( fn ) ; <nl> int64_t offset = 10 ; <nl> int64_t totalLength = 40960 ; <nl> <nl> / / we have to open file first . <nl> - writer . openExistingFile ( fn ) ; <nl> + writer . openExistingFile ( ) ; <nl> FallocFileAllocationIterator itr ( & writer , offset , totalLength ) ; <nl> <nl> itr . allocateChunk ( ) ; <nl> mmm a / test / MessageDigestHelperTest . cc <nl> ppp b / test / MessageDigestHelperTest . cc <nl> class MessageDigestHelperTest : public CppUnit : : TestFixture { <nl> CPPUNIT_TEST_SUITE_REGISTRATION ( MessageDigestHelperTest ) ; <nl> <nl> void MessageDigestHelperTest : : testDigestDiskWriter ( ) { <nl> - SharedHandle < DefaultDiskWriter > diskio ( new DefaultDiskWriter ( ) ) ; <nl> - diskio - > openExistingFile ( " 4096chunk . txt " ) ; <nl> + SharedHandle < DefaultDiskWriter > diskio <nl> + ( new DefaultDiskWriter ( " 4096chunk . txt " ) ) ; <nl> + diskio - > openExistingFile ( ) ; <nl> CPPUNIT_ASSERT_EQUAL ( std : : string ( " 608cabc0f2fa18c260cafd974516865c772363d5 " ) , <nl> MessageDigestHelper : : digest ( " sha1 " , diskio , 0 , 4096 ) ) ; <nl> <nl> mmm a / test / MetalinkProcessorTest . cc <nl> ppp b / test / MetalinkProcessorTest . cc <nl> void MetalinkProcessorTest : : testParseFile ( ) <nl> void MetalinkProcessorTest : : testParseFromBinaryStream ( ) <nl> { <nl> MetalinkProcessor proc ; <nl> - DefaultDiskWriterHandle dw ( new DefaultDiskWriter ( ) ) ; <nl> - dw - > openExistingFile ( " test . xml " ) ; <nl> + DefaultDiskWriterHandle dw ( new DefaultDiskWriter ( " test . xml " ) ) ; <nl> + dw - > openExistingFile ( ) ; <nl> <nl> try { <nl> SharedHandle < Metalinker > m = proc . parseFromBinaryStream ( dw ) ; <nl> mmm a / test / MultiDiskAdaptorTest . cc <nl> ppp b / test / MultiDiskAdaptorTest . cc <nl> class MultiDiskAdaptorTest : public CppUnit : : TestFixture { <nl> void setUp ( ) { <nl> adaptor . reset ( new MultiDiskAdaptor ( ) ) ; <nl> adaptor - > setPieceLength ( 2 ) ; <nl> - adaptor - > setStoreDir ( " . " ) ; <nl> } <nl> <nl> void testWriteData ( ) ; <nl> void MultiDiskAdaptorTest : : testCutTrailingGarbage ( ) <nl> ( & entries [ 0 ] , & entries [ arrayLength ( entries ) ] ) ; <nl> <nl> MultiDiskAdaptor adaptor ; <nl> - adaptor . setStoreDir ( dir ) ; <nl> adaptor . setFileEntries ( fileEntries ) ; <nl> adaptor . setMaxOpenFiles ( 1 ) ; <nl> adaptor . setPieceLength ( 1 ) ; <nl> void MultiDiskAdaptorTest : : testSize ( ) <nl> ( & entries [ 0 ] , & entries [ arrayLength ( entries ) ] ) ; <nl> <nl> MultiDiskAdaptor adaptor ; <nl> - adaptor . setStoreDir ( dir ) ; <nl> adaptor . setFileEntries ( fileEntries ) ; <nl> adaptor . setMaxOpenFiles ( 1 ) ; <nl> adaptor . setPieceLength ( 1 ) ; <nl> void MultiDiskAdaptorTest : : testUtime ( ) <nl> std : : deque < SharedHandle < FileEntry > > fileEntries <nl> ( & entries [ 0 ] , & entries [ arrayLength ( entries ) ] ) ; <nl> MultiDiskAdaptor adaptor ; <nl> - adaptor . setStoreDir ( storeDir ) ; <nl> adaptor . setFileEntries ( fileEntries ) ; <nl> <nl> time_t atime = ( time_t ) 100000 ; <nl> mmm a / test / MultiFileAllocationIteratorTest . cc <nl> ppp b / test / MultiFileAllocationIteratorTest . cc <nl> void MultiFileAllocationIteratorTest : : testMakeDiskWriterEntries ( ) <nl> diskAdaptor - > setFileEntries <nl> ( std : : deque < SharedHandle < FileEntry > > ( & fs [ 0 ] , & fs [ arrayLength ( fs ) ] ) ) ; <nl> diskAdaptor - > setPieceLength ( 1024 ) ; <nl> - diskAdaptor - > setStoreDir ( storeDir ) ; <nl> diskAdaptor - > openFile ( ) ; <nl> <nl> SharedHandle < MultiFileAllocationIterator > itr <nl> void MultiFileAllocationIteratorTest : : testAllocate ( ) <nl> <nl> try { <nl> SharedHandle < MultiDiskAdaptor > diskAdaptor ( new MultiDiskAdaptor ( ) ) ; <nl> - diskAdaptor - > setStoreDir ( storeDir ) ; <nl> diskAdaptor - > setPieceLength ( 1 ) ; <nl> <nl> int64_t offset = 0 ; <nl> mmm a / test / SingleFileAllocationIteratorTest . cc <nl> ppp b / test / SingleFileAllocationIteratorTest . cc <nl> void SingleFileAllocationIteratorTest : : testAllocate ( ) <nl> File x ( fn ) ; <nl> CPPUNIT_ASSERT_EQUAL ( ( uint64_t ) 10 , x . size ( ) ) ; <nl> <nl> - DefaultDiskWriter writer ; <nl> + DefaultDiskWriter writer ( fn ) ; <nl> int64_t offset = 10 ; <nl> int64_t totalLength = 16 * 1024 * 2 + 8 * 1024 ; <nl> <nl> / / we have to open file first . <nl> - writer . openExistingFile ( fn ) ; <nl> + writer . openExistingFile ( ) ; <nl> SingleFileAllocationIterator itr ( & writer , offset , totalLength ) ; <nl> itr . init ( ) ; <nl> <nl> mmm a / test / UtilTest . cc <nl> ppp b / test / UtilTest . cc <nl> void UtilTest : : testToString_binaryStream ( ) <nl> { <nl> SharedHandle < DiskWriter > dw ( new ByteArrayDiskWriter ( ) ) ; <nl> std : : string data ( 16 * 1024 + 256 , ' a ' ) ; <nl> - dw - > initAndOpenFile ( " dummy " ) ; <nl> + dw - > initAndOpenFile ( ) ; <nl> dw - > writeData ( ( const unsigned char * ) data . c_str ( ) , data . size ( ) , 0 ) ; <nl> <nl> std : : string readData = Util : : toString ( dw ) ; <nl> | 2009 - 05 - 04 Tatsuhiro Tsujikawa < t - tujikawa @ users . sourceforge . net > | aria2/aria2 | c1aef8e2d1c7cb018856e1f28cb51f1e3cdc6f45 | 2009-05-04T07:50:38Z |
mmm a / docs / third_party . md <nl> ppp b / docs / third_party . md <nl> There are miscellaneous other things you may find useful as a Protocol Buffers d <nl> * [ Protocol Buffers Dynamic Schema - create protobuf schemas programmatically ( Java ) ] ( https : / / github . com / os72 / protobuf - dynamic ) <nl> * [ Make protoc plugins in NodeJS ] ( https : / / github . com / konsumer / node - protoc - plugin ) <nl> * [ ProfaneDB - A Protocol Buffers database ] ( https : / / profanedb . gitlab . io ) <nl> + * [ Protocol Buffer property - based testing utility and example message generator ( Python / Hypothesis ) ] ( https : / / github . com / CurataEng / hypothesis - protobuf ) <nl> | Add hypothesis - protobuf library to the 3rd party doc . | protocolbuffers/protobuf | 3c331432b565b3cfb4c3659c285f6d969262777c | 2017-11-13T16:42:41Z |
mmm a / xbmc / cores / VideoPlayer / DVDCodecs / Video / MMALCodec . cpp <nl> ppp b / xbmc / cores / VideoPlayer / DVDCodecs / Video / MMALCodec . cpp <nl> using namespace KODI : : MESSAGING ; <nl> <nl> # define VERBOSE 0 <nl> <nl> + void CMMALBuffer : : SetVideoDeintMethod ( std : : string method ) { if ( m_pool ) m_pool - > SetVideoDeintMethod ( method ) ; } <nl> <nl> CMMALVideoBuffer : : CMMALVideoBuffer ( CMMALVideo * omv , std : : shared_ptr < CMMALPool > pool ) <nl> : CMMALBuffer ( pool ) , m_omv ( omv ) <nl> bool CMMALVideo : : Open ( CDVDStreamInfo & hints , CDVDCodecOptions & options ) <nl> if ( ! CSettings : : GetInstance ( ) . GetBool ( CSettings : : SETTING_VIDEOPLAYER_USEMMAL ) | | hints . software ) <nl> return false ; <nl> <nl> - m_processInfo . SetVideoDeintMethod ( " none " ) ; <nl> - <nl> std : : list < EINTERLACEMETHOD > deintMethods ; <nl> deintMethods . push_back ( EINTERLACEMETHOD : : VS_INTERLACEMETHOD_AUTO ) ; <nl> deintMethods . push_back ( EINTERLACEMETHOD : : VS_INTERLACEMETHOD_MMAL_ADVANCED ) ; <nl> mmm a / xbmc / cores / VideoPlayer / DVDCodecs / Video / MMALCodec . h <nl> ppp b / xbmc / cores / VideoPlayer / DVDCodecs / Video / MMALCodec . h <nl> class CMMALBuffer : public IDVDResourceCounted < CMMALBuffer > <nl> bool m_rendered ; <nl> bool m_stills ; <nl> std : : shared_ptr < CMMALPool > m_pool ; <nl> + void SetVideoDeintMethod ( std : : string method ) ; <nl> const char * GetStateName ( ) { <nl> static const char * names [ ] = { " MMALStateNone " , " MMALStateHWDec " , " MMALStateFFDec " , " MMALStateDeint " , } ; <nl> if ( ( size_t ) m_state < vcos_countof ( names ) ) <nl> mmm a / xbmc / cores / VideoPlayer / VideoRenderers / HwDecRender / MMALRenderer . cpp <nl> ppp b / xbmc / cores / VideoPlayer / VideoRenderers / HwDecRender / MMALRenderer . cpp <nl> void CMMALRenderer : : Run ( ) <nl> { <nl> if ( buffer - > length > 0 ) <nl> { <nl> + EINTERLACEMETHOD last_interlace_method = m_interlace_method ; <nl> EINTERLACEMETHOD interlace_method = CMediaSettings : : GetInstance ( ) . GetCurrentVideoSettings ( ) . m_InterlaceMethod ; <nl> if ( interlace_method = = VS_INTERLACEMETHOD_AUTO ) <nl> { <nl> void CMMALRenderer : : Run ( ) <nl> else if ( m_deint_input | | interlace ) <nl> CheckConfigurationDeint ( omvb - > m_width , omvb - > m_height , omvb - > m_aligned_width , omvb - > m_aligned_height , omvb - > m_encoding , interlace_method ) ; <nl> <nl> + if ( ! m_deint_input ) <nl> + m_interlace_method = VS_INTERLACEMETHOD_NONE ; <nl> + <nl> + if ( last_interlace_method = = m_interlace_method ) <nl> + ; <nl> + else if ( m_interlace_method = = VS_INTERLACEMETHOD_MMAL_ADVANCED ) <nl> + omvb - > SetVideoDeintMethod ( " adv ( x2 ) " ) ; <nl> + else if ( m_interlace_method = = VS_INTERLACEMETHOD_MMAL_ADVANCED_HALF ) <nl> + omvb - > SetVideoDeintMethod ( " adv ( x1 ) " ) ; <nl> + else if ( m_interlace_method = = VS_INTERLACEMETHOD_MMAL_BOB ) <nl> + omvb - > SetVideoDeintMethod ( " bob ( x2 ) " ) ; <nl> + else if ( m_interlace_method = = VS_INTERLACEMETHOD_MMAL_BOB_HALF ) <nl> + omvb - > SetVideoDeintMethod ( " bob ( x1 ) " ) ; <nl> + else <nl> + omvb - > SetVideoDeintMethod ( " none " ) ; <nl> + <nl> if ( m_deint_input ) <nl> { <nl> MMAL_STATUS_T status = mmal_port_send_buffer ( m_deint_input , omvb - > mmal_buffer ) ; <nl> void CMMALRenderer : : DestroyDeinterlace ( ) <nl> CLog : : Log ( LOGERROR , " % s : : % s Failed to disable deinterlace output port ( status = % x % s ) " , CLASSNAME , __func__ , status , mmal_status_to_string ( status ) ) ; <nl> } <nl> m_deint_output = nullptr ; <nl> - m_interlace_method = VS_INTERLACEMETHOD_NONE ; <nl> + m_interlace_method = VS_INTERLACEMETHOD_MAX ; <nl> m_deint_width = 0 ; <nl> m_deint_height = 0 ; <nl> m_deint_aligned_width = 0 ; <nl> mmm a / xbmc / cores / VideoPlayer / VideoRenderers / HwDecRender / MMALRenderer . h <nl> ppp b / xbmc / cores / VideoPlayer / VideoRenderers / HwDecRender / MMALRenderer . h <nl> class CMMALPool : public std : : enable_shared_from_this < CMMALPool > <nl> void SetFormat ( uint32_t mmal_format , uint32_t width , uint32_t height , uint32_t aligned_width , uint32_t aligned_height , uint32_t size , AVCodecContext * avctx ) <nl> { m_mmal_format = mmal_format ; m_width = width ; m_height = height ; m_aligned_width = aligned_width ; m_aligned_height = aligned_height ; m_size = size , m_avctx = avctx ; m_software = true ; } <nl> bool IsSoftware ( ) { return m_software ; } <nl> + void SetVideoDeintMethod ( std : : string method ) { if ( m_processInfo ) m_processInfo - > SetVideoDeintMethod ( method ) ; } <nl> protected : <nl> uint32_t m_mmal_format , m_width , m_height , m_aligned_width , m_aligned_height , m_size ; <nl> AVCodecContext * m_avctx ; <nl> | MMAL : Report deinterlace method to processinfo overlay | xbmc/xbmc | 3b394659bd76a516d0c76b7e8666bfa30014f26f | 2016-11-04T11:42:50Z |
mmm a / src / wallet / rpcwallet . cpp <nl> ppp b / src / wallet / rpcwallet . cpp <nl> static RPCHelpMan settxfee ( ) <nl> " \ nSet the transaction fee per kB for this wallet . Overrides the global - paytxfee command line parameter . \ n " <nl> " Can be deactivated by passing 0 as the fee . In that case automatic fee selection will be used by default . \ n " , <nl> { <nl> - { " amount " , RPCArg : : Type : : AMOUNT , RPCArg : : Optional : : NO , " The transaction fee in " + CURRENCY_UNIT + " / kB " } , <nl> + { " amount " , RPCArg : : Type : : AMOUNT , RPCArg : : Optional : : NO , " The transaction fee in " + CURRENCY_UNIT + " / kvB " } , <nl> } , <nl> RPCResult { <nl> RPCResult : : Type : : BOOL , " " , " Returns true if successful " <nl> static RPCHelpMan getwalletinfo ( ) <nl> { RPCResult : : Type : : NUM , " keypoolsize " , " how many new keys are pre - generated ( only counts external keys ) " } , <nl> { RPCResult : : Type : : NUM , " keypoolsize_hd_internal " , " how many new keys are pre - generated for internal use ( used for change outputs , only appears if the wallet is using this feature , otherwise external keys are used ) " } , <nl> { RPCResult : : Type : : NUM_TIME , " unlocked_until " , / * optional * / true , " the " + UNIX_EPOCH_TIME + " until which the wallet is unlocked for transfers , or 0 if the wallet is locked ( only present for passphrase - encrypted wallets ) " } , <nl> - { RPCResult : : Type : : STR_AMOUNT , " paytxfee " , " the transaction fee configuration , set in " + CURRENCY_UNIT + " / kB " } , <nl> + { RPCResult : : Type : : STR_AMOUNT , " paytxfee " , " the transaction fee configuration , set in " + CURRENCY_UNIT + " / kvB " } , <nl> { RPCResult : : Type : : STR_HEX , " hdseedid " , / * optional * / true , " the Hash160 of the HD seed ( only present when HD is enabled ) " } , <nl> { RPCResult : : Type : : BOOL , " private_keys_enabled " , " false if privatekeys are disabled for this wallet ( enforced watch - only wallet ) " } , <nl> { RPCResult : : Type : : BOOL , " avoid_reuse " , " whether this wallet tracks clean / dirty coins in terms of reuse " } , <nl> static RPCHelpMan fundrawtransaction ( ) <nl> " e . g . with ' importpubkey ' or ' importmulti ' with the ' pubkeys ' or ' desc ' field . " } , <nl> { " lockUnspents " , RPCArg : : Type : : BOOL , / * default * / " false " , " Lock selected unspent outputs " } , <nl> { " fee_rate " , RPCArg : : Type : : AMOUNT , / * default * / " not set , fall back to wallet fee estimation " , " Specify a fee rate in " + CURRENCY_ATOM + " / vB . " } , <nl> - { " feeRate " , RPCArg : : Type : : AMOUNT , / * default * / " not set , fall back to wallet fee estimation " , " Specify a fee rate in " + CURRENCY_UNIT + " / kB . " } , <nl> + { " feeRate " , RPCArg : : Type : : AMOUNT , / * default * / " not set , fall back to wallet fee estimation " , " Specify a fee rate in " + CURRENCY_UNIT + " / kvB . " } , <nl> { " subtractFeeFromOutputs " , RPCArg : : Type : : ARR , / * default * / " empty array " , " The integers . \ n " <nl> " The fee will be equally deducted from the amount of each specified output . \ n " <nl> " Those recipients will receive less bitcoins than you enter in their corresponding amount field . \ n " <nl> static RPCHelpMan walletcreatefundedpsbt ( ) <nl> { " includeWatching " , RPCArg : : Type : : BOOL , / * default * / " true for watch - only wallets , otherwise false " , " Also select inputs which are watch only " } , <nl> { " lockUnspents " , RPCArg : : Type : : BOOL , / * default * / " false " , " Lock selected unspent outputs " } , <nl> { " fee_rate " , RPCArg : : Type : : AMOUNT , / * default * / " not set , fall back to wallet fee estimation " , " Specify a fee rate in " + CURRENCY_ATOM + " / vB . " } , <nl> - { " feeRate " , RPCArg : : Type : : AMOUNT , / * default * / " not set , fall back to wallet fee estimation " , " Specify a fee rate in " + CURRENCY_UNIT + " / kB . " } , <nl> + { " feeRate " , RPCArg : : Type : : AMOUNT , / * default * / " not set , fall back to wallet fee estimation " , " Specify a fee rate in " + CURRENCY_UNIT + " / kvB . " } , <nl> { " subtractFeeFromOutputs " , RPCArg : : Type : : ARR , / * default * / " empty array " , " The outputs to subtract the fee from . \ n " <nl> " The fee will be equally deducted from the amount of each specified output . \ n " <nl> " Those recipients will receive less bitcoins than you enter in their corresponding amount field . \ n " <nl> | wallet : update remaining rpcwallet fee rate units to BTC / kvB | bitcoin/bitcoin | 6da3afbaee5809ebf6d88efaa3958c505c2d71c7 | 2020-11-12T10:43:14Z |
mmm a / js / apps / system / aardvark / frontend / js / config / dygraphConfig . js <nl> ppp b / js / apps / system / aardvark / frontend / js / config / dygraphConfig . js <nl> <nl> } ; <nl> <nl> / / colors for dygraphs <nl> - var colors = [ " # 617e2b " , " # 296e9c " , " # 81ccd8 " , " # 7ca530 " , " # f6fbac " , " # 3c3c3c " , <nl> + var colors = [ " # 617e2b " , " # 296e9c " , " # 81ccd8 " , " # 7ca530 " , " # 3c3c3c " , <nl> " # aa90bd " , " # e1811d " , " # c7d4b2 " , " # d0b2d4 " ] ; <nl> <nl> / / figure dependend options <nl> mmm a / js / apps / system / aardvark / frontend / js / views / dashboardView . js <nl> ppp b / js / apps / system / aardvark / frontend / js / views / dashboardView . js <nl> <nl> el : ' # content ' , <nl> contentEl : ' . contentDiv ' , <nl> distributionChartDiv : " # distributionChartDiv " , <nl> - interval : 100000 , / / in milliseconds <nl> + interval : 5000 , / / in milliseconds <nl> detailTemplate : templateEngine . createTemplate ( " lineChartDetailView . ejs " ) , <nl> detailEl : ' # modalPlaceholder ' , <nl> <nl> mmm a / js / apps / system / aardvark / frontend / scss / cluster . css <nl> ppp b / js / apps / system / aardvark / frontend / scss / cluster . css <nl> a . warning . coordinator , a . warning . dbserver { <nl> . button - inactive { <nl> background - color : lightgrey ; } <nl> . button - inactive : hover { <nl> - background - color : grey ; } <nl> + background - color : gray ; } <nl> <nl> a . inactive . coordinator , a . inactive . dbserver { <nl> color : lightgrey ; } <nl> a . inactive . coordinator : hover , a . inactive . dbserver : hover { <nl> - color : grey ; } <nl> + color : gray ; } <nl> <nl> a . inactive . coordinator , a . inactive . dbserver { <nl> fill : lightgrey ; } <nl> a . inactive . coordinator : hover , a . inactive . dbserver : hover { <nl> - fill : grey ; } <nl> + fill : gray ; } <nl> <nl> ul . link - dropdown - menu , ul . user - dropdown - menu , ul . gv - dropdown - menu { <nl> - moz - border - radius : 3px ; <nl> svg . clusterChart { <nl> . lineGraph { <nl> position : absolute ; } <nl> . lineGraph . few . dygraph - legend > span . highlight { <nl> - border : 1px solid grey ; } <nl> + border : 1px solid gray ; } <nl> . lineGraph . many . dygraph - legend > span { <nl> display : none ; } <nl> . lineGraph . many . dygraph - legend > span . highlight { <nl> mmm a / js / apps / system / aardvark / frontend / scss / generated . css <nl> ppp b / js / apps / system / aardvark / frontend / scss / generated . css <nl> nav . navbar , footer . footer { <nl> . button - inactive { <nl> background - color : lightgrey ; } <nl> . button - inactive : hover { <nl> - background - color : grey ; } <nl> + background - color : gray ; } <nl> <nl> ul . link - dropdown - menu , ul . user - dropdown - menu , ul . gv - dropdown - menu { <nl> - moz - border - radius : 3px ; <nl> | DASHBOARD CLEANUP | arangodb/arangodb | 24b9e9492fd2983b416d6a8a581d9629c451fec2 | 2014-03-17T14:04:09Z |
mmm a / hphp / hack / src / utils / bser / bser . ml <nl> ppp b / hphp / hack / src / utils / bser / bser . ml <nl> let json_callbacks = { <nl> ( Js_buildingObject ( ( f , x ) : : elts ) ) : : xs <nl> | _ - > raise ( ParseStateException ( - 1 ) ) ) ; <nl> <nl> + boolean_value = <nl> + ( fun acc b - > <nl> + ( Js_value ( Hh_json . JSON_Bool b ) ) : : acc ) ; <nl> + <nl> + null_value = <nl> + ( fun acc - > <nl> + ( Js_value ( Hh_json . JSON_Null ) ) : : acc ) ; <nl> + <nl> } <nl> <nl> <nl> new file mode 100644 <nl> index 00000000000 . . aa9c70a5e08 <nl> Binary files / dev / null and b / hphp / hack / test / utils / bser / json_output / 19_bools_and_null . bser differ <nl> new file mode 100644 <nl> index 00000000000 . . 6fd91306f46 <nl> mmm / dev / null <nl> ppp b / hphp / hack / test / utils / bser / json_output / 19_bools_and_null . bser . exp <nl> @ @ - 0 , 0 + 1 @ @ <nl> + [ null , false , true ] <nl> | null , bools | facebook/hhvm | e8d315491fa4877aeaa8fddc5709a1021f6eb54a | 2016-12-01T18:13:34Z |
mmm a / src / mongo / client / dbclient . cpp <nl> ppp b / src / mongo / client / dbclient . cpp <nl> namespace mongo { <nl> / / old version of server , ok , fall through to old code <nl> } <nl> else { <nl> - uasserted ( 18530 , str : : stream ( ) < < " listCollections failed : " < < res ) ; <nl> + uasserted ( 18630 , str : : stream ( ) < < " listCollections failed : " < < res ) ; <nl> } <nl> <nl> } <nl> namespace mongo { <nl> return specs ; <nl> } <nl> else { <nl> - uasserted ( 18531 , str : : stream ( ) < < " listIndexes failed : " < < res ) ; <nl> + uasserted ( 18631 , str : : stream ( ) < < " listIndexes failed : " < < res ) ; <nl> } <nl> } <nl> <nl> | SERVER - 14378 fix duplicate assert codes | mongodb/mongo | e3b915cec0233b4fcb5c1cd558cc57790b7b7386 | 2014-07-28T15:29:31Z |
mmm a / src / python / grpcio / grpc / _links / service . py <nl> ppp b / src / python / grpcio / grpc / _links / service . py <nl> def start ( self ) : <nl> self . _server . start ( ) <nl> self . _server . service ( None ) <nl> <nl> - def graceful_stop ( self ) : <nl> + def begin_stop ( self ) : <nl> with self . _lock : <nl> self . _server . stop ( ) <nl> self . _server = None <nl> + <nl> + def end_stop ( self ) : <nl> + with self . _lock : <nl> self . _completion_queue . stop ( ) <nl> self . _completion_queue = None <nl> pool = self . _pool <nl> def graceful_stop ( self ) : <nl> self . _rpc_states = None <nl> pool . shutdown ( wait = True ) <nl> <nl> - def immediate_stop ( self ) : <nl> - # TODO ( nathaniel ) : Implementation . <nl> - raise NotImplementedError ( <nl> - ' TODO ( nathaniel ) : after merge of rewritten lower layers ' ) <nl> - <nl> <nl> class ServiceLink ( links . Link ) : <nl> " " " A links . Link for use on the service - side of a gRPC connection . <nl> def start ( self ) : <nl> raise NotImplementedError ( ) <nl> <nl> @ abc . abstractmethod <nl> - def stop_gracefully ( self ) : <nl> - " " " Stops this link . <nl> + def begin_stop ( self ) : <nl> + " " " Indicate imminent link stop and immediate rejection of new RPCs . <nl> <nl> New RPCs will be rejected as soon as this method is called , but ongoing RPCs <nl> - will be allowed to continue until they terminate . This method blocks until <nl> - all RPCs have terminated . <nl> + will be allowed to continue until they terminate . This method does not <nl> + block . <nl> " " " <nl> raise NotImplementedError ( ) <nl> <nl> @ abc . abstractmethod <nl> - def stop_immediately ( self ) : <nl> - " " " Stops this link . <nl> + def end_stop ( self ) : <nl> + " " " Finishes stopping this link . <nl> + <nl> + begin_stop must have been called exactly once before calling this method . <nl> <nl> All in - progress RPCs will be terminated immediately . <nl> " " " <nl> def start ( self ) : <nl> self . _relay . start ( ) <nl> return self . _kernel . start ( ) <nl> <nl> - def stop_gracefully ( self ) : <nl> - self . _kernel . graceful_stop ( ) <nl> - self . _relay . stop ( ) <nl> + def begin_stop ( self ) : <nl> + self . _kernel . begin_stop ( ) <nl> <nl> - def stop_immediately ( self ) : <nl> - self . _kernel . immediate_stop ( ) <nl> + def end_stop ( self ) : <nl> + self . _kernel . end_stop ( ) <nl> self . _relay . stop ( ) <nl> <nl> <nl> mmm a / src / python / grpcio_test / grpc_test / _core_over_links_base_interface_test . py <nl> ppp b / src / python / grpcio_test / grpc_test / _core_over_links_base_interface_test . py <nl> def instantiate ( self , serializations , servicer ) : <nl> def destantiate ( self , memo ) : <nl> invocation_grpc_link , service_grpc_link = memo <nl> invocation_grpc_link . stop ( ) <nl> - service_grpc_link . stop_gracefully ( ) <nl> + service_grpc_link . begin_stop ( ) <nl> + service_grpc_link . end_stop ( ) <nl> <nl> def invocation_initial_metadata ( self ) : <nl> return _INVOCATION_INITIAL_METADATA <nl> mmm a / src / python / grpcio_test / grpc_test / _crust_over_core_over_links_face_interface_test . py <nl> ppp b / src / python / grpcio_test / grpc_test / _crust_over_core_over_links_face_interface_test . py <nl> def destantiate ( self , memo ) : <nl> service_end_link , pool ) = memo <nl> invocation_end_link . stop ( 0 ) . wait ( ) <nl> invocation_grpc_link . stop ( ) <nl> - service_grpc_link . stop_gracefully ( ) <nl> + service_grpc_link . begin_stop ( ) <nl> service_end_link . stop ( 0 ) . wait ( ) <nl> + service_grpc_link . end_stop ( ) <nl> invocation_end_link . join_link ( utilities . NULL_LINK ) <nl> invocation_grpc_link . join_link ( utilities . NULL_LINK ) <nl> service_grpc_link . join_link ( utilities . NULL_LINK ) <nl> mmm a / src / python / grpcio_test / grpc_test / _links / _transmission_test . py <nl> ppp b / src / python / grpcio_test / grpc_test / _links / _transmission_test . py <nl> def create_transmitting_links ( self ) : <nl> <nl> def destroy_transmitting_links ( self , invocation_side_link , service_side_link ) : <nl> invocation_side_link . stop ( ) <nl> - service_side_link . stop_gracefully ( ) <nl> + service_side_link . begin_stop ( ) <nl> + service_side_link . end_stop ( ) <nl> <nl> def create_invocation_initial_metadata ( self ) : <nl> return ( <nl> def testZeroMessageRoundTrip ( self ) : <nl> invocation_mate . block_until_tickets_satisfy ( test_cases . terminated ) <nl> <nl> invocation_link . stop ( ) <nl> - service_link . stop_gracefully ( ) <nl> + service_link . begin_stop ( ) <nl> + service_link . end_stop ( ) <nl> <nl> self . assertIs ( <nl> service_mate . tickets ( ) [ - 1 ] . termination , <nl> def _perform_scenario_test ( self , scenario ) : <nl> invocation_mate . block_until_tickets_satisfy ( test_cases . terminated ) <nl> <nl> invocation_link . stop ( ) <nl> - service_link . stop_gracefully ( ) <nl> + service_link . begin_stop ( ) <nl> + service_link . end_stop ( ) <nl> <nl> observed_requests = tuple ( <nl> ticket . payload for ticket in service_mate . tickets ( ) <nl> | Make ServiceLink shut - down a two step process | grpc/grpc | 4354f3e6809f12512d93b33e667133bc15f44029 | 2015-08-28T21:08:25Z |
mmm a / scripts / create_release . sh <nl> ppp b / scripts / create_release . sh <nl> fi <nl> if [ ! - f aseprite . exe ] ; then <nl> cd build <nl> ninja aseprite <nl> - cp src / aseprite . exe . . <nl> - cd . . <nl> + cd src <nl> + aseprite - sign aseprite . exe <nl> + cp aseprite . exe . . / . . <nl> + cd . . / . . <nl> fi <nl> <nl> # mmmmmmmmmmmmmmm <nl> | create_release . sh : Add command to sign the . exe file | aseprite/aseprite | 8d22664f7e9e494ad7dc79c073657c4bd207b489 | 2014-01-06T01:41:57Z |
mmm a / src / ui / int_entry . cpp <nl> ppp b / src / ui / int_entry . cpp <nl> bool IntEntry : : onProcessMessage ( Message * msg ) <nl> / / text is automatically selected . <nl> case kMouseEnterMessage : <nl> requestFocus ( ) ; <nl> - selectText ( 0 , - 1 ) ; <nl> + break ; <nl> + <nl> + / / Reset value if it ' s out of bounds when focus is lost <nl> + case kFocusLeaveMessage : <nl> + setValue ( MID ( m_min , getValue ( ) , m_max ) ) ; <nl> break ; <nl> <nl> case kMouseDownMessage : <nl> | Merge pull request from DocHoncho / int - entry - fix | aseprite/aseprite | 2eb84124d00dcc994dad0521b89c2e7bc507d833 | 2013-12-02T01:08:02Z |
mmm a / src / index / txindex . cpp <nl> ppp b / src / index / txindex . cpp <nl> void BaseIndex : : ThreadSync ( ) <nl> <nl> int64_t current_time = GetTime ( ) ; <nl> if ( last_log_time + SYNC_LOG_INTERVAL < current_time ) { <nl> - LogPrintf ( " Syncing txindex with block chain from height % d \ n " , pindex - > nHeight ) ; <nl> + LogPrintf ( " Syncing % s with block chain from height % d \ n " , <nl> + GetName ( ) , pindex - > nHeight ) ; <nl> last_log_time = current_time ; <nl> } <nl> <nl> void BaseIndex : : ThreadSync ( ) <nl> return ; <nl> } <nl> if ( ! WriteBlock ( block , pindex ) ) { <nl> - FatalError ( " % s : Failed to write block % s to tx index database " , <nl> + FatalError ( " % s : Failed to write block % s to index database " , <nl> __func__ , pindex - > GetBlockHash ( ) . ToString ( ) ) ; <nl> return ; <nl> } <nl> void BaseIndex : : ThreadSync ( ) <nl> } <nl> <nl> if ( pindex ) { <nl> - LogPrintf ( " txindex is enabled at height % d \ n " , pindex - > nHeight ) ; <nl> + LogPrintf ( " % s is enabled at height % d \ n " , GetName ( ) , pindex - > nHeight ) ; <nl> } else { <nl> - LogPrintf ( " txindex is enabled \ n " ) ; <nl> + LogPrintf ( " % s is enabled \ n " , GetName ( ) ) ; <nl> } <nl> } <nl> <nl> void BaseIndex : : BlockConnected ( const std : : shared_ptr < const CBlock > & block , const <nl> / / new chain tip . In this unlikely event , log a warning and let the queue clear . <nl> if ( best_block_index - > GetAncestor ( pindex - > nHeight - 1 ) ! = pindex - > pprev ) { <nl> LogPrintf ( " % s : WARNING : Block % s does not connect to an ancestor of " / * Continued * / <nl> - " known best chain ( tip = % s ) ; not updating txindex \ n " , <nl> + " known best chain ( tip = % s ) ; not updating index \ n " , <nl> __func__ , pindex - > GetBlockHash ( ) . ToString ( ) , <nl> best_block_index - > GetBlockHash ( ) . ToString ( ) ) ; <nl> return ; <nl> void BaseIndex : : BlockConnected ( const std : : shared_ptr < const CBlock > & block , const <nl> if ( WriteBlock ( * block , pindex ) ) { <nl> m_best_block_index = pindex ; <nl> } else { <nl> - FatalError ( " % s : Failed to write block % s to txindex " , <nl> + FatalError ( " % s : Failed to write block % s to index " , <nl> __func__ , pindex - > GetBlockHash ( ) . ToString ( ) ) ; <nl> return ; <nl> } <nl> void BaseIndex : : ChainStateFlushed ( const CBlockLocator & locator ) <nl> const CBlockIndex * best_block_index = m_best_block_index . load ( ) ; <nl> if ( best_block_index - > GetAncestor ( locator_tip_index - > nHeight ) ! = locator_tip_index ) { <nl> LogPrintf ( " % s : WARNING : Locator contains block ( hash = % s ) not on known best " / * Continued * / <nl> - " chain ( tip = % s ) ; not writing txindex locator \ n " , <nl> + " chain ( tip = % s ) ; not writing index locator \ n " , <nl> __func__ , locator_tip_hash . ToString ( ) , <nl> best_block_index - > GetBlockHash ( ) . ToString ( ) ) ; <nl> return ; <nl> bool BaseIndex : : BlockUntilSyncedToCurrentChain ( ) <nl> } <nl> } <nl> <nl> - LogPrintf ( " % s : txindex is catching up on block notifications \ n " , __func__ ) ; <nl> + LogPrintf ( " % s : % s is catching up on block notifications \ n " , __func__ , GetName ( ) ) ; <nl> SyncWithValidationInterfaceQueue ( ) ; <nl> return true ; <nl> } <nl> void BaseIndex : : Start ( ) <nl> / / callbacks are not missed if Init sets m_synced to true . <nl> RegisterValidationInterface ( this ) ; <nl> if ( ! Init ( ) ) { <nl> - FatalError ( " % s : txindex failed to initialize " , __func__ ) ; <nl> + FatalError ( " % s : % s failed to initialize " , __func__ , GetName ( ) ) ; <nl> return ; <nl> } <nl> <nl> - m_thread_sync = std : : thread ( & TraceThread < std : : function < void ( ) > > , " txindex " , <nl> + m_thread_sync = std : : thread ( & TraceThread < std : : function < void ( ) > > , GetName ( ) , <nl> std : : bind ( & BaseIndex : : ThreadSync , this ) ) ; <nl> } <nl> <nl> mmm a / src / index / txindex . h <nl> ppp b / src / index / txindex . h <nl> class BaseIndex : public CValidationInterface <nl> <nl> virtual BaseIndexDB & GetDB ( ) const = 0 ; <nl> <nl> + / / / Get the name of the index for display in logs . <nl> + virtual const char * GetName ( ) const = 0 ; <nl> + <nl> public : <nl> / / / Destructor interrupts sync thread if running and blocks until it exits . <nl> virtual ~ BaseIndex ( ) ; <nl> class TxIndex final : public BaseIndex <nl> <nl> BaseIndexDB & GetDB ( ) const override ; <nl> <nl> + const char * GetName ( ) const override { return " txindex " ; } <nl> + <nl> public : <nl> / / / Constructs the index , which becomes available to be queried . <nl> explicit TxIndex ( std : : unique_ptr < TxIndexDB > db ) ; <nl> | index : Generalize logged statements in BaseIndex . | bitcoin/bitcoin | f376a4924109af2496b5fd16a787299eb039f1c8 | 2018-06-05T02:22:24Z |
mmm a / WATCHLISTS <nl> ppp b / WATCHLISTS <nl> <nl> ' inspector ' : { <nl> ' filepath ' : ' inspector ' , <nl> } , <nl> + ' wasm ' : { <nl> + ' filepath ' : ' src / wasm / ' \ <nl> + ' | src / compiler / wasm ' , <nl> + } , <nl> } , <nl> <nl> ' WATCHLISTS ' : { <nl> <nl> ' inspector ' : [ <nl> ' devtools - reviews @ chromium . org ' , <nl> ] , <nl> + ' wasm ' : [ <nl> + ' wasm - v8 @ google . com ' , <nl> + ] , <nl> } , <nl> } <nl> | [ wasm ] wasm WATCHLISTS | v8/v8 | 25f86ffea5dbf239b9311ac2e045666956f0c437 | 2017-03-21T02:49:39Z |
mmm a / yarn . lock <nl> ppp b / yarn . lock <nl> <nl> integrity sha512 - kaYyLYf6ICn6 / isAyD4K1MyWWd5Q3JgH6bnMN089LUx88 + s4W8GvK9Q6JMBVu5vsFFp7pMdSxdKmlBXwH / VFRg = = <nl> <nl> " @ types / node @ ^ 10 . 12 . 18 " , " @ types / node @ ^ 10 . 14 . 8 " : <nl> - version " 10 . 17 . 6 " <nl> - resolved " https : / / registry . yarnpkg . com / @ types / node / - / node - 10 . 17 . 6 . tgz # 1aaabd6f6470a6ac3824ab1e94d731ca1326d93d " <nl> - integrity sha512 - 0a2X6cgN3RdPBL2MIlR6Lt0KlM7fOFsutuXcdglcOq6WvLnYXgPQSh0Mx6tO1KCAE8MxbHSOSTWDoUxRq + l3DA = = <nl> + version " 10 . 17 . 7 " <nl> + resolved " https : / / registry . yarnpkg . com / @ types / node / - / node - 10 . 17 . 7 . tgz # 2604f41a51bd652961b0c5abae082f7daf403d5d " <nl> + integrity sha512 - P / 82C + 0fGuQW8 / z2MbcJ337e9rrj32zuag00P + Yim / DU / u / bwERwHiMKE6Nnc / rXZaxa5 / 6IdvWZXG3 / qhStZg = = <nl> <nl> " @ types / normalize - package - data @ ^ 2 . 4 . 0 " : <nl> version " 2 . 4 . 0 " <nl> | Bump @ types / node from 10 . 17 . 6 to 10 . 17 . 7 ( ) | microsoft/react-native-windows | 069668aef587db5dabeb8f08080d7e9370d317af | 2019-12-10T00:48:51Z |
mmm a / tensorflow / contrib / rnn / python / kernel_tests / core_rnn_cell_test . py <nl> ppp b / tensorflow / contrib / rnn / python / kernel_tests / core_rnn_cell_test . py <nl> def testGRUCell ( self ) : <nl> # Smoke test <nl> self . assertAllClose ( res [ 0 ] , [ [ 0 . 156736 , 0 . 156736 ] ] ) <nl> <nl> - def testSRUCell ( self ) : <nl> - with self . test_session ( ) as sess : <nl> - with variable_scope . variable_scope ( <nl> - " root " , initializer = init_ops . constant_initializer ( 0 . 5 ) ) : <nl> - x = array_ops . zeros ( [ 1 , 2 ] ) <nl> - m = array_ops . zeros ( [ 1 , 2 ] ) <nl> - g , _ = rnn_cell_impl . SRUCell ( 2 ) ( x , m ) <nl> - sess . run ( [ variables_lib . global_variables_initializer ( ) ] ) <nl> - res = sess . run ( <nl> - [ g ] , { x . name : np . array ( [ [ 1 . , 1 . ] ] ) , <nl> - m . name : np . array ( [ [ 0 . 1 , 0 . 1 ] ] ) } ) <nl> - # Smoke test <nl> - self . assertAllClose ( res [ 0 ] , [ [ 0 . 509682 , 0 . 509682 ] ] ) <nl> - <nl> def testBasicLSTMCell ( self ) : <nl> for dtype in [ dtypes . float16 , dtypes . float32 ] : <nl> np_dtype = dtype . as_numpy_dtype <nl> mmm a / tensorflow / python / ops / rnn_cell . py <nl> ppp b / tensorflow / python / ops / rnn_cell . py <nl> <nl> @ @ BasicLSTMCell <nl> @ @ GRUCell <nl> @ @ LSTMCell <nl> - @ @ SRUCell <nl> <nl> # # Classes storing split ` RNNCell ` state <nl> <nl> mmm a / tensorflow / python / ops / rnn_cell_impl . py <nl> ppp b / tensorflow / python / ops / rnn_cell_impl . py <nl> def zero_state ( self , batch_size , dtype ) : <nl> self . _last_zero_state = ( state_size , batch_size , dtype , output ) <nl> return output <nl> <nl> + <nl> class _LayerRNNCell ( RNNCell ) : <nl> " " " Subclass of RNNCells that act like proper ` tf . Layer ` objects . <nl> <nl> def __call__ ( self , inputs , state , scope = None , * args , * * kwargs ) : <nl> return base_layer . Layer . __call__ ( self , inputs , state , scope = scope , <nl> * args , * * kwargs ) <nl> <nl> - class SRUCell ( _LayerRNNCell ) : <nl> - " " " Training RNNs as Fast as CNNs ( cf . https : / / arxiv . org / abs / 1709 . 02755 ) . <nl> - <nl> - Args : <nl> - num_units : int , The number of units in the SRU cell . <nl> - activation : Nonlinearity to use . Default : ` tanh ` . <nl> - reuse : ( optional ) Python boolean describing whether to reuse variables <nl> - in an existing scope . If not ` True ` , and the existing scope already has <nl> - the given variables , an error is raised . <nl> - name : ( optional ) String , the name of the layer . Layers with the same name <nl> - will share weights , but to avoid mistakes we require reuse = True in such <nl> - cases . <nl> - " " " <nl> - def __init__ ( self , num_units , <nl> - activation = None , reuse = None , name = None ) : <nl> - super ( SRUCell , self ) . __init__ ( _reuse = reuse , name = name ) <nl> - self . _num_units = num_units <nl> - self . _activation = activation or math_ops . tanh <nl> - <nl> - # Restrict inputs to be 2 - dimensional matrices <nl> - self . input_spec = base_layer . InputSpec ( ndim = 2 ) <nl> - <nl> - @ property <nl> - def state_size ( self ) : <nl> - return self . _num_units <nl> - <nl> - @ property <nl> - def output_size ( self ) : <nl> - return self . _num_units <nl> - <nl> - def build ( self , inputs_shape ) : <nl> - if inputs_shape [ 1 ] . value is None : <nl> - raise ValueError ( " Expected inputs . shape [ - 1 ] to be known , saw shape : % s " <nl> - % inputs_shape ) <nl> - <nl> - input_depth = inputs_shape [ 1 ] . value <nl> - <nl> - # Here the contributor believes that the following constraints <nl> - # are implied . The reasoning is explained here with reference to <nl> - # the paper https : / / arxiv . org / pdf / 1709 . 02755 . pdf upon which this <nl> - # implementation is based . <nl> - # In section 2 . 1 Equation 5 , specifically : <nl> - # h_t = r_t \ odot g ( c_t ) + ( 1 - r_t ) \ odot x_t <nl> - # the pointwise operation between r_t and x_t means they have <nl> - # the same shape ( since we are implementing an RNN cell , braodcasting <nl> - # does not happen to input of a single timestep ) ; by the same <nl> - # reasons , x_t has the same shape as h_t , essentially mandating that <nl> - # input_depth = unit_num . <nl> - if input_depth ! = self . _num_units : <nl> - raise ValueError ( " SRU requires input_depth = = num_units , got " <nl> - " input_depth = % s , num_units = % s " % ( input_depth , <nl> - self . _num_units ) ) <nl> - <nl> - self . _kernel = self . add_variable ( <nl> - _WEIGHTS_VARIABLE_NAME , <nl> - shape = [ input_depth , 3 * self . _num_units ] ) <nl> - <nl> - self . _bias = self . add_variable ( <nl> - _BIAS_VARIABLE_NAME , <nl> - shape = [ 2 * self . _num_units ] , <nl> - initializer = init_ops . constant_initializer ( 0 . 0 , dtype = self . dtype ) ) <nl> - <nl> - self . _built = True <nl> - <nl> - def call ( self , inputs , state ) : <nl> - " " " Simple recurrent unit ( SRU ) with num_units cells . " " " <nl> - <nl> - U = math_ops . matmul ( inputs , self . _kernel ) <nl> - x_bar , f_intermediate , r_intermediate = array_ops . split ( value = U , <nl> - num_or_size_splits = 3 , <nl> - axis = 1 ) <nl> - <nl> - f_r = math_ops . sigmoid ( nn_ops . bias_add ( array_ops . concat ( <nl> - [ f_intermediate , r_intermediate ] , 1 ) , self . _bias ) ) <nl> - f , r = array_ops . split ( value = f_r , num_or_size_splits = 2 , axis = 1 ) <nl> - <nl> - c = f * state + ( 1 . 0 - f ) * x_bar <nl> - h = r * self . _activation ( c ) + ( 1 . 0 - r ) * inputs <nl> - <nl> - return h , c <nl> <nl> class BasicRNNCell ( _LayerRNNCell ) : <nl> " " " The most basic RNN cell . <nl> | Revert " Initial SRU Implementation ( ) " | tensorflow/tensorflow | 2853a0d4a5b0d1d11aa4c68548a250b1b8084bb4 | 2017-12-18T06:00:34Z |
mmm a / docs / docs / term_index . xml <nl> ppp b / docs / docs / term_index . xml <nl> <nl> < term file = " ml . html " name = " svm_struct_controller_node " / > <nl> < term file = " ml . html " name = " svm_struct_processing_node " / > <nl> < term file = " ml . html " name = " sequence_labeler " / > <nl> + < term file = " dlib / svm / sequence_labeler_abstract . h . html " name = " contains_invalid_labeling " / > <nl> < term file = " ml . html " name = " structural_svm_sequence_labeling_problem " / > <nl> < term file = " ml . html " name = " structural_sequence_labeling_trainer " / > <nl> <nl> | updated docs | davisking/dlib | a80d9d57e238be7f3611791e9d86b64bcc8575e7 | 2011-12-10T03:42:33Z |
mmm a / binaries / core_overhead_benchmark_gpu . cc <nl> ppp b / binaries / core_overhead_benchmark_gpu . cc <nl> BENCHMARK ( BM_cudaStreamWaitEventThenStreamSynchronize ) ; <nl> <nl> static void BM_CudaPointerAffinity ( benchmark : : State & state ) { <nl> CAFFE2_SKIP_IF_NO_GPU ; <nl> - Tensor tensor ( vector < TIndex > { 1 , 2 , 3 , 4 } , CUDA ) ; <nl> + Tensor tensor ( vector < int64_t > { 1 , 2 , 3 , 4 } , CUDA ) ; <nl> float * ptr = tensor . mutable_data < float > ( ) ; <nl> while ( state . KeepRunning ( ) ) { <nl> volatile int id = GetGPUIDForPointer ( ptr ) ; <nl> mmm a / caffe2 / contrib / aten / aten_op_template . h <nl> ppp b / caffe2 / contrib / aten / aten_op_template . h <nl> class ATenOp : public Operator < Context > { <nl> } <nl> template < typename T > <nl> void assignToValue ( Tensor * dst , T v ) { <nl> - dst - > Resize ( std : : vector < TIndex > ( ) ) ; <nl> + dst - > Resize ( std : : vector < int64_t > ( ) ) ; <nl> math : : Set ( 1 , v , dst - > template mutable_data < T > ( ) , & context_ ) ; <nl> } <nl> int findImplementation ( const OperatorDef & operator_def ) { <nl> mmm a / caffe2 / contrib / gloo / allgather_ops . h <nl> ppp b / caffe2 / contrib / gloo / allgather_ops . h <nl> class AllgatherOp final : public Operator < Context > { <nl> auto comm_size = <nl> OperatorBase : : Input < std : : shared_ptr < : : gloo : : Context > > ( 0 ) - > size ; <nl> const auto dims = <nl> - std : : vector < TIndex > ( 1 , ( InputSize ( ) - 1 ) * Input ( 1 ) . size ( ) * comm_size ) ; <nl> + std : : vector < int64_t > ( 1 , ( InputSize ( ) - 1 ) * Input ( 1 ) . size ( ) * comm_size ) ; <nl> Output ( 0 ) - > Resize ( dims ) ; <nl> <nl> / / Store which inputs / outputs this instance initialized with <nl> mmm a / caffe2 / contrib / nccl / cuda_nccl_gpu . cc <nl> ppp b / caffe2 / contrib / nccl / cuda_nccl_gpu . cc <nl> void NCCL < T > : : AllGather ( const NCCLExecution & ex ) { <nl> ex , <nl> [ n ] ( const NCCLElement & ctx ) { <nl> CAFFE_ENFORCE_NE ( ctx . src , ctx . dst ) ; <nl> - std : : vector < TIndex > dims ; <nl> + std : : vector < int64_t > dims ; <nl> dims . reserve ( ctx . src - > ndim ( ) + 1 ) ; <nl> dims . push_back ( n ) ; <nl> for ( auto d : ctx . src - > dims ( ) ) { <nl> void NCCL < T > : : ReduceScatter ( const NCCLExecution & ex ) { <nl> [ ] ( const NCCLElement & ctx ) { <nl> CAFFE_ENFORCE_NE ( ctx . src , ctx . dst ) ; <nl> const auto & srcDims = ctx . src - > dims ( ) ; <nl> - std : : vector < TIndex > dstDims ( srcDims . begin ( ) + 1 , srcDims . end ( ) ) ; <nl> + std : : vector < int64_t > dstDims ( srcDims . begin ( ) + 1 , srcDims . end ( ) ) ; <nl> ctx . dst - > Resize ( dstDims ) ; <nl> ctx . dst - > template mutable_data < T > ( ) ; <nl> } , <nl> mmm a / caffe2 / contrib / tensorrt / tensorrt_op_trt . cc <nl> ppp b / caffe2 / contrib / tensorrt / tensorrt_op_trt . cc <nl> namespace { <nl> / / Otherwise , return the product of CHW dimensions <nl> int64_t CheckDims ( <nl> const nvinfer1 : : Dims & nv_dims , <nl> - const std : : vector < TIndex > & c2_dims ) { <nl> + const std : : vector < int64_t > & c2_dims ) { <nl> if ( nv_dims . nbDims + 1 ! = c2_dims . size ( ) ) { <nl> CAFFE_THROW ( <nl> " Mismatched dimensions between TRT input ( " , <nl> TensorRTOp : : TensorRTOp ( const OperatorDef & operator_def , Workspace * ws ) <nl> const std : : string key = MakeString ( " output_size_hint_ " , output_idx ) ; <nl> auto output_size_hint = OperatorBase : : GetRepeatedArgument < int > ( key ) ; <nl> if ( ! output_size_hint . empty ( ) ) { <nl> - std : : vector < TIndex > dims ; <nl> + std : : vector < int64_t > dims ; <nl> for ( const auto v : output_size_hint ) { <nl> dims . push_back ( v ) ; <nl> } <nl> TensorRTOp : : TensorRTOp ( const OperatorDef & operator_def , Workspace * ws ) <nl> <nl> void TensorRTOp : : MaybeAdjustOutputShape ( <nl> int output_idx , <nl> - std : : vector < TIndex > * dims ) { <nl> + std : : vector < int64_t > * dims ) { <nl> const auto it = output_size_hints_ . find ( output_idx ) ; <nl> if ( it ! = output_size_hints_ . end ( ) ) { <nl> const auto & dims_hint = it - > second ; <nl> auto total_trt = std : : accumulate ( <nl> - dims - > begin ( ) , dims - > end ( ) , ( TIndex ) ( 1 ) , std : : multiplies < TIndex > ( ) ) ; <nl> + dims - > begin ( ) , dims - > end ( ) , ( int64_t ) ( 1 ) , std : : multiplies < int64_t > ( ) ) ; <nl> auto total_c2 = std : : accumulate ( <nl> dims_hint . begin ( ) , <nl> dims_hint . end ( ) , <nl> - ( TIndex ) ( 1 ) , <nl> - std : : multiplies < TIndex > ( ) ) ; <nl> + ( int64_t ) ( 1 ) , <nl> + std : : multiplies < int64_t > ( ) ) ; <nl> CAFFE_ENFORCE_EQ ( <nl> total_trt , <nl> total_c2 , <nl> bool TensorRTOp : : RunOnDevice ( ) { <nl> } else { <nl> / / output , we need to allocate the output tensor at first batch run <nl> auto * output_tensor = Output ( output_idx ) ; <nl> - std : : vector < TIndex > tensor_dims ; <nl> + std : : vector < int64_t > tensor_dims ; <nl> tensor_dims . push_back ( N ) ; <nl> int64_t chw = 1 ; <nl> for ( int i = 0 ; i < dims . nbDims ; + + i ) { <nl> mmm a / caffe2 / contrib / tensorrt / tensorrt_op_trt . h <nl> ppp b / caffe2 / contrib / tensorrt / tensorrt_op_trt . h <nl> class TensorRTOp final : public Operator < CUDAContext > { <nl> virtual ~ TensorRTOp ( ) noexcept { } <nl> <nl> private : <nl> - void MaybeAdjustOutputShape ( int output_idx , std : : vector < TIndex > * dims ) ; <nl> + void MaybeAdjustOutputShape ( int output_idx , std : : vector < int64_t > * dims ) ; <nl> <nl> tensorrt : : TrtLogger logger_ ; <nl> int max_batch_size_ ; <nl> std : : vector < nvinfer1 : : Dims > nv_dims_ ; <nl> std : : vector < bool > is_input_ ; <nl> - std : : unordered_map < int , std : : vector < TIndex > > output_size_hints_ ; <nl> + std : : unordered_map < int , std : : vector < int64_t > > output_size_hints_ ; <nl> std : : shared_ptr < nvinfer1 : : ICudaEngine > trt_engine_ { nullptr } ; <nl> std : : shared_ptr < nvinfer1 : : IExecutionContext > trt_executor_ { nullptr } ; <nl> bool batch_warning_issued_ { false } ; <nl> mmm a / caffe2 / core / blob_serialization . cc <nl> ppp b / caffe2 / core / blob_serialization . cc <nl> void TensorSerializer : : SerializeWithChunkSize ( <nl> / / Serialize whole vector . If vector is empty , it ' s shape still needs to be <nl> / / serialized in empty proto <nl> for ( size_t chunkBegin = 0 ; <nl> - chunkBegin < std : : max ( tensor . size ( ) , static_cast < TIndex > ( 1 ) ) ; <nl> + chunkBegin < std : : max ( tensor . size ( ) , static_cast < int64_t > ( 1 ) ) ; <nl> chunkBegin + = chunk_size ) { <nl> VLOG ( 2 ) < < " Starting a chunk at " < < chunkBegin ; <nl> # ifndef __ANDROID__ <nl> void TensorDeserializer : : Deserialize ( const TensorProto & proto , Tensor * tensor ) { <nl> tensor - > GetStaticContext ( ) - > CreateContext ( proto . device_detail ( ) ) ; <nl> auto context = uniq_ptr . get ( ) ; <nl> context - > SwitchToDevice ( 0 ) ; <nl> - vector < TIndex > dims ; <nl> - for ( const TIndex d : proto . dims ( ) ) { <nl> + vector < int64_t > dims ; <nl> + for ( const int64_t d : proto . dims ( ) ) { <nl> dims . push_back ( d ) ; <nl> } <nl> tensor - > Resize ( dims ) ; <nl> mmm a / caffe2 / core / blob_test . cc <nl> ppp b / caffe2 / core / blob_test . cc <nl> TEST ( TensorTest , TensorNonFundamentalTypeClone ) { <nl> <nl> TEST ( TensorTest , Tensor64BitDimension ) { <nl> / / Initialize a large tensor . <nl> - TIndex large_number = <nl> + int64_t large_number = <nl> static_cast < int64_t > ( std : : numeric_limits < int > : : max ( ) ) + 1 ; <nl> - Tensor tensor ( vector < TIndex > { large_number } , CPU ) ; <nl> + Tensor tensor ( vector < int64_t > { large_number } , CPU ) ; <nl> EXPECT_EQ ( tensor . ndim ( ) , 1 ) ; <nl> EXPECT_EQ ( tensor . dim ( 0 ) , large_number ) ; <nl> EXPECT_EQ ( tensor . size ( ) , large_number ) ; <nl> TEST ( TensorTest , Tensor64BitDimension ) { <nl> } <nl> <nl> TEST ( TensorDeathTest , CannotCastDownLargeDims ) { <nl> - TIndex large_number = <nl> + int64_t large_number = <nl> static_cast < int64_t > ( std : : numeric_limits < int > : : max ( ) ) + 1 ; <nl> - Tensor tensor ( vector < TIndex > { large_number } , CPU ) ; <nl> + Tensor tensor ( vector < int64_t > { large_number } , CPU ) ; <nl> EXPECT_EQ ( tensor . ndim ( ) , 1 ) ; <nl> EXPECT_EQ ( tensor . dim ( 0 ) , large_number ) ; <nl> ASSERT_THROW ( tensor . dim32 ( 0 ) , EnforceNotMet ) ; <nl> TEST ( TensorTest , TensorSerialization_CustomType ) { <nl> } <nl> <nl> TEST ( TensorTest , Half ) { <nl> - const TIndex kSize = 3000000 ; <nl> + const int64_t kSize = 3000000 ; <nl> Blob blob ; <nl> TensorCPU * tensor = blob . GetMutableTensor ( CPU ) ; <nl> tensor - > Resize ( kSize ) ; <nl> mmm a / caffe2 / core / logging . h <nl> ppp b / caffe2 / core / logging . h <nl> using EnforceNotMet = at : : Error ; <nl> * functions to caffe2 : : enforce_detail namespace . For example : <nl> * <nl> * namespace caffe2 { namespace enforce_detail { <nl> - * inline EnforceFailMessage IsVector ( const vector < TIndex > & shape ) { <nl> + * inline EnforceFailMessage IsVector ( const vector < int64_t > & shape ) { <nl> * if ( shape . size ( ) = = 1 ) { return EnforceOK ( ) ; } <nl> * return MakeString ( " Shape " , shape , " is not a vector " ) ; <nl> * } <nl> mmm a / caffe2 / core / operator . cc <nl> ppp b / caffe2 / core / operator . cc <nl> TensorShapes InferBlobShapesAndTypesFromWorkspace ( <nl> } <nl> <nl> TensorShapes InferBlobShapesAndTypesFromMap ( <nl> - const CaffeMap < std : : string , std : : vector < TIndex > > & blob_dimensions , <nl> + const CaffeMap < std : : string , std : : vector < int64_t > > & blob_dimensions , <nl> const vector < NetDef * > & nets ) { <nl> CaffeMap < string , TensorShape > blob_desc ; <nl> / / Populate shapes from known blobs <nl> TensorShapes InferBlobShapesAndTypesFromMap ( <nl> } <nl> <nl> TensorShapes InferBlobShapesAndTypesFromMap ( <nl> - const CaffeMap < std : : string , std : : vector < TIndex > > & blob_dimensions , <nl> + const CaffeMap < std : : string , std : : vector < int64_t > > & blob_dimensions , <nl> const CaffeMap < std : : string , TensorProto_DataType > & blob_types , <nl> const vector < NetDef * > & nets ) { <nl> CaffeMap < string , TensorShape > blob_desc ; <nl> mmm a / caffe2 / core / operator . h <nl> ppp b / caffe2 / core / operator . h <nl> struct DispatchHelper < FixedValues < FirstVal , Values . . . > , ExtraArgs . . . > { <nl> template < typename . . . ExtraArgs > <nl> struct DispatchHelper < FixedValues < > , ExtraArgs . . . > { <nl> template < typename Op > <nl> - static bool call ( Op * op , TIndex / * size * / ) { <nl> + static bool call ( Op * op , int64_t / * size * / ) { <nl> return op - > template DoRunWithValue < ExtraArgs . . . , - 1 > ( ) ; <nl> } <nl> } ; <nl> CAFFE2_API TensorShapes InferBlobShapesAndTypesFromWorkspace ( <nl> const vector < NetDef * > & nets ) ; <nl> <nl> CAFFE2_API TensorShapes InferBlobShapesAndTypesFromMap ( <nl> - const CaffeMap < std : : string , std : : vector < TIndex > > & blob_dimensions , <nl> + const CaffeMap < std : : string , std : : vector < int64_t > > & blob_dimensions , <nl> const vector < NetDef * > & nets ) ; <nl> <nl> CAFFE2_API TensorShapes InferBlobShapesAndTypesFromMap ( <nl> - const CaffeMap < std : : string , std : : vector < TIndex > > & blob_dimensions , <nl> + const CaffeMap < std : : string , std : : vector < int64_t > > & blob_dimensions , <nl> const CaffeMap < std : : string , TensorProto_DataType > & blob_types , <nl> const vector < NetDef * > & nets ) ; <nl> <nl> mmm a / caffe2 / core / operator_schema . cc <nl> ppp b / caffe2 / core / operator_schema . cc <nl> int OpSchema : : CalculateOutput ( int num_input ) const { <nl> } <nl> <nl> static void SparseLengthsFillerHelper ( <nl> - const std : : vector < std : : vector < TIndex > > & shapes , <nl> + const std : : vector < std : : vector < int64_t > > & shapes , <nl> size_t value_index , <nl> size_t length_index , <nl> std : : vector < TensorFiller > * fillers ) { <nl> static void SparseLengthsFillerHelper ( <nl> } <nl> <nl> static void SparseSegmentsFillerHelper ( <nl> - const std : : vector < std : : vector < TIndex > > & shapes , <nl> + const std : : vector < std : : vector < int64_t > > & shapes , <nl> size_t value_index , <nl> size_t segment_index , <nl> std : : vector < TensorFiller > * fillers ) { <nl> OpSchema & OpSchema : : ValueKeyLengthInputFillers ( <nl> size_t key_index , <nl> size_t length_index ) { <nl> filler_supplier_ = [ this , value_index , key_index , length_index ] ( <nl> - const std : : vector < std : : vector < TIndex > > & shapes ) { <nl> + const std : : vector < std : : vector < int64_t > > & shapes ) { <nl> auto fillers = SupplyDenseFillers ( shapes ) ; <nl> / / fill in the length ( value_index is used to get the correct shape ) <nl> SparseLengthsFillerHelper ( shapes , key_index , length_index , & fillers ) ; <nl> OpSchema & OpSchema : : ValueLengthInputFillers ( <nl> size_t value_index , <nl> size_t length_index ) { <nl> filler_supplier_ = [ this , value_index , length_index ] ( <nl> - const std : : vector < std : : vector < TIndex > > & shapes ) { <nl> + const std : : vector < std : : vector < int64_t > > & shapes ) { <nl> auto fillers = SupplyDenseFillers ( shapes ) ; <nl> / / fill in the length ( value_index is used to get the correct shape ) <nl> SparseLengthsFillerHelper ( shapes , value_index , length_index , & fillers ) ; <nl> OpSchema & OpSchema : : ValueLengthInputFillers ( <nl> <nl> OpSchema & OpSchema : : DisallowInputFillers ( ) { <nl> filler_supplier_ = <nl> - [ this ] ( const std : : vector < std : : vector < TIndex > > & / * unused * / ) { <nl> + [ this ] ( const std : : vector < std : : vector < int64_t > > & / * unused * / ) { <nl> throw std : : invalid_argument ( type_ + " does not have input fillers " ) ; <nl> return std : : vector < TensorFiller > ( ) ; <nl> } ; <nl> OpSchema & OpSchema : : DisallowInputFillers ( ) { <nl> } <nl> <nl> std : : vector < TensorFiller > OpSchema : : InputFillers ( <nl> - const std : : vector < std : : vector < TIndex > > & shapes ) const { <nl> + const std : : vector < std : : vector < int64_t > > & shapes ) const { <nl> return filler_supplier_ ( shapes ) ; <nl> } <nl> <nl> std : : vector < TensorFiller > OpSchema : : SupplyDenseFillers ( <nl> - const std : : vector < std : : vector < TIndex > > & shapes ) { <nl> + const std : : vector < std : : vector < int64_t > > & shapes ) { <nl> std : : vector < TensorFiller > fillers ; <nl> for ( const auto & shape : shapes ) { <nl> fillers . emplace_back ( shape ) ; <nl> mmm a / caffe2 / core / operator_schema . h <nl> ppp b / caffe2 / core / operator_schema . h <nl> class CAFFE2_API OpSchema { <nl> OpSchema & DisallowInputFillers ( ) ; <nl> <nl> std : : vector < TensorFiller > InputFillers ( <nl> - const std : : vector < std : : vector < TIndex > > & shapes ) const ; <nl> + const std : : vector < std : : vector < int64_t > > & shapes ) const ; <nl> <nl> private : <nl> std : : vector < TensorFiller > SupplyDenseFillers ( <nl> - const std : : vector < std : : vector < TIndex > > & shapes ) ; <nl> + const std : : vector < std : : vector < int64_t > > & shapes ) ; <nl> <nl> private : <nl> string type_ ; <nl> class CAFFE2_API OpSchema { <nl> } ; <nl> <nl> std : : function < std : : vector < TensorFiller > ( <nl> - const std : : vector < std : : vector < TIndex > > & ) > <nl> + const std : : vector < std : : vector < int64_t > > & ) > <nl> filler_supplier_ = <nl> - [ this ] ( const std : : vector < std : : vector < TIndex > > & shapes ) { <nl> + [ this ] ( const std : : vector < std : : vector < int64_t > > & shapes ) { <nl> return SupplyDenseFillers ( shapes ) ; <nl> } ; <nl> } ; <nl> inline TensorShape CreateTensorShape ( <nl> } <nl> <nl> / / Helper function <nl> - inline vector < TIndex > GetDimsVector ( const TensorShape & shape ) { <nl> - vector < TIndex > dims ; <nl> + inline vector < int64_t > GetDimsVector ( const TensorShape & shape ) { <nl> + vector < int64_t > dims ; <nl> for ( auto d : shape . dims ( ) ) { <nl> dims . push_back ( d ) ; <nl> } <nl> mmm a / caffe2 / core / qtensor . h <nl> ppp b / caffe2 / core / qtensor . h <nl> class CAFFE2_EXPORT QTensor { <nl> / * * <nl> * Return product of all dimensions starting from K . <nl> * / <nl> - inline TIndex size_from_dim ( int k ) const { <nl> - TIndex r = 1 ; <nl> + inline int64_t size_from_dim ( int k ) const { <nl> + int64_t r = 1 ; <nl> for ( int i = k ; i < dims_ . size ( ) ; + + i ) { <nl> r * = dims_ [ i ] ; <nl> } <nl> class CAFFE2_EXPORT QTensor { <nl> / * * <nl> * Product of all dims up to . <nl> * / <nl> - inline TIndex size_to_dim ( int k ) const { <nl> + inline int64_t size_to_dim ( int k ) const { <nl> CAFFE_ENFORCE ( k < dims_ . size ( ) ) ; <nl> - TIndex r = 1 ; <nl> + int64_t r = 1 ; <nl> for ( int i = 0 ; i < k ; + + i ) { <nl> r * = dims_ [ i ] ; <nl> } <nl> mmm a / caffe2 / core / tensor . cc <nl> ppp b / caffe2 / core / tensor . cc <nl> void RegisterTypeCallFunction ( TypeIdentifier id , TypeCall c ) { <nl> <nl> int GetGPUIDForPointer ( const void * ptr ) ; <nl> <nl> - vector < TIndex > GetTensorInfo ( <nl> + vector < int64_t > GetTensorInfo ( <nl> const void * c , <nl> size_t * capacity , <nl> DeviceOption * device ) { <nl> mmm a / caffe2 / core / tensor . h <nl> ppp b / caffe2 / core / tensor . h <nl> class CAFFE2_API Tensor final { <nl> * Note that the actual data allocation is not going to be carried out until <nl> * the first time mutable_data ( ) is called . <nl> * / <nl> - explicit Tensor ( const vector < TIndex > & dims , DeviceType type ) <nl> + explicit Tensor ( const vector < int64_t > & dims , DeviceType type ) <nl> : Tensor ( Storage ( type ) ) { <nl> / / TODO : here , we create a Storage <nl> / / and immediately discard it in Resize ( ) since <nl> class CAFFE2_API Tensor final { <nl> * / <nl> template < typename T > <nl> Tensor ( <nl> - const vector < TIndex > & dims , <nl> + const vector < int64_t > & dims , <nl> const vector < T > & values , <nl> BaseContext * context ) <nl> : Tensor ( Storage ( context - > device_type ( ) , TypeMeta : : Make < T > ( ) ) ) { <nl> class CAFFE2_API Tensor final { <nl> typename = typename std : : enable_if < std : : is_scalar < T > : : value > : : type > <nl> Tensor ( const T & value , BaseContext * context ) <nl> : Tensor ( Storage ( context - > device_type ( ) , TypeMeta : : Make < T > ( ) ) ) { <nl> - Resize ( std : : vector < TIndex > { } ) ; <nl> + Resize ( std : : vector < int64_t > { } ) ; <nl> context - > CopyItemsFromCPU ( <nl> storage ( ) . dtype ( ) , size ( ) , & value , mutable_data < T > ( ) ) ; <nl> } <nl> class CAFFE2_API Tensor final { <nl> impl_ . get ( ) - > CopyFrom ( * src . impl_ . get ( ) , context ) ; <nl> } <nl> <nl> - void ExtendTo ( TIndex num , float growthPct , BaseContext * context ) const { <nl> + void ExtendTo ( int64_t num , float growthPct , BaseContext * context ) const { <nl> impl_ . get ( ) - > ExtendTo ( num , growthPct , context ) ; <nl> } <nl> <nl> - void Extend ( TIndex num , float growthPct , BaseContext * context ) const { <nl> + void Extend ( int64_t num , float growthPct , BaseContext * context ) const { <nl> impl_ . get ( ) - > Extend ( num , growthPct , context ) ; <nl> } <nl> <nl> - void ShrinkTo ( TIndex outer_dim ) const { <nl> + void ShrinkTo ( int64_t outer_dim ) const { <nl> impl_ . get ( ) - > ShrinkTo ( outer_dim ) ; <nl> } <nl> <nl> class CAFFE2_API Tensor final { <nl> impl_ . get ( ) - > ResizeLike ( * src_tensor . impl_ . get ( ) ) ; <nl> } <nl> <nl> - inline void Reshape ( const vector < TIndex > & dims ) const { <nl> + inline void Reshape ( const vector < int64_t > & dims ) const { <nl> impl_ . get ( ) - > Reshape ( dims ) ; <nl> } <nl> <nl> class CAFFE2_API Tensor final { <nl> return impl_ . get ( ) - > ndim ( ) ; <nl> } <nl> <nl> - inline TIndex size ( ) const { <nl> + inline int64_t size ( ) const { <nl> return impl_ . get ( ) - > size ( ) ; <nl> } <nl> <nl> class CAFFE2_API Tensor final { <nl> return impl_ . get ( ) - > capacity_nbytes ( ) ; <nl> } <nl> <nl> - inline const vector < TIndex > & dims ( ) const { <nl> + inline const vector < int64_t > & dims ( ) const { <nl> return impl_ . get ( ) - > dims ( ) ; <nl> } <nl> <nl> - inline TIndex size_from_dim ( int k ) const { <nl> + inline int64_t size_from_dim ( int k ) const { <nl> return impl_ . get ( ) - > size_from_dim ( k ) ; <nl> } <nl> <nl> - inline TIndex size_to_dim ( int k ) const { <nl> + inline int64_t size_to_dim ( int k ) const { <nl> return impl_ . get ( ) - > size_to_dim ( k ) ; <nl> } <nl> <nl> - inline TIndex size_between_dim ( int k , int l ) const { <nl> + inline int64_t size_between_dim ( int k , int l ) const { <nl> return impl_ . get ( ) - > size_between_dim ( k , l ) ; <nl> } <nl> <nl> class CAFFE2_API Tensor final { <nl> return impl_ . get ( ) - > dim32 ( i ) ; <nl> } <nl> <nl> - inline TIndex dim ( const int i ) const { <nl> + inline int64_t dim ( const int i ) const { <nl> return impl_ . get ( ) - > dim ( i ) ; <nl> } <nl> <nl> TypeCall GetTypeCallFunction ( TypeIdentifier id ) ; <nl> void RegisterTypeCallFunction ( TypeIdentifier id , TypeCall c ) ; <nl> <nl> / / Shape call registry <nl> - typedef vector < TIndex > ( * TensorInfoCall ) ( <nl> + typedef vector < int64_t > ( * TensorInfoCall ) ( <nl> const void * , <nl> size_t * capacity , <nl> DeviceOption * device ) ; <nl> void TensorPrinter : : Print ( const Tensor & tensor ) { <nl> std : : stringstream values_stream ; <nl> / / One most likely doesn ' t want to print int64 - number of items for visual <nl> / / inspection , so we cast down to int here . <nl> - int total_count = static_cast < int > ( std : : min ( tensor . size ( ) , TIndex ( limit_ ) ) ) ; <nl> + int total_count = static_cast < int > ( std : : min ( tensor . size ( ) , int64_t ( limit_ ) ) ) ; <nl> const T * tensor_data = tensor . template data < T > ( ) ; <nl> for ( int i = 0 ; i < total_count - 1 ; + + i ) { <nl> values_stream < < tensor_data [ i ] < < " , " ; <nl> mmm a / caffe2 / core / tensor_impl . h <nl> ppp b / caffe2 / core / tensor_impl . h <nl> namespace caffe2 { <nl> class DeviceOption ; <nl> <nl> / * * <nl> - * A utility function to convert vector < int > to vector < TIndex > . <nl> + * A utility function to convert vector < int > to vector < int64_t > . <nl> * / <nl> - inline std : : vector < TIndex > ToVectorTIndex ( const std : : vector < int > & src ) { <nl> - return std : : vector < TIndex > ( src . begin ( ) , src . end ( ) ) ; <nl> + inline std : : vector < int64_t > ToVectorint64_t ( const std : : vector < int > & src ) { <nl> + return std : : vector < int64_t > ( src . begin ( ) , src . end ( ) ) ; <nl> } <nl> <nl> / * * <nl> * Return product of all dimensions starting from k <nl> * / <nl> - inline TIndex size_from_dim_ ( int k , const std : : vector < TIndex > & dims ) { <nl> - TIndex r = 1 ; <nl> + inline int64_t size_from_dim_ ( int k , const std : : vector < int64_t > & dims ) { <nl> + int64_t r = 1 ; <nl> for ( size_t i = k ; i < dims . size ( ) ; + + i ) { <nl> r * = dims [ i ] ; <nl> } <nl> inline TIndex size_from_dim_ ( int k , const std : : vector < TIndex > & dims ) { <nl> } <nl> <nl> / / Product of all dims up to k ( not including dims [ k ] ) <nl> - inline TIndex size_to_dim_ ( int k , const std : : vector < TIndex > & dims ) { <nl> + inline int64_t size_to_dim_ ( int k , const std : : vector < int64_t > & dims ) { <nl> CAFFE_ENFORCE ( ( unsigned ) k < = dims . size ( ) ) ; <nl> - TIndex r = 1 ; <nl> + int64_t r = 1 ; <nl> for ( int i = 0 ; i < k ; + + i ) { <nl> r * = dims [ i ] ; <nl> } <nl> inline TIndex size_to_dim_ ( int k , const std : : vector < TIndex > & dims ) { <nl> } <nl> <nl> / / Product of all dims between k and l ( not including dims [ k ] and dims [ l ] ) <nl> - inline TIndex size_between_dim_ ( int k , int l , const std : : vector < TIndex > & dims ) { <nl> + inline int64_t size_between_dim_ ( int k , int l , const std : : vector < int64_t > & dims ) { <nl> CAFFE_ENFORCE ( ( unsigned ) l < dims . size ( ) ) ; <nl> - TIndex r = 1 ; <nl> + int64_t r = 1 ; <nl> if ( k < l ) { <nl> for ( int i = k + 1 ; i < l ; + + i ) { <nl> r * = dims [ i ] ; <nl> class CAFFE2_API TensorImpl : public c10 : : intrusive_ptr_target { <nl> * @ brief Extend the outer - most dimension of this tensor <nl> * to dimension of ` num ` . <nl> * / <nl> - void ExtendTo ( TIndex num , float growthPct , at : : BaseContext * context ) { <nl> + void ExtendTo ( int64_t num , float growthPct , at : : BaseContext * context ) { <nl> CAFFE_ENFORCE_GE_WITH_CALLER ( dims_ . size ( ) , 1 ) ; <nl> CAFFE_ENFORCE_GE_WITH_CALLER ( growthPct , 0 ) ; <nl> CAFFE_ENFORCE ( context ! = nullptr , " Context must be provided . " ) ; <nl> class CAFFE2_API TensorImpl : public c10 : : intrusive_ptr_target { <nl> * growthPct . This ensures that Extend runs on an amortized O ( 1 ) time <nl> * complexity . <nl> * / <nl> - void Extend ( TIndex num , float growthPct , at : : BaseContext * context ) { <nl> + void Extend ( int64_t num , float growthPct , at : : BaseContext * context ) { <nl> CAFFE_ENFORCE_GE_WITH_CALLER ( dims_ . size ( ) , 1 ) ; <nl> CAFFE_ENFORCE_GE_WITH_CALLER ( <nl> num , 0 , " ` num ` must be non - negative for Extend " ) ; <nl> class CAFFE2_API TensorImpl : public c10 : : intrusive_ptr_target { <nl> auto newNumel = std : : accumulate ( <nl> newDims . begin ( ) , <nl> newDims . end ( ) , <nl> - static_cast < TIndex > ( 1 ) , <nl> - std : : multiplies < TIndex > ( ) ) ; <nl> + static_cast < int64_t > ( 1 ) , <nl> + std : : multiplies < int64_t > ( ) ) ; <nl> if ( newNumel * storage_ . itemsize ( ) < = storage_ . capacity ( ) ) { <nl> dims_ = newDims ; <nl> numel_ = newNumel ; <nl> class CAFFE2_API TensorImpl : public c10 : : intrusive_ptr_target { <nl> * This method guarantees that no re - allocations are carried out , which means <nl> * that the extra capacity after the end of the shurnk tensor is maintained . <nl> * / <nl> - void ShrinkTo ( TIndex outer_dim ) { <nl> + void ShrinkTo ( int64_t outer_dim ) { <nl> CAFFE_ENFORCE_WITH_CALLER ( <nl> is_contiguous_ , <nl> " Right now ShrinkTo is only supported on contiguous Tensor . " ) ; <nl> class CAFFE2_API TensorImpl : public c10 : : intrusive_ptr_target { <nl> numel_ = std : : accumulate ( <nl> dims_ . begin ( ) , <nl> dims_ . end ( ) , <nl> - static_cast < TIndex > ( 1 ) , <nl> - std : : multiplies < TIndex > ( ) ) ; <nl> + static_cast < int64_t > ( 1 ) , <nl> + std : : multiplies < int64_t > ( ) ) ; <nl> } <nl> <nl> / * * <nl> class CAFFE2_API TensorImpl : public c10 : : intrusive_ptr_target { <nl> auto newNumel = std : : accumulate ( <nl> newCapacity . begin ( ) , <nl> newCapacity . end ( ) , <nl> - static_cast < TIndex > ( 1 ) , <nl> - std : : multiplies < TIndex > ( ) ) ; <nl> + static_cast < int64_t > ( 1 ) , <nl> + std : : multiplies < int64_t > ( ) ) ; <nl> if ( newNumel * storage_ . itemsize ( ) < = storage_ . capacity ( ) ) { <nl> return ; <nl> } <nl> class CAFFE2_API TensorImpl : public c10 : : intrusive_ptr_target { <nl> * Resizes the tensor without touching underlying storage . <nl> * This requires the total size of the tensor to remains constant . <nl> * / <nl> - inline void Reshape ( const std : : vector < TIndex > & dims ) { <nl> + inline void Reshape ( const std : : vector < int64_t > & dims ) { <nl> CAFFE_ENFORCE_WITH_CALLER ( <nl> is_contiguous_ , <nl> " Right now Reshape is only supported for contiguous Tensor . " ) ; <nl> - TIndex new_size = 1 ; <nl> + int64_t new_size = 1 ; <nl> for ( auto d : dims ) { <nl> CAFFE_ENFORCE_GE_WITH_CALLER ( d , 0 ) ; <nl> new_size * = d ; <nl> class CAFFE2_API TensorImpl : public c10 : : intrusive_ptr_target { <nl> } <nl> <nl> inline void Reshape ( const std : : vector < int > & dims ) { <nl> - Reshape ( ToVectorTIndex ( dims ) ) ; <nl> + Reshape ( ToVectorint64_t ( dims ) ) ; <nl> } <nl> <nl> / * * <nl> class CAFFE2_API TensorImpl : public c10 : : intrusive_ptr_target { <nl> / * * <nl> * Returns the size ( i . e . the number of items ) of the tensor . <nl> * / <nl> - inline TIndex size ( ) const { <nl> + inline int64_t size ( ) const { <nl> return numel_ ; <nl> } <nl> / * * <nl> class CAFFE2_API TensorImpl : public c10 : : intrusive_ptr_target { <nl> / * * <nl> * Returns the dimensions of the tensor as a vector . <nl> * / <nl> - inline const std : : vector < TIndex > & dims ( ) const { <nl> + inline const std : : vector < int64_t > & dims ( ) const { <nl> return dims_ ; <nl> } <nl> <nl> - inline TIndex size_from_dim ( int k ) const { <nl> + inline int64_t size_from_dim ( int k ) const { <nl> return size_from_dim_ ( k , dims_ ) ; <nl> } <nl> <nl> - inline TIndex size_to_dim ( int k ) const { <nl> + inline int64_t size_to_dim ( int k ) const { <nl> return size_to_dim_ ( k , dims_ ) ; <nl> } <nl> <nl> - inline TIndex size_between_dim ( int k , int l ) const { <nl> + inline int64_t size_between_dim ( int k , int l ) const { <nl> return size_between_dim_ ( k , l , dims_ ) ; <nl> } <nl> <nl> class CAFFE2_API TensorImpl : public c10 : : intrusive_ptr_target { <nl> / * * <nl> * Returns the i - th dimension of the tensor in int . <nl> * <nl> - * This function returns an int value instead of TIndex , which depending on <nl> + * This function returns an int value instead of int64_t , which depending on <nl> * the typedef could be int64 . If you want int64 dim values , make sure you <nl> * call dim ( ) instead . <nl> * / <nl> class CAFFE2_API TensorImpl : public c10 : : intrusive_ptr_target { <nl> * must be between 0 ( inclusive ) and the number of dimensions , otherwise <nl> * this function will produce a fatal message . <nl> * / <nl> - inline TIndex dim ( const int i ) const { <nl> + inline int64_t dim ( const int i ) const { <nl> # ifndef NDEBUG <nl> CAFFE_ENFORCE_LT_WITH_CALLER ( i , dims_ . size ( ) , " Exceeding ndim limit " ) ; <nl> CAFFE_ENFORCE_GE_WITH_CALLER ( i , 0 , " Cannot have negative dimension index " ) ; <nl> class CAFFE2_API TensorImpl : public c10 : : intrusive_ptr_target { <nl> <nl> protected : <nl> / / TODO : change to DimVector <nl> - std : : vector < TIndex > dims_ ; / / sizes_ <nl> + std : : vector < int64_t > dims_ ; / / sizes_ <nl> at : : DimVector strides_ ; <nl> - TIndex numel_ = - 1 ; / / numel_ <nl> + int64_t numel_ = - 1 ; / / numel_ <nl> bool is_contiguous_ = true ; <nl> / / we decide to keep reserved_ and it will <nl> / / live in Tensor after the split <nl> class CAFFE2_API TensorImpl : public c10 : : intrusive_ptr_target { <nl> bool SetDims ( const std : : vector < T > & src ) { <nl> auto old_numel = numel_ ; <nl> dims_ . resize ( src . size ( ) ) ; <nl> - TIndex new_numel = 1 ; <nl> + int64_t new_numel = 1 ; <nl> for ( size_t i = 0 ; i < src . size ( ) ; + + i ) { <nl> new_numel * = src [ i ] ; <nl> dims_ [ i ] = src [ i ] ; <nl> class CAFFE2_API TensorImpl : public c10 : : intrusive_ptr_target { <nl> / / TODO ( jiayq ) : maybe rewrite the following functions with initializer list . <nl> / / NVCC does not play well with initializer lists last time , but worth <nl> / / another shot . <nl> - bool SetDims ( const TIndex d0 ) { <nl> + bool SetDims ( const int64_t d0 ) { <nl> auto old_numel = numel_ ; <nl> dims_ . resize ( 1 ) ; <nl> dims_ [ 0 ] = d0 ; <nl> class CAFFE2_API TensorImpl : public c10 : : intrusive_ptr_target { <nl> return numel_ ! = old_numel ; <nl> } <nl> <nl> - bool SetDims ( const TIndex d0 , const TIndex d1 ) { <nl> + bool SetDims ( const int64_t d0 , const int64_t d1 ) { <nl> auto old_numel = numel_ ; <nl> dims_ . resize ( 2 ) ; <nl> dims_ [ 0 ] = d0 ; <nl> class CAFFE2_API TensorImpl : public c10 : : intrusive_ptr_target { <nl> return numel_ ! = old_numel ; <nl> } <nl> <nl> - bool SetDims ( const TIndex d0 , const TIndex d1 , const TIndex d2 ) { <nl> + bool SetDims ( const int64_t d0 , const int64_t d1 , const int64_t d2 ) { <nl> auto old_numel = numel_ ; <nl> dims_ . resize ( 3 ) ; <nl> dims_ [ 0 ] = d0 ; <nl> class CAFFE2_API TensorImpl : public c10 : : intrusive_ptr_target { <nl> } <nl> <nl> bool <nl> - SetDims ( const TIndex d0 , const TIndex d1 , const TIndex d2 , const TIndex d3 ) { <nl> + SetDims ( const int64_t d0 , const int64_t d1 , const int64_t d2 , const int64_t d3 ) { <nl> auto old_numel = numel_ ; <nl> dims_ . resize ( 4 ) ; <nl> dims_ [ 0 ] = d0 ; <nl> mmm a / caffe2 / cuda_rtc / pool_op_rtc_gpu . cc <nl> ppp b / caffe2 / cuda_rtc / pool_op_rtc_gpu . cc <nl> class MaxPoolRTCOp final : public ConvPoolOpBase < CUDAContext > { <nl> <nl> private : <nl> MaxPoolRTCFunction func_ ; <nl> - vector < TIndex > input_dims_ ; <nl> + vector < int64_t > input_dims_ ; <nl> } ; <nl> <nl> class MaxPoolGradientRTCOp final : public ConvPoolOpBase < CUDAContext > { <nl> class MaxPoolGradientRTCOp final : public ConvPoolOpBase < CUDAContext > { <nl> <nl> private : <nl> MaxPoolGradientRTCFunction func_ ; <nl> - vector < TIndex > input_dims_ ; <nl> + vector < int64_t > input_dims_ ; <nl> } ; <nl> <nl> namespace { <nl> mmm a / caffe2 / experiments / operators / fully_connected_op_prune . h <nl> ppp b / caffe2 / experiments / operators / fully_connected_op_prune . h <nl> namespace caffe2 { <nl> using Shape = std : : array < int , N > ; <nl> <nl> template < int N > <nl> - const std : : vector < TIndex > & shape ( Shape < N > vs ) { <nl> - static thread_local std : : vector < TIndex > cache ; <nl> + const std : : vector < int64_t > & shape ( Shape < N > vs ) { <nl> + static thread_local std : : vector < int64_t > cache ; <nl> cache . resize ( vs . size ( ) ) ; <nl> for ( auto i = 0 ; i < vs . size ( ) ; + + i ) { <nl> cache [ i ] = vs [ i ] ; <nl> namespace caffe2 { <nl> return cache ; <nl> } <nl> <nl> - inline const std : : vector < TIndex > & shape ( int i ) { <nl> + inline const std : : vector < int64_t > & shape ( int i ) { <nl> return shape < 1 > ( Shape < 1 > ( { i } ) ) ; <nl> } <nl> <nl> - inline const std : : vector < TIndex > & shape ( int i , int j ) { <nl> + inline const std : : vector < int64_t > & shape ( int i , int j ) { <nl> return shape < 2 > ( Shape < 2 > ( { i , j } ) ) ; <nl> } <nl> <nl> namespace caffe2 { <nl> Y - > template mutable_data < T > ( ) , & context_ ) ; <nl> if ( OutputSize ( ) = = 2 ) { <nl> auto * Comp_rate = Output ( 1 ) ; <nl> - Comp_rate - > Resize ( vector < TIndex > ( ) ) ; <nl> + Comp_rate - > Resize ( vector < int64_t > ( ) ) ; <nl> T * comp_data = Comp_rate - > template mutable_data < T > ( ) ; <nl> math : : Sum < T , Context > ( <nl> Mask . size ( ) , Mask . template data < T > ( ) , comp_data , & context_ ) ; <nl> namespace caffe2 { <nl> 0 , dW - > template mutable_data < T > ( ) , <nl> & context_ ) ; <nl> <nl> - comp_r_buf_ . Resize ( vector < TIndex > ( ) ) ; <nl> + comp_r_buf_ . Resize ( vector < int64_t > ( ) ) ; <nl> T * comp_data = comp_r_buf_ . template mutable_data < T > ( ) ; <nl> math : : Sum < T , Context > ( <nl> Mask . size ( ) , Mask . template data < T > ( ) , comp_data , & context_ ) ; <nl> mmm a / caffe2 / experiments / operators / fully_connected_op_sparse . h <nl> ppp b / caffe2 / experiments / operators / fully_connected_op_sparse . h <nl> template < int N > <nl> using Shape = std : : array < int , N > ; <nl> <nl> template < int N > <nl> - const std : : vector < TIndex > & shape ( Shape < N > vs ) { <nl> - static thread_local std : : vector < TIndex > cache ; <nl> + const std : : vector < int64_t > & shape ( Shape < N > vs ) { <nl> + static thread_local std : : vector < int64_t > cache ; <nl> cache . resize ( vs . size ( ) ) ; <nl> for ( auto i = 0 ; i < vs . size ( ) ; + + i ) { <nl> cache [ i ] = vs [ i ] ; <nl> const std : : vector < TIndex > & shape ( Shape < N > vs ) { <nl> return cache ; <nl> } <nl> <nl> - inline const std : : vector < TIndex > & shape ( int i ) { <nl> + inline const std : : vector < int64_t > & shape ( int i ) { <nl> return shape < 1 > ( Shape < 1 > ( { i } ) ) ; <nl> } <nl> <nl> - inline const std : : vector < TIndex > & shape ( int i , int j ) { <nl> + inline const std : : vector < int64_t > & shape ( int i , int j ) { <nl> return shape < 2 > ( Shape < 2 > ( { i , j } ) ) ; <nl> } <nl> <nl> mmm a / caffe2 / experiments / operators / funhash_op . h <nl> ppp b / caffe2 / experiments / operators / funhash_op . h <nl> class FunHashOp : public Operator < Context > { <nl> FunHashOp ( const OperatorDef & operator_def , Workspace * ws ) <nl> : Operator < Context > ( operator_def , ws ) , <nl> num_outputs_ ( <nl> - OperatorBase : : GetSingleArgument < TIndex > ( " num_outputs " , - 1 ) ) , <nl> + OperatorBase : : GetSingleArgument < int64_t > ( " num_outputs " , - 1 ) ) , <nl> num_segments_ ( <nl> - OperatorBase : : GetSingleArgument < TIndex > ( " num_segments " , - 1 ) ) , <nl> + OperatorBase : : GetSingleArgument < int64_t > ( " num_segments " , - 1 ) ) , <nl> seed_ ( OperatorBase : : GetSingleArgument < uint64_t > ( " seed " , 0 ) ) { <nl> CAFFE_ENFORCE ( <nl> OperatorBase : : HasArgument ( " num_outputs " ) , <nl> class FunHashOp : public Operator < Context > { <nl> const auto & seg = Input ( 2 ) ; <nl> const auto & weight = Input ( 3 ) ; <nl> <nl> - TIndex num_alpha = 1 ; <nl> + int64_t num_alpha = 1 ; <nl> if ( adaptive_ ) { <nl> const auto & alpha = Input ( 4 ) ; <nl> num_alpha = alpha . dim ( 0 ) ; <nl> class FunHashOp : public Operator < Context > { <nl> <nl> const auto * seg_data = seg . template data < int > ( ) ; <nl> <nl> - TIndex num_weight = weight . dim ( 0 ) ; <nl> - TIndex num_nz_ent = seg . dim ( 0 ) ; <nl> + int64_t num_weight = weight . dim ( 0 ) ; <nl> + int64_t num_nz_ent = seg . dim ( 0 ) ; <nl> <nl> - TIndex n_segments = num_segments_ ; <nl> + int64_t n_segments = num_segments_ ; <nl> if ( num_segments_ = = - 1 ) { <nl> - for ( TIndex i = 0 ; i < num_nz_ent ; + + i ) { <nl> + for ( int64_t i = 0 ; i < num_nz_ent ; + + i ) { <nl> if ( seg_data [ i ] > n_segments ) { <nl> n_segments = seg_data [ i ] ; <nl> } <nl> class FunHashOp : public Operator < Context > { <nl> const auto * weight_data = weight . template data < T > ( ) ; <nl> const auto * alpha_data = adaptive_ ? Input ( 4 ) . template data < T > ( ) : 0 ; <nl> const auto * val_data = val . template data < T > ( ) ; <nl> - const auto * key_data = key . template data < TIndex > ( ) ; <nl> + const auto * key_data = key . template data < int64_t > ( ) ; <nl> <nl> - for ( TIndex j = 0 ; j < num_nz_ent ; + + j ) { <nl> - TIndex cur_seg = seg_data [ j ] ; <nl> - TIndex cur_key = key_data [ j ] ; <nl> + for ( int64_t j = 0 ; j < num_nz_ent ; + + j ) { <nl> + int64_t cur_seg = seg_data [ j ] ; <nl> + int64_t cur_key = key_data [ j ] ; <nl> T cur_val = val_data [ j ] ; <nl> - TIndex output_stride = cur_seg * num_outputs_ ; <nl> - for ( TIndex i = 0 ; i < num_outputs_ ; + + i ) { <nl> + int64_t output_stride = cur_seg * num_outputs_ ; <nl> + for ( int64_t i = 0 ; i < num_outputs_ ; + + i ) { <nl> T sum = 0 ; <nl> - for ( TIndex k = 0 ; k < num_alpha ; + + k ) { <nl> + for ( int64_t k = 0 ; k < num_alpha ; + + k ) { <nl> uint64_t hash ; <nl> / / The hash function takes as input four integers : <nl> / / 1 . feature index <nl> class FunHashOp : public Operator < Context > { <nl> <nl> hash_data [ 3 ] = INDEX_MAGIC ; <nl> hash = XXH64 ( hash_data . data ( ) , hash_data . size ( ) , seed_ ) ; <nl> - TIndex index = hash % num_weight ; <nl> + int64_t index = hash % num_weight ; <nl> <nl> T cur_weight = weight_data [ index ] ; <nl> # ifdef USE_SIGN <nl> class FunHashOp : public Operator < Context > { <nl> } <nl> <nl> protected : <nl> - TIndex num_outputs_ ; <nl> - TIndex num_segments_ ; <nl> + int64_t num_outputs_ ; <nl> + int64_t num_segments_ ; <nl> uint64_t seed_ ; <nl> std : : array < uint64_t , 4 > hash_data ; <nl> bool adaptive_ ; <nl> class FunHashGradientOp : public Operator < Context > { <nl> FunHashGradientOp ( const OperatorDef & operator_def , Workspace * ws ) <nl> : Operator < Context > ( operator_def , ws ) , <nl> num_outputs_ ( <nl> - OperatorBase : : GetSingleArgument < TIndex > ( " num_outputs " , - 1 ) ) , <nl> + OperatorBase : : GetSingleArgument < int64_t > ( " num_outputs " , - 1 ) ) , <nl> seed_ ( OperatorBase : : GetSingleArgument < uint64_t > ( " seed " , 0 ) ) { <nl> adaptive_ = ( InputSize ( ) = = 6 ) ; <nl> } <nl> class FunHashGradientOp : public Operator < Context > { <nl> const auto & seg = Input ( 3 ) ; <nl> const auto & weight = Input ( 4 ) ; <nl> <nl> - TIndex num_alpha = 1 ; <nl> + int64_t num_alpha = 1 ; <nl> T * grad_alpha_data = 0 ; <nl> <nl> if ( adaptive_ ) { <nl> class FunHashGradientOp : public Operator < Context > { <nl> <nl> const auto * seg_data = seg . template data < int > ( ) ; <nl> <nl> - TIndex num_weight = weight . dim ( 0 ) ; <nl> - TIndex num_nz_ent = seg . dim ( 0 ) ; <nl> + int64_t num_weight = weight . dim ( 0 ) ; <nl> + int64_t num_nz_ent = seg . dim ( 0 ) ; <nl> <nl> auto * grad_weight = Output ( 0 ) ; <nl> grad_weight - > ResizeLike ( weight ) ; <nl> class FunHashGradientOp : public Operator < Context > { <nl> const auto * weight_data = weight . template data < T > ( ) ; <nl> const auto * alpha_data = adaptive_ ? Input ( 5 ) . template data < T > ( ) : 0 ; <nl> const auto * val_data = val . template data < T > ( ) ; <nl> - const auto * key_data = key . template data < TIndex > ( ) ; <nl> + const auto * key_data = key . template data < int64_t > ( ) ; <nl> <nl> memset ( grad_weight_data , 0 , sizeof ( T ) * num_weight ) ; <nl> <nl> - for ( TIndex j = 0 ; j < num_nz_ent ; + + j ) { <nl> - TIndex cur_seg = seg_data [ j ] ; <nl> - TIndex cur_key = key_data [ j ] ; <nl> + for ( int64_t j = 0 ; j < num_nz_ent ; + + j ) { <nl> + int64_t cur_seg = seg_data [ j ] ; <nl> + int64_t cur_key = key_data [ j ] ; <nl> T cur_val = val_data [ j ] ; <nl> - TIndex grad_out_stride = cur_seg * num_outputs_ ; <nl> - for ( TIndex i = 0 ; i < num_outputs_ ; + + i ) { <nl> + int64_t grad_out_stride = cur_seg * num_outputs_ ; <nl> + for ( int64_t i = 0 ; i < num_outputs_ ; + + i ) { <nl> T grad_out_scale = grad_out_data [ grad_out_stride + i ] * cur_val ; <nl> - for ( TIndex k = 0 ; k < num_alpha ; + + k ) { <nl> + for ( int64_t k = 0 ; k < num_alpha ; + + k ) { <nl> uint64_t hash ; <nl> hash_data [ 0 ] = cur_key ; <nl> hash_data [ 1 ] = i ; <nl> class FunHashGradientOp : public Operator < Context > { <nl> <nl> hash_data [ 3 ] = INDEX_MAGIC ; <nl> hash = XXH64 ( hash_data . data ( ) , hash_data . size ( ) , seed_ ) ; <nl> - TIndex index = hash % num_weight ; <nl> + int64_t index = hash % num_weight ; <nl> <nl> T cur_grad_out_scale = grad_out_scale ; <nl> # ifdef USE_SIGN <nl> class FunHashGradientOp : public Operator < Context > { <nl> } <nl> <nl> protected : <nl> - TIndex num_outputs_ ; <nl> + int64_t num_outputs_ ; <nl> uint64_t seed_ ; <nl> std : : array < uint64_t , 4 > hash_data ; <nl> bool adaptive_ ; <nl> mmm a / caffe2 / experiments / operators / sparse_funhash_op . h <nl> ppp b / caffe2 / experiments / operators / sparse_funhash_op . h <nl> class SparseFunHashOp : public Operator < Context > { <nl> SparseFunHashOp ( const OperatorDef & operator_def , Workspace * ws ) <nl> : Operator < Context > ( operator_def , ws ) , <nl> num_outputs_ ( <nl> - OperatorBase : : GetSingleArgument < TIndex > ( " num_outputs " , - 1 ) ) , <nl> + OperatorBase : : GetSingleArgument < int64_t > ( " num_outputs " , - 1 ) ) , <nl> num_segments_ ( <nl> - OperatorBase : : GetSingleArgument < TIndex > ( " num_segments " , - 1 ) ) , <nl> + OperatorBase : : GetSingleArgument < int64_t > ( " num_segments " , - 1 ) ) , <nl> seed_ ( OperatorBase : : GetSingleArgument < uint64_t > ( " seed " , 0 ) ) { <nl> CAFFE_ENFORCE ( <nl> OperatorBase : : HasArgument ( " num_outputs " ) , <nl> class SparseFunHashOp : public Operator < Context > { <nl> const auto & seg = Input ( 2 ) ; <nl> const auto & weight = Input ( 3 ) ; <nl> <nl> - TIndex num_alpha = 1 ; <nl> + int64_t num_alpha = 1 ; <nl> if ( adaptive_ ) { <nl> const auto & alpha = Input ( 4 ) ; <nl> num_alpha = alpha . dim ( 0 ) ; <nl> class SparseFunHashOp : public Operator < Context > { <nl> <nl> const auto * seg_data = seg . template data < int > ( ) ; <nl> <nl> - TIndex num_weight = weight . dim ( 0 ) ; <nl> - TIndex num_nz_ent = seg . dim ( 0 ) ; <nl> + int64_t num_weight = weight . dim ( 0 ) ; <nl> + int64_t num_nz_ent = seg . dim ( 0 ) ; <nl> <nl> - TIndex n_segments = num_segments_ ; <nl> + int64_t n_segments = num_segments_ ; <nl> if ( num_segments_ = = - 1 ) { <nl> - for ( TIndex i = 0 ; i < num_nz_ent ; + + i ) { <nl> + for ( int64_t i = 0 ; i < num_nz_ent ; + + i ) { <nl> if ( seg_data [ i ] > n_segments ) { <nl> n_segments = seg_data [ i ] ; <nl> } <nl> class SparseFunHashOp : public Operator < Context > { <nl> const auto * weight_data = weight . template data < T > ( ) ; <nl> const auto * alpha_data = adaptive_ ? Input ( 4 ) . template data < T > ( ) : 0 ; <nl> const auto * val_data = val . template data < T > ( ) ; <nl> - const auto * key_data = key . template data < TIndex > ( ) ; <nl> + const auto * key_data = key . template data < int64_t > ( ) ; <nl> <nl> - for ( TIndex j = 0 ; j < num_nz_ent ; + + j ) { <nl> - TIndex cur_seg = seg_data [ j ] ; <nl> - TIndex cur_key = key_data [ j ] ; <nl> + for ( int64_t j = 0 ; j < num_nz_ent ; + + j ) { <nl> + int64_t cur_seg = seg_data [ j ] ; <nl> + int64_t cur_key = key_data [ j ] ; <nl> T cur_val = val_data [ j ] ; <nl> - TIndex output_stride = cur_seg * num_outputs_ ; <nl> - for ( TIndex i = 0 ; i < num_outputs_ ; + + i ) { <nl> + int64_t output_stride = cur_seg * num_outputs_ ; <nl> + for ( int64_t i = 0 ; i < num_outputs_ ; + + i ) { <nl> T sum = 0 ; <nl> - for ( TIndex k = 0 ; k < num_alpha ; + + k ) { <nl> + for ( int64_t k = 0 ; k < num_alpha ; + + k ) { <nl> / / The hash function takes as input three integers : <nl> / / 1 . feature index <nl> / / 2 . output index <nl> class SparseFunHashOp : public Operator < Context > { <nl> <nl> # ifdef USE_SIGN <nl> / / Use the least significant bit for sign , the rest for weights . <nl> - TIndex index = ( hash > > 1 ) % num_weight ; <nl> + int64_t index = ( hash > > 1 ) % num_weight ; <nl> T cur_weight = weight_data [ index ] ; <nl> if ( hash & 1 ) { <nl> cur_weight = - cur_weight ; <nl> } <nl> # else <nl> - TIndex index = hash % num_weight ; <nl> + int64_t index = hash % num_weight ; <nl> T cur_weight = weight_data [ index ] ; <nl> # endif <nl> <nl> class SparseFunHashOp : public Operator < Context > { <nl> } <nl> <nl> protected : <nl> - TIndex num_outputs_ ; <nl> - TIndex num_segments_ ; <nl> + int64_t num_outputs_ ; <nl> + int64_t num_segments_ ; <nl> uint64_t seed_ ; <nl> std : : array < uint64_t , 4 > hash_data ; <nl> bool adaptive_ ; <nl> class SparseFunHashGradientOp : public Operator < Context > { <nl> SparseFunHashGradientOp ( const OperatorDef & operator_def , Workspace * ws ) <nl> : Operator < Context > ( operator_def , ws ) , <nl> num_outputs_ ( <nl> - OperatorBase : : GetSingleArgument < TIndex > ( " num_outputs " , - 1 ) ) , <nl> + OperatorBase : : GetSingleArgument < int64_t > ( " num_outputs " , - 1 ) ) , <nl> seed_ ( OperatorBase : : GetSingleArgument < uint64_t > ( " seed " , 0 ) ) { <nl> adaptive_ = ( InputSize ( ) = = 6 ) ; <nl> } <nl> class SparseFunHashGradientOp : public Operator < Context > { <nl> const auto & seg = Input ( 3 ) ; <nl> const auto & weight = Input ( 4 ) ; <nl> <nl> - TIndex num_alpha = 1 ; <nl> + int64_t num_alpha = 1 ; <nl> T * grad_alpha_data = 0 ; <nl> <nl> if ( adaptive_ ) { <nl> class SparseFunHashGradientOp : public Operator < Context > { <nl> <nl> const auto * seg_data = seg . template data < int > ( ) ; <nl> <nl> - TIndex num_weight = weight . dim ( 0 ) ; <nl> - TIndex num_nz_ent = seg . dim ( 0 ) ; <nl> + int64_t num_weight = weight . dim ( 0 ) ; <nl> + int64_t num_nz_ent = seg . dim ( 0 ) ; <nl> <nl> - TIndex grad_weight_size = num_nz_ent * num_outputs_ * num_alpha ; <nl> + int64_t grad_weight_size = num_nz_ent * num_outputs_ * num_alpha ; <nl> auto * grad_weight_val = Output ( 0 ) ; <nl> grad_weight_val - > Resize ( grad_weight_size ) ; <nl> T * grad_weight_val_data = grad_weight_val - > template mutable_data < T > ( ) ; <nl> class SparseFunHashGradientOp : public Operator < Context > { <nl> auto * grad_weight_ind = Output ( 1 ) ; <nl> grad_weight_ind - > Resize ( grad_weight_size ) ; <nl> auto * grad_weight_ind_data = <nl> - grad_weight_ind - > template mutable_data < TIndex > ( ) ; <nl> + grad_weight_ind - > template mutable_data < int64_t > ( ) ; <nl> <nl> const auto * grad_out_data = grad_out . template data < T > ( ) ; <nl> const auto * weight_data = weight . template data < T > ( ) ; <nl> const auto * alpha_data = adaptive_ ? Input ( 5 ) . template data < T > ( ) : 0 ; <nl> const auto * val_data = val . template data < T > ( ) ; <nl> - const auto * key_data = key . template data < TIndex > ( ) ; <nl> + const auto * key_data = key . template data < int64_t > ( ) ; <nl> <nl> - TIndex w_ind = 0 ; <nl> - for ( TIndex j = 0 ; j < num_nz_ent ; + + j ) { <nl> - TIndex cur_seg = seg_data [ j ] ; <nl> - TIndex cur_key = key_data [ j ] ; <nl> + int64_t w_ind = 0 ; <nl> + for ( int64_t j = 0 ; j < num_nz_ent ; + + j ) { <nl> + int64_t cur_seg = seg_data [ j ] ; <nl> + int64_t cur_key = key_data [ j ] ; <nl> T cur_val = val_data [ j ] ; <nl> - TIndex grad_out_stride = cur_seg * num_outputs_ ; <nl> - for ( TIndex i = 0 ; i < num_outputs_ ; + + i ) { <nl> + int64_t grad_out_stride = cur_seg * num_outputs_ ; <nl> + for ( int64_t i = 0 ; i < num_outputs_ ; + + i ) { <nl> T grad_out_scale = grad_out_data [ grad_out_stride + i ] * cur_val ; <nl> - for ( TIndex k = 0 ; k < num_alpha ; + + k ) { <nl> + for ( int64_t k = 0 ; k < num_alpha ; + + k ) { <nl> hash_data [ 0 ] = cur_key ; <nl> hash_data [ 1 ] = i ; <nl> hash_data [ 2 ] = k ; <nl> class SparseFunHashGradientOp : public Operator < Context > { <nl> <nl> T cur_grad_out_scale = grad_out_scale ; <nl> # ifdef USE_SIGN <nl> - TIndex index = ( hash > > 1 ) % num_weight ; <nl> + int64_t index = ( hash > > 1 ) % num_weight ; <nl> if ( hash & 1 ) { <nl> cur_grad_out_scale = - cur_grad_out_scale ; <nl> } <nl> # else <nl> - TIndex index = hash % num_weight ; <nl> + int64_t index = hash % num_weight ; <nl> # endif <nl> <nl> if ( adaptive_ ) { <nl> class SparseFunHashGradientOp : public Operator < Context > { <nl> } <nl> <nl> protected : <nl> - TIndex num_outputs_ ; <nl> + int64_t num_outputs_ ; <nl> uint64_t seed_ ; <nl> std : : array < uint64_t , 4 > hash_data ; <nl> bool adaptive_ ; <nl> mmm a / caffe2 / experiments / operators / sparse_matrix_reshape_op . h <nl> ppp b / caffe2 / experiments / operators / sparse_matrix_reshape_op . h <nl> class SparseMatrixReshapeOp : public Operator < Context > { <nl> OperatorBase : : HasArgument ( " new_shape " ) , <nl> " Argument ` new_shape ` is missing . " ) ; <nl> <nl> - vector < TIndex > old_shape = <nl> - OperatorBase : : GetRepeatedArgument < TIndex > ( " old_shape " ) ; <nl> - vector < TIndex > new_shape = <nl> - OperatorBase : : GetRepeatedArgument < TIndex > ( " new_shape " ) ; <nl> + vector < int64_t > old_shape = <nl> + OperatorBase : : GetRepeatedArgument < int64_t > ( " old_shape " ) ; <nl> + vector < int64_t > new_shape = <nl> + OperatorBase : : GetRepeatedArgument < int64_t > ( " new_shape " ) ; <nl> <nl> CAFFE_ENFORCE ( <nl> old_shape . size ( ) = = 2 , <nl> class SparseMatrixReshapeOp : public Operator < Context > { <nl> old_shape [ 0 ] > 0 , <nl> " The first dimension in ` old_shape ` must be positive . " ) ; <nl> <nl> - TIndex matrix_size = old_shape [ 0 ] * old_shape [ 1 ] ; <nl> + int64_t matrix_size = old_shape [ 0 ] * old_shape [ 1 ] ; <nl> <nl> if ( new_shape [ 0 ] = = - 1 ) { <nl> CAFFE_ENFORCE ( <nl> class SparseMatrixReshapeOp : public Operator < Context > { <nl> new_col - > Resize ( nnz ) ; <nl> new_row - > Resize ( nnz ) ; <nl> <nl> - const auto * old_col_data = old_col . template data < TIndex > ( ) ; <nl> + const auto * old_col_data = old_col . template data < int64_t > ( ) ; <nl> const auto * old_row_data = old_row . template data < int > ( ) ; <nl> <nl> - auto * new_col_data = new_col - > template mutable_data < TIndex > ( ) ; <nl> + auto * new_col_data = new_col - > template mutable_data < int64_t > ( ) ; <nl> auto * new_row_data = new_row - > template mutable_data < int > ( ) ; <nl> <nl> for ( int i = 0 ; i < nnz ; + + i ) { <nl> - TIndex offset = old_row_data [ i ] * old_stride_ + old_col_data [ i ] ; <nl> + int64_t offset = old_row_data [ i ] * old_stride_ + old_col_data [ i ] ; <nl> new_row_data [ i ] = offset / new_stride_ ; <nl> new_col_data [ i ] = offset % new_stride_ ; <nl> } <nl> class SparseMatrixReshapeOp : public Operator < Context > { <nl> } <nl> <nl> private : <nl> - TIndex old_stride_ ; <nl> - TIndex new_stride_ ; <nl> + int64_t old_stride_ ; <nl> + int64_t new_stride_ ; <nl> } ; <nl> <nl> } / / namespace caffe2 <nl> mmm a / caffe2 / experiments / operators / tt_contraction_op . h <nl> ppp b / caffe2 / experiments / operators / tt_contraction_op . h <nl> class TTContractionOp final : public Operator < Context > { <nl> USE_OPERATOR_CONTEXT_FUNCTIONS ; <nl> TTContractionOp ( const OperatorDef & operator_def , Workspace * ws ) <nl> : Operator < Context > ( operator_def , ws ) , <nl> - K_ ( OperatorBase : : GetSingleArgument < TIndex > ( " K " , 0 ) ) , <nl> - M_ ( OperatorBase : : GetSingleArgument < TIndex > ( " M " , 0 ) ) , <nl> - N_ ( OperatorBase : : GetSingleArgument < TIndex > ( " N " , 0 ) ) { <nl> + K_ ( OperatorBase : : GetSingleArgument < int64_t > ( " K " , 0 ) ) , <nl> + M_ ( OperatorBase : : GetSingleArgument < int64_t > ( " M " , 0 ) ) , <nl> + N_ ( OperatorBase : : GetSingleArgument < int64_t > ( " N " , 0 ) ) { <nl> CAFFE_ENFORCE ( OperatorBase : : HasArgument ( " K " ) , " Argument ` K ` is missing . " ) ; <nl> CAFFE_ENFORCE ( OperatorBase : : HasArgument ( " M " ) , " Argument ` M ` is missing . " ) ; <nl> CAFFE_ENFORCE ( OperatorBase : : HasArgument ( " N " ) , " Argument ` N ` is missing . " ) ; <nl> class TTContractionOp final : public Operator < Context > { <nl> <nl> CAFFE_ENFORCE ( A . ndim ( ) = = 2 , A . ndim ( ) ) ; <nl> <nl> - TIndex A_size = A . size_from_dim ( 0 ) ; <nl> - TIndex B_size = B . size_from_dim ( 0 ) ; <nl> + int64_t A_size = A . size_from_dim ( 0 ) ; <nl> + int64_t B_size = B . size_from_dim ( 0 ) ; <nl> <nl> CAFFE_ENFORCE ( <nl> K_ * M_ = = A_size , <nl> class TTContractionOp final : public Operator < Context > { <nl> B_size % ( K_ * N_ ) = = 0 , <nl> " Argument ` K ` and ` N ` do not agree with the size of B . " ) ; <nl> <nl> - TIndex D_ = B_size / ( K_ * N_ ) ; <nl> + int64_t D_ = B_size / ( K_ * N_ ) ; <nl> <nl> - TIndex C_size = D_ * M_ * N_ ; <nl> - C - > Resize ( vector < TIndex > { C_size } ) ; <nl> + int64_t C_size = D_ * M_ * N_ ; <nl> + C - > Resize ( vector < int64_t > { C_size } ) ; <nl> <nl> - TIndex B_stride = K_ * N_ ; <nl> - TIndex C_stride = M_ * N_ ; <nl> + int64_t B_stride = K_ * N_ ; <nl> + int64_t C_stride = M_ * N_ ; <nl> <nl> const T * A_data = A . template data < T > ( ) ; <nl> const T * B_data = B . template data < T > ( ) ; <nl> T * C_data = C - > template mutable_data < T > ( ) ; <nl> <nl> - for ( TIndex B_index = 0 ; B_index < B_size ; B_index + = B_stride ) { <nl> + for ( int64_t B_index = 0 ; B_index < B_size ; B_index + = B_stride ) { <nl> math : : Gemm < T , Context , Engine > ( <nl> CblasTrans , <nl> CblasNoTrans , <nl> class TTContractionOp final : public Operator < Context > { <nl> } <nl> <nl> protected : <nl> - TIndex K_ ; <nl> - TIndex M_ ; <nl> - TIndex N_ ; <nl> + int64_t K_ ; <nl> + int64_t M_ ; <nl> + int64_t N_ ; <nl> } ; <nl> <nl> template < typename T , class Context , class Engine = DefaultEngine > <nl> class TTContractionGradientOp final : public Operator < Context > { <nl> USE_OPERATOR_CONTEXT_FUNCTIONS ; <nl> TTContractionGradientOp ( const OperatorDef & operator_def , Workspace * ws ) <nl> : Operator < Context > ( operator_def , ws ) , <nl> - K_ ( OperatorBase : : GetSingleArgument < TIndex > ( " K " , 0 ) ) , <nl> - M_ ( OperatorBase : : GetSingleArgument < TIndex > ( " M " , 0 ) ) , <nl> - N_ ( OperatorBase : : GetSingleArgument < TIndex > ( " N " , 0 ) ) { } <nl> + K_ ( OperatorBase : : GetSingleArgument < int64_t > ( " K " , 0 ) ) , <nl> + M_ ( OperatorBase : : GetSingleArgument < int64_t > ( " M " , 0 ) ) , <nl> + N_ ( OperatorBase : : GetSingleArgument < int64_t > ( " N " , 0 ) ) { } <nl> <nl> bool RunOnDevice ( ) override { <nl> const auto & G = Input ( 0 ) ; <nl> class TTContractionGradientOp final : public Operator < Context > { <nl> auto * dA = Output ( 0 ) ; <nl> auto * dB = Output ( 1 ) ; <nl> <nl> - TIndex G_size = G . size_from_dim ( 0 ) ; <nl> - TIndex D_ = G_size / ( M_ * N_ ) ; <nl> + int64_t G_size = G . size_from_dim ( 0 ) ; <nl> + int64_t D_ = G_size / ( M_ * N_ ) ; <nl> <nl> - TIndex dB_size = D_ * K_ * N_ ; <nl> + int64_t dB_size = D_ * K_ * N_ ; <nl> <nl> dA - > Resize ( A . dims ( ) ) ; <nl> dB - > Resize ( B . dims ( ) ) ; <nl> <nl> - TIndex B_stride = K_ * N_ ; <nl> - TIndex G_stride = M_ * N_ ; <nl> + int64_t B_stride = K_ * N_ ; <nl> + int64_t G_stride = M_ * N_ ; <nl> <nl> const T * G_data = G . template data < T > ( ) ; <nl> const T * A_data = A . template data < T > ( ) ; <nl> class TTContractionGradientOp final : public Operator < Context > { <nl> T * dB_data = dB - > template mutable_data < T > ( ) ; <nl> <nl> const T * G_ptr = G_data ; <nl> - for ( TIndex B_index = 0 ; B_index < dB_size ; B_index + = B_stride ) { <nl> + for ( int64_t B_index = 0 ; B_index < dB_size ; B_index + = B_stride ) { <nl> math : : Gemm < T , Context , Engine > ( <nl> CblasNoTrans , <nl> CblasTrans , <nl> class TTContractionGradientOp final : public Operator < Context > { <nl> } <nl> <nl> G_ptr = G_data ; <nl> - for ( TIndex B_index = 0 ; B_index < dB_size ; B_index + = B_stride ) { <nl> + for ( int64_t B_index = 0 ; B_index < dB_size ; B_index + = B_stride ) { <nl> math : : Gemm < T , Context , Engine > ( <nl> CblasNoTrans , <nl> CblasNoTrans , <nl> class TTContractionGradientOp final : public Operator < Context > { <nl> } <nl> <nl> protected : <nl> - TIndex K_ ; <nl> - TIndex M_ ; <nl> - TIndex N_ ; <nl> + int64_t K_ ; <nl> + int64_t M_ ; <nl> + int64_t N_ ; <nl> } ; <nl> <nl> } / / namespace caffe2 <nl> mmm a / caffe2 / experiments / operators / tt_pad_op . h <nl> ppp b / caffe2 / experiments / operators / tt_pad_op . h <nl> class TTPadOp final : public Operator < Context > { <nl> USE_OPERATOR_CONTEXT_FUNCTIONS ; <nl> TTPadOp ( const OperatorDef & operator_def , Workspace * ws ) <nl> : Operator < Context > ( operator_def , ws ) , <nl> - scale_ ( OperatorBase : : GetSingleArgument < TIndex > ( " scale " , 0 ) ) { <nl> + scale_ ( OperatorBase : : GetSingleArgument < int64_t > ( " scale " , 0 ) ) { <nl> CAFFE_ENFORCE ( <nl> OperatorBase : : HasArgument ( " scale " ) , " Argument ` scale ` is missing . " ) ; <nl> } <nl> class TTPadOp final : public Operator < Context > { <nl> <nl> auto * X_orig_dim0 = Output ( 1 ) ; <nl> X_orig_dim0 - > Resize ( 1 ) ; <nl> - * X_orig_dim0 - > template mutable_data < TIndex > ( ) = X_dim0 ; <nl> + * X_orig_dim0 - > template mutable_data < int64_t > ( ) = X_dim0 ; <nl> <nl> if ( X_dim0 % scale_ ! = 0 ) { <nl> - TIndex padded_dim0 = ( X_dim0 / scale_ + 1 ) * scale_ ; <nl> + int64_t padded_dim0 = ( X_dim0 / scale_ + 1 ) * scale_ ; <nl> auto dim0_diff = padded_dim0 - X_dim0 ; <nl> / / set growthPct to the upper bound percentage : ( 100 * scale_ / X_dim0 ) <nl> X_pad - > Extend ( dim0_diff , 100 * scale_ / X_dim0 , & context_ ) ; <nl> <nl> auto * X_pad_data = X_pad - > template mutable_data < T > ( ) ; <nl> - TIndex X_size = X_dim0 * X_dim1 ; <nl> + int64_t X_size = X_dim0 * X_dim1 ; <nl> memset ( X_pad_data + X_size , 0 , dim0_diff * X_dim1 * sizeof ( T ) ) ; <nl> } <nl> <nl> class TTPadOp final : public Operator < Context > { <nl> } <nl> <nl> protected : <nl> - TIndex scale_ ; <nl> + int64_t scale_ ; <nl> } ; <nl> <nl> template < typename T , class Context , class Engine = DefaultEngine > <nl> class TTPadGradientOp final : public Operator < Context > { <nl> auto * output = Output ( 0 ) ; <nl> CAFFE_ENFORCE ( & G = = output ) ; <nl> <nl> - auto old_dim0 = * Input ( 1 ) . template data < TIndex > ( ) ; <nl> + auto old_dim0 = * Input ( 1 ) . template data < int64_t > ( ) ; <nl> auto new_dim0 = G . dim ( 0 ) ; <nl> auto dim1 = G . dim ( 1 ) ; <nl> <nl> mmm a / caffe2 / ideep / operators / concat_split_op . cc <nl> ppp b / caffe2 / ideep / operators / concat_split_op . cc <nl> class IDEEPConcatOp final : public IDEEPOperator { <nl> } <nl> <nl> auto axis_vdata = ideep : : concat : : compute ( inputs , axis_ , add_axis_ , * output ) ; <nl> - axis_info - > Resize ( vector < TIndex > ( 1 , InputSize ( ) ) ) ; <nl> + axis_info - > Resize ( vector < int64_t > ( 1 , InputSize ( ) ) ) ; <nl> int * axis_data = axis_info - > template mutable_data < int > ( ) ; <nl> for ( int i = 0 ; i < axis_vdata . size ( ) ; i + + ) { <nl> axis_data [ i ] = axis_vdata [ i ] ; <nl> mmm a / caffe2 / ideep / operators / conv_pool_base_op . h <nl> ppp b / caffe2 / ideep / operators / conv_pool_base_op . h <nl> class IDEEPConvPoolOpBase : public ConvPoolOpBase < IDEEPContext > { <nl> ideep : : tensor : : dims output_dims ; <nl> <nl> auto input_dims = input . get_dims ( ) ; <nl> - vector < TIndex > input_Tdims ( input_dims . begin ( ) , input_dims . end ( ) ) ; <nl> + vector < int64_t > input_Tdims ( input_dims . begin ( ) , input_dims . end ( ) ) ; <nl> InferOutputSize ( <nl> input_Tdims , <nl> output_channel , <nl> mmm a / caffe2 / ideep / operators / squeeze_op . cc <nl> ppp b / caffe2 / ideep / operators / squeeze_op . cc <nl> class IDEEPSqueezeOp final : public IDEEPOperator { <nl> ( dims_ . back ( ) + 1 ) , <nl> " dimensions . " ) ; <nl> const auto & ideep_dims = X . get_dims ( ) ; <nl> - vector < TIndex > dims ( ideep_dims . begin ( ) , ideep_dims . end ( ) ) ; <nl> + vector < int64_t > dims ( ideep_dims . begin ( ) , ideep_dims . end ( ) ) ; <nl> const auto & new_dims = SqueezeOp < IDEEPContext > : : ComputeDims ( dims , dims_ ) ; <nl> itensor : : dims new_dims_ideep ( new_dims . begin ( ) , new_dims . end ( ) ) ; <nl> if ( & X ! = Y ) { <nl> mmm a / caffe2 / image / image_input_op . h <nl> ppp b / caffe2 / image / image_input_op . h <nl> ImageInputOp < Context > : : ImageInputOp ( <nl> randgen_per_thread_ . emplace_back ( meta_randgen ( ) ) ; <nl> } <nl> prefetched_image_ . Resize ( <nl> - TIndex ( batch_size_ ) , <nl> - TIndex ( crop_ ) , <nl> - TIndex ( crop_ ) , <nl> - TIndex ( color_ ? 3 : 1 ) ) ; <nl> + int64_t ( batch_size_ ) , <nl> + int64_t ( crop_ ) , <nl> + int64_t ( crop_ ) , <nl> + int64_t ( color_ ? 3 : 1 ) ) ; <nl> if ( label_type_ ! = SINGLE_LABEL & & label_type_ ! = SINGLE_LABEL_WEIGHTED ) { <nl> - prefetched_label_ . Resize ( TIndex ( batch_size_ ) , TIndex ( num_labels_ ) ) ; <nl> + prefetched_label_ . Resize ( int64_t ( batch_size_ ) , int64_t ( num_labels_ ) ) ; <nl> } else { <nl> - prefetched_label_ . Resize ( vector < TIndex > ( 1 , batch_size_ ) ) ; <nl> + prefetched_label_ . Resize ( vector < int64_t > ( 1 , batch_size_ ) ) ; <nl> } <nl> <nl> for ( int i = 0 ; i < additional_output_sizes . size ( ) ; + + i ) { <nl> ImageInputOp < Context > : : ImageInputOp ( <nl> Context : : GetDeviceType ( ) ) ; <nl> prefetched_additional_outputs_ . emplace_back ( CPU ) ; <nl> prefetched_additional_outputs_ [ i ] . Resize ( <nl> - TIndex ( batch_size_ ) , TIndex ( additional_output_sizes [ i ] ) ) ; <nl> + int64_t ( batch_size_ ) , int64_t ( additional_output_sizes [ i ] ) ) ; <nl> } <nl> } <nl> <nl> mmm a / caffe2 / mkl / mkl_utils_test . cc <nl> ppp b / caffe2 / mkl / mkl_utils_test . cc <nl> TEST ( MKLDNNTest , SimpleConvolutionTest ) { <nl> int pads [ 2 ] = { 0 , 0 } ; <nl> <nl> / / Creating Input and output tensors <nl> - Tensor X ( vector < TIndex > { 16 , 8 , 32 , 32 } , CPU ) ; <nl> - Tensor W ( vector < TIndex > { 64 , 8 , 3 , 3 } , CPU ) ; <nl> - Tensor b ( vector < TIndex > { 64 } , CPU ) ; <nl> - Tensor Y ( vector < TIndex > { 16 , 64 , 30 , 30 } , CPU ) ; <nl> + Tensor X ( vector < int64_t > { 16 , 8 , 32 , 32 } , CPU ) ; <nl> + Tensor W ( vector < int64_t > { 64 , 8 , 3 , 3 } , CPU ) ; <nl> + Tensor b ( vector < int64_t > { 64 } , CPU ) ; <nl> + Tensor Y ( vector < int64_t > { 16 , 64 , 30 , 30 } , CPU ) ; <nl> <nl> float * data = X . mutable_data < float > ( ) ; <nl> for ( int i = 0 ; i < X . size ( ) ; + + i ) { <nl> TEST ( MKLDNNTest , MKLMemoryCopyTest ) { <nl> / / the buffer size being empty for both - former in dnnAllocateBuffer and <nl> / / the latter in dnnConversionExecute ( likely due to some difference in <nl> / / layout ? ) . Test both cases . <nl> - vector < vector < TIndex > > dims_list { { 10 , 3 , 20 , 20 } , { 0 } , { 0 , 10 } } ; <nl> + vector < vector < int64_t > > dims_list { { 10 , 3 , 20 , 20 } , { 0 } , { 0 , 10 } } ; <nl> for ( const auto & dims : dims_list ) { <nl> auto X_cpu_in = caffe2 : : make_unique < Tensor > ( dims , CPU ) ; <nl> CPUContext ctx ; <nl> mmm a / caffe2 / mkl / mklmemory_serialization . cc <nl> ppp b / caffe2 / mkl / mklmemory_serialization . cc <nl> class MKLMemoryDeserializer : public BlobDeserializerBase { <nl> " MKLMemory only supports either float or double formats . " ) ; <nl> CAFFE_ENFORCE ( <nl> ! proto . has_segment ( ) , " MKLMemory does not support segment right now . " ) ; <nl> - vector < TIndex > dims ; <nl> - for ( const TIndex d : proto . dims ( ) ) { <nl> + vector < int64_t > dims ; <nl> + for ( const int64_t d : proto . dims ( ) ) { <nl> dims . push_back ( d ) ; <nl> } <nl> / / TODO : right now , every time we do a deserializer we create a new MKL <nl> mmm a / caffe2 / mkl / operators / concat_op . cc <nl> ppp b / caffe2 / mkl / operators / concat_op . cc <nl> class MKLConcatOp final : public MKLOperator < T > { <nl> <nl> private : <nl> int axis_ ; <nl> - vector < TIndex > cached_output_dims_ ; <nl> + vector < int64_t > cached_output_dims_ ; <nl> } ; <nl> <nl> } / / namespace mkl <nl> mmm a / caffe2 / mkl / operators / conv_op . cc <nl> ppp b / caffe2 / mkl / operators / conv_op . cc <nl> class MKLConvOp final : public ConvPoolOpBase < MKLContext > { <nl> math : : Set < T , CPUContext > ( <nl> M , 0 . 0 , cpu_zero_bias . template mutable_data < float > ( ) , & ctx ) ; <nl> <nl> - zero_bias_ . reset ( new MKLMemory < T > ( std : : vector < TIndex > { M } ) ) ; <nl> + zero_bias_ . reset ( new MKLMemory < T > ( std : : vector < int64_t > { M } ) ) ; <nl> zero_bias_ - > CopyFrom ( cpu_zero_bias ) ; <nl> } <nl> const auto & bias = InputSize ( ) = = 2 <nl> class MKLConvOp final : public ConvPoolOpBase < MKLContext > { <nl> if ( group_ > 1 ) { <nl> / / Explicitly reformat the buffer . <nl> MKLMemory < float > group_filter ( <nl> - std : : vector < TIndex > { TIndex ( group_ ) , <nl> - TIndex ( filter . dim32 ( 0 ) / group_ ) , <nl> - TIndex ( filter . dim32 ( 1 ) ) , <nl> - TIndex ( filter . dim32 ( 2 ) ) , <nl> - TIndex ( filter . dim32 ( 3 ) ) } , <nl> + std : : vector < int64_t > { int64_t ( group_ ) , <nl> + int64_t ( filter . dim32 ( 0 ) / group_ ) , <nl> + int64_t ( filter . dim32 ( 1 ) ) , <nl> + int64_t ( filter . dim32 ( 2 ) ) , <nl> + int64_t ( filter . dim32 ( 3 ) ) } , <nl> nullptr , <nl> dnnResourceFilter , <nl> / * share_memory_if_possible = * / true ) ; <nl> class MKLConvOp final : public ConvPoolOpBase < MKLContext > { <nl> / / Input : X , W , b <nl> / / Output : Y <nl> std : : unique_ptr < MKLMemory < T > > zero_bias_ ; <nl> - vector < TIndex > cached_input_dims_ ; <nl> - vector < TIndex > cached_filter_dims_ ; <nl> + vector < int64_t > cached_input_dims_ ; <nl> + vector < int64_t > cached_filter_dims_ ; <nl> PrimitiveWrapper < T > primitive_ ; <nl> LayoutWrapper < T > input_layout_ ; <nl> LayoutWrapper < T > filter_layout_ ; <nl> mmm a / caffe2 / mkl / operators / conv_op_mkldnn . cc <nl> ppp b / caffe2 / mkl / operators / conv_op_mkldnn . cc <nl> class ConvMKLDNNOp final : public ConvPoolOpBase < CPUContext > { <nl> private : <nl> / / Input : X , W , b <nl> / / Output : Y <nl> - vector < TIndex > cached_input_dims_ ; <nl> - vector < TIndex > cached_filter_dims_ ; <nl> + vector < int64_t > cached_input_dims_ ; <nl> + vector < int64_t > cached_filter_dims_ ; <nl> PrimitiveWrapper < T > primitive_ ; <nl> unique_ptr < MKLMemory < T > > X_wrapper_ = nullptr ; <nl> unique_ptr < MKLMemory < T > > filter_wrapper_ = nullptr ; <nl> mmm a / caffe2 / mkl / operators / elementwise_sum_op . cc <nl> ppp b / caffe2 / mkl / operators / elementwise_sum_op . cc <nl> class MKLSumOp final : public MKLOperator < T > { <nl> <nl> private : <nl> std : : vector < float > coefficients_ ; <nl> - vector < TIndex > cached_input_dims_ ; <nl> + vector < int64_t > cached_input_dims_ ; <nl> vector < std : : shared_ptr < void > > input_views_ ; <nl> } ; <nl> <nl> mmm a / caffe2 / mkl / operators / fully_connected_op . cc <nl> ppp b / caffe2 / mkl / operators / fully_connected_op . cc <nl> class MKLFullyConnectedOp final : public MKLOperator < T > { <nl> / / Input : X , W , b <nl> / / Output : Y <nl> size_t axis_ { 1 } ; <nl> - vector < TIndex > cached_input_dims_ ; <nl> - vector < TIndex > cached_filter_dims_ ; <nl> + vector < int64_t > cached_input_dims_ ; <nl> + vector < int64_t > cached_filter_dims_ ; <nl> PrimitiveWrapper < T > primitive_ ; <nl> LayoutWrapper < T > input_layout_ ; <nl> LayoutWrapper < T > filter_layout_ ; <nl> mmm a / caffe2 / mkl / operators / local_response_normalization_op . cc <nl> ppp b / caffe2 / mkl / operators / local_response_normalization_op . cc <nl> class MKLLRNOp final : public LRNOpBase < T , MKLContext > { <nl> bool RunOnDeviceWithOrderNHWC ( ) override ; <nl> <nl> private : <nl> - vector < TIndex > cached_input_dims_ ; <nl> + vector < int64_t > cached_input_dims_ ; <nl> LayoutWrapper < T > workspace_layout_ ; <nl> std : : unique_ptr < MKLWorkspace < T > > workspace_buffer_ ; <nl> PrimitiveWrapper < T > primitive_ ; <nl> mmm a / caffe2 / mkl / operators / packed_fc_op . cc <nl> ppp b / caffe2 / mkl / operators / packed_fc_op . cc <nl> class PackedFCOp final : public Operator < CPUContext > { <nl> } <nl> size_t axis_ { 1 } ; <nl> uint32_t hash_ { 0 } ; <nl> - vector < TIndex > Y_shape_cache_ ; <nl> + vector < int64_t > Y_shape_cache_ ; <nl> Tensor bias_multiplier_ { CPU } ; <nl> std : : unique_ptr < MKLPackedMatrix > local_packed_matrix_ ; <nl> } ; <nl> mmm a / caffe2 / mkl / operators / pool_op . cc <nl> ppp b / caffe2 / mkl / operators / pool_op . cc <nl> class MKLPoolOp final : public ConvPoolOpBase < MKLContext > { <nl> / / Input : X <nl> / / Output : Y <nl> private : <nl> - vector < TIndex > cached_input_dims_ ; <nl> - / / vector < TIndex > cached_avgpool_input_dims_ ; <nl> + vector < int64_t > cached_input_dims_ ; <nl> + / / vector < int64_t > cached_avgpool_input_dims_ ; <nl> LayoutWrapper < T > workspace_layout_ ; <nl> std : : unique_ptr < MKLWorkspace < T > > workspace_buffer_ ; <nl> PrimitiveWrapper < T > primitive_ ; <nl> mmm a / caffe2 / mkl / operators / relu_op . cc <nl> ppp b / caffe2 / mkl / operators / relu_op . cc <nl> class MKLReluOp : public MKLOperator < T > { <nl> } <nl> <nl> private : <nl> - vector < TIndex > cached_input_dims_ ; <nl> + vector < int64_t > cached_input_dims_ ; <nl> } ; <nl> <nl> template < typename T > <nl> mmm a / caffe2 / mkl / operators / spatial_batch_norm_op . cc <nl> ppp b / caffe2 / mkl / operators / spatial_batch_norm_op . cc <nl> class MKLBNOp final : public Operator < MKLContext > { <nl> const StorageOrder order_ ; <nl> const int num_batches_ ; <nl> <nl> - vector < TIndex > cached_input_dims_ ; <nl> + vector < int64_t > cached_input_dims_ ; <nl> LayoutWrapper < T > scale_bias_layout_ ; <nl> LayoutWrapper < T > saved_mean_layout_ ; <nl> LayoutWrapper < T > saved_var_layout_ ; <nl> mmm a / caffe2 / mkl / operators / squeeze_op . cc <nl> ppp b / caffe2 / mkl / operators / squeeze_op . cc <nl> class MKLSqueezeOp final : public MKLOperator < T > { <nl> <nl> private : <nl> vector < int > dims_ ; <nl> - vector < TIndex > cached_input_dims_ ; <nl> + vector < int64_t > cached_input_dims_ ; <nl> } ; <nl> <nl> } / / namespace mkl <nl> mmm a / caffe2 / mkl / utils / mkl_memory . cc <nl> ppp b / caffe2 / mkl / utils / mkl_memory . cc <nl> CAFFE_KNOWN_TYPE ( mkl : : MKLMemory < float > ) ; <nl> CAFFE_KNOWN_TYPE ( mkl : : MKLMemory < double > ) ; <nl> <nl> template < typename T > <nl> - static vector < TIndex > GetMKLTensorInfo ( <nl> + static vector < int64_t > GetMKLTensorInfo ( <nl> const void * c , <nl> size_t * capacity , <nl> DeviceOption * device ) { <nl> mmm a / caffe2 / mkl / utils / mkl_memory . h <nl> ppp b / caffe2 / mkl / utils / mkl_memory . h <nl> <nl> # include < vector > <nl> # include < mutex > <nl> <nl> - # include " caffe2 / core / flags . h " / / for TIndex <nl> - # include " caffe2 / core / tensor . h " / / for TIndex <nl> + # include " caffe2 / core / flags . h " / / for int64_t <nl> + # include " caffe2 / core / tensor . h " / / for int64_t <nl> # include " caffe2 / mkl / utils / mkl_dnn_cppwrapper . h " <nl> <nl> / / A global boolean variable that controls the behavior when we call View ( ) on <nl> class MKLMemory { <nl> " Reshape is not allowed for custom layouts . " <nl> " Convert to plain layout before invoking Reshape ( ) . " ) ; <nl> <nl> - TIndex new_size = 1 ; <nl> + int64_t new_size = 1 ; <nl> for ( auto i = 0 ; i < dims . size ( ) ; + + i ) { <nl> CAFFE_ENFORCE_GE_WITH_CALLER ( dims [ i ] , 0 ) ; <nl> new_size * = dims [ i ] ; <nl> class MKLMemory { <nl> new_size = = size_ , <nl> " New size and old size are not equal . Reshape is not possible . " ) ; <nl> <nl> - vector < TIndex > new_dims ( dims . size ( ) ) ; <nl> + vector < int64_t > new_dims ( dims . size ( ) ) ; <nl> vector < size_t > size ( dims . size ( ) ) ; <nl> vector < size_t > strides ( dims . size ( ) ) ; <nl> for ( int i = 0 ; i < dims . size ( ) ; + + i ) { <nl> class MKLMemory { <nl> return buffer_ . get ( ) ; <nl> } <nl> <nl> - inline const vector < TIndex > & dims ( ) const { <nl> + inline const vector < int64_t > & dims ( ) const { <nl> return dims_ ; <nl> } <nl> <nl> class MKLMemory { <nl> / * * <nl> * Returns the size ( i . e . , the number of items ) in the buffer . <nl> * / <nl> - inline TIndex size ( ) const { <nl> + inline int64_t size ( ) const { <nl> return size_ ; <nl> } <nl> <nl> class MKLMemory { <nl> * must be between 0 ( inclusive ) and the number of dimensions , otherwise <nl> * this function will produce a fatal message . <nl> * / <nl> - inline TIndex dim ( const int i ) const { <nl> + inline int64_t dim ( const int i ) const { <nl> return dims_ . at ( i ) ; <nl> } <nl> <nl> class MKLMemory { <nl> mutable std : : mutex buffer_lock_ ; <nl> / / The dimensions in the same order as Caffe2 does . This is used to <nl> / / interface with C2 . <nl> - vector < TIndex > dims_ ; <nl> + vector < int64_t > dims_ ; <nl> / / Number of items in the buffer . <nl> - TIndex size_ = - 1 ; <nl> + int64_t size_ = - 1 ; <nl> / / The user dnn layout . <nl> LayoutWrapper < T > user_layout_ ; <nl> / / The internal dnn layout . <nl> mmm a / caffe2 / mkl / utils / mkl_operator . h <nl> ppp b / caffe2 / mkl / utils / mkl_operator . h <nl> class MKLOperator : public OperatorBase { <nl> / / The primitive used in the operator . <nl> PrimitiveWrapper < T > primitive_ ; <nl> / / Size cache for all the input sizes . <nl> - vector < vector < TIndex > > input_size_cache_ ; <nl> + vector < vector < int64_t > > input_size_cache_ ; <nl> / / An internal MKLMemory buffer . This is usually handy when we have a <nl> / / single output from the operator . If your operator has multiple outputs <nl> / / then you should allocate your own buffer . <nl> mmm a / caffe2 / mobile / contrib / arm - compute / core / context . h <nl> ppp b / caffe2 / mobile / contrib / arm - compute / core / context . h <nl> template < typename T > class GLTensor { <nl> <nl> const int32_t ndim ( ) const { return dims_ . size ( ) ; } <nl> <nl> - vector < TIndex > dims ( ) const { return dims_ ; } <nl> + vector < int64_t > dims ( ) const { return dims_ ; } <nl> <nl> const int32_t dim32 ( const int index ) const { return dims_ . at ( index ) ; } <nl> <nl> template < typename T > class GLTensor { <nl> bool SetDims ( const vector < TI > & src ) { <nl> auto old_size = size_ ; <nl> dims_ . resize ( src . size ( ) ) ; <nl> - TIndex new_size = 1 ; <nl> + int64_t new_size = 1 ; <nl> for ( unsigned int i = 0 ; i < src . size ( ) ; + + i ) { <nl> new_size * = src [ i ] ; <nl> dims_ [ i ] = src [ i ] ; <nl> template < typename T > class GLTensor { <nl> return size_ > old_size ; <nl> } <nl> <nl> - bool SetDims ( const TIndex d0 ) { <nl> + bool SetDims ( const int64_t d0 ) { <nl> auto old_size = size_ ; <nl> dims_ . resize ( 1 ) ; <nl> dims_ [ 0 ] = d0 ; <nl> template < typename T > class GLTensor { <nl> return size_ > old_size ; <nl> } <nl> <nl> - bool SetDims ( const TIndex d0 , const TIndex d1 ) { <nl> + bool SetDims ( const int64_t d0 , const int64_t d1 ) { <nl> auto old_size = size_ ; <nl> dims_ . resize ( 2 ) ; <nl> dims_ [ 0 ] = d0 ; <nl> template < typename T > class GLTensor { <nl> return size_ > old_size ; <nl> } <nl> <nl> - bool SetDims ( const TIndex d0 , const TIndex d1 , const TIndex d2 ) { <nl> + bool SetDims ( const int64_t d0 , const int64_t d1 , const int64_t d2 ) { <nl> auto old_size = size_ ; <nl> dims_ . resize ( 3 ) ; <nl> dims_ [ 0 ] = d0 ; <nl> template < typename T > class GLTensor { <nl> return size_ > old_size ; <nl> } <nl> <nl> - bool SetDims ( const TIndex d0 , const TIndex d1 , const TIndex d2 , <nl> - const TIndex d3 ) { <nl> + bool SetDims ( const int64_t d0 , const int64_t d1 , const int64_t d2 , <nl> + const int64_t d3 ) { <nl> auto old_size = size_ ; <nl> dims_ . resize ( 4 ) ; <nl> dims_ [ 0 ] = d0 ; <nl> template < typename T > class GLTensor { <nl> return size_ > old_size ; <nl> } <nl> <nl> - vector < TIndex > dims_ ; <nl> - TIndex size_ = - 1 ; <nl> + vector < int64_t > dims_ ; <nl> + int64_t size_ = - 1 ; <nl> arm_compute : : TensorShape shape_ ; <nl> unique_ptr < arm_compute : : GCTensor > tensor_ ; <nl> } ; <nl> mmm a / caffe2 / mobile / contrib / arm - compute / operators / fully_connected_op . cc <nl> ppp b / caffe2 / mobile / contrib / arm - compute / operators / fully_connected_op . cc <nl> bool GLFullyConnectedOp < T > : : RunOnDevice ( ) { <nl> CAFFE_ENFORCE_EQ ( 1 , B_ - > ndim ( ) ) ; <nl> CAFFE_ENFORCE_EQ ( N , B_ - > dim32 ( 0 ) ) ; <nl> <nl> - vector < TIndex > output_dims = { M , N } ; <nl> + vector < int64_t > output_dims = { M , N } ; <nl> GLTensor < T > * Y = <nl> OperatorBase : : Outputs ( ) [ 0 ] - > template GetMutable < GLTensor < T > > ( ) ; <nl> if ( first_run_ ) { <nl> mmm a / caffe2 / mobile / contrib / arm - compute / operators / pool_op . cc <nl> ppp b / caffe2 / mobile / contrib / arm - compute / operators / pool_op . cc <nl> bool GLAveragePoolOp < DataType > : : RunOnDeviceWithOrderNCHW ( ) { <nl> int height = X_ - > dim32 ( 2 ) ; <nl> int width = X_ - > dim32 ( 3 ) ; <nl> <nl> - vector < TIndex > output_dims = { N , channels , 1 , 1 } ; <nl> + vector < int64_t > output_dims = { N , channels , 1 , 1 } ; <nl> if ( ! global_pooling_ ) { <nl> output_dims [ 2 ] = ( height + pad_t ( ) + pad_b ( ) - kernel_h ( ) ) / stride_h ( ) + 1 ; <nl> output_dims [ 3 ] = ( width + pad_l ( ) + pad_r ( ) - kernel_w ( ) ) / stride_w ( ) + 1 ; <nl> template < > bool GLMaxPoolOp < DataType > : : RunOnDeviceWithOrderNCHW ( ) { <nl> int height = X_ - > dim32 ( 2 ) ; <nl> int width = X_ - > dim32 ( 3 ) ; <nl> <nl> - vector < TIndex > output_dims = { N , channels , 1 , 1 } ; <nl> + vector < int64_t > output_dims = { N , channels , 1 , 1 } ; <nl> if ( ! global_pooling_ ) { <nl> output_dims [ 2 ] = ( height + pad_t ( ) + pad_b ( ) - kernel_h ( ) ) / stride_h ( ) + 1 ; <nl> output_dims [ 3 ] = ( width + pad_l ( ) + pad_r ( ) - kernel_w ( ) ) / stride_w ( ) + 1 ; <nl> mmm a / caffe2 / mobile / contrib / arm - compute / operators / resize_op . cc <nl> ppp b / caffe2 / mobile / contrib / arm - compute / operators / resize_op . cc <nl> bool GLResizeNearestOp < T > : : RunOnDevice ( ) { <nl> <nl> GLTensor < T > * Y = <nl> OperatorBase : : Outputs ( ) [ 0 ] - > template GetMutable < GLTensor < T > > ( ) ; <nl> - vector < TIndex > output_dims = { N , C , H * height_scale_ , W * width_scale_ } ; <nl> + vector < int64_t > output_dims = { N , C , H * height_scale_ , W * width_scale_ } ; <nl> <nl> if ( first_run_ ) { <nl> Y - > Resize ( output_dims ) ; <nl> mmm a / caffe2 / mobile / contrib / ios / mpscnn / mpscnn . mm <nl> ppp b / caffe2 / mobile / contrib / ios / mpscnn / mpscnn . mm <nl> bool RunOnDevice ( ) override { <nl> for ( auto i = 0 ; i < Inputs ( ) . size ( ) ; + + i ) { <nl> const auto & X = Input ( i ) ; <nl> CAFFE_ENFORCE ( X . ndim ( ) > 0 & & X . ndim ( ) < = 4 ) ; <nl> - std : : vector < TIndex > XDims = { 1 , 1 , 1 , 1 } ; <nl> + std : : vector < int64_t > XDims = { 1 , 1 , 1 , 1 } ; <nl> XDims . assign ( X . dims ( ) . begin ( ) , X . dims ( ) . end ( ) ) ; <nl> <nl> caffe2 : : Timer t ; <nl> bool RunOnDevice ( ) override { <nl> <nl> / / bbox_deltas : ( num_images , A * 4 , H , W ) <nl> CAFFE_ENFORCE_EQ ( <nl> - bbox_deltas . dims ( ) , ( vector < TIndex > { num_images , 4 * A , height , width } ) ) ; <nl> + bbox_deltas . dims ( ) , ( vector < int64_t > { num_images , 4 * A , height , width } ) ) ; <nl> <nl> / / im_info_tensor : ( num_images , 3 ) , format [ height , width , scale ; . . . ] <nl> - CAFFE_ENFORCE_EQ ( im_info_tensor . dims ( ) , ( vector < TIndex > { num_images , 3 } ) ) ; <nl> + CAFFE_ENFORCE_EQ ( im_info_tensor . dims ( ) , ( vector < int64_t > { num_images , 3 } ) ) ; <nl> CAFFE_ENFORCE ( <nl> im_info_tensor . template IsType < float > ( ) , im_info_tensor . meta ( ) . name ( ) ) ; <nl> <nl> / / anchors : ( A , 4 ) <nl> - CAFFE_ENFORCE_EQ ( anchors . dims ( ) , ( vector < TIndex > { A , 4 } ) ) ; <nl> + CAFFE_ENFORCE_EQ ( anchors . dims ( ) , ( vector < int64_t > { A , 4 } ) ) ; <nl> CAFFE_ENFORCE ( anchors . template IsType < float > ( ) , anchors . meta ( ) . name ( ) ) ; <nl> / / Broadcast the anchors to all pixels <nl> auto all_anchors_vec = <nl> mmm a / caffe2 / mobile / contrib / ios / mpscnn / mpscnn_test . mm <nl> ppp b / caffe2 / mobile / contrib / ios / mpscnn / mpscnn_test . mm <nl> void testMPSCNN ( ) { <nl> CAFFE_ENFORCE_EQ ( t1 . ndim ( ) , 2 ) ; <nl> CAFFE_ENFORCE ( t2 . dim32 ( 2 ) = = 1 & & t2 . dim32 ( 3 ) = = 1 ) ; <nl> const_cast < TensorCPU & > ( t2 ) . Reshape ( <nl> - std : : vector < TIndex > { TIndex ( batchSize ) , TIndex ( COut ) } ) ; <nl> + std : : vector < int64_t > { int64_t ( batchSize ) , int64_t ( COut ) } ) ; <nl> / / Note dims do not match , as Metal leaves a 1x1 spatial <nl> / / dimension . <nl> CAFFE_ENFORCE_EQ ( t1 . dims ( ) , t2 . dims ( ) ) ; <nl> mmm a / caffe2 / mobile / contrib / ios / pool_test . cc <nl> ppp b / caffe2 / mobile / contrib / ios / pool_test . cc <nl> namespace caffe2 { <nl> <nl> namespace { <nl> <nl> - void AddNoiseInput ( const vector < TIndex > & shape , const string & name , Workspace * ws ) { <nl> + void AddNoiseInput ( const vector < int64_t > & shape , const string & name , Workspace * ws ) { <nl> DeviceOption option ; <nl> CPUContext context ( option ) ; <nl> Blob * blob = ws - > CreateBlob ( name ) ; <nl> void compareMaxPooling ( int N , <nl> def1 . add_arg ( ) - > CopyFrom ( MakeArgument ( " pad_b " , padB ) ) ; <nl> def1 . add_arg ( ) - > CopyFrom ( MakeArgument ( " pad_r " , padR ) ) ; <nl> <nl> - AddNoiseInput ( vector < TIndex > { N , C , H , W } , " X " , & ws ) ; <nl> + AddNoiseInput ( vector < int64_t > { N , C , H , W } , " X " , & ws ) ; <nl> <nl> unique_ptr < OperatorBase > op1 ( CreateOperator ( def1 , & ws ) ) ; <nl> EXPECT_NE ( nullptr , op1 . get ( ) ) ; <nl> mmm a / caffe2 / mobile / contrib / ios / resize_test . cc <nl> ppp b / caffe2 / mobile / contrib / ios / resize_test . cc <nl> namespace caffe2 { <nl> <nl> namespace { <nl> <nl> - void AddNoiseInput ( const vector < TIndex > & shape , const string & name , Workspace * ws ) { <nl> + void AddNoiseInput ( const vector < int64_t > & shape , const string & name , Workspace * ws ) { <nl> DeviceOption option ; <nl> CPUContext context ( option ) ; <nl> Blob * blob = ws - > CreateBlob ( name ) ; <nl> void compareResizeNeareast ( int N , <nl> def1 . add_arg ( ) - > CopyFrom ( MakeArgument ( " width_scale " , wscale ) ) ; <nl> def1 . add_arg ( ) - > CopyFrom ( MakeArgument ( " height_scale " , hscale ) ) ; <nl> <nl> - AddNoiseInput ( vector < TIndex > { N , C , H , W } , " X " , & ws ) ; <nl> + AddNoiseInput ( vector < int64_t > { N , C , H , W } , " X " , & ws ) ; <nl> <nl> unique_ptr < OperatorBase > op1 ( CreateOperator ( def1 , & ws ) ) ; <nl> EXPECT_NE ( nullptr , op1 . get ( ) ) ; <nl> mmm a / caffe2 / mobile / contrib / opengl / test / TestGLConvolution . cc <nl> ppp b / caffe2 / mobile / contrib / opengl / test / TestGLConvolution . cc <nl> <nl> <nl> # include < vector > <nl> <nl> - void AddNoiseInput ( const std : : vector < caffe2 : : TIndex > & shape , <nl> + void AddNoiseInput ( const std : : vector < int64_t > & shape , <nl> const std : : string & name , <nl> caffe2 : : Workspace * ws ) { <nl> caffe2 : : CPUContext context ; <nl> double BenchOp ( const std : : string & typ , <nl> def1 . add_arg ( ) - > CopyFrom ( caffe2 : : MakeArgument ( " pad_r " , 0 ) ) ; <nl> def1 . add_arg ( ) - > CopyFrom ( caffe2 : : MakeArgument ( " convolution_transform_strategy " , std : : string ( " PRECOMPUTE " ) ) ) ; <nl> <nl> - AddNoiseInput ( std : : vector < caffe2 : : TIndex > { 1 , inputC , inH , inW } , " X " , ws ) ; <nl> + AddNoiseInput ( std : : vector < int64_t > { 1 , inputC , inH , inW } , " X " , ws ) ; <nl> if ( transposed ) { <nl> - AddNoiseInput ( std : : vector < caffe2 : : TIndex > { inputC , outputC , kH , kW } , " W " , ws ) ; <nl> + AddNoiseInput ( std : : vector < int64_t > { inputC , outputC , kH , kW } , " W " , ws ) ; <nl> } else { <nl> - AddNoiseInput ( std : : vector < caffe2 : : TIndex > { outputC , inputC , kH , kW } , " W " , ws ) ; <nl> + AddNoiseInput ( std : : vector < int64_t > { outputC , inputC , kH , kW } , " W " , ws ) ; <nl> } <nl> - AddNoiseInput ( std : : vector < caffe2 : : TIndex > { outputC } , " B " , ws ) ; <nl> + AddNoiseInput ( std : : vector < int64_t > { outputC } , " B " , ws ) ; <nl> <nl> std : : unique_ptr < caffe2 : : OperatorBase > op1 ( CreateOperator ( def1 , ws ) ) ; <nl> <nl> static double BenchGLConvolution ( int input_channels , <nl> } <nl> <nl> AddNoiseInput ( <nl> - std : : vector < caffe2 : : TIndex > { 1 , input_channels , input_height , input_width } , " X_cpu " , ws ) ; <nl> + std : : vector < int64_t > { 1 , input_channels , input_height , input_width } , " X_cpu " , ws ) ; <nl> if ( transposed ) { <nl> AddNoiseInput ( <nl> - std : : vector < caffe2 : : TIndex > { input_channels , output_channels , kernel_height , kernel_width } , <nl> + std : : vector < int64_t > { input_channels , output_channels , kernel_height , kernel_width } , <nl> " W " , <nl> ws ) ; <nl> } else { <nl> AddNoiseInput ( <nl> - std : : vector < caffe2 : : TIndex > { output_channels , input_channels , kernel_height , kernel_width } , <nl> + std : : vector < int64_t > { output_channels , input_channels , kernel_height , kernel_width } , <nl> " W " , <nl> ws ) ; <nl> } <nl> - AddNoiseInput ( std : : vector < caffe2 : : TIndex > { output_channels } , " b " , ws ) ; <nl> + AddNoiseInput ( std : : vector < int64_t > { output_channels } , " b " , ws ) ; <nl> <nl> caffe2 : : NetDef netdef ; <nl> { <nl> mmm a / caffe2 / mobile / contrib / snpe / snpe_op_benchmark . cc <nl> ppp b / caffe2 / mobile / contrib / snpe / snpe_op_benchmark . cc <nl> <nl> <nl> namespace caffe2 { <nl> <nl> - void AddConstInput ( const vector < TIndex > & shape , <nl> + void AddConstInput ( const vector < int64_t > & shape , <nl> const float value , <nl> const string & name , <nl> Workspace * ws ) { <nl> void AddConstInput ( const vector < TIndex > & shape , <nl> & context ) ; <nl> } <nl> <nl> - void AddNoiseInput ( const vector < TIndex > & shape , <nl> + void AddNoiseInput ( const vector < int64_t > & shape , <nl> const string & name , <nl> Workspace * ws ) { <nl> DeviceOption option ; <nl> float snpe_run ( int iters , Workspace & ws ) { <nl> const int W = 227 ; <nl> const int C = 3 ; <nl> <nl> - POPULATE_DATA ( " X_snpe " , ( caffe2 : : vector < caffe2 : : TIndex > { H , W , C } ) , hwc ) ; <nl> + POPULATE_DATA ( " X_snpe " , ( caffe2 : : vector < int64_t > { H , W , C } ) , hwc ) ; <nl> <nl> OperatorDef def ; <nl> def . set_name ( " snpe_test " ) ; <nl> float caffe2_run ( int iters , Workspace & ws ) { <nl> ReadProtoFromBinaryFile ( " / data / local / tmp / squeeze_init_net . pb " , & init_net ) ; <nl> ReadProtoFromBinaryFile ( " / data / local / tmp / squeeze_predict_net . pb " , & predict_net ) ; <nl> ws . RunNetOnce ( init_net ) ; <nl> - POPULATE_DATA ( " data " , ( caffe2 : : vector < caffe2 : : TIndex > { N , C , H , W } ) , chw ) ; <nl> + POPULATE_DATA ( " data " , ( caffe2 : : vector < int64_t > { N , C , H , W } ) , chw ) ; <nl> predict_net . set_name ( " SqueezeNet " ) ; <nl> ws . CreateNet ( predict_net ) ; <nl> <nl> mmm a / caffe2 / mobile / contrib / ulp2 / ulp_neon . cc <nl> ppp b / caffe2 / mobile / contrib / ulp2 / ulp_neon . cc <nl> void run2b1bConvIm2ColGEMM ( QConvState * state , <nl> CAFFE_ENFORCE_EQ ( Y - > dim32 ( 0 ) , divRoundUp ( X . dim32 ( 0 ) * OH * OW , kGEMMTileSize ) * kGEMMTileSize ) ; <nl> CAFFE_ENFORCE_EQ ( Y - > dim32 ( 1 ) , OC ) ; <nl> Y - > ShrinkTo ( X . dim32 ( 0 ) * OH * OW ) ; <nl> - Y - > Reshape ( std : : vector < TIndex > { { TIndex ( X . dim ( 0 ) ) , TIndex ( OH ) , TIndex ( OW ) , TIndex ( OC ) } } ) ; <nl> + Y - > Reshape ( std : : vector < int64_t > { { int64_t ( X . dim ( 0 ) ) , int64_t ( OH ) , int64_t ( OW ) , int64_t ( OC ) } } ) ; <nl> } <nl> } <nl> <nl> mmm a / caffe2 / mobile / contrib / ulp2 / ulp_test . cc <nl> ppp b / caffe2 / mobile / contrib / ulp2 / ulp_test . cc <nl> int randInt ( int a , int b ) { <nl> return std : : uniform_int_distribution < int > ( a , b ) ( gen ) ; <nl> } <nl> <nl> - TensorCPU genTensor11 ( std : : vector < TIndex > shape ) { <nl> + TensorCPU genTensor11 ( std : : vector < int64_t > shape ) { <nl> Tensor r ( CPU ) ; <nl> r . Resize ( shape ) ; <nl> <nl> TensorCPU genTensor11 ( std : : vector < TIndex > shape ) { <nl> return r ; <nl> } <nl> <nl> - TensorCPU genTensorUniform11 ( std : : vector < TIndex > shape ) { <nl> + TensorCPU genTensorUniform11 ( std : : vector < int64_t > shape ) { <nl> Tensor r ( CPU ) ; <nl> r . Resize ( shape ) ; <nl> <nl> TensorCPU genTensorUniform11 ( std : : vector < TIndex > shape ) { <nl> return r ; <nl> } <nl> <nl> - TensorCPU genTensor0123 ( std : : vector < TIndex > shape ) { <nl> + TensorCPU genTensor0123 ( std : : vector < int64_t > shape ) { <nl> Tensor r ( CPU ) ; <nl> r . Resize ( shape ) ; <nl> <nl> inline void qgemmNT ( int M , int N , int K , const uint8_t * A , const uint8_t * B , flo <nl> } <nl> } <nl> <nl> - void gemmTest ( TIndex M , TIndex N , TIndex K ) { <nl> + void gemmTest ( int64_t M , int64_t N , int64_t K ) { <nl> auto X = genTensor11 ( { M , K } ) ; <nl> auto W = genTensor11 ( { N , K } ) ; <nl> Tensor XQ ( CPU ) , WQ ( CPU ) , YQ ( CPU ) , Y ( CPU ) ; <nl> mmm a / caffe2 / mpi / mpi_ops . h <nl> ppp b / caffe2 / mpi / mpi_ops . h <nl> class MPIAllgatherOp final : public Operator < Context > { <nl> MPI_Comm comm = OperatorBase : : Input < MPICommonWorldWrapper > ( 0 ) . comm ( ) ; <nl> auto & input = Input ( 1 ) ; <nl> auto * output = Output ( 0 ) ; <nl> - vector < TIndex > output_dims = input . dims ( ) ; <nl> + vector < int64_t > output_dims = input . dims ( ) ; <nl> output_dims [ 0 ] * = OperatorBase : : Input < MPICommonWorldWrapper > ( 0 ) . size ( ) ; <nl> output - > Resize ( output_dims ) ; <nl> MPI_CHECK ( MPI_Allgather ( <nl> mmm a / caffe2 / operators / accuracy_op . cc <nl> ppp b / caffe2 / operators / accuracy_op . cc <nl> bool AccuracyOp < float , CPUContext > : : RunOnDevice ( ) { <nl> int D = X . dim32 ( 1 ) ; <nl> CAFFE_ENFORCE_EQ ( label . ndim ( ) , 1 ) ; <nl> CAFFE_ENFORCE_EQ ( label . dim32 ( 0 ) , N ) ; <nl> - Y - > Resize ( vector < TIndex > ( ) ) ; <nl> + Y - > Resize ( vector < int64_t > ( ) ) ; <nl> const auto * Xdata = X . data < float > ( ) ; <nl> const auto * labelData = label . data < int > ( ) ; <nl> const int top_k = top_k_ ; <nl> mmm a / caffe2 / operators / accuracy_op . cu <nl> ppp b / caffe2 / operators / accuracy_op . cu <nl> bool AccuracyOp < float , CUDAContext > : : RunOnDevice ( ) { <nl> int D = X . dim32 ( 1 ) ; <nl> CAFFE_ENFORCE_EQ ( label . ndim ( ) , 1 ) ; <nl> CAFFE_ENFORCE_EQ ( label . dim32 ( 0 ) , N ) ; <nl> - Y - > Resize ( vector < TIndex > ( ) ) ; <nl> + Y - > Resize ( vector < int64_t > ( ) ) ; <nl> float * Ydata = Y - > template mutable_data < float > ( ) ; <nl> math : : Set < float , CUDAContext > ( 1 , 0 , Ydata , & context_ ) ; <nl> AccuracyKernel < < < <nl> mmm a / caffe2 / operators / arg_ops . cc <nl> ppp b / caffe2 / operators / arg_ops . cc <nl> void ComputeArgImpl ( <nl> const int n , <nl> const Compare & comp , <nl> const T * X , <nl> - TIndex * Y , <nl> + int64_t * Y , <nl> Context * context ) { <nl> - math : : Set < TIndex , Context > ( prev_size * next_size , TIndex ( 0 ) , Y , context ) ; <nl> + math : : Set < int64_t , Context > ( prev_size * next_size , int64_t ( 0 ) , Y , context ) ; <nl> for ( int i = 0 ; i < prev_size ; + + i ) { <nl> const T * cur_X = X + i * n * next_size + next_size ; <nl> for ( int k = 1 ; k < n ; + + k ) { <nl> for ( int j = 0 ; j < next_size ; + + j ) { <nl> - TIndex * cur_Y = Y + i * next_size + j ; <nl> + int64_t * cur_Y = Y + i * next_size + j ; <nl> if ( comp ( * cur_X , X [ i * n * next_size + * cur_Y * next_size + j ] ) ) { <nl> * cur_Y = k ; <nl> } <nl> bool ArgMaxReducer < CPUContext > : : operator ( ) ( <nl> const int next_size , <nl> const int n , <nl> const T * X , <nl> - TIndex * Y , <nl> + int64_t * Y , <nl> CPUContext * context ) const { <nl> ComputeArgImpl ( prev_size , next_size , n , std : : greater < T > ( ) , X , Y , context ) ; <nl> return true ; <nl> bool ArgMinReducer < CPUContext > : : operator ( ) ( <nl> const int next_size , <nl> const int n , <nl> const T * X , <nl> - TIndex * Y , <nl> + int64_t * Y , <nl> CPUContext * context ) const { <nl> ComputeArgImpl ( prev_size , next_size , n , std : : less < T > ( ) , X , Y , context ) ; <nl> return true ; <nl> mmm a / caffe2 / operators / arg_ops . cu <nl> ppp b / caffe2 / operators / arg_ops . cu <nl> __global__ void ComputeArgCUDAKernel ( <nl> const Reducer reducer , <nl> const T init , <nl> const T * X , <nl> - TIndex * Y ) { <nl> + int64_t * Y ) { <nl> __shared__ typename BlockReduce < int , T > : : TempStorage temp_storage ; <nl> const int d = stride . d ( ) ; <nl> for ( int idx = blockIdx . x ; idx < outer_size ; idx + = gridDim . x ) { <nl> __global__ void ComputeArgCUDAKernel ( <nl> } <nl> kv = BlockReduce < int , T > ( temp_storage ) . Reduce ( kv , reducer ) ; <nl> if ( threadIdx . x = = 0 ) { <nl> - Y [ idx ] = static_cast < TIndex > ( kv . key ) ; <nl> + Y [ idx ] = static_cast < int64_t > ( kv . key ) ; <nl> } <nl> __syncthreads ( ) ; <nl> } <nl> bool ArgMaxReducer < CUDAContext > : : operator ( ) ( <nl> const int next_size , <nl> const int n , <nl> const T * X , <nl> - TIndex * Y , <nl> + int64_t * Y , <nl> CUDAContext * context ) const { <nl> const int outer_size = prev_size * next_size ; <nl> const FixedDivisor < int > stride ( next_size ) ; <nl> bool ArgMinReducer < CUDAContext > : : operator ( ) ( <nl> const int next_size , <nl> const int n , <nl> const T * X , <nl> - TIndex * Y , <nl> + int64_t * Y , <nl> CUDAContext * context ) const { <nl> const int outer_size = prev_size * next_size ; <nl> const FixedDivisor < int > stride ( next_size ) ; <nl> mmm a / caffe2 / operators / arg_ops . h <nl> ppp b / caffe2 / operators / arg_ops . h <nl> class ArgOp final : public Operator < Context > { <nl> next_size , <nl> n , <nl> X . template data < T > ( ) , <nl> - Y - > template mutable_data < TIndex > ( ) , <nl> + Y - > template mutable_data < int64_t > ( ) , <nl> & context_ ) ; <nl> } <nl> <nl> struct ArgMaxReducer { <nl> const int next_size , <nl> const int n , <nl> const T * X , <nl> - TIndex * Y , <nl> + int64_t * Y , <nl> Context * context ) const ; <nl> } ; <nl> <nl> struct ArgMinReducer { <nl> const int next_size , <nl> const int n , <nl> const T * X , <nl> - TIndex * Y , <nl> + int64_t * Y , <nl> Context * context ) const ; <nl> } ; <nl> <nl> mmm a / caffe2 / operators / assert_op . h <nl> ppp b / caffe2 / operators / assert_op . h <nl> class AssertOp final : public Operator < Context > { <nl> cmp_tensor_ . CopyFrom ( Input ( 0 ) ) ; <nl> auto * cmp_data = cmp_tensor_ . template data < T > ( ) ; <nl> <nl> - for ( TIndex i = 0 ; i < cmp_tensor_ . size ( ) ; + + i ) { <nl> + for ( int64_t i = 0 ; i < cmp_tensor_ . size ( ) ; + + i ) { <nl> CAFFE_ENFORCE ( ( bool ) cmp_data [ i ] , [ & ] ( ) { <nl> std : : stringstream ss ; <nl> ss < < " Assert failed for element " < < i <nl> mmm a / caffe2 / operators / atomic_ops . cc <nl> ppp b / caffe2 / operators / atomic_ops . cc <nl> class AtomicFetchAddOp final : public Operator < CPUContext > { <nl> auto & b = Input ( 2 ) ; <nl> auto * c = Output ( 0 ) ; <nl> auto * d = Output ( 1 ) ; <nl> - c - > Resize ( std : : vector < TIndex > ( ) ) ; <nl> - d - > Resize ( std : : vector < TIndex > ( ) ) ; <nl> + c - > Resize ( std : : vector < int64_t > ( ) ) ; <nl> + d - > Resize ( std : : vector < int64_t > ( ) ) ; <nl> auto * aPtr = a . data < int32_t > ( ) ; <nl> auto * bPtr = b . data < int32_t > ( ) ; <nl> auto * cPtr = c - > template mutable_data < int32_t > ( ) ; <nl> mmm a / caffe2 / operators / batch_box_cox_op . cc <nl> ppp b / caffe2 / operators / batch_box_cox_op . cc <nl> bool BatchBoxCoxOp < CPUContext > : : DoRunWithType ( ) { <nl> zeros_ . clear ( ) ; <nl> nonzeros_ . reserve ( D ) ; <nl> zeros_ . reserve ( D ) ; <nl> - for ( TIndex j = 0 ; j < D ; j + + ) { <nl> + for ( int64_t j = 0 ; j < D ; j + + ) { <nl> if ( lambda1_ptr [ j ] = = 0 ) { <nl> zeros_ . push_back ( j ) ; <nl> } else { <nl> bool BatchBoxCoxOp < CPUContext > : : DoRunWithType ( ) { <nl> / / rows by replicating the input parameters K times . Then finish row - by - row . <nl> TypedCachedBuffers < T > & b = GetBuffers < T > ( ) ; <nl> if ( nonzeros_ . size ( ) = = D ) { <nl> - TIndex i = 0 ; <nl> + int64_t i = 0 ; <nl> if ( K > 1 ) { <nl> TileArrayIntoVector ( lambda1_ptr , D , K , & b . lambda1_ ) ; <nl> TileArrayIntoVector ( lambda2_ptr , D , K , & b . lambda2_ ) ; <nl> bool BatchBoxCoxOp < CPUContext > : : DoRunWithType ( ) { <nl> D , data_ptr , lambda1_ptr , lambda2_ptr , k_eps , output_ptr ) ; <nl> } <nl> } else if ( zeros_ . size ( ) = = D ) { <nl> - TIndex i = 0 ; <nl> + int64_t i = 0 ; <nl> if ( K > 1 ) { <nl> TileArrayIntoVector ( lambda2_ptr , D , K , & b . lambda2_z_ ) ; <nl> DCHECK_EQ ( K * D , b . lambda2_z_ . size ( ) ) ; <nl> bool BatchBoxCoxOp < CPUContext > : : DoRunWithType ( ) { <nl> PackV ( nonzeros_ . size ( ) , lambda2_ptr , nonzeros_ . data ( ) , b . lambda2_ . data ( ) ) ; <nl> PackV ( zeros_ . size ( ) , lambda2_ptr , zeros_ . data ( ) , b . lambda2_z_ . data ( ) ) ; <nl> <nl> - TIndex i = 0 ; <nl> + int64_t i = 0 ; <nl> b . accumulator_ . resize ( std : : max ( nonzeros_ . size ( ) , zeros_ . size ( ) ) ) ; <nl> if ( K > 1 ) { <nl> / / Truncate to original size , and re - tile with offsets this time . <nl> bool BatchBoxCoxOp < CPUContext > : : DoRunWithType ( ) { <nl> template < > <nl> template < typename T > <nl> void BatchBoxCoxOp < CPUContext > : : BoxCoxNaive ( <nl> - TIndex N , <nl> - TIndex D , <nl> + int64_t N , <nl> + int64_t D , <nl> const T * data_ptr , <nl> const T * lambda1_ptr , <nl> const T * lambda2_ptr , <nl> T k_eps , <nl> T * output_ptr ) { <nl> - for ( TIndex i = 0 ; i < N ; i + + ) { <nl> - for ( TIndex j = 0 ; j < D ; j + + , data_ptr + + , output_ptr + + ) { <nl> + for ( int64_t i = 0 ; i < N ; i + + ) { <nl> + for ( int64_t j = 0 ; j < D ; j + + , data_ptr + + , output_ptr + + ) { <nl> T lambda1_v = lambda1_ptr [ j ] ; <nl> T lambda2_v = lambda2_ptr [ j ] ; <nl> T tmp = std : : max ( * data_ptr + lambda2_v , k_eps ) ; <nl> void BatchBoxCoxOp < CPUContext > : : BoxCoxNaive ( <nl> template < > <nl> template < typename T > <nl> void BatchBoxCoxOp < CPUContext > : : BoxCoxNonzeroLambda ( <nl> - TIndex D , <nl> + int64_t D , <nl> const T * data_ptr , <nl> const T * lambda1 , <nl> const T * lambda2 , <nl> T k_eps , <nl> T * out ) { <nl> caffe2 : : math : : Add ( D , data_ptr , lambda2 , out , & context_ ) ; <nl> - for ( TIndex j = 0 ; j < D ; j + + ) { <nl> + for ( int64_t j = 0 ; j < D ; j + + ) { <nl> out [ j ] = std : : max ( out [ j ] , k_eps ) ; <nl> } <nl> Pow ( D , out , lambda1 , out ) ; <nl> - for ( TIndex j = 0 ; j < D ; j + + ) { <nl> + for ( int64_t j = 0 ; j < D ; j + + ) { <nl> out [ j ] - = 1 . 0 ; <nl> } <nl> caffe2 : : math : : Div ( D , out , lambda1 , out , & context_ ) ; <nl> void BatchBoxCoxOp < CPUContext > : : BoxCoxNonzeroLambda ( <nl> template < > <nl> template < typename T > <nl> void BatchBoxCoxOp < CPUContext > : : BoxCoxZeroLambda ( <nl> - TIndex D , <nl> + int64_t D , <nl> const T * data_ptr , <nl> const T * lambda2 , <nl> T k_eps , <nl> T * output_ptr ) { <nl> caffe2 : : math : : Add ( D , data_ptr , lambda2 , output_ptr , & context_ ) ; <nl> - for ( TIndex j = 0 ; j < D ; j + + ) { <nl> + for ( int64_t j = 0 ; j < D ; j + + ) { <nl> output_ptr [ j ] = std : : max ( output_ptr [ j ] , k_eps ) ; <nl> } <nl> caffe2 : : math : : Log ( D , output_ptr , output_ptr , & context_ ) ; <nl> mmm a / caffe2 / operators / batch_box_cox_op . h <nl> ppp b / caffe2 / operators / batch_box_cox_op . h <nl> class BatchBoxCoxOp final : public Operator < Context > { <nl> protected : <nl> template < typename T > <nl> void BoxCoxNaive ( <nl> - TIndex N , <nl> - TIndex D , <nl> + int64_t N , <nl> + int64_t D , <nl> const T * data_ptr , <nl> const T * lambda1_ptr , <nl> const T * lambda2_ptr , <nl> class BatchBoxCoxOp final : public Operator < Context > { <nl> # ifdef CAFFE2_USE_MKL <nl> template < typename T > <nl> void BoxCoxNonzeroLambda ( <nl> - TIndex D , <nl> + int64_t D , <nl> const T * data_ptr , <nl> const T * lambda1 , <nl> const T * lambda2 , <nl> class BatchBoxCoxOp final : public Operator < Context > { <nl> <nl> template < typename T > <nl> void BoxCoxZeroLambda ( <nl> - TIndex D , <nl> + int64_t D , <nl> const T * data_ptr , <nl> const T * lambda2 , <nl> T k_eps , <nl> mmm a / caffe2 / operators / batch_bucketize_op . cc <nl> ppp b / caffe2 / operators / batch_bucketize_op . cc <nl> bool BatchBucketizeOp < CPUContext > : : RunOnDevice ( ) { <nl> auto feature_dim = feature . dim ( 1 ) ; <nl> auto output_dim = indices . size ( ) ; <nl> <nl> - TIndex length_sum = 0 ; <nl> - for ( TIndex i = 0 ; i < lengths . size ( ) ; i + + ) { <nl> + int64_t length_sum = 0 ; <nl> + for ( int64_t i = 0 ; i < lengths . size ( ) ; i + + ) { <nl> CAFFE_ENFORCE_GE ( feature_dim , indices_data [ i ] ) ; <nl> length_sum + = lengths_data [ i ] ; <nl> } <nl> CAFFE_ENFORCE_EQ ( length_sum , boundaries . size ( ) ) ; <nl> <nl> - TIndex lower_bound = 0 ; <nl> + int64_t lower_bound = 0 ; <nl> output - > Resize ( batch_size , output_dim ) ; <nl> auto * output_data = output - > template mutable_data < int32_t > ( ) ; <nl> <nl> - for ( TIndex i = 0 ; i < batch_size ; i + + ) { <nl> + for ( int64_t i = 0 ; i < batch_size ; i + + ) { <nl> lower_bound = 0 ; <nl> - for ( TIndex j = 0 ; j < output_dim ; j + + ) { <nl> - for ( TIndex k = 0 ; k < = lengths_data [ j ] ; k + + ) { <nl> + for ( int64_t j = 0 ; j < output_dim ; j + + ) { <nl> + for ( int64_t k = 0 ; k < = lengths_data [ j ] ; k + + ) { <nl> if ( k = = lengths_data [ j ] | | <nl> feature_data [ i * feature_dim + indices_data [ j ] ] < = <nl> boundaries_data [ lower_bound + k ] ) { <nl> mmm a / caffe2 / operators / batch_gather_ops . cu <nl> ppp b / caffe2 / operators / batch_gather_ops . cu <nl> bool BatchGatherOp < CUDAContext > : : DoRunWithType ( ) { <nl> auto & indices = Input ( INDICES ) ; <nl> auto * output = Output ( 0 ) ; <nl> <nl> - vector < TIndex > shape ; <nl> + vector < int64_t > shape ; <nl> shape . push_back ( data . dim ( 0 ) ) ; <nl> shape . insert ( shape . end ( ) , indices . dims ( ) . begin ( ) , indices . dims ( ) . end ( ) ) ; <nl> shape . insert ( shape . end ( ) , data . dims ( ) . begin ( ) + 2 , data . dims ( ) . end ( ) ) ; <nl> mmm a / caffe2 / operators / batch_gather_ops . h <nl> ppp b / caffe2 / operators / batch_gather_ops . h <nl> class BatchGatherOp final : public Operator < Context > { <nl> <nl> CAFFE_ENFORCE_GE ( data . ndim ( ) , 2 , " DATA should be at least 2 - D " ) ; <nl> <nl> - vector < TIndex > shape ; <nl> + vector < int64_t > shape ; <nl> shape . push_back ( data . dim ( 0 ) ) ; <nl> shape . insert ( shape . end ( ) , indices . dims ( ) . begin ( ) , indices . dims ( ) . end ( ) ) ; <nl> shape . insert ( shape . end ( ) , data . dims ( ) . begin ( ) + 2 , data . dims ( ) . end ( ) ) ; <nl> mmm a / caffe2 / operators / batch_matmul_op . cc <nl> ppp b / caffe2 / operators / batch_matmul_op . cc <nl> vector < TensorShape > TensorInferenceForBatchMatMul ( <nl> b_dim1 = in [ 1 ] . dims ( ndim - 1 ) ; <nl> } <nl> <nl> - auto output_dims = vector < TIndex > { in [ 0 ] . dims ( ) . begin ( ) , in [ 0 ] . dims ( ) . end ( ) } ; <nl> + auto output_dims = vector < int64_t > { in [ 0 ] . dims ( ) . begin ( ) , in [ 0 ] . dims ( ) . end ( ) } ; <nl> output_dims [ ndim - 2 ] = a_dim0 ; <nl> output_dims [ ndim - 1 ] = b_dim1 ; <nl> <nl> return vector < TensorShape > { <nl> - CreateTensorShape ( vector < TIndex > { output_dims } , in [ 0 ] . data_type ( ) ) } ; <nl> + CreateTensorShape ( vector < int64_t > { output_dims } , in [ 0 ] . data_type ( ) ) } ; <nl> } else { <nl> auto ndims_A = in [ 0 ] . dims_size ( ) ; <nl> auto ndims_B = in [ 1 ] . dims_size ( ) ; <nl> - std : : vector < TIndex > dims_A ( ndims_A ) , dims_B ( ndims_B ) ; <nl> + std : : vector < int64_t > dims_A ( ndims_A ) , dims_B ( ndims_B ) ; <nl> for ( int i = 0 ; i < ndims_A ; + + i ) { <nl> dims_A [ i ] = in [ 0 ] . dims ( i ) ; <nl> } <nl> vector < TensorShape > TensorInferenceForBatchMatMul ( <nl> N = dims_B [ ndims_B - 1 ] ; <nl> } <nl> <nl> - std : : vector < TIndex > new_dims ; <nl> + std : : vector < int64_t > new_dims ; <nl> if ( ndims_A > = ndims_B ) { <nl> new_dims . assign ( dims_A . begin ( ) , dims_A . end ( ) - 2 ) ; <nl> } else { <nl> vector < TensorShape > TensorInferenceForBatchMatMul ( <nl> new_dims . push_back ( 1 ) ; <nl> } <nl> return vector < TensorShape > { <nl> - CreateTensorShape ( vector < TIndex > { new_dims } , in [ 0 ] . data_type ( ) ) } ; <nl> + CreateTensorShape ( vector < int64_t > { new_dims } , in [ 0 ] . data_type ( ) ) } ; <nl> } <nl> } <nl> <nl> mmm a / caffe2 / operators / batch_matmul_op . h <nl> ppp b / caffe2 / operators / batch_matmul_op . h <nl> class BatchMatMulOp final : public Operator < Context > { <nl> / / Calculate output tensor shapes [ B . . . , ( M ) , ( N ) ] <nl> / / Batch dimensions will be broadcasted out to those of the longer tensor <nl> / / A or B . Either M or N are optional if A or B , respectively are 1 - D . <nl> - std : : vector < TIndex > new_dims ; <nl> + std : : vector < int64_t > new_dims ; <nl> if ( ndims_A > = ndims_B ) { <nl> new_dims . assign ( dims_A . begin ( ) , dims_A . end ( ) - 2 ) ; <nl> } else { <nl> mmm a / caffe2 / operators / batch_matmul_op_gpu_test . cc <nl> ppp b / caffe2 / operators / batch_matmul_op_gpu_test . cc <nl> class BatchMatMulOpGPUTest : public testing : : Test { <nl> } <nl> <nl> void AddConstInput ( <nl> - const std : : vector < TIndex > & dims , <nl> + const std : : vector < int64_t > & dims , <nl> const float value , <nl> const string & name ) { <nl> Blob * blob = ws_ . CreateBlob ( name ) ; <nl> class BatchMatMulOpGPUTest : public testing : : Test { <nl> cuda_context_ . get ( ) ) ; <nl> } <nl> <nl> - void VerifyOutput ( const std : : vector < TIndex > & dims , const float value ) const { <nl> + void VerifyOutput ( const std : : vector < int64_t > & dims , const float value ) const { <nl> const Blob * Y_blob = ws_ . GetBlob ( " Y " ) ; <nl> ASSERT_NE ( nullptr , Y_blob ) ; <nl> const auto & Y = Y_blob - > Get < Tensor > ( ) ; <nl> TEST_F ( BatchMatMulOpGPUTest , BatchMatMulOpGPUNormalTest ) { <nl> if ( ! HasCudaGPU ( ) ) { <nl> return ; <nl> } <nl> - AddConstInput ( std : : vector < TIndex > { 3 , 5 , 10 } , 1 . 0f , " A " ) ; <nl> - AddConstInput ( std : : vector < TIndex > { 3 , 10 , 6 } , 1 . 0f , " B " ) ; <nl> + AddConstInput ( std : : vector < int64_t > { 3 , 5 , 10 } , 1 . 0f , " A " ) ; <nl> + AddConstInput ( std : : vector < int64_t > { 3 , 10 , 6 } , 1 . 0f , " B " ) ; <nl> std : : unique_ptr < OperatorBase > op ( CreateOperator ( def_ , & ws_ ) ) ; <nl> ASSERT_NE ( nullptr , op ) ; <nl> ASSERT_TRUE ( op - > Run ( ) ) ; <nl> - VerifyOutput ( std : : vector < TIndex > { 3 , 5 , 6 } , 10 . 0f ) ; <nl> + VerifyOutput ( std : : vector < int64_t > { 3 , 5 , 6 } , 10 . 0f ) ; <nl> } <nl> <nl> TEST_F ( BatchMatMulOpGPUTest , BatchMatMulOpGPUBroadcastTest ) { <nl> TEST_F ( BatchMatMulOpGPUTest , BatchMatMulOpGPUBroadcastTest ) { <nl> auto * arg = def_ . add_arg ( ) ; <nl> arg - > set_name ( " broadcast " ) ; <nl> arg - > set_i ( 1 ) ; <nl> - AddConstInput ( std : : vector < TIndex > { 3 , 5 , 10 } , 1 . 0f , " A " ) ; <nl> - AddConstInput ( std : : vector < TIndex > { 2 , 3 , 10 , 6 } , 1 . 0f , " B " ) ; <nl> + AddConstInput ( std : : vector < int64_t > { 3 , 5 , 10 } , 1 . 0f , " A " ) ; <nl> + AddConstInput ( std : : vector < int64_t > { 2 , 3 , 10 , 6 } , 1 . 0f , " B " ) ; <nl> std : : unique_ptr < OperatorBase > op ( CreateOperator ( def_ , & ws_ ) ) ; <nl> ASSERT_NE ( nullptr , op ) ; <nl> ASSERT_TRUE ( op - > Run ( ) ) ; <nl> - VerifyOutput ( std : : vector < TIndex > { 2 , 3 , 5 , 6 } , 10 . 0f ) ; <nl> + VerifyOutput ( std : : vector < int64_t > { 2 , 3 , 5 , 6 } , 10 . 0f ) ; <nl> } <nl> <nl> } / / namespace <nl> mmm a / caffe2 / operators / batch_matmul_op_test . cc <nl> ppp b / caffe2 / operators / batch_matmul_op_test . cc <nl> class BatchMatMulOpTest : public testing : : Test { <nl> } <nl> <nl> void AddConstInput ( <nl> - const std : : vector < TIndex > & dims , <nl> + const std : : vector < int64_t > & dims , <nl> const float value , <nl> const string & name ) { <nl> Blob * blob = ws_ . CreateBlob ( name ) ; <nl> class BatchMatMulOpTest : public testing : : Test { <nl> cpu_context_ . get ( ) ) ; <nl> } <nl> <nl> - void VerifyOutput ( const std : : vector < TIndex > & dims , const float value ) const { <nl> + void VerifyOutput ( const std : : vector < int64_t > & dims , const float value ) const { <nl> const Blob * Y_blob = ws_ . GetBlob ( " Y " ) ; <nl> ASSERT_NE ( nullptr , Y_blob ) ; <nl> const auto & Y = Y_blob - > Get < TensorCPU > ( ) ; <nl> class BatchMatMulOpTest : public testing : : Test { <nl> } ; <nl> <nl> TEST_F ( BatchMatMulOpTest , BatchMatMulOpNormalTest ) { <nl> - AddConstInput ( std : : vector < TIndex > { 3 , 5 , 10 } , 1 . 0f , " A " ) ; <nl> - AddConstInput ( std : : vector < TIndex > { 3 , 10 , 6 } , 1 . 0f , " B " ) ; <nl> + AddConstInput ( std : : vector < int64_t > { 3 , 5 , 10 } , 1 . 0f , " A " ) ; <nl> + AddConstInput ( std : : vector < int64_t > { 3 , 10 , 6 } , 1 . 0f , " B " ) ; <nl> std : : unique_ptr < OperatorBase > op ( CreateOperator ( def_ , & ws_ ) ) ; <nl> ASSERT_NE ( nullptr , op ) ; <nl> ASSERT_TRUE ( op - > Run ( ) ) ; <nl> - VerifyOutput ( std : : vector < TIndex > { 3 , 5 , 6 } , 10 . 0f ) ; <nl> + VerifyOutput ( std : : vector < int64_t > { 3 , 5 , 6 } , 10 . 0f ) ; <nl> } <nl> <nl> TEST_F ( BatchMatMulOpTest , BatchMatMulOpBroadcastTest ) { <nl> auto * arg = def_ . add_arg ( ) ; <nl> arg - > set_name ( " broadcast " ) ; <nl> arg - > set_i ( 1 ) ; <nl> - AddConstInput ( std : : vector < TIndex > { 3 , 5 , 10 } , 1 . 0f , " A " ) ; <nl> - AddConstInput ( std : : vector < TIndex > { 2 , 3 , 10 , 6 } , 1 . 0f , " B " ) ; <nl> + AddConstInput ( std : : vector < int64_t > { 3 , 5 , 10 } , 1 . 0f , " A " ) ; <nl> + AddConstInput ( std : : vector < int64_t > { 2 , 3 , 10 , 6 } , 1 . 0f , " B " ) ; <nl> std : : unique_ptr < OperatorBase > op ( CreateOperator ( def_ , & ws_ ) ) ; <nl> ASSERT_NE ( nullptr , op ) ; <nl> ASSERT_TRUE ( op - > Run ( ) ) ; <nl> - VerifyOutput ( std : : vector < TIndex > { 2 , 3 , 5 , 6 } , 10 . 0f ) ; <nl> + VerifyOutput ( std : : vector < int64_t > { 2 , 3 , 5 , 6 } , 10 . 0f ) ; <nl> } <nl> <nl> } / / namespace <nl> mmm a / caffe2 / operators / batch_sparse_to_dense_op . cc <nl> ppp b / caffe2 / operators / batch_sparse_to_dense_op . cc <nl> bool BatchSparseToDenseOp < T , Context > : : RunOnDevice ( ) { <nl> CAFFE_ENFORCE_EQ ( lengths . ndim ( ) , 1 ) ; <nl> CAFFE_ENFORCE_EQ ( indices . ndim ( ) , 1 ) ; <nl> <nl> - const TIndex * lengths_data = lengths . template data < TIndex > ( ) ; <nl> - const TIndex * indices_data = indices . template data < TIndex > ( ) ; <nl> + const int64_t * lengths_data = lengths . template data < int64_t > ( ) ; <nl> + const int64_t * indices_data = indices . template data < int64_t > ( ) ; <nl> const T * values_data = values . template data < T > ( ) ; <nl> - TIndex batch_size = lengths . size ( ) ; <nl> - TIndex lengths_sum = 0 ; <nl> - math : : Sum < TIndex , Context > ( batch_size , lengths_data , & lengths_sum , & context_ ) ; <nl> + int64_t batch_size = lengths . size ( ) ; <nl> + int64_t lengths_sum = 0 ; <nl> + math : : Sum < int64_t , Context > ( batch_size , lengths_data , & lengths_sum , & context_ ) ; <nl> CAFFE_ENFORCE_EQ ( lengths_sum , indices . size ( ) ) ; <nl> <nl> - vector < TIndex > output_shape = { batch_size } ; <nl> + vector < int64_t > output_shape = { batch_size } ; <nl> if ( InputSize ( ) = = 4 ) { <nl> auto & shaper = Input ( 3 ) ; <nl> CAFFE_ENFORCE_EQ ( shaper . ndim ( ) , 2 ) ; <nl> bool BatchSparseToDenseOp < T , Context > : : RunOnDevice ( ) { <nl> math : : Set ( <nl> output - > size ( ) , static_cast < T > ( default_value_ ) , output_data , & context_ ) ; <nl> <nl> - TIndex k = 0 ; <nl> - for ( TIndex i = 0 ; i < batch_size ; + + i ) { <nl> - for ( TIndex j = 0 ; j < lengths_data [ i ] ; + + j ) { <nl> + int64_t k = 0 ; <nl> + for ( int64_t i = 0 ; i < batch_size ; + + i ) { <nl> + for ( int64_t j = 0 ; j < lengths_data [ i ] ; + + j ) { <nl> CAFFE_ENFORCE ( <nl> indices_data [ k ] < dense_last_dim_ , <nl> " An indice ( " , <nl> bool BatchDenseToSparseOp < T , Context > : : RunOnDevice ( ) { <nl> CAFFE_ENFORCE_EQ ( lengths . ndim ( ) , 1 ) ; <nl> CAFFE_ENFORCE_EQ ( indices . ndim ( ) , 1 ) ; <nl> CAFFE_ENFORCE_EQ ( dense . ndim ( ) , 2 ) ; <nl> - const TIndex * lengths_data = lengths . template data < TIndex > ( ) ; <nl> - const TIndex * indices_data = indices . template data < TIndex > ( ) ; <nl> + const int64_t * lengths_data = lengths . template data < int64_t > ( ) ; <nl> + const int64_t * indices_data = indices . template data < int64_t > ( ) ; <nl> const T * dense_data = dense . template data < T > ( ) ; <nl> <nl> - TIndex batch_size = lengths . size ( ) ; <nl> - TIndex lengths_sum = 0 ; <nl> - math : : Sum < TIndex , Context > ( batch_size , lengths_data , & lengths_sum , & context_ ) ; <nl> + int64_t batch_size = lengths . size ( ) ; <nl> + int64_t lengths_sum = 0 ; <nl> + math : : Sum < int64_t , Context > ( batch_size , lengths_data , & lengths_sum , & context_ ) ; <nl> CAFFE_ENFORCE_EQ ( lengths_sum , indices . size ( ) ) ; <nl> <nl> CAFFE_ENFORCE_EQ ( batch_size , dense . dim ( 0 ) ) ; <nl> dense_last_dim_ = dense . dim ( 1 ) ; <nl> - vector < TIndex > output_shape = indices . dims ( ) ; <nl> + vector < int64_t > output_shape = indices . dims ( ) ; <nl> output - > Resize ( output_shape ) ; <nl> T * output_data = output - > template mutable_data < T > ( ) ; <nl> <nl> - TIndex k = 0 ; <nl> - for ( TIndex i = 0 ; i < batch_size ; + + i ) { <nl> - for ( TIndex j = 0 ; j < lengths_data [ i ] ; + + j ) { <nl> + int64_t k = 0 ; <nl> + for ( int64_t i = 0 ; i < batch_size ; + + i ) { <nl> + for ( int64_t j = 0 ; j < lengths_data [ i ] ; + + j ) { <nl> CAFFE_ENFORCE ( <nl> indices_data [ k ] < dense . dim ( 1 ) , <nl> " An indice ( " , <nl> mmm a / caffe2 / operators / batch_sparse_to_dense_op . h <nl> ppp b / caffe2 / operators / batch_sparse_to_dense_op . h <nl> class BatchSparseToDenseOp : public Operator < Context > { <nl> USE_OPERATOR_CONTEXT_FUNCTIONS ; <nl> BatchSparseToDenseOp ( const OperatorDef & operator_def , Workspace * ws ) <nl> : Operator < Context > ( operator_def , ws ) , <nl> - OP_SINGLE_ARG ( TIndex , " dense_last_dim " , dense_last_dim_ , - 1 ) , <nl> + OP_SINGLE_ARG ( int64_t , " dense_last_dim " , dense_last_dim_ , - 1 ) , <nl> OP_SINGLE_ARG ( T , " default_value " , default_value_ , static_cast < T > ( 0 ) ) { } <nl> bool RunOnDevice ( ) override ; <nl> <nl> private : <nl> - TIndex dense_last_dim_ ; <nl> + int64_t dense_last_dim_ ; <nl> T default_value_ ; <nl> INPUT_TAGS ( LENGTHS , INDICES , VALUES ) ; <nl> } ; <nl> class BatchDenseToSparseOp : public Operator < Context > { <nl> bool RunOnDevice ( ) override ; <nl> <nl> private : <nl> - TIndex dense_last_dim_ ; <nl> + int64_t dense_last_dim_ ; <nl> INPUT_TAGS ( LENGTHS , INDICES , DENSE ) ; <nl> } ; <nl> <nl> mmm a / caffe2 / operators / bbox_transform_op . cc <nl> ppp b / caffe2 / operators / bbox_transform_op . cc <nl> bool BBoxTransformOp < float , CPUContext > : : RunOnDevice ( ) { <nl> } <nl> } <nl> <nl> - CAFFE_ENFORCE_EQ ( iminfo_in . dims ( ) , ( vector < TIndex > { batch_size , 3 } ) ) ; <nl> + CAFFE_ENFORCE_EQ ( iminfo_in . dims ( ) , ( vector < int64_t > { batch_size , 3 } ) ) ; <nl> Eigen : : Map < const ERArrXXf > iminfo ( <nl> iminfo_in . data < float > ( ) , iminfo_in . dim ( 0 ) , iminfo_in . dim ( 1 ) ) ; <nl> <nl> mmm a / caffe2 / operators / boolean_mask_ops . cc <nl> ppp b / caffe2 / operators / boolean_mask_ops . cc <nl> bool BooleanMaskOp < CPUContext > : : RunOnDevice ( ) { <nl> + + numOutputs ; <nl> } <nl> } <nl> - std : : vector < TIndex > outShape ; <nl> + std : : vector < int64_t > outShape ; <nl> outShape . push_back ( numOutputs ) ; <nl> outShape . insert ( outShape . end ( ) , data . dims ( ) . begin ( ) + 1 , data . dims ( ) . end ( ) ) ; <nl> dataOut - > Resize ( outShape ) ; <nl> bool BooleanMaskOp < CPUContext > : : RunOnDevice ( ) { <nl> const auto innerSize = data . size_from_dim ( 1 ) ; <nl> const auto innerSizeBytes = innerSize * data . meta ( ) . itemsize ( ) ; <nl> <nl> - TIndex lastStart = - 1 ; <nl> + int64_t lastStart = - 1 ; <nl> const auto * inPtr = ( char * ) data . raw_data ( ) ; <nl> - TIndex outStart = 0 ; <nl> + int64_t outStart = 0 ; <nl> <nl> - for ( TIndex i = 0 ; ; + + i ) { <nl> + for ( int64_t i = 0 ; ; + + i ) { <nl> / / mask was true and either a ) became false , or b ) sequence finished <nl> if ( lastStart ! = - 1 & & ( ( i > = outerSize ) | | ! maskPtr [ i ] ) ) { <nl> const auto * src = inPtr + lastStart * innerSizeBytes ; <nl> mmm a / caffe2 / operators / boolean_mask_ops . cu <nl> ppp b / caffe2 / operators / boolean_mask_ops . cu <nl> namespace caffe2 { <nl> <nl> namespace { <nl> __global__ void BooleanMaskCopyKernel ( <nl> - const TIndex numOfOutput , <nl> - const TIndex numBytes , <nl> - const TIndex * indices , <nl> + const int64_t numOfOutput , <nl> + const int64_t numBytes , <nl> + const int64_t * indices , <nl> const uint8_t * src , <nl> uint8_t * dest ) { <nl> - for ( TIndex i = blockIdx . x ; i < numOfOutput ; i + = gridDim . x ) { <nl> + for ( int64_t i = blockIdx . x ; i < numOfOutput ; i + = gridDim . x ) { <nl> const auto srcBase = indices [ i ] * numBytes ; <nl> const auto destBase = i * numBytes ; <nl> - for ( TIndex j = threadIdx . x ; j < numBytes ; j + = blockDim . x ) { <nl> + for ( int64_t j = threadIdx . x ; j < numBytes ; j + = blockDim . x ) { <nl> dest [ destBase + j ] = src [ srcBase + j ] ; <nl> } <nl> } <nl> class BooleanMaskOp < CUDAContext > final : public Operator < CUDAContext > { <nl> const auto * maskData = mask . data < bool > ( ) ; <nl> const auto outerSize = mask . dims ( ) [ 0 ] ; <nl> indices_ . Resize ( outerSize ) ; <nl> - auto * indicesData = indices_ . mutable_data < TIndex > ( ) ; <nl> + auto * indicesData = indices_ . mutable_data < int64_t > ( ) ; <nl> <nl> size_t numBytes = 0 ; <nl> cub : : CountingInputIterator < int > itr ( 0 ) ; <nl> class BooleanMaskOp < CUDAContext > final : public Operator < CUDAContext > { <nl> itr , <nl> maskData , <nl> indicesData , <nl> - static_cast < TIndex * > ( nullptr ) , <nl> + static_cast < int64_t * > ( nullptr ) , <nl> outerSize , <nl> context_ . cuda_stream ( ) ) ; <nl> <nl> - auto numTIndex = <nl> - static_cast < TIndex > ( ( numBytes + sizeof ( TIndex ) - 1 ) / sizeof ( TIndex ) ) ; <nl> - / / allocate one more TIndex at the end of scratch for storing numOfOutput <nl> - scratch_ . Resize ( numTIndex + 1 ) ; <nl> - auto * scratchData = scratch_ . mutable_data < TIndex > ( ) ; <nl> - auto * numOfOutputData = scratchData + numTIndex ; <nl> + auto numint64_t = <nl> + static_cast < int64_t > ( ( numBytes + sizeof ( int64_t ) - 1 ) / sizeof ( int64_t ) ) ; <nl> + / / allocate one more int64_t at the end of scratch for storing numOfOutput <nl> + scratch_ . Resize ( numint64_t + 1 ) ; <nl> + auto * scratchData = scratch_ . mutable_data < int64_t > ( ) ; <nl> + auto * numOfOutputData = scratchData + numint64_t ; <nl> <nl> cub : : DeviceSelect : : Flagged ( <nl> static_cast < void * > ( scratchData ) , <nl> class BooleanMaskOp < CUDAContext > final : public Operator < CUDAContext > { <nl> context_ . cuda_stream ( ) ) ; <nl> <nl> / / Copy numOfOutput from gpu to cpu <nl> - TIndex numOfOutput ; <nl> + int64_t numOfOutput ; <nl> context_ . CopyToCPU ( 1 , numOfOutputData , & numOfOutput ) ; <nl> <nl> indices_ . Resize ( numOfOutput ) ; <nl> - std : : vector < TIndex > dims = src . dims ( ) ; <nl> + std : : vector < int64_t > dims = src . dims ( ) ; <nl> dims [ 0 ] = numOfOutput ; <nl> dest - > Resize ( dims ) ; <nl> auto * destData = ( uint8_t * ) dest - > raw_mutable_data ( src . meta ( ) ) ; <nl> class BooleanMaskOp < CUDAContext > final : public Operator < CUDAContext > { <nl> if ( OutputSize ( ) = = 2 ) { <nl> auto * indicesOut = Output ( 1 ) ; <nl> indicesOut - > Resize ( numOfOutput ) ; <nl> - indicesOut - > template mutable_data < TIndex > ( ) ; <nl> + indicesOut - > template mutable_data < int64_t > ( ) ; <nl> } <nl> <nl> if ( numOfOutput > 0 ) { <nl> BooleanMaskCopyKernel < < < <nl> - min ( numOfOutput , static_cast < TIndex > ( CAFFE_MAXIMUM_NUM_BLOCKS ) ) , <nl> + min ( numOfOutput , static_cast < int64_t > ( CAFFE_MAXIMUM_NUM_BLOCKS ) ) , <nl> CAFFE_CUDA_NUM_THREADS , <nl> 0 , <nl> context_ . cuda_stream ( ) > > > ( <nl> mmm a / caffe2 / operators / boolean_unmask_ops_test . cc <nl> ppp b / caffe2 / operators / boolean_unmask_ops_test . cc <nl> static void AddScalarInput ( <nl> Blob * blob = ws - > CreateBlob ( name ) ; <nl> auto * tensor = blob - > GetMutableTensor ( CPU ) ; <nl> if ( ! isEmpty ) { <nl> - tensor - > Resize ( vector < TIndex > { 1 } ) ; <nl> + tensor - > Resize ( vector < int64_t > { 1 } ) ; <nl> * ( tensor - > template mutable_data < DataT > ( ) ) = value ; <nl> } else { <nl> - tensor - > Resize ( vector < TIndex > { 0 } ) ; <nl> + tensor - > Resize ( vector < int64_t > { 0 } ) ; <nl> tensor - > template mutable_data < DataT > ( ) ; <nl> } <nl> return ; <nl> mmm a / caffe2 / operators / cast_op . cc <nl> ppp b / caffe2 / operators / cast_op . cc <nl> bool CastOp < CPUContext > : : DoRunWithType ( ) { <nl> const auto * data = input . template data < SrcType > ( ) ; <nl> auto * out = output - > template mutable_data < DstType > ( ) ; <nl> auto N = input . size ( ) ; <nl> - for ( TIndex i = 0 ; i < N ; + + i ) { <nl> + for ( int64_t i = 0 ; i < N ; + + i ) { <nl> out [ i ] = static_cast < DstType > ( data [ i ] ) ; <nl> } <nl> return true ; <nl> mmm a / caffe2 / operators / cast_op . h <nl> ppp b / caffe2 / operators / cast_op . h <nl> class CastOp : public Operator < Context > { <nl> const auto * data = input . template data < SrcType > ( ) ; <nl> auto * out = output - > template mutable_data < DstType > ( ) ; <nl> auto N = input . size ( ) ; <nl> - for ( TIndex i = 0 ; i < N ; + + i ) { <nl> + for ( int64_t i = 0 ; i < N ; + + i ) { <nl> out [ i ] = static_cast < DstType > ( data [ i ] ) ; <nl> } <nl> return true ; <nl> mmm a / caffe2 / operators / concat_split_op . h <nl> ppp b / caffe2 / operators / concat_split_op . h <nl> bool SplitOp < Context > : : RunOnDevice ( ) { <nl> input_channels , <nl> " Sum of split dimensions do not match : should be " , <nl> input_channels ) ; <nl> - vector < TIndex > output_dims ( input . dims ( ) ) ; <nl> + vector < int64_t > output_dims ( input . dims ( ) ) ; <nl> int before = 1 , after = 1 ; <nl> for ( int i = 0 ; i < canonical_axis ; + + i ) { <nl> before * = input . dim32 ( i ) ; <nl> bool SplitByLengthsOp < Context > : : RunOnDevice ( ) { <nl> input_channels , <nl> " Sum of split dimensions do not match : should be " , <nl> input_channels ) ; <nl> - vector < TIndex > output_dims ( input . dims ( ) ) ; <nl> + vector < int64_t > output_dims ( input . dims ( ) ) ; <nl> int before = input . size_to_dim ( canonical_axis ) ; <nl> int after = input . size_from_dim ( canonical_axis + 1 ) ; <nl> size_t input_offset = 0 ; <nl> template < class Context > <nl> bool ConcatOp < Context > : : RunOnDevice ( ) { <nl> auto * output = Output ( 0 ) ; <nl> Tensor * split = this - > template Output < Tensor > ( 1 , CPU ) ; <nl> - split - > Resize ( vector < TIndex > ( 1 , InputSize ( ) ) ) ; <nl> + split - > Resize ( vector < int64_t > ( 1 , InputSize ( ) ) ) ; <nl> int * axis_data = split - > template mutable_data < int > ( ) ; <nl> auto & input_zero = Input ( 0 ) ; <nl> int adj_size = input_zero . ndim ( ) + ( add_axis_ ? 1 : 0 ) ; <nl> bool ConcatOp < Context > : : RunOnDevice ( ) { <nl> } <nl> <nl> int before = 1 , after = 1 ; <nl> - vector < TIndex > output_dims ( input_zero . dims ( ) ) ; <nl> + vector < int64_t > output_dims ( input_zero . dims ( ) ) ; <nl> for ( int i = 0 ; i < input_zero . ndim ( ) ; + + i ) { <nl> if ( i = = canonical_axis & & ! add_axis_ ) { <nl> continue ; <nl> mmm a / caffe2 / operators / conditional_op . cc <nl> ppp b / caffe2 / operators / conditional_op . cc <nl> bool ConditionalOp < CPUContext > : : RunOnDevice ( ) { <nl> / / perform conditional op along first dimension <nl> const auto * ptrT = ( char * ) dataT . raw_data ( ) ; <nl> const auto * ptrF = ( char * ) dataF . raw_data ( ) ; <nl> - for ( TIndex i = 0 ; i < condition . size ( ) ; i + + ) { <nl> + for ( int64_t i = 0 ; i < condition . size ( ) ; i + + ) { <nl> auto * dst = outPtr + i * innerSizeBytes ; <nl> if ( condPtr [ i ] ) { <nl> context_ . CopyItemsSameDevice ( <nl> mmm a / caffe2 / operators / conv_op_cache_cudnn . h <nl> ppp b / caffe2 / operators / conv_op_cache_cudnn . h <nl> class AlgorithmsCache { <nl> / / combination of tensor dimensions & compute data type . <nl> / / <nl> TAlgorithm getAlgorithm ( <nl> - const std : : vector < TIndex > & tensorDimensions1 , <nl> - const std : : vector < TIndex > & tensorDimensions2 , <nl> + const std : : vector < int64_t > & tensorDimensions1 , <nl> + const std : : vector < int64_t > & tensorDimensions2 , <nl> int algorithmFlags , / / Differentiate between algorithms with different <nl> / / parameters in a generic way <nl> std : : function < TAlgorithm ( ) > generatingFunc ) ; <nl> class AlgorithmsCache { <nl> <nl> template < typename TAlgorithm > <nl> TAlgorithm AlgorithmsCache < TAlgorithm > : : getAlgorithm ( <nl> - const std : : vector < TIndex > & tensorDimensions1 , <nl> - const std : : vector < TIndex > & tensorDimensions2 , <nl> + const std : : vector < int64_t > & tensorDimensions1 , <nl> + const std : : vector < int64_t > & tensorDimensions2 , <nl> int algorithmFlags , <nl> std : : function < TAlgorithm ( ) > generatingFunc ) { <nl> int64_t seed = 0 ; <nl> / / Hash all of the inputs , which we wiill then use to try and look up <nl> / / a previously discovered algorithm , or fall back to generating a new one . <nl> - std : : hash < TIndex > hashFn ; <nl> + std : : hash < int64_t > hashFn ; <nl> for ( const auto num : tensorDimensions1 ) { <nl> / / Copied from boost : : hash_combine . <nl> / / Adding 1 to differentiate between first and second vector . <nl> mmm a / caffe2 / operators / conv_op_cache_cudnn_test . cc <nl> ppp b / caffe2 / operators / conv_op_cache_cudnn_test . cc <nl> namespace caffe2 { <nl> TEST ( AlgorithmsCacheTest , CachesCorrectly ) { <nl> AlgorithmsCache < int > cache ; <nl> int result = cache . getAlgorithm ( <nl> - std : : vector < TIndex > ( 1 ) , std : : vector < TIndex > ( 1 ) , 0 , [ ] ( ) { return 5 ; } ) ; <nl> + std : : vector < int64_t > ( 1 ) , std : : vector < int64_t > ( 1 ) , 0 , [ ] ( ) { return 5 ; } ) ; <nl> EXPECT_EQ ( result , 5 ) ; <nl> <nl> int res2 = cache . getAlgorithm ( <nl> - std : : vector < TIndex > ( 1 ) , std : : vector < TIndex > ( 1 ) , 0 , [ ] ( ) { return 10 ; } ) ; <nl> + std : : vector < int64_t > ( 1 ) , std : : vector < int64_t > ( 1 ) , 0 , [ ] ( ) { return 10 ; } ) ; <nl> <nl> EXPECT_EQ ( res2 , 5 ) ; <nl> } <nl> TEST ( AlgorithmsCacheTest , CachesCorrectly ) { <nl> TEST ( AlgorithmsCacheTest , KeysDifferIfOneVectorIsEmpty ) { <nl> AlgorithmsCache < int > cache ; <nl> int result = cache . getAlgorithm ( <nl> - std : : vector < TIndex > ( 1 , 10 ) , std : : vector < TIndex > ( ) , 0 , [ ] ( ) { return 5 ; } ) ; <nl> + std : : vector < int64_t > ( 1 , 10 ) , std : : vector < int64_t > ( ) , 0 , [ ] ( ) { return 5 ; } ) ; <nl> EXPECT_EQ ( result , 5 ) ; <nl> <nl> int res2 = cache . getAlgorithm ( <nl> - std : : vector < TIndex > ( ) , std : : vector < TIndex > ( 1 , 10 ) , 0 , [ ] ( ) { <nl> + std : : vector < int64_t > ( ) , std : : vector < int64_t > ( 1 , 10 ) , 0 , [ ] ( ) { <nl> return 10 ; <nl> } ) ; <nl> <nl> TEST ( AlgorithmsCacheTest , KeysDifferIfOneVectorIsEmpty ) { <nl> TEST ( AlgorithmsCacheTest , KeysDifferIfFlagsAreDifferent ) { <nl> AlgorithmsCache < int > cache ; <nl> int result = cache . getAlgorithm ( <nl> - std : : vector < TIndex > { 2 , 3 , 4 } , std : : vector < TIndex > { 5 , 6 } , 123 , [ ] ( ) { <nl> + std : : vector < int64_t > { 2 , 3 , 4 } , std : : vector < int64_t > { 5 , 6 } , 123 , [ ] ( ) { <nl> return 5 ; <nl> } ) ; <nl> EXPECT_EQ ( result , 5 ) ; <nl> <nl> int res2 = cache . getAlgorithm ( <nl> - std : : vector < TIndex > { 2 , 3 , 4 } , std : : vector < TIndex > { 5 , 6 } , 456 , [ ] ( ) { <nl> + std : : vector < int64_t > { 2 , 3 , 4 } , std : : vector < int64_t > { 5 , 6 } , 456 , [ ] ( ) { <nl> return 10 ; <nl> } ) ; <nl> <nl> EXPECT_EQ ( res2 , 10 ) ; <nl> <nl> int res3 = cache . getAlgorithm ( <nl> - std : : vector < TIndex > { 2 , 3 , 4 } , std : : vector < TIndex > { 5 , 6 } , 456 , [ ] ( ) { <nl> + std : : vector < int64_t > { 2 , 3 , 4 } , std : : vector < int64_t > { 5 , 6 } , 456 , [ ] ( ) { <nl> return 15 ; <nl> } ) ; <nl> <nl> mmm a / caffe2 / operators / conv_op_cudnn . cc <nl> ppp b / caffe2 / operators / conv_op_cudnn . cc <nl> class CudnnConvOpBase : public ConvPoolOpBase < CUDAContext > { <nl> } <nl> } <nl> <nl> - vector < TIndex > cudnn_input_dims_ ; <nl> - vector < TIndex > cudnn_filter_dims_ ; <nl> + vector < int64_t > cudnn_input_dims_ ; <nl> + vector < int64_t > cudnn_filter_dims_ ; <nl> <nl> CuDNNWrapper cudnn_wrapper_ ; <nl> cudnnTensorDescriptor_t bottom_desc_ ; <nl> mmm a / caffe2 / operators / conv_op_eigen . cc <nl> ppp b / caffe2 / operators / conv_op_eigen . cc <nl> bool EigenConvOp < T > : : RunOnDeviceWithOrderNCHW ( ) { <nl> CAFFE_ENFORCE ( filter . dim32 ( 2 ) = = kernel_h ( ) ) ; <nl> CAFFE_ENFORCE ( filter . dim32 ( 3 ) = = kernel_w ( ) ) ; <nl> ConvPoolOpBase < CPUContext > : : SetOutputSize ( X , Y , filter . dim32 ( 0 ) ) ; <nl> - Eigen : : array < TIndex , 4 > kernel_shuffles <nl> - { { TIndex ( 2 ) , TIndex ( 3 ) , TIndex ( 1 ) , TIndex ( 0 ) } } ; <nl> - Eigen : : array < TIndex , 4 > input_shuffles <nl> - { { TIndex ( 0 ) , TIndex ( 2 ) , TIndex ( 3 ) , TIndex ( 1 ) } } ; <nl> + Eigen : : array < int64_t , 4 > kernel_shuffles <nl> + { { int64_t ( 2 ) , int64_t ( 3 ) , int64_t ( 1 ) , int64_t ( 0 ) } } ; <nl> + Eigen : : array < int64_t , 4 > input_shuffles <nl> + { { int64_t ( 0 ) , int64_t ( 2 ) , int64_t ( 3 ) , int64_t ( 1 ) } } ; <nl> <nl> Eigen : : Tensor < T , 4 , Eigen : : RowMajor > filter_tensor = <nl> Eigen : : TensorMap < Eigen : : Tensor < T , 4 , Eigen : : RowMajor > > ( <nl> bool EigenConvOp < T > : : RunOnDeviceWithOrderNCHW ( ) { <nl> / / It seems that the bias broadcast is still slower so let ' s do the <nl> / / following for now . <nl> EigenArrayMap < T > Y_arr ( <nl> - Y_tensor . data ( ) , static_cast < TIndex > ( M ) , Y - > size ( ) / M ) ; <nl> + Y_tensor . data ( ) , static_cast < int64_t > ( M ) , Y - > size ( ) / M ) ; <nl> ConstEigenVectorArrayMap < T > bias_arr ( bias . template data < T > ( ) , M ) ; <nl> Y_arr = Y_arr . colwise ( ) + bias_arr ; <nl> } <nl> <nl> / / Do a last transpose . <nl> - Eigen : : array < TIndex , 4 > output_shuffles <nl> - { { TIndex ( 0 ) , TIndex ( 3 ) , TIndex ( 1 ) , TIndex ( 2 ) } } ; <nl> + Eigen : : array < int64_t , 4 > output_shuffles <nl> + { { int64_t ( 0 ) , int64_t ( 3 ) , int64_t ( 1 ) , int64_t ( 2 ) } } ; <nl> <nl> Eigen : : TensorMap < Eigen : : Tensor < T , 4 , Eigen : : RowMajor > > ( <nl> Y - > template mutable_data < T > ( ) , N , M , Y - > dim32 ( 2 ) , Y - > dim32 ( 3 ) ) = <nl> bool EigenConvOp < T > : : RunOnDeviceWithOrderNHWC ( ) { <nl> / / It seems that the bias broadcast is still slower so let ' s do the <nl> / / following for now . <nl> EigenArrayMap < T > Y_arr ( <nl> - Y - > template mutable_data < T > ( ) , static_cast < TIndex > ( M ) , Y - > size ( ) / M ) ; <nl> + Y - > template mutable_data < T > ( ) , static_cast < int64_t > ( M ) , Y - > size ( ) / M ) ; <nl> ConstEigenVectorArrayMap < T > bias_arr ( bias . template data < T > ( ) , M ) ; <nl> Y_arr = Y_arr . colwise ( ) + bias_arr ; <nl> } <nl> mmm a / caffe2 / operators / conv_op_impl . h <nl> ppp b / caffe2 / operators / conv_op_impl . h <nl> bool ConvOp < T , Context > : : RunOnDeviceWithOrderNHWC ( ) { <nl> } <nl> auto f = [ & ] ( Tensor * col_buffer ) { <nl> col_buffer - > Resize ( <nl> - vector < TIndex > { Y - > dim32 ( 1 ) , Y - > dim32 ( 2 ) , kernel_h ( ) , kernel_w ( ) , C } ) ; <nl> + vector < int64_t > { Y - > dim32 ( 1 ) , Y - > dim32 ( 2 ) , kernel_h ( ) , kernel_w ( ) , C } ) ; <nl> T * col_buffer_data = col_buffer - > template mutable_data < T > ( ) ; <nl> / / Im2Col , followed by gemm . <nl> for ( int image_id = 0 ; image_id < N ; + + image_id ) { <nl> bool ConvGradientOp < T , Context > : : RunOnDeviceWithOrderNCHW ( ) { <nl> dbias - > Resize ( M ) ; <nl> if ( bias_multiplier_ . size ( ) ! = output_image_size ) { <nl> / / If the helper bias multiplier is not M , reshape and fill it with one . <nl> - bias_multiplier_ . Resize ( vector < TIndex > ( 1 , output_image_size ) ) ; <nl> + bias_multiplier_ . Resize ( vector < int64_t > ( 1 , output_image_size ) ) ; <nl> math : : Set < T , Context > ( <nl> output_image_size , <nl> static_cast < T > ( 1 ) , <nl> bool ConvGradientOp < T , Context > : : RunOnDeviceWithOrderNHWC ( ) { <nl> math : : Set < T , Context > ( dbias - > size ( ) , 0 , dbias_data , & context_ ) ; <nl> if ( bias_multiplier_ . size ( ) ! = output_image_size ) { <nl> / / If the helper bias multiplier is not M , reshape and fill it with one . <nl> - bias_multiplier_ . Resize ( vector < TIndex > ( 1 , output_image_size ) ) ; <nl> + bias_multiplier_ . Resize ( vector < int64_t > ( 1 , output_image_size ) ) ; <nl> math : : Set < T , Context > ( <nl> output_image_size , <nl> static_cast < T > ( 1 ) , <nl> mmm a / caffe2 / operators / conv_pool_op_base . h <nl> ppp b / caffe2 / operators / conv_pool_op_base . h <nl> class ConvPoolOpBase : public Operator < Context > { <nl> / / Helper function that is also called from OperatorSchema . Modified <nl> / / kernel parameters and output output_dims and channel_first . <nl> static inline void InferOutputSize ( <nl> - vector < TIndex > input_dims , <nl> + vector < int64_t > input_dims , <nl> int / * output_channel * / , <nl> StorageOrder order , <nl> bool global_pooling , <nl> class ConvPoolOpBase : public Operator < Context > { <nl> vector < int > & pads , <nl> bool & channel_first ) { <nl> channel_first = false ; / / initialized to suppress compiler warning . <nl> - vector < TIndex > dims ; <nl> + vector < int64_t > dims ; <nl> switch ( order ) { <nl> case StorageOrder : : NHWC : <nl> channel_first = false ; <nl> class ConvPoolOpBase : public Operator < Context > { <nl> if ( bias_multiplier_ - > size ( ) ! = size ) { <nl> / / If the helper bias multiplier is not image size , reshape and fill it <nl> / / with one . <nl> - bias_multiplier_ - > Resize ( std : : vector < TIndex > { size } ) ; <nl> + bias_multiplier_ - > Resize ( std : : vector < int64_t > { size } ) ; <nl> math : : Set < T , Context > ( <nl> size , <nl> static_cast < T > ( 1 ) , <nl> mmm a / caffe2 / operators / conv_transpose_op_cudnn . cc <nl> ppp b / caffe2 / operators / conv_transpose_op_cudnn . cc <nl> class CudnnConvTransposeOpBase : public ConvTransposeUnpoolBase < CUDAContext > { <nl> } <nl> <nl> protected : <nl> - vector < TIndex > cudnn_input_dims_ ; <nl> - vector < TIndex > cudnn_filter_dims_ ; <nl> + vector < int64_t > cudnn_input_dims_ ; <nl> + vector < int64_t > cudnn_filter_dims_ ; <nl> <nl> CuDNNWrapper cudnn_wrapper_ ; <nl> cudnnTensorDescriptor_t bottom_desc_ ; <nl> mmm a / caffe2 / operators / conv_transpose_op_impl . h <nl> ppp b / caffe2 / operators / conv_transpose_op_impl . h <nl> bool ConvTransposeOp < T , Context > : : RunOnDeviceWithOrderNCHW ( ) { <nl> bias . dim32 ( 0 ) = = C , <nl> " bias dimension must be equal to output channel number " ) ; <nl> if ( bias_multiplier_ . size ( ) ! = output_image_size ) { <nl> - bias_multiplier_ . Resize ( vector < TIndex > ( 1 , output_image_size ) ) ; <nl> + bias_multiplier_ . Resize ( vector < int64_t > ( 1 , output_image_size ) ) ; <nl> T * bm_data = bias_multiplier_ . template mutable_data < T > ( ) ; <nl> math : : Set < T , Context > ( <nl> output_image_size , <nl> bool ConvTransposeOp < T , Context > : : RunOnDeviceWithOrderNCHW ( ) { <nl> <nl> auto f = [ & ] ( Tensor * col_buffer ) { <nl> col_buffer - > Resize ( <nl> - vector < TIndex > { C , this - > kernel_h ( ) , this - > kernel_w ( ) , H , W } ) ; <nl> + vector < int64_t > { C , this - > kernel_h ( ) , this - > kernel_w ( ) , H , W } ) ; <nl> T * col_buffer_data = col_buffer - > template mutable_data < T > ( ) ; <nl> for ( auto image_id = 0 ; image_id < N ; + + image_id ) { <nl> / / Weight term <nl> bool ConvTransposeOp < T , Context > : : RunOnDeviceWithOrderNHWC ( ) { <nl> bias . dim32 ( 0 ) = = C , <nl> " bias dimension must be equal to output channel number " ) ; <nl> if ( bias_multiplier_ . size ( ) ! = output_image_size ) { <nl> - bias_multiplier_ . Resize ( vector < TIndex > ( 1 , output_image_size ) ) ; <nl> + bias_multiplier_ . Resize ( vector < int64_t > ( 1 , output_image_size ) ) ; <nl> T * bm_data = bias_multiplier_ . template mutable_data < T > ( ) ; <nl> math : : Set < T , Context > ( <nl> output_image_size , <nl> bool ConvTransposeOp < T , Context > : : RunOnDeviceWithOrderNHWC ( ) { <nl> <nl> auto f = [ & ] ( Tensor * / * col_buffer * / ) { <nl> col_buffer_ . Resize ( <nl> - vector < TIndex > { H , W , this - > kernel_h ( ) , this - > kernel_w ( ) , C } ) ; <nl> + vector < int64_t > { H , W , this - > kernel_h ( ) , this - > kernel_w ( ) , C } ) ; <nl> T * col_buffer_data = col_buffer_ . template mutable_data < T > ( ) ; <nl> for ( auto image_id = 0 ; image_id < N ; + + image_id ) { <nl> / / Weight term <nl> bool ConvTransposeGradientOp < T , Context > : : RunOnDeviceWithOrderNCHW ( ) { <nl> const int output_image_size = dY . dim32 ( 2 ) * dY . dim32 ( 3 ) ; <nl> / / The col buffer is stored in CHW order as well <nl> col_buffer_ . Resize ( <nl> - vector < TIndex > { C , this - > kernel_h ( ) , this - > kernel_w ( ) , H , W } ) ; <nl> + vector < int64_t > { C , this - > kernel_h ( ) , this - > kernel_w ( ) , H , W } ) ; <nl> if ( ! no_bias_ ) { <nl> auto * dbias = Output ( BIAS_OR_INPUT_GRAD ) ; <nl> dbias - > Resize ( C ) ; <nl> bool ConvTransposeGradientOp < T , Context > : : RunOnDeviceWithOrderNHWC ( ) { <nl> const int output_image_size = dY . dim32 ( 1 ) * dY . dim32 ( 2 ) ; <nl> / / The col buffer is stored in HWC order as well <nl> col_buffer_ . Resize ( <nl> - vector < TIndex > { H , W , this - > kernel_h ( ) , this - > kernel_w ( ) , C } ) ; <nl> + vector < int64_t > { H , W , this - > kernel_h ( ) , this - > kernel_w ( ) , C } ) ; <nl> if ( ! no_bias_ ) { <nl> auto * dbias = Output ( BIAS_OR_INPUT_GRAD ) ; <nl> dbias - > Resize ( C ) ; <nl> mmm a / caffe2 / operators / conv_transpose_op_mobile_test . cc <nl> ppp b / caffe2 / operators / conv_transpose_op_mobile_test . cc <nl> <nl> <nl> namespace caffe2 { <nl> <nl> - void AddConstInput ( const vector < TIndex > & shape , <nl> + void AddConstInput ( const vector < int64_t > & shape , <nl> const float value , <nl> const string & name , <nl> Workspace * ws ) { <nl> void AddConstInput ( const vector < TIndex > & shape , <nl> tensor - > size ( ) , value , tensor - > template mutable_data < float > ( ) , & context ) ; <nl> } <nl> <nl> - void AddNoiseInput ( const vector < TIndex > & shape , <nl> + void AddNoiseInput ( const vector < int64_t > & shape , <nl> const string & name , <nl> Workspace * ws ) { <nl> DeviceOption option ; <nl> void compare ( int N , int inputC , int H , int W , <nl> def1 . add_arg ( ) - > CopyFrom ( MakeArgument ( " adj_h " , adjH ) ) ; <nl> def1 . add_arg ( ) - > CopyFrom ( MakeArgument ( " adj_w " , adjW ) ) ; <nl> <nl> - AddNoiseInput ( vector < TIndex > { N , inputC , H , W } , " X " , & ws ) ; <nl> - AddNoiseInput ( vector < TIndex > { inputC , outputC , kernelH , kernelW } , " W " , & ws ) ; <nl> - AddNoiseInput ( vector < TIndex > { outputC } , " B " , & ws ) ; <nl> + AddNoiseInput ( vector < int64_t > { N , inputC , H , W } , " X " , & ws ) ; <nl> + AddNoiseInput ( vector < int64_t > { inputC , outputC , kernelH , kernelW } , " W " , & ws ) ; <nl> + AddNoiseInput ( vector < int64_t > { outputC } , " B " , & ws ) ; <nl> <nl> unique_ptr < OperatorBase > op1 ( CreateOperator ( def1 , & ws ) ) ; <nl> EXPECT_NE ( nullptr , op1 . get ( ) ) ; <nl> mmm a / caffe2 / operators / cross_entropy_op . cc <nl> ppp b / caffe2 / operators / cross_entropy_op . cc <nl> bool SigmoidCrossEntropyWithLogitsOp < float , CPUContext > : : RunOnDevice ( ) { <nl> <nl> auto * out = Output ( 0 ) ; <nl> if ( logits . ndim ( ) = = 0 ) { <nl> - out - > Resize ( std : : vector < TIndex > { } ) ; <nl> + out - > Resize ( std : : vector < int64_t > { } ) ; <nl> } else { <nl> - std : : vector < TIndex > dims ( logits . dims ( ) . begin ( ) , logits . dims ( ) . end ( ) - 1 ) ; <nl> + std : : vector < int64_t > dims ( logits . dims ( ) . begin ( ) , logits . dims ( ) . end ( ) - 1 ) ; <nl> out - > Resize ( dims ) ; <nl> } <nl> auto * out_ptr = out - > template mutable_data < float > ( ) ; <nl> bool WeightedSigmoidCrossEntropyWithLogitsOp < float , CPUContext > : : RunOnDevice ( ) { <nl> <nl> auto * out = Output ( 0 ) ; <nl> if ( logits . ndim ( ) = = 0 ) { <nl> - out - > Resize ( std : : vector < TIndex > { } ) ; <nl> + out - > Resize ( std : : vector < int64_t > { } ) ; <nl> } else { <nl> - std : : vector < TIndex > dims ( logits . dims ( ) . begin ( ) , logits . dims ( ) . end ( ) - 1 ) ; <nl> + std : : vector < int64_t > dims ( logits . dims ( ) . begin ( ) , logits . dims ( ) . end ( ) - 1 ) ; <nl> out - > Resize ( dims ) ; <nl> } <nl> auto * out_ptr = out - > template mutable_data < float > ( ) ; <nl> bool MakeTwoClassOp < float , CPUContext > : : RunOnDevice ( ) { <nl> auto * Y = Output ( 0 ) ; <nl> auto shape = X . dims ( ) ; <nl> shape . push_back ( 2 ) ; <nl> - TIndex N = X . size ( ) ; <nl> + int64_t N = X . size ( ) ; <nl> Y - > Resize ( shape ) ; <nl> const auto * Xdata = X . data < float > ( ) ; <nl> auto * Ydata = Y - > template mutable_data < float > ( ) ; <nl> - for ( TIndex i = 0 ; i < N ; + + i ) { <nl> + for ( int64_t i = 0 ; i < N ; + + i ) { <nl> DCHECK_GE ( Xdata [ i ] , 0 . 0 ) ; <nl> DCHECK_LE ( Xdata [ i ] , 1 . 0 ) ; <nl> Ydata [ i * 2 ] = 1 . 0 - Xdata [ i ] ; <nl> bool MakeTwoClassGradientOp < float , CPUContext > : : RunOnDevice ( ) { <nl> dX - > Resize ( shape ) ; <nl> const float * dYdata = dY . data < float > ( ) ; <nl> float * dXdata = dX - > template mutable_data < float > ( ) ; <nl> - TIndex N = dX - > size ( ) ; <nl> + int64_t N = dX - > size ( ) ; <nl> / / use eigen ? <nl> - for ( TIndex i = 0 ; i < N ; + + i ) { <nl> + for ( int64_t i = 0 ; i < N ; + + i ) { <nl> dXdata [ i ] = dYdata [ i * 2 + 1 ] - dYdata [ i * 2 ] ; <nl> } <nl> return true ; <nl> bool CrossEntropyOp < float , CPUContext > : : RunOnDevice ( ) { <nl> CAFFE_ENFORCE ( <nl> ( label . ndim ( ) = = 1 ) | | ( label . ndim ( ) = = 2 & & label . dim32 ( 1 ) = = D ) ) ; <nl> CAFFE_ENFORCE_EQ ( label . dim32 ( 0 ) , N ) ; <nl> - Y - > Resize ( vector < TIndex > { N } ) ; <nl> + Y - > Resize ( vector < int64_t > { N } ) ; <nl> const float * Xdata = X . data < float > ( ) ; <nl> const float * labelData = label . data < float > ( ) ; <nl> auto * Ydata = Y - > template mutable_data < float > ( ) ; <nl> mmm a / caffe2 / operators / cross_entropy_op . cu <nl> ppp b / caffe2 / operators / cross_entropy_op . cu <nl> bool LabelCrossEntropyOp < float , CUDAContext > : : RunOnDevice ( ) { <nl> CAFFE_ENFORCE ( <nl> ( label . ndim ( ) = = 1 ) | | ( label . ndim ( ) = = 2 & & label . dim32 ( 1 ) = = 1 ) ) ; <nl> CAFFE_ENFORCE_EQ ( label . dim32 ( 0 ) , N ) ; <nl> - Y - > Resize ( vector < TIndex > ( size_t ( 1 ) , N ) ) ; <nl> + Y - > Resize ( vector < int64_t > ( size_t ( 1 ) , N ) ) ; <nl> LabelCrossEntropyKernel < < < <nl> CAFFE_GET_BLOCKS ( N ) , <nl> CAFFE_CUDA_NUM_THREADS , <nl> bool SigmoidCrossEntropyWithLogitsOp < float , CUDAContext > : : RunOnDevice ( ) { <nl> <nl> auto * out = Output ( 0 ) ; <nl> if ( logits . ndim ( ) = = 0 ) { <nl> - out - > Resize ( std : : vector < TIndex > { } ) ; <nl> + out - > Resize ( std : : vector < int64_t > { } ) ; <nl> } else { <nl> - std : : vector < TIndex > dims ( logits . dims ( ) . begin ( ) , logits . dims ( ) . end ( ) - 1 ) ; <nl> + std : : vector < int64_t > dims ( logits . dims ( ) . begin ( ) , logits . dims ( ) . end ( ) - 1 ) ; <nl> out - > Resize ( dims ) ; <nl> } <nl> auto * out_ptr = out - > template mutable_data < float > ( ) ; <nl> bool WeightedSigmoidCrossEntropyWithLogitsOp < float , CUDAContext > : : <nl> <nl> auto * out = Output ( 0 ) ; <nl> if ( logits . ndim ( ) = = 0 ) { <nl> - out - > Resize ( std : : vector < TIndex > { } ) ; <nl> + out - > Resize ( std : : vector < int64_t > { } ) ; <nl> } else { <nl> - std : : vector < TIndex > dims ( logits . dims ( ) . begin ( ) , logits . dims ( ) . end ( ) - 1 ) ; <nl> + std : : vector < int64_t > dims ( logits . dims ( ) . begin ( ) , logits . dims ( ) . end ( ) - 1 ) ; <nl> out - > Resize ( dims ) ; <nl> } <nl> auto * out_ptr = out - > template mutable_data < float > ( ) ; <nl> mmm a / caffe2 / operators / ctc_beam_search_decoder_op . cc <nl> ppp b / caffe2 / operators / ctc_beam_search_decoder_op . cc <nl> bool CTCBeamSearchDecoderOp < CPUContext > : : RunOnDevice ( ) { <nl> ( InputSize ( ) = = 2 ) ? Input ( SEQ_LEN ) . data < int > ( ) : nullptr ; <nl> <nl> vector < int32_t > values_cache ; <nl> - output_len - > Resize ( vector < TIndex > { batch_size } ) ; <nl> + output_len - > Resize ( vector < int64_t > { batch_size } ) ; <nl> int * output_len_data = output_len - > mutable_data < int > ( ) ; <nl> <nl> for ( int32_t i = 0 ; i < batch_size ; + + i ) { <nl> bool CTCBeamSearchDecoderOp < CPUContext > : : RunOnDevice ( ) { <nl> } <nl> <nl> int32_t cache_size = values_cache . size ( ) ; <nl> - values - > Resize ( vector < TIndex > { cache_size } ) ; <nl> + values - > Resize ( vector < int64_t > { cache_size } ) ; <nl> int * values_data = values - > mutable_data < int > ( ) ; <nl> for ( int i = 0 ; i < values_cache . size ( ) ; + + i ) { <nl> values_data [ i ] = values_cache . at ( i ) ; <nl> mmm a / caffe2 / operators / ctc_greedy_decoder_op . cc <nl> ppp b / caffe2 / operators / ctc_greedy_decoder_op . cc <nl> bool CTCGreedyDecoderOp < CPUContext > : : RunOnDevice ( ) { <nl> ( InputSize ( ) = = 2 ) ? Input ( SEQ_LEN ) . data < int > ( ) : nullptr ; <nl> <nl> vector < int > values_cach ; <nl> - output_len - > Resize ( vector < TIndex > { batch_size } ) ; <nl> + output_len - > Resize ( vector < int64_t > { batch_size } ) ; <nl> int * output_len_data = output_len - > template mutable_data < int > ( ) ; <nl> <nl> for ( int32_t i = 0 ; i < batch_size ; + + i ) { <nl> bool CTCGreedyDecoderOp < CPUContext > : : RunOnDevice ( ) { <nl> } <nl> <nl> int32_t values_cach_size = values_cach . size ( ) ; <nl> - values - > Resize ( vector < TIndex > { values_cach_size } ) ; <nl> + values - > Resize ( vector < int64_t > { values_cach_size } ) ; <nl> int * values_data = values - > mutable_data < int > ( ) ; <nl> for ( int i = 0 ; i < values_cach . size ( ) ; + + i ) { <nl> values_data [ i ] = values_cach . at ( i ) ; <nl> mmm a / caffe2 / operators / dataset_ops . cc <nl> ppp b / caffe2 / operators / dataset_ops . cc <nl> void TreeWalker : : advance ( ) { <nl> cursor_ . it . advance ( lengths_ , cursor_ . offsets , sizes_ , limits_ , 1 ) ; <nl> } <nl> <nl> - std : : vector < TIndex > TreeWalker : : fieldDim ( int fieldId ) const { <nl> + std : : vector < int64_t > TreeWalker : : fieldDim ( int fieldId ) const { <nl> auto tensorDim = input ( fieldId ) . dims ( ) ; <nl> tensorDim [ 0 ] = sizes_ [ lengthIdx ( fieldId ) ] ; <nl> return tensorDim ; <nl> class UnPackRecordsOp : public Operator < CPUContext > { <nl> auto numTensors = OutputSize ( ) ; <nl> <nl> / / Precomputer the output sizes to avoid resizing <nl> - std : : vector < std : : vector < TIndex > > outputDims ( numTensors ) ; <nl> + std : : vector < std : : vector < int64_t > > outputDims ( numTensors ) ; <nl> std : : vector < const TypeMeta * > metas ( numTensors ) ; <nl> <nl> CAFFE_ENFORCE ( <nl> class UnPackRecordsOp : public Operator < CPUContext > { <nl> <nl> private : <nl> void getShapeAndMetaFromInput ( <nl> - std : : vector < std : : vector < TIndex > > & outputDims , <nl> + std : : vector < std : : vector < int64_t > > & outputDims , <nl> std : : vector < const TypeMeta * > & metas ) { <nl> const auto * inputs = Input ( 0 ) . template data < SharedTensorVectorPtr > ( ) ; <nl> <nl> class UnPackRecordsOp : public Operator < CPUContext > { <nl> } <nl> <nl> void getShapeAndMetaFromPrototypeBlobs ( <nl> - std : : vector < std : : vector < TIndex > > & outputDims , <nl> + std : : vector < std : : vector < int64_t > > & outputDims , <nl> std : : vector < const TypeMeta * > & metas ) { <nl> const auto numTensors = fields_ . size ( ) ; <nl> CAFFE_ENFORCE_EQ ( numTensors , InputSize ( ) - 1 ) ; <nl> class ReadNextBatchOp : public Operator < CPUContext > { <nl> } <nl> } <nl> / / gather data <nl> - std : : vector < TIndex > outDim ; <nl> + std : : vector < int64_t > outDim ; <nl> for ( int i = 0 ; i < cursor - > it . fields ( ) . size ( ) ; + + i ) { <nl> auto lengthIdx = cursor - > it . fields ( ) [ i ] . lengthFieldId + 1 ; <nl> auto size = sizes [ lengthIdx ] ; <nl> class ReadRandomBatchOp : public Operator < CPUContext > { <nl> auto idxvec = idxblob . template data < int64_t > ( ) ; <nl> auto & offsetdim = offsetsmat . dims ( ) ; <nl> / / gather data <nl> - std : : vector < TIndex > outDim ; <nl> + std : : vector < int64_t > outDim ; <nl> int64_t idx ; <nl> { <nl> std : : lock_guard < std : : mutex > lock ( cursor - > mutex_ ) ; <nl> class ConcatTensorVectorOp final : public Operator < Context > { <nl> auto * tensor = Output ( TENSOR ) ; <nl> CAFFE_ENFORCE ( ! tensorVector - > empty ( ) ) ; <nl> <nl> - vector < TIndex > outputDims ( tensorVector - > at ( 0 ) . dims ( ) ) ; <nl> + vector < int64_t > outputDims ( tensorVector - > at ( 0 ) . dims ( ) ) ; <nl> CAFFE_ENFORCE ( outputDims . size ( ) > 0 ) ; <nl> for ( int i = 1 ; i < tensorVector - > size ( ) ; i + + ) { <nl> / / the tensor shapes are the same except for the first dimension <nl> class ConcatTensorVectorOp final : public Operator < Context > { <nl> } <nl> <nl> tensor - > Resize ( outputDims ) ; <nl> - TIndex offset = 0 ; <nl> + int64_t offset = 0 ; <nl> auto * dst = ( char * ) tensor - > raw_mutable_data ( tensorVector - > at ( 0 ) . meta ( ) ) ; <nl> <nl> for ( const auto & t : * tensorVector ) { <nl> mmm a / caffe2 / operators / dataset_ops . h <nl> ppp b / caffe2 / operators / dataset_ops . h <nl> class TreeWalker { <nl> return prevOffsets_ [ lengthIdx ( fieldId ) ] ; <nl> } <nl> <nl> - std : : vector < TIndex > fieldDim ( int fieldId ) const ; <nl> + std : : vector < int64_t > fieldDim ( int fieldId ) const ; <nl> <nl> void * fieldPtr ( int fieldId ) const ; <nl> <nl> class TreeWalker { <nl> Field ( TreeWalker & walker , int fieldId ) <nl> : walker_ ( walker ) , fieldId_ ( fieldId ) { } <nl> <nl> - inline std : : vector < TIndex > dim ( ) const { <nl> + inline std : : vector < int64_t > dim ( ) const { <nl> return walker_ . fieldDim ( fieldId_ ) ; <nl> } <nl> <nl> - inline TIndex size ( ) const { <nl> - TIndex size = 1 ; <nl> + inline int64_t size ( ) const { <nl> + int64_t size = 1 ; <nl> for ( const auto d : dim ( ) ) { <nl> size * = d ; <nl> } <nl> mmm a / caffe2 / operators / deform_conv_op . cu <nl> ppp b / caffe2 / operators / deform_conv_op . cu <nl> <nl> <nl> namespace caffe2 { <nl> <nl> - typedef TIndex index_t ; <nl> - typedef std : : vector < TIndex > TShape ; <nl> + typedef int64_t index_t ; <nl> + typedef std : : vector < int64_t > TShape ; <nl> <nl> template < typename DType > <nl> __device__ DType deformable_im2col_bilinear ( <nl> template < typename DType , typename Context > <nl> void DeformConvOpBase < DType , Context > : : DeformableIm2col ( <nl> const DType * data_im , <nl> const DType * data_offset , <nl> - const std : : vector < TIndex > & im_shape , <nl> - const std : : vector < TIndex > & col_shape , <nl> + const std : : vector < int64_t > & im_shape , <nl> + const std : : vector < int64_t > & col_shape , <nl> DType * data_col ) { <nl> CHECK_LT ( 2 , CAFFE_CUDA_NUM_THREADS ) ; <nl> CAFFE_ENFORCE_EQ ( pad_t ( ) , pad_b ( ) ) ; <nl> template < typename DType , typename Context > <nl> void DeformConvOpBase < DType , Context > : : DeformableCol2im ( <nl> const DType * data_col , <nl> const DType * data_offset , <nl> - const std : : vector < TIndex > & im_shape , <nl> - const std : : vector < TIndex > & col_shape , <nl> + const std : : vector < int64_t > & im_shape , <nl> + const std : : vector < int64_t > & col_shape , <nl> DType * grad_im ) { <nl> CAFFE_ENFORCE_EQ ( pad_t ( ) , pad_b ( ) ) ; <nl> CAFFE_ENFORCE_EQ ( pad_l ( ) , pad_r ( ) ) ; <nl> void DeformConvOpBase < DType , Context > : : DeformableCol2imCoord ( <nl> const DType * data_col , <nl> const DType * data_im , <nl> const DType * data_offset , <nl> - const std : : vector < TIndex > & im_shape , <nl> - const std : : vector < TIndex > & col_shape , <nl> + const std : : vector < int64_t > & im_shape , <nl> + const std : : vector < int64_t > & col_shape , <nl> DType * grad_offset ) { <nl> CAFFE_ENFORCE_EQ ( pad_t ( ) , pad_b ( ) ) ; <nl> CAFFE_ENFORCE_EQ ( pad_l ( ) , pad_r ( ) ) ; <nl> mmm a / caffe2 / operators / deform_conv_op . h <nl> ppp b / caffe2 / operators / deform_conv_op . h <nl> class DeformConvOpBase : public ConvPoolOpBase < Context > { <nl> void DeformableIm2col ( <nl> const T * data_im , <nl> const T * data_offset , <nl> - const std : : vector < TIndex > & im_shape , <nl> - const std : : vector < TIndex > & col_shape , <nl> + const std : : vector < int64_t > & im_shape , <nl> + const std : : vector < int64_t > & col_shape , <nl> T * data_col ) ; <nl> void DeformableCol2im ( <nl> const T * data_col , <nl> const T * data_offset , <nl> - const std : : vector < TIndex > & im_shape , <nl> - const std : : vector < TIndex > & col_shape , <nl> + const std : : vector < int64_t > & im_shape , <nl> + const std : : vector < int64_t > & col_shape , <nl> T * grad_im ) ; <nl> void DeformableCol2imCoord ( <nl> const T * data_col , <nl> const T * data_im , <nl> const T * data_offset , <nl> - const std : : vector < TIndex > & im_shape , <nl> - const std : : vector < TIndex > & col_shape , <nl> + const std : : vector < int64_t > & im_shape , <nl> + const std : : vector < int64_t > & col_shape , <nl> T * grad_offset ) ; <nl> <nl> protected : <nl> mmm a / caffe2 / operators / deform_conv_op_impl . h <nl> ppp b / caffe2 / operators / deform_conv_op_impl . h <nl> bool DeformConvOp < T , Context > : : RunOnDeviceWithOrderNCHW ( ) { <nl> / / If the helper bias multiplier is not image size , reshape and fill it <nl> / / with <nl> / / one . <nl> - bias_multiplier_ . Resize ( vector < TIndex > ( 1 , output_image_size ) ) ; <nl> + bias_multiplier_ . Resize ( vector < int64_t > ( 1 , output_image_size ) ) ; <nl> math : : Set < T , Context > ( <nl> output_image_size , <nl> static_cast < T > ( 1 ) , <nl> bool DeformConvGradientOp < T , Context > : : RunOnDeviceWithOrderNCHW ( ) { <nl> <nl> / / The col buffer is stored in CHW order as well - kernel_dim , and the <nl> / / height and width . <nl> - vector < TIndex > img_shape ; <nl> + vector < int64_t > img_shape ; <nl> img_shape . assign ( X . dims ( ) . begin ( ) + 1 , X . dims ( ) . end ( ) ) ; <nl> - vector < TIndex > col_buffer_shape ; <nl> + vector < int64_t > col_buffer_shape ; <nl> col_buffer_shape . push_back ( C * kernel_dims_size ) ; <nl> col_buffer_shape . insert ( <nl> col_buffer_shape . end ( ) , output_dims . begin ( ) , output_dims . end ( ) ) ; <nl> bool DeformConvGradientOp < T , Context > : : RunOnDeviceWithOrderNCHW ( ) { <nl> dbias - > Resize ( M ) ; <nl> if ( bias_multiplier_ . size ( ) ! = output_image_size ) { <nl> / / If the helper bias multiplier is not M , reshape and fill it with one . <nl> - bias_multiplier_ . Resize ( vector < TIndex > ( 1 , output_image_size ) ) ; <nl> + bias_multiplier_ . Resize ( vector < int64_t > ( 1 , output_image_size ) ) ; <nl> math : : Set < T , Context > ( <nl> output_image_size , <nl> static_cast < T > ( 1 ) , <nl> mmm a / caffe2 / operators / distance_op . cc <nl> ppp b / caffe2 / operators / distance_op . cc <nl> vector < TensorShape > TensorInferenceForDotProduct ( <nl> const vector < TensorShape > & in ) { <nl> CAFFE_ENFORCE_GT ( in . size ( ) , 0 ) ; <nl> <nl> - vector < TIndex > dims ( 1 ) ; <nl> + vector < int64_t > dims ( 1 ) ; <nl> dims [ 0 ] = in [ 0 ] . dims ( ) . size ( ) > 0 ? in [ 0 ] . dims ( 0 ) : 1 ; <nl> return vector < TensorShape > { CreateTensorShape ( dims , in [ 0 ] . data_type ( ) ) } ; <nl> } <nl> mmm a / caffe2 / operators / distance_op . cu <nl> ppp b / caffe2 / operators / distance_op . cu <nl> bool SquaredL2DistanceOp < float , CUDAContext > : : RunOnDevice ( ) { <nl> } <nl> int N = X . ndim ( ) > 0 ? X . dim32 ( 0 ) : 1 ; <nl> int D = X . size ( ) / N ; <nl> - distance - > Resize ( vector < TIndex > ( size_t ( 1 ) , N ) ) ; <nl> + distance - > Resize ( vector < int64_t > ( size_t ( 1 ) , N ) ) ; <nl> SquaredL2DistanceKernel < < < <nl> std : : min ( N , CAFFE_MAXIMUM_NUM_BLOCKS ) , <nl> CAFFE_CUDA_NUM_THREADS , <nl> bool L1DistanceOp < float , CUDAContext > : : RunOnDevice ( ) { <nl> } <nl> const int N = X . ndim ( ) > 0 ? X . dim32 ( 0 ) : 1 ; <nl> const int D = N > 0 ? X . size ( ) / N : 0 ; <nl> - distance - > Resize ( vector < TIndex > ( size_t ( 1 ) , N ) ) ; <nl> + distance - > Resize ( vector < int64_t > ( size_t ( 1 ) , N ) ) ; <nl> L1DistanceKernel < < < <nl> std : : min ( N , CAFFE_MAXIMUM_NUM_BLOCKS ) , <nl> CAFFE_CUDA_NUM_THREADS , <nl> mmm a / caffe2 / operators / dropout_op_cudnn . cc <nl> ppp b / caffe2 / operators / dropout_op_cudnn . cc <nl> class CuDNNDropoutOp final : public Operator < CUDAContext > { <nl> cudnnTensorDescriptor_t data_desc_ ; <nl> cudnnDropoutDescriptor_t dropout_desc_ ; <nl> <nl> - vector < TIndex > cudnn_input_dims_ ; <nl> + vector < int64_t > cudnn_input_dims_ ; <nl> <nl> float ratio_ ; <nl> bool is_test_ ; <nl> class CuDNNDropoutGradientOp final : public Operator < CUDAContext > { <nl> cudnnTensorDescriptor_t data_desc_ ; <nl> cudnnDropoutDescriptor_t dropout_desc_ ; <nl> <nl> - vector < TIndex > cudnn_input_dims_ ; <nl> + vector < int64_t > cudnn_input_dims_ ; <nl> <nl> Blob * scratch_blob_ ; <nl> <nl> mmm a / caffe2 / operators / elementwise_op_test . h <nl> ppp b / caffe2 / operators / elementwise_op_test . h <nl> template < typename Context , typename I_Type , typename O_Type > <nl> void FillTensor ( <nl> caffe2 : : Workspace * ws , <nl> const std : : string & name , <nl> - const std : : vector < caffe2 : : TIndex > & shape , <nl> + const std : : vector < int64_t > & shape , <nl> const std : : vector < I_Type > & values ) { <nl> auto * blob = ws - > CreateBlob ( name ) ; <nl> auto * tensor = blob - > GetMutableTensor ( Context : : GetDeviceType ( ) ) ; <nl> mmm a / caffe2 / operators / elementwise_ops_schema . cc <nl> ppp b / caffe2 / operators / elementwise_ops_schema . cc <nl> Performs element - wise { desc } comparison * * { name } * * ( with limited broadcast suppo <nl> } \ <nl> } \ <nl> auto output_dims = \ <nl> - std : : vector < TIndex > ( in [ 0 ] . dims ( ) . begin ( ) , in [ 0 ] . dims ( ) . end ( ) ) ; \ <nl> + std : : vector < int64_t > ( in [ 0 ] . dims ( ) . begin ( ) , in [ 0 ] . dims ( ) . end ( ) ) ; \ <nl> return vector < TensorShape > { \ <nl> CreateTensorShape ( output_dims , TensorProto : : BOOL ) } ; \ <nl> } ) \ <nl> mmm a / caffe2 / operators / expand_squeeze_dims_op . h <nl> ppp b / caffe2 / operators / expand_squeeze_dims_op . h <nl> class SqueezeOp : public Operator < Context > { <nl> } <nl> <nl> static std : : vector < int > ComputeDims ( <nl> - std : : vector < TIndex > inputDims , <nl> + std : : vector < int64_t > inputDims , <nl> std : : vector < int > dims ) { <nl> int j = 0 ; <nl> std : : vector < int > newDims ; <nl> mmm a / caffe2 / operators / experimental / c10 / cpu / averaged_loss_cpu . cc <nl> ppp b / caffe2 / operators / experimental / c10 / cpu / averaged_loss_cpu . cc <nl> <nl> <nl> using caffe2 : : BaseContext ; <nl> using caffe2 : : Tensor ; <nl> - using caffe2 : : TIndex ; <nl> using std : : vector ; <nl> <nl> namespace caffe2 { <nl> void averaged_loss_op_cpu_impl ( <nl> Tensor * sum , <nl> caffe2 : : ops : : AveragedLoss : : State * state , <nl> BaseContext * context ) { <nl> - sum - > Resize ( vector < TIndex > ( ) ) ; <nl> + sum - > Resize ( vector < int64_t > ( ) ) ; <nl> <nl> T * data = sum - > template mutable_data < T > ( ) ; <nl> <nl> mmm a / caffe2 / operators / experimental / c10 / cpu / batch_gather_cpu . cc <nl> ppp b / caffe2 / operators / experimental / c10 / cpu / batch_gather_cpu . cc <nl> <nl> <nl> using caffe2 : : BaseContext ; <nl> using caffe2 : : Tensor ; <nl> - using caffe2 : : TIndex ; <nl> using std : : vector ; <nl> <nl> namespace caffe2 { <nl> void batch_gather_op_cpu_impl ( <nl> BaseContext * context ) { <nl> CAFFE_ENFORCE_GE ( data . ndim ( ) , 2 , " DATA should be at least 2 - D " ) ; <nl> <nl> - vector < TIndex > shape ; <nl> + vector < int64_t > shape ; <nl> shape . push_back ( data . dim ( 0 ) ) ; <nl> shape . insert ( shape . end ( ) , indices . dims ( ) . begin ( ) , indices . dims ( ) . end ( ) ) ; <nl> shape . insert ( shape . end ( ) , data . dims ( ) . begin ( ) + 2 , data . dims ( ) . end ( ) ) ; <nl> mmm a / caffe2 / operators / experimental / c10 / cpu / batch_matmul_cpu . cc <nl> ppp b / caffe2 / operators / experimental / c10 / cpu / batch_matmul_cpu . cc <nl> <nl> <nl> using caffe2 : : BaseContext ; <nl> using caffe2 : : Tensor ; <nl> - using caffe2 : : TIndex ; <nl> using std : : vector ; <nl> namespace math = caffe2 : : math ; <nl> <nl> void batch_matmul_op_cpu_impl ( <nl> / / Calculate output tensor shapes [ B . . . , ( M ) , ( N ) ] <nl> / / Batch dimensions will be broadcasted out to those of the longer tensor <nl> / / A or B . Either M or N are optional if A or B , respectively are 1 - D . <nl> - std : : vector < TIndex > new_dims ; <nl> + std : : vector < int64_t > new_dims ; <nl> if ( ndims_A > = ndims_B ) { <nl> new_dims . assign ( dims_A . begin ( ) , dims_A . end ( ) - 2 ) ; <nl> } else { <nl> mmm a / caffe2 / operators / experimental / c10 / cpu / cast_cpu . cc <nl> ppp b / caffe2 / operators / experimental / c10 / cpu / cast_cpu . cc <nl> <nl> using caffe2 : : CPUContext ; <nl> using caffe2 : : Tensor ; <nl> using caffe2 : : TensorProto_DataType ; <nl> - using caffe2 : : TIndex ; <nl> <nl> namespace caffe2 { <nl> namespace { <nl> void do_cast_ ( const Tensor & input , Tensor * output ) { <nl> const auto * data = input . template data < SrcType > ( ) ; <nl> auto * out = output - > template mutable_data < DstType > ( ) ; <nl> auto N = input . size ( ) ; <nl> - for ( TIndex i = 0 ; i < N ; + + i ) { <nl> + for ( int64_t i = 0 ; i < N ; + + i ) { <nl> out [ i ] = static_cast < DstType > ( data [ i ] ) ; <nl> } <nl> } <nl> mmm a / caffe2 / operators / experimental / c10 / cpu / concat_cpu . cc <nl> ppp b / caffe2 / operators / experimental / c10 / cpu / concat_cpu . cc <nl> using caffe2 : : BaseContext ; <nl> using caffe2 : : CPUContext ; <nl> using caffe2 : : Tensor ; <nl> using caffe2 : : TensorCPU ; <nl> - using caffe2 : : TIndex ; <nl> using std : : vector ; <nl> <nl> namespace caffe2 { <nl> void concat_op_cpu_impl ( <nl> int axis , <nl> int add_axis , <nl> BaseContext * context ) { <nl> - split - > Resize ( vector < TIndex > ( 1 , inputs . size ( ) ) ) ; <nl> + split - > Resize ( vector < int64_t > ( 1 , inputs . size ( ) ) ) ; <nl> int * axis_data = split - > template mutable_data < int > ( ) ; <nl> int adj_size = inputs [ 0 ] - > ndim ( ) + ( add_axis ? 1 : 0 ) ; <nl> int canonical_axis = caffe2 : : canonical_axis_index_ ( axis , adj_size ) ; <nl> void concat_op_cpu_impl ( <nl> } <nl> <nl> int before = 1 , after = 1 ; <nl> - vector < TIndex > output_dims ( inputs [ 0 ] - > dims ( ) ) ; <nl> + vector < int64_t > output_dims ( inputs [ 0 ] - > dims ( ) ) ; <nl> for ( int i = 0 ; i < inputs [ 0 ] - > ndim ( ) ; + + i ) { <nl> if ( i = = canonical_axis & & ! add_axis ) { <nl> continue ; <nl> mmm a / caffe2 / operators / experimental / c10 / cpu / filler_cpu . cc <nl> ppp b / caffe2 / operators / experimental / c10 / cpu / filler_cpu . cc <nl> <nl> using caffe2 : : CPUContext ; <nl> using caffe2 : : Tensor ; <nl> using caffe2 : : TensorCPU ; <nl> - using caffe2 : : TIndex ; <nl> using std : : vector ; <nl> <nl> namespace caffe2 { <nl> void filler_init ( <nl> const std : : vector < int > & extra_shape , <nl> bool input_as_shape ) { <nl> if ( inputs . size ( ) ) { <nl> - auto real_shape = vector < TIndex > { } ; <nl> + auto real_shape = vector < int64_t > { } ; <nl> if ( input_as_shape ) { <nl> / / Shape input must be in CPU context <nl> auto & input = * inputs [ 0 ] ; <nl> void filler_init ( <nl> input . ndim ( ) , <nl> 1 , <nl> " When input_as_shape is true , the input must be a 1D tensor of " <nl> - " data type TIndex " ) ; <nl> - auto * shape_data = input . template data < TIndex > ( ) ; <nl> + " data type int64_t " ) ; <nl> + auto * shape_data = input . template data < int64_t > ( ) ; <nl> real_shape . insert ( <nl> real_shape . end ( ) , shape_data , shape_data + input . dim32 ( 0 ) ) ; <nl> } else { <nl> mmm a / caffe2 / operators / experimental / c10 / cpu / sigmoid_cross_entropy_with_logits_cpu . cc <nl> ppp b / caffe2 / operators / experimental / c10 / cpu / sigmoid_cross_entropy_with_logits_cpu . cc <nl> <nl> # include " caffe2 / utils / math . h " <nl> <nl> using caffe2 : : Tensor ; <nl> - using caffe2 : : TIndex ; <nl> <nl> namespace caffe2 { <nl> namespace { <nl> void sigmoid_cross_entropy_with_logits_op_cpu_impl ( <nl> const auto outer_size = logits . size ( ) / inner_size ; <nl> <nl> if ( logits . ndim ( ) = = 0 ) { <nl> - out - > Resize ( std : : vector < TIndex > { } ) ; <nl> + out - > Resize ( std : : vector < int64_t > { } ) ; <nl> } else { <nl> - std : : vector < TIndex > dims ( logits . dims ( ) . begin ( ) , logits . dims ( ) . end ( ) - 1 ) ; <nl> + std : : vector < int64_t > dims ( logits . dims ( ) . begin ( ) , logits . dims ( ) . end ( ) - 1 ) ; <nl> out - > Resize ( dims ) ; <nl> } <nl> auto * out_ptr = out - > mutable_data < float > ( ) ; <nl> mmm a / caffe2 / operators / experimental / c10 / cpu / sparse_lengths_sum_cpu . cc <nl> ppp b / caffe2 / operators / experimental / c10 / cpu / sparse_lengths_sum_cpu . cc <nl> <nl> # include " caffe2 / utils / math . h " <nl> <nl> using caffe2 : : Tensor ; <nl> - using caffe2 : : TIndex ; <nl> <nl> namespace caffe2 { <nl> namespace { <nl> void sparse_lengths_sum_op_cpu_impl ( <nl> <nl> CAFFE_ENFORCE_EQ ( 1 , indicesInput . ndim ( ) , " INDICES must be a vector " ) ; <nl> CAFFE_ENFORCE_EQ ( 1 , lengthsInput . ndim ( ) , " LENGTHS must be a vector " ) ; <nl> - const TIndex N = dataInput . dim ( 0 ) ; <nl> + const int64_t N = dataInput . dim ( 0 ) ; <nl> const int D = dataInput . size_from_dim ( 1 ) ; <nl> - const TIndex M = lengthsInput . dim ( 0 ) ; <nl> - const TIndex indices_size = indicesInput . size ( ) ; <nl> + const int64_t M = lengthsInput . dim ( 0 ) ; <nl> + const int64_t indices_size = indicesInput . size ( ) ; <nl> <nl> auto shape = dataInput . dims ( ) ; <nl> shape [ 0 ] = M ; <nl> mmm a / caffe2 / operators / experimental / c10 / schemas / fc . h <nl> ppp b / caffe2 / operators / experimental / c10 / schemas / fc . h <nl> struct FullyConnected final { <nl> static constexpr const char * name = " FC " ; <nl> <nl> struct Cache final { <nl> - vector < TIndex > Y_shape_cache_ ; <nl> + vector < int64_t > Y_shape_cache_ ; <nl> Tensor bias_multiplier_ = Tensor { CPU } ; <nl> } ; <nl> <nl> mmm a / caffe2 / operators / extend_tensor_op . cc <nl> ppp b / caffe2 / operators / extend_tensor_op . cc <nl> class ExtendTensorOp final : public Operator < Context > { <nl> indices . template data < int > ( ) , <nl> indices . template data < int > ( ) + indices . size ( ) ) ) ; <nl> <nl> - auto extendSize = ( TIndex ) maxElem - oldSize ; <nl> + auto extendSize = ( int64_t ) maxElem - oldSize ; <nl> if ( extendSize > 0 ) { <nl> new_tensor - > Extend ( extendSize , growthPct_ , & context_ ) ; <nl> if ( ! new_tensor - > meta ( ) . ctor ( ) ) { <nl> mmm a / caffe2 / operators / filler_op . cc <nl> ppp b / caffe2 / operators / filler_op . cc <nl> bool DiagonalFillOp < CPUContext > : : FillWithType ( Tensor * output ) { <nl> math : : Set < T , CPUContext > ( output - > size ( ) , T ( 0 ) , data , & context_ ) ; <nl> / / then calculate step size for diagonal <nl> auto step = GetStepSize ( output ) ; <nl> - for ( TIndex i = 0 ; i < output - > size ( ) ; i + = step ) { <nl> + for ( int64_t i = 0 ; i < output - > size ( ) ; i + = step ) { <nl> math : : Set < T , CPUContext > ( 1 , value , data , & context_ ) ; <nl> data + = step ; <nl> } <nl> mmm a / caffe2 / operators / filler_op . cu <nl> ppp b / caffe2 / operators / filler_op . cu <nl> __global__ void FillRangeKernel ( const int n , float * data ) { <nl> template < typename T > <nl> __global__ void FillDiagonalKernel ( <nl> const int num_diagonal_elements , <nl> - const TIndex step_size , <nl> + const int64_t step_size , <nl> const T value , <nl> T * data ) { <nl> CUDA_1D_KERNEL_LOOP ( index , num_diagonal_elements ) { <nl> bool DiagonalFillOp < CUDAContext > : : FillWithType ( Tensor * output ) { <nl> math : : Set < T , CUDAContext > ( size , T ( 0 ) , data , & context_ ) ; <nl> <nl> T value = OperatorBase : : GetSingleArgument < T > ( " value " , 0 ) ; <nl> - TIndex step_size = GetStepSize ( output ) ; <nl> + int64_t step_size = GetStepSize ( output ) ; <nl> int num_diagonal_elements = ceil ( ( float ) size / step_size ) ; <nl> <nl> FillDiagonalKernel < < < <nl> mmm a / caffe2 / operators / filler_op . h <nl> ppp b / caffe2 / operators / filler_op . h <nl> class FillerOp : public Operator < Context > { <nl> FillerOp ( const OperatorDef & operator_def , Workspace * ws ) <nl> : Operator < Context > ( operator_def , ws ) , <nl> shape_ ( this - > template GetRepeatedArgument < int64_t > ( " shape " ) ) , <nl> - extra_shape_ ( ToVectorTIndex ( <nl> + extra_shape_ ( ToVectorint64_t ( <nl> this - > template GetRepeatedArgument < int > ( " extra_shape " ) ) ) , <nl> input_as_shape_ ( <nl> this - > template GetSingleArgument < bool > ( " input_as_shape " , false ) ) { <nl> class FillerOp : public Operator < Context > { <nl> bool RunOnDevice ( ) override { <nl> auto * output = Operator < Context > : : Output ( 0 ) ; <nl> if ( InputSize ( ) ) { <nl> - auto shape = vector < TIndex > { } ; <nl> + auto shape = vector < int64_t > { } ; <nl> if ( input_as_shape_ ) { <nl> / / Shape input must be in CPU context <nl> auto & input = this - > template Input < Tensor > ( 0 , CPU ) ; <nl> class FillerOp : public Operator < Context > { <nl> input . ndim ( ) , <nl> 1 , <nl> " When input_as_shape is true , the input must be a 1D tensor of " <nl> - " data type TIndex " ) ; <nl> - auto * shape_data = input . template data < TIndex > ( ) ; <nl> + " data type int64_t " ) ; <nl> + auto * shape_data = input . template data < int64_t > ( ) ; <nl> shape . insert ( shape . end ( ) , shape_data , shape_data + input . dim32 ( 0 ) ) ; <nl> } else { <nl> auto & input = Input ( 0 ) ; <nl> class FillerOp : public Operator < Context > { <nl> virtual bool Fill ( Tensor * output ) = 0 ; <nl> <nl> protected : <nl> - vector < TIndex > shape_ ; <nl> - vector < TIndex > extra_shape_ ; <nl> + vector < int64_t > shape_ ; <nl> + vector < int64_t > extra_shape_ ; <nl> bool input_as_shape_ ; <nl> } ; <nl> <nl> class DiagonalFillOp final : public FillerOp < Context > { <nl> CAFFE_ENFORCE ( output - > ndim ( ) > = 2 , " Input shape must be > = 2D " ) ; <nl> } <nl> <nl> - TIndex GetStepSize ( Tensor * output ) { <nl> - TIndex step ; <nl> + int64_t GetStepSize ( Tensor * output ) { <nl> + int64_t step ; <nl> if ( output - > ndim ( ) = = 2 ) { <nl> step = output - > dim ( 1 ) + 1 ; <nl> } else { <nl> - TIndex prev_i = output - > dim ( 0 ) ; <nl> + int64_t prev_i = output - > dim ( 0 ) ; <nl> for ( auto i : output - > dims ( ) ) { <nl> if ( i ! = prev_i ) { <nl> CAFFE_THROW ( " All dimensions of input must be of equal length " ) ; <nl> } <nl> } <nl> - vector < TIndex > cumprod ( output - > ndim ( ) ) ; <nl> + vector < int64_t > cumprod ( output - > ndim ( ) ) ; <nl> auto dims = output - > dims ( ) ; <nl> std : : partial_sum ( <nl> dims . begin ( ) , <nl> dims . end ( ) - 1 , <nl> cumprod . begin ( ) , <nl> - std : : multiplies < TIndex > ( ) ) ; <nl> + std : : multiplies < int64_t > ( ) ) ; <nl> step = 1 + <nl> std : : accumulate ( <nl> - cumprod . begin ( ) , cumprod . end ( ) , static_cast < TIndex > ( 0 ) ) ; <nl> + cumprod . begin ( ) , cumprod . end ( ) , static_cast < int64_t > ( 0 ) ) ; <nl> VLOG ( 0 ) < < step ; <nl> } <nl> return step ; <nl> mmm a / caffe2 / operators / flatten_op . cc <nl> ppp b / caffe2 / operators / flatten_op . cc <nl> OPERATOR_SCHEMA ( Flatten ) <nl> ArgumentHelper helper ( def ) ; <nl> const int axis = helper . GetSingleArgument < int > ( " axis " , 1 ) ; <nl> vector < TensorShape > out ( 1 ) ; <nl> - TIndex outer = 1 ; <nl> - TIndex inner = 1 ; <nl> + int64_t outer = 1 ; <nl> + int64_t inner = 1 ; <nl> std : : size_t index = 0 ; <nl> for ( auto d : in [ 0 ] . dims ( ) ) { <nl> if ( index < axis ) { <nl> mmm a / caffe2 / operators / flexible_top_k . cc <nl> ppp b / caffe2 / operators / flexible_top_k . cc <nl> namespace { <nl> template < typename T > <nl> struct ValueCmp { <nl> bool operator ( ) ( <nl> - const std : : pair < T , TIndex > & lhs , <nl> - const std : : pair < T , TIndex > & rhs ) { <nl> + const std : : pair < T , int64_t > & lhs , <nl> + const std : : pair < T , int64_t > & rhs ) { <nl> return ( <nl> lhs . first > rhs . first | | <nl> ( lhs . first = = rhs . first & & lhs . second < rhs . second ) ) ; <nl> bool FlexibleTopKOp < T , Context > : : RunOnDevice ( ) { <nl> auto * indices = Output ( 1 ) ; <nl> <nl> const T * input_data = input . template data < T > ( ) ; <nl> - const TIndex * k_data = k . template data < TIndex > ( ) ; <nl> + const int64_t * k_data = k . template data < int64_t > ( ) ; <nl> <nl> / / get flatten shape of input <nl> CAFFE_ENFORCE_GT ( input . ndim ( ) , 0 ) ; <nl> - vector < TIndex > input_dims = input . dims ( ) ; <nl> - vector < TIndex > linear_shape = { <nl> + vector < int64_t > input_dims = input . dims ( ) ; <nl> + vector < int64_t > linear_shape = { <nl> size_to_dim_ ( input_dims . size ( ) - 1 , input_dims ) , input_dims . back ( ) } ; <nl> CAFFE_ENFORCE_EQ ( <nl> linear_shape [ 0 ] , <nl> k . size ( ) , <nl> " first n - 1 dims of input data and K does not match . " ) ; <nl> <nl> - TIndex output_size = 0 ; <nl> - for ( TIndex i = 0 ; i < linear_shape [ 0 ] ; + + i ) { <nl> + int64_t output_size = 0 ; <nl> + for ( int64_t i = 0 ; i < linear_shape [ 0 ] ; + + i ) { <nl> CAFFE_ENFORCE ( <nl> linear_shape [ 1 ] > = k_data [ i ] , <nl> " k should not be greater than last dim , error at index " , <nl> bool FlexibleTopKOp < T , Context > : : RunOnDevice ( ) { <nl> values - > Resize ( output_size ) ; <nl> indices - > Resize ( output_size ) ; <nl> T * values_data = values - > template mutable_data < T > ( ) ; <nl> - TIndex * indices_data = indices - > template mutable_data < TIndex > ( ) ; <nl> + int64_t * indices_data = indices - > template mutable_data < int64_t > ( ) ; <nl> <nl> - TIndex output_offset = 0 ; <nl> + int64_t output_offset = 0 ; <nl> / / Sort preserving indices <nl> - for ( TIndex i = 0 ; i < linear_shape [ 0 ] ; + + i ) { <nl> + for ( int64_t i = 0 ; i < linear_shape [ 0 ] ; + + i ) { <nl> / / Build a min - heap , the heap element is pair of ( value , idx ) <nl> / / the top of the heap is the smallest value <nl> std : : priority_queue < <nl> - std : : pair < T , TIndex > , <nl> - std : : vector < std : : pair < T , TIndex > > , <nl> + std : : pair < T , int64_t > , <nl> + std : : vector < std : : pair < T , int64_t > > , <nl> ValueCmp < T > > <nl> PQ ; <nl> <nl> - TIndex k_ = k_data [ i ] ; <nl> - for ( TIndex j = 0 ; j < linear_shape [ 1 ] ; + + j ) { <nl> + int64_t k_ = k_data [ i ] ; <nl> + for ( int64_t j = 0 ; j < linear_shape [ 1 ] ; + + j ) { <nl> const T value = input_data [ i * linear_shape [ 1 ] + j ] ; <nl> if ( PQ . size ( ) < k_ | | value > PQ . top ( ) . first ) { <nl> PQ . push ( std : : make_pair ( value , j ) ) ; <nl> bool FlexibleTopKOp < T , Context > : : RunOnDevice ( ) { <nl> PQ . pop ( ) ; <nl> } <nl> } <nl> - for ( TIndex j = 0 ; j < k_ ; + + j ) { <nl> + for ( int64_t j = 0 ; j < k_ ; + + j ) { <nl> auto & pqElem = PQ . top ( ) ; <nl> values_data [ output_offset + k_ - j - 1 ] = pqElem . first ; <nl> indices_data [ output_offset + k_ - j - 1 ] = pqElem . second ; <nl> bool FlexibleTopKGradientOp < T , Context > : : RunOnDevice ( ) { <nl> auto & indices = Input ( 3 ) ; <nl> auto * output = Output ( 0 ) ; <nl> <nl> - const TIndex * k_data = k . template data < TIndex > ( ) ; <nl> + const int64_t * k_data = k . template data < int64_t > ( ) ; <nl> const T * values_data = values . template data < T > ( ) ; <nl> - const TIndex * indices_data = indices . template data < TIndex > ( ) ; <nl> + const int64_t * indices_data = indices . template data < int64_t > ( ) ; <nl> <nl> / / Resize output tensors to be as orignial_input size and initialized with 0 <nl> CAFFE_ENFORCE_GT ( original_input . ndim ( ) , 0 ) ; <nl> - vector < TIndex > original_dims = original_input . dims ( ) ; <nl> + vector < int64_t > original_dims = original_input . dims ( ) ; <nl> output - > Resize ( original_dims ) ; <nl> T * output_data = output - > template mutable_data < T > ( ) ; <nl> math : : Set < T , Context > ( <nl> output - > size ( ) , static_cast < T > ( 0 ) , output_data , & context_ ) ; <nl> <nl> - TIndex index_offset = 0 ; <nl> - for ( TIndex i = 0 ; i < k . size ( ) ; + + i ) { <nl> + int64_t index_offset = 0 ; <nl> + for ( int64_t i = 0 ; i < k . size ( ) ; + + i ) { <nl> / / offset of output_data <nl> - TIndex output_offset = i * original_dims . back ( ) ; <nl> - for ( TIndex j = 0 ; j < k_data [ i ] ; + + j ) { <nl> - TIndex index = indices_data [ index_offset + j ] ; <nl> + int64_t output_offset = i * original_dims . back ( ) ; <nl> + for ( int64_t j = 0 ; j < k_data [ i ] ; + + j ) { <nl> + int64_t index = indices_data [ index_offset + j ] ; <nl> T value = values_data [ index_offset + j ] ; <nl> output_data [ output_offset + index ] = value ; <nl> } <nl> mmm a / caffe2 / operators / fully_connected_op . h <nl> ppp b / caffe2 / operators / fully_connected_op . h <nl> class FullyConnectedOp final : public Operator < Context > { <nl> size_t axis_w_ { 1 } ; <nl> / / A local vector to cache the output shape so we don ' t need to recreate <nl> / / a vector object every time we run Run ( ) . <nl> - vector < TIndex > Y_shape_cache_ ; <nl> + vector < int64_t > Y_shape_cache_ ; <nl> Tensor bias_multiplier_ { Context : : GetDeviceType ( ) } ; <nl> ; <nl> <nl> mmm a / caffe2 / operators / fused_rowwise_8bit_conversion_ops . h <nl> ppp b / caffe2 / operators / fused_rowwise_8bit_conversion_ops . h <nl> class FloatToFused8BitRowwiseQuantizedOp : public Operator < Context > { <nl> / / bytes of each row for scale ( 4 bytes ) and bias ( 4 bytes ) . <nl> / / | . . . int8 data . . . | scale | bias | <nl> / / | number_of_columns | 4B | 4B | <nl> - const std : : vector < TIndex > output_dimensions = { input_rows , <nl> + const std : : vector < int64_t > output_dimensions = { input_rows , <nl> input_columns + 8 } ; <nl> output - > Resize ( output_dimensions ) ; <nl> <nl> class Fused8BitRowwiseQuantizedToFloatOp : public Operator < Context > { <nl> <nl> / / The last 8 bytes per row are the scale and the bias . The rest of <nl> / / input_columns is the number of values in the original row . <nl> - const std : : vector < TIndex > output_dimensions = { input_rows , <nl> + const std : : vector < int64_t > output_dimensions = { input_rows , <nl> input_columns - 8 } ; <nl> output - > Resize ( output_dimensions ) ; <nl> const auto output_columns = output - > dim ( 1 ) ; <nl> mmm a / caffe2 / operators / fused_rowwise_random_quantization_ops . cc <nl> ppp b / caffe2 / operators / fused_rowwise_random_quantization_ops . cc <nl> bool FloatToFusedRandRowwiseQuantizedOp < Context > : : RunOnDevice ( ) { <nl> size_t data_per_byte = 8 / bitwidth_ ; <nl> / / How many bytes in the output <nl> size_t segment_size = ( input_columns + data_per_byte - 1 ) / data_per_byte ; <nl> - const std : : vector < TIndex > output_dimensions = { <nl> - input_rows , 10 + static_cast < TIndex > ( segment_size ) } ; <nl> + const std : : vector < int64_t > output_dimensions = { <nl> + input_rows , 10 + static_cast < int64_t > ( segment_size ) } ; <nl> output - > Resize ( output_dimensions ) ; <nl> <nl> const auto * input_data = input . template data < float > ( ) ; <nl> bool FusedRandRowwiseQuantizedToFloatOp < Context > : : RunOnDevice ( ) { <nl> " Unsupported bitwidth " ) ; <nl> const size_t tail = input_data [ 1 ] ; <nl> const size_t output_columns = ( input_columns - 10 ) * ( 8 / bitwidth ) - tail ; <nl> - const std : : vector < TIndex > output_dimensions = { <nl> - input_rows , static_cast < TIndex > ( output_columns ) } ; <nl> + const std : : vector < int64_t > output_dimensions = { <nl> + input_rows , static_cast < int64_t > ( output_columns ) } ; <nl> output - > Resize ( output_dimensions ) ; <nl> auto * output_data = output - > template mutable_data < float > ( ) ; <nl> for ( size_t row = 0 ; row < input_rows ; + + row ) { <nl> mmm a / caffe2 / operators / gather_fused_8bit_rowwise_op . h <nl> ppp b / caffe2 / operators / gather_fused_8bit_rowwise_op . h <nl> class GatherFused8BitRowwiseOp : public Operator < Context > { <nl> CAFFE_ENFORCE_GT ( data . dim ( 1 ) , 8 , " DATA must have more than 8 columns " ) ; <nl> / / Subtract 8 from the # columns of data for the 4 bytes for scale and 4 <nl> / / bytes for bias that we use in the fused representation ( per row ) . <nl> - const std : : vector < TIndex > shape = { indices . dim ( 0 ) , data . dim ( 1 ) - 8 } ; <nl> + const std : : vector < int64_t > shape = { indices . dim ( 0 ) , data . dim ( 1 ) - 8 } ; <nl> output - > Resize ( shape ) ; <nl> <nl> int block_size = shape [ 1 ] ; <nl> mmm a / caffe2 / operators / gather_ranges_to_dense_op . h <nl> ppp b / caffe2 / operators / gather_ranges_to_dense_op . h <nl> class GatherRangesToDenseOp final : public Operator < Context > { <nl> auto itemsize = data . meta ( ) . itemsize ( ) ; <nl> <nl> auto batchSize = ranges . dim ( 0 ) ; <nl> - vector < TIndex > outputDims { batchSize , 0 } ; <nl> + vector < int64_t > outputDims { batchSize , 0 } ; <nl> vector < char * > outputRawData ; <nl> for ( int i = 0 ; i < OutputSize ( ) ; + + i ) { <nl> auto * output = Output ( i ) ; <nl> mmm a / caffe2 / operators / generate_proposals_op . cc <nl> ppp b / caffe2 / operators / generate_proposals_op . cc <nl> bool GenerateProposalsOp < CPUContext > : : RunOnDevice ( ) { <nl> / / bbox_deltas : ( num_images , A * box_dim , H , W ) <nl> CAFFE_ENFORCE_EQ ( <nl> bbox_deltas . dims ( ) , <nl> - ( vector < TIndex > { num_images , box_dim * A , height , width } ) ) ; <nl> + ( vector < int64_t > { num_images , box_dim * A , height , width } ) ) ; <nl> <nl> / / im_info_tensor : ( num_images , 3 ) , format [ height , width , scale ; . . . ] <nl> - CAFFE_ENFORCE_EQ ( im_info_tensor . dims ( ) , ( vector < TIndex > { num_images , 3 } ) ) ; <nl> + CAFFE_ENFORCE_EQ ( im_info_tensor . dims ( ) , ( vector < int64_t > { num_images , 3 } ) ) ; <nl> CAFFE_ENFORCE ( <nl> im_info_tensor . template IsType < float > ( ) , im_info_tensor . meta ( ) . name ( ) ) ; <nl> <nl> / / anchors : ( A , box_dim ) <nl> - CAFFE_ENFORCE_EQ ( anchors . dims ( ) , ( vector < TIndex > { A , box_dim } ) ) ; <nl> + CAFFE_ENFORCE_EQ ( anchors . dims ( ) , ( vector < int64_t > { A , box_dim } ) ) ; <nl> CAFFE_ENFORCE ( anchors . template IsType < float > ( ) , anchors . meta ( ) . name ( ) ) ; <nl> <nl> / / Broadcast the anchors to all pixels <nl> mmm a / caffe2 / operators / generate_proposals_op_test . cc <nl> ppp b / caffe2 / operators / generate_proposals_op_test . cc <nl> <nl> namespace caffe2 { <nl> <nl> static void AddConstInput ( <nl> - const vector < TIndex > & shape , <nl> + const vector < int64_t > & shape , <nl> const float value , <nl> const string & name , <nl> Workspace * ws ) { <nl> static void AddConstInput ( <nl> } <nl> <nl> static void AddLinSpacedInput ( <nl> - const vector < TIndex > & shape , <nl> + const vector < int64_t > & shape , <nl> const float min_val , <nl> const float max_val , <nl> const string & name , <nl> static void AddLinSpacedInput ( <nl> } <nl> <nl> static void AddInput ( <nl> - const vector < TIndex > & shape , <nl> + const vector < int64_t > & shape , <nl> const vector < float > & values , <nl> const string & name , <nl> Workspace * ws ) { <nl> TEST ( GenerateProposalsTest , TestComputeAllAnchors ) { <nl> 79 , - 68 , 8 , 115 , 103 , - 160 , - 40 , 207 , 151 , - 6 , 32 , 85 , 79 , - 52 , 8 , 131 , <nl> 103 , - 144 , - 40 , 223 , 151 ; <nl> <nl> - Tensor anchors_tensor ( vector < TIndex > { anchors . rows ( ) , anchors . cols ( ) } , CPU ) ; <nl> + Tensor anchors_tensor ( vector < int64_t > { anchors . rows ( ) , anchors . cols ( ) } , CPU ) ; <nl> Eigen : : Map < ERMatXf > ( <nl> anchors_tensor . mutable_data < float > ( ) , anchors . rows ( ) , anchors . cols ( ) ) = <nl> anchors ; <nl> TEST ( GenerateProposalsTest , TestComputeAllAnchorsRotated ) { <nl> all_anchors_gt ( i , 4 ) = angles [ i % angles . size ( ) ] ; <nl> } <nl> <nl> - Tensor anchors_tensor ( vector < TIndex > { anchors . rows ( ) , anchors . cols ( ) } , CPU ) ; <nl> + Tensor anchors_tensor ( vector < int64_t > { anchors . rows ( ) , anchors . cols ( ) } , CPU ) ; <nl> Eigen : : Map < ERMatXf > ( <nl> anchors_tensor . mutable_data < float > ( ) , anchors . rows ( ) , anchors . cols ( ) ) = <nl> anchors ; <nl> TEST ( GenerateProposalsTest , TestEmpty ) { <nl> const int A = 4 ; <nl> const int H = 10 ; <nl> const int W = 8 ; <nl> - AddConstInput ( vector < TIndex > { img_count , A , H , W } , 1 . , " scores " , & ws ) ; <nl> + AddConstInput ( vector < int64_t > { img_count , A , H , W } , 1 . , " scores " , & ws ) ; <nl> AddLinSpacedInput ( <nl> - vector < TIndex > { img_count , 4 * A , H , W } , 0 , 10 , " bbox_deltas " , & ws ) ; <nl> - AddConstInput ( vector < TIndex > { img_count , 3 } , 0 . 1 , " im_info " , & ws ) ; <nl> - AddConstInput ( vector < TIndex > { A , 4 } , 1 . 0 , " anchors " , & ws ) ; <nl> + vector < int64_t > { img_count , 4 * A , H , W } , 0 , 10 , " bbox_deltas " , & ws ) ; <nl> + AddConstInput ( vector < int64_t > { img_count , 3 } , 0 . 1 , " im_info " , & ws ) ; <nl> + AddConstInput ( vector < int64_t > { A , 4 } , 1 . 0 , " anchors " , & ws ) ; <nl> <nl> def . add_arg ( ) - > CopyFrom ( MakeArgument ( " spatial_scale " , 2 . 0f ) ) ; <nl> <nl> TEST ( GenerateProposalsTest , TestRealDownSampled ) { <nl> 1 . 50015003e - 05f , <nl> 8 . 91025957e - 06f } ; <nl> <nl> - AddInput ( vector < TIndex > { img_count , A , H , W } , scores , " scores " , & ws ) ; <nl> - AddInput ( vector < TIndex > { img_count , 4 * A , H , W } , bbx , " bbox_deltas " , & ws ) ; <nl> - AddInput ( vector < TIndex > { img_count , 3 } , im_info , " im_info " , & ws ) ; <nl> - AddInput ( vector < TIndex > { A , 4 } , anchors , " anchors " , & ws ) ; <nl> + AddInput ( vector < int64_t > { img_count , A , H , W } , scores , " scores " , & ws ) ; <nl> + AddInput ( vector < int64_t > { img_count , 4 * A , H , W } , bbx , " bbox_deltas " , & ws ) ; <nl> + AddInput ( vector < int64_t > { img_count , 3 } , im_info , " im_info " , & ws ) ; <nl> + AddInput ( vector < int64_t > { A , 4 } , anchors , " anchors " , & ws ) ; <nl> <nl> def . add_arg ( ) - > CopyFrom ( MakeArgument ( " spatial_scale " , 1 . 0f / 16 . 0f ) ) ; <nl> def . add_arg ( ) - > CopyFrom ( MakeArgument ( " pre_nms_topN " , 6000 ) ) ; <nl> TEST ( GenerateProposalsTest , TestRealDownSampled ) { <nl> Blob * rois_blob = ws . GetBlob ( " rois " ) ; <nl> EXPECT_NE ( nullptr , rois_blob ) ; <nl> auto & rois = rois_blob - > Get < TensorCPU > ( ) ; <nl> - EXPECT_EQ ( rois . dims ( ) , ( vector < TIndex > { rois_gt . rows ( ) , rois_gt . cols ( ) } ) ) ; <nl> + EXPECT_EQ ( rois . dims ( ) , ( vector < int64_t > { rois_gt . rows ( ) , rois_gt . cols ( ) } ) ) ; <nl> auto rois_data = <nl> Eigen : : Map < const ERMatXf > ( rois . data < float > ( ) , rois . dim ( 0 ) , rois . dim ( 1 ) ) ; <nl> EXPECT_NEAR ( ( rois_data . matrix ( ) - rois_gt ) . cwiseAbs ( ) . maxCoeff ( ) , 0 , 1e - 4 ) ; <nl> TEST ( GenerateProposalsTest , TestRealDownSampled ) { <nl> Blob * rois_probs_blob = ws . GetBlob ( " rois_probs " ) ; <nl> EXPECT_NE ( nullptr , rois_probs_blob ) ; <nl> auto & rois_probs = rois_probs_blob - > Get < TensorCPU > ( ) ; <nl> - EXPECT_EQ ( rois_probs . dims ( ) , ( vector < TIndex > { TIndex ( rois_probs_gt . size ( ) ) } ) ) ; <nl> + EXPECT_EQ ( rois_probs . dims ( ) , ( vector < int64_t > { int64_t ( rois_probs_gt . size ( ) ) } ) ) ; <nl> auto rois_probs_data = <nl> ConstEigenVectorArrayMap < float > ( rois_probs . data < float > ( ) , rois . dim ( 0 ) ) ; <nl> EXPECT_NEAR ( <nl> TEST ( GenerateProposalsTest , TestRealDownSampledRotatedAngle0 ) { <nl> 1 . 50015003e - 05f , <nl> 8 . 91025957e - 06f } ; <nl> <nl> - AddInput ( vector < TIndex > { img_count , A , H , W } , scores , " scores " , & ws ) ; <nl> + AddInput ( vector < int64_t > { img_count , A , H , W } , scores , " scores " , & ws ) ; <nl> AddInput ( <nl> - vector < TIndex > { img_count , 5 * A , H , W } , <nl> + vector < int64_t > { img_count , 5 * A , H , W } , <nl> bbx_with_angle , <nl> " bbox_deltas " , <nl> & ws ) ; <nl> - AddInput ( vector < TIndex > { img_count , 3 } , im_info , " im_info " , & ws ) ; <nl> - AddInput ( vector < TIndex > { A , 5 } , anchors , " anchors " , & ws ) ; <nl> + AddInput ( vector < int64_t > { img_count , 3 } , im_info , " im_info " , & ws ) ; <nl> + AddInput ( vector < int64_t > { A , 5 } , anchors , " anchors " , & ws ) ; <nl> <nl> def . add_arg ( ) - > CopyFrom ( MakeArgument ( " spatial_scale " , 1 . 0f / 16 . 0f ) ) ; <nl> def . add_arg ( ) - > CopyFrom ( MakeArgument ( " pre_nms_topN " , 6000 ) ) ; <nl> TEST ( GenerateProposalsTest , TestRealDownSampledRotatedAngle0 ) { <nl> Blob * rois_blob = ws . GetBlob ( " rois " ) ; <nl> EXPECT_NE ( nullptr , rois_blob ) ; <nl> auto & rois = rois_blob - > Get < TensorCPU > ( ) ; <nl> - EXPECT_EQ ( rois . dims ( ) , ( vector < TIndex > { rois_gt . rows ( ) , rois_gt . cols ( ) } ) ) ; <nl> + EXPECT_EQ ( rois . dims ( ) , ( vector < int64_t > { rois_gt . rows ( ) , rois_gt . cols ( ) } ) ) ; <nl> auto rois_data = <nl> Eigen : : Map < const ERMatXf > ( rois . data < float > ( ) , rois . dim ( 0 ) , rois . dim ( 1 ) ) ; <nl> EXPECT_NEAR ( ( rois_data . matrix ( ) - rois_gt ) . cwiseAbs ( ) . maxCoeff ( ) , 0 , 1e - 3 ) ; <nl> TEST ( GenerateProposalsTest , TestRealDownSampledRotatedAngle0 ) { <nl> Blob * rois_probs_blob = ws . GetBlob ( " rois_probs " ) ; <nl> EXPECT_NE ( nullptr , rois_probs_blob ) ; <nl> auto & rois_probs = rois_probs_blob - > Get < TensorCPU > ( ) ; <nl> - EXPECT_EQ ( rois_probs . dims ( ) , ( vector < TIndex > { TIndex ( rois_probs_gt . size ( ) ) } ) ) ; <nl> + EXPECT_EQ ( rois_probs . dims ( ) , ( vector < int64_t > { int64_t ( rois_probs_gt . size ( ) ) } ) ) ; <nl> auto rois_probs_data = <nl> ConstEigenVectorArrayMap < float > ( rois_probs . data < float > ( ) , rois . dim ( 0 ) ) ; <nl> EXPECT_NEAR ( <nl> TEST ( GenerateProposalsTest , TestRealDownSampledRotated ) { <nl> / / vector < float > anchors { - 38 , - 16 , 53 , 31 , - 120 , - 120 , 135 , 135 } ; <nl> vector < float > anchors { 8 , 8 , 92 , 48 , angle , 8 , 8 , 256 , 256 , angle } ; <nl> <nl> - AddInput ( vector < TIndex > { img_count , A , H , W } , scores , " scores " , & ws ) ; <nl> + AddInput ( vector < int64_t > { img_count , A , H , W } , scores , " scores " , & ws ) ; <nl> AddInput ( <nl> - vector < TIndex > { img_count , 5 * A , H , W } , <nl> + vector < int64_t > { img_count , 5 * A , H , W } , <nl> bbx_with_angle , <nl> " bbox_deltas " , <nl> & ws ) ; <nl> - AddInput ( vector < TIndex > { img_count , 3 } , im_info , " im_info " , & ws ) ; <nl> - AddInput ( vector < TIndex > { A , 5 } , anchors , " anchors " , & ws ) ; <nl> + AddInput ( vector < int64_t > { img_count , 3 } , im_info , " im_info " , & ws ) ; <nl> + AddInput ( vector < int64_t > { A , 5 } , anchors , " anchors " , & ws ) ; <nl> <nl> def . add_arg ( ) - > CopyFrom ( MakeArgument ( " spatial_scale " , 1 . 0f / 16 . 0f ) ) ; <nl> def . add_arg ( ) - > CopyFrom ( MakeArgument ( " pre_nms_topN " , 6000 ) ) ; <nl> mmm a / caffe2 / operators / glu_op . h <nl> ppp b / caffe2 / operators / glu_op . h <nl> class GluOp final : public Operator < Context > { <nl> bool RunOnDevice ( ) { <nl> auto & X = Input ( 0 ) ; <nl> auto * Y = Output ( 0 ) ; <nl> - vector < TIndex > Yshape ; <nl> + vector < int64_t > Yshape ; <nl> Yshape . insert ( Yshape . end ( ) , X . dims ( ) . begin ( ) , X . dims ( ) . end ( ) ) ; <nl> const int split_index = dim_ = = - 1 ? Yshape . size ( ) - 1 : dim_ ; <nl> CAFFE_ENFORCE ( <nl> mmm a / caffe2 / operators / half_float_ops . h <nl> ppp b / caffe2 / operators / half_float_ops . h <nl> class Float16ConstantFillOp : public Operator < CPUContext > { <nl> bool RunOnDevice ( ) override ; <nl> <nl> private : <nl> - vector < TIndex > shape_ ; <nl> + vector < int64_t > shape_ ; <nl> } ; <nl> <nl> class Float16UniformFillOp : public Operator < CPUContext > { <nl> class Float16UniformFillOp : public Operator < CPUContext > { <nl> bool RunOnDevice ( ) override ; <nl> <nl> private : <nl> - vector < TIndex > shape_ ; <nl> + vector < int64_t > shape_ ; <nl> float min_ ; <nl> float max_ ; <nl> } ; <nl> mmm a / caffe2 / operators / hip / local_response_normalization_op_miopen . cc <nl> ppp b / caffe2 / operators / hip / local_response_normalization_op_miopen . cc <nl> class MIOPEN_LRNOP final : public Operator < HIPContext > { <nl> MIOPENWrapper miopen_wrapper_ ; <nl> miopenTensorDescriptor_t data_desc_ ; <nl> miopenLRNDescriptor_t norm_desc_ ; <nl> - vector < TIndex > miopen_input_dims_ ; <nl> + vector < int64_t > miopen_input_dims_ ; <nl> const miopenLRNMode_t mode_ ; <nl> const int size_ ; <nl> const float alpha_ ; <nl> class MIOPENLRNGradientOp final : public Operator < HIPContext > { <nl> MIOPENWrapper miopen_wrapper_ ; <nl> miopenTensorDescriptor_t data_desc_ ; <nl> miopenLRNDescriptor_t norm_desc_ ; <nl> - vector < TIndex > miopen_input_dims_ ; <nl> + vector < int64_t > miopen_input_dims_ ; <nl> const miopenLRNMode_t mode_ ; <nl> const int size_ ; <nl> const float alpha_ ; <nl> mmm a / caffe2 / operators / hip / relu_op_miopen . cc <nl> ppp b / caffe2 / operators / hip / relu_op_miopen . cc <nl> class MIOPENReluOp final : public Operator < HIPContext > { <nl> MIOPENWrapper miopen_wrapper_ ; <nl> miopenTensorDescriptor_t data_desc_ ; <nl> miopenActivationDescriptor_t activ_desc_ ; <nl> - vector < TIndex > miopen_input_dims_ ; <nl> + vector < int64_t > miopen_input_dims_ ; <nl> const float alpha_ ; <nl> const float beta_ ; <nl> const double power_ ; <nl> class MIOPENReluGradientOp final : public Operator < HIPContext > { <nl> MIOPENWrapper miopen_wrapper_ ; <nl> miopenTensorDescriptor_t data_desc_ ; <nl> miopenActivationDescriptor_t activ_desc_ ; <nl> - vector < TIndex > miopen_input_dims_ ; <nl> + vector < int64_t > miopen_input_dims_ ; <nl> const float alpha_ ; <nl> const float beta_ ; <nl> const double power_ ; <nl> mmm a / caffe2 / operators / hip / softmax_op_miopen . cc <nl> ppp b / caffe2 / operators / hip / softmax_op_miopen . cc <nl> class MIOpenSoftmaxOp final : public Operator < HIPContext > { <nl> protected : <nl> MIOPENWrapper miopen_wrapper_ ; <nl> miopenTensorDescriptor_t desc_ ; <nl> - vector < TIndex > dims_ ; <nl> + vector < int64_t > dims_ ; <nl> const int axis_ ; <nl> const float alpha_ ; <nl> const float beta_ ; <nl> class MIOpenSoftmaxGradientOp final : public Operator < HIPContext > { <nl> const float alpha_ ; <nl> const float beta_ ; <nl> miopenTensorDescriptor_t desc_ ; <nl> - vector < TIndex > dims_ ; <nl> + vector < int64_t > dims_ ; <nl> } ; <nl> <nl> namespace { <nl> mmm a / caffe2 / operators / hip / spatial_batch_norm_op_miopen . cc <nl> ppp b / caffe2 / operators / hip / spatial_batch_norm_op_miopen . cc <nl> class MIOpenSpatialBNOp final : public SpatialBNOp < HIPContext > { <nl> MIOPENWrapper miopen_wrapper_ ; <nl> miopenTensorDescriptor_t data_desc_ ; <nl> miopenTensorDescriptor_t bn_param_desc_ ; <nl> - vector < TIndex > miopen_input_dims_ ; <nl> + vector < int64_t > miopen_input_dims_ ; <nl> float alpha_ ; <nl> float beta_ ; <nl> miopenBatchNormMode_t mode_ ; <nl> class MIOpenSpatialBNGradientOp final : public SpatialBNGradientOp < HIPContext > { <nl> MIOPENWrapper miopen_wrapper_ ; <nl> miopenTensorDescriptor_t data_desc_ ; <nl> miopenTensorDescriptor_t bn_param_desc_ ; <nl> - vector < TIndex > miopen_input_dims_ ; <nl> + vector < int64_t > miopen_input_dims_ ; <nl> float alpha_ ; <nl> float beta_ ; <nl> miopenBatchNormMode_t mode_ ; <nl> mmm a / caffe2 / operators / im2col_op . h <nl> ppp b / caffe2 / operators / im2col_op . h <nl> class Im2ColOp final : public Operator < Context > { <nl> switch ( order_ ) { <nl> case StorageOrder : : NCHW : { <nl> Y - > Resize ( <nl> - std : : vector < TIndex > { N , C * kernel_h_ * kernel_w_ , out_h , out_w } ) ; <nl> + std : : vector < int64_t > { N , C * kernel_h_ * kernel_w_ , out_h , out_w } ) ; <nl> <nl> const size_t dx = X . size ( ) / N ; <nl> const size_t dy = Y - > size ( ) / N ; <nl> class Im2ColOp final : public Operator < Context > { <nl> } ; break ; <nl> case StorageOrder : : NHWC : { <nl> Y - > Resize ( <nl> - std : : vector < TIndex > { N , out_h , out_w , kernel_h_ * kernel_w_ * C } ) ; <nl> + std : : vector < int64_t > { N , out_h , out_w , kernel_h_ * kernel_w_ * C } ) ; <nl> <nl> const size_t dx = X . size ( ) / N ; <nl> const size_t dy = Y - > size ( ) / N ; <nl> mmm a / caffe2 / operators / index_hash_ops . cc <nl> ppp b / caffe2 / operators / index_hash_ops . cc <nl> specified number . All input and output indices are enforced to be positive . <nl> . TensorInferenceFunction ( [ ] ( const OperatorDef & / * unused * / , <nl> const vector < TensorShape > & in ) { <nl> std : : vector < TensorShape > out ( 1 ) ; <nl> - std : : vector < TIndex > output_dims = GetDimsVector ( in [ 0 ] ) ; <nl> + std : : vector < int64_t > output_dims = GetDimsVector ( in [ 0 ] ) ; <nl> out [ 0 ] = CreateTensorShape ( output_dims , in [ 0 ] . data_type ( ) ) ; <nl> return out ; <nl> } ) ; <nl> mmm a / caffe2 / operators / index_ops . cc <nl> ppp b / caffe2 / operators / index_ops . cc <nl> <nl> namespace caffe2 { <nl> namespace { <nl> using IndexKeyTypes = TensorTypes < int32_t , int64_t , std : : string > ; <nl> - using TIndexValue = int64_t ; <nl> + using int64_tValue = int64_t ; <nl> } / / namespace <nl> <nl> struct IndexBase { <nl> public : <nl> - IndexBase ( TIndexValue maxElements , const TypeMeta & type ) <nl> + IndexBase ( int64_tValue maxElements , const TypeMeta & type ) <nl> : maxElements_ { maxElements } <nl> , meta_ ( type ) <nl> , frozen_ { false } { } <nl> struct IndexBase { <nl> <nl> const TypeMeta & Type ( ) const { return meta_ ; } <nl> <nl> - TIndexValue Size ( ) { <nl> + int64_tValue Size ( ) { <nl> std : : lock_guard < std : : mutex > guard ( dictMutex_ ) ; <nl> return nextId_ ; <nl> } <nl> struct IndexBase { <nl> protected : <nl> int64_t maxElements_ ; <nl> TypeMeta meta_ ; <nl> - TIndexValue nextId_ { 1 } ; / / guarded by dictMutex_ <nl> + int64_tValue nextId_ { 1 } ; / / guarded by dictMutex_ <nl> std : : atomic < bool > frozen_ { false } ; <nl> std : : mutex dictMutex_ ; <nl> } ; <nl> <nl> template < typename T > <nl> struct Index : IndexBase { <nl> - explicit Index ( TIndexValue maxElements ) <nl> + explicit Index ( int64_tValue maxElements ) <nl> : IndexBase ( maxElements , TypeMeta : : Make < T > ( ) ) { } <nl> <nl> - void Get ( const T * keys , TIndexValue * values , size_t numKeys ) { <nl> + void Get ( const T * keys , int64_tValue * values , size_t numKeys ) { <nl> if ( frozen_ ) { <nl> FrozenGet ( keys , values , numKeys ) ; <nl> return ; <nl> struct Index : IndexBase { <nl> } <nl> <nl> private : <nl> - void FrozenGet ( const T * keys , TIndexValue * values , size_t numKeys ) { <nl> + void FrozenGet ( const T * keys , int64_tValue * values , size_t numKeys ) { <nl> for ( int i = 0 ; i < numKeys ; + + i ) { <nl> auto it = dict_ . find ( keys [ i ] ) ; <nl> values [ i ] = it ! = dict_ . end ( ) ? it - > second : 0 ; <nl> } <nl> } <nl> <nl> - std : : unordered_map < T , TIndexValue > dict_ ; <nl> + std : : unordered_map < T , int64_tValue > dict_ ; <nl> } ; <nl> <nl> / / TODO ( azzolini ) : support sizes larger than int32 <nl> class IndexCreateOp : public Operator < CPUContext > { <nl> } <nl> <nl> private : <nl> - TIndexValue maxElements_ ; <nl> + int64_tValue maxElements_ ; <nl> } ; <nl> <nl> class IndexGetOp : public Operator < CPUContext > { <nl> class IndexGetOp : public Operator < CPUContext > { <nl> values - > ResizeLike ( keys ) ; <nl> dict - > Get ( <nl> keys . data < T > ( ) , <nl> - values - > template mutable_data < TIndexValue > ( ) , <nl> + values - > template mutable_data < int64_tValue > ( ) , <nl> keys . size ( ) ) ; <nl> return true ; <nl> } <nl> class IndexSizeOp : public Operator < CPUContext > { <nl> bool RunOnDevice ( ) override { <nl> auto & base = OperatorBase : : Input < std : : unique_ptr < IndexBase > > ( 0 ) ; <nl> auto * out = Output ( 0 ) ; <nl> - out - > Resize ( std : : vector < TIndex > { } ) ; <nl> - * out - > template mutable_data < TIndexValue > ( ) = base - > Size ( ) ; <nl> + out - > Resize ( std : : vector < int64_t > { } ) ; <nl> + * out - > template mutable_data < int64_tValue > ( ) = base - > Size ( ) ; <nl> return true ; <nl> } <nl> } ; <nl> mmm a / caffe2 / operators / integral_image_op . cc <nl> ppp b / caffe2 / operators / integral_image_op . cc <nl> bool IntegralImageOp < float , CPUContext > : : RunOnDevice ( ) { <nl> auto * Y = Output ( 0 ) ; <nl> CAFFE_ENFORCE_EQ ( X . ndim ( ) , 4 , " Only supports 4D tensors for the momement " ) ; <nl> <nl> - vector < TIndex > out_shape ( X . dims ( ) ) ; <nl> + vector < int64_t > out_shape ( X . dims ( ) ) ; <nl> out_shape [ 2 ] + = 1 ; / / H + 1 output size <nl> out_shape [ 3 ] + = 1 ; / / W + 1 output size <nl> Y - > Resize ( out_shape ) ; <nl> mmm a / caffe2 / operators / integral_image_op . cu <nl> ppp b / caffe2 / operators / integral_image_op . cu <nl> bool IntegralImageOp < float , CUDAContext > : : RunOnDevice ( ) { <nl> <nl> / / Input is ( N , C , H , W ) <nl> / / Output is ( N , C , H + 1 , W + 1 ) <nl> - vector < TIndex > out_shape ( X . dims ( ) ) ; <nl> + vector < int64_t > out_shape ( X . dims ( ) ) ; <nl> out_shape [ 2 ] + = 1 ; / / H + 1 output size <nl> out_shape [ 3 ] + = 1 ; / / W + 1 output size <nl> Y - > Resize ( out_shape ) ; <nl> bool IntegralImageGradientOp < float , CUDAContext > : : RunOnDevice ( ) { <nl> / / Row pass reduces shape of dY from ( N , C , H + 1 , W + 1 ) <nl> / / to ( N , C , H + 1 , W ) <nl> / / Col pass reduces shape to ( N , C , H , W ) <nl> - vector < TIndex > row_pass_shape ( dY . dims ( ) ) ; <nl> + vector < int64_t > row_pass_shape ( dY . dims ( ) ) ; <nl> row_pass_shape [ 3 ] - = 1 ; <nl> row_pass_buffer_ . Resize ( row_pass_shape ) ; <nl> const int chans = row_pass_buffer_ . dim32 ( 1 ) ; <nl> mmm a / caffe2 / operators / is_empty_op . h <nl> ppp b / caffe2 / operators / is_empty_op . h <nl> class IsEmptyOp : public Operator < Context > { <nl> bool RunOnDevice ( ) override { <nl> auto & input = Input ( 0 ) ; <nl> auto * output = Output ( 0 ) ; <nl> - output - > Resize ( std : : vector < TIndex > { } ) ; <nl> + output - > Resize ( std : : vector < int64_t > { } ) ; <nl> * output - > template mutable_data < bool > ( ) = ( input . size ( ) = = 0 ) ; <nl> return true ; <nl> } <nl> mmm a / caffe2 / operators / layer_norm_op . cc <nl> ppp b / caffe2 / operators / layer_norm_op . cc <nl> bool LayerNormOp < CPUContext > : : DoRunWithType < float > ( ) { <nl> const int right = input . size_from_dim ( canonical_axis ) ; <nl> <nl> output - > ResizeLike ( input ) ; <nl> - std : : vector < TIndex > stats_dims ( <nl> + std : : vector < int64_t > stats_dims ( <nl> input . dims ( ) . begin ( ) , input . dims ( ) . begin ( ) + canonical_axis ) ; <nl> stats_dims . push_back ( 1 ) ; <nl> mean - > Resize ( stats_dims ) ; <nl> mmm a / caffe2 / operators / layer_norm_op . cu <nl> ppp b / caffe2 / operators / layer_norm_op . cu <nl> bool LayerNormOp < CUDAContext > : : DoRunWithType < float > ( ) { <nl> const int right = input . size_from_dim ( canonical_axis ) ; <nl> <nl> output - > ResizeLike ( input ) ; <nl> - std : : vector < TIndex > stats_dims ( <nl> + std : : vector < int64_t > stats_dims ( <nl> input . dims ( ) . begin ( ) , input . dims ( ) . begin ( ) + canonical_axis ) ; <nl> stats_dims . push_back ( 1 ) ; <nl> mean - > Resize ( stats_dims ) ; <nl> bool LayerNormGradientOp < CUDAContext > : : DoRunWithType < float > ( ) { <nl> const unsigned long right = norm_inputs . size_from_dim ( canonical_axis ) ; <nl> <nl> ginput - > ResizeLike ( norm_inputs ) ; <nl> - std : : vector < TIndex > stats_dims ( <nl> + std : : vector < int64_t > stats_dims ( <nl> norm_inputs . dims ( ) . begin ( ) , norm_inputs . dims ( ) . begin ( ) + canonical_axis ) ; <nl> stats_dims . push_back ( 1 ) ; <nl> dmean_ . Resize ( stats_dims ) ; <nl> mmm a / caffe2 / operators / lengths_pad_op . h <nl> ppp b / caffe2 / operators / lengths_pad_op . h <nl> class LengthsPadOp : public Operator < Context > { <nl> <nl> math : : Set ( <nl> output - > size ( ) , static_cast < T > ( padding_value_ ) , out_data , & context_ ) ; <nl> - for ( TIndex i = 0 ; i < lengths_size ; + + i ) { <nl> + for ( int64_t i = 0 ; i < lengths_size ; + + i ) { <nl> auto length = lengths_data [ i ] ; <nl> CAFFE_ENFORCE_GE ( length , 0 ) ; <nl> CAFFE_ENFORCE_GE ( <nl> mmm a / caffe2 / operators / lengths_reducer_fused_8bit_rowwise_ops . h <nl> ppp b / caffe2 / operators / lengths_reducer_fused_8bit_rowwise_ops . h <nl> class SparseLengthsFused8BitRowwiseOp : public Operator < Context > { <nl> CAFFE_ENFORCE_GT ( data . dim ( 1 ) , 8 , " DATA must have more than 8 columns " ) ; <nl> / / Subtract 8 from the # columns of data for the 4 bytes for scale and 4 <nl> / / bytes for bias that we use in the fused representation ( per row ) . <nl> - const std : : vector < TIndex > shape = { lengths . dim ( 0 ) , data . dim ( 1 ) - 8 } ; <nl> + const std : : vector < int64_t > shape = { lengths . dim ( 0 ) , data . dim ( 1 ) - 8 } ; <nl> output - > Resize ( shape ) ; <nl> <nl> Fused8BitRowwiseEmbeddingLookup ( <nl> mmm a / caffe2 / operators / lengths_reducer_ops . h <nl> ppp b / caffe2 / operators / lengths_reducer_ops . h <nl> class CPUSparseLengthsReductionOp : public Operator < CPUContext > { <nl> <nl> CAFFE_ENFORCE_EQ ( 1 , indicesInput . ndim ( ) , " INDICES must be a vector " ) ; <nl> CAFFE_ENFORCE_EQ ( 1 , lengthsInput . ndim ( ) , " LENGTHS must be a vector " ) ; <nl> - const TIndex N = dataInput . dim ( 0 ) ; <nl> + const int64_t N = dataInput . dim ( 0 ) ; <nl> const int D = dataInput . size_from_dim ( 1 ) ; <nl> - const TIndex M = lengthsInput . dim ( 0 ) ; <nl> - const TIndex indices_size = indicesInput . size ( ) ; <nl> + const int64_t M = lengthsInput . dim ( 0 ) ; <nl> + const int64_t indices_size = indicesInput . size ( ) ; <nl> <nl> auto * output = Output ( 0 ) ; <nl> auto shape = dataInput . dims ( ) ; <nl> mmm a / caffe2 / operators / lengths_reducer_rowwise_8bit_ops . h <nl> ppp b / caffe2 / operators / lengths_reducer_rowwise_8bit_ops . h <nl> class SparseLengths8BitsRowwiseOp : public Operator < Context > { <nl> auto * output = Output ( 0 ) ; <nl> auto * scale_bias = Input ( SCALE_BIAS ) . template data < float > ( ) ; <nl> CAFFE_ENFORCE_EQ ( 1 , lengthsInput . ndim ( ) , " LENGTHS must be a vector " ) ; <nl> - const TIndex outputSize = lengthsInput . dim ( 0 ) ; <nl> + const int64_t outputSize = lengthsInput . dim ( 0 ) ; <nl> <nl> auto & indicesInput = Input ( INDICES ) ; <nl> CAFFE_ENFORCE_EQ ( <nl> class SparseLengths8BitsRowwiseOp : public Operator < Context > { <nl> " the second dim of scale_bias has to be equal to 2 " ) ; <nl> CAFFE_ENFORCE_EQ ( 1 , indicesInput . ndim ( ) , " INDICES must be a vector " ) ; <nl> const IndexType * indices = indicesInput . template data < IndexType > ( ) ; <nl> - TIndex dataToReduceSize = indicesInput . dim ( 0 ) ; <nl> + int64_t dataToReduceSize = indicesInput . dim ( 0 ) ; <nl> <nl> const int * lengths = lengthsInput . template data < int > ( ) ; <nl> - vector < TIndex > shape = dataInput . dims ( ) ; <nl> + vector < int64_t > shape = dataInput . dims ( ) ; <nl> shape [ 0 ] = outputSize ; <nl> output - > Resize ( shape ) ; <nl> const float * w = nullptr ; <nl> if ( USE_WEIGHTS ) { <nl> w = Input ( WEIGHTS ) . template data < float > ( ) ; <nl> } <nl> - TIndex in_block_size = dataInput . size_from_dim ( 1 ) ; <nl> + int64_t in_block_size = dataInput . size_from_dim ( 1 ) ; <nl> OutDataT * out = output - > template mutable_data < OutDataT > ( ) ; <nl> const uint8_t * input_data = dataInput . template data < uint8_t > ( ) ; <nl> <nl> / / delegate work to perfkernel that branches based on architecture <nl> - const TIndex indices_size = indicesInput . size ( ) ; <nl> - const TIndex N = dataInput . dim ( 0 ) ; <nl> + const int64_t indices_size = indicesInput . size ( ) ; <nl> + const int64_t N = dataInput . dim ( 0 ) ; <nl> EmbeddingLookup ( <nl> in_block_size , <nl> outputSize , <nl> class FloatToRowwiseQuantized8BitsOp : public Operator < Context > { <nl> auto * scale_bias = Output ( SCALE_BIAS ) ; <nl> auto * input_data = input . template data < float > ( ) ; <nl> output - > ResizeLike ( input ) ; <nl> - vector < TIndex > scale_bias_dims = { input . dim ( 0 ) , 2 } ; <nl> + vector < int64_t > scale_bias_dims = { input . dim ( 0 ) , 2 } ; <nl> scale_bias - > Resize ( scale_bias_dims ) ; <nl> auto * output_data = output - > template mutable_data < uint8_t > ( ) ; <nl> float * scale_bias_data = scale_bias - > template mutable_data < float > ( ) ; <nl> mmm a / caffe2 / operators / lengths_tile_op . cc <nl> ppp b / caffe2 / operators / lengths_tile_op . cc <nl> bool LengthsTileOp < CPUContext > : : RunOnDevice ( ) { <nl> auto src = static_cast < const char * > ( data . raw_data ( ) ) ; <nl> auto out = static_cast < char * > ( output - > raw_mutable_data ( data . meta ( ) ) ) ; <nl> <nl> - for ( TIndex i = 0 ; i < lengths_size ; + + i ) { <nl> + for ( int64_t i = 0 ; i < lengths_size ; + + i ) { <nl> auto length = lengths_data [ i ] ; <nl> CAFFE_ENFORCE_GE ( length , 0 ) ; <nl> for ( int32_t j = 0 ; j < length ; + + j ) { <nl> mmm a / caffe2 / operators / lengths_tile_op . cu <nl> ppp b / caffe2 / operators / lengths_tile_op . cu <nl> bool LengthsTileOp < CUDAContext > : : RunOnDevice ( ) { <nl> rowMappingDevice_ . Resize ( total_length ) ; <nl> auto * rowOffsets = rowMappingHost_ . mutable_data < int32_t > ( ) ; <nl> int32_t outputRow = 0 ; <nl> - for ( TIndex i = 0 ; i < lengths_size ; i + + ) { <nl> + for ( int64_t i = 0 ; i < lengths_size ; i + + ) { <nl> auto length = lengths_data [ i ] ; <nl> for ( int32_t j = 0 ; j < length ; j + + ) { <nl> rowOffsets [ outputRow + + ] = i * numElementsPerRow ; <nl> mmm a / caffe2 / operators / lengths_top_k_op . cc <nl> ppp b / caffe2 / operators / lengths_top_k_op . cc <nl> bool LengthsTopKOp < T , Context > : : RunOnDevice ( ) { <nl> int * output_topk_indices_data = <nl> output_topk_indices - > template mutable_data < int > ( ) ; <nl> <nl> - auto cmp = [ ] ( std : : pair < T , TIndex > & lhs , std : : pair < T , TIndex > & rhs ) { <nl> + auto cmp = [ ] ( std : : pair < T , int64_t > & lhs , std : : pair < T , int64_t > & rhs ) { <nl> return lhs . first > rhs . first | | <nl> ( lhs . first = = rhs . first & & lhs . second < rhs . second ) ; <nl> } ; <nl> <nl> / / Sort preserving indices <nl> int next_index = 0 ; <nl> - for ( TIndex i = 0 ; i < N ; + + i ) { <nl> + for ( int64_t i = 0 ; i < N ; + + i ) { <nl> / / Build a min - heap , the heap element is pair of ( value , idx ) <nl> / / the top of the heap is the smallest value <nl> std : : priority_queue < <nl> - std : : pair < T , TIndex > , <nl> - std : : vector < std : : pair < T , TIndex > > , <nl> + std : : pair < T , int64_t > , <nl> + std : : vector < std : : pair < T , int64_t > > , <nl> decltype ( cmp ) > <nl> p_queue ( cmp ) ; <nl> <nl> / / Maintain the size of heap to be less or equal to k_ , so the <nl> / / heap will hold the k_ largest values <nl> - for ( TIndex j = 0 ; j < input_len [ i ] ; + + j ) { <nl> + for ( int64_t j = 0 ; j < input_len [ i ] ; + + j ) { <nl> const auto value = X_data [ next_index + + ] ; <nl> if ( p_queue . size ( ) < k_ | | value > p_queue . top ( ) . first ) { <nl> p_queue . push ( std : : make_pair ( value , j ) ) ; <nl> bool LengthsTopKOp < T , Context > : : RunOnDevice ( ) { <nl> } <nl> <nl> int last_index = p_queue . size ( ) ; <nl> - for ( TIndex j = 0 ; j < k_ ; + + j ) { <nl> + for ( int64_t j = 0 ; j < k_ ; + + j ) { <nl> if ( p_queue . size ( ) > 0 ) { <nl> auto & pqElem = p_queue . top ( ) ; <nl> output_topk_values_data [ i * k_ + last_index - j - 1 ] = pqElem . first ; <nl> mmm a / caffe2 / operators / local_response_normalization_op . cc <nl> ppp b / caffe2 / operators / local_response_normalization_op . cc <nl> bool LRNOp < float , CPUContext > : : RunOnDeviceWithOrderNCHW ( ) { <nl> scale_ - > ResizeLike ( X ) ; <nl> float * scale_data = scale_ - > template mutable_data < float > ( ) ; <nl> math : : Set < float , CPUContext > ( X . size ( ) , bias_ , scale_data , & context_ ) ; <nl> - Tensor padded_square ( vector < TIndex > { C + size_ - 1 , H , W } , CPU ) ; <nl> + Tensor padded_square ( vector < int64_t > { C + size_ - 1 , H , W } , CPU ) ; <nl> float * padded_square_data = padded_square . template mutable_data < float > ( ) ; <nl> math : : Set < float , CPUContext > ( padded_square . size ( ) , 0 . , padded_square_data , <nl> & context_ ) ; <nl> bool LRNOp < float , CPUContext > : : RunOnDeviceWithOrderNHWC ( ) { <nl> scale_ - > ResizeLike ( X ) ; <nl> float * scale_data = scale_ - > template mutable_data < float > ( ) ; <nl> <nl> - Tensor padded_square ( vector < TIndex > ( 1 , C + size_ - 1 ) , CPU ) ; <nl> + Tensor padded_square ( vector < int64_t > ( 1 , C + size_ - 1 ) , CPU ) ; <nl> float * padded_square_data = padded_square . template mutable_data < float > ( ) ; <nl> math : : Set < float , CPUContext > ( padded_square . size ( ) , 0 . , padded_square_data , <nl> & context_ ) ; <nl> bool LRNGradientOp < float , CPUContext > : : RunOnDeviceWithOrderNCHW ( ) { <nl> const float * dYdata = dY . data < float > ( ) ; <nl> float * dXdata = dX - > template mutable_data < float > ( ) ; <nl> <nl> - Tensor padded_ratio ( vector < TIndex > { C + size_ - 1 , H , W } , CPU ) ; <nl> + Tensor padded_ratio ( vector < int64_t > { C + size_ - 1 , H , W } , CPU ) ; <nl> float * padded_ratio_data = padded_ratio . template mutable_data < float > ( ) ; <nl> / / Compute scale ( copied from LRNOp ) - reusing padded_ratio <nl> math : : Set < float , CPUContext > ( X . size ( ) , bias_ , scale_data , & context_ ) ; <nl> bool LRNGradientOp < float , CPUContext > : : RunOnDeviceWithOrderNCHW ( ) { <nl> <nl> math : : Set < float , CPUContext > ( padded_ratio . size ( ) , 0 . , padded_ratio_data , <nl> & context_ ) ; <nl> - Tensor accum_ratio ( vector < TIndex > { H , W } , CPU ) ; <nl> + Tensor accum_ratio ( vector < int64_t > { H , W } , CPU ) ; <nl> float * accum_ratio_data = accum_ratio . template mutable_data < float > ( ) ; <nl> <nl> const float cache_ratio = 2 . * alpha_ * beta_ / size_ ; <nl> bool LRNGradientOp < float , CPUContext > : : RunOnDeviceWithOrderNHWC ( ) { <nl> scale_ = & local_scale_tensor_ ; <nl> } <nl> scale_ - > ResizeLike ( X ) ; <nl> - Tensor padded_ratio ( vector < TIndex > ( 1 , C + size_ - 1 ) , CPU ) ; <nl> + Tensor padded_ratio ( vector < int64_t > ( 1 , C + size_ - 1 ) , CPU ) ; <nl> float * padded_ratio_data = padded_ratio . template mutable_data < float > ( ) ; <nl> float * scale_data = scale_ - > template mutable_data < float > ( ) ; <nl> / / Compute scale ( copied from LRNOp ) - reusing padded_ratio <nl> mmm a / caffe2 / operators / local_response_normalization_op_cudnn . cc <nl> ppp b / caffe2 / operators / local_response_normalization_op_cudnn . cc <nl> class CuDNNLRNOp final : public Operator < CUDAContext > { <nl> cudnnTensorDescriptor_t data_desc_ ; <nl> cudnnLRNDescriptor_t norm_desc_ ; <nl> <nl> - vector < TIndex > cudnn_input_dims_ ; <nl> + vector < int64_t > cudnn_input_dims_ ; <nl> <nl> const int size_ ; <nl> const float alpha_ ; <nl> class CuDNNLRNGradientOp final : public Operator < CUDAContext > { <nl> cudnnTensorDescriptor_t data_desc_ ; <nl> cudnnLRNDescriptor_t norm_desc_ ; <nl> <nl> - vector < TIndex > cudnn_input_dims_ ; <nl> + vector < int64_t > cudnn_input_dims_ ; <nl> <nl> const int size_ ; <nl> const float alpha_ ; <nl> mmm a / caffe2 / operators / lpnorm_op . cc <nl> ppp b / caffe2 / operators / lpnorm_op . cc <nl> print ( " Y : \ n " , workspace . FetchBlob ( " Y " ) ) <nl> " * ( type : bool ; default : False ) * Whether we calculate norm or averaged_norm . The Lp_averaged_norm ( x ) is defined as Lp_averaged_norm ( x ) = LpNorm ( x ) / size ( x ) " ) <nl> . TensorInferenceFunction ( [ ] ( const OperatorDef & / * unused * / , <nl> const vector < TensorShape > & in ) { <nl> - std : : vector < TIndex > output_dims ( 1 ) ; <nl> + std : : vector < int64_t > output_dims ( 1 ) ; <nl> output_dims [ 0 ] = 1 ; / / 1 <nl> return vector < TensorShape > { <nl> - CreateTensorShape ( vector < TIndex > { output_dims } , in [ 0 ] . data_type ( ) ) } ; <nl> + CreateTensorShape ( vector < int64_t > { output_dims } , in [ 0 ] . data_type ( ) ) } ; <nl> } ) ; <nl> <nl> OPERATOR_SCHEMA ( LpNormGradient ) <nl> mmm a / caffe2 / operators / map_ops . h <nl> ppp b / caffe2 / operators / map_ops . h <nl> class MapSerializer : public BlobSerializerBase { <nl> BlobSerializerBase : : SerializationAcceptor acceptor ) override { <nl> CAFFE_ENFORCE ( blob . IsType < MapType > ( ) ) ; <nl> const MapType & map_data = blob . template Get < MapType > ( ) ; <nl> - TIndex sz = map_data . size ( ) ; <nl> + int64_t sz = map_data . size ( ) ; <nl> Tensor key_tensor ( CPU ) ; <nl> key_tensor . Resize ( sz ) ; <nl> Tensor value_tensor ( CPU ) ; <nl> mmm a / caffe2 / operators / matmul_op . h <nl> ppp b / caffe2 / operators / matmul_op . h <nl> class MatMulOp final : public Operator < Context > { <nl> protected : <nl> / / A local vector to cache the output shape so we don ' t need to recreate <nl> / / a vector object every time we run Run ( ) . <nl> - vector < TIndex > Y_shape_cache_ { 0 , 0 } ; <nl> + vector < int64_t > Y_shape_cache_ { 0 , 0 } ; <nl> int axis_a_ { 1 } ; <nl> int axis_b_ { 1 } ; <nl> bool trans_a_ ; <nl> mmm a / caffe2 / operators / numpy_tile_op . h <nl> ppp b / caffe2 / operators / numpy_tile_op . h <nl> class NumpyTileOp : public Operator < Context > { <nl> / / output tensor . <nl> Tensor * src = & buffer , * dst = output ; <nl> src - > CopyFrom ( input ) ; <nl> - vector < TIndex > output_dims ( input . dims ( ) ) ; <nl> + vector < int64_t > output_dims ( input . dims ( ) ) ; <nl> for ( size_t i = 0 ; i < repeats . size ( ) ; + + i ) { <nl> if ( repeats_data [ i ] = = 1 ) { <nl> continue ; <nl> mmm a / caffe2 / operators / one_hot_ops . cc <nl> ppp b / caffe2 / operators / one_hot_ops . cc <nl> bool BatchOneHotOp < CPUContext > : : DoRunWithType ( ) { <nl> CAFFE_ENFORCE_EQ ( lens . size ( ) , D ) ; <nl> <nl> const auto * lens_data = lens . template data < int32_t > ( ) ; <nl> - TIndex output_dim = 0 ; <nl> + int64_t output_dim = 0 ; <nl> valsOffsets_ . resize ( D + 1 ) ; <nl> - for ( TIndex i = 0 ; i < D ; i + + ) { <nl> + for ( int64_t i = 0 ; i < D ; i + + ) { <nl> CAFFE_ENFORCE_GE ( lens_data [ i ] , 0 ) ; <nl> valsOffsets_ [ i ] = output_dim ; <nl> output_dim + = lens_data [ i ] ; <nl> bool BatchOneHotOp < CPUContext > : : DoRunWithType ( ) { <nl> const auto * vals_data = vals . template data < T > ( ) ; <nl> auto * output_data = output - > template mutable_data < T > ( ) ; <nl> <nl> - for ( TIndex i = 0 ; i < N ; + + i ) { <nl> - for ( TIndex j = 0 ; j < D ; j + + ) { <nl> + for ( int64_t i = 0 ; i < N ; + + i ) { <nl> + for ( int64_t j = 0 ; j < D ; j + + ) { <nl> const auto input_val = input_data [ i * D + j ] ; <nl> - for ( TIndex k = valsOffsets_ [ j ] ; k < valsOffsets_ [ j + 1 ] ; + + k ) { <nl> + for ( int64_t k = valsOffsets_ [ j ] ; k < valsOffsets_ [ j + 1 ] ; + + k ) { <nl> output_data [ k ] = vals_data [ k ] = = input_val ; <nl> } <nl> } <nl> bool BatchOneHotOp < CPUContext > : : DoRunWithType ( ) { <nl> vector < TensorShape > TensorInferenceForBatchOneHot ( <nl> const OperatorDef & / * def * / , <nl> const vector < TensorShape > & in ) { <nl> - std : : vector < TIndex > output_dims ( 2 ) ; <nl> + std : : vector < int64_t > output_dims ( 2 ) ; <nl> output_dims [ 0 ] = in [ 0 ] . dims ( 0 ) ; / / N <nl> output_dims [ 1 ] = in [ 2 ] . dims ( 0 ) ; / / vals . size ( ) <nl> return vector < TensorShape > { <nl> - CreateTensorShape ( vector < TIndex > { output_dims } , in [ 0 ] . data_type ( ) ) } ; <nl> + CreateTensorShape ( vector < int64_t > { output_dims } , in [ 0 ] . data_type ( ) ) } ; <nl> } <nl> <nl> vector < TensorShape > TensorInferenceForBucketBatchOneHot ( <nl> const OperatorDef & / * def * / , <nl> const vector < TensorShape > & in ) { <nl> - std : : vector < TIndex > output_dims ( 2 ) ; <nl> + std : : vector < int64_t > output_dims ( 2 ) ; <nl> output_dims [ 0 ] = in [ 0 ] . dims ( 0 ) ; / / N <nl> output_dims [ 1 ] = in [ 1 ] . dims ( 0 ) + in [ 2 ] . dims ( 0 ) ; / / vals . size ( ) + length . size ( ) <nl> return vector < TensorShape > { <nl> - CreateTensorShape ( vector < TIndex > { output_dims } , in [ 0 ] . data_type ( ) ) } ; <nl> + CreateTensorShape ( vector < int64_t > { output_dims } , in [ 0 ] . data_type ( ) ) } ; <nl> } <nl> <nl> OpSchema : : Cost CostInferenceForBatchOneHot ( <nl> OpSchema : : Cost CostInferenceForBatchOneHot ( <nl> <nl> template < > <nl> void OneHotOp < CPUContext > : : DoOneHotOp ( <nl> - TIndex batch_size , <nl> - TIndex index_size , <nl> + int64_t batch_size , <nl> + int64_t index_size , <nl> const Tensor & indices , <nl> Tensor * one_hots ) { <nl> - const TIndex * indices_ptr = indices . template data < TIndex > ( ) ; <nl> + const int64_t * indices_ptr = indices . template data < int64_t > ( ) ; <nl> float * one_hots_ptr = one_hots - > template mutable_data < float > ( ) ; <nl> memset ( one_hots_ptr , 0 , one_hots - > nbytes ( ) ) ; <nl> for ( int i = 0 ; i < batch_size ; + + i ) { <nl> bool BatchBucketOneHotOp < CPUContext > : : RunOnDevice ( ) { <nl> boundaries . size ( ) , <nl> " The sum of length should be equal to the length of boundaries " ) ; <nl> <nl> - TIndex output_dim = 0 ; <nl> - for ( TIndex i = 0 ; i < D ; i + + ) { <nl> + int64_t output_dim = 0 ; <nl> + for ( int64_t i = 0 ; i < D ; i + + ) { <nl> CAFFE_ENFORCE_GT ( lens_data [ i ] , 0 ) ; <nl> / / Number of buckets is number of bucket edges + 1 <nl> output_dim + = ( lens_data [ i ] + 1 ) ; <nl> bool BatchBucketOneHotOp < CPUContext > : : RunOnDevice ( ) { <nl> <nl> math : : Set < float , CPUContext > ( output - > size ( ) , 0 . f , output_data , & context_ ) ; <nl> <nl> - TIndex pos = 0 ; <nl> - for ( TIndex i = 0 ; i < N ; i + + ) { <nl> + int64_t pos = 0 ; <nl> + for ( int64_t i = 0 ; i < N ; i + + ) { <nl> auto * boundaries_offset = boundaries_data ; <nl> - TIndex output_offset = 0 ; <nl> + int64_t output_offset = 0 ; <nl> <nl> - for ( TIndex j = 0 ; j < D ; j + + ) { <nl> + for ( int64_t j = 0 ; j < D ; j + + ) { <nl> / / here we assume the boundary values for each feature are sorted <nl> - TIndex lower_bucket_idx = std : : lower_bound ( <nl> + int64_t lower_bucket_idx = std : : lower_bound ( <nl> boundaries_offset , <nl> boundaries_offset + lens_data [ j ] , <nl> input_data [ pos ] ) - <nl> boundaries_offset ; <nl> <nl> - TIndex upper_bucket_idx = std : : upper_bound ( <nl> + int64_t upper_bucket_idx = std : : upper_bound ( <nl> boundaries_offset , <nl> boundaries_offset + lens_data [ j ] , <nl> input_data [ pos ] ) - <nl> boundaries_offset ; <nl> <nl> - TIndex bucket_idx = ( lower_bucket_idx + upper_bucket_idx ) / 2 ; <nl> + int64_t bucket_idx = ( lower_bucket_idx + upper_bucket_idx ) / 2 ; <nl> output_data [ i * output_dim + output_offset + bucket_idx ] = 1 . 0 ; <nl> boundaries_offset + = lens_data [ j ] ; <nl> output_offset + = ( lens_data [ j ] + 1 ) ; <nl> mmm a / caffe2 / operators / one_hot_ops . cu <nl> ppp b / caffe2 / operators / one_hot_ops . cu <nl> <nl> namespace caffe2 { <nl> <nl> __global__ void OneHotOpKernel ( <nl> - const TIndex batch_size , <nl> - const TIndex index_size , <nl> - const TIndex * indices , <nl> + const int64_t batch_size , <nl> + const int64_t index_size , <nl> + const int64_t * indices , <nl> float * output ) { <nl> CUDA_1D_KERNEL_LOOP ( i , batch_size ) { <nl> output [ i * index_size + indices [ i ] ] = 1 . ; <nl> __global__ void OneHotOpKernel ( <nl> <nl> template < > <nl> void OneHotOp < CUDAContext > : : DoOneHotOp ( <nl> - TIndex batch_size , <nl> - TIndex index_size , <nl> + int64_t batch_size , <nl> + int64_t index_size , <nl> const Tensor & indices , <nl> Tensor * output ) { <nl> float * output_ptr = output - > template mutable_data < float > ( ) ; <nl> void OneHotOp < CUDAContext > : : DoOneHotOp ( <nl> CAFFE_CUDA_NUM_THREADS , <nl> 0 , <nl> context_ . cuda_stream ( ) > > > ( <nl> - batch_size , index_size , indices . data < TIndex > ( ) , output_ptr ) ; <nl> + batch_size , index_size , indices . data < int64_t > ( ) , output_ptr ) ; <nl> } <nl> <nl> REGISTER_CUDA_OPERATOR ( OneHot , OneHotOp < CUDAContext > ) ; <nl> mmm a / caffe2 / operators / one_hot_ops . h <nl> ppp b / caffe2 / operators / one_hot_ops . h <nl> class OneHotOp final : public Operator < Context > { <nl> CAFFE_ENFORCE_EQ ( <nl> indices . ndim ( ) , <nl> 1 , <nl> - " indices input must be 1D tensor of data type TIndex " ) ; <nl> + " indices input must be 1D tensor of data type int64_t " ) ; <nl> <nl> / / Index size input must be in CPU context <nl> auto & index_size_tensor = this - > template Input < Tensor > ( 1 , CPU ) ; <nl> CAFFE_ENFORCE_EQ ( <nl> index_size_tensor . size ( ) , <nl> 1 , <nl> - " index_size_tensor input must be scalar of data type TIndex " ) ; <nl> + " index_size_tensor input must be scalar of data type int64_t " ) ; <nl> <nl> auto batch_size = indices . size ( ) ; <nl> - auto index_size = * index_size_tensor . template data < TIndex > ( ) ; <nl> + auto index_size = * index_size_tensor . template data < int64_t > ( ) ; <nl> auto one_hots = Output ( 0 ) ; <nl> one_hots - > Resize ( batch_size , index_size ) ; <nl> auto output_size = one_hots - > size ( ) ; <nl> class OneHotOp final : public Operator < Context > { <nl> <nl> protected : <nl> void DoOneHotOp ( <nl> - TIndex batch_size , <nl> - TIndex index_size , <nl> + int64_t batch_size , <nl> + int64_t index_size , <nl> const Tensor & indices , <nl> Tensor * output ) ; <nl> } ; <nl> class BatchOneHotOp final : public Operator < Context > { <nl> <nl> private : <nl> / / allows for fast random access to a given dict and is re - used across runs <nl> - std : : vector < TIndex > valsOffsets_ ; <nl> + std : : vector < int64_t > valsOffsets_ ; <nl> } ; <nl> <nl> template < class Context > <nl> mmm a / caffe2 / operators / onnx_while_op . h <nl> ppp b / caffe2 / operators / onnx_while_op . h <nl> class ONNXWhileOp final : public Operator < Context > { <nl> <nl> / / Use this to keep track of the sizes of the scan outputs and validate <nl> / / they ' re the same across iterations . <nl> - std : : vector < std : : vector < TIndex > > scan_outputs_sizes ; <nl> + std : : vector < std : : vector < int64_t > > scan_outputs_sizes ; <nl> <nl> Workspace * cur_ws = nullptr ; <nl> bool cur_output_condition = false ; <nl> class ONNXWhileOp final : public Operator < Context > { <nl> dims . insert ( dims . begin ( ) , itr ) ; <nl> scan_output_target - > Extend ( 1 , 2 . 0f , & context_ ) ; <nl> <nl> - TIndex timestep_size = 1 ; <nl> - for ( const TIndex t : scan_outputs_sizes [ i ] ) { <nl> + int64_t timestep_size = 1 ; <nl> + for ( const int64_t t : scan_outputs_sizes [ i ] ) { <nl> timestep_size * = t ; <nl> } <nl> <nl> mmm a / caffe2 / operators / onnxifi_op . cc <nl> ppp b / caffe2 / operators / onnxifi_op . cc <nl> bool OnnxifiOp < float , CPUContext > : : RunOnDevice ( ) { <nl> <nl> for ( unsigned i = 0U ; i < OutputSize ( ) ; + + i ) { <nl> auto * output_tensor = Output ( i ) ; <nl> - std : : vector < TIndex > tensor_dims ; <nl> + std : : vector < int64_t > tensor_dims ; <nl> SetOutputShape ( i , & tensor_dims ) ; <nl> output_tensor - > Resize ( tensor_dims ) ; <nl> auto & tensor_descriptor = output_desc_ . at ( i ) ; <nl> mmm a / caffe2 / operators / onnxifi_op . h <nl> ppp b / caffe2 / operators / onnxifi_op . h <nl> class OnnxifiOp final : public Operator < Context > { <nl> const std : : string key = MakeString ( " output_size_hint_ " , output_idx ) ; <nl> auto output_size_hint = this - > template GetRepeatedArgument < int > ( key ) ; <nl> if ( ! output_size_hint . empty ( ) ) { <nl> - std : : vector < TIndex > dims ; <nl> + std : : vector < int64_t > dims ; <nl> for ( const auto v : output_size_hint ) { <nl> dims . push_back ( v ) ; <nl> } <nl> class OnnxifiOp final : public Operator < Context > { <nl> bool RunOnDevice ( ) override ; <nl> <nl> private : <nl> - void SetOutputShape ( int output_idx , std : : vector < TIndex > * dims ) { <nl> + void SetOutputShape ( int output_idx , std : : vector < int64_t > * dims ) { <nl> const auto it = output_size_hints_ . find ( output_idx ) ; <nl> if ( it ! = output_size_hints_ . end ( ) ) { <nl> * dims = it - > second ; <nl> class OnnxifiOp final : public Operator < Context > { <nl> std : : vector < std : : vector < uint64_t > > output_shapes_ ; <nl> <nl> / / output shape hints <nl> - std : : unordered_map < int , std : : vector < TIndex > > output_size_hints_ ; <nl> + std : : unordered_map < int , std : : vector < int64_t > > output_size_hints_ ; <nl> } ; <nl> <nl> } / / namespace caffe2 <nl> mmm a / caffe2 / operators / operator_fallback_gpu_test . cc <nl> ppp b / caffe2 / operators / operator_fallback_gpu_test . cc <nl> TEST ( OperatorFallbackTest , IncrementByOneOp ) { <nl> " IncrementByOne " , " " , vector < string > { " X " } , <nl> vector < string > { " X " } ) ; <nl> Workspace ws ; <nl> - Tensor source_tensor ( vector < TIndex > { 2 , 3 } , CPU ) ; <nl> + Tensor source_tensor ( vector < int64_t > { 2 , 3 } , CPU ) ; <nl> for ( int i = 0 ; i < 6 ; + + i ) { <nl> source_tensor . mutable_data < float > ( ) [ i ] = i ; <nl> } <nl> TEST ( OperatorFallbackTest , GPUIncrementByOneOp ) { <nl> vector < string > { " X " } ) ; <nl> op_def . mutable_device_option ( ) - > set_device_type ( PROTO_CUDA ) ; <nl> Workspace ws ; <nl> - Tensor source_tensor ( vector < TIndex > { 2 , 3 } , CPU ) ; <nl> + Tensor source_tensor ( vector < int64_t > { 2 , 3 } , CPU ) ; <nl> for ( int i = 0 ; i < 6 ; + + i ) { <nl> source_tensor . mutable_data < float > ( ) [ i ] = i ; <nl> } <nl> mmm a / caffe2 / operators / order_switch_ops . cc <nl> ppp b / caffe2 / operators / order_switch_ops . cc <nl> bool NHWC2NCHWOp < float , CPUContext > : : RunOnDevice ( ) { <nl> auto ndim = X . ndim ( ) ; <nl> CAFFE_ENFORCE_GE ( ndim , 3 ) ; <nl> const int N = X . dim32 ( 0 ) , C = X . dim32 ( ndim - 1 ) ; <nl> - vector < TIndex > Y_dims ( ndim ) ; <nl> + vector < int64_t > Y_dims ( ndim ) ; <nl> Y_dims [ 0 ] = N ; <nl> Y_dims [ 1 ] = C ; <nl> int image_size = 1 ; <nl> bool NCHW2NHWCOp < float , CPUContext > : : RunOnDevice ( ) { <nl> auto ndim = X . ndim ( ) ; <nl> CAFFE_ENFORCE_GE ( X . ndim ( ) , 3 ) ; <nl> const int N = X . dim32 ( 0 ) , C = X . dim32 ( 1 ) ; <nl> - vector < TIndex > Y_dims ( ndim ) ; <nl> + vector < int64_t > Y_dims ( ndim ) ; <nl> Y_dims [ 0 ] = N ; <nl> int image_size = 1 ; <nl> for ( auto i = 1 ; i < ndim - 1 ; + + i ) { <nl> mmm a / caffe2 / operators / order_switch_ops . cu <nl> ppp b / caffe2 / operators / order_switch_ops . cu <nl> bool NHWC2NCHWOp < float , CUDAContext > : : RunOnDevice ( ) { <nl> CAFFE_ENFORCE_GE ( ndim , 3 ) ; <nl> const int N = X . dim32 ( 0 ) ; <nl> const int C = X . dim32 ( ndim - 1 ) ; <nl> - vector < TIndex > Y_dims ( ndim ) ; <nl> + vector < int64_t > Y_dims ( ndim ) ; <nl> Y_dims [ 0 ] = N ; <nl> Y_dims [ 1 ] = C ; <nl> int HxW = 1 ; <nl> bool NCHW2NHWCOp < float , CUDAContext > : : RunOnDevice ( ) { <nl> CAFFE_ENFORCE_GE ( X . ndim ( ) , 3 ) ; <nl> const int N = X . dim32 ( 0 ) ; <nl> const int C = X . dim32 ( 1 ) ; <nl> - vector < TIndex > Y_dims ( ndim ) ; <nl> + vector < int64_t > Y_dims ( ndim ) ; <nl> Y_dims [ 0 ] = N ; <nl> int HxW = 1 ; <nl> for ( auto i = 1 ; i < ndim - 1 ; + + i ) { <nl> mmm a / caffe2 / operators / pack_rnn_sequence_op . h <nl> ppp b / caffe2 / operators / pack_rnn_sequence_op . h <nl> class PackRNNSequenceOpBase : public Operator < Context > { <nl> CAFFE_ENFORCE_GT ( values . ndim ( ) , dim_offset ) ; <nl> <nl> / / block_size is the size for each individual feature <nl> - TIndex block_size = values . size_from_dim ( dim_offset ) ; <nl> + int64_t block_size = values . size_from_dim ( dim_offset ) ; <nl> auto values_vec = values . template data < ValT > ( ) ; <nl> <nl> auto & lengths = Input ( LENGTHS ) ; <nl> class PackRNNSequenceOpBase : public Operator < Context > { <nl> math : : Sum < int , Context > ( cols , lengths_vec , & length_sum , & context_ ) ; <nl> } <nl> <nl> - vector < TIndex > shape ; <nl> + vector < int64_t > shape ; <nl> / / the output shape is rows * cols for the pack , <nl> / / or length_sum for the sequence <nl> if ( Forward ) { <nl> mmm a / caffe2 / operators / pack_segments . cc <nl> ppp b / caffe2 / operators / pack_segments . cc <nl> bool PackSegmentsOp < CPUContext > : : DoRunWithType2 ( ) { <nl> / / Find the length of the longest sequence . <nl> const T * l = lengths . template data < T > ( ) ; <nl> T max_length = 0 ; <nl> - TIndex total_length = 0 ; <nl> + int64_t total_length = 0 ; <nl> for ( T i = 0 ; i < lengths . dim ( 0 ) ; + + i ) { <nl> max_length = std : : max ( max_length , l [ i ] ) ; <nl> total_length + = l [ i ] ; <nl> bool PackSegmentsOp < CPUContext > : : DoRunWithType2 ( ) { <nl> bool * presence_mask_data = nullptr ; <nl> if ( return_presence_mask_ ) { <nl> / / Shape of presence is batch_size x max_len <nl> - std : : vector < caffe2 : : TIndex > presence_shape { lengths . size ( ) , max_length } ; <nl> + std : : vector < int64_t > presence_shape { lengths . size ( ) , max_length } ; <nl> presence_mask - > Resize ( presence_shape ) ; <nl> presence_mask_data = presence_mask - > template mutable_data < bool > ( ) ; <nl> } <nl> bool PackSegmentsOp < CPUContext > : : DoRunWithType2 ( ) { <nl> auto block_size = data . size_from_dim ( 1 ) ; <nl> auto block_bytesize = data . itemsize ( ) * block_size ; <nl> const auto * d = static_cast < const char * > ( data . raw_data ( ) ) ; <nl> - TIndex start = 0 ; <nl> - for ( TIndex i = 0 ; i < lengths . dim ( 0 ) ; + + i ) { <nl> + int64_t start = 0 ; <nl> + for ( int64_t i = 0 ; i < lengths . dim ( 0 ) ; + + i ) { <nl> context_ . CopyItemsSameDevice ( <nl> data . meta ( ) , <nl> l [ i ] * block_size , <nl> bool UnpackSegmentsOp < CPUContext > : : DoRunWithType2 ( ) { <nl> } <nl> const T * l = lengths . template data < T > ( ) ; <nl> <nl> - TIndex total_l = std : : accumulate ( l , l + lengths . dim ( 0 ) , ( TIndex ) 0 ) ; <nl> + int64_t total_l = std : : accumulate ( l , l + lengths . dim ( 0 ) , ( int64_t ) 0 ) ; <nl> <nl> auto shape = data . dims ( ) ; <nl> CAFFE_ENFORCE_EQ ( <nl> bool UnpackSegmentsOp < CPUContext > : : DoRunWithType2 ( ) { <nl> auto block_size = data . size_from_dim ( 2 ) ; <nl> auto block_bytesize = data . itemsize ( ) * block_size ; <nl> const auto * d = static_cast < const char * > ( data . raw_data ( ) ) ; <nl> - TIndex start = 0 ; <nl> - for ( TIndex i = 0 ; i < lengths . dim ( 0 ) ; + + i ) { <nl> + int64_t start = 0 ; <nl> + for ( int64_t i = 0 ; i < lengths . dim ( 0 ) ; + + i ) { <nl> context_ . CopyItemsSameDevice ( <nl> data . meta ( ) , <nl> l [ i ] * block_size , <nl> mmm a / caffe2 / operators / pack_segments . h <nl> ppp b / caffe2 / operators / pack_segments . h <nl> class PackSegmentsOp final : public Operator < Context > { <nl> INPUT_TAGS ( LENGTHS , DATA ) ; <nl> <nl> private : <nl> - TIndex max_length_ ; <nl> + int64_t max_length_ ; <nl> bool pad_minf_ ; <nl> float padding_ ; <nl> bool return_presence_mask_ ; <nl> class UnpackSegmentsOp final : public Operator < Context > { <nl> INPUT_TAGS ( LENGTHS , DATA ) ; <nl> <nl> private : <nl> - TIndex max_length_ ; <nl> + int64_t max_length_ ; <nl> Tensor dev_buffer_ { Context : : GetDeviceType ( ) } ; <nl> Tensor dev_lengths_prefix_sum_ { Context : : GetDeviceType ( ) } ; <nl> Tensor dev_max_length_ { Context : : GetDeviceType ( ) } ; <nl> mmm a / caffe2 / operators / partition_ops . h <nl> ppp b / caffe2 / operators / partition_ops . h <nl> class GatherByKeyOp : public Operator < CPUContext > { <nl> const auto & in0Shape = Input ( 1 ) . dims ( ) ; <nl> CAFFE_ENFORCE_GE ( in0Shape . size ( ) , 1 ) ; <nl> <nl> - vector < TIndex > outShape ( keysShape ) ; <nl> + vector < int64_t > outShape ( keysShape ) ; <nl> outShape . insert ( outShape . end ( ) , in0Shape . begin ( ) + 1 , in0Shape . end ( ) ) ; <nl> <nl> CAFFE_ENFORCE_GE ( outShape . size ( ) , 1 ) ; <nl> class PartitionOpBase : public Operator < CPUContext > { <nl> CAFFE_ENFORCE_GT ( partitions , 0 , " Invalid number of partitions " ) ; <nl> <nl> auto & main_input = Input ( mainInputIndex ) ; <nl> - TIndex size = main_input . size ( ) ; <nl> + int64_t size = main_input . size ( ) ; <nl> const Index * data = main_input . template data < Index > ( ) ; <nl> counts_ . assign ( partitions , 0 ) ; <nl> - for ( TIndex p = 0 ; p < size ; p + + ) { <nl> + for ( int64_t p = 0 ; p < size ; p + + ) { <nl> int shard = moduloPartition ( data [ p ] , partitions ) ; <nl> + + counts_ [ shard ] ; <nl> } <nl> class PartitionOpBase : public Operator < CPUContext > { <nl> block_sizes_ [ i ] = input . size_from_dim ( main_input . ndim ( ) ) ; <nl> metas_ [ i ] = input . meta ( ) ; <nl> / / shape = partition_size + suffix of input dims <nl> - vector < TIndex > shape ( <nl> + vector < int64_t > shape ( <nl> input . dims ( ) . begin ( ) + main_input . ndim ( ) - 1 , input . dims ( ) . end ( ) ) ; <nl> for ( int j = 0 ; j < partitions ; + + j ) { <nl> int out_idx = i + j * inputSize ; <nl> class PartitionOpBase : public Operator < CPUContext > { <nl> } <nl> <nl> counts_ . assign ( partitions , 0 ) ; <nl> - for ( TIndex p = 0 ; p < size ; p + + ) { <nl> + for ( int64_t p = 0 ; p < size ; p + + ) { <nl> int shard = moduloPartition ( data [ p ] , partitions ) ; <nl> - TIndex idx = counts_ [ shard ] + + ; <nl> + int64_t idx = counts_ [ shard ] + + ; <nl> <nl> / / special case first input <nl> static_cast < Index * > ( out_datas_ [ shard * inputSize + mainInputIndex ] ) [ idx ] = <nl> class PartitionOpBase : public Operator < CPUContext > { <nl> bool pack_first_input_ ; <nl> <nl> / / use member fields to reuse memory <nl> - vector < TIndex > counts_ ; <nl> - vector < TIndex > block_sizes_ ; <nl> + vector < int64_t > counts_ ; <nl> + vector < int64_t > block_sizes_ ; <nl> vector < TypeMeta > metas_ ; <nl> vector < const void * > raw_datas_ ; <nl> vector < void * > out_datas_ ; <nl> class LengthsPartitionOp : public PartitionOpBase { <nl> <nl> / / Compute lengths after sharding <nl> auto & main_input = Input ( 1 ) ; <nl> - TIndex size = main_input . size ( ) ; <nl> + int64_t size = main_input . size ( ) ; <nl> const Index * data = main_input . template data < Index > ( ) ; <nl> <nl> auto & length_input = Input ( 0 ) ; <nl> - TIndex elements = length_input . size ( ) ; <nl> + int64_t elements = length_input . size ( ) ; <nl> const int32_t * lengths_data = length_input . template data < int32_t > ( ) ; <nl> out_length_ . resize ( partitions ) ; <nl> for ( int i = 0 ; i < partitions ; + + i ) { <nl> mmm a / caffe2 / operators / perplexity_op . cc <nl> ppp b / caffe2 / operators / perplexity_op . cc <nl> bool PerplexityOp < float , CPUContext > : : RunOnDevice ( ) { <nl> DCHECK_EQ ( X . ndim ( ) , 1 ) ; <nl> int N = X . dim32 ( 0 ) ; <nl> <nl> - Y - > Resize ( vector < TIndex > ( ) ) ; <nl> + Y - > Resize ( vector < int64_t > ( ) ) ; <nl> const auto * Xdata = X . data < float > ( ) ; <nl> <nl> float perplexity = 1 . 0 ; <nl> mmm a / caffe2 / operators / perplexity_op . cu <nl> ppp b / caffe2 / operators / perplexity_op . cu <nl> bool PerplexityOp < float , CUDAContext > : : RunOnDevice ( ) { <nl> DCHECK_EQ ( X . ndim ( ) , 1 ) ; <nl> int N = X . dim32 ( 0 ) ; <nl> <nl> - Y - > Resize ( vector < TIndex > ( ) ) ; <nl> + Y - > Resize ( vector < int64_t > ( ) ) ; <nl> float * Ydata = Y - > template mutable_data < float > ( ) ; <nl> const float * Xdata = X . data < float > ( ) ; <nl> <nl> mmm a / caffe2 / operators / piecewise_linear_transform_op . cu <nl> ppp b / caffe2 / operators / piecewise_linear_transform_op . cu <nl> __global__ void PieceWiseLinearTransformBinaryKernel2 ( <nl> <nl> template < > <nl> void PiecewiseLinearTransformOp < float , CUDAContext > : : setUpTensors ( <nl> - TIndex & num_func_per_group , <nl> - TIndex & num_group , <nl> - TIndex M ) { <nl> + int64_t & num_func_per_group , <nl> + int64_t & num_group , <nl> + int64_t M ) { <nl> if ( transform_param_from_arg_ ) { <nl> if ( ! gpu_copied_ ) { <nl> - TIndex num_bounds ; <nl> - TIndex num_slopes ; <nl> - TIndex num_intercepts ; <nl> + int64_t num_bounds ; <nl> + int64_t num_slopes ; <nl> + int64_t num_intercepts ; <nl> <nl> CAFFE_ENFORCE_EQ ( InputSize ( ) , 1 ) ; <nl> <nl> void PiecewiseLinearTransformOp < float , CUDAContext > : : setUpTensors ( <nl> gpu_copied_ = true ; <nl> } <nl> } else { <nl> - TIndex num_bounds ; <nl> - TIndex num_slopes ; <nl> - TIndex num_intercepts ; <nl> + int64_t num_bounds ; <nl> + int64_t num_slopes ; <nl> + int64_t num_intercepts ; <nl> CAFFE_ENFORCE_EQ ( InputSize ( ) , 4 ) ; <nl> auto & bounds_input = Input ( BOUNDS ) ; <nl> auto & slopes_input = Input ( SLOPES ) ; <nl> bool PiecewiseLinearTransformOp < float , CUDAContext > : : TransformGeneral ( ) { <nl> auto & X = Input ( 0 ) ; <nl> auto * Y = Output ( 0 ) ; <nl> CAFFE_ENFORCE_EQ ( X . ndim ( ) , 2 ) ; <nl> - TIndex N = X . dim32 ( 0 ) ; <nl> - TIndex M = X . dim32 ( 1 ) ; <nl> + int64_t N = X . dim32 ( 0 ) ; <nl> + int64_t M = X . dim32 ( 1 ) ; <nl> Y - > ResizeLike ( X ) ; <nl> <nl> - TIndex num_func_per_group ; <nl> - TIndex num_group ; <nl> + int64_t num_func_per_group ; <nl> + int64_t num_group ; <nl> <nl> setUpTensors ( num_func_per_group , num_group , M ) ; <nl> <nl> bool PiecewiseLinearTransformOp < float , CUDAContext > : : TransformBinary ( ) { <nl> auto & X = Input ( 0 ) ; <nl> auto * Y = Output ( 0 ) ; <nl> CAFFE_ENFORCE ( X . ndim ( ) = = 1 | | X . ndim ( ) = = 2 ) ; <nl> - TIndex N = X . dim32 ( 0 ) ; <nl> - TIndex M = X . ndim ( ) = = 2 ? X . dim32 ( 1 ) : 1 ; <nl> + int64_t N = X . dim32 ( 0 ) ; <nl> + int64_t M = X . ndim ( ) = = 2 ? X . dim32 ( 1 ) : 1 ; <nl> CAFFE_ENFORCE ( <nl> M = = 1 | | M = = 2 , <nl> " If binary is set to true , the input must be Nx2 or Nx1 tensor " ) ; <nl> Y - > ResizeLike ( X ) ; <nl> <nl> - TIndex num_func_per_group ; <nl> - TIndex num_group ; <nl> + int64_t num_func_per_group ; <nl> + int64_t num_group ; <nl> <nl> setUpTensors ( num_func_per_group , num_group , M ) ; <nl> <nl> mmm a / caffe2 / operators / piecewise_linear_transform_op . h <nl> ppp b / caffe2 / operators / piecewise_linear_transform_op . h <nl> class PiecewiseLinearTransformOp final : public Operator < Context > { <nl> / / num_group : The number of groups of linear functions . Each group is for <nl> / / transforming one column of predictions . <nl> void InferNumFunctionsPerGroup ( <nl> - const TIndex num_bounds , <nl> - const TIndex num_slopes , <nl> - const TIndex num_intercepts , <nl> - TIndex * num_func_per_group , <nl> - TIndex * num_group ) { <nl> + const int64_t num_bounds , <nl> + const int64_t num_slopes , <nl> + const int64_t num_intercepts , <nl> + int64_t * num_func_per_group , <nl> + int64_t * num_group ) { <nl> CAFFE_ENFORCE_EQ ( num_slopes , num_intercepts ) ; <nl> <nl> / / This is based on the facts : <nl> class PiecewiseLinearTransformOp final : public Operator < Context > { <nl> <nl> bool CheckBoundsSorted ( <nl> const T * bounds , <nl> - const TIndex num_bounds_per_group , <nl> - const TIndex num_group ) { <nl> + const int64_t num_bounds_per_group , <nl> + const int64_t num_group ) { <nl> const T * start = bounds ; <nl> - for ( TIndex i = 0 ; i < num_group ; i + + ) { <nl> + for ( int64_t i = 0 ; i < num_group ; i + + ) { <nl> if ( ! std : : is_sorted ( start , start + num_bounds_per_group ) ) { <nl> return false ; <nl> } <nl> class PiecewiseLinearTransformOp final : public Operator < Context > { <nl> good_param = = 0 | | good_param = = 3 , <nl> " bounds , slopes , intercepts must be all set or all not set " ) ; <nl> if ( good_param = = 3 ) { <nl> - TIndex num_func_per_group ; <nl> - TIndex num_group ; <nl> + int64_t num_func_per_group ; <nl> + int64_t num_group ; <nl> InferNumFunctionsPerGroup ( <nl> bounds_from_arg_ . size ( ) , <nl> slopes_from_arg_ . size ( ) , <nl> class PiecewiseLinearTransformOp final : public Operator < Context > { <nl> return good_param = = 3 ; <nl> } <nl> <nl> - void setUpTensors ( TIndex & num_func_per_group , TIndex & num_group , TIndex M ) ; <nl> + void setUpTensors ( int64_t & num_func_per_group , int64_t & num_group , int64_t M ) ; <nl> <nl> void GetTransParamData ( <nl> const T * * bounds , <nl> const T * * slopes , <nl> const T * * intercepts , <nl> - TIndex * num_func_per_group , <nl> - TIndex * num_group ) { <nl> - TIndex num_bounds ; <nl> - TIndex num_slopes ; <nl> - TIndex num_intercepts ; <nl> + int64_t * num_func_per_group , <nl> + int64_t * num_group ) { <nl> + int64_t num_bounds ; <nl> + int64_t num_slopes ; <nl> + int64_t num_intercepts ; <nl> <nl> if ( transform_param_from_arg_ ) { <nl> CAFFE_ENFORCE_EQ ( InputSize ( ) , 1 ) ; <nl> class PiecewiseLinearTransformOp final : public Operator < Context > { <nl> auto & X = Input ( 0 ) ; <nl> auto * Y = Output ( 0 ) ; <nl> CAFFE_ENFORCE_EQ ( X . ndim ( ) , 2 ) ; <nl> - TIndex N = X . dim32 ( 0 ) ; <nl> - TIndex M = X . dim32 ( 1 ) ; <nl> + int64_t N = X . dim32 ( 0 ) ; <nl> + int64_t M = X . dim32 ( 1 ) ; <nl> Y - > ResizeLike ( X ) ; <nl> const auto * Xdata = X . template data < T > ( ) ; <nl> T * Ydata = Y - > template mutable_data < T > ( ) ; <nl> class PiecewiseLinearTransformOp final : public Operator < Context > { <nl> const T * bounds ; <nl> const T * slopes ; <nl> const T * intercepts ; <nl> - TIndex num_func_per_group ; <nl> - TIndex num_group ; <nl> + int64_t num_func_per_group ; <nl> + int64_t num_group ; <nl> GetTransParamData ( <nl> & bounds , & slopes , & intercepts , & num_func_per_group , & num_group ) ; <nl> CAFFE_ENFORCE_EQ ( num_group , M ) ; <nl> <nl> - for ( TIndex j = 0 ; j < M ; + + j ) { <nl> + for ( int64_t j = 0 ; j < M ; + + j ) { <nl> const T * bounds_group = bounds + j * ( num_func_per_group + 1 ) ; <nl> const T * slopes_group = slopes + j * num_func_per_group ; <nl> const T * intercepts_group = intercepts + j * num_func_per_group ; <nl> - for ( TIndex i = 0 ; i < N ; + + i ) { <nl> + for ( int64_t i = 0 ; i < N ; + + i ) { <nl> Ydata [ i * M + j ] = PiecewiseLinearTransform ( <nl> Xdata [ i * M + j ] , <nl> bounds_group , <nl> class PiecewiseLinearTransformOp final : public Operator < Context > { <nl> auto & X = Input ( PREDICTIONS ) ; <nl> auto * Y = Output ( 0 ) ; <nl> CAFFE_ENFORCE ( X . ndim ( ) = = 1 | | X . ndim ( ) = = 2 ) ; <nl> - TIndex N = X . dim32 ( 0 ) ; <nl> - TIndex M = X . ndim ( ) = = 2 ? X . dim32 ( 1 ) : 1 ; <nl> + int64_t N = X . dim32 ( 0 ) ; <nl> + int64_t M = X . ndim ( ) = = 2 ? X . dim32 ( 1 ) : 1 ; <nl> CAFFE_ENFORCE ( <nl> M = = 1 | | M = = 2 , <nl> " If binary is set to true , the input must be Nx2 or Nx1 tensor " ) ; <nl> class PiecewiseLinearTransformOp final : public Operator < Context > { <nl> const T * bounds ; <nl> const T * slopes ; <nl> const T * intercepts ; <nl> - TIndex num_func_per_group ; <nl> - TIndex num_group ; <nl> + int64_t num_func_per_group ; <nl> + int64_t num_group ; <nl> GetTransParamData ( <nl> & bounds , & slopes , & intercepts , & num_func_per_group , & num_group ) ; <nl> CAFFE_ENFORCE_EQ ( num_group , 1 ) ; <nl> <nl> if ( M = = 1 ) { <nl> - for ( TIndex i = 0 ; i < N ; + + i ) { <nl> + for ( int64_t i = 0 ; i < N ; + + i ) { <nl> Ydata [ i ] = PiecewiseLinearTransform ( <nl> Xdata [ i ] , bounds , slopes , intercepts , num_func_per_group ) ; <nl> } <nl> } else { <nl> - for ( TIndex i = 0 ; i < N ; + + i ) { <nl> + for ( int64_t i = 0 ; i < N ; + + i ) { <nl> Ydata [ i * M + 1 ] = PiecewiseLinearTransform ( <nl> Xdata [ i * M + 1 ] , bounds , slopes , intercepts , num_func_per_group ) ; <nl> Ydata [ i * M ] = 1 . 0f - Ydata [ i * M + 1 ] ; <nl> class PiecewiseLinearTransformOp final : public Operator < Context > { <nl> const T * bounds , <nl> const T * slopes , <nl> const T * intercepts , <nl> - const TIndex num_func_per_group ) { <nl> + const int64_t num_func_per_group ) { <nl> T y = 0 ; <nl> / / deal with samples out of bounds <nl> / / make it the same as the upper / lower bound value <nl> mmm a / caffe2 / operators / pool_op_cudnn . cu <nl> ppp b / caffe2 / operators / pool_op_cudnn . cu <nl> class CuDNNPoolOp : public ConvPoolOpBase < CUDAContext > { <nl> } <nl> <nl> protected : <nl> - vector < TIndex > cudnn_input_dims_ ; <nl> + vector < int64_t > cudnn_input_dims_ ; <nl> <nl> CuDNNWrapper cudnn_wrapper_ ; <nl> cudnnTensorDescriptor_t bottom_desc_ ; <nl> class CuDNNPoolGradientOp : public ConvPoolOpBase < CUDAContext > { <nl> } <nl> <nl> protected : <nl> - vector < TIndex > cudnn_input_dims_ ; <nl> + vector < int64_t > cudnn_input_dims_ ; <nl> <nl> CuDNNWrapper cudnn_wrapper_ ; <nl> cudnnTensorDescriptor_t bottom_desc_ ; <nl> mmm a / caffe2 / operators / reducer_functors . h <nl> ppp b / caffe2 / operators / reducer_functors . h <nl> template < typename T > <nl> class SumRangeReducer < T , CPUContext > { <nl> public : <nl> void operator ( ) ( <nl> - const TIndex block_size , <nl> - const TIndex blocks , <nl> + const int64_t block_size , <nl> + const int64_t blocks , <nl> const T * in , <nl> T * out , <nl> CPUContext * / * context * / ) { <nl> template < typename T , class Context > <nl> class SumRangeReducerGradient { <nl> public : <nl> void operator ( ) ( <nl> - const TIndex block_size , <nl> - const TIndex blocks , <nl> + const int64_t block_size , <nl> + const int64_t blocks , <nl> const T * segment_grad , <nl> T * data_grad , <nl> const T * / * data_in * / , / / unused <nl> const T * / * data_out * / , / / unused <nl> Context * context ) { <nl> / / do we have some op that does it smartly with minimum number of memcpy ? <nl> - for ( TIndex i = 0 ; i < blocks ; + + i ) { <nl> + for ( int64_t i = 0 ; i < blocks ; + + i ) { <nl> context - > template CopySameDevice < T > ( <nl> block_size , segment_grad , data_grad + block_size * i ) ; <nl> } <nl> template < typename T > <nl> class LogSumExpRangeReducer < T , CPUContext > { <nl> public : <nl> void operator ( ) ( <nl> - const TIndex block_size , <nl> - const TIndex blocks , <nl> + const int64_t block_size , <nl> + const int64_t blocks , <nl> const T * in , <nl> T * out , <nl> CPUContext * / * context * / ) { <nl> template < typename T , class Context > <nl> class LogSumExpRangeReducerGradient { <nl> public : <nl> void operator ( ) ( <nl> - const TIndex block_size , <nl> - const TIndex blocks , <nl> + const int64_t block_size , <nl> + const int64_t blocks , <nl> const T * segment_grad , / / GO <nl> T * data_grad , / / GI <nl> const T * data_in , / / I <nl> template < typename T > <nl> class LogMeanExpRangeReducer < T , CPUContext > { <nl> public : <nl> void operator ( ) ( <nl> - const TIndex block_size , <nl> - const TIndex blocks , <nl> + const int64_t block_size , <nl> + const int64_t blocks , <nl> const T * in , <nl> T * out , <nl> CPUContext * / * context * / ) { <nl> template < typename T , class Context > <nl> class LogMeanExpRangeReducerGradient { <nl> public : <nl> void operator ( ) ( <nl> - const TIndex block_size , <nl> - const TIndex blocks , <nl> + const int64_t block_size , <nl> + const int64_t blocks , <nl> const T * segment_grad , / / GO <nl> T * data_grad , / / GI <nl> const T * data_in , / / I <nl> template < typename T > <nl> class MeanRangeReducer < T , CPUContext > { <nl> public : <nl> void operator ( ) ( <nl> - const TIndex block_size , <nl> - const TIndex blocks , <nl> + const int64_t block_size , <nl> + const int64_t blocks , <nl> const T * in , <nl> T * out , <nl> CPUContext * / * context * / ) { <nl> template < typename T , class Context > <nl> class MeanRangeReducerGradient { <nl> public : <nl> void operator ( ) ( <nl> - const TIndex block_size , <nl> - const TIndex blocks , <nl> + const int64_t block_size , <nl> + const int64_t blocks , <nl> const T * segment_grad , / / GO <nl> T * data_grad , / / GI <nl> const T * / * data_in * / , / / I <nl> template < typename T > <nl> class MaxRangeReducer < T , CPUContext > { <nl> public : <nl> void operator ( ) ( <nl> - const TIndex block_size , <nl> - const TIndex blocks , <nl> + const int64_t block_size , <nl> + const int64_t blocks , <nl> const T * in , <nl> T * out , <nl> CPUContext * / * context * / ) { <nl> template < typename T , class Context > <nl> class MaxRangeReducerGradient { <nl> public : <nl> void operator ( ) ( <nl> - const TIndex block_size , <nl> - const TIndex blocks , <nl> + const int64_t block_size , <nl> + const int64_t blocks , <nl> const T * segment_grad , / / GO <nl> T * data_grad , / / GI <nl> const T * data_in , / / I <nl> class BaseReducer { <nl> static constexpr int kInputCount = 1 ; <nl> <nl> struct Meta { <nl> - TIndex block_size ; <nl> - vector < TIndex > block_shape ; <nl> + int64_t block_size ; <nl> + vector < int64_t > block_shape ; <nl> bool first_dim ; <nl> <nl> explicit Meta ( bool first = true ) : first_dim ( first ) { } <nl> <nl> - void computeMeta ( const std : : vector < TIndex > & dims , int skip_dims ) { <nl> + void computeMeta ( const std : : vector < int64_t > & dims , int skip_dims ) { <nl> first_dim ? block_shape . assign ( dims . begin ( ) + skip_dims , dims . end ( ) ) <nl> : block_shape . assign ( dims . begin ( ) , dims . end ( ) - skip_dims ) ; <nl> block_size = first_dim ? size_from_dim_ ( skip_dims , dims ) <nl> class BaseReducer { <nl> computeMeta ( dims , skip_dims ) ; <nl> } <nl> <nl> - void appendOutputShape ( vector < TIndex > * output_shape ) { <nl> + void appendOutputShape ( vector < int64_t > * output_shape ) { <nl> output_shape - > insert ( <nl> output_shape - > end ( ) , block_shape . begin ( ) , block_shape . end ( ) ) ; <nl> } <nl> <nl> - vector < TIndex > getOutputShape ( const TensorShape & in , int skip_dims ) { <nl> - vector < TIndex > dims ( in . dims ( ) . begin ( ) , in . dims ( ) . end ( ) ) ; <nl> + vector < int64_t > getOutputShape ( const TensorShape & in , int skip_dims ) { <nl> + vector < int64_t > dims ( in . dims ( ) . begin ( ) , in . dims ( ) . end ( ) ) ; <nl> computeMeta ( dims , skip_dims ) ; <nl> return block_shape ; <nl> } <nl> class BaseReducerGradient { <nl> } <nl> <nl> struct Meta { <nl> - TIndex block_size ; <nl> - vector < TIndex > block_shape ; <nl> + int64_t block_size ; <nl> + vector < int64_t > block_shape ; <nl> bool first_dim ; <nl> <nl> Meta ( const Tensor & out_grad , int skip_dims , bool first_dim = true ) <nl> class BaseReducerGradient { <nl> Tensor * / * input_grad * / , / / optional grad to populate <nl> int / * skip_dims * / ) { } <nl> <nl> - void appendGradShape ( vector < TIndex > * output_shape ) { <nl> + void appendGradShape ( vector < int64_t > * output_shape ) { <nl> output_shape - > insert ( <nl> output_shape - > end ( ) , block_shape . begin ( ) , block_shape . end ( ) ) ; <nl> } <nl> class SumReducer < T , CPUContext > : public BaseReducer { <nl> void process ( <nl> const Meta & meta , <nl> const T * in , <nl> - TIndex / * offset * / , <nl> + int64_t / * offset * / , <nl> CPUContext * context ) { <nl> if ( meta . first_dim ) { <nl> math : : AxpyFixedSize < T , CPUContext , FixedSize > ( <nl> class SumReducerGradient : public BaseReducerGradient { <nl> void fillGrad ( <nl> const Meta & meta , <nl> T * data_grad , <nl> - TIndex offset , <nl> + int64_t offset , <nl> Context * context , <nl> const int length ) { <nl> if ( FixedSize = = 1 ) { / / static if <nl> class WeightedSumReducer < T , CPUContext > : public BaseReducer { <nl> } <nl> template < int FixedSize > <nl> void <nl> - process ( const Meta & meta , const T * in , TIndex offset , CPUContext * context ) { <nl> + process ( const Meta & meta , const T * in , int64_t offset , CPUContext * context ) { <nl> CAFFE_ENFORCE ( <nl> meta . first_dim , <nl> " WeightedSumReducer implemented only for " <nl> class WeightedSumReducerGradient : public BaseReducerGradient { <nl> void fillGrad ( <nl> const Meta & meta , <nl> T * data_grad , <nl> - TIndex offset , <nl> + int64_t offset , <nl> Context * context , <nl> const int / * length * / ) { <nl> math : : ScaleFixedSize < T , CPUContext , FixedSize > ( <nl> class WeightedSumReducerGradient : public BaseReducerGradient { <nl> const Meta & meta , <nl> const T * data , <nl> T * data_grad , <nl> - TIndex offset , <nl> + int64_t offset , <nl> Context * context , <nl> const int / * length * / ) { <nl> math : : ScaleFixedSize < T , CPUContext , FixedSize > ( <nl> class MeanReducer < T , CPUContext > : public BaseReducer { <nl> void process ( <nl> const Meta & meta , <nl> const T * in , <nl> - TIndex / * offset * / , <nl> + int64_t / * offset * / , <nl> CPUContext * context ) { <nl> if ( meta . first_dim ) { <nl> math : : AxpyFixedSize < T , CPUContext , FixedSize > ( <nl> class MeanReducerGradient : public BaseReducerGradient { <nl> void fillGrad ( <nl> const Meta & meta , <nl> T * data_grad , <nl> - TIndex offset , <nl> + int64_t offset , <nl> Context * context , <nl> const int length ) { <nl> CAFFE_ENFORCE_GT ( length , 0 , " Segment length must be > 0 " ) ; <nl> class MaxReducer < T , CPUContext > : public BaseReducer { <nl> void process ( <nl> const Meta & meta , <nl> const T * in , <nl> - TIndex / * offset * / , <nl> + int64_t / * offset * / , <nl> CPUContext * context ) { <nl> CAFFE_ENFORCE ( <nl> meta . first_dim , <nl> class MaxReducerGradient : public BaseReducerGradient { <nl> const T * data , <nl> T * data_grad , <nl> const T * forward_output , <nl> - TIndex / * offset * / , <nl> + int64_t / * offset * / , <nl> Context * / * context * / , <nl> const int / * length * / ) { <nl> - for ( TIndex i = 0 ; i < meta . block_size ; + + i ) { <nl> + for ( int64_t i = 0 ; i < meta . block_size ; + + i ) { <nl> data_grad [ i ] = data [ i ] = = forward_output [ i ] ? s_grad_ [ i ] : 0 ; <nl> } <nl> } <nl> mmm a / caffe2 / operators / reduction_front_back_ops . h <nl> ppp b / caffe2 / operators / reduction_front_back_ops . h <nl> class SumReduceDimsOp final : public Operator < Context > { <nl> num_reduce_dims_ > = 0 & & num_reduce_dims_ < = X . dims ( ) . size ( ) , <nl> " For N - dim input tensor , support num_reduce_dims in range [ 0 , N ] . " ) ; <nl> <nl> - vector < TIndex > output_shape ; <nl> + vector < int64_t > output_shape ; <nl> int start_index = FIRSTDIMS ? num_reduce_dims_ : 0 ; <nl> int end_index = <nl> FIRSTDIMS ? X . dims ( ) . size ( ) : X . dims ( ) . size ( ) - num_reduce_dims_ ; <nl> class SumReduceDimsGradientOp final : public Operator < Context > { <nl> / / the shape of the input to the data tensor . This made the backward <nl> / / computation incompatible with old models . To fix this , we check <nl> / / the dimension and type of Input ( 1 ) . <nl> - if ( input_1 . ndim ( ) = = 1 & & input_1 . template IsType < TIndex > ( ) ) { <nl> + if ( input_1 . ndim ( ) = = 1 & & input_1 . template IsType < int64_t > ( ) ) { <nl> / / Input ( 1 ) is the shape of the input <nl> shape_ . CopyFrom ( input_1 ) ; <nl> / / Copy first dims <nl> - vector < TIndex > output_shape ( <nl> - shape_ . template data < TIndex > ( ) , <nl> - shape_ . template data < TIndex > ( ) + shape_ . size ( ) ) ; <nl> + vector < int64_t > output_shape ( <nl> + shape_ . template data < int64_t > ( ) , <nl> + shape_ . template data < int64_t > ( ) + shape_ . size ( ) ) ; <nl> dX - > Resize ( output_shape ) ; <nl> } else { <nl> / / Input ( 1 ) is data tensor X <nl> class MaxReduceDimsOp final : public Operator < Context > { <nl> const int cols = FIRSTDIMS ? X . size_from_dim ( num_reduce_dims_ ) <nl> : X . size_from_dim ( X . ndim ( ) - num_reduce_dims_ ) ; <nl> <nl> - vector < TIndex > output_shape ; <nl> + vector < int64_t > output_shape ; <nl> int start_index = FIRSTDIMS ? num_reduce_dims_ : 0 ; <nl> int end_index = <nl> FIRSTDIMS ? X . dims ( ) . size ( ) : X . dims ( ) . size ( ) - num_reduce_dims_ ; <nl> mmm a / caffe2 / operators / reduction_ops . h <nl> ppp b / caffe2 / operators / reduction_ops . h <nl> class SumElementsOp : public Operator < Context > { <nl> bool RunOnDevice ( ) override { <nl> auto & X = Input ( 0 ) ; <nl> auto * sum = Output ( 0 ) ; <nl> - sum - > Resize ( vector < TIndex > ( ) ) ; <nl> + sum - > Resize ( vector < int64_t > ( ) ) ; <nl> <nl> T * data = sum - > template mutable_data < T > ( ) ; <nl> <nl> class SumElementsIntOp : public Operator < Context > { <nl> bool RunOnDevice ( ) override { <nl> auto & X = Input ( 0 ) ; <nl> auto * sum = Output ( 0 ) ; <nl> - sum - > Resize ( vector < TIndex > ( ) ) ; <nl> + sum - > Resize ( vector < int64_t > ( ) ) ; <nl> T * data = sum - > template mutable_data < T > ( ) ; <nl> math : : Sum < T , Context > ( <nl> X . size ( ) , X . template data < T > ( ) , data , & context_ , & scratch_ ) ; <nl> class SumSqrElementsOp : public Operator < Context > { <nl> bool average = this - > template GetSingleArgument < bool > ( " average " , false ) ; <nl> auto & X = Input ( 0 ) ; <nl> auto * sum = Output ( 0 ) ; <nl> - sum - > Resize ( vector < TIndex > ( ) ) ; <nl> + sum - > Resize ( vector < int64_t > ( ) ) ; <nl> math : : SumSqr < T , Context > ( <nl> X . size ( ) , <nl> X . template data < T > ( ) , <nl> mmm a / caffe2 / operators / replace_nan_op . cc <nl> ppp b / caffe2 / operators / replace_nan_op . cc <nl> template < > <nl> template < typename T > <nl> void ReplaceNaNOp < CPUContext > : : ReplaceNaN ( <nl> const T & value , <nl> - const TIndex size , <nl> + const int64_t size , <nl> const T * X , <nl> T * Y ) { <nl> - for ( TIndex i = 0 ; i < size ; i + + ) { <nl> + for ( int64_t i = 0 ; i < size ; i + + ) { <nl> if ( std : : isnan ( X [ i ] ) ) { <nl> Y [ i ] = value ; <nl> } else { <nl> mmm a / caffe2 / operators / replace_nan_op . cu <nl> ppp b / caffe2 / operators / replace_nan_op . cu <nl> namespace caffe2 { <nl> namespace { <nl> template < typename T > <nl> __global__ void <nl> - replace_nan_kernel ( const T value , const TIndex size , const T * X , T * Y ) { <nl> + replace_nan_kernel ( const T value , const int64_t size , const T * X , T * Y ) { <nl> CUDA_1D_KERNEL_LOOP ( i , size ) { <nl> if ( isnan ( X [ i ] ) ) { <nl> Y [ i ] = value ; <nl> template < > <nl> template < typename T > <nl> void ReplaceNaNOp < CUDAContext > : : ReplaceNaN ( <nl> const T & value , <nl> - const TIndex size , <nl> + const int64_t size , <nl> const T * X , <nl> T * Y ) { <nl> replace_nan_kernel < < < <nl> mmm a / caffe2 / operators / replace_nan_op . h <nl> ppp b / caffe2 / operators / replace_nan_op . h <nl> class ReplaceNaNOp final : public Operator < Context > { <nl> } <nl> <nl> template < typename T > <nl> - void ReplaceNaN ( const T & value , const TIndex size , const T * X , T * Y ) ; <nl> + void ReplaceNaN ( const T & value , const int64_t size , const T * X , T * Y ) ; <nl> <nl> template < typename T > <nl> bool DoRunWithType ( ) { <nl> mmm a / caffe2 / operators / reshape_op_gpu_test . cc <nl> ppp b / caffe2 / operators / reshape_op_gpu_test . cc <nl> CAFFE2_DECLARE_string ( caffe_test_root ) ; <nl> namespace caffe2 { <nl> <nl> static void AddConstInput ( <nl> - const vector < TIndex > & shape , <nl> + const vector < int64_t > & shape , <nl> const float value , <nl> const string & name , <nl> Workspace * ws ) { <nl> TEST ( ReshapeOpGPUTest , testReshapeWithScalar ) { <nl> def . add_output ( " OldShape " ) ; <nl> def . add_arg ( ) - > CopyFrom ( MakeArgument ( " shape " , vector < int64_t > { 1 } ) ) ; <nl> def . mutable_device_option ( ) - > set_device_type ( PROTO_CUDA ) ; <nl> - AddConstInput ( vector < TIndex > ( ) , 3 . 14 , " X " , & ws ) ; <nl> + AddConstInput ( vector < int64_t > ( ) , 3 . 14 , " X " , & ws ) ; <nl> / / execute the op <nl> unique_ptr < OperatorBase > op ( CreateOperator ( def , & ws ) ) ; <nl> EXPECT_TRUE ( op - > Run ( ) ) ; <nl> mmm a / caffe2 / operators / reverse_packed_segs_op . h <nl> ppp b / caffe2 / operators / reverse_packed_segs_op . h <nl> class ReversePackedSegsOp final : public Operator < Context > { <nl> context_ . FinishDeviceComputation ( ) ; <nl> <nl> T * rev_data_ptr = output - > template mutable_data < T > ( ) ; <nl> - for ( TIndex i = 0 ; i < batch_size ; i + + ) { <nl> + for ( int64_t i = 0 ; i < batch_size ; i + + ) { <nl> const auto & seg_length = lengths_host [ i ] ; <nl> CAFFE_ENFORCE_LE ( seg_length , max_length ) ; <nl> - TIndex j = 0 ; <nl> + int64_t j = 0 ; <nl> for ( ; j < seg_length ; j + + ) { <nl> const T * data_block_ptr = data_ptr + ( j * batch_size + i ) * block_size ; <nl> T * rev_data_block_ptr = <nl> mmm a / caffe2 / operators / rnn / hip / recurrent_op_miopen . h <nl> ppp b / caffe2 / operators / rnn / hip / recurrent_op_miopen . h <nl> class RecurrentBaseOp : public Operator < HIPContext > { <nl> std : : unique_ptr < detail : : TensorDescriptors < T > > xDesc_ ; <nl> std : : unique_ptr < detail : : TensorDescriptors < T > > yDesc_ ; <nl> <nl> - std : : vector < TIndex > cachedInputDims_ ; <nl> + std : : vector < int64_t > cachedInputDims_ ; <nl> size_t reserveNbytes_ ; <nl> size_t miopenWsNbytes_ ; <nl> <nl> mmm a / caffe2 / operators / rnn / recurrent_network_blob_fetcher_op . h <nl> ppp b / caffe2 / operators / rnn / recurrent_network_blob_fetcher_op . h <nl> class RecurrentNetworkBlobFetcherOp final : public Operator < Context > { <nl> <nl> std : : vector < std : : string > blob_names_vector = { } ; <nl> <nl> - for ( TIndex i = 0 ; i < stepWorkspaces . size ( ) ; i + + ) { <nl> + for ( int64_t i = 0 ; i < stepWorkspaces . size ( ) ; i + + ) { <nl> Workspace * currentStepWorkspace = stepWorkspaces [ i ] . get ( ) ; <nl> std : : vector < std : : string > blob_names = currentStepWorkspace - > LocalBlobs ( ) ; <nl> <nl> mmm a / caffe2 / operators / rnn / recurrent_network_op . h <nl> ppp b / caffe2 / operators / rnn / recurrent_network_op . h <nl> class RNNApplyLinkOp : public Operator < Context > { <nl> auto * external_out = Output ( 1 ) ; <nl> <nl> CAFFE_ENFORCE_GT ( external . size ( ) , 0 ) ; <nl> - const TIndex externalTimestepSize = external . size ( ) / external . dim ( 0 ) ; <nl> + const int64_t externalTimestepSize = external . size ( ) / external . dim ( 0 ) ; <nl> auto * externalData = external_out - > template mutable_data < T > ( ) + <nl> ( t + offset_ ) * externalTimestepSize ; <nl> auto internalDims = external_out - > dims ( ) ; <nl> mmm a / caffe2 / operators / rnn / recurrent_op_cudnn . h <nl> ppp b / caffe2 / operators / rnn / recurrent_op_cudnn . h <nl> class RecurrentBaseOp : public Operator < CUDAContext > { <nl> std : : unique_ptr < detail : : TensorDescriptors < T > > xDesc_ ; <nl> std : : unique_ptr < detail : : TensorDescriptors < T > > yDesc_ ; <nl> <nl> - std : : vector < TIndex > cachedInputDims_ ; <nl> + std : : vector < int64_t > cachedInputDims_ ; <nl> size_t reserveNbytes_ ; <nl> size_t cudnnWsNbytes_ ; <nl> <nl> mmm a / caffe2 / operators / roi_align_op_gpu_test . cc <nl> ppp b / caffe2 / operators / roi_align_op_gpu_test . cc <nl> namespace { <nl> <nl> template < class Context > <nl> void AddConstInput ( <nl> - const vector < TIndex > & shape , <nl> + const vector < int64_t > & shape , <nl> const float value , <nl> const string & name , <nl> Context * context , <nl> void AddConstInput ( <nl> <nl> template < class Context > <nl> void AddInput ( <nl> - const vector < TIndex > & shape , <nl> + const vector < int64_t > & shape , <nl> const vector < float > & values , <nl> const string & name , <nl> Workspace * ws ) ; <nl> <nl> template < > <nl> void AddInput < CPUContext > ( <nl> - const vector < TIndex > & shape , <nl> + const vector < int64_t > & shape , <nl> const vector < float > & values , <nl> const string & name , <nl> Workspace * ws ) { <nl> void AddInput < CPUContext > ( <nl> <nl> template < > <nl> void AddInput < CUDAContext > ( <nl> - const vector < TIndex > & shape , <nl> + const vector < int64_t > & shape , <nl> const vector < float > & values , <nl> const string & name , <nl> Workspace * ws ) { <nl> void CreateAndRun ( <nl> vector < float > features ( N * C * H * W ) ; <nl> std : : iota ( features . begin ( ) , features . end ( ) , 0 ) ; <nl> / / utils : : AsEArrXt ( features ) / = features . size ( ) ; <nl> - AddInput < Context > ( vector < TIndex > { N , C , H , W } , features , " X " , & ws ) ; <nl> + AddInput < Context > ( vector < int64_t > { N , C , H , W } , features , " X " , & ws ) ; <nl> const int n_rois = test_params . n_rois ; <nl> const vector < float > & rois = test_params . rois_array ; <nl> - AddInput < Context > ( vector < TIndex > { n_rois , 5 } , rois , " R " , & ws ) ; <nl> + AddInput < Context > ( vector < int64_t > { n_rois , 5 } , rois , " R " , & ws ) ; <nl> } else { <nl> const int N = 2 ; <nl> const int C = 3 ; <nl> void CreateAndRun ( <nl> vector < float > features ( N * C * H * W ) ; <nl> std : : iota ( features . begin ( ) , features . end ( ) , 0 ) ; <nl> / / utils : : AsEArrXt ( features ) / = features . size ( ) ; <nl> - AddInput < Context > ( vector < TIndex > { N , C , H , W } , features , " X " , & ws ) ; <nl> + AddInput < Context > ( vector < int64_t > { N , C , H , W } , features , " X " , & ws ) ; <nl> vector < float > rois { 0 , 0 , 0 , 79 , 59 , <nl> 0 , 0 , 5 . 0005703f , 52 . 63237f , 43 . 69501495f , <nl> 0 , 24 . 13628387f , 7 . 51243401f , 79 , 46 . 06628418f , <nl> void CreateAndRun ( <nl> 0 , 23 . 57396317f , 29 . 98791885f , 79 , 59 , <nl> 0 , 0 , 41 . 90219116f , 79 , 59 , <nl> 0 , 0 , 23 . 30098343f , 79 , 59 } ; <nl> - AddInput < Context > ( vector < TIndex > { 9 , 5 } , rois , " R " , & ws ) ; <nl> + AddInput < Context > ( vector < int64_t > { 9 , 5 } , rois , " R " , & ws ) ; <nl> } <nl> <nl> std : : vector < unique_ptr < OperatorBase > > ops ; <nl> mmm a / caffe2 / operators / segment_reduction_op . h <nl> ppp b / caffe2 / operators / segment_reduction_op . h <nl> class BaseInputAccessor { <nl> } <nl> <nl> inline const TData * <nl> - getBlockPtr ( TIndex in_block_size , TIndex idx , TIndex / * blocks * / = 1 ) { <nl> + getBlockPtr ( int64_t in_block_size , int64_t idx , int64_t / * blocks * / = 1 ) { <nl> return static_cast < const TData * > ( data_ ) + in_block_size * idx ; <nl> } <nl> <nl> class AbstractSortedSegmentRangeOp : public Operator < Context > { <nl> return true ; <nl> } <nl> <nl> - TIndex block_size = dataInput . size ( ) / N ; <nl> + int64_t block_size = dataInput . size ( ) / N ; <nl> <nl> / / Assume the segments are sorted and there are no gaps <nl> CAFFE_ENFORCE_EQ ( 0 , s_ids [ 0 ] , " Indices must be sorted and not have gaps " ) ; <nl> - for ( TIndex i = 0 ; i < N ; ) { <nl> - TIndex start = i ; <nl> + for ( int64_t i = 0 ; i < N ; ) { <nl> + int64_t start = i ; <nl> for ( + + i ; i < N & & s_ids [ start ] = = s_ids [ i ] ; + + i ) <nl> ; <nl> <nl> class AbstractSortedSegmentRangeGradientOp : public Operator < Context > { <nl> auto * data_grads = Output ( 0 ) ; <nl> <nl> CAFFE_ENFORCE_EQ ( 1 , segment_ids . ndim ( ) , " SEGMENT_IDS must be a vector " ) ; <nl> - TIndex N = segment_ids . dim ( 0 ) ; <nl> + int64_t N = segment_ids . dim ( 0 ) ; <nl> <nl> const SIndex * s_ids = segment_ids . template data < SIndex > ( ) ; <nl> const T * s_grads = segment_grads . template data < T > ( ) ; <nl> class AbstractSortedSegmentRangeGradientOp : public Operator < Context > { <nl> return true ; <nl> } <nl> <nl> - TIndex block_size = segment_grads . size_from_dim ( 1 ) ; <nl> + int64_t block_size = segment_grads . size_from_dim ( 1 ) ; <nl> <nl> / / Assume the segments are sorted and there are no gaps <nl> CAFFE_ENFORCE_EQ ( 0 , s_ids [ 0 ] , " Indices must be sorted and not have gaps " ) ; <nl> / / repeat the check from forward op <nl> CAFFE_ENFORCE_EQ ( <nl> K - 1 , s_ids [ N - 1 ] , " Indices must be sorted and not have gaps " ) ; <nl> - for ( TIndex i = 0 ; i < N ; ) { <nl> - TIndex start = i ; <nl> + for ( int64_t i = 0 ; i < N ; ) { <nl> + int64_t start = i ; <nl> for ( + + i ; i < N & & s_ids [ start ] = = s_ids [ i ] ; + + i ) <nl> ; <nl> <nl> class AbstractReduceFrontOrBackOp : public Operator < Context > { <nl> auto & data = Input ( 0 ) ; <nl> / / If more complicated fixed size logic becomes necessary , it can be moved <nl> / / to the reducer class <nl> - TIndex in_block_size = FirstDim <nl> + int64_t in_block_size = FirstDim <nl> ? data . size_from_dim ( num_reduce_dims_ ) <nl> : data . size_to_dim ( data . ndim ( ) - num_reduce_dims_ ) ; <nl> return DispatchHelper < typename Reducer : : FixedDispatch > : : call ( <nl> class AbstractReduceFrontOrBackOp : public Operator < Context > { <nl> data . meta ( ) . name ( ) , <nl> " . " ) ; <nl> <nl> - vector < TIndex > shape ; <nl> + vector < int64_t > shape ; <nl> ctx . appendOutputShape ( & shape ) ; <nl> output - > Resize ( shape ) ; <nl> <nl> class AbstractReduceFrontOrBackOp : public Operator < Context > { <nl> const int num_blocks = block_size > 0 ? data . size ( ) / block_size : 0 ; <nl> <nl> Reducer r ( ctx , out , & context_ ) ; <nl> - for ( TIndex i = 0 ; i < num_blocks ; + + i ) { <nl> + for ( int64_t i = 0 ; i < num_blocks ; + + i ) { <nl> r . template process < FixedSize > ( <nl> ctx , inputAccessor_ . getBlockPtr ( block_size , i ) , i , & context_ ) ; <nl> } <nl> class AbstractReduceFrontOrBackGradientOp : public Operator < Context > { <nl> bool RunOnDevice ( ) override { <nl> / / If more complicated fixed size logic becomes necessary , it can be moved <nl> / / to the reducer class <nl> - TIndex grad_block_size = Input ( REDUCTION_GRAD ) . size ( ) ; <nl> + int64_t grad_block_size = Input ( REDUCTION_GRAD ) . size ( ) ; <nl> return DispatchHelper < typename ReducerGradient : : FixedDispatch > : : call ( <nl> this , grad_block_size ) ; <nl> } <nl> class AbstractReduceFrontOrBackGradientOp : public Operator < Context > { <nl> <nl> CAFFE_ENFORCE_LE ( num_reduce_dims_ , source_shape . size ( ) ) ; <nl> <nl> - vector < TIndex > shape ( <nl> - source_shape . template data < TIndex > ( ) , <nl> - source_shape . template data < TIndex > ( ) + source_shape . size ( ) ) ; <nl> + vector < int64_t > shape ( <nl> + source_shape . template data < int64_t > ( ) , <nl> + source_shape . template data < int64_t > ( ) + source_shape . size ( ) ) ; <nl> <nl> data_grads - > Resize ( shape ) ; <nl> <nl> - TIndex block_size = FirstDim <nl> + int64_t block_size = FirstDim <nl> ? data_grads - > size_from_dim ( num_reduce_dims_ ) <nl> : data_grads - > size_from_dim ( data_grads - > ndim ( ) - num_reduce_dims_ ) ; <nl> - TIndex block_num = block_size > 0 ? data_grads - > size ( ) / block_size : 0 ; <nl> + int64_t block_num = block_size > 0 ? data_grads - > size ( ) / block_size : 0 ; <nl> <nl> T * out = data_grads - > template mutable_data < T > ( ) ; <nl> <nl> ReducerGradient r ( ctx , r_grad , & context_ ) ; <nl> - for ( TIndex i = 0 ; i < block_num ; + + i ) { <nl> + for ( int64_t i = 0 ; i < block_num ; + + i ) { <nl> r . template fillGrad < FixedSize > ( <nl> ctx , <nl> out + block_size * i , <nl> UnsortedSegment { op } but as if all input slices belong to a single segment . <nl> ArgumentHelper helper ( def ) ; <nl> int num_reduce_dims = helper . GetSingleArgument < int > ( " num_reduce_dim " , 1 ) ; <nl> typename ReducerDef : : template Reducer < T , Context > : : Meta ctx ( true ) ; <nl> - vector < TIndex > out_dims = ctx . getOutputShape ( in [ 0 ] , num_reduce_dims ) ; <nl> + vector < int64_t > out_dims = ctx . getOutputShape ( in [ 0 ] , num_reduce_dims ) ; <nl> return vector < TensorShape > { <nl> CreateTensorShape ( out_dims , in [ 0 ] . data_type ( ) ) } ; <nl> } ) ; <nl> UnsortedSegment { op } but as if all input slices belong to a single segment . <nl> ArgumentHelper helper ( def ) ; <nl> int num_reduce_dims = helper . GetSingleArgument < int > ( " num_reduce_dim " , 1 ) ; <nl> typename ReducerDef : : template Reducer < T , Context > : : Meta ctx ( false ) ; <nl> - vector < TIndex > out_dims = ctx . getOutputShape ( in [ 0 ] , num_reduce_dims ) ; <nl> + vector < int64_t > out_dims = ctx . getOutputShape ( in [ 0 ] , num_reduce_dims ) ; <nl> return vector < TensorShape > { <nl> CreateTensorShape ( out_dims , in [ 0 ] . data_type ( ) ) } ; <nl> } ) ; <nl> class AbstractSortedSegmentOp : public Operator < Context > { <nl> this , Input ( INDICES ) ) ; <nl> } else { <nl> / / type doesn ' t matter <nl> - return DoRunWithType < TIndex > ( ) ; <nl> + return DoRunWithType < int64_t > ( ) ; <nl> } <nl> } <nl> <nl> class AbstractSortedSegmentOp : public Operator < Context > { <nl> bool DoRunWithType ( ) { <nl> / / If more complicated fixed size logic becomes necessary , it can be moved <nl> / / to the reducer class <nl> - TIndex in_block_size = Input ( 0 ) . size_from_dim ( 1 ) ; <nl> + int64_t in_block_size = Input ( 0 ) . size_from_dim ( 1 ) ; <nl> return DispatchHelper < typename Reducer : : FixedDispatch , IndexType > : : call ( <nl> this , in_block_size ) ; <nl> } <nl> class AbstractSortedSegmentOp : public Operator < Context > { <nl> auto * output = Output ( 0 ) ; <nl> <nl> CAFFE_ENFORCE_EQ ( 1 , segment_ids . ndim ( ) , " SEGMENT_IDS must be a vector " ) ; <nl> - TIndex N = segment_ids . dim ( 0 ) ; <nl> - const TIndex M = dataInput . dim ( 0 ) ; <nl> + int64_t N = segment_ids . dim ( 0 ) ; <nl> + const int64_t M = dataInput . dim ( 0 ) ; <nl> <nl> const IndexType * idxs ; <nl> if ( SparseFused ) { / / static if <nl> class AbstractSortedSegmentOp : public Operator < Context > { <nl> const SIndex * s_ids = segment_ids . template data < SIndex > ( ) ; <nl> <nl> const SIndex K = N > 0 ? s_ids [ N - 1 ] + 1 : 0 ; <nl> - vector < TIndex > shape ; <nl> + vector < int64_t > shape ; <nl> shape . push_back ( K ) ; <nl> ctx . appendOutputShape ( & shape ) ; <nl> output - > Resize ( shape ) ; <nl> class AbstractSortedSegmentOp : public Operator < Context > { <nl> if ( N = = 0 ) { <nl> return true ; <nl> } <nl> - TIndex in_block_size = dataInput . size_from_dim ( 1 ) ; <nl> - TIndex out_block_size = output - > size_from_dim ( 1 ) ; <nl> + int64_t in_block_size = dataInput . size_from_dim ( 1 ) ; <nl> + int64_t out_block_size = output - > size_from_dim ( 1 ) ; <nl> <nl> / / Assume the segments are sorted and there are no gaps <nl> CAFFE_ENFORCE_EQ ( 0 , s_ids [ 0 ] , " Indices must be sorted and not have gaps " ) ; <nl> - for ( TIndex i = 0 ; i < N ; ) { <nl> - TIndex start = i ; <nl> + for ( int64_t i = 0 ; i < N ; ) { <nl> + int64_t start = i ; <nl> <nl> Reducer r ( ctx , out + out_block_size * s_ids [ start ] , & context_ ) ; <nl> for ( ; i < N & & s_ids [ start ] = = s_ids [ i ] ; + + i ) { <nl> class AbstractSortedSegmentGradientOp : public Operator < Context > { <nl> bool RunOnDevice ( ) override { <nl> / / If more complicated fixed size logic becomes necessary , it can be moved <nl> / / to the reducer class <nl> - TIndex grad_block_size = Input ( SEGMENT_GRADS ) . size_from_dim ( 1 ) ; <nl> + int64_t grad_block_size = Input ( SEGMENT_GRADS ) . size_from_dim ( 1 ) ; <nl> return DispatchHelper < typename ReducerGradient : : FixedDispatch > : : call ( <nl> this , grad_block_size ) ; <nl> } <nl> class AbstractSortedSegmentGradientOp : public Operator < Context > { <nl> auto * data_grads = Output ( 0 ) ; <nl> <nl> CAFFE_ENFORCE_EQ ( 1 , segment_ids . ndim ( ) , " SEGMENT_IDS must be a vector " ) ; <nl> - TIndex N = segment_ids . dim ( 0 ) ; <nl> + int64_t N = segment_ids . dim ( 0 ) ; <nl> <nl> typename ReducerGradient : : Meta ctx ( segment_grads , 1 ) ; <nl> for ( int i = 0 ; i < ReducerGradient : : originalInputs ( ) . size ( ) ; + + i ) { <nl> class AbstractSortedSegmentGradientOp : public Operator < Context > { <nl> const SIndex * s_ids = segment_ids . template data < SIndex > ( ) ; <nl> const T * s_grads = segment_grads . template data < T > ( ) ; <nl> <nl> - vector < TIndex > shape ; <nl> + vector < int64_t > shape ; <nl> shape . push_back ( N ) ; <nl> ctx . appendGradShape ( & shape ) ; <nl> data_grads - > Resize ( shape ) ; <nl> <nl> - TIndex d_block_size = data_grads - > size_from_dim ( 1 ) ; <nl> + int64_t d_block_size = data_grads - > size_from_dim ( 1 ) ; <nl> const SIndex K = segment_grads . dim ( 0 ) ; <nl> - TIndex s_block_size = segment_grads . size_from_dim ( 1 ) ; <nl> + int64_t s_block_size = segment_grads . size_from_dim ( 1 ) ; <nl> T * out = data_grads - > template mutable_data < T > ( ) ; <nl> <nl> if ( N = = 0 ) { <nl> class AbstractSortedSegmentGradientOp : public Operator < Context > { <nl> / / repeat the check from forward op <nl> CAFFE_ENFORCE_EQ ( <nl> K - 1 , s_ids [ N - 1 ] , " Indices must be sorted and not have gaps " ) ; <nl> - for ( TIndex i = 0 ; i < N ; ) { <nl> - TIndex start = i ; <nl> - TIndex end = start ; <nl> + for ( int64_t i = 0 ; i < N ; ) { <nl> + int64_t start = i ; <nl> + int64_t end = start ; <nl> <nl> if ( ReducerGradient : : computeLength ( ) ) { <nl> for ( ; end < N & & s_ids [ start ] = = s_ids [ end ] ; + + end ) { <nl> class AbstractUnsortedSegmentOp : public Operator < Context > { <nl> this , Input ( INDICES ) ) ; <nl> } else { <nl> / / type doesn ' t matter <nl> - return DoRunWithType < TIndex > ( ) ; <nl> + return DoRunWithType < int64_t > ( ) ; <nl> } <nl> } <nl> <nl> class AbstractUnsortedSegmentOp : public Operator < Context > { <nl> bool DoRunWithType ( ) { <nl> / / If more complicated fixed size logic becomes necessary , it can be moved <nl> / / to the reducer class <nl> - TIndex in_block_size = Input ( 0 ) . size_from_dim ( 1 ) ; <nl> + int64_t in_block_size = Input ( 0 ) . size_from_dim ( 1 ) ; <nl> return DispatchHelper < typename Reducer : : FixedDispatch , IndexType > : : call ( <nl> this , in_block_size ) ; <nl> } <nl> class AbstractUnsortedSegmentOp : public Operator < Context > { <nl> auto * output = Output ( 0 ) ; <nl> <nl> CAFFE_ENFORCE_EQ ( 1 , segment_ids . ndim ( ) , " SEGMENT_IDS must be a vector " ) ; <nl> - TIndex N = segment_ids . dim ( 0 ) ; <nl> - const TIndex M = data . dim ( 0 ) ; <nl> + int64_t N = segment_ids . dim ( 0 ) ; <nl> + const int64_t M = data . dim ( 0 ) ; <nl> <nl> const IndexType * idxs ; <nl> if ( SparseFused ) { / / static if <nl> class AbstractUnsortedSegmentOp : public Operator < Context > { <nl> K = num_segments_ ; <nl> } else { <nl> K = 0 ; <nl> - for ( TIndex i = 0 ; i < N ; + + i ) { <nl> + for ( int64_t i = 0 ; i < N ; + + i ) { <nl> K = std : : max ( K , s_ids [ i ] + 1 ) ; <nl> } <nl> } <nl> <nl> - vector < TIndex > shape ; <nl> + vector < int64_t > shape ; <nl> shape . push_back ( K ) ; <nl> ctx . appendOutputShape ( & shape ) ; <nl> output - > Resize ( shape ) ; <nl> <nl> - TIndex in_block_size = data . size_from_dim ( 1 ) ; <nl> - TIndex out_block_size = output - > size_from_dim ( 1 ) ; <nl> + int64_t in_block_size = data . size_from_dim ( 1 ) ; <nl> + int64_t out_block_size = output - > size_from_dim ( 1 ) ; <nl> T * out = output - > template mutable_data < T > ( ) ; <nl> <nl> reducers_ . clear ( ) ; <nl> reducers_ . reserve ( K ) ; <nl> - for ( TIndex i = 0 ; i < K ; + + i ) { <nl> + for ( int64_t i = 0 ; i < K ; + + i ) { <nl> reducers_ . emplace_back ( ctx , out + out_block_size * i , & context_ ) ; <nl> } <nl> <nl> - for ( TIndex i = 0 ; i < N ; + + i ) { <nl> + for ( int64_t i = 0 ; i < N ; + + i ) { <nl> auto s_id = s_ids [ i ] ; <nl> CAFFE_ENFORCE ( <nl> 0 < = s_id & & s_id < K , <nl> class AbstractUnsortedSegmentOp : public Operator < Context > { <nl> ctx , inputAccessor_ . getBlockPtr ( in_block_size , idx ) , i , & context_ ) ; <nl> } <nl> <nl> - for ( TIndex i = 0 ; i < K ; + + i ) { <nl> + for ( int64_t i = 0 ; i < K ; + + i ) { <nl> reducers_ [ i ] . template finish < FixedSize > ( ctx , & context_ ) ; <nl> } <nl> / / call reducers destructors ( if there is any ) <nl> class AbstractUnsortedSegmentOp : public Operator < Context > { <nl> static constexpr int kNumInputs = Reducer : : kInputCount + kSelfInputs ; <nl> <nl> private : <nl> - TIndex num_segments_ ; <nl> + int64_t num_segments_ ; <nl> / / member field to reuse memory <nl> vector < Reducer > reducers_ ; <nl> InputAccessor inputAccessor_ ; <nl> class AbstractUnsortedSegmentGradientOp : public Operator < Context > { <nl> bool RunOnDevice ( ) override { <nl> / / If more complicated fixed size logic becomes necessary , it can be moved <nl> / / to the reducer class <nl> - TIndex grad_block_size = Input ( SEGMENT_GRADS ) . size_from_dim ( 1 ) ; <nl> + int64_t grad_block_size = Input ( SEGMENT_GRADS ) . size_from_dim ( 1 ) ; <nl> return DispatchHelper < typename ReducerGradient : : FixedDispatch > : : call ( <nl> this , grad_block_size ) ; <nl> } <nl> class AbstractUnsortedSegmentGradientOp : public Operator < Context > { <nl> auto * data_grads = Output ( 0 ) ; <nl> <nl> CAFFE_ENFORCE_EQ ( 1 , segment_ids . ndim ( ) , " SEGMENT_IDS must be a vector " ) ; <nl> - TIndex N = segment_ids . dim ( 0 ) ; <nl> + int64_t N = segment_ids . dim ( 0 ) ; <nl> <nl> typename ReducerGradient : : Meta ctx ( segment_grads , 1 ) ; <nl> for ( int i = 0 ; i < ReducerGradient : : originalInputs ( ) . size ( ) ; + + i ) { <nl> class AbstractUnsortedSegmentGradientOp : public Operator < Context > { <nl> const SIndex * s_ids = segment_ids . template data < SIndex > ( ) ; <nl> const T * s_grads = segment_grads . template data < T > ( ) ; <nl> <nl> - vector < TIndex > shape ; <nl> + vector < int64_t > shape ; <nl> shape . push_back ( N ) ; <nl> ctx . appendGradShape ( & shape ) ; <nl> data_grads - > Resize ( shape ) ; <nl> <nl> - TIndex d_block_size = data_grads - > size_from_dim ( 1 ) ; <nl> + int64_t d_block_size = data_grads - > size_from_dim ( 1 ) ; <nl> const SIndex K = segment_grads . dim ( 0 ) ; <nl> - TIndex s_block_size = segment_grads . size_from_dim ( 1 ) ; <nl> + int64_t s_block_size = segment_grads . size_from_dim ( 1 ) ; <nl> T * out = data_grads - > template mutable_data < T > ( ) ; <nl> <nl> if ( ReducerGradient : : computeLength ( ) ) { <nl> class AbstractUnsortedSegmentGradientOp : public Operator < Context > { <nl> reducers_ . emplace_back ( ctx , s_grads + s_block_size * i , & context_ ) ; <nl> } <nl> <nl> - for ( TIndex i = 0 ; i < N ; + + i ) { <nl> + for ( int64_t i = 0 ; i < N ; + + i ) { <nl> auto s_id = s_ids [ i ] ; <nl> if ( ReducerGradient : : computeLength ( ) ) { <nl> reducers_ [ s_id ] . template fillGrad < FixedSize > ( <nl> class AbstractLengthsOp : public Operator < Context > { <nl> this , Input ( INDICES ) ) ; <nl> } else { <nl> / / type doesn ' t matter <nl> - return DoRunWithType < TIndex > ( ) ; <nl> + return DoRunWithType < int64_t > ( ) ; <nl> } <nl> } <nl> <nl> class AbstractLengthsOp : public Operator < Context > { <nl> bool DoRunWithType ( ) { <nl> / / If more complicated fixed size logic becomes necessary , it can be moved <nl> / / to the reducer class <nl> - TIndex in_block_size = Input ( 0 ) . size_from_dim ( 1 ) ; <nl> + int64_t in_block_size = Input ( 0 ) . size_from_dim ( 1 ) ; <nl> return DispatchHelper < typename Reducer : : FixedDispatch , IndexType > : : call ( <nl> this , in_block_size ) ; <nl> } <nl> class AbstractLengthsOp : public Operator < Context > { <nl> auto * output = Output ( 0 ) ; <nl> <nl> CAFFE_ENFORCE_EQ ( 1 , lengthsInput . ndim ( ) , " LENGTHS must be a vector " ) ; <nl> - const TIndex dataSize = dataInput . dim ( 0 ) ; <nl> + const int64_t dataSize = dataInput . dim ( 0 ) ; <nl> / / Either first dim the data or how much we pull in indexies from it <nl> - TIndex dataToReduceSize ; <nl> - const TIndex outputSize = lengthsInput . dim ( 0 ) ; <nl> + int64_t dataToReduceSize ; <nl> + const int64_t outputSize = lengthsInput . dim ( 0 ) ; <nl> <nl> const IndexType * indices ; <nl> if ( SparseFused ) { / / static if <nl> class AbstractLengthsOp : public Operator < Context > { <nl> dataInput . meta ( ) . name ( ) , <nl> " . " ) ; <nl> <nl> - vector < TIndex > shape { outputSize } ; <nl> + vector < int64_t > shape { outputSize } ; <nl> ctx . appendOutputShape ( & shape ) ; <nl> output - > Resize ( shape ) ; <nl> <nl> - TIndex in_block_size = dataInput . size_from_dim ( 1 ) ; <nl> - TIndex out_block_size = output - > size_from_dim ( 1 ) ; <nl> + int64_t in_block_size = dataInput . size_from_dim ( 1 ) ; <nl> + int64_t out_block_size = output - > size_from_dim ( 1 ) ; <nl> TData * out = output - > template mutable_data < TData > ( ) ; <nl> <nl> - TIndex dataIndex = 0 ; <nl> - for ( TIndex rangeIndex = 0 ; rangeIndex < outputSize ; + + rangeIndex ) { <nl> + int64_t dataIndex = 0 ; <nl> + for ( int64_t rangeIndex = 0 ; rangeIndex < outputSize ; + + rangeIndex ) { <nl> Reducer reducer ( ctx , out + out_block_size * rangeIndex , & context_ ) ; <nl> - for ( TIndex start = dataIndex ; dataIndex < start + lengths [ rangeIndex ] ; <nl> + for ( int64_t start = dataIndex ; dataIndex < start + lengths [ rangeIndex ] ; <nl> + + dataIndex ) { <nl> IndexType idx ; <nl> if ( SparseFused ) { / / static if <nl> class AbstractLengthsGradientOp : public Operator < Context > { <nl> bool RunOnDevice ( ) override { <nl> / / If more complicated fixed size logic becomes necessary , it can be moved <nl> / / to the reducer class <nl> - TIndex gradBlockSize = Input ( SEGMENT_GRADS ) . size_from_dim ( 1 ) ; <nl> + int64_t gradBlockSize = Input ( SEGMENT_GRADS ) . size_from_dim ( 1 ) ; <nl> return DispatchHelper < typename ReducerGradient : : FixedDispatch > : : call ( <nl> this , gradBlockSize ) ; <nl> } <nl> class AbstractLengthsGradientOp : public Operator < Context > { <nl> auto * dataGradsOutput = Output ( 0 ) ; <nl> <nl> CAFFE_ENFORCE ( lengthsInput . ndim ( ) = = 1 , " LENGTHS must be a vector " ) ; <nl> - TIndex reducedDataSize = 0 ; <nl> - TIndex numSegments = lengthsInput . dim ( 0 ) ; <nl> + int64_t reducedDataSize = 0 ; <nl> + int64_t numSegments = lengthsInput . dim ( 0 ) ; <nl> CAFFE_ENFORCE ( segmentGradsInput . ndim ( ) > 0 ) ; <nl> CAFFE_ENFORCE ( numSegments = = segmentGradsInput . dim ( 0 ) ) ; <nl> const TLengths * lengths = lengthsInput . template data < TLengths > ( ) ; <nl> - for ( TIndex i = 0 ; i < numSegments ; + + i ) { <nl> + for ( int64_t i = 0 ; i < numSegments ; + + i ) { <nl> reducedDataSize + = lengths [ i ] ; <nl> } <nl> <nl> class AbstractLengthsGradientOp : public Operator < Context > { <nl> <nl> const T * segmentGrads = segmentGradsInput . template data < T > ( ) ; <nl> <nl> - vector < TIndex > shape ; <nl> + vector < int64_t > shape ; <nl> shape . push_back ( reducedDataSize ) ; <nl> ctx . appendGradShape ( & shape ) ; <nl> dataGradsOutput - > Resize ( shape ) ; <nl> <nl> - TIndex dataGradsBlockSize = dataGradsOutput - > size_from_dim ( 1 ) ; <nl> - TIndex segmentBlockSize = segmentGradsInput . size_from_dim ( 1 ) ; <nl> + int64_t dataGradsBlockSize = dataGradsOutput - > size_from_dim ( 1 ) ; <nl> + int64_t segmentBlockSize = segmentGradsInput . size_from_dim ( 1 ) ; <nl> T * dataGrads = dataGradsOutput - > template mutable_data < T > ( ) ; <nl> <nl> - TIndex dataIndex = 0 ; <nl> - for ( TIndex rangeIndex = 0 ; rangeIndex < numSegments ; + + rangeIndex ) { <nl> + int64_t dataIndex = 0 ; <nl> + for ( int64_t rangeIndex = 0 ; rangeIndex < numSegments ; + + rangeIndex ) { <nl> ReducerGradient reducer ( <nl> ctx , segmentGrads + segmentBlockSize * rangeIndex , & context_ ) ; <nl> - for ( TIndex start = dataIndex ; dataIndex < start + lengths [ rangeIndex ] ; <nl> + for ( int64_t start = dataIndex ; dataIndex < start + lengths [ rangeIndex ] ; <nl> + + dataIndex ) { <nl> reducer . template fillGrad < FixedSize > ( <nl> ctx , <nl> class AbstractLengthsWithMainInputGradientOp : public Operator < Context > { <nl> this , Input ( INDICES ) ) ; <nl> } else { <nl> / / type doesn ' t matter <nl> - return DoRunWithType < TIndex > ( ) ; <nl> + return DoRunWithType < int64_t > ( ) ; <nl> } <nl> } <nl> <nl> class AbstractLengthsWithMainInputGradientOp : public Operator < Context > { <nl> bool DoRunWithType ( ) { <nl> / / If more complicated fixed size logic becomes necessary , it can be moved <nl> / / to the reducer class <nl> - TIndex in_block_size = Input ( SEGMENT_GRADS ) . size_from_dim ( 1 ) ; <nl> + int64_t in_block_size = Input ( SEGMENT_GRADS ) . size_from_dim ( 1 ) ; <nl> return DispatchHelper < typename ReducerGradient : : FixedDispatch , IndexType > : : <nl> call ( this , in_block_size ) ; <nl> } <nl> class AbstractLengthsWithMainInputGradientOp : public Operator < Context > { <nl> auto * dataGradsOutput = Output ( 0 ) ; <nl> <nl> CAFFE_ENFORCE ( lengthsInput . ndim ( ) = = 1 , " LENGTHS must be a vector " ) ; <nl> - TIndex numSegments = lengthsInput . dim ( 0 ) ; <nl> + int64_t numSegments = lengthsInput . dim ( 0 ) ; <nl> CAFFE_ENFORCE ( segmentGradsInput . ndim ( ) > 0 ) ; <nl> CAFFE_ENFORCE ( numSegments = = segmentGradsInput . dim ( 0 ) ) ; <nl> const TLengths * lengths = lengthsInput . template data < TLengths > ( ) ; <nl> class AbstractLengthsWithMainInputGradientOp : public Operator < Context > { <nl> } <nl> <nl> / / Either first dim the data or how much we pull in indexies from it <nl> - TIndex dataToReduceSize ; <nl> + int64_t dataToReduceSize ; <nl> const IndexType * indices = nullptr ; <nl> if ( SparseFused ) { / / static if <nl> auto & indicesInput = Input ( INDICES ) ; <nl> class AbstractLengthsWithMainInputGradientOp : public Operator < Context > { <nl> <nl> const T * segmentGrads = segmentGradsInput . template data < T > ( ) ; <nl> <nl> - vector < TIndex > shape ; <nl> + vector < int64_t > shape ; <nl> shape . push_back ( dataToReduceSize ) ; <nl> ctx . appendGradShape ( & shape ) ; <nl> dataGradsOutput - > Resize ( shape ) ; <nl> <nl> - TIndex dataGradsBlockSize = dataGradsOutput - > size_from_dim ( 1 ) ; <nl> - TIndex segmentBlockSize = segmentGradsInput . size_from_dim ( 1 ) ; <nl> + int64_t dataGradsBlockSize = dataGradsOutput - > size_from_dim ( 1 ) ; <nl> + int64_t segmentBlockSize = segmentGradsInput . size_from_dim ( 1 ) ; <nl> T * dataGrads = dataGradsOutput - > template mutable_data < T > ( ) ; <nl> <nl> const T * data = dataInput . template data < T > ( ) ; <nl> <nl> - TIndex dataIndex = 0 ; <nl> - for ( TIndex rangeIndex = 0 ; rangeIndex < numSegments ; + + rangeIndex ) { <nl> + int64_t dataIndex = 0 ; <nl> + for ( int64_t rangeIndex = 0 ; rangeIndex < numSegments ; + + rangeIndex ) { <nl> ReducerGradient reducer ( <nl> ctx , segmentGrads + segmentBlockSize * rangeIndex , & context_ ) ; <nl> - for ( TIndex start = dataIndex ; dataIndex < start + lengths [ rangeIndex ] ; <nl> + for ( int64_t start = dataIndex ; dataIndex < start + lengths [ rangeIndex ] ; <nl> + + dataIndex ) { <nl> IndexType data_pos ; <nl> / / No range checking , should ' ve been verified in forward pass <nl> class AbstractLengthsWithMainInputAndForwardOutputGradientOp <nl> bool RunOnDevice ( ) override { <nl> / / If more complicated fixed size logic becomes necessary , it can be moved <nl> / / to the reducer class . <nl> - TIndex in_block_size = Input ( SEGMENT_GRADS ) . size_from_dim ( 1 ) ; <nl> + int64_t in_block_size = Input ( SEGMENT_GRADS ) . size_from_dim ( 1 ) ; <nl> return DispatchHelper < typename ReducerGradient : : FixedDispatch > : : call ( <nl> this , in_block_size ) ; <nl> } <nl> class AbstractLengthsWithMainInputAndForwardOutputGradientOp <nl> auto * dataGradsOutput = Output ( 0 ) ; <nl> <nl> CAFFE_ENFORCE ( lengthsInput . ndim ( ) = = 1 , " LENGTHS must be a vector " ) ; <nl> - TIndex numSegments = lengthsInput . dim ( 0 ) ; <nl> + int64_t numSegments = lengthsInput . dim ( 0 ) ; <nl> CAFFE_ENFORCE ( segmentGradsInput . ndim ( ) > 0 ) ; <nl> CAFFE_ENFORCE ( numSegments = = segmentGradsInput . dim ( 0 ) ) ; <nl> const TLengths * lengths = lengthsInput . template data < TLengths > ( ) ; <nl> class AbstractLengthsWithMainInputAndForwardOutputGradientOp <nl> CAFFE_ENFORCE ( numSegments = = forwardOutputInput . dim ( 0 ) ) ; <nl> const T * forwardOutput = forwardOutputInput . template data < T > ( ) ; <nl> <nl> - TIndex dataToReduceSize = dataInput . dim ( 0 ) ; <nl> + int64_t dataToReduceSize = dataInput . dim ( 0 ) ; <nl> <nl> const T * segmentGrads = segmentGradsInput . template data < T > ( ) ; <nl> <nl> - vector < TIndex > shape ; <nl> + vector < int64_t > shape ; <nl> shape . push_back ( dataToReduceSize ) ; <nl> ctx . appendGradShape ( & shape ) ; <nl> dataGradsOutput - > Resize ( shape ) ; <nl> <nl> - TIndex dataGradsBlockSize = dataGradsOutput - > size_from_dim ( 1 ) ; <nl> - TIndex segmentBlockSize = segmentGradsInput . size_from_dim ( 1 ) ; <nl> + int64_t dataGradsBlockSize = dataGradsOutput - > size_from_dim ( 1 ) ; <nl> + int64_t segmentBlockSize = segmentGradsInput . size_from_dim ( 1 ) ; <nl> T * dataGrads = dataGradsOutput - > template mutable_data < T > ( ) ; <nl> <nl> const T * data = dataInput . template data < T > ( ) ; <nl> <nl> - TIndex dataIndex = 0 ; <nl> - for ( TIndex rangeIndex = 0 ; rangeIndex < numSegments ; + + rangeIndex ) { <nl> + int64_t dataIndex = 0 ; <nl> + for ( int64_t rangeIndex = 0 ; rangeIndex < numSegments ; + + rangeIndex ) { <nl> ReducerGradient reducer ( <nl> ctx , segmentGrads + segmentBlockSize * rangeIndex , & context_ ) ; <nl> - for ( TIndex start = dataIndex ; dataIndex < start + lengths [ rangeIndex ] ; <nl> + for ( int64_t start = dataIndex ; dataIndex < start + lengths [ rangeIndex ] ; <nl> + + dataIndex ) { <nl> / / No range checking , should ' ve been verified in forward pass <nl> reducer . template fillGradWithMainInputAndForwardOutput < FixedSize > ( <nl> mmm a / caffe2 / operators / segment_reduction_op_gpu . cu <nl> ppp b / caffe2 / operators / segment_reduction_op_gpu . cu <nl> class CUDASparseLengthsSumOp : public Operator < CUDAContext > { <nl> auto * output = Output ( 0 ) ; <nl> <nl> CAFFE_ENFORCE_EQ ( 1 , lengthsInput . ndim ( ) , " LENGTHS must be a vector " ) ; <nl> - const TIndex dataSize = dataInput . dim ( 0 ) ; <nl> + const int64_t dataSize = dataInput . dim ( 0 ) ; <nl> / / Either first dim the data or how much we pull in indexies from it <nl> - TIndex dataToReduceSize ; <nl> - const TIndex outputSize = lengthsInput . dim ( 0 ) ; <nl> + int64_t dataToReduceSize ; <nl> + const int64_t outputSize = lengthsInput . dim ( 0 ) ; <nl> const int len_length = outputSize ; <nl> <nl> auto shape = dataInput . dims ( ) ; <nl> class CUDASparseLengthsMeanOp : public Operator < CUDAContext > { <nl> auto * output = Output ( 0 ) ; <nl> <nl> CAFFE_ENFORCE_EQ ( 1 , lengthsInput . ndim ( ) , " LENGTHS must be a vector " ) ; <nl> - const TIndex dataSize = dataInput . dim ( 0 ) ; <nl> + const int64_t dataSize = dataInput . dim ( 0 ) ; <nl> / / Either first dim the data or how much we pull in indexies from it <nl> - TIndex dataToReduceSize ; <nl> - const TIndex outputSize = lengthsInput . dim ( 0 ) ; <nl> + int64_t dataToReduceSize ; <nl> + const int64_t outputSize = lengthsInput . dim ( 0 ) ; <nl> const int len_length = outputSize ; <nl> <nl> auto shape = dataInput . dims ( ) ; <nl> class CUDASparseLengthsMaxOp : public Operator < CUDAContext > { <nl> auto * output = Output ( 0 ) ; <nl> <nl> CAFFE_ENFORCE_EQ ( 1 , lengthsInput . ndim ( ) , " LENGTHS must be a vector " ) ; <nl> - const TIndex dataSize = dataInput . dim ( 0 ) ; <nl> + const int64_t dataSize = dataInput . dim ( 0 ) ; <nl> / / Either first dim the data or how much we pull in indexies from it <nl> - TIndex dataToReduceSize ; <nl> - const TIndex outputSize = lengthsInput . dim ( 0 ) ; <nl> + int64_t dataToReduceSize ; <nl> + const int64_t outputSize = lengthsInput . dim ( 0 ) ; <nl> int len_length = outputSize ; <nl> <nl> auto shape = dataInput . dims ( ) ; <nl> class CUDASparseLengthsWeightedSumOp : public Operator < CUDAContext > { <nl> CAFFE_ENFORCE_EQ ( 1 , indicesInput . ndim ( ) , " INDICES must be a vector " ) ; <nl> CAFFE_ENFORCE_EQ ( 1 , lengthsInput . ndim ( ) , " LENGTHS must be a vector " ) ; <nl> <nl> - const TIndex dataSize = dataInput . dim ( 0 ) ; <nl> + const int64_t dataSize = dataInput . dim ( 0 ) ; <nl> / / Either first dim the data or how much we pull in indexies from it <nl> - const TIndex dataToReduceSize = indicesInput . dim ( 0 ) ; <nl> - const TIndex outputSize = lengthsInput . dim ( 0 ) ; <nl> + const int64_t dataToReduceSize = indicesInput . dim ( 0 ) ; <nl> + const int64_t outputSize = lengthsInput . dim ( 0 ) ; <nl> const int len_length = outputSize ; <nl> <nl> auto shape = dataInput . dims ( ) ; <nl> class CUDAUnsortedSegmentSumOp : public Operator < CUDAContext > { <nl> } <nl> <nl> CAFFE_ENFORCE_EQ ( 1 , segment_ids . ndim ( ) , " SEGMENT_IDS must be a vector " ) ; <nl> - TIndex slize_sz = data . size_from_dim ( 1 ) ; <nl> + int64_t slize_sz = data . size_from_dim ( 1 ) ; <nl> <nl> K_tensor_ . Resize ( 1 ) ; <nl> / / Get maximum segment id so we can size the output . <nl> mmm a / caffe2 / operators / sequence_ops . cc <nl> ppp b / caffe2 / operators / sequence_ops . cc <nl> bool RemovePaddingOp < CPUContext > : : DoRunWithType ( ) { <nl> CAFFE_ENFORCE_GE ( in . ndim ( ) , 1 ) ; <nl> const int32_t outer_size = in . dims ( ) [ 0 ] ; <nl> const auto block_size = std : : accumulate ( <nl> - in . dims ( ) . begin ( ) + 1 , in . dims ( ) . end ( ) , 1 , std : : multiplies < TIndex > ( ) ) ; <nl> + in . dims ( ) . begin ( ) + 1 , in . dims ( ) . end ( ) , 1 , std : : multiplies < int64_t > ( ) ) ; <nl> const auto pad_width = startPaddingWidth_ + endPaddingWidth_ ; <nl> <nl> / / if no lengths is provided , assume it is a single full - span entry <nl> mmm a / caffe2 / operators / sequence_ops . cu <nl> ppp b / caffe2 / operators / sequence_ops . cu <nl> bool RemovePaddingOp < CUDAContext > : : DoRunWithType ( ) { <nl> CAFFE_ENFORCE_GE ( in . ndim ( ) , 1 ) ; <nl> const int32_t outer_size = in . dims ( ) [ 0 ] ; <nl> const auto block_size = std : : accumulate ( <nl> - in . dims ( ) . begin ( ) + 1 , in . dims ( ) . end ( ) , 1 , std : : multiplies < TIndex > ( ) ) ; <nl> + in . dims ( ) . begin ( ) + 1 , in . dims ( ) . end ( ) , 1 , std : : multiplies < int64_t > ( ) ) ; <nl> <nl> / / if no lengths is provided , assume it is a single full - span entry <nl> const int32_t * lengths_ptr = nullptr ; <nl> mmm a / caffe2 / operators / sequence_ops . h <nl> ppp b / caffe2 / operators / sequence_ops . h <nl> class GatherPaddingOp final : public Operator < Context > { <nl> <nl> bool RunOnDevice ( ) override { <nl> if ( startPaddingWidth_ = = 0 & & endPaddingWidth_ = = 0 ) { <nl> - Output ( 0 ) - > Resize ( std : : vector < TIndex > ( 0 ) ) ; <nl> - Output ( 0 ) - > template mutable_data < TIndex > ( ) ; <nl> + Output ( 0 ) - > Resize ( std : : vector < int64_t > ( 0 ) ) ; <nl> + Output ( 0 ) - > template mutable_data < int64_t > ( ) ; <nl> if ( OutputSize ( ) = = 2 ) { <nl> - Output ( 1 ) - > Resize ( std : : vector < TIndex > ( 0 ) ) ; <nl> - Output ( 1 ) - > template mutable_data < TIndex > ( ) ; <nl> + Output ( 1 ) - > Resize ( std : : vector < int64_t > ( 0 ) ) ; <nl> + Output ( 1 ) - > template mutable_data < int64_t > ( ) ; <nl> } <nl> return true ; <nl> } <nl> class GatherPaddingOp final : public Operator < Context > { <nl> lengths_ptr = lengths . template data < int32_t > ( ) ; <nl> lengths_size = lengths . size ( ) ; <nl> } <nl> - std : : vector < TIndex > padShape ( in . dims ( ) . begin ( ) + 1 , in . dims ( ) . end ( ) ) ; <nl> + std : : vector < int64_t > padShape ( in . dims ( ) . begin ( ) + 1 , in . dims ( ) . end ( ) ) ; <nl> / / output will contain accumulator over paddings <nl> Output ( 0 ) - > Resize ( padShape ) ; <nl> T * padding_start_ptr = Output ( 0 ) - > template mutable_data < T > ( ) ; <nl> mmm a / caffe2 / operators / shape_op . h <nl> ppp b / caffe2 / operators / shape_op . h <nl> class ShapeOp : public Operator < Context > { <nl> int numAxes = axes_ . size ( ) ; <nl> if ( numAxes = = 0 ) { <nl> output - > Resize ( numDims ) ; <nl> - TIndex * output_data = output - > template mutable_data < TIndex > ( ) ; <nl> + int64_t * output_data = output - > template mutable_data < int64_t > ( ) ; <nl> context_ . CopyBytesSameDevice ( <nl> - numDims * sizeof ( TIndex ) , data . dims ( ) . data ( ) , output_data ) ; <nl> + numDims * sizeof ( int64_t ) , data . dims ( ) . data ( ) , output_data ) ; <nl> return true ; <nl> } <nl> <nl> output - > Resize ( numAxes ) ; <nl> auto src = reinterpret_cast < const char * > ( data . dims ( ) . data ( ) ) ; <nl> - auto out = reinterpret_cast < char * > ( output - > template mutable_data < TIndex > ( ) ) ; <nl> + auto out = reinterpret_cast < char * > ( output - > template mutable_data < int64_t > ( ) ) ; <nl> for ( int i = 0 ; i < numAxes ; i + + ) { <nl> auto axis = axes_ [ i ] ; <nl> CAFFE_ENFORCE_LT ( axis , numDims , " Axis out of range " ) ; <nl> CAFFE_ENFORCE_GE ( axis , 0 , " Each axis should be non - negative " ) ; <nl> context_ . CopyBytesSameDevice ( <nl> - sizeof ( TIndex ) , src + axis * sizeof ( TIndex ) , out ) ; <nl> - out + = sizeof ( TIndex ) ; <nl> + sizeof ( int64_t ) , src + axis * sizeof ( int64_t ) , out ) ; <nl> + out + = sizeof ( int64_t ) ; <nl> } <nl> return true ; <nl> } <nl> mmm a / caffe2 / operators / slice_op . cu <nl> ppp b / caffe2 / operators / slice_op . cu <nl> class SliceOp < CUDAContext > : public Operator < CUDAContext > { <nl> USE_OPERATOR_FUNCTIONS ( CUDAContext ) ; <nl> SliceOp ( const OperatorDef & operator_def , Workspace * ws ) <nl> : Operator < CUDAContext > ( operator_def , ws ) , <nl> - starts_ ( this - > template GetRepeatedArgument < TIndex > ( " starts " ) ) , <nl> - ends_ ( this - > template GetRepeatedArgument < TIndex > ( " ends " ) ) , <nl> + starts_ ( this - > template GetRepeatedArgument < int64_t > ( " starts " ) ) , <nl> + ends_ ( this - > template GetRepeatedArgument < int64_t > ( " ends " ) ) , <nl> statically_inited_ ( false ) { } <nl> <nl> bool RunOnDevice ( ) override { <nl> if ( InputSize ( ) > 1 ) { <nl> - return DispatchHelper < TensorTypes < int , TIndex > > : : call ( this , Input ( 1 ) ) ; <nl> + return DispatchHelper < TensorTypes < int , int64_t > > : : call ( this , Input ( 1 ) ) ; <nl> } else { <nl> - return DoRunWithType < TIndex > ( ) ; <nl> + return DoRunWithType < int64_t > ( ) ; <nl> } <nl> } <nl> <nl> class SliceOp < CUDAContext > : public Operator < CUDAContext > { <nl> output , data , starts_host_ , ends_host_ , & context_ ) ; <nl> } <nl> private : <nl> - std : : vector < TIndex > starts_ ; <nl> - std : : vector < TIndex > ends_ ; <nl> + std : : vector < int64_t > starts_ ; <nl> + std : : vector < int64_t > ends_ ; <nl> bool statically_inited_ ; <nl> Tensor starts_host_ { CPU } ; <nl> Tensor ends_host_ { CPU } ; <nl> class SliceGradientOp < CUDAContext > : public Operator < CUDAContext > { <nl> USE_OPERATOR_FUNCTIONS ( CUDAContext ) ; <nl> SliceGradientOp ( const OperatorDef & operator_def , Workspace * ws ) <nl> : Operator < CUDAContext > ( operator_def , ws ) , <nl> - starts_ ( this - > template GetRepeatedArgument < TIndex > ( " starts " ) ) , <nl> - ends_ ( this - > template GetRepeatedArgument < TIndex > ( " ends " ) ) , <nl> + starts_ ( this - > template GetRepeatedArgument < int64_t > ( " starts " ) ) , <nl> + ends_ ( this - > template GetRepeatedArgument < int64_t > ( " ends " ) ) , <nl> statically_inited_ ( false ) { } <nl> <nl> AT_DISABLE_COPY_AND_ASSIGN ( SliceGradientOp ) ; <nl> <nl> bool RunOnDevice ( ) override { <nl> if ( InputSize ( ) = = 4 ) { <nl> - return DispatchHelper < TensorTypes < int , TIndex > > : : call ( this , Input ( 1 ) ) ; <nl> + return DispatchHelper < TensorTypes < int , int64_t > > : : call ( this , Input ( 1 ) ) ; <nl> } else { <nl> - return DoRunWithType < TIndex > ( ) ; <nl> + return DoRunWithType < int64_t > ( ) ; <nl> } <nl> } <nl> <nl> class SliceGradientOp < CUDAContext > : public Operator < CUDAContext > { <nl> } <nl> private : <nl> <nl> - std : : vector < TIndex > starts_ ; <nl> - std : : vector < TIndex > ends_ ; <nl> + std : : vector < int64_t > starts_ ; <nl> + std : : vector < int64_t > ends_ ; <nl> bool statically_inited_ ; <nl> Tensor starts_host_ { CPU } ; <nl> Tensor ends_host_ { CPU } ; <nl> mmm a / caffe2 / operators / slice_op . h <nl> ppp b / caffe2 / operators / slice_op . h <nl> class SliceOp : public Operator < Context > { <nl> USE_OPERATOR_CONTEXT_FUNCTIONS ; <nl> SliceOp ( const OperatorDef & operator_def , Workspace * ws ) <nl> : Operator < Context > ( operator_def , ws ) , <nl> - starts_ ( this - > template GetRepeatedArgument < TIndex > ( " starts " ) ) , <nl> - ends_ ( this - > template GetRepeatedArgument < TIndex > ( " ends " ) ) , <nl> + starts_ ( this - > template GetRepeatedArgument < int64_t > ( " starts " ) ) , <nl> + ends_ ( this - > template GetRepeatedArgument < int64_t > ( " ends " ) ) , <nl> statically_inited_ ( false ) { } <nl> <nl> bool RunOnDevice ( ) override { <nl> if ( InputSize ( ) > 1 ) { <nl> - return DispatchHelper < TensorTypes < int , TIndex > > : : call ( this , Input ( 1 ) ) ; <nl> + return DispatchHelper < TensorTypes < int , int64_t > > : : call ( this , Input ( 1 ) ) ; <nl> } else { <nl> - return DoRunWithType < TIndex > ( ) ; <nl> + return DoRunWithType < int64_t > ( ) ; <nl> } <nl> } <nl> <nl> class SliceOp : public Operator < Context > { <nl> AT_DISABLE_COPY_AND_ASSIGN ( SliceOp ) ; <nl> <nl> protected : <nl> - std : : vector < TIndex > starts_ ; <nl> - std : : vector < TIndex > ends_ ; <nl> + std : : vector < int64_t > starts_ ; <nl> + std : : vector < int64_t > ends_ ; <nl> bool statically_inited_ ; <nl> Tensor starts_host_ { CPU } ; <nl> Tensor ends_host_ { CPU } ; <nl> class SliceGradientOp : public Operator < Context > { <nl> USE_OPERATOR_CONTEXT_FUNCTIONS ; <nl> SliceGradientOp ( const OperatorDef & operator_def , Workspace * ws ) <nl> : Operator < Context > ( operator_def , ws ) , <nl> - starts_ ( this - > template GetRepeatedArgument < TIndex > ( " starts " ) ) , <nl> - ends_ ( this - > template GetRepeatedArgument < TIndex > ( " ends " ) ) , <nl> + starts_ ( this - > template GetRepeatedArgument < int64_t > ( " starts " ) ) , <nl> + ends_ ( this - > template GetRepeatedArgument < int64_t > ( " ends " ) ) , <nl> statically_inited_ ( false ) { } <nl> <nl> AT_DISABLE_COPY_AND_ASSIGN ( SliceGradientOp ) ; <nl> <nl> bool RunOnDevice ( ) override { <nl> if ( InputSize ( ) = = 4 ) { <nl> - return DispatchHelper < TensorTypes < int , TIndex > > : : call ( this , Input ( 1 ) ) ; <nl> + return DispatchHelper < TensorTypes < int , int64_t > > : : call ( this , Input ( 1 ) ) ; <nl> } else { <nl> - return DoRunWithType < TIndex > ( ) ; <nl> + return DoRunWithType < int64_t > ( ) ; <nl> } <nl> } <nl> <nl> class SliceGradientOp : public Operator < Context > { <nl> <nl> private : <nl> <nl> - std : : vector < TIndex > starts_ ; <nl> - std : : vector < TIndex > ends_ ; <nl> + std : : vector < int64_t > starts_ ; <nl> + std : : vector < int64_t > ends_ ; <nl> bool statically_inited_ ; <nl> Tensor starts_host_ { CPU } ; <nl> Tensor ends_host_ { CPU } ; <nl> mmm a / caffe2 / operators / softmax_op_cudnn . cc <nl> ppp b / caffe2 / operators / softmax_op_cudnn . cc <nl> class CuDNNSoftmaxOp final : public Operator < CUDAContext > { <nl> CuDNNWrapper cudnn_wrapper_ ; <nl> int axis_ ; <nl> cudnnTensorDescriptor_t desc_ ; <nl> - vector < TIndex > dims_ ; <nl> + vector < int64_t > dims_ ; <nl> } ; <nl> <nl> <nl> class CuDNNSoftmaxGradientOp final : public Operator < CUDAContext > { <nl> CuDNNWrapper cudnn_wrapper_ ; <nl> int axis_ ; <nl> cudnnTensorDescriptor_t desc_ ; <nl> - vector < TIndex > dims_ ; <nl> + vector < int64_t > dims_ ; <nl> } ; <nl> <nl> namespace { <nl> mmm a / caffe2 / operators / softmax_ops . cu <nl> ppp b / caffe2 / operators / softmax_ops . cu <nl> bool SoftmaxWithLossOp < float , CUDAContext > : : RunOnDevice ( ) { <nl> } <nl> } <nl> <nl> - avg_loss - > Resize ( vector < TIndex > ( ) ) ; <nl> + avg_loss - > Resize ( vector < int64_t > ( ) ) ; <nl> if ( losses_ . size ( ) ! = N ) { <nl> losses_ . Resize ( N ) ; <nl> } <nl> bool SpatialSoftmaxWithLossOp < float , CUDAContext > : : RunOnDevice ( ) { <nl> context_ . cuda_stream ( ) > > > ( N , D , W , H , Xdata , Pdata ) ; <nl> <nl> / / Cross entropy <nl> - avg_loss - > Resize ( vector < TIndex > ( ) ) ; <nl> + avg_loss - > Resize ( vector < int64_t > ( ) ) ; <nl> float * avg_loss_data = avg_loss - > template mutable_data < float > ( ) ; <nl> math : : Set < float , CUDAContext > ( 1 , 0 . 0f , avg_loss_data , & context_ ) ; <nl> <nl> mmm a / caffe2 / operators / softmax_with_loss_op . cc <nl> ppp b / caffe2 / operators / softmax_with_loss_op . cc <nl> bool SoftmaxWithLossOp < float , CPUContext > : : RunOnDevice ( ) { <nl> } <nl> } <nl> <nl> - avg_loss - > Resize ( vector < TIndex > ( ) ) ; <nl> + avg_loss - > Resize ( vector < int64_t > ( ) ) ; <nl> float * avg_loss_data = avg_loss - > template mutable_data < float > ( ) ; <nl> if ( weight_sum ! = 0 . 0 ) { <nl> avg_loss_data [ 0 ] = loss_sum * scale_ / weight_sum ; <nl> mmm a / caffe2 / operators / sparse_to_dense_mask_op . h <nl> ppp b / caffe2 / operators / sparse_to_dense_mask_op . h <nl> class SparseToDenseMaskOp : public SparseToDenseMaskBase < Context > { <nl> static_cast < const char * > ( sparse_values . raw_data ( ) ) ; <nl> const void * default_val = default_value . raw_data ( ) ; <nl> <nl> - TIndex block_size = default_value . size ( ) ; <nl> + int64_t block_size = default_value . size ( ) ; <nl> size_t block_nbytes = default_value . nbytes ( ) ; <nl> <nl> const int cols = this - > featuresCount_ ; <nl> class SparseToDenseMaskOp : public SparseToDenseMaskBase < Context > { <nl> if ( returnPresenceMask_ ) { <nl> presence_mask = Output ( PRESENCEMASK ) ; <nl> } <nl> - vector < TIndex > shape ; <nl> + vector < int64_t > shape ; <nl> if ( InputSize ( ) = = 4 ) { <nl> auto & lengths = Input ( LENGTHS ) ; <nl> CAFFE_ENFORCE_EQ ( lengths . ndim ( ) , 1 ) ; <nl> class SparseToDenseMaskGradientOp : public SparseToDenseMaskBase < Context > { <nl> CAFFE_ENFORCE_EQ ( sparse_indices . ndim ( ) , 1 ) ; <nl> auto & gradient_output = Input ( GOUTPUT ) ; <nl> <nl> - TIndex block_size = gradient_output . size_from_dim ( 1 ) ; <nl> + int64_t block_size = gradient_output . size_from_dim ( 1 ) ; <nl> size_t block_nbytes = gradient_output . itemsize ( ) * block_size ; <nl> <nl> const int cols = this - > featuresCount_ ; <nl> class SparseToDenseMaskGradientOp : public SparseToDenseMaskBase < Context > { <nl> int32_t default_length = sparse_indices . dim32 ( 0 ) ; <nl> const int32_t * lengths_vec = nullptr ; <nl> auto * output = Output ( GVALUES ) ; <nl> - vector < TIndex > shape ; <nl> + vector < int64_t > shape ; <nl> if ( InputSize ( ) > LENGTHS ) { <nl> / / if the LENGTHS is set , the gradient_output has dim : <nl> / / lengths * mask . size ( ) * feature_dim <nl> mmm a / caffe2 / operators / sparse_to_dense_op . cu <nl> ppp b / caffe2 / operators / sparse_to_dense_op . cu <nl> namespace caffe2 { <nl> <nl> template < typename TInd , typename TData > <nl> __global__ void SparseToDenseKernel ( <nl> - size_t N , TIndex block_nitems , const TInd * indices , const TData * vals , TData * dst ) { <nl> + size_t N , int64_t block_nitems , const TInd * indices , const TData * vals , TData * dst ) { <nl> CUDA_1D_KERNEL_LOOP ( i , N ) { <nl> int idx = indices [ i / block_nitems ] ; <nl> int dst_idx = block_nitems * idx + i % block_nitems ; <nl> mmm a / caffe2 / operators / spatial_softmax_with_loss_op . cc <nl> ppp b / caffe2 / operators / spatial_softmax_with_loss_op . cc <nl> bool SpatialSoftmaxWithLossOp < float , CPUContext > : : RunOnDevice ( ) { <nl> } <nl> <nl> / / Compute the avg cross - entropy loss <nl> - avg_loss - > Resize ( vector < TIndex > ( ) ) ; <nl> + avg_loss - > Resize ( vector < int64_t > ( ) ) ; <nl> float * avg_loss_data = avg_loss - > template mutable_data < float > ( ) ; <nl> const int * label_data = T . data < int > ( ) ; <nl> <nl> mmm a / caffe2 / operators / text_file_reader . cc <nl> ppp b / caffe2 / operators / text_file_reader . cc <nl> class TextFileReaderReadOp : public Operator < CPUContext > { <nl> } <nl> <nl> private : <nl> - TIndex batchSize_ ; <nl> + int64_t batchSize_ ; <nl> } ; <nl> <nl> CAFFE_KNOWN_TYPE ( std : : unique_ptr < TextFileReaderInstance > ) ; <nl> mmm a / caffe2 / operators / tile_op . h <nl> ppp b / caffe2 / operators / tile_op . h <nl> class TileOp : public Operator < Context > { <nl> const auto axis = input . canonical_axis_index ( axis_ ) ; <nl> <nl> / / reshape output to be input tiled along the axis <nl> - vector < TIndex > output_dims ( input . dims ( ) ) ; <nl> + vector < int64_t > output_dims ( input . dims ( ) ) ; <nl> output_dims [ axis_ ] = output_dims [ axis_ ] * tiles_ ; <nl> output - > Resize ( output_dims ) ; <nl> <nl> class TileGradientOp : public Operator < Context > { <nl> const auto axis = input . canonical_axis_index ( axis_ ) ; <nl> <nl> / / reshape output to be input " untiled " along the axis <nl> - vector < TIndex > output_dims ( input . dims ( ) ) ; <nl> + vector < int64_t > output_dims ( input . dims ( ) ) ; <nl> output_dims [ axis_ ] = output_dims [ axis_ ] / tiles_ ; <nl> output - > Resize ( output_dims ) ; <nl> <nl> mmm a / caffe2 / operators / top_k . cc <nl> ppp b / caffe2 / operators / top_k . cc <nl> namespace { <nl> template < typename T > <nl> struct ValueComp { <nl> bool operator ( ) ( <nl> - const std : : pair < T , TIndex > & lhs , <nl> - const std : : pair < T , TIndex > & rhs ) const { <nl> + const std : : pair < T , int64_t > & lhs , <nl> + const std : : pair < T , int64_t > & rhs ) const { <nl> return lhs . first > rhs . first | | <nl> ( lhs . first = = rhs . first & & lhs . second < rhs . second ) ; <nl> } <nl> struct ValueComp { <nl> template < typename T > <nl> void GetTopK ( <nl> const T * input , <nl> - const TIndex n , <nl> - const TIndex k , <nl> - const TIndex src_offset , <nl> - const TIndex dst_offset , <nl> - const TIndex stride , <nl> + const int64_t n , <nl> + const int64_t k , <nl> + const int64_t src_offset , <nl> + const int64_t dst_offset , <nl> + const int64_t stride , <nl> T * values , <nl> - TIndex * indices , <nl> - TIndex * flatten_indices ) { <nl> + int64_t * indices , <nl> + int64_t * flatten_indices ) { <nl> const T * src_ptr = input + src_offset ; <nl> - std : : vector < std : : pair < T , TIndex > > heap_data ; <nl> + std : : vector < std : : pair < T , int64_t > > heap_data ; <nl> heap_data . reserve ( k ) ; <nl> - for ( TIndex i = 0 ; i < k & & i < n ; + + i ) { <nl> + for ( int64_t i = 0 ; i < k & & i < n ; + + i ) { <nl> heap_data . emplace_back ( * src_ptr , i ) ; <nl> src_ptr + = stride ; <nl> } <nl> std : : priority_queue < <nl> - std : : pair < T , TIndex > , <nl> - std : : vector < std : : pair < T , TIndex > > , <nl> + std : : pair < T , int64_t > , <nl> + std : : vector < std : : pair < T , int64_t > > , <nl> ValueComp < T > > <nl> pq ( ValueComp < T > ( ) , std : : move ( heap_data ) ) ; <nl> - for ( TIndex i = k ; i < n ; + + i ) { <nl> + for ( int64_t i = k ; i < n ; + + i ) { <nl> if ( pq . top ( ) . first < * src_ptr ) { <nl> pq . pop ( ) ; <nl> pq . emplace ( * src_ptr , i ) ; <nl> } <nl> src_ptr + = stride ; <nl> } <nl> - TIndex dst_pos = dst_offset + ( std : : min ( k , n ) - 1 ) * stride ; <nl> + int64_t dst_pos = dst_offset + ( std : : min ( k , n ) - 1 ) * stride ; <nl> while ( ! pq . empty ( ) ) { <nl> const auto & item = pq . top ( ) ; <nl> values [ dst_pos ] = item . first ; <nl> void GetTopK ( <nl> template < typename T > <nl> void SetTopKGradient ( <nl> const T * values , <nl> - const TIndex * indices , <nl> + const int64_t * indices , <nl> const int k , <nl> - const TIndex src_offset , <nl> - const TIndex dst_offset , <nl> - const TIndex stride , <nl> + const int64_t src_offset , <nl> + const int64_t dst_offset , <nl> + const int64_t stride , <nl> T * gradient ) { <nl> - TIndex src_pos = src_offset ; <nl> + int64_t src_pos = src_offset ; <nl> for ( int i = 0 ; i < k ; + + i ) { <nl> if ( indices [ src_pos ] < 0 ) { <nl> continue ; <nl> bool TopKOp < T , Context > : : RunOnDevice ( ) { <nl> auto * indices = Output ( 1 ) ; <nl> auto * flatten_indices = OutputSize ( ) > 2 ? Output ( 2 ) : nullptr ; <nl> <nl> - const std : : vector < TIndex > & input_dims = input . dims ( ) ; <nl> + const std : : vector < int64_t > & input_dims = input . dims ( ) ; <nl> if ( axis_ = = - 1 ) { <nl> axis_ = input_dims . size ( ) - 1 ; <nl> } <nl> CAFFE_ENFORCE_GE ( axis_ , 0 ) ; <nl> CAFFE_ENFORCE_LT ( axis_ , input_dims . size ( ) ) ; <nl> <nl> - std : : vector < TIndex > output_dims = input_dims ; <nl> + std : : vector < int64_t > output_dims = input_dims ; <nl> output_dims [ axis_ ] = k_ ; <nl> values - > Resize ( output_dims ) ; <nl> indices - > Resize ( output_dims ) ; <nl> bool TopKOp < T , Context > : : RunOnDevice ( ) { <nl> } <nl> const T * input_data = input . template data < T > ( ) ; <nl> T * values_data = values - > template mutable_data < T > ( ) ; <nl> - TIndex * indices_data = indices - > template mutable_data < TIndex > ( ) ; <nl> - TIndex * flatten_indices_data = flatten_indices = = nullptr <nl> + int64_t * indices_data = indices - > template mutable_data < int64_t > ( ) ; <nl> + int64_t * flatten_indices_data = flatten_indices = = nullptr <nl> ? nullptr <nl> - : flatten_indices - > template mutable_data < TIndex > ( ) ; <nl> + : flatten_indices - > template mutable_data < int64_t > ( ) ; <nl> / / init values as the default value <nl> math : : Set < T , Context > ( values - > size ( ) , T ( 0 ) , values_data , & context_ ) ; <nl> - math : : Set < TIndex , Context > ( <nl> - indices - > size ( ) , TIndex ( - 1 ) , indices_data , & context_ ) ; <nl> + math : : Set < int64_t , Context > ( <nl> + indices - > size ( ) , int64_t ( - 1 ) , indices_data , & context_ ) ; <nl> if ( flatten_indices_data ! = nullptr ) { <nl> - math : : Set < TIndex , Context > ( <nl> - flatten_indices - > size ( ) , TIndex ( - 1 ) , flatten_indices_data , & context_ ) ; <nl> + math : : Set < int64_t , Context > ( <nl> + flatten_indices - > size ( ) , int64_t ( - 1 ) , flatten_indices_data , & context_ ) ; <nl> } <nl> <nl> - const TIndex prev_size = std : : accumulate ( <nl> + const int64_t prev_size = std : : accumulate ( <nl> input_dims . cbegin ( ) , <nl> input_dims . cbegin ( ) + axis_ , <nl> - TIndex ( 1 ) , <nl> - std : : multiplies < TIndex > ( ) ) ; <nl> - const TIndex next_size = std : : accumulate ( <nl> + int64_t ( 1 ) , <nl> + std : : multiplies < int64_t > ( ) ) ; <nl> + const int64_t next_size = std : : accumulate ( <nl> input_dims . cbegin ( ) + axis_ + 1 , <nl> input_dims . cend ( ) , <nl> - TIndex ( 1 ) , <nl> - std : : multiplies < TIndex > ( ) ) ; <nl> - const TIndex src_offset_stride = input_dims [ axis_ ] * next_size ; <nl> - const TIndex dst_offset_stride = k_ * next_size ; <nl> - TIndex src_offset = 0 ; <nl> - TIndex dst_offset = 0 ; <nl> - for ( TIndex i = 0 ; i < prev_size ; + + i ) { <nl> - for ( TIndex j = 0 ; j < next_size ; + + j ) { <nl> + int64_t ( 1 ) , <nl> + std : : multiplies < int64_t > ( ) ) ; <nl> + const int64_t src_offset_stride = input_dims [ axis_ ] * next_size ; <nl> + const int64_t dst_offset_stride = k_ * next_size ; <nl> + int64_t src_offset = 0 ; <nl> + int64_t dst_offset = 0 ; <nl> + for ( int64_t i = 0 ; i < prev_size ; + + i ) { <nl> + for ( int64_t j = 0 ; j < next_size ; + + j ) { <nl> GetTopK ( <nl> input_data , <nl> input_dims [ axis_ ] , <nl> bool TopKGradientOp < T , Context > : : RunOnDevice ( ) { <nl> const auto & indices = Input ( 1 ) ; <nl> const auto & original_input = Input ( 2 ) ; <nl> auto * output = Output ( 0 ) ; <nl> - const std : : vector < TIndex > & values_dims = values . dims ( ) ; <nl> - const std : : vector < TIndex > & origin_dims = original_input . dims ( ) ; <nl> + const std : : vector < int64_t > & values_dims = values . dims ( ) ; <nl> + const std : : vector < int64_t > & origin_dims = original_input . dims ( ) ; <nl> CAFFE_ENFORCE_EQ ( values_dims . size ( ) , origin_dims . size ( ) ) ; <nl> output - > Resize ( origin_dims ) ; <nl> const T * values_data = values . template data < T > ( ) ; <nl> - const TIndex * indices_data = indices . template data < TIndex > ( ) ; <nl> + const int64_t * indices_data = indices . template data < int64_t > ( ) ; <nl> T * output_data = output - > template mutable_data < T > ( ) ; <nl> if ( axis_ = = - 1 ) { <nl> axis_ = values_dims . size ( ) - 1 ; <nl> } <nl> const int k = values_dims [ axis_ ] ; <nl> math : : Set < T , Context > ( output - > size ( ) , T ( 0 ) , output_data , & context_ ) ; <nl> - const TIndex prev_size = std : : accumulate ( <nl> + const int64_t prev_size = std : : accumulate ( <nl> values_dims . cbegin ( ) , <nl> values_dims . cbegin ( ) + axis_ , <nl> - TIndex ( 1 ) , <nl> - std : : multiplies < TIndex > ( ) ) ; <nl> - const TIndex next_size = std : : accumulate ( <nl> + int64_t ( 1 ) , <nl> + std : : multiplies < int64_t > ( ) ) ; <nl> + const int64_t next_size = std : : accumulate ( <nl> values_dims . cbegin ( ) + axis_ + 1 , <nl> values_dims . cend ( ) , <nl> - TIndex ( 1 ) , <nl> - std : : multiplies < TIndex > ( ) ) ; <nl> - const TIndex src_offset_stride = k * next_size ; <nl> - const TIndex dst_offset_stride = origin_dims [ axis_ ] * next_size ; <nl> - TIndex src_offset = 0 ; <nl> - TIndex dst_offset = 0 ; <nl> - for ( TIndex i = 0 ; i < prev_size ; + + i ) { <nl> - for ( TIndex j = 0 ; j < next_size ; + + j ) { <nl> + int64_t ( 1 ) , <nl> + std : : multiplies < int64_t > ( ) ) ; <nl> + const int64_t src_offset_stride = k * next_size ; <nl> + const int64_t dst_offset_stride = origin_dims [ axis_ ] * next_size ; <nl> + int64_t src_offset = 0 ; <nl> + int64_t dst_offset = 0 ; <nl> + for ( int64_t i = 0 ; i < prev_size ; + + i ) { <nl> + for ( int64_t j = 0 ; j < next_size ; + + j ) { <nl> SetTopKGradient ( <nl> values_data , <nl> indices_data , <nl> mmm a / caffe2 / operators / top_k . cu <nl> ppp b / caffe2 / operators / top_k . cu <nl> namespace { <nl> template < typename T , int kHeapSize , bool kSelectMax = true > <nl> void RunHeapSelectionImpl ( <nl> const T * input , <nl> - const TIndex outer_size , <nl> - const TIndex inner_size , <nl> + const int64_t outer_size , <nl> + const int64_t inner_size , <nl> const int k , <nl> T * values , <nl> - TIndex * indices , <nl> + int64_t * indices , <nl> CUDAContext * context ) { <nl> constexpr int kBlockSize = 256 ; <nl> constexpr int kNumWarps = kBlockSize / kWarpSize ; <nl> - constexpr int smem = kNumWarps * kHeapSize * ( sizeof ( T ) + sizeof ( TIndex ) ) ; <nl> + constexpr int smem = kNumWarps * kHeapSize * ( sizeof ( T ) + sizeof ( int64_t ) ) ; <nl> constexpr T kInitVal = kSelectMax ? std : : numeric_limits < T > : : lowest ( ) <nl> : std : : numeric_limits < T > : : max ( ) ; <nl> - selectRowsViaHeap < T , TIndex , TIndex , kBlockSize , kHeapSize , kSelectMax > <nl> + selectRowsViaHeap < T , int64_t , int64_t , kBlockSize , kHeapSize , kSelectMax > <nl> < < < outer_size , kBlockSize , smem , context - > cuda_stream ( ) > > > ( <nl> input , <nl> values , <nl> indices , <nl> kInitVal , <nl> - std : : numeric_limits < TIndex > : : max ( ) , <nl> + std : : numeric_limits < int64_t > : : max ( ) , <nl> outer_size , <nl> inner_size , <nl> k ) ; <nl> void RunHeapSelectionImpl ( <nl> template < typename T , bool kSelectMax = true > <nl> void RunRadixSelectionImpl ( <nl> const T * input , <nl> - const TIndex outer_size , <nl> - const TIndex inner_size , <nl> + const int64_t outer_size , <nl> + const int64_t inner_size , <nl> const int k , <nl> T * values , <nl> - TIndex * indices , <nl> + int64_t * indices , <nl> CUDAContext * context ) { <nl> const int block = std : : min ( <nl> math : : roundUp ( static_cast < int > ( inner_size ) , kWarpSize ) , <nl> CAFFE_CUDA_NUM_THREADS ) ; <nl> - gatherTopK < T , kSelectMax , TIndex > <nl> + gatherTopK < T , kSelectMax , int64_t > <nl> < < < outer_size , block , 0 , context - > cuda_stream ( ) > > > ( <nl> input , inner_size , k , outer_size , values , indices ) ; <nl> / / Unfortunately the output is not currently sorted , and there is no batch <nl> void RunRadixSelectionImpl ( <nl> template < typename T > <nl> void RunTopKOnLastDimCUDAImpl ( <nl> const T * input , <nl> - const TIndex outer_size , <nl> - const TIndex inner_size , <nl> + const int64_t outer_size , <nl> + const int64_t inner_size , <nl> const int k , <nl> T * values , <nl> - TIndex * indices , <nl> + int64_t * indices , <nl> CUDAContext * context ) { <nl> / / If k is small , uses heap selection , otherwise uses radix selection . <nl> if ( k < 32 ) { <nl> void RunTopKOnLastDimCUDAImpl ( <nl> } <nl> <nl> __global__ void FlattenIndicesCUDAKernel ( <nl> - const TIndex * src , <nl> - const TIndex size , <nl> - const TIndex stride , <nl> - const TIndex n , <nl> + const int64_t * src , <nl> + const int64_t size , <nl> + const int64_t stride , <nl> + const int64_t n , <nl> const int k , <nl> - TIndex * dst ) { <nl> + int64_t * dst ) { <nl> CUDA_1D_KERNEL_LOOP ( i , size ) { <nl> if ( src [ i ] < 0 ) { <nl> continue ; <nl> } <nl> - const TIndex x = i / stride / k ; <nl> - const TIndex y = i % stride ; <nl> + const int64_t x = i / stride / k ; <nl> + const int64_t y = i % stride ; <nl> # if __CUDA_ARCH__ > = 350 <nl> dst [ i ] = __ldg ( src + i ) * stride + x * n * stride + y ; <nl> # else <nl> __global__ void FlattenIndicesCUDAKernel ( <nl> template < typename T > <nl> __global__ void SetTopKGradientCUDAKernel ( <nl> const T * values , <nl> - const TIndex * indices , <nl> - const TIndex size , <nl> - const TIndex stride , <nl> - const TIndex n , <nl> + const int64_t * indices , <nl> + const int64_t size , <nl> + const int64_t stride , <nl> + const int64_t n , <nl> const int k , <nl> T * dst ) { <nl> CUDA_1D_KERNEL_LOOP ( i , size ) { <nl> if ( indices [ i ] < 0 ) { <nl> continue ; <nl> } <nl> - const TIndex x = i / stride / k ; <nl> - const TIndex y = i % stride ; <nl> + const int64_t x = i / stride / k ; <nl> + const int64_t y = i % stride ; <nl> # if __CUDA_ARCH__ > = 350 <nl> dst [ __ldg ( indices + i ) * stride + x * n * stride + y ] = __ldg ( values + i ) ; <nl> # else <nl> bool TopKCudaOp < T , Context > : : RunOnDevice ( ) { <nl> auto * indices = Output ( 1 ) ; <nl> auto * flatten_indices = OutputSize ( ) > 2 ? Output ( 2 ) : nullptr ; <nl> <nl> - const std : : vector < TIndex > & input_dims = input . dims ( ) ; <nl> + const std : : vector < int64_t > & input_dims = input . dims ( ) ; <nl> if ( axis_ = = - 1 ) { <nl> axis_ = input_dims . size ( ) - 1 ; <nl> } <nl> bool TopKCudaOp < T , Context > : : RunOnDevice ( ) { <nl> CAFFE_ENFORCE_LT ( axis_ , input_dims . size ( ) ) ; <nl> <nl> const bool need_transpose = axis_ < input_dims . size ( ) - 1 ; <nl> - std : : vector < TIndex > output_dims = input_dims ; <nl> + std : : vector < int64_t > output_dims = input_dims ; <nl> output_dims [ axis_ ] = k_ ; <nl> - const TIndex prev_size = std : : accumulate ( <nl> + const int64_t prev_size = std : : accumulate ( <nl> input_dims . cbegin ( ) , <nl> input_dims . cbegin ( ) + axis_ , <nl> - TIndex ( 1 ) , <nl> - std : : multiplies < TIndex > ( ) ) ; <nl> - const TIndex next_size = std : : accumulate ( <nl> + int64_t ( 1 ) , <nl> + std : : multiplies < int64_t > ( ) ) ; <nl> + const int64_t next_size = std : : accumulate ( <nl> input_dims . cbegin ( ) + axis_ + 1 , <nl> input_dims . cend ( ) , <nl> - TIndex ( 1 ) , <nl> - std : : multiplies < TIndex > ( ) ) ; <nl> - const TIndex outer_size = input . size ( ) / input_dims [ axis_ ] ; <nl> - const TIndex inner_size = input_dims [ axis_ ] ; <nl> + int64_t ( 1 ) , <nl> + std : : multiplies < int64_t > ( ) ) ; <nl> + const int64_t outer_size = input . size ( ) / input_dims [ axis_ ] ; <nl> + const int64_t inner_size = input_dims [ axis_ ] ; <nl> <nl> values - > Resize ( output_dims ) ; <nl> indices - > Resize ( output_dims ) ; <nl> bool TopKCudaOp < T , Context > : : RunOnDevice ( ) { <nl> } <nl> const T * input_data = input . template data < T > ( ) ; <nl> T * values_data = values - > template mutable_data < T > ( ) ; <nl> - TIndex * indices_data = indices - > template mutable_data < TIndex > ( ) ; <nl> - TIndex * flatten_indices_data = flatten_indices = = nullptr <nl> + int64_t * indices_data = indices - > template mutable_data < int64_t > ( ) ; <nl> + int64_t * flatten_indices_data = flatten_indices = = nullptr <nl> ? nullptr <nl> - : flatten_indices - > template mutable_data < TIndex > ( ) ; <nl> + : flatten_indices - > template mutable_data < int64_t > ( ) ; <nl> <nl> if ( need_transpose ) { <nl> const std : : array < int , 3 > dims = { static_cast < int > ( prev_size ) , <nl> bool TopKCudaOp < T , Context > : : RunOnDevice ( ) { <nl> static_cast < int > ( next_size ) } ; <nl> const std : : array < int , 3 > axes = { 0 , 2 , 1 } ; <nl> input_transposed_buffer_ . Resize ( <nl> - std : : vector < TIndex > { outer_size , inner_size } ) ; <nl> - values_transposed_buffer_ . Resize ( std : : vector < TIndex > { outer_size , k_ } ) ; <nl> - indices_transposed_buffer_ . Resize ( std : : vector < TIndex > { outer_size , k_ } ) ; <nl> + std : : vector < int64_t > { outer_size , inner_size } ) ; <nl> + values_transposed_buffer_ . Resize ( std : : vector < int64_t > { outer_size , k_ } ) ; <nl> + indices_transposed_buffer_ . Resize ( std : : vector < int64_t > { outer_size , k_ } ) ; <nl> math : : Transpose ( <nl> 3 , <nl> dims . data ( ) , <nl> bool TopKCudaOp < T , Context > : : RunOnDevice ( ) { <nl> & context_ ) ; <nl> input_data = input_transposed_buffer_ . template data < T > ( ) ; <nl> values_data = values_transposed_buffer_ . template mutable_data < T > ( ) ; <nl> - indices_data = indices_transposed_buffer_ . template mutable_data < TIndex > ( ) ; <nl> + indices_data = indices_transposed_buffer_ . template mutable_data < int64_t > ( ) ; <nl> } <nl> <nl> / / init values as the default value <nl> math : : Set < T , CUDAContext > ( values - > size ( ) , T ( 0 ) , values_data , & context_ ) ; <nl> - math : : Set < TIndex , CUDAContext > ( <nl> - indices - > size ( ) , TIndex ( - 1 ) , indices_data , & context_ ) ; <nl> + math : : Set < int64_t , CUDAContext > ( <nl> + indices - > size ( ) , int64_t ( - 1 ) , indices_data , & context_ ) ; <nl> if ( flatten_indices_data ! = nullptr ) { <nl> - math : : Set < TIndex , CUDAContext > ( <nl> - flatten_indices - > size ( ) , TIndex ( - 1 ) , flatten_indices_data , & context_ ) ; <nl> + math : : Set < int64_t , CUDAContext > ( <nl> + flatten_indices - > size ( ) , int64_t ( - 1 ) , flatten_indices_data , & context_ ) ; <nl> } <nl> <nl> RunTopKOnLastDimCUDAImpl < T > ( <nl> bool TopKCudaOp < T , Context > : : RunOnDevice ( ) { <nl> 3 , <nl> dims . data ( ) , <nl> axes . data ( ) , <nl> - indices_transposed_buffer_ . template data < TIndex > ( ) , <nl> - indices - > template mutable_data < TIndex > ( ) , <nl> + indices_transposed_buffer_ . template data < int64_t > ( ) , <nl> + indices - > template mutable_data < int64_t > ( ) , <nl> & context_ ) ; <nl> } <nl> <nl> bool TopKCudaOp < T , Context > : : RunOnDevice ( ) { <nl> CAFFE_CUDA_NUM_THREADS , <nl> 0 , <nl> context_ . cuda_stream ( ) > > > ( <nl> - indices - > template data < TIndex > ( ) , <nl> + indices - > template data < int64_t > ( ) , <nl> indices - > size ( ) , <nl> next_size , <nl> inner_size , <nl> k_ , <nl> - flatten_indices - > template mutable_data < TIndex > ( ) ) ; <nl> + flatten_indices - > template mutable_data < int64_t > ( ) ) ; <nl> } <nl> return true ; <nl> } <nl> bool TopKGradientCudaOp < T , Context > : : RunOnDevice ( ) { <nl> const auto & indices = Input ( 1 ) ; <nl> const auto & original_input = Input ( 2 ) ; <nl> auto * output = Output ( 0 ) ; <nl> - const std : : vector < TIndex > & values_dims = values . dims ( ) ; <nl> - const std : : vector < TIndex > & origin_dims = original_input . dims ( ) ; <nl> + const std : : vector < int64_t > & values_dims = values . dims ( ) ; <nl> + const std : : vector < int64_t > & origin_dims = original_input . dims ( ) ; <nl> CAFFE_ENFORCE_EQ ( values_dims . size ( ) , origin_dims . size ( ) ) ; <nl> output - > Resize ( origin_dims ) ; <nl> T * output_data = output - > template mutable_data < T > ( ) ; <nl> bool TopKGradientCudaOp < T , Context > : : RunOnDevice ( ) { <nl> } <nl> const int k = values_dims [ axis_ ] ; <nl> math : : Set < T , Context > ( output - > size ( ) , T ( 0 ) , output_data , & context_ ) ; <nl> - const TIndex stride = std : : accumulate ( <nl> + const int64_t stride = std : : accumulate ( <nl> values_dims . cbegin ( ) + axis_ + 1 , <nl> values_dims . cend ( ) , <nl> - TIndex ( 1 ) , <nl> - std : : multiplies < TIndex > ( ) ) ; <nl> + int64_t ( 1 ) , <nl> + std : : multiplies < int64_t > ( ) ) ; <nl> SetTopKGradientCUDAKernel < < < <nl> CAFFE_GET_BLOCKS ( indices . size ( ) ) , <nl> CAFFE_CUDA_NUM_THREADS , <nl> 0 , <nl> context_ . cuda_stream ( ) > > > ( <nl> values . template data < T > ( ) , <nl> - indices . template data < TIndex > ( ) , <nl> + indices . template data < int64_t > ( ) , <nl> values . size ( ) , <nl> stride , <nl> origin_dims [ axis_ ] , <nl> mmm a / caffe2 / operators / transpose_op . h <nl> ppp b / caffe2 / operators / transpose_op . h <nl> class TransposeOp final : public Operator < Context > { <nl> <nl> bool RunOnDevice ( ) override { <nl> / / Do the actual transpose , which is implemented in DoRunWithType ( ) . <nl> - return DispatchHelper < TensorTypes < float , double , int , TIndex > > : : call ( <nl> + return DispatchHelper < TensorTypes < float , double , int , int64_t > > : : call ( <nl> this , Input ( 0 ) ) ; <nl> } <nl> <nl> mmm a / caffe2 / operators / utility_ops . cu <nl> ppp b / caffe2 / operators / utility_ops . cu <nl> bool SelectGradientOpBase < float , CUDAContext > : : RunOnDevice ( ) { <nl> template < typename T_INDEX > <nl> __global__ void AxpySliceKernel ( <nl> const float * weight0 , <nl> - const TIndex N , <nl> - const TIndex B , <nl> - const TIndex slice_size , <nl> + const int64_t N , <nl> + const int64_t B , <nl> + const int64_t slice_size , <nl> const float * * alpha , <nl> const float * * X , <nl> const T_INDEX * Indices , <nl> float * Y , <nl> - const TIndex M ) { <nl> + const int64_t M ) { <nl> / / This implementation requires that the first weight is 1 . 0 <nl> CUDA_KERNEL_ASSERT ( weight0 [ 0 ] = = 1 . 0 ) ; <nl> for ( int i = blockIdx . x ; i < N ; i + = gridDim . x ) { <nl> bool ScatterWeightedSumOp < float , CUDAContext > : : DoRunWithType ( ) { <nl> CAFFE_ENFORCE_GT ( X0 . ndim ( ) , 0 , " X0 has to be at least the vector " ) ; <nl> CAFFE_ENFORCE_EQ ( weight0 . size ( ) , 1 ) ; <nl> <nl> - TIndex M = X0 . size ( ) ; <nl> - TIndex N = X0 . dim ( 0 ) ; <nl> - TIndex K = indices . size ( ) ; <nl> - TIndex block_size = M / N ; <nl> + int64_t M = X0 . size ( ) ; <nl> + int64_t N = X0 . dim ( 0 ) ; <nl> + int64_t K = indices . size ( ) ; <nl> + int64_t block_size = M / N ; <nl> <nl> float * data = output - > template mutable_data < float > ( ) ; <nl> <nl> / / In order to have all device pointers of x_i ( and weight_i similarly ) <nl> / / consecutively in device memory , copy pointers to a host vector and then <nl> / / copy back into a device array . <nl> - const TIndex B = ( InputSize ( ) - 3 ) / 2 ; <nl> + const int64_t B = ( InputSize ( ) - 3 ) / 2 ; <nl> x_data_host_ . Resize ( B ) ; <nl> weights_host_ . Resize ( B ) ; <nl> x_data_device_ . Resize ( B ) ; <nl> bool ScatterWeightedSumOp < float , CUDAContext > : : DoRunWithType ( ) { <nl> B , weights_host , weights_device ) ; <nl> <nl> AxpySliceKernel < < < <nl> - std : : min < TIndex > ( K , CAFFE_MAXIMUM_NUM_BLOCKS ) , <nl> + std : : min < int64_t > ( K , CAFFE_MAXIMUM_NUM_BLOCKS ) , <nl> CAFFE_CUDA_NUM_THREADS , <nl> 0 , <nl> context_ . cuda_stream ( ) > > > ( <nl> __global__ void scatter_assign_kernel ( <nl> T * data , <nl> const Index * idxs , <nl> const T * slicesData , <nl> - TIndex N , <nl> - TIndex K , <nl> - TIndex block_size ) { <nl> - for ( TIndex i = blockIdx . x ; i < K ; i + = gridDim . x ) { <nl> + int64_t N , <nl> + int64_t K , <nl> + int64_t block_size ) { <nl> + for ( int64_t i = blockIdx . x ; i < K ; i + = gridDim . x ) { <nl> Index idx = idxs [ i ] ; <nl> CUDA_KERNEL_ASSERT ( 0 < = idx & & idx < N ) ; <nl> const T * src = slicesData + block_size * i ; <nl> T * dest = data + block_size * idx ; <nl> - for ( TIndex j = threadIdx . x ; j < block_size ; j + = blockDim . x ) { <nl> + for ( int64_t j = threadIdx . x ; j < block_size ; j + = blockDim . x ) { <nl> dest [ j ] = src [ j ] ; <nl> } <nl> } <nl> void ScatterAssignOp < CUDAContext > : : DoScatterAssign ( <nl> T * data , <nl> const Index * idxs , <nl> const T * slicesData , <nl> - TIndex N , <nl> - TIndex K , <nl> - TIndex block_size ) { <nl> + int64_t N , <nl> + int64_t K , <nl> + int64_t block_size ) { <nl> scatter_assign_kernel < < < <nl> - std : : min ( K , static_cast < TIndex > ( CAFFE_MAXIMUM_NUM_BLOCKS ) ) , <nl> + std : : min ( K , static_cast < int64_t > ( CAFFE_MAXIMUM_NUM_BLOCKS ) ) , <nl> CAFFE_CUDA_NUM_THREADS , <nl> 0 , <nl> context_ . cuda_stream ( ) > > > ( data , idxs , slicesData , N , K , block_size ) ; <nl> mmm a / caffe2 / operators / utility_ops . h <nl> ppp b / caffe2 / operators / utility_ops . h <nl> class ScatterWeightedSumOp : public Operator < Context > { <nl> private : <nl> template < typename Index > <nl> bool DoRunWithType ( ) { <nl> - TIndex block_size = Input ( 0 ) . size_from_dim ( 1 ) ; <nl> + int64_t block_size = Input ( 0 ) . size_from_dim ( 1 ) ; <nl> return DispatchHelper < FixedValues < 1 > , Index > : : call ( this , block_size ) ; <nl> } <nl> <nl> class ScatterWeightedSumOp : public Operator < Context > { <nl> CAFFE_ENFORCE_GT ( X0 . size ( ) , 0 ) ; <nl> CAFFE_ENFORCE_GT ( X0 . ndim ( ) , 0 , " X0 has to be at least the vector " ) ; <nl> CAFFE_ENFORCE_EQ ( weight0 . size ( ) , 1 ) ; <nl> - TIndex M = X0 . size ( ) ; <nl> - TIndex N = X0 . dim ( 0 ) ; <nl> - TIndex K = indices . size ( ) ; <nl> - TIndex block_size = M / N ; <nl> + int64_t M = X0 . size ( ) ; <nl> + int64_t N = X0 . dim ( 0 ) ; <nl> + int64_t K = indices . size ( ) ; <nl> + int64_t block_size = M / N ; <nl> T * data = output - > template mutable_data < T > ( ) ; <nl> const Index * idxs = indices . template data < Index > ( ) ; <nl> T w0 = * weight0 . template data < T > ( ) ; <nl> class ScatterAssignOp : public Operator < Context > { <nl> CAFFE_ENFORCE_EQ ( & input , output , " In place operation is required " ) ; <nl> <nl> CAFFE_ENFORCE_GT ( input . ndim ( ) , 0 , " X0 has to be at least the vector " ) ; <nl> - TIndex M = input . size ( ) ; <nl> - TIndex N = input . dim ( 0 ) ; <nl> - TIndex K = indices . size ( ) ; <nl> - TIndex block_size = M / N ; <nl> + int64_t M = input . size ( ) ; <nl> + int64_t N = input . dim ( 0 ) ; <nl> + int64_t K = indices . size ( ) ; <nl> + int64_t block_size = M / N ; <nl> CAFFE_ENFORCE_EQ ( slices . size ( ) , block_size * K ) ; <nl> / / TODO ( dzhulgakov ) : it can be made to work with arbitrary data type by <nl> / / using raw_mutable_data <nl> class ScatterAssignOp : public Operator < Context > { <nl> T * data , <nl> const Index * idxs , <nl> const T * slicesData , <nl> - TIndex N , <nl> - TIndex K , <nl> - TIndex block_size ) { <nl> + int64_t N , <nl> + int64_t K , <nl> + int64_t block_size ) { <nl> for ( int i = 0 ; i < K ; + + i ) { <nl> Index idx = idxs [ i ] ; <nl> / / double - checking the indices , but it ' s fine as it ' s DCHECK only <nl> class HasElementsOp : public Operator < Context > { <nl> bool RunOnDevice ( ) override { <nl> auto & input = Input ( 0 ) ; <nl> auto * output = Output ( 0 ) ; <nl> - output - > Resize ( std : : vector < TIndex > { } ) ; <nl> + output - > Resize ( std : : vector < int64_t > { } ) ; <nl> * output - > template mutable_data < bool > ( ) = input . size ( ) > 0 ; <nl> return true ; <nl> } <nl> class SizeOp : public Operator < Context > { <nl> auto & input = Input ( 0 ) ; <nl> auto * output = Output ( 0 ) ; <nl> <nl> - output - > Resize ( vector < TIndex > ( ) ) ; <nl> + output - > Resize ( vector < int64_t > ( ) ) ; <nl> auto * output_data = output - > template mutable_data < int64_t > ( ) ; <nl> <nl> auto size = input . size ( ) ; <nl> class LengthsGatherOp : public Operator < Context > { <nl> const auto * lengths_data = lengths . template data < int32_t > ( ) ; <nl> const auto * indices_data = indices . template data < Index > ( ) ; <nl> <nl> - TIndex total_length = 0 ; <nl> + int64_t total_length = 0 ; <nl> for ( size_t i = 0 ; i < indices . size ( ) ; + + i ) { <nl> auto idx = indices_data [ i ] ; <nl> CAFFE_ENFORCE_LT ( idx , lengths . size ( ) ) ; <nl> class LengthsGatherOp : public Operator < Context > { <nl> output - > Resize ( shape ) ; <nl> <nl> offsets_ . clear ( ) ; <nl> - TIndex running_offset = 0 ; <nl> + int64_t running_offset = 0 ; <nl> offsets_ . reserve ( lengths . size ( ) ) ; <nl> for ( size_t i = 0 ; i < lengths . size ( ) ; + + i ) { <nl> offsets_ . push_back ( running_offset ) ; <nl> class LengthsGatherOp : public Operator < Context > { <nl> return true ; <nl> } <nl> <nl> - std : : vector < TIndex > offsets_ ; <nl> + std : : vector < int64_t > offsets_ ; <nl> <nl> INPUT_TAGS ( ITEMS , LENGTHS , INDICES ) ; <nl> } ; <nl> mmm a / caffe2 / operators / utility_ops_gpu_test . cc <nl> ppp b / caffe2 / operators / utility_ops_gpu_test . cc <nl> CAFFE2_DECLARE_string ( caffe_test_root ) ; <nl> namespace caffe2 { <nl> <nl> static void AddConstInput ( <nl> - const vector < TIndex > & shape , <nl> + const vector < int64_t > & shape , <nl> const float value , <nl> const string & name , <nl> Workspace * ws ) { <nl> TEST ( UtilityOpGPUTest , testReshapeWithScalar ) { <nl> def . add_output ( " OldShape " ) ; <nl> def . add_arg ( ) - > CopyFrom ( MakeArgument ( " shape " , vector < int64_t > { 1 } ) ) ; <nl> def . mutable_device_option ( ) - > set_device_type ( PROTO_CUDA ) ; <nl> - AddConstInput ( vector < TIndex > ( ) , 3 . 14 , " X " , & ws ) ; <nl> + AddConstInput ( vector < int64_t > ( ) , 3 . 14 , " X " , & ws ) ; <nl> / / execute the op <nl> unique_ptr < OperatorBase > op ( CreateOperator ( def , & ws ) ) ; <nl> EXPECT_TRUE ( op - > Run ( ) ) ; <nl> mmm a / caffe2 / operators / utility_ops_test . cc <nl> ppp b / caffe2 / operators / utility_ops_test . cc <nl> CAFFE2_DECLARE_string ( caffe_test_root ) ; <nl> namespace caffe2 { <nl> <nl> static void AddConstInput ( <nl> - const vector < TIndex > & shape , <nl> + const vector < int64_t > & shape , <nl> const float value , <nl> const string & name , <nl> Workspace * ws ) { <nl> TEST ( UtilityOpTest , testReshapeWithScalar ) { <nl> def . add_output ( " XNew " ) ; <nl> def . add_output ( " OldShape " ) ; <nl> def . add_arg ( ) - > CopyFrom ( MakeArgument ( " shape " , vector < int64_t > { 1 } ) ) ; <nl> - AddConstInput ( vector < TIndex > ( ) , 3 . 14 , " X " , & ws ) ; <nl> + AddConstInput ( vector < int64_t > ( ) , 3 . 14 , " X " , & ws ) ; <nl> / / execute the op <nl> unique_ptr < OperatorBase > op ( CreateOperator ( def , & ws ) ) ; <nl> EXPECT_TRUE ( op - > Run ( ) ) ; <nl> mmm a / caffe2 / opt / onnxifi_transformer . cc <nl> ppp b / caffe2 / opt / onnxifi_transformer . cc <nl> NetDef OnnxifiTransformer : : SubnetToOnnxifiOp ( <nl> / / Feed into workspace as CPU Tensors <nl> auto * blob = ws - > CreateBlob ( t . name ( ) ) ; <nl> auto * cpu_tensor = blob - > GetMutableTensor ( CPU ) ; <nl> - std : : vector < TIndex > dims ; <nl> + std : : vector < int64_t > dims ; <nl> for ( const auto & d : t . dims ( ) ) { <nl> dims . push_back ( d ) ; <nl> } <nl> mmm a / caffe2 / perfkernels / embedding_lookup . cc <nl> ppp b / caffe2 / perfkernels / embedding_lookup . cc <nl> template < <nl> typename OutType , <nl> bool IS_WEIGHT_POSITIONAL = false > <nl> static void EmbeddingLookupGenericSlow ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const InType * input , <nl> const IndexType * indices , <nl> const int * lengths , <nl> static void EmbeddingLookupGenericSlow ( <nl> const float * scale_bias , / / optional scale & bias params for uint8 input <nl> bool normalize_by_lengths , <nl> OutType * out ) { <nl> - TIndex current = 0 ; <nl> + int64_t current = 0 ; <nl> for ( int m = 0 ; m < output_size ; + + m ) { <nl> memset ( out , 0 , sizeof ( OutType ) * block_size ) ; <nl> EigenVectorArrayMap < OutType > out_vector ( out , block_size ) ; <nl> for ( int i = 0 ; i < lengths [ m ] ; + + i ) { <nl> CAFFE_ENFORCE_LT ( current , index_size ) ; <nl> - TIndex idx = indices [ current ] ; <nl> + int64_t idx = indices [ current ] ; <nl> CAFFE_ENFORCE ( <nl> 0 < = idx & & idx < data_size , <nl> " Index " , <nl> static void EmbeddingLookupGenericSlow ( <nl> IndexTypeName , IndexType , InTypeName , InType , OutTypeName , OutType , IS_WEIGHT_POSITIONAL ) \ <nl> void \ <nl> EmbeddingLookup_ # # IndexTypeName # # _ # # InTypeName # # _ # # OutTypeName # # _ # # IS_WEIGHT_POSITIONAL # # __base ( \ <nl> - const TIndex block_size , \ <nl> - const TIndex output_size , \ <nl> - const TIndex index_size , \ <nl> - const TIndex data_size , \ <nl> + const int64_t block_size , \ <nl> + const int64_t output_size , \ <nl> + const int64_t index_size , \ <nl> + const int64_t data_size , \ <nl> const InType * input , \ <nl> const IndexType * indices , \ <nl> const int * lengths , \ <nl> static void EmbeddingLookupGenericSlow ( <nl> } \ <nl> template < > \ <nl> void EmbeddingLookup < IndexType , InType , OutType , IS_WEIGHT_POSITIONAL > ( \ <nl> - const TIndex block_size , \ <nl> - const TIndex output_size , \ <nl> - const TIndex index_size , \ <nl> - const TIndex data_size , \ <nl> + const int64_t block_size , \ <nl> + const int64_t output_size , \ <nl> + const int64_t index_size , \ <nl> + const int64_t data_size , \ <nl> const InType * input , \ <nl> const IndexType * indices , \ <nl> const int * lengths , \ <nl> mmm a / caffe2 / perfkernels / embedding_lookup . h <nl> ppp b / caffe2 / perfkernels / embedding_lookup . h <nl> template < <nl> typename OutType , <nl> bool IS_WEIGHT_POSITIONAL = false > <nl> void EmbeddingLookup ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const InType * input , <nl> const IndexType * indices , <nl> const int * lengths , <nl> mmm a / caffe2 / perfkernels / embedding_lookup_avx2 . cc <nl> ppp b / caffe2 / perfkernels / embedding_lookup_avx2 . cc <nl> namespace caffe2 { <nl> <nl> template < bool IS_WEIGHT_POSITIONAL > <nl> static void EmbeddingLookup_int32_t_float_float__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const float * input , <nl> const int32_t * indices , <nl> const int * lengths , <nl> static void EmbeddingLookup_int32_t_float_float__avx2_fma ( <nl> int32_t dataInd = 0 ; <nl> for ( int32_t rangeIndex = 0 ; rangeIndex < output_size ; + + rangeIndex ) { <nl> float * op = & out [ rangeIndex * block_size ] ; <nl> - TIndex j = 0 ; <nl> + int64_t j = 0 ; <nl> for ( ; j + 8 < = block_size ; j + = 8 ) { <nl> _mm256_storeu_ps ( op + j , _mm256_setzero_ps ( ) ) ; <nl> } <nl> static void EmbeddingLookup_int32_t_float_float__avx2_fma ( <nl> } <nl> } <nl> void EmbeddingLookup_int32_t_float_float_false__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const float * input , <nl> const int32_t * indices , <nl> const int * lengths , <nl> void EmbeddingLookup_int32_t_float_float_false__avx2_fma ( <nl> out ) ; <nl> } <nl> void EmbeddingLookup_int32_t_float_float_true__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const float * input , <nl> const int32_t * indices , <nl> const int * lengths , <nl> void EmbeddingLookup_int32_t_float_float_true__avx2_fma ( <nl> <nl> template < bool IS_WEIGHT_POSITIONAL > <nl> static void EmbeddingLookup_int64_t_float_float__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const float * input , <nl> const int64_t * indices , <nl> const int * lengths , <nl> static void EmbeddingLookup_int64_t_float_float__avx2_fma ( <nl> int64_t dataInd = 0 ; <nl> for ( int64_t rangeIndex = 0 ; rangeIndex < output_size ; + + rangeIndex ) { <nl> float * op = & out [ rangeIndex * block_size ] ; <nl> - TIndex j = 0 ; <nl> + int64_t j = 0 ; <nl> for ( ; j + 8 < = block_size ; j + = 8 ) { <nl> _mm256_storeu_ps ( op + j , _mm256_setzero_ps ( ) ) ; <nl> } <nl> static void EmbeddingLookup_int64_t_float_float__avx2_fma ( <nl> } <nl> } <nl> void EmbeddingLookup_int64_t_float_float_false__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const float * input , <nl> const int64_t * indices , <nl> const int * lengths , <nl> void EmbeddingLookup_int64_t_float_float_false__avx2_fma ( <nl> out ) ; <nl> } <nl> void EmbeddingLookup_int64_t_float_float_true__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const float * input , <nl> const int64_t * indices , <nl> const int * lengths , <nl> void EmbeddingLookup_int64_t_float_float_true__avx2_fma ( <nl> <nl> template < bool IS_WEIGHT_POSITIONAL > <nl> static void EmbeddingLookup_int32_t_half_float__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const at : : Half * input , <nl> const int32_t * indices , <nl> const int * lengths , <nl> static void EmbeddingLookup_int32_t_half_float__avx2_fma ( <nl> int32_t dataInd = 0 ; <nl> for ( int32_t rangeIndex = 0 ; rangeIndex < output_size ; + + rangeIndex ) { <nl> float * op = & out [ rangeIndex * block_size ] ; <nl> - TIndex j = 0 ; <nl> + int64_t j = 0 ; <nl> for ( ; j + 8 < = block_size ; j + = 8 ) { <nl> _mm256_storeu_ps ( op + j , _mm256_setzero_ps ( ) ) ; <nl> } <nl> static void EmbeddingLookup_int32_t_half_float__avx2_fma ( <nl> } <nl> } <nl> void EmbeddingLookup_int32_t_half_float_false__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const at : : Half * input , <nl> const int32_t * indices , <nl> const int * lengths , <nl> void EmbeddingLookup_int32_t_half_float_false__avx2_fma ( <nl> out ) ; <nl> } <nl> void EmbeddingLookup_int32_t_half_float_true__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const at : : Half * input , <nl> const int32_t * indices , <nl> const int * lengths , <nl> void EmbeddingLookup_int32_t_half_float_true__avx2_fma ( <nl> <nl> template < bool IS_WEIGHT_POSITIONAL > <nl> static void EmbeddingLookup_int64_t_half_float__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const at : : Half * input , <nl> const int64_t * indices , <nl> const int * lengths , <nl> static void EmbeddingLookup_int64_t_half_float__avx2_fma ( <nl> int64_t dataInd = 0 ; <nl> for ( int64_t rangeIndex = 0 ; rangeIndex < output_size ; + + rangeIndex ) { <nl> float * op = & out [ rangeIndex * block_size ] ; <nl> - TIndex j = 0 ; <nl> + int64_t j = 0 ; <nl> for ( ; j + 8 < = block_size ; j + = 8 ) { <nl> _mm256_storeu_ps ( op + j , _mm256_setzero_ps ( ) ) ; <nl> } <nl> static void EmbeddingLookup_int64_t_half_float__avx2_fma ( <nl> } <nl> } <nl> void EmbeddingLookup_int64_t_half_float_false__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const at : : Half * input , <nl> const int64_t * indices , <nl> const int * lengths , <nl> void EmbeddingLookup_int64_t_half_float_false__avx2_fma ( <nl> out ) ; <nl> } <nl> void EmbeddingLookup_int64_t_half_float_true__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const at : : Half * input , <nl> const int64_t * indices , <nl> const int * lengths , <nl> void EmbeddingLookup_int64_t_half_float_true__avx2_fma ( <nl> <nl> template < bool IS_WEIGHT_POSITIONAL > <nl> static void EmbeddingLookup_int32_t_uint8_t_float__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const uint8_t * input , <nl> const int32_t * indices , <nl> const int * lengths , <nl> static void EmbeddingLookup_int32_t_uint8_t_float__avx2_fma ( <nl> int32_t dataInd = 0 ; <nl> for ( int32_t rangeIndex = 0 ; rangeIndex < output_size ; + + rangeIndex ) { <nl> float * op = & out [ rangeIndex * block_size ] ; <nl> - TIndex j = 0 ; <nl> + int64_t j = 0 ; <nl> for ( ; j + 8 < = block_size ; j + = 8 ) { <nl> _mm256_storeu_ps ( op + j , _mm256_setzero_ps ( ) ) ; <nl> } <nl> static void EmbeddingLookup_int32_t_uint8_t_float__avx2_fma ( <nl> } <nl> } <nl> void EmbeddingLookup_int32_t_uint8_t_float_false__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const uint8_t * input , <nl> const int32_t * indices , <nl> const int * lengths , <nl> void EmbeddingLookup_int32_t_uint8_t_float_false__avx2_fma ( <nl> out ) ; <nl> } <nl> void EmbeddingLookup_int32_t_uint8_t_float_true__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const uint8_t * input , <nl> const int32_t * indices , <nl> const int * lengths , <nl> void EmbeddingLookup_int32_t_uint8_t_float_true__avx2_fma ( <nl> <nl> template < bool IS_WEIGHT_POSITIONAL > <nl> static void EmbeddingLookup_int64_t_uint8_t_float__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const uint8_t * input , <nl> const int64_t * indices , <nl> const int * lengths , <nl> static void EmbeddingLookup_int64_t_uint8_t_float__avx2_fma ( <nl> int64_t dataInd = 0 ; <nl> for ( int64_t rangeIndex = 0 ; rangeIndex < output_size ; + + rangeIndex ) { <nl> float * op = & out [ rangeIndex * block_size ] ; <nl> - TIndex j = 0 ; <nl> + int64_t j = 0 ; <nl> for ( ; j + 8 < = block_size ; j + = 8 ) { <nl> _mm256_storeu_ps ( op + j , _mm256_setzero_ps ( ) ) ; <nl> } <nl> static void EmbeddingLookup_int64_t_uint8_t_float__avx2_fma ( <nl> } <nl> } <nl> void EmbeddingLookup_int64_t_uint8_t_float_false__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const uint8_t * input , <nl> const int64_t * indices , <nl> const int * lengths , <nl> void EmbeddingLookup_int64_t_uint8_t_float_false__avx2_fma ( <nl> out ) ; <nl> } <nl> void EmbeddingLookup_int64_t_uint8_t_float_true__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const uint8_t * input , <nl> const int64_t * indices , <nl> const int * lengths , <nl> mmm a / caffe2 / perfkernels / embedding_lookup_fused_8bit_rowwise_avx2 . cc <nl> ppp b / caffe2 / perfkernels / embedding_lookup_fused_8bit_rowwise_avx2 . cc <nl> namespace caffe2 { <nl> <nl> template < bool IS_WEIGHT_POSITIONAL > <nl> static void Fused8BitRowwiseEmbeddingLookup_int32_t_float_float__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const float * input , <nl> const int32_t * indices , <nl> const int * lengths , <nl> static void Fused8BitRowwiseEmbeddingLookup_int32_t_float_float__avx2_fma ( <nl> int32_t dataInd = 0 ; <nl> for ( int32_t rangeIndex = 0 ; rangeIndex < output_size ; + + rangeIndex ) { <nl> float * op = & out [ rangeIndex * block_size ] ; <nl> - TIndex j = 0 ; <nl> + int64_t j = 0 ; <nl> for ( ; j + 8 < = block_size ; j + = 8 ) { <nl> _mm256_storeu_ps ( op + j , _mm256_setzero_ps ( ) ) ; <nl> } <nl> static void Fused8BitRowwiseEmbeddingLookup_int32_t_float_float__avx2_fma ( <nl> } <nl> } <nl> void Fused8BitRowwiseEmbeddingLookup_int32_t_float_float_false__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const float * input , <nl> const int32_t * indices , <nl> const int * lengths , <nl> void Fused8BitRowwiseEmbeddingLookup_int32_t_float_float_false__avx2_fma ( <nl> out ) ; <nl> } <nl> void Fused8BitRowwiseEmbeddingLookup_int32_t_float_float_true__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const float * input , <nl> const int32_t * indices , <nl> const int * lengths , <nl> void Fused8BitRowwiseEmbeddingLookup_int32_t_float_float_true__avx2_fma ( <nl> <nl> template < bool IS_WEIGHT_POSITIONAL > <nl> static void Fused8BitRowwiseEmbeddingLookup_int64_t_float_float__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const float * input , <nl> const int64_t * indices , <nl> const int * lengths , <nl> static void Fused8BitRowwiseEmbeddingLookup_int64_t_float_float__avx2_fma ( <nl> int64_t dataInd = 0 ; <nl> for ( int64_t rangeIndex = 0 ; rangeIndex < output_size ; + + rangeIndex ) { <nl> float * op = & out [ rangeIndex * block_size ] ; <nl> - TIndex j = 0 ; <nl> + int64_t j = 0 ; <nl> for ( ; j + 8 < = block_size ; j + = 8 ) { <nl> _mm256_storeu_ps ( op + j , _mm256_setzero_ps ( ) ) ; <nl> } <nl> static void Fused8BitRowwiseEmbeddingLookup_int64_t_float_float__avx2_fma ( <nl> } <nl> } <nl> void Fused8BitRowwiseEmbeddingLookup_int64_t_float_float_false__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const float * input , <nl> const int64_t * indices , <nl> const int * lengths , <nl> void Fused8BitRowwiseEmbeddingLookup_int64_t_float_float_false__avx2_fma ( <nl> out ) ; <nl> } <nl> void Fused8BitRowwiseEmbeddingLookup_int64_t_float_float_true__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const float * input , <nl> const int64_t * indices , <nl> const int * lengths , <nl> void Fused8BitRowwiseEmbeddingLookup_int64_t_float_float_true__avx2_fma ( <nl> <nl> template < bool IS_WEIGHT_POSITIONAL > <nl> static void Fused8BitRowwiseEmbeddingLookup_int32_t_half_float__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const at : : Half * input , <nl> const int32_t * indices , <nl> const int * lengths , <nl> static void Fused8BitRowwiseEmbeddingLookup_int32_t_half_float__avx2_fma ( <nl> int32_t dataInd = 0 ; <nl> for ( int32_t rangeIndex = 0 ; rangeIndex < output_size ; + + rangeIndex ) { <nl> float * op = & out [ rangeIndex * block_size ] ; <nl> - TIndex j = 0 ; <nl> + int64_t j = 0 ; <nl> for ( ; j + 8 < = block_size ; j + = 8 ) { <nl> _mm256_storeu_ps ( op + j , _mm256_setzero_ps ( ) ) ; <nl> } <nl> static void Fused8BitRowwiseEmbeddingLookup_int32_t_half_float__avx2_fma ( <nl> } <nl> } <nl> void Fused8BitRowwiseEmbeddingLookup_int32_t_half_float_false__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const at : : Half * input , <nl> const int32_t * indices , <nl> const int * lengths , <nl> void Fused8BitRowwiseEmbeddingLookup_int32_t_half_float_false__avx2_fma ( <nl> out ) ; <nl> } <nl> void Fused8BitRowwiseEmbeddingLookup_int32_t_half_float_true__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const at : : Half * input , <nl> const int32_t * indices , <nl> const int * lengths , <nl> void Fused8BitRowwiseEmbeddingLookup_int32_t_half_float_true__avx2_fma ( <nl> <nl> template < bool IS_WEIGHT_POSITIONAL > <nl> static void Fused8BitRowwiseEmbeddingLookup_int64_t_half_float__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const at : : Half * input , <nl> const int64_t * indices , <nl> const int * lengths , <nl> static void Fused8BitRowwiseEmbeddingLookup_int64_t_half_float__avx2_fma ( <nl> int64_t dataInd = 0 ; <nl> for ( int64_t rangeIndex = 0 ; rangeIndex < output_size ; + + rangeIndex ) { <nl> float * op = & out [ rangeIndex * block_size ] ; <nl> - TIndex j = 0 ; <nl> + int64_t j = 0 ; <nl> for ( ; j + 8 < = block_size ; j + = 8 ) { <nl> _mm256_storeu_ps ( op + j , _mm256_setzero_ps ( ) ) ; <nl> } <nl> static void Fused8BitRowwiseEmbeddingLookup_int64_t_half_float__avx2_fma ( <nl> } <nl> } <nl> void Fused8BitRowwiseEmbeddingLookup_int64_t_half_float_false__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const at : : Half * input , <nl> const int64_t * indices , <nl> const int * lengths , <nl> void Fused8BitRowwiseEmbeddingLookup_int64_t_half_float_false__avx2_fma ( <nl> out ) ; <nl> } <nl> void Fused8BitRowwiseEmbeddingLookup_int64_t_half_float_true__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const at : : Half * input , <nl> const int64_t * indices , <nl> const int * lengths , <nl> void Fused8BitRowwiseEmbeddingLookup_int64_t_half_float_true__avx2_fma ( <nl> <nl> template < bool IS_WEIGHT_POSITIONAL > <nl> static void Fused8BitRowwiseEmbeddingLookup_int32_t_uint8_t_float__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const uint8_t * input , <nl> const int32_t * indices , <nl> const int * lengths , <nl> static void Fused8BitRowwiseEmbeddingLookup_int32_t_uint8_t_float__avx2_fma ( <nl> int32_t dataInd = 0 ; <nl> for ( int32_t rangeIndex = 0 ; rangeIndex < output_size ; + + rangeIndex ) { <nl> float * op = & out [ rangeIndex * block_size ] ; <nl> - TIndex j = 0 ; <nl> + int64_t j = 0 ; <nl> for ( ; j + 8 < = block_size ; j + = 8 ) { <nl> _mm256_storeu_ps ( op + j , _mm256_setzero_ps ( ) ) ; <nl> } <nl> static void Fused8BitRowwiseEmbeddingLookup_int32_t_uint8_t_float__avx2_fma ( <nl> } <nl> } <nl> void Fused8BitRowwiseEmbeddingLookup_int32_t_uint8_t_float_false__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const uint8_t * input , <nl> const int32_t * indices , <nl> const int * lengths , <nl> void Fused8BitRowwiseEmbeddingLookup_int32_t_uint8_t_float_false__avx2_fma ( <nl> out ) ; <nl> } <nl> void Fused8BitRowwiseEmbeddingLookup_int32_t_uint8_t_float_true__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const uint8_t * input , <nl> const int32_t * indices , <nl> const int * lengths , <nl> void Fused8BitRowwiseEmbeddingLookup_int32_t_uint8_t_float_true__avx2_fma ( <nl> <nl> template < bool IS_WEIGHT_POSITIONAL > <nl> static void Fused8BitRowwiseEmbeddingLookup_int64_t_uint8_t_float__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const uint8_t * input , <nl> const int64_t * indices , <nl> const int * lengths , <nl> static void Fused8BitRowwiseEmbeddingLookup_int64_t_uint8_t_float__avx2_fma ( <nl> int64_t dataInd = 0 ; <nl> for ( int64_t rangeIndex = 0 ; rangeIndex < output_size ; + + rangeIndex ) { <nl> float * op = & out [ rangeIndex * block_size ] ; <nl> - TIndex j = 0 ; <nl> + int64_t j = 0 ; <nl> for ( ; j + 8 < = block_size ; j + = 8 ) { <nl> _mm256_storeu_ps ( op + j , _mm256_setzero_ps ( ) ) ; <nl> } <nl> static void Fused8BitRowwiseEmbeddingLookup_int64_t_uint8_t_float__avx2_fma ( <nl> } <nl> } <nl> void Fused8BitRowwiseEmbeddingLookup_int64_t_uint8_t_float_false__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const uint8_t * input , <nl> const int64_t * indices , <nl> const int * lengths , <nl> void Fused8BitRowwiseEmbeddingLookup_int64_t_uint8_t_float_false__avx2_fma ( <nl> out ) ; <nl> } <nl> void Fused8BitRowwiseEmbeddingLookup_int64_t_uint8_t_float_true__avx2_fma ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const uint8_t * input , <nl> const int64_t * indices , <nl> const int * lengths , <nl> mmm a / caffe2 / perfkernels / fused_8bit_rowwise_embedding_lookup . cc <nl> ppp b / caffe2 / perfkernels / fused_8bit_rowwise_embedding_lookup . cc <nl> template < <nl> typename OutType , <nl> bool IS_WEIGHT_POSITIONAL = false > <nl> static void Fused8BitRowwiseEmbeddingLookupGenericSlow ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const InType * input , <nl> const IndexType * indices , <nl> const int * lengths , <nl> static void Fused8BitRowwiseEmbeddingLookupGenericSlow ( <nl> / / block_size is the number of elements and fused_block_size is the size of <nl> / / an entire row , including scale and bias . <nl> const auto scale_bias_offset = 8 / sizeof ( InType ) ; <nl> - const TIndex fused_block_size = block_size + scale_bias_offset ; <nl> - TIndex current = 0 ; <nl> + const int64_t fused_block_size = block_size + scale_bias_offset ; <nl> + int64_t current = 0 ; <nl> for ( int m = 0 ; m < output_size ; + + m ) { <nl> memset ( out , 0 , sizeof ( OutType ) * block_size ) ; <nl> EigenVectorArrayMap < OutType > out_vector ( out , block_size ) ; <nl> for ( int i = 0 ; i < lengths [ m ] ; + + i ) { <nl> CAFFE_ENFORCE_LT ( current , index_size ) ; <nl> - TIndex idx = indices [ current ] ; <nl> + int64_t idx = indices [ current ] ; <nl> CAFFE_ENFORCE ( <nl> 0 < = idx & & idx < data_size , <nl> " Index " , <nl> static void Fused8BitRowwiseEmbeddingLookupGenericSlow ( <nl> IndexType , InType , OutType ) \ <nl> void \ <nl> Fused8BitRowwiseEmbeddingLookup_ # # IndexType # # _ # # InType # # _ # # OutType # # _false__base ( \ <nl> - const TIndex block_size , \ <nl> - const TIndex output_size , \ <nl> - const TIndex index_size , \ <nl> - const TIndex data_size , \ <nl> + const int64_t block_size , \ <nl> + const int64_t output_size , \ <nl> + const int64_t index_size , \ <nl> + const int64_t data_size , \ <nl> const InType * input , \ <nl> const IndexType * indices , \ <nl> const int * lengths , \ <nl> static void Fused8BitRowwiseEmbeddingLookupGenericSlow ( <nl> } \ <nl> template < > \ <nl> void Fused8BitRowwiseEmbeddingLookup < IndexType , InType , OutType , false > ( \ <nl> - const TIndex block_size , \ <nl> - const TIndex output_size , \ <nl> - const TIndex index_size , \ <nl> - const TIndex data_size , \ <nl> + const int64_t block_size , \ <nl> + const int64_t output_size , \ <nl> + const int64_t index_size , \ <nl> + const int64_t data_size , \ <nl> const InType * input , \ <nl> const IndexType * indices , \ <nl> const int * lengths , \ <nl> mmm a / caffe2 / perfkernels / fused_8bit_rowwise_embedding_lookup . h <nl> ppp b / caffe2 / perfkernels / fused_8bit_rowwise_embedding_lookup . h <nl> template < <nl> typename OutType , <nl> bool IS_WEIGHT_POSITIONAL = false > <nl> void Fused8BitRowwiseEmbeddingLookup ( <nl> - const TIndex block_size , <nl> - const TIndex output_size , <nl> - const TIndex index_size , <nl> - const TIndex data_size , <nl> + const int64_t block_size , <nl> + const int64_t output_size , <nl> + const int64_t index_size , <nl> + const int64_t data_size , <nl> const InType * input , <nl> const IndexType * indices , <nl> const int * lengths , <nl> mmm a / caffe2 / perfkernels / hp_emblookup_codegen . py <nl> ppp b / caffe2 / perfkernels / hp_emblookup_codegen . py <nl> def compute ( InType , use_weights , isa ) : <nl> code . append ( OutType + " * op = & out [ rangeIndex * block_size ] ; " ) <nl> <nl> # initialize to 0 <nl> - code . append ( " TIndex j = 0 ; " ) <nl> + code . append ( " int64_t j = 0 ; " ) <nl> code . append ( " for ( ; j + 8 < = block_size ; j + = 8 ) { " ) <nl> code . append ( " _mm256_storeu_ps ( op + j , _mm256_setzero_ps ( ) ) ; " ) <nl> code . append ( " } " ) <nl> def compute ( InType , use_weights , isa ) : <nl> code . append ( fn + " ( " ) <nl> <nl> args = [ ] <nl> - args . append ( " const TIndex block_size , " ) <nl> - args . append ( " const TIndex output_size , " ) <nl> - args . append ( " const TIndex index_size , " ) <nl> - args . append ( " const TIndex data_size , " ) <nl> + args . append ( " const int64_t block_size , " ) <nl> + args . append ( " const int64_t output_size , " ) <nl> + args . append ( " const int64_t index_size , " ) <nl> + args . append ( " const int64_t data_size , " ) <nl> args . append ( " const " + InType + " * input , " ) <nl> args . append ( " const " + IndexType + " * indices , " ) <nl> args . append ( " const int * lengths , " ) <nl> mmm a / caffe2 / predictor / predictor_test . cc <nl> ppp b / caffe2 / predictor / predictor_test . cc <nl> const char * metaSpec = R " DOC ( <nl> ) DOC " ; <nl> <nl> std : : unique_ptr < Blob > randomTensor ( <nl> - const std : : vector < TIndex > & dims , <nl> + const std : : vector < int64_t > & dims , <nl> CPUContext * ctx ) { <nl> auto blob = make_unique < Blob > ( ) ; <nl> auto * t = blob - > GetMutableTensor ( CPU ) ; <nl> mmm a / caffe2 / python / pybind_state . cc <nl> ppp b / caffe2 / python / pybind_state . cc <nl> void addObjectMethods ( py : : module & m ) { <nl> } ) <nl> . def ( <nl> " _reshape " , <nl> - [ ] ( DLPackWrapper < CPUContext > * t , std : : vector < TIndex > dims ) { <nl> + [ ] ( DLPackWrapper < CPUContext > * t , std : : vector < int64_t > dims ) { <nl> auto * tensor = t - > tensor ; <nl> tensor - > Resize ( dims ) ; <nl> } ) ; <nl> void addObjectMethods ( py : : module & m ) { <nl> " Copy data from this tensor into a new numpy array . " ) <nl> . def ( <nl> " init " , <nl> - [ ] ( Tensor * t , std : : vector < TIndex > dims , int caffe_type ) { <nl> + [ ] ( Tensor * t , std : : vector < int64_t > dims , int caffe_type ) { <nl> const auto & meta = <nl> DataTypeToTypeMeta ( ( TensorProto : : DataType ) caffe_type ) ; <nl> CAFFE_ENFORCE ( <nl> void addObjectMethods ( py : : module & m ) { <nl> " Fail if the given data type cannot be accessed from python . " ) <nl> . def_property_readonly ( <nl> " _shape " , [ ] ( const TensorCPU & t ) { return t . dims ( ) ; } ) <nl> - . def ( " _reshape " , [ ] ( TensorCPU * t , std : : vector < TIndex > dims ) { <nl> + . def ( " _reshape " , [ ] ( TensorCPU * t , std : : vector < int64_t > dims ) { <nl> t - > Resize ( dims ) ; <nl> } ) ; <nl> <nl> void addGlobalMethods ( py : : module & m ) { <nl> m . def ( <nl> " infer_shapes_and_types_from_map " , <nl> [ ] ( const std : : vector < py : : bytes > & net_protos , <nl> - const std : : map < std : : string , std : : vector < TIndex > > blob_dimensions ) { <nl> + const std : : map < std : : string , std : : vector < int64_t > > blob_dimensions ) { <nl> / / Parse protobuffers to NetDefs <nl> std : : vector < std : : unique_ptr < caffe2 : : NetDef > > nets ; <nl> std : : vector < caffe2 : : NetDef * > nets_ptr ; <nl> void addGlobalMethods ( py : : module & m ) { <nl> m . def ( <nl> " infer_shapes_and_types_from_map " , <nl> [ ] ( const std : : vector < py : : bytes > & net_protos , <nl> - const std : : map < std : : string , std : : vector < TIndex > > blob_dimensions , <nl> + const std : : map < std : : string , std : : vector < int64_t > > blob_dimensions , <nl> const std : : map < std : : string , int > int_blob_types ) { <nl> / / Parse protobuffers to NetDefs <nl> std : : vector < std : : unique_ptr < caffe2 : : NetDef > > nets ; <nl> mmm a / caffe2 / python / pybind_state . h <nl> ppp b / caffe2 / python / pybind_state . h <nl> class TensorFeeder : public BlobFeederBase { <nl> / / numpy requires long int as its dims . <nl> int ndim = PyArray_NDIM ( array ) ; <nl> npy_intp * npy_dims = PyArray_DIMS ( array ) ; <nl> - std : : vector < TIndex > dims ; <nl> + std : : vector < int64_t > dims ; <nl> for ( int i = 0 ; i < ndim ; + + i ) { <nl> dims . push_back ( npy_dims [ i ] ) ; <nl> } <nl> mmm a / caffe2 / python / pybind_state_dlpack . h <nl> ppp b / caffe2 / python / pybind_state_dlpack . h <nl> class DLPackWrapper { <nl> device_option . cuda_gpu_id ( ) , <nl> " Expected same device id for DLPack and C2 tensors " ) ; <nl> <nl> - std : : vector < TIndex > dims ; <nl> + std : : vector < int64_t > dims ; <nl> dims . reserve ( dlTensor - > ndim ) ; <nl> for ( int idx = 0 ; idx < dlTensor - > ndim ; + + idx ) { <nl> dims . push_back ( dlTensor - > shape [ idx ] ) ; <nl> mmm a / caffe2 / python / pybind_state_gpu . cc <nl> ppp b / caffe2 / python / pybind_state_gpu . cc <nl> void addCUDAObjectMethods ( py : : module & m ) { <nl> [ ] ( const DLPackWrapper < CUDAContext > & t ) { return t . tensor - > dims ( ) ; } ) <nl> . def ( <nl> " _reshape " , <nl> - [ ] ( DLPackWrapper < CUDAContext > * t , std : : vector < TIndex > dims ) { <nl> + [ ] ( DLPackWrapper < CUDAContext > * t , std : : vector < int64_t > dims ) { <nl> t - > tensor - > Resize ( dims ) ; <nl> } ) ; <nl> } <nl> mmm a / caffe2 / python / pybind_state_hip . cc <nl> ppp b / caffe2 / python / pybind_state_hip . cc <nl> void addHIPObjectMethods ( py : : module & m ) { <nl> [ ] ( const DLPackWrapper < HIPContext > & t ) { return t . tensor - > dims ( ) ; } ) <nl> . def ( <nl> " _reshape " , <nl> - [ ] ( DLPackWrapper < HIPContext > * t , std : : vector < TIndex > dims ) { <nl> + [ ] ( DLPackWrapper < HIPContext > * t , std : : vector < int64_t > dims ) { <nl> t - > tensor - > Resize ( dims ) ; <nl> } ) ; <nl> } <nl> mmm a / caffe2 / python / pybind_state_mkl . cc <nl> ppp b / caffe2 / python / pybind_state_mkl . cc <nl> class MKLMemoryFeeder : public BlobFeederBase { <nl> / / numpy requires long int as its dims . <nl> int ndim = PyArray_NDIM ( array ) ; <nl> npy_intp * npy_dims = PyArray_DIMS ( array ) ; <nl> - std : : vector < TIndex > dims ; <nl> + std : : vector < int64_t > dims ; <nl> for ( int i = 0 ; i < ndim ; + + i ) { <nl> dims . push_back ( npy_dims [ i ] ) ; <nl> } <nl> mmm a / caffe2 / queue / rebatching_queue . cc <nl> ppp b / caffe2 / queue / rebatching_queue . cc <nl> void concat ( <nl> const auto numRows = inputs . size ( ) ; <nl> <nl> / / Precompute the output sizes to avoid resizing <nl> - std : : vector < std : : vector < TIndex > > outputDims ( numTensors ) ; <nl> + std : : vector < std : : vector < int64_t > > outputDims ( numTensors ) ; <nl> <nl> for ( int i = 0 ; i < numTensors ; + + i ) { <nl> SmartTensorPrinter : : PrintTensor ( inputZero . at ( i ) ) ; <nl> mmm a / caffe2 / sgd / ftrl_op . cc <nl> ppp b / caffe2 / sgd / ftrl_op . cc <nl> void SparseFtrlOp < T > : : DoRun ( ) { <nl> auto & grad = Input ( GRAD ) ; <nl> CAFFE_ENFORCE_EQ ( & Input ( VAR ) , var , " In place operation is required " ) ; <nl> CAFFE_ENFORCE_EQ ( & Input ( N_Z ) , n_z , " In place operation is required " ) ; <nl> - TIndex M = var - > size ( ) ; <nl> - TIndex N = var - > dim ( 0 ) ; <nl> - TIndex block_size = M / N ; <nl> - TIndex K = indices . size ( ) ; <nl> + int64_t M = var - > size ( ) ; <nl> + int64_t N = var - > dim ( 0 ) ; <nl> + int64_t block_size = M / N ; <nl> + int64_t K = indices . size ( ) ; <nl> DCHECK_EQ ( M * 2 , n_z - > size ( ) ) ; <nl> DCHECK_EQ ( grad . size ( ) , K * block_size ) ; <nl> T * w = var - > template mutable_data < T > ( ) ; <nl> void SparseFtrlOp < T > : : DoRun ( ) { <nl> <nl> / / TODO ( cxj ) : use OMP when it is reliable <nl> / / # pragma omp parallel for <nl> - for ( TIndex i = 0 ; i < K ; + + i ) { <nl> + for ( int64_t i = 0 ; i < K ; + + i ) { <nl> SIndex idx = idxs [ i ] ; <nl> DCHECK ( 0 < = idx & & idx < N ) < < " Index out of bounds : " < < idx <nl> < < " , range 0 to " < < N ; <nl> void SparseFtrlOp < T > : : DoRun ( ) { <nl> nz [ idx * 2 + 1 ] , <nl> params_ ) ; <nl> } else { <nl> - TIndex x = block_size * idx ; <nl> + int64_t x = block_size * idx ; <nl> ftrl_update ( <nl> block_size , <nl> w + x , <nl> mmm a / caffe2 / sgd / lars_op . h <nl> ppp b / caffe2 / sgd / lars_op . h <nl> class LarsOp final : public Operator < Context > { <nl> auto & trust = Input ( 3 ) ; <nl> auto & lr_max = Input ( 4 ) ; <nl> auto * lr_rescaled = Output ( 0 ) ; <nl> - lr_rescaled - > Resize ( vector < TIndex > { 1 } ) ; <nl> + lr_rescaled - > Resize ( vector < int64_t > { 1 } ) ; <nl> <nl> X_norm_tensor_ . Resize ( 1 ) ; <nl> T * X_norm_ = X_norm_tensor_ . template mutable_data < T > ( ) ; <nl> class LarsOp final : public Operator < Context > { <nl> private : <nl> / / Compute the l2 norm of X_data and dX_data <nl> void ComputeNorms ( <nl> - TIndex N , <nl> + int64_t N , <nl> const T * X_data , <nl> const T * dX_data , <nl> T * X_norm , <nl> mmm a / caffe2 / sgd / learning_rate_op . h <nl> ppp b / caffe2 / sgd / learning_rate_op . h <nl> class LearningRateOp final : public Operator < Context > { <nl> T learning_rate = cur_base_lr_ * ( * functor_ ) ( iter ) ; <nl> / / Write to output . <nl> auto * output = Output ( 0 ) ; <nl> - output - > Resize ( vector < TIndex > ( ) ) ; <nl> + output - > Resize ( vector < int64_t > ( ) ) ; <nl> context_ . template CopyFromCPU < T > ( <nl> 1 , & learning_rate , Output ( 0 ) - > template mutable_data < T > ( ) ) ; <nl> return true ; <nl> mmm a / caffe2 / share / contrib / depthwise / depthwise3x3_conv_op_test . cc <nl> ppp b / caffe2 / share / contrib / depthwise / depthwise3x3_conv_op_test . cc <nl> namespace caffe2 { <nl> namespace { <nl> <nl> void AddNoiseInput ( <nl> - const vector < TIndex > & shape , <nl> + const vector < int64_t > & shape , <nl> const string & name , <nl> Workspace * ws ) { <nl> DeviceOption option ; <nl> void compare ( <nl> depthwiseOpDef . add_arg ( ) - > CopyFrom ( MakeArgument ( " pad_r " , padR ) ) ; <nl> depthwiseOpDef . add_arg ( ) - > CopyFrom ( MakeArgument ( " group " , group ) ) ; <nl> <nl> - AddNoiseInput ( vector < TIndex > { N , inputC , H , W } , " X " , & ws ) ; <nl> + AddNoiseInput ( vector < int64_t > { N , inputC , H , W } , " X " , & ws ) ; <nl> AddNoiseInput ( <nl> - vector < TIndex > { outputC , inputC / group , kernelH , kernelW } , " W " , & ws ) ; <nl> - AddNoiseInput ( vector < TIndex > { outputC } , " B " , & ws ) ; <nl> + vector < int64_t > { outputC , inputC / group , kernelH , kernelW } , " W " , & ws ) ; <nl> + AddNoiseInput ( vector < int64_t > { outputC } , " B " , & ws ) ; <nl> <nl> unique_ptr < OperatorBase > depthwiseOp ( CreateOperator ( depthwiseOpDef , & ws ) ) ; <nl> EXPECT_NE ( nullptr , depthwiseOp . get ( ) ) ; <nl> mmm a / caffe2 / share / contrib / nnpack / nnpack_test . cc <nl> ppp b / caffe2 / share / contrib / nnpack / nnpack_test . cc <nl> namespace caffe2 { <nl> namespace { <nl> <nl> void AddNoiseInput ( <nl> - const vector < TIndex > & shape , <nl> + const vector < int64_t > & shape , <nl> const string & name , <nl> Workspace * ws ) { <nl> DeviceOption option ; <nl> void compare ( <nl> nnpackOpDef . add_arg ( ) - > CopyFrom ( MakeArgument ( " pad_r " , padR ) ) ; <nl> nnpackOpDef . add_arg ( ) - > CopyFrom ( MakeArgument ( " group " , group ) ) ; <nl> <nl> - AddNoiseInput ( vector < TIndex > { N , inputC , H , W } , " X " , & ws ) ; <nl> + AddNoiseInput ( vector < int64_t > { N , inputC , H , W } , " X " , & ws ) ; <nl> AddNoiseInput ( <nl> - vector < TIndex > { outputC , inputC / group , kernelH , kernelW } , " W " , & ws ) ; <nl> - AddNoiseInput ( vector < TIndex > { outputC } , " B " , & ws ) ; <nl> + vector < int64_t > { outputC , inputC / group , kernelH , kernelW } , " W " , & ws ) ; <nl> + AddNoiseInput ( vector < int64_t > { outputC } , " B " , & ws ) ; <nl> <nl> unique_ptr < OperatorBase > nnpackOp ( CreateOperator ( nnpackOpDef , & ws ) ) ; <nl> EXPECT_NE ( nullptr , nnpackOp . get ( ) ) ; <nl> mmm a / caffe2 / share / contrib / zstd / quant_decomp_zstd_op . cc <nl> ppp b / caffe2 / share / contrib / zstd / quant_decomp_zstd_op . cc <nl> TensorProtos GetTensorsProto ( const TensorCPU & compressed ) { <nl> / / Decompress tensor stored in compressed format <nl> / / It is compressed using mutils . compress_data_list ( ) <nl> void Decompress ( const TensorProto & compressed , TensorCPU * outDecomp ) { <nl> - vector < TIndex > shape ( compressed . dims ( ) . begin ( ) , compressed . dims ( ) . end ( ) ) ; <nl> + vector < int64_t > shape ( compressed . dims ( ) . begin ( ) , compressed . dims ( ) . end ( ) ) ; <nl> / / shape stores the dimensions of data before compression , <nl> / / see _compress_data_single ( ) in mutils . py <nl> outDecomp - > Resize ( shape ) ; <nl> mmm a / caffe2 / utils / filler . h <nl> ppp b / caffe2 / utils / filler . h <nl> class TensorFiller { <nl> return Min ( 0 ) . Max ( max_segment ) . Dist ( FD_SYNTHETIC ) ; <nl> } <nl> <nl> - TensorFiller & Shape ( const std : : vector < TIndex > & shape ) { <nl> + TensorFiller & Shape ( const std : : vector < int64_t > & shape ) { <nl> shape_ = shape ; <nl> return * this ; <nl> } <nl> <nl> template < class Type > <nl> - TensorFiller ( const std : : vector < TIndex > & shape , Type fixed_sum ) <nl> + TensorFiller ( const std : : vector < int64_t > & shape , Type fixed_sum ) <nl> : shape_ ( shape ) , dist_ ( FD_FIXEDSUM ) , fixed_sum_ ( ( double ) fixed_sum ) { } <nl> <nl> - TensorFiller ( const std : : vector < TIndex > & shape ) <nl> + TensorFiller ( const std : : vector < int64_t > & shape ) <nl> : shape_ ( shape ) , dist_ ( FD_UNIFORM ) , fixed_sum_ ( 0 ) { } <nl> <nl> - TensorFiller ( ) : TensorFiller ( std : : vector < TIndex > ( ) ) { } <nl> + TensorFiller ( ) : TensorFiller ( std : : vector < int64_t > ( ) ) { } <nl> <nl> std : : string DebugString ( ) const { <nl> std : : stringstream stream ; <nl> class TensorFiller { <nl> } <nl> <nl> private : <nl> - std : : vector < TIndex > shape_ ; <nl> + std : : vector < int64_t > shape_ ; <nl> / / TODO : type is unknown until a user starts to fill data ; <nl> / / cast everything to double for now . <nl> double min_ = 0 . 0 ; <nl> mmm a / caffe2 / utils / hip / math_hip . cc <nl> ppp b / caffe2 / utils / hip / math_hip . cc <nl> DEFINE_BROADCAST_HIP_BITWISE_BINARY_FUNCTION ( BitwiseXor , thrust : : bit_xor ) <nl> cub : : DeviceReduce : : func ( \ <nl> nullptr , memRequired , src , dst , N , context - > hip_stream ( ) ) ; \ <nl> auto buffer_size = \ <nl> - static_cast < TIndex > ( ( memRequired + sizeof ( T ) - 1 ) / sizeof ( T ) ) ; \ <nl> - scratch_ptr - > Resize ( std : : vector < TIndex > { buffer_size } ) ; \ <nl> + static_cast < int64_t > ( ( memRequired + sizeof ( T ) - 1 ) / sizeof ( T ) ) ; \ <nl> + scratch_ptr - > Resize ( std : : vector < int64_t > { buffer_size } ) ; \ <nl> cub : : DeviceReduce : : func ( \ <nl> static_cast < void * > ( scratch_ptr - > mutable_data < T > ( ) ) , \ <nl> memRequired , \ <nl> void SumGenericIter ( <nl> cub : : DeviceReduce : : Sum ( <nl> nullptr , memRequired , it , dest , N , context - > hip_stream ( ) ) ; <nl> auto buffer_size = <nl> - static_cast < TIndex > ( ( memRequired + sizeof ( T ) - 1 ) / sizeof ( T ) ) ; <nl> + static_cast < int64_t > ( ( memRequired + sizeof ( T ) - 1 ) / sizeof ( T ) ) ; <nl> if ( ! dest ) { <nl> / / allocate one more T at the end of scratch for dest <nl> - scratch_ptr - > Resize ( std : : vector < TIndex > { buffer_size + 1 } ) ; <nl> + scratch_ptr - > Resize ( std : : vector < int64_t > { buffer_size + 1 } ) ; <nl> dest = scratch_ptr - > template mutable_data < T > ( ) + buffer_size ; <nl> } else { <nl> - scratch_ptr - > Resize ( std : : vector < TIndex > { buffer_size } ) ; <nl> + scratch_ptr - > Resize ( std : : vector < int64_t > { buffer_size } ) ; <nl> } <nl> cub : : DeviceReduce : : Sum ( <nl> static_cast < void * > ( scratch_ptr - > template mutable_data < T > ( ) ) , <nl> void TransposeHIPImpl ( <nl> CAFFE2_SPECIALIZED_HIP_TRANSPOSE ( float ) <nl> CAFFE2_SPECIALIZED_HIP_TRANSPOSE ( double ) <nl> CAFFE2_SPECIALIZED_HIP_TRANSPOSE ( int ) <nl> - CAFFE2_SPECIALIZED_HIP_TRANSPOSE ( TIndex ) <nl> + CAFFE2_SPECIALIZED_HIP_TRANSPOSE ( int64_t ) <nl> # undef CAFFE2_SPECIALIZED_HIP_TRANSPOSE <nl> <nl> namespace { <nl> mmm a / caffe2 / utils / math_cpu . cc <nl> ppp b / caffe2 / utils / math_cpu . cc <nl> CAFFE2_SPECIALIZED_COPY_MATRIX ( double ) <nl> # endif / / CAFFE2_USE_MKL <nl> <nl> CAFFE2_SPECIALIZED_COPY_MATRIX ( int ) <nl> - CAFFE2_SPECIALIZED_COPY_MATRIX ( TIndex ) <nl> + CAFFE2_SPECIALIZED_COPY_MATRIX ( int64_t ) <nl> # ifdef CAFFE2_UNIQUE_LONG_TYPEMETA <nl> CAFFE2_SPECIALIZED_COPY_MATRIX ( long ) <nl> # endif <nl> CAFFE2_SPECIALIZED_TRANSPOSE_2D ( double ) <nl> # endif / / CAFFE2_USE_MKL <nl> <nl> CAFFE2_SPECIALIZED_TRANSPOSE_2D ( int ) <nl> - CAFFE2_SPECIALIZED_TRANSPOSE_2D ( TIndex ) <nl> + CAFFE2_SPECIALIZED_TRANSPOSE_2D ( int64_t ) <nl> # ifdef CAFFE2_UNIQUE_LONG_TYPEMETA <nl> CAFFE2_SPECIALIZED_TRANSPOSE_2D ( long ) <nl> # endif <nl> void TransposeCPUImpl ( <nl> CAFFE2_SPECIALIZED_TRANSPOSE ( float ) <nl> CAFFE2_SPECIALIZED_TRANSPOSE ( double ) <nl> CAFFE2_SPECIALIZED_TRANSPOSE ( int ) <nl> - CAFFE2_SPECIALIZED_TRANSPOSE ( TIndex ) <nl> + CAFFE2_SPECIALIZED_TRANSPOSE ( int64_t ) <nl> # ifdef CAFFE2_UNIQUE_LONG_TYPEMETA <nl> CAFFE2_SPECIALIZED_TRANSPOSE ( long ) <nl> # endif <nl> mmm a / caffe2 / utils / math_gpu . cu <nl> ppp b / caffe2 / utils / math_gpu . cu <nl> DEFINE_BROADCAST_CUDA_BITWISE_BINARY_FUNCTION ( BitwiseXor , thrust : : bit_xor ) <nl> cub : : DeviceReduce : : func ( \ <nl> nullptr , memRequired , src , dst , N , context - > cuda_stream ( ) ) ; \ <nl> auto buffer_size = \ <nl> - static_cast < TIndex > ( ( memRequired + sizeof ( T ) - 1 ) / sizeof ( T ) ) ; \ <nl> - scratch_ptr - > Resize ( std : : vector < TIndex > { buffer_size } ) ; \ <nl> + static_cast < int64_t > ( ( memRequired + sizeof ( T ) - 1 ) / sizeof ( T ) ) ; \ <nl> + scratch_ptr - > Resize ( std : : vector < int64_t > { buffer_size } ) ; \ <nl> cub : : DeviceReduce : : func ( \ <nl> static_cast < void * > ( scratch_ptr - > mutable_data < T > ( ) ) , \ <nl> memRequired , \ <nl> CAFFE2_CUDA_EXPORT void SumGenericIter ( <nl> cub : : DeviceReduce : : Sum ( <nl> nullptr , memRequired , it , dest , N , context - > cuda_stream ( ) ) ; <nl> auto buffer_size = <nl> - static_cast < TIndex > ( ( memRequired + sizeof ( T ) - 1 ) / sizeof ( T ) ) ; <nl> + static_cast < int64_t > ( ( memRequired + sizeof ( T ) - 1 ) / sizeof ( T ) ) ; <nl> if ( ! dest ) { <nl> / / allocate one more T at the end of scratch for dest <nl> - scratch_ptr - > Resize ( std : : vector < TIndex > { buffer_size + 1 } ) ; <nl> + scratch_ptr - > Resize ( std : : vector < int64_t > { buffer_size + 1 } ) ; <nl> dest = scratch_ptr - > template mutable_data < T > ( ) + buffer_size ; <nl> } else { <nl> - scratch_ptr - > Resize ( std : : vector < TIndex > { buffer_size } ) ; <nl> + scratch_ptr - > Resize ( std : : vector < int64_t > { buffer_size } ) ; <nl> } <nl> cub : : DeviceReduce : : Sum ( <nl> static_cast < void * > ( scratch_ptr - > template mutable_data < T > ( ) ) , <nl> CAFFE2_CUDA_EXPORT void CopyMatrix < CUDAContext > ( <nl> CAFFE2_SPECIALIZED_CUDA_COPY_MATRIX ( float ) <nl> CAFFE2_SPECIALIZED_CUDA_COPY_MATRIX ( double ) <nl> CAFFE2_SPECIALIZED_CUDA_COPY_MATRIX ( int ) <nl> - CAFFE2_SPECIALIZED_CUDA_COPY_MATRIX ( TIndex ) <nl> + CAFFE2_SPECIALIZED_CUDA_COPY_MATRIX ( int64_t ) <nl> # undef CAFFE2_SPECIALIZED_CUDA_COPY_MATRIX <nl> <nl> template < > <nl> CAFFE2_CUDA_EXPORT void TransposeCUDAImpl ( <nl> CAFFE2_SPECIALIZED_CUDA_TRANSPOSE ( float ) <nl> CAFFE2_SPECIALIZED_CUDA_TRANSPOSE ( double ) <nl> CAFFE2_SPECIALIZED_CUDA_TRANSPOSE ( int ) <nl> - CAFFE2_SPECIALIZED_CUDA_TRANSPOSE ( TIndex ) <nl> + CAFFE2_SPECIALIZED_CUDA_TRANSPOSE ( int64_t ) <nl> # undef CAFFE2_SPECIALIZED_CUDA_TRANSPOSE <nl> <nl> namespace { <nl> mmm a / caffe2 / utils / math_gpu_test . cc <nl> ppp b / caffe2 / utils / math_gpu_test . cc <nl> class GemmBatchedGPUTest <nl> X_ = X_blob - > GetMutableTensor ( CUDA ) ; <nl> W_ = W_blob - > GetMutableTensor ( CUDA ) ; <nl> Y_ = Y_blob - > GetMutableTensor ( CUDA ) ; <nl> - X_ - > Resize ( std : : vector < TIndex > { 3 , 5 , 10 } ) ; <nl> - W_ - > Resize ( std : : vector < TIndex > { 3 , 6 , 10 } ) ; <nl> - Y_ - > Resize ( std : : vector < TIndex > { 3 , 5 , 6 } ) ; <nl> + X_ - > Resize ( std : : vector < int64_t > { 3 , 5 , 10 } ) ; <nl> + W_ - > Resize ( std : : vector < int64_t > { 3 , 6 , 10 } ) ; <nl> + Y_ - > Resize ( std : : vector < int64_t > { 3 , 5 , 6 } ) ; <nl> math : : Set < float , CUDAContext > ( <nl> X_ - > size ( ) , 1 . 0f , X_ - > mutable_data < float > ( ) , cuda_context_ . get ( ) ) ; <nl> math : : Set < float , CUDAContext > ( <nl> mmm a / caffe2 / utils / math_test . cc <nl> ppp b / caffe2 / utils / math_test . cc <nl> class GemmBatchedTest <nl> protected : <nl> void SetUp ( ) override { <nl> cpu_context_ = make_unique < CPUContext > ( option_ ) ; <nl> - X_ . Resize ( std : : vector < TIndex > { 3 , 5 , 10 } ) ; <nl> - W_ . Resize ( std : : vector < TIndex > { 3 , 6 , 10 } ) ; <nl> - Y_ . Resize ( std : : vector < TIndex > { 3 , 5 , 6 } ) ; <nl> + X_ . Resize ( std : : vector < int64_t > { 3 , 5 , 10 } ) ; <nl> + W_ . Resize ( std : : vector < int64_t > { 3 , 6 , 10 } ) ; <nl> + Y_ . Resize ( std : : vector < int64_t > { 3 , 5 , 6 } ) ; <nl> math : : Set < float , CPUContext > ( <nl> X_ . size ( ) , 1 , X_ . mutable_data < float > ( ) , cpu_context_ . get ( ) ) ; <nl> math : : Set < float , CPUContext > ( <nl> mmm a / caffe2 / utils / smart_tensor_printer_test . cc <nl> ppp b / caffe2 / utils / smart_tensor_printer_test . cc <nl> void printTensorAndCheck ( const std : : vector < T > & values ) { <nl> CPUContext cpuContext ; <nl> <nl> Tensor tensor ( <nl> - std : : vector < TIndex > { static_cast < TIndex > ( values . size ( ) ) } , <nl> + std : : vector < int64_t > { static_cast < int64_t > ( values . size ( ) ) } , <nl> values , <nl> & cpuContext ) ; <nl> <nl> mmm a / caffe2 / video / video_input_op . h <nl> ppp b / caffe2 / video / video_input_op . h <nl> VideoInputOp < Context > : : VideoInputOp ( <nl> CAFFE_ENFORCE_GT ( <nl> operator_def . input_size ( ) , 0 , " Need to have a DBReader blob input " ) ; <nl> <nl> - vector < TIndex > data_shape ( 5 ) ; <nl> - vector < TIndex > label_shape ( 2 ) ; <nl> + vector < int64_t > data_shape ( 5 ) ; <nl> + vector < int64_t > label_shape ( 2 ) ; <nl> <nl> / / for RGB data <nl> data_shape [ 0 ] = batch_size_ * clip_per_video_ * multi_crop_count_ ; <nl> VideoInputOp < Context > : : VideoInputOp ( <nl> prefetched_label_ . Resize ( label_shape ) ; <nl> } else { <nl> prefetched_label_ . Resize ( <nl> - vector < TIndex > ( 1 , batch_size_ * clip_per_video_ * multi_crop_count_ ) ) ; <nl> + vector < int64_t > ( 1 , batch_size_ * clip_per_video_ * multi_crop_count_ ) ) ; <nl> } <nl> <nl> prefetched_video_id_ . Resize ( <nl> - vector < TIndex > ( 1 , batch_size_ * clip_per_video_ * multi_crop_count_ ) ) ; <nl> + vector < int64_t > ( 1 , batch_size_ * clip_per_video_ * multi_crop_count_ ) ) ; <nl> } <nl> <nl> template < class Context > <nl> mmm a / modules / detectron / sample_as_op . cu <nl> ppp b / modules / detectron / sample_as_op . cu <nl> bool SampleAsOp < float , CUDAContext > : : RunOnDevice ( ) { <nl> assert ( count > 0 ) ; <nl> <nl> / / resize Y <nl> - vector < TIndex > out_shape ( X . dims ( ) ) ; <nl> + vector < int64_t > out_shape ( X . dims ( ) ) ; <nl> out_shape [ 0 ] = count ; <nl> Y - > Resize ( out_shape ) ; <nl> <nl> mmm a / modules / detectron / select_smooth_l1_loss_op . cu <nl> ppp b / modules / detectron / select_smooth_l1_loss_op . cu <nl> bool SelectSmoothL1LossOp < float , CUDAContext > : : RunOnDevice ( ) { <nl> auto & S = Input ( 3 ) ; <nl> auto * avg_loss = Output ( 0 ) ; <nl> <nl> - avg_loss - > Resize ( vector < TIndex > ( ) ) ; <nl> + avg_loss - > Resize ( vector < int64_t > ( ) ) ; <nl> if ( Y . size ( ) = = 0 ) { <nl> math : : Set < float , CUDAContext > ( <nl> 1 , static_cast < float > ( 0 ) , avg_loss - > mutable_data < float > ( ) , & context_ ) ; <nl> mmm a / modules / detectron / sigmoid_cross_entropy_loss_op . cu <nl> ppp b / modules / detectron / sigmoid_cross_entropy_loss_op . cu <nl> bool SigmoidCrossEntropyLossOp < float , CUDAContext > : : RunOnDevice ( ) { <nl> " vs . " , <nl> T . size ( ) , <nl> " ) " ) ; <nl> - avg_loss - > Resize ( vector < TIndex > ( ) ) ; <nl> + avg_loss - > Resize ( vector < int64_t > ( ) ) ; <nl> counts_ . ResizeLike ( X ) ; <nl> losses_ . ResizeLike ( X ) ; <nl> - normalizer_ . Resize ( vector < TIndex > ( ) ) ; <nl> + normalizer_ . Resize ( vector < int64_t > ( ) ) ; <nl> SigmoidCrossEntropyLossKernel < < < <nl> CAFFE_GET_BLOCKS ( X . size ( ) ) , <nl> CAFFE_CUDA_NUM_THREADS , <nl> bool SigmoidCrossEntropyLossGradientOp < float , CUDAContext > : : RunOnDevice ( ) { <nl> <nl> dX - > ResizeLike ( X ) ; <nl> counts_ . ResizeLike ( X ) ; <nl> - normalizer_ . Resize ( vector < TIndex > ( ) ) ; <nl> + normalizer_ . Resize ( vector < int64_t > ( ) ) ; <nl> SigmoidCrossEntropyLossGradientKernel < < < <nl> CAFFE_GET_BLOCKS ( X . size ( ) ) , <nl> CAFFE_CUDA_NUM_THREADS , <nl> mmm a / modules / detectron / sigmoid_focal_loss_op . cu <nl> ppp b / modules / detectron / sigmoid_focal_loss_op . cu <nl> bool SigmoidFocalLossOp < float , CUDAContext > : : RunOnDevice ( ) { <nl> int H = X . dim32 ( 2 ) ; <nl> int W = X . dim32 ( 3 ) ; <nl> <nl> - avg_loss - > Resize ( vector < TIndex > ( ) ) ; <nl> + avg_loss - > Resize ( vector < int64_t > ( ) ) ; <nl> losses_ . ResizeLike ( X ) ; <nl> float * avg_loss_data = avg_loss - > mutable_data < float > ( ) ; <nl> <nl> mmm a / modules / detectron / smooth_l1_loss_op . cu <nl> ppp b / modules / detectron / smooth_l1_loss_op . cu <nl> bool SmoothL1LossOp < float , CUDAContext > : : RunOnDevice ( ) { <nl> CAFFE_ENFORCE_EQ ( Y_hat . size ( ) , alpha_in . size ( ) ) ; <nl> CAFFE_ENFORCE_EQ ( Y_hat . size ( ) , alpha_out . size ( ) ) ; <nl> <nl> - avg_loss - > Resize ( vector < TIndex > ( ) ) ; <nl> + avg_loss - > Resize ( vector < int64_t > ( ) ) ; <nl> buff_ . ResizeLike ( Y ) ; <nl> <nl> / / Difference <nl> mmm a / modules / detectron / softmax_focal_loss_op . cu <nl> ppp b / modules / detectron / softmax_focal_loss_op . cu <nl> bool SoftmaxFocalLossOp < float , CUDAContext > : : RunOnDevice ( ) { <nl> <nl> losses_ . Resize ( N * A * H * W ) ; <nl> P - > Resize ( N * D * H * W ) ; <nl> - avg_loss - > Resize ( vector < TIndex > ( ) ) ; <nl> + avg_loss - > Resize ( vector < int64_t > ( ) ) ; <nl> math : : Set < float , CUDAContext > ( <nl> avg_loss - > size ( ) , 0 . f , avg_loss - > mutable_data < float > ( ) , & context_ ) ; <nl> math : : Set < float , CUDAContext > ( <nl> mmm a / modules / detectron / upsample_nearest_op . cu <nl> ppp b / modules / detectron / upsample_nearest_op . cu <nl> bool UpsampleNearestOp < float , CUDAContext > : : RunOnDevice ( ) { <nl> auto & X = Input ( 0 ) ; <nl> auto * Y = Output ( 0 ) ; <nl> <nl> - vector < TIndex > out_shape ; <nl> + vector < int64_t > out_shape ; <nl> for ( int i = 0 ; i < X . ndim ( ) ; + + i ) { <nl> out_shape . push_back ( X . dim32 ( i ) ) ; <nl> } <nl> | Remove many caffe2 : : TIndex and replace them with int64_t ( ) | pytorch/pytorch | a6630e25afb49642cf517ee948f5a0c06a9cba6d | 2018-09-23T01:11:04Z |
new file mode 100644 <nl> index 000000000000 . . caa55673f93b <nl> mmm / dev / null <nl> ppp b / test / Incremental / Inputs / superfluous - cascade - across - modules / doesNotUseLib . swift <nl> <nl> + extension Map { <nl> + func pin ( ) { } <nl> + } <nl> new file mode 100644 <nl> index 000000000000 . . 8b137891791f <nl> mmm / dev / null <nl> ppp b / test / Incremental / Inputs / superfluous - cascade - across - modules / main . swift <nl> @ @ - 0 , 0 + 1 @ @ <nl> + <nl> new file mode 100644 <nl> index 000000000000 . . 2d6538c29269 <nl> mmm / dev / null <nl> ppp b / test / Incremental / Inputs / superfluous - cascade - across - modules / ofm . json <nl> <nl> + { <nl> + " main . swift " : { <nl> + " object " : " . / main . o " , <nl> + " swift - dependencies " : " . / main . swiftdeps " <nl> + } , <nl> + " usesLib . swift " : { <nl> + " object " : " . / usesLib . o " , <nl> + " swift - dependencies " : " . / usesLib . swiftdeps " <nl> + } , <nl> + " usesLibTransitively . swift " : { <nl> + " object " : " . / usesLib . o " , <nl> + " swift - dependencies " : " . / usesLib . swiftdeps " <nl> + } , <nl> + " doesNotUseLib . swift " : { <nl> + " object " : " . / doesNotUseLib . o " , <nl> + " swift - dependencies " : " . / doesNotUseLib . swiftdeps " <nl> + } , <nl> + " " : { <nl> + " swift - dependencies " : " . / main ~ buildrecord . swiftdeps " <nl> + } <nl> + } <nl> + <nl> new file mode 100644 <nl> index 000000000000 . . 347f0da653ba <nl> mmm / dev / null <nl> ppp b / test / Incremental / Inputs / superfluous - cascade - across - modules / submodule / lib - after . swift <nl> <nl> + public struct Library { <nl> + var catalog : [ Book ] <nl> + } <nl> + <nl> + public struct Book { <nl> + var title : String <nl> + var checkOutCount : Int <nl> + } <nl> new file mode 100644 <nl> index 000000000000 . . c9bb3d05e9d0 <nl> mmm / dev / null <nl> ppp b / test / Incremental / Inputs / superfluous - cascade - across - modules / submodule / lib - before . swift <nl> <nl> + public struct Library { <nl> + var catalog : [ Book ] <nl> + } <nl> + <nl> + public struct Book { <nl> + var title : String <nl> + } <nl> new file mode 100644 <nl> index 000000000000 . . d2f9889464c4 <nl> mmm / dev / null <nl> ppp b / test / Incremental / Inputs / superfluous - cascade - across - modules / submodule / ofm . json <nl> <nl> + { <nl> + " lib . swift " : { <nl> + " object " : " . / lib . o " , <nl> + " swift - dependencies " : " . / lib . swiftdeps " <nl> + } , <nl> + " " : { <nl> + " swift - dependencies " : " . / submodule ~ buildrecord . swiftdeps " <nl> + } <nl> + } <nl> + <nl> new file mode 100644 <nl> index 000000000000 . . 96bb74c8750c <nl> mmm / dev / null <nl> ppp b / test / Incremental / Inputs / superfluous - cascade - across - modules / usesLib . swift <nl> <nl> + import Lib <nl> + <nl> + public struct District { <nl> + var libraries : [ Library ] <nl> + } <nl> + <nl> + struct Map { } <nl> new file mode 100644 <nl> index 000000000000 . . a205027f286c <nl> mmm / dev / null <nl> ppp b / test / Incremental / Inputs / superfluous - cascade - across - modules / usesLibTransitively . swift <nl> <nl> + struct County { <nl> + var districts : [ District ] <nl> + } <nl> new file mode 100644 <nl> index 000000000000 . . 0c76afd0864a <nl> mmm / dev / null <nl> ppp b / test / Incremental / superfluous - cascade - across - modules . swift <nl> <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + / / Without private dependencies <nl> + / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + <nl> + / / First , build a submodule <nl> + <nl> + / / RUN : % empty - directory ( % t ) <nl> + / / RUN : cp % S / Inputs / superfluous - cascade - across - modules / * . swift % t <nl> + / / RUN : cp % S / Inputs / superfluous - cascade - across - modules / * . json % t <nl> + <nl> + / / RUN : % target - build - swift % S / Inputs / superfluous - cascade - across - modules / submodule / lib - before . swift - emit - module - emit - library - module - name Lib - module - link - name Lib - emit - module - path % t / Lib . swiftmodule - o % t / % target - library - name ( Lib ) <nl> + <nl> + / / Build the main executable that depends on the submodule we just built <nl> + <nl> + / / RUN : cd % t & & % swiftc_driver - emit - module - enable - batch - mode - j2 - incremental - driver - show - incremental - I % t - L % t - lLib - module - name main \ <nl> + / / RUN : - output - file - map ofm . json \ <nl> + / / RUN : main . swift \ <nl> + / / RUN : doesNotUseLib . swift \ <nl> + / / RUN : usesLib . swift \ <nl> + / / RUN : usesLibTransitively . swift > & output1 <nl> + <nl> + / / Rebuild the submodule <nl> + <nl> + / / RUN : % target - build - swift % S / Inputs / superfluous - cascade - across - modules / submodule / lib - after . swift - emit - module - emit - library - module - name Lib - module - link - name Lib - emit - module - path % t / Lib . swiftmodule - o % t / % target - library - name ( Lib ) <nl> + <nl> + / / Rebuild the main executable <nl> + <nl> + / / RUN : cd % t & & % swiftc_driver - emit - module - enable - batch - mode - j2 - incremental - driver - show - incremental - I % t - L % t - lLib - module - name main \ <nl> + / / RUN : - output - file - map ofm . json \ <nl> + / / RUN : main . swift \ <nl> + / / RUN : doesNotUseLib . swift \ <nl> + / / RUN : usesLib . swift \ <nl> + / / RUN : usesLibTransitively . swift > & output2 <nl> + <nl> + / / RUN : % FileCheck - check - prefix = CHECK - STATUS - QUO - RECOMPILED % s < % t / output2 <nl> + <nl> + / / CHECK - STATUS - QUO - RECOMPILED - DAG : Queuing because of external dependencies : { compile : main <nl> + / / CHECK - STATUS - QUO - RECOMPILED - DAG : Queuing because of external dependencies : { compile : usesLib <nl> + / / CHECK - STATUS - QUO - RECOMPILED - DAG : Queuing because of external dependencies : { compile : doesNotUseLib <nl> | Add a Test Demonstrating Superfluous Cascading Across Module Boundaries | apple/swift | 71d4c3ac5591d7002d83486d7cddee6c2c1a19b6 | 2020-06-01T17:45:25Z |
mmm a / src / mongo / db / catalog / capped_utils . cpp <nl> ppp b / src / mongo / db / catalog / capped_utils . cpp <nl> mongo : : Status mongo : : convertToCapped ( OperationContext * opCtx , <nl> double size ) { <nl> StringData dbname = collectionName . db ( ) ; <nl> StringData shortSource = collectionName . coll ( ) ; <nl> - const std : : string shortTmpName = str : : stream ( ) < < " tmp . convertToCapped . " < < shortSource ; <nl> - const NamespaceString longTmpName ( dbname , shortTmpName ) ; <nl> <nl> AutoGetDb autoDb ( opCtx , collectionName . db ( ) , MODE_X ) ; <nl> <nl> mongo : : Status mongo : : convertToCapped ( OperationContext * opCtx , <nl> <nl> BackgroundOperation : : assertNoBgOpInProgForDb ( dbname ) ; <nl> <nl> - / / If the temporary collection already exists due to an earlier aborted attempt , delete it . <nl> - if ( db - > getCollection ( opCtx , longTmpName ) ) { <nl> - BSONObjBuilder unusedResult ; <nl> - Status status = <nl> - dropCollection ( opCtx , <nl> - longTmpName , <nl> - unusedResult , <nl> - repl : : OpTime ( ) , <nl> - DropCollectionSystemCollectionMode : : kAllowSystemCollectionDrops ) ; <nl> - if ( ! status . isOK ( ) ) <nl> - return status ; <nl> + / / Generate a temporary collection name that will not collide with any existing collections . <nl> + auto tmpNameResult = <nl> + db - > makeUniqueCollectionNamespace ( opCtx , " tmp % % % % % . convertToCapped . " + shortSource ) ; <nl> + if ( ! tmpNameResult . isOK ( ) ) { <nl> + return Status ( tmpNameResult . getStatus ( ) . code ( ) , <nl> + str : : stream ( ) < < " Cannot generate temporary collection namespace to convert " <nl> + < < collectionName . ns ( ) <nl> + < < " to a capped collection : " <nl> + < < tmpNameResult . getStatus ( ) . reason ( ) ) ; <nl> } <nl> + const auto & longTmpName = tmpNameResult . getValue ( ) ; <nl> + const auto shortTmpName = longTmpName . coll ( ) . toString ( ) ; <nl> <nl> { <nl> Status status = <nl> | SERVER - 29057 convertToCapped uses randomly generated temporary collection name | mongodb/mongo | 8f61a856fc7add0eed9f1572c18b0e4b996ff177 | 2017-07-28T15:14:38Z |
mmm a / src / os / async_thread . cc <nl> ppp b / src / os / async_thread . cc <nl> class ThreadPool <nl> _event_copy - > pipe_fd = SwooleTG . aio_pipe_write ; <nl> _queue . push ( _event_copy ) ; <nl> _cv . notify_one ( ) ; <nl> + swDebug ( " push and notify one : % f " , swoole_microtime ( ) ) ; <nl> return _event_copy ; <nl> } <nl> <nl> void swoole : : async : : ThreadPool : : create_thread ( const bool is_core_worker ) <nl> while ( running ) <nl> { <nl> AsyncEvent * event = _queue . pop ( ) ; <nl> + <nl> + swDebug ( " % s : % f " , event ? " pop 1 event " : " no event " , swoole_microtime ( ) ) ; <nl> + <nl> if ( event ) <nl> { <nl> if ( sw_unlikely ( event - > handler = = nullptr ) ) <nl> static int swAio_init ( ) <nl> init_lock . lock ( ) ; <nl> if ( ( refcount + + ) = = 0 ) <nl> { <nl> - pool = new swoole : : async : : ThreadPool ( SwooleG . aio_core_worker_num , SwooleG . aio_worker_num , <nl> - SwooleG . aio_max_wait_time , SwooleG . aio_max_idle_time ) ; <nl> + pool = new swoole : : async : : ThreadPool ( <nl> + SwooleG . aio_core_worker_num , SwooleG . aio_worker_num , <nl> + SwooleG . aio_max_wait_time , SwooleG . aio_max_idle_time <nl> + ) ; <nl> pool - > start ( ) ; <nl> SwooleTG . aio_schedule = 1 ; <nl> SwooleG . aio_default_pipe_fd = SwooleTG . aio_pipe_write ; <nl> | debug | swoole/swoole-src | a98f65d69c707658f00ea8ba23977e2b7fd016cb | 2019-09-10T09:20:37Z |
mmm a / tensorflow / tensorflow . bzl <nl> ppp b / tensorflow / tensorflow . bzl <nl> def tf_gpu_library ( deps = None , cuda_deps = None , copts = tf_copts ( ) , * * kwargs ) : <nl> " @ local_config_cuda / / cuda : cuda_headers " , <nl> ] ) + if_rocm_is_configured ( cuda_deps + [ <nl> # rocm_header placeholder <nl> - # rocm_header placeholder <nl> + " @ local_config_rocm / / rocm : rocm_headers " , <nl> ] ) , <nl> copts = ( copts + if_cuda ( [ " - DGOOGLE_CUDA = 1 " ] ) + if_rocm ( [ " - DTENSORFLOW_USE_ROCM = 1 " ] ) + if_mkl ( [ " - DINTEL_MKL = 1 " ] ) + if_mkl_open_source_only ( [ " - DINTEL_MKL_DNN_ONLY " ] ) + if_enable_mkl ( [ " - DENABLE_MKL " ] ) + if_tensorrt ( [ " - DGOOGLE_TENSORRT = 1 " ] ) ) , <nl> * * kwargs <nl> | fix incorrect tensorflow . bzl for ROCm headers | tensorflow/tensorflow | b9a119247f95e1593e37f0a46c6636047779a442 | 2019-03-15T15:07:12Z |
mmm a / scene / gui / text_edit . cpp <nl> ppp b / scene / gui / text_edit . cpp <nl> void TextEdit : : _notification ( int p_what ) { <nl> cursor_pos = Point2i ( char_ofs + char_margin , ofs_y ) ; <nl> if ( insert_mode ) { <nl> cursor_pos . y + = get_row_height ( ) ; <nl> - VisualServer : : get_singleton ( ) - > canvas_item_add_rect ( ci , Rect2 ( cursor_pos , Size2i ( char_w , 1 ) ) , cache . font_color ) ; <nl> + VisualServer : : get_singleton ( ) - > canvas_item_add_rect ( ci , Rect2 ( cursor_pos , Size2i ( char_w , 1 ) ) , cache . caret_color ) ; <nl> } else { <nl> - VisualServer : : get_singleton ( ) - > canvas_item_add_rect ( ci , Rect2 ( cursor_pos , Size2i ( 1 , get_row_height ( ) ) ) , cache . font_color ) ; <nl> + VisualServer : : get_singleton ( ) - > canvas_item_add_rect ( ci , Rect2 ( cursor_pos , Size2i ( 1 , get_row_height ( ) ) ) , cache . caret_color ) ; <nl> } <nl> <nl> <nl> void TextEdit : : _notification ( int p_what ) { <nl> if ( insert_mode ) { <nl> cursor_pos . y + = get_row_height ( ) ; <nl> int char_w = cache . font - > get_char_size ( ' ' ) . width ; <nl> - VisualServer : : get_singleton ( ) - > canvas_item_add_rect ( ci , Rect2 ( cursor_pos , Size2i ( char_w , 1 ) ) , cache . font_color ) ; <nl> + VisualServer : : get_singleton ( ) - > canvas_item_add_rect ( ci , Rect2 ( cursor_pos , Size2i ( char_w , 1 ) ) , cache . caret_color ) ; <nl> } else { <nl> - VisualServer : : get_singleton ( ) - > canvas_item_add_rect ( ci , Rect2 ( cursor_pos , Size2i ( 1 , get_row_height ( ) ) ) , cache . font_color ) ; <nl> + VisualServer : : get_singleton ( ) - > canvas_item_add_rect ( ci , Rect2 ( cursor_pos , Size2i ( 1 , get_row_height ( ) ) ) , cache . caret_color ) ; <nl> } <nl> } <nl> } <nl> void TextEdit : : _update_caches ( ) { <nl> cache . style_normal = get_stylebox ( " normal " ) ; <nl> cache . style_focus = get_stylebox ( " focus " ) ; <nl> cache . font = get_font ( " font " ) ; <nl> + cache . caret_color = get_color ( " caret_color " ) ; <nl> cache . font_color = get_color ( " font_color " ) ; <nl> cache . font_selected_color = get_color ( " font_selected_color " ) ; <nl> cache . keyword_color = get_color ( " keyword_color " ) ; <nl> mmm a / scene / gui / text_edit . h <nl> ppp b / scene / gui / text_edit . h <nl> class TextEdit : public Control { <nl> Ref < StyleBox > style_normal ; <nl> Ref < StyleBox > style_focus ; <nl> Ref < Font > font ; <nl> + Color caret_color ; <nl> Color font_color ; <nl> Color font_selected_color ; <nl> Color keyword_color ; <nl> mmm a / tools / editor / editor_settings . cpp <nl> ppp b / tools / editor / editor_settings . cpp <nl> void EditorSettings : : _load_defaults ( Ref < ConfigFile > p_extra_config ) { <nl> hints [ " global / default_project_export_path " ] = PropertyInfo ( Variant : : STRING , " global / default_project_export_path " , PROPERTY_HINT_GLOBAL_DIR ) ; <nl> set ( " global / show_script_in_scene_tabs " , false ) ; <nl> set ( " text_editor / background_color " , Color : : html ( " 3b000000 " ) ) ; <nl> + set ( " text_editor / caret_color " , Color : : html ( " aaaaaa " ) ) ; <nl> set ( " text_editor / text_color " , Color : : html ( " aaaaaa " ) ) ; <nl> set ( " text_editor / text_selected_color " , Color : : html ( " 000000 " ) ) ; <nl> set ( " text_editor / keyword_color " , Color : : html ( " ffffb3 " ) ) ; <nl> mmm a / tools / editor / plugins / script_editor_plugin . cpp <nl> ppp b / tools / editor / plugins / script_editor_plugin . cpp <nl> void ScriptTextEditor : : _load_theme_settings ( ) { <nl> <nl> get_text_edit ( ) - > set_custom_bg_color ( EDITOR_DEF ( " text_editor / background_color " , Color ( 0 , 0 , 0 , 0 ) ) ) ; <nl> get_text_edit ( ) - > add_color_override ( " font_color " , EDITOR_DEF ( " text_editor / text_color " , Color ( 0 , 0 , 0 ) ) ) ; <nl> + get_text_edit ( ) - > add_color_override ( " caret_color " , EDITOR_DEF ( " text_editor / caret_color " , Color ( 0 , 0 , 0 ) ) ) ; <nl> get_text_edit ( ) - > add_color_override ( " font_selected_color " , EDITOR_DEF ( " text_editor / text_selected_color " , Color ( 1 , 1 , 1 ) ) ) ; <nl> get_text_edit ( ) - > add_color_override ( " selection_color " , EDITOR_DEF ( " text_editor / selection_color " , Color ( 0 . 2 , 0 . 2 , 1 ) ) ) ; <nl> get_text_edit ( ) - > add_color_override ( " brace_mismatch_color " , EDITOR_DEF ( " text_editor / brace_mismatch_color " , Color ( 1 , 0 . 2 , 0 . 2 ) ) ) ; <nl> | Ability to change the caret color | godotengine/godot | c7519f091d6c4bd3f7edc1b8213fb4aa418fad3a | 2016-04-05T16:06:56Z |
mmm a / src / ndarray . jl <nl> ppp b / src / ndarray . jl <nl> end <nl> <nl> Elementwise divide a scalar by an ` NDArray ` . Inplace updating . <nl> " " " <nl> - function rdiv_from ! ( x : : Real , y : : NDArray { T } ) where { T } <nl> + function rdiv_from ! ( x : : Real , y : : NDArray ) <nl> @ assert y . writable <nl> - _rdiv_scalar ( y , scalar = convert ( T , x ) , out = y ) <nl> + _rdiv_scalar ( y , scalar = x , out = y ) <nl> + y <nl> end <nl> <nl> import Base : / <nl> mmm a / test / unittest / ndarray . jl <nl> ppp b / test / unittest / ndarray . jl <nl> function test_rdiv ( ) <nl> y = 1 . / Float32 [ 1 2 ; 3 4 ] <nl> @ test copy ( x ) ≈ y <nl> end <nl> + <nl> + info ( " NDArray : rdiv : : type convert " ) <nl> + let x = mx . NDArray ( [ 1 , 2 , 3 ] ) <nl> + y = 5 . 5 . / x <nl> + @ test eltype ( y ) = = Int # this differs from julia <nl> + @ test copy ( y ) = = [ 5 , 2 , 1 ] <nl> + end <nl> end # function test_rdiv <nl> <nl> <nl> | ndarray : type convertion of _rdiv_scalar ( ) | apache/incubator-mxnet | 642b17b1c06f81ecf485588f00006b581d53ae41 | 2017-12-04T03:53:34Z |
mmm a / dlib / dnn / core . h <nl> ppp b / dlib / dnn / core . h <nl> namespace dlib <nl> { <nl> std : : vector < label_type > results ( std : : distance ( data . begin ( ) , data . end ( ) ) ) ; <nl> auto o = results . begin ( ) ; <nl> - for ( auto i = data . begin ( ) ; i < data . end ( ) ; i + = batch_size , o + = batch_size ) <nl> + auto i = data . begin ( ) ; <nl> + auto num_remaining = results . size ( ) ; <nl> + while ( num_remaining ! = 0 ) <nl> { <nl> - auto end = std : : min ( i + batch_size , data . end ( ) ) ; <nl> - ( * this ) ( i , end , o ) ; <nl> + auto inc = std : : min ( batch_size , num_remaining ) ; <nl> + ( * this ) ( i , i + inc , o ) ; <nl> + i + = inc ; <nl> + o + = inc ; <nl> + num_remaining - = inc ; <nl> } <nl> return results ; <nl> } <nl> | Changed code to avoid advancing iterator beyond end since some compilers | davisking/dlib | 3a096469efdf30d2d691d3ff1051d8bf46166913 | 2016-07-28T23:09:07Z |
mmm a / src / cpp / common / channel_arguments . cc <nl> ppp b / src / cpp / common / channel_arguments . cc <nl> void ChannelArguments : : SetSocketMutator ( grpc_socket_mutator * mutator ) { <nl> for ( auto it = args_ . begin ( ) ; it ! = args_ . end ( ) ; + + it ) { <nl> if ( it - > type = = mutator_arg . type & & <nl> grpc : : string ( it - > key ) = = grpc : : string ( mutator_arg . key ) ) { <nl> + GPR_ASSERT ( ! replaced ) ; <nl> it - > value . pointer . vtable - > destroy ( & exec_ctx , it - > value . pointer . p ) ; <nl> it - > value . pointer = mutator_arg . value . pointer ; <nl> + replaced = true ; <nl> } <nl> } <nl> grpc_exec_ctx_finish ( & exec_ctx ) ; <nl> void ChannelArguments : : SetPointerWithVtable ( <nl> arg . type = GRPC_ARG_POINTER ; <nl> strings_ . push_back ( key ) ; <nl> arg . key = const_cast < char * > ( strings_ . back ( ) . c_str ( ) ) ; <nl> - arg . value . pointer . p = value ; <nl> + arg . value . pointer . p = vtable - > copy ( value ) ; <nl> arg . value . pointer . vtable = vtable ; <nl> args_ . push_back ( arg ) ; <nl> } <nl> mmm a / test / cpp / common / channel_arguments_test . cc <nl> ppp b / test / cpp / common / channel_arguments_test . cc <nl> TEST_F ( ChannelArgumentsTest , SetSocketMutator ) { <nl> EXPECT_TRUE ( HasArg ( arg1 ) ) ; <nl> / / arg0 is replaced by arg1 <nl> EXPECT_FALSE ( HasArg ( arg0 ) ) ; <nl> - <nl> - / / arg0 is destroyed by grpc_socket_mutator_to_arg ( mutator1 ) <nl> - { <nl> - grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT ; <nl> - arg1 . value . pointer . vtable - > destroy ( & exec_ctx , arg1 . value . pointer . p ) ; <nl> - grpc_exec_ctx_finish ( & exec_ctx ) ; <nl> - } <nl> } <nl> <nl> TEST_F ( ChannelArgumentsTest , SetUserAgentPrefix ) { <nl> | Copy value at SetPointerWithVtable | grpc/grpc | 4564b8cde72f74b88ec2ddf4943768e809dff94b | 2017-03-14T18:40:56Z |
mmm a / src / csharp / Grpc . HealthCheck . Tests / HealthServiceImplTest . cs <nl> ppp b / src / csharp / Grpc . HealthCheck . Tests / HealthServiceImplTest . cs <nl> public async Task Watch ( ) <nl> impl . ClearStatus ( " " ) ; <nl> Assert . AreEqual ( HealthCheckResponse . Types . ServingStatus . ServiceUnknown , ( await nextWriteTask ) . Status ) ; <nl> <nl> + Assert . IsFalse ( callTask . IsCompleted ) ; <nl> cts . Cancel ( ) ; <nl> await callTask ; <nl> } <nl> mmm a / src / csharp / Grpc . HealthCheck . Tests / NUnitMain . cs <nl> ppp b / src / csharp / Grpc . HealthCheck . Tests / NUnitMain . cs <nl> public class NUnitMain <nl> public static int Main ( string [ ] args ) <nl> { <nl> / / Make logger immune to NUnit capturing stdout and stderr to workaround https : / / github . com / nunit / nunit / issues / 1406 . <nl> - / / GrpcEnvironment . SetLogger ( new ConsoleLogger ( ) ) ; <nl> + GrpcEnvironment . SetLogger ( new ConsoleLogger ( ) ) ; <nl> return new AutoRun ( typeof ( NUnitMain ) . GetTypeInfo ( ) . Assembly ) . Execute ( args ) ; <nl> } <nl> } <nl> mmm a / src / csharp / Grpc . HealthCheck . Tests / TestResponseStreamWriter . cs <nl> ppp b / src / csharp / Grpc . HealthCheck . Tests / TestResponseStreamWriter . cs <nl> <nl> - # region Copyright notice and license <nl> + # region Copyright notice and license <nl> / / Copyright 2015 gRPC authors . <nl> / / <nl> / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> <nl> <nl> namespace Grpc . HealthCheck . Tests <nl> { <nl> - private class TestResponseStreamWriter : IServerStreamWriter < HealthCheckResponse > <nl> + internal class TestResponseStreamWriter : IServerStreamWriter < HealthCheckResponse > <nl> { <nl> private TaskCompletionSource < HealthCheckResponse > _tcs ; <nl> <nl> | Clean up | grpc/grpc | 48ba78a7de0495adfb28386540ff53d328364b64 | 2019-11-13T01:39:41Z |
mmm a / lib / IRGen / LoadableByAddress . cpp <nl> ppp b / lib / IRGen / LoadableByAddress . cpp <nl> static SILType getNewSILType ( GenericEnvironment * GenericEnv , <nl> nonOptionalType = optType ; <nl> } <nl> if ( nonOptionalType . getAs < TupleType > ( ) ) { <nl> - return getNewTupleType ( GenericEnv , Mod , nonOptionalType , storageType ) ; <nl> + SILType newSILType = <nl> + getNewTupleType ( GenericEnv , Mod , nonOptionalType , storageType ) ; <nl> + return isLargeLoadableType ( GenericEnv , newSILType , Mod ) <nl> + ? newSILType . getAddressType ( ) <nl> + : newSILType ; <nl> } <nl> SILType newSILType = getNewOptionalFunctionType ( GenericEnv , storageType , Mod ) ; <nl> if ( newSILType ! = storageType ) { <nl> | LoadableByAddress : Fix commit 0ca90b8 - add tuple check that went missing when committing the code | apple/swift | 82fdc3afbe6bec1cbbed97b21386423d853642bf | 2018-02-19T21:17:53Z |
mmm a / Tools / samples . json <nl> ppp b / Tools / samples . json <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / wiki / Evaluate - a - model - in - an - Azure - WebApi " , <nl> " description " : " Host an already trained CNTK model on Azure . " , <nl> " language " : [ ] , <nl> - " type " : [ " Tutorial " ] <nl> + " type " : [ " Tutorial " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / wiki / CNTK - Eval - Examples " , <nl> " description " : " Evaluation or inference of an already trained CNTK model in C + + / C # . " , <nl> " language " : [ " C # " ] , <nl> - " type " : [ " Example " ] <nl> + " type " : [ " Example " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Image / TransferLearning " , <nl> " description " : " Transfer Learning : adapt a pretrained model to a new classification task . " , <nl> " language " : [ " Python " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / blob / master / Tutorials / CNTK_301_Image_Recognition_with_Deep_Transfer_Learning . ipynb " , <nl> " description " : " Recognize flowers and animals in natural scene images using deep transfer learning with pre - trained ResNet data . " , <nl> " language " : [ " Python " ] , <nl> - " type " : [ " Tutorial " , " Recipe " ] <nl> + " type " : [ " Tutorial " , " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Image / GettingStarted # 07_deconvolution " , <nl> " description " : " A simple image auto encoder using deconvolution and unpooling . " , <nl> " language " : [ " BrainScript , Python " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Image / FeatureExtraction " , <nl> " description " : " Evaluate and write out different layers of a trained model using Python . " , <nl> " language " : [ " Python " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Video / GettingStarted " , <nl> " description " : " Train a Basic 3 - D convolutional neural network for video action recognition on the UCF11 dataset . " , <nl> " language " : [ " Python " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Image / Classification / AlexNet " , <nl> " description " : " CNN based network by Alex Krizhevsky . This was the winning model of the ILSVRC2012 classification task . " , <nl> " language " : [ " Python " , " BrainScript " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Image / Classification / ConvNet # cntk - examples - imageclassificationconvnet " , <nl> " description " : " A popular convolutional neural network for image - related tasks . " , <nl> " language " : [ " Python " , " BrainScript " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / wiki / Object - Detection - using - Fast - R - CNN " , <nl> " description " : " Train object detection from images by adapting pre - trained classification models on arbitrarily sized regions of interest using ROI pooling . " , <nl> " language " : [ " Python " , " BrainScript " ] , <nl> - " type " : [ " Tutorial " , " Recipe " ] <nl> + " type " : [ " Tutorial " , " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Image / Classification / GoogLeNet / BN - Inception # cntk - examples - imageclassificationgooglenetbn - inception " , <nl> " description " : " GoogLeNet ( BN - Inception ) network for image classification . " , <nl> " language " : [ " Python " , " BrainScript " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Image / Classification / GoogLeNet / InceptionV3 # cntk - examples - imageclassificationgooglenetinceptionv3 " , <nl> " description " : " GoogLeNet ( Inception V3 ) network for image classification . " , <nl> " language " : [ " BrainScript " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / blob / master / Tutorials / CNTK_103B_MNIST_FeedForwardNetwork . ipynb " , <nl> " description " : " Recognize hand written digits ( OCR ) with MNIST data . " , <nl> " language " : [ " Python " ] , <nl> - " type " : [ " Tutorial " , " Recipe " ] <nl> + " type " : [ " Tutorial " , " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / blob / master / Tutorials / CNTK_105_Basic_Autoencoder_for_Dimensionality_Reduction . ipynb " , <nl> " description " : " Compress ( using autoencoder ) hand written digits from MNIST data with no human input ( unsupervised learning ) . " , <nl> " language " : [ " Python " ] , <nl> - " type " : [ " Tutorial " , " Recipe " ] <nl> + " type " : [ " Tutorial " , " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / blob / master / Tutorials / CNTK_201B_CIFAR - 10_ImageHandsOn . ipynb " , <nl> " description " : " Hands - on lab that shows how to implement an image recognition task using convolutional neural networks . " , <nl> " language " : [ " Python " ] , <nl> - " type " : [ " Tutorial " , " Recipe " ] <nl> + " type " : [ " Tutorial " , " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / blob / master / Tutorials / CNTK_205_Artistic_Style_Transfer . ipynb " , <nl> " description " : " This tutorial shows how to transfer the style of one image to another . This allows us to take our ordinary photos and render them in the style of famous images or paintings . " , <nl> " language " : [ " Python " ] , <nl> - " type " : [ " Tutorial " , " Recipe " ] <nl> + " type " : [ " Tutorial " , " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / blob / master / Tutorials / CNTK_206A_Basic_GAN . ipynb " , <nl> " description " : " This tutorial is a basic implementation of GAN networks . This allows us generate realistic looking MNIST images with no human input ( unsupervised learning ) . " , <nl> " language " : [ " Python " ] , <nl> - " type " : [ " Tutorial " , " Recipe " ] <nl> + " type " : [ " Tutorial " , " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / blob / master / Tutorials / CNTK_206B_DCGAN . ipynb " , <nl> " description " : " This tutorial is an implementation of deep convolutional GAN ( DCGAN ) networks . This allows us generate realistic looking MNIST images with no human input ( unsupervised learning ) . " , <nl> " language " : [ " Python " ] , <nl> - " type " : [ " Tutorial " , " Recipe " ] <nl> + " type " : [ " Tutorial " , " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Image / GettingStarted # 02_oneconvcntk " , <nl> " description " : " Simple network with one convolutional layer . " , <nl> " language " : [ " BrainScript " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Image / GettingStarted # 04_oneconvbncntk " , <nl> " description " : " Simple network showing how to add batch normalization to a CNN . " , <nl> " language " : [ " BrainScript " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Image / GettingStarted # 03_oneconvdropoutcntk " , <nl> " description " : " Simple network showing how to add dropout to a CNN . " , <nl> " language " : [ " BrainScript " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Image / GettingStarted # 01_onehiddencntk " , <nl> " description " : " Simple network with one hidden layer . " , <nl> " language " : [ " BrainScript " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Image / GettingStarted # 05_oneconvregrcntk " , <nl> " description " : " Simple network showing how to treat MNIST as a regression problem using Root Mean Square Error . " , <nl> " language " : [ " BrainScript " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Image / Regression # cntk - examples - imageregression " , <nl> " description " : " A simple neural network to predict the average RGB values of normalized images . " , <nl> " language " : [ " BrainScript " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Image / Classification / ResNet # cntk - examples - imageclassificationresnet " , <nl> " description " : " Deep residual learning invented by Microsoft Research . This was the winning model of the ILSVRC and MS - COCO challenges in 2015 . " , <nl> " language " : [ " Python " , " BrainScript " ] , <nl> - " type " : [ " Tutorial " , " Recipe " ] <nl> + " type " : [ " Tutorial " , " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Image " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Image / Classification / VGG " , <nl> " description " : " Deep CNN from University of Oxford . This was the winning model for the ILSVRC2014 localization task . " , <nl> " language " : [ " Python " , " BrainScript " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Numeric " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / blob / master / Tutorials / CNTK_102_FeedForward . ipynb " , <nl> " description " : " Classify cancer using simulated data ( Feed Forward ) with Numpy " , <nl> " language " : [ " Python " ] , <nl> - " type " : [ " Tutorial " ] <nl> + " type " : [ " Tutorial " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Numeric " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / blob / master / Tutorials / CNTK_104_Finance_Timeseries_Basic_with_Pandas_Numpy . ipynb " , <nl> " description " : " : Looking at the predictive potential on classification of an Exchange - traded Funds ( ETF ) , and in this simplified setting how one could trade it . " , <nl> " language " : [ " Python " ] , <nl> - " type " : [ " Tutorial " , " Recipe " ] <nl> + " type " : [ " Tutorial " , " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Numeric " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / blob / master / Tutorials / CNTK_101_LogisticRegression . ipynb " , <nl> " description " : " Classify cancer using simulated data ( Logistic Regression ) . " , <nl> " language " : [ " Python " , " BrainScript " ] , <nl> - " type " : [ " Tutorial " , " Recipe " ] <nl> + " type " : [ " Tutorial " , " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Numeric " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / blob / master / Tutorials / CNTK_106A_LSTM_Timeseries_with_Simulated_Data . ipynb " , <nl> " description " : " Timeseries modeling with LSTMs using simulated data . " , <nl> " language " : [ " Python " ] , <nl> - " type " : [ " Tutorial " , " Recipe " ] <nl> + " type " : [ " Tutorial " , " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Numeric " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / blob / master / Tutorials / CNTK_106B_LSTM_Timeseries_with_IOT_Data . ipynb " , <nl> " description " : " Forecasting using data from an IOT device . " , <nl> " language " : [ " Python " ] , <nl> - " type " : [ " Tutorial " , " Recipe " ] <nl> + " type " : [ " Tutorial " , " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Numeric " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / blob / master / Tutorials / CNTK_203_Reinforcement_Learning_Basics . ipynb " , <nl> " description " : " Example how software agents could take actions in an environment so as to maximize some notion of cumulative reward . " , <nl> " language " : [ " Python " ] , <nl> - " type " : [ " Tutorial " , " Recipe " ] <nl> + " type " : [ " Tutorial " , " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Numeric " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / blob / master / Tutorials / CNTK_207_Training_with_Sampled_Softmax . ipynb " , <nl> " description " : " Training with Sampled Softmax " , <nl> " language " : [ " Python " ] , <nl> - " type " : [ " Tutorial " , " Recipe " ] <nl> + " type " : [ " Tutorial " , " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Speech " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Speech / AN4 " , <nl> " description " : " Train a speech recognition DNN acoustic model on the CMU AN4 dataset . " , <nl> " language " : [ " BrainScript " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Speech " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Speech / AN4 " , <nl> " description " : " Train a speech recognition LSTM acoustic model on the CMU AN4 dataset . " , <nl> " language " : [ " BrainScript " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Speech " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Speech / Miscellaneous / AMI " , <nl> " description " : " Train a speech recognition DNN acoustic model on top of fMLLR features generated with the Kaldi toolchain . " , <nl> " language " : [ " BrainScript " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Speech " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Speech / Miscellaneous / TIMIT / config " , <nl> " description " : " Train a speech recognition model with learning rate adapted based on dev set on the TIMIT dataset . " , <nl> " language " : [ " BrainScript " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Speech " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Speech / Miscellaneous / TIMIT / config " , <nl> " description " : " Train autoencoder with bottleneck layer on the TIMIT dataset . " , <nl> " language " : [ " BrainScript " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Speech " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Speech / Miscellaneous / TIMIT / config " , <nl> " description " : " Train with two different inputs , fbank and mfcc , on the TIMIT dataset . " , <nl> " language " : [ " BrainScript " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Speech " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Speech / Miscellaneous / TIMIT / config " , <nl> " description " : " Train with multi - task learning and joint prediction of senone labels and dialect region on the TIMIT dataset . " , <nl> " language " : [ " BrainScript " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Speech " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Speech / Miscellaneous / TIMIT / config " , <nl> " description " : " Pre - train using layerwise discriminative pre - training , then full network training on the TIMIT dataset . " , <nl> " language " : [ " BrainScript " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Speech " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Speech / Miscellaneous / TIMIT / config " , <nl> " description " : " Train a speech recognition DNN acoustic model on the TIMIT dataset ( TrainSimpleNetwork ) . " , <nl> " language " : [ " BrainScript " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Speech " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Speech / Miscellaneous / TIMIT / config " , <nl> " description " : " Train a speech recognition LSTM acoustic model on the TIMIT dataset ( TrainNDLNetwork ) . " , <nl> " language " : [ " BrainScript " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Speech " , " Text " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / SequenceToSequence / CMUDict " , <nl> " description " : " Sequence - to - sequence model with attention mechanism for a grapheme to phoneme translation task on the CMUDict dataset . " , <nl> " language " : [ " Python " , " BrainScript " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Speech " , " Text " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / blob / master / Tutorials / CNTK_204_Sequence_To_Sequence . ipynb " , <nl> " description " : " Translate text from one domain ( grapheme ) to other ( phoneme ) . The input is a sequence with a dynamic length , and the output is also a sequence with some dynamic length . This is a natural fit for machine translation , automatic text summarization , word to pronunciation models and even parse tree generation . " , <nl> " language " : [ " Python " ] , <nl> - " type " : [ " Tutorial " ] <nl> + " type " : [ " Tutorial " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Text " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / LanguageUnderstanding / ATIS " , <nl> " description " : " LSTM based model for language understanding on the ATIS dataset . " , <nl> " language " : [ " Python " , " BrainScript " ] , <nl> - " type " : [ " Tutorial " , " Recipe " ] <nl> + " type " : [ " Tutorial " , " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Text " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / blob / master / Tutorials / CNTK_202_Language_Understanding . ipynb " , <nl> " description " : " Implement a recurrent network for language understanding of the ATIS dataset . " , <nl> " language " : [ " Python " ] , <nl> - " type " : [ " Tutorial " , " Recipe " ] <nl> + " type " : [ " Tutorial " , " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Text " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Text / CharacterLM " , <nl> " description " : " A neural language model uses a recurrent neural network to predict words ( or characters ) with a richer context than traditional n - gram models allow . " , <nl> " language " : [ " Python " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Text " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / Text / WordLMWithSampledSoftmax " , <nl> " description " : " An example on how to use sampled softmax to train a neural language model . " , <nl> " language " : [ " Python " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Text " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / SequenceToSequence / PennTreebank " , <nl> " description " : " Recurrent neural network for language modeling on the PennTreebank dataset . " , <nl> " language " : [ " BrainScript " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Text " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / tree / master / Examples / SequenceClassification / SimpleExample / Python " , <nl> " description " : " Create and train an LSTM sequence classification model . " , <nl> " language " : [ " Python " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } , <nl> { <nl> " category " : [ " Text " ] , <nl> <nl> " url " : " https : / / github . com / Microsoft / CNTK / blob / master / Tutorials / CNTK_207_Training_with_Sampled_Softmax . ipynb " , <nl> " description " : " Improve training speed for models with large vocabularies . " , <nl> " language " : [ " Python " ] , <nl> - " type " : [ " Recipe " ] <nl> + " type " : [ " Recipe " ] , <nl> + " dateadded " : " 4 / 14 / 2017 " <nl> } <nl> ] <nl> | Add date to samples . json | microsoft/CNTK | 8e200ae8578a34fb8cdb4b294fc8f9d809a7ac59 | 2017-04-17T18:47:34Z |
mmm a / addons / resource . language . en_gb / resources / strings . po <nl> ppp b / addons / resource . language . en_gb / resources / strings . po <nl> msgstr " " <nl> # . Button in Add - on Manager - > Available Updates for updating all add - ons when auto - updating is off . <nl> # : xbmc / filesystem / AddonDirectory . cpp <nl> msgctxt " # 24122 " <nl> - msgid " Update all " <nl> + msgid " Install all updates " <nl> msgstr " " <nl> <nl> # . Description of setting with label # 24105 " Pause when searching for subtitles " <nl> msgctxt " # 24136 " <nl> msgid " Would you like to enable this add - on ? " <nl> msgstr " " <nl> <nl> - # empty strings from id 24137 to 24138 <nl> + # . Button in Add - on Manager - > Available Updates for updating all possible add - ons when auto - updating is off . <nl> + # : xbmc / filesystem / AddonDirectory . cpp <nl> + msgctxt " # 24137 " <nl> + msgid " Install auto updates only " <nl> + msgstr " " <nl> + <nl> + # empty strings from id 24138 to 24138 <nl> <nl> # . Label for the action provided by addon management events to jump to a specific Add - on <nl> # : xbmc / events / AddonManagementEvent . cpp <nl> mmm a / xbmc / addons / AddonDatabase . cpp <nl> ppp b / xbmc / addons / AddonDatabase . cpp <nl> int CAddonDatabase : : GetMinSchemaVersion ( ) const <nl> <nl> int CAddonDatabase : : GetSchemaVersion ( ) const <nl> { <nl> - return 31 ; <nl> + return 32 ; <nl> } <nl> <nl> void CAddonDatabase : : CreateTables ( ) <nl> void CAddonDatabase : : CreateTables ( ) <nl> CLog : : Log ( LOGINFO , " create addonlinkrepo table " ) ; <nl> m_pDS - > exec ( " CREATE TABLE addonlinkrepo ( idRepo integer , idAddon integer ) \ n " ) ; <nl> <nl> - CLog : : Log ( LOGINFO , " create blacklist table " ) ; <nl> - m_pDS - > exec ( " CREATE TABLE blacklist ( id integer primary key , addonID text ) \ n " ) ; <nl> + CLog : : Log ( LOGINFO , " create update_rules table " ) ; <nl> + m_pDS - > exec ( <nl> + " CREATE TABLE update_rules ( id integer primary key , addonID TEXT , updateRule INTEGER ) \ n " ) ; <nl> <nl> CLog : : Log ( LOGINFO , " create package table " ) ; <nl> m_pDS - > exec ( " CREATE TABLE package ( id integer primary key , addonID text , filename text , hash text ) \ n " ) ; <nl> void CAddonDatabase : : CreateAnalytics ( ) <nl> m_pDS - > exec ( " CREATE INDEX idxAddons ON addons ( addonID ) " ) ; <nl> m_pDS - > exec ( " CREATE UNIQUE INDEX ix_addonlinkrepo_1 ON addonlinkrepo ( idAddon , idRepo ) \ n " ) ; <nl> m_pDS - > exec ( " CREATE UNIQUE INDEX ix_addonlinkrepo_2 ON addonlinkrepo ( idRepo , idAddon ) \ n " ) ; <nl> - m_pDS - > exec ( " CREATE UNIQUE INDEX idxBlack ON blacklist ( addonID ) " ) ; <nl> + m_pDS - > exec ( " CREATE UNIQUE INDEX idxUpdate_rules ON update_rules ( addonID , updateRule ) " ) ; <nl> m_pDS - > exec ( " CREATE UNIQUE INDEX idxPackage ON package ( filename ) " ) ; <nl> } <nl> <nl> void CAddonDatabase : : UpdateTables ( int version ) <nl> m_pDS - > exec ( " UPDATE installed SET origin = addonID WHERE ( origin = ' ' ) AND " <nl> " EXISTS ( SELECT * FROM repo WHERE repo . addonID = installed . addonID ) " ) ; <nl> } <nl> + if ( version < 32 ) <nl> + { <nl> + m_pDS - > exec ( <nl> + " CREATE TABLE update_rules ( id integer primary key , addonID text , updateRule INTEGER ) " ) ; <nl> + m_pDS - > exec ( " INSERT INTO update_rules ( addonID , updateRule ) SELECT addonID , 1 updateRule FROM " <nl> + " blacklist " ) ; <nl> + m_pDS - > exec ( " DROP INDEX IF EXISTS idxBlack " ) ; <nl> + m_pDS - > exec ( " DROP TABLE blacklist " ) ; <nl> + } <nl> } <nl> <nl> void CAddonDatabase : : SyncInstalled ( const std : : set < std : : string > & ids , <nl> void CAddonDatabase : : SyncInstalled ( const std : : set < std : : string > & ids , <nl> for ( const auto & id : removed ) <nl> { <nl> m_pDS - > exec ( PrepareSQL ( " DELETE FROM installed WHERE addonID = ' % s ' " , id . c_str ( ) ) ) ; <nl> - RemoveAddonFromBlacklist ( id ) ; <nl> + RemoveAllUpdateRulesForAddon ( id ) ; <nl> DeleteRepository ( id ) ; <nl> } <nl> <nl> bool CAddonDatabase : : GetDisabled ( std : : map < std : : string , AddonDisabledReason > & add <nl> return false ; <nl> } <nl> <nl> - bool CAddonDatabase : : GetBlacklisted ( std : : set < std : : string > & addons ) <nl> + bool CAddonDatabase : : GetAddonUpdateRules ( <nl> + std : : map < std : : string , std : : vector < AddonUpdateRule > > & rulesMap ) const <nl> { <nl> try <nl> { <nl> bool CAddonDatabase : : GetBlacklisted ( std : : set < std : : string > & addons ) <nl> if ( ! m_pDS ) <nl> return false ; <nl> <nl> - std : : string sql = PrepareSQL ( " SELECT addonID FROM blacklist " ) ; <nl> + std : : string sql = PrepareSQL ( " SELECT * FROM update_rules " ) ; <nl> m_pDS - > query ( sql ) ; <nl> while ( ! m_pDS - > eof ( ) ) <nl> { <nl> - addons . insert ( m_pDS - > fv ( " addonID " ) . get_asString ( ) ) ; <nl> + rulesMap [ m_pDS - > fv ( " addonID " ) . get_asString ( ) ] . emplace_back ( <nl> + static_cast < AddonUpdateRule > ( m_pDS - > fv ( " updateRule " ) . get_asInt ( ) ) ) ; <nl> m_pDS - > next ( ) ; <nl> } <nl> m_pDS - > close ( ) ; <nl> bool CAddonDatabase : : GetBlacklisted ( std : : set < std : : string > & addons ) <nl> return false ; <nl> } <nl> <nl> - bool CAddonDatabase : : BlacklistAddon ( const std : : string & addonID ) <nl> + bool CAddonDatabase : : AddUpdateRuleForAddon ( const std : : string & addonID , AddonUpdateRule updateRule ) <nl> { <nl> try <nl> { <nl> bool CAddonDatabase : : BlacklistAddon ( const std : : string & addonID ) <nl> if ( ! m_pDS ) <nl> return false ; <nl> <nl> - std : : string sql = PrepareSQL ( " INSERT INTO blacklist ( id , addonID ) VALUES ( NULL , ' % s ' ) " , addonID . c_str ( ) ) ; <nl> + std : : string sql = <nl> + PrepareSQL ( " INSERT INTO update_rules ( id , addonID , updateRule ) VALUES ( NULL , ' % s ' , % d ) " , <nl> + addonID . c_str ( ) , static_cast < int > ( updateRule ) ) ; <nl> m_pDS - > exec ( sql ) ; <nl> return true ; <nl> } <nl> bool CAddonDatabase : : BlacklistAddon ( const std : : string & addonID ) <nl> return false ; <nl> } <nl> <nl> - bool CAddonDatabase : : RemoveAddonFromBlacklist ( const std : : string & addonID ) <nl> + bool CAddonDatabase : : RemoveAllUpdateRulesForAddon ( const std : : string & addonID ) <nl> + { <nl> + return RemoveUpdateRuleForAddon ( addonID , AddonUpdateRule : : ANY ) ; <nl> + } <nl> + <nl> + bool CAddonDatabase : : RemoveUpdateRuleForAddon ( const std : : string & addonID , <nl> + AddonUpdateRule updateRule ) <nl> { <nl> try <nl> { <nl> bool CAddonDatabase : : RemoveAddonFromBlacklist ( const std : : string & addonID ) <nl> if ( ! m_pDS ) <nl> return false ; <nl> <nl> - std : : string sql = PrepareSQL ( " DELETE FROM blacklist WHERE addonID = ' % s ' " , addonID . c_str ( ) ) ; <nl> + std : : string sql = PrepareSQL ( " DELETE FROM update_rules WHERE addonID = ' % s ' " , addonID . c_str ( ) ) ; <nl> + <nl> + if ( updateRule ! = AddonUpdateRule : : ANY ) <nl> + { <nl> + sql + = PrepareSQL ( " AND updateRule = % d " , static_cast < int > ( updateRule ) ) ; <nl> + } <nl> + <nl> m_pDS - > exec ( sql ) ; <nl> return true ; <nl> } <nl> bool CAddonDatabase : : RemovePackage ( const std : : string & packageFileName ) <nl> <nl> void CAddonDatabase : : OnPostUnInstall ( const std : : string & addonId ) <nl> { <nl> - RemoveAddonFromBlacklist ( addonId ) ; <nl> + RemoveAllUpdateRulesForAddon ( addonId ) ; <nl> DeleteRepository ( addonId ) ; <nl> <nl> / / ! @ todo should be done before uninstall to avoid any race conditions <nl> mmm a / xbmc / addons / AddonDatabase . h <nl> ppp b / xbmc / addons / AddonDatabase . h <nl> class CAddonDatabase : public CDatabase <nl> * / <nl> bool EnableAddon ( const std : : string & addonID ) ; <nl> <nl> - bool BlacklistAddon ( const std : : string & addonID ) ; <nl> - bool RemoveAddonFromBlacklist ( const std : : string & addonID ) ; <nl> - bool GetBlacklisted ( std : : set < std : : string > & addons ) ; <nl> + / * ! <nl> + * \ brief Write dataset with addon - id and rule to the db <nl> + * \ param addonID the addonID <nl> + * \ param updateRule the rule value to be written <nl> + * \ return true on success , false otherwise <nl> + * / <nl> + bool AddUpdateRuleForAddon ( const std : : string & addonID , ADDON : : AddonUpdateRule updateRule ) ; <nl> + <nl> + / * ! <nl> + * \ brief Remove all rule datasets for an addon - id from the db <nl> + * \ param addonID the addonID <nl> + * \ return true on success , false otherwise <nl> + * / <nl> + bool RemoveAllUpdateRulesForAddon ( const std : : string & addonID ) ; <nl> + <nl> + / * ! <nl> + * \ brief Remove a single rule dataset for an addon - id from the db <nl> + * \ note specifying AddonUpdateRule : : ANY will remove all rules . <nl> + * use @ ref RemoveAllUpdateRulesForAddon ( ) instead <nl> + * \ param addonID the addonID <nl> + * \ param updateRule the rule to remove <nl> + * \ return true on success , false otherwise <nl> + * / <nl> + bool RemoveUpdateRuleForAddon ( const std : : string & addonID , AddonUpdateRule updateRule ) ; <nl> + <nl> + / * ! <nl> + * \ brief Retrieve all rule datasets from db and store them into map <nl> + * \ param rulesMap target map <nl> + * \ return true on success , false otherwise <nl> + * / <nl> + bool GetAddonUpdateRules ( std : : map < std : : string , std : : vector < AddonUpdateRule > > & rulesMap ) const ; <nl> <nl> / * ! \ brief Store an addon ' s package filename and that file ' s hash for future verification <nl> \ param addonID id of the addon we ' re adding a package for <nl> mmm a / xbmc / addons / AddonManager . cpp <nl> ppp b / xbmc / addons / AddonManager . cpp <nl> bool CAddonMgr : : GetAddonUpdateCandidates ( VECADDONS & updates ) const <nl> updates = GetAvailableUpdates ( ) ; <nl> updates . erase ( <nl> std : : remove_if ( updates . begin ( ) , updates . end ( ) , <nl> - [ this ] ( const AddonPtr & addon ) { return IsBlacklisted ( addon - > ID ( ) ) ; } ) , <nl> + [ this ] ( const AddonPtr & addon ) { return ! IsAutoUpdateable ( addon - > ID ( ) ) ; } ) , <nl> updates . end ( ) ) ; <nl> return updates . empty ( ) ; <nl> } <nl> bool CAddonMgr : : FindAddons ( ) <nl> m_database . GetDisabled ( tmpDisabled ) ; <nl> m_disabled = std : : move ( tmpDisabled ) ; <nl> <nl> - std : : set < std : : string > tmpBlacklist ; <nl> - m_database . GetBlacklisted ( tmpBlacklist ) ; <nl> - m_updateBlacklist = std : : move ( tmpBlacklist ) ; <nl> + m_updateRules . RefreshRulesMap ( m_database ) ; <nl> <nl> return true ; <nl> } <nl> void CAddonMgr : : OnPostUnInstall ( const std : : string & id ) <nl> { <nl> CSingleLock lock ( m_critSection ) ; <nl> m_disabled . erase ( id ) ; <nl> - m_updateBlacklist . erase ( id ) ; <nl> + RemoveAllUpdateRulesFromList ( id ) ; <nl> m_events . Publish ( AddonEvents : : UnInstalled ( id ) ) ; <nl> } <nl> <nl> - bool CAddonMgr : : RemoveFromUpdateBlacklist ( const std : : string & id ) <nl> - { <nl> - CSingleLock lock ( m_critSection ) ; <nl> - if ( ! IsBlacklisted ( id ) ) <nl> - return true ; <nl> - return m_database . RemoveAddonFromBlacklist ( id ) & & m_updateBlacklist . erase ( id ) > 0 ; <nl> - } <nl> - <nl> - bool CAddonMgr : : AddToUpdateBlacklist ( const std : : string & id ) <nl> - { <nl> - CSingleLock lock ( m_critSection ) ; <nl> - if ( IsBlacklisted ( id ) ) <nl> - return true ; <nl> - return m_database . BlacklistAddon ( id ) & & m_updateBlacklist . insert ( id ) . second ; <nl> - } <nl> - <nl> - bool CAddonMgr : : IsBlacklisted ( const std : : string & id ) const <nl> - { <nl> - CSingleLock lock ( m_critSection ) ; <nl> - return m_updateBlacklist . find ( id ) ! = m_updateBlacklist . end ( ) ; <nl> - } <nl> - <nl> void CAddonMgr : : UpdateLastUsed ( const std : : string & id ) <nl> { <nl> auto time = CDateTime : : GetCurrentDateTime ( ) ; <nl> bool CAddonMgr : : LoadAddonDescription ( const std : : string & directory , AddonPtr & add <nl> return addon ! = nullptr ; <nl> } <nl> <nl> + bool CAddonMgr : : AddUpdateRuleToList ( const std : : string & id , AddonUpdateRule updateRule ) <nl> + { <nl> + return m_updateRules . AddUpdateRuleToList ( m_database , id , updateRule ) ; <nl> + } <nl> + <nl> + bool CAddonMgr : : RemoveAllUpdateRulesFromList ( const std : : string & id ) <nl> + { <nl> + return m_updateRules . RemoveAllUpdateRulesFromList ( m_database , id ) ; <nl> + } <nl> + <nl> + bool CAddonMgr : : RemoveUpdateRuleFromList ( const std : : string & id , AddonUpdateRule updateRule ) <nl> + { <nl> + return m_updateRules . RemoveUpdateRuleFromList ( m_database , id , updateRule ) ; <nl> + } <nl> + <nl> + bool CAddonMgr : : IsAutoUpdateable ( const std : : string & id ) const <nl> + { <nl> + return m_updateRules . IsAutoUpdateable ( id ) ; <nl> + } <nl> + <nl> bool CAddonMgr : : AddonsFromRepoXML ( const CRepository : : DirInfo & repo , const std : : string & xml , VECADDONS & addons ) <nl> { <nl> CXBMCTinyXML doc ; <nl> mmm a / xbmc / addons / AddonManager . h <nl> ppp b / xbmc / addons / AddonManager . h <nl> <nl> <nl> # include " Addon . h " <nl> # include " AddonDatabase . h " <nl> + # include " AddonUpdateRules . h " <nl> # include " Repository . h " <nl> # include " threads / CriticalSection . h " <nl> # include " utils / EventStream . h " <nl> namespace ADDON <nl> <nl> bool IsSystemAddon ( const std : : string & id ) ; <nl> <nl> - bool AddToUpdateBlacklist ( const std : : string & id ) ; <nl> - bool RemoveFromUpdateBlacklist ( const std : : string & id ) ; <nl> - bool IsBlacklisted ( const std : : string & id ) const ; <nl> + / * ! <nl> + * @ brief Addon update rules . <nl> + * <nl> + * member functions for handling and querying add - on update rules <nl> + * <nl> + * @ warning This should be never used from other places outside of addon <nl> + * system directory . <nl> + * <nl> + * / <nl> + / * @ { { { * / <nl> + <nl> + / * \ brief Add a single update rule to the list for an addon <nl> + * \ sa CAddonUpdateRules : : AddUpdateRuleToList ( ) <nl> + * / <nl> + bool AddUpdateRuleToList ( const std : : string & id , AddonUpdateRule updateRule ) ; <nl> + <nl> + / * \ brief Remove all rules from update rules list for an addon <nl> + * \ sa CAddonUpdateRules : : RemoveAllUpdateRulesFromList ( ) <nl> + * / <nl> + bool RemoveAllUpdateRulesFromList ( const std : : string & id ) ; <nl> + <nl> + / * \ brief Remove a specific rule from update rules list for an addon <nl> + * \ sa CAddonUpdateRules : : RemoveUpdateRuleFromList ( ) <nl> + * / <nl> + bool RemoveUpdateRuleFromList ( const std : : string & id , AddonUpdateRule updateRule ) ; <nl> + <nl> + / * \ brief Check if an addon version is auto - updateable <nl> + * \ param id addon id to be checked <nl> + * \ return true is addon is auto - updateable , false otherwise <nl> + * \ sa CAddonUpdateRules : : IsAutoUpdateable ( ) <nl> + * / <nl> + bool IsAutoUpdateable ( const std : : string & id ) const ; <nl> + <nl> + / * @ } } } * / <nl> <nl> void UpdateLastUsed ( const std : : string & id ) ; <nl> <nl> namespace ADDON <nl> mutable std : : mutex m_installAddonsMutex ; <nl> <nl> std : : map < std : : string , AddonDisabledReason > m_disabled ; <nl> - std : : set < std : : string > m_updateBlacklist ; <nl> static std : : map < TYPE , IAddonMgrCallback * > m_managers ; <nl> mutable CCriticalSection m_critSection ; <nl> CAddonDatabase m_database ; <nl> + CAddonUpdateRules m_updateRules ; <nl> CEventSource < AddonEvent > m_events ; <nl> CBlockingEventSource < AddonEvent > m_unloadEvents ; <nl> std : : set < std : : string > m_systemAddons ; <nl> new file mode 100644 <nl> index 000000000000 . . 3cabc9b7d92f <nl> mmm / dev / null <nl> ppp b / xbmc / addons / AddonUpdateRules . cpp <nl> <nl> + / * <nl> + * Copyright ( C ) 2005 - 2020 Team Kodi <nl> + * This file is part of Kodi - https : / / kodi . tv <nl> + * <nl> + * SPDX - License - Identifier : GPL - 2 . 0 - or - later <nl> + * See LICENSES / README . md for more information . <nl> + * / <nl> + <nl> + # include " AddonUpdateRules . h " <nl> + <nl> + # include " AddonDatabase . h " <nl> + # include " threads / SingleLock . h " <nl> + # include " utils / log . h " <nl> + <nl> + using namespace ADDON ; <nl> + <nl> + bool CAddonUpdateRules : : RefreshRulesMap ( const CAddonDatabase & db ) <nl> + { <nl> + m_updateRules . clear ( ) ; <nl> + db . GetAddonUpdateRules ( m_updateRules ) ; <nl> + return true ; <nl> + } <nl> + <nl> + bool CAddonUpdateRules : : IsAutoUpdateable ( const std : : string & id ) const <nl> + { <nl> + CSingleLock lock ( m_critSection ) ; <nl> + return m_updateRules . find ( id ) = = m_updateRules . end ( ) ; <nl> + } <nl> + <nl> + bool CAddonUpdateRules : : IsUpdateableByRule ( const std : : string & id , AddonUpdateRule updateRule ) const <nl> + { <nl> + CSingleLock lock ( m_critSection ) ; <nl> + const auto & updateRulesEntry = m_updateRules . find ( id ) ; <nl> + return ( updateRulesEntry = = m_updateRules . end ( ) | | <nl> + std : : none_of ( updateRulesEntry - > second . begin ( ) , updateRulesEntry - > second . end ( ) , <nl> + [ updateRule ] ( AddonUpdateRule rule ) { return rule = = updateRule ; } ) ) ; <nl> + } <nl> + <nl> + bool CAddonUpdateRules : : AddUpdateRuleToList ( CAddonDatabase & db , <nl> + const std : : string & id , <nl> + AddonUpdateRule updateRule ) <nl> + { <nl> + CSingleLock lock ( m_critSection ) ; <nl> + <nl> + if ( ! IsUpdateableByRule ( id , updateRule ) ) <nl> + { <nl> + return true ; <nl> + } <nl> + <nl> + m_updateRules [ id ] . emplace_back ( updateRule ) ; <nl> + return db . AddUpdateRuleForAddon ( id , updateRule ) ; <nl> + } <nl> + <nl> + bool CAddonUpdateRules : : RemoveUpdateRuleFromList ( CAddonDatabase & db , <nl> + const std : : string & id , <nl> + AddonUpdateRule updateRule ) <nl> + { <nl> + return ( updateRule ! = AddonUpdateRule : : ANY & & RemoveFromUpdateRuleslist ( db , id , updateRule ) ) ; <nl> + } <nl> + <nl> + bool CAddonUpdateRules : : RemoveAllUpdateRulesFromList ( CAddonDatabase & db , const std : : string & id ) <nl> + { <nl> + return RemoveFromUpdateRuleslist ( db , id , AddonUpdateRule : : ANY ) ; <nl> + } <nl> + <nl> + bool CAddonUpdateRules : : RemoveFromUpdateRuleslist ( CAddonDatabase & db , <nl> + const std : : string & id , <nl> + AddonUpdateRule updateRule ) <nl> + { <nl> + CSingleLock lock ( m_critSection ) ; <nl> + <nl> + const auto & updateRulesEntry = m_updateRules . find ( id ) ; <nl> + if ( updateRulesEntry ! = m_updateRules . end ( ) ) <nl> + { <nl> + bool onlySingleRule = ( updateRulesEntry - > second . size ( ) = = 1 ) ; <nl> + <nl> + if ( updateRule = = AddonUpdateRule : : ANY | | <nl> + ( onlySingleRule & & updateRulesEntry - > second . front ( ) = = updateRule ) ) <nl> + { <nl> + m_updateRules . erase ( id ) ; <nl> + db . RemoveAllUpdateRulesForAddon ( id ) ; <nl> + return true ; <nl> + } <nl> + else if ( ! onlySingleRule ) <nl> + { <nl> + const auto & position = <nl> + std : : find ( updateRulesEntry - > second . begin ( ) , updateRulesEntry - > second . end ( ) , updateRule ) ; <nl> + if ( position ! = updateRulesEntry - > second . end ( ) ) <nl> + { <nl> + updateRulesEntry - > second . erase ( position ) ; <nl> + db . RemoveUpdateRuleForAddon ( id , updateRule ) ; <nl> + } <nl> + return true ; <nl> + } <nl> + } <nl> + return false ; <nl> + } <nl> new file mode 100644 <nl> index 000000000000 . . 08af4ca5925e <nl> mmm / dev / null <nl> ppp b / xbmc / addons / AddonUpdateRules . h <nl> <nl> + / * <nl> + * Copyright ( C ) 2005 - 2020 Team Kodi <nl> + * This file is part of Kodi - https : / / kodi . tv <nl> + * <nl> + * SPDX - License - Identifier : GPL - 2 . 0 - or - later <nl> + * See LICENSES / README . md for more information . <nl> + * / <nl> + <nl> + # pragma once <nl> + <nl> + # include " addoninfo / AddonInfo . h " <nl> + # include " threads / CriticalSection . h " <nl> + <nl> + # include < map > <nl> + # include < string > <nl> + # include < vector > <nl> + <nl> + namespace ADDON <nl> + { <nl> + <nl> + class CAddonDatabase ; <nl> + <nl> + / * * <nl> + * Class - CAddonUpdateRules <nl> + * Manages information about the updateability of addons by defining <nl> + * and handling certain rules . <nl> + * / <nl> + class CAddonUpdateRules <nl> + { <nl> + public : <nl> + / * \ brief Refresh addon update rules map from the database <nl> + * \ param db database connection <nl> + * \ return true on success , false otherwise <nl> + * / <nl> + bool RefreshRulesMap ( const CAddonDatabase & db ) ; <nl> + <nl> + / * \ brief Check if an addon version is auto updateable <nl> + * \ param id addon id to be checked <nl> + * \ return true is addon is auto updateable , false otherwise <nl> + * / <nl> + bool IsAutoUpdateable ( const std : : string & id ) const ; <nl> + <nl> + / * \ brief Add a single rule to the update rules list for an addon <nl> + * \ param db database connection <nl> + * \ param id addon - id to set rule for <nl> + * \ param the rule to set <nl> + * \ return true on success , false otherwise <nl> + * / <nl> + bool AddUpdateRuleToList ( CAddonDatabase & db , const std : : string & id , AddonUpdateRule updateRule ) ; <nl> + <nl> + / * \ brief Remove a single rule from the update rules list for an addon <nl> + * \ param db database connection <nl> + * \ param id addon - id to remove rule for <nl> + * \ param the rule to remove <nl> + * \ return true on success , false otherwise <nl> + * / <nl> + bool RemoveUpdateRuleFromList ( CAddonDatabase & db , <nl> + const std : : string & id , <nl> + AddonUpdateRule updateRule ) ; <nl> + <nl> + / * \ brief Remove all rules from the update rules list for an addon <nl> + * \ param db database connection <nl> + * \ param id addon - id to remove rules for <nl> + * \ return true on success , false otherwise <nl> + * / <nl> + bool RemoveAllUpdateRulesFromList ( CAddonDatabase & db , const std : : string & id ) ; <nl> + <nl> + private : <nl> + / * \ brief Checks if an addon version is updateable with a specific rule <nl> + * \ param id addon id to be checked <nl> + * \ param updateRule the rule to check for <nl> + * \ return true is addon is updateable by that updateRule , false otherwise <nl> + * \ sa CAddonUpdateRules : : IsAutoUpdateable ( ) <nl> + * / <nl> + bool IsUpdateableByRule ( const std : : string & id , AddonUpdateRule updateRule ) const ; <nl> + <nl> + / * \ brief Executor for @ ref RemoveUpdateRuleFromList ( ) and @ ref RemoveAllUpdateRulesFromList ( ) <nl> + * / <nl> + bool RemoveFromUpdateRuleslist ( CAddonDatabase & db , <nl> + const std : : string & id , <nl> + AddonUpdateRule updateRule ) ; <nl> + <nl> + mutable CCriticalSection m_critSection ; <nl> + std : : map < std : : string , std : : vector < AddonUpdateRule > > m_updateRules ; <nl> + } ; <nl> + <nl> + } ; / * namespace ADDON * / <nl> mmm a / xbmc / addons / CMakeLists . txt <nl> ppp b / xbmc / addons / CMakeLists . txt <nl> set ( SOURCES Addon . cpp <nl> AddonRepos . cpp <nl> AddonStatusHandler . cpp <nl> AddonSystemSettings . cpp <nl> + AddonUpdateRules . cpp <nl> AddonVersion . cpp <nl> AudioDecoder . cpp <nl> AudioEncoder . cpp <nl> set ( HEADERS Addon . h <nl> AddonRepos . h <nl> AddonStatusHandler . h <nl> AddonSystemSettings . h <nl> + AddonUpdateRules . h <nl> AddonVersion . h <nl> AudioDecoder . h <nl> AudioEncoder . h <nl> mmm a / xbmc / addons / addoninfo / AddonInfo . h <nl> ppp b / xbmc / addons / addoninfo / AddonInfo . h <nl> enum class AddonOriginType <nl> MANUAL = 2 / / / The addon origin is a zip file , package or development build <nl> } ; <nl> <nl> + / / ! @ brief Reasons why an addon is not updateable <nl> + enum class AddonUpdateRule <nl> + { <nl> + ANY = 0 , / / ! < used internally , not to be explicitly set <nl> + USER_DISABLED_AUTO_UPDATE = 1 , / / ! < automatic updates disabled via AddonInfo dialog <nl> + PIN_OLD_VERSION = 2 / / ! < user downgraded to an older version <nl> + } ; <nl> + <nl> struct DependencyInfo <nl> { <nl> std : : string id ; <nl> mmm a / xbmc / addons / gui / GUIDialogAddonInfo . cpp <nl> ppp b / xbmc / addons / gui / GUIDialogAddonInfo . cpp <nl> void CGUIDialogAddonInfo : : UpdateControls ( ) <nl> CONTROL_ENABLE_ON_CONDITION ( CONTROL_BTN_AUTOUPDATE , isInstalled & & autoUpdatesOn ) ; <nl> SET_CONTROL_SELECTED ( GetID ( ) , CONTROL_BTN_AUTOUPDATE , <nl> isInstalled & & autoUpdatesOn & & <nl> - ! CServiceBroker : : GetAddonMgr ( ) . IsBlacklisted ( m_localAddon - > ID ( ) ) ) ; <nl> + CServiceBroker : : GetAddonMgr ( ) . IsAutoUpdateable ( m_localAddon - > ID ( ) ) ) ; <nl> SET_CONTROL_LABEL ( CONTROL_BTN_AUTOUPDATE , 21340 ) ; <nl> <nl> CONTROL_ENABLE_ON_CONDITION ( <nl> void CGUIDialogAddonInfo : : OnUpdate ( ) <nl> if ( i ! = - 1 ) <nl> { <nl> Close ( ) ; <nl> - / / turn auto updating off if downgrading <nl> + / / turn auto updating off if downgrading <nl> + <nl> if ( m_localAddon - > Version ( ) > versions [ i ] . first ) <nl> - CServiceBroker : : GetAddonMgr ( ) . AddToUpdateBlacklist ( m_localAddon - > ID ( ) ) ; <nl> + CServiceBroker : : GetAddonMgr ( ) . AddUpdateRuleToList ( m_localAddon - > ID ( ) , <nl> + AddonUpdateRule : : PIN_OLD_VERSION ) ; <nl> + <nl> + / / turn auto updating on if upgrading or changing origin <nl> + / / ( but not when changing to local cache ) <nl> + <nl> + if ( ( m_localAddon - > Version ( ) < versions [ i ] . first & & <nl> + m_localAddon - > Origin ( ) = = versions [ i ] . second ) | | <nl> + ( m_localAddon - > Origin ( ) ! = versions [ i ] . second & & versions [ i ] . second ! = LOCAL_CACHE ) ) <nl> + CServiceBroker : : GetAddonMgr ( ) . RemoveUpdateRuleFromList ( m_localAddon - > ID ( ) , <nl> + AddonUpdateRule : : PIN_OLD_VERSION ) ; <nl> <nl> if ( versions [ i ] . second = = LOCAL_CACHE ) <nl> CAddonInstaller : : GetInstance ( ) . InstallFromZip ( <nl> void CGUIDialogAddonInfo : : OnToggleAutoUpdates ( ) <nl> { <nl> bool selected = msg . GetParam1 ( ) = = 1 ; <nl> if ( selected ) <nl> - CServiceBroker : : GetAddonMgr ( ) . RemoveFromUpdateBlacklist ( m_localAddon - > ID ( ) ) ; <nl> + CServiceBroker : : GetAddonMgr ( ) . RemoveAllUpdateRulesFromList ( m_localAddon - > ID ( ) ) ; <nl> else <nl> - CServiceBroker : : GetAddonMgr ( ) . AddToUpdateBlacklist ( m_localAddon - > ID ( ) ) ; <nl> + CServiceBroker : : GetAddonMgr ( ) . AddUpdateRuleToList ( m_localAddon - > ID ( ) , <nl> + AddonUpdateRule : : USER_DISABLED_AUTO_UPDATE ) ; <nl> } <nl> } <nl> <nl> mmm a / xbmc / addons / gui / GUIWindowAddonBrowser . cpp <nl> ppp b / xbmc / addons / gui / GUIWindowAddonBrowser . cpp <nl> class UpdateAddons : public IRunnable <nl> } <nl> } ; <nl> <nl> + class UpdateAllowedAddons : public IRunnable <nl> + { <nl> + void Run ( ) override <nl> + { <nl> + for ( const auto & addon : CServiceBroker : : GetAddonMgr ( ) . GetAvailableUpdates ( ) ) <nl> + if ( CServiceBroker : : GetAddonMgr ( ) . IsAutoUpdateable ( addon - > ID ( ) ) ) <nl> + CAddonInstaller : : GetInstance ( ) . InstallOrUpdate ( addon - > ID ( ) ) ; <nl> + } <nl> + } ; <nl> + <nl> void CGUIWindowAddonBrowser : : OnEvent ( const ADDON : : CRepositoryUpdater : : RepositoryUpdated & event ) <nl> { <nl> CGUIMessage msg ( GUI_MSG_NOTIFY_ALL , 0 , 0 , GUI_MSG_UPDATE ) ; <nl> bool CGUIWindowAddonBrowser : : OnClick ( int iItem , const std : : string & player ) <nl> CGUIDialogBusy : : Wait ( & updater , 100 , true ) ; <nl> return true ; <nl> } <nl> + if ( item - > GetPath ( ) = = " addons : / / update_allowed / " ) <nl> + { <nl> + UpdateAllowedAddons updater ; <nl> + CGUIDialogBusy : : Wait ( & updater , 100 , true ) ; <nl> + return true ; <nl> + } <nl> if ( ! item - > m_bIsFolder ) <nl> { <nl> / / cancel a downloading job <nl> mmm a / xbmc / filesystem / AddonsDirectory . cpp <nl> ppp b / xbmc / filesystem / AddonsDirectory . cpp <nl> static void OutdatedAddons ( const CURL & path , CFileItemList & items ) <nl> <nl> if ( ! items . IsEmpty ( ) ) <nl> { <nl> - CFileItemPtr item ( new CFileItem ( " addons : / / update_all / " , false ) ) ; <nl> - item - > SetLabel ( g_localizeStrings . Get ( 24122 ) ) ; <nl> - item - > SetSpecialSort ( SortSpecialOnTop ) ; <nl> - items . Add ( item ) ; <nl> + if ( CAddonSystemSettings : : GetInstance ( ) . GetAddonAutoUpdateMode ( ) = = AUTO_UPDATES_ON ) <nl> + { <nl> + const CFileItemPtr itemUpdateAllowed ( <nl> + std : : make_shared < CFileItem > ( " addons : / / update_allowed / " , false ) ) ; <nl> + itemUpdateAllowed - > SetLabel ( g_localizeStrings . Get ( 24137 ) ) ; <nl> + itemUpdateAllowed - > SetSpecialSort ( SortSpecialOnTop ) ; <nl> + items . Add ( itemUpdateAllowed ) ; <nl> + } <nl> + <nl> + const CFileItemPtr itemUpdateAll ( std : : make_shared < CFileItem > ( " addons : / / update_all / " , false ) ) ; <nl> + itemUpdateAll - > SetLabel ( g_localizeStrings . Get ( 24122 ) ) ; <nl> + itemUpdateAll - > SetSpecialSort ( SortSpecialOnTop ) ; <nl> + items . Add ( itemUpdateAll ) ; <nl> } <nl> } <nl> <nl> | [ addons ] version pinning | xbmc/xbmc | db42ff91d67667d2772cc16294d3fd5c6f590a03 | 2020-09-11T11:57:25Z |
mmm a / NEWS . md <nl> ppp b / NEWS . md <nl> XGBoost Change Log <nl> <nl> This file records the changes in xgboost library in reverse chronological order . <nl> <nl> + # # v0 . 82 ( 2019 . 03 . 03 ) <nl> + This release is packed with many new features and bug fixes . <nl> + <nl> + # # # Roadmap : better performance scaling for multi - core CPUs ( # 3957 ) <nl> + * Poor performance scaling of the ` hist ` algorithm for multi - core CPUs has been under investigation ( # 3810 ) . # 3957 marks an important step toward better performance scaling , by using software pre - fetching and replacing STL vectors with C - style arrays . Special thanks to @ Laurae2 and @ SmirnovEgorRu . <nl> + * See # 3810 for latest progress on this roadmap . <nl> + <nl> + # # # New feature : Distributed Fast Histogram Algorithm ( ` hist ` ) ( # 4011 , # 4102 , # 4140 , # 4128 ) <nl> + * It is now possible to run the ` hist ` algorithm in distributed setting . Special thanks to @ CodingCat . The benefits include : <nl> + 1 . Faster local computation via feature binning <nl> + 2 . Support for monotonic constraints and feature interaction constraints <nl> + 3 . Simpler codebase than ` approx ` , allowing for future improvement <nl> + * Depth - wise tree growing is now performed in a separate code path , so that cross - node syncronization is performed only once per level . <nl> + <nl> + # # # New feature : Multi - Node , Multi - GPU training ( # 4095 ) <nl> + * Distributed training is now able to utilize clusters equipped with NVIDIA GPUs . In particular , the rabit AllReduce layer will communicate GPU device information . Special thanks to @ mt - jones , @ RAMitchell , @ rongou , @ trivialfis , @ canonizer , and @ jeffdk . <nl> + * Resource management systems will be able to assign a rank for each GPU in the cluster . <nl> + * In Dask , users will be able to construct a collection of XGBoost processes over an inhomogeneous device cluster ( i . e . workers with different number and / or kinds of GPUs ) . <nl> + <nl> + # # # New feature : Multiple validation datasets in XGBoost4J - Spark ( # 3904 , # 3910 ) <nl> + * You can now track the performance of the model during training with multiple evaluation datasets . By specifying ` eval_sets ` or call ` setEvalSets ` over a ` XGBoostClassifier ` or ` XGBoostRegressor ` , you can pass in multiple evaluation datasets typed as a ` Map ` from ` String ` to ` DataFrame ` . Special thanks to @ CodingCat . <nl> + * See the usage of multiple validation datasets [ here ] ( https : / / github . com / dmlc / xgboost / blob / 0c1d5f1120c0a159f2567b267f0ec4ffadee00d0 / jvm - packages / xgboost4j - example / src / main / scala / ml / dmlc / xgboost4j / scala / example / spark / SparkTraining . scala # L66 - L78 ) <nl> + <nl> + # # # New feature : Additional metric functions for GPUs ( # 3952 ) <nl> + * Element - wise metrics have been ported to GPU : ` rmse ` , ` mae ` , ` logloss ` , ` poisson - nloglik ` , ` gamma - deviance ` , ` gamma - nloglik ` , ` error ` , ` tweedie - nloglik ` . Special thanks to @ trivialfis and @ RAMitchell . <nl> + * With supported metrics , XGBoost will select the correct devices based on your system and ` n_gpus ` parameter . <nl> + <nl> + # # # New feature : Column sampling at individual nodes ( splits ) ( # 3971 ) <nl> + * Columns ( features ) can now be sampled at individual tree nodes , in addition to per - tree and per - level sampling . To enable per - node sampling , set ` colsample_bynode ` parameter , which represents the fraction of columns sampled at each node . This parameter is set to 1 . 0 by default ( i . e . no sampling per node ) . Special thanks to @ canonizer . <nl> + * The ` colsample_bynode ` parameter works cumulatively with other ` colsample_by * ` parameters : for example , ` { ' colsample_bynode ' : 0 . 5 , ' colsample_bytree ' : 0 . 5 } ` with 100 columns will give 25 features to choose from at each split . <nl> + <nl> + # # # Major API change : consistent logging level via ` verbosity ` ( # 3982 , # 4002 , # 4138 ) <nl> + * XGBoost now allows fine - grained control over logging . You can set ` verbosity ` to 0 ( silent ) , 1 ( warning ) , 2 ( info ) , and 3 ( debug ) . This is useful for controlling the amount of logging outputs . Special thanks to @ trivialfis . <nl> + * Parameters ` silent ` and ` debug_verbose ` are now deprecated . <nl> + * Note : Sometimes XGBoost tries to change configurations based on heuristics , which is displayed as warning message . If there ' s unexpected behaviour , please try to increase value of verbosity . <nl> + <nl> + # # # Major bug fix : external memory ( # 4040 , # 4193 ) <nl> + * Clarify object ownership in multi - threaded prefetcher , to avoid memory error . <nl> + * Correctly merge two column batches ( which uses [ CSC layout ] ( https : / / en . wikipedia . org / wiki / Sparse_matrix # Compressed_sparse_column_ ( CSC_or_CCS ) ) ) . <nl> + * Add unit tests for external memory . <nl> + * Special thanks to @ trivialfis and @ hcho3 . <nl> + <nl> + # # # Major bug fix : early stopping fixed in XGBoost4J and XGBoost4J - Spark ( # 3928 , # 4176 ) <nl> + * Early stopping in XGBoost4J and XGBoost4J - Spark is now consistent with its counterpart in the Python package . Training stops if the current iteration is ` earlyStoppingSteps ` away from the best iteration . If there are multiple evaluation sets , only the last one is used to determinate early stop . <nl> + * See the updated documentation [ here ] ( https : / / xgboost . readthedocs . io / en / release_0 . 82 / jvm / xgboost4j_spark_tutorial . html # early - stopping ) <nl> + * Special thanks to @ CodingCat , @ yanboliang , and @ mingyang . <nl> + <nl> + # # # Major bug fix : infrequent features should not crash distributed training ( # 4045 ) <nl> + * For infrequently occuring features , some partitions may not get any instance . This scenario used to crash distributed training due to mal - formed ranges . The problem has now been fixed . <nl> + * In practice , one - hot - encoded categorical variables tend to produce rare features , particularly when the cardinality is high . <nl> + * Special thanks to @ CodingCat . <nl> + <nl> + # # # Performance improvements <nl> + * Faster , more space - efficient radix sorting in ` gpu_hist ` ( # 3895 ) <nl> + * Subtraction trick in histogram calculation in ` gpu_hist ` ( # 3945 ) <nl> + * More performant re - partition in XGBoost4J - Spark ( # 4049 ) <nl> + <nl> + # # # Bug - fixes <nl> + * Fix semantics of ` gpu_id ` when running multiple XGBoost processes on a multi - GPU machine ( # 3851 ) <nl> + * Fix page storage path for external memory on Windows ( # 3869 ) <nl> + * Fix configuration setup so that DART utilizes GPU ( # 4024 ) <nl> + * Eliminate NAN values from SHAP prediction ( # 3943 ) <nl> + * Prevent empty quantile sketches in ` hist ` ( # 4155 ) <nl> + * Enable running objectives with 0 GPU ( # 3878 ) <nl> + * Parameters are no longer dependent on system locale ( # 3891 , # 3907 ) <nl> + * Use consistent data type in the GPU coordinate descent code ( # 3917 ) <nl> + * Remove undefined behavior in the CLI config parser on the ARM platform ( # 3976 ) <nl> + * Initialize counters in GPU AllReduce ( # 3987 ) <nl> + * Prevent deadlocks in GPU AllReduce ( # 4113 ) <nl> + * Load correct values from sliced NumPy arrays ( # 4147 , # 4165 ) <nl> + * Fix incorrect GPU device selection ( # 4161 ) <nl> + * Make feature binning logic in ` hist ` aware of query groups when running a ranking task ( # 4115 ) . For ranking task , query groups are weighted , not individual instances . <nl> + * Generate correct C + + exception type for ` LOG ( FATAL ) ` macro ( # 4159 ) <nl> + * Python package <nl> + - Python package should run on system without ` PATH ` environment variable ( # 3845 ) <nl> + - Fix ` coef_ ` and ` intercept_ ` signature to be compatible with ` sklearn . RFECV ` ( # 3873 ) <nl> + - Use UTF - 8 encoding in Python package README , to support non - English locale ( # 3867 ) <nl> + - Add AUC - PR to list of metrics to maximize for early stopping ( # 3936 ) <nl> + - Allow loading pickles without ` self . booster ` attribute , for backward compatibility ( # 3938 , # 3944 ) <nl> + - White - list DART for feature importances ( # 4073 ) <nl> + - Update usage of [ h2oai / datatable ] ( https : / / github . com / h2oai / datatable ) ( # 4123 ) <nl> + * XGBoost4J - Spark <nl> + - Address scalability issue in prediction ( # 4033 ) <nl> + - Enforce the use of per - group weights for ranking task ( # 4118 ) <nl> + - Fix vector size of ` rawPredictionCol ` in ` XGBoostClassificationModel ` ( # 3932 ) <nl> + - More robust error handling in Spark tracker ( # 4046 , # 4108 ) <nl> + - Fix return type of ` setEvalSets ` ( # 4105 ) <nl> + - Return correct value of ` getMaxLeaves ` ( # 4114 ) <nl> + <nl> + # # # API changes <nl> + * Add experimental parameter ` single_precision_histogram ` to use single - precision histograms for the ` gpu_hist ` algorithm ( # 3965 ) <nl> + * Python package <nl> + - Add option to select type of feature importances in the scikit - learn inferface ( # 3876 ) <nl> + - Add ` trees_to_df ( ) ` method to dump decision trees as Pandas data frame ( # 4153 ) <nl> + - Add options to control node shapes in the GraphViz plotting function ( # 3859 ) <nl> + - Add ` xgb_model ` option to ` XGBClassifier ` , to load previously saved model ( # 4092 ) <nl> + - Passing lists into ` DMatrix ` is now deprecated ( # 3970 ) <nl> + * XGBoost4J <nl> + - Support multiple feature importance features ( # 3801 ) <nl> + <nl> + # # # Maintenance : Refactor C + + code for legibility and maintainability <nl> + * Refactor ` hist ` algorithm code and add unit tests ( # 3836 ) <nl> + * Minor refactoring of split evaluator in ` gpu_hist ` ( # 3889 ) <nl> + * Removed unused leaf vector field in the tree model ( # 3989 ) <nl> + * Simplify the tree representation by combining ` TreeModel ` and ` RegTree ` classes ( # 3995 ) <nl> + * Simplify and harden tree expansion code ( # 4008 , # 4015 ) <nl> + * De - duplicate parameter classes in the linear model algorithms ( # 4013 ) <nl> + * Robust handling of ranges with C + + 20 span in ` gpu_exact ` and ` gpu_coord_descent ` ( # 4020 , # 4029 ) <nl> + * Simplify tree training code ( # 3825 ) . Also use Span class for robust handling of ranges . <nl> + <nl> + # # # Maintenance : testing , continuous integration , build system <nl> + * Disallow ` std : : regex ` since it ' s not supported by GCC 4 . 8 . x ( # 3870 ) <nl> + * Add multi - GPU tests for coordinate descent algorithm for linear models ( # 3893 , # 3974 ) <nl> + * Enforce naming style in Python lint ( # 3896 ) <nl> + * Refactor Python tests ( # 3897 , # 3901 ) : Use pytest exclusively , display full trace upon failure <nl> + * Address ` DeprecationWarning ` when using Python collections ( # 3909 ) <nl> + * Use correct group for maven site plugin ( # 3937 ) <nl> + * Jenkins CI is now using on - demand EC2 instances exclusively , due to unreliability of Spot instances ( # 3948 ) <nl> + * Better GPU performance logging ( # 3945 ) <nl> + * Fix GPU tests on machines with only 1 GPU ( # 4053 ) <nl> + * Eliminate CRAN check warnings and notes ( # 3988 ) <nl> + * Add unit tests for tree serialization ( # 3989 ) <nl> + * Add unit tests for tree fitting functions in ` hist ` ( # 4155 ) <nl> + * Add a unit test for ` gpu_exact ` algorithm ( # 4020 ) <nl> + * Correct JVM CMake GPU flag ( # 4071 ) <nl> + * Fix failing Travis CI on Mac ( # 4086 ) <nl> + * Speed up Jenkins by not compiling CMake ( # 4099 ) <nl> + * Analyze C + + and CUDA code using clang - tidy , as part of Jenkins CI pipeline ( # 4034 ) <nl> + * Fix broken R test : Install Homebrew GCC ( # 4142 ) <nl> + * Check for empty datasets in GPU unit tests ( # 4151 ) <nl> + * Fix Windows compilation ( # 4139 ) <nl> + * Comply with latest convention of cpplint ( # 4157 ) <nl> + * Fix a unit test in ` gpu_hist ` ( # 4158 ) <nl> + * Speed up data generation in Python tests ( # 4164 ) <nl> + <nl> + # # # Usability Improvements <nl> + * Add link to [ InfoWorld 2019 Technology of the Year Award ] ( https : / / www . infoworld . com / article / 3336072 / application - development / infoworlds - 2019 - technology - of - the - year - award - winners . html ) ( # 4116 ) <nl> + * Remove outdated AWS YARN tutorial ( # 3885 ) <nl> + * Document current limitation in number of features ( # 3886 ) <nl> + * Remove unnecessary warning when ` gblinear ` is selected ( # 3888 ) <nl> + * Document limitation of CSV parser : header not supported ( # 3934 ) <nl> + * Log training parameters in XGBoost4J - Spark ( # 4091 ) <nl> + * Clarify early stopping behavior in the scikit - learn interface ( # 3967 ) <nl> + * Clarify behavior of ` max_depth ` parameter ( # 4078 ) <nl> + * Revise Python docstrings for ranking task ( # 4121 ) . In particular , weights must be per - group in learning - to - rank setting . <nl> + * Document parameter ` num_parallel_tree ` ( # 4022 ) <nl> + * Add Jenkins status badge ( # 4090 ) <nl> + * Warn users against using internal functions of ` Booster ` object ( # 4066 ) <nl> + * Reformat ` benchmark_tree . py ` to comply with Python style convention ( # 4126 ) <nl> + * Clarify a comment in ` objectiveTrait ` ( # 4174 ) <nl> + * Fix typos and broken links in documentation ( # 3890 , # 3872 , # 3902 , # 3919 , # 3975 , # 4027 , # 4156 , # 4167 ) <nl> + <nl> + # # # Acknowledgement <nl> + * * Contributors * * ( in no particular order ) : Jiaming Yuan ( @ trivialfis ) , Hyunsu Cho ( @ hcho3 ) , Nan Zhu ( @ CodingCat ) , Rory Mitchell ( @ RAMitchell ) , Yanbo Liang ( @ yanboliang ) , Andy Adinets ( @ canonizer ) , Tong He ( @ hetong007 ) , Yuan Tang ( @ terrytangyuan ) <nl> + <nl> + * * First - time Contributors * * ( in no particular order ) : Jelle Zijlstra ( @ JelleZijlstra ) , Jiacheng Xu ( @ jiachengxu ) , @ ajing , Kashif Rasul ( @ kashif ) , @ theycallhimavi , Joey Gao ( @ pjgao ) , Prabakaran Kumaresshan ( @ nixphix ) , Huafeng Wang ( @ huafengw ) , @ lyxthe , Sam Wilkinson ( @ scwilkinson ) , Tatsuhito Kato ( @ stabacov ) , Shayak Banerjee ( @ shayakbanerjee ) , Kodi Arfer ( @ Kodiologist ) , @ KyleLi1985 , Egor Smirnov ( @ SmirnovEgorRu ) , @ tmitanitky , Pasha Stetsenko ( @ st - pasha ) , Kenichi Nagahara ( @ keni - chi ) , Abhai Kollara Dilip ( @ abhaikollara ) , Patrick Ford ( @ pford221 ) , @ hshujuan , Matthew Jones ( @ mt - jones ) , Thejaswi Rao ( @ teju85 ) , Adam November ( @ anovember ) <nl> + <nl> + * * First - time Reviewers * * ( in no particular order ) : Mingyang Hu ( @ mingyang ) , Theodore Vasiloudis ( @ thvasilo ) , Jakub Troszok ( @ troszok ) , Rong Ou ( @ rongou ) , @ Denisevi4 , Matthew Jones ( @ mt - jones ) , Jeff Kaplan ( @ jeffdk ) <nl> + <nl> # # v0 . 81 ( 2018 . 11 . 04 ) <nl> # # # New feature : feature interaction constraints <nl> * Users are now able to control which features ( independent variables ) are allowed to interact by specifying feature interaction constraints ( # 3466 ) . <nl> This file records the changes in xgboost library in reverse chronological order . <nl> - Latest master : https : / / xgboost . readthedocs . io / en / latest <nl> - 0 . 80 stable : https : / / xgboost . readthedocs . io / en / release_0 . 80 <nl> - 0 . 72 stable : https : / / xgboost . readthedocs . io / en / release_0 . 72 <nl> - * Ranking task now uses instance weights ( # 3379 ) <nl> + * Support for per - group weights in ranking objective ( # 3379 ) <nl> * Fix inaccurate decimal parsing ( # 3546 ) <nl> * New functionality <nl> - Query ID column support in LIBSVM data files ( # 2749 ) . This is convenient for performing ranking task in distributed setting . <nl> | Release 0 . 82 ( ) | dmlc/xgboost | 3f83dcd50286d7c8d22e552942bd6572547c32b9 | 2019-03-05T02:14:36Z |
mmm a / lib / browser / api / session . js <nl> ppp b / lib / browser / api / session . js <nl> <nl> <nl> const { EventEmitter } = require ( ' events ' ) ; <nl> const { app , deprecate } = require ( ' electron ' ) ; <nl> - const { fromPartition , Session , Cookies , Protocol , ServiceWorkerContext } = process . electronBinding ( ' session ' ) ; <nl> + const { fromPartition , Session , Cookies , Protocol } = process . electronBinding ( ' session ' ) ; <nl> <nl> / / Public API . <nl> Object . defineProperties ( exports , { <nl> Object . defineProperties ( exports , { <nl> } ) ; <nl> <nl> Object . setPrototypeOf ( Cookies . prototype , EventEmitter . prototype ) ; <nl> - Object . setPrototypeOf ( ServiceWorkerContext . prototype , EventEmitter . prototype ) ; <nl> Object . setPrototypeOf ( Session . prototype , EventEmitter . prototype ) ; <nl> <nl> Session . prototype . _init = function ( ) { <nl> mmm a / shell / browser / api / electron_api_service_worker_context . cc <nl> ppp b / shell / browser / api / electron_api_service_worker_context . cc <nl> <nl> # include " content / public / browser / storage_partition . h " <nl> # include " gin / data_object_builder . h " <nl> # include " gin / handle . h " <nl> + # include " gin / object_template_builder . h " <nl> # include " shell / browser / electron_browser_context . h " <nl> # include " shell / common / gin_converters / value_converter . h " <nl> # include " shell / common / gin_helper / dictionary . h " <nl> - # include " shell / common / gin_helper / object_template_builder . h " <nl> + # include " shell / common / gin_helper / function_template_extensions . h " <nl> # include " shell / common / node_includes . h " <nl> <nl> namespace electron { <nl> v8 : : Local < v8 : : Value > ServiceWorkerRunningInfoToDict ( <nl> <nl> } / / namespace <nl> <nl> + gin : : WrapperInfo ServiceWorkerContext : : kWrapperInfo = { gin : : kEmbedderNativeGin } ; <nl> + <nl> ServiceWorkerContext : : ServiceWorkerContext ( <nl> v8 : : Isolate * isolate , <nl> ElectronBrowserContext * browser_context ) <nl> : browser_context_ ( browser_context ) , weak_ptr_factory_ ( this ) { <nl> - Init ( isolate ) ; <nl> service_worker_context_ = <nl> content : : BrowserContext : : GetDefaultStoragePartition ( browser_context_ ) <nl> - > GetServiceWorkerContext ( ) ; <nl> gin : : Handle < ServiceWorkerContext > ServiceWorkerContext : : Create ( <nl> } <nl> <nl> / / static <nl> - void ServiceWorkerContext : : BuildPrototype ( <nl> - v8 : : Isolate * isolate , <nl> - v8 : : Local < v8 : : FunctionTemplate > prototype ) { <nl> - prototype - > SetClassName ( gin : : StringToV8 ( isolate , " ServiceWorkerContext " ) ) ; <nl> - gin_helper : : ObjectTemplateBuilder ( isolate , prototype - > PrototypeTemplate ( ) ) <nl> + gin : : ObjectTemplateBuilder ServiceWorkerContext : : GetObjectTemplateBuilder ( <nl> + v8 : : Isolate * isolate ) { <nl> + return gin_helper : : EventEmitterMixin < <nl> + ServiceWorkerContext > : : GetObjectTemplateBuilder ( isolate ) <nl> . SetMethod ( " getAllRunning " , <nl> & ServiceWorkerContext : : GetAllRunningWorkerInfo ) <nl> . SetMethod ( " getFromVersionID " , <nl> & ServiceWorkerContext : : GetWorkerInfoFromID ) ; <nl> } <nl> <nl> + const char * ServiceWorkerContext : : GetTypeName ( ) { <nl> + return " ServiceWorkerContext " ; <nl> + } <nl> + <nl> } / / namespace api <nl> <nl> } / / namespace electron <nl> mmm a / shell / browser / api / electron_api_service_worker_context . h <nl> ppp b / shell / browser / api / electron_api_service_worker_context . h <nl> <nl> # include " content / public / browser / service_worker_context . h " <nl> # include " content / public / browser / service_worker_context_observer . h " <nl> # include " gin / handle . h " <nl> - # include " shell / common / gin_helper / trackable_object . h " <nl> + # include " gin / wrappable . h " <nl> + # include " shell / browser / event_emitter_mixin . h " <nl> <nl> namespace electron { <nl> <nl> class ElectronBrowserContext ; <nl> namespace api { <nl> <nl> class ServiceWorkerContext <nl> - : public gin_helper : : TrackableObject < ServiceWorkerContext > , <nl> + : public gin : : Wrappable < ServiceWorkerContext > , <nl> + public gin_helper : : EventEmitterMixin < ServiceWorkerContext > , <nl> public content : : ServiceWorkerContextObserver { <nl> public : <nl> static gin : : Handle < ServiceWorkerContext > Create ( <nl> v8 : : Isolate * isolate , <nl> ElectronBrowserContext * browser_context ) ; <nl> <nl> - static void BuildPrototype ( v8 : : Isolate * isolate , <nl> - v8 : : Local < v8 : : FunctionTemplate > prototype ) ; <nl> - <nl> v8 : : Local < v8 : : Value > GetAllRunningWorkerInfo ( v8 : : Isolate * isolate ) ; <nl> v8 : : Local < v8 : : Value > GetWorkerInfoFromID ( gin_helper : : ErrorThrower thrower , <nl> int64_t version_id ) ; <nl> class ServiceWorkerContext <nl> const content : : ConsoleMessage & message ) override ; <nl> void OnDestruct ( content : : ServiceWorkerContext * context ) override ; <nl> <nl> + / / gin : : Wrappable <nl> + static gin : : WrapperInfo kWrapperInfo ; <nl> + gin : : ObjectTemplateBuilder GetObjectTemplateBuilder ( <nl> + v8 : : Isolate * isolate ) override ; <nl> + const char * GetTypeName ( ) override ; <nl> + <nl> protected : <nl> explicit ServiceWorkerContext ( v8 : : Isolate * isolate , <nl> ElectronBrowserContext * browser_context ) ; <nl> mmm a / shell / browser / api / electron_api_session . cc <nl> ppp b / shell / browser / api / electron_api_session . cc <nl> void Initialize ( v8 : : Local < v8 : : Object > exports , <nl> dict . Set ( <nl> " Protocol " , <nl> Protocol : : GetConstructor ( isolate ) - > GetFunction ( context ) . ToLocalChecked ( ) ) ; <nl> - dict . Set ( " ServiceWorkerContext " , ServiceWorkerContext : : GetConstructor ( isolate ) <nl> - - > GetFunction ( context ) <nl> - . ToLocalChecked ( ) ) ; <nl> dict . SetMethod ( " fromPartition " , & FromPartition ) ; <nl> } <nl> <nl> | refactor : ginify ServiceWorkerContext ( ) | electron/electron | 22c17bcc5b73c915267d163c09566294c21baa7b | 2020-03-20T21:15:14Z |
mmm a / lib / Sema / TypeCheckStmt . cpp <nl> ppp b / lib / Sema / TypeCheckStmt . cpp <nl> <nl> / / <nl> / / This source file is part of the Swift . org open source project <nl> / / <nl> - / / Copyright ( c ) 2014 - 2017 Apple Inc . and the Swift project authors <nl> + / / Copyright ( c ) 2014 - 2018 Apple Inc . and the Swift project authors <nl> / / Licensed under Apache License v2 . 0 with Runtime Library Exception <nl> / / <nl> / / See https : / / swift . org / LICENSE . txt for license information <nl> class StmtChecker : public StmtVisitor < StmtChecker , Stmt * > { <nl> <nl> / / If the previous case fellthrough , similarly check that that case ' s bindings <nl> / / includes our first label item ' s pattern bindings and types . <nl> - if ( PreviousFallthrough ) { <nl> + if ( PreviousFallthrough & & previousBlock ) { <nl> auto firstPattern = caseBlock - > getCaseLabelItems ( ) [ 0 ] . getPattern ( ) ; <nl> SmallVector < VarDecl * , 4 > Vars ; <nl> firstPattern - > collectVariables ( Vars ) ; <nl> mmm a / test / stmt / switch_stmt2 . swift <nl> ppp b / test / stmt / switch_stmt2 . swift <nl> func non_fully_covered_switch ( x : Int ) - > Int { <nl> } <nl> return x <nl> } <nl> + <nl> + / / Do not crash if another switch statement follows a fallthrough . <nl> + func fallthrough_not_last ( i : Int ) { <nl> + switch i { <nl> + case 1 : <nl> + fallthrough <nl> + switch i { <nl> + case 1 : break <nl> + default : break <nl> + } <nl> + default : <nl> + break <nl> + } <nl> + } <nl> | Merge pull request from rudkx / rdar41305565 | apple/swift | a65105c3822b1ce64b7bb6b37613051602b2d3d1 | 2018-06-27T04:28:35Z |
mmm a / src / rdb_protocol / term . cc <nl> ppp b / src / rdb_protocol / term . cc <nl> counted_t < val_t > term_t : : eval ( eval_flags_t eval_flags ) { <nl> } <nl> <nl> counted_t < val_t > term_t : : new_val ( counted_t < const datum_t > d ) { <nl> - return make_counted < val_t > ( d , this ) ; <nl> + return make_counted < val_t > ( env , d , this ) ; <nl> } <nl> counted_t < val_t > term_t : : new_val ( counted_t < const datum_t > d , counted_t < table_t > t ) { <nl> - return make_counted < val_t > ( d , t , this ) ; <nl> + return make_counted < val_t > ( env , d , t , this ) ; <nl> } <nl> <nl> counted_t < val_t > term_t : : new_val ( counted_t < datum_stream_t > s ) { <nl> - return make_counted < val_t > ( s , this ) ; <nl> + return make_counted < val_t > ( env , s , this ) ; <nl> } <nl> counted_t < val_t > term_t : : new_val ( counted_t < datum_stream_t > s , counted_t < table_t > d ) { <nl> - return make_counted < val_t > ( d , s , this ) ; <nl> + return make_counted < val_t > ( env , d , s , this ) ; <nl> } <nl> counted_t < val_t > term_t : : new_val ( counted_t < const db_t > db ) { <nl> - return make_counted < val_t > ( db , this ) ; <nl> + return make_counted < val_t > ( env , db , this ) ; <nl> } <nl> counted_t < val_t > term_t : : new_val ( counted_t < table_t > t ) { <nl> - return make_counted < val_t > ( t , this ) ; <nl> + return make_counted < val_t > ( env , t , this ) ; <nl> } <nl> counted_t < val_t > term_t : : new_val ( counted_t < func_t > f ) { <nl> - return make_counted < val_t > ( f , this ) ; <nl> + return make_counted < val_t > ( env , f , this ) ; <nl> } <nl> counted_t < val_t > term_t : : new_val_bool ( bool b ) { <nl> return new_val ( make_counted < const datum_t > ( datum_t : : R_BOOL , b ) ) ; <nl> mmm a / src / rdb_protocol / term . hpp <nl> ppp b / src / rdb_protocol / term . hpp <nl> class term_t : public single_threaded_countable_t < term_t > , public pb_rcheckable_ <nl> <nl> protob_t < const Term > get_src ( ) const ; <nl> void prop_bt ( Term * t ) const ; <nl> - env_t * val_t_get_env ( ) const { return env ; } / / Only ` val_t ` should call this . <nl> <nl> protected : <nl> env_t * env ; <nl> mmm a / src / rdb_protocol / val . cc <nl> ppp b / src / rdb_protocol / val . cc <nl> const char * val_t : : type_t : : name ( ) const { <nl> unreachable ( ) ; <nl> } <nl> <nl> - val_t : : val_t ( counted_t < const datum_t > _datum , const term_t * parent ) <nl> + / / RSI : Probably shouldn ' t take term_t , should just take a backtrace . <nl> + val_t : : val_t ( env_t * _env , counted_t < const datum_t > _datum , const term_t * parent ) <nl> : pb_rcheckable_t ( parent - > backtrace ( ) ) , <nl> - env ( parent - > val_t_get_env ( ) ) , <nl> + env ( _env ) , <nl> type ( type_t : : DATUM ) , <nl> u ( _datum ) { <nl> guarantee ( datum ( ) . has ( ) ) ; <nl> } <nl> <nl> - val_t : : val_t ( counted_t < const datum_t > _datum , counted_t < table_t > _table , <nl> + val_t : : val_t ( env_t * _env , counted_t < const datum_t > _datum , counted_t < table_t > _table , <nl> const term_t * parent ) <nl> : pb_rcheckable_t ( parent - > backtrace ( ) ) , <nl> - env ( parent - > val_t_get_env ( ) ) , <nl> + env ( _env ) , <nl> type ( type_t : : SINGLE_SELECTION ) , <nl> table ( _table ) , <nl> u ( _datum ) { <nl> val_t : : val_t ( counted_t < const datum_t > _datum , counted_t < table_t > _table , <nl> guarantee ( datum ( ) . has ( ) ) ; <nl> } <nl> <nl> - val_t : : val_t ( counted_t < datum_stream_t > _sequence , const term_t * parent ) <nl> + val_t : : val_t ( env_t * _env , counted_t < datum_stream_t > _sequence , const term_t * parent ) <nl> : pb_rcheckable_t ( parent - > backtrace ( ) ) , <nl> - env ( parent - > val_t_get_env ( ) ) , <nl> + env ( _env ) , <nl> type ( type_t : : SEQUENCE ) , <nl> u ( _sequence ) { <nl> guarantee ( sequence ( ) . has ( ) ) ; <nl> val_t : : val_t ( counted_t < datum_stream_t > _sequence , const term_t * parent ) <nl> } <nl> } <nl> <nl> - val_t : : val_t ( counted_t < table_t > _table , counted_t < datum_stream_t > _sequence , <nl> + val_t : : val_t ( env_t * _env , counted_t < table_t > _table , <nl> + counted_t < datum_stream_t > _sequence , <nl> const term_t * parent ) <nl> : pb_rcheckable_t ( parent - > backtrace ( ) ) , <nl> - env ( parent - > val_t_get_env ( ) ) , <nl> + env ( _env ) , <nl> type ( type_t : : SELECTION ) , <nl> table ( _table ) , <nl> u ( _sequence ) { <nl> val_t : : val_t ( counted_t < table_t > _table , counted_t < datum_stream_t > _sequence , <nl> guarantee ( sequence ( ) . has ( ) ) ; <nl> } <nl> <nl> - val_t : : val_t ( counted_t < table_t > _table , const term_t * parent ) <nl> + val_t : : val_t ( env_t * _env , counted_t < table_t > _table , const term_t * parent ) <nl> : pb_rcheckable_t ( parent - > backtrace ( ) ) , <nl> - env ( parent - > val_t_get_env ( ) ) , <nl> + env ( _env ) , <nl> type ( type_t : : TABLE ) , <nl> table ( _table ) { <nl> guarantee ( table . has ( ) ) ; <nl> } <nl> - val_t : : val_t ( counted_t < const db_t > _db , const term_t * parent ) <nl> + val_t : : val_t ( env_t * _env , counted_t < const db_t > _db , const term_t * parent ) <nl> : pb_rcheckable_t ( parent - > backtrace ( ) ) , <nl> - env ( parent - > val_t_get_env ( ) ) , <nl> + env ( _env ) , <nl> type ( type_t : : DB ) , <nl> u ( _db ) { <nl> guarantee ( db ( ) . has ( ) ) ; <nl> } <nl> - val_t : : val_t ( counted_t < func_t > _func , const term_t * parent ) <nl> + val_t : : val_t ( env_t * _env , counted_t < func_t > _func , const term_t * parent ) <nl> : pb_rcheckable_t ( parent - > backtrace ( ) ) , <nl> - env ( parent - > val_t_get_env ( ) ) , <nl> + env ( _env ) , <nl> type ( type_t : : FUNC ) , <nl> u ( _func ) { <nl> guarantee ( func ( ) . has ( ) ) ; <nl> mmm a / src / rdb_protocol / val . hpp <nl> ppp b / src / rdb_protocol / val . hpp <nl> class table_t : public single_threaded_countable_t < table_t > , public pb_rcheckabl <nl> durability_requirement_t durability_requirement , <nl> bool return_vals ) ; <nl> <nl> + / / RSI : Probably we shouldn ' t have env as a local . <nl> env_t * env ; <nl> bool use_outdated ; <nl> std : : string pkey ; <nl> class table_t : public single_threaded_countable_t < table_t > , public pb_rcheckabl <nl> boost : : optional < std : : string > sindex_id ; <nl> sorting_t sorting ; <nl> <nl> - struct bound_t { <nl> + struct bound_t { <nl> bound_t ( counted_t < const datum_t > _value , bool _bound_open ) <nl> : value ( _value ) , bound_open ( _bound_open ) { } <nl> counted_t < const datum_t > value ; <nl> class val_t : public single_threaded_countable_t < val_t > , public pb_rcheckable_t <nl> type_t get_type ( ) const ; <nl> const char * get_type_name ( ) const ; <nl> <nl> - val_t ( counted_t < const datum_t > _datum , const term_t * parent ) ; <nl> - val_t ( counted_t < const datum_t > _datum , counted_t < table_t > _table , const term_t * parent ) ; <nl> - val_t ( counted_t < datum_stream_t > _sequence , const term_t * parent ) ; <nl> - val_t ( counted_t < table_t > _table , const term_t * parent ) ; <nl> - val_t ( counted_t < table_t > _table , counted_t < datum_stream_t > _sequence , const term_t * parent ) ; <nl> - val_t ( counted_t < const db_t > _db , const term_t * parent ) ; <nl> - val_t ( counted_t < func_t > _func , const term_t * parent ) ; <nl> + val_t ( env_t * env , counted_t < const datum_t > _datum , const term_t * parent ) ; <nl> + val_t ( env_t * env , counted_t < const datum_t > _datum , counted_t < table_t > _table , const term_t * parent ) ; <nl> + val_t ( env_t * env , counted_t < datum_stream_t > _sequence , const term_t * parent ) ; <nl> + val_t ( env_t * env , counted_t < table_t > _table , const term_t * parent ) ; <nl> + val_t ( env_t * env , counted_t < table_t > _table , counted_t < datum_stream_t > _sequence , const term_t * parent ) ; <nl> + val_t ( env_t * env , counted_t < const db_t > _db , const term_t * parent ) ; <nl> + val_t ( env_t * env , counted_t < func_t > _func , const term_t * parent ) ; <nl> ~ val_t ( ) ; <nl> <nl> counted_t < const db_t > as_db ( ) ; <nl> | Made val_t constructor explicitly take an env_t , removed val_t_get_env function . | rethinkdb/rethinkdb | 7fbd58074ce36278a2162cc64b3650a4c7b6db5c | 2013-09-02T13:26:57Z |
mmm a / scripting / engine_spidermonkey . cpp <nl> ppp b / scripting / engine_spidermonkey . cpp <nl> namespace mongo { <nl> assert ( JS_ValueToId ( cx , c . toval ( name . c_str ( ) ) , idp ) ) ; <nl> } <nl> else { <nl> + delete it ; <nl> * statep = 0 ; <nl> } <nl> return JS_TRUE ; <nl> } <nl> <nl> if ( enum_op = = JSENUMERATE_DESTROY ) { <nl> - delete it ; <nl> + if ( it ) <nl> + delete it ; <nl> return JS_TRUE ; <nl> } <nl> <nl> | fix sm leak b / c of iterator api confusion - part of SERVER - 73 | mongodb/mongo | 7f6c3e9ebe5c6d820351354bdc08e9498eb87e59 | 2009-05-28T19:08:03Z |
mmm a / tensorflow / python / keras / engine / input_layer . py <nl> ppp b / tensorflow / python / keras / engine / input_layer . py <nl> def __init__ ( self , <nl> super ( InputLayer , self ) . __init__ ( dtype = dtype , name = name ) <nl> self . built = True <nl> self . sparse = sparse <nl> + self . ragged = ragged <nl> self . batch_size = batch_size <nl> self . supports_masking = True <nl> <nl> def get_config ( self ) : <nl> ' batch_input_shape ' : self . _batch_input_shape , <nl> ' dtype ' : self . dtype , <nl> ' sparse ' : self . sparse , <nl> + ' ragged ' : self . ragged , <nl> ' name ' : self . name <nl> } <nl> return config <nl> mmm a / tensorflow / python / keras / models . py <nl> ppp b / tensorflow / python / keras / models . py <nl> def _clone_functional_model ( model , input_tensors = None , layer_fn = _clone_layer ) : <nl> # Create placeholders to build the model on top of . <nl> input_tensors = [ ] <nl> for layer in model . _input_layers : <nl> - input_tensor = Input ( <nl> - batch_shape = layer . _batch_input_shape , <nl> - dtype = layer . dtype , <nl> - sparse = layer . sparse , <nl> - name = layer . name ) <nl> + input_tensor = Input ( * * layer . get_config ( ) ) <nl> input_tensors . append ( input_tensor ) <nl> # Cache newly created input layer . <nl> newly_created_input_layer = input_tensor . _keras_history . layer <nl> | Persist ragged arg when it ' s needed . | tensorflow/tensorflow | aadd70e3c259979689a7020f1af933b0f06eda97 | 2019-08-09T00:52:28Z |
mmm a / lib / Frontend / SerializedDiagnosticConsumer . cpp <nl> ppp b / lib / Frontend / SerializedDiagnosticConsumer . cpp <nl> void SerializedDiagnosticConsumer : : emitBlockInfoBlock ( ) { <nl> Abbrev - > Add ( BitCodeAbbrevOp ( BitCodeAbbrevOp : : Fixed , 10 ) ) ; / / Category . <nl> Abbrev - > Add ( BitCodeAbbrevOp ( BitCodeAbbrevOp : : Fixed , 10 ) ) ; / / Mapped Diag ID . <nl> Abbrev - > Add ( BitCodeAbbrevOp ( BitCodeAbbrevOp : : Fixed , 16 ) ) ; / / Text size . <nl> - Abbrev - > Add ( BitCodeAbbrevOp ( BitCodeAbbrevOp : : Blob ) ) ; / / Diagnostc text . <nl> + Abbrev - > Add ( BitCodeAbbrevOp ( BitCodeAbbrevOp : : Blob ) ) ; / / Diagnostic text . <nl> Abbrevs . set ( RECORD_DIAG , Stream . EmitBlockInfoAbbrev ( BLOCK_DIAG , Abbrev ) ) ; <nl> <nl> / / Emit abbreviation for RECORD_CATEGORY . <nl> mmm a / lib / SILGen / SILGenApply . cpp <nl> ppp b / lib / SILGen / SILGenApply . cpp <nl> namespace { <nl> & init , destTL ) ; <nl> } <nl> <nl> - / / / Deactive this special destination . Must always be called <nl> + / / / Deactivate this special destination . Must always be called <nl> / / / before destruction . <nl> void deactivate ( SILGenFunction & gen ) { <nl> assert ( isValid ( ) & & " deactivating an invalid destination " ) ; <nl> mmm a / lib / SILOptimizer / Analysis / LoopRegionAnalysis . cpp <nl> ppp b / lib / SILOptimizer / Analysis / LoopRegionAnalysis . cpp <nl> markMultipleLoopLatchLoopBackEdges ( RegionTy * LoopHeaderRegion , LoopTy * Loop , <nl> <nl> void LoopRegionFunctionInfo : : initializeBlockRegions ( PostOrderFunctionInfo * PI , <nl> LoopInfoTy * LI ) { <nl> - DEBUG ( llvm : : dbgs ( ) < < " Visting BB Regions : \ n " ) ; <nl> + DEBUG ( llvm : : dbgs ( ) < < " Visiting BB Regions : \ n " ) ; <nl> <nl> / / Initialize regions for each BB and associate RPO numbers with each BB . <nl> / / <nl> mmm a / lib / SILOptimizer / LoopTransforms / COWArrayOpt . cpp <nl> ppp b / lib / SILOptimizer / LoopTransforms / COWArrayOpt . cpp <nl> static bool isRelease ( SILInstruction * Inst , SILValue RetainedValue , <nl> / / We don ' t want to match the release with both retains in the example below . <nl> / / <nl> / / retain % a < - - | <nl> - / / retain % a | Match . < - | Dont ' t match . <nl> + / / retain % a | Match . < - | Don ' t match . <nl> / / release % a < - - | < - | <nl> / / <nl> if ( auto * R = dyn_cast < ReleaseValueInst > ( Inst ) ) <nl> | Merge pull request from Saisi / niggling - typos | apple/swift | 6810116ff6909ab8fb354f9deb7a7134534b1048 | 2016-01-30T04:02:50Z |
mmm a / docs / mnist . md <nl> ppp b / docs / mnist . md <nl> You will first need to download and convert the data format from the MNIST websi <nl> <nl> cd $ CAFFE_ROOT / data / mnist <nl> . / get_mnist . sh <nl> - cd $ CAFFE_ROOT / examples / lenet <nl> + cd $ CAFFE_ROOT / examples / mnist <nl> . / create_mnist . sh <nl> <nl> If it complains that ` wget ` or ` gunzip ` are not installed , you need to install them respectively . After running the script there should be two datasets , ` mnist - train - leveldb ` , and ` mnist - test - leveldb ` . <nl> Training and Testing the Model <nl> <nl> Training the model is simple after you have written the network definition protobuf and solver protobuf files . Simply run ` train_mnist . sh ` , or the following command directly : <nl> <nl> - cd $ CAFFE_ROOT / examples / lenet <nl> + cd $ CAFFE_ROOT / examples / mnist <nl> . / train_lenet . sh <nl> <nl> ` train_lenet . sh ` is a simple script , but here are a few explanations : ` GLOG_logtostderr = 1 ` is the google logging flag that prints all the logging messages directly to stderr . The main tool for training is ` train_net . bin ` , with the solver protobuf text file as its argument . <nl> similarity index 100 % <nl> rename from examples / lenet / convert_mnist_data . cpp <nl> rename to examples / mnist / convert_mnist_data . cpp <nl> similarity index 100 % <nl> rename from examples / lenet / create_mnist . sh <nl> rename to examples / mnist / create_mnist . sh <nl> similarity index 100 % <nl> rename from examples / lenet / lenet . prototxt <nl> rename to examples / mnist / lenet . prototxt <nl> similarity index 100 % <nl> rename from examples / lenet / lenet_solver . prototxt <nl> rename to examples / mnist / lenet_solver . prototxt <nl> similarity index 100 % <nl> rename from examples / lenet / lenet_test . prototxt <nl> rename to examples / mnist / lenet_test . prototxt <nl> similarity index 100 % <nl> rename from examples / lenet / lenet_train . prototxt <nl> rename to examples / mnist / lenet_train . prototxt <nl> new file mode 100644 <nl> index 00000000000 . . 9b48c30eca6 <nl> mmm / dev / null <nl> ppp b / examples / mnist / mnist_autoencoder_solver . prototxt <nl> <nl> + train_net : " mnist_autoencoder_train . prototxt " <nl> + test_net : " mnist_autoencoder_test . prototxt " <nl> + test_iter : 50 <nl> + test_interval : 100 <nl> + test_compute_loss : true <nl> + base_lr : 0 . 0001 <nl> + lr_policy : " fixed " <nl> + display : 20 <nl> + max_iter : 4000000 <nl> + weight_decay : 0 . 0005 <nl> + snapshot : 10000 <nl> + snapshot_prefix : " mnist_autoencoder_train " <nl> + momentum : 0 . 9 <nl> + solver_mode : 1 <nl> new file mode 100644 <nl> index 00000000000 . . 5090e82fe0a <nl> mmm / dev / null <nl> ppp b / examples / mnist / mnist_autoencoder_test . prototxt <nl> <nl> + name : " MNISTAutoencoder " <nl> + layers { <nl> + top : " data " <nl> + name : " data " <nl> + type : DATA <nl> + data_param { <nl> + source : " mnist - test - leveldb " <nl> + scale : 0 . 0039215684 <nl> + batch_size : 100 <nl> + } <nl> + } <nl> + layers { <nl> + bottom : " data " <nl> + top : " flatdata " <nl> + name : " flatdata " <nl> + type : FLATTEN <nl> + } <nl> + layers { <nl> + bottom : " data " <nl> + top : " encode1 " <nl> + name : " encode1 " <nl> + type : INNER_PRODUCT <nl> + inner_product_param { <nl> + num_output : 1000 <nl> + } <nl> + } <nl> + layers { <nl> + bottom : " encode1 " <nl> + top : " encode1neuron " <nl> + name : " encode1neuron " <nl> + type : SIGMOID <nl> + } <nl> + layers { <nl> + bottom : " encode1neuron " <nl> + top : " encode2 " <nl> + name : " encode2 " <nl> + type : INNER_PRODUCT <nl> + inner_product_param { <nl> + num_output : 500 <nl> + } <nl> + } <nl> + layers { <nl> + bottom : " encode2 " <nl> + top : " encode2neuron " <nl> + name : " encode2neuron " <nl> + type : SIGMOID <nl> + } <nl> + layers { <nl> + bottom : " encode2neuron " <nl> + top : " encode3 " <nl> + name : " encode3 " <nl> + type : INNER_PRODUCT <nl> + inner_product_param { <nl> + num_output : 250 <nl> + } <nl> + } <nl> + layers { <nl> + bottom : " encode3 " <nl> + top : " encode3neuron " <nl> + name : " encode3neuron " <nl> + type : SIGMOID <nl> + } <nl> + layers { <nl> + bottom : " encode3neuron " <nl> + top : " encode4 " <nl> + name : " encode4 " <nl> + type : INNER_PRODUCT <nl> + blobs_lr : 1 <nl> + blobs_lr : 1 <nl> + weight_decay : 1 <nl> + weight_decay : 0 <nl> + inner_product_param { <nl> + num_output : 30 <nl> + } <nl> + } <nl> + layers { <nl> + bottom : " encode4 " <nl> + top : " decode4 " <nl> + name : " decode4 " <nl> + type : INNER_PRODUCT <nl> + blobs_lr : 1 <nl> + blobs_lr : 1 <nl> + weight_decay : 1 <nl> + weight_decay : 0 <nl> + inner_product_param { <nl> + num_output : 250 <nl> + } <nl> + } <nl> + layers { <nl> + bottom : " decode4 " <nl> + top : " decode4neuron " <nl> + name : " decode4neuron " <nl> + type : SIGMOID <nl> + } <nl> + layers { <nl> + bottom : " decode4neuron " <nl> + top : " decode3 " <nl> + name : " decode3 " <nl> + type : INNER_PRODUCT <nl> + inner_product_param { <nl> + num_output : 500 <nl> + } <nl> + } <nl> + layers { <nl> + bottom : " decode3 " <nl> + top : " decode3neuron " <nl> + name : " decode3neuron " <nl> + type : SIGMOID <nl> + } <nl> + layers { <nl> + bottom : " decode3neuron " <nl> + top : " decode2 " <nl> + name : " decode2 " <nl> + type : INNER_PRODUCT <nl> + inner_product_param { <nl> + num_output : 1000 <nl> + } <nl> + } <nl> + layers { <nl> + bottom : " decode2 " <nl> + top : " decode2neuron " <nl> + name : " decode2neuron " <nl> + type : SIGMOID <nl> + } <nl> + layers { <nl> + bottom : " decode2neuron " <nl> + top : " decode1 " <nl> + name : " decode1 " <nl> + type : INNER_PRODUCT <nl> + inner_product_param { <nl> + num_output : 784 <nl> + } <nl> + } <nl> + layers { <nl> + bottom : " decode1 " <nl> + top : " decode1neuron " <nl> + name : " decode1neuron " <nl> + type : SIGMOID <nl> + } <nl> + layers { <nl> + bottom : " decode1neuron " <nl> + bottom : " flatdata " <nl> + name : " loss " <nl> + type : EUCLIDEAN_LOSS <nl> + } <nl> new file mode 100644 <nl> index 00000000000 . . 90d2cff99b8 <nl> mmm / dev / null <nl> ppp b / examples / mnist / mnist_autoencoder_train . prototxt <nl> <nl> + name : " MNISTAutoencoder " <nl> + layers { <nl> + top : " data " <nl> + name : " data " <nl> + type : DATA <nl> + data_param { <nl> + source : " mnist - train - leveldb " <nl> + scale : 0 . 0039215684 <nl> + batch_size : 100 <nl> + } <nl> + } <nl> + layers { <nl> + bottom : " data " <nl> + top : " flatdata " <nl> + name : " flatdata " <nl> + type : FLATTEN <nl> + } <nl> + layers { <nl> + bottom : " data " <nl> + top : " encode1 " <nl> + name : " encode1 " <nl> + type : INNER_PRODUCT <nl> + blobs_lr : 1 <nl> + blobs_lr : 1 <nl> + weight_decay : 1 <nl> + weight_decay : 0 <nl> + inner_product_param { <nl> + num_output : 1000 <nl> + weight_filler { <nl> + type : " gaussian " <nl> + std : 1 <nl> + sparse : 15 <nl> + } <nl> + bias_filler { <nl> + type : " constant " <nl> + value : 0 <nl> + } <nl> + } <nl> + } <nl> + layers { <nl> + bottom : " encode1 " <nl> + top : " encode1neuron " <nl> + name : " encode1neuron " <nl> + type : SIGMOID <nl> + } <nl> + layers { <nl> + bottom : " encode1neuron " <nl> + top : " encode2 " <nl> + name : " encode2 " <nl> + type : INNER_PRODUCT <nl> + blobs_lr : 1 <nl> + blobs_lr : 1 <nl> + weight_decay : 1 <nl> + weight_decay : 0 <nl> + inner_product_param { <nl> + num_output : 500 <nl> + weight_filler { <nl> + type : " gaussian " <nl> + std : 1 <nl> + sparse : 15 <nl> + } <nl> + bias_filler { <nl> + type : " constant " <nl> + value : 0 <nl> + } <nl> + } <nl> + } <nl> + layers { <nl> + bottom : " encode2 " <nl> + top : " encode2neuron " <nl> + name : " encode2neuron " <nl> + type : SIGMOID <nl> + } <nl> + layers { <nl> + bottom : " encode2neuron " <nl> + top : " encode3 " <nl> + name : " encode3 " <nl> + type : INNER_PRODUCT <nl> + blobs_lr : 1 <nl> + blobs_lr : 1 <nl> + weight_decay : 1 <nl> + weight_decay : 0 <nl> + inner_product_param { <nl> + num_output : 250 <nl> + weight_filler { <nl> + type : " gaussian " <nl> + std : 1 <nl> + sparse : 15 <nl> + } <nl> + bias_filler { <nl> + type : " constant " <nl> + value : 0 <nl> + } <nl> + } <nl> + } <nl> + layers { <nl> + bottom : " encode3 " <nl> + top : " encode3neuron " <nl> + name : " encode3neuron " <nl> + type : SIGMOID <nl> + } <nl> + layers { <nl> + bottom : " encode3neuron " <nl> + top : " encode4 " <nl> + name : " encode4 " <nl> + type : INNER_PRODUCT <nl> + blobs_lr : 1 <nl> + blobs_lr : 1 <nl> + weight_decay : 1 <nl> + weight_decay : 0 <nl> + inner_product_param { <nl> + num_output : 30 <nl> + weight_filler { <nl> + type : " gaussian " <nl> + std : 1 <nl> + sparse : 15 <nl> + } <nl> + bias_filler { <nl> + type : " constant " <nl> + value : 0 <nl> + } <nl> + } <nl> + } <nl> + layers { <nl> + bottom : " encode4 " <nl> + top : " decode4 " <nl> + name : " decode4 " <nl> + type : INNER_PRODUCT <nl> + blobs_lr : 1 <nl> + blobs_lr : 1 <nl> + weight_decay : 1 <nl> + weight_decay : 0 <nl> + inner_product_param { <nl> + num_output : 250 <nl> + weight_filler { <nl> + type : " gaussian " <nl> + std : 1 <nl> + sparse : 15 <nl> + } <nl> + bias_filler { <nl> + type : " constant " <nl> + value : 0 <nl> + } <nl> + } <nl> + } <nl> + layers { <nl> + bottom : " decode4 " <nl> + top : " decode4neuron " <nl> + name : " decode4neuron " <nl> + type : SIGMOID <nl> + } <nl> + layers { <nl> + bottom : " decode4neuron " <nl> + top : " decode3 " <nl> + name : " decode3 " <nl> + type : INNER_PRODUCT <nl> + blobs_lr : 1 <nl> + blobs_lr : 1 <nl> + weight_decay : 1 <nl> + weight_decay : 0 <nl> + inner_product_param { <nl> + num_output : 500 <nl> + weight_filler { <nl> + type : " gaussian " <nl> + std : 1 <nl> + sparse : 15 <nl> + } <nl> + bias_filler { <nl> + type : " constant " <nl> + value : 0 <nl> + } <nl> + } <nl> + } <nl> + layers { <nl> + bottom : " decode3 " <nl> + top : " decode3neuron " <nl> + name : " decode3neuron " <nl> + type : SIGMOID <nl> + } <nl> + layers { <nl> + bottom : " decode3neuron " <nl> + top : " decode2 " <nl> + name : " decode2 " <nl> + type : INNER_PRODUCT <nl> + blobs_lr : 1 <nl> + blobs_lr : 1 <nl> + weight_decay : 1 <nl> + weight_decay : 0 <nl> + inner_product_param { <nl> + num_output : 1000 <nl> + weight_filler { <nl> + type : " gaussian " <nl> + std : 1 <nl> + sparse : 15 <nl> + } <nl> + bias_filler { <nl> + type : " constant " <nl> + value : 0 <nl> + } <nl> + } <nl> + } <nl> + layers { <nl> + bottom : " decode2 " <nl> + top : " decode2neuron " <nl> + name : " decode2neuron " <nl> + type : SIGMOID <nl> + } <nl> + layers { <nl> + bottom : " decode2neuron " <nl> + top : " decode1 " <nl> + name : " decode1 " <nl> + type : INNER_PRODUCT <nl> + blobs_lr : 1 <nl> + blobs_lr : 1 <nl> + weight_decay : 1 <nl> + weight_decay : 0 <nl> + inner_product_param { <nl> + num_output : 784 <nl> + weight_filler { <nl> + type : " gaussian " <nl> + std : 1 <nl> + sparse : 15 <nl> + } <nl> + bias_filler { <nl> + type : " constant " <nl> + value : 0 <nl> + } <nl> + } <nl> + } <nl> + layers { <nl> + bottom : " decode1 " <nl> + bottom : " flatdata " <nl> + name : " loss " <nl> + type : SIGMOID_CROSS_ENTROPY_LOSS <nl> + } <nl> similarity index 100 % <nl> rename from examples / lenet / train_lenet . sh <nl> rename to examples / mnist / train_lenet . sh <nl> new file mode 100755 <nl> index 00000000000 . . af2245e07f0 <nl> mmm / dev / null <nl> ppp b / examples / mnist / train_mnist_autoencoder . sh <nl> <nl> + # ! / bin / bash <nl> + TOOLS = . . / . . / build / tools <nl> + <nl> + GLOG_logtostderr = 1 $ TOOLS / train_net . bin mnist_autoencoder_solver . prototxt <nl> mmm a / include / caffe / filler . hpp <nl> ppp b / include / caffe / filler . hpp <nl> class ConstantFiller : public Filler < Dtype > { <nl> for ( int i = 0 ; i < count ; + + i ) { <nl> data [ i ] = value ; <nl> } <nl> + CHECK_EQ ( this - > filler_param_ . sparse ( ) , - 1 ) <nl> + < < " Sparsity not supported by this Filler . " ; <nl> } <nl> } ; <nl> <nl> class UniformFiller : public Filler < Dtype > { <nl> CHECK ( blob - > count ( ) ) ; <nl> caffe_rng_uniform < Dtype > ( blob - > count ( ) , Dtype ( this - > filler_param_ . min ( ) ) , <nl> Dtype ( this - > filler_param_ . max ( ) ) , blob - > mutable_cpu_data ( ) ) ; <nl> + CHECK_EQ ( this - > filler_param_ . sparse ( ) , - 1 ) <nl> + < < " Sparsity not supported by this Filler . " ; <nl> } <nl> } ; <nl> <nl> class GaussianFiller : public Filler < Dtype > { <nl> CHECK ( blob - > count ( ) ) ; <nl> caffe_rng_gaussian < Dtype > ( blob - > count ( ) , Dtype ( this - > filler_param_ . mean ( ) ) , <nl> Dtype ( this - > filler_param_ . std ( ) ) , blob - > mutable_cpu_data ( ) ) ; <nl> + int sparse = this - > filler_param_ . sparse ( ) ; <nl> + CHECK_GE ( sparse , - 1 ) ; <nl> + if ( sparse > = 0 ) { <nl> + / / Sparse initialization is implemented for " weight " blobs ; i . e . matrices . <nl> + / / These have num = = channels = = 1 ; height is number of inputs ; width is <nl> + / / number of outputs . The ' sparse ' variable specifies the mean number <nl> + / / of non - zero input weights for a given output . <nl> + CHECK_EQ ( blob - > num ( ) , 1 ) ; <nl> + CHECK_EQ ( blob - > channels ( ) , 1 ) ; <nl> + int num_inputs = blob - > height ( ) ; <nl> + Dtype non_zero_probability = Dtype ( sparse ) / Dtype ( num_inputs ) ; <nl> + rand_vec_ . reset ( new SyncedMemory ( blob - > count ( ) * sizeof ( int ) ) ) ; <nl> + int * mask = reinterpret_cast < int * > ( rand_vec_ - > mutable_cpu_data ( ) ) ; <nl> + caffe_rng_bernoulli ( blob - > count ( ) , non_zero_probability , mask ) ; <nl> + for ( int i = 0 ; i < blob - > count ( ) ; + + i ) { <nl> + data [ i ] * = mask [ i ] ; <nl> + } <nl> + } <nl> } <nl> + <nl> + protected : <nl> + shared_ptr < SyncedMemory > rand_vec_ ; <nl> } ; <nl> <nl> template < typename Dtype > <nl> class PositiveUnitballFiller : public Filler < Dtype > { <nl> data [ i * dim + j ] / = sum ; <nl> } <nl> } <nl> + CHECK_EQ ( this - > filler_param_ . sparse ( ) , - 1 ) <nl> + < < " Sparsity not supported by this Filler . " ; <nl> } <nl> } ; <nl> <nl> class XavierFiller : public Filler < Dtype > { <nl> Dtype scale = sqrt ( Dtype ( 3 ) / fan_in ) ; <nl> caffe_rng_uniform < Dtype > ( blob - > count ( ) , - scale , scale , <nl> blob - > mutable_cpu_data ( ) ) ; <nl> + CHECK_EQ ( this - > filler_param_ . sparse ( ) , - 1 ) <nl> + < < " Sparsity not supported by this Filler . " ; <nl> } <nl> } ; <nl> <nl> mmm a / include / caffe / vision_layers . hpp <nl> ppp b / include / caffe / vision_layers . hpp <nl> class SigmoidLayer : public NeuronLayer < Dtype > { <nl> const bool propagate_down , vector < Blob < Dtype > * > * bottom ) ; <nl> } ; <nl> <nl> + template < typename Dtype > <nl> + class SigmoidCrossEntropyLossLayer : public Layer < Dtype > { <nl> + public : <nl> + explicit SigmoidCrossEntropyLossLayer ( const LayerParameter & param ) <nl> + : Layer < Dtype > ( param ) , <nl> + sigmoid_layer_ ( new SigmoidLayer < Dtype > ( param ) ) , <nl> + sigmoid_output_ ( new Blob < Dtype > ( ) ) { } <nl> + virtual void SetUp ( const vector < Blob < Dtype > * > & bottom , <nl> + vector < Blob < Dtype > * > * top ) ; <nl> + <nl> + protected : <nl> + virtual Dtype Forward_cpu ( const vector < Blob < Dtype > * > & bottom , <nl> + vector < Blob < Dtype > * > * top ) ; <nl> + virtual Dtype Forward_gpu ( const vector < Blob < Dtype > * > & bottom , <nl> + vector < Blob < Dtype > * > * top ) ; <nl> + virtual void Backward_cpu ( const vector < Blob < Dtype > * > & top , <nl> + const bool propagate_down , vector < Blob < Dtype > * > * bottom ) ; <nl> + virtual void Backward_gpu ( const vector < Blob < Dtype > * > & top , <nl> + const bool propagate_down , vector < Blob < Dtype > * > * bottom ) ; <nl> + <nl> + shared_ptr < SigmoidLayer < Dtype > > sigmoid_layer_ ; <nl> + / / sigmoid_output stores the output of the sigmoid layer . <nl> + shared_ptr < Blob < Dtype > > sigmoid_output_ ; <nl> + / / Vector holders to call the underlying sigmoid layer forward and backward . <nl> + vector < Blob < Dtype > * > sigmoid_bottom_vec_ ; <nl> + vector < Blob < Dtype > * > sigmoid_top_vec_ ; <nl> + } ; <nl> + <nl> template < typename Dtype > <nl> class TanHLayer : public NeuronLayer < Dtype > { <nl> public : <nl> class DataLayer : public Layer < Dtype > { <nl> shared_ptr < Blob < Dtype > > prefetch_data_ ; <nl> shared_ptr < Blob < Dtype > > prefetch_label_ ; <nl> Blob < Dtype > data_mean_ ; <nl> + bool output_labels_ ; <nl> } ; <nl> <nl> template < typename Dtype > <nl> mmm a / src / caffe / layer_factory . cpp <nl> ppp b / src / caffe / layer_factory . cpp <nl> Layer < Dtype > * GetLayer ( const LayerParameter & param ) { <nl> return new ReLULayer < Dtype > ( param ) ; <nl> case LayerParameter_LayerType_SIGMOID : <nl> return new SigmoidLayer < Dtype > ( param ) ; <nl> + case LayerParameter_LayerType_SIGMOID_CROSS_ENTROPY_LOSS : <nl> + return new SigmoidCrossEntropyLossLayer < Dtype > ( param ) ; <nl> case LayerParameter_LayerType_SOFTMAX : <nl> return new SoftmaxLayer < Dtype > ( param ) ; <nl> case LayerParameter_LayerType_SOFTMAX_LOSS : <nl> mmm a / src / caffe / layers / data_layer . cpp <nl> ppp b / src / caffe / layers / data_layer . cpp <nl> <nl> <nl> # include " caffe / layer . hpp " <nl> # include " caffe / util / io . hpp " <nl> + # include " caffe / util / math_functions . hpp " <nl> # include " caffe / vision_layers . hpp " <nl> <nl> using std : : string ; <nl> void * DataLayerPrefetch ( void * layer_pointer ) { <nl> Datum datum ; <nl> CHECK ( layer - > prefetch_data_ ) ; <nl> Dtype * top_data = layer - > prefetch_data_ - > mutable_cpu_data ( ) ; <nl> - Dtype * top_label = layer - > prefetch_label_ - > mutable_cpu_data ( ) ; <nl> + Dtype * top_label ; <nl> + if ( layer - > output_labels_ ) { <nl> + top_label = layer - > prefetch_label_ - > mutable_cpu_data ( ) ; <nl> + } <nl> const Dtype scale = layer - > layer_param_ . data_param ( ) . scale ( ) ; <nl> const int batch_size = layer - > layer_param_ . data_param ( ) . batch_size ( ) ; <nl> const int crop_size = layer - > layer_param_ . data_param ( ) . crop_size ( ) ; <nl> void * DataLayerPrefetch ( void * layer_pointer ) { <nl> } <nl> } <nl> <nl> - top_label [ item_id ] = datum . label ( ) ; <nl> + if ( layer - > output_labels_ ) { <nl> + top_label [ item_id ] = datum . label ( ) ; <nl> + } <nl> / / go to the next iter <nl> layer - > iter_ - > Next ( ) ; <nl> if ( ! layer - > iter_ - > Valid ( ) ) { <nl> template < typename Dtype > <nl> void DataLayer < Dtype > : : SetUp ( const vector < Blob < Dtype > * > & bottom , <nl> vector < Blob < Dtype > * > * top ) { <nl> CHECK_EQ ( bottom . size ( ) , 0 ) < < " Data Layer takes no input blobs . " ; <nl> - CHECK_EQ ( top - > size ( ) , 2 ) < < " Data Layer takes two blobs as output . " ; <nl> + CHECK_GE ( top - > size ( ) , 1 ) < < " Data Layer takes at least one blob as output . " ; <nl> + CHECK_LE ( top - > size ( ) , 2 ) < < " Data Layer takes at most two blobs as output . " ; <nl> + if ( top - > size ( ) = = 1 ) { <nl> + output_labels_ = false ; <nl> + } else { <nl> + output_labels_ = true ; <nl> + } <nl> / / Initialize the leveldb <nl> leveldb : : DB * db_temp ; <nl> leveldb : : Options options ; <nl> void DataLayer < Dtype > : : SetUp ( const vector < Blob < Dtype > * > & bottom , <nl> < < ( * top ) [ 0 ] - > channels ( ) < < " , " < < ( * top ) [ 0 ] - > height ( ) < < " , " <nl> < < ( * top ) [ 0 ] - > width ( ) ; <nl> / / label <nl> - ( * top ) [ 1 ] - > Reshape ( this - > layer_param_ . data_param ( ) . batch_size ( ) , 1 , 1 , 1 ) ; <nl> - prefetch_label_ . reset ( <nl> - new Blob < Dtype > ( this - > layer_param_ . data_param ( ) . batch_size ( ) , 1 , 1 , 1 ) ) ; <nl> + if ( output_labels_ ) { <nl> + ( * top ) [ 1 ] - > Reshape ( this - > layer_param_ . data_param ( ) . batch_size ( ) , 1 , 1 , 1 ) ; <nl> + prefetch_label_ . reset ( <nl> + new Blob < Dtype > ( this - > layer_param_ . data_param ( ) . batch_size ( ) , 1 , 1 , 1 ) ) ; <nl> + } <nl> / / datum size <nl> datum_channels_ = datum . channels ( ) ; <nl> datum_height_ = datum . height ( ) ; <nl> void DataLayer < Dtype > : : SetUp ( const vector < Blob < Dtype > * > & bottom , <nl> / / simultaneous cudaMalloc calls when the main thread is running . In some <nl> / / GPUs this seems to cause failures if we do not so . <nl> prefetch_data_ - > mutable_cpu_data ( ) ; <nl> - prefetch_label_ - > mutable_cpu_data ( ) ; <nl> + if ( output_labels_ ) { <nl> + prefetch_label_ - > mutable_cpu_data ( ) ; <nl> + } <nl> data_mean_ . cpu_data ( ) ; <nl> DLOG ( INFO ) < < " Initializing prefetch " ; <nl> CHECK ( ! pthread_create ( & thread_ , NULL , DataLayerPrefetch < Dtype > , <nl> Dtype DataLayer < Dtype > : : Forward_cpu ( const vector < Blob < Dtype > * > & bottom , <nl> / / First , join the thread <nl> CHECK ( ! pthread_join ( thread_ , NULL ) ) < < " Pthread joining failed . " ; <nl> / / Copy the data <nl> - memcpy ( ( * top ) [ 0 ] - > mutable_cpu_data ( ) , prefetch_data_ - > cpu_data ( ) , <nl> - sizeof ( Dtype ) * prefetch_data_ - > count ( ) ) ; <nl> - memcpy ( ( * top ) [ 1 ] - > mutable_cpu_data ( ) , prefetch_label_ - > cpu_data ( ) , <nl> - sizeof ( Dtype ) * prefetch_label_ - > count ( ) ) ; <nl> + caffe_copy ( prefetch_data_ - > count ( ) , prefetch_data_ - > cpu_data ( ) , <nl> + ( * top ) [ 0 ] - > mutable_cpu_data ( ) ) ; <nl> + if ( output_labels_ ) { <nl> + caffe_copy ( prefetch_label_ - > count ( ) , prefetch_label_ - > cpu_data ( ) , <nl> + ( * top ) [ 1 ] - > mutable_cpu_data ( ) ) ; <nl> + } <nl> / / Start a new prefetch thread <nl> CHECK ( ! pthread_create ( & thread_ , NULL , DataLayerPrefetch < Dtype > , <nl> reinterpret_cast < void * > ( this ) ) ) < < " Pthread execution failed . " ; <nl> mmm a / src / caffe / layers / data_layer . cu <nl> ppp b / src / caffe / layers / data_layer . cu <nl> Dtype DataLayer < Dtype > : : Forward_gpu ( const vector < Blob < Dtype > * > & bottom , <nl> CUDA_CHECK ( cudaMemcpy ( ( * top ) [ 0 ] - > mutable_gpu_data ( ) , <nl> prefetch_data_ - > cpu_data ( ) , sizeof ( Dtype ) * prefetch_data_ - > count ( ) , <nl> cudaMemcpyHostToDevice ) ) ; <nl> - CUDA_CHECK ( cudaMemcpy ( ( * top ) [ 1 ] - > mutable_gpu_data ( ) , <nl> - prefetch_label_ - > cpu_data ( ) , sizeof ( Dtype ) * prefetch_label_ - > count ( ) , <nl> - cudaMemcpyHostToDevice ) ) ; <nl> + if ( output_labels_ ) { <nl> + CUDA_CHECK ( cudaMemcpy ( ( * top ) [ 1 ] - > mutable_gpu_data ( ) , <nl> + prefetch_label_ - > cpu_data ( ) , sizeof ( Dtype ) * prefetch_label_ - > count ( ) , <nl> + cudaMemcpyHostToDevice ) ) ; <nl> + } <nl> / / Start a new prefetch thread <nl> CHECK ( ! pthread_create ( & thread_ , NULL , DataLayerPrefetch < Dtype > , <nl> reinterpret_cast < void * > ( this ) ) ) < < " Pthread execution failed . " ; <nl> new file mode 100644 <nl> index 00000000000 . . f2186d65c16 <nl> mmm / dev / null <nl> ppp b / src / caffe / layers / sigmoid_cross_entropy_loss_layer . cpp <nl> <nl> + / / Copyright 2014 BVLC and contributors . <nl> + <nl> + # include < algorithm > <nl> + # include < cfloat > <nl> + # include < vector > <nl> + <nl> + # include " caffe / layer . hpp " <nl> + # include " caffe / vision_layers . hpp " <nl> + # include " caffe / util / math_functions . hpp " <nl> + <nl> + using std : : max ; <nl> + <nl> + namespace caffe { <nl> + <nl> + template < typename Dtype > <nl> + void SigmoidCrossEntropyLossLayer < Dtype > : : SetUp ( <nl> + const vector < Blob < Dtype > * > & bottom , vector < Blob < Dtype > * > * top ) { <nl> + CHECK_EQ ( bottom . size ( ) , 2 ) < < <nl> + " SigmoidCrossEntropyLoss Layer takes two blobs as input . " ; <nl> + CHECK_EQ ( top - > size ( ) , 0 ) < < <nl> + " SigmoidCrossEntropyLoss Layer takes no blob as output . " ; <nl> + sigmoid_bottom_vec_ . clear ( ) ; <nl> + sigmoid_bottom_vec_ . push_back ( bottom [ 0 ] ) ; <nl> + sigmoid_top_vec_ . clear ( ) ; <nl> + sigmoid_top_vec_ . push_back ( sigmoid_output_ . get ( ) ) ; <nl> + sigmoid_layer_ - > SetUp ( sigmoid_bottom_vec_ , & sigmoid_top_vec_ ) ; <nl> + } <nl> + <nl> + template < typename Dtype > <nl> + Dtype SigmoidCrossEntropyLossLayer < Dtype > : : Forward_cpu ( <nl> + const vector < Blob < Dtype > * > & bottom , vector < Blob < Dtype > * > * top ) { <nl> + / / The forward pass computes the sigmoid outputs . <nl> + sigmoid_bottom_vec_ [ 0 ] = bottom [ 0 ] ; <nl> + sigmoid_layer_ - > Forward ( sigmoid_bottom_vec_ , & sigmoid_top_vec_ ) ; <nl> + / / Compute the loss ( negative log likelihood ) <nl> + int count = bottom [ 0 ] - > count ( ) ; <nl> + int num = bottom [ 0 ] - > num ( ) ; <nl> + / / Stable version of loss computation from input data <nl> + const Dtype * input_data = bottom [ 0 ] - > cpu_data ( ) ; <nl> + const Dtype * ground_truth = bottom [ 1 ] - > cpu_data ( ) ; <nl> + Dtype loss = 0 ; <nl> + for ( int i = 0 ; i < count ; + + i ) { <nl> + loss - = input_data [ i ] * ( ground_truth [ i ] - ( input_data [ i ] > = 0 ) ) - <nl> + log ( 1 + exp ( input_data [ i ] - 2 * input_data [ i ] * ( input_data [ i ] > = 0 ) ) ) ; <nl> + } <nl> + return loss / num ; <nl> + } <nl> + <nl> + template < typename Dtype > <nl> + void SigmoidCrossEntropyLossLayer < Dtype > : : Backward_cpu ( <nl> + const vector < Blob < Dtype > * > & top , const bool propagate_down , <nl> + vector < Blob < Dtype > * > * bottom ) { <nl> + / / First , compute the diff <nl> + int count = ( * bottom ) [ 0 ] - > count ( ) ; <nl> + int num = ( * bottom ) [ 0 ] - > num ( ) ; <nl> + const Dtype * sigmoid_output_data = sigmoid_output_ - > cpu_data ( ) ; <nl> + const Dtype * ground_truth = ( * bottom ) [ 1 ] - > cpu_data ( ) ; <nl> + Dtype * bottom_diff = ( * bottom ) [ 0 ] - > mutable_cpu_diff ( ) ; <nl> + caffe_sub ( count , sigmoid_output_data , ground_truth , bottom_diff ) ; <nl> + / / Scale down gradient <nl> + caffe_scal ( count , Dtype ( 1 ) / num , bottom_diff ) ; <nl> + } <nl> + <nl> + INSTANTIATE_CLASS ( SigmoidCrossEntropyLossLayer ) ; <nl> + <nl> + <nl> + } / / namespace caffe <nl> new file mode 100644 <nl> index 00000000000 . . 64bc476b00f <nl> mmm / dev / null <nl> ppp b / src / caffe / layers / sigmoid_cross_entropy_loss_layer . cu <nl> <nl> + / / Copyright 2014 BVLC and contributors . <nl> + <nl> + # include < algorithm > <nl> + # include < cfloat > <nl> + # include < vector > <nl> + <nl> + # include " caffe / layer . hpp " <nl> + # include " caffe / vision_layers . hpp " <nl> + # include " caffe / util / math_functions . hpp " <nl> + <nl> + using std : : max ; <nl> + <nl> + namespace caffe { <nl> + <nl> + template < typename Dtype > <nl> + Dtype SigmoidCrossEntropyLossLayer < Dtype > : : Forward_gpu ( <nl> + const vector < Blob < Dtype > * > & bottom , vector < Blob < Dtype > * > * top ) { <nl> + / / The forward pass computes the sigmoid outputs . <nl> + sigmoid_bottom_vec_ [ 0 ] = bottom [ 0 ] ; <nl> + sigmoid_layer_ - > Forward ( sigmoid_bottom_vec_ , & sigmoid_top_vec_ ) ; <nl> + / / Compute the loss ( negative log likelihood ) <nl> + int count = bottom [ 0 ] - > count ( ) ; <nl> + int num = bottom [ 0 ] - > num ( ) ; <nl> + / / Stable version of loss computation from input data <nl> + const Dtype * input_data = bottom [ 0 ] - > cpu_data ( ) ; <nl> + const Dtype * ground_truth = bottom [ 1 ] - > cpu_data ( ) ; <nl> + Dtype loss = 0 ; <nl> + for ( int i = 0 ; i < count ; + + i ) { <nl> + loss - = input_data [ i ] * ( ground_truth [ i ] - ( input_data [ i ] > = 0 ) ) - <nl> + log ( 1 + exp ( input_data [ i ] - 2 * input_data [ i ] * ( input_data [ i ] > = 0 ) ) ) ; <nl> + } <nl> + return loss / num ; <nl> + } <nl> + <nl> + template < typename Dtype > <nl> + void SigmoidCrossEntropyLossLayer < Dtype > : : Backward_gpu ( <nl> + const vector < Blob < Dtype > * > & top , const bool propagate_down , <nl> + vector < Blob < Dtype > * > * bottom ) { <nl> + / / First , compute the diff <nl> + int count = ( * bottom ) [ 0 ] - > count ( ) ; <nl> + int num = ( * bottom ) [ 0 ] - > num ( ) ; <nl> + const Dtype * sigmoid_output_data = sigmoid_output_ - > gpu_data ( ) ; <nl> + const Dtype * ground_truth = ( * bottom ) [ 1 ] - > gpu_data ( ) ; <nl> + Dtype * bottom_diff = ( * bottom ) [ 0 ] - > mutable_gpu_diff ( ) ; <nl> + caffe_gpu_copy ( count , sigmoid_output_data , bottom_diff ) ; <nl> + caffe_gpu_axpy ( count , Dtype ( - 1 ) , ground_truth , bottom_diff ) ; <nl> + / / Scale down gradient <nl> + caffe_gpu_scal ( count , Dtype ( 1 ) / num , bottom_diff ) ; <nl> + } <nl> + <nl> + INSTANTIATE_CLASS ( SigmoidCrossEntropyLossLayer ) ; <nl> + <nl> + <nl> + } / / namespace caffe <nl> mmm a / src / caffe / proto / caffe . proto <nl> ppp b / src / caffe / proto / caffe . proto <nl> message FillerParameter { <nl> optional float value = 2 [ default = 0 ] ; / / the value in constant filler <nl> optional float min = 3 [ default = 0 ] ; / / the min value in uniform filler <nl> optional float max = 4 [ default = 1 ] ; / / the max value in uniform filler <nl> - optional float mean = 5 [ default = 0 ] ; / / the mean value in gaussian filler <nl> - optional float std = 6 [ default = 1 ] ; / / the std value in gaussian filler <nl> + optional float mean = 5 [ default = 0 ] ; / / the mean value in Gaussian filler <nl> + optional float std = 6 [ default = 1 ] ; / / the std value in Gaussian filler <nl> + / / The expected number of non - zero input weights for a given output in <nl> + / / Gaussian filler - - the default - 1 means don ' t perform sparsification . <nl> + optional int32 sparse = 7 [ default = - 1 ] ; <nl> } <nl> <nl> message NetParameter { <nl> message SolverParameter { <nl> optional int32 test_iter = 3 [ default = 0 ] ; <nl> / / The number of iterations between two testing phases . <nl> optional int32 test_interval = 4 [ default = 0 ] ; <nl> + optional bool test_compute_loss = 19 [ default = false ] ; <nl> optional float base_lr = 5 ; / / The base learning rate <nl> / / the number of iterations between displaying info . If display = 0 , no info <nl> / / will be displayed . <nl> message LayerParameter { <nl> / / line above the enum . Update the next available ID when you add a new <nl> / / LayerType . <nl> / / <nl> - / / LayerType next available ID : 27 <nl> + / / LayerType next available ID : 28 <nl> enum LayerType { <nl> / / " NONE " layer type is 0th enum element so that we don ' t cause confusion <nl> / / by defaulting to an existent LayerType ( instead , should usually error if <nl> message LayerParameter { <nl> POWER = 26 ; <nl> RELU = 18 ; <nl> SIGMOID = 19 ; <nl> + SIGMOID_CROSS_ENTROPY_LOSS = 27 ; <nl> SOFTMAX = 20 ; <nl> SOFTMAX_LOSS = 21 ; <nl> SPLIT = 22 ; <nl> mmm a / src / caffe / solver . cpp <nl> ppp b / src / caffe / solver . cpp <nl> void Solver < Dtype > : : Test ( ) { <nl> CHECK_NOTNULL ( test_net_ . get ( ) ) - > CopyTrainedLayersFrom ( net_param ) ; <nl> vector < Dtype > test_score ; <nl> vector < Blob < Dtype > * > bottom_vec ; <nl> + Dtype loss = 0 ; <nl> for ( int i = 0 ; i < param_ . test_iter ( ) ; + + i ) { <nl> + Dtype iter_loss ; <nl> const vector < Blob < Dtype > * > & result = <nl> - test_net_ - > Forward ( bottom_vec ) ; <nl> + test_net_ - > Forward ( bottom_vec , & iter_loss ) ; <nl> + if ( param_ . test_compute_loss ( ) ) { <nl> + loss + = iter_loss ; <nl> + } <nl> if ( i = = 0 ) { <nl> for ( int j = 0 ; j < result . size ( ) ; + + j ) { <nl> const Dtype * result_vec = result [ j ] - > cpu_data ( ) ; <nl> void Solver < Dtype > : : Test ( ) { <nl> } <nl> } <nl> } <nl> + if ( param_ . test_compute_loss ( ) ) { <nl> + loss / = param_ . test_iter ( ) ; <nl> + LOG ( INFO ) < < " Test loss : " < < loss ; <nl> + } <nl> for ( int i = 0 ; i < test_score . size ( ) ; + + i ) { <nl> LOG ( INFO ) < < " Test score # " < < i < < " : " <nl> < < test_score [ i ] / param_ . test_iter ( ) ; <nl> new file mode 100644 <nl> index 00000000000 . . fe899d43d53 <nl> mmm / dev / null <nl> ppp b / src / caffe / test / test_sigmoid_cross_entropy_loss_layer . cpp <nl> <nl> + / / Copyright 2014 BVLC and contributors . <nl> + <nl> + # include < cmath > <nl> + # include < cstdlib > <nl> + # include < cstring > <nl> + # include < vector > <nl> + <nl> + # include " gtest / gtest . h " <nl> + # include " caffe / blob . hpp " <nl> + # include " caffe / common . hpp " <nl> + # include " caffe / filler . hpp " <nl> + # include " caffe / vision_layers . hpp " <nl> + # include " caffe / test / test_gradient_check_util . hpp " <nl> + <nl> + # include " caffe / test / test_caffe_main . hpp " <nl> + <nl> + namespace caffe { <nl> + <nl> + extern cudaDeviceProp CAFFE_TEST_CUDA_PROP ; <nl> + <nl> + template < typename Dtype > <nl> + class SigmoidCrossEntropyLossLayerTest : public : : testing : : Test { <nl> + protected : <nl> + SigmoidCrossEntropyLossLayerTest ( ) <nl> + : blob_bottom_data_ ( new Blob < Dtype > ( 10 , 5 , 1 , 1 ) ) , <nl> + blob_bottom_targets_ ( new Blob < Dtype > ( 10 , 5 , 1 , 1 ) ) { <nl> + / / Fill the data vector <nl> + FillerParameter data_filler_param ; <nl> + data_filler_param . set_std ( 10 ) ; <nl> + GaussianFiller < Dtype > data_filler ( data_filler_param ) ; <nl> + data_filler . Fill ( blob_bottom_data_ ) ; <nl> + blob_bottom_vec_ . push_back ( blob_bottom_data_ ) ; <nl> + / / Fill the targets vector <nl> + FillerParameter targets_filler_param ; <nl> + targets_filler_param . set_min ( 0 . 0 ) ; <nl> + targets_filler_param . set_max ( 1 . 0 ) ; <nl> + UniformFiller < Dtype > targets_filler ( targets_filler_param ) ; <nl> + targets_filler . Fill ( blob_bottom_targets_ ) ; <nl> + blob_bottom_vec_ . push_back ( blob_bottom_targets_ ) ; <nl> + } <nl> + virtual ~ SigmoidCrossEntropyLossLayerTest ( ) { <nl> + delete blob_bottom_data_ ; <nl> + delete blob_bottom_targets_ ; <nl> + } <nl> + Blob < Dtype > * const blob_bottom_data_ ; <nl> + Blob < Dtype > * const blob_bottom_targets_ ; <nl> + vector < Blob < Dtype > * > blob_bottom_vec_ ; <nl> + vector < Blob < Dtype > * > blob_top_vec_ ; <nl> + } ; <nl> + <nl> + typedef : : testing : : Types < float , double > Dtypes ; <nl> + TYPED_TEST_CASE ( SigmoidCrossEntropyLossLayerTest , Dtypes ) ; <nl> + <nl> + <nl> + TYPED_TEST ( SigmoidCrossEntropyLossLayerTest , TestGradientCPU ) { <nl> + LayerParameter layer_param ; <nl> + Caffe : : set_mode ( Caffe : : CPU ) ; <nl> + SigmoidCrossEntropyLossLayer < TypeParam > layer ( layer_param ) ; <nl> + layer . SetUp ( this - > blob_bottom_vec_ , & this - > blob_top_vec_ ) ; <nl> + GradientChecker < TypeParam > checker ( 1e - 2 , 1e - 2 , 1701 ) ; <nl> + checker . CheckGradientSingle ( & layer , & ( this - > blob_bottom_vec_ ) , <nl> + & ( this - > blob_top_vec_ ) , 0 , - 1 , - 1 ) ; <nl> + } <nl> + <nl> + TYPED_TEST ( SigmoidCrossEntropyLossLayerTest , TestGradientGPU ) { <nl> + LayerParameter layer_param ; <nl> + Caffe : : set_mode ( Caffe : : GPU ) ; <nl> + SigmoidCrossEntropyLossLayer < TypeParam > layer ( layer_param ) ; <nl> + layer . SetUp ( this - > blob_bottom_vec_ , & this - > blob_top_vec_ ) ; <nl> + GradientChecker < TypeParam > checker ( 1e - 2 , 1e - 2 , 1701 ) ; <nl> + checker . CheckGradientSingle ( & layer , & ( this - > blob_bottom_vec_ ) , <nl> + & ( this - > blob_top_vec_ ) , 0 , - 1 , - 1 ) ; <nl> + } <nl> + <nl> + <nl> + } / / namespace caffe <nl> | Merge pull request from jeffdonahue / mnist - autoencoder - example | BVLC/caffe | 2dad9ca76268ce4cf64f4c52733b74991063131f | 2014-04-16T15:46:49Z |
mmm a / tensorflow / core / grappler / optimizers / data / auto_shard . cc <nl> ppp b / tensorflow / core / grappler / optimizers / data / auto_shard . cc <nl> limitations under the License . <nl> <nl> # include " absl / container / flat_hash_map . h " <nl> # include " absl / container / flat_hash_set . h " <nl> + # include " tensorflow / core / framework / attr_value . pb . h " <nl> # include " tensorflow / core / framework / function . h " <nl> # include " tensorflow / core / framework / function . pb . h " <nl> # include " tensorflow / core / framework / node_def . pb . h " <nl> Status AddShardNode ( MutableGraphView * graph , const NodeDef & add_before , <nl> return Status : : OK ( ) ; <nl> } <nl> <nl> + Status AddShuffleNode ( MutableGraphView * graph , const NodeDef & add_before , <nl> + const string & buffer_node ) { <nl> + NodeDef * add_after = graph - > GetNode ( add_before . input ( 0 ) ) ; <nl> + <nl> + NodeDef new_node ; <nl> + new_node . set_op ( kShuffleDatasetOpName ) ; <nl> + graph_utils : : SetUniqueGraphNodeName ( kShuffleDatasetOpName , graph - > graph ( ) , <nl> + & new_node ) ; <nl> + <nl> + NodeDef * seed = graph_utils : : AddScalarConstNode < int64 > ( 1 , graph ) ; <nl> + NodeDef * seed2 = graph_utils : : AddScalarConstNode < int64 > ( 2 , graph ) ; <nl> + AttrValue reshuffle ; <nl> + reshuffle . set_b ( false ) ; <nl> + <nl> + new_node . add_input ( add_before . input ( 0 ) ) ; <nl> + new_node . add_input ( buffer_node ) ; <nl> + new_node . add_input ( seed - > name ( ) ) ; <nl> + new_node . add_input ( seed2 - > name ( ) ) ; <nl> + <nl> + graph_utils : : CopyAttribute ( " output_shapes " , * add_after , & new_node ) ; <nl> + graph_utils : : CopyAttribute ( " output_types " , * add_after , & new_node ) ; <nl> + ( * new_node . mutable_attr ( ) ) [ " reshuffle_each_iteration " ] = reshuffle ; <nl> + <nl> + NodeDef * new_node_graph = graph - > AddNode ( std : : move ( new_node ) ) ; <nl> + <nl> + TF_RETURN_IF_ERROR ( <nl> + graph - > UpdateFanouts ( add_after - > name ( ) , new_node_graph - > name ( ) ) ) ; <nl> + return Status : : OK ( ) ; <nl> + } <nl> + <nl> bool ReaderOpInFunction ( const NodeDef & node , <nl> const FunctionLibraryDefinition & flib ) { <nl> const FunctionDef * func = flib . Find ( node . attr ( ) . at ( " f " ) . func ( ) . name ( ) ) ; <nl> bool ReaderOpInFunction ( const NodeDef & node , <nl> } <nl> <nl> Status RemoveShuffleDataset ( MutableGraphView * graph , const NodeDef & node , <nl> - absl : : flat_hash_set < string > * nodes_to_delete ) { <nl> + absl : : flat_hash_set < string > * nodes_to_delete , <nl> + bool * shuffle_removed , <nl> + string * buffer_size_node_name ) { <nl> if ( node . op ( ) = = kShuffleDatasetOpName ) { <nl> + * shuffle_removed = true ; <nl> + * buffer_size_node_name = node . input ( 1 ) ; <nl> TF_RETURN_IF_ERROR ( graph - > UpdateFanouts ( node . name ( ) , node . input ( 0 ) ) ) ; <nl> nodes_to_delete - > insert ( node . name ( ) ) ; <nl> } <nl> <nl> for ( const auto & fanin : graph - > GetFanins ( node , true ) ) { <nl> - TF_RETURN_IF_ERROR ( <nl> - RemoveShuffleDataset ( graph , * fanin . node , nodes_to_delete ) ) ; <nl> + TF_RETURN_IF_ERROR ( RemoveShuffleDataset ( graph , * fanin . node , nodes_to_delete , <nl> + shuffle_removed , <nl> + buffer_size_node_name ) ) ; <nl> } <nl> <nl> / / TODO ( frankchn ) : Traverse functions too . <nl> return Status : : OK ( ) ; <nl> } <nl> <nl> + Status ProcessDatasetSourceNode ( MutableGraphView * graph , const NodeDef & node , <nl> + absl : : flat_hash_set < string > * nodes_to_delete , <nl> + int64 num_workers , int64 index ) { <nl> + bool shuffle_removed = false ; <nl> + string buffer_size_node_name = " " ; <nl> + <nl> + TF_RETURN_IF_ERROR ( AddShardNode ( graph , node , num_workers , index ) ) ; <nl> + TF_RETURN_IF_ERROR ( RemoveShuffleDataset ( <nl> + graph , node , nodes_to_delete , & shuffle_removed , & buffer_size_node_name ) ) ; <nl> + <nl> + if ( shuffle_removed ) { <nl> + TF_RETURN_IF_ERROR ( AddShuffleNode ( graph , node , buffer_size_node_name ) ) ; <nl> + } <nl> + <nl> + return Status : : OK ( ) ; <nl> + } <nl> + <nl> Status RecursivelyHandleOp ( const NodeDef & node , int64 num_workers , int64 index , <nl> FunctionLibraryDefinition * flib , <nl> MutableGraphView * graph , <nl> Status RecursivelyHandleOp ( const NodeDef & node , int64 num_workers , int64 index , <nl> / / function in flat_map . <nl> if ( IsDatasetNodeOfType ( node , kFuncDatasetOps ) & & <nl> ReaderOpInFunction ( node , * flib ) ) { <nl> - TF_RETURN_IF_ERROR ( AddShardNode ( graph , node , num_workers , index ) ) ; <nl> - TF_RETURN_IF_ERROR ( RemoveShuffleDataset ( graph , node , nodes_to_delete ) ) ; <nl> + TF_RETURN_IF_ERROR ( ProcessDatasetSourceNode ( graph , node , nodes_to_delete , <nl> + num_workers , index ) ) ; <nl> return Status : : OK ( ) ; <nl> } <nl> <nl> if ( IsDatasetNodeOfType ( node , kReaderDatasetOps ) ) { <nl> / / We reached a reader dataset directly and we try to shard input 0 . <nl> - TF_RETURN_IF_ERROR ( AddShardNode ( graph , node , num_workers , index ) ) ; <nl> - TF_RETURN_IF_ERROR ( RemoveShuffleDataset ( graph , node , nodes_to_delete ) ) ; <nl> + TF_RETURN_IF_ERROR ( ProcessDatasetSourceNode ( graph , node , nodes_to_delete , <nl> + num_workers , index ) ) ; <nl> return Status : : OK ( ) ; <nl> } <nl> <nl> mmm a / tensorflow / core / kernels / data / reader_dataset_ops . cc <nl> ppp b / tensorflow / core / kernels / data / reader_dataset_ops . cc <nl> class TFRecordDatasetOp : public DatasetOpKernel { <nl> std : : vector < string > filenames ; <nl> filenames . reserve ( filenames_tensor - > NumElements ( ) ) ; <nl> for ( int i = 0 ; i < filenames_tensor - > NumElements ( ) ; + + i ) { <nl> + VLOG ( 2 ) < < " Reading file : " < < filenames_tensor - > flat < string > ( ) ( i ) ; <nl> filenames . push_back ( filenames_tensor - > flat < string > ( ) ( i ) ) ; <nl> } <nl> <nl> mmm a / tensorflow / python / data / experimental / kernel_tests / auto_shard_dataset_test . py <nl> ppp b / tensorflow / python / data / experimental / kernel_tests / auto_shard_dataset_test . py <nl> def setUp ( self ) : <nl> self . _num_records = 10 <nl> self . test_filenames = self . _createFiles ( ) <nl> <nl> - def testFlatMapReaderPipeline ( self ) : <nl> - dataset = dataset_ops . Dataset . list_files ( self . test_filenames , shuffle = True ) <nl> + def assertDatasetProducesWithShuffle ( self , dataset , expected , batch , <nl> + num_examples , shuffle ) : <nl> + if shuffle : <nl> + actual = [ ] <nl> + next_fn = self . getNext ( dataset ) <nl> + for _ in range ( num_examples ) : <nl> + elem = self . evaluate ( next_fn ( ) ) <nl> + if isinstance ( elem , tuple ) : <nl> + actual . extend ( elem ) <nl> + else : <nl> + actual . extend ( elem . tolist ( ) ) <nl> + <nl> + self . assertCountEqual ( actual , expected ) <nl> + with self . assertRaises ( errors . OutOfRangeError ) : <nl> + self . evaluate ( next_fn ( ) ) <nl> + else : <nl> + self . assertDatasetProduces ( dataset , list ( chunk ( expected , batch ) ) ) <nl> + <nl> + @ parameterized . parameters ( True , False ) <nl> + def testFlatMapReaderPipeline ( self , shuffle ) : <nl> + dataset = dataset_ops . Dataset . list_files ( <nl> + self . test_filenames , shuffle = shuffle ) <nl> dataset = dataset . flat_map ( core_readers . TFRecordDataset ) <nl> dataset = dataset . batch ( 5 ) <nl> dataset = distribute . _AutoShardDataset ( dataset , 5 , 3 ) <nl> def testFlatMapReaderPipeline ( self ) : <nl> for f in ( 3 , 8 ) <nl> for r in range ( 0 , 10 ) <nl> ] <nl> - self . assertDatasetProduces ( dataset , list ( chunk ( expected , 5 ) ) ) <nl> + self . assertDatasetProducesWithShuffle ( dataset , expected , 5 , 4 , shuffle ) <nl> <nl> def testZipReaderPipeline ( self ) : <nl> - dataset1 = dataset_ops . Dataset . list_files ( self . test_filenames , shuffle = True ) <nl> + dataset1 = dataset_ops . Dataset . list_files ( <nl> + self . test_filenames , shuffle = False ) <nl> dataset1 = dataset1 . apply ( <nl> interleave_ops . parallel_interleave ( core_readers . TFRecordDataset , 10 ) ) <nl> - dataset2 = dataset_ops . Dataset . list_files ( self . test_filenames , shuffle = True ) <nl> + dataset2 = dataset_ops . Dataset . list_files ( <nl> + self . test_filenames , shuffle = False ) <nl> dataset2 = dataset2 . apply ( <nl> interleave_ops . parallel_interleave ( core_readers . TFRecordDataset , 10 ) ) <nl> <nl> def testZipReaderPipeline ( self ) : <nl> <nl> self . assertDatasetProduces ( dataset , expected ) <nl> <nl> - def testConcatenateReaderPipeline ( self ) : <nl> - dataset1 = dataset_ops . Dataset . list_files ( self . test_filenames , shuffle = True ) <nl> + @ parameterized . parameters ( True , False ) <nl> + def testConcatenateReaderPipeline ( self , shuffle ) : <nl> + dataset1 = dataset_ops . Dataset . list_files ( <nl> + self . test_filenames , shuffle = shuffle ) <nl> dataset1 = dataset1 . apply ( <nl> interleave_ops . parallel_interleave ( core_readers . TFRecordDataset , 10 ) ) <nl> dataset1 = dataset1 . batch ( 5 ) <nl> - dataset2 = dataset_ops . Dataset . list_files ( self . test_filenames , shuffle = True ) <nl> + dataset2 = dataset_ops . Dataset . list_files ( <nl> + self . test_filenames , shuffle = shuffle ) <nl> dataset2 = dataset2 . apply ( <nl> interleave_ops . parallel_interleave ( core_readers . TFRecordDataset , 10 ) ) <nl> dataset2 = dataset2 . batch ( 5 ) <nl> def testConcatenateReaderPipeline ( self ) : <nl> for f in ( 3 , 8 ) <nl> ] <nl> expected + = expected <nl> - self . assertDatasetProduces ( dataset , list ( chunk ( expected , 5 ) ) ) <nl> + self . assertDatasetProducesWithShuffle ( dataset , expected , 5 , 8 , shuffle ) <nl> <nl> - def testPipelineWithMap ( self ) : <nl> - dataset = dataset_ops . Dataset . list_files ( self . test_filenames , shuffle = True ) <nl> + @ parameterized . parameters ( True , False ) <nl> + def testPipelineWithMap ( self , shuffle ) : <nl> + dataset = dataset_ops . Dataset . list_files ( self . test_filenames , shuffle = False ) <nl> dataset = dataset . apply ( <nl> interleave_ops . parallel_interleave ( core_readers . TFRecordDataset , 10 ) ) <nl> dataset = dataset . map ( lambda x : string_ops . substr_v2 ( x , 2 , 1000 ) ) <nl> def testPipelineWithMap ( self ) : <nl> for r in range ( 0 , 10 ) <nl> for f in ( 3 , 8 ) <nl> ] <nl> - self . assertDatasetProduces ( dataset , list ( chunk ( expected , 5 ) ) ) <nl> + self . assertDatasetProducesWithShuffle ( dataset , expected , 5 , 4 , shuffle ) <nl> <nl> - def testValidPipelineWithRangeDataset ( self ) : <nl> + @ parameterized . parameters ( True , False ) <nl> + def testValidPipelineWithRangeDataset ( self , shuffle ) : <nl> dataset = dataset_ops . Dataset . range ( self . _num_files ) <nl> dataset = dataset . map ( lambda n : string_ops . string_join ( # pylint : disable = g - long - lambda <nl> [ self . get_temp_dir ( ) , <nl> def testValidPipelineWithRangeDataset ( self ) : <nl> for r in range ( 0 , 10 ) <nl> for f in ( 3 , 8 ) <nl> ] <nl> - self . assertDatasetProduces ( dataset , list ( chunk ( expected , 5 ) ) ) <nl> + self . assertDatasetProducesWithShuffle ( dataset , expected , 5 , 4 , shuffle ) <nl> <nl> @ parameterized . parameters ( ( 1 , 0 , 10 , 10 ) , ( 2 , 1 , 20 , 5 ) , ( 10 , 1 , 1 , 10 ) ) <nl> def testStandardReaderPipeline ( self , num_epochs , index , batch_size , <nl> def testStandardReaderPipeline ( self , num_epochs , index , batch_size , <nl> with self . assertRaises ( errors . OutOfRangeError ) : <nl> self . evaluate ( outputs ( ) ) <nl> <nl> - def testSampleResNetPipeline ( self ) : <nl> - dataset = dataset_ops . Dataset . list_files ( self . test_filenames , shuffle = True ) <nl> + @ parameterized . parameters ( True , False ) <nl> + def testSampleResNetPipeline ( self , shuffle ) : <nl> + dataset = dataset_ops . Dataset . list_files ( <nl> + self . test_filenames , shuffle = shuffle ) <nl> dataset = dataset . apply ( <nl> interleave_ops . parallel_interleave ( core_readers . TFRecordDataset , 10 ) ) <nl> dataset = dataset . batch ( 5 ) <nl> def testSampleResNetPipeline ( self ) : <nl> for r in range ( 0 , 10 ) <nl> for f in ( 3 , 8 ) <nl> ] <nl> - self . assertDatasetProduces ( dataset , list ( chunk ( expected , 5 ) ) ) <nl> + self . assertDatasetProducesWithShuffle ( dataset , expected , 5 , 4 , shuffle ) <nl> <nl> def testWorkersGreaterThanNumFiles ( self ) : <nl> - dataset = dataset_ops . Dataset . list_files ( self . test_filenames , shuffle = True ) <nl> + dataset = dataset_ops . Dataset . list_files ( self . test_filenames ) <nl> dataset = dataset . apply ( <nl> interleave_ops . parallel_interleave ( core_readers . TFRecordDataset , 10 ) ) <nl> dataset = dataset . batch ( 5 ) <nl> def testNoReaderPipelines ( self ) : <nl> self . evaluate ( self . getNext ( dataset ) ( ) ) <nl> <nl> def testUnsupportedOpInPipeline ( self ) : <nl> - dataset = dataset_ops . Dataset . list_files ( self . test_filenames , shuffle = True ) <nl> + dataset = dataset_ops . Dataset . list_files ( self . test_filenames ) <nl> dataset = dataset . flat_map ( core_readers . TFRecordDataset ) <nl> dataset = dataset . batch ( 5 ) <nl> dataset = dataset . apply ( unique . unique ( ) ) <nl> def testUnsupportedOpInPipeline ( self ) : <nl> self . evaluate ( self . getNext ( dataset ) ( ) ) <nl> <nl> def testInvalidWorkerIndex ( self ) : <nl> - dataset = dataset_ops . Dataset . list_files ( self . test_filenames , shuffle = True ) <nl> + dataset = dataset_ops . Dataset . list_files ( self . test_filenames ) <nl> dataset = dataset . flat_map ( core_readers . TFRecordDataset ) <nl> dataset = dataset . batch ( 5 ) <nl> <nl> | Add handling of shuffle = True in list_files by re - adding a ShuffleDataset node after the shard | tensorflow/tensorflow | 30892d7cac0f95b42e6fcffdccb3c40b2fc88736 | 2019-03-27T23:36:27Z |
mmm a / brightray / brightray . gyp <nl> ppp b / brightray / brightray . gyp <nl> <nl> [ ' OS = = " win " ' , { <nl> ' conditions ' : [ <nl> [ ' libchromiumcontent_component ' , { <nl> - # sandbox , base_static , devtools_discovery , devtools_http_handler , <nl> - # http_server are always linked statically . <nl> ' link_settings ' : { <nl> ' libraries ' : [ <nl> + # Needed by desktop_capture . lib : <nl> + ' - ld3d11 . lib ' , <nl> + # Following libs are always linked statically . <nl> ' < ( libchromiumcontent_dir ) / base_static . lib ' , <nl> ' < ( libchromiumcontent_dir ) / sandbox . lib ' , <nl> ' < ( libchromiumcontent_dir ) / sandbox_helper_win . lib ' , <nl> mmm a / brightray / browser / browser_context . cc <nl> ppp b / brightray / browser / browser_context . cc <nl> <nl> # include " content / public / browser / resource_context . h " <nl> # include " content / public / browser / storage_partition . h " <nl> # include " net / base / escape . h " <nl> - # include " net / ssl / client_cert_store . h " <nl> - <nl> - # if defined ( USE_NSS_CERTS ) <nl> - # include " net / ssl / client_cert_store_nss . h " <nl> - # elif defined ( OS_WIN ) <nl> - # include " net / ssl / client_cert_store_win . h " <nl> - # elif defined ( OS_MACOSX ) <nl> - # include " net / ssl / client_cert_store_mac . h " <nl> - # endif <nl> <nl> using content : : BrowserThread ; <nl> <nl> class BrowserContext : : ResourceContext : public content : : ResourceContext { <nl> return getter_ - > GetURLRequestContext ( ) ; <nl> } <nl> <nl> - std : : unique_ptr < net : : ClientCertStore > CreateClientCertStore ( ) override { <nl> - # if defined ( USE_NSS_CERTS ) <nl> - return std : : unique_ptr < net : : ClientCertStore > ( new net : : ClientCertStoreNSS ( <nl> - net : : ClientCertStoreNSS : : PasswordDelegateFactory ( ) ) ) ; <nl> - # elif defined ( OS_WIN ) <nl> - return std : : unique_ptr < net : : ClientCertStore > ( new net : : ClientCertStoreWin ( ) ) ; <nl> - # elif defined ( OS_MACOSX ) <nl> - return std : : unique_ptr < net : : ClientCertStore > ( new net : : ClientCertStoreMac ( ) ) ; <nl> - # elif defined ( USE_OPENSSL ) <nl> - return std : : unique_ptr < net : : ClientCertStore > ( ) ; <nl> - # endif <nl> - } <nl> - <nl> URLRequestContextGetter * getter_ ; <nl> } ; <nl> <nl> mmm a / brightray / browser / devtools_embedder_message_dispatcher . cc <nl> ppp b / brightray / browser / devtools_embedder_message_dispatcher . cc <nl> namespace { <nl> <nl> using DispatchCallback = DevToolsEmbedderMessageDispatcher : : DispatchCallback ; <nl> <nl> - bool GetValue ( const base : : Value * value , std : : string * result ) { <nl> - return value - > GetAsString ( result ) ; <nl> + bool GetValue ( const base : : Value & value , std : : string * result ) { <nl> + return value . GetAsString ( result ) ; <nl> } <nl> <nl> - bool GetValue ( const base : : Value * value , int * result ) { <nl> - return value - > GetAsInteger ( result ) ; <nl> + bool GetValue ( const base : : Value & value , int * result ) { <nl> + return value . GetAsInteger ( result ) ; <nl> } <nl> <nl> - bool GetValue ( const base : : Value * value , bool * result ) { <nl> - return value - > GetAsBoolean ( result ) ; <nl> + bool GetValue ( const base : : Value & value , bool * result ) { <nl> + return value . GetAsBoolean ( result ) ; <nl> } <nl> <nl> - bool GetValue ( const base : : Value * value , gfx : : Rect * rect ) { <nl> + bool GetValue ( const base : : Value & value , gfx : : Rect * rect ) { <nl> const base : : DictionaryValue * dict ; <nl> - if ( ! value - > GetAsDictionary ( & dict ) ) <nl> + if ( ! value . GetAsDictionary ( & dict ) ) <nl> return false ; <nl> int x = 0 ; <nl> int y = 0 ; <nl> template < typename T , typename . . . Ts > <nl> struct ParamTuple < T , Ts . . . > { <nl> bool Parse ( const base : : ListValue & list , <nl> const base : : ListValue : : const_iterator & it ) { <nl> - return it ! = list . end ( ) & & GetValue ( * it , & head ) & & tail . Parse ( list , it + 1 ) ; <nl> + return it ! = list . end ( ) & & GetValue ( * * it , & head ) & & <nl> + tail . Parse ( list , it + 1 ) ; <nl> } <nl> <nl> template < typename H , typename . . . As > <nl> mmm a / brightray / browser / inspectable_web_contents_impl . cc <nl> ppp b / brightray / browser / inspectable_web_contents_impl . cc <nl> void InspectableWebContentsImpl : : AttachTo ( const scoped_refptr < content : : DevToolsA <nl> <nl> void InspectableWebContentsImpl : : Detach ( ) { <nl> if ( agent_host_ . get ( ) ) <nl> - agent_host_ - > DetachClient ( ) ; <nl> + agent_host_ - > DetachClient ( this ) ; <nl> agent_host_ = nullptr ; <nl> } <nl> <nl> void InspectableWebContentsImpl : : DispatchProtocolMessageFromDevToolsFrontend ( <nl> } <nl> <nl> if ( agent_host_ . get ( ) ) <nl> - agent_host_ - > DispatchProtocolMessage ( message ) ; <nl> + agent_host_ - > DispatchProtocolMessage ( this , message ) ; <nl> } <nl> <nl> void InspectableWebContentsImpl : : RecordActionUMA ( const std : : string & name , int action ) { <nl> content : : ColorChooser * InspectableWebContentsImpl : : OpenColorChooser ( <nl> } <nl> <nl> void InspectableWebContentsImpl : : RunFileChooser ( <nl> - content : : WebContents * source , <nl> + content : : RenderFrameHost * render_frame_host , <nl> const content : : FileChooserParams & params ) { <nl> auto delegate = web_contents_ - > GetDelegate ( ) ; <nl> if ( delegate ) <nl> - delegate - > RunFileChooser ( source , params ) ; <nl> + delegate - > RunFileChooser ( render_frame_host , params ) ; <nl> } <nl> <nl> void InspectableWebContentsImpl : : EnumerateDirectory ( <nl> mmm a / brightray / browser / inspectable_web_contents_impl . h <nl> ppp b / brightray / browser / inspectable_web_contents_impl . h <nl> class InspectableWebContentsImpl : <nl> content : : WebContents * source , <nl> SkColor color , <nl> const std : : vector < content : : ColorSuggestion > & suggestions ) override ; <nl> - void RunFileChooser ( content : : WebContents * source , <nl> + void RunFileChooser ( content : : RenderFrameHost * render_frame_host , <nl> const content : : FileChooserParams & params ) override ; <nl> void EnumerateDirectory ( content : : WebContents * source , <nl> int request_id , <nl> mmm a / brightray / browser / net / devtools_network_transaction . cc <nl> ppp b / brightray / browser / net / devtools_network_transaction . cc <nl> void DevToolsNetworkTransaction : : SetBeforeNetworkStartCallback ( <nl> transaction_ - > SetBeforeNetworkStartCallback ( callback ) ; <nl> } <nl> <nl> - void DevToolsNetworkTransaction : : SetBeforeProxyHeadersSentCallback ( <nl> - const BeforeProxyHeadersSentCallback & callback ) { <nl> - transaction_ - > SetBeforeProxyHeadersSentCallback ( callback ) ; <nl> + void DevToolsNetworkTransaction : : SetBeforeHeadersSentCallback ( <nl> + const BeforeHeadersSentCallback & callback ) { <nl> + transaction_ - > SetBeforeHeadersSentCallback ( callback ) ; <nl> } <nl> <nl> int DevToolsNetworkTransaction : : ResumeNetworkStart ( ) { <nl> mmm a / brightray / browser / net / devtools_network_transaction . h <nl> ppp b / brightray / browser / net / devtools_network_transaction . h <nl> class DevToolsNetworkTransaction : public net : : HttpTransaction { <nl> net : : WebSocketHandshakeStreamBase : : CreateHelper * create_helper ) override ; <nl> void SetBeforeNetworkStartCallback ( <nl> const BeforeNetworkStartCallback & callback ) override ; <nl> - void SetBeforeProxyHeadersSentCallback ( <nl> - const BeforeProxyHeadersSentCallback & callback ) override ; <nl> + void SetBeforeHeadersSentCallback ( <nl> + const BeforeHeadersSentCallback & callback ) override ; <nl> int ResumeNetworkStart ( ) override ; <nl> void GetConnectionAttempts ( net : : ConnectionAttempts * out ) const override ; <nl> <nl> mmm a / brightray / browser / network_delegate . cc <nl> ppp b / brightray / browser / network_delegate . cc <nl> int NetworkDelegate : : OnBeforeURLRequest ( <nl> return net : : OK ; <nl> } <nl> <nl> - int NetworkDelegate : : OnBeforeSendHeaders ( <nl> + int NetworkDelegate : : OnBeforeStartTransaction ( <nl> net : : URLRequest * request , <nl> const net : : CompletionCallback & callback , <nl> net : : HttpRequestHeaders * headers ) { <nl> return net : : OK ; <nl> } <nl> <nl> - void NetworkDelegate : : OnBeforeSendProxyHeaders ( net : : URLRequest * request , <nl> - const net : : ProxyInfo & proxy_info , <nl> - net : : HttpRequestHeaders * headers ) { <nl> + void NetworkDelegate : : OnStartTransaction ( <nl> + net : : URLRequest * request , <nl> + const net : : HttpRequestHeaders & headers ) { <nl> } <nl> <nl> - void NetworkDelegate : : OnSendHeaders ( <nl> + void NetworkDelegate : : OnBeforeSendHeaders ( <nl> net : : URLRequest * request , <nl> - const net : : HttpRequestHeaders & headers ) { <nl> + const net : : ProxyInfo & proxy_info , <nl> + const net : : ProxyRetryInfoMap & proxy_retry_info , <nl> + net : : HttpRequestHeaders * headers ) { <nl> } <nl> <nl> int NetworkDelegate : : OnHeadersReceived ( <nl> mmm a / brightray / browser / network_delegate . h <nl> ppp b / brightray / browser / network_delegate . h <nl> class NetworkDelegate : public net : : NetworkDelegate { <nl> int OnBeforeURLRequest ( net : : URLRequest * request , <nl> const net : : CompletionCallback & callback , <nl> GURL * new_url ) override ; <nl> - int OnBeforeSendHeaders ( net : : URLRequest * request , <nl> - const net : : CompletionCallback & callback , <nl> - net : : HttpRequestHeaders * headers ) override ; <nl> - void OnBeforeSendProxyHeaders ( net : : URLRequest * request , <nl> - const net : : ProxyInfo & proxy_info , <nl> - net : : HttpRequestHeaders * headers ) override ; <nl> - void OnSendHeaders ( net : : URLRequest * request , <nl> - const net : : HttpRequestHeaders & headers ) override ; <nl> + int OnBeforeStartTransaction ( net : : URLRequest * request , <nl> + const net : : CompletionCallback & callback , <nl> + net : : HttpRequestHeaders * headers ) override ; <nl> + void OnBeforeSendHeaders ( net : : URLRequest * request , <nl> + const net : : ProxyInfo & proxy_info , <nl> + const net : : ProxyRetryInfoMap & proxy_retry_info , <nl> + net : : HttpRequestHeaders * headers ) override ; <nl> + void OnStartTransaction ( net : : URLRequest * request , <nl> + const net : : HttpRequestHeaders & headers ) override ; <nl> int OnHeadersReceived ( <nl> net : : URLRequest * request , <nl> const net : : CompletionCallback & callback , <nl> mmm a / brightray / browser / url_request_context_getter . cc <nl> ppp b / brightray / browser / url_request_context_getter . cc <nl> <nl> # include " content / public / common / content_switches . h " <nl> # include " net / base / host_mapping_rules . h " <nl> # include " net / cert / cert_verifier . h " <nl> + # include " net / cert / ct_policy_enforcer . h " <nl> + # include " net / cert / multi_log_ct_verifier . h " <nl> # include " net / cookies / cookie_monster . h " <nl> # include " net / dns / mapped_host_resolver . h " <nl> # include " net / http / http_auth_filter . h " <nl> net : : URLRequestContext * URLRequestContextGetter : : GetURLRequestContext ( ) { <nl> new net : : HttpServerPropertiesImpl ) ; <nl> storage_ - > set_http_server_properties ( std : : move ( server_properties ) ) ; <nl> <nl> + cert_transparency_verifier_ . reset ( new net : : MultiLogCTVerifier ( ) ) ; <nl> + ct_policy_enforcer_ . reset ( new net : : CTPolicyEnforcer ( ) ) ; <nl> + <nl> net : : HttpNetworkSession : : Params network_session_params ; <nl> network_session_params . cert_verifier = url_request_context_ - > cert_verifier ( ) ; <nl> network_session_params . proxy_service = url_request_context_ - > proxy_service ( ) ; <nl> net : : URLRequestContext * URLRequestContextGetter : : GetURLRequestContext ( ) { <nl> network_session_params . http_auth_handler_factory = <nl> url_request_context_ - > http_auth_handler_factory ( ) ; <nl> network_session_params . net_log = url_request_context_ - > net_log ( ) ; <nl> + network_session_params . cert_transparency_verifier = <nl> + cert_transparency_verifier_ . get ( ) ; <nl> + network_session_params . ct_policy_enforcer = ct_policy_enforcer_ . get ( ) ; <nl> <nl> / / - - disable - http2 <nl> if ( command_line . HasSwitch ( switches : : kDisableHttp2 ) ) { <nl> net : : URLRequestContext * URLRequestContextGetter : : GetURLRequestContext ( ) { <nl> } <nl> <nl> / / - - ignore - certificate - errors <nl> - if ( command_line . HasSwitch ( : : switches : : kIgnoreCertificateErrors ) ) <nl> + if ( command_line . HasSwitch ( switches : : kIgnoreCertificateErrors ) ) <nl> network_session_params . ignore_certificate_errors = true ; <nl> <nl> / / - - host - rules <nl> mmm a / brightray / browser / url_request_context_getter . h <nl> ppp b / brightray / browser / url_request_context_getter . h <nl> class URLRequestContextGetter : public net : : URLRequestContextGetter { <nl> std : : unique_ptr < net : : HostMappingRules > host_mapping_rules_ ; <nl> std : : unique_ptr < net : : HttpAuthPreferences > http_auth_preferences_ ; <nl> std : : unique_ptr < net : : HttpNetworkSession > http_network_session_ ; <nl> + std : : unique_ptr < net : : CTVerifier > cert_transparency_verifier_ ; <nl> + std : : unique_ptr < net : : CTPolicyEnforcer > ct_policy_enforcer_ ; <nl> content : : ProtocolHandlerMap protocol_handlers_ ; <nl> content : : URLRequestInterceptorScopedVector protocol_interceptors_ ; <nl> <nl> mmm a / brightray / common / content_client . cc <nl> ppp b / brightray / common / content_client . cc <nl> gfx : : Image & ContentClient : : GetNativeImageNamed ( int resource_id ) const { <nl> resource_id ) ; <nl> } <nl> <nl> - base : : RefCountedStaticMemory * ContentClient : : GetDataResourceBytes ( <nl> - int resource_id ) const { <nl> + base : : RefCountedMemory * ContentClient : : GetDataResourceBytes ( <nl> + int resource_id ) const { <nl> return ResourceBundle : : GetSharedInstance ( ) . LoadDataResourceBytes ( resource_id ) ; <nl> } <nl> <nl> mmm a / brightray / common / content_client . h <nl> ppp b / brightray / common / content_client . h <nl> class ContentClient : public content : : ContentClient { <nl> base : : StringPiece GetDataResource ( int resource_id , <nl> ui : : ScaleFactor ) const override ; <nl> gfx : : Image & GetNativeImageNamed ( int resource_id ) const override ; <nl> - base : : RefCountedStaticMemory * GetDataResourceBytes ( <nl> - int resource_id ) const override ; <nl> + base : : RefCountedMemory * GetDataResourceBytes ( int resource_id ) const override ; <nl> <nl> DISALLOW_COPY_AND_ASSIGN ( ContentClient ) ; <nl> } ; <nl> mmm a / brightray / common / switches . cc <nl> ppp b / brightray / common / switches . cc <nl> const char kAuthServerWhitelist [ ] = " auth - server - whitelist " ; <nl> / / Whitelist containing servers for which Kerberos delegation is allowed . <nl> const char kAuthNegotiateDelegateWhitelist [ ] = " auth - negotiate - delegate - whitelist " ; <nl> <nl> + / / Ignores certificate - related errors . <nl> + const char kIgnoreCertificateErrors [ ] = " ignore - certificate - errors " ; <nl> + <nl> } / / namespace switches <nl> <nl> } / / namespace brightray <nl> mmm a / brightray / common / switches . h <nl> ppp b / brightray / common / switches . h <nl> extern const char kProxyPacUrl [ ] ; <nl> extern const char kDisableHttp2 [ ] ; <nl> extern const char kAuthServerWhitelist [ ] ; <nl> extern const char kAuthNegotiateDelegateWhitelist [ ] ; <nl> + extern const char kIgnoreCertificateErrors [ ] ; <nl> <nl> } / / namespace switches <nl> <nl> mmm a / brightray / vendor / libchromiumcontent <nl> ppp b / brightray / vendor / libchromiumcontent <nl> @ @ - 1 + 1 @ @ <nl> - Subproject commit c5cf295ef93d4ee88bff0c4b06b28ff0969a890e <nl> + Subproject commit 346dfe40a9658cc40924d29a1deb1d9669509076 <nl> | Merge pull request from electron / chrome53 | electron/electron | a0565bad2e46fd39057e56519a8d2b263634e606 | 2016-09-08T06:06:02Z |
mmm a / db / queryutil . cpp <nl> ppp b / db / queryutil . cpp <nl> namespace mongo { <nl> return i ; <nl> } <nl> } <nl> + bool first = true ; <nl> while ( _i [ i ] < ( int ) _v . _ranges [ i ] . intervals ( ) . size ( ) ) { <nl> int x = _v . _ranges [ i ] . intervals ( ) [ _i [ i ] ] . _upper . _bound . woCompare ( jj , false ) ; <nl> if ( reverse ) { <nl> namespace mongo { <nl> break ; <nl> } <nl> if ( x > 0 ) { <nl> + if ( i = = 0 & & first ) { <nl> + break ; / / the value of 1st field won ' t go backward <nl> + } <nl> if ( ! _v . _ranges [ i ] . intervals ( ) [ _i [ i ] ] . equality ( ) ) { <nl> x = _v . _ranges [ i ] . intervals ( ) [ _i [ i ] ] . _lower . _bound . woCompare ( jj , false ) ; <nl> if ( reverse ) { <nl> namespace mongo { <nl> } <nl> + + _i [ i ] ; <nl> setZero ( i + 1 ) ; <nl> - / / mark need to check lower bound ? <nl> + first = false ; <nl> } <nl> int diff = ( int ) _v . _ranges [ i ] . intervals ( ) . size ( ) - _i [ i ] ; <nl> if ( diff > 1 | | ( ! eq & & diff = = 1 ) ) { <nl> similarity index 100 % <nl> rename from jstests / slowWeekly / in1 . js <nl> rename to jstests / in7 . js <nl> | move slow test that is now fast , add small optimization to cursor advance | mongodb/mongo | 7782698bb81f2ba6b9cf36c4340e3c416681ac34 | 2010-07-21T07:10:10Z |
mmm a / cocos2dx / platform / ios / CCFileUtils_ios . mm <nl> ppp b / cocos2dx / platform / ios / CCFileUtils_ios . mm <nl> static void static_addValueToCCDict ( id key , id value , CCDictionary < std : : string , <nl> * pSize = fread ( pBuffer , sizeof ( unsigned char ) , * pSize , fp ) ; <nl> fclose ( fp ) ; <nl> } while ( 0 ) ; <nl> - <nl> - if ( ! pBuffer & & getIsPopupNotify ( ) ) <nl> + <nl> + if ( ! pBuffer ) <nl> { <nl> - std : : string title = " Notification " ; <nl> - std : : string msg = " Get data from file ( " ; <nl> - msg . append ( pszFileName ) . append ( " ) failed ! " ) ; <nl> - <nl> - CCMessageBox ( msg . c_str ( ) , title . c_str ( ) ) ; <nl> + CCLOG ( " Get data from file ( % s ) failed ! " , pszFileName ) ; <nl> + <nl> + if ( getIsPopupNotify ( ) ) <nl> + { <nl> + std : : string title = " Notification " ; <nl> + std : : string msg = " Get data from file ( " ; <nl> + msg . append ( pszFileName ) . append ( " ) failed ! " ) ; <nl> + <nl> + CCMessageBox ( msg . c_str ( ) , title . c_str ( ) ) ; <nl> + } <nl> } <nl> return pBuffer ; <nl> } <nl> | * CCFileUtils_ios dump error message to console | cocos2d/cocos2d-x | 43226d190f809bfb274f79610da586fa24a2e441 | 2011-11-21T10:50:45Z |
mmm a / tensorflow / contrib / tpu / python / tpu / tpu_optimizer . py <nl> ppp b / tensorflow / contrib / tpu / python / tpu / tpu_optimizer . py <nl> <nl> <nl> from tensorflow . contrib . tpu . python . ops import tpu_ops <nl> from tensorflow . contrib . tpu . python . tpu import tpu_function <nl> + from tensorflow . python . framework import ops <nl> from tensorflow . python . ops . losses import losses <nl> from tensorflow . python . platform import tf_logging as logging <nl> from tensorflow . python . training import optimizer <nl> def apply_gradients ( self , grads_and_vars , global_step = None , name = None ) : <nl> if grad is None : <nl> summed_grads_and_vars . append ( ( grad , var ) ) <nl> else : <nl> - summed_grads_and_vars . append ( ( tpu_ops . cross_replica_sum ( <nl> - grad , self . _group_assignment ) , var ) ) <nl> + with ops . colocate_with ( grad ) : <nl> + summed_grads_and_vars . append ( ( tpu_ops . cross_replica_sum ( <nl> + grad , self . _group_assignment ) , var ) ) <nl> return self . _opt . apply_gradients ( summed_grads_and_vars , global_step , name ) <nl> <nl> def get_slot ( self , * args , * * kwargs ) : <nl> | PUBLIC : Colocates cross_replica_sum to grad for removing unnecessary send / recv pairs . | tensorflow/tensorflow | 332124d4fe534045ec478f63c6dddb3c70482e45 | 2018-07-09T21:49:37Z |
mmm a / test <nl> ppp b / test <nl> @ @ - 1 + 1 @ @ <nl> - Subproject commit 1a223c9254341a3b2b21f83aa4637d06fa31dafb <nl> + Subproject commit 81cc289f087b20602627c818b8f6cbee4d82cd08 <nl> | Update test submodule | tesseract-ocr/tesseract | e78b5f2af396b0498fed5ce861fb466bd583a458 | 2019-03-11T12:00:17Z |
mmm a / stdlib / public / runtime / MetadataLookup . cpp <nl> ppp b / stdlib / public / runtime / MetadataLookup . cpp <nl> buildDescriptorPath ( const ContextDescriptor * context ) const { <nl> if ( ! context ) <nl> return 0 ; <nl> <nl> - / / Add the parent ' s contributino to the descriptor path . <nl> + / / Add the parent ' s contribution to the descriptor path . <nl> unsigned numKeyGenericParamsInParent = <nl> buildDescriptorPath ( context - > Parent . get ( ) ) ; <nl> <nl> buildDescriptorPath ( const ContextDescriptor * context ) const { <nl> / / Count the number of key generic params at this level . <nl> unsigned numKeyGenericParamsHere = 0 ; <nl> bool hasNonKeyGenericParams = false ; <nl> - for ( const auto & genericParam : getLocalGenericParams ( context ) ) { <nl> + auto localGenericParams = getLocalGenericParams ( context ) ; <nl> + for ( const auto & genericParam : localGenericParams ) { <nl> if ( genericParam . hasKeyArgument ( ) ) <nl> + + numKeyGenericParamsHere ; <nl> else <nl> buildDescriptorPath ( const ContextDescriptor * context ) const { <nl> } <nl> <nl> / / Form the path element . <nl> - descriptorPath . push_back ( PathElement { context , numKeyGenericParamsInParent , <nl> + descriptorPath . push_back ( PathElement { localGenericParams , <nl> + context - > getNumGenericParams ( ) , <nl> + numKeyGenericParamsInParent , <nl> numKeyGenericParamsHere , <nl> hasNonKeyGenericParams } ) ; <nl> return numKeyGenericParamsInParent + numKeyGenericParamsHere ; <nl> SubstGenericParametersFromMetadata : : operator ( ) ( <nl> <nl> / / / Retrieve the descriptor path element at this depth . <nl> auto & pathElement = descriptorPath [ depth ] ; <nl> - auto currentContext = pathElement . context ; <nl> <nl> / / Check whether the index is clearly out of bounds . <nl> - if ( index > = currentContext - > getNumGenericParams ( ) ) <nl> + if ( index > = pathElement . numTotalGenericParams ) <nl> return nullptr ; <nl> <nl> / / Compute the flat index . <nl> SubstGenericParametersFromMetadata : : operator ( ) ( <nl> if ( pathElement . hasNonKeyGenericParams > 0 ) { <nl> / / We have non - key generic parameters at this level , so the index needs to <nl> / / be checked more carefully . <nl> - auto genericParams = getLocalGenericParams ( currentContext ) ; <nl> + auto genericParams = pathElement . localGenericParams ; <nl> <nl> / / Make sure that the requested parameter itself has a key argument . <nl> if ( ! genericParams [ index ] . hasKeyArgument ( ) ) <nl> SubstGenericParametersFromMetadata : : operator ( ) ( <nl> flatIndex + = index ; <nl> } <nl> <nl> - return base - > getGenericArgs ( ) [ flatIndex ] ; <nl> + return ( const Metadata * ) genericArgs [ flatIndex ] ; <nl> } <nl> <nl> const WitnessTable * <nl> SubstGenericParametersFromMetadata : : operator ( ) ( const Metadata * type , <nl> / / On first access , compute the descriptor path . <nl> setup ( ) ; <nl> <nl> - return ( const WitnessTable * ) base - > getGenericArgs ( ) [ <nl> - index + numKeyGenericParameters ] ; <nl> + return ( const WitnessTable * ) genericArgs [ index + numKeyGenericParameters ] ; <nl> } <nl> <nl> const Metadata * SubstGenericParametersFromWrittenArgs : : operator ( ) ( <nl> mmm a / stdlib / public / runtime / Private . h <nl> ppp b / stdlib / public / runtime / Private . h <nl> class TypeInfo { <nl> class SWIFT_RUNTIME_LIBRARY_VISIBILITY SubstGenericParametersFromMetadata { <nl> const Metadata * base ; <nl> <nl> + / / / The generic arguments . <nl> + const void * const * genericArgs ; <nl> + <nl> / / / An element in the descriptor path . <nl> struct PathElement { <nl> - / / / The context described by this path element . <nl> - const ContextDescriptor * context ; <nl> + / / / The generic parameters local to this element . <nl> + ArrayRef < GenericParamDescriptor > localGenericParams ; <nl> + <nl> + / / / The total number of generic parameters . <nl> + unsigned numTotalGenericParams ; <nl> <nl> / / / The number of key parameters in the parent . <nl> unsigned numKeyGenericParamsInParent ; <nl> class TypeInfo { <nl> public : <nl> / / / Produce substitutions entirely from the given metadata . <nl> explicit SubstGenericParametersFromMetadata ( const Metadata * base ) <nl> - : base ( base ) { } <nl> + : base ( base ) , <nl> + genericArgs ( base ? ( const void * const * ) base - > getGenericArgs ( ) <nl> + : nullptr ) { } <nl> <nl> const Metadata * operator ( ) ( unsigned depth , unsigned index ) const ; <nl> const WitnessTable * operator ( ) ( const Metadata * type , unsigned index ) const ; <nl> | [ Runtime ] Generalize SubstGenericParametersFromMetadata slightly . | apple/swift | cdd2928fec325e5f43e9e0efcc5f90bd6ff8aee7 | 2018-11-16T18:13:06Z |
mmm a / src / rpc / rawtransaction . cpp <nl> ppp b / src / rpc / rawtransaction . cpp <nl> UniValue utxoupdatepsbt ( const JSONRPCRequest & request ) <nl> <nl> const Coin & coin = view . AccessCoin ( psbtx . tx - > vin [ i ] . prevout ) ; <nl> <nl> - std : : vector < std : : vector < unsigned char > > solutions_data ; <nl> - txnouttype which_type = Solver ( coin . out . scriptPubKey , solutions_data ) ; <nl> - if ( which_type = = TX_WITNESS_V0_SCRIPTHASH | | which_type = = TX_WITNESS_V0_KEYHASH | | which_type = = TX_WITNESS_UNKNOWN ) { <nl> + if ( IsSegWitOutput ( DUMMY_SIGNING_PROVIDER , coin . out . scriptPubKey ) ) { <nl> input . witness_utxo = coin . out ; <nl> } <nl> } <nl> mmm a / src / script / sign . cpp <nl> ppp b / src / script / sign . cpp <nl> FlatSigningProvider Merge ( const FlatSigningProvider & a , const FlatSigningProvide <nl> ret . origins . insert ( b . origins . begin ( ) , b . origins . end ( ) ) ; <nl> return ret ; <nl> } <nl> + <nl> + bool IsSegWitOutput ( const SigningProvider & provider , const CScript & script ) <nl> + { <nl> + std : : vector < valtype > solutions ; <nl> + auto whichtype = Solver ( script , solutions ) ; <nl> + if ( whichtype = = TX_WITNESS_V0_SCRIPTHASH | | whichtype = = TX_WITNESS_V0_KEYHASH | | whichtype = = TX_WITNESS_UNKNOWN ) return true ; <nl> + if ( whichtype = = TX_SCRIPTHASH ) { <nl> + auto h160 = uint160 ( solutions [ 0 ] ) ; <nl> + CScript subscript ; <nl> + if ( provider . GetCScript ( h160 , subscript ) ) { <nl> + whichtype = Solver ( subscript , solutions ) ; <nl> + if ( whichtype = = TX_WITNESS_V0_SCRIPTHASH | | whichtype = = TX_WITNESS_V0_KEYHASH | | whichtype = = TX_WITNESS_UNKNOWN ) return true ; <nl> + } <nl> + } <nl> + return false ; <nl> + } <nl> mmm a / src / script / sign . h <nl> ppp b / src / script / sign . h <nl> void UpdateInput ( CTxIn & input , const SignatureData & data ) ; <nl> * Solvability is unrelated to whether we consider this output to be ours . * / <nl> bool IsSolvable ( const SigningProvider & provider , const CScript & script ) ; <nl> <nl> + / * * Check whether a scriptPubKey is known to be segwit . * / <nl> + bool IsSegWitOutput ( const SigningProvider & provider , const CScript & script ) ; <nl> + <nl> # endif / / BITCOIN_SCRIPT_SIGN_H <nl> | Abstract out IsSegWitOutput from utxoupdatepsbt | bitcoin/bitcoin | eaf4f887348a08c620732125ad4430e1a133d434 | 2019-05-10T21:22:33Z |
mmm a / tensorflow / core / grappler / costs / graph_properties . cc <nl> ppp b / tensorflow / core / grappler / costs / graph_properties . cc <nl> Status GraphProperties : : InferDynamically ( Cluster * cluster ) { <nl> return InferFromCostGraph ( metadata . cost_graph ( ) ) ; <nl> } <nl> <nl> - Status GraphProperties : : AnnotateOutputShapes ( GraphDef * output_graph_def ) const { <nl> + Status GraphProperties : : AnnotateOutputShapes ( GraphDef * output_graph_def , <nl> + bool allow_symbolic_shapes ) const { <nl> * output_graph_def = item_ . graph ; <nl> for ( int i = 0 ; i < output_graph_def - > node_size ( ) ; i + + ) { <nl> auto node = output_graph_def - > mutable_node ( i ) ; <nl> AttrValue attr_output_shape ; <nl> auto tensor_properties = GetOutputProperties ( node - > name ( ) ) ; <nl> for ( const auto & tensor_property : tensor_properties ) { <nl> - * attr_output_shape . mutable_list ( ) - > add_shape ( ) = tensor_property . shape ( ) ; <nl> + TensorShapeProto * proto = attr_output_shape . mutable_list ( ) - > add_shape ( ) ; <nl> + * proto = tensor_property . shape ( ) ; <nl> + if ( ! allow_symbolic_shapes ) { <nl> + / / There may be dim . size < - 1 in SymbolicShapeRefiner . Change those to <nl> + / / - 1 . <nl> + for ( int i = 0 ; i < proto - > dim_size ( ) ; i + + ) { <nl> + if ( proto - > dim ( i ) . size ( ) < - 1 ) { <nl> + proto - > mutable_dim ( i ) - > set_size ( - 1 ) ; <nl> + } <nl> + } <nl> + } <nl> } <nl> ( * node - > mutable_attr ( ) ) [ " _output_shapes " ] = attr_output_shape ; <nl> } <nl> mmm a / tensorflow / core / grappler / costs / graph_properties . h <nl> ppp b / tensorflow / core / grappler / costs / graph_properties . h <nl> class GraphProperties { <nl> Status InferFromCostGraph ( const CostGraphDef & cost_graph ) ; <nl> <nl> / / Stores ` item_ . graph ` with the inferred output shapes to ` output_graph_def ` . <nl> - Status AnnotateOutputShapes ( GraphDef * output_graph_def ) const ; <nl> + Status AnnotateOutputShapes ( GraphDef * output_graph_def , <nl> + bool allow_symbolic_shapes ) const ; <nl> + <nl> + Status AnnotateOutputShapes ( GraphDef * output_graph_def ) const { <nl> + return AnnotateOutputShapes ( output_graph_def , false ) ; <nl> + } <nl> <nl> / / Return the properties of node inputs / outputs , including data types and <nl> / / shapes . Note that the dimensions in the shapes can be negative . We use the <nl> mmm a / tensorflow / core / grappler / optimizers / generic_layout_optimizer_transposer . cc <nl> ppp b / tensorflow / core / grappler / optimizers / generic_layout_optimizer_transposer . cc <nl> Status TransposeContext : : InitializeTransposeContext ( const GrapplerItem & item , <nl> DCHECK ( context ! = nullptr ) ; <nl> context - > graph_properties = absl : : make_unique < GraphProperties > ( item ) ; <nl> TF_RETURN_IF_ERROR ( context - > graph_properties - > InferStatically ( false ) ) ; <nl> - TF_RETURN_IF_ERROR ( <nl> - context - > graph_properties - > AnnotateOutputShapes ( & context - > graph ) ) ; <nl> + TF_RETURN_IF_ERROR ( context - > graph_properties - > AnnotateOutputShapes ( <nl> + & context - > graph , / * allow_symbolic_shapes = * / true ) ) ; <nl> Status status ; <nl> context - > graph_view = <nl> absl : : make_unique < utils : : MutableGraphView > ( & context - > graph , & status ) ; <nl> mmm a / tensorflow / core / grappler / optimizers / layout_optimizer . cc <nl> ppp b / tensorflow / core / grappler / optimizers / layout_optimizer . cc <nl> int GetNumGPUs ( const Cluster & cluster ) { <nl> Status LayoutOptimizer : : Tune ( const GrapplerItem & item , <nl> const GraphProperties & graph_properties , <nl> const TuningConfig & config , GraphDef * output ) { <nl> - auto status = graph_properties . AnnotateOutputShapes ( output ) ; <nl> + auto status = graph_properties . AnnotateOutputShapes ( <nl> + output , / * allow_symbolic_shapes = * / true ) ; <nl> if ( ! status . ok ( ) ) { <nl> VLOG ( 1 ) < < " Annotate shape return status : " < < status . ToString ( ) ; <nl> * output = item . graph ; <nl> mmm a / tensorflow / core / grappler / optimizers / meta_optimizer . cc <nl> ppp b / tensorflow / core / grappler / optimizers / meta_optimizer . cc <nl> Status MetaOptimizer : : Optimize ( Cluster * cluster , const GrapplerItem & item , <nl> func_item . optimization_options ( ) . allow_pruning_stateful_and_dataset_ops = <nl> false ; <nl> <nl> - / / TODO ( b / 129545186 ) : Shape inference in GraphProperties doesn ' t work well <nl> - / / with _Arg nodes . Replace them with Placeholders with unknown shape . <nl> - absl : : flat_hash_set < absl : : string_view > input_nodes ; <nl> - for ( auto & input_arg : func_item . inputs ( ) ) { <nl> - input_nodes . insert ( input_arg . node_name ) ; <nl> - } <nl> - for ( NodeDef & func_node : * func_item . graph . mutable_node ( ) ) { <nl> - if ( input_nodes . contains ( func_node . name ( ) ) ) { <nl> - func_node . set_op ( " Placeholder " ) ; <nl> - auto & attrs = * func_node . mutable_attr ( ) ; <nl> - attrs [ " dtype " ] = attrs [ " T " ] ; <nl> - attrs . erase ( " index " ) ; <nl> - attrs . erase ( " T " ) ; <nl> - TensorShapeProto unknown_shape ; <nl> - unknown_shape . set_unknown_rank ( true ) ; <nl> - * ( attrs [ " shape " ] . mutable_shape ( ) ) = unknown_shape ; <nl> - } <nl> - } <nl> - <nl> / / Optimize function body graph . <nl> GraphDef optimized_func_graph ; <nl> if ( IsTPUGraphDef ( * optimized_graph ) ) { <nl> | Don ' t replace _Arg nodes with Placeholder for nested functions in Grappler , as it might drop shape information . | tensorflow/tensorflow | 48bf9acb2e9cd90cc1d1fc9342576cf2892fbfe2 | 2020-01-30T02:41:36Z |
mmm a / xbmc / screensavers / rsxs - 0 . 9 / src / solarwinds / solarwinds . cc <nl> ppp b / xbmc / screensavers / rsxs - 0 . 9 / src / solarwinds / solarwinds . cc <nl> ADDON_STATUS Create ( void * hdl , void * props ) <nl> Common : : width = scrprops - > width ; <nl> Common : : height = scrprops - > height ; <nl> Common : : aspectRatio = float ( Common : : width ) / float ( Common : : height ) ; <nl> + Common : : resources = new ResourceManager ; <nl> <nl> return STATUS_OK ; <nl> } <nl> <nl> void Start ( ) <nl> { <nl> - Common : : resources = new ResourceManager ; <nl> Hack : : start ( ) ; <nl> } <nl> <nl> void Render ( ) <nl> void Stop ( ) <nl> { <nl> Hack : : stop ( ) ; <nl> - delete Common : : resources ; <nl> } <nl> <nl> void Destroy ( ) <nl> { <nl> + delete Common : : resources ; <nl> } <nl> <nl> ADDON_STATUS GetStatus ( ) <nl> | changed : Moved allocate / deallocate of date from start / stop to Create / Destroy inside Solarwinds screensaver | xbmc/xbmc | 038913a5906bed986c8b0749b24be8029be239c3 | 2010-03-03T15:18:10Z |
mmm a / src / elements . cc <nl> ppp b / src / elements . cc <nl> static Failure * ThrowArrayLengthRangeError ( Heap * heap ) { <nl> template < typename ElementsAccessorSubclass , typename BackingStoreClass > <nl> class ElementsAccessorBase : public ElementsAccessor { <nl> protected : <nl> - ElementsAccessorBase ( ) { } <nl> + explicit ElementsAccessorBase ( const char * name ) : ElementsAccessor ( name ) { } <nl> virtual MaybeObject * Get ( FixedArrayBase * backing_store , <nl> uint32_t key , <nl> JSObject * obj , <nl> template < typename FastElementsAccessorSubclass , <nl> int ElementSize > <nl> class FastElementsAccessor <nl> : public ElementsAccessorBase < FastElementsAccessorSubclass , BackingStore > { <nl> + public : <nl> + explicit FastElementsAccessor ( const char * name ) <nl> + : ElementsAccessorBase < FastElementsAccessorSubclass , <nl> + BackingStore > ( name ) { } <nl> protected : <nl> friend class ElementsAccessorBase < FastElementsAccessorSubclass , BackingStore > ; <nl> <nl> class FastObjectElementsAccessor <nl> FixedArray , <nl> kPointerSize > { <nl> public : <nl> + explicit FastObjectElementsAccessor ( const char * name ) <nl> + : FastElementsAccessor < FastObjectElementsAccessor , <nl> + FixedArray , <nl> + kPointerSize > ( name ) { } <nl> + <nl> static MaybeObject * DeleteCommon ( JSObject * obj , <nl> uint32_t key ) { <nl> ASSERT ( obj - > HasFastElements ( ) | | <nl> class FastDoubleElementsAccessor <nl> : public FastElementsAccessor < FastDoubleElementsAccessor , <nl> FixedDoubleArray , <nl> kDoubleSize > { <nl> + public : <nl> + explicit FastDoubleElementsAccessor ( const char * name ) <nl> + : FastElementsAccessor < FastDoubleElementsAccessor , <nl> + FixedDoubleArray , <nl> + kDoubleSize > ( name ) { } <nl> + <nl> static MaybeObject * SetFastElementsCapacityAndLength ( JSObject * obj , <nl> uint32_t capacity , <nl> uint32_t length ) { <nl> template < typename ExternalElementsAccessorSubclass , <nl> class ExternalElementsAccessor <nl> : public ElementsAccessorBase < ExternalElementsAccessorSubclass , <nl> ExternalArray > { <nl> + public : <nl> + explicit ExternalElementsAccessor ( const char * name ) <nl> + : ElementsAccessorBase < ExternalElementsAccessorSubclass , <nl> + ExternalArray > ( name ) { } <nl> + <nl> protected : <nl> friend class ElementsAccessorBase < ExternalElementsAccessorSubclass , <nl> ExternalArray > ; <nl> class ExternalElementsAccessor <nl> class ExternalByteElementsAccessor <nl> : public ExternalElementsAccessor < ExternalByteElementsAccessor , <nl> ExternalByteArray > { <nl> + public : <nl> + explicit ExternalByteElementsAccessor ( const char * name ) <nl> + : ExternalElementsAccessor < ExternalByteElementsAccessor , <nl> + ExternalByteArray > ( name ) { } <nl> } ; <nl> <nl> <nl> class ExternalUnsignedByteElementsAccessor <nl> : public ExternalElementsAccessor < ExternalUnsignedByteElementsAccessor , <nl> ExternalUnsignedByteArray > { <nl> + public : <nl> + explicit ExternalUnsignedByteElementsAccessor ( const char * name ) <nl> + : ExternalElementsAccessor < ExternalUnsignedByteElementsAccessor , <nl> + ExternalUnsignedByteArray > ( name ) { } <nl> } ; <nl> <nl> <nl> class ExternalShortElementsAccessor <nl> : public ExternalElementsAccessor < ExternalShortElementsAccessor , <nl> ExternalShortArray > { <nl> + public : <nl> + explicit ExternalShortElementsAccessor ( const char * name ) <nl> + : ExternalElementsAccessor < ExternalShortElementsAccessor , <nl> + ExternalShortArray > ( name ) { } <nl> } ; <nl> <nl> <nl> class ExternalUnsignedShortElementsAccessor <nl> : public ExternalElementsAccessor < ExternalUnsignedShortElementsAccessor , <nl> ExternalUnsignedShortArray > { <nl> + public : <nl> + explicit ExternalUnsignedShortElementsAccessor ( const char * name ) <nl> + : ExternalElementsAccessor < ExternalUnsignedShortElementsAccessor , <nl> + ExternalUnsignedShortArray > ( name ) { } <nl> } ; <nl> <nl> <nl> class ExternalIntElementsAccessor <nl> : public ExternalElementsAccessor < ExternalIntElementsAccessor , <nl> ExternalIntArray > { <nl> + public : <nl> + explicit ExternalIntElementsAccessor ( const char * name ) <nl> + : ExternalElementsAccessor < ExternalIntElementsAccessor , <nl> + ExternalIntArray > ( name ) { } <nl> } ; <nl> <nl> <nl> class ExternalUnsignedIntElementsAccessor <nl> : public ExternalElementsAccessor < ExternalUnsignedIntElementsAccessor , <nl> ExternalUnsignedIntArray > { <nl> + public : <nl> + explicit ExternalUnsignedIntElementsAccessor ( const char * name ) <nl> + : ExternalElementsAccessor < ExternalUnsignedIntElementsAccessor , <nl> + ExternalUnsignedIntArray > ( name ) { } <nl> } ; <nl> <nl> <nl> class ExternalFloatElementsAccessor <nl> : public ExternalElementsAccessor < ExternalFloatElementsAccessor , <nl> ExternalFloatArray > { <nl> + public : <nl> + explicit ExternalFloatElementsAccessor ( const char * name ) <nl> + : ExternalElementsAccessor < ExternalFloatElementsAccessor , <nl> + ExternalFloatArray > ( name ) { } <nl> } ; <nl> <nl> <nl> class ExternalDoubleElementsAccessor <nl> : public ExternalElementsAccessor < ExternalDoubleElementsAccessor , <nl> ExternalDoubleArray > { <nl> + public : <nl> + explicit ExternalDoubleElementsAccessor ( const char * name ) <nl> + : ExternalElementsAccessor < ExternalDoubleElementsAccessor , <nl> + ExternalDoubleArray > ( name ) { } <nl> } ; <nl> <nl> <nl> class PixelElementsAccessor <nl> : public ExternalElementsAccessor < PixelElementsAccessor , <nl> ExternalPixelArray > { <nl> + public : <nl> + explicit PixelElementsAccessor ( const char * name ) <nl> + : ExternalElementsAccessor < PixelElementsAccessor , <nl> + ExternalPixelArray > ( name ) { } <nl> } ; <nl> <nl> <nl> class DictionaryElementsAccessor <nl> : public ElementsAccessorBase < DictionaryElementsAccessor , <nl> SeededNumberDictionary > { <nl> public : <nl> + explicit DictionaryElementsAccessor ( const char * name ) <nl> + : ElementsAccessorBase < DictionaryElementsAccessor , <nl> + SeededNumberDictionary > ( name ) { } <nl> + <nl> / / Adjusts the length of the dictionary backing store and returns the new <nl> / / length according to ES5 section 15 . 4 . 5 . 2 behavior . <nl> static MaybeObject * SetLengthWithoutNormalize ( SeededNumberDictionary * dict , <nl> class DictionaryElementsAccessor <nl> class NonStrictArgumentsElementsAccessor <nl> : public ElementsAccessorBase < NonStrictArgumentsElementsAccessor , <nl> FixedArray > { <nl> + public : <nl> + explicit NonStrictArgumentsElementsAccessor ( const char * name ) <nl> + : ElementsAccessorBase < NonStrictArgumentsElementsAccessor , <nl> + FixedArray > ( name ) { } <nl> protected : <nl> friend class ElementsAccessorBase < NonStrictArgumentsElementsAccessor , <nl> FixedArray > ; <nl> void ElementsAccessor : : InitializeOncePerProcess ( ) { <nl> ELEMENTS_LIST ( ACCESSOR_STRUCT ) <nl> # undef ACCESSOR_STRUCT <nl> } element_accessors = { <nl> - # define ACCESSOR_INIT ( Class , Name ) new Class ( ) , <nl> + # define ACCESSOR_INIT ( Class , Name ) new Class ( # Name ) , <nl> ELEMENTS_LIST ( ACCESSOR_INIT ) <nl> # undef ACCESSOR_INIT <nl> } ; <nl> mmm a / src / elements . h <nl> ppp b / src / elements . h <nl> namespace internal { <nl> / / ElementsKinds . <nl> class ElementsAccessor { <nl> public : <nl> - ElementsAccessor ( ) { } <nl> + explicit ElementsAccessor ( const char * name ) : name_ ( name ) { } <nl> virtual ~ ElementsAccessor ( ) { } <nl> + <nl> + virtual const char * name ( ) const { return name_ ; } <nl> + <nl> virtual MaybeObject * Get ( FixedArrayBase * backing_store , <nl> uint32_t key , <nl> JSObject * holder , <nl> class ElementsAccessor { <nl> <nl> private : <nl> static ElementsAccessor * * elements_accessors_ ; <nl> + const char * name_ ; <nl> <nl> DISALLOW_COPY_AND_ASSIGN ( ElementsAccessor ) ; <nl> } ; <nl> mmm a / src / objects . cc <nl> ppp b / src / objects . cc <nl> namespace v8 { <nl> namespace internal { <nl> <nl> void PrintElementsKind ( FILE * out , ElementsKind kind ) { <nl> - switch ( kind ) { <nl> - case FAST_SMI_ONLY_ELEMENTS : <nl> - PrintF ( out , " FAST_SMI_ONLY_ELEMENTS " ) ; <nl> - break ; <nl> - case FAST_ELEMENTS : <nl> - PrintF ( out , " FAST_ELEMENTS " ) ; <nl> - break ; <nl> - case FAST_DOUBLE_ELEMENTS : <nl> - PrintF ( out , " FAST_DOUBLE_ELEMENTS " ) ; <nl> - break ; <nl> - case DICTIONARY_ELEMENTS : <nl> - PrintF ( out , " DICTIONARY_ELEMENTS " ) ; <nl> - break ; <nl> - case NON_STRICT_ARGUMENTS_ELEMENTS : <nl> - PrintF ( out , " NON_STRICT_ARGUMENTS_ELEMENTS " ) ; <nl> - break ; <nl> - case EXTERNAL_BYTE_ELEMENTS : <nl> - PrintF ( out , " EXTERNAL_BYTE_ELEMENTS " ) ; <nl> - break ; <nl> - case EXTERNAL_UNSIGNED_BYTE_ELEMENTS : <nl> - PrintF ( out , " EXTERNAL_UNSIGNED_BYTE_ELEMENTS " ) ; <nl> - break ; <nl> - case EXTERNAL_SHORT_ELEMENTS : <nl> - PrintF ( out , " EXTERNAL_SHORT_ELEMENTS " ) ; <nl> - break ; <nl> - case EXTERNAL_UNSIGNED_SHORT_ELEMENTS : <nl> - PrintF ( out , " EXTERNAL_UNSIGNED_SHORT_ELEMENTS " ) ; <nl> - break ; <nl> - case EXTERNAL_INT_ELEMENTS : <nl> - PrintF ( out , " EXTERNAL_INT_ELEMENTS " ) ; <nl> - break ; <nl> - case EXTERNAL_UNSIGNED_INT_ELEMENTS : <nl> - PrintF ( out , " EXTERNAL_UNSIGNED_INT_ELEMENTS " ) ; <nl> - break ; <nl> - case EXTERNAL_FLOAT_ELEMENTS : <nl> - PrintF ( out , " EXTERNAL_FLOAT_ELEMENTS " ) ; <nl> - break ; <nl> - case EXTERNAL_DOUBLE_ELEMENTS : <nl> - PrintF ( out , " EXTERNAL_DOUBLE_ELEMENTS " ) ; <nl> - break ; <nl> - case EXTERNAL_PIXEL_ELEMENTS : <nl> - PrintF ( out , " EXTERNAL_DOUBLE_ELEMENTS " ) ; <nl> - break ; <nl> - } <nl> + ElementsAccessor * accessor = ElementsAccessor : : ForKind ( kind ) ; <nl> + PrintF ( out , " % s " , accessor - > name ( ) ) ; <nl> } <nl> <nl> <nl> | Automatically determine ElementsKind name for debug printing | v8/v8 | 3e155c66f480b3380e4c89147860bb74eb67a850 | 2012-03-06T12:03:14Z |
mmm a / dbms / programs / client / Client . cpp <nl> ppp b / dbms / programs / client / Client . cpp <nl> class Client : public Poco : : Util : : Application <nl> 31446 , 31800 , 32155 , 32539 , 32894 , 33248 , 33632 , 33986 , 34369 , 34724 , 35078 , 35462 , 35817 , 36171 , 36555 , 36909 , 37293 , 37647 , <nl> 38002 , 38386 , 38740 , 39095 , 39479 , 39833 , 40187 , 40571 , 40925 , 41309 , 41664 , 42018 , 42402 , 42757 , 43111 , 43495 , 43849 , 44233 , <nl> 44587 , 44942 , 45326 , 45680 , 46035 , 46418 , 46772 , 47126 , 47510 , 47865 , 48249 , 48604 , 48958 , 49342 } ; <nl> - static constexpr size_t N = sizeof ( chineseNewYearIndicators ) / sizeof ( chineseNewYearIndicators [ 0 ] ) ; <nl> <nl> / / / All time zone names are acquired from https : / / www . iana . org / time - zones <nl> static constexpr const char * chineseNewYearTimeZoneIndicators [ ] = { <nl> mmm a / dbms / src / AggregateFunctions / AggregateFunctionWindowFunnel . cpp <nl> ppp b / dbms / src / AggregateFunctions / AggregateFunctionWindowFunnel . cpp <nl> namespace <nl> template < template < typename > class Data > <nl> AggregateFunctionPtr createAggregateFunctionWindowFunnel ( const std : : string & name , const DataTypes & arguments , const Array & params ) <nl> { <nl> - if ( params . size ( ) < 1 ) <nl> + if ( params . empty ( ) ) <nl> throw Exception { " Aggregate function " + name + " requires at least one parameter : < window > , [ option , [ option , . . . ] ] " , ErrorCodes : : NUMBER_OF_ARGUMENTS_DOESNT_MATCH } ; <nl> <nl> if ( arguments . size ( ) < 2 ) <nl> mmm a / dbms / src / Functions / array / arrayCumSumNonNegative . cpp <nl> ppp b / dbms / src / Functions / array / arrayCumSumNonNegative . cpp <nl> struct ArrayCumSumNonNegativeImpl <nl> <nl> } <nl> <nl> - static ColumnPtr execute ( const ColumnArray & array , ColumnPtr & mapped ) <nl> + static ColumnPtr execute ( const ColumnArray & array , ColumnPtr mapped ) <nl> { <nl> ColumnPtr res ; <nl> <nl> mmm a / dbms / src / Functions / array / arrayReverse . cpp <nl> ppp b / dbms / src / Functions / array / arrayReverse . cpp <nl> void FunctionArrayReverse : : executeImpl ( Block & block , const ColumnNumbers & argu <nl> const IColumn * src_inner_col = src_nullable_col ? & src_nullable_col - > getNestedColumn ( ) : & src_data ; <nl> IColumn * res_inner_col = res_nullable_col ? & res_nullable_col - > getNestedColumn ( ) : & res_data ; <nl> <nl> - false <nl> + false / / NOLINT <nl> | | executeNumber < UInt8 > ( * src_inner_col , offsets , * res_inner_col ) <nl> | | executeNumber < UInt16 > ( * src_inner_col , offsets , * res_inner_col ) <nl> | | executeNumber < UInt32 > ( * src_inner_col , offsets , * res_inner_col ) <nl> | clang - tidy , part 24 | ClickHouse/ClickHouse | 10e5550c02af8f8789e720ebe8aded5c449a3381 | 2020-03-09T03:44:48Z |
mmm a / python - package / lightgbm / basic . py <nl> ppp b / python - package / lightgbm / basic . py <nl> def is_numpy_1d_array ( data ) : <nl> def is_1d_list ( data ) : <nl> " " " Check is 1d list " " " <nl> return isinstance ( data , list ) and \ <nl> - ( not data or isinstance ( data [ 0 ] , numeric_types ) ) <nl> + ( not data or is_numeric ( data [ 0 ] ) ) <nl> <nl> <nl> def list_to_1d_numpy ( data , dtype = np . float32 , name = ' list ' ) : <nl> | python package : use is_numeric check in is_1d_list in basics . py ( ) | microsoft/LightGBM | bf35c961afc08bd8641331051558bd3ffe25f1b4 | 2017-07-28T07:12:11Z |
mmm a / hphp / runtime / test / vasm - fold - test . cpp <nl> ppp b / hphp / runtime / test / vasm - fold - test . cpp <nl> TEST ( Vasm , FoldImms ) { <nl> " addqi 0 , % 64 = > % 65 , % 67 \ n " <nl> " copy % 64 = > % 66 \ n " <nl> " movl % 67 = > % 71 \ n " <nl> - " ret \ n " , <nl> + " ret { } \ n " , <nl> genTestCode < addq > ( 0 , 0u ) / / addq 0 , r <nl> ) ; <nl> EXPECT_EQ ( <nl> TEST ( Vasm , FoldImms ) { <nl> " addqi 0 , % 64 = > % 65 , % 67 \ n " <nl> " copy % 64 = > % 66 \ n " <nl> " movl % 67 = > % 71 \ n " <nl> - " ret \ n " , <nl> + " ret { } \ n " , <nl> genTestCode < addq > ( 1 , 0u ) / / addq r , 0 <nl> ) ; <nl> EXPECT_EQ ( <nl> TEST ( Vasm , FoldImms ) { <nl> " addqi 1 , % 64 = > % 65 , % 67 \ n " <nl> " incq % 64 = > % 66 , % 68 \ n " <nl> " movl % 67 = > % 71 \ n " <nl> - " ret \ n " , <nl> + " ret { } \ n " , <nl> genTestCode < addq > ( 0 , 1u ) / / addq 1 , r <nl> ) ; <nl> EXPECT_EQ ( <nl> TEST ( Vasm , FoldImms ) { <nl> " addqi 1 , % 64 = > % 65 , % 67 \ n " <nl> " incq % 64 = > % 66 , % 68 \ n " <nl> " movl % 67 = > % 71 \ n " <nl> - " ret \ n " , <nl> + " ret { } \ n " , <nl> genTestCode < addq > ( 1 , 1u ) / / addq r , 1 <nl> ) ; <nl> <nl> TEST ( Vasm , FoldImms ) { <nl> " subqi 0 , % 64 = > % 65 , % 67 \ n " <nl> " copy % 64 = > % 66 \ n " <nl> " movl % 67 = > % 71 \ n " <nl> - " ret \ n " , <nl> + " ret { } \ n " , <nl> genTestCode < subq > ( 0 , 0u ) / / subq 0 , r <nl> ) ; <nl> <nl> TEST ( Vasm , FoldImms ) { <nl> " neg % 64 = > % 65 , % 67 \ n " <nl> " neg % 64 = > % 66 , % 68 \ n " <nl> " movl % 67 = > % 71 \ n " <nl> - " ret \ n " , <nl> + " ret { } \ n " , <nl> genTestCode < subq > ( 1 , 0u ) / / subq r , 0 <nl> ) ; <nl> <nl> TEST ( Vasm , FoldImms ) { <nl> " subqi 1 , % 64 = > % 65 , % 67 \ n " <nl> " decq % 64 = > % 66 , % 68 \ n " <nl> " movl % 67 = > % 71 \ n " <nl> - " ret \ n " , <nl> + " ret { } \ n " , <nl> genTestCode < subq > ( 0 , 1u ) / / subq 1 , r <nl> ) ; <nl> <nl> TEST ( Vasm , FoldImms ) { <nl> " xorbi 0 , % 64 = > % 65 , % 67 \ n " <nl> " copy % 64 = > % 66 \ n " <nl> " movl % 67 = > % 71 \ n " <nl> - " ret \ n " , <nl> + " ret { } \ n " , <nl> genTestCode < xorb > ( 0 , 0u ) / / xorb 0 , r <nl> ) ; <nl> EXPECT_EQ ( <nl> TEST ( Vasm , FoldImms ) { <nl> " xorbi 0 , % 64 = > % 65 , % 67 \ n " <nl> " copy % 64 = > % 66 \ n " <nl> " movl % 67 = > % 71 \ n " <nl> - " ret \ n " , <nl> + " ret { } \ n " , <nl> genTestCode < xorb > ( 1 , 0u ) / / xorb r , 0 <nl> ) ; <nl> EXPECT_EQ ( <nl> TEST ( Vasm , FoldImms ) { <nl> " xorbi - 1 , % 64 = > % 65 , % 67 \ n " <nl> " notb % 64 = > % 66 \ n " <nl> " movl % 67 = > % 71 \ n " <nl> - " ret \ n " , <nl> + " ret { } \ n " , <nl> genTestCode < xorb > ( 0 , - 1 ) / / xorb - 1 , r <nl> ) ; <nl> EXPECT_EQ ( <nl> TEST ( Vasm , FoldImms ) { <nl> " xorbi - 1 , % 64 = > % 65 , % 67 \ n " <nl> " notb % 64 = > % 66 \ n " <nl> " movl % 67 = > % 71 \ n " <nl> - " ret \ n " , <nl> + " ret { } \ n " , <nl> genTestCode < xorb > ( 1 , - 1 ) / / xorb r , - 1 <nl> ) ; <nl> <nl> TEST ( Vasm , FoldImms ) { <nl> " xorqi 0 , % 64 = > % 65 , % 67 \ n " <nl> " copy % 64 = > % 66 \ n " <nl> " movl % 67 = > % 71 \ n " <nl> - " ret \ n " , <nl> + " ret { } \ n " , <nl> genTestCode < xorq > ( 0 , 0u ) / / xorq 0 , r <nl> ) ; <nl> EXPECT_EQ ( <nl> TEST ( Vasm , FoldImms ) { <nl> " xorqi 0 , % 64 = > % 65 , % 67 \ n " <nl> " copy % 64 = > % 66 \ n " <nl> " movl % 67 = > % 71 \ n " <nl> - " ret \ n " , <nl> + " ret { } \ n " , <nl> genTestCode < xorq > ( 1 , 0u ) / / xorq r , 0 <nl> ) ; <nl> EXPECT_EQ ( <nl> TEST ( Vasm , FoldImms ) { <nl> " xorqi - 1 , % 64 = > % 65 , % 67 \ n " <nl> " not % 64 = > % 66 \ n " <nl> " movl % 67 = > % 71 \ n " <nl> - " ret \ n " , <nl> + " ret { } \ n " , <nl> genTestCode < xorq > ( 0 , - 1 ) / / xorq - 1 , r <nl> ) ; <nl> EXPECT_EQ ( <nl> TEST ( Vasm , FoldImms ) { <nl> " xorqi - 1 , % 64 = > % 65 , % 67 \ n " <nl> " not % 64 = > % 66 \ n " <nl> " movl % 67 = > % 71 \ n " <nl> - " ret \ n " , <nl> + " ret { } \ n " , <nl> genTestCode < xorq > ( 1 , - 1 ) / / xorq r , - 1 <nl> ) ; <nl> } <nl> mmm a / hphp / runtime / vm / jit / code - gen - x64 . cpp <nl> ppp b / hphp / runtime / vm / jit / code - gen - x64 . cpp <nl> void CodeGenerator : : cgCallArray ( IRInstruction * inst ) { <nl> v < < syncvmsp { syncSP } ; <nl> <nl> auto done = v . makeBlock ( ) ; <nl> - v < < vcallstub { target , v . makeTuple ( { pc , after } ) , <nl> + v < < vcallstub { target , kCrossTraceRegs , v . makeTuple ( { pc , after } ) , <nl> { done , m_state . labels [ inst - > taken ( ) ] } } ; <nl> v = done ; <nl> v < < defvmsp { dstLoc ( inst , 0 ) . reg ( ) } ; <nl> void CodeGenerator : : cgInterpOneCF ( IRInstruction * inst ) { <nl> auto const adjustedSp = v . makeReg ( ) ; <nl> v < < lea { srcLoc ( inst , 0 ) . reg ( ) [ cellsToBytes ( spOff . offset ) ] , adjustedSp } ; <nl> v < < syncvmsp { adjustedSp } ; <nl> - v < < ldimml { pcOff , r32 ( rAsm ) } ; <nl> + v < < ldimmq { pcOff , rAsm } ; / / pcOff is int32_t but ldimmq keeps the type <nl> + / / system happy and generates the same code . <nl> assertx ( mcg - > tx ( ) . uniqueStubs . interpOneCFHelpers . count ( op ) ) ; <nl> v < < jmpi { mcg - > tx ( ) . uniqueStubs . interpOneCFHelpers [ op ] , <nl> kCrossTraceRegs | rAsm } ; <nl> mmm a / hphp / runtime / vm / jit / mc - generator . cpp <nl> ppp b / hphp / runtime / vm / jit / mc - generator . cpp <nl> void emitServiceReq ( Vout & v , TCA stub_block , <nl> } <nl> } <nl> } <nl> - v < < svcreq { req , v . makeTuple ( args ) , stub_block } ; <nl> + v < < svcreq { req , x64 : : kCrossTraceRegs , v . makeTuple ( args ) , stub_block } ; <nl> } <nl> <nl> } / / HPHP : : jit <nl> mmm a / hphp / runtime / vm / jit / phys - reg . cpp <nl> ppp b / hphp / runtime / vm / jit / phys - reg . cpp <nl> int PhysReg : : getNumSIMD ( ) { <nl> return mcg - > backEnd ( ) . abi ( ) . simd ( ) . size ( ) ; <nl> } <nl> <nl> + std : : string show ( RegSet regs ) { <nl> + auto & backEnd = mcg - > backEnd ( ) ; <nl> + std : : ostringstream out ; <nl> + auto sep = " " ; <nl> + <nl> + out < < ' { ' ; <nl> + regs . forEach ( [ & ] ( PhysReg r ) { <nl> + out < < sep ; <nl> + backEnd . streamPhysReg ( out , r ) ; <nl> + sep = " , " ; <nl> + } ) ; <nl> + out < < ' } ' ; <nl> + <nl> + return out . str ( ) ; <nl> + } <nl> + <nl> PhysRegSaverParity : : PhysRegSaverParity ( int parity , Vout & v , <nl> RegSet regs ) <nl> : m_as ( nullptr ) <nl> mmm a / hphp / runtime / vm / jit / phys - reg . h <nl> ppp b / hphp / runtime / vm / jit / phys - reg . h <nl> inline RegSet operator | ( RegSet regs , PhysReg r ) { <nl> return regs . add ( r ) ; <nl> } <nl> <nl> + std : : string show ( RegSet regs ) ; <nl> + <nl> static_assert ( std : : is_trivially_destructible < RegSet > : : value , <nl> " RegSet must have a trivial destructor " ) ; <nl> <nl> mmm a / hphp / runtime / vm / jit / vasm - arm . cpp <nl> ppp b / hphp / runtime / vm / jit / vasm - arm . cpp <nl> void Vgen : : emit ( tbcc & i ) { <nl> void lower_svcreq ( Vunit & unit , Vlabel b , Vinstr & inst ) { <nl> auto svcreq = inst . svcreq_ ; / / copy it <nl> auto origin = inst . origin ; <nl> - auto & argv = unit . tuples [ svcreq . args ] ; <nl> + auto & argv = unit . tuples [ svcreq . extraArgs ] ; <nl> unit . blocks [ b ] . code . pop_back ( ) ; / / delete the svcreq instruction <nl> Vout v ( unit , b , origin ) ; <nl> <nl> void lower_svcreq ( Vunit & unit , Vlabel b , Vinstr & inst ) { <nl> arg_dests . push_back ( d ) ; <nl> arg_regs | = d ; <nl> } <nl> - v < < copyargs { svcreq . args , v . makeTuple ( arg_dests ) } ; <nl> + v < < copyargs { svcreq . extraArgs , v . makeTuple ( arg_dests ) } ; <nl> / / Save VM regs <nl> PhysReg vmfp { rVmFp } , vmsp { rVmSp } , sp { vixl : : sp } , rdsp { rVmTl } ; <nl> v < < store { vmfp , rdsp [ rds : : kVmfpOff ] } ; <nl> mmm a / hphp / runtime / vm / jit / vasm - instr . h <nl> ppp b / hphp / runtime / vm / jit / vasm - instr . h <nl> struct Vunit ; <nl> O ( phijmp , Inone , U ( uses ) , Dn ) \ <nl> O ( phijcc , I ( cc ) , U ( uses ) U ( sf ) , Dn ) \ <nl> O ( store , Inone , U ( s ) U ( d ) , Dn ) \ <nl> - O ( svcreq , I ( req ) I ( stub_block ) , U ( args ) , Dn ) \ <nl> + O ( svcreq , I ( req ) I ( stub_block ) , U ( args ) U ( extraArgs ) , Dn ) \ <nl> O ( syncpoint , I ( fix ) , Un , Dn ) \ <nl> O ( unwind , Inone , Un , Dn ) \ <nl> O ( vcall , I ( call ) I ( destType ) I ( fixup ) , U ( args ) , D ( d ) ) \ <nl> O ( vinvoke , I ( call ) I ( destType ) I ( fixup ) , U ( args ) , D ( d ) ) \ <nl> - O ( vcallstub , I ( target ) , U ( args ) , Dn ) \ <nl> + O ( vcallstub , I ( target ) , U ( args ) U ( extraArgs ) , Dn ) \ <nl> O ( landingpad , Inone , Un , Dn ) \ <nl> O ( countbytecode , Inone , U ( base ) , D ( sf ) ) \ <nl> O ( defvmsp , Inone , Un , D ( d ) ) \ <nl> struct phidef { Vtuple defs ; } ; <nl> struct phijmp { Vlabel target ; Vtuple uses ; } ; <nl> struct phijcc { ConditionCode cc ; VregSF sf ; Vlabel targets [ 2 ] ; Vtuple uses ; } ; <nl> struct store { Vreg s ; Vptr d ; } ; <nl> - struct svcreq { ServiceRequest req ; Vtuple args ; TCA stub_block ; } ; <nl> + struct svcreq { ServiceRequest req ; RegSet args ; Vtuple extraArgs ; <nl> + TCA stub_block ; } ; <nl> struct syncpoint { Fixup fix ; } ; <nl> struct unwind { Vlabel targets [ 2 ] ; } ; <nl> <nl> struct vinvoke { CppCall call ; VcallArgsId args ; Vtuple d ; Vlabel targets [ 2 ] ; <nl> * Non - smashable PHP function call with exception edges and additional <nl> * integer arguments . <nl> * / <nl> - struct vcallstub { TCA target ; Vtuple args ; Vlabel targets [ 2 ] ; } ; <nl> + struct vcallstub { TCA target ; RegSet args ; Vtuple extraArgs ; <nl> + Vlabel targets [ 2 ] ; } ; <nl> <nl> struct landingpad { } ; <nl> struct countbytecode { Vreg base ; VregSF sf ; } ; <nl> mmm a / hphp / runtime / vm / jit / vasm - llvm . cpp <nl> ppp b / hphp / runtime / vm / jit / vasm - llvm . cpp <nl> VASM_OPCODES <nl> llvm : : Value * emitFuncPtr ( const std : : string & name , <nl> llvm : : FunctionType * type , <nl> uint64_t address ) ; <nl> - llvm : : CallInst * emitTraceletTailCall ( llvm : : Value * target ) ; <nl> + llvm : : CallInst * emitTraceletTailCall ( llvm : : Value * target , RegSet argRegs ) ; <nl> + std : : vector < llvm : : Value * > makePhysRegArgs ( <nl> + RegSet argRegs , std : : initializer_list < PhysReg > order ) ; <nl> <nl> / / Emit code for the pointer . Return value is of the given type , or <nl> / / < i { bits } * > for the second overload . <nl> O ( countbytecode ) <nl> defineValue ( x64 : : rVmSp , nullptr ) ; <nl> defineValue ( x64 : : rVmFp , nullptr ) ; <nl> defineValue ( x64 : : rStashedAR , nullptr ) ; <nl> + defineValue ( x64 : : rAsm , nullptr ) ; <nl> } <nl> <nl> timer . stop ( ) ; <nl> void LLVMEmitter : : emit ( const bindjmp & inst ) { <nl> ) ; <nl> auto stubName = folly : : sformat ( " bindjmpStub_ { } " , reqIp ) ; <nl> auto stubFunc = emitFuncPtr ( stubName , m_traceletFnTy , uint64_t ( reqIp ) ) ; <nl> - auto call = emitTraceletTailCall ( stubFunc ) ; <nl> + auto call = emitTraceletTailCall ( stubFunc , inst . args ) ; <nl> call - > setSmashable ( ) ; <nl> <nl> auto id = m_nextLocRec + + ; <nl> void LLVMEmitter : : emit ( const bindcall & inst ) { <nl> / / name to ensure LLVM doesn ' t collapse the calls together . <nl> auto funcName = m_tcMM - > getUniqueSymbolName ( " bindcall_ " ) ; <nl> auto func = emitFuncPtr ( funcName , m_bindcallFnTy , uint64_t ( inst . stub ) ) ; <nl> - std : : vector < llvm : : Value * > args { <nl> - value ( x64 : : rVmSp ) , value ( x64 : : rVmTl ) , value ( x64 : : rVmFp ) , <nl> - value ( x64 : : rStashedAR ) <nl> - } ; <nl> + auto args = makePhysRegArgs ( <nl> + inst . args , { x64 : : rVmSp , x64 : : rVmTl , x64 : : rVmFp , x64 : : rStashedAR } ) ; <nl> auto next = block ( inst . targets [ 0 ] ) ; <nl> auto unwind = block ( inst . targets [ 1 ] ) ; <nl> auto call = m_irb . CreateInvoke ( func , next , unwind , args ) ; <nl> void LLVMEmitter : : emit ( const vcallstub & inst ) { <nl> / / vcallstub is like bindcall but it ' s not smashable and it can take extra <nl> / / arguments . <nl> auto funcName = folly : : sformat ( " vcallstub_ { } " , inst . target ) ; <nl> - std : : vector < llvm : : Value * > args { <nl> - value ( x64 : : rVmSp ) , value ( x64 : : rVmTl ) , value ( x64 : : rVmFp ) , m_int64Undef <nl> - } ; <nl> - for ( auto arg : m_unit . tuples [ inst . args ] ) args . emplace_back ( value ( arg ) ) ; <nl> + auto args = makePhysRegArgs ( <nl> + inst . args , { x64 : : rVmSp , x64 : : rVmTl , x64 : : rVmFp , x64 : : rStashedAR } ) ; <nl> + for ( auto arg : m_unit . tuples [ inst . extraArgs ] ) args . emplace_back ( value ( arg ) ) ; <nl> std : : vector < llvm : : Type * > argTypes ( args . size ( ) , m_int64 ) ; <nl> auto funcTy = llvm : : FunctionType : : get ( m_int64 , argTypes , false ) ; <nl> auto func = emitFuncPtr ( funcName , funcTy , uint64_t ( inst . target ) ) ; <nl> void LLVMEmitter : : emit ( const bindjcc1st & inst ) { <nl> emitJcc ( <nl> inst . sf , inst . cc , " jcc1 " , <nl> [ & ] { <nl> - emit ( bindjmp { inst . targets [ 1 ] } ) ; <nl> + emit ( bindjmp { inst . targets [ 1 ] , TransFlags { } , inst . args } ) ; <nl> } <nl> ) ; <nl> <nl> - emit ( bindjmp { inst . targets [ 0 ] } ) ; <nl> + emit ( bindjmp { inst . targets [ 0 ] , TransFlags { } , inst . args } ) ; <nl> } <nl> <nl> void LLVMEmitter : : emit ( const bindjcc & inst ) { <nl> emitJcc ( <nl> inst . sf , inst . cc , " jcc " , <nl> [ & ] { <nl> - emit ( bindjmp { inst . target , inst . trflags } ) ; <nl> + emit ( bindjmp { inst . target , inst . trflags , inst . args } ) ; <nl> } <nl> ) ; <nl> } <nl> llvm : : Value * LLVMEmitter : : emitFuncPtr ( const std : : string & name , <nl> return funcPtr ; <nl> } <nl> <nl> - llvm : : CallInst * LLVMEmitter : : emitTraceletTailCall ( llvm : : Value * target ) { <nl> - std : : vector < llvm : : Value * > args { <nl> - value ( x64 : : rVmSp ) , value ( x64 : : rVmTl ) , value ( x64 : : rVmFp ) <nl> - } ; <nl> + / * <nl> + * Return a vector of values for the PhysRegs in ` order ' , using undef for any <nl> + * PhysRegs that aren ' t in argRegs . <nl> + * / <nl> + std : : vector < llvm : : Value * > LLVMEmitter : : makePhysRegArgs ( <nl> + RegSet argRegs , <nl> + std : : initializer_list < PhysReg > order <nl> + ) { <nl> + RegSet passed ; <nl> + std : : vector < llvm : : Value * > ret ; <nl> + ret . reserve ( order . size ( ) ) ; <nl> + <nl> + for ( auto reg : order ) { <nl> + if ( argRegs . contains ( reg ) ) { <nl> + ret . emplace_back ( value ( reg ) ) ; <nl> + passed . add ( reg ) ; <nl> + } else { <nl> + ret . emplace_back ( m_int64Undef ) ; <nl> + } <nl> + } <nl> + <nl> + always_assert_flog ( passed = = argRegs , <nl> + " argRegs = { } , but only passed { } " , <nl> + show ( argRegs ) , show ( passed ) ) ; <nl> + return ret ; <nl> + } <nl> + <nl> + llvm : : CallInst * LLVMEmitter : : emitTraceletTailCall ( llvm : : Value * target , <nl> + RegSet argRegs ) { <nl> + auto args = makePhysRegArgs ( argRegs , { x64 : : rVmSp , x64 : : rVmTl , x64 : : rVmFp } ) ; <nl> auto call = m_irb . CreateCall ( target , args ) ; <nl> call - > setCallingConv ( llvm : : CallingConv : : X86_64_HHVM_TC ) ; <nl> call - > setTailCallKind ( llvm : : CallInst : : TCK_MustTail ) ; <nl> void LLVMEmitter : : emit ( const fallback & inst ) { <nl> auto func = emitFuncPtr ( folly : : sformat ( " reqRetranslate_ { } " , stub ) , <nl> m_traceletFnTy , <nl> uint64_t ( stub ) ) ; <nl> - auto call = emitTraceletTailCall ( func ) ; <nl> + auto call = emitTraceletTailCall ( func , inst . args ) ; <nl> call - > setSmashable ( ) ; <nl> <nl> LLVMFallback req { m_nextLocRec + + , inst . dest } ; <nl> void LLVMEmitter : : emit ( const jmp & inst ) { <nl> <nl> void LLVMEmitter : : emit ( const jmpr & inst ) { <nl> auto func = m_irb . CreateIntToPtr ( value ( inst . target ) , ptrType ( m_traceletFnTy ) ) ; <nl> - emitTraceletTailCall ( func ) ; <nl> + emitTraceletTailCall ( func , inst . args ) ; <nl> } <nl> <nl> void LLVMEmitter : : emit ( const jmpm & inst ) { <nl> auto func = m_irb . CreateLoad ( emitPtr ( inst . target , <nl> ptrType ( ptrType ( m_traceletFnTy ) ) ) ) ; <nl> - emitTraceletTailCall ( func ) ; <nl> + emitTraceletTailCall ( func , inst . args ) ; <nl> } <nl> <nl> void LLVMEmitter : : emit ( const jmpi & inst ) { <nl> - std : : vector < llvm : : Value * > args ; <nl> - std : : vector < llvm : : Type * > argTypes ; <nl> - <nl> - if ( inst . target = = mcg - > tx ( ) . uniqueStubs . endCatchHelper ) { <nl> - assert_not_implemented ( inst . args = = ( x64 : : rVmTl | x64 : : rVmFp ) ) ; <nl> - args = { m_int64Undef , value ( x64 : : rVmTl ) , value ( x64 : : rVmFp ) } ; <nl> - argTypes . resize ( 3 , m_int64 ) ; <nl> - } else { <nl> - assert_not_implemented ( inst . args = = ( x64 : : kCrossTraceRegs | x64 : : rAsm ) ) ; <nl> - args = { <nl> - value ( x64 : : rVmSp ) , value ( x64 : : rVmTl ) , value ( x64 : : rVmFp ) , <nl> - zext ( value ( x64 : : rAsm ) , 64 ) <nl> - } ; <nl> - argTypes . resize ( 4 , m_int64 ) ; <nl> - } <nl> + auto args = makePhysRegArgs ( <nl> + inst . args , { x64 : : rVmSp , x64 : : rVmTl , x64 : : rVmFp , x64 : : rAsm } ) ; <nl> + std : : vector < llvm : : Type * > argTypes ( args . size ( ) , m_int64 ) ; <nl> <nl> auto func = emitFuncPtr ( <nl> folly : : sformat ( " jmpi_ { } " , inst . target ) , <nl> void LLVMEmitter : : emit ( const ldimml & inst ) { <nl> } <nl> <nl> void LLVMEmitter : : emit ( const ldimmq & inst ) { <nl> - assertx ( inst . d . isVirt ( ) ) ; <nl> defineValue ( inst . d , cns ( inst . s . q ( ) ) ) ; <nl> } <nl> <nl> UNUSED void LLVMEmitter : : emitAsm ( const std : : string & asmStatement , <nl> } <nl> <nl> void LLVMEmitter : : emit ( const vretm & inst ) { <nl> - assert_not_implemented ( inst . args = = x64 : : kCrossTraceRegs ) ; <nl> auto const retPtr = emitPtr ( inst . retAddr , ptrType ( ptrType ( m_traceletFnTy ) ) ) ; <nl> auto const retAddr = m_irb . CreateLoad ( retPtr ) ; <nl> auto const prevFp = m_irb . CreateLoad ( emitPtr ( inst . prevFp , 64 ) ) ; <nl> defineValue ( inst . d , prevFp ) ; <nl> <nl> / / " Return " with a tail call to the loaded address <nl> - emitTraceletTailCall ( retAddr ) ; <nl> + emitTraceletTailCall ( retAddr , inst . args ) ; <nl> } <nl> <nl> void LLVMEmitter : : emit ( const vret & inst ) { <nl> - assert_not_implemented ( inst . args = = x64 : : kCrossTraceRegs ) ; <nl> auto const retAddr = m_irb . CreateIntToPtr ( value ( inst . retAddr ) , <nl> ptrType ( m_traceletFnTy ) ) ; <nl> - emitTraceletTailCall ( retAddr ) ; <nl> + emitTraceletTailCall ( retAddr , inst . args ) ; <nl> } <nl> <nl> void LLVMEmitter : : emit ( const absdbl & inst ) { <nl> void LLVMEmitter : : emit ( const subsd & inst ) { <nl> } <nl> <nl> void LLVMEmitter : : emit ( const svcreq & inst ) { <nl> - std : : vector < llvm : : Value * > args { <nl> - value ( x64 : : rVmSp ) , <nl> - value ( x64 : : rVmTl ) , <nl> - value ( x64 : : rVmFp ) , <nl> - cns ( reinterpret_cast < uintptr_t > ( inst . stub_block ) ) , <nl> - cns ( uint64_t { inst . req } ) <nl> - } ; <nl> - for ( auto arg : m_unit . tuples [ inst . args ] ) { <nl> + auto args = makePhysRegArgs ( inst . args , { x64 : : rVmSp , x64 : : rVmTl , x64 : : rVmFp } ) ; <nl> + args . emplace_back ( cns ( reinterpret_cast < uintptr_t > ( inst . stub_block ) ) ) ; <nl> + args . emplace_back ( cns ( uint64_t { inst . req } ) ) ; <nl> + for ( auto arg : m_unit . tuples [ inst . extraArgs ] ) { <nl> args . push_back ( value ( arg ) ) ; <nl> } <nl> - <nl> std : : vector < llvm : : Type * > argTypes ( args . size ( ) , m_int64 ) ; <nl> auto funcType = llvm : : FunctionType : : get ( m_void , argTypes , false ) ; <nl> auto func = emitFuncPtr ( folly : : to < std : : string > ( " handleSRHelper_ " , <nl> mmm a / hphp / runtime / vm / jit / vasm - print . cpp <nl> ppp b / hphp / runtime / vm / jit / vasm - print . cpp <nl> struct FormatVisitor { <nl> } <nl> <nl> void print ( RegSet regs ) { <nl> - regs . forEach ( [ & ] ( Vreg r ) { print ( r ) ; } ) ; <nl> + str < < sep ( ) < < show ( regs ) ; <nl> } <nl> <nl> void print ( Vreg r ) { <nl> mmm a / hphp / runtime / vm / jit / vasm - x64 . cpp <nl> ppp b / hphp / runtime / vm / jit / vasm - x64 . cpp <nl> void vector_splice ( V & out , size_t idx , size_t count , V & in ) { <nl> / / at the end of a block , so we can just keep appending to the same <nl> / / block . <nl> void lower_svcreq ( Vunit & unit , Vlabel b , const Vinstr & inst ) { <nl> - assertx ( unit . tuples [ inst . svcreq_ . args ] . size ( ) < kNumServiceReqArgRegs ) ; <nl> + assertx ( unit . tuples [ inst . svcreq_ . extraArgs ] . size ( ) < kNumServiceReqArgRegs ) ; <nl> auto svcreq = inst . svcreq_ ; / / copy it <nl> auto origin = inst . origin ; <nl> - auto & argv = unit . tuples [ svcreq . args ] ; <nl> + auto & argv = unit . tuples [ svcreq . extraArgs ] ; <nl> unit . blocks [ b ] . code . pop_back ( ) ; / / delete the svcreq instruction <nl> Vout v ( unit , b , origin ) ; <nl> <nl> - RegSet arg_regs = kCrossTraceRegs ; <nl> + RegSet arg_regs = svcreq . args ; <nl> VregList arg_dests ; <nl> for ( int i = 0 , n = argv . size ( ) ; i < n ; + + i ) { <nl> PhysReg d { serviceReqArgRegs [ i ] } ; <nl> arg_dests . push_back ( d ) ; <nl> arg_regs | = d ; <nl> } <nl> - v < < copyargs { svcreq . args , v . makeTuple ( arg_dests ) } ; <nl> + v < < copyargs { svcreq . extraArgs , v . makeTuple ( arg_dests ) } ; <nl> if ( svcreq . stub_block ) { <nl> v < < leap { rip [ ( int64_t ) svcreq . stub_block ] , rAsm } ; <nl> } else { <nl> void lower_vcallstub ( Vunit & unit , Vlabel b ) { <nl> auto const inst = code . back ( ) . get < vcallstub > ( ) ; <nl> auto const origin = code . back ( ) . origin ; <nl> <nl> - auto argRegs = kCrossTraceRegs ; <nl> - auto const & srcs = unit . tuples [ inst . args ] ; <nl> + auto argRegs = inst . args ; <nl> + auto const & srcs = unit . tuples [ inst . extraArgs ] ; <nl> jit : : vector < Vreg > dsts ; <nl> for ( int i = 0 ; i < srcs . size ( ) ; + + i ) { <nl> dsts . emplace_back ( argNumToRegName [ i ] ) ; <nl> | Don ' t ignore args RegSets in vasm - llvm | facebook/hhvm | 949a1f94b6a04e5401cc766bc070f47ec22e1f11 | 2015-04-10T00:00:48Z |
mmm a / include / spdlog / details / format . cc <nl> ppp b / include / spdlog / details / format . cc <nl> FMT_FUNC void fmt : : internal : : report_unknown_type ( char code , const char * type ) { <nl> <nl> # ifdef _WIN32 <nl> <nl> - fmt : : internal : : UTF8ToUTF16 : : UTF8ToUTF16 ( fmt : : StringRef s ) { <nl> + FMT_FUNC fmt : : internal : : UTF8ToUTF16 : : UTF8ToUTF16 ( fmt : : StringRef s ) { <nl> int length = MultiByteToWideChar ( <nl> CP_UTF8 , MB_ERR_INVALID_CHARS , s . c_str ( ) , - 1 , 0 , 0 ) ; <nl> static const char ERROR [ ] = " cannot convert string from UTF - 8 to UTF - 16 " ; <nl> fmt : : internal : : UTF8ToUTF16 : : UTF8ToUTF16 ( fmt : : StringRef s ) { <nl> FMT_THROW ( WindowsError ( GetLastError ( ) , ERROR ) ) ; <nl> } <nl> <nl> - fmt : : internal : : UTF16ToUTF8 : : UTF16ToUTF8 ( fmt : : WStringRef s ) { <nl> + FMT_FUNC fmt : : internal : : UTF16ToUTF8 : : UTF16ToUTF8 ( fmt : : WStringRef s ) { <nl> if ( int error_code = convert ( s ) ) { <nl> FMT_THROW ( WindowsError ( error_code , <nl> " cannot convert string from UTF - 16 to UTF - 8 " ) ) ; <nl> } <nl> } <nl> <nl> - int fmt : : internal : : UTF16ToUTF8 : : convert ( fmt : : WStringRef s ) { <nl> + FMT_FUNC int fmt : : internal : : UTF16ToUTF8 : : convert ( fmt : : WStringRef s ) { <nl> int length = WideCharToMultiByte ( CP_UTF8 , 0 , s . c_str ( ) , - 1 , 0 , 0 , 0 , 0 ) ; <nl> if ( length = = 0 ) <nl> return GetLastError ( ) ; <nl> int fmt : : internal : : UTF16ToUTF8 : : convert ( fmt : : WStringRef s ) { <nl> return 0 ; <nl> } <nl> <nl> - void fmt : : WindowsError : : init ( <nl> + FMT_FUNC void fmt : : WindowsError : : init ( <nl> int error_code , StringRef format_str , ArgList args ) { <nl> error_code_ = error_code ; <nl> MemoryWriter w ; <nl> FMT_FUNC void fmt : : internal : : format_system_error ( <nl> } <nl> <nl> # ifdef _WIN32 <nl> - void fmt : : internal : : format_windows_error ( <nl> + FMT_FUNC void fmt : : internal : : format_windows_error ( <nl> fmt : : Writer & out , int error_code , <nl> fmt : : StringRef message ) FMT_NOEXCEPT ( true ) { <nl> class String { <nl> FMT_FUNC void fmt : : report_system_error ( <nl> } <nl> <nl> # ifdef _WIN32 <nl> - void fmt : : report_windows_error ( <nl> + FMT_FUNC void fmt : : report_windows_error ( <nl> int error_code , fmt : : StringRef message ) FMT_NOEXCEPT ( true ) { <nl> report_error ( internal : : format_windows_error , error_code , message ) ; <nl> } <nl> | Fixed linkage errors under VC on the new version | gabime/spdlog | b1a495dbb096099de3752dadc8b20732ba0ba5b5 | 2014-12-07T14:34:22Z |
mmm a / torch / utils / tensorboard / _pytorch_graph . py <nl> ppp b / torch / utils / tensorboard / _pytorch_graph . py <nl> <nl> import logging <nl> - import numpy as np <nl> - import time <nl> from collections import OrderedDict <nl> <nl> from tensorboard . compat . proto . config_pb2 import RunMetadata <nl> from tensorboard . compat . proto . graph_pb2 import GraphDef <nl> - from tensorboard . compat . proto . step_stats_pb2 import StepStats , DeviceStepStats , NodeExecStats , AllocatorMemoryUsed <nl> + from tensorboard . compat . proto . step_stats_pb2 import StepStats , DeviceStepStats <nl> from tensorboard . compat . proto . versions_pb2 import VersionDef <nl> <nl> import torch <nl> def to_proto ( self ) : <nl> # TODO : compute correct memory usage and CPU time once <nl> # PyTorch supports it <nl> nodes = [ ] <nl> - node_stats = [ ] <nl> for v in self . nodes_io . values ( ) : <nl> nodes . append ( node_proto ( v . uniqueName , <nl> input = v . inputs , <nl> outputsize = v . tensor_size , <nl> op = v . kind , <nl> attributes = v . attributes ) ) <nl> - <nl> - if v . tensor_size and len ( v . tensor_size ) > 0 : # assume data is float32 , only parameter is counted <nl> - node_stats . append ( <nl> - NodeExecStats ( node_name = v . uniqueName , <nl> - all_start_micros = int ( time . time ( ) * 1e7 ) , <nl> - all_end_rel_micros = 42 , <nl> - memory = [ AllocatorMemoryUsed ( allocator_name = " cpu " , <nl> - total_bytes = int ( np . prod ( v . tensor_size ) ) * 4 ) ] ) ) <nl> - <nl> - return nodes , node_stats <nl> + return nodes <nl> <nl> <nl> def parse ( graph , args = None , omit_useless_nodes = True ) : <nl> def graph ( model , args , verbose = False , operator_export_type = ' ONNX ' , omit_useless_ <nl> graph = trace . graph ( ) <nl> if verbose : <nl> print ( graph ) <nl> - list_of_nodes , node_stats = parse ( graph , args , omit_useless_nodes ) <nl> + list_of_nodes = parse ( graph , args , omit_useless_nodes ) <nl> # We are hardcoding that this was run on CPU even though it might have actually <nl> # run on GPU . Note this is what is shown in TensorBoard and has no bearing <nl> # on actual execution . <nl> def graph ( model , args , verbose = False , operator_export_type = ' ONNX ' , omit_useless_ <nl> # https : / / github . com / tensorflow / tensorboard / blob / master / tensorboard / plugins / graph / tf_graph_common / test / graph - test . ts <nl> # and <nl> # https : / / github . com / tensorflow / tensorboard / blob / master / tensorboard / compat / proto / step_stats . proto <nl> - stepstats = RunMetadata ( step_stats = StepStats ( dev_stats = [ DeviceStepStats ( device = " / device : CPU : 0 " , <nl> - node_stats = node_stats ) ] ) ) <nl> + stepstats = RunMetadata ( step_stats = StepStats ( dev_stats = [ DeviceStepStats ( device = " / device : CPU : 0 " ) ] ) ) <nl> return GraphDef ( node = list_of_nodes , versions = VersionDef ( producer = 22 ) ) , stepstats <nl> | Remove NodeExecStats and AllocatorMemoryUsed ( ) | pytorch/pytorch | 3b6362d98e1f99e497b82fe005fec0ef11201e86 | 2019-06-06T20:35:52Z |
mmm a / test / test262 / test262 . status <nl> ppp b / test / test262 / test262 . status <nl> <nl> ' built - ins / Atomics / wake / count - defaults - to - infinity - undefined ' : [ SKIP ] , <nl> ' built - ins / Atomics / wake / undefined - index - defaults - to - zero ' : [ SKIP ] , <nl> <nl> + # Flaky failure <nl> + # https : / / bugs . chromium . org / p / v8 / issues / detail ? id = 7876 <nl> + ' built - ins / Atomics / wait / waiterlist - block - indexedposition - wake ' : [ SKIP ] , <nl> + <nl> # # # # # # # # # # # # # # # # # # # # # DELIBERATE INCOMPATIBILITIES # # # # # # # # # # # # # # # # # # # # # <nl> <nl> # https : / / github . com / tc39 / ecma262 / pull / 889 <nl> | Skip flaky test262 Atomics test | v8/v8 | d64e990865a0b907f1cd6fbca6d1647902288330 | 2018-06-21T16:16:36Z |
mmm a / src / heap / incremental - marking - inl . h <nl> ppp b / src / heap / incremental - marking - inl . h <nl> void IncrementalMarking : : BlackToGreyAndUnshift ( HeapObject * obj , <nl> } <nl> } <nl> <nl> - heap_ - > mark_compact_collector ( ) - > marking_deque ( ) - > UnshiftGrey ( obj ) ; <nl> + heap_ - > mark_compact_collector ( ) - > marking_deque ( ) - > Unshift ( obj ) ; <nl> } <nl> <nl> <nl> void IncrementalMarking : : WhiteToGreyAndPush ( HeapObject * obj , MarkBit mark_bit ) { <nl> Marking : : WhiteToGrey ( mark_bit ) ; <nl> - heap_ - > mark_compact_collector ( ) - > marking_deque ( ) - > PushGrey ( obj ) ; <nl> + heap_ - > mark_compact_collector ( ) - > marking_deque ( ) - > Push ( obj ) ; <nl> } <nl> } <nl> } / / namespace v8 : : internal <nl> mmm a / src / heap / incremental - marking . cc <nl> ppp b / src / heap / incremental - marking . cc <nl> class IncrementalMarkingMarkingVisitor <nl> chunk - > set_progress_bar ( start_offset ) ; <nl> if ( start_offset < object_size ) { <nl> if ( Marking : : IsGrey ( Marking : : MarkBitFrom ( object ) ) ) { <nl> - heap - > mark_compact_collector ( ) - > marking_deque ( ) - > UnshiftGrey ( object ) ; <nl> + heap - > mark_compact_collector ( ) - > marking_deque ( ) - > Unshift ( object ) ; <nl> } else { <nl> DCHECK ( Marking : : IsBlack ( Marking : : MarkBitFrom ( object ) ) ) ; <nl> heap - > mark_compact_collector ( ) - > UnshiftBlack ( object ) ; <nl> mmm a / src / heap / mark - compact - inl . h <nl> ppp b / src / heap / mark - compact - inl . h <nl> void MarkCompactCollector : : SetFlags ( int flags ) { <nl> <nl> <nl> void MarkCompactCollector : : PushBlack ( HeapObject * obj ) { <nl> - if ( marking_deque_ . PushBlack ( obj ) ) { <nl> + DCHECK ( Marking : : IsBlack ( Marking : : MarkBitFrom ( obj ) ) ) ; <nl> + if ( marking_deque_ . Push ( obj ) ) { <nl> MemoryChunk : : IncrementLiveBytesFromGC ( obj , obj - > Size ( ) ) ; <nl> } else { <nl> Marking : : BlackToGrey ( obj ) ; <nl> void MarkCompactCollector : : PushBlack ( HeapObject * obj ) { <nl> <nl> <nl> void MarkCompactCollector : : UnshiftBlack ( HeapObject * obj ) { <nl> - if ( ! marking_deque_ . UnshiftBlack ( obj ) ) { <nl> + DCHECK ( Marking : : IsBlack ( Marking : : MarkBitFrom ( obj ) ) ) ; <nl> + if ( ! marking_deque_ . Unshift ( obj ) ) { <nl> MemoryChunk : : IncrementLiveBytesFromGC ( obj , - obj - > Size ( ) ) ; <nl> Marking : : BlackToGrey ( obj ) ; <nl> } <nl> mmm a / src / heap / mark - compact . h <nl> ppp b / src / heap / mark - compact . h <nl> class MarkingDeque { <nl> <nl> void SetOverflowed ( ) { overflowed_ = true ; } <nl> <nl> - / / Push the ( marked ) object on the marking stack if there is room , otherwise <nl> - / / mark the deque as overflowed and wait for a rescan of the heap . <nl> - INLINE ( bool PushBlack ( HeapObject * object ) ) { <nl> + / / Push the object on the marking stack if there is room , otherwise mark the <nl> + / / deque as overflowed and wait for a rescan of the heap . <nl> + INLINE ( bool Push ( HeapObject * object ) ) { <nl> DCHECK ( object - > IsHeapObject ( ) ) ; <nl> if ( IsFull ( ) ) { <nl> SetOverflowed ( ) ; <nl> class MarkingDeque { <nl> } <nl> } <nl> <nl> - INLINE ( void PushGrey ( HeapObject * object ) ) { <nl> - DCHECK ( object - > IsHeapObject ( ) ) ; <nl> - if ( IsFull ( ) ) { <nl> - SetOverflowed ( ) ; <nl> - } else { <nl> - array_ [ top_ ] = object ; <nl> - top_ = ( ( top_ + 1 ) & mask_ ) ; <nl> - } <nl> - } <nl> - <nl> INLINE ( HeapObject * Pop ( ) ) { <nl> DCHECK ( ! IsEmpty ( ) ) ; <nl> top_ = ( ( top_ - 1 ) & mask_ ) ; <nl> class MarkingDeque { <nl> return object ; <nl> } <nl> <nl> - INLINE ( void UnshiftGrey ( HeapObject * object ) ) { <nl> - DCHECK ( object - > IsHeapObject ( ) ) ; <nl> - if ( IsFull ( ) ) { <nl> - SetOverflowed ( ) ; <nl> - } else { <nl> - bottom_ = ( ( bottom_ - 1 ) & mask_ ) ; <nl> - array_ [ bottom_ ] = object ; <nl> - } <nl> - } <nl> - <nl> - INLINE ( bool UnshiftBlack ( HeapObject * object ) ) { <nl> + / / Unshift the object into the marking stack if there is room , otherwise mark <nl> + / / the deque as overflowed and wait for a rescan of the heap . <nl> + INLINE ( bool Unshift ( HeapObject * object ) ) { <nl> DCHECK ( object - > IsHeapObject ( ) ) ; <nl> - DCHECK ( Marking : : IsBlack ( Marking : : MarkBitFrom ( object ) ) ) ; <nl> if ( IsFull ( ) ) { <nl> SetOverflowed ( ) ; <nl> return false ; <nl> mmm a / test / cctest / test - mark - compact . cc <nl> ppp b / test / cctest / test - mark - compact . cc <nl> TEST ( MarkingDeque ) { <nl> Address original_address = reinterpret_cast < Address > ( & s ) ; <nl> Address current_address = original_address ; <nl> while ( ! s . IsFull ( ) ) { <nl> - s . PushBlack ( HeapObject : : FromAddress ( current_address ) ) ; <nl> + s . Push ( HeapObject : : FromAddress ( current_address ) ) ; <nl> current_address + = kPointerSize ; <nl> } <nl> <nl> | [ heap ] Unify MarkingDeque push and unshift operations . | v8/v8 | 26241740bbbd5990eb940154c53ab85f0c5628cc | 2015-08-17T16:58:28Z |
mmm a / s / commands_public . cpp <nl> ppp b / s / commands_public . cpp <nl> namespace mongo { <nl> <nl> log ( ) < < " DROP DATABASE : " < < dbName < < endl ; <nl> <nl> - if ( ! conf | | ! conf - > isShardingEnabled ( ) ) { <nl> + if ( ! conf ) { <nl> log ( 1 ) < < " passing though drop database for : " < < dbName < < endl ; <nl> return passthrough ( conf , cmdObj , result ) ; <nl> } <nl> | SERVER - 1301 Let DBConfig perform the drop database logic | mongodb/mongo | 97dc2c6b1273b0bdb4b292f77dc6e37c86f4f31d | 2010-06-30T20:13:18Z |
mmm a / config / openalpr . conf . in <nl> ppp b / config / openalpr . conf . in <nl> max_detection_input_height = 720 <nl> ; morphcpu - Experimental detector that detects white rectangles in an image . Does not require training . <nl> detector = lbpcpu <nl> <nl> + ; If set to true , all results must match a postprocess text pattern if a pattern is available . <nl> + ; If not , the result is disqualified . <nl> + must_match_pattern = 0 <nl> + <nl> ; Bypasses plate detection . If this is set to 1 , the library assumes that each region provided is a likely plate area . <nl> skip_detection = 0 <nl> <nl> mmm a / src / openalpr / config . cpp <nl> ppp b / src / openalpr / config . cpp <nl> namespace alpr <nl> maxDetectionInputWidth = getInt ( ini , " " , " max_detection_input_width " , 1280 ) ; <nl> maxDetectionInputHeight = getInt ( ini , " " , " max_detection_input_height " , 768 ) ; <nl> <nl> + mustMatchPattern = getBoolean ( ini , " " , " must_match_pattern " , false ) ; <nl> + <nl> skipDetection = getBoolean ( ini , " " , " skip_detection " , false ) ; <nl> <nl> prewarp = getString ( ini , " " , " prewarp " , " " ) ; <nl> mmm a / src / openalpr / config . h <nl> ppp b / src / openalpr / config . h <nl> namespace alpr <nl> std : : string ocrLanguage ; <nl> int ocrMinFontSize ; <nl> <nl> + bool mustMatchPattern ; <nl> + <nl> float postProcessMinConfidence ; <nl> float postProcessConfidenceSkipLevel ; <nl> unsigned int postProcessMinCharacters ; <nl> mmm a / src / openalpr / postprocess / postprocess . cpp <nl> ppp b / src / openalpr / postprocess / postprocess . cpp <nl> namespace alpr <nl> if ( allPossibilitiesLetters . end ( ) ! = allPossibilitiesLetters . find ( possibility . letters ) ) <nl> return false ; <nl> <nl> - allPossibilities . push_back ( possibility ) ; <nl> - allPossibilitiesLetters . insert ( possibility . letters ) ; <nl> - return true ; <nl> + / / If mustMatchPattern is toggled in the config and a template is provided , <nl> + / / only include this result if there is a pattern match <nl> + if ( ! config - > mustMatchPattern | | templateregion . size ( ) = = 0 | | <nl> + ( config - > mustMatchPattern & & possibility . matchesTemplate ) ) <nl> + { <nl> + allPossibilities . push_back ( possibility ) ; <nl> + allPossibilitiesLetters . insert ( possibility . letters ) ; <nl> + return true ; <nl> + } <nl> + <nl> + return false ; <nl> } <nl> <nl> std : : vector < string > PostProcess : : getPatterns ( ) { <nl> | Added a must_match_pattern config option . When a text pattern is available , all non - matching values will be disregarded . | openalpr/openalpr | 61f37ba596949e87e29d4fc3b00f9bb5fca1ef65 | 2015-10-01T02:03:01Z |
mmm a / src / taichi_llvm_context . cpp <nl> ppp b / src / taichi_llvm_context . cpp <nl> TLANG_NAMESPACE_BEGIN <nl> static llvm : : ExitOnError exit_on_err ; <nl> <nl> TaichiLLVMContext : : TaichiLLVMContext ( ) { <nl> - return ; <nl> llvm : : InitializeNativeTarget ( ) ; <nl> llvm : : InitializeNativeTargetAsmPrinter ( ) ; <nl> llvm : : InitializeNativeTargetAsmParser ( ) ; <nl> | reenable llvm after fixing glibc ABI version issue on Ubuntu | taichi-dev/taichi | a354c0a850a332d3208ade3f30d62f9b51de4b74 | 2019-07-26T22:21:06Z |
mmm a / emcc <nl> ppp b / emcc <nl> Options that are modified or new in % s include : <nl> slower because JS optimization will be <nl> limited to 1 core . ( default in - O0 ) <nl> <nl> - - g2 Like - g1 , but we generate source maps as well , <nl> - and we preserve comments even with - O1 and above . <nl> - Note that this may be considerably slower because <nl> - JS optimization is limited to a single core . <nl> - <nl> - - typed - arrays < mode > 0 : No typed arrays <nl> 1 : Parallel typed arrays <nl> 2 : Shared ( C - like ) typed arrays ( default ) <nl> | remove incorrect comment | emscripten-core/emscripten | deacdfa1297cb3bbbb8aedb439f52aae11571630 | 2013-06-26T18:47:20Z |
mmm a / include / mxnet / c_api . h <nl> ppp b / include / mxnet / c_api . h <nl> MXNET_DLL int MXCreateCachedOpEx ( SymbolHandle handle , <nl> int num_flags , <nl> const char * * keys , <nl> const char * * vals , <nl> - int num_inputs , <nl> - const char * * input_names , <nl> - int num_params , <nl> - const char * * param_names , <nl> - NDArrayHandle * params , <nl> CachedOpHandle * out ) ; <nl> / * ! <nl> * \ brief free cached operator <nl> mmm a / include / mxnet / imperative . h <nl> ppp b / include / mxnet / imperative . h <nl> <nl> # include " . / ndarray . h " <nl> <nl> namespace mxnet { <nl> - / * ! \ brief CachedOp Parameters * / <nl> - struct CachedOpConfig : public dmlc : : Parameter < CachedOpConfig > { <nl> - uint32_t inline_limit ; <nl> - uint32_t forward_bulk_size ; <nl> - uint32_t backward_bulk_size ; <nl> - DMLC_DECLARE_PARAMETER ( CachedOpConfig ) { <nl> - DMLC_DECLARE_FIELD ( inline_limit ) <nl> - . set_default ( 2 ) <nl> - . describe ( " Maximum number of operators that can be inlined . " ) ; <nl> - DMLC_DECLARE_FIELD ( forward_bulk_size ) <nl> - . set_default ( dmlc : : GetEnv ( " MXNET_EXEC_BULK_EXEC_MAX_NODE_TRAIN " , 15 ) ) <nl> - . describe ( " Segment size of bulk execution during forward pass . " ) ; <nl> - DMLC_DECLARE_FIELD ( backward_bulk_size ) <nl> - . set_default ( dmlc : : GetEnv ( " MXNET_EXEC_BULK_EXEC_MAX_NODE_TRAIN " , 15 ) ) <nl> - . describe ( " Segment size of bulk execution during backward pass . " ) ; <nl> - } <nl> - } ; <nl> / * ! \ brief runtime functions for NDArray * / <nl> class Imperative { <nl> public : <nl> class Imperative { <nl> & & info . out_grads . size ( ) = = 1 ; <nl> } <nl> } ; <nl> - class CachedOp { <nl> - public : <nl> - CachedOp ( <nl> - const nnvm : : Symbol & sym , <nl> - const std : : vector < std : : pair < std : : string , std : : string > > & flags , <nl> - const std : : vector < std : : string > arg_names , <nl> - const std : : unordered_map < std : : string , std : : vector < NDArray > > & params ) ; <nl> - uint32_t num_inputs ( ) { <nl> - return fwd_graph_ . indexed_graph ( ) . input_nodes ( ) . size ( ) ; <nl> - } <nl> - uint32_t num_outputs ( ) { <nl> - return fwd_graph_ . outputs . size ( ) ; <nl> - } <nl> - uint32_t num_backward_inputs ( ) { <nl> - return bwd_ograd_dep_ . size ( ) + bwd_in_dep_ . size ( ) + bwd_out_dep_ . size ( ) ; <nl> - } <nl> - std : : vector < bool > & save_inputs ( ) { <nl> - return save_inputs_ ; <nl> - } <nl> - std : : vector < bool > & save_outputs ( ) { <nl> - return save_outputs_ ; <nl> - } <nl> - const std : : unordered_set < uint32_t > & mutable_input_nodes ( ) { <nl> - return fwd_graph_ . indexed_graph ( ) . mutable_input_nodes ( ) ; <nl> - } <nl> - nnvm : : Graph GetForwardGraph ( const bool recording , <nl> - const std : : vector < NDArray * > & inputs ) ; <nl> - nnvm : : Graph GetBackwardGraph ( const OpStatePtr & state , <nl> - const std : : vector < OpReqType > & reqs , <nl> - const std : : vector < NDArray * > & inputs ) ; <nl> - std : : vector < nnvm : : NodeEntry > Gradient ( const nnvm : : NodePtr & node , <nl> - const std : : vector < nnvm : : NodeEntry > & ograds ) ; <nl> - void Forward ( const std : : shared_ptr < CachedOp > & op_ptr , <nl> - const std : : vector < NDArray * > & args , <nl> - const std : : vector < NDArray * > & outputs ) ; <nl> - void Backward ( const bool retain_graph , <nl> - const OpStatePtr & state , <nl> - const std : : vector < NDArray * > & inputs , <nl> - const std : : vector < OpReqType > & reqs , <nl> - const std : : vector < NDArray * > & outputs ) ; <nl> - <nl> - private : <nl> - struct CachedOpState { <nl> - std : : vector < NDArray > buff ; <nl> - std : : vector < OpStatePtr > states ; <nl> - } ; <nl> - std : : mutex mutex_ ; <nl> - CachedOpConfig config_ ; <nl> - nnvm : : Graph fwd_graph_ ; <nl> - nnvm : : Graph grad_graph_ ; <nl> - nnvm : : Graph full_graph_ ; <nl> - std : : unordered_map < Context , std : : vector < NDArray > > params_ ; <nl> - bool inlining_ ; <nl> - std : : vector < nnvm : : NodeEntry > ograd_entries_ ; <nl> - std : : vector < bool > curr_grad_req_ ; <nl> - std : : vector < uint32_t > bwd_in_dep_ , bwd_out_dep_ , bwd_ograd_dep_ ; <nl> - std : : vector < uint32_t > fwd_args_idx_ ; <nl> - std : : vector < uint32_t > fwd_params_idx_ ; <nl> - std : : vector < uint32_t > bwd_input_eid_ ; <nl> - std : : vector < bool > save_inputs_ , save_outputs_ ; <nl> - } ; <nl> / * ! \ brief whether operator recording is on . * / <nl> bool is_training ( ) const { <nl> return is_train_ ; <nl> class Imperative { <nl> uint32_t num_inputs , uint32_t num_outputs , <nl> std : : vector < bool > * p_save_inputs , <nl> std : : vector < bool > * p_save_outputs ) ; <nl> - void RunGraph ( <nl> - const bool retain_graph , <nl> - const nnvm : : IndexedGraph & idx , <nl> - const std : : vector < NDArray * > arrays , <nl> - size_t node_start , size_t node_end , <nl> - std : : vector < OpReqType > & & array_reqs , <nl> - std : : vector < uint32_t > & & ref_count , <nl> - std : : vector < OpStatePtr > * p_states , <nl> - const DispatchModeVector & dispatch_modes ) ; <nl> / * ! \ brief indicate whether is training . * / <nl> # if DMLC_CXX11_THREAD_LOCAL <nl> static thread_local bool is_train_ ; <nl> class Imperative { <nl> int backward_bulk_size_ { 0 } ; <nl> } ; <nl> <nl> - using CachedOpPtr = std : : shared_ptr < Imperative : : CachedOp > ; <nl> - <nl> } / / namespace mxnet <nl> # endif / / MXNET_IMPERATIVE_H_ <nl> mmm a / include / mxnet / ndarray . h <nl> ppp b / include / mxnet / ndarray . h <nl> class NDArray { <nl> return byte_offset_ > 0 | | shape ( ) ! = ptr_ - > storage_shape ; <nl> } <nl> <nl> + / * \ brief Check whether the two arrays are the same array * / <nl> + inline bool IsSame ( const NDArray & other ) { <nl> + return ptr_ = = other . ptr_ & & <nl> + shape_ = = other . shape_ & & <nl> + byte_offset_ = = other . byte_offset_ & & <nl> + dtype_ = = other . dtype_ ; <nl> + } <nl> + <nl> / * ! <nl> * \ return the shape of current NDArray . <nl> * / <nl> mmm a / include / mxnet / op_attr_types . h <nl> ppp b / include / mxnet / op_attr_types . h <nl> class OpStatePtr { <nl> template < typename T , typename . . . Args > <nl> static OpStatePtr Create ( Args & & . . . args ) { <nl> OpStatePtr ret ; <nl> - ret . ptr_ = std : : make_shared < OpState > ( ) ; <nl> - ret . ptr_ - > var_ = Engine : : Get ( ) - > NewVariable ( ) ; <nl> - ret . ptr_ - > state_ . construct < T > ( std : : forward < Args > ( args ) . . . ) ; <nl> + auto state = new T ( std : : forward < Args > ( args ) . . . ) ; <nl> + auto var = Engine : : Get ( ) - > NewVariable ( ) ; <nl> + ret . ptr_ . reset ( <nl> + new OpState ( var , state ) , <nl> + [ ] ( OpState * p ) { <nl> + Engine : : Get ( ) - > DeleteVariable ( [ ] ( RunContext s ) { } , Context : : CPU ( ) , p - > var ) ; <nl> + delete reinterpret_cast < T * > ( p - > state ) ; <nl> + delete p ; <nl> + } ) ; <nl> <nl> return ret ; <nl> } <nl> / * \ brief Get engine variable associated with this state * / <nl> engine : : VarHandle get_var ( ) const { <nl> - return ptr_ - > var_ ; <nl> + return ptr_ - > var ; <nl> } <nl> / * \ brief Get state of type T * / <nl> template < typename T > <nl> T & get_state ( ) const { <nl> - return dmlc : : get < T > ( ptr_ - > state_ ) ; <nl> + return * reinterpret_cast < T * > ( ptr_ - > state ) ; <nl> } <nl> / * \ brief clear state * / <nl> void reset ( ) { <nl> ptr_ . reset ( ) ; <nl> } <nl> + / * \ brief checks whether the managed object is managed only by the current <nl> + OpStatePtr instance * / <nl> + bool unique ( ) const { <nl> + return ptr_ . unique ( ) ; <nl> + } <nl> / * \ brief Whether state is empty * / <nl> explicit operator bool ( ) const { <nl> return ptr_ ? true : false ; <nl> class OpStatePtr { <nl> private : <nl> / * \ brief state structure * / <nl> struct OpState { <nl> - OpState ( ) { } <nl> + engine : : VarHandle var ; <nl> + void * state ; <nl> + <nl> + OpState ( engine : : VarHandle var_ , void * state_ ) : var ( var_ ) , state ( state_ ) { } <nl> OpState ( const OpState & other ) = delete ; <nl> OpState & operator = ( const OpState & other ) = delete ; <nl> - <nl> - ~ OpState ( ) { <nl> - Engine : : Get ( ) - > DeleteVariable ( [ ] ( RunContext s ) { } , Context : : CPU ( ) , var_ ) ; <nl> - } <nl> - <nl> - engine : : VarHandle var_ ; <nl> - dmlc : : any state_ ; <nl> } ; <nl> / * \ brief shared pointer to state * / <nl> std : : shared_ptr < OpState > ptr_ ; <nl> mmm a / python / mxnet / _ctypes / ndarray . py <nl> ppp b / python / mxnet / _ctypes / ndarray . py <nl> def _imperative_invoke ( handle , ndargs , keys , vals , out ) : <nl> class CachedOp ( object ) : <nl> " " " Cached operator handle . " " " <nl> __slots__ = [ " handle " ] <nl> - def __init__ ( self , sym , flags = ( ) , inputs = None , params = None ) : <nl> + def __init__ ( self , sym , flags = ( ) ) : <nl> self . handle = CachedOpHandle ( ) <nl> - param_names = [ ] <nl> - param_arrays = [ ] <nl> - if inputs is None : <nl> - assert params is None , " When inputs is None params must also be None . " <nl> - inputs = sym . list_inputs ( ) <nl> - elif params is not None : <nl> - for name , arrs in params . items ( ) : <nl> - param_arrays . extend ( arrs ) <nl> - param_names . extend ( [ name ] * len ( arrs ) ) <nl> <nl> check_call ( _LIB . MXCreateCachedOpEx ( <nl> sym . handle , <nl> len ( flags ) , <nl> c_str_array ( [ key for key , _ in flags ] ) , <nl> c_str_array ( [ str ( val ) for _ , val in flags ] ) , <nl> - len ( inputs ) , <nl> - c_str_array ( inputs ) , <nl> - len ( param_names ) , <nl> - c_str_array ( param_names ) , <nl> - c_handle_array ( param_arrays ) , <nl> ctypes . byref ( self . handle ) ) ) <nl> <nl> def __del__ ( self ) : <nl> mmm a / python / mxnet / gluon / block . py <nl> ppp b / python / mxnet / gluon / block . py <nl> def hybridize ( self , active = True , * * kwargs ) : <nl> mmmmmmmmm - <nl> active : bool , default True <nl> Whether to turn hybrid on or off . <nl> - * * kwargs : string <nl> - Additional flags for hybridized operator . <nl> + static_alloc : bool , default False <nl> + Statically allocate memory to improve speed . Memory usage may increase . <nl> + static_shape : bool , default False <nl> + Optimize for invariant input shapes between iterations . Must also <nl> + set static_alloc to True . Change of input shapes is still allowed <nl> + but slower . <nl> + forward_bulk_size : int , default 15 <nl> + Segment size of bulk execution during forward pass . <nl> + backward_bulk_size : int , default 15 <nl> + Segment size of bulk execution during backward pass . <nl> " " " <nl> for cld in self . _children . values ( ) : <nl> cld . hybridize ( active , * * kwargs ) <nl> def __init__ ( self , prefix = None , params = None ) : <nl> self . _out_format = None <nl> self . _in_format = None <nl> self . _active = False <nl> - self . _flags = { } <nl> + self . _flags = [ ] <nl> <nl> def __setattr__ ( self , name , value ) : <nl> " " " Registers parameters . " " " <nl> def _get_graph ( self , * args ) : <nl> return self . _cached_graph <nl> <nl> def _build_cache ( self , * args ) : <nl> - inputs , out = self . _get_graph ( * args ) <nl> - input_names = [ i . name for i in inputs ] <nl> - <nl> + data , out = self . _get_graph ( * args ) <nl> + data_names = { data . name : i for i , data in enumerate ( data ) } <nl> params = self . collect_params ( ) <nl> + input_names = out . list_inputs ( ) <nl> + <nl> param_names = set ( params . keys ( ) ) <nl> - expected_names = set ( out . list_inputs ( ) ) <nl> + expected_names = set ( input_names ) <nl> for name in expected_names : <nl> - assert name in param_names or name in input_names , \ <nl> + assert name in param_names or name in data_names , \ <nl> " Unknown input to HybridBlock : % s " % name <nl> <nl> - used_input_names = [ i for i in input_names if i in expected_names ] <nl> - if len ( used_input_names ) ! = len ( input_names ) : <nl> - unused = ' , ' . join ( [ ' % d - th ' % i for i , name in enumerate ( input_names ) <nl> + used_data_names = [ i for i in data_names if i in expected_names ] <nl> + if len ( used_data_names ) ! = len ( data_names ) : <nl> + unused = ' , ' . join ( [ ' % d - th ' % i for name , i in data_names . items ( ) <nl> if name not in expected_names ] ) <nl> warnings . warn ( " The % s input to HybridBlock is not used by any " <nl> " computation . Is this intended ? " % unused , stacklevel = 4 ) <nl> <nl> - used_param_names = set ( i for i in param_names if i in expected_names ) <nl> + used_param_names = [ i for i in param_names if i in expected_names ] <nl> if len ( used_param_names ) ! = len ( param_names ) : <nl> - unused = ' , ' . join ( list ( param_names - used_param_names ) ) <nl> + unused = ' , ' . join ( list ( param_names - set ( used_param_names ) ) ) <nl> warnings . warn ( " Parameter % s is not used by any computation . " <nl> " Is this intended ? " % unused , stacklevel = 4 ) <nl> <nl> - used_params = { k : params [ k ] for k in used_param_names } <nl> - try : <nl> - param_dict = { k : v . list_data ( ) for k , v in used_params . items ( ) } <nl> - except DeferredInitializationError : <nl> - self . _deferred_infer_shape ( * args ) <nl> - for i in used_params . values ( ) : <nl> - i . _finish_deferred_init ( ) <nl> - param_dict = { k : v . list_data ( ) for k , v in used_params . items ( ) } <nl> - <nl> - self . _cached_op = ndarray . CachedOp ( out , self . _flags , input_names , param_dict ) <nl> + data_indices = [ ] <nl> + param_indices = [ ] <nl> + self . _cached_op_args = [ ] <nl> + for i , name in enumerate ( input_names ) : <nl> + if name in data_names : <nl> + data_indices . append ( i ) <nl> + self . _cached_op_args . append ( ( True , data_names [ name ] ) ) <nl> + else : <nl> + param_indices . append ( i ) <nl> + self . _cached_op_args . append ( ( False , params [ name ] ) ) <nl> + flags = [ ( ' data_indices ' , data_indices ) , ( ' param_indices ' , param_indices ) ] + \ <nl> + self . _flags <nl> + self . _cached_op = ndarray . CachedOp ( out , flags ) <nl> <nl> def _deferred_infer_shape ( self , * args ) : <nl> try : <nl> def _call_cached_op ( self , * args ) : <nl> <nl> args , fmt = _flatten ( args , " input " ) <nl> assert fmt = = self . _in_format , " Invalid input format " <nl> - out = self . _cached_op ( * args ) <nl> + try : <nl> + cargs = [ args [ i ] if is_arg else i . data ( ) <nl> + for is_arg , i in self . _cached_op_args ] <nl> + except DeferredInitializationError : <nl> + self . _deferred_infer_shape ( * args ) <nl> + cargs = [ ] <nl> + for is_arg , i in self . _cached_op_args : <nl> + if is_arg : <nl> + cargs . append ( args [ i ] ) <nl> + else : <nl> + i . _finish_deferred_init ( ) <nl> + cargs . append ( i . data ( ) ) <nl> + out = self . _cached_op ( * cargs ) <nl> if isinstance ( out , NDArray ) : <nl> out = [ out ] <nl> return _regroup ( out , self . _out_format ) [ 0 ] <nl> def register_child ( self , block , name = None ) : <nl> <nl> def hybridize ( self , active = True , * * kwargs ) : <nl> self . _active = active <nl> - self . _flags = kwargs . items ( ) <nl> + self . _flags = list ( kwargs . items ( ) ) <nl> self . _clear_cached_op ( ) <nl> if active and self . _forward_hooks or self . _forward_pre_hooks : <nl> warnings . warn ( ' " { } " is being hybridized while still having forward hook / pre - hook . ' <nl> mmm a / src / c_api / c_api_ndarray . cc <nl> ppp b / src / c_api / c_api_ndarray . cc <nl> <nl> # include " . . / common / utils . h " <nl> # include " . . / common / exec_utils . h " <nl> # include " . . / imperative / imperative_utils . h " <nl> + # include " . . / imperative / cached_op . h " <nl> <nl> using namespace mxnet ; <nl> <nl> int MXCreateCachedOp ( SymbolHandle handle , <nl> std : : vector < std : : string > input_names ; <nl> input_names . reserve ( inputs . size ( ) ) ; <nl> for ( const auto & i : inputs ) input_names . push_back ( i - > attrs . name ) ; <nl> - * out = new std : : shared_ptr < Imperative : : CachedOp > ( <nl> - new Imperative : : CachedOp ( <nl> - * sym , <nl> - std : : vector < std : : pair < std : : string , std : : string > > ( ) , <nl> - input_names , <nl> - std : : unordered_map < std : : string , std : : vector < NDArray > > ( ) ) ) ; <nl> + * out = new CachedOpPtr ( new CachedOp ( <nl> + * sym , std : : vector < std : : pair < std : : string , std : : string > > ( ) ) ) ; <nl> API_END ( ) ; <nl> } <nl> <nl> int MXCreateCachedOpEx ( SymbolHandle handle , <nl> int num_flags , <nl> const char * * keys , <nl> const char * * vals , <nl> - int num_args , <nl> - const char * * arg_names , <nl> - int num_params , <nl> - const char * * param_names , <nl> - NDArrayHandle * params , <nl> CachedOpHandle * out ) { <nl> nnvm : : Symbol * sym = static_cast < nnvm : : Symbol * > ( handle ) ; <nl> <nl> int MXCreateCachedOpEx ( SymbolHandle handle , <nl> for ( int i = 0 ; i < num_flags ; + + i ) { <nl> flags . push_back ( { keys [ i ] , vals [ i ] } ) ; <nl> } <nl> - std : : vector < std : : string > args ; <nl> - for ( int i = 0 ; i < num_args ; + + i ) { <nl> - args . push_back ( arg_names [ i ] ) ; <nl> - } <nl> - std : : unordered_map < std : : string , std : : vector < NDArray > > param_dict ; <nl> - for ( int i = 0 ; i < num_params ; + + i ) { <nl> - param_dict [ param_names [ i ] ] . emplace_back ( <nl> - * reinterpret_cast < NDArray * > ( params [ i ] ) ) ; <nl> - } <nl> - * out = new std : : shared_ptr < Imperative : : CachedOp > ( <nl> - new Imperative : : CachedOp ( * sym , flags , args , param_dict ) ) ; <nl> + * out = new CachedOpPtr ( new CachedOp ( * sym , flags ) ) ; <nl> API_END ( ) ; <nl> } <nl> <nl> mmm a / src / engine / threaded_engine . cc <nl> ppp b / src / engine / threaded_engine . cc <nl> void ThreadedEngine : : DeleteOperator ( OprHandle op ) { <nl> } <nl> <nl> void ThreadedEngine : : Push ( OprHandle op , Context exec_ctx , int priority , bool profiling ) { <nl> + BulkFlush ( ) ; <nl> + <nl> ThreadedOpr * threaded_opr = ThreadedOpr : : CastFromBase ( op ) ; <nl> OprBlock * opr_block = OprBlock : : New ( ) ; <nl> opr_block - > opr = threaded_opr ; <nl> void ThreadedEngine : : PushAsync ( AsyncFn fn , Context exec_ctx , <nl> < < device_count_ ; <nl> } <nl> # endif <nl> - BulkFlush ( ) ; <nl> ThreadedOpr * opr = NewOperator ( std : : move ( fn ) , const_vars , mutable_vars , prop , opr_name , wait ) ; <nl> opr - > temporary = true ; <nl> const bool profiling = profiler_ - > IsProfiling ( profiler : : Profiler : : kImperative ) ; <nl> mmm a / src / executor / attach_op_execs_pass . cc <nl> ppp b / src / executor / attach_op_execs_pass . cc <nl> class StatefulComputeExecutor : public StorageFallbackOpExecutor { <nl> return state_ . get_var ( ) ; <nl> } <nl> <nl> + OpStatePtr state ( ) const override { <nl> + return state_ ; <nl> + } <nl> + <nl> explicit StatefulComputeExecutor ( const OpStatePtr & state , <nl> const FStatefulCompute & fcompute , <nl> ExecType exec_type , <nl> class StatefulComputeExecutor : public StorageFallbackOpExecutor { <nl> state_ ( state ) , fcompute_ ( fcompute ) , exec_type_ ( exec_type ) { } <nl> <nl> private : <nl> - friend Graph AttachOpExecs ( Graph g ) ; <nl> OpStatePtr state_ ; <nl> FStatefulCompute fcompute_ ; <nl> ExecType exec_type_ ; <nl> class StatefulComputeExExecutor : public OpExecutor { <nl> return state_ . get_var ( ) ; <nl> } <nl> <nl> + OpStatePtr state ( ) const override { <nl> + return state_ ; <nl> + } <nl> + <nl> explicit StatefulComputeExExecutor ( const OpStatePtr & state , <nl> const FStatefulComputeEx & fcompute , <nl> ExecType exec_type ) <nl> : state_ ( state ) , fcompute_ ( fcompute ) , exec_type_ ( exec_type ) { } <nl> <nl> private : <nl> - friend Graph AttachOpExecs ( Graph g ) ; <nl> OpStatePtr state_ ; <nl> FStatefulComputeEx fcompute_ ; <nl> ExecType exec_type_ ; <nl> class FComputeExExecutor : public OpExecutor { <nl> ExecType exec_type_ ; <nl> } ; <nl> <nl> - / / pass to attach operator executors <nl> - Graph AttachOpExecs ( Graph g ) { <nl> + void CreateOpExecs ( const Graph & g , OpExecVector * p_ret , size_t i ) { <nl> using nnvm : : DTypeVector ; <nl> using nnvm : : ShapeVector ; <nl> using nnvm : : FMutateInputs ; <nl> <nl> - auto & fcreate_op_state = nnvm : : Op : : GetAttr < FCreateOpState > ( " FCreateOpState " ) ; <nl> - auto & fmutate_inputs = nnvm : : Op : : GetAttr < FMutateInputs > ( " FMutateInputs " ) ; <nl> - auto & fexec_type = nnvm : : Op : : GetAttr < FExecType > ( " FExecType " ) ; <nl> - auto & is_layer_backward = nnvm : : Op : : GetAttr < bool > ( " TIsLayerOpBackward " ) ; <nl> + static auto & fcreate_op_state = nnvm : : Op : : GetAttr < FCreateOpState > ( " FCreateOpState " ) ; <nl> + static auto & fmutate_inputs = nnvm : : Op : : GetAttr < FMutateInputs > ( " FMutateInputs " ) ; <nl> + static auto & fexec_type = nnvm : : Op : : GetAttr < FExecType > ( " FExecType " ) ; <nl> + static auto & is_layer_backward = nnvm : : Op : : GetAttr < bool > ( " TIsLayerOpBackward " ) ; <nl> <nl> const auto & vdtype = g . GetAttr < DTypeVector > ( " dtype " ) ; <nl> const auto & vshape = g . GetAttr < ShapeVector > ( " shape " ) ; <nl> Graph AttachOpExecs ( Graph g ) { <nl> <nl> / / get the graph <nl> const auto & idx = g . indexed_graph ( ) ; <nl> - std : : vector < std : : shared_ptr < OpExecutor > > ret ( idx . num_nodes ( ) ) ; <nl> + OpExecVector & ret = * p_ret ; <nl> <nl> / / initialize the nodes <nl> - for ( size_t i = 0 ; i < idx . num_nodes ( ) ; + + i ) { <nl> - const auto & inode = idx [ i ] ; <nl> - if ( inode . source - > is_variable ( ) ) continue ; <nl> - const nnvm : : Op * op = inode . source - > op ( ) ; <nl> - ExecType exec_type = ExecType : : kSync ; <nl> - std : : vector < uint32_t > mutate_index ; <nl> - if ( fmutate_inputs . count ( op ) ) { <nl> - mutate_index = fmutate_inputs [ op ] ( inode . source - > attrs ) ; <nl> - } <nl> - if ( fexec_type . count ( op ) ) { <nl> - exec_type = fexec_type [ op ] ( inode . source - > attrs ) ; <nl> + const auto & inode = idx [ i ] ; <nl> + if ( inode . source - > is_variable ( ) ) return ; <nl> + const nnvm : : Op * op = inode . source - > op ( ) ; <nl> + ExecType exec_type = ExecType : : kSync ; <nl> + std : : vector < uint32_t > mutate_index ; <nl> + if ( fmutate_inputs . count ( op ) ) { <nl> + mutate_index = fmutate_inputs [ op ] ( inode . source - > attrs ) ; <nl> + } <nl> + if ( fexec_type . count ( op ) ) { <nl> + exec_type = fexec_type [ op ] ( inode . source - > attrs ) ; <nl> + } <nl> + CHECK ( dispatch_modes [ i ] ! = DispatchMode : : kUndefined ) ; <nl> + if ( fcreate_op_state . count ( op ) ) { <nl> + std : : vector < TShape > ishape ; <nl> + std : : vector < int > itype ; <nl> + for ( const auto & e : inode . inputs ) { <nl> + ishape . emplace_back ( vshape [ idx . entry_id ( e ) ] ) ; <nl> + itype . emplace_back ( vdtype [ idx . entry_id ( e ) ] ) ; <nl> } <nl> - CHECK ( dispatch_modes [ i ] ! = DispatchMode : : kUndefined ) ; <nl> - if ( fcreate_op_state . count ( op ) ) { <nl> - std : : vector < TShape > ishape ; <nl> - std : : vector < int > itype ; <nl> - for ( const auto & e : inode . inputs ) { <nl> - ishape . emplace_back ( vshape [ idx . entry_id ( e ) ] ) ; <nl> - itype . emplace_back ( vdtype [ idx . entry_id ( e ) ] ) ; <nl> - } <nl> <nl> - OpStatePtr state = fcreate_op_state [ op ] ( <nl> - inode . source - > attrs , vctx [ i ] , ishape , itype ) ; <nl> - FStatefulComputeEx fcompute_ex = common : : GetFCompute < FStatefulComputeEx > ( <nl> - op , " FStatefulComputeEx " , vctx [ i ] ) ; <nl> - / / FStatefulComputeEx is dispatched only when dispatch_mode is DispatchMode : : kFComputeEx <nl> - if ( fcompute_ex ! = nullptr & & dispatch_modes [ i ] = = DispatchMode : : kFComputeEx ) { <nl> - ret [ i ] = std : : make_shared < StatefulComputeExExecutor > ( state , fcompute_ex , exec_type ) ; <nl> - } else { <nl> - FStatefulCompute fcompute = common : : GetFCompute < FStatefulCompute > ( <nl> - op , " FStatefulCompute " , vctx [ i ] ) ; <nl> - CHECK ( fcompute ! = nullptr ) <nl> - < < " One of FStatefulCompute and FStatefulComputeEx must be registered " <nl> - < < " for stateful operator " < < op - > name ; <nl> - ret [ i ] = std : : make_shared < StatefulComputeExecutor > ( state , fcompute , <nl> - exec_type , mutate_index ) ; <nl> - } <nl> - } else if ( is_layer_backward . get ( op , false ) ) { <nl> - CHECK_GE ( inode . control_deps . size ( ) , 1 ) ; <nl> - uint32_t fwd_id = inode . control_deps [ 0 ] ; <nl> - CHECK ( vctx [ fwd_id ] = = vctx [ i ] ) ; <nl> - CHECK ( ret [ fwd_id ] ! = nullptr ) ; <nl> - FStatefulComputeEx fcompute_ex = common : : GetFCompute < FStatefulComputeEx > ( <nl> - op , " FStatefulComputeEx " , vctx [ i ] ) ; <nl> - / / FStatefulComputeEx is dispatched only when dispatch_mode is DispatchMode : : kFComputeEx <nl> - if ( fcompute_ex ! = nullptr & & dispatch_modes [ i ] = = DispatchMode : : kFComputeEx ) { <nl> - ret [ i ] = std : : make_shared < StatefulComputeExExecutor > ( <nl> - dynamic_cast < StatefulComputeExExecutor * > ( ret [ fwd_id ] . get ( ) ) - > state_ , <nl> - fcompute_ex , exec_type ) ; <nl> - } else { <nl> - FStatefulCompute fcompute = common : : GetFCompute < FStatefulCompute > ( <nl> - op , " FStatefulCompute " , vctx [ i ] ) ; <nl> - CHECK ( fcompute ! = nullptr ) <nl> - < < " One of FStatefulCompute and FStatefulComputeEx must be registered " <nl> - < < " for stateful operator " < < op - > name ; <nl> - ret [ i ] = std : : make_shared < StatefulComputeExecutor > ( <nl> - dynamic_cast < StatefulComputeExecutor * > ( ret [ fwd_id ] . get ( ) ) - > state_ , <nl> - fcompute , exec_type , mutate_index ) ; <nl> - } <nl> + OpStatePtr state = fcreate_op_state [ op ] ( <nl> + inode . source - > attrs , vctx [ i ] , ishape , itype ) ; <nl> + FStatefulComputeEx fcompute_ex = common : : GetFCompute < FStatefulComputeEx > ( <nl> + op , " FStatefulComputeEx " , vctx [ i ] ) ; <nl> + / / FStatefulComputeEx is dispatched only when dispatch_mode is DispatchMode : : kFComputeEx <nl> + if ( fcompute_ex ! = nullptr & & dispatch_modes [ i ] = = DispatchMode : : kFComputeEx ) { <nl> + ret [ i ] = std : : make_shared < StatefulComputeExExecutor > ( state , fcompute_ex , exec_type ) ; <nl> } else { <nl> - FCompute fcompute = common : : GetFCompute < FCompute > ( op , " FCompute " , vctx [ i ] ) ; <nl> - FComputeEx fcomp_ex = common : : GetFCompute < FComputeEx > ( op , " FComputeEx " , vctx [ i ] ) ; <nl> - if ( fcomp_ex ! = nullptr & & dispatch_modes [ i ] = = DispatchMode : : kFComputeEx ) { <nl> - ret [ i ] = std : : make_shared < FComputeExExecutor > ( <nl> - inode . source - > attrs , fcomp_ex , exec_type ) ; <nl> - } else if ( fcompute ! = nullptr ) { <nl> - ret [ i ] = std : : make_shared < FComputeExecutor > ( <nl> - inode . source - > attrs , fcompute , exec_type , mutate_index ) ; <nl> - } else { <nl> - LOG ( INFO ) < < " Neither FCompute nor FComputeEx registered " < < op - > name ; <nl> - } <nl> + FStatefulCompute fcompute = common : : GetFCompute < FStatefulCompute > ( <nl> + op , " FStatefulCompute " , vctx [ i ] ) ; <nl> + CHECK ( fcompute ! = nullptr ) <nl> + < < " One of FStatefulCompute and FStatefulComputeEx must be registered " <nl> + < < " for stateful operator " < < op - > name ; <nl> + ret [ i ] = std : : make_shared < StatefulComputeExecutor > ( state , fcompute , <nl> + exec_type , mutate_index ) ; <nl> + } <nl> + } else if ( is_layer_backward . get ( op , false ) ) { <nl> + CHECK_GE ( inode . control_deps . size ( ) , 1 ) ; <nl> + uint32_t fwd_id = inode . control_deps [ 0 ] ; <nl> + CHECK ( vctx [ fwd_id ] = = vctx [ i ] ) ; <nl> + CHECK ( ret [ fwd_id ] ! = nullptr ) ; <nl> + FStatefulComputeEx fcompute_ex = common : : GetFCompute < FStatefulComputeEx > ( <nl> + op , " FStatefulComputeEx " , vctx [ i ] ) ; <nl> + / / FStatefulComputeEx is dispatched only when dispatch_mode is DispatchMode : : kFComputeEx <nl> + if ( fcompute_ex ! = nullptr & & dispatch_modes [ i ] = = DispatchMode : : kFComputeEx ) { <nl> + ret [ i ] = std : : make_shared < StatefulComputeExExecutor > ( <nl> + ret [ fwd_id ] . get ( ) - > state ( ) , fcompute_ex , exec_type ) ; <nl> + } else { <nl> + FStatefulCompute fcompute = common : : GetFCompute < FStatefulCompute > ( <nl> + op , " FStatefulCompute " , vctx [ i ] ) ; <nl> + CHECK ( fcompute ! = nullptr ) <nl> + < < " One of FStatefulCompute and FStatefulComputeEx must be registered " <nl> + < < " for stateful operator " < < op - > name ; <nl> + ret [ i ] = std : : make_shared < StatefulComputeExecutor > ( <nl> + ret [ fwd_id ] . get ( ) - > state ( ) , fcompute , exec_type , mutate_index ) ; <nl> } <nl> + } else { <nl> + FCompute fcompute = common : : GetFCompute < FCompute > ( op , " FCompute " , vctx [ i ] ) ; <nl> + FComputeEx fcomp_ex = common : : GetFCompute < FComputeEx > ( op , " FComputeEx " , vctx [ i ] ) ; <nl> + if ( fcomp_ex ! = nullptr & & dispatch_modes [ i ] = = DispatchMode : : kFComputeEx ) { <nl> + ret [ i ] = std : : make_shared < FComputeExExecutor > ( <nl> + inode . source - > attrs , fcomp_ex , exec_type ) ; <nl> + } else if ( fcompute ! = nullptr ) { <nl> + ret [ i ] = std : : make_shared < FComputeExecutor > ( <nl> + inode . source - > attrs , fcompute , exec_type , mutate_index ) ; <nl> + } else { <nl> + LOG ( INFO ) < < " Neither FCompute nor FComputeEx registered " < < op - > name ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + <nl> + / / pass to attach operator executors <nl> + Graph AttachOpExecs ( Graph g ) { <nl> + const auto & idx = g . indexed_graph ( ) ; <nl> + OpExecVector ret ( idx . num_nodes ( ) ) ; <nl> + for ( size_t i = 0 ; i < idx . num_nodes ( ) ; + + i ) { <nl> + CreateOpExecs ( g , & ret , i ) ; <nl> } <nl> g . attrs [ " op_execs " ] = std : : make_shared < nnvm : : any > ( ret ) ; <nl> return g ; <nl> mmm a / src / executor / attach_op_resource_pass . cc <nl> ppp b / src / executor / attach_op_resource_pass . cc <nl> <nl> namespace mxnet { <nl> namespace exec { <nl> <nl> - Graph AttachOpResources ( Graph g ) { <nl> + void AttachOpResources ( <nl> + const Graph & g , <nl> + const OpExecVector & op_execs , <nl> + size_t start_nid , <nl> + size_t end_nid ) { <nl> static auto & fresource = <nl> nnvm : : Op : : GetAttr < FResourceRequest > ( " FResourceRequest " ) ; <nl> static auto & fresource_ex = <nl> nnvm : : Op : : GetAttr < FResourceRequestEx > ( " FResourceRequestEx " ) ; <nl> - auto & op_execs = nnvm : : get < OpExecVector > ( * g . attrs . at ( " op_execs " ) ) ; <nl> const auto & vctx = g . GetAttr < ContextVector > ( " context " ) ; <nl> const auto & vdispatch = g . GetAttr < DispatchModeVector > ( " dispatch_mode " ) ; <nl> const auto & dev_masks = g . GetAttr < DevMaskVector > ( " dev_mask " ) ; <nl> Graph AttachOpResources ( Graph g ) { <nl> / / Use global resource pool for each executor for now . <nl> std : : map < Context , Resource > cached_temp ; <nl> / / Resource allocation <nl> - for ( uint32_t nid = 0 ; nid < idx . num_nodes ( ) ; + + nid ) { <nl> + for ( uint32_t nid = start_nid ; nid < end_nid ; + + nid ) { <nl> const auto & inode = idx [ nid ] ; <nl> if ( inode . source - > is_variable ( ) ) continue ; <nl> const Context & ctx = vctx [ nid ] ; <nl> Graph AttachOpResources ( Graph g ) { <nl> requested . push_back ( ResourceManager : : Get ( ) - > Request ( ctx , ResourceRequest : : kTempSpace ) ) ; <nl> } <nl> } <nl> - return g ; <nl> } <nl> + <nl> + void AttachOpResources ( const Graph & g ) { <nl> + const auto & op_execs = g . GetAttr < OpExecVector > ( " op_execs " ) ; <nl> + AttachOpResources ( g , op_execs , 0 , g . indexed_graph ( ) . num_nodes ( ) ) ; <nl> + } <nl> + <nl> } / / namespace exec <nl> } / / namespace mxnet <nl> mmm a / src / executor / exec_pass . h <nl> ppp b / src / executor / exec_pass . h <nl> class OpExecutor { <nl> virtual engine : : VarHandle var ( ) const { <nl> return nullptr ; <nl> } <nl> + / * ! \ return return operator state * / <nl> + virtual OpStatePtr state ( ) const { <nl> + return OpStatePtr ( ) ; <nl> + } <nl> } ; <nl> <nl> / * ! <nl> using ContextVector = std : : vector < Context > ; <nl> * / <nl> using DevMaskVector = std : : vector < int > ; <nl> <nl> + / * ! <nl> + * \ brief create OpExecutor for a node in graph <nl> + * <nl> + * \ param g input graph <nl> + * \ param p_ret OpExecVector for input and output <nl> + * \ param i the id of the node <nl> + * / <nl> + void CreateOpExecs ( const Graph & g , OpExecVector * p_ret , size_t i ) ; <nl> / * ! <nl> * \ brief Attach OpExecutor to the graph attributes . <nl> * <nl> Graph AttachOpExecs ( Graph g ) ; <nl> * \ brief Attach Resource to the OpExecVector of the graph . <nl> * <nl> * \ param g input graph need to contain op_exec attribute . <nl> + * / <nl> + void AttachOpResources ( const Graph & g ) ; <nl> + / * ! <nl> + * \ brief Attach Resource to the OpExecVector <nl> * <nl> - * \ return graph with new attribute " op_exec " of type OpExecVector <nl> - * The fields on the OpExecVector are not yet been setup . <nl> + * \ param g input graph <nl> + * \ param op_execs OpExecutor vector <nl> + * \ param start_nid starting node id <nl> + * \ param end_nid end node id <nl> * / <nl> - Graph AttachOpResources ( Graph g ) ; <nl> - <nl> + void AttachOpResources ( const Graph & g , <nl> + const OpExecVector & op_execs , <nl> + size_t start_nid , <nl> + size_t end_nid ) ; <nl> / * ! <nl> * \ brief Discover chance of inplace addto operators . <nl> * i . e . z = plus ( z , source_op ) , and encourage it to become z + = source_op . <nl> mmm a / src / executor / graph_executor . cc <nl> ppp b / src / executor / graph_executor . cc <nl> void GraphExecutor : : FinishInitGraph ( nnvm : : Symbol symbol , <nl> } <nl> <nl> g = AttachOpExecs ( g ) ; <nl> - g = AttachOpResources ( g ) ; <nl> + AttachOpResources ( g ) ; <nl> graph_ = std : : move ( g ) ; <nl> <nl> if ( shared_exec ! = nullptr ) { <nl> mmm a / src / imperative / cached_op . cc <nl> ppp b / src / imperative / cached_op . cc <nl> <nl> # include < unordered_set > <nl> # include < iostream > <nl> # include " . / imperative_utils . h " <nl> + # include " . / cached_op . h " <nl> + # include " . . / executor / exec_pass . h " <nl> + # include " . . / profiler / profiler . h " <nl> + <nl> <nl> namespace mxnet { <nl> <nl> DMLC_REGISTER_PARAMETER ( CachedOpConfig ) ; <nl> <nl> - Imperative : : CachedOp : : CachedOp ( <nl> + struct CachedOp : : GraphInfo { <nl> + nnvm : : Graph fwd_graph ; <nl> + nnvm : : Graph full_graph ; <nl> + std : : vector < OpReqType > bwd_output_reqs ; <nl> + std : : vector < uint32_t > bwd_input_eid ; <nl> + } ; <nl> + <nl> + struct CachedOp : : DynamicRuntime { <nl> + GraphInfo info ; <nl> + std : : vector < NDArray > buff ; <nl> + std : : vector < OpStatePtr > op_states ; <nl> + } ; <nl> + <nl> + struct CachedOp : : CachedOpState { <nl> + CachedOpState ( const Context & context_ , <nl> + const nnvm : : Graph & fwd_graph_ , <nl> + const nnvm : : Graph & full_graph_ ) { <nl> + context = context_ ; <nl> + info . fwd_graph = fwd_graph_ ; <nl> + info . full_graph = full_graph_ ; <nl> + <nl> + size_t max_nodes = info . full_graph . indexed_graph ( ) . num_nodes ( ) ; <nl> + size_t max_entries = info . full_graph . indexed_graph ( ) . num_node_entries ( ) ; <nl> + info . fwd_graph . attrs [ " context " ] = std : : make_shared < dmlc : : any > ( <nl> + std : : vector < Context > ( info . fwd_graph . indexed_graph ( ) . num_nodes ( ) , context ) ) ; <nl> + info . full_graph . attrs [ " context " ] = std : : make_shared < dmlc : : any > ( <nl> + std : : vector < Context > ( max_nodes , context ) ) ; <nl> + <nl> + buff . resize ( max_entries ) ; <nl> + arrays . resize ( max_entries ) ; <nl> + array_reqs . resize ( max_entries ) ; <nl> + dynamic_entries . resize ( max_entries , false ) ; <nl> + op_states . resize ( max_nodes ) ; <nl> + execs . resize ( max_nodes ) ; <nl> + opr_segs . resize ( max_nodes ) ; <nl> + } <nl> + <nl> + std : : mutex mutex ; <nl> + Context context ; <nl> + GraphInfo info ; <nl> + <nl> + bool recording = false ; <nl> + bool fwd_alloc = false ; <nl> + bool bwd_alloc = false ; <nl> + bool fwd_exec_init = false ; <nl> + bool bwd_exec_init = false ; <nl> + <nl> + std : : vector < NDArray > buff ; <nl> + std : : vector < NDArray * > arrays ; <nl> + std : : vector < OpReqType > array_reqs ; <nl> + <nl> + std : : vector < OpStatePtr > op_states ; <nl> + std : : vector < std : : shared_ptr < exec : : OpExecutor > > execs ; <nl> + std : : vector < imperative : : EngineOprSeg > opr_segs ; <nl> + <nl> + std : : vector < bool > dynamic_entries ; <nl> + std : : multimap < size_t , NDArray > fwd_reuse_pool ; <nl> + std : : multimap < size_t , NDArray > bwd_reuse_pool ; <nl> + } ; <nl> + <nl> + CachedOp : : CachedOp ( <nl> const nnvm : : Symbol & sym , <nl> - const std : : vector < std : : pair < std : : string , std : : string > > & flags , <nl> - const std : : vector < std : : string > arg_names , <nl> - const std : : unordered_map < std : : string , std : : vector < NDArray > > & params ) { <nl> + const std : : vector < std : : pair < std : : string , std : : string > > & flags ) { <nl> using namespace nnvm ; <nl> using namespace imperative ; <nl> static const std : : vector < const Op * > zero_ops { Op : : Get ( " zeros_like " ) , Op : : Get ( " _zeros " ) } ; <nl> Imperative : : CachedOp : : CachedOp ( <nl> fwd_graph_ . attrs [ " forward_ref_count " ] = <nl> std : : make_shared < dmlc : : any > ( std : : move ( ref_count ) ) ; <nl> <nl> - inlining_ = ( idx . num_nodes ( ) - idx . input_nodes ( ) . size ( ) ) < = config_ . inline_limit ; <nl> + inlining_ = ! config_ . static_alloc & & <nl> + ( idx . num_nodes ( ) - idx . input_nodes ( ) . size ( ) ) < = config_ . inline_limit ; <nl> } <nl> <nl> / / Set params <nl> { <nl> const auto & idx = fwd_graph_ . indexed_graph ( ) ; <nl> - std : : unordered_map < std : : string , size_t > arg_name_to_id ; <nl> - for ( size_t i = 0 ; i < idx . input_nodes ( ) . size ( ) ; + + i ) { <nl> - const auto & name = idx [ idx . input_nodes ( ) [ i ] ] . source - > attrs . name ; <nl> - auto iter = params . find ( name ) ; <nl> - if ( iter = = params . end ( ) ) { <nl> - arg_name_to_id [ name ] = i ; <nl> - continue ; <nl> - } <nl> - fwd_params_idx_ . push_back ( i ) ; <nl> - for ( const auto & param : iter - > second ) { <nl> - params_ [ param . ctx ( ) ] . emplace_back ( param ) ; <nl> + if ( config_ . data_indices . ndim ( ) | | config_ . param_indices . ndim ( ) ) { <nl> + CHECK_EQ ( config_ . data_indices . ndim ( ) + config_ . param_indices . ndim ( ) , <nl> + idx . input_nodes ( ) . size ( ) ) ; <nl> + } else { <nl> + std : : vector < uint32_t > tmp ; <nl> + for ( size_t i = 0 ; i < idx . input_nodes ( ) . size ( ) ; + + i ) { <nl> + tmp . push_back ( i ) ; <nl> } <nl> - } <nl> - <nl> - CHECK_EQ ( arg_name_to_id . size ( ) , arg_names . size ( ) ) <nl> - < < " CachedOp expects " < < arg_name_to_id . size ( ) <nl> - < < " inputs , given " < < arg_names . size ( ) ; <nl> - <nl> - for ( const auto & name : arg_names ) { <nl> - auto iter = arg_name_to_id . find ( name ) ; <nl> - CHECK ( iter ! = arg_name_to_id . end ( ) ) < < " Unexpected input name " < < name ; <nl> - fwd_args_idx_ . push_back ( iter - > second ) ; <nl> + config_ . data_indices . assign ( tmp . begin ( ) , tmp . end ( ) ) ; <nl> } <nl> } <nl> <nl> Imperative : : CachedOp : : CachedOp ( <nl> } <nl> <nl> std : : vector < NodeEntry > xs ; <nl> - std : : vector < NodePtr > args = sym . ListInputs ( Symbol : : kReadOnlyArgs ) ; <nl> - xs . reserve ( args . size ( ) ) ; <nl> - for ( const auto & i : args ) xs . emplace_back ( NodeEntry { i , 0 , 0 } ) ; <nl> + const auto & idx = fwd_graph_ . indexed_graph ( ) ; <nl> + for ( size_t i = 0 ; i < idx . input_nodes ( ) . size ( ) ; + + i ) { <nl> + auto nid = idx . input_nodes ( ) [ i ] ; <nl> + if ( idx . mutable_input_nodes ( ) . count ( nid ) ) continue ; <nl> + fwd_input_to_grad_output_ [ i ] = xs . size ( ) ; <nl> + xs . emplace_back ( NodeEntry { idx [ nid ] . weak_ref . lock ( ) , 0 , 0 } ) ; <nl> + } <nl> + <nl> CHECK_GT ( xs . size ( ) , 0 ) <nl> < < " There are no inputs in computation graph that require gradients . " ; <nl> <nl> Imperative : : CachedOp : : CachedOp ( <nl> size_t num_forward_entries = fwd_graph_ . indexed_graph ( ) . num_node_entries ( ) ; <nl> <nl> full_graph_ . outputs = fwd_graph_ . outputs ; <nl> - curr_grad_req_ = std : : vector < bool > ( grad_graph_ . outputs . size ( ) , true ) ; <nl> + bwd_output_reqs_ = std : : vector < OpReqType > ( grad_graph_ . outputs . size ( ) , kWriteTo ) ; <nl> for ( const auto & i : grad_graph_ . outputs ) full_graph_ . outputs . emplace_back ( i ) ; <nl> const auto & idx = full_graph_ . indexed_graph ( ) ; <nl> <nl> Imperative : : CachedOp : : CachedOp ( <nl> } <nl> } <nl> <nl> - std : : vector < nnvm : : NodeEntry > Imperative : : CachedOp : : Gradient ( <nl> + CachedOp : : ~ CachedOp ( ) { <nl> + } <nl> + <nl> + std : : vector < nnvm : : NodeEntry > CachedOp : : Gradient ( <nl> const nnvm : : NodePtr & node , <nl> const std : : vector < nnvm : : NodeEntry > & ograds ) { <nl> using namespace nnvm ; <nl> std : : vector < nnvm : : NodeEntry > Imperative : : CachedOp : : Gradient ( <nl> return ret ; <nl> } <nl> <nl> - nnvm : : Graph Imperative : : CachedOp : : GetForwardGraph ( <nl> - const bool recording , const std : : vector < NDArray * > & inputs ) { <nl> + <nl> + bool CachedOp : : SetForwardGraph ( <nl> + GraphInfo * info , <nl> + const bool recording , <nl> + const std : : vector < NDArray * > & inputs ) { <nl> using namespace nnvm ; <nl> using namespace imperative ; <nl> - std : : lock_guard < std : : mutex > lock ( mutex_ ) ; <nl> CHECK_EQ ( inputs . size ( ) , num_inputs ( ) ) ; <nl> - nnvm : : Graph & g = fwd_graph_ ; <nl> + nnvm : : Graph & g = info - > fwd_graph ; <nl> <nl> ShapeVector shape_inputs ; <nl> DTypeVector dtype_inputs ; <nl> nnvm : : Graph Imperative : : CachedOp : : GetForwardGraph ( <nl> g . attrs . erase ( " forward_mem_plan " ) ; <nl> g . attrs . erase ( " full_mem_plan " ) ; <nl> } else if ( g . attrs . count ( recording ? " full_mem_plan " : " forward_mem_plan " ) ) { <nl> - return g ; <nl> + return true ; <nl> } <nl> <nl> const auto & idx = g . indexed_graph ( ) ; <nl> <nl> StorageVector storage ( idx . num_node_entries ( ) , exec : : kBadStorageID ) ; <nl> - for ( const auto i : idx . input_nodes ( ) ) storage [ idx . entry_id ( i , 0 ) ] = exec : : kExternalStorageID ; <nl> const auto & stypes = g . GetAttr < StorageTypeVector > ( " storage_type " ) ; <nl> CHECK_EQ ( stypes . size ( ) , storage . size ( ) ) ; <nl> for ( size_t i = 0 ; i < stypes . size ( ) ; i + + ) { <nl> - if ( stypes [ i ] ! = kDefaultStorage ) <nl> - storage [ i ] = exec : : kDynamicStorageID ; <nl> + if ( stypes [ i ] ! = kDefaultStorage ) storage [ i ] = exec : : kDynamicStorageID ; <nl> + } <nl> + for ( const auto i : idx . input_nodes ( ) ) { <nl> + storage [ idx . entry_id ( i , 0 ) ] = exec : : kExternalStorageID ; <nl> + } <nl> + for ( size_t i = 0 ; i < idx . outputs ( ) . size ( ) ; + + i ) { <nl> + storage [ idx . entry_id ( idx . outputs ( ) [ i ] ) ] = exec : : kExternalStorageID ; <nl> } <nl> <nl> auto mem_plan = PlanMemory ( <nl> nnvm : : Graph Imperative : : CachedOp : : GetForwardGraph ( <nl> g . attrs [ recording ? " full_mem_plan " : " forward_mem_plan " ] = <nl> std : : make_shared < dmlc : : any > ( std : : move ( mem_plan ) ) ; <nl> <nl> - return g ; <nl> + return false ; <nl> } <nl> <nl> - nnvm : : Graph Imperative : : CachedOp : : GetBackwardGraph ( <nl> - const OpStatePtr & op_state , <nl> + bool CachedOp : : SetBackwardGraph ( <nl> + GraphInfo * info , <nl> const std : : vector < OpReqType > & reqs , <nl> - const std : : vector < NDArray * > & inputs ) { <nl> + const std : : vector < NDArray * > & inputs , <nl> + bool detect_inplace_addto ) { <nl> using namespace nnvm ; <nl> using namespace imperative ; <nl> std : : lock_guard < std : : mutex > lock ( mutex_ ) ; <nl> - nnvm : : Graph & g = full_graph_ ; <nl> - auto & state = op_state . get_state < CachedOpState > ( ) ; <nl> - bool req_match = true ; <nl> - for ( size_t i = 0 ; i < reqs . size ( ) ; + + i ) { <nl> - if ( curr_grad_req_ [ i ] ! = ( reqs [ i ] ! = kNullOp ) ) { <nl> - curr_grad_req_ [ i ] = reqs [ i ] ! = kNullOp ; <nl> - req_match = false ; <nl> - } <nl> - } <nl> - if ( ! req_match ) { <nl> + Context default_ctx = inputs [ 0 ] - > ctx ( ) ; <nl> + nnvm : : Graph & g = info - > full_graph ; <nl> + <nl> + if ( info - > bwd_output_reqs ! = reqs ) { <nl> + info - > bwd_output_reqs = reqs ; <nl> + info - > bwd_input_eid . clear ( ) ; <nl> g = nnvm : : Graph ( ) ; <nl> g . outputs = fwd_graph_ . outputs ; <nl> for ( size_t i = 0 ; i < grad_graph_ . outputs . size ( ) ; + + i ) { <nl> - if ( curr_grad_req_ [ i ] ) g . outputs . emplace_back ( grad_graph_ . outputs [ i ] ) ; <nl> + if ( info - > bwd_output_reqs [ i ] = = kNullOp ) continue ; <nl> + g . outputs . emplace_back ( grad_graph_ . outputs [ i ] ) ; <nl> } <nl> - bwd_input_eid_ . clear ( ) ; <nl> + g . attrs [ " context " ] = std : : make_shared < dmlc : : any > ( <nl> + std : : vector < Context > ( g . indexed_graph ( ) . num_nodes ( ) , default_ctx ) ) ; <nl> } <nl> <nl> const auto & idx = g . indexed_graph ( ) ; <nl> <nl> - if ( bwd_input_eid_ . size ( ) ! = inputs . size ( ) ) { <nl> - bwd_input_eid_ . clear ( ) ; <nl> + if ( info - > bwd_input_eid . size ( ) ! = inputs . size ( ) ) { <nl> + info - > bwd_input_eid . clear ( ) ; <nl> for ( const auto & i : bwd_ograd_dep_ ) { <nl> auto eid = idx . entry_id ( ograd_entries_ [ i ] ) ; <nl> - bwd_input_eid_ . push_back ( eid ) ; <nl> + info - > bwd_input_eid . push_back ( eid ) ; <nl> } <nl> for ( const auto & i : bwd_in_dep_ ) { <nl> auto eid = idx . entry_id ( idx . input_nodes ( ) [ i ] , 0 ) ; <nl> - bwd_input_eid_ . push_back ( eid ) ; <nl> + info - > bwd_input_eid . push_back ( eid ) ; <nl> } <nl> for ( const auto & i : bwd_out_dep_ ) { <nl> auto eid = idx . entry_id ( idx . outputs ( ) [ i ] ) ; <nl> - bwd_input_eid_ . push_back ( eid ) ; <nl> + info - > bwd_input_eid . push_back ( eid ) ; <nl> } <nl> - CHECK_EQ ( inputs . size ( ) , bwd_input_eid_ . size ( ) ) ; <nl> + CHECK_EQ ( inputs . size ( ) , info - > bwd_input_eid . size ( ) ) ; <nl> } <nl> <nl> size_t num_forward_nodes = fwd_graph_ . indexed_graph ( ) . num_nodes ( ) ; <nl> nnvm : : Graph Imperative : : CachedOp : : GetBackwardGraph ( <nl> for ( size_t i = num_forward_nodes ; i < idx . num_nodes ( ) ; + + i ) { <nl> for ( const auto & j : idx [ i ] . inputs ) + + ref_count [ idx . entry_id ( j ) ] ; <nl> } <nl> - for ( size_t i = 0 ; i < inputs . size ( ) ; + + i ) + + ref_count [ bwd_input_eid_ [ i ] ] ; <nl> + for ( size_t i = 0 ; i < inputs . size ( ) ; + + i ) + + ref_count [ info - > bwd_input_eid [ i ] ] ; <nl> for ( const auto & i : idx . outputs ( ) ) + + ref_count [ idx . entry_id ( i ) ] ; <nl> g . attrs [ " backward_ref_count " ] = std : : make_shared < dmlc : : any > ( std : : move ( ref_count ) ) ; <nl> } <nl> <nl> - ShapeVector shapes ( idx . num_node_entries ( ) , TShape ( ) ) ; <nl> - DTypeVector dtypes ( idx . num_node_entries ( ) , - 1 ) ; <nl> - StorageTypeVector stypes ( idx . num_node_entries ( ) , - 1 ) ; <nl> - <nl> - for ( size_t i = 0 ; i < num_forward_entries ; + + i ) { <nl> - shapes [ i ] = state . buff [ i ] . shape ( ) ; <nl> - dtypes [ i ] = state . buff [ i ] . dtype ( ) ; <nl> - stypes [ i ] = state . buff [ i ] . storage_type ( ) ; <nl> - } <nl> + auto shapes = info - > fwd_graph . GetAttr < ShapeVector > ( " shape " ) ; <nl> + shapes . resize ( idx . num_node_entries ( ) , TShape ( ) ) ; <nl> + auto dtypes = info - > fwd_graph . GetAttr < DTypeVector > ( " dtype " ) ; <nl> + dtypes . resize ( idx . num_node_entries ( ) , - 1 ) ; <nl> + auto stypes = info - > fwd_graph . GetAttr < StorageTypeVector > ( " storage_type " ) ; <nl> + stypes . resize ( idx . num_node_entries ( ) , - 1 ) ; <nl> <nl> for ( size_t i = 0 ; i < inputs . size ( ) ; + + i ) { <nl> - shapes [ bwd_input_eid_ [ i ] ] = inputs [ i ] - > shape ( ) ; <nl> - dtypes [ bwd_input_eid_ [ i ] ] = inputs [ i ] - > dtype ( ) ; <nl> - stypes [ bwd_input_eid_ [ i ] ] = inputs [ i ] - > storage_type ( ) ; <nl> + shapes [ info - > bwd_input_eid [ i ] ] = inputs [ i ] - > shape ( ) ; <nl> + dtypes [ info - > bwd_input_eid [ i ] ] = inputs [ i ] - > dtype ( ) ; <nl> + stypes [ info - > bwd_input_eid [ i ] ] = inputs [ i ] - > storage_type ( ) ; <nl> } <nl> <nl> std : : pair < uint32_t , uint32_t > node_range , entry_range ; <nl> nnvm : : Graph Imperative : : CachedOp : : GetBackwardGraph ( <nl> node_range , entry_range ) ; <nl> match & = CheckAndInferType ( & g , std : : move ( dtypes ) , false , <nl> node_range , entry_range ) ; <nl> - exec : : DevMaskVector dev_mask ( idx . num_nodes ( ) , inputs [ 0 ] - > ctx ( ) . dev_mask ( ) ) ; <nl> + exec : : DevMaskVector dev_mask ( idx . num_nodes ( ) , default_ctx . dev_mask ( ) ) ; <nl> match & = CheckAndInferStorageType ( & g , std : : move ( dev_mask ) , std : : move ( stypes ) , <nl> false , node_range , entry_range ) ; <nl> <nl> if ( ! match ) { <nl> g . attrs . erase ( " backward_mem_plan " ) ; <nl> } else if ( g . attrs . count ( " backward_mem_plan " ) ) { <nl> - return g ; <nl> + return true ; <nl> } <nl> <nl> StorageVector storage ( idx . num_node_entries ( ) , exec : : kBadStorageID ) ; <nl> + const auto & bwd_stypes = g . GetAttr < StorageTypeVector > ( " storage_type " ) ; <nl> + for ( size_t i = 0 ; i < bwd_stypes . size ( ) ; i + + ) { <nl> + if ( bwd_stypes [ i ] ! = kDefaultStorage ) storage [ i ] = exec : : kDynamicStorageID ; <nl> + } <nl> for ( size_t i = 0 ; i < num_forward_entries ; + + i ) storage [ i ] = exec : : kExternalStorageID ; <nl> for ( const auto i : idx . input_nodes ( ) ) storage [ idx . entry_id ( i , 0 ) ] = exec : : kExternalStorageID ; <nl> for ( const auto i : idx . outputs ( ) ) storage [ idx . entry_id ( i ) ] = exec : : kExternalStorageID ; <nl> - for ( size_t i = 0 ; i < stypes . size ( ) ; i + + ) { <nl> - if ( stypes [ i ] ! = kDefaultStorage ) <nl> - storage [ i ] = exec : : kDynamicStorageID ; <nl> - } <nl> <nl> auto mem_plan = PlanMemory ( <nl> & g , std : : move ( storage ) , g . GetAttr < std : : vector < uint32_t > > ( " backward_ref_count " ) , <nl> - { num_forward_nodes , idx . num_nodes ( ) } , { num_forward_entries , idx . num_node_entries ( ) } ) ; <nl> + { num_forward_nodes , idx . num_nodes ( ) } , <nl> + { num_forward_entries , idx . num_node_entries ( ) } , <nl> + detect_inplace_addto ) ; <nl> g . attrs [ " backward_mem_plan " ] = std : : make_shared < dmlc : : any > ( std : : move ( mem_plan ) ) ; <nl> <nl> - return g ; <nl> + return false ; <nl> } <nl> <nl> - void Imperative : : CachedOp : : Forward ( <nl> - const std : : shared_ptr < CachedOp > & op_ptr , <nl> - const std : : vector < NDArray * > & args , <nl> - const std : : vector < NDArray * > & outputs ) { <nl> + OpStatePtr CachedOp : : GetCachedOpState ( <nl> + const Context & ctx ) { <nl> + std : : lock_guard < std : : mutex > lock ( mutex_ ) ; <nl> + for ( const auto & i : cached_op_states_ [ ctx ] ) { <nl> + / / only create one state per device when not using static memory <nl> + if ( ! config_ . static_alloc | | i . unique ( ) ) { <nl> + return i ; <nl> + } <nl> + } <nl> + auto state_ptr = OpStatePtr : : Create < CachedOpState > ( ctx , fwd_graph_ , full_graph_ ) ; <nl> + <nl> + cached_op_states_ [ ctx ] . push_back ( state_ptr ) ; <nl> + return state_ptr ; <nl> + } <nl> + <nl> + void CachedOp : : StaticAllocMemory ( <nl> + const OpStatePtr & state_ptr , <nl> + bool recording , <nl> + bool keep_fwd ) { <nl> using namespace nnvm ; <nl> using namespace imperative ; <nl> - static const auto cached_op = nnvm : : Op : : Get ( " _CachedOp " ) ; <nl> <nl> - CHECK_EQ ( args . size ( ) , fwd_args_idx_ . size ( ) ) <nl> - < < " CachedOp requires " < < fwd_args_idx_ . size ( ) <nl> - < < " inputs but got " < < args . size ( ) ; <nl> + auto & state = state_ptr . get_state < CachedOpState > ( ) ; <nl> + const auto & default_ctx = state . context ; <nl> + nnvm : : Graph & g = keep_fwd ? state . info . full_graph : state . info . fwd_graph ; <nl> + const auto & idx = g . indexed_graph ( ) ; <nl> + const auto & vstorage_inplace = g . GetAttr < std : : vector < int > > ( " storage_inplace_index " ) ; <nl> + const auto & mem_plan = g . GetAttr < MemoryPlanVector > ( <nl> + keep_fwd ? " backward_mem_plan " : ( recording ? " full_mem_plan " : " forward_mem_plan " ) ) ; <nl> + std : : vector < int > addto_entry ; <nl> + if ( g . attrs . count ( " addto_entry " ) ) { <nl> + addto_entry = g . GetAttr < std : : vector < int > > ( " addto_entry " ) ; <nl> + } <nl> + size_t start_eid = <nl> + keep_fwd ? state . info . fwd_graph . indexed_graph ( ) . num_node_entries ( ) : 0 ; <nl> + size_t end_eid = idx . num_node_entries ( ) ; <nl> + <nl> + if ( ! keep_fwd ) state . fwd_alloc = false ; <nl> + state . bwd_alloc = false ; <nl> + for ( size_t i = start_eid ; i < state . buff . size ( ) ; + + i ) { <nl> + state . buff [ i ] = NDArray ( ) ; <nl> + state . arrays [ i ] = & state . buff [ i ] ; <nl> + state . array_reqs [ i ] = kNullOp ; <nl> + state . dynamic_entries [ i ] = false ; <nl> + } <nl> + <nl> + for ( auto i : idx . input_nodes ( ) ) { <nl> + auto eid = idx . entry_id ( i , 0 ) ; <nl> + if ( eid > = start_eid ) state . dynamic_entries [ eid ] = true ; <nl> + } <nl> + for ( auto i : idx . outputs ( ) ) { <nl> + auto eid = idx . entry_id ( i ) ; <nl> + if ( eid > = start_eid ) state . dynamic_entries [ eid ] = true ; <nl> + } <nl> + <nl> + for ( size_t i = start_eid ; i < end_eid ; + + i ) { <nl> + if ( addto_entry . size ( ) & & addto_entry [ i ] ) { <nl> + state . array_reqs [ i ] = kAddTo ; <nl> + } else if ( vstorage_inplace [ i ] > = 0 ) { <nl> + state . array_reqs [ i ] = kWriteInplace ; <nl> + } else if ( vstorage_inplace [ i ] = = - 2 ) { <nl> + / / - 2 indicate that the entry is never referenced . <nl> + state . array_reqs [ i ] = kNullOp ; <nl> + } else { <nl> + state . array_reqs [ i ] = kWriteTo ; <nl> + } <nl> + } <nl> + <nl> + auto & reuse_pool = keep_fwd ? state . bwd_reuse_pool : state . fwd_reuse_pool ; <nl> + reuse_pool = imperative : : AllocateMemory ( <nl> + g , idx , default_ctx , start_eid , end_eid , mem_plan , <nl> + state . arrays , & state . array_reqs , std : : move ( reuse_pool ) ) ; <nl> <nl> - Context default_ctx = args [ 0 ] - > ctx ( ) ; <nl> + state . recording = recording ; <nl> + if ( keep_fwd ) { <nl> + state . bwd_alloc = true ; <nl> + } else { <nl> + state . fwd_alloc = true ; <nl> + } <nl> + } <nl> <nl> + void CachedOp : : StaticInitExec ( <nl> + const OpStatePtr & state_ptr , <nl> + bool recording , <nl> + bool keep_fwd ) { <nl> + using namespace nnvm ; <nl> + using namespace imperative ; <nl> <nl> - std : : vector < NDArray * > inputs ( num_inputs ( ) ) ; <nl> - for ( index_t i = 0 ; i < fwd_args_idx_ . size ( ) ; + + i ) { <nl> - inputs [ fwd_args_idx_ [ i ] ] = args [ i ] ; <nl> + auto & state = state_ptr . get_state < CachedOpState > ( ) ; <nl> + const auto & default_ctx = state . context ; <nl> + nnvm : : Graph & g = keep_fwd ? state . info . full_graph : state . info . fwd_graph ; <nl> + const auto & idx = g . indexed_graph ( ) ; <nl> + std : : vector < int > skip_plus_node ; <nl> + if ( g . attrs . count ( " skip_plus_node " ) ) { <nl> + skip_plus_node = g . GetAttr < std : : vector < int > > ( " skip_plus_node " ) ; <nl> } <nl> - if ( fwd_params_idx_ . size ( ) ) { <nl> - CHECK ( params_ . find ( default_ctx ) ! = params_ . end ( ) ) <nl> - < < " CachedOp is not initialized on context " < < default_ctx ; <nl> + size_t start_nid = <nl> + keep_fwd ? state . info . fwd_graph . indexed_graph ( ) . num_nodes ( ) : 0 ; <nl> + size_t end_nid = idx . num_nodes ( ) ; <nl> <nl> - for ( size_t i = 0 ; i < fwd_params_idx_ . size ( ) ; + + i ) { <nl> - inputs [ fwd_params_idx_ [ i ] ] = & params_ [ default_ctx ] [ i ] ; <nl> + if ( ! keep_fwd ) state . fwd_exec_init = false ; <nl> + state . bwd_exec_init = false ; <nl> + <nl> + for ( size_t i = start_nid ; i < state . execs . size ( ) ; + + i ) { <nl> + state . execs [ i ] . reset ( ) ; <nl> + state . opr_segs [ i ] = EngineOprSeg ( ) ; <nl> + } <nl> + <nl> + if ( ! config_ . static_shape ) { <nl> + for ( size_t i = start_nid ; i < end_nid ; + + i ) { <nl> + state . opr_segs [ i ] . next_nid = i + 1 ; <nl> + state . opr_segs [ i ] . skip = skip_plus_node . size ( ) & & skip_plus_node [ i ] ; <nl> + } <nl> + } else { <nl> + for ( size_t i = start_nid ; i < end_nid ; + + i ) { <nl> + exec : : CreateOpExecs ( g , & state . execs , i ) ; <nl> + } <nl> + exec : : AttachOpResources ( g , state . execs , start_nid , end_nid ) ; <nl> + <nl> + for ( size_t i = start_nid ; i < end_nid ; + + i ) { <nl> + bool skip = idx [ i ] . source - > is_variable ( ) ; <nl> + for ( size_t j = 0 ; ! skip & & j < idx [ i ] . inputs . size ( ) ; + + j ) { <nl> + skip = state . dynamic_entries [ idx . entry_id ( idx [ i ] . inputs [ j ] ) ] ; <nl> + } <nl> + for ( size_t j = 0 ; ! skip & & j < idx [ i ] . source - > num_outputs ( ) ; + + j ) { <nl> + skip = state . dynamic_entries [ idx . entry_id ( i , j ) ] ; <nl> + } <nl> + if ( skip ) continue ; <nl> + SetupOpExec ( g , i , state . execs [ i ] , state . arrays , state . array_reqs ) ; <nl> } <nl> + <nl> + size_t bulk_size = idx . num_nodes ( ) ; <nl> + std : : unordered_set < uint32_t > excludes ; <nl> + if ( recording | | keep_fwd ) { <nl> + bulk_size = keep_fwd ? config_ . backward_bulk_size : config_ . forward_bulk_size ; <nl> + for ( const auto & i : idx . outputs ( ) ) excludes . insert ( idx . entry_id ( i ) ) ; <nl> + for ( const auto & i : idx . input_nodes ( ) ) excludes . insert ( idx . entry_id ( i , 0 ) ) ; <nl> + } <nl> + <nl> + CreateEngineOpSeg ( idx , default_ctx , start_nid , end_nid , bulk_size , excludes , <nl> + state . execs , skip_plus_node , & state . opr_segs ) ; <nl> } <nl> <nl> - / / Initialize <nl> + if ( keep_fwd ) { <nl> + state . bwd_exec_init = true ; <nl> + } else { <nl> + state . fwd_exec_init = true ; <nl> + } <nl> + } <nl> + <nl> + void CachedOp : : StaticRunOps ( <nl> + const Context & default_ctx , <nl> + const nnvm : : Graph & g , <nl> + const OpStatePtr & state_ptr , <nl> + size_t start_nid , <nl> + size_t end_nid ) { <nl> + static auto & createop = nnvm : : Op : : GetAttr < FCreateOpState > ( " FCreateOpState " ) ; <nl> + static auto & is_layer_backward = Op : : GetAttr < bool > ( " TIsLayerOpBackward " ) ; <nl> + <nl> + bool profiling = profiler : : Profiler : : Get ( ) - > GetState ( ) = = profiler : : Profiler : : kRunning ; <nl> + bool is_training = Imperative : : Get ( ) - > is_training ( ) ; <nl> + auto & state = state_ptr . get_state < CachedOpState > ( ) ; <nl> + const auto & idx = g . indexed_graph ( ) ; <nl> + const auto & dispatch_modes = g . GetAttr < DispatchModeVector > ( " dispatch_mode " ) ; <nl> + const auto & op_execs = state . execs ; <nl> + <nl> + std : : vector < NDArray * > ndinputs , ndoutputs ; <nl> + nnvm : : ShapeVector arg_shapes ; <nl> + nnvm : : DTypeVector arg_dtypes ; <nl> + std : : vector < OpReqType > req ; <nl> + <nl> + for ( size_t i = start_nid ; config_ . static_shape & & i < end_nid ; + + i ) { <nl> + if ( op_execs [ i ] ) op_execs [ i ] - > op_ctx . is_train = is_training ; <nl> + } <nl> + <nl> + for ( size_t i = start_nid ; i < end_nid ; i = state . opr_segs [ i ] . next_nid ) { <nl> + const auto & opr_seg = state . opr_segs [ i ] ; <nl> + if ( opr_seg . skip ) continue ; <nl> + if ( opr_seg . opr ! = nullptr ) { <nl> + Engine : : Get ( ) - > Push ( opr_seg . opr . get ( ) , default_ctx , 0 , profiling ) ; <nl> + } else { <nl> + const nnvm : : IndexedGraph : : Node & node = idx [ i ] ; <nl> + if ( node . source - > is_variable ( ) ) continue ; <nl> + auto num_outputs = node . source - > num_outputs ( ) ; <nl> + ndinputs . clear ( ) ; <nl> + ndinputs . reserve ( node . inputs . size ( ) ) ; <nl> + for ( const auto & j : node . inputs ) { <nl> + ndinputs . emplace_back ( state . arrays [ idx . entry_id ( j ) ] ) ; <nl> + CHECK ( ! ndinputs . back ( ) - > is_none ( ) ) ; <nl> + } <nl> + ndoutputs . clear ( ) ; <nl> + ndoutputs . reserve ( num_outputs ) ; <nl> + req . clear ( ) ; <nl> + req . reserve ( num_outputs ) ; <nl> + for ( size_t j = 0 ; j < num_outputs ; + + j ) { <nl> + size_t eid = idx . entry_id ( i , j ) ; <nl> + ndoutputs . emplace_back ( state . arrays [ eid ] ) ; <nl> + req . push_back ( state . array_reqs [ eid ] ) ; <nl> + CHECK ( req . back ( ) = = kNullOp | | ! ndoutputs . back ( ) - > is_none ( ) ) ; <nl> + } <nl> + const DispatchMode dispatch_mode = dispatch_modes [ i ] ; <nl> + if ( createop . count ( node . source - > op ( ) ) ) { <nl> + arg_shapes . clear ( ) ; <nl> + arg_dtypes . clear ( ) ; <nl> + arg_shapes . reserve ( ndinputs . size ( ) ) ; <nl> + arg_dtypes . reserve ( ndinputs . size ( ) ) ; <nl> + for ( size_t i = 0 ; i < ndinputs . size ( ) ; + + i ) { <nl> + arg_shapes . emplace_back ( ndinputs [ i ] - > shape ( ) ) ; <nl> + arg_dtypes . emplace_back ( ndinputs [ i ] - > dtype ( ) ) ; <nl> + } <nl> + state . op_states [ i ] = createop [ node . source - > op ( ) ] ( <nl> + node . source - > attrs , default_ctx , arg_shapes , arg_dtypes ) ; <nl> + Imperative : : Get ( ) - > InvokeOp ( <nl> + default_ctx , node . source - > attrs , ndinputs , ndoutputs , req , <nl> + dispatch_mode , state . op_states [ i ] ) ; <nl> + } else if ( is_layer_backward . get ( node . source - > op ( ) , false ) ) { <nl> + nnvm : : Node * fwd_node = node . source - > control_deps [ 0 ] . get ( ) ; <nl> + auto fwd_node_id = idx . node_id ( fwd_node ) ; <nl> + Imperative : : Get ( ) - > InvokeOp ( <nl> + default_ctx , node . source - > attrs , ndinputs , ndoutputs , <nl> + req , dispatch_mode , state . op_states [ fwd_node_id ] ) ; <nl> + } else { <nl> + Imperative : : Get ( ) - > InvokeOp ( <nl> + default_ctx , node . source - > attrs , ndinputs , ndoutputs , req , <nl> + dispatch_mode ) ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + <nl> + OpStatePtr CachedOp : : StaticForward ( <nl> + const Context & default_ctx , <nl> + const std : : vector < NDArray * > & inputs , <nl> + const std : : vector < NDArray * > & outputs ) { <nl> + using namespace nnvm ; <nl> + using namespace imperative ; <nl> + <nl> bool recording = Imperative : : Get ( ) - > is_recording ( ) ; <nl> - nnvm : : Graph g = GetForwardGraph ( recording , inputs ) ; <nl> + auto state_ptr = GetCachedOpState ( default_ctx ) ; <nl> + auto & state = state_ptr . get_state < CachedOpState > ( ) ; <nl> + std : : lock_guard < std : : mutex > lock ( state . mutex ) ; <nl> + <nl> + bool match = SetForwardGraph ( & state . info , recording , inputs ) ; <nl> + match = match & & state . recording ! = recording ; <nl> + <nl> + nnvm : : Graph & g = state . info . fwd_graph ; <nl> const auto & idx = g . indexed_graph ( ) ; <nl> - size_t num_inputs = idx . input_nodes ( ) . size ( ) ; <nl> + if ( ! state . fwd_alloc | | ! match ) { <nl> + StaticAllocMemory ( state_ptr , recording , false ) ; <nl> + } <nl> <nl> - for ( size_t i = 0 ; i < inputs . size ( ) ; + + i ) { <nl> - CHECK_EQ ( inputs [ i ] - > ctx ( ) , default_ctx ) <nl> - < < " CachedOp requires all inputs to live on the same context . But " <nl> - < < idx [ idx . input_nodes ( ) [ 0 ] ] . source - > attrs . name < < " is on " < < default_ctx <nl> - < < " while " < < idx [ idx . input_nodes ( ) [ i ] ] . source - > attrs . name < < " is on " <nl> - < < inputs [ i ] - > ctx ( ) ; <nl> + if ( config_ . static_shape ) { <nl> + for ( auto i : config_ . param_indices ) { <nl> + auto nid = idx . input_nodes ( ) [ i ] ; <nl> + if ( ! state . arrays [ idx . entry_id ( nid , 0 ) ] - > IsSame ( * inputs [ i ] ) ) { <nl> + match = false ; <nl> + auto ptr = & state . buff [ idx . entry_id ( nid , 0 ) ] ; <nl> + CHECK_EQ ( state . arrays [ idx . entry_id ( nid , 0 ) ] , ptr ) ; <nl> + * state . arrays [ idx . entry_id ( nid , 0 ) ] = * inputs [ i ] ; <nl> + state . dynamic_entries [ idx . entry_id ( nid , 0 ) ] = false ; <nl> + } <nl> + } <nl> + for ( auto i : config_ . data_indices ) { <nl> + auto eid = idx . entry_id ( idx . input_nodes ( ) [ i ] , 0 ) ; <nl> + state . arrays [ eid ] = inputs [ i ] ; <nl> + } <nl> + } else { <nl> + for ( size_t i = 0 ; i < num_inputs ( ) ; + + i ) { <nl> + auto nid = idx . input_nodes ( ) [ i ] ; <nl> + state . arrays [ idx . entry_id ( nid , 0 ) ] = inputs [ i ] ; <nl> + } <nl> } <nl> <nl> - auto op_state_ptr = OpStatePtr : : Create < CachedOpState > ( ) ; <nl> - auto & cached_op_state = op_state_ptr . get_state < CachedOpState > ( ) ; <nl> - auto & buff = cached_op_state . buff ; <nl> - auto & states = cached_op_state . states ; <nl> + if ( ! state . fwd_exec_init | | ! match ) { <nl> + StaticInitExec ( state_ptr , recording , false ) ; <nl> + } <nl> + <nl> + const auto & dtypes = g . GetAttr < DTypeVector > ( " dtype " ) ; <nl> + const auto & shapes = g . GetAttr < ShapeVector > ( " shape " ) ; <nl> + const auto & stypes = g . GetAttr < StorageTypeVector > ( " storage_type " ) ; <nl> + <nl> + for ( size_t i = 0 ; i < outputs . size ( ) ; + + i ) { <nl> + auto eid = idx . entry_id ( idx . outputs ( ) [ i ] ) ; <nl> + state . arrays [ eid ] = outputs [ i ] ; <nl> + if ( ! outputs [ i ] - > is_none ( ) ) continue ; <nl> + * outputs [ i ] = NDArray ( static_cast < NDArrayStorageType > ( stypes [ eid ] ) , <nl> + shapes [ eid ] , default_ctx , true , dtypes [ eid ] ) ; <nl> + } <nl> + <nl> + StaticRunOps ( default_ctx , g , state_ptr , 0 , idx . num_nodes ( ) ) ; <nl> + <nl> + return recording ? state_ptr : OpStatePtr ( ) ; <nl> + } <nl> + <nl> + <nl> + OpStatePtr CachedOp : : DynamicForward ( <nl> + const Context & default_ctx , <nl> + const std : : vector < NDArray * > & inputs , <nl> + const std : : vector < NDArray * > & outputs ) { <nl> + using namespace nnvm ; <nl> + using namespace imperative ; <nl> + <nl> + / / Initialize <nl> + bool recording = Imperative : : Get ( ) - > is_recording ( ) ; <nl> + auto op_state = OpStatePtr : : Create < DynamicRuntime > ( ) ; <nl> + auto & runtime = op_state . get_state < DynamicRuntime > ( ) ; <nl> + { <nl> + auto state_ptr = GetCachedOpState ( default_ctx ) ; <nl> + auto & state = state_ptr . get_state < CachedOpState > ( ) ; <nl> + std : : lock_guard < std : : mutex > lock ( state . mutex ) ; <nl> + SetForwardGraph ( & state . info , recording , inputs ) ; <nl> + runtime . info . fwd_graph = state . info . fwd_graph ; <nl> + } <nl> + nnvm : : Graph & g = runtime . info . fwd_graph ; <nl> + const auto & idx = g . indexed_graph ( ) ; <nl> + size_t num_inputs = idx . input_nodes ( ) . size ( ) ; <nl> + auto & buff = runtime . buff ; <nl> + auto & states = runtime . op_states ; <nl> <nl> / / Allocate entries <nl> states . resize ( idx . num_nodes ( ) ) ; <nl> void Imperative : : CachedOp : : Forward ( <nl> AllocateMemory ( g , idx , default_ctx , 0 , idx . num_node_entries ( ) , <nl> mem_plan , arrays , & array_reqs ) ; <nl> <nl> + const auto & dtypes = g . GetAttr < DTypeVector > ( " dtype " ) ; <nl> + const auto & shapes = g . GetAttr < ShapeVector > ( " shape " ) ; <nl> + const auto & stypes = g . GetAttr < StorageTypeVector > ( " storage_type " ) ; <nl> + <nl> + for ( size_t i = 0 ; i < outputs . size ( ) ; + + i ) { <nl> + auto eid = idx . entry_id ( idx . outputs ( ) [ i ] ) ; <nl> + arrays [ eid ] = outputs [ i ] ; <nl> + if ( ! outputs [ i ] - > is_none ( ) ) continue ; <nl> + * outputs [ i ] = NDArray ( static_cast < NDArrayStorageType > ( stypes [ eid ] ) , <nl> + shapes [ eid ] , default_ctx , true , dtypes [ eid ] ) ; <nl> + } <nl> + <nl> const auto & dispatch_modes = g . GetAttr < DispatchModeVector > ( " dispatch_mode " ) ; <nl> <nl> if ( recording & & ! inlining_ ) Imperative : : Get ( ) - > set_is_recording ( false ) ; <nl> - int prev_bulk_size = Engine : : Get ( ) - > set_bulk_size ( config_ . forward_bulk_size ) ; <nl> <nl> - Imperative : : Get ( ) - > RunGraph ( <nl> - false , idx , arrays , 0 , idx . num_nodes ( ) , std : : move ( array_reqs ) , <nl> - std : : move ( ref_count ) , & states , dispatch_modes ) ; <nl> + RunGraph ( false , idx , arrays , 0 , idx . num_nodes ( ) , std : : move ( array_reqs ) , <nl> + std : : move ( ref_count ) , & states , dispatch_modes ) ; <nl> <nl> - Engine : : Get ( ) - > set_bulk_size ( prev_bulk_size ) ; <nl> Imperative : : Get ( ) - > set_is_recording ( recording ) ; <nl> <nl> - for ( size_t i = 0 ; i < idx . num_node_entries ( ) ; + + i ) { <nl> - if ( arrays [ i ] = = & buff [ i ] ) continue ; <nl> - buff [ i ] . shape_ = arrays [ i ] - > shape_ ; <nl> - buff [ i ] . dtype_ = arrays [ i ] - > dtype_ ; <nl> - buff [ i ] . storage_type_ = arrays [ i ] - > storage_type_ ; <nl> + return op_state ; <nl> + } <nl> + <nl> + void CachedOp : : Forward ( <nl> + const std : : shared_ptr < CachedOp > & op_ptr , <nl> + const std : : vector < NDArray * > & inputs , <nl> + const std : : vector < NDArray * > & outputs ) { <nl> + static const auto cached_op = nnvm : : Op : : Get ( " _CachedOp " ) ; <nl> + <nl> + CHECK_EQ ( inputs . size ( ) , num_inputs ( ) ) ; <nl> + <nl> + Context default_ctx = inputs [ 0 ] - > ctx ( ) ; <nl> + <nl> + const auto & idx = fwd_graph_ . indexed_graph ( ) ; <nl> + for ( size_t i = 0 ; i < inputs . size ( ) ; + + i ) { <nl> + CHECK_EQ ( inputs [ i ] - > ctx ( ) , default_ctx ) <nl> + < < " CachedOp requires all inputs to live on the same context . But " <nl> + < < idx [ idx . input_nodes ( ) [ 0 ] ] . source - > attrs . name <nl> + < < " is on " < < default_ctx < < " while " <nl> + < < idx [ idx . input_nodes ( ) [ i ] ] . source - > attrs . name <nl> + < < " is on " < < inputs [ i ] - > ctx ( ) ; <nl> } <nl> <nl> - if ( recording & & ! inlining_ ) { <nl> + int prev_bulk_size = Engine : : Get ( ) - > set_bulk_size ( config_ . forward_bulk_size ) ; <nl> + <nl> + OpStatePtr op_state ; <nl> + if ( config_ . static_alloc ) { <nl> + op_state = StaticForward ( default_ctx , inputs , outputs ) ; <nl> + } else { <nl> + op_state = DynamicForward ( default_ctx , inputs , outputs ) ; <nl> + } <nl> + <nl> + Engine : : Get ( ) - > set_bulk_size ( prev_bulk_size ) ; <nl> + <nl> + if ( Imperative : : Get ( ) - > is_recording ( ) & & ! inlining_ ) { <nl> nnvm : : NodeAttrs attrs ; <nl> attrs . op = cached_op ; <nl> attrs . name = " _cachedop " ; <nl> attrs . parsed = op_ptr ; <nl> Imperative : : Get ( ) - > RecordOp ( <nl> - std : : move ( attrs ) , inputs , outputs , op_state_ptr , <nl> + std : : move ( attrs ) , inputs , outputs , op_state , <nl> & save_inputs ( ) , & save_outputs ( ) ) ; <nl> } <nl> } <nl> <nl> <nl> - void Imperative : : CachedOp : : Backward ( <nl> + void CachedOp : : DynamicBackward ( <nl> const bool retain_graph , <nl> - const OpStatePtr & state , <nl> + const OpStatePtr & op_state , <nl> const std : : vector < NDArray * > & inputs , <nl> const std : : vector < OpReqType > & reqs , <nl> const std : : vector < NDArray * > & outputs ) { <nl> using namespace nnvm ; <nl> using namespace imperative ; <nl> - CHECK ( ! Imperative : : Get ( ) - > is_recording ( ) ) <nl> - < < " CachedOp does not support higher order gradients . " <nl> - < < " If you want to do backward with create_graph = True please " <nl> - < < " do not use hybridize . " ; <nl> <nl> / / Initialize <nl> - nnvm : : Graph g = GetBackwardGraph ( state , reqs , inputs ) ; <nl> + Context default_ctx = outputs [ 0 ] - > ctx ( ) ; <nl> + auto & runtime = op_state . get_state < DynamicRuntime > ( ) ; <nl> + { <nl> + auto state_ptr = GetCachedOpState ( default_ctx ) ; <nl> + auto & state = state_ptr . get_state < CachedOpState > ( ) ; <nl> + std : : lock_guard < std : : mutex > lock ( state . mutex ) ; <nl> + state . info . fwd_graph = runtime . info . fwd_graph ; <nl> + SetBackwardGraph ( & state . info , reqs , inputs ) ; <nl> + runtime . info . full_graph = state . info . full_graph ; <nl> + runtime . info . bwd_input_eid = state . info . bwd_input_eid ; <nl> + } <nl> + nnvm : : Graph & g = runtime . info . full_graph ; <nl> const auto & idx = g . indexed_graph ( ) ; <nl> - <nl> - auto & cached_op_state = state . get_state < CachedOpState > ( ) ; <nl> - auto & buff = cached_op_state . buff ; <nl> - auto & states = cached_op_state . states ; <nl> + auto & buff = runtime . buff ; <nl> + auto & states = runtime . op_states ; <nl> <nl> size_t num_forward_outputs = fwd_graph_ . outputs . size ( ) ; <nl> size_t num_forward_nodes = fwd_graph_ . indexed_graph ( ) . num_nodes ( ) ; <nl> void Imperative : : CachedOp : : Backward ( <nl> arrays . reserve ( buff . size ( ) ) ; <nl> for ( size_t i = 0 ; i < buff . size ( ) ; + + i ) arrays . push_back ( & buff [ i ] ) ; <nl> for ( size_t i = 0 ; i < inputs . size ( ) ; + + i ) { <nl> - arrays [ bwd_input_eid_ [ i ] ] = inputs [ i ] ; <nl> + arrays [ runtime . info . bwd_input_eid [ i ] ] = inputs [ i ] ; <nl> } <nl> for ( size_t i = 0 , j = num_forward_outputs ; i < reqs . size ( ) ; + + i ) { <nl> if ( reqs [ i ] = = kNullOp ) continue ; <nl> void Imperative : : CachedOp : : Backward ( <nl> if ( ref_count [ i ] = = 0 ) array_reqs [ i ] = kNullOp ; <nl> } <nl> <nl> - Context default_ctx = outputs [ 0 ] - > ctx ( ) ; <nl> const auto & mem_plan = g . GetAttr < MemoryPlanVector > ( " backward_mem_plan " ) ; <nl> AllocateMemory ( g , idx , default_ctx , num_forward_entries , idx . num_node_entries ( ) , <nl> mem_plan , arrays , & array_reqs ) ; <nl> <nl> const auto & dispatch_modes = g . GetAttr < DispatchModeVector > ( " dispatch_mode " ) ; <nl> <nl> - int prev_bulk_size = Engine : : Get ( ) - > set_bulk_size ( config_ . backward_bulk_size ) ; <nl> - <nl> - Imperative : : Get ( ) - > RunGraph ( <nl> - retain_graph , idx , arrays , num_forward_nodes , idx . num_nodes ( ) , <nl> - std : : move ( array_reqs ) , std : : move ( ref_count ) , & states , dispatch_modes ) ; <nl> - <nl> - Engine : : Get ( ) - > set_bulk_size ( prev_bulk_size ) ; <nl> + RunGraph ( retain_graph , idx , arrays , num_forward_nodes , idx . num_nodes ( ) , <nl> + std : : move ( array_reqs ) , std : : move ( ref_count ) , & states , dispatch_modes ) ; <nl> <nl> if ( retain_graph ) { <nl> buff . resize ( num_forward_entries ) ; <nl> void Imperative : : CachedOp : : Backward ( <nl> } <nl> } <nl> <nl> + void CachedOp : : StaticBackward ( <nl> + const bool retain_graph , <nl> + const OpStatePtr & state_ptr , <nl> + const std : : vector < NDArray * > & inputs , <nl> + const std : : vector < OpReqType > & reqs , <nl> + const std : : vector < NDArray * > & outputs ) { <nl> + using namespace nnvm ; <nl> + using namespace imperative ; <nl> + <nl> + Context default_ctx = outputs [ 0 ] - > ctx ( ) ; <nl> + <nl> + auto & state = state_ptr . get_state < CachedOpState > ( ) ; <nl> + std : : lock_guard < std : : mutex > lock ( state . mutex ) ; <nl> + <nl> + bool match = SetBackwardGraph ( & state . info , reqs , inputs , true ) ; <nl> + <nl> + nnvm : : Graph & g = state . info . full_graph ; <nl> + const auto & idx = g . indexed_graph ( ) ; <nl> + auto num_forward_nodes = state . info . fwd_graph . indexed_graph ( ) . num_nodes ( ) ; <nl> + <nl> + if ( ! state . bwd_alloc | | ! match ) { <nl> + StaticAllocMemory ( state_ptr , true , true ) ; <nl> + } <nl> + <nl> + if ( config_ . static_shape ) { <nl> + for ( auto i : config_ . param_indices ) { <nl> + const auto iter = fwd_input_to_grad_output_ . find ( i ) ; <nl> + if ( iter = = fwd_input_to_grad_output_ . end ( ) ) continue ; <nl> + auto entry = grad_graph_ . outputs [ iter - > second ] ; <nl> + if ( ! idx . exist ( entry . node . get ( ) ) ) continue ; <nl> + auto eid = idx . entry_id ( entry ) ; <nl> + if ( ! state . arrays [ eid ] - > IsSame ( * outputs [ iter - > second ] ) | | <nl> + ! ( state . array_reqs [ eid ] = = reqs [ iter - > second ] ) ) { <nl> + match = false ; <nl> + state . array_reqs [ eid ] = reqs [ iter - > second ] ; <nl> + * state . arrays [ eid ] = * outputs [ iter - > second ] ; <nl> + state . dynamic_entries [ eid ] = false ; <nl> + } <nl> + } <nl> + for ( auto i : config_ . data_indices ) { <nl> + const auto iter = fwd_input_to_grad_output_ . find ( i ) ; <nl> + if ( iter = = fwd_input_to_grad_output_ . end ( ) ) continue ; <nl> + auto entry = grad_graph_ . outputs [ iter - > second ] ; <nl> + if ( ! idx . exist ( entry . node . get ( ) ) ) continue ; <nl> + auto eid = idx . entry_id ( entry ) ; <nl> + state . array_reqs [ eid ] = reqs [ iter - > second ] ; <nl> + state . arrays [ eid ] = outputs [ iter - > second ] ; <nl> + } <nl> + } else { <nl> + for ( size_t i = 0 ; i < grad_graph_ . outputs . size ( ) ; + + i ) { <nl> + auto entry = grad_graph_ . outputs [ i ] ; <nl> + if ( ! idx . exist ( entry . node . get ( ) ) ) continue ; <nl> + auto eid = idx . entry_id ( entry ) ; <nl> + state . array_reqs [ eid ] = reqs [ i ] ; <nl> + state . arrays [ eid ] = outputs [ i ] ; <nl> + } <nl> + } <nl> + <nl> + if ( ! state . bwd_exec_init | | ! match ) { <nl> + StaticInitExec ( state_ptr , true , true ) ; <nl> + } <nl> + <nl> + for ( size_t i = 0 ; i < state . info . bwd_input_eid . size ( ) ; + + i ) { <nl> + auto eid = state . info . bwd_input_eid [ i ] ; <nl> + if ( state . dynamic_entries [ eid ] ) state . arrays [ eid ] = inputs [ i ] ; <nl> + } <nl> + <nl> + StaticRunOps ( default_ctx , g , state_ptr , num_forward_nodes , idx . num_nodes ( ) ) ; <nl> + } <nl> + <nl> + void CachedOp : : Backward ( <nl> + const bool retain_graph , <nl> + const OpStatePtr & state , <nl> + const std : : vector < NDArray * > & inputs , <nl> + const std : : vector < OpReqType > & reqs , <nl> + const std : : vector < NDArray * > & outputs ) { <nl> + using namespace imperative ; <nl> + CHECK ( ! Imperative : : Get ( ) - > is_recording ( ) ) <nl> + < < " CachedOp does not support higher order gradients . " <nl> + < < " If you want to do backward with create_graph = True please " <nl> + < < " do not use hybridize . " ; <nl> + <nl> + int prev_bulk_size = Engine : : Get ( ) - > set_bulk_size ( config_ . backward_bulk_size ) ; <nl> + <nl> + if ( config_ . static_alloc ) { <nl> + StaticBackward ( retain_graph , state , inputs , reqs , outputs ) ; <nl> + } else { <nl> + DynamicBackward ( retain_graph , state , inputs , reqs , outputs ) ; <nl> + } <nl> + <nl> + Engine : : Get ( ) - > set_bulk_size ( prev_bulk_size ) ; <nl> + } <nl> + <nl> <nl> NNVM_REGISTER_OP ( _CachedOp ) <nl> . set_num_inputs ( [ ] ( const NodeAttrs & attrs ) { <nl> new file mode 100644 <nl> index 00000000000 . . 60a40c5e4a5 <nl> mmm / dev / null <nl> ppp b / src / imperative / cached_op . h <nl> <nl> + / * <nl> + * Licensed to the Apache Software Foundation ( ASF ) under one <nl> + * or more contributor license agreements . See the NOTICE file <nl> + * distributed with this work for additional information <nl> + * regarding copyright ownership . The ASF licenses this file <nl> + * to you under the Apache License , Version 2 . 0 ( the <nl> + * " License " ) ; you may not use this file except in compliance <nl> + * with the License . You may obtain a copy of the License at <nl> + * <nl> + * http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + * <nl> + * Unless required by applicable law or agreed to in writing , <nl> + * software distributed under the License is distributed on an <nl> + * " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY <nl> + * KIND , either express or implied . See the License for the <nl> + * specific language governing permissions and limitations <nl> + * under the License . <nl> + * / <nl> + <nl> + # ifndef MXNET_IMPERATIVE_CACHED_OP_H_ <nl> + # define MXNET_IMPERATIVE_CACHED_OP_H_ <nl> + <nl> + # include < mxnet / imperative . h > <nl> + # include < vector > <nl> + # include < atomic > <nl> + # include < utility > <nl> + # include < string > <nl> + # include < unordered_map > <nl> + <nl> + namespace mxnet { <nl> + / * ! \ brief CachedOp Parameters * / <nl> + struct CachedOpConfig : public dmlc : : Parameter < CachedOpConfig > { <nl> + uint32_t inline_limit ; <nl> + uint32_t forward_bulk_size ; <nl> + uint32_t backward_bulk_size ; <nl> + bool static_alloc ; <nl> + bool static_shape ; <nl> + nnvm : : Tuple < uint32_t > data_indices ; <nl> + nnvm : : Tuple < uint32_t > param_indices ; <nl> + DMLC_DECLARE_PARAMETER ( CachedOpConfig ) { <nl> + DMLC_DECLARE_FIELD ( static_alloc ) <nl> + . set_default ( false ) <nl> + . describe ( " Statically allocate memory to improve speed . " <nl> + " Memory usage may increase . " ) ; <nl> + DMLC_DECLARE_FIELD ( static_shape ) <nl> + . set_default ( false ) <nl> + . describe ( " Optimize for invariant input shapes between iterations . " <nl> + " Must also set static_alloc to True . " <nl> + " Change of input shapes is still allowed but slower . " ) ; <nl> + DMLC_DECLARE_FIELD ( inline_limit ) <nl> + . set_default ( 2 ) <nl> + . describe ( " Maximum number of operators that can be inlined . " ) ; <nl> + DMLC_DECLARE_FIELD ( forward_bulk_size ) <nl> + . set_default ( dmlc : : GetEnv ( " MXNET_EXEC_BULK_EXEC_MAX_NODE_TRAIN " , 15 ) ) <nl> + . describe ( " Segment size of bulk execution during forward pass . " ) ; <nl> + DMLC_DECLARE_FIELD ( backward_bulk_size ) <nl> + . set_default ( dmlc : : GetEnv ( " MXNET_EXEC_BULK_EXEC_MAX_NODE_TRAIN " , 15 ) ) <nl> + . describe ( " Segment size of bulk execution during backward pass . " ) ; <nl> + DMLC_DECLARE_FIELD ( data_indices ) <nl> + . set_default ( nnvm : : Tuple < uint32_t > ( ) ) <nl> + . describe ( " Position of argument variables . " ) ; <nl> + DMLC_DECLARE_FIELD ( param_indices ) <nl> + . set_default ( nnvm : : Tuple < uint32_t > ( ) ) <nl> + . describe ( " Position of parameters . " ) ; <nl> + } <nl> + } ; <nl> + <nl> + class CachedOp { <nl> + public : <nl> + CachedOp ( <nl> + const nnvm : : Symbol & sym , <nl> + const std : : vector < std : : pair < std : : string , std : : string > > & flags ) ; <nl> + ~ CachedOp ( ) ; <nl> + uint32_t num_inputs ( ) { <nl> + return fwd_graph_ . indexed_graph ( ) . input_nodes ( ) . size ( ) ; <nl> + } <nl> + uint32_t num_outputs ( ) { <nl> + return fwd_graph_ . outputs . size ( ) ; <nl> + } <nl> + uint32_t num_backward_inputs ( ) { <nl> + return bwd_ograd_dep_ . size ( ) + bwd_in_dep_ . size ( ) + bwd_out_dep_ . size ( ) ; <nl> + } <nl> + std : : vector < bool > & save_inputs ( ) { <nl> + return save_inputs_ ; <nl> + } <nl> + std : : vector < bool > & save_outputs ( ) { <nl> + return save_outputs_ ; <nl> + } <nl> + const std : : unordered_set < uint32_t > & mutable_input_nodes ( ) { <nl> + return fwd_graph_ . indexed_graph ( ) . mutable_input_nodes ( ) ; <nl> + } <nl> + std : : vector < nnvm : : NodeEntry > Gradient ( <nl> + const nnvm : : NodePtr & node , <nl> + const std : : vector < nnvm : : NodeEntry > & ograds ) ; <nl> + void Forward ( <nl> + const std : : shared_ptr < CachedOp > & op_ptr , <nl> + const std : : vector < NDArray * > & inputs , <nl> + const std : : vector < NDArray * > & outputs ) ; <nl> + void Backward ( <nl> + const bool retain_graph , <nl> + const OpStatePtr & state , <nl> + const std : : vector < NDArray * > & inputs , <nl> + const std : : vector < OpReqType > & reqs , <nl> + const std : : vector < NDArray * > & outputs ) ; <nl> + <nl> + private : <nl> + struct GraphInfo ; <nl> + struct DynamicRuntime ; <nl> + struct CachedOpState ; <nl> + <nl> + OpStatePtr GetCachedOpState ( const Context & ctx ) ; <nl> + bool SetForwardGraph ( <nl> + GraphInfo * info , <nl> + const bool recording , <nl> + const std : : vector < NDArray * > & inputs ) ; <nl> + bool SetBackwardGraph ( <nl> + GraphInfo * info , <nl> + const std : : vector < OpReqType > & reqs , <nl> + const std : : vector < NDArray * > & inputs , <nl> + bool detect_inplace_addto = false ) ; <nl> + OpStatePtr DynamicForward ( <nl> + const Context & default_ctx , <nl> + const std : : vector < NDArray * > & inputs , <nl> + const std : : vector < NDArray * > & outputs ) ; <nl> + void DynamicBackward ( <nl> + const bool retain_graph , <nl> + const OpStatePtr & op_state , <nl> + const std : : vector < NDArray * > & inputs , <nl> + const std : : vector < OpReqType > & reqs , <nl> + const std : : vector < NDArray * > & outputs ) ; <nl> + void StaticAllocMemory ( <nl> + const OpStatePtr & state_ptr , <nl> + bool recording , <nl> + bool keep_fwd ) ; <nl> + void StaticInitExec ( <nl> + const OpStatePtr & state_ptr , <nl> + bool recording , <nl> + bool keep_fwd ) ; <nl> + void StaticRunOps ( <nl> + const Context & default_ctx , <nl> + const nnvm : : Graph & g , <nl> + const OpStatePtr & state_ptr , <nl> + size_t start_nid , <nl> + size_t end_nid ) ; <nl> + OpStatePtr StaticForward ( <nl> + const Context & default_ctx , <nl> + const std : : vector < NDArray * > & inputs , <nl> + const std : : vector < NDArray * > & outputs ) ; <nl> + void StaticBackward ( <nl> + const bool retain_graph , <nl> + const OpStatePtr & state_ptr , <nl> + const std : : vector < NDArray * > & inputs , <nl> + const std : : vector < OpReqType > & reqs , <nl> + const std : : vector < NDArray * > & outputs ) ; <nl> + <nl> + CachedOpConfig config_ ; <nl> + nnvm : : Graph fwd_graph_ ; <nl> + nnvm : : Graph grad_graph_ ; <nl> + nnvm : : Graph full_graph_ ; <nl> + bool inlining_ ; <nl> + std : : vector < nnvm : : NodeEntry > ograd_entries_ ; <nl> + std : : vector < uint32_t > bwd_in_dep_ , bwd_out_dep_ , bwd_ograd_dep_ ; <nl> + std : : unordered_map < uint32_t , uint32_t > fwd_input_to_grad_output_ ; <nl> + std : : vector < bool > save_inputs_ , save_outputs_ ; <nl> + std : : vector < OpReqType > bwd_output_reqs_ ; <nl> + <nl> + std : : mutex mutex_ ; <nl> + std : : unordered_map < Context , std : : vector < OpStatePtr > > cached_op_states_ ; <nl> + } ; <nl> + <nl> + using CachedOpPtr = std : : shared_ptr < CachedOp > ; <nl> + <nl> + } / / namespace mxnet <nl> + # endif / / MXNET_IMPERATIVE_CACHED_OP_H_ <nl> mmm a / src / imperative / imperative . cc <nl> ppp b / src / imperative / imperative . cc <nl> <nl> # include < unordered_set > <nl> # include < iostream > <nl> # include " . / imperative_utils . h " <nl> + # include " . / cached_op . h " <nl> <nl> namespace mxnet { <nl> # if DMLC_CXX11_THREAD_LOCAL <nl> void Imperative : : RecordOp ( <nl> } <nl> } <nl> <nl> - void Imperative : : RunGraph ( <nl> - const bool retain_graph , <nl> - const nnvm : : IndexedGraph & idx , <nl> - const std : : vector < NDArray * > arrays , <nl> - size_t node_start , size_t node_end , <nl> - std : : vector < OpReqType > & & array_reqs , <nl> - std : : vector < uint32_t > & & ref_count , <nl> - std : : vector < OpStatePtr > * p_states , <nl> - const DispatchModeVector & dispatch_modes ) { <nl> - using namespace nnvm ; <nl> - using namespace imperative ; <nl> - static auto & createop = nnvm : : Op : : GetAttr < FCreateOpState > ( " FCreateOpState " ) ; <nl> - static auto & is_layer_backward = Op : : GetAttr < bool > ( " TIsLayerOpBackward " ) ; <nl> - static const auto bwd_cached_op = Op : : Get ( " _backward_CachedOp " ) ; <nl> - <nl> - std : : vector < OpStatePtr > & states = * p_states ; <nl> - bool recording = is_recording ( ) ; <nl> - <nl> - std : : vector < NDArray * > ndinputs , ndoutputs ; <nl> - ShapeVector arg_shapes ; <nl> - DTypeVector arg_dtypes ; <nl> - std : : vector < OpReqType > req ; <nl> - <nl> - for ( size_t i = node_start ; i < node_end ; + + i ) { <nl> - const nnvm : : IndexedGraph : : Node & node = idx [ i ] ; <nl> - if ( node . source - > op ( ) = = nullptr ) continue ; <nl> - auto num_outputs = node . source - > num_outputs ( ) ; <nl> - ndinputs . clear ( ) ; <nl> - ndinputs . reserve ( node . inputs . size ( ) ) ; <nl> - for ( const auto & j : node . inputs ) { <nl> - ndinputs . emplace_back ( arrays [ idx . entry_id ( j ) ] ) ; <nl> - CHECK ( ! ndinputs . back ( ) - > is_none ( ) ) < < idx [ j . node_id ] . source - > attrs . name < < " " < < j . index ; <nl> - } <nl> - ndoutputs . clear ( ) ; <nl> - ndoutputs . reserve ( num_outputs ) ; <nl> - req . clear ( ) ; <nl> - req . reserve ( num_outputs ) ; <nl> - for ( size_t j = 0 ; j < num_outputs ; + + j ) { <nl> - size_t eid = idx . entry_id ( i , j ) ; <nl> - ndoutputs . emplace_back ( arrays [ eid ] ) ; <nl> - req . push_back ( array_reqs [ eid ] ) ; <nl> - CHECK ( ! ndoutputs . back ( ) - > is_none ( ) ) ; <nl> - } <nl> - const Context & ctx = ndoutputs [ 0 ] - > ctx ( ) ; <nl> - const DispatchMode dispatch_mode = dispatch_modes [ i ] ; <nl> - if ( node . source - > op ( ) = = bwd_cached_op ) { <nl> - const auto & cached_op = dmlc : : get < CachedOpPtr > ( node . source - > attrs . parsed ) ; <nl> - nnvm : : Node * fwd_node = node . source - > control_deps [ 0 ] . get ( ) ; <nl> - auto fwd_node_id = idx . node_id ( fwd_node ) ; <nl> - cached_op - > Backward ( retain_graph , states [ fwd_node_id ] , ndinputs , req , ndoutputs ) ; <nl> - } else if ( createop . count ( node . source - > op ( ) ) ) { <nl> - arg_shapes . clear ( ) ; <nl> - arg_dtypes . clear ( ) ; <nl> - arg_shapes . reserve ( ndinputs . size ( ) ) ; <nl> - arg_dtypes . reserve ( ndinputs . size ( ) ) ; <nl> - for ( size_t i = 0 ; i < ndinputs . size ( ) ; + + i ) { <nl> - arg_shapes . emplace_back ( ndinputs [ i ] - > shape ( ) ) ; <nl> - arg_dtypes . emplace_back ( ndinputs [ i ] - > dtype ( ) ) ; <nl> - } <nl> - states [ i ] = createop [ node . source - > op ( ) ] ( <nl> - node . source - > attrs , ctx , arg_shapes , arg_dtypes ) ; <nl> - InvokeOp ( ctx , node . source - > attrs , ndinputs , ndoutputs , req , dispatch_mode , states [ i ] ) ; <nl> - if ( recording ) RecordOp ( NodeAttrs ( node . source - > attrs ) , ndinputs , ndoutputs , states [ i ] ) ; <nl> - } else if ( is_layer_backward . get ( node . source - > op ( ) , false ) ) { <nl> - nnvm : : Node * fwd_node = node . source - > control_deps [ 0 ] . get ( ) ; <nl> - auto fwd_node_id = idx . node_id ( fwd_node ) ; <nl> - InvokeOp ( ctx , node . source - > attrs , ndinputs , ndoutputs , <nl> - req , dispatch_mode , states [ fwd_node_id ] ) ; <nl> - if ( recording ) { <nl> - RecordOp ( NodeAttrs ( node . source - > attrs ) , ndinputs , ndoutputs , states [ fwd_node_id ] ) ; <nl> - } <nl> - } else { <nl> - InvokeOp ( ctx , node . source - > attrs , ndinputs , ndoutputs , req , dispatch_mode ) ; <nl> - if ( recording ) RecordOp ( NodeAttrs ( node . source - > attrs ) , ndinputs , ndoutputs ) ; <nl> - } <nl> - <nl> - for ( const auto & j : node . inputs ) { <nl> - size_t eid = idx . entry_id ( j ) ; <nl> - - - ref_count [ eid ] ; <nl> - if ( ref_count [ eid ] = = 0 ) arrays [ eid ] - > ptr_ . reset ( ) ; <nl> - } <nl> - for ( size_t j = 0 ; j < ndoutputs . size ( ) ; + + j ) { <nl> - size_t eid = idx . entry_id ( i , j ) ; <nl> - if ( ref_count [ eid ] = = 0 ) arrays [ eid ] - > ptr_ . reset ( ) ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - <nl> std : : vector < NDArray * > Imperative : : Backward ( <nl> const std : : vector < NDArray * > & outputs , <nl> const std : : vector < NDArray * > & ograds , <nl> new file mode 100644 <nl> index 00000000000 . . 464aefc220d <nl> mmm / dev / null <nl> ppp b / src / imperative / imperative_utils . cc <nl> <nl> + / * <nl> + * Licensed to the Apache Software Foundation ( ASF ) under one <nl> + * or more contributor license agreements . See the NOTICE file <nl> + * distributed with this work for additional information <nl> + * regarding copyright ownership . The ASF licenses this file <nl> + * to you under the Apache License , Version 2 . 0 ( the <nl> + * " License " ) ; you may not use this file except in compliance <nl> + * with the License . You may obtain a copy of the License at <nl> + * <nl> + * http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + * <nl> + * Unless required by applicable law or agreed to in writing , <nl> + * software distributed under the License is distributed on an <nl> + * " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY <nl> + * KIND , either express or implied . See the License for the <nl> + * specific language governing permissions and limitations <nl> + * under the License . <nl> + * / <nl> + <nl> + # include " . / imperative_utils . h " <nl> + # include " . / cached_op . h " <nl> + <nl> + namespace mxnet { <nl> + namespace imperative { <nl> + void RunGraph ( <nl> + const bool retain_graph , <nl> + const nnvm : : IndexedGraph & idx , <nl> + const std : : vector < NDArray * > arrays , <nl> + size_t node_start , size_t node_end , <nl> + std : : vector < OpReqType > & & array_reqs , <nl> + std : : vector < uint32_t > & & ref_count , <nl> + std : : vector < OpStatePtr > * p_states , <nl> + const DispatchModeVector & dispatch_modes ) { <nl> + using namespace nnvm ; <nl> + using namespace imperative ; <nl> + static auto & createop = nnvm : : Op : : GetAttr < FCreateOpState > ( " FCreateOpState " ) ; <nl> + static auto & is_layer_backward = Op : : GetAttr < bool > ( " TIsLayerOpBackward " ) ; <nl> + static const auto bwd_cached_op = Op : : Get ( " _backward_CachedOp " ) ; <nl> + <nl> + const auto imp = Imperative : : Get ( ) ; <nl> + <nl> + std : : vector < OpStatePtr > & states = * p_states ; <nl> + bool recording = imp - > is_recording ( ) ; <nl> + <nl> + std : : vector < NDArray * > ndinputs , ndoutputs ; <nl> + ShapeVector arg_shapes ; <nl> + DTypeVector arg_dtypes ; <nl> + std : : vector < OpReqType > req ; <nl> + <nl> + for ( size_t i = node_start ; i < node_end ; + + i ) { <nl> + const nnvm : : IndexedGraph : : Node & node = idx [ i ] ; <nl> + if ( node . source - > op ( ) = = nullptr ) continue ; <nl> + auto num_outputs = node . source - > num_outputs ( ) ; <nl> + ndinputs . clear ( ) ; <nl> + ndinputs . reserve ( node . inputs . size ( ) ) ; <nl> + for ( const auto & j : node . inputs ) { <nl> + ndinputs . emplace_back ( arrays [ idx . entry_id ( j ) ] ) ; <nl> + CHECK ( ! ndinputs . back ( ) - > is_none ( ) ) < < idx [ j . node_id ] . source - > attrs . name < < " " < < j . index ; <nl> + } <nl> + ndoutputs . clear ( ) ; <nl> + ndoutputs . reserve ( num_outputs ) ; <nl> + req . clear ( ) ; <nl> + req . reserve ( num_outputs ) ; <nl> + for ( size_t j = 0 ; j < num_outputs ; + + j ) { <nl> + size_t eid = idx . entry_id ( i , j ) ; <nl> + ndoutputs . emplace_back ( arrays [ eid ] ) ; <nl> + req . push_back ( array_reqs [ eid ] ) ; <nl> + CHECK ( array_reqs [ eid ] = = kNullOp | | ! ndoutputs . back ( ) - > is_none ( ) ) ; <nl> + } <nl> + const Context & ctx = ndoutputs [ 0 ] - > ctx ( ) ; <nl> + const DispatchMode dispatch_mode = dispatch_modes [ i ] ; <nl> + if ( node . source - > op ( ) = = bwd_cached_op ) { <nl> + const auto & cached_op = dmlc : : get < CachedOpPtr > ( node . source - > attrs . parsed ) ; <nl> + nnvm : : Node * fwd_node = node . source - > control_deps [ 0 ] . get ( ) ; <nl> + auto fwd_node_id = idx . node_id ( fwd_node ) ; <nl> + cached_op - > Backward ( retain_graph , states [ fwd_node_id ] , ndinputs , req , ndoutputs ) ; <nl> + } else if ( createop . count ( node . source - > op ( ) ) ) { <nl> + arg_shapes . clear ( ) ; <nl> + arg_dtypes . clear ( ) ; <nl> + arg_shapes . reserve ( ndinputs . size ( ) ) ; <nl> + arg_dtypes . reserve ( ndinputs . size ( ) ) ; <nl> + for ( size_t i = 0 ; i < ndinputs . size ( ) ; + + i ) { <nl> + arg_shapes . emplace_back ( ndinputs [ i ] - > shape ( ) ) ; <nl> + arg_dtypes . emplace_back ( ndinputs [ i ] - > dtype ( ) ) ; <nl> + } <nl> + states [ i ] = createop [ node . source - > op ( ) ] ( <nl> + node . source - > attrs , ctx , arg_shapes , arg_dtypes ) ; <nl> + imp - > InvokeOp ( ctx , node . source - > attrs , ndinputs , ndoutputs , req , dispatch_mode , states [ i ] ) ; <nl> + if ( recording ) { <nl> + imp - > RecordOp ( NodeAttrs ( node . source - > attrs ) , ndinputs , ndoutputs , states [ i ] ) ; <nl> + } <nl> + } else if ( is_layer_backward . get ( node . source - > op ( ) , false ) ) { <nl> + nnvm : : Node * fwd_node = node . source - > control_deps [ 0 ] . get ( ) ; <nl> + auto fwd_node_id = idx . node_id ( fwd_node ) ; <nl> + imp - > InvokeOp ( ctx , node . source - > attrs , ndinputs , ndoutputs , <nl> + req , dispatch_mode , states [ fwd_node_id ] ) ; <nl> + if ( recording ) { <nl> + imp - > RecordOp ( NodeAttrs ( node . source - > attrs ) , ndinputs , ndoutputs , states [ fwd_node_id ] ) ; <nl> + } <nl> + } else { <nl> + imp - > InvokeOp ( ctx , node . source - > attrs , ndinputs , ndoutputs , req , dispatch_mode ) ; <nl> + if ( recording ) { <nl> + imp - > RecordOp ( NodeAttrs ( node . source - > attrs ) , ndinputs , ndoutputs ) ; <nl> + } <nl> + } <nl> + <nl> + for ( const auto & j : node . inputs ) { <nl> + size_t eid = idx . entry_id ( j ) ; <nl> + - - ref_count [ eid ] ; <nl> + if ( ref_count [ eid ] = = 0 ) * arrays [ eid ] = NDArray ( ) ; <nl> + } <nl> + for ( size_t j = 0 ; j < ndoutputs . size ( ) ; + + j ) { <nl> + size_t eid = idx . entry_id ( i , j ) ; <nl> + if ( ref_count [ eid ] = = 0 ) * arrays [ eid ] = NDArray ( ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + } / / namespace imperative <nl> + } / / namespace mxnet <nl> mmm a / src / imperative / imperative_utils . h <nl> ppp b / src / imperative / imperative_utils . h <nl> <nl> # include < utility > <nl> # include < algorithm > <nl> # include < vector > <nl> + # include < map > <nl> # include < string > <nl> # include " . . / executor / graph_executor . h " <nl> # include " . . / executor / exec_pass . h " <nl> namespace mxnet { <nl> namespace imperative { <nl> <nl> struct MemoryPlanInfo { <nl> - uint32_t sid ; <nl> + int storage_id ; <nl> + uint32_t root ; <nl> size_t size ; <nl> bool inplace ; <nl> } ; <nl> <nl> + struct EngineOprDeleter { <nl> + void operator ( ) ( engine : : Opr * handle ) { <nl> + Engine : : Get ( ) - > DeleteOperator ( handle ) ; <nl> + } <nl> + } ; <nl> + <nl> + struct EngineOprSeg { <nl> + bool skip ; <nl> + size_t next_nid ; <nl> + std : : unique_ptr < engine : : Opr , EngineOprDeleter > opr ; <nl> + } ; <nl> + <nl> using MemoryPlanVector = std : : vector < MemoryPlanInfo > ; <nl> <nl> inline Context GetContext ( const nnvm : : NodeAttrs & attrs , <nl> inline std : : vector < Context > PlaceDevice ( const nnvm : : IndexedGraph & idx ) { <nl> <nl> <nl> inline MemoryPlanVector PlanMemory ( <nl> - nnvm : : Graph * p_g , nnvm : : StorageVector & & storage , <nl> + nnvm : : Graph * p_g , <nl> + nnvm : : StorageVector & & storage , <nl> const std : : vector < uint32_t > & ref_count , <nl> const std : : pair < uint32_t , uint32_t > & node_range = { 0 , 0 } , <nl> - const std : : pair < uint32_t , uint32_t > & entry_range = { 0 , 0 } ) { <nl> + const std : : pair < uint32_t , uint32_t > & entry_range = { 0 , 0 } , <nl> + bool detect_inplace_addto = false ) { <nl> using namespace nnvm ; <nl> nnvm : : Graph & g = * p_g ; <nl> const auto & idx = g . indexed_graph ( ) ; <nl> inline MemoryPlanVector PlanMemory ( <nl> g . attrs [ " ref_count " ] = std : : make_shared < dmlc : : any > ( ref_count ) ; <nl> g . attrs [ " storage " ] = std : : make_shared < dmlc : : any > ( std : : move ( storage ) ) ; <nl> g = nnvm : : ApplyPass ( g , " PlanMemory " ) ; <nl> + if ( detect_inplace_addto ) g = exec : : DetectInplaceAddTo ( g ) ; <nl> <nl> const auto & dtypes = g . GetAttr < DTypeVector > ( " dtype " ) ; <nl> const auto & shapes = g . GetAttr < ShapeVector > ( " shape " ) ; <nl> - const auto & stypes = g . GetAttr < StorageTypeVector > ( " storage_type " ) ; <nl> - auto storage_ids = g . MoveCopyAttr < StorageVector > ( " storage_id " ) ; <nl> - auto storage_inplace = g . MoveCopyAttr < std : : vector < int > > ( " storage_inplace_index " ) ; <nl> + const auto & storage_inplace = g . GetAttr < std : : vector < int > > ( " storage_inplace_index " ) ; <nl> + const auto & storage_ids = g . GetAttr < StorageVector > ( " storage_id " ) ; <nl> uint32_t entry_start = entry_range . first ; <nl> uint32_t entry_end = <nl> entry_range . second > entry_start ? entry_range . second : idx . num_node_entries ( ) ; <nl> MemoryPlanVector mem_plan ( idx . num_node_entries ( ) ) ; <nl> - std : : unordered_map < int , uint32_t > sid_to_loc ; <nl> + std : : unordered_map < int , uint32_t > sid_to_root ; <nl> <nl> for ( uint32_t i = entry_start ; i < entry_end ; + + i ) { <nl> - if ( stypes [ i ] ! = kDefaultStorage ) continue ; <nl> if ( storage_ids [ i ] < 0 ) { <nl> - mem_plan [ i ] = { i , mshadow : : mshadow_sizeof ( dtypes [ i ] ) * shapes [ i ] . Size ( ) , false } ; <nl> - } else if ( ! sid_to_loc . count ( storage_ids [ i ] ) ) { <nl> + mem_plan [ i ] = { storage_ids [ i ] , i , 0 , false } ; <nl> + } else if ( ! sid_to_root . count ( storage_ids [ i ] ) ) { <nl> CHECK_LT ( storage_inplace [ i ] , 0 ) ; <nl> - sid_to_loc [ storage_ids [ i ] ] = i ; <nl> - mem_plan [ i ] . sid = i ; <nl> - mem_plan [ i ] . size = mshadow : : mshadow_sizeof ( dtypes [ i ] ) * shapes [ i ] . Size ( ) ; <nl> + sid_to_root [ storage_ids [ i ] ] = i ; <nl> + mem_plan [ i ] = { storage_ids [ i ] , i , <nl> + mshadow : : mshadow_sizeof ( dtypes [ i ] ) * shapes [ i ] . Size ( ) , <nl> + false } ; <nl> } else { <nl> - uint32_t loc = sid_to_loc [ storage_ids [ i ] ] ; <nl> - mem_plan [ i ] = { loc , 0 , storage_inplace [ i ] > = 0 } ; <nl> - mem_plan [ loc ] . size = std : : max ( mem_plan [ loc ] . size , <nl> + uint32_t root = sid_to_root [ storage_ids [ i ] ] ; <nl> + mem_plan [ i ] = { storage_ids [ i ] , root , 0 , storage_inplace [ i ] > = 0 } ; <nl> + mem_plan [ root ] . size = std : : max ( mem_plan [ root ] . size , <nl> mshadow : : mshadow_sizeof ( dtypes [ i ] ) * shapes [ i ] . Size ( ) ) ; <nl> } <nl> } <nl> inline MemoryPlanVector PlanMemory ( <nl> } <nl> <nl> <nl> - inline void AllocateMemory ( const nnvm : : Graph & g , <nl> - const nnvm : : IndexedGraph & idx , <nl> - const Context & default_ctx , <nl> - const uint32_t entry_start , const uint32_t entry_end , <nl> - const MemoryPlanVector & mem_plan , <nl> - const std : : vector < NDArray * > & arrays , <nl> - std : : vector < OpReqType > * array_reqs ) { <nl> + inline std : : multimap < size_t , NDArray > AllocateMemory ( <nl> + const nnvm : : Graph & g , <nl> + const nnvm : : IndexedGraph & idx , <nl> + const Context & default_ctx , <nl> + const uint32_t entry_start , const uint32_t entry_end , <nl> + const MemoryPlanVector & mem_plan , <nl> + const std : : vector < NDArray * > & arrays , <nl> + std : : vector < OpReqType > * array_reqs , <nl> + std : : multimap < size_t , NDArray > & & pool = std : : multimap < size_t , NDArray > ( ) ) { <nl> using namespace nnvm ; <nl> const auto & dtypes = g . GetAttr < DTypeVector > ( " dtype " ) ; <nl> const auto & shapes = g . GetAttr < ShapeVector > ( " shape " ) ; <nl> const auto & stypes = g . GetAttr < StorageTypeVector > ( " storage_type " ) ; <nl> <nl> + std : : multimap < size_t , NDArray > new_pool ; <nl> + <nl> for ( uint32_t i = entry_start ; i < entry_end ; + + i ) { <nl> - if ( ! arrays [ i ] - > is_none ( ) ) continue ; <nl> - if ( stypes [ i ] = = kDefaultStorage ) { <nl> - if ( mem_plan [ i ] . sid = = i ) { <nl> - CHECK_GT ( mem_plan [ i ] . size , 0 ) ; <nl> + if ( mem_plan [ i ] . storage_id = = exec : : kExternalStorageID ) continue ; <nl> + CHECK ( arrays [ i ] - > is_none ( ) ) ; <nl> + if ( mem_plan [ i ] . storage_id = = exec : : kDynamicStorageID ) { <nl> + * arrays [ i ] = NDArray ( static_cast < NDArrayStorageType > ( stypes [ i ] ) , <nl> + shapes [ i ] , default_ctx , true , dtypes [ i ] ) ; <nl> + continue ; <nl> + } <nl> + CHECK_EQ ( stypes [ i ] , kDefaultStorage ) ; <nl> + if ( mem_plan [ i ] . root = = i ) { <nl> + CHECK_GT ( mem_plan [ i ] . size , 0 ) ; <nl> + auto iter = pool . lower_bound ( mem_plan [ i ] . size ) ; <nl> + if ( iter ! = pool . end ( ) ) { <nl> + * arrays [ i ] = iter - > second . AsArray ( shapes [ i ] , dtypes [ i ] ) ; <nl> + new_pool . insert ( * iter ) ; <nl> + pool . erase ( iter ) ; <nl> + } else { <nl> NDArray buff ( TShape ( { static_cast < nnvm : : dim_t > ( mem_plan [ i ] . size ) } ) , <nl> default_ctx , true , mshadow : : kUint8 ) ; <nl> * arrays [ i ] = buff . AsArray ( shapes [ i ] , dtypes [ i ] ) ; <nl> + new_pool . insert ( { mem_plan [ i ] . size , buff } ) ; <nl> + } <nl> + } else { <nl> + CHECK_GE ( mem_plan [ mem_plan [ i ] . root ] . storage_id , 0 ) ; <nl> + * arrays [ i ] = arrays [ mem_plan [ i ] . root ] - > AsArray ( shapes [ i ] , dtypes [ i ] ) ; <nl> + if ( mem_plan [ i ] . inplace & & array_reqs - > at ( i ) = = kWriteTo ) { <nl> + array_reqs - > at ( i ) = kWriteInplace ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + return new_pool ; <nl> + } <nl> + <nl> + inline void SetupOpExec ( <nl> + const nnvm : : Graph & g , <nl> + size_t nid , <nl> + const std : : shared_ptr < exec : : OpExecutor > & exec , <nl> + const std : : vector < NDArray * > arrays , <nl> + const std : : vector < OpReqType > array_reqs ) { <nl> + const auto & idx = g . indexed_graph ( ) ; <nl> + const auto & inode = idx [ nid ] ; <nl> + CHECK_EQ ( exec - > in_array . size ( ) , 0U ) ; <nl> + CHECK_EQ ( exec - > out_array . size ( ) , 0U ) ; <nl> + for ( const auto & e : inode . inputs ) { <nl> + CHECK ( ! arrays [ idx . entry_id ( e ) ] - > is_none ( ) ) < < inode . source - > attrs . name ; <nl> + exec - > in_array . push_back ( * arrays [ idx . entry_id ( e ) ] ) ; <nl> + } <nl> + for ( uint32_t index = 0 ; index < inode . source - > num_outputs ( ) ; + + index ) { <nl> + uint32_t eid = idx . entry_id ( nid , index ) ; <nl> + CHECK ( ! arrays [ eid ] - > is_none ( ) ) < < inode . source - > attrs . name ; <nl> + exec - > out_array . push_back ( * arrays [ eid ] ) ; <nl> + exec - > req . push_back ( array_reqs [ eid ] ) ; <nl> + } <nl> + <nl> + exec - > Setup ( ) ; <nl> + } <nl> + <nl> + inline Engine : : OprHandle CreateEngineOp ( <nl> + const Context & default_ctx , <nl> + const std : : vector < std : : shared_ptr < exec : : OpExecutor > > & execs ) { <nl> + CHECK_GT ( execs . size ( ) , 0 ) ; <nl> + std : : vector < Engine : : VarHandle > use_vars , mutate_vars ; <nl> + <nl> + for ( const auto & exec : execs ) { <nl> + CHECK_GT ( exec - > out_array . size ( ) , 0 ) ; <nl> + CHECK ( execs . size ( ) = = 1 | | exec - > exec_type ( ) = = ExecType : : kSync ) ; <nl> + <nl> + / / the variables <nl> + for ( const auto & nd : exec - > in_array ) { <nl> + use_vars . push_back ( nd . var ( ) ) ; <nl> + } <nl> + for ( auto & r : exec - > op_ctx . requested ) { <nl> + mutate_vars . push_back ( r . var ) ; <nl> + } <nl> + for ( auto & nd : exec - > out_array ) { <nl> + mutate_vars . push_back ( nd . var ( ) ) ; <nl> + } <nl> + if ( exec - > var ( ) ! = nullptr ) { <nl> + mutate_vars . push_back ( exec - > var ( ) ) ; <nl> + } <nl> + } <nl> + <nl> + / / dedup vars <nl> + Engine : : Get ( ) - > DeduplicateVarHandle ( & use_vars , & mutate_vars ) ; <nl> + bool is_gpu = default_ctx . dev_mask ( ) = = gpu : : kDevMask ; <nl> + bool is_async = execs . size ( ) > 1 ? false : execs [ 0 ] - > exec_type ( ) = = ExecType : : kAsync ; <nl> + <nl> + auto exec_fun = [ execs , is_async , is_gpu ] ( <nl> + RunContext ctx , Engine : : CallbackOnComplete on_complete ) { <nl> + if ( is_async ) { <nl> + execs [ 0 ] - > op_ctx . async_on_complete = on_complete ; <nl> + } <nl> + for ( const auto & exec : execs ) exec - > Run ( ctx , is_gpu ) ; <nl> + / / call on complete only if it is async op <nl> + if ( ! is_async ) { <nl> + if ( is_gpu ) { <nl> + # if MXNET_USE_CUDA <nl> + / / Wait GPU kernel to finish . <nl> + ctx . get_stream < gpu > ( ) - > Wait ( ) ; <nl> + # else <nl> + LOG ( FATAL ) < < MXNET_GPU_NOT_ENABLED_ERROR ; <nl> + # endif <nl> + } <nl> + on_complete ( ) ; <nl> + } <nl> + } ; <nl> + <nl> + return Engine : : Get ( ) - > NewOperator ( <nl> + exec_fun , use_vars , mutate_vars , FnProperty : : kNormal ) ; <nl> + } <nl> + <nl> + inline void CreateEngineOpSeg ( <nl> + const nnvm : : IndexedGraph & idx , <nl> + const Context default_ctx , <nl> + const size_t start_nid , <nl> + const size_t end_nid , <nl> + const size_t bulk_size , <nl> + const std : : unordered_set < uint32_t > & excludes , <nl> + const std : : vector < std : : shared_ptr < exec : : OpExecutor > > & execs , <nl> + const std : : vector < int > skip_plus_node , <nl> + std : : vector < EngineOprSeg > * opr_segs ) { <nl> + size_t seg_start = start_nid ; <nl> + std : : vector < std : : shared_ptr < exec : : OpExecutor > > seg_execs ; <nl> + for ( size_t nid = start_nid ; nid < end_nid ; + + nid ) { <nl> + const auto & node = idx [ nid ] ; <nl> + if ( node . source - > is_variable ( ) ) continue ; <nl> + if ( skip_plus_node . size ( ) & & skip_plus_node [ nid ] ) continue ; <nl> + auto & exec = execs [ nid ] ; <nl> + bool is_async = exec - > exec_type ( ) ! = ExecType : : kSync ; <nl> + bool valid = exec - > out_array . size ( ) > 0 ; <nl> + <nl> + / / Stop at async nodes and invalid node ( due to input / output is not allocated ) <nl> + bool stop = is_async | | ! valid | | seg_execs . size ( ) > = bulk_size ; <nl> + for ( size_t i = 0 ; i < node . inputs . size ( ) & & ! stop ; + + i ) { <nl> + if ( excludes . count ( idx . entry_id ( node . inputs [ i ] ) ) ) stop = true ; <nl> + } <nl> + auto num_outputs = node . source - > num_outputs ( ) ; <nl> + for ( size_t i = 0 ; i < num_outputs & & ! stop ; + + i ) { <nl> + if ( excludes . count ( idx . entry_id ( nid , i ) ) ) stop = true ; <nl> + } <nl> + <nl> + / / Create opr segment for previous nodes . <nl> + if ( stop & & nid > seg_start ) { <nl> + auto & seg = ( * opr_segs ) [ seg_start ] ; <nl> + if ( seg_execs . size ( ) ) { <nl> + seg = EngineOprSeg { false , nid } ; <nl> + seg . opr . reset ( CreateEngineOp ( default_ctx , seg_execs ) ) ; <nl> } else { <nl> - * arrays [ i ] = arrays [ mem_plan [ i ] . sid ] - > AsArray ( shapes [ i ] , dtypes [ i ] ) ; <nl> - if ( mem_plan [ i ] . inplace & & array_reqs - > at ( i ) = = kWriteTo ) { <nl> - array_reqs - > at ( i ) = kWriteInplace ; <nl> - } <nl> + seg = EngineOprSeg { true , nid , nullptr } ; <nl> } <nl> + seg_start = nid ; <nl> + seg_execs . clear ( ) ; <nl> + } <nl> + <nl> + seg_execs . push_back ( exec ) ; <nl> + <nl> + auto & seg = ( * opr_segs ) [ nid ] ; <nl> + if ( is_async ) { <nl> + seg = EngineOprSeg { false , nid + 1 } ; <nl> + seg . opr . reset ( CreateEngineOp ( default_ctx , seg_execs ) ) ; <nl> + seg_execs . clear ( ) ; <nl> + seg_start = nid + 1 ; <nl> + } else if ( ! valid ) { <nl> + seg = EngineOprSeg { false , nid + 1 , nullptr } ; <nl> + seg_execs . clear ( ) ; <nl> + seg_start = nid + 1 ; <nl> + } <nl> + } <nl> + / / The last segment <nl> + if ( end_nid > seg_start ) { <nl> + auto & seg = ( * opr_segs ) [ seg_start ] ; <nl> + if ( seg_execs . size ( ) ) { <nl> + seg = EngineOprSeg { false , end_nid } ; <nl> + seg . opr . reset ( CreateEngineOp ( default_ctx , seg_execs ) ) ; <nl> } else { <nl> - * arrays [ i ] = NDArray ( static_cast < NDArrayStorageType > ( stypes [ i ] ) , <nl> - shapes [ i ] , default_ctx , true , dtypes [ i ] ) ; <nl> + seg = EngineOprSeg { true , end_nid , nullptr } ; <nl> } <nl> } <nl> } <nl> <nl> + <nl> + void RunGraph ( const bool retain_graph , <nl> + const nnvm : : IndexedGraph & idx , <nl> + const std : : vector < NDArray * > arrays , <nl> + size_t node_start , size_t node_end , <nl> + std : : vector < OpReqType > & & array_reqs , <nl> + std : : vector < uint32_t > & & ref_count , <nl> + std : : vector < OpStatePtr > * p_states , <nl> + const DispatchModeVector & dispatch_modes ) ; <nl> + <nl> } / / namespace imperative <nl> } / / namespace mxnet <nl> <nl> mmm a / tests / python / unittest / test_gluon . py <nl> ppp b / tests / python / unittest / test_gluon . py <nl> <nl> from mxnet . ndarray . ndarray import _STORAGE_TYPE_STR_TO_ID <nl> from common import setup_module , with_seed , assertRaises <nl> import numpy as np <nl> + from numpy . testing import assert_array_equal <nl> from nose . tools import raises , assert_raises <nl> from copy import deepcopy <nl> import warnings <nl> def test_hybrid_multi_context ( ) : <nl> net . hybridize ( ) <nl> net ( mx . nd . zeros ( ( 1 , 3 , 32 , 32 ) , ctx = mx . cpu ( 0 ) ) ) . asnumpy ( ) <nl> <nl> - <nl> @ with_seed ( ) <nl> def test_zero_grad ( ) : <nl> data = mx . nd . random . uniform ( shape = ( 3 , 3 ) ) <nl> def test_zero_grad ( ) : <nl> grad = net . collect_params ( ) [ ' test_zero_grad_weight ' ] . grad ( ) <nl> assert_almost_equal ( grad . asnumpy ( ) , grad . asnumpy ( ) * 0 ) <nl> <nl> + def check_hybrid_static_memory ( * * kwargs ) : <nl> + x = mx . nd . random . uniform ( shape = ( 2 , 3 , 32 , 32 ) ) <nl> + x . attach_grad ( ) <nl> + <nl> + net1 = gluon . model_zoo . vision . get_resnet ( <nl> + 1 , 18 , pretrained = True , prefix = ' net_ ' , ctx = mx . context . current_context ( ) ) <nl> + net2 = gluon . model_zoo . vision . get_resnet ( <nl> + 1 , 18 , pretrained = True , prefix = ' net_ ' , ctx = mx . context . current_context ( ) ) <nl> + net2 . hybridize ( * * kwargs ) <nl> + net1 ( x ) <nl> + net2 ( x ) <nl> + <nl> + def test ( net , x ) : <nl> + with mx . autograd . record ( ) : <nl> + y = net ( x ) + net ( x ) <nl> + y . backward ( ) <nl> + <nl> + grads = { k : v . grad ( ) for k , v in net . collect_params ( ) . items ( ) if v . grad_req ! = ' null ' } <nl> + <nl> + return y , grads <nl> + <nl> + y1 , grads1 = test ( net1 , x ) <nl> + y2 , grads2 = test ( net2 , x ) <nl> + <nl> + assert_almost_equal ( y1 . asnumpy ( ) , y2 . asnumpy ( ) , rtol = 1e - 3 , atol = 1e - 5 ) <nl> + for key in grads1 : <nl> + assert_almost_equal ( grads1 [ key ] . asnumpy ( ) , grads2 [ key ] . asnumpy ( ) , rtol = 1e - 3 , atol = 1e - 5 ) <nl> + <nl> + def test_hybrid_static_memory ( ) : <nl> + check_hybrid_static_memory ( ) <nl> + check_hybrid_static_memory ( static_alloc = True ) <nl> + check_hybrid_static_memory ( static_alloc = True , static_shape = True ) <nl> + <nl> + def check_hybrid_static_memory_switching ( * * kwargs ) : <nl> + net = gluon . model_zoo . vision . get_resnet ( <nl> + 1 , 18 , pretrained = True , ctx = mx . context . current_context ( ) ) <nl> + net . hybridize ( * * kwargs ) <nl> + <nl> + x = mx . nd . random . uniform ( shape = ( 4 , 3 , 32 , 32 ) ) <nl> + net ( x ) <nl> + with mx . autograd . record ( ) : <nl> + y = net ( x ) <nl> + y . backward ( ) <nl> + x = mx . nd . random . uniform ( shape = ( 2 , 3 , 32 , 32 ) ) <nl> + net ( x ) <nl> + with mx . autograd . record ( ) : <nl> + y = net ( x ) <nl> + y . backward ( ) <nl> + mx . nd . waitall ( ) <nl> + <nl> + def test_hybrid_static_memory_switching ( ) : <nl> + check_hybrid_static_memory_switching ( ) <nl> + check_hybrid_static_memory_switching ( static_alloc = True ) <nl> + check_hybrid_static_memory_switching ( static_alloc = True , static_shape = True ) <nl> <nl> @ with_seed ( ) <nl> def test_hook ( ) : <nl> | [ WIP ] Do Not Merge . Static memory allocation for cached_op ( ) | apache/incubator-mxnet | 2dbd143e4892bb9ad4aa1835c79f0046603e3531 | 2018-05-31T01:30:49Z |
mmm a / php7_wrapper . h <nl> ppp b / php7_wrapper . h <nl> static inline int sw_zend_hash_find ( HashTable * ht , char * k , int len , void * * v ) <nl> # define sw_zend_hash_exists zend_hash_exists <nl> # define sw_php_format_date php_format_date <nl> # define sw_php_url_encode php_url_encode <nl> + # define sw_php_array_merge php_array_merge <nl> # define SW_RETURN_STRINGL RETURN_STRINGL <nl> # define sw_zend_register_internal_class_ex zend_register_internal_class_ex <nl> # define sw_zend_call_method_with_1_params zend_call_method_with_1_params <nl> static sw_inline int sw_call_user_function_ex ( HashTable * function_table , zval * * <nl> # define SW_RETURN_STRING ( val , duplicate ) RETURN_STRING ( val ) <nl> # define sw_add_assoc_string ( array , key , value , duplicate ) add_assoc_string ( array , key , value ) <nl> # define sw_zend_hash_copy ( target , source , pCopyConstructor , tmp , size ) zend_hash_copy ( target , source , pCopyConstructor ) <nl> + # ifdef ZTS <nl> + # define sw_php_array_merge ( dest , src , recursive , tsrm ) php_array_merge ( dest , src ) <nl> + # else <nl> + # define sw_php_array_merge ( dest , src , recursive ) php_array_merge ( dest , src ) <nl> + # endif <nl> # define sw_zend_register_internal_class_ex ( entry , parent_ptr , str ) zend_register_internal_class_ex ( entry , parent_ptr ) <nl> # define sw_zend_call_method_with_1_params ( obj , ptr , what , method , retval , v1 ) zend_call_method_with_1_params ( * obj , ptr , what , method , * retval , v1 ) <nl> # define sw_zend_call_method_with_2_params ( obj , ptr , what , method , retval , name , cb ) zend_call_method_with_2_params ( * obj , ptr , what , method , * retval , name , cb ) <nl> mmm a / src / network / ReactorThread . c <nl> ppp b / src / network / ReactorThread . c <nl> int swReactorThread_start ( swServer * serv , swReactor * main_reactor_ptr ) <nl> <nl> int i ; <nl> <nl> + swServer_store_listen_socket ( serv ) ; <nl> + <nl> / / listen UDP <nl> if ( serv - > have_udp_sock = = 1 ) <nl> { <nl> int swReactorThread_start ( swServer * serv , swReactor * main_reactor_ptr ) <nl> main_reactor_ptr - > add ( main_reactor_ptr , ls - > sock , SW_FD_LISTEN ) ; <nl> } <nl> <nl> - swServer_store_listen_socket ( serv ) ; <nl> - <nl> # ifdef HAVE_PTHREAD_BARRIER <nl> / / init thread barrier <nl> pthread_barrier_init ( & serv - > barrier , NULL , serv - > reactor_num + 1 ) ; <nl> mmm a / swoole_http_server . c <nl> ppp b / swoole_http_server . c <nl> <nl> # include < ext / standard / php_var . h > <nl> # include < ext / standard / php_string . h > <nl> # include < ext / standard / php_math . h > <nl> + # include < ext / standard / php_array . h > <nl> # include < ext / date / php_date . h > <nl> # include < ext / standard / md5 . h > <nl> <nl> static int multipart_body_on_header_complete ( multipart_parser * p ) ; <nl> static int multipart_body_on_data_end ( multipart_parser * p ) ; <nl> static int multipart_body_end ( multipart_parser * p ) ; <nl> <nl> - static void http_global_merge ( zval * val , zval * zrequest , int type ) ; <nl> + static void http_global_merge ( zval * val , zval * zrequest_object , int type ) ; <nl> static void http_global_clear ( TSRMLS_D ) ; <nl> static void http_global_init ( TSRMLS_D ) ; <nl> static http_context * http_get_context ( zval * object , int check_end TSRMLS_DC ) ; <nl> static void http_global_init ( TSRMLS_D ) <nl> } <nl> } <nl> <nl> - static void http_global_merge ( zval * val , zval * zrequest , int type ) <nl> + static void http_global_merge ( zval * val , zval * zrequest_object , int type ) <nl> { <nl> - zval * _request ; <nl> + zval * zrequest ; <nl> <nl> # if PHP_MAJOR_VERSION < 7 <nl> TSRMLS_FETCH_FROM_CTX ( sw_thread_ctx ? sw_thread_ctx : NULL ) ; <nl> static void http_global_merge ( zval * val , zval * zrequest , int type ) <nl> sw_add_assoc_stringl_ex ( php_global_server , _php_key , keylen + 1 , Z_STRVAL_P ( value ) , Z_STRLEN_P ( value ) , 1 ) ; <nl> SW_HASHTABLE_FOREACH_END ( ) ; <nl> <nl> - zval * header = sw_zend_read_property ( swoole_http_request_class_entry_ptr , zrequest , ZEND_STRL ( " header " ) , 1 TSRMLS_CC ) ; <nl> + zval * header = sw_zend_read_property ( swoole_http_request_class_entry_ptr , zrequest_object , ZEND_STRL ( " header " ) , 1 TSRMLS_CC ) ; <nl> if ( header | | ! ZVAL_IS_NULL ( header ) ) <nl> { <nl> SW_HASHTABLE_FOREACH_START2 ( Z_ARRVAL_P ( header ) , key , keylen , keytype , value ) <nl> static void http_global_merge ( zval * val , zval * zrequest , int type ) <nl> { <nl> return ; <nl> } <nl> - _request = sw_zend_read_property ( swoole_http_request_class_entry_ptr , zrequest , ZEND_STRL ( " request " ) , 1 TSRMLS_CC ) ; <nl> - if ( _request & & ! ( ZVAL_IS_NULL ( _request ) ) ) <nl> + zrequest = sw_zend_read_property ( swoole_http_request_class_entry_ptr , zrequest_object , ZEND_STRL ( " request " ) , 1 TSRMLS_CC ) ; <nl> + if ( zrequest & & ! ( ZVAL_IS_NULL ( zrequest ) ) ) <nl> { <nl> - ZEND_SET_SYMBOL ( & EG ( symbol_table ) , " _REQUEST " , _request ) ; <nl> + ZEND_SET_SYMBOL ( & EG ( symbol_table ) , " _REQUEST " , zrequest ) ; <nl> } <nl> return ; <nl> <nl> static void http_global_merge ( zval * val , zval * zrequest , int type ) <nl> <nl> if ( http_merge_request_flag & type ) <nl> { <nl> - _request = sw_zend_read_property ( swoole_http_request_class_entry_ptr , zrequest , ZEND_STRL ( " request " ) , 1 TSRMLS_CC ) ; <nl> - if ( ! _request | | ZVAL_IS_NULL ( _request ) ) <nl> + zrequest = sw_zend_read_property ( swoole_http_request_class_entry_ptr , zrequest_object , ZEND_STRL ( " request " ) , 1 TSRMLS_CC ) ; <nl> + if ( ! zrequest | | ZVAL_IS_NULL ( zrequest ) ) <nl> { <nl> - _request = val ; <nl> - } <nl> - else <nl> - { <nl> - sw_zend_hash_copy ( Z_ARRVAL_P ( _request ) , Z_ARRVAL_P ( val ) , NULL , NULL , sizeof ( zval ) ) ; <nl> + http_context * ctx = http_get_context ( zrequest_object , 0 TSRMLS_CC ) ; <nl> + if ( ! ctx ) <nl> + { <nl> + return ; <nl> + } <nl> + http_alloc_zval ( ctx , request , zrequest ) ; <nl> + array_init ( zrequest ) ; <nl> + zend_update_property ( swoole_http_request_class_entry_ptr , ctx - > request . zrequest_object , ZEND_STRL ( " request " ) , zrequest TSRMLS_CC ) ; <nl> } <nl> - zend_update_property ( swoole_http_request_class_entry_ptr , zrequest , ZEND_STRL ( " request " ) , _request TSRMLS_CC ) ; <nl> + php_array_merge ( Z_ARRVAL_P ( zrequest ) , Z_ARRVAL_P ( val ) , 1 TSRMLS_CC ) ; <nl> } <nl> } <nl> <nl> static PHP_METHOD ( swoole_http_server , setglobal ) <nl> <nl> static PHP_METHOD ( swoole_http_server , start ) <nl> { <nl> - swServer * serv ; <nl> int ret ; <nl> <nl> if ( SwooleGS - > start > 0 ) <nl> static PHP_METHOD ( swoole_http_server , start ) <nl> RETURN_FALSE ; <nl> } <nl> <nl> - serv = swoole_get_object ( getThis ( ) ) ; <nl> + swServer * serv = swoole_get_object ( getThis ( ) ) ; <nl> php_swoole_register_callback ( serv ) ; <nl> <nl> if ( serv - > listen_list - > open_websocket_protocol ) <nl> | fixed | swoole/swoole-src | 4e759e924883113a577d56a0489ce0a6e8feb710 | 2016-03-15T11:04:59Z |
mmm a / src / qt / forms / coincontroldialog . ui <nl> ppp b / src / qt / forms / coincontroldialog . ui <nl> <nl> < / item > <nl> < item > <nl> < widget class = " QDialogButtonBox " name = " buttonBox " > <nl> - < property name = " sizePolicy " > <nl> - < sizepolicy hsizetype = " Maximum " vsizetype = " Fixed " > <nl> - < horstretch > 0 < / horstretch > <nl> - < verstretch > 0 < / verstretch > <nl> - < / sizepolicy > <nl> - < / property > <nl> < property name = " orientation " > <nl> < enum > Qt : : Horizontal < / enum > <nl> < / property > <nl> | gui : move coin control OK to the right | bitcoin/bitcoin | d595b4aae9d6eca7094ed5612f4773d98e422057 | 2019-05-28T15:16:39Z |
mmm a / x64_dbg_gui / Project / Src / Bridge / Bridge . cpp <nl> ppp b / x64_dbg_gui / Project / Src / Bridge / Bridge . cpp <nl> __declspec ( dllexport ) void * _gui_sendmessage ( GUIMSG type , void * param1 , void * pa <nl> <nl> case GUI_SELECTION_GET : <nl> { <nl> - Bridge : : getBridge ( ) - > emitSelectionGet ( ( int ) ( uint_t ) param1 , ( SELECTIONDATA * ) param2 ) ; <nl> + return ( void * ) ( int_t ) Bridge : : getBridge ( ) - > emitSelectionGet ( ( int ) ( uint_t ) param1 , ( SELECTIONDATA * ) param2 ) ; <nl> } <nl> break ; <nl> <nl> case GUI_SELECTION_SET : <nl> { <nl> - Bridge : : getBridge ( ) - > emitSelectionSet ( ( int ) ( uint_t ) param1 , ( const SELECTIONDATA * ) param2 ) ; <nl> + return ( void * ) ( int_t ) Bridge : : getBridge ( ) - > emitSelectionSet ( ( int ) ( uint_t ) param1 , ( const SELECTIONDATA * ) param2 ) ; <nl> } <nl> break ; <nl> <nl> | GUI : fixed bugs in GuiSelectionGet & GuiSelectionSet ( thanks to ahmadmansoor for finding ) | x64dbg/x64dbg | eabf2e293e36c969fc5aa8f14c37e02baff176d9 | 2014-05-21T00:22:14Z |
mmm a / Marlin / language_de . h <nl> ppp b / Marlin / language_de . h <nl> <nl> # define MSG_LEVEL_BED_WAITING _UxGT ( " Klick für Start " ) <nl> # define MSG_LEVEL_BED_NEXT_POINT _UxGT ( " Nächste Koordinate " ) <nl> # define MSG_LEVEL_BED_DONE _UxGT ( " Fertig " ) <nl> + # define MSG_Z_FADE_HEIGHT _UxGT ( " Niv . Ausblendhöhe " ) <nl> # define MSG_SET_HOME_OFFSETS _UxGT ( " Setze Homeversatz " ) <nl> # define MSG_HOME_OFFSETS_APPLIED _UxGT ( " Homeversatz aktiv " ) <nl> # define MSG_SET_ORIGIN _UxGT ( " Setze Nullpunkt " ) / / " G92 X0 Y0 Z0 " commented out in ultralcd . cpp <nl> <nl> # define MSG_INIT_SDCARD _UxGT ( " SD - Karte erkennen " ) / / Manually initialize the SD - card via user interface <nl> # define MSG_CNG_SDCARD _UxGT ( " SD - Karte getauscht " ) / / SD - card changed by user . For machines with no autocarddetect . Both send " M21 " <nl> # define MSG_ZPROBE_OUT _UxGT ( " Sensor ausserhalb " ) <nl> + # define MSG_BLTOUCH _UxGT ( " BLTouch " ) <nl> # define MSG_BLTOUCH_SELFTEST _UxGT ( " BLTouch Test " ) <nl> # define MSG_BLTOUCH_RESET _UxGT ( " BLTouch Reset " ) <nl> # define MSG_BLTOUCH_DEPLOY _UxGT ( " BLTouch ausfahren " ) <nl> <nl> # define MSG_DELTA_CALIBRATE_Y _UxGT ( " Kalibriere Y " ) <nl> # define MSG_DELTA_CALIBRATE_Z _UxGT ( " Kalibriere Z " ) <nl> # define MSG_DELTA_CALIBRATE_CENTER _UxGT ( " Kalibriere Mitte " ) <nl> + # define MSG_DELTA_SETTINGS _UxGT ( " Delta Einst . anzeig . " ) <nl> # define MSG_DELTA_AUTO_CALIBRATE _UxGT ( " Autom . Kalibrierung " ) <nl> # define MSG_DELTA_HEIGHT_CALIBRATE _UxGT ( " Delta Höhe setzen " ) <nl> <nl> <nl> # define MSG_UBL_CUSTOM_BED_TEMP MSG_UBL_SET_BED_TEMP <nl> # define MSG_UBL_SET_HOTEND_TEMP _UxGT ( " Hotend Temp . " ) <nl> # define MSG_UBL_CUSTOM_HOTEND_TEMP MSG_UBL_SET_HOTEND_TEMP <nl> + # define MSG_UBL_MESH_EDIT _UxGT ( " Netz bearbeiten " ) <nl> # define MSG_UBL_EDIT_CUSTOM_MESH _UxGT ( " Eigenes Netz bearb . " ) <nl> # define MSG_UBL_FINE_TUNE_MESH _UxGT ( " Feineinstellung . . . " ) <nl> # define MSG_UBL_DONE_EDITING_MESH _UxGT ( " Bearbeitung beendet " ) <nl> <nl> # define MSG_UBL_OUTPUT_MAP _UxGT ( " Karte ausgeben " ) <nl> # define MSG_UBL_OUTPUT_MAP_HOST _UxGT ( " Ausgabe für Host " ) <nl> # define MSG_UBL_OUTPUT_MAP_CSV _UxGT ( " Ausgabe für CSV " ) <nl> + # define MSG_UBL_OUTPUT_MAP_BACKUP _UxGT ( " Externe Sicherung " ) <nl> # define MSG_UBL_INFO_UBL _UxGT ( " UBL Info ausgeben " ) <nl> # define MSG_UBL_EDIT_MESH_MENU _UxGT ( " Netz bearbeiten " ) <nl> # define MSG_UBL_FILLIN_AMOUNT _UxGT ( " Menge an Fill - in " ) <nl> <nl> # define MSG_UBL_SAVE_ERROR _UxGT ( " ERR : UBL speichern " ) <nl> # define MSG_UBL_RESTORE_ERROR _UxGT ( " ERR : UBL wiederherst . " ) <nl> # define MSG_UBL_Z_OFFSET_STOPPED _UxGT ( " Z - Versatz angehalten " ) <nl> + # define MSG_UBL_STEP_BY_STEP_MENU _UxGT ( " Schrittweises UBL " ) <nl> <nl> # if LCD_WIDTH > = 20 <nl> # define MSG_INFO_PRINT_COUNT _UxGT ( " Gesamte Drucke " ) <nl> | Merge pull request from FHeilmann / bf_update_de_translation | MarlinFirmware/Marlin | db188934d18dee0bd8f326afa9a0c17af14c2293 | 2017-08-05T07:53:32Z |
mmm a / doc / examples / meta . output <nl> ppp b / doc / examples / meta . output <nl> <nl> " compiler " : { <nl> " c + + " : " 201103 " , <nl> " family " : " clang " , <nl> - " version " : " 10 . 0 . 0 ( clang - 1000 . 11 . 45 . 5 ) " <nl> + " version " : " 10 . 0 . 1 ( clang - 1001 . 0 . 46 . 4 ) " <nl> } , <nl> " copyright " : " ( C ) 2013 - 2017 Niels Lohmann " , <nl> " name " : " JSON for Modern C + + " , <nl> | : hammer : adjust version | nlohmann/json | d80f8b09f5aeebe223a47870e4fa5ebbe8aa5276 | 2019-07-28T13:20:07Z |
mmm a / scripts / generate_join_macros . py <nl> ppp b / scripts / generate_join_macros . py <nl> def generate_make_equality_comparable_macro ( nfields ) : <nl> <nl> if __name__ = = " __main__ " : <nl> <nl> - print " / / Copyright 2010 - 2012 RethinkDB , all rights reserved . " <nl> print " # ifndef RPC_SEMILATTICE_JOINS_MACROS_HPP_ " <nl> print " # define RPC_SEMILATTICE_JOINS_MACROS_HPP_ " <nl> print <nl> mmm a / scripts / generate_rpc_templates . py <nl> ppp b / scripts / generate_rpc_templates . py <nl> def cpre ( template ) : <nl> print <nl> <nl> if __name__ = = " __main__ " : <nl> - print " / / Copyright 2010 - 2012 RethinkDB , all rights reserved . " <nl> + <nl> print " # ifndef RPC_MAILBOX_TYPED_HPP_ " <nl> print " # define RPC_MAILBOX_TYPED_HPP_ " <nl> print <nl> mmm a / scripts / generate_serialize_macros . py <nl> ppp b / scripts / generate_serialize_macros . py <nl> def generate_impl_me_serializable_macro ( nfields ) : <nl> <nl> if __name__ = = " __main__ " : <nl> <nl> - print " / / Copyright 2010 - 2012 RethinkDB , all rights reserved . " <nl> print " # ifndef RPC_SERIALIZE_MACROS_HPP_ " <nl> print " # define RPC_SERIALIZE_MACROS_HPP_ " <nl> print <nl> mmm a / src / rpc / mailbox / typed . hpp <nl> ppp b / src / rpc / mailbox / typed . hpp <nl> <nl> - / / Copyright 2010 - 2012 RethinkDB , all rights reserved . <nl> # ifndef RPC_MAILBOX_TYPED_HPP_ <nl> # define RPC_MAILBOX_TYPED_HPP_ <nl> <nl> mmm a / src / rpc / semilattice / joins / macros . hpp <nl> ppp b / src / rpc / semilattice / joins / macros . hpp <nl> <nl> - / / Copyright 2010 - 2012 RethinkDB , all rights reserved . <nl> # ifndef RPC_SEMILATTICE_JOINS_MACROS_HPP_ <nl> # define RPC_SEMILATTICE_JOINS_MACROS_HPP_ <nl> <nl> mmm a / src / rpc / serialize_macros . hpp <nl> ppp b / src / rpc / serialize_macros . hpp <nl> <nl> - / / Copyright 2010 - 2012 RethinkDB , all rights reserved . <nl> # ifndef RPC_SERIALIZE_MACROS_HPP_ <nl> # define RPC_SERIALIZE_MACROS_HPP_ <nl> <nl> | Merge commit ' 44563e5 ' into jd_secondary_indexes | rethinkdb/rethinkdb | f0d3a592838b033bf9836a81a54add061440b4d6 | 2013-01-30T21:12:33Z |
mmm a / folly / Checksum . cpp <nl> ppp b / folly / Checksum . cpp <nl> <nl> * / <nl> <nl> # include < folly / Checksum . h > <nl> - # include < algorithm > <nl> - # include < stdexcept > <nl> # include < boost / crc . hpp > <nl> # include < folly / CpuId . h > <nl> + # include < folly / detail / ChecksumDetail . h > <nl> + # include < algorithm > <nl> + # include < stdexcept > <nl> <nl> # if FOLLY_X64 & & ( __SSE4_2__ | | defined ( __clang__ ) | | __GNUC_PREREQ ( 4 , 9 ) ) <nl> # include < nmmintrin . h > <nl> namespace folly { <nl> <nl> namespace detail { <nl> <nl> + uint32_t <nl> + crc32c_sw ( const uint8_t * data , size_t nbytes , uint32_t startingChecksum ) ; <nl> # if FOLLY_X64 & & ( __SSE4_2__ | | defined ( __clang__ ) | | __GNUC_PREREQ ( 4 , 9 ) ) <nl> <nl> / / Fast SIMD implementation of CRC - 32C for x86 with SSE 4 . 2 <nl> uint32_t crc32c_hw ( const uint8_t * data , size_t nbytes , <nl> return sum ; <nl> } <nl> <nl> + uint32_t <nl> + crc32_sw ( const uint8_t * data , size_t nbytes , uint32_t startingChecksum ) ; <nl> + <nl> + / / Fast SIMD implementation of CRC - 32 for x86 with pclmul <nl> + uint32_t <nl> + crc32_hw ( const uint8_t * data , size_t nbytes , uint32_t startingChecksum ) { <nl> + uint32_t sum = startingChecksum ; <nl> + size_t offset = 0 ; <nl> + <nl> + / / Process unaligned bytes <nl> + if ( ( uintptr_t ) data & 15 ) { <nl> + size_t limit = std : : min ( nbytes , - ( uintptr_t ) data & 15 ) ; <nl> + sum = crc32_sw ( data , limit , sum ) ; <nl> + offset + = limit ; <nl> + nbytes - = limit ; <nl> + } <nl> + <nl> + if ( nbytes > = 16 ) { <nl> + sum = crc32_hw_aligned ( sum , ( const __m128i * ) ( data + offset ) , nbytes / 16 ) ; <nl> + offset + = nbytes & ~ 15 ; <nl> + nbytes & = 15 ; <nl> + } <nl> + <nl> + / / Remaining unaligned bytes <nl> + return crc32_sw ( data + offset , nbytes , sum ) ; <nl> + } <nl> + <nl> bool crc32c_hw_supported ( ) { <nl> static folly : : CpuId id ; <nl> return id . sse42 ( ) ; <nl> } <nl> <nl> + bool crc32_hw_supported ( ) { <nl> + static folly : : CpuId id ; <nl> + return id . sse42 ( ) ; <nl> + } <nl> + <nl> # else <nl> <nl> uint32_t crc32c_hw ( const uint8_t * data , size_t nbytes , <nl> bool crc32c_hw_supported ( ) { <nl> return false ; <nl> } <nl> <nl> + bool crc32_hw_supported ( ) { <nl> + return false ; <nl> + } <nl> # endif <nl> <nl> - uint32_t crc32c_sw ( const uint8_t * data , size_t nbytes , <nl> - uint32_t startingChecksum ) { <nl> - <nl> + template < uint32_t CRC_POLYNOMIAL > <nl> + uint32_t crc_sw ( const uint8_t * data , size_t nbytes , uint32_t startingChecksum ) { <nl> / / Reverse the bits in the starting checksum so they ' ll be in the <nl> / / right internal format for Boost ' s CRC engine . <nl> / / O ( 1 ) - time , branchless bit reversal algorithm from <nl> uint32_t crc32c_sw ( const uint8_t * data , size_t nbytes , <nl> startingChecksum = ( startingChecksum > > 16 ) | <nl> ( startingChecksum < < 16 ) ; <nl> <nl> - static const uint32_t CRC32C_POLYNOMIAL = 0x1EDC6F41 ; <nl> - boost : : crc_optimal < 32 , CRC32C_POLYNOMIAL , ~ 0U , 0 , true , true > sum ( <nl> + boost : : crc_optimal < 32 , CRC_POLYNOMIAL , ~ 0U , 0 , true , true > sum ( <nl> startingChecksum ) ; <nl> sum . process_bytes ( data , nbytes ) ; <nl> return sum . checksum ( ) ; <nl> } <nl> <nl> + uint32_t <nl> + crc32c_sw ( const uint8_t * data , size_t nbytes , uint32_t startingChecksum ) { <nl> + constexpr uint32_t CRC32C_POLYNOMIAL = 0x1EDC6F41 ; <nl> + return crc_sw < CRC32C_POLYNOMIAL > ( data , nbytes , startingChecksum ) ; <nl> + } <nl> + <nl> + uint32_t <nl> + crc32_sw ( const uint8_t * data , size_t nbytes , uint32_t startingChecksum ) { <nl> + constexpr uint32_t CRC32_POLYNOMIAL = 0x04C11DB7 ; <nl> + return crc_sw < CRC32_POLYNOMIAL > ( data , nbytes , startingChecksum ) ; <nl> + } <nl> + <nl> } / / folly : : detail <nl> <nl> uint32_t crc32c ( const uint8_t * data , size_t nbytes , <nl> uint32_t crc32c ( const uint8_t * data , size_t nbytes , <nl> } <nl> } <nl> <nl> + uint32_t crc32 ( const uint8_t * data , size_t nbytes , uint32_t startingChecksum ) { <nl> + if ( detail : : crc32_hw_supported ( ) ) { <nl> + return detail : : crc32_hw ( data , nbytes , startingChecksum ) ; <nl> + } else { <nl> + return detail : : crc32_sw ( data , nbytes , startingChecksum ) ; <nl> + } <nl> + } <nl> + <nl> } / / folly <nl> mmm a / folly / Checksum . h <nl> ppp b / folly / Checksum . h <nl> namespace folly { <nl> uint32_t crc32c ( const uint8_t * data , size_t nbytes , <nl> uint32_t startingChecksum = ~ 0U ) ; <nl> <nl> + / * * <nl> + * Compute the CRC - 32 checksum of a buffer , using a hardware - accelerated <nl> + * implementation if available or a portable software implementation as <nl> + * a default . <nl> + * / <nl> + uint32_t <nl> + crc32 ( const uint8_t * data , size_t nbytes , uint32_t startingChecksum = ~ 0U ) ; <nl> + <nl> } / / folly <nl> mmm a / folly / Makefile . am <nl> ppp b / folly / Makefile . am <nl> GroupVarintTables . cpp : build / generate_varint_tables . py <nl> CLEANFILES + = GroupVarintTables . cpp <nl> <nl> libfollybasesse42_la_SOURCES = \ <nl> + detail / ChecksumDetail . cpp \ <nl> detail / RangeSse42 . cpp <nl> <nl> libfollybase_la_SOURCES = \ <nl> libfolly_la_SOURCES + = \ <nl> endif <nl> <nl> libfollybasesse42_la_LDFLAGS = $ ( AM_LDFLAGS ) - version - info $ ( LT_VERSION ) <nl> - libfollybasesse42_la_CXXFLAGS = - msse4 . 2 <nl> + libfollybasesse42_la_CXXFLAGS = - msse4 . 2 - mpclmul <nl> <nl> libfollybase_la_LIBADD = libfollybasesse42 . la <nl> libfollybase_la_LDFLAGS = $ ( AM_LDFLAGS ) - version - info $ ( LT_VERSION ) <nl> new file mode 100644 <nl> index 00000000000 . . 5128c1a4d19 <nl> mmm / dev / null <nl> ppp b / folly / detail / ChecksumDetail . cpp <nl> <nl> + / * <nl> + * crc32_impl . h <nl> + * <nl> + * Copyright 2016 Eric Biggers <nl> + * <nl> + * Permission is hereby granted , free of charge , to any person <nl> + * obtaining a copy of this software and associated documentation <nl> + * files ( the " Software " ) , to deal in the Software without <nl> + * restriction , including without limitation the rights to use , <nl> + * copy , modify , merge , publish , distribute , sublicense , and / or sell <nl> + * copies of the Software , and to permit persons to whom the <nl> + * Software is furnished to do so , subject to the following <nl> + * conditions : <nl> + * <nl> + * The above copyright notice and this permission notice shall be <nl> + * included in all copies or substantial portions of the Software . <nl> + * <nl> + * THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , <nl> + * EXPRESS OR IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES <nl> + * OF MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND <nl> + * NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT <nl> + * HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , <nl> + * WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING <nl> + * FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR <nl> + * OTHER DEALINGS IN THE SOFTWARE . <nl> + * / <nl> + <nl> + / * <nl> + * CRC - 32 folding with PCLMULQDQ . <nl> + * <nl> + * The basic idea is to repeatedly " fold " each 512 bits into the next <nl> + * 512 bits , producing an abbreviated message which is congruent the <nl> + * original message modulo the generator polynomial G ( x ) . <nl> + * <nl> + * Folding each 512 bits is implemented as eight 64 - bit folds , each of <nl> + * which uses one carryless multiplication instruction . It ' s expected <nl> + * that CPUs may be able to execute some of these multiplications in <nl> + * parallel . <nl> + * <nl> + * Explanation of " folding " : let A ( x ) be 64 bits from the message , and <nl> + * let B ( x ) be 95 bits from a constant distance D later in the <nl> + * message . The relevant portion of the message can be written as : <nl> + * <nl> + * M ( x ) = A ( x ) * x ^ D + B ( x ) <nl> + * <nl> + * . . . where + and * represent addition and multiplication , <nl> + * respectively , of polynomials over GF ( 2 ) . Note that when <nl> + * implemented on a computer , these operations are equivalent to XOR <nl> + * and carryless multiplication , respectively . <nl> + * <nl> + * For the purpose of CRC calculation , only the remainder modulo the <nl> + * generator polynomial G ( x ) matters : <nl> + * <nl> + * M ( x ) mod G ( x ) = ( A ( x ) * x ^ D + B ( x ) ) mod G ( x ) <nl> + * <nl> + * Since the modulo operation can be applied anywhere in a sequence of <nl> + * additions and multiplications without affecting the result , this is <nl> + * equivalent to : <nl> + * <nl> + * M ( x ) mod G ( x ) = ( A ( x ) * ( x ^ D mod G ( x ) ) + B ( x ) ) mod G ( x ) <nl> + * <nl> + * For any D , ' x ^ D mod G ( x ) ' will be a polynomial with maximum degree <nl> + * 31 , i . e . a 32 - bit quantity . So ' A ( x ) * ( x ^ D mod G ( x ) ) ' is <nl> + * equivalent to a carryless multiplication of a 64 - bit quantity by a <nl> + * 32 - bit quantity , producing a 95 - bit product . Then , adding <nl> + * ( XOR - ing ) the product to B ( x ) produces a polynomial with the same <nl> + * length as B ( x ) but with the same remainder as ' A ( x ) * x ^ D + B ( x ) ' . <nl> + * This is the basic fold operation with 64 bits . <nl> + * <nl> + * Note that the carryless multiplication instruction PCLMULQDQ <nl> + * actually takes two 64 - bit inputs and produces a 127 - bit product in <nl> + * the low - order bits of a 128 - bit XMM register . This works fine , but <nl> + * care must be taken to account for " bit endianness " . With the CRC <nl> + * version implemented here , bits are always ordered such that the <nl> + * lowest - order bit represents the coefficient of highest power of x <nl> + * and the highest - order bit represents the coefficient of the lowest <nl> + * power of x . This is backwards from the more intuitive order . <nl> + * Still , carryless multiplication works essentially the same either <nl> + * way . It just must be accounted for that when we XOR the 95 - bit <nl> + * product in the low - order 95 bits of a 128 - bit XMM register into <nl> + * 128 - bits of later data held in another XMM register , we ' ll really <nl> + * be XOR - ing the product into the mathematically higher degree end of <nl> + * those later bits , not the lower degree end as may be expected . <nl> + * <nl> + * So given that caveat and the fact that we process 512 bits per <nl> + * iteration , the ' D ' values we need for the two 64 - bit halves of each <nl> + * 128 bits of data are : <nl> + * <nl> + * D = ( 512 + 95 ) - 64 for the higher - degree half of each 128 <nl> + * bits , i . e . the lower order bits in <nl> + * the XMM register <nl> + * <nl> + * D = ( 512 + 95 ) - 128 for the lower - degree half of each 128 <nl> + * bits , i . e . the higher order bits in <nl> + * the XMM register <nl> + * <nl> + * The required ' x ^ D mod G ( x ) ' values were precomputed . <nl> + * <nl> + * When < = 512 bits remain in the message , we finish up by folding <nl> + * across smaller distances . This works similarly ; the distance D is <nl> + * just different , so different constant multipliers must be used . <nl> + * Finally , once the remaining message is just 64 bits , it is is <nl> + * reduced to the CRC - 32 using Barrett reduction ( explained later ) . <nl> + * <nl> + * For more information see the original paper from Intel : " Fast CRC <nl> + * Computation for Generic Polynomials Using PCLMULQDQ <nl> + * Instruction " December 2009 <nl> + * http : / / www . intel . com / content / dam / www / public / us / en / documents / <nl> + * white - papers / <nl> + * fast - crc - computation - generic - polynomials - pclmulqdq - paper . pdf <nl> + * / <nl> + <nl> + # include < folly / detail / ChecksumDetail . h > <nl> + <nl> + namespace folly { <nl> + namespace detail { <nl> + <nl> + uint32_t <nl> + crc32_hw_aligned ( uint32_t remainder , const __m128i * p , size_t vec_count ) { <nl> + / * Constants precomputed by gen_crc32_multipliers . c . Do not edit ! * / <nl> + const __m128i multipliers_4 = _mm_set_epi32 ( 0 , 0x1D9513D7 , 0 , 0x8F352D95 ) ; <nl> + const __m128i multipliers_2 = _mm_set_epi32 ( 0 , 0x81256527 , 0 , 0xF1DA05AA ) ; <nl> + const __m128i multipliers_1 = _mm_set_epi32 ( 0 , 0xCCAA009E , 0 , 0xAE689191 ) ; <nl> + const __m128i final_multiplier = _mm_set_epi32 ( 0 , 0 , 0 , 0xB8BC6765 ) ; <nl> + const __m128i mask32 = _mm_set_epi32 ( 0 , 0 , 0 , 0xFFFFFFFF ) ; <nl> + const __m128i barrett_reduction_constants = <nl> + _mm_set_epi32 ( 0x1 , 0xDB710641 , 0x1 , 0xF7011641 ) ; <nl> + <nl> + const __m128i * const end = p + vec_count ; <nl> + const __m128i * const end512 = p + ( vec_count & ~ 3 ) ; <nl> + __m128i x0 , x1 , x2 , x3 ; <nl> + <nl> + / * <nl> + * Account for the current ' remainder ' , i . e . the CRC of the part of <nl> + * the message already processed . Explanation : rewrite the message <nl> + * polynomial M ( x ) in terms of the first part A ( x ) , the second part <nl> + * B ( x ) , and the length of the second part in bits | B ( x ) | > = 32 : <nl> + * <nl> + * M ( x ) = A ( x ) * x ^ | B ( x ) | + B ( x ) <nl> + * <nl> + * Then the CRC of M ( x ) is : <nl> + * <nl> + * CRC ( M ( x ) ) = CRC ( A ( x ) * x ^ | B ( x ) | + B ( x ) ) <nl> + * = CRC ( A ( x ) * x ^ 32 * x ^ ( | B ( x ) | - 32 ) + B ( x ) ) <nl> + * = CRC ( CRC ( A ( x ) ) * x ^ ( | B ( x ) | - 32 ) + B ( x ) ) <nl> + * <nl> + * Note : all arithmetic is modulo G ( x ) , the generator polynomial ; that ' s <nl> + * why A ( x ) * x ^ 32 can be replaced with CRC ( A ( x ) ) = A ( x ) * x ^ 32 mod G ( x ) . <nl> + * <nl> + * So the CRC of the full message is the CRC of the second part of the <nl> + * message where the first 32 bits of the second part of the message <nl> + * have been XOR ' ed with the CRC of the first part of the message . <nl> + * / <nl> + x0 = * p + + ; <nl> + x0 ^ = _mm_set_epi32 ( 0 , 0 , 0 , remainder ) ; <nl> + <nl> + if ( p > end512 ) / * only 128 , 256 , or 384 bits of input ? * / <nl> + goto _128_bits_at_a_time ; <nl> + x1 = * p + + ; <nl> + x2 = * p + + ; <nl> + x3 = * p + + ; <nl> + <nl> + / * Fold 512 bits at a time * / <nl> + for ( ; p ! = end512 ; p + = 4 ) { <nl> + __m128i y0 , y1 , y2 , y3 ; <nl> + <nl> + y0 = p [ 0 ] ; <nl> + y1 = p [ 1 ] ; <nl> + y2 = p [ 2 ] ; <nl> + y3 = p [ 3 ] ; <nl> + <nl> + / * <nl> + * Note : the immediate constant for PCLMULQDQ specifies which <nl> + * 64 - bit halves of the 128 - bit vectors to multiply : <nl> + * <nl> + * 0x00 means low halves ( higher degree polynomial terms for us ) <nl> + * 0x11 means high halves ( lower degree polynomial terms for us ) <nl> + * / <nl> + y0 ^ = _mm_clmulepi64_si128 ( x0 , multipliers_4 , 0x00 ) ; <nl> + y1 ^ = _mm_clmulepi64_si128 ( x1 , multipliers_4 , 0x00 ) ; <nl> + y2 ^ = _mm_clmulepi64_si128 ( x2 , multipliers_4 , 0x00 ) ; <nl> + y3 ^ = _mm_clmulepi64_si128 ( x3 , multipliers_4 , 0x00 ) ; <nl> + y0 ^ = _mm_clmulepi64_si128 ( x0 , multipliers_4 , 0x11 ) ; <nl> + y1 ^ = _mm_clmulepi64_si128 ( x1 , multipliers_4 , 0x11 ) ; <nl> + y2 ^ = _mm_clmulepi64_si128 ( x2 , multipliers_4 , 0x11 ) ; <nl> + y3 ^ = _mm_clmulepi64_si128 ( x3 , multipliers_4 , 0x11 ) ; <nl> + <nl> + x0 = y0 ; <nl> + x1 = y1 ; <nl> + x2 = y2 ; <nl> + x3 = y3 ; <nl> + } <nl> + <nl> + / * Fold 512 bits = > 128 bits * / <nl> + x2 ^ = _mm_clmulepi64_si128 ( x0 , multipliers_2 , 0x00 ) ; <nl> + x3 ^ = _mm_clmulepi64_si128 ( x1 , multipliers_2 , 0x00 ) ; <nl> + x2 ^ = _mm_clmulepi64_si128 ( x0 , multipliers_2 , 0x11 ) ; <nl> + x3 ^ = _mm_clmulepi64_si128 ( x1 , multipliers_2 , 0x11 ) ; <nl> + x3 ^ = _mm_clmulepi64_si128 ( x2 , multipliers_1 , 0x00 ) ; <nl> + x3 ^ = _mm_clmulepi64_si128 ( x2 , multipliers_1 , 0x11 ) ; <nl> + x0 = x3 ; <nl> + <nl> + _128_bits_at_a_time : <nl> + while ( p ! = end ) { <nl> + / * Fold 128 bits into next 128 bits * / <nl> + x1 = * p + + ; <nl> + x1 ^ = _mm_clmulepi64_si128 ( x0 , multipliers_1 , 0x00 ) ; <nl> + x1 ^ = _mm_clmulepi64_si128 ( x0 , multipliers_1 , 0x11 ) ; <nl> + x0 = x1 ; <nl> + } <nl> + <nl> + / * Now there are just 128 bits left , stored in ' x0 ' . * / <nl> + <nl> + / * <nl> + * Fold 128 = > 96 bits . This also implicitly appends 32 zero bits , <nl> + * which is equivalent to multiplying by x ^ 32 . This is needed because <nl> + * the CRC is defined as M ( x ) * x ^ 32 mod G ( x ) , not just M ( x ) mod G ( x ) . <nl> + * / <nl> + x0 = _mm_srli_si128 ( x0 , 8 ) ^ _mm_clmulepi64_si128 ( x0 , multipliers_1 , 0x10 ) ; <nl> + <nl> + / * Fold 96 = > 64 bits * / <nl> + x0 = _mm_srli_si128 ( x0 , 4 ) ^ <nl> + _mm_clmulepi64_si128 ( x0 & mask32 , final_multiplier , 0x00 ) ; <nl> + <nl> + / * <nl> + * Finally , reduce 64 = > 32 bits using Barrett reduction . <nl> + * <nl> + * Let M ( x ) = A ( x ) * x ^ 32 + B ( x ) be the remaining message . The goal is to <nl> + * compute R ( x ) = M ( x ) mod G ( x ) . Since degree ( B ( x ) ) < degree ( G ( x ) ) : <nl> + * <nl> + * R ( x ) = ( A ( x ) * x ^ 32 + B ( x ) ) mod G ( x ) <nl> + * = ( A ( x ) * x ^ 32 ) mod G ( x ) + B ( x ) <nl> + * <nl> + * Then , by the Division Algorithm there exists a unique q ( x ) such that : <nl> + * <nl> + * A ( x ) * x ^ 32 mod G ( x ) = A ( x ) * x ^ 32 - q ( x ) * G ( x ) <nl> + * <nl> + * Since the left - hand side is of maximum degree 31 , the right - hand side <nl> + * must be too . This implies that we can apply ' mod x ^ 32 ' to the <nl> + * right - hand side without changing its value : <nl> + * <nl> + * ( A ( x ) * x ^ 32 - q ( x ) * G ( x ) ) mod x ^ 32 = q ( x ) * G ( x ) mod x ^ 32 <nl> + * <nl> + * Note that ' + ' is equivalent to ' - ' in polynomials over GF ( 2 ) . <nl> + * <nl> + * We also know that : <nl> + * <nl> + * / A ( x ) * x ^ 32 \ <nl> + * q ( x ) = floor ( mmmmmmmmm ) <nl> + * \ G ( x ) / <nl> + * <nl> + * To compute this efficiently , we can multiply the top and bottom by <nl> + * x ^ 32 and move the division by G ( x ) to the top : <nl> + * <nl> + * / A ( x ) * floor ( x ^ 64 / G ( x ) ) \ <nl> + * q ( x ) = floor ( mmmmmmmmmmmmmmmmmmmmmmmm - ) <nl> + * \ x ^ 32 / <nl> + * <nl> + * Note that floor ( x ^ 64 / G ( x ) ) is a constant . <nl> + * <nl> + * So finally we have : <nl> + * <nl> + * / A ( x ) * floor ( x ^ 64 / G ( x ) ) \ <nl> + * R ( x ) = B ( x ) + G ( x ) * floor ( mmmmmmmmmmmmmmmmmmmmmmmm - ) <nl> + * \ x ^ 32 / <nl> + * / <nl> + x1 = x0 ; <nl> + x0 = _mm_clmulepi64_si128 ( x0 & mask32 , barrett_reduction_constants , 0x00 ) ; <nl> + x0 = _mm_clmulepi64_si128 ( x0 & mask32 , barrett_reduction_constants , 0x10 ) ; <nl> + return _mm_cvtsi128_si32 ( _mm_srli_si128 ( x0 ^ x1 , 4 ) ) ; <nl> + } <nl> + } <nl> + } / / namespace <nl> mmm a / folly / detail / ChecksumDetail . h <nl> ppp b / folly / detail / ChecksumDetail . h <nl> <nl> <nl> # pragma once <nl> <nl> + # include < immintrin . h > <nl> + # include < stdint . h > <nl> + # include < cstddef > <nl> + <nl> namespace folly { namespace detail { <nl> <nl> / * * <nl> bool crc32c_hw_supported ( ) ; <nl> uint32_t crc32c_sw ( const uint8_t * data , size_t nbytes , <nl> uint32_t startingChecksum = ~ 0U ) ; <nl> <nl> + / * * <nl> + * Compute a CRC - 32 checksum of a buffer using a hardware - accelerated <nl> + * implementation . <nl> + * <nl> + * @ note This function is exposed to support special cases where the <nl> + * calling code is absolutely certain it ought to invoke a hardware - <nl> + * accelerated CRC - 32 implementation - unit tests , for example . For <nl> + * all other scenarios , please call crc32 ( ) and let it pick an <nl> + * implementation based on the capabilities of the underlying CPU . <nl> + * / <nl> + uint32_t <nl> + crc32_hw ( const uint8_t * data , size_t nbytes , uint32_t startingChecksum = ~ 0U ) ; <nl> + <nl> + uint32_t <nl> + crc32_hw_aligned ( uint32_t remainder , const __m128i * p , size_t vec_count ) ; <nl> + <nl> + / * * <nl> + * Check whether a hardware - accelerated CRC - 32 implementation is <nl> + * supported on the current CPU . <nl> + * / <nl> + bool crc32_hw_supported ( ) ; <nl> <nl> + / * * <nl> + * Compute a CRC - 32 checksum of a buffer using a portable , <nl> + * software - only implementation . <nl> + * <nl> + * @ note This function is exposed to support special cases where the <nl> + * calling code is absolutely certain it wants to use the software <nl> + * implementation instead of the hardware - accelerated code - unit <nl> + * tests , for example . For all other scenarios , please call crc32 ( ) <nl> + * and let it pick an implementation based on the capabilities of <nl> + * the underlying CPU . <nl> + * / <nl> + uint32_t <nl> + crc32_sw ( const uint8_t * data , size_t nbytes , uint32_t startingChecksum = ~ 0U ) ; <nl> } } / / folly : : detail <nl> mmm a / folly / test / ChecksumTest . cpp <nl> ppp b / folly / test / ChecksumTest . cpp <nl> TEST ( Checksum , crc32c_continuation_autodetect ) { <nl> testCRC32CContinuation ( folly : : crc32c ) ; <nl> } <nl> <nl> + TEST ( Checksum , crc32 ) { <nl> + if ( folly : : detail : : crc32c_hw_supported ( ) ) { <nl> + / / Just check that sw and hw match <nl> + for ( auto expected : expectedResults ) { <nl> + uint32_t sw_res = <nl> + folly : : detail : : crc32_sw ( buffer + expected . offset , expected . length , 0 ) ; <nl> + uint32_t hw_res = <nl> + folly : : detail : : crc32_hw ( buffer + expected . offset , expected . length , 0 ) ; <nl> + EXPECT_EQ ( sw_res , hw_res ) ; <nl> + } <nl> + } else { <nl> + LOG ( WARNING ) < < " skipping hardware - accelerated CRC - 32 tests " <nl> + < < " ( not supported on this CPU ) " ; <nl> + } <nl> + } <nl> + <nl> + TEST ( Checksum , crc32_continuation ) { <nl> + if ( folly : : detail : : crc32c_hw_supported ( ) ) { <nl> + / / Just check that sw and hw match <nl> + for ( auto expected : expectedResults ) { <nl> + auto halflen = expected . length / 2 ; <nl> + uint32_t sw_res = <nl> + folly : : detail : : crc32_sw ( buffer + expected . offset , halflen , 0 ) ; <nl> + sw_res = folly : : detail : : crc32_sw ( <nl> + buffer + expected . offset + halflen , halflen , sw_res ) ; <nl> + uint32_t hw_res = <nl> + folly : : detail : : crc32_hw ( buffer + expected . offset , halflen , 0 ) ; <nl> + hw_res = folly : : detail : : crc32_hw ( <nl> + buffer + expected . offset + halflen , halflen , hw_res ) ; <nl> + EXPECT_EQ ( sw_res , hw_res ) ; <nl> + uint32_t sw_res2 = <nl> + folly : : detail : : crc32_sw ( buffer + expected . offset , halflen * 2 , 0 ) ; <nl> + EXPECT_EQ ( sw_res , sw_res2 ) ; <nl> + uint32_t hw_res2 = <nl> + folly : : detail : : crc32_hw ( buffer + expected . offset , halflen * 2 , 0 ) ; <nl> + EXPECT_EQ ( hw_res , hw_res2 ) ; <nl> + } <nl> + } else { <nl> + LOG ( WARNING ) < < " skipping hardware - accelerated CRC - 32 tests " <nl> + < < " ( not supported on this CPU ) " ; <nl> + } <nl> + } <nl> + <nl> void benchmarkHardwareCRC32C ( unsigned long iters , size_t blockSize ) { <nl> if ( folly : : detail : : crc32c_hw_supported ( ) ) { <nl> uint32_t checksum ; <nl> void benchmarkSoftwareCRC32C ( unsigned long iters , size_t blockSize ) { <nl> } <nl> } <nl> <nl> + void benchmarkHardwareCRC32 ( unsigned long iters , size_t blockSize ) { <nl> + if ( folly : : detail : : crc32_hw_supported ( ) ) { <nl> + uint32_t checksum ; <nl> + for ( unsigned long i = 0 ; i < iters ; i + + ) { <nl> + checksum = folly : : detail : : crc32_hw ( buffer , blockSize ) ; <nl> + folly : : doNotOptimizeAway ( checksum ) ; <nl> + } <nl> + } else { <nl> + LOG ( WARNING ) < < " skipping hardware - accelerated CRC - 32 benchmarks " <nl> + < < " ( not supported on this CPU ) " ; <nl> + } <nl> + } <nl> + <nl> + void benchmarkSoftwareCRC32 ( unsigned long iters , size_t blockSize ) { <nl> + uint32_t checksum ; <nl> + for ( unsigned long i = 0 ; i < iters ; i + + ) { <nl> + checksum = folly : : detail : : crc32_sw ( buffer , blockSize ) ; <nl> + folly : : doNotOptimizeAway ( checksum ) ; <nl> + } <nl> + } <nl> + <nl> / / This test fits easily in the L1 cache on modern server processors , <nl> / / and thus it mainly measures the speed of the checksum computation . <nl> BENCHMARK ( crc32c_hardware_1KB_block , iters ) { <nl> BENCHMARK ( crc32c_software_1KB_block , iters ) { <nl> benchmarkSoftwareCRC32C ( iters , 1024 ) ; <nl> } <nl> <nl> + BENCHMARK ( crc32_hardware_1KB_block , iters ) { <nl> + benchmarkHardwareCRC32 ( iters , 1024 ) ; <nl> + } <nl> + <nl> + BENCHMARK ( crc32_software_1KB_block , iters ) { <nl> + benchmarkSoftwareCRC32 ( iters , 1024 ) ; <nl> + } <nl> + <nl> BENCHMARK_DRAW_LINE ( ) ; <nl> <nl> / / This test is too big for the L1 cache but fits in L2 <nl> BENCHMARK ( crc32c_software_64KB_block , iters ) { <nl> benchmarkSoftwareCRC32C ( iters , 64 * 1024 ) ; <nl> } <nl> <nl> + BENCHMARK ( crc32_hardware_64KB_block , iters ) { <nl> + benchmarkHardwareCRC32 ( iters , 64 * 1024 ) ; <nl> + } <nl> + <nl> + BENCHMARK ( crc32_software_64KB_block , iters ) { <nl> + benchmarkSoftwareCRC32 ( iters , 64 * 1024 ) ; <nl> + } <nl> + <nl> BENCHMARK_DRAW_LINE ( ) ; <nl> <nl> / / This test is too big for the L2 cache but fits in L3 <nl> BENCHMARK ( crc32c_software_512KB_block , iters ) { <nl> benchmarkSoftwareCRC32C ( iters , 512 * 1024 ) ; <nl> } <nl> <nl> + BENCHMARK ( crc32_hardware_512KB_block , iters ) { <nl> + benchmarkHardwareCRC32 ( iters , 512 * 1024 ) ; <nl> + } <nl> + <nl> + BENCHMARK ( crc32_software_512KB_block , iters ) { <nl> + benchmarkSoftwareCRC32 ( iters , 512 * 1024 ) ; <nl> + } <nl> <nl> int main ( int argc , char * * argv ) { <nl> testing : : InitGoogleTest ( & argc , argv ) ; <nl> | Add hardware crc impl | facebook/folly | d9acfc9e4d3f94c3470df9b45c7f0b6c172e8c23 | 2017-05-08T18:43:29Z |
mmm a / src / csharp / Grpc . IntegrationTesting / MetadataCredentialsTest . cs <nl> ppp b / src / csharp / Grpc . IntegrationTesting / MetadataCredentialsTest . cs <nl> public void MetadataCredentials_InterceptorLeavesMetadataEmpty ( ) <nl> client = new TestService . TestServiceClient ( channel ) ; <nl> <nl> var ex = Assert . Throws < RpcException > ( ( ) = > client . UnaryCall ( new SimpleRequest { } ) ) ; <nl> + / / StatusCode . Unknown as the server - side handler throws an exception after not receiving the authorization header . <nl> Assert . AreEqual ( StatusCode . Unknown , ex . Status . StatusCode ) ; <nl> } <nl> <nl> | add a comment | grpc/grpc | 60d0f4ced3204e4559ce915a320bef307a291c66 | 2016-11-10T08:54:33Z |
mmm a / packaging / msi / FDBInstaller . wxs <nl> ppp b / packaging / msi / FDBInstaller . wxs <nl> <nl> <nl> < Wix xmlns = ' http : / / schemas . microsoft . com / wix / 2006 / wi ' > <nl> < Product Name = ' $ ( var . Title ) ' <nl> - Id = ' { 77E8C5DC - 24D9 - 46BD - 863A - BD5B1D2BE2FE } ' <nl> + Id = ' { 06EE6C90 - 3838 - 4C25 - 95D6 - A4716F8CE7D0 } ' <nl> UpgradeCode = ' { A95EA002 - 686E - 4164 - 8356 - C715B7F8B1C8 } ' <nl> Version = ' $ ( var . Version ) ' <nl> Manufacturer = ' $ ( var . Manufacturer ) ' <nl> | Merge from release - 5 . 0 . 4 | apple/foundationdb | d9bc7edda0a12cd2d424a0b29481aecb57f6d2a2 | 2017-08-29T22:04:28Z |
mmm a / test_uphone / test_uphone . vcproj <nl> ppp b / test_uphone / test_uphone . vcproj <nl> <nl> > <nl> < / File > <nl> < / Filter > <nl> + < Filter <nl> + Name = " RenderTextureTest " <nl> + > <nl> + < File <nl> + RelativePath = " . \ tests \ RenderTextureTest \ RenderTextureTest . cpp " <nl> + > <nl> + < / File > <nl> + < File <nl> + RelativePath = " . \ tests \ RenderTextureTest \ RenderTextureTest . h " <nl> + > <nl> + < / File > <nl> + < / Filter > <nl> < / Filter > <nl> < File <nl> RelativePath = " . \ test_uphoneUnicodeScript . h " <nl> new file mode 100644 <nl> index 000000000000 . . 91988eb92547 <nl> mmm / dev / null <nl> ppp b / test_uphone / tests / RenderTextureTest / RenderTextureTest . cpp <nl> <nl> + # include " RenderTextureTest . h " <nl> + <nl> + RenderTextureTest : : RenderTextureTest ( ) <nl> + { <nl> + CGSize s = CCDirector : : getSharedDirector ( ) - > getWinSize ( ) ; <nl> + CCLabel * label = CCLabel : : labelWithString ( " Render Texture Test " , " Arial " , 28 ) ; <nl> + addChild ( label , 0 ) ; <nl> + label - > setPosition ( ccp ( s . width / 2 , s . height - 50 ) ) ; <nl> + <nl> + / / create a render texture , this is what we ' re going to draw into <nl> + m_target = CCRenderTexture : : renderTextureWithWidthAndHeight ( s . width , s . height ) ; <nl> + m_target - > setPosition ( ccp ( s . width / 2 , s . height / 2 ) ) ; <nl> + <nl> + / / note that the render texture is a cocosnode , and contains a sprite of it ' s texture for convience , <nl> + / / so we can just parent it to the scene like any other cocos node <nl> + addChild ( m_target , 1 ) ; <nl> + <nl> + / / create a brush image to draw into the texture with <nl> + m_brush = CCSprite : : spriteWithFile ( " Images / stars . png " ) ; <nl> + m_brush - > retain ( ) ; <nl> + <nl> + ccBlendFunc bf = { GL_ONE , GL_ONE_MINUS_SRC_ALPHA } ; <nl> + m_brush - > setBlendFunc ( bf ) ; <nl> + m_brush - > setOpacity ( 20 ) ; <nl> + setIsTouchEnabled ( true ) ; <nl> + } <nl> + <nl> + RenderTextureTest : : ~ RenderTextureTest ( ) <nl> + { <nl> + m_brush - > release ( ) ; <nl> + } <nl> + <nl> + void RenderTextureTest : : ccTouchesMoved ( NSSet * touches , UIEvent * event ) <nl> + { <nl> + NSSetIterator it = touches - > begin ( ) ; <nl> + CCTouch * touch = ( CCTouch * ) ( * it ) ; <nl> + CGPoint start = touch - > locationInView ( touch - > view ( ) ) ; <nl> + start = CCDirector : : getSharedDirector ( ) - > convertToGL ( start ) ; <nl> + CGPoint end = touch - > previousLocationInView ( touch - > view ( ) ) ; <nl> + end = CCDirector : : getSharedDirector ( ) - > convertToGL ( end ) ; <nl> + <nl> + / / begin drawing to the render texture <nl> + m_target - > begin ( ) ; <nl> + <nl> + / / for extra points , we ' ll draw this smoothly from the last position and vary the sprite ' s <nl> + / / scale / rotation / offset <nl> + float distance = ccpDistance ( start , end ) ; <nl> + if ( distance > 1 ) <nl> + { <nl> + int d = ( int ) distance ; <nl> + for ( int i = 0 ; i < d ; i + + ) <nl> + { <nl> + float difx = end . x - start . x ; <nl> + float dify = end . y - start . y ; <nl> + float delta = ( float ) i / distance ; <nl> + m_brush - > setPosition ( ccp ( start . x + ( difx * delta ) , start . y + ( dify * delta ) ) ) ; <nl> + m_brush - > setRotation ( rand ( ) % 360 ) ; <nl> + float r = ( ( float ) ( rand ( ) % 50 ) / 50 . f ) + 0 . 25f ; <nl> + m_brush - > setScale ( r ) ; <nl> + / / Call visit to draw the brush , don ' t call draw . . <nl> + m_brush - > visit ( ) ; <nl> + } <nl> + } <nl> + / / finish drawing and return context back to the screen <nl> + m_target - > end ( ) ; <nl> + } <nl> + <nl> + void RenderTextureScene : : runThisTest ( ) <nl> + { <nl> + CCLayer * pLayer = new RenderTextureTest ( ) ; <nl> + addChild ( pLayer ) ; <nl> + <nl> + CCDirector : : getSharedDirector ( ) - > replaceScene ( this ) ; <nl> + pLayer - > release ( ) ; <nl> + } <nl> new file mode 100644 <nl> index 000000000000 . . b592bfe63b32 <nl> mmm / dev / null <nl> ppp b / test_uphone / tests / RenderTextureTest / RenderTextureTest . h <nl> <nl> + # ifndef _RENDERTEXTURE_TEST_H_ <nl> + # define _RENDERTEXTURE_TEST_H_ <nl> + <nl> + # include " cocos2d . h " <nl> + # include " . . / testBasic . h " <nl> + <nl> + class RenderTextureTest : public CCLayer <nl> + { <nl> + public : <nl> + RenderTextureTest ( ) ; <nl> + ~ RenderTextureTest ( ) ; <nl> + virtual void ccTouchesMoved ( NSSet * touches , UIEvent * event ) ; <nl> + <nl> + private : <nl> + CCRenderTexture * m_target ; <nl> + CCSprite * m_brush ; <nl> + } ; <nl> + <nl> + class RenderTextureScene : public TestScene <nl> + { <nl> + public : <nl> + virtual void runThisTest ( ) ; <nl> + } ; <nl> + <nl> + # endif <nl> mmm a / test_uphone / tests / TransitionsTest / TransitionsTest . cpp <nl> ppp b / test_uphone / tests / TransitionsTest / TransitionsTest . cpp <nl> class PageTransitionBackward : public CCPageTurnTransition <nl> } <nl> } ; <nl> <nl> - # define MAX_LAYER 25 / / 37 <nl> + # define MAX_LAYER 37 <nl> <nl> static std : : string transitions [ MAX_LAYER ] = { <nl> " JumpZoomTransition " , <nl> static std : : string transitions [ MAX_LAYER ] = { <nl> " SlideInTTransition " , <nl> " SlideInBTransition " , <nl> <nl> - / / " CCCrossFadeTransition " , <nl> - / / " CCRadialCCWTransition " , <nl> - / / " CCRadialCWTransition " , <nl> - / / " PageTransitionForward " , <nl> - / / " PageTransitionBackward " , <nl> - / / " FadeTRTransition " , <nl> - / / " FadeBLTransition " , <nl> - / / " FadeUpTransition " , <nl> - / / " FadeDownTransition " , <nl> - / / " TurnOffTilesTransition " , <nl> - / / " SplitRowsTransition " , <nl> - / / " SplitColsTransition " , <nl> + " CCCrossFadeTransition " , <nl> + " CCRadialCCWTransition " , <nl> + " CCRadialCWTransition " , <nl> + " PageTransitionForward " , <nl> + " PageTransitionBackward " , <nl> + " FadeTRTransition " , <nl> + " FadeBLTransition " , <nl> + " FadeUpTransition " , <nl> + " FadeDownTransition " , <nl> + " TurnOffTilesTransition " , <nl> + " SplitRowsTransition " , <nl> + " SplitColsTransition " , <nl> } ; <nl> static int s_nSceneIdx = 0 ; <nl> <nl> CCTransitionScene * createTransition ( int nIndex , ccTime t , CCScene * s ) <nl> case 23 : return CCSlideInTTransition : : transitionWithDuration ( t , s ) ; <nl> case 24 : return CCSlideInBTransition : : transitionWithDuration ( t , s ) ; <nl> <nl> - / / case 25 : return CCCrossFadeTransition : : transitionWithDuration ( t , s ) ; <nl> - / / case 26 : return CCRadialCCWTransition : : transitionWithDuration ( t , s ) ; <nl> - / / case 27 : return CCRadialCWTransition : : transitionWithDuration ( t , s ) ; <nl> - / / case 28 : return PageTransitionForward : : transitionWithDuration ( t , s ) ; <nl> - / / case 29 : return PageTransitionBackward : : transitionWithDuration ( t , s ) ; <nl> - / / case 30 : return CCFadeTRTransition : : transitionWithDuration ( t , s ) ; <nl> - / / case 31 : return CCFadeBLTransition : : transitionWithDuration ( t , s ) ; <nl> - / / case 32 : return CCFadeUpTransition : : transitionWithDuration ( t , s ) ; <nl> - / / case 33 : return CCFadeDownTransition : : transitionWithDuration ( t , s ) ; <nl> - / / case 34 : return CCTurnOffTilesTransition : : transitionWithDuration ( t , s ) ; <nl> - / / case 35 : return CCSplitRowsTransition : : transitionWithDuration ( t , s ) ; <nl> - / / case 36 : return CCSplitColsTransition : : transitionWithDuration ( t , s ) ; <nl> + case 25 : return CCCrossFadeTransition : : transitionWithDuration ( t , s ) ; <nl> + case 26 : return CCRadialCCWTransition : : transitionWithDuration ( t , s ) ; <nl> + case 27 : return CCRadialCWTransition : : transitionWithDuration ( t , s ) ; <nl> + case 28 : return PageTransitionForward : : transitionWithDuration ( t , s ) ; <nl> + case 29 : return PageTransitionBackward : : transitionWithDuration ( t , s ) ; <nl> + case 30 : return CCFadeTRTransition : : transitionWithDuration ( t , s ) ; <nl> + case 31 : return CCFadeBLTransition : : transitionWithDuration ( t , s ) ; <nl> + case 32 : return CCFadeUpTransition : : transitionWithDuration ( t , s ) ; <nl> + case 33 : return CCFadeDownTransition : : transitionWithDuration ( t , s ) ; <nl> + case 34 : return CCTurnOffTilesTransition : : transitionWithDuration ( t , s ) ; <nl> + case 35 : return CCSplitRowsTransition : : transitionWithDuration ( t , s ) ; <nl> + case 36 : return CCSplitColsTransition : : transitionWithDuration ( t , s ) ; <nl> default : break ; <nl> } <nl> <nl> mmm a / test_uphone / tests / controller . cpp <nl> ppp b / test_uphone / tests / controller . cpp <nl> static TestScene * CreateTestScene ( int nIdx ) <nl> pScene = new TransitionsTestScene ( ) ; break ; <nl> case TEST_PROGRESS_ACTIONS : <nl> pScene = new ProgressActionsTestScene ( ) ; break ; <nl> - / * * <nl> - @ todo <nl> case TEST_EFFECTS : <nl> pScene = new EffectTestScene ( ) ; break ; <nl> - * / <nl> case TEST_CLICK_AND_MOVE : <nl> pScene = new ClickAndMoveTestScene ( ) ; break ; <nl> case TEST_ROTATE_WORLD : <nl> static TestScene * CreateTestScene ( int nIdx ) <nl> pScene = new TileMapTestScene ( ) ; break ; <nl> case TEST_INTERVAL : <nl> pScene = new IntervalTestScene ( ) ; break ; <nl> - / / case TESTS_CHIPMUNK : <nl> + / / case TEST_CHIPMUNK : <nl> / / CCDirector : : getSharedDirector ( ) - > setDeviceOrientation ( kCCDeviceOrientationPortrait ) ; <nl> / / pScene = new ChipmunkTestScene ( ) ; break ; <nl> case TEST_ATLAS : <nl> static TestScene * CreateTestScene ( int nIdx ) <nl> pScene = new SpriteTestScene ( ) ; break ; <nl> case TEST_SCHEDULER : <nl> pScene = new SchedulerTestScene ( ) ; break ; <nl> + case TEST_RENDERTEXTURE : <nl> + pScene = new RenderTextureScene ( ) ; break ; <nl> default : <nl> break ; <nl> } <nl> void TestController : : menuCallback ( NSObject * pSender ) <nl> if ( pScene ) <nl> { <nl> pScene - > runThisTest ( ) ; <nl> - pScene - > autorelease ( ) ; <nl> + pScene - > release ( ) ; <nl> } <nl> } <nl> <nl> mmm a / test_uphone / tests / tests . h <nl> ppp b / test_uphone / tests / tests . h <nl> <nl> # include " AtlasTest / AtlasTest . h " <nl> # include " SpriteTest / SpriteTest . h " <nl> # include " SchedulerTest / SchedulerTest . h " <nl> + # include " RenderTextureTest / RenderTextureTest . h " <nl> <nl> enum <nl> { <nl> enum <nl> TEST_PARALLAX , <nl> TEST_TILE_MAP , <nl> TEST_INTERVAL , <nl> - TESTS_CHIPMUNK , <nl> + TEST_CHIPMUNK , <nl> TEST_ATLAS , <nl> TEST_SPRITE , <nl> TEST_SCHEDULER , <nl> + TEST_RENDERTEXTURE , <nl> + <nl> TESTS_COUNT , <nl> } ; <nl> <nl> const std : : string g_aTestNames [ TESTS_COUNT ] = { <nl> " AtlasTest " , <nl> " SpriteTest " , <nl> " SchdulerTest " , <nl> + " RenderTextureTest " , <nl> } ; <nl> <nl> # endif <nl> | fixed | cocos2d/cocos2d-x | f2e09d15415823794eec6569bc628fdaa23b6948 | 2010-09-10T02:29:39Z |
mmm a / googletest / include / gtest / gtest - printers . h <nl> ppp b / googletest / include / gtest / gtest - printers . h <nl> GTEST_API_ void PrintBytesInObjectTo ( const unsigned char * obj_bytes , <nl> / / nor PrintTo ( ) . <nl> enum TypeKind { <nl> kProtobuf , / / a protobuf type <nl> - kConvertibleToInteger , / / a type implicitly convertible to std : : intmax_t <nl> + kConvertibleToInteger , / / a type implicitly convertible to BiggestInt <nl> / / ( e . g . a named or unnamed enum type ) <nl> # if GTEST_HAS_ABSL <nl> kConvertibleToStringView , / / a type implicitly convertible to <nl> template < typename T > <nl> class TypeWithoutFormatter < T , kConvertibleToInteger > { <nl> public : <nl> / / Since T has no < < operator or PrintTo ( ) but can be implicitly <nl> - / / converted to the maximum width integer , we print it as a std : : intmax_t . <nl> + / / converted to BiggestInt , we print it as a BiggestInt . <nl> / / <nl> / / Most likely T is an enum type ( either named or unnamed ) , in which <nl> - / / case printing it as an integer is the desired behavior . In case <nl> + / / case printing it as an integer is the desired behavior . In case <nl> / / T is not an enum , printing it as an integer is the best we can do <nl> / / given that it has no user - defined printer . <nl> static void PrintValue ( const T & value , : : std : : ostream * os ) { <nl> - const std : : intmax_t kBigInt = value ; <nl> + const internal : : BiggestInt kBigInt = value ; <nl> * os < < kBigInt ; <nl> } <nl> } ; <nl> class TypeWithoutFormatter < T , kConvertibleToStringView > { <nl> } ; <nl> # endif <nl> <nl> - / / Prints the given value to the given ostream . If the value is a <nl> + / / Prints the given value to the given ostream . If the value is a <nl> / / protocol message , its debug string is printed ; if it ' s an enum or <nl> - / / of a type implicitly convertible to std : : intmax_t , it ' s printed as an <nl> - / / integer ; otherwise the bytes in the value are printed . This is <nl> + / / of a type implicitly convertible to BiggestInt , it ' s printed as an <nl> + / / integer ; otherwise the bytes in the value are printed . This is <nl> / / what UniversalPrinter < T > : : Print ( ) does when it knows nothing about <nl> / / type T and T has neither < < operator nor PrintTo ( ) . <nl> / / <nl> class TypeWithoutFormatter < T , kConvertibleToStringView > { <nl> template < typename Char , typename CharTraits , typename T > <nl> : : std : : basic_ostream < Char , CharTraits > & operator < < ( <nl> : : std : : basic_ostream < Char , CharTraits > & os , const T & x ) { <nl> - TypeWithoutFormatter < <nl> - T , ( internal : : IsAProtocolMessage < T > : : value <nl> - ? kProtobuf <nl> - : std : : is_convertible < const T & , std : : intmax_t > : : value <nl> - ? kConvertibleToInteger <nl> - : <nl> + TypeWithoutFormatter < T , ( internal : : IsAProtocolMessage < T > : : value <nl> + ? kProtobuf <nl> + : std : : is_convertible < <nl> + const T & , internal : : BiggestInt > : : value <nl> + ? kConvertibleToInteger <nl> + : <nl> # if GTEST_HAS_ABSL <nl> - std : : is_convertible < const T & , absl : : string_view > : : value <nl> - ? kConvertibleToStringView <nl> - : <nl> + std : : is_convertible < <nl> + const T & , absl : : string_view > : : value <nl> + ? kConvertibleToStringView <nl> + : <nl> # endif <nl> - kOtherType ) > : : PrintValue ( x , & os ) ; <nl> + kOtherType ) > : : PrintValue ( x , & os ) ; <nl> return os ; <nl> } <nl> <nl> mmm a / googletest / include / gtest / gtest . h <nl> ppp b / googletest / include / gtest / gtest . h <nl> AssertionResult CmpHelperEQ ( const char * lhs_expression , <nl> return CmpHelperEQFailure ( lhs_expression , rhs_expression , lhs , rhs ) ; <nl> } <nl> <nl> - / / With this overloaded version , we allow anonymous enums to be used in <nl> - / / { ASSERT | EXPECT } _EQ as anonymous enums can be implicitly cast to integers . <nl> + / / With this overloaded version , we allow anonymous enums to be used <nl> + / / in { ASSERT | EXPECT } _EQ when compiled with gcc 4 , as anonymous enums <nl> + / / can be implicitly cast to BiggestInt . <nl> GTEST_API_ AssertionResult CmpHelperEQ ( const char * lhs_expression , <nl> const char * rhs_expression , <nl> - std : : intmax_t lhs , std : : intmax_t rhs ) ; <nl> + BiggestInt lhs , <nl> + BiggestInt rhs ) ; <nl> <nl> class EqHelper { <nl> public : <nl> class EqHelper { <nl> return CmpHelperEQ ( lhs_expression , rhs_expression , lhs , rhs ) ; <nl> } <nl> <nl> - / / With this overloaded version , we allow anonymous enums to be used in <nl> - / / { ASSERT | EXPECT } _EQ as anonymous enums can be implicitly cast to integers . <nl> + / / With this overloaded version , we allow anonymous enums to be used <nl> + / / in { ASSERT | EXPECT } _EQ when compiled with gcc 4 , as anonymous <nl> + / / enums can be implicitly cast to BiggestInt . <nl> / / <nl> / / Even though its body looks the same as the above version , we <nl> / / cannot merge the two , as it will make anonymous enums unhappy . <nl> static AssertionResult Compare ( const char * lhs_expression , <nl> - const char * rhs_expression , std : : intmax_t lhs , <nl> - std : : intmax_t rhs ) { <nl> + const char * rhs_expression , <nl> + BiggestInt lhs , <nl> + BiggestInt rhs ) { <nl> return CmpHelperEQ ( lhs_expression , rhs_expression , lhs , rhs ) ; <nl> } <nl> <nl> AssertionResult CmpHelperOpFailure ( const char * expr1 , const char * expr2 , <nl> / / of similar code . <nl> / / <nl> / / For each templatized helper function , we also define an overloaded <nl> - / / version for std : : intmax_t in order to reduce code bloat and allow <nl> - / / anonymous enums to be used with { ASSERT | EXPECT } _ ? ? . <nl> + / / version for BiggestInt in order to reduce code bloat and allow <nl> + / / anonymous enums to be used with { ASSERT | EXPECT } _ ? ? when compiled <nl> + / / with gcc 4 . <nl> / / <nl> / / INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM . <nl> <nl> - # define GTEST_IMPL_CMP_HELPER_ ( op_name , op ) \ <nl> - template < typename T1 , typename T2 > \ <nl> - AssertionResult CmpHelper # # op_name ( const char * expr1 , const char * expr2 , \ <nl> - const T1 & val1 , const T2 & val2 ) { \ <nl> - if ( val1 op val2 ) { \ <nl> - return AssertionSuccess ( ) ; \ <nl> - } else { \ <nl> - return CmpHelperOpFailure ( expr1 , expr2 , val1 , val2 , # op ) ; \ <nl> - } \ <nl> - } \ <nl> - GTEST_API_ AssertionResult CmpHelper # # op_name ( \ <nl> - const char * expr1 , const char * expr2 , std : : intmax_t val1 , \ <nl> - std : : intmax_t val2 ) <nl> + # define GTEST_IMPL_CMP_HELPER_ ( op_name , op ) \ <nl> + template < typename T1 , typename T2 > \ <nl> + AssertionResult CmpHelper # # op_name ( const char * expr1 , const char * expr2 , \ <nl> + const T1 & val1 , const T2 & val2 ) { \ <nl> + if ( val1 op val2 ) { \ <nl> + return AssertionSuccess ( ) ; \ <nl> + } else { \ <nl> + return CmpHelperOpFailure ( expr1 , expr2 , val1 , val2 , # op ) ; \ <nl> + } \ <nl> + } \ <nl> + GTEST_API_ AssertionResult CmpHelper # # op_name ( \ <nl> + const char * expr1 , const char * expr2 , BiggestInt val1 , BiggestInt val2 ) <nl> <nl> / / INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM . <nl> <nl> mmm a / googletest / include / gtest / internal / gtest - port . h <nl> ppp b / googletest / include / gtest / internal / gtest - port . h <nl> <nl> / / TypeWithSize - maps an integer to a int type . <nl> / / Int32 , UInt32 , Int64 , UInt64 , TimeInMillis <nl> / / - integers of known sizes . <nl> + / / BiggestInt - the biggest signed integer type . <nl> / / <nl> / / Command - line utilities : <nl> / / GTEST_DECLARE_ * ( ) - declares a flag . <nl> GTEST_API_ size_t GetThreadCount ( ) ; <nl> # if GTEST_OS_WINDOWS <nl> # define GTEST_PATH_SEP_ " \ \ " <nl> # define GTEST_HAS_ALT_PATH_SEP_ 1 <nl> + / / The biggest signed integer type the compiler supports . <nl> + typedef __int64 BiggestInt ; <nl> # else <nl> # define GTEST_PATH_SEP_ " / " <nl> # define GTEST_HAS_ALT_PATH_SEP_ 0 <nl> + typedef long long BiggestInt ; / / NOLINT <nl> # endif / / GTEST_OS_WINDOWS <nl> <nl> / / Utilities for char . <nl> GTEST_DISABLE_MSC_DEPRECATED_POP_ ( ) <nl> # define GTEST_SNPRINTF_ snprintf <nl> # endif <nl> <nl> + / / The maximum number a BiggestInt can represent . This definition <nl> + / / works no matter BiggestInt is represented in one ' s complement or <nl> + / / two ' s complement . <nl> + / / <nl> + / / We cannot rely on numeric_limits in STL , as __int64 and long long <nl> + / / are not part of standard C + + and numeric_limits doesn ' t need to be <nl> + / / defined for them . <nl> + const BiggestInt kMaxBiggestInt = <nl> + ~ ( static_cast < BiggestInt > ( 1 ) < < ( 8 * sizeof ( BiggestInt ) - 1 ) ) ; <nl> + <nl> / / This template class serves as a compile - time function from size to <nl> / / type . It maps a size in bytes to a primitive type with that <nl> / / size . e . g . <nl> mmm a / googletest / src / gtest . cc <nl> ppp b / googletest / src / gtest . cc <nl> namespace internal { <nl> / / The helper function for { ASSERT | EXPECT } _EQ with int or enum <nl> / / arguments . <nl> AssertionResult CmpHelperEQ ( const char * lhs_expression , <nl> - const char * rhs_expression , std : : intmax_t lhs , <nl> - std : : intmax_t rhs ) { <nl> + const char * rhs_expression , <nl> + BiggestInt lhs , <nl> + BiggestInt rhs ) { <nl> if ( lhs = = rhs ) { <nl> return AssertionSuccess ( ) ; <nl> } <nl> AssertionResult CmpHelperEQ ( const char * lhs_expression , <nl> } <nl> <nl> / / A macro for implementing the helper functions needed to implement <nl> - / / ASSERT_ ? ? and EXPECT_ ? ? with integer or enum arguments . It is here <nl> + / / ASSERT_ ? ? and EXPECT_ ? ? with integer or enum arguments . It is here <nl> / / just to avoid copy - and - paste of similar code . <nl> - # define GTEST_IMPL_CMP_HELPER_ ( op_name , op ) \ <nl> - AssertionResult CmpHelper # # op_name ( const char * expr1 , const char * expr2 , \ <nl> - std : : intmax_t val1 , std : : intmax_t val2 ) { \ <nl> - if ( val1 op val2 ) { \ <nl> - return AssertionSuccess ( ) ; \ <nl> - } else { \ <nl> - return AssertionFailure ( ) \ <nl> - < < " Expected : ( " < < expr1 < < " ) " # op " ( " < < expr2 \ <nl> - < < " ) , actual : " < < FormatForComparisonFailureMessage ( val1 , val2 ) \ <nl> - < < " vs " < < FormatForComparisonFailureMessage ( val2 , val1 ) ; \ <nl> - } \ <nl> - } <nl> + # define GTEST_IMPL_CMP_HELPER_ ( op_name , op ) \ <nl> + AssertionResult CmpHelper # # op_name ( const char * expr1 , const char * expr2 , \ <nl> + BiggestInt val1 , BiggestInt val2 ) { \ <nl> + if ( val1 op val2 ) { \ <nl> + return AssertionSuccess ( ) ; \ <nl> + } else { \ <nl> + return AssertionFailure ( ) \ <nl> + < < " Expected : ( " < < expr1 < < " ) " # op " ( " < < expr2 \ <nl> + < < " ) , actual : " < < FormatForComparisonFailureMessage ( val1 , val2 ) \ <nl> + < < " vs " < < FormatForComparisonFailureMessage ( val2 , val1 ) ; \ <nl> + } \ <nl> + } <nl> <nl> / / Implements the helper function for { ASSERT | EXPECT } _NE with int or <nl> / / enum arguments . <nl> mmm a / googletest / test / googletest - printers - test . cc <nl> ppp b / googletest / test / googletest - printers - test . cc <nl> void PrintTo ( EnumWithPrintTo e , std : : ostream * os ) { <nl> * os < < ( e = = kEWPT1 ? " kEWPT1 " : " invalid " ) ; <nl> } <nl> <nl> - / / A class implicitly convertible to std : : intmax_t . <nl> - class IntMaxConvertible { <nl> + / / A class implicitly convertible to BiggestInt . <nl> + class BiggestIntConvertible { <nl> public : <nl> - constexpr operator std : : intmax_t ( ) const { / / NOLINT ( runtime / explicit ) <nl> - return 42 ; <nl> - } <nl> + operator : : testing : : internal : : BiggestInt ( ) const { return 42 ; } <nl> } ; <nl> <nl> / / A user - defined unprintable class template in the global namespace . <nl> TEST ( PrintEnumTest , EnumWithPrintTo ) { <nl> EXPECT_EQ ( " invalid " , Print ( static_cast < EnumWithPrintTo > ( 0 ) ) ) ; <nl> } <nl> <nl> - / / Tests printing a class implicitly convertible to std : : intmax_t . <nl> + / / Tests printing a class implicitly convertible to BiggestInt . <nl> <nl> - TEST ( PrintClassTest , IntMaxConvertible ) { <nl> - EXPECT_EQ ( " 42 " , Print ( IntMaxConvertible ( ) ) ) ; <nl> + TEST ( PrintClassTest , BiggestIntConvertible ) { <nl> + EXPECT_EQ ( " 42 " , Print ( BiggestIntConvertible ( ) ) ) ; <nl> } <nl> <nl> / / Tests printing various char types . <nl> TEST ( PrintPointerTest , NonMemberFunctionPointer ) { <nl> / / standard disallows casting between pointers to functions and <nl> / / pointers to objects , and some compilers ( e . g . GCC 3 . 4 ) enforce <nl> / / this limitation . <nl> - EXPECT_EQ ( PrintPointer ( reinterpret_cast < const void * > ( <nl> - reinterpret_cast < std : : intptr_t > ( & MyFunction ) ) ) , <nl> - Print ( & MyFunction ) ) ; <nl> + EXPECT_EQ ( <nl> + PrintPointer ( reinterpret_cast < const void * > ( <nl> + reinterpret_cast < internal : : BiggestInt > ( & MyFunction ) ) ) , <nl> + Print ( & MyFunction ) ) ; <nl> int ( * p ) ( bool ) = NULL ; / / NOLINT <nl> EXPECT_EQ ( " NULL " , Print ( p ) ) ; <nl> } <nl> TEST ( PrintReferenceTest , HandlesFunctionPointer ) { <nl> / / standard disallows casting between pointers to functions and <nl> / / pointers to objects , and some compilers ( e . g . GCC 3 . 4 ) enforce <nl> / / this limitation . <nl> - const std : : string fp_string = PrintPointer ( <nl> - reinterpret_cast < const void * > ( reinterpret_cast < std : : intptr_t > ( fp ) ) ) ; <nl> + const std : : string fp_string = PrintPointer ( reinterpret_cast < const void * > ( <nl> + reinterpret_cast < internal : : BiggestInt > ( fp ) ) ) ; <nl> EXPECT_EQ ( " @ " + fp_pointer_string + " " + fp_string , <nl> PrintByRef ( fp ) ) ; <nl> } <nl> mmm a / googletest / test / gtest_unittest . cc <nl> ppp b / googletest / test / gtest_unittest . cc <nl> TEST ( CommandLineFlagsTest , CanBeAccessedInCodeOnceGTestHIsIncluded ) { <nl> EXPECT_TRUE ( dummy | | ! dummy ) ; / / Suppresses warning that dummy is unused . <nl> } <nl> <nl> + # include < limits . h > / / For INT_MAX . <nl> # include < stdlib . h > <nl> # include < string . h > <nl> # include < time . h > <nl> <nl> - # include < limits > <nl> # include < map > <nl> # include < ostream > <nl> # include < type_traits > <nl> enum { <nl> / / On Linux , kCaseB and kCaseA have the same value when truncated to <nl> / / int size . We want to test whether this will confuse the <nl> / / assertions . <nl> - kCaseB = ( std : : numeric_limits < std : : intmax_t > : : max ) ( ) , <nl> + kCaseB = testing : : internal : : kMaxBiggestInt , <nl> <nl> # else <nl> <nl> - kCaseB = ( std : : numeric_limits < int > : : max ) ( ) , <nl> + kCaseB = INT_MAX , <nl> <nl> # endif / / GTEST_OS_LINUX <nl> <nl> | Merge pull request from kuzkry : gtest - port - clean - up_kMaxBiggestInt | google/googletest | 8697709e0308af4cd5b09dc108480804e5447cf0 | 2019-11-04T16:43:27Z |
mmm a / src / bitcoin - cli . cpp <nl> ppp b / src / bitcoin - cli . cpp <nl> static int CommandLineRPC ( int argc , char * argv [ ] ) <nl> return nRet ; <nl> } <nl> <nl> - int main ( int argc , char * argv [ ] ) <nl> - { <nl> # ifdef WIN32 <nl> + / / Export main ( ) and ensure working ASLR on Windows . <nl> + / / Exporting a symbol will prevent the linker from stripping <nl> + / / the . reloc section from the binary , which is a requirement <nl> + / / for ASLR . This is a temporary workaround until a fixed <nl> + / / version of binutils is used for releases . <nl> + __declspec ( dllexport ) int main ( int argc , char * argv [ ] ) <nl> + { <nl> util : : WinCmdLineArgs winArgs ; <nl> std : : tie ( argc , argv ) = winArgs . get ( ) ; <nl> + # else <nl> + int main ( int argc , char * argv [ ] ) <nl> + { <nl> # endif <nl> SetupEnvironment ( ) ; <nl> if ( ! SetupNetworking ( ) ) { <nl> | build : fix ASLR for bitcoin - cli on Windows | bitcoin/bitcoin | 315a4d36f716341a38bc4e4de8630b3246d27dbc | 2020-04-19T02:05:29Z |
mmm a / Telegram / SourceFiles / application . cpp <nl> ppp b / Telegram / SourceFiles / application . cpp <nl> Application : : Application ( int & argc , char * * argv ) : PsApplication ( argc , argv ) , <nl> cSetRetina ( true ) ; <nl> cSetRetinaFactor ( devicePixelRatio ( ) ) ; <nl> cSetIntRetinaFactor ( int32 ( cRetinaFactor ( ) ) ) ; <nl> + cSetConfigScale ( dbisOne ) ; <nl> + cSetRealScale ( dbisOne ) ; <nl> } <nl> <nl> if ( cLang ( ) < languageTest ) { <nl> | scale to dbisOne in retina | telegramdesktop/tdesktop | a3781727759f7e6210b31110a443bd0b928fd530 | 2015-02-03T15:06:15Z |
mmm a / src / x87 / ic - x87 . cc <nl> ppp b / src / x87 / ic - x87 . cc <nl> static void GenerateGlobalInstanceTypeCheck ( MacroAssembler * masm , <nl> } <nl> <nl> <nl> - / / Generated code falls through if the receiver is a regular non - global <nl> - / / JS object with slow properties and no interceptors . <nl> - static void GenerateNameDictionaryReceiverCheck ( MacroAssembler * masm , <nl> - Register receiver , <nl> - Register r0 , <nl> - Register r1 , <nl> - Label * miss ) { <nl> - / / Register usage : <nl> - / / receiver : holds the receiver on entry and is unchanged . <nl> - / / r0 : used to hold receiver instance type . <nl> - / / Holds the property dictionary on fall through . <nl> - / / r1 : used to hold receivers map . <nl> - <nl> - / / Check that the receiver isn ' t a smi . <nl> - __ JumpIfSmi ( receiver , miss ) ; <nl> - <nl> - / / Check that the receiver is a valid JS object . <nl> - __ mov ( r1 , FieldOperand ( receiver , HeapObject : : kMapOffset ) ) ; <nl> - __ movzx_b ( r0 , FieldOperand ( r1 , Map : : kInstanceTypeOffset ) ) ; <nl> - __ cmp ( r0 , FIRST_SPEC_OBJECT_TYPE ) ; <nl> - __ j ( below , miss ) ; <nl> - <nl> - / / If this assert fails , we have to check upper bound too . <nl> - STATIC_ASSERT ( LAST_TYPE = = LAST_SPEC_OBJECT_TYPE ) ; <nl> - <nl> - GenerateGlobalInstanceTypeCheck ( masm , r0 , miss ) ; <nl> - <nl> - / / Check for non - global object that requires access check . <nl> - __ test_b ( FieldOperand ( r1 , Map : : kBitFieldOffset ) , <nl> - ( 1 < < Map : : kIsAccessCheckNeeded ) | <nl> - ( 1 < < Map : : kHasNamedInterceptor ) ) ; <nl> - __ j ( not_zero , miss ) ; <nl> - <nl> - __ mov ( r0 , FieldOperand ( receiver , JSObject : : kPropertiesOffset ) ) ; <nl> - __ CheckMap ( r0 , masm - > isolate ( ) - > factory ( ) - > hash_table_map ( ) , miss , <nl> - DONT_DO_SMI_CHECK ) ; <nl> - } <nl> - <nl> - <nl> / / Helper function used to load a property from a dictionary backing <nl> / / storage . This function may fail to load a property even though it is <nl> / / in the dictionary , so code at miss_label must always call a backup <nl> void LoadIC : : GenerateMegamorphic ( MacroAssembler * masm ) { <nl> <nl> <nl> void LoadIC : : GenerateNormal ( MacroAssembler * masm ) { <nl> - / / mmmmmmmmm - - S t a t e mmmmmmmmmmmm - <nl> - / / - - ecx : name <nl> - / / - - edx : receiver <nl> - / / - - esp [ 0 ] : return address <nl> - / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> - ASSERT ( edx . is ( ReceiverRegister ( ) ) ) ; <nl> - ASSERT ( ecx . is ( NameRegister ( ) ) ) ; <nl> - <nl> - Label miss , slow ; <nl> + Register dictionary = eax ; <nl> + ASSERT ( ! dictionary . is ( ReceiverRegister ( ) ) ) ; <nl> + ASSERT ( ! dictionary . is ( NameRegister ( ) ) ) ; <nl> <nl> - GenerateNameDictionaryReceiverCheck ( masm , edx , eax , ebx , & miss ) ; <nl> + Label slow ; <nl> <nl> - / / eax : elements <nl> - / / Search the dictionary placing the result in eax . <nl> - GenerateDictionaryLoad ( masm , & slow , eax , ecx , edi , ebx , eax ) ; <nl> + __ mov ( dictionary , <nl> + FieldOperand ( ReceiverRegister ( ) , JSObject : : kPropertiesOffset ) ) ; <nl> + GenerateDictionaryLoad ( masm , & slow , dictionary , NameRegister ( ) , edi , ebx , <nl> + eax ) ; <nl> __ ret ( 0 ) ; <nl> <nl> / / Dictionary load failed , go slow ( but don ' t miss ) . <nl> __ bind ( & slow ) ; <nl> GenerateRuntimeGetProperty ( masm ) ; <nl> - <nl> - / / Cache miss : Jump to runtime . <nl> - __ bind ( & miss ) ; <nl> - GenerateMiss ( masm ) ; <nl> } <nl> <nl> <nl> void StoreIC : : GenerateMiss ( MacroAssembler * masm ) { <nl> <nl> <nl> void StoreIC : : GenerateNormal ( MacroAssembler * masm ) { <nl> - / / Return address is on the stack . <nl> - Label miss , restore_miss ; <nl> + Label restore_miss ; <nl> Register receiver = ReceiverRegister ( ) ; <nl> Register name = NameRegister ( ) ; <nl> Register value = ValueRegister ( ) ; <nl> + Register dictionary = ebx ; <nl> <nl> - GenerateNameDictionaryReceiverCheck ( masm , receiver , ebx , edi , & miss ) ; <nl> + __ mov ( dictionary , FieldOperand ( receiver , JSObject : : kPropertiesOffset ) ) ; <nl> <nl> / / A lot of registers are needed for storing to slow case <nl> / / objects . Push and restore receiver but rely on <nl> / / GenerateDictionaryStore preserving the value and name . <nl> __ push ( receiver ) ; <nl> - GenerateDictionaryStore ( masm , & restore_miss , ebx , name , value , receiver , edi ) ; <nl> + GenerateDictionaryStore ( masm , & restore_miss , dictionary , name , value , <nl> + receiver , edi ) ; <nl> __ Drop ( 1 ) ; <nl> Counters * counters = masm - > isolate ( ) - > counters ( ) ; <nl> __ IncrementCounter ( counters - > store_normal_hit ( ) , 1 ) ; <nl> void StoreIC : : GenerateNormal ( MacroAssembler * masm ) { <nl> <nl> __ bind ( & restore_miss ) ; <nl> __ pop ( receiver ) ; <nl> - <nl> - __ bind ( & miss ) ; <nl> __ IncrementCounter ( counters - > store_normal_miss ( ) , 1 ) ; <nl> GenerateMiss ( masm ) ; <nl> } <nl> | X87 : Drop unnecessary receiver validity checks from { Load , Store } IC_Normal | v8/v8 | 3150bf387025639b618a4fe841e5d93b67388c3d | 2014-07-16T03:12:29Z |
mmm a / buildscripts / aws_ec2 . py <nl> ppp b / buildscripts / aws_ec2 . py <nl> def wait_for_state ( instance , state , wait_time_secs = 0 , show_progress = False ) : <nl> print ( " . " , end = " " , file = sys . stdout ) <nl> sys . stdout . flush ( ) <nl> try : <nl> + client_error = " " <nl> time_left = end_time - time . time ( ) <nl> instance . load ( ) <nl> if instance . state [ " Name " ] = = state : <nl> def wait_for_state ( instance , state , wait_time_secs = 0 , show_progress = False ) : <nl> break <nl> if time_left < = 0 : <nl> break <nl> - except botocore . exceptions . ClientError : <nl> + except botocore . exceptions . ClientError as err : <nl> # A ClientError exception can sometimes be generated , due to RequestLimitExceeded , <nl> # so we ignore it and retry until we time out . <nl> - pass <nl> + client_error = " { } " . format ( err . message ) <nl> + <nl> wait_interval_secs = 15 if time_left > 15 else time_left <nl> time . sleep ( wait_interval_secs ) <nl> if show_progress : <nl> if reached_state : <nl> print ( " Instance { } ! " . format ( instance . state [ " Name " ] ) , file = sys . stdout ) <nl> else : <nl> - print ( " Instance in state ' { } ' , failed to reach state ' { } ' ! " . format ( <nl> - instance . state [ " Name " ] , state ) , file = sys . stdout ) <nl> + print ( " Instance in state ' { } ' , failed to reach state ' { } ' { } ! " . format ( <nl> + instance . state [ " Name " ] , state , client_error ) , file = sys . stdout ) <nl> sys . stdout . flush ( ) <nl> return 0 if reached_state else 1 <nl> <nl> mmm a / buildscripts / remote_operations . py <nl> ppp b / buildscripts / remote_operations . py <nl> <nl> <nl> _OPERATIONS = [ " shell " , " copy_to " , " copy_from " ] <nl> <nl> - _SSH_CONNECTION_ERRORS = [ " System is booting up . " , " Permission denied " ] <nl> + _SSH_CONNECTION_ERRORS = [ <nl> + " System is booting up . " , <nl> + " Permission denied " , <nl> + " ssh_exchange_identification : read : Connection reset by peer " <nl> + ] <nl> <nl> <nl> def posix_path ( path ) : <nl> mmm a / etc / evergreen . yml <nl> ppp b / etc / evergreen . yml <nl> variables : <nl> <nl> - & powercycle_test <nl> ec2_artifacts : $ { monitor_proc_file } $ { monitor_system_file } $ { log_path } $ { backup_path_after } $ { backup_path_before } <nl> - program_options : - - logLevel info - - backupPathBefore $ { backup_path_before } - - backupPathAfter $ { backup_path_after } <nl> - connection_options : - - sshUserHost $ { ip_address } - - sshConnection \ " $ { ssh_identity } $ { ssh_connection_options } \ " <nl> - test_options : - - testLoops 15 - - seedDocNum 10000 - - rsync - - validate local - - canary local <nl> - crash_options : " - - crashMethod aws_ec2 - - crashOptions $ { instance_id } : private_ip_address - - crashWaitTime 30 - - jitterForCrashWaitTime 5 " <nl> - client_options : - - numCrudClients 20 - - numFsmClients 20 <nl> - mongodb_options : - - rootDir $ { remote_dir } - $ { task_id } - - mongodbBinDir $ { remote_dir } <nl> - mongod_options : - - mongodUsablePorts $ { standard_port } $ { secret_port } - - dbPath $ { db_path } - - logPath $ { log_path } <nl> - mongod_extra_options : - - mongodOptions \ " - - setParameter enableTestCommands = 1 \ " <nl> + program_options : - - logLevel = info - - backupPathBefore = $ { backup_path_before } - - backupPathAfter = $ { backup_path_after } <nl> + connection_options : - - sshUserHost = $ { ip_address } - - sshConnection = \ " $ { ssh_identity } $ { ssh_connection_options } \ " <nl> + test_options : - - testLoops = 15 - - seedDocNum = 10000 - - rsync - - validate = local - - canary = local <nl> + crash_options : " - - crashMethod = aws_ec2 - - crashOptions = $ { instance_id } : private_ip_address - - crashWaitTime = 45 - - jitterForCrashWaitTime = 5 " <nl> + client_options : - - numCrudClients = 20 - - numFsmClients = 20 <nl> + mongodb_options : - - rootDir = $ { remote_dir } - $ { task_id } - - mongodbBinDir = $ { remote_dir } <nl> + mongod_options : - - mongodUsablePorts $ { standard_port } $ { secret_port } - - dbPath = $ { db_path } - - logPath = $ { log_path } <nl> + mongod_extra_options : - - mongodOptions = \ " - - setParameter enableTestCommands = 1 \ " <nl> <nl> # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # <nl> # Functions # <nl> functions : <nl> type : test <nl> params : <nl> working_dir : src <nl> + shell : bash <nl> script : | <nl> set - o verbose <nl> set - o errexit <nl> functions : <nl> cmds = " source $ { virtualenv_dir | venv } / $ bin_dir / activate " <nl> cmds = " $ cmds ; python - u " <nl> # The remote python operates in a virtualenv <nl> - remote_python = " - - remotePython \ " $ cmds \ " " <nl> + remote_python = " - - remotePython = \ " $ cmds \ " " <nl> <nl> + # Initialize report . json . The report will be finalized by powertest . py . <nl> + report_json = " report . json " <nl> start_time = $ ( date + % s ) <nl> - status = " \ " pass \ " " <nl> + status = " \ " fail \ " " <nl> failures = 0 <nl> + exit_code = 1 <nl> + end_time = $ start_time <nl> + elapsed_secs = 0 <nl> + echo " { \ " failures \ " : $ failures , \ " results \ " : [ { \ " status \ " : $ status , \ " exit_code \ " : $ exit_code , \ " test_file \ " : \ " $ { task_name } \ " , \ " start \ " : $ start_time , \ " end \ " : $ end_time , \ " elapsed \ " : $ elapsed_secs } ] } " > $ report_json <nl> + generate_report_json = " - - reportJsonFile = $ report_json " <nl> <nl> - set + o errexit <nl> - eval python - u pytests / powertest . py \ <nl> - " $ { connection_options } \ <nl> + # # On Windows execute 10 test loops , cap the maximum number of clients to 10 each . <nl> + if [ " Windows_NT " = " $ OS " ] ; then <nl> + test_override = " - - testLoops = 10 " <nl> + max_clients = 10 <nl> + for client in - - numCrudClients - - numFsmClients <nl> + do <nl> + override = $ ( echo $ { client_options } | awk " BEGIN { FS = \ " | = \ " } { for ( j = 1 ; j < = NF ; j + + ) if ( \ $ j ~ / ^ $ client / ) { min = ( \ $ ( j + 1 ) < $ max_clients ) ? \ $ ( j + 1 ) : $ max_clients ; printf \ " % s = % d \ " , \ $ j , min } } " ) <nl> + client_override = " $ client_override $ override " <nl> + done <nl> + fi <nl> + <nl> + config_file = powertest . yml <nl> + eval python pytests / powertest . py \ <nl> + " - - saveConfigOptions = $ config_file \ <nl> + $ { connection_options } \ <nl> $ { program_options } \ <nl> + $ generate_report_json \ <nl> $ remote_sudo \ <nl> $ remote_python \ <nl> $ { test_options } \ <nl> + $ test_override \ <nl> $ { crash_options } \ <nl> $ { client_options } \ <nl> + $ client_override \ <nl> $ { mongodb_options } \ <nl> $ { mongod_options } \ <nl> $ { mongod_extra_options } " <nl> - exit_code = $ ? <nl> - <nl> - # Create report . json <nl> - end_time = $ ( date + % s ) <nl> - elapsed_secs = $ ( ( end_time - start_time ) ) <nl> - if [ $ exit_code - ne 0 ] ; then <nl> - status = " \ " fail \ " " <nl> - failures = 1 <nl> - fi <nl> - echo " { \ " failures \ " : $ failures , \ " results \ " : [ { \ " status \ " : $ status , \ " exit_code \ " : $ exit_code , \ " test_file \ " : \ " $ { task_name } \ " , \ " start \ " : $ start_time , \ " end \ " : $ end_time , \ " elapsed \ " : $ elapsed_secs } ] } " > report . json <nl> - exit $ exit_code <nl> + python - u pytests / powertest . py - - configFile = $ config_file <nl> <nl> " do multiversion setup " : <nl> command : shell . exec <nl> tasks : <nl> # mongod will not start if it crashed mongod while creating a namespace ( SERVER - 26499 ) . <nl> vars : <nl> < < : * powercycle_test <nl> - client_options : - - numCrudClients 20 - - numFsmClients 0 <nl> - mongod_extra_options : - - mongodOptions \ " - - setParameter enableTestCommands = 1 - - storageEngine mmapv1 \ " <nl> + client_options : - - numCrudClients = 20 - - numFsmClients = 0 <nl> + mongod_extra_options : - - mongodOptions = \ " - - setParameter enableTestCommands = 1 - - storageEngine mmapv1 \ " <nl> <nl> - name : powercycle_WT <nl> depends_on : <nl> tasks : <nl> - func : " run powercycle test " <nl> vars : <nl> < < : * powercycle_test <nl> - mongod_extra_options : - - mongodOptions \ " - - setParameter enableTestCommands = 1 - - storageEngine wiredTiger \ " <nl> + mongod_extra_options : - - mongodOptions = \ " - - setParameter enableTestCommands = 1 - - storageEngine wiredTiger \ " <nl> <nl> - name : powercycle_fcv3 . 4_WT <nl> depends_on : <nl> tasks : <nl> - func : " run powercycle test " <nl> vars : <nl> < < : * powercycle_test <nl> - client_options : - - numCrudClients 20 - - numFsmClients 20 - - fsmWorkloadBlacklistFiles toggle_feature_compatibility . js <nl> - mongod_options : - - mongodUsablePorts $ { standard_port } $ { secret_port } - - dbPath $ { db_path } - - logPath $ { log_path } - - fcv 3 . 4 <nl> - mongod_extra_options : - - mongodOptions \ " - - setParameter enableTestCommands = 1 - - storageEngine wiredTiger \ " <nl> + client_options : - - numCrudClients = 20 - - numFsmClients = 20 - - fsmWorkloadBlacklistFiles = toggle_feature_compatibility . js <nl> + mongod_options : - - mongodUsablePorts $ { standard_port } $ { secret_port } - - dbPath = $ { db_path } - - logPath = $ { log_path } - - fcv = 3 . 4 <nl> + mongod_extra_options : - - mongodOptions = \ " - - setParameter enableTestCommands = 1 - - storageEngine wiredTiger \ " <nl> <nl> - name : powercycle_replication_WT <nl> depends_on : <nl> tasks : <nl> - func : " run powercycle test " <nl> vars : <nl> < < : * powercycle_test <nl> - mongod_extra_options : - - replSet powercyle - - mongodOptions \ " - - setParameter enableTestCommands = 1 - - storageEngine wiredTiger \ " <nl> + mongod_extra_options : - - replSet = powercyle - - mongodOptions = \ " - - setParameter enableTestCommands = 1 - - storageEngine wiredTiger \ " <nl> <nl> - name : powercycle_replication_smalloplog_WT <nl> depends_on : <nl> tasks : <nl> - func : " run powercycle test " <nl> vars : <nl> < < : * powercycle_test <nl> - mongod_extra_options : - - replSet powercyle - - mongodOptions \ " - - setParameter enableTestCommands = 1 - - oplogSize 1 - - storageEngine wiredTiger \ " <nl> + mongod_extra_options : - - replSet = powercyle - - mongodOptions = \ " - - setParameter enableTestCommands = 1 - - oplogSize 20 - - storageEngine wiredTiger \ " <nl> <nl> - name : powercycle_syncdelay_WT <nl> depends_on : <nl> tasks : <nl> - func : " run powercycle test " <nl> vars : <nl> < < : * powercycle_test <nl> - mongod_extra_options : - - mongodOptions \ " - - setParameter enableTestCommands = 1 - - syncdelay 10 - - storageEngine wiredTiger \ " <nl> + mongod_extra_options : - - mongodOptions = \ " - - setParameter enableTestCommands = 1 - - syncdelay 10 - - storageEngine wiredTiger \ " <nl> <nl> - name : powercycle_write_concern_majority_WT <nl> depends_on : <nl> tasks : <nl> - func : " run powercycle test " <nl> vars : <nl> < < : * powercycle_test <nl> - client_options : " - - numCrudClients 20 - - numFsmClients 20 - - writeConcern ' { \ " w \ " : \ " majority \ " } ' " <nl> + client_options : " - - numCrudClients = 20 - - numFsmClients = 20 - - writeConcern = ' { \ " w \ " : \ " majority \ " } ' " <nl> mongod_extra_options : - - mongodOptions \ " - - setParameter enableTestCommands = 1 - - storageEngine wiredTiger \ " <nl> <nl> - name : idl_tests <nl> buildvariants : <nl> - name : ssl <nl> - name : sslSpecial <nl> - name : tool_WT <nl> + - name : powercycle <nl> + - name : powercycle_WT <nl> + - name : powercycle_fcv3 . 4_WT <nl> + - name : powercycle_replication_WT <nl> + - name : powercycle_syncdelay_WT <nl> - name : push <nl> distros : <nl> - rhel70 - small <nl> mmm a / pytests / powertest . py <nl> ppp b / pytests / powertest . py <nl> <nl> import copy <nl> import datetime <nl> import distutils . spawn <nl> + import json <nl> import importlib <nl> import logging <nl> import optparse <nl> def _try_import ( module , name = None ) : <nl> <nl> LOGGER = logging . getLogger ( __name__ ) <nl> <nl> + _report_json_success = False <nl> + _report_json = { } <nl> + _report_json_file = " " <nl> + <nl> " " " Client & server side powercycle test script . <nl> <nl> This script can be run against any host which is reachable via ssh . <nl> def _try_import ( module , name = None ) : <nl> <nl> <nl> def exit_handler ( ) : <nl> - " " " Exit handler , deletes all named temporary files . " " " <nl> - LOGGER . debug ( " Exit handler invoked , cleaning up temporary files " ) <nl> + " " " Exit handler actions : <nl> + - Generate report . json <nl> + - Kill spawned processes <nl> + - Delete all named temporary files <nl> + " " " <nl> + if _report_json : <nl> + LOGGER . debug ( " Exit handler : Updating report file % s " , _report_json_file ) <nl> + try : <nl> + test_start = _report_json [ " results " ] [ 0 ] [ " start " ] <nl> + test_end = int ( time . time ( ) ) <nl> + test_time = test_end - test_start <nl> + if _report_json_success : <nl> + failures = 0 <nl> + status = " pass " <nl> + exit_code = 0 <nl> + else : <nl> + failures = 1 <nl> + status = " fail " <nl> + exit_code = 1 <nl> + _report_json [ " failures " ] = failures <nl> + _report_json [ " results " ] [ 0 ] [ " status " ] = status <nl> + _report_json [ " results " ] [ 0 ] [ " exit_code " ] = exit_code <nl> + _report_json [ " results " ] [ 0 ] [ " end " ] = test_end <nl> + _report_json [ " results " ] [ 0 ] [ " elapsed " ] = test_time <nl> + with open ( _report_json_file , " w " ) as jstream : <nl> + json . dump ( _report_json , jstream ) <nl> + LOGGER . debug ( " Exit handler : report file contents % s " , _report_json ) <nl> + except : <nl> + pass <nl> + <nl> + LOGGER . debug ( " Exit handler : Killing processes " ) <nl> + try : <nl> + Processes . kill_all ( ) <nl> + except : <nl> + pass <nl> + <nl> + LOGGER . debug ( " Exit handler : Cleaning up temporary files " ) <nl> try : <nl> NamedTempFile . delete_all ( ) <nl> except : <nl> def exit_handler ( ) : <nl> <nl> def child_processes ( parent_pid ) : <nl> " " " Returns a list of all child processes for a pid . " " " <nl> - # The child processes cannot be obtained from the parent on Windows . See <nl> + # The child processes cannot be obtained from the parent on Windows from psutil . See <nl> # https : / / stackoverflow . com / questions / 30220732 / python - psutil - not - showing - all - child - processes <nl> child_procs = [ ] <nl> while psutil . pid_exists ( parent_pid ) : <nl> def kill_process ( pid , kill_children = True ) : <nl> try : <nl> parent = psutil . Process ( pid ) <nl> except psutil . NoSuchProcess : <nl> - LOGGER . error ( " Could not kill process % d , as it no longer exists " , pid ) <nl> + LOGGER . warn ( " Could not kill process % d , as it no longer exists " , pid ) <nl> return 0 <nl> <nl> - procs = [ ] <nl> + procs = [ parent ] <nl> if kill_children : <nl> procs + = child_processes ( pid ) <nl> - procs . append ( parent ) <nl> <nl> for proc in procs : <nl> try : <nl> - LOGGER . debug ( " Killing process % d " , proc . pid ) <nl> + LOGGER . debug ( " Killing process ' % s ' pid % d " , proc . name ( ) , proc . pid ) <nl> proc . kill ( ) <nl> except psutil . NoSuchProcess : <nl> - LOGGER . error ( " Could not kill process % d , as it no longer exists " , pid ) <nl> + LOGGER . warn ( " Could not kill process % d , as it no longer exists " , pid ) <nl> <nl> _ , alive = psutil . wait_procs ( procs , timeout = 30 , callback = None ) <nl> if alive : <nl> def kill_process ( pid , kill_children = True ) : <nl> def kill_processes ( procs , kill_children = True ) : <nl> " " " Kill a list of processes and optionally it ' s children . " " " <nl> for proc in procs : <nl> - LOGGER . debug ( " Killing parent process % d " , proc . pid ) <nl> + LOGGER . debug ( " Starting kill of parent process % d " , proc . pid ) <nl> kill_process ( proc . pid , kill_children = kill_children ) <nl> ret = proc . wait ( ) <nl> - LOGGER . debug ( " Kill of parent process % d has return code of % d " , proc . pid , ret ) <nl> + LOGGER . debug ( " Finished kill of parent process % d has return code of % d " , proc . pid , ret ) <nl> <nl> <nl> def get_extension ( filename ) : <nl> def get_bin_dir ( root_dir ) : <nl> <nl> def create_temp_executable_file ( cmds ) : <nl> " " " Creates an executable temporary file containing ' cmds ' . Returns file name . " " " <nl> - temp_file_name = NamedTempFile . create ( suffix = " . sh " , dir = " tmp " ) <nl> + temp_file_name = NamedTempFile . create ( suffix = " . sh " , directory = " tmp " ) <nl> with NamedTempFile . get ( temp_file_name ) as temp_file : <nl> temp_file . write ( cmds ) <nl> os_st = os . stat ( temp_file_name ) <nl> def start_cmd ( cmd , use_file = False ) : <nl> LOGGER . debug ( " Executing ' % s ' " , cmd ) <nl> <nl> proc = subprocess . Popen ( cmd , close_fds = True ) <nl> + LOGGER . debug ( " Spawned process % s pid % d " , psutil . Process ( proc . pid ) . name ( ) , proc . pid ) <nl> <nl> return proc <nl> <nl> def call_remote_operation ( local_ops , remote_python , script_name , client_args , op <nl> return ret , output <nl> <nl> <nl> + class Processes ( object ) : <nl> + " " " Class to create and kill spawned processes . " " " <nl> + <nl> + _PROC_LIST = [ ] <nl> + <nl> + @ classmethod <nl> + def create ( cls , cmds ) : <nl> + " " " Creates a spawned process . " " " <nl> + proc = start_cmd ( cmds , use_file = True ) <nl> + cls . _PROC_LIST . append ( proc ) <nl> + <nl> + @ classmethod <nl> + def kill ( cls , proc ) : <nl> + " " " Kills a spawned process and all it ' s children . " " " <nl> + kill_processes ( [ proc ] , kill_children = True ) <nl> + cls . _PROC_LIST . remove ( proc ) <nl> + <nl> + @ classmethod <nl> + def kill_all ( cls ) : <nl> + " " " Kill all spawned processes . " " " <nl> + procs = copy . copy ( cls . _PROC_LIST ) <nl> + for proc in procs : <nl> + cls . kill ( proc ) <nl> + <nl> + <nl> class NamedTempFile ( object ) : <nl> " " " Class to control temporary files . " " " <nl> <nl> class NamedTempFile ( object ) : <nl> _DIR_LIST = [ ] <nl> <nl> @ classmethod <nl> - def create ( cls , dir = None , suffix = " " ) : <nl> + def create ( cls , directory = None , suffix = " " ) : <nl> " " " Creates a temporary file , and optional directory , and returns the file name . " " " <nl> - if dir and not os . path . isdir ( dir ) : <nl> - os . makedirs ( dir ) <nl> - cls . _DIR_LIST . append ( dir ) <nl> - temp_file = tempfile . NamedTemporaryFile ( suffix = suffix , dir = dir , delete = False ) <nl> + if directory and not os . path . isdir ( directory ) : <nl> + LOGGER . debug ( " Creating temporary directory % s " , directory ) <nl> + os . makedirs ( directory ) <nl> + cls . _DIR_LIST . append ( directory ) <nl> + temp_file = tempfile . NamedTemporaryFile ( suffix = suffix , dir = directory , delete = False ) <nl> cls . _FILE_MAP [ temp_file . name ] = temp_file <nl> return temp_file . name <nl> <nl> def delete ( cls , name ) : <nl> " " " Deletes temporary file . Raises an exception if the file is unknown . " " " <nl> if name not in cls . _FILE_MAP : <nl> raise Exception ( " Unknown temporary file { } . " . format ( name ) ) <nl> + if not os . path . exists ( name ) : <nl> + LOGGER . debug ( " Temporary file % s no longer exists " , name ) <nl> + del cls . _FILE_MAP [ name ] <nl> + return <nl> try : <nl> os . remove ( name ) <nl> except ( IOError , OSError ) as err : <nl> - LOGGER . warn ( " Unable to delete temporary file { } with error { } " . format ( name , err ) ) <nl> + LOGGER . warn ( " Unable to delete temporary file % s with error % s " , name , err ) <nl> if not os . path . exists ( name ) : <nl> del cls . _FILE_MAP [ name ] <nl> <nl> @ classmethod <nl> - def delete_dir ( cls , dir ) : <nl> + def delete_dir ( cls , directory ) : <nl> " " " Deletes temporary directory . Raises an exception if the directory is unknown . " " " <nl> - if dir not in cls . _DIR_LIST : <nl> - raise Exception ( " Unknown temporary directory { } . " . format ( dir ) ) <nl> + if directory not in cls . _DIR_LIST : <nl> + raise Exception ( " Unknown temporary directory { } . " . format ( directory ) ) <nl> + if not os . path . exists ( directory ) : <nl> + LOGGER . debug ( " Temporary directory % s no longer exists " , directory ) <nl> + cls . _DIR_LIST . remove ( directory ) <nl> + return <nl> try : <nl> - shutil . rmtree ( dir ) <nl> + shutil . rmtree ( directory ) <nl> except ( IOError , OSError ) as err : <nl> - LOGGER . warn ( " Unable to delete temporary directory { } with error { } " . format ( dir , err ) ) <nl> - if not os . path . exists ( dir ) : <nl> - cls . _DIR_LIST . remove ( dir ) <nl> + LOGGER . warn ( <nl> + " Unable to delete temporary directory % s with error % s " , directory , err ) <nl> + if not os . path . exists ( directory ) : <nl> + cls . _DIR_LIST . remove ( directory ) <nl> <nl> @ classmethod <nl> def delete_all ( cls ) : <nl> " " " Deletes all temporary files and directories . " " " <nl> for name in list ( cls . _FILE_MAP ) : <nl> cls . delete ( name ) <nl> - for dir in cls . _DIR_LIST : <nl> - cls . delete_dir ( dir ) <nl> + for directory in cls . _DIR_LIST : <nl> + cls . delete_dir ( directory ) <nl> <nl> <nl> class ProcessControl ( object ) : <nl> def status ( self ) : <nl> win32serviceutil . QueryServiceStatus ( serviceName = self . name ) ) <nl> if svc_state in self . _states : <nl> return self . _states [ svc_state ] <nl> - else : <nl> - return " unknown " <nl> + return " unknown " <nl> except pywintypes . error : <nl> return " not installed " <nl> <nl> def remote_handler ( options , operations ) : <nl> port = options . port , <nl> options = options . mongod_options ) <nl> <nl> + mongo_client_opts = get_mongo_client_args ( options , host = " localhost " , port = options . port ) <nl> + <nl> # Perform the sequence of operations specified . If any operation fails <nl> # then return immediately . <nl> for operation in operations : <nl> # This is the internal " crash " mechanism , which is executed on the remote host . <nl> if operation = = " crash_server " : <nl> ret , output = internal_crash ( options . remote_sudo ) <nl> + # An internal crash on Windows is not immediate <nl> + try : <nl> + LOGGER . info ( " Waiting after issuing internal crash ! " ) <nl> + time . sleep ( 30 ) <nl> + except IOError : <nl> + pass <nl> <nl> elif operation = = " install_mongod " : <nl> ret , output = mongod . install ( root_dir , options . tarball_url ) <nl> def remote_handler ( options , operations ) : <nl> return ret <nl> LOGGER . info ( " Started mongod running on port % d pid % s " , <nl> options . port , mongod . get_pids ( ) ) <nl> - mongo = pymongo . MongoClient ( host = " localhost " , port = options . port ) <nl> + mongo = pymongo . MongoClient ( * * mongo_client_opts ) <nl> LOGGER . info ( " Server buildinfo : % s " , mongo . admin . command ( " buildinfo " ) ) <nl> LOGGER . info ( " Server serverStatus : % s " , mongo . admin . command ( " serverStatus " ) ) <nl> if options . use_replica_set and options . repl_set : <nl> def remote_handler ( options , operations ) : <nl> ret = wait_for_mongod_shutdown ( options . db_path ) <nl> <nl> elif operation = = " shutdown_mongod " : <nl> - mongo = pymongo . MongoClient ( host = " localhost " , port = options . port ) <nl> + mongo = pymongo . MongoClient ( * * mongo_client_opts ) <nl> try : <nl> mongo . admin . command ( " shutdown " , force = True ) <nl> except pymongo . errors . AutoReconnect : <nl> def remote_handler ( options , operations ) : <nl> LOGGER . info ( output ) <nl> <nl> elif operation = = " seed_docs " : <nl> - mongo = pymongo . MongoClient ( host = " localhost " , port = options . port ) <nl> + mongo = pymongo . MongoClient ( * * mongo_client_opts ) <nl> ret = mongo_seed_docs ( <nl> mongo , options . db_name , options . collection_name , options . seed_doc_num ) <nl> <nl> elif operation = = " validate_collections " : <nl> - mongo = pymongo . MongoClient ( host = " localhost " , port = options . port ) <nl> + mongo = pymongo . MongoClient ( * * mongo_client_opts ) <nl> ret = mongo_validate_collections ( mongo ) <nl> <nl> elif operation = = " insert_canary " : <nl> - mongo = pymongo . MongoClient ( host = " localhost " , port = options . port ) <nl> + mongo = pymongo . MongoClient ( * * mongo_client_opts ) <nl> ret = mongo_insert_canary ( <nl> mongo , options . db_name , options . collection_name , options . canary_doc ) <nl> <nl> elif operation = = " validate_canary " : <nl> - mongo = pymongo . MongoClient ( host = " localhost " , port = options . port ) <nl> + mongo = pymongo . MongoClient ( * * mongo_client_opts ) <nl> ret = mongo_validate_canary ( <nl> mongo , options . db_name , options . collection_name , options . canary_doc ) <nl> <nl> elif operation = = " set_fcv " : <nl> - mongo = pymongo . MongoClient ( host = " localhost " , port = options . port ) <nl> + mongo = pymongo . MongoClient ( * * mongo_client_opts ) <nl> try : <nl> ret = mongo . admin . command ( " setFeatureCompatibilityVersion " , options . fcv_version ) <nl> ret = 0 if ret [ " ok " ] = = 1 else 1 <nl> def crash_server ( options , crash_canary , canary_port , local_ops , script_name , cli <nl> ec2 = aws_ec2 . AwsEc2 ( ) <nl> crash_func = ec2 . control_instance <nl> instance_id , _ = get_aws_crash_options ( options . crash_options ) <nl> - crash_args = [ " force - stop " , instance_id , 240 , True ] <nl> + crash_args = [ " force - stop " , instance_id , 600 , True ] <nl> <nl> else : <nl> message = " Unsupported crash method ' { } ' provided " . format ( options . crash_method ) <nl> - LOGGER . error ( " Unsupported crash method ' % s ' provided " , message ) <nl> + LOGGER . error ( message ) <nl> return 1 , message <nl> <nl> # Invoke the crash canary function , right before crashing the server . <nl> def wait_for_mongod_shutdown ( data_dir , timeout = 120 ) : <nl> return 0 <nl> <nl> <nl> - def get_mongo_client_args ( options ) : <nl> + def get_mongo_client_args ( options , host = None , port = None ) : <nl> " " " Returns keyword arg dict used in PyMongo client . " " " <nl> - mongo_args = { } <nl> + # Set the serverSelectionTimeoutMS to 600 seconds <nl> + mongo_args = { " serverSelectionTimeoutMS " : 600000 } <nl> + # Set the serverSelectionTimeoutMS to 120 seconds <nl> + mongo_args [ " socketTimeoutMS " ] = 120000 <nl> # Set the writeConcern <nl> mongo_args = yaml . safe_load ( options . write_concern ) <nl> # Set the readConcernLevel <nl> if options . read_concern_level : <nl> mongo_args [ " readConcernLevel " ] = options . read_concern_level <nl> + if host : <nl> + mongo_args [ " host " ] = host <nl> + if port : <nl> + mongo_args [ " port " ] = port <nl> return mongo_args <nl> <nl> <nl> def mongo_shell ( mongo_path , work_dir , host_port , mongo_cmds , retries = 5 , retry_sl <nl> cmds = ( " " " <nl> cd { } ; <nl> echo { } | { } { } " " " . format ( <nl> - pipes . quote ( work_dir ) , <nl> - pipes . quote ( mongo_cmds ) , <nl> - pipes . quote ( mongo_path ) , <nl> - host_port ) ) <nl> + pipes . quote ( work_dir ) , <nl> + pipes . quote ( mongo_cmds ) , <nl> + pipes . quote ( mongo_path ) , <nl> + host_port ) ) <nl> attempt_num = 0 <nl> while True : <nl> ret , output = execute_cmd ( cmds , use_file = True ) <nl> def mongo_validate_canary ( mongo , db_name , coll_name , doc ) : <nl> <nl> def mongo_insert_canary ( mongo , db_name , coll_name , doc ) : <nl> " " " Inserts a canary document with ' j ' True . Returns 0 if successful . " " " <nl> - LOGGER . info ( " Inserting canary document % s " , doc ) <nl> + LOGGER . info ( " Inserting canary document % s to DB % s Collection % s " , doc , db_name , coll_name ) <nl> coll = mongo [ db_name ] [ coll_name ] . with_options ( <nl> write_concern = pymongo . write_concern . WriteConcern ( j = True ) ) <nl> res = coll . insert_one ( doc ) <nl> def resmoke_client ( work_dir , <nl> repeat_num , <nl> pipes . quote ( js_test ) , <nl> log_output ) ) <nl> - ret , output , proc = None , None , None <nl> + ret , output = None , None <nl> if no_wait : <nl> - proc = start_cmd ( cmds , use_file = True ) <nl> + Processes . create ( cmds ) <nl> else : <nl> ret , output = execute_cmd ( cmds , use_file = True ) <nl> - return ret , output , proc <nl> + return ret , output <nl> <nl> <nl> def main ( ) : <nl> " " " Main program . " " " <nl> <nl> + global _report_json_success <nl> + global _report_json <nl> + global _report_json_file <nl> + <nl> atexit . register ( exit_handler ) <nl> <nl> parser = optparse . OptionParser ( usage = " " " <nl> def main ( ) : <nl> action = " store_true " , <nl> default = False ) <nl> <nl> + test_options . add_option ( " - - backupPathBefore " , <nl> + dest = " backup_path_before " , <nl> + help = " Path where the db_path is backed up before crash recovery , " <nl> + " defaults to ' < rootDir > / data - beforerecovery ' " , <nl> + default = None ) <nl> + <nl> + test_options . add_option ( " - - backupPathAfter " , <nl> + dest = " backup_path_after " , <nl> + help = " Path where the db_path is backed up after crash recovery , " <nl> + " defaults to ' < rootDir > / data - afterrecovery ' " , <nl> + default = None ) <nl> + <nl> validate_locations = [ " local " , " remote " ] <nl> test_options . add_option ( " - - validate " , <nl> dest = " validate_collections " , <nl> def main ( ) : <nl> help = " Set the FeatureCompatibilityVersion of mongod . " , <nl> default = None ) <nl> <nl> - # Program options <nl> - program_options . add_option ( " - - remotePython " , <nl> - dest = " remote_python " , <nl> - help = " The python intepreter to use on the remote host " <nl> - " [ default : ' % default ' ] . " <nl> - " To be able to use a python virtual environment , " <nl> - " which has already been provisioned on the remote " <nl> - " host , specify something similar to this : " <nl> - " ' source venv / bin / activate ; python ' " , <nl> - default = " python " ) <nl> - <nl> # Client options <nl> mongo_path = distutils . spawn . find_executable ( <nl> " mongo " , os . getcwd ( ) + os . pathsep + os . environ [ " PATH " ] ) <nl> def main ( ) : <nl> default = [ ] ) <nl> <nl> # Program options <nl> + program_options . add_option ( " - - configFile " , <nl> + dest = " config_file " , <nl> + help = " YAML configuration file of program options . " <nl> + " Option values are mapped to command line option names . " <nl> + " The command line option overrides any specified options " <nl> + " from this file . " , <nl> + default = None ) <nl> + <nl> + program_options . add_option ( " - - saveConfigOptions " , <nl> + dest = " save_config_options " , <nl> + help = " Save the program options to a YAML configuration file . " <nl> + " If this options is specified the program only saves " <nl> + " the configuration file and exits . " , <nl> + default = None ) <nl> + <nl> + program_options . add_option ( " - - reportJsonFile " , <nl> + dest = " report_json_file " , <nl> + help = " Create or update the specified report file upon program " <nl> + " exit . " , <nl> + default = None ) <nl> + <nl> + program_options . add_option ( " - - remotePython " , <nl> + dest = " remote_python " , <nl> + help = " The python intepreter to use on the remote host " <nl> + " [ default : ' % default ' ] . " <nl> + " To be able to use a python virtual environment , " <nl> + " which has already been provisioned on the remote " <nl> + " host , specify something similar to this : " <nl> + " ' source venv / bin / activate ; python ' " , <nl> + default = " python " ) <nl> + <nl> program_options . add_option ( " - - remoteSudo " , <nl> dest = " remote_sudo " , <nl> help = " Use sudo on the remote host for priveleged operations . " <nl> def main ( ) : <nl> action = " store_true " , <nl> default = False ) <nl> <nl> - program_options . add_option ( " - - backupPathBefore " , <nl> - dest = " backup_path_before " , <nl> - help = " Path where the db_path is backed up before crash recovery , " <nl> - " defaults to ' < rootDir > / data - beforerecovery / db ' " , <nl> - default = None ) <nl> - <nl> - program_options . add_option ( " - - backupPathAfter " , <nl> - dest = " backup_path_after " , <nl> - help = " Path where the db_path is backed up after crash recovery , " <nl> - " defaults to ' < rootDir > / data - afterrecovery / db ' " , <nl> - default = None ) <nl> - <nl> program_options . add_option ( " - - rsyncDest " , <nl> dest = " rsync_dest " , <nl> help = optparse . SUPPRESS_HELP , <nl> def main ( ) : <nl> <nl> LOGGER . info ( " powertest . py invocation : % s " , " " . join ( sys . argv ) ) <nl> <nl> + # Command line options override the config file options . <nl> + config_options = None <nl> + if options . config_file : <nl> + with open ( options . config_file ) as ystream : <nl> + config_options = yaml . safe_load ( ystream ) <nl> + LOGGER . info ( " Loading config file % s with options % s " , options . config_file , config_options ) <nl> + # Load the options specified in the config_file <nl> + parser . set_defaults ( * * config_options ) <nl> + options , args = parser . parse_args ( ) <nl> + # Disable this option such that the remote side does not load a config_file . <nl> + options . config_file = None <nl> + config_options [ " config_file " ] = None <nl> + <nl> + if options . save_config_options : <nl> + # Disable this option such that the remote side does not save the config options . <nl> + save_config_options = options . save_config_options <nl> + options . save_config_options = None <nl> + save_options = { } <nl> + for opt_group in parser . option_groups : <nl> + for opt in opt_group . option_list : <nl> + if getattr ( options , opt . dest ) ! = opt . default : <nl> + save_options [ opt . dest ] = getattr ( options , opt . dest ) <nl> + LOGGER . info ( " Config options being saved % s " , save_options ) <nl> + with open ( save_config_options , " w " ) as ystream : <nl> + yaml . safe_dump ( save_options , ystream , default_flow_style = False ) <nl> + sys . exit ( 0 ) <nl> + <nl> script_name = os . path . basename ( __file__ ) <nl> # Print script name and version . <nl> if options . version : <nl> print ( " { } : { } " . format ( script_name , __version__ ) ) <nl> sys . exit ( 0 ) <nl> <nl> + if options . report_json_file : <nl> + _report_json_file = options . report_json_file <nl> + if _report_json_file and os . path . exists ( _report_json_file ) : <nl> + with open ( _report_json_file ) as jstream : <nl> + _report_json = json . load ( jstream ) <nl> + else : <nl> + _report_json = { <nl> + " failures " : 0 , <nl> + " results " : [ <nl> + { " status " : " fail " , <nl> + " test_file " : __name__ , <nl> + " exit_code " : 0 , <nl> + " elapsed " : 0 , <nl> + " start " : int ( time . time ( ) ) , <nl> + " end " : int ( time . time ( ) ) } <nl> + ] <nl> + } <nl> + LOGGER . debug ( " Updating / creating report JSON % s " , _report_json ) <nl> + # Disable this option such that the remote side does not generate report . json <nl> + options . report_json_file = None <nl> + <nl> # Setup the crash options <nl> if ( ( options . crash_method = = " aws_ec2 " or options . crash_method = = " mpower " ) and <nl> options . crash_options is None ) : <nl> def main ( ) : <nl> <nl> if options . rsync_data : <nl> rsync_cmd = " rsync_data " <nl> + backup_path_before = options . backup_path_before <nl> + if not backup_path_before : <nl> + backup_path_before = " { } / data - beforerecovery " . format ( options . root_dir ) <nl> + backup_path_after = options . backup_path_after <nl> + if not backup_path_after : <nl> + backup_path_after = " { } / data - afterrecovery " . format ( options . root_dir ) <nl> else : <nl> rsync_cmd = " " <nl> rsync_opt = " " <nl> def main ( ) : <nl> # remote host ' s invocation of this script . <nl> elif isinstance ( option_value , str ) and re . search ( " \ " | ' | " , option_value ) : <nl> option_value = " ' { } ' " . format ( option_value ) <nl> - # The tuple options need to be changed to a string . <nl> - elif isinstance ( option_value , tuple ) : <nl> + # The tuple , list or set options need to be changed to a string . <nl> + elif isinstance ( option_value , ( tuple , list , set ) ) : <nl> option_value = " " . join ( map ( str , option_value ) ) <nl> client_args = " { } { } { } " . format ( client_args , option . get_opt_string ( ) , option_value ) <nl> <nl> def main ( ) : <nl> <nl> temp_client_files = [ ] <nl> <nl> + validate_canary_local = False <nl> if options . canary and loop_num > 1 : <nl> - canary_opt = " - - docForCanary \ " { } \ " " . format ( canary_doc ) <nl> - validate_canary_cmd = " validate_canary " if options . canary else " " <nl> + if options . canary = = " remote " : <nl> + canary_opt = " - - docForCanary \ " { } \ " " . format ( canary_doc ) <nl> + validate_canary_cmd = " validate_canary " if options . canary else " " <nl> + else : <nl> + validate_canary_local = True <nl> else : <nl> canary_opt = " " <nl> <nl> # Since rsync requires Posix style paths , we do not use os . path . join to <nl> # construct the rsync destination directory . <nl> if rsync_cmd : <nl> - if options . backup_path_before : <nl> - rsync_dest = options . backup_path_before <nl> - else : <nl> - rsync_dest = " { } / data - afterrecovery " . format ( options . root_dir ) <nl> - rsync_opt = " - - rsyncDest { } " . format ( rsync_dest ) <nl> + rsync_opt = " - - rsyncDest { } " . format ( backup_path_before ) <nl> <nl> # Optionally , rsync the pre - recovery database . <nl> # Start monogd on the secret port . <nl> def main ( ) : <nl> if ret : <nl> sys . exit ( ret ) <nl> <nl> + # Optionally validate canary document locally . <nl> + if validate_canary_local : <nl> + mongo = pymongo . MongoClient ( <nl> + * * get_mongo_client_args ( options , host = mongod_host , port = secret_port ) ) <nl> + ret = mongo_validate_canary ( <nl> + mongo , options . db_name , options . collection_name , canary_doc ) <nl> + LOGGER . info ( " Local canary validation : % d " , ret ) <nl> + if ret : <nl> + sys . exit ( ret ) <nl> + <nl> # Optionally , run local validation of collections . <nl> if options . validate_collections = = " local " : <nl> host_port = " { } : { } " . format ( mongod_host , secret_port ) <nl> - new_config_file = NamedTempFile . create ( suffix = " . yml " , dir = " tmp " ) <nl> + new_config_file = NamedTempFile . create ( suffix = " . yml " , directory = " tmp " ) <nl> temp_client_files . append ( new_config_file ) <nl> validation_test_data = { " skipValidationOnNamespaceNotFound " : True } <nl> new_resmoke_config ( with_external_server , new_config_file , validation_test_data ) <nl> - ret , output , _ = resmoke_client ( <nl> + ret , output = resmoke_client ( <nl> mongo_repo_root_dir , <nl> mongo_path , <nl> host_port , <nl> " jstests / hooks / run_validate_collections . js " , <nl> new_config_file ) <nl> - LOGGER . info ( " Collection validation : % d % s " , ret , output ) <nl> + LOGGER . info ( " Local collection validation : % d % s " , ret , output ) <nl> if ret : <nl> sys . exit ( ret ) <nl> <nl> def main ( ) : <nl> # Since rsync requires Posix style paths , we do not use os . path . join to <nl> # construct the rsync destination directory . <nl> if rsync_cmd : <nl> - if options . backup_path_after : <nl> - rsync_dest = options . backup_path_after <nl> - else : <nl> - rsync_dest = " { } / data - afterrecovery " . format ( options . root_dir ) <nl> - rsync_opt = " - - rsyncDest { } " . format ( rsync_dest ) <nl> + rsync_opt = " - - rsyncDest { } " . format ( backup_path_after ) <nl> <nl> # Optionally , rsync the post - recovery database . <nl> # Start monogd on the standard port . <nl> def main ( ) : <nl> " { } " <nl> " { } " <nl> " start_mongod " ) . format ( <nl> - rsync_opt , standard_port , use_replica_set , rsync_cmd ) <nl> + rsync_opt , standard_port , use_replica_set , rsync_cmd ) <nl> ret , output = call_remote_operation ( <nl> local_ops , <nl> options . remote_python , <nl> def main ( ) : <nl> <nl> # Start CRUD clients <nl> host_port = " { } : { } " . format ( mongod_host , standard_port ) <nl> - crud_procs = [ ] <nl> for i in xrange ( options . num_crud_clients ) : <nl> if options . config_crud_client = = with_external_server : <nl> - crud_config_file = NamedTempFile . create ( suffix = " . yml " , dir = " tmp " ) <nl> + crud_config_file = NamedTempFile . create ( suffix = " . yml " , directory = " tmp " ) <nl> crud_test_data [ " collectionName " ] = " { } - { } " . format ( options . collection_name , i ) <nl> new_resmoke_config ( <nl> with_external_server , crud_config_file , crud_test_data , eval_str ) <nl> else : <nl> crud_config_file = options . config_crud_client <nl> - _ , _ , proc = resmoke_client ( <nl> + _ , _ = resmoke_client ( <nl> work_dir = mongo_repo_root_dir , <nl> mongo_path = mongo_path , <nl> host_port = host_port , <nl> def main ( ) : <nl> repeat_num = 100 , <nl> no_wait = True , <nl> log_file = " crud_ { } . log " . format ( i ) ) <nl> - crud_procs . append ( proc ) <nl> <nl> - if crud_procs : <nl> - LOGGER . info ( <nl> - " * * * * Started % d CRUD client ( s ) * * * * " , options . num_crud_clients ) <nl> + if options . num_crud_clients : <nl> + LOGGER . info ( " * * * * Started % d CRUD client ( s ) * * * * " , options . num_crud_clients ) <nl> <nl> # Start FSM clients <nl> - fsm_procs = [ ] <nl> for i in xrange ( options . num_fsm_clients ) : <nl> - fsm_config_file = NamedTempFile . create ( suffix = " . yml " , dir = " tmp " ) <nl> + fsm_config_file = NamedTempFile . create ( suffix = " . yml " , directory = " tmp " ) <nl> fsm_test_data [ " dbNamePrefix " ] = " fsm - { } " . format ( i ) <nl> # Do collection validation only for the first FSM client . <nl> fsm_test_data [ " validateCollections " ] = True if i = = 0 else False <nl> new_resmoke_config ( with_external_server , fsm_config_file , fsm_test_data , eval_str ) <nl> - _ , _ , proc = resmoke_client ( <nl> + _ , _ = resmoke_client ( <nl> work_dir = mongo_repo_root_dir , <nl> mongo_path = mongo_path , <nl> host_port = host_port , <nl> def main ( ) : <nl> repeat_num = 100 , <nl> no_wait = True , <nl> log_file = " fsm_ { } . log " . format ( i ) ) <nl> - fsm_procs . append ( proc ) <nl> <nl> - if fsm_procs : <nl> + if options . num_fsm_clients : <nl> LOGGER . info ( " * * * * Started % d FSM client ( s ) * * * * " , options . num_fsm_clients ) <nl> <nl> # Crash the server . A pre - crash canary document is optionally written to the DB . <nl> def main ( ) : <nl> if options . canary : <nl> canary_doc = { " x " : time . time ( ) } <nl> orig_canary_doc = copy . deepcopy ( canary_doc ) <nl> - mongo_opts = get_mongo_client_args ( options ) <nl> - mongo = pymongo . MongoClient ( host = mongod_host , port = standard_port , * * mongo_opts ) <nl> + mongo = pymongo . MongoClient ( <nl> + * * get_mongo_client_args ( options , host = mongod_host , port = standard_port ) ) <nl> crash_canary [ " function " ] = mongo_insert_canary <nl> crash_canary [ " args " ] = [ <nl> mongo , <nl> def main ( ) : <nl> time . sleep ( 10 ) <nl> <nl> # Kill any running clients and cleanup temporary files . <nl> - kill_processes ( crud_procs + fsm_procs ) <nl> + Processes . kill_all ( ) <nl> for temp_file in temp_client_files : <nl> NamedTempFile . delete ( temp_file ) <nl> <nl> def main ( ) : <nl> if options . crash_method = = " aws_ec2 " : <nl> ec2 = aws_ec2 . AwsEc2 ( ) <nl> ret , aws_status = ec2 . control_instance ( <nl> - mode = " start " , image_id = instance_id , wait_time_secs = 240 , show_progress = True ) <nl> + mode = " start " , image_id = instance_id , wait_time_secs = 600 , show_progress = True ) <nl> LOGGER . info ( " Start instance : % d % s * * * * " , ret , aws_status ) <nl> if ret : <nl> raise Exception ( " Start instance failed : { } " . format ( aws_status ) ) <nl> def main ( ) : <nl> LOGGER . info ( " * * * * Completed test loop % d test time % d seconds * * * * " , loop_num , test_time ) <nl> if loop_num = = options . num_loops or test_time > = options . test_time : <nl> break <nl> + <nl> + _report_json_success = True <nl> sys . exit ( 0 ) <nl> <nl> <nl> | SERVER - 31886 Add powercycle tasks to run on Windows | mongodb/mongo | dcaf6432b7219d57cc5cf0de56b61264b8155e5d | 2017-11-21T18:13:21Z |
mmm a / src / compiler / objective_c_generator_helpers . h <nl> ppp b / src / compiler / objective_c_generator_helpers . h <nl> inline : : grpc : : string LocalImport ( const : : grpc : : string & import ) { <nl> <nl> inline : : grpc : : string FrameworkImport ( const : : grpc : : string & import , <nl> const : : grpc : : string & framework ) { <nl> - / / Flattens the directory structure <nl> + / / Flattens the directory structure : grab the file name only <nl> std : : size_t pos = import . rfind ( " / " ) ; <nl> - : : grpc : : string filename = import . substr ( pos + 1 , import . size ( ) - pos ) ; <nl> - cerr < < filename < < endl ; <nl> + / / If pos is npos , pos + 1 is 0 , which gives us the entire string , <nl> + / / so there ' s no need to check that <nl> + : : grpc : : string filename = import . substr ( pos + 1 , import . size ( ) - ( pos + 1 ) ) ; <nl> return : : grpc : : string ( " # import < " + framework + " / " + filename + " > \ n " ) ; <nl> } <nl> <nl> mmm a / src / compiler / objective_c_plugin . cc <nl> ppp b / src / compiler / objective_c_plugin . cc <nl> inline : : grpc : : string ImportProtoHeaders ( <nl> const : : grpc : : string & framework ) { <nl> : : grpc : : string header = grpc_objective_c_generator : : MessageHeaderName ( dep ) ; <nl> <nl> - / / cerr < < header < < endl ; <nl> if ( ! IsProtobufLibraryBundledProtoFile ( dep ) ) { <nl> if ( framework . empty ( ) ) { <nl> return indent + LocalImport ( header ) ; <nl> class ObjectiveCGrpcGenerator : public grpc : : protobuf : : compiler : : CodeGenerator { <nl> std : : vector < : : grpc : : string > param = <nl> grpc_generator : : tokenize ( * param_str , " = " ) ; <nl> if ( param [ 0 ] = = " generate_for_named_framework " ) { <nl> + if ( param [ 1 ] . empty ( ) ) { <nl> + * error = grpc : : string ( " Name of framework cannot be empty for parameter : " ) + param [ 0 ] ; <nl> + return false ; <nl> + } <nl> framework = param [ 1 ] ; <nl> } <nl> } <nl> | Added some edge case checks | grpc/grpc | 8f3b487838ebb50543185ddef22692d761422e7f | 2019-07-28T20:50:32Z |
mmm a / modules / planning / common / obstacle . h <nl> ppp b / modules / planning / common / obstacle . h <nl> class Obstacle { <nl> const common : : math : : Box2d & PerceptionBoundingBox ( ) const ; <nl> <nl> const prediction : : Trajectory & Trajectory ( ) const ; <nl> + bool has_trajectory ( ) const { return has_trajectory_ ; } <nl> <nl> const perception : : PerceptionObstacle & Perception ( ) const ; <nl> <nl> mmm a / modules / planning / common / path_obstacle . h <nl> ppp b / modules / planning / common / path_obstacle . h <nl> class PathObstacle { <nl> std : : vector < ObjectDecisionType > decisions_ ; <nl> std : : vector < std : : string > decider_tags_ ; <nl> SLBoundary sl_boundary_ ; <nl> + StGraphBoundary st_boundary_ ; <nl> } ; <nl> <nl> } / / namespace planning <nl> mmm a / modules / planning / optimizer / st_graph / st_boundary_mapper . cc <nl> ppp b / modules / planning / optimizer / st_graph / st_boundary_mapper . cc <nl> Status StBoundaryMapper : : GetGraphBoundary ( <nl> if ( path_obstacle - > Decisions ( ) . empty ( ) ) { <nl> const auto ret = <nl> MapObstacleWithoutDecision ( * path_obstacle , st_graph_boundaries ) ; <nl> - if ( ! ret . ok ( ) ) { <nl> + if ( ret . code ( ) = = ErrorCode : : PLANNING_ERROR ) { <nl> std : : string msg = common : : util : : StrCat ( <nl> " Fail to map obstacle " , path_obstacle - > Id ( ) , " without decision . " ) ; <nl> AERROR < < msg ; <nl> Status StBoundaryMapper : : MapObstacleWithoutDecision ( <nl> : Status : : OK ( ) ; <nl> } <nl> <nl> - Status StBoundaryMapper : : MapObstacleWithPredictionTrajectory ( <nl> - const PathObstacle & path_obstacle , const ObjectDecisionType & obj_decision , <nl> - std : : vector < StGraphBoundary > * const boundary ) const { <nl> - std : : vector < STPoint > lower_points ; <nl> - std : : vector < STPoint > upper_points ; <nl> - <nl> - const auto * obstacle = path_obstacle . Obstacle ( ) ; <nl> - const auto & speed = obstacle - > Perception ( ) . velocity ( ) ; <nl> - const double scalar_speed = std : : hypot ( speed . x ( ) , speed . y ( ) ) ; <nl> - const double minimal_follow_time = st_boundary_config_ . minimal_follow_time ( ) ; <nl> - double follow_distance = - 1 . 0 ; <nl> - if ( obj_decision . has_follow ( ) ) { <nl> - follow_distance = std : : fmax ( scalar_speed * minimal_follow_time , <nl> - std : : fabs ( obj_decision . follow ( ) . distance_s ( ) ) ) + <nl> - vehicle_param_ . front_edge_to_center ( ) ; <nl> - } <nl> - <nl> - bool skip = true ; <nl> - std : : vector < STPoint > boundary_points ; <nl> - const auto & adc_path_points = path_data_ . discretized_path ( ) . path_points ( ) ; <nl> - if ( adc_path_points . size ( ) = = 0 ) { <nl> + bool StBoundaryMapper : : GetOverlapBoundaryPoints ( <nl> + const std : : vector < PathPoint > & path_points , const Obstacle & obstacle , <nl> + std : : vector < STPoint > * upper_points , <nl> + std : : vector < STPoint > * lower_points ) const { <nl> + DCHECK_NOTNULL ( upper_points ) ; <nl> + DCHECK_NOTNULL ( lower_points ) ; <nl> + DCHECK ( upper_points - > empty ( ) ) ; <nl> + DCHECK ( lower_points - > empty ( ) ) ; <nl> + DCHECK_GT ( path_points . size ( ) , 0 ) ; <nl> + <nl> + if ( path_points . size ( ) = = 0 ) { <nl> std : : string msg = common : : util : : StrCat ( <nl> " Too few points in path_data_ . discretized_path ( ) ; size = " , <nl> - adc_path_points . size ( ) ) ; <nl> + path_points . size ( ) ) ; <nl> AERROR < < msg ; <nl> - return Status ( ErrorCode : : PLANNING_ERROR , msg ) ; <nl> - } <nl> - const auto & trajectory = obstacle - > Trajectory ( ) ; <nl> - if ( trajectory . trajectory_point_size ( ) = = 0 ) { <nl> - AWARN < < " Obstacle ( id = " < < obstacle - > Id ( ) <nl> - < < " ) has NO prediction trajectory . " ; <nl> + return false ; <nl> } <nl> <nl> + const auto & trajectory = obstacle . Trajectory ( ) ; <nl> for ( int j = 0 ; j < trajectory . trajectory_point_size ( ) ; + + j ) { <nl> const auto & trajectory_point = trajectory . trajectory_point ( j ) ; <nl> double trajectory_point_time = trajectory_point . relative_time ( ) ; <nl> - const Box2d obs_box = obstacle - > GetBoundingBox ( trajectory_point ) ; <nl> + const Box2d obs_box = obstacle . GetBoundingBox ( trajectory_point ) ; <nl> int64_t low = 0 ; <nl> - int64_t high = adc_path_points . size ( ) - 1 ; <nl> + int64_t high = path_points . size ( ) - 1 ; <nl> bool find_low = false ; <nl> bool find_high = false ; <nl> while ( low < high ) { <nl> Status StBoundaryMapper : : MapObstacleWithPredictionTrajectory ( <nl> break ; <nl> } <nl> if ( ! find_low ) { <nl> - if ( ! CheckOverlap ( adc_path_points [ low ] , obs_box , <nl> + if ( ! CheckOverlap ( path_points [ low ] , obs_box , <nl> st_boundary_config_ . boundary_buffer ( ) ) ) { <nl> + + low ; <nl> } else { <nl> Status StBoundaryMapper : : MapObstacleWithPredictionTrajectory ( <nl> } <nl> } <nl> if ( ! find_high ) { <nl> - if ( ! CheckOverlap ( adc_path_points [ high ] , obs_box , <nl> + if ( ! CheckOverlap ( path_points [ high ] , obs_box , <nl> st_boundary_config_ . boundary_buffer ( ) ) ) { <nl> - - high ; <nl> } else { <nl> Status StBoundaryMapper : : MapObstacleWithPredictionTrajectory ( <nl> } <nl> } <nl> if ( find_high & & find_low ) { <nl> - lower_points . emplace_back ( <nl> - adc_path_points [ low ] . s ( ) - st_boundary_config_ . point_extension ( ) , <nl> + lower_points - > emplace_back ( <nl> + path_points [ low ] . s ( ) - st_boundary_config_ . point_extension ( ) , <nl> trajectory_point_time ) ; <nl> - upper_points . emplace_back ( <nl> - adc_path_points [ high ] . s ( ) + st_boundary_config_ . point_extension ( ) , <nl> + upper_points - > emplace_back ( <nl> + path_points [ high ] . s ( ) + st_boundary_config_ . point_extension ( ) , <nl> trajectory_point_time ) ; <nl> - } else { <nl> - if ( obj_decision . has_yield ( ) | | obj_decision . has_overtake ( ) ) { <nl> - AINFO < < " Point [ " < < j < < " ] cannot find low or high index . " ; <nl> - } <nl> } <nl> + } <nl> + DCHECK_EQ ( lower_points - > size ( ) , upper_points - > size ( ) ) ; <nl> + return ( lower_points - > size ( ) > 0 & & upper_points - > size ( ) > 0 ) ; <nl> + } <nl> <nl> - if ( lower_points . size ( ) > 0 ) { <nl> + Status StBoundaryMapper : : MapObstacleWithPredictionTrajectory ( <nl> + const PathObstacle & path_obstacle , const ObjectDecisionType & obj_decision , <nl> + std : : vector < StGraphBoundary > * const boundary ) const { <nl> + std : : vector < STPoint > lower_points ; <nl> + std : : vector < STPoint > upper_points ; <nl> + <nl> + bool skip = true ; <nl> + std : : vector < STPoint > boundary_points ; <nl> + if ( ! GetOverlapBoundaryPoints ( path_data_ . discretized_path ( ) . path_points ( ) , <nl> + * ( path_obstacle . Obstacle ( ) ) , & upper_points , <nl> + & lower_points ) ) { <nl> + return skip ? Status ( ErrorCode : : PLANNING_SKIP , " PLANNING_SKIP " ) <nl> + : Status : : OK ( ) ; <nl> + ; <nl> + <nl> + if ( lower_points . size ( ) > 0 & & upper_points . size ( ) > 0 ) { <nl> boundary_points . clear ( ) ; <nl> const double buffer = st_boundary_config_ . follow_buffer ( ) ; <nl> boundary_points . emplace_back ( lower_points . at ( 0 ) . s ( ) - buffer , <nl> Status StBoundaryMapper : : MapObstacleWithPredictionTrajectory ( <nl> / / change boundary according to obj_decision . <nl> StGraphBoundary : : BoundaryType b_type = <nl> StGraphBoundary : : BoundaryType : : UNKNOWN ; <nl> + double characteristic_length = 0 . 0 ; <nl> if ( obj_decision . has_follow ( ) ) { <nl> - boundary_points . at ( 0 ) . set_s ( boundary_points . at ( 0 ) . s ( ) - <nl> - follow_distance ) ; <nl> - boundary_points . at ( 1 ) . set_s ( boundary_points . at ( 1 ) . s ( ) - <nl> - follow_distance ) ; <nl> + const auto & speed = obstacle - > Perception ( ) . velocity ( ) ; <nl> + const double scalar_speed = std : : hypot ( speed . x ( ) , speed . y ( ) ) ; <nl> + const double minimal_follow_time = <nl> + st_boundary_config_ . minimal_follow_time ( ) ; <nl> + characteristic_length = <nl> + std : : fmax ( scalar_speed * minimal_follow_time , <nl> + std : : fabs ( obj_decision . follow ( ) . distance_s ( ) ) ) + <nl> + vehicle_param_ . front_edge_to_center ( ) ; <nl> + <nl> + boundary_points . at ( 0 ) . set_s ( boundary_points . at ( 0 ) . s ( ) ) ; <nl> + boundary_points . at ( 1 ) . set_s ( boundary_points . at ( 1 ) . s ( ) ) ; <nl> boundary_points . at ( 3 ) . set_t ( - 1 . 0 ) ; <nl> b_type = StGraphBoundary : : BoundaryType : : FOLLOW ; <nl> } else if ( obj_decision . has_yield ( ) ) { <nl> const double dis = std : : fabs ( obj_decision . yield ( ) . distance_s ( ) ) ; <nl> + characteristic_length = dis ; <nl> / / TODO ( all ) : remove the arbitrary numbers in this part . <nl> if ( boundary_points . at ( 0 ) . s ( ) - dis < 0 . 0 ) { <nl> boundary_points . at ( 0 ) . set_s ( <nl> Status StBoundaryMapper : : MapObstacleWithPredictionTrajectory ( <nl> b_type = StGraphBoundary : : BoundaryType : : YIELD ; <nl> } else if ( obj_decision . has_overtake ( ) ) { <nl> const double dis = std : : fabs ( obj_decision . overtake ( ) . distance_s ( ) ) ; <nl> + characteristic_length = dis ; <nl> boundary_points . at ( 2 ) . set_s ( boundary_points . at ( 2 ) . s ( ) + dis ) ; <nl> boundary_points . at ( 3 ) . set_s ( boundary_points . at ( 3 ) . s ( ) + dis ) ; <nl> } <nl> Status StBoundaryMapper : : MapObstacleWithPredictionTrajectory ( <nl> boundary - > emplace_back ( & path_obstacle , boundary_points ) ; <nl> boundary - > back ( ) . SetBoundaryType ( b_type ) ; <nl> boundary - > back ( ) . set_id ( obstacle - > Id ( ) ) ; <nl> + boundary - > back ( ) . SetCharacteristicLength ( characteristic_length ) ; <nl> skip = false ; <nl> } <nl> } <nl> + return skip ? Status ( ErrorCode : : PLANNING_SKIP , " PLANNING_SKIP " ) <nl> + : Status : : OK ( ) ; <nl> } <nl> - return skip ? Status ( ErrorCode : : PLANNING_SKIP , " PLANNING_SKIP " ) <nl> - : Status : : OK ( ) ; <nl> - } <nl> <nl> - Status StBoundaryMapper : : MapFollowDecision ( <nl> - const PathObstacle & path_obstacle , const ObjectDecisionType & obj_decision , <nl> - StGraphBoundary * const boundary ) const { <nl> - if ( ! obj_decision . has_follow ( ) ) { <nl> - std : : string msg = common : : util : : StrCat ( <nl> - " Map obstacle without prediction trajectory is ONLY supported when " <nl> - " the " <nl> - " object decision is follow . The current object decision is : \ n " , <nl> - obj_decision . DebugString ( ) ) ; <nl> - AERROR < < msg ; <nl> - return Status ( ErrorCode : : PLANNING_ERROR , msg ) ; <nl> - } <nl> + Status StBoundaryMapper : : MapFollowDecision ( <nl> + const PathObstacle & path_obstacle , const ObjectDecisionType & obj_decision , <nl> + StGraphBoundary * const boundary ) const { <nl> + if ( ! obj_decision . has_follow ( ) ) { <nl> + std : : string msg = common : : util : : StrCat ( <nl> + " Map obstacle without prediction trajectory is ONLY supported when " <nl> + " the " <nl> + " object decision is follow . The current object decision is : \ n " , <nl> + obj_decision . DebugString ( ) ) ; <nl> + AERROR < < msg ; <nl> + return Status ( ErrorCode : : PLANNING_ERROR , msg ) ; <nl> + } <nl> <nl> - const auto * obstacle = path_obstacle . Obstacle ( ) ; <nl> + const auto * obstacle = path_obstacle . Obstacle ( ) ; <nl> <nl> - const auto & speed = obstacle - > Perception ( ) . velocity ( ) ; <nl> - const double scalar_speed = std : : hypot ( speed . x ( ) , speed . y ( ) ) ; <nl> - <nl> - const auto & perception = obstacle - > Perception ( ) ; <nl> - const PathPoint ref_point = reference_line_ . get_reference_point ( <nl> - perception . position ( ) . x ( ) , perception . position ( ) . y ( ) ) ; <nl> - const double speed_coeff = std : : cos ( perception . theta ( ) - ref_point . theta ( ) ) ; <nl> - if ( speed_coeff < 0 . 0 ) { <nl> - AERROR < < " Obstacle is moving opposite to the reference line . Obstacle : " <nl> - < < perception . DebugString ( ) ; <nl> - return common : : Status ( ErrorCode : : PLANNING_ERROR , <nl> - " obstacle is moving opposite the reference line " ) ; <nl> - } <nl> + const auto & speed = obstacle - > Perception ( ) . velocity ( ) ; <nl> + const double scalar_speed = std : : hypot ( speed . x ( ) , speed . y ( ) ) ; <nl> <nl> - const auto & point = path_data_ . discretized_path ( ) . StartPoint ( ) ; <nl> - const PathPoint curr_point = <nl> - reference_line_ . get_reference_point ( point . x ( ) , point . y ( ) ) ; <nl> - const double distance_to_obstacle = ref_point . s ( ) - curr_point . s ( ) - <nl> - vehicle_param_ . front_edge_to_center ( ) - <nl> - st_boundary_config_ . follow_buffer ( ) ; <nl> - <nl> - if ( distance_to_obstacle > planning_distance_ ) { <nl> - std : : string msg = " obstacle is out of range . " ; <nl> - AINFO < < msg ; <nl> - return Status ( ErrorCode : : PLANNING_SKIP , msg ) ; <nl> - } <nl> + const auto & perception = obstacle - > Perception ( ) ; <nl> + const PathPoint ref_point = reference_line_ . get_reference_point ( <nl> + perception . position ( ) . x ( ) , perception . position ( ) . y ( ) ) ; <nl> + const double speed_coeff = std : : cos ( perception . theta ( ) - ref_point . theta ( ) ) ; <nl> + if ( speed_coeff < 0 . 0 ) { <nl> + AERROR < < " Obstacle is moving opposite to the reference line . Obstacle : " <nl> + < < perception . DebugString ( ) ; <nl> + return common : : Status ( ErrorCode : : PLANNING_ERROR , <nl> + " obstacle is moving opposite the reference line " ) ; <nl> + } <nl> <nl> - double follow_speed = 0 . 0 ; <nl> - if ( scalar_speed > st_boundary_config_ . follow_speed_threshold ( ) ) { <nl> - follow_speed = st_boundary_config_ . follow_speed_threshold ( ) * speed_coeff ; <nl> - } else { <nl> - follow_speed = scalar_speed * speed_coeff * <nl> - st_boundary_config_ . follow_speed_damping_factor ( ) ; <nl> - } <nl> + const auto & point = path_data_ . discretized_path ( ) . StartPoint ( ) ; <nl> + const PathPoint curr_point = <nl> + reference_line_ . get_reference_point ( point . x ( ) , point . y ( ) ) ; <nl> + const double distance_to_obstacle = ref_point . s ( ) - curr_point . s ( ) - <nl> + vehicle_param_ . front_edge_to_center ( ) - <nl> + st_boundary_config_ . follow_buffer ( ) ; <nl> + <nl> + if ( distance_to_obstacle > planning_distance_ ) { <nl> + std : : string msg = " obstacle is out of range . " ; <nl> + AINFO < < msg ; <nl> + return Status ( ErrorCode : : PLANNING_SKIP , msg ) ; <nl> + } <nl> <nl> - const double s_min_lower = distance_to_obstacle ; <nl> - const double s_min_upper = <nl> - std : : max ( distance_to_obstacle + 1 . 0 , planning_distance_ ) ; <nl> - const double s_max_upper = <nl> - std : : max ( s_min_upper + planning_time_ * follow_speed , planning_distance_ ) ; <nl> - const double s_max_lower = s_min_lower + planning_time_ * follow_speed ; <nl> + double follow_speed = 0 . 0 ; <nl> + if ( scalar_speed > st_boundary_config_ . follow_speed_threshold ( ) ) { <nl> + follow_speed = st_boundary_config_ . follow_speed_threshold ( ) * speed_coeff ; <nl> + } else { <nl> + follow_speed = scalar_speed * speed_coeff * <nl> + st_boundary_config_ . follow_speed_damping_factor ( ) ; <nl> + } <nl> <nl> - std : : vector < STPoint > boundary_points ; <nl> - boundary_points . emplace_back ( s_min_lower , 0 . 0 ) ; <nl> - boundary_points . emplace_back ( s_max_lower , planning_time_ ) ; <nl> - boundary_points . emplace_back ( s_max_upper , planning_time_ ) ; <nl> - boundary_points . emplace_back ( s_min_upper , 0 . 0 ) ; <nl> - <nl> - const double area = GetArea ( boundary_points ) ; <nl> - if ( Double : : Compare ( area , 0 . 0 ) < = 0 ) { <nl> - std : : string msg = " Do not need to map because area is zero . " ; <nl> - AINFO < < msg ; <nl> - return Status ( ErrorCode : : PLANNING_SKIP , msg ) ; <nl> - } <nl> - * boundary = StGraphBoundary ( & path_obstacle , boundary_points ) ; <nl> - <nl> - const double characteristic_length = <nl> - std : : fmax ( scalar_speed * speed_coeff * <nl> - st_boundary_config_ . minimal_follow_time ( ) , <nl> - std : : fabs ( obj_decision . follow ( ) . distance_s ( ) ) ) + <nl> - vehicle_param_ . front_edge_to_center ( ) + <nl> - st_boundary_config_ . follow_buffer ( ) ; <nl> - <nl> - boundary - > SetCharacteristicLength ( characteristic_length * <nl> - st_boundary_config_ . follow_coeff ( ) ) ; <nl> - boundary - > SetBoundaryType ( StGraphBoundary : : BoundaryType : : FOLLOW ) ; <nl> - boundary - > set_id ( obstacle - > Id ( ) ) ; <nl> - return Status : : OK ( ) ; <nl> - } <nl> + const double s_min_lower = distance_to_obstacle ; <nl> + const double s_min_upper = <nl> + std : : max ( distance_to_obstacle + 1 . 0 , planning_distance_ ) ; <nl> + const double s_max_upper = std : : max ( <nl> + s_min_upper + planning_time_ * follow_speed , planning_distance_ ) ; <nl> + const double s_max_lower = s_min_lower + planning_time_ * follow_speed ; <nl> <nl> - double StBoundaryMapper : : GetArea ( <nl> - const std : : vector < STPoint > & boundary_points ) const { <nl> - if ( boundary_points . size ( ) < 3 ) { <nl> - return 0 . 0 ; <nl> + std : : vector < STPoint > boundary_points ; <nl> + boundary_points . emplace_back ( s_min_lower , 0 . 0 ) ; <nl> + boundary_points . emplace_back ( s_max_lower , planning_time_ ) ; <nl> + boundary_points . emplace_back ( s_max_upper , planning_time_ ) ; <nl> + boundary_points . emplace_back ( s_min_upper , 0 . 0 ) ; <nl> + <nl> + const double area = GetArea ( boundary_points ) ; <nl> + if ( Double : : Compare ( area , 0 . 0 ) < = 0 ) { <nl> + std : : string msg = " Do not need to map because area is zero . " ; <nl> + AINFO < < msg ; <nl> + return Status ( ErrorCode : : PLANNING_SKIP , msg ) ; <nl> + } <nl> + * boundary = StGraphBoundary ( & path_obstacle , boundary_points ) ; <nl> + <nl> + const double characteristic_length = <nl> + std : : fmax ( scalar_speed * speed_coeff * <nl> + st_boundary_config_ . minimal_follow_time ( ) , <nl> + std : : fabs ( obj_decision . follow ( ) . distance_s ( ) ) ) + <nl> + vehicle_param_ . front_edge_to_center ( ) + <nl> + st_boundary_config_ . follow_buffer ( ) ; <nl> + <nl> + boundary - > SetCharacteristicLength ( characteristic_length * <nl> + st_boundary_config_ . follow_coeff ( ) ) ; <nl> + boundary - > SetBoundaryType ( StGraphBoundary : : BoundaryType : : FOLLOW ) ; <nl> + boundary - > set_id ( obstacle - > Id ( ) ) ; <nl> + return Status : : OK ( ) ; <nl> } <nl> <nl> - double area = 0 . 0 ; <nl> - for ( uint32_t i = 2 ; i < boundary_points . size ( ) ; + + i ) { <nl> - const double ds1 = boundary_points [ i - 1 ] . s ( ) - boundary_points [ 0 ] . s ( ) ; <nl> - const double dt1 = boundary_points [ i - 1 ] . t ( ) - boundary_points [ 0 ] . t ( ) ; <nl> + double StBoundaryMapper : : GetArea ( const std : : vector < STPoint > & boundary_points ) <nl> + const { <nl> + if ( boundary_points . size ( ) < 3 ) { <nl> + return 0 . 0 ; <nl> + } <nl> + <nl> + double area = 0 . 0 ; <nl> + for ( uint32_t i = 2 ; i < boundary_points . size ( ) ; + + i ) { <nl> + const double ds1 = boundary_points [ i - 1 ] . s ( ) - boundary_points [ 0 ] . s ( ) ; <nl> + const double dt1 = boundary_points [ i - 1 ] . t ( ) - boundary_points [ 0 ] . t ( ) ; <nl> <nl> - const double ds2 = boundary_points [ i ] . s ( ) - boundary_points [ 0 ] . s ( ) ; <nl> - const double dt2 = boundary_points [ i ] . t ( ) - boundary_points [ 0 ] . t ( ) ; <nl> - / / cross product <nl> - area + = ( ds1 * dt2 - ds2 * dt1 ) ; <nl> + const double ds2 = boundary_points [ i ] . s ( ) - boundary_points [ 0 ] . s ( ) ; <nl> + const double dt2 = boundary_points [ i ] . t ( ) - boundary_points [ 0 ] . t ( ) ; <nl> + / / cross product <nl> + area + = ( ds1 * dt2 - ds2 * dt1 ) ; <nl> + } <nl> + return fabs ( area * 0 . 5 ) ; <nl> } <nl> - return fabs ( area * 0 . 5 ) ; <nl> - } <nl> <nl> - bool StBoundaryMapper : : CheckOverlap ( const PathPoint & path_point , <nl> - const Box2d & obs_box , <nl> - const double buffer ) const { <nl> - const double mid_to_rear_center = <nl> - vehicle_param_ . length ( ) / 2 . 0 - vehicle_param_ . front_edge_to_center ( ) ; <nl> - const double x = <nl> - path_point . x ( ) - mid_to_rear_center * std : : cos ( path_point . theta ( ) ) ; <nl> - const double y = <nl> - path_point . y ( ) - mid_to_rear_center * std : : sin ( path_point . theta ( ) ) ; <nl> - const Box2d adc_box = <nl> - Box2d ( { x , y } , path_point . theta ( ) , vehicle_param_ . length ( ) + 2 * buffer , <nl> - vehicle_param_ . width ( ) + 2 * buffer ) ; <nl> - return obs_box . HasOverlap ( adc_box ) ; <nl> - } <nl> + bool StBoundaryMapper : : CheckOverlap ( const PathPoint & path_point , <nl> + const Box2d & obs_box , const double buffer ) <nl> + const { <nl> + const double mid_to_rear_center = <nl> + vehicle_param_ . length ( ) / 2 . 0 - vehicle_param_ . front_edge_to_center ( ) ; <nl> + const double x = <nl> + path_point . x ( ) - mid_to_rear_center * std : : cos ( path_point . theta ( ) ) ; <nl> + const double y = <nl> + path_point . y ( ) - mid_to_rear_center * std : : sin ( path_point . theta ( ) ) ; <nl> + const Box2d adc_box = <nl> + Box2d ( { x , y } , path_point . theta ( ) , vehicle_param_ . length ( ) + 2 * buffer , <nl> + vehicle_param_ . width ( ) + 2 * buffer ) ; <nl> + return obs_box . HasOverlap ( adc_box ) ; <nl> + } <nl> <nl> - Status StBoundaryMapper : : GetSpeedLimits ( <nl> - SpeedLimit * const speed_limit_data ) const { <nl> - CHECK_NOTNULL ( speed_limit_data ) ; <nl> + Status StBoundaryMapper : : GetSpeedLimits ( SpeedLimit * const speed_limit_data ) <nl> + const { <nl> + CHECK_NOTNULL ( speed_limit_data ) ; <nl> <nl> - std : : vector < double > speed_limits ; <nl> - for ( const auto & path_point : path_data_ . discretized_path ( ) . path_points ( ) ) { <nl> - if ( Double : : Compare ( path_point . s ( ) , reference_line_ . length ( ) ) > 0 ) { <nl> - std : : string msg = common : : util : : StrCat ( <nl> - " path length [ " , path_data_ . discretized_path ( ) . Length ( ) , <nl> - " ] is LARGER than reference_line_ length [ " , reference_line_ . length ( ) , <nl> - " ] . Please debug before proceeding . " ) ; <nl> - AWARN < < msg ; <nl> - break ; <nl> - } <nl> + std : : vector < double > speed_limits ; <nl> + for ( const auto & path_point : path_data_ . discretized_path ( ) . path_points ( ) ) { <nl> + if ( Double : : Compare ( path_point . s ( ) , reference_line_ . length ( ) ) > 0 ) { <nl> + std : : string msg = common : : util : : StrCat ( <nl> + " path length [ " , path_data_ . discretized_path ( ) . Length ( ) , <nl> + " ] is LARGER than reference_line_ length [ " , <nl> + reference_line_ . length ( ) , " ] . Please debug before proceeding . " ) ; <nl> + AWARN < < msg ; <nl> + break ; <nl> + } <nl> <nl> - double speed_limit_on_reference_line = <nl> - reference_line_ . GetSpeedLimitFromS ( path_point . s ( ) ) ; <nl> + double speed_limit_on_reference_line = <nl> + reference_line_ . GetSpeedLimitFromS ( path_point . s ( ) ) ; <nl> <nl> - / / speed limit from path curvature <nl> - double speed_limit_on_path = <nl> - std : : sqrt ( st_boundary_config_ . centric_acceleration_limit ( ) / <nl> - std : : fmax ( std : : fabs ( path_point . kappa ( ) ) , <nl> - st_boundary_config_ . minimal_kappa ( ) ) ) ; <nl> + / / speed limit from path curvature <nl> + double speed_limit_on_path = <nl> + std : : sqrt ( st_boundary_config_ . centric_acceleration_limit ( ) / <nl> + std : : fmax ( std : : fabs ( path_point . kappa ( ) ) , <nl> + st_boundary_config_ . minimal_kappa ( ) ) ) ; <nl> <nl> - const double curr_speed_limit = std : : fmax ( <nl> - st_boundary_config_ . lowest_speed ( ) , <nl> - std : : fmin ( speed_limit_on_path , speed_limit_on_reference_line ) ) ; <nl> + const double curr_speed_limit = std : : fmax ( <nl> + st_boundary_config_ . lowest_speed ( ) , <nl> + std : : fmin ( speed_limit_on_path , speed_limit_on_reference_line ) ) ; <nl> <nl> - speed_limit_data - > AddSpeedLimit ( path_point . s ( ) , curr_speed_limit ) ; <nl> + speed_limit_data - > AddSpeedLimit ( path_point . s ( ) , curr_speed_limit ) ; <nl> + } <nl> + return Status : : OK ( ) ; <nl> } <nl> - return Status : : OK ( ) ; <nl> - } <nl> <nl> } / / namespace planning <nl> } / / namespace apollo <nl> mmm a / modules / planning / optimizer / st_graph / st_boundary_mapper . h <nl> ppp b / modules / planning / optimizer / st_graph / st_boundary_mapper . h <nl> class StBoundaryMapper { <nl> <nl> double GetArea ( const std : : vector < STPoint > & boundary_points ) const ; <nl> <nl> + bool GetOverlapBoundaryPoints ( <nl> + const std : : vector < apollo : : common : : PathPoint > & path_points , <nl> + const Obstacle & obstacle , std : : vector < STPoint > * upper_points , <nl> + std : : vector < STPoint > * lower_points ) const ; <nl> + <nl> apollo : : common : : Status MapObstacleWithoutDecision ( <nl> const PathObstacle & path_obstacle , <nl> std : : vector < StGraphBoundary > * const boundary ) const ; <nl> mmm a / modules / planning / optimizer / st_graph / st_graph_boundary . h <nl> ppp b / modules / planning / optimizer / st_graph / st_graph_boundary . h <nl> class StGraphBoundary : public common : : math : : Polygon2d { <nl> <nl> ~ StGraphBoundary ( ) = default ; <nl> <nl> + bool IsEmpty ( ) const { return points . empty ( ) ; } <nl> bool IsPointInBoundary ( const StGraphPoint & st_graph_point ) const ; <nl> bool IsPointInBoundary ( const STPoint & st_point ) const ; <nl> <nl> | Planning : allow empty st_graph_boundary ; do not return error when no mapping of obstacle . abstract redundant code to seperate function . | ApolloAuto/apollo | 4286eaa6048b4f0ae0330acc9d943e15263508eb | 2017-08-11T21:57:53Z |
mmm a / examples / CMakeLists . txt <nl> ppp b / examples / CMakeLists . txt <nl> target_link_libraries ( mobilenetssd ncnn $ { OpenCV_LIBS } ) <nl> <nl> add_executable ( squeezenetssd squeezenetssd . cpp ) <nl> target_link_libraries ( squeezenetssd ncnn $ { OpenCV_LIBS } ) <nl> + <nl> + add_executable ( shufflenetv2 shufflenetv2 . cpp ) <nl> + target_link_libraries ( shufflenetv2 ncnn $ { OpenCV_LIBS } ) <nl> new file mode 100644 <nl> index 0000000000 . . 6823e41016 <nl> mmm / dev / null <nl> ppp b / examples / shufflenetv2 . cpp <nl> <nl> + / / Tencent is pleased to support the open source community by making ncnn available . <nl> + / / <nl> + / / Copyright ( C ) 2018 THL A29 Limited , a Tencent company . All rights reserved . <nl> + / / <nl> + / / Licensed under the BSD 3 - Clause License ( the " License " ) ; you may not use this file except <nl> + / / in compliance with the License . You may obtain a copy of the License at <nl> + / / <nl> + / / https : / / opensource . org / licenses / BSD - 3 - Clause <nl> + / / <nl> + / / Unless required by applicable law or agreed to in writing , software distributed <nl> + / / under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR <nl> + / / CONDITIONS OF ANY KIND , either express or implied . See the License for the <nl> + / / specific language governing permissions and limitations under the License . <nl> + <nl> + # include < stdio . h > <nl> + # include < algorithm > <nl> + # include < vector > <nl> + # include < opencv2 / core / core . hpp > <nl> + # include < opencv2 / highgui / highgui . hpp > <nl> + <nl> + # include " net . h " <nl> + <nl> + static int detect_shufflenetv2 ( const cv : : Mat & bgr , std : : vector < float > & cls_scores ) <nl> + { <nl> + ncnn : : Net shufflenetv2 ; <nl> + <nl> + / / https : / / github . com / miaow1988 / ShuffleNet_V2_pytorch_caffe <nl> + / / models can be downloaded from https : / / github . com / miaow1988 / ShuffleNet_V2_pytorch_caffe / releases <nl> + shufflenetv2 . load_param ( " shufflenet_v2_x0 . 5 . param " ) ; <nl> + shufflenetv2 . load_model ( " shufflenet_v2_x0 . 5 . bin " ) ; <nl> + <nl> + ncnn : : Mat in = ncnn : : Mat : : from_pixels_resize ( bgr . data , ncnn : : Mat : : PIXEL_BGR , bgr . cols , bgr . rows , 224 , 224 ) ; <nl> + <nl> + const float norm_vals [ 3 ] = { 1 / 255 . f , 1 / 255 . f , 1 / 255 . f } ; <nl> + in . substract_mean_normalize ( 0 , norm_vals ) ; <nl> + <nl> + ncnn : : Extractor ex = shufflenetv2 . create_extractor ( ) ; <nl> + <nl> + ex . input ( " data " , in ) ; <nl> + <nl> + ncnn : : Mat out ; <nl> + ex . extract ( " fc " , out ) ; <nl> + <nl> + / / manually call softmax on the fc output <nl> + / / convert result into probability <nl> + / / skip if your model already has softmax operation <nl> + { <nl> + ncnn : : Layer * softmax = ncnn : : create_layer ( " Softmax " ) ; <nl> + <nl> + ncnn : : ParamDict pd ; <nl> + softmax - > load_param ( pd ) ; <nl> + <nl> + softmax - > forward_inplace ( out ) ; <nl> + <nl> + delete softmax ; <nl> + } <nl> + <nl> + out = out . reshape ( out . w * out . h * out . c ) ; <nl> + <nl> + cls_scores . resize ( out . w ) ; <nl> + for ( int j = 0 ; j < out . w ; j + + ) <nl> + { <nl> + cls_scores [ j ] = out [ j ] ; <nl> + } <nl> + <nl> + return 0 ; <nl> + } <nl> + <nl> + static int print_topk ( const std : : vector < float > & cls_scores , int topk ) <nl> + { <nl> + / / partial sort topk with index <nl> + int size = cls_scores . size ( ) ; <nl> + std : : vector < std : : pair < float , int > > vec ; <nl> + vec . resize ( size ) ; <nl> + for ( int i = 0 ; i < size ; i + + ) <nl> + { <nl> + vec [ i ] = std : : make_pair ( cls_scores [ i ] , i ) ; <nl> + } <nl> + <nl> + std : : partial_sort ( vec . begin ( ) , vec . begin ( ) + topk , vec . end ( ) , <nl> + std : : greater < std : : pair < float , int > > ( ) ) ; <nl> + <nl> + / / print topk and score <nl> + for ( int i = 0 ; i < topk ; i + + ) <nl> + { <nl> + float score = vec [ i ] . first ; <nl> + int index = vec [ i ] . second ; <nl> + fprintf ( stderr , " % d = % f \ n " , index , score ) ; <nl> + } <nl> + <nl> + return 0 ; <nl> + } <nl> + <nl> + int main ( int argc , char * * argv ) <nl> + { <nl> + if ( argc ! = 2 ) <nl> + { <nl> + fprintf ( stderr , " Usage : % s [ imagepath ] \ n " , argv [ 0 ] ) ; <nl> + return - 1 ; <nl> + } <nl> + <nl> + const char * imagepath = argv [ 1 ] ; <nl> + <nl> + cv : : Mat m = cv : : imread ( imagepath , CV_LOAD_IMAGE_COLOR ) ; <nl> + if ( m . empty ( ) ) <nl> + { <nl> + fprintf ( stderr , " cv : : imread % s failed \ n " , imagepath ) ; <nl> + return - 1 ; <nl> + } <nl> + <nl> + std : : vector < float > cls_scores ; <nl> + detect_shufflenetv2 ( m , cls_scores ) ; <nl> + <nl> + print_topk ( cls_scores , 3 ) ; <nl> + <nl> + return 0 ; <nl> + } <nl> | shufflenetv2 example | Tencent/ncnn | e6bbb17821284fe64ae4009e7bc203fd690f6617 | 2018-12-10T08:29:03Z |
mmm a / googletest / include / gtest / gtest - typed - test . h <nl> ppp b / googletest / include / gtest / gtest - typed - test . h <nl> INSTANTIATE_TYPED_TEST_CASE_P ( My , FooTest , MyTypes ) ; <nl> namespace GTEST_CASE_NAMESPACE_ ( CaseName ) { \ <nl> typedef : : testing : : internal : : Templates < __VA_ARGS__ > : : type gtest_AllTests_ ; \ <nl> } \ <nl> - static const char * const GTEST_REGISTERED_TEST_NAMES_ ( CaseName ) = \ <nl> - GTEST_TYPED_TEST_CASE_P_STATE_ ( CaseName ) . VerifyRegisteredTestNames ( \ <nl> - __FILE__ , __LINE__ , # __VA_ARGS__ ) <nl> + static const char * const GTEST_REGISTERED_TEST_NAMES_ ( CaseName ) \ <nl> + GTEST_ATTRIBUTE_UNUSED = \ <nl> + GTEST_TYPED_TEST_CASE_P_STATE_ ( CaseName ) . VerifyRegisteredTestNames ( \ <nl> + __FILE__ , __LINE__ , # __VA_ARGS__ ) <nl> <nl> / / The ' Types ' template argument below must have spaces around it <nl> / / since some compilers may choke on ' > > ' when passing a template <nl> | Add GTEST_ATTRIBUTE_UNUSED_ to REGISTER_TYPED_TEST_CASE_P | google/googletest | 06a81e9357b6e5cf023ac65b7468191cd1949d42 | 2017-01-10T00:02:55Z |
mmm a / docs / RELEASE_NOTES . md <nl> ppp b / docs / RELEASE_NOTES . md <nl> Please refer to this document : [ ReadMe ] ( . . / README . md ) <nl> * Device : added ` setKeepScreenOn ( ) ` on iOS and Android <nl> * Added c + + 11 random support <nl> * RenderTexture : added a call back function for ` saveToFile ( ) ` <nl> + * Primitive : Support Points , Lines and Triagles for rendering <nl> * SpriteFrameCache : support loading from plist file content data <nl> * Many other small features added and many bugs fixed <nl> <nl> renderTexture - > saveToFile ( " myFile . png " , true , callback ) ; <nl> <nl> ` ` ` <nl> <nl> + # # Primitive <nl> + <nl> + ` Primitive ` is added to support ` Points ` , ` Lines ` , ` Triangles ` rendering . Previously , if we want to draw a custom geometry ( sphere , line ) , we can only do this by using ` CustomCommand ` . Now , what is need is to create a Primitive , set datas , and use the corresponding ` PrimitiveCommand ` to draw the Primitive . <nl> + <nl> + Here is a simple example of rendering a quad in ` Sprite ` . <nl> + <nl> + 1 . create verexBuffer <nl> + <nl> + ` ` ` c + + <nl> + auto vertexBuffer = VerexBuffer : : create ( sizeof ( V3F_C4B_T2F ) , 4 ) ; <nl> + vertexBuffer - > updateVertices ( & _quad , 4 , 0 ) ; <nl> + ` ` ` <nl> + <nl> + 2 . create vertexData <nl> + <nl> + ` ` ` c + + <nl> + auto vertexData = VertexData : : create ( ) ; <nl> + vertexData - > addStream ( vertexBuffer , VertexStreamAttribute ( 0 , VERTEX_ATTRIB_POSITION , GL_FLOAT , 3 , fasle ) ) ; <nl> + vertexData - > addStream ( vertexBuffer , VertexStreamAttribute ( 12 , VERTEX_ATTRIB_COLOR , GL_UNSIGNED_BTYE , 4 , true ) ) ; <nl> + vertexData - > addStream ( vertexBuffer , VertexStreamAttribute ( 16 , VERTEX_ATTRIB_TEX_COORD , GL_FLOAT , 2 , fasle ) ) ; <nl> + ` ` ` <nl> + 3 . create IndexBuffer <nl> + <nl> + ` ` ` c + + <nl> + auto indexBuffer = IndexBuffer : : create ( IndexType : : INDEX_TYPE_SHORT_16 , 6 ) ; <nl> + short indices [ 6 ] = { 0 , 1 , 2 , 3 , 2 , 1 } ; <nl> + indexBuffer - > updateIndices ( indices , 6 , 0 ) ; <nl> + ` ` ` <nl> + 4 . create primitive <nl> + <nl> + ` ` ` c + + <nl> + auto primitve = Primitive : : create ( vertexData , indexBuffer , GL_TRIANGLES ) ; <nl> + primitive - > setStart ( 0 ) ; <nl> + primitive - > setCount ( 6 ) ; <nl> + ` ` ` <nl> + 5 . add command to renderer <nl> + <nl> + ` ` ` c + + <nl> + _command - > init ( globalZorder , textureID , glprogramState , blend , primitve , modelViewMatrix ) ; <nl> + renderer - > addCommand ( & _command ) ; <nl> + ` ` ` <nl> + <nl> + Primitive supports three typs of primitives ( POINTS , LINES , TRIANGLES ) , vertex and index sharing , multiple streams . It has some constrains : <nl> + <nl> + 1 . The size of vertex and index Buffer is fixed , which means data must be pre allocated . <nl> + 2 . Batching is not supported . <nl> | Merge pull request from dabingnn / v3_PrimitiveReleaseNots | cocos2d/cocos2d-x | c9c0591293e66999d45d339e41bcac90589a7b13 | 2014-08-23T07:32:17Z |
mmm a / atom / browser / api / event_emitter . h <nl> ppp b / atom / browser / api / event_emitter . h <nl> class EventEmitter : public Wrappable { <nl> content : : WebContents * sender , <nl> IPC : : Message * message , <nl> const Args & . . . args ) { <nl> + v8 : : Locker locker ( isolate ( ) ) ; <nl> + v8 : : HandleScope handle_scope ( isolate ( ) ) ; <nl> v8 : : Local < v8 : : Object > event = CreateJSEvent ( isolate ( ) , sender , message ) ; <nl> return EmitWithEvent ( name , event , args . . . ) ; <nl> } <nl> mmm a / atom / browser / lib / objects - registry . coffee <nl> ppp b / atom / browser / lib / objects - registry . coffee <nl> <nl> EventEmitter = require ( ' events ' ) . EventEmitter <nl> - IDWeakMap = process . atomBinding ( ' id_weak_map ' ) . IDWeakMap <nl> v8Util = process . atomBinding ' v8_util ' <nl> <nl> - # Class to reference all objects . <nl> - class ObjectsStore <nl> - @ stores = { } <nl> - <nl> - constructor : - > <nl> - @ nextId = 0 <nl> - @ objects = [ ] <nl> - <nl> - getNextId : - > <nl> - + + @ nextId <nl> - <nl> - add : ( obj ) - > <nl> - id = @ getNextId ( ) <nl> - @ objects [ id ] = obj <nl> - id <nl> - <nl> - has : ( id ) - > <nl> - @ objects [ id ] ? <nl> - <nl> - remove : ( id ) - > <nl> - throw new Error ( " Invalid key # { id } for ObjectsStore " ) unless @ has id <nl> - delete @ objects [ id ] <nl> - <nl> - get : ( id ) - > <nl> - throw new Error ( " Invalid key # { id } for ObjectsStore " ) unless @ has id <nl> - @ objects [ id ] <nl> - <nl> - @ forRenderView : ( key ) - > <nl> - @ stores [ key ] = new ObjectsStore unless @ stores [ key ] ? <nl> - @ stores [ key ] <nl> - <nl> - @ releaseForRenderView : ( key ) - > <nl> - delete @ stores [ key ] <nl> - <nl> class ObjectsRegistry extends EventEmitter <nl> constructor : - > <nl> @ setMaxListeners Number . MAX_VALUE <nl> + @ nextId = 0 <nl> + <nl> + # Stores all objects by ref - counting . <nl> + # ( id ) = > { object , count } <nl> + @ storage = { } <nl> <nl> - # Objects in weak map will be not referenced ( so we won ' t leak memory ) , and <nl> - # every object created in browser will have a unique id in weak map . <nl> - @ objectsWeakMap = new IDWeakMap <nl> - @ objectsWeakMap . add = ( obj ) - > <nl> - id = IDWeakMap : : add . call this , obj <nl> - v8Util . setHiddenValue obj , ' atomId ' , id <nl> - id <nl> + # Stores the IDs of objects referenced by WebContents . <nl> + # ( webContentsId ) = > { ( id ) = > ( count ) } <nl> + @ owners = { } <nl> <nl> # Register a new object , the object would be kept referenced until you release <nl> # it explicitly . <nl> - add : ( key , obj ) - > <nl> - # Some native objects may already been added to objectsWeakMap , be care not <nl> - # to add it twice . <nl> - @ objectsWeakMap . add obj unless v8Util . getHiddenValue obj , ' atomId ' <nl> - id = v8Util . getHiddenValue obj , ' atomId ' <nl> - <nl> - # Store and reference the object , then return the storeId which points to <nl> - # where the object is stored . The caller can later dereference the object <nl> - # with the storeId . <nl> - # We use a difference key because the same object can be referenced for <nl> - # multiple times by the same renderer view . <nl> - store = ObjectsStore . forRenderView key <nl> - storeId = store . add obj <nl> - <nl> - [ id , storeId ] <nl> + add : ( webContentsId , obj ) - > <nl> + id = @ saveToStorage obj <nl> + # Remember the owner . <nl> + @ owners [ webContentsId ] ? = { } <nl> + @ owners [ webContentsId ] [ id ] ? = 0 <nl> + @ owners [ webContentsId ] [ id ] + + <nl> + # Returns object ' s id <nl> + id <nl> <nl> - # Get an object according to its id . <nl> + # Get an object according to its ID . <nl> get : ( id ) - > <nl> - @ objectsWeakMap . get id <nl> - <nl> - # Remove an object according to its storeId . <nl> - remove : ( key , storeId ) - > <nl> - ObjectsStore . forRenderView ( key ) . remove storeId <nl> + @ storage [ id ] ? . object <nl> + <nl> + # Dereference an object according to its ID . <nl> + remove : ( webContentsId , id ) - > <nl> + @ dereference id , 1 <nl> + # Also reduce the count in owner . <nl> + pointer = @ owners [ webContentsId ] <nl> + - - pointer [ id ] <nl> + delete pointer [ id ] if pointer [ id ] is 0 <nl> + <nl> + # Clear all references to objects refrenced by the WebContents . <nl> + clear : ( webContentsId ) - > <nl> + @ emit " clear - # { webContentsId } " <nl> + return unless @ owners [ webContentsId ] ? <nl> + @ dereference id , count for id , count of @ owners [ webContentsId ] <nl> + delete @ owners [ webContentsId ] <nl> + <nl> + # Private : Saves the object into storage and assigns an ID for it . <nl> + saveToStorage : ( object ) - > <nl> + id = v8Util . getHiddenValue object , ' atomId ' <nl> + unless id <nl> + id = + + @ nextId <nl> + @ storage [ id ] = { count : 0 , object } <nl> + v8Util . setHiddenValue object , ' atomId ' , id <nl> + + + @ storage [ id ] . count <nl> + id <nl> <nl> - # Clear all references to objects from renderer view . <nl> - clear : ( key ) - > <nl> - @ emit " clear - # { key } " <nl> - ObjectsStore . releaseForRenderView key <nl> + # Private : Dereference the object from store . <nl> + dereference : ( id , count ) - > <nl> + pointer = @ storage [ id ] <nl> + pointer . count - = count <nl> + if pointer . count is 0 <nl> + v8Util . deleteHiddenValue pointer . object , ' atomId ' <nl> + delete @ storage [ id ] <nl> <nl> module . exports = new ObjectsRegistry <nl> mmm a / atom / browser / lib / rpc - server . coffee <nl> ppp b / atom / browser / lib / rpc - server . coffee <nl> objectsRegistry = require ' . / objects - registry . js ' <nl> v8Util = process . atomBinding ' v8_util ' <nl> <nl> # Convert a real value into meta data . <nl> - valueToMeta = ( sender , value ) - > <nl> + valueToMeta = ( sender , value , optimizeSimpleObject = false ) - > <nl> meta = type : typeof value <nl> <nl> meta . type = ' buffer ' if Buffer . isBuffer value <nl> valueToMeta = ( sender , value ) - > <nl> meta . type = ' array ' if Array . isArray value <nl> meta . type = ' promise ' if value ? and value . constructor . name is ' Promise ' <nl> <nl> + # Treat simple objects as value . <nl> + if optimizeSimpleObject and meta . type is ' object ' and v8Util . getHiddenValue value , ' simple ' <nl> + meta . type = ' value ' <nl> + <nl> # Treat the arguments object as array . <nl> meta . type = ' array ' if meta . type is ' object ' and value . callee ? and value . length ? <nl> <nl> valueToMeta = ( sender , value ) - > <nl> # Reference the original value if it ' s an object , because when it ' s <nl> # passed to renderer we would assume the renderer keeps a reference of <nl> # it . <nl> - [ meta . id , meta . storeId ] = objectsRegistry . add sender . getId ( ) , value <nl> + meta . id = objectsRegistry . add sender . getId ( ) , value <nl> <nl> meta . members = [ ] <nl> meta . members . push { name : prop , type : typeof field } for prop , field of value <nl> unwrapArgs = ( sender , args ) - > <nl> callFunction = ( event , func , caller , args ) - > <nl> if v8Util . getHiddenValue ( func , ' asynchronous ' ) and typeof args [ args . length - 1 ] isnt ' function ' <nl> args . push ( ret ) - > <nl> - event . returnValue = valueToMeta event . sender , ret <nl> + event . returnValue = valueToMeta event . sender , ret , true <nl> func . apply caller , args <nl> else <nl> ret = func . apply caller , args <nl> - event . returnValue = valueToMeta event . sender , ret <nl> + event . returnValue = valueToMeta event . sender , ret , true <nl> <nl> # Send by BrowserWindow when its render view is deleted . <nl> process . on ' ATOM_BROWSER_RELEASE_RENDER_VIEW ' , ( id ) - > <nl> ipc . on ' ATOM_BROWSER_MEMBER_GET ' , ( event , id , name ) - > <nl> catch e <nl> event . returnValue = errorToMeta e <nl> <nl> - ipc . on ' ATOM_BROWSER_DEREFERENCE ' , ( event , storeId ) - > <nl> - objectsRegistry . remove event . sender . getId ( ) , storeId <nl> + ipc . on ' ATOM_BROWSER_DEREFERENCE ' , ( event , id ) - > <nl> + objectsRegistry . remove event . sender . getId ( ) , id <nl> <nl> ipc . on ' ATOM_BROWSER_GUEST_WEB_CONTENTS ' , ( event , guestInstanceId ) - > <nl> try <nl> deleted file mode 100644 <nl> index c5fbf09370f2 . . 000000000000 <nl> mmm a / atom / common / api / atom_api_id_weak_map . cc <nl> ppp / dev / null <nl> <nl> - / / Copyright ( c ) 2013 GitHub , Inc . <nl> - / / Use of this source code is governed by the MIT license that can be <nl> - / / found in the LICENSE file . <nl> - <nl> - # include " atom / common / api / atom_api_id_weak_map . h " <nl> - <nl> - # include " native_mate / constructor . h " <nl> - # include " native_mate / object_template_builder . h " <nl> - <nl> - # include " atom / common / node_includes . h " <nl> - <nl> - namespace atom { <nl> - <nl> - namespace api { <nl> - <nl> - IDWeakMap : : IDWeakMap ( ) { <nl> - } <nl> - <nl> - IDWeakMap : : ~ IDWeakMap ( ) { <nl> - } <nl> - <nl> - int32_t IDWeakMap : : Add ( v8 : : Isolate * isolate , v8 : : Local < v8 : : Object > object ) { <nl> - return map_ . Add ( isolate , object ) ; <nl> - } <nl> - <nl> - v8 : : Local < v8 : : Value > IDWeakMap : : Get ( v8 : : Isolate * isolate , int32_t key ) { <nl> - v8 : : MaybeLocal < v8 : : Object > result = map_ . Get ( isolate , key ) ; <nl> - if ( result . IsEmpty ( ) ) { <nl> - isolate - > ThrowException ( v8 : : Exception : : Error ( <nl> - mate : : StringToV8 ( isolate , " Invalid key " ) ) ) ; <nl> - return v8 : : Undefined ( isolate ) ; <nl> - } else { <nl> - return result . ToLocalChecked ( ) ; <nl> - } <nl> - } <nl> - <nl> - bool IDWeakMap : : Has ( int32_t key ) const { <nl> - return map_ . Has ( key ) ; <nl> - } <nl> - <nl> - std : : vector < int32_t > IDWeakMap : : Keys ( ) const { <nl> - return map_ . Keys ( ) ; <nl> - } <nl> - <nl> - void IDWeakMap : : Remove ( int32_t key ) { <nl> - map_ . Remove ( key ) ; <nl> - } <nl> - <nl> - / / static <nl> - void IDWeakMap : : BuildPrototype ( v8 : : Isolate * isolate , <nl> - v8 : : Local < v8 : : ObjectTemplate > prototype ) { <nl> - mate : : ObjectTemplateBuilder ( isolate , prototype ) <nl> - . SetMethod ( " add " , & IDWeakMap : : Add ) <nl> - . SetMethod ( " get " , & IDWeakMap : : Get ) <nl> - . SetMethod ( " has " , & IDWeakMap : : Has ) <nl> - . SetMethod ( " keys " , & IDWeakMap : : Keys ) <nl> - . SetMethod ( " remove " , & IDWeakMap : : Remove ) ; <nl> - } <nl> - <nl> - } / / namespace api <nl> - <nl> - } / / namespace atom <nl> - <nl> - <nl> - namespace { <nl> - <nl> - void Initialize ( v8 : : Local < v8 : : Object > exports , v8 : : Local < v8 : : Value > unused , <nl> - v8 : : Local < v8 : : Context > context , void * priv ) { <nl> - using atom : : api : : IDWeakMap ; <nl> - v8 : : Isolate * isolate = context - > GetIsolate ( ) ; <nl> - v8 : : Local < v8 : : Function > constructor = mate : : CreateConstructor < IDWeakMap > ( <nl> - isolate , <nl> - " IDWeakMap " , <nl> - base : : Bind ( & mate : : NewOperatorFactory < IDWeakMap > ) ) ; <nl> - exports - > Set ( mate : : StringToSymbol ( isolate , " IDWeakMap " ) , constructor ) ; <nl> - } <nl> - <nl> - } / / namespace <nl> - <nl> - NODE_MODULE_CONTEXT_AWARE_BUILTIN ( atom_common_id_weak_map , Initialize ) <nl> deleted file mode 100644 <nl> index 955bd83088ac . . 000000000000 <nl> mmm a / atom / common / api / atom_api_id_weak_map . h <nl> ppp / dev / null <nl> <nl> - / / Copyright ( c ) 2013 GitHub , Inc . <nl> - / / Copyright ( c ) 2012 Intel Corp . All rights reserved . <nl> - / / Use of this source code is governed by the MIT license that can be <nl> - / / found in the LICENSE file . <nl> - <nl> - # ifndef ATOM_COMMON_API_ATOM_API_ID_WEAK_MAP_H_ <nl> - # define ATOM_COMMON_API_ATOM_API_ID_WEAK_MAP_H_ <nl> - <nl> - # include < vector > <nl> - <nl> - # include " atom / common / id_weak_map . h " <nl> - # include " native_mate / wrappable . h " <nl> - <nl> - namespace atom { <nl> - <nl> - namespace api { <nl> - <nl> - / / Like ES6 ' s WeakMap , but the key is Integer and the value is Weak Pointer . <nl> - class IDWeakMap : public mate : : Wrappable { <nl> - public : <nl> - IDWeakMap ( ) ; <nl> - <nl> - static void BuildPrototype ( v8 : : Isolate * isolate , <nl> - v8 : : Local < v8 : : ObjectTemplate > prototype ) ; <nl> - <nl> - private : <nl> - virtual ~ IDWeakMap ( ) ; <nl> - <nl> - int32_t Add ( v8 : : Isolate * isolate , v8 : : Local < v8 : : Object > object ) ; <nl> - v8 : : Local < v8 : : Value > Get ( v8 : : Isolate * isolate , int32_t key ) ; <nl> - bool Has ( int32_t key ) const ; <nl> - std : : vector < int32_t > Keys ( ) const ; <nl> - void Remove ( int32_t key ) ; <nl> - <nl> - atom : : IDWeakMap map_ ; <nl> - <nl> - DISALLOW_COPY_AND_ASSIGN ( IDWeakMap ) ; <nl> - } ; <nl> - <nl> - } / / namespace api <nl> - <nl> - } / / namespace atom <nl> - <nl> - # endif / / ATOM_COMMON_API_ATOM_API_ID_WEAK_MAP_H_ <nl> mmm a / atom / common / api / atom_api_v8_util . cc <nl> ppp b / atom / common / api / atom_api_v8_util . cc <nl> void SetHiddenValue ( v8 : : Local < v8 : : Object > object , <nl> object - > SetHiddenValue ( key , value ) ; <nl> } <nl> <nl> + void DeleteHiddenValue ( v8 : : Local < v8 : : Object > object , <nl> + v8 : : Local < v8 : : String > key ) { <nl> + object - > DeleteHiddenValue ( key ) ; <nl> + } <nl> + <nl> int32_t GetObjectHash ( v8 : : Local < v8 : : Object > object ) { <nl> return object - > GetIdentityHash ( ) ; <nl> } <nl> void Initialize ( v8 : : Local < v8 : : Object > exports , v8 : : Local < v8 : : Value > unused , <nl> dict . SetMethod ( " createObjectWithName " , & CreateObjectWithName ) ; <nl> dict . SetMethod ( " getHiddenValue " , & GetHiddenValue ) ; <nl> dict . SetMethod ( " setHiddenValue " , & SetHiddenValue ) ; <nl> + dict . SetMethod ( " deleteHiddenValue " , & DeleteHiddenValue ) ; <nl> dict . SetMethod ( " getObjectHash " , & GetObjectHash ) ; <nl> dict . SetMethod ( " setDestructor " , & SetDestructor ) ; <nl> dict . SetMethod ( " takeHeapSnapshot " , & TakeHeapSnapshot ) ; <nl> mmm a / atom / common / api / object_life_monitor . cc <nl> ppp b / atom / common / api / object_life_monitor . cc <nl> <nl> <nl> # include " atom / common / api / object_life_monitor . h " <nl> <nl> - # include " native_mate / compat . h " <nl> + # include " base / bind . h " <nl> + # include " base / message_loop / message_loop . h " <nl> <nl> namespace atom { <nl> <nl> / / static <nl> void ObjectLifeMonitor : : BindTo ( v8 : : Isolate * isolate , <nl> v8 : : Local < v8 : : Object > target , <nl> - v8 : : Local < v8 : : Value > destructor ) { <nl> - target - > SetHiddenValue ( MATE_STRING_NEW ( isolate , " destructor " ) , destructor ) ; <nl> - <nl> - ObjectLifeMonitor * olm = new ObjectLifeMonitor ( ) ; <nl> - olm - > handle_ . reset ( isolate , target ) ; <nl> - olm - > handle_ . SetWeak ( olm , WeakCallback ) ; <nl> + v8 : : Local < v8 : : Function > destructor ) { <nl> + new ObjectLifeMonitor ( isolate , target , destructor ) ; <nl> } <nl> <nl> - ObjectLifeMonitor : : ObjectLifeMonitor ( ) { <nl> + ObjectLifeMonitor : : ObjectLifeMonitor ( v8 : : Isolate * isolate , <nl> + v8 : : Local < v8 : : Object > target , <nl> + v8 : : Local < v8 : : Function > destructor ) <nl> + : isolate_ ( isolate ) , <nl> + context_ ( isolate , isolate - > GetCurrentContext ( ) ) , <nl> + target_ ( isolate , target ) , <nl> + destructor_ ( isolate , destructor ) , <nl> + weak_ptr_factory_ ( this ) { <nl> + target_ . SetWeak ( this , OnObjectGC , v8 : : WeakCallbackType : : kParameter ) ; <nl> } <nl> <nl> / / static <nl> - void ObjectLifeMonitor : : WeakCallback ( <nl> - const v8 : : WeakCallbackData < v8 : : Object , ObjectLifeMonitor > & data ) { <nl> - / / destructor . call ( object , object ) ; <nl> - v8 : : Local < v8 : : Object > obj = data . GetValue ( ) ; <nl> - v8 : : Local < v8 : : Function > : : Cast ( obj - > GetHiddenValue ( <nl> - MATE_STRING_NEW ( data . GetIsolate ( ) , " destructor " ) ) ) - > Call ( obj , 0 , NULL ) ; <nl> - delete data . GetParameter ( ) ; <nl> + void ObjectLifeMonitor : : OnObjectGC ( <nl> + const v8 : : WeakCallbackInfo < ObjectLifeMonitor > & data ) { <nl> + / / Usually FirstWeakCallback should do nothing other than reset | object_ | <nl> + / / and then set a second weak callback to run later . We can sidestep that , <nl> + / / because posting a task to the current message loop is all but free - but <nl> + / / DO NOT add any more work to this method . The only acceptable place to add <nl> + / / code is RunCallback . <nl> + ObjectLifeMonitor * self = data . GetParameter ( ) ; <nl> + self - > target_ . Reset ( ) ; <nl> + base : : MessageLoop : : current ( ) - > PostTask ( <nl> + FROM_HERE , base : : Bind ( & ObjectLifeMonitor : : RunCallback , <nl> + self - > weak_ptr_factory_ . GetWeakPtr ( ) ) ) ; <nl> + } <nl> + <nl> + void ObjectLifeMonitor : : RunCallback ( ) { <nl> + v8 : : HandleScope handle_scope ( isolate_ ) ; <nl> + v8 : : Local < v8 : : Context > context = v8 : : Local < v8 : : Context > : : New ( <nl> + isolate_ , context_ ) ; <nl> + v8 : : Context : : Scope context_scope ( context ) ; <nl> + v8 : : Local < v8 : : Function > : : New ( isolate_ , destructor_ ) - > Call ( <nl> + context - > Global ( ) , 0 , nullptr ) ; <nl> + delete this ; <nl> } <nl> <nl> } / / namespace atom <nl> mmm a / atom / common / api / object_life_monitor . h <nl> ppp b / atom / common / api / object_life_monitor . h <nl> <nl> # define ATOM_COMMON_API_OBJECT_LIFE_MONITOR_H_ <nl> <nl> # include " base / basictypes . h " <nl> - # include " native_mate / scoped_persistent . h " <nl> + # include " base / memory / weak_ptr . h " <nl> + # include " v8 / include / v8 . h " <nl> <nl> namespace atom { <nl> <nl> class ObjectLifeMonitor { <nl> public : <nl> static void BindTo ( v8 : : Isolate * isolate , <nl> v8 : : Local < v8 : : Object > target , <nl> - v8 : : Local < v8 : : Value > destructor ) ; <nl> + v8 : : Local < v8 : : Function > destructor ) ; <nl> <nl> private : <nl> - ObjectLifeMonitor ( ) ; <nl> + ObjectLifeMonitor ( v8 : : Isolate * isolate , <nl> + v8 : : Local < v8 : : Object > target , <nl> + v8 : : Local < v8 : : Function > destructor ) ; <nl> <nl> - static void WeakCallback ( <nl> - const v8 : : WeakCallbackData < v8 : : Object , ObjectLifeMonitor > & data ) ; <nl> + static void OnObjectGC ( const v8 : : WeakCallbackInfo < ObjectLifeMonitor > & data ) ; <nl> <nl> - mate : : ScopedPersistent < v8 : : Object > handle_ ; <nl> + void RunCallback ( ) ; <nl> + <nl> + v8 : : Isolate * isolate_ ; <nl> + v8 : : Global < v8 : : Context > context_ ; <nl> + v8 : : Global < v8 : : Object > target_ ; <nl> + v8 : : Global < v8 : : Function > destructor_ ; <nl> + <nl> + base : : WeakPtrFactory < ObjectLifeMonitor > weak_ptr_factory_ ; <nl> <nl> DISALLOW_COPY_AND_ASSIGN ( ObjectLifeMonitor ) ; <nl> } ; <nl> mmm a / atom / common / id_weak_map . cc <nl> ppp b / atom / common / id_weak_map . cc <nl> <nl> <nl> namespace atom { <nl> <nl> + namespace { <nl> + <nl> + struct ObjectKey { <nl> + ObjectKey ( int id , IDWeakMap * map ) : id ( id ) , map ( map ) { } <nl> + int id ; <nl> + IDWeakMap * map ; <nl> + } ; <nl> + <nl> + void OnObjectGC ( const v8 : : WeakCallbackInfo < ObjectKey > & data ) { <nl> + ObjectKey * key = data . GetParameter ( ) ; <nl> + key - > map - > Remove ( key - > id ) ; <nl> + delete key ; <nl> + } <nl> + <nl> + } / / namespace <nl> + <nl> IDWeakMap : : IDWeakMap ( ) : next_id_ ( 0 ) { <nl> } <nl> <nl> IDWeakMap : : ~ IDWeakMap ( ) { <nl> <nl> int32_t IDWeakMap : : Add ( v8 : : Isolate * isolate , v8 : : Local < v8 : : Object > object ) { <nl> int32_t id = GetNextID ( ) ; <nl> - object - > SetHiddenValue ( mate : : StringToSymbol ( isolate , " IDWeakMapKey " ) , <nl> - mate : : Converter < int32_t > : : ToV8 ( isolate , id ) ) ; <nl> - <nl> auto global = make_linked_ptr ( new v8 : : Global < v8 : : Object > ( isolate , object ) ) ; <nl> - global - > SetWeak ( this , & WeakCallback ) ; <nl> + ObjectKey * key = new ObjectKey ( id , this ) ; <nl> + global - > SetWeak ( key , OnObjectGC , v8 : : WeakCallbackType : : kParameter ) ; <nl> map_ [ id ] = global ; <nl> return id ; <nl> } <nl> int32_t IDWeakMap : : GetNextID ( ) { <nl> return + + next_id_ ; <nl> } <nl> <nl> - / / static <nl> - void IDWeakMap : : WeakCallback ( <nl> - const v8 : : WeakCallbackData < v8 : : Object , IDWeakMap > & data ) { <nl> - int32_t id = data . GetValue ( ) - > GetHiddenValue ( <nl> - mate : : StringToV8 ( data . GetIsolate ( ) , " IDWeakMapKey " ) ) - > Int32Value ( ) ; <nl> - data . GetParameter ( ) - > Remove ( id ) ; <nl> - } <nl> - <nl> } / / namespace atom <nl> mmm a / atom / common / id_weak_map . h <nl> ppp b / atom / common / id_weak_map . h <nl> class IDWeakMap { <nl> / / Returns next available ID . <nl> int32_t GetNextID ( ) ; <nl> <nl> - static void WeakCallback ( <nl> - const v8 : : WeakCallbackData < v8 : : Object , IDWeakMap > & data ) ; <nl> - <nl> / / ID of next stored object . <nl> int32_t next_id_ ; <nl> <nl> mmm a / atom / common / native_mate_converters / gfx_converter . cc <nl> ppp b / atom / common / native_mate_converters / gfx_converter . cc <nl> namespace mate { <nl> <nl> v8 : : Local < v8 : : Value > Converter < gfx : : Point > : : ToV8 ( v8 : : Isolate * isolate , <nl> const gfx : : Point & val ) { <nl> - mate : : Dictionary dict ( isolate , v8 : : Object : : New ( isolate ) ) ; <nl> + mate : : Dictionary dict = mate : : Dictionary : : CreateEmpty ( isolate ) ; <nl> + dict . SetHidden ( " simple " , true ) ; <nl> dict . Set ( " x " , val . x ( ) ) ; <nl> dict . Set ( " y " , val . y ( ) ) ; <nl> return dict . GetHandle ( ) ; <nl> bool Converter < gfx : : Point > : : FromV8 ( v8 : : Isolate * isolate , <nl> <nl> v8 : : Local < v8 : : Value > Converter < gfx : : Size > : : ToV8 ( v8 : : Isolate * isolate , <nl> const gfx : : Size & val ) { <nl> - mate : : Dictionary dict ( isolate , v8 : : Object : : New ( isolate ) ) ; <nl> + mate : : Dictionary dict = mate : : Dictionary : : CreateEmpty ( isolate ) ; <nl> + dict . SetHidden ( " simple " , true ) ; <nl> dict . Set ( " width " , val . width ( ) ) ; <nl> dict . Set ( " height " , val . height ( ) ) ; <nl> return dict . GetHandle ( ) ; <nl> bool Converter < gfx : : Size > : : FromV8 ( v8 : : Isolate * isolate , <nl> <nl> v8 : : Local < v8 : : Value > Converter < gfx : : Rect > : : ToV8 ( v8 : : Isolate * isolate , <nl> const gfx : : Rect & val ) { <nl> - mate : : Dictionary dict ( isolate , v8 : : Object : : New ( isolate ) ) ; <nl> + mate : : Dictionary dict = mate : : Dictionary : : CreateEmpty ( isolate ) ; <nl> + dict . SetHidden ( " simple " , true ) ; <nl> dict . Set ( " x " , val . x ( ) ) ; <nl> dict . Set ( " y " , val . y ( ) ) ; <nl> dict . Set ( " width " , val . width ( ) ) ; <nl> struct Converter < gfx : : Display : : TouchSupport > { <nl> <nl> v8 : : Local < v8 : : Value > Converter < gfx : : Display > : : ToV8 ( v8 : : Isolate * isolate , <nl> const gfx : : Display & val ) { <nl> - mate : : Dictionary dict ( isolate , v8 : : Object : : New ( isolate ) ) ; <nl> + mate : : Dictionary dict = mate : : Dictionary : : CreateEmpty ( isolate ) ; <nl> + dict . SetHidden ( " simple " , true ) ; <nl> dict . Set ( " id " , val . id ( ) ) ; <nl> dict . Set ( " bounds " , val . bounds ( ) ) ; <nl> dict . Set ( " workArea " , val . work_area ( ) ) ; <nl> mmm a / atom / common / native_mate_converters / v8_value_converter . cc <nl> ppp b / atom / common / native_mate_converters / v8_value_converter . cc <nl> <nl> # include " base / logging . h " <nl> # include " base / memory / scoped_ptr . h " <nl> # include " base / values . h " <nl> + # include " native_mate / dictionary . h " <nl> # include " vendor / node / src / node_buffer . h " <nl> <nl> namespace atom { <nl> v8 : : Local < v8 : : Value > V8ValueConverter : : ToV8Array ( <nl> <nl> v8 : : Local < v8 : : Value > V8ValueConverter : : ToV8Object ( <nl> v8 : : Isolate * isolate , const base : : DictionaryValue * val ) const { <nl> - v8 : : Local < v8 : : Object > result ( v8 : : Object : : New ( isolate ) ) ; <nl> + mate : : Dictionary result = mate : : Dictionary : : CreateEmpty ( isolate ) ; <nl> + result . SetHidden ( " simple " , true ) ; <nl> <nl> for ( base : : DictionaryValue : : Iterator iter ( * val ) ; <nl> ! iter . IsAtEnd ( ) ; iter . Advance ( ) ) { <nl> v8 : : Local < v8 : : Value > V8ValueConverter : : ToV8Object ( <nl> CHECK ( ! child_v8 . IsEmpty ( ) ) ; <nl> <nl> v8 : : TryCatch try_catch ; <nl> - result - > Set ( <nl> - v8 : : String : : NewFromUtf8 ( isolate , key . c_str ( ) , v8 : : String : : kNormalString , <nl> - key . length ( ) ) , <nl> - child_v8 ) ; <nl> + result . Set ( key , child_v8 ) ; <nl> if ( try_catch . HasCaught ( ) ) { <nl> LOG ( ERROR ) < < " Setter for property " < < key . c_str ( ) < < " threw an " <nl> < < " exception . " ; <nl> } <nl> } <nl> <nl> - return result ; <nl> + return result . GetHandle ( ) ; <nl> } <nl> <nl> base : : Value * V8ValueConverter : : FromV8ValueImpl ( <nl> mmm a / atom / common / node_bindings . cc <nl> ppp b / atom / common / node_bindings . cc <nl> REFERENCE_MODULE ( atom_browser_window ) ; <nl> REFERENCE_MODULE ( atom_common_asar ) ; <nl> REFERENCE_MODULE ( atom_common_clipboard ) ; <nl> REFERENCE_MODULE ( atom_common_crash_reporter ) ; <nl> - REFERENCE_MODULE ( atom_common_id_weak_map ) ; <nl> REFERENCE_MODULE ( atom_common_native_image ) ; <nl> REFERENCE_MODULE ( atom_common_screen ) ; <nl> REFERENCE_MODULE ( atom_common_shell ) ; <nl> mmm a / atom / renderer / api / lib / remote . coffee <nl> ppp b / atom / renderer / api / lib / remote . coffee <nl> metaToValue = ( meta ) - > <nl> # Track delegate object ' s life time , and tell the browser to clean up <nl> # when the object is GCed . <nl> v8Util . setDestructor ret , - > <nl> - ipc . send ' ATOM_BROWSER_DEREFERENCE ' , meta . storeId <nl> + ipc . send ' ATOM_BROWSER_DEREFERENCE ' , meta . id <nl> <nl> # Remember object ' s id . <nl> v8Util . setHiddenValue ret , ' atomId ' , meta . id <nl> mmm a / filenames . gypi <nl> ppp b / filenames . gypi <nl> <nl> ' atom / common / api / atom_api_asar . cc ' , <nl> ' atom / common / api / atom_api_clipboard . cc ' , <nl> ' atom / common / api / atom_api_crash_reporter . cc ' , <nl> - ' atom / common / api / atom_api_id_weak_map . cc ' , <nl> - ' atom / common / api / atom_api_id_weak_map . h ' , <nl> ' atom / common / api / atom_api_native_image . cc ' , <nl> ' atom / common / api / atom_api_native_image . h ' , <nl> ' atom / common / api / atom_api_native_image_mac . mm ' , <nl> mmm a / spec / chromium - spec . coffee <nl> ppp b / spec / chromium - spec . coffee <nl> remote = require ' remote ' <nl> describe ' chromium feature ' , - > <nl> fixtures = path . resolve __dirname , ' fixtures ' <nl> <nl> - describe ' heap snapshot ' , - > <nl> + xdescribe ' heap snapshot ' , - > <nl> it ' does not crash ' , - > <nl> process . atomBinding ( ' v8_util ' ) . takeHeapSnapshot ( ) <nl> <nl> mmm a / vendor / native_mate <nl> ppp b / vendor / native_mate <nl> @ @ - 1 + 1 @ @ <nl> - Subproject commit b41635e80921bddbf1a36f030490e063cd593477 <nl> + Subproject commit 8ca005eb41591f583ebab804945311903f866ad6 <nl> | Merge pull request from atom / pod - optimize | electron/electron | c91ab5ec7c4ab8ec58d2004849c827f9d02827b0 | 2015-08-27T12:51:02Z |
mmm a / tools / autograd / templates / python_torch_functions . cpp <nl> ppp b / tools / autograd / templates / python_torch_functions . cpp <nl> static PyObject * THPVariable_randint ( PyObject * self_ , PyObject * args , PyObject * <nl> static PyObject * THPVariable_as_tensor ( PyObject * self , PyObject * args , PyObject * kwargs ) <nl> { <nl> HANDLE_TH_ERRORS <nl> - jit : : tracer : : warn ( " torch . as_tensor " ) ; <nl> + jit : : tracer : : warn ( " torch . as_tensor " , jit : : tracer : : WARN_CONSTRUCTOR ) ; <nl> return THPVariable_Wrap ( torch : : utils : : as_tensor ( default_type ( ) , args , kwargs ) ) ; <nl> END_HANDLE_TH_ERRORS <nl> } <nl> static PyObject * THPVariable_as_tensor ( PyObject * self , PyObject * args , PyObject <nl> static PyObject * THPVariable_from_numpy ( PyObject * module , PyObject * arg ) <nl> { <nl> HANDLE_TH_ERRORS <nl> - jit : : tracer : : warn ( " torch . from_numpy " ) ; <nl> + jit : : tracer : : warn ( " torch . from_numpy " , jit : : tracer : : WARN_CONSTRUCTOR ) ; <nl> auto data = torch : : utils : : tensor_from_numpy ( arg ) ; <nl> return THPVariable_Wrap ( make_variable ( std : : move ( data ) , / * requires_grad = * / false ) ) ; <nl> END_HANDLE_TH_ERRORS <nl> static PyObject * THPVariable__promote_types ( PyObject * self , PyObject * args , PyO <nl> static PyObject * THPVariable_sparse_coo_tensor ( PyObject * self , PyObject * args , PyObject * kwargs ) <nl> { <nl> HANDLE_TH_ERRORS <nl> - jit : : tracer : : warn ( " torch . sparse_coo_tensor " ) ; <nl> + jit : : tracer : : warn ( " torch . sparse_coo_tensor " , jit : : tracer : : WARN_CONSTRUCTOR ) ; <nl> return THPVariable_Wrap ( torch : : utils : : sparse_coo_tensor_ctor ( default_type ( ) , args , kwargs ) ) ; <nl> END_HANDLE_TH_ERRORS <nl> } <nl> static PyObject * THPVariable_sparse_coo_tensor ( PyObject * self , PyObject * args , <nl> static PyObject * THPVariable_tensor ( PyObject * self , PyObject * args , PyObject * kwargs ) <nl> { <nl> HANDLE_TH_ERRORS <nl> - jit : : tracer : : warn ( " torch . tensor " ) ; <nl> + jit : : tracer : : warn ( " torch . tensor " , jit : : tracer : : WARN_CONSTRUCTOR ) ; <nl> return THPVariable_Wrap ( torch : : utils : : tensor_ctor ( default_type ( ) , args , kwargs ) ) ; <nl> END_HANDLE_TH_ERRORS <nl> } <nl> mmm a / tools / autograd / templates / python_variable_methods . cpp <nl> ppp b / tools / autograd / templates / python_variable_methods . cpp <nl> static int64_t dispatch_to_CLong ( const Tensor & self ) { <nl> <nl> static PyObject * THPVariable_float_scalar ( PyObject * self , PyObject * args ) { <nl> HANDLE_TH_ERRORS <nl> - jit : : tracer : : warn ( " Converting a tensor to a Python float " ) ; <nl> + jit : : tracer : : warn ( " Converting a tensor to a Python float " , jit : : tracer : : WARN_PYTHON_DATAFLOW ) ; <nl> auto & self_ = reinterpret_cast < THPVariable * > ( self ) - > cdata ; <nl> return wrap ( dispatch_to_CDouble ( self_ ) ) ; <nl> END_HANDLE_TH_ERRORS <nl> static PyObject * THPVariable_float_scalar ( PyObject * self , PyObject * args ) { <nl> <nl> static PyObject * THPVariable_integral_scalar ( PyObject * self , PyObject * args ) { <nl> HANDLE_TH_ERRORS <nl> - jit : : tracer : : warn ( " Converting a tensor to a Python integer " ) ; <nl> + jit : : tracer : : warn ( " Converting a tensor to a Python integer " , jit : : tracer : : WARN_PYTHON_DATAFLOW ) ; <nl> auto & self_ = reinterpret_cast < THPVariable * > ( self ) - > cdata ; <nl> if ( isFloatingType ( self_ . type ( ) . scalarType ( ) ) ) { <nl> / / we can ' t dispatch to toCLong here because we want to avoid ATen overflow checks ; <nl> static PyObject * THPVariable_integral_scalar ( PyObject * self , PyObject * args ) { <nl> / / called when used as a slice . <nl> static PyObject * THPVariable_index_scalar ( PyObject * self , PyObject * args ) { <nl> HANDLE_TH_ERRORS <nl> - jit : : tracer : : warn ( " Converting a tensor to a Python index " ) ; <nl> + jit : : tracer : : warn ( " Converting a tensor to a Python index " , jit : : tracer : : WARN_PYTHON_DATAFLOW ) ; <nl> auto & self_ = reinterpret_cast < THPVariable * > ( self ) - > cdata ; <nl> / / TODO : change the condition to ` self_ . dim ( ) ! = 0 ` once we expose scalars <nl> / / in PyTorch . <nl> static PyObject * THPVariable_element_size ( PyObject * self , PyObject * args ) <nl> static PyObject * THPVariable_numpy ( PyObject * self , PyObject * arg ) <nl> { <nl> HANDLE_TH_ERRORS <nl> - jit : : tracer : : warn ( " Converting a tensor to a NumPy array " ) ; <nl> + jit : : tracer : : warn ( " Converting a tensor to a NumPy array " , jit : : tracer : : WARN_PYTHON_DATAFLOW ) ; <nl> auto & self_ = reinterpret_cast < THPVariable * > ( self ) - > cdata ; <nl> if ( self_ . requires_grad ( ) ) { <nl> throw std : : runtime_error ( <nl> static PyObject * THPVariable_requires_grad_ ( PyObject * self , PyObject * args , PyO <nl> static PyObject * THPVariable_item ( PyObject * self , PyObject * args ) <nl> { <nl> HANDLE_TH_ERRORS <nl> - jit : : tracer : : warn ( " Converting a tensor to a Python number " ) ; <nl> + jit : : tracer : : warn ( " Converting a tensor to a Python number " , jit : : tracer : : WARN_PYTHON_DATAFLOW ) ; <nl> auto & self_ = reinterpret_cast < THPVariable * > ( self ) - > cdata ; <nl> if ( self_ . is_floating_point ( ) ) { <nl> return wrap ( dispatch_to_CDouble ( self_ ) ) ; <nl> static PyObject * THPVariable_to ( PyObject * self , PyObject * args , PyObject * kwarg <nl> static PyObject * THPVariable_tolist ( PyObject * self , PyObject * args ) <nl> { <nl> HANDLE_TH_ERRORS <nl> - jit : : tracer : : warn ( " Converting a tensor to a Python list " ) ; <nl> + jit : : tracer : : warn ( " Converting a tensor to a Python list " , jit : : tracer : : WARN_PYTHON_DATAFLOW ) ; <nl> auto self_ = reinterpret_cast < THPVariable * > ( self ) - > cdata ; <nl> return torch : : utils : : tensor_to_list ( self_ . data ( ) ) ; <nl> END_HANDLE_TH_ERRORS <nl> static PyObject * THPVariable_type ( PyObject * self , PyObject * args , PyObject * kwa <nl> $ { py_methods } <nl> <nl> static PyObject * THPVariable_bool ( PyObject * self , PyObject * args ) { <nl> - jit : : tracer : : warn ( " Converting a tensor to a Python boolean " ) ; <nl> + jit : : tracer : : warn ( " Converting a tensor to a Python boolean " , jit : : tracer : : WARN_PYTHON_DATAFLOW ) ; <nl> return THPVariable_is_nonzero ( self , args ) ; <nl> } <nl> <nl> mmm a / torch / csrc / autograd / python_variable . cpp <nl> ppp b / torch / csrc / autograd / python_variable . cpp <nl> static void THPVariable_dealloc ( THPVariable * self ) <nl> static PyObject * THPVariable_pynew ( PyTypeObject * type , PyObject * args , PyObject * kwargs ) <nl> { <nl> HANDLE_TH_ERRORS <nl> - jit : : tracer : : warn ( " torch . Tensor " ) ; <nl> + jit : : tracer : : warn ( " torch . Tensor " , jit : : tracer : : WARN_CONSTRUCTOR ) ; <nl> auto & default_type = torch : : tensors : : get_default_tensor_type ( ) ; <nl> auto tensor = torch : : utils : : legacy_tensor_ctor ( default_type , args , kwargs ) ; <nl> return THPVariable_NewWithVar ( type , std : : move ( tensor ) ) ; <nl> mmm a / torch / csrc / jit / tracer . cpp <nl> ppp b / torch / csrc / jit / tracer . cpp <nl> void setRecordSourceLocation ( void ( * v ) ( Node * ) ) { <nl> void defaultWarn ( const std : : string & str ) { AT_WARN ( str ) ; } <nl> std : : atomic < warn_fn_type > warn_callback { defaultWarn } ; <nl> <nl> - void _do_warn ( const char * _reason ) { <nl> + const char * WARN_PYTHON_DATAFLOW = <nl> + " might cause the trace to be incorrect . We can ' t record the data flow of " <nl> + " Python values , so this value will be treated as a constant in the future . " <nl> + " This means that the trace might not generalize to other inputs ! " ; <nl> + const char * WARN_CONSTRUCTOR = <nl> + " results are registered as constants in the trace . You can safely ignore this " <nl> + " warning if you use this function to create tensors out of constant variables " <nl> + " that would be the same every time you call this function . In any other case , " <nl> + " this might cause the trace to be incorrect . " ; <nl> + <nl> + / / XXX : _kind can be a nullptr <nl> + void _do_warn ( const char * _reason , const char * _kind ) { <nl> std : : string reason { _reason } ; <nl> + std : : string kind { _kind ? _kind : " " } ; <nl> std : : ostringstream s ; <nl> - s < < std : : string ( reason ) ; <nl> - s < < " might cause the trace to be incorrect . We can ' t record the data flow of " <nl> - " Python values , which means the trace might not generalize to other inputs . " ; <nl> + s < < reason < < kind ; <nl> warn_callback . load ( ) ( s . str ( ) ) ; <nl> } <nl> <nl> void setWarn ( warn_fn_type fn ) { <nl> warn_callback . store ( fn ) ; <nl> } <nl> <nl> - void ensureUnique ( const char * name , const at : : Tensor & tensor ) { <nl> - auto aliases = tensor . storage ( ) . use_count ( ) ; <nl> - if ( aliases > 1 ) { <nl> - std : : stringstream ss ; <nl> - ss < < " There are " < < aliases <nl> - < < " live references to the tensor being modified when tracing in - place operator " <nl> - < < name < < " which " ; <nl> - warn ( ss . str ( ) . c_str ( ) ) ; <nl> - } <nl> - } <nl> - <nl> } } } <nl> mmm a / torch / csrc / jit / tracer . h <nl> ppp b / torch / csrc / jit / tracer . h <nl> void addInputs ( Node * n , const char * name , std : : array < bool , N > value ) { <nl> throw std : : runtime_error ( " Found an unsupported argument type in the JIT tracer . File a bug report . " ) ; <nl> } <nl> <nl> - TORCH_API void ensureUnique ( const char * name , const at : : Tensor & tensor ) ; <nl> + inline void ensureUnique ( const char * name , const at : : Tensor & tensor ) { <nl> + auto aliases = tensor . storage ( ) . use_count ( ) ; <nl> + if ( isTracing ( ) & & aliases > 1 ) { <nl> + std : : stringstream ss ; <nl> + ss < < " There are " < < aliases <nl> + < < " live references to the data region being modified when tracing in - place operator " <nl> + < < name < < " . This might cause the trace to be incorrect , because all other views " <nl> + < < " that also reference this data will not not reflect this change in the trace ! " <nl> + < < " On the other hand , if all other views use the same memory chunk , but are disjoint ( e . g . " <nl> + < < " are outputs of torch . split ) , this might still be safe . " ; <nl> + warn ( ss . str ( ) . c_str ( ) ) ; <nl> + } <nl> + } <nl> + <nl> <nl> template < <nl> typename T , <nl> mmm a / torch / csrc / jit / tracing_state . h <nl> ppp b / torch / csrc / jit / tracing_state . h <nl> inline bool isTracing ( ) { <nl> } <nl> <nl> using warn_fn_type = void ( * ) ( const std : : string & msg ) ; <nl> - TORCH_API void _do_warn ( const char * _reason ) ; <nl> - inline void warn ( const char * _reason ) { <nl> + TORCH_API extern const char * WARN_PYTHON_DATAFLOW ; <nl> + TORCH_API extern const char * WARN_CONSTRUCTOR ; <nl> + TORCH_API void _do_warn ( const char * _reason , const char * _kind ) ; <nl> + inline void warn ( const char * _reason , const char * _kind = nullptr ) { <nl> if ( auto state = getTracingState ( ) ) { <nl> if ( ! state - > warn ) return ; <nl> - _do_warn ( _reason ) ; <nl> + _do_warn ( _reason , _kind ) ; <nl> } <nl> } <nl> TORCH_API void setWarn ( warn_fn_type fn ) ; <nl> mmm a / torch / jit / __init__ . py <nl> ppp b / torch / jit / __init__ . py <nl> def maybe_warn_nondeterministic ( ) : <nl> nondeterministic_ops_warning = " Trace had nondeterministic nodes . Nodes : \ n " <nl> nondeterministic_ops_warning + = " \ n " . join ( [ indent ( str ( op ) ) for op in nondeterm_ops ] [ : 20 ] ) <nl> nondeterministic_ops_warning + = " \ nThis may cause errors in trace checking . To disable trace checking , " \ <nl> - " pass disable_checks = True to torch . jit . trace ( ) " <nl> + " pass check_trace = False to torch . jit . trace ( ) " <nl> warnings . warn ( nondeterministic_ops_warning , category = TracerWarning , stacklevel = 5 ) <nl> <nl> def compare_outputs ( original , reference , match_what ) : <nl> | Improve tracer warnings ( ) | pytorch/pytorch | 90e31f4896c2062b97f7a4efb73754b840ba5dc6 | 2018-09-12T05:10:32Z |
mmm a / test / rpc_test . py <nl> ppp b / test / rpc_test . py <nl> def test_py_udf_remote ( self ) : <nl> ) <nl> self . assertEqual ( rref . to_here ( ) , my_function ( n , n + 1 , n + 2 ) ) <nl> <nl> - @ unittest . skip ( " Test is flaky , see https : / / github . com / pytorch / pytorch / issues / 29156 " ) <nl> @ dist_init <nl> def test_multi_py_udf_remote ( self ) : <nl> def kwargs_fn ( n ) : <nl> | Enable test_multi_py_udf_remote in rpc_test . py | pytorch/pytorch | b885eff4be274284f6f3877e564655c77a27902d | 2019-11-11T20:22:01Z |
similarity index 100 % <nl> rename from code / bit - manipulation / convert_number_binary / convert_number_binary . java <nl> rename to code / bit - manipulation / convert_number_binary / ConvertNumberBinary . java <nl> similarity index 100 % <nl> rename from code / bit - manipulation / thrice_unique_number / thrice_Unique_number . java <nl> rename to code / bit - manipulation / thrice_unique_number / ThriceUniqueNumber . java <nl> similarity index 100 % <nl> rename from code / computational_geometry / area_of_polygon / area_of_polygon . java <nl> rename to code / computational_geometry / area_of_polygon / AreaOfPolygon . java <nl> similarity index 100 % <nl> rename from code / computational_geometry / area_of_triangle / area_of_triangle . java <nl> rename to code / computational_geometry / area_of_triangle / AreaOfTriangle . java <nl> similarity index 100 % <nl> rename from code / computational_geometry / distance_between_points / distance_between_points . java <nl> rename to code / computational_geometry / distance_between_points / DistanceBetweenPoints . java <nl> similarity index 100 % <nl> rename from code / computational_geometry / graham_scan / graham_scan . java <nl> rename to code / computational_geometry / graham_scan / GrahamScan . java <nl> similarity index 100 % <nl> rename from code / data_structures / linked_list / doubly_linked_list / doubly_linked_list . java <nl> rename to code / data_structures / linked_list / doubly_linked_list / DoublyLinkedList . java <nl> similarity index 100 % <nl> rename from code / data_structures / linked_list / linked_list / singly_linked_list . java <nl> rename to code / data_structures / linked_list / linked_list / SinglyLinkedList . java <nl> similarity index 100 % <nl> rename from code / sorting / pigeonhole_sort / pigeonhole_sort . java <nl> rename to code / sorting / pigeonhole_sort / PigeonHoleSort . java <nl> similarity index 100 % <nl> rename from code / sorting / stooge_sort / Stooge_Sort . java <nl> rename to code / sorting / stooge_sort / StoogeSort . java <nl> | Merge pull request from jsmayo / jsmayo - rename - 1 | OpenGenus/cosmos | fc457220b1d1c93ac1088893da2bf9cad31b7639 | 2017-10-28T15:09:43Z |
mmm a / src / csharp / Grpc . Core . Api / Grpc . Core . Api . csproj <nl> ppp b / src / csharp / Grpc . Core . Api / Grpc . Core . Api . csproj <nl> <nl> < Import Project = " . . \ Grpc . Core \ SourceLink . csproj . include " / > <nl> <nl> < ItemGroup > <nl> - < PackageReference Include = " System . Interactive . Async " Version = " 3 . 1 . 1 " / > <nl> + < PackageReference Include = " System . Interactive . Async " Version = " 3 . 2 . 0 " / > <nl> < / ItemGroup > <nl> <nl> < ItemGroup Condition = " ' $ ( TargetFramework ) ' = = ' net45 ' " > <nl> mmm a / src / csharp / Grpc . Core / Grpc . Core . csproj <nl> ppp b / src / csharp / Grpc . Core / Grpc . Core . csproj <nl> <nl> < / ItemGroup > <nl> <nl> < ItemGroup > <nl> - < PackageReference Include = " System . Interactive . Async " Version = " 3 . 1 . 1 " / > <nl> + < PackageReference Include = " System . Interactive . Async " Version = " 3 . 2 . 0 " / > <nl> < / ItemGroup > <nl> <nl> < ItemGroup Condition = " ' $ ( TargetFramework ) ' = = ' net45 ' " > <nl> | Merge pull request from jtattermusch / upgrade_async_320 | grpc/grpc | 6d30b5933909b4e882ba9e4c909fecce38b78e6c | 2019-02-11T16:53:19Z |
mmm a / build / cocos2d_libs . xcodeproj / project . pbxproj . REMOVED . git - id <nl> ppp b / build / cocos2d_libs . xcodeproj / project . pbxproj . REMOVED . git - id <nl> @ @ - 1 + 1 @ @ <nl> - dfbc1763de24004bc22496be8456fc4a21fda7b4 <nl> \ No newline at end of file <nl> + 695569fbf5580abb74dbc9b9d9fc7ad8d21db805 <nl> \ No newline at end of file <nl> mmm a / cocos / gui / UIHelper . h <nl> ppp b / cocos / gui / UIHelper . h <nl> class UIHelper <nl> / * * <nl> * Default destructor <nl> * / <nl> - ~ UIHelper ( ) ; <nl> + virtual ~ UIHelper ( ) ; <nl> <nl> / / initializes state of UIHelper . <nl> void init ( ) ; <nl> mmm a / cocos / scripting / CMakeLists . txt <nl> ppp b / cocos / scripting / CMakeLists . txt <nl> <nl> set ( LUABINDING_SRC <nl> auto - generated / lua - bindings / lua_cocos2dx_auto . cpp <nl> auto - generated / lua - bindings / lua_cocos2dx_extension_auto . cpp <nl> + auto - generated / lua - bindings / lua_cocos2dx_studio_auto . cpp <nl> lua / bindings / tolua_fix . c <nl> lua / bindings / CCLuaBridge . cpp <nl> lua / bindings / CCLuaEngine . cpp <nl> mmm a / cocos / scripting / lua / bindings / Android . mk <nl> ppp b / cocos / scripting / lua / bindings / Android . mk <nl> LOCAL_SRC_FILES : = CCLuaBridge . cpp \ <nl> LuaBasicConversions . cpp \ <nl> . . / . . / auto - generated / lua - bindings / lua_cocos2dx_auto . cpp \ <nl> . . / . . / auto - generated / lua - bindings / lua_cocos2dx_extension_auto . cpp \ <nl> + . . / . . / auto - generated / lua - bindings / lua_cocos2dx_studio_auto . cpp \ <nl> lua_cocos2dx_manual . cpp \ <nl> lua_cocos2dx_extension_manual . cpp \ <nl> lua_cocos2dx_deprecated . cpp \ <nl> mmm a / cocos / scripting / lua / bindings / CCLuaStack . cpp <nl> ppp b / cocos / scripting / lua / bindings / CCLuaStack . cpp <nl> extern " C " { <nl> # include " lua_cocos2dx_extension_manual . h " <nl> # include " lua_cocos2dx_deprecated . h " <nl> # include " lua_xml_http_request . h " <nl> + # include " lua_cocos2dx_studio_auto . hpp " <nl> <nl> namespace { <nl> int lua_print ( lua_State * luastate ) <nl> bool LuaStack : : init ( void ) <nl> register_all_cocos2dx_deprecated ( _state ) ; <nl> register_cocos2dx_extension_CCBProxy ( _state ) ; <nl> tolua_opengl_open ( _state ) ; <nl> + register_all_cocos2dx_studio ( _state ) ; <nl> register_all_cocos2dx_manual ( _state ) ; <nl> register_all_cocos2dx_extension_manual ( _state ) ; <nl> register_all_cocos2dx_manual_deprecated ( _state ) ; <nl> mmm a / cocos / scripting / lua / bindings / Makefile <nl> ppp b / cocos / scripting / lua / bindings / Makefile <nl> SOURCES = . . / . . / . . / . . / external / lua / lua / lapi . c \ <nl> tolua_fix . c \ <nl> . . / . . / auto - generated / lua - bindings / lua_cocos2dx_auto . cpp \ <nl> . . / . . / auto - generated / lua - bindings / lua_cocos2dx_extension_auto . cpp \ <nl> + . . / . . / auto - generated / lua - bindings / lua_cocos2dx_studio_auto . cpp \ <nl> CCLuaBridge . cpp \ <nl> CCLuaEngine . cpp \ <nl> CCLuaStack . cpp \ <nl> mmm a / samples / Lua / TestLua / Resources / luaScript / ExtensionTest / ArmatureTest . lua <nl> ppp b / samples / Lua / TestLua / Resources / luaScript / ExtensionTest / ArmatureTest . lua <nl> local scheduler = cc . Director : getInstance ( ) : getScheduler ( ) <nl> local ArmatureTestIndex = <nl> { <nl> TEST_COCOSTUDIO_WITH_SKELETON = 1 , <nl> - TEST_COCOSTUDIO_WITHOUT_SKELETON = 2 , <nl> - TEST_DRAGON_BONES_2_0 = 3 , <nl> - TEST_PERFORMANCE = 4 , <nl> - TEST_CHANGE_ZORDER = 5 , <nl> - TEST_ANIMATION_EVENT = 6 , <nl> - TEST_PARTICLE_DISPLAY = 7 , <nl> - TEST_USE_DIFFERENT_PICTURE = 8 , <nl> - TEST_BOUDINGBOX = 9 , <nl> - TEST_ANCHORPOINT = 10 , <nl> - TEST_ARMATURE_NESTING = 11 , <nl> + TEST_DRAGON_BONES_2_0 = 2 , <nl> + TEST_PERFORMANCE = 3 , <nl> + TEST_CHANGE_ZORDER = 4 , <nl> + TEST_ANIMATION_EVENT = 5 , <nl> + TEST_PARTICLE_DISPLAY = 6 , <nl> + TEST_USE_DIFFERENT_PICTURE = 7 , <nl> + TEST_BOUDINGBOX = 8 , <nl> + TEST_ANCHORPOINT = 9 , <nl> + TEST_ARMATURE_NESTING = 10 , <nl> } <nl> local armatureSceneIdx = ArmatureTestIndex . TEST_COCOSTUDIO_WITH_SKELETON <nl> <nl> function ArmatureTestScene . extend ( target ) <nl> end <nl> <nl> function ArmatureTestScene : runThisTest ( ) <nl> - cc . ArmatureDataManager : getInstance ( ) : addArmatureFileInfo ( " armature / TestBone0 . png " , " armature / TestBone0 . plist " , " armature / TestBone . json " ) <nl> - cc . ArmatureDataManager : getInstance ( ) : addArmatureFileInfo ( " armature / Cowboy0 . png " , " armature / Cowboy0 . plist " , " armature / Cowboy . ExportJson " ) <nl> - cc . ArmatureDataManager : getInstance ( ) : addArmatureFileInfo ( " armature / knight . png " , " armature / knight . plist " , " armature / knight . xml " ) <nl> - cc . ArmatureDataManager : getInstance ( ) : addArmatureFileInfo ( " armature / weapon . png " , " armature / weapon . plist " , " armature / weapon . xml " ) <nl> - cc . ArmatureDataManager : getInstance ( ) : addArmatureFileInfo ( " armature / robot . png " , " armature / robot . plist " , " armature / robot . xml " ) <nl> - cc . ArmatureDataManager : getInstance ( ) : addArmatureFileInfo ( " armature / cyborg . png " , " armature / cyborg . plist " , " armature / cyborg . xml " ) <nl> - cc . ArmatureDataManager : getInstance ( ) : addArmatureFileInfo ( " armature / Dragon . png " , " armature / Dragon . plist " , " armature / Dragon . xml " ) <nl> + ccs . ArmatureDataManager : getInstance ( ) : addArmatureFileInfo ( " armature / TestBone0 . png " , " armature / TestBone0 . plist " , " armature / TestBone . json " ) <nl> + ccs . ArmatureDataManager : getInstance ( ) : addArmatureFileInfo ( " armature / Cowboy0 . png " , " armature / Cowboy0 . plist " , " armature / Cowboy . ExportJson " ) <nl> + ccs . ArmatureDataManager : getInstance ( ) : addArmatureFileInfo ( " armature / knight . png " , " armature / knight . plist " , " armature / knight . xml " ) <nl> + ccs . ArmatureDataManager : getInstance ( ) : addArmatureFileInfo ( " armature / weapon . png " , " armature / weapon . plist " , " armature / weapon . xml " ) <nl> + ccs . ArmatureDataManager : getInstance ( ) : addArmatureFileInfo ( " armature / robot . png " , " armature / robot . plist " , " armature / robot . xml " ) <nl> + ccs . ArmatureDataManager : getInstance ( ) : addArmatureFileInfo ( " armature / cyborg . png " , " armature / cyborg . plist " , " armature / cyborg . xml " ) <nl> + ccs . ArmatureDataManager : getInstance ( ) : addArmatureFileInfo ( " armature / Dragon . png " , " armature / Dragon . plist " , " armature / Dragon . xml " ) <nl> <nl> armatureSceneIdx = ArmatureTestIndex . TEST_COCOSTUDIO_WITH_SKELETON <nl> self : addChild ( restartArmatureTest ( ) ) <nl> function ArmatureTestScene . create ( ) <nl> end <nl> <nl> function ArmatureTestScene . toMainMenuCallback ( ) <nl> - cc . ArmatureDataManager : purgeArmatureSystem ( ) <nl> + ccs . ArmatureDataManager : purgeArmatureSystem ( ) <nl> end <nl> <nl> local ArmatureTestLayer = class ( " ArmatureTestLayer " ) <nl> end <nl> function ArmatureTestLayer . title ( idx ) <nl> if ArmatureTestIndex . TEST_COCOSTUDIO_WITH_SKELETON = = idx then <nl> return " Test Export From CocoStudio With Skeleton Effect " <nl> - elseif ArmatureTestIndex . TEST_COCOSTUDIO_WITHOUT_SKELETON = = idx then <nl> - return " Test Export From CocoStudio Without Skeleton Effect " <nl> elseif ArmatureTestIndex . TEST_DRAGON_BONES_2_0 = = idx then <nl> return " Test Export From DragonBones version 2 . 0 " <nl> elseif ArmatureTestIndex . TEST_PERFORMANCE = = idx then <nl> function TestCSWithSkeleton . extend ( target ) <nl> end <nl> <nl> function TestCSWithSkeleton : onEnter ( ) <nl> - local armature = cc . Armature : create ( " Cowboy " ) <nl> + local armature = ccs . Armature : create ( " Cowboy " ) <nl> armature : getAnimation ( ) : playByIndex ( 0 ) <nl> armature : setScale ( 0 . 2 ) <nl> armature : setAnchorPoint ( cc . p ( 0 . 5 , 0 . 5 ) ) <nl> function TestCSWithSkeleton . create ( ) <nl> return layer <nl> end <nl> <nl> - local TestCSWithoutSkeleton = class ( " TestCSWithoutSkeleton " , ArmatureTestLayer ) <nl> - TestCSWithoutSkeleton . __index = TestCSWithoutSkeleton <nl> - <nl> - function TestCSWithoutSkeleton . extend ( target ) <nl> - local t = tolua . getpeer ( target ) <nl> - if not t then <nl> - t = { } <nl> - tolua . setpeer ( target , t ) <nl> - end <nl> - setmetatable ( t , TestCSWithoutSkeleton ) <nl> - return target <nl> - end <nl> - <nl> - function TestCSWithoutSkeleton : onEnter ( ) <nl> - local armature = cc . Armature : create ( " TestBone " ) <nl> - armature : getAnimation ( ) : playByIndex ( 0 ) <nl> - armature : setScale ( 0 . 2 ) <nl> - armature : setAnchorPoint ( cc . p ( 0 . 5 , 0 . 5 ) ) <nl> - armature : setPosition ( cc . p ( winSize . width / 2 , winSize . height / 2 ) ) <nl> - self : addChild ( armature ) <nl> - end <nl> - <nl> - function TestCSWithoutSkeleton . create ( ) <nl> - local layer = TestCSWithoutSkeleton . extend ( cc . Layer : create ( ) ) <nl> - <nl> - if nil ~ = layer then <nl> - layer : createMenu ( ) <nl> - layer : createToExtensionMenu ( ) <nl> - layer : onEnter ( ) <nl> - layer : creatTitleAndSubTitle ( armatureSceneIdx ) <nl> - end <nl> - return layer <nl> - end <nl> - <nl> local TestDragonBones20 = class ( " TestDragonBones20 " , ArmatureTestLayer ) <nl> TestDragonBones20 . __index = TestDragonBones20 <nl> <nl> function TestDragonBones20 . extend ( target ) <nl> end <nl> <nl> function TestDragonBones20 : onEnter ( ) <nl> - local armature = cc . Armature : create ( " Dragon " ) <nl> + local armature = ccs . Armature : create ( " Dragon " ) <nl> armature : getAnimation ( ) : playByIndex ( 1 ) <nl> armature : getAnimation ( ) : setAnimationScale ( 0 . 4 ) <nl> armature : setScale ( 0 . 6 ) <nl> function TestPerformance . update ( delta ) <nl> TestPerformance . times = TestPerformance . times + delta <nl> if TestPerformance . times > 0 . 25 then <nl> TestPerformance . time = 0 <nl> - local armature = cc . Armature : create ( " Knight_f / Knight " ) <nl> + local armature = ccs . Armature : create ( " Knight_f / Knight " ) <nl> armature : getAnimation ( ) : playByIndex ( 0 ) <nl> armature : setPosition ( cc . p ( 50 + TestPerformance . armatureCount * 5 , winSize . height / 2 ) ) <nl> armature : setScale ( 0 . 6 ) <nl> function TestPerformance . create ( ) <nl> return layer <nl> end <nl> <nl> - local TestCSWithoutSkeleton = class ( " TestCSWithoutSkeleton " , ArmatureTestLayer ) <nl> - TestCSWithoutSkeleton . __index = TestCSWithoutSkeleton <nl> - <nl> - function TestCSWithoutSkeleton . extend ( target ) <nl> - local t = tolua . getpeer ( target ) <nl> - if not t then <nl> - t = { } <nl> - tolua . setpeer ( target , t ) <nl> - end <nl> - setmetatable ( t , TestCSWithoutSkeleton ) <nl> - return target <nl> - end <nl> - <nl> - function TestCSWithoutSkeleton : onEnter ( ) <nl> - local armature = cc . Armature : create ( " TestBone " ) <nl> - armature : getAnimation ( ) : playByIndex ( 0 ) <nl> - armature : setScale ( 0 . 2 ) <nl> - armature : setAnchorPoint ( cc . p ( 0 . 5 , 0 . 5 ) ) <nl> - armature : setPosition ( cc . p ( winSize . width / 2 , winSize . height / 2 ) ) <nl> - self : addChild ( armature ) <nl> - end <nl> - <nl> - function TestCSWithoutSkeleton . create ( ) <nl> - local layer = TestCSWithoutSkeleton . extend ( cc . Layer : create ( ) ) <nl> - <nl> - if nil ~ = layer then <nl> - layer : createMenu ( ) <nl> - layer : createToExtensionMenu ( ) <nl> - layer : onEnter ( ) <nl> - layer : creatTitleAndSubTitle ( armatureSceneIdx ) <nl> - end <nl> - return layer <nl> - end <nl> - <nl> local TestChangeZorder = class ( " TestChangeZorder " , ArmatureTestLayer ) <nl> TestChangeZorder . __index = TestChangeZorder <nl> TestChangeZorder . currentTag = - 1 <nl> end <nl> function TestChangeZorder : onEnter ( ) <nl> self . currentTag = - 1 <nl> <nl> - local armature = cc . Armature : create ( " Knight_f / Knight " ) <nl> + local armature = ccs . Armature : create ( " Knight_f / Knight " ) <nl> armature : getAnimation ( ) : playByIndex ( 0 ) <nl> armature : setPosition ( cc . p ( winSize . width / 2 , winSize . height / 2 - 100 ) ) <nl> armature : setScale ( 0 . 6 ) <nl> self . currentTag = self . currentTag + 1 <nl> self : addChild ( armature , self . currentTag , self . currentTag ) <nl> <nl> - armature = cc . Armature : create ( " TestBone " ) <nl> + armature = ccs . Armature : create ( " Cowboy " ) <nl> armature : getAnimation ( ) : playByIndex ( 0 ) <nl> armature : setScale ( 0 . 24 ) <nl> armature : setPosition ( cc . p ( winSize . width / 2 , winSize . height / 2 - 100 ) ) <nl> self . currentTag = self . currentTag + 1 <nl> self : addChild ( armature , self . currentTag , self . currentTag ) <nl> <nl> - armature = cc . Armature : create ( " Dragon " ) <nl> + armature = ccs . Armature : create ( " Dragon " ) <nl> armature : getAnimation ( ) : playByIndex ( 0 ) <nl> armature : setPosition ( cc . p ( winSize . width / 2 , winSize . height / 2 - 100 ) ) <nl> armature : setScale ( 0 . 6 ) <nl> function TestAnimationEvent . extend ( target ) <nl> end <nl> <nl> function TestAnimationEvent : onEnter ( ) <nl> - local armature = cc . Armature : create ( " Cowboy " ) <nl> + local armature = ccs . Armature : create ( " Cowboy " ) <nl> armature : getAnimation ( ) : play ( " Fire " ) <nl> armature : setScaleX ( - 0 . 24 ) <nl> armature : setScaleY ( 0 . 24 ) <nl> function TestParticleDisplay : onEnter ( ) <nl> self : setTouchEnabled ( true ) <nl> self . animationID = 0 <nl> <nl> - self . armature = cc . Armature : create ( " robot " ) <nl> + self . armature = ccs . Armature : create ( " robot " ) <nl> self . armature : getAnimation ( ) : playByIndex ( 0 ) <nl> self . armature : setPosition ( VisibleRect : center ( ) ) <nl> self . armature : setScale ( 0 . 48 ) <nl> self : addChild ( self . armature ) <nl> <nl> - local displayData = cc . ParticleDisplayData : create ( ) <nl> - displayData : setParam ( " Particles / SmallSun . plist " ) <nl> + local p1 = cc . ParticleSystemQuad : create ( " Particles / SmallSun . plist " ) <nl> + local p2 = cc . ParticleSystemQuad : create ( " Particles / SmallSun . plist " ) <nl> <nl> - local bone = cc . Bone : create ( " p1 " ) <nl> - bone : addDisplay ( displayData , 0 ) <nl> + local bone = ccs . Bone : create ( " p1 " ) <nl> + bone : addDisplay ( p1 , 0 ) <nl> bone : changeDisplayByIndex ( 0 , true ) <nl> bone : setIgnoreMovementBoneData ( true ) <nl> bone : setZOrder ( 100 ) <nl> bone : setScale ( 1 . 2 ) <nl> self . armature : addBone ( bone , " bady - a3 " ) <nl> <nl> - bone = cc . Bone : create ( " p2 " ) <nl> - bone : addDisplay ( displayData , 0 ) <nl> + bone = ccs . Bone : create ( " p2 " ) <nl> + bone : addDisplay ( p2 , 0 ) <nl> bone : changeDisplayByIndex ( 0 , true ) <nl> bone : setIgnoreMovementBoneData ( true ) <nl> bone : setZOrder ( 100 ) <nl> function TestUseMutiplePicture : onEnter ( ) <nl> self : setTouchEnabled ( true ) <nl> self . displayIndex = 1 <nl> <nl> - self . armature = cc . Armature : create ( " Knight_f / Knight " ) <nl> + self . armature = ccs . Armature : create ( " Knight_f / Knight " ) <nl> self . armature : getAnimation ( ) : playByIndex ( 0 ) <nl> self . armature : setPosition ( cc . p ( VisibleRect : left ( ) . x + 70 , VisibleRect : left ( ) . y ) ) <nl> self . armature : setScale ( 1 . 2 ) <nl> function TestUseMutiplePicture : onEnter ( ) <nl> " weapon_f - hammer . png " , <nl> } ; <nl> <nl> - local spriteDisplayData = cc . SpriteDisplayData : create ( ) <nl> local i = 1 <nl> for i = 1 , table . getn ( weapon ) do <nl> - spriteDisplayData : setParam ( weapon [ i ] ) <nl> - self . armature : getBone ( " weapon " ) : addDisplay ( spriteDisplayData , i - 1 ) <nl> + local skin = ccs . Skin : createWithSpriteFrameName ( weapon [ i ] ) <nl> + self . armature : getBone ( " weapon " ) : addDisplay ( skin , i - 1 ) <nl> end <nl> <nl> local function onTouchBegan ( x , y ) <nl> function TestBoundingBox . extend ( target ) <nl> end <nl> <nl> function TestBoundingBox : onEnter ( ) <nl> - local armature = cc . Armature : create ( " Cowboy " ) <nl> + local armature = ccs . Armature : create ( " Cowboy " ) <nl> armature : getAnimation ( ) : playByIndex ( 0 ) <nl> armature : setPosition ( VisibleRect : center ( ) ) <nl> armature : setScale ( 0 . 2 ) <nl> end <nl> function TestAnchorPoint : onEnter ( ) <nl> local i = 1 <nl> for i = 1 , 5 do <nl> - local armature = cc . Armature : create ( " Cowboy " ) <nl> + local armature = ccs . Armature : create ( " Cowboy " ) <nl> armature : getAnimation ( ) : playByIndex ( 0 ) ; <nl> armature : setPosition ( VisibleRect : center ( ) ) <nl> armature : setScale ( 0 . 2 ) <nl> function TestArmatureNesting : onEnter ( ) <nl> self : setTouchEnabled ( true ) <nl> self . weaponIndex = 0 <nl> <nl> - self . armature = cc . Armature : create ( " cyborg " ) <nl> + self . armature = ccs . Armature : create ( " cyborg " ) <nl> self . armature : getAnimation ( ) : playByIndex ( 1 ) <nl> self . armature : setPosition ( VisibleRect : center ( ) ) <nl> self . armature : setScale ( 1 . 2 ) <nl> end <nl> local armatureSceneArr = <nl> { <nl> TestCSWithSkeleton . create , <nl> - TestCSWithoutSkeleton . create , <nl> TestDragonBones20 . create , <nl> TestPerformance . create , <nl> TestChangeZorder . create , <nl> mmm a / tools / bindings - generator <nl> ppp b / tools / bindings - generator <nl> @ @ - 1 + 1 @ @ <nl> - Subproject commit eb2dbfef01a1d43691f31386069b65c319e41e2c <nl> + Subproject commit d41959ab0b15c20aa0802ab5c9ef92be7b742bd4 <nl> mmm a / tools / tolua / cocos2dx_extension . ini <nl> ppp b / tools / tolua / cocos2dx_extension . ini <nl> android_flags = - D_SIZE_T_DEFINED_ <nl> clang_headers = - I % ( clangllvmdir ) s / lib / clang / 3 . 3 / include <nl> clang_flags = - nostdinc - x c + + - std = c + + 11 <nl> <nl> - cocos_headers = - I % ( cocosdir ) s / cocos - I % ( cocosdir ) s / cocos / 2d - I % ( cocosdir ) s / cocos / base - I % ( cocosdir ) s / cocos / gui - I % ( cocosdir ) s / cocos / physics - I % ( cocosdir ) s / cocos / 2d / platform - I % ( cocosdir ) s / cocos / 2d / platform / android - I % ( cocosdir ) s / cocos / math / kazmath / include - I % ( cocosdir ) s / extensions - I % ( cocosdir ) s / external - I % ( cocosdir ) s / cocos / editor - support - I % ( cocosdir ) s <nl> + cocos_headers = - I % ( cocosdir ) s / cocos - I % ( cocosdir ) s / cocos / 2d - I % ( cocosdir ) s / cocos / base - I % ( cocosdir ) s / cocos / physics - I % ( cocosdir ) s / cocos / 2d / platform - I % ( cocosdir ) s / cocos / 2d / platform / android - I % ( cocosdir ) s / cocos / math / kazmath / include - I % ( cocosdir ) s / extensions - I % ( cocosdir ) s / external - I % ( cocosdir ) s / cocos / editor - support - I % ( cocosdir ) s <nl> + <nl> cocos_flags = - DANDROID - DCOCOS2D_JAVASCRIPT <nl> <nl> cxxgenerator_headers = <nl> cxxgenerator_headers = <nl> extra_arguments = % ( android_headers ) s % ( clang_headers ) s % ( cxxgenerator_headers ) s % ( cocos_headers ) s % ( android_flags ) s % ( clang_flags ) s % ( cocos_flags ) s % ( extra_flags ) s <nl> <nl> # what headers to parse <nl> - headers = % ( cocosdir ) s / extensions / cocos - ext . h % ( cocosdir ) s / cocos / editor - support / cocosbuilder / CocosBuilder . h % ( cocosdir ) s / cocos / editor - support / cocostudio / CocoStudio . h <nl> + headers = % ( cocosdir ) s / extensions / cocos - ext . h % ( cocosdir ) s / cocos / editor - support / cocosbuilder / CocosBuilder . h <nl> <nl> # what classes to produce code for . You can use regular expressions here . When testing the regular <nl> # expression , it will be enclosed in " ^ $ " , like this : " ^ Menu * $ " . <nl> - classes = AssetsManager . * CCBReader . * CCBAnimationManager . * Scale9Sprite Control . * ControlButton . * ScrollView $ TableView $ TableViewCell $ EditBox $ Armature ArmatureAnimation Skin Bone ArmatureDataManager \ w + Data $ <nl> + classes = AssetsManager . * CCBReader . * CCBAnimationManager . * Scale9Sprite Control . * ControlButton . * ScrollView $ TableView $ TableViewCell $ EditBox $ <nl> <nl> # what should we skip ? in the format ClassName : : [ function function ] <nl> # ClassName is a regular expression , but will be used like this : " ^ ClassName $ " functions are also <nl> skip = CCBReader : : [ ^ CCBReader $ addOwnerCallbackName isJSControlled readByte getC <nl> AssetsManagerDelegateProtocol : : [ * ] , <nl> Control : : [ removeHandleOfControlEvent addHandleOfControlEvent ] , <nl> ControlUtils : : [ * ] , <nl> - ControlSwitchSprite : : [ * ] , <nl> - ArmatureDataManager : : [ CCArmatureDataManager ~ CCArmatureDataManager ] , <nl> - Armature : : [ createBone updateBlendType getCPBody setCPBody ( s | g ) etBlendFunc getShapeList ^ getBody $ ] , <nl> - Skin : : [ getSkinData setSkinData ] , <nl> - ArmatureAnimation : : [ updateHandler updateFrameData frameEvent ] , <nl> - Bone : : [ ( s | g ) etIgnoreMovementBoneData ] <nl> + ControlSwitchSprite : : [ * ] <nl> <nl> <nl> - rename_functions = CCBReader : : [ getAnimationManager = getActionManager setAnimationManager = setActionManager ] , <nl> - ArmatureDataManager : : [ sharedArmatureDataManager = getInstance ] <nl> + rename_functions = CCBReader : : [ getAnimationManager = getActionManager setAnimationManager = setActionManager ] <nl> <nl> rename_classes = CCBReader : : _Reader , <nl> CCBAnimationManager : : AnimationManager <nl> new file mode 100644 <nl> index 000000000000 . . 8959fd0005f5 <nl> mmm / dev / null <nl> ppp b / tools / tolua / cocos2dx_studio . ini <nl> <nl> + [ cocos2dx_studio ] <nl> + # the prefix to be added to the generated functions . You might or might not use this in your own <nl> + # templates <nl> + prefix = cocos2dx_studio <nl> + <nl> + # create a target namespace ( in javascript , this would create some code like the equiv . to ` ns = ns | | { } ` ) <nl> + # all classes will be embedded in that namespace <nl> + target_namespace = ccs <nl> + <nl> + android_headers = - I % ( androidndkdir ) s / platforms / android - 14 / arch - arm / usr / include - I % ( androidndkdir ) s / sources / cxx - stl / gnu - libstdc + + / 4 . 7 / libs / armeabi - v7a / include - I % ( androidndkdir ) s / sources / cxx - stl / gnu - libstdc + + / 4 . 7 / include <nl> + android_flags = - D_SIZE_T_DEFINED_ <nl> + <nl> + clang_headers = - I % ( clangllvmdir ) s / lib / clang / 3 . 3 / include <nl> + clang_flags = - nostdinc - x c + + - std = c + + 11 <nl> + <nl> + cocos_headers = - I % ( cocosdir ) s / cocos - I % ( cocosdir ) s / cocos / 2d - I % ( cocosdir ) s / cocos / base - I % ( cocosdir ) s / cocos / gui - I % ( cocosdir ) s / cocos / physics - I % ( cocosdir ) s / cocos / 2d / platform - I % ( cocosdir ) s / cocos / 2d / platform / android - I % ( cocosdir ) s / cocos / math / kazmath / include - I % ( cocosdir ) s / extensions - I % ( cocosdir ) s / external - I % ( cocosdir ) s / cocos / editor - support - I % ( cocosdir ) s <nl> + <nl> + cocos_flags = - DANDROID - DCOCOS2D_JAVASCRIPT <nl> + <nl> + cxxgenerator_headers = <nl> + <nl> + # extra arguments for clang <nl> + extra_arguments = % ( android_headers ) s % ( clang_headers ) s % ( cxxgenerator_headers ) s % ( cocos_headers ) s % ( android_flags ) s % ( clang_flags ) s % ( cocos_flags ) s % ( extra_flags ) s <nl> + <nl> + # what headers to parse <nl> + headers = % ( cocosdir ) s / cocos / editor - support / cocostudio / CocoStudio . h <nl> + <nl> + # what classes to produce code for . You can use regular expressions here . When testing the regular <nl> + # expression , it will be enclosed in " ^ $ " , like this : " ^ Menu * $ " . <nl> + classes = Armature ArmatureAnimation Skin Bone ArmatureDataManager \ w + Data $ <nl> + <nl> + # what should we skip ? in the format ClassName : : [ function function ] <nl> + # ClassName is a regular expression , but will be used like this : " ^ ClassName $ " functions are also <nl> + # regular expressions , they will not be surrounded by " ^ $ " . If you want to skip a whole class , just <nl> + # add a single " * " as functions . See bellow for several examples . A special class name is " * " , which <nl> + # will apply to all class names . This is a convenience wildcard to be able to skip similar named <nl> + # functions from all classes . <nl> + <nl> + skip = . * Delegate : : [ * ] , <nl> + . * Loader . * : : [ * ] , <nl> + * : : [ ^ visit $ copyWith . * onEnter . * onExit . * ^ description $ getObjectType . * HSV onTouch . * onAcc . * onKey . * onRegisterTouchListener ] , <nl> + ArmatureDataManager : : [ CCArmatureDataManager ~ CCArmatureDataManager ] , <nl> + Armature : : [ createBone updateBlendType getCPBody setCPBody ( s | g ) etBlendFunc getShapeList ^ getBody $ ] , <nl> + Skin : : [ ( s | g ) etSkinData ] , <nl> + ArmatureAnimation : : [ updateHandler updateFrameData frameEvent ] , <nl> + Bone : : [ ( s | g ) etIgnoreMovementBoneData ] <nl> + <nl> + rename_functions = ArmatureDataManager : : [ sharedArmatureDataManager = getInstance ] <nl> + <nl> + rename_classes = <nl> + <nl> + # for all class names , should we remove something when registering in the target VM ? <nl> + remove_prefix = <nl> + <nl> + # classes for which there will be no " parent " lookup <nl> + classes_have_no_parents = <nl> + <nl> + # base classes which will be skipped when their sub - classes found them . <nl> + base_classes_to_skip = Object ProcessBase <nl> + <nl> + # classes that create no constructor <nl> + # Set is special and we will use a hand - written constructor <nl> + abstract_classes = ArmatureDataManager <nl> + <nl> + # Determining whether to use script object ( js object ) to control the lifecycle of native ( cpp ) object or the other way around . Supported values are ' yes ' or ' no ' . <nl> + script_control_cpp = no <nl> + <nl> mmm a / tools / tolua / genbindings . sh <nl> ppp b / tools / tolua / genbindings . sh <nl> LD_LIBRARY_PATH = $ { CLANG_ROOT } / lib $ PYTHON_BIN $ { CXX_GENERATOR_ROOT } / generator . py <nl> <nl> echo " Generating bindings for cocos2dx_extension . . . " <nl> LD_LIBRARY_PATH = $ { CLANG_ROOT } / lib $ PYTHON_BIN $ { CXX_GENERATOR_ROOT } / generator . py $ { TO_JS_ROOT } / cocos2dx_extension . ini - s cocos2dx_extension - t lua - o $ { COCOS2DX_ROOT } / cocos / scripting / auto - generated / lua - bindings - n lua_cocos2dx_extension_auto <nl> + <nl> + echo " Generating bindings for cocos2dx_studio . . . " <nl> + LD_LIBRARY_PATH = $ { CLANG_ROOT } / lib $ PYTHON_BIN $ { CXX_GENERATOR_ROOT } / generator . py $ { TO_JS_ROOT } / cocos2dx_studio . ini - s cocos2dx_studio - t lua - o $ { COCOS2DX_ROOT } / cocos / scripting / auto - generated / lua - bindings - n lua_cocos2dx_studio_auto <nl> | Merge pull request from samuele3hu / developCCS | cocos2d/cocos2d-x | 64b9cba5d5a2a452b9203be58868384a6fc02a71 | 2013-11-05T11:24:20Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.