diff --git a/Jenkinsfile2 b/Jenkinsfile2 index 9c28489a39..6c72f8216e 100644 --- a/Jenkinsfile2 +++ b/Jenkinsfile2 @@ -423,7 +423,7 @@ pipeline { echo "${WKDIR}/restore.sh -p ${BRANCH_NAME} -n ${BUILD_ID} -c {container name}" } catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') { - timeout(time: 120, unit: 'MINUTES'){ + timeout(time: 130, unit: 'MINUTES'){ pre_test() script { sh ''' diff --git a/cmake/cmake.version b/cmake/cmake.version index a30618157b..d0d455c73d 100644 --- a/cmake/cmake.version +++ b/cmake/cmake.version @@ -2,7 +2,7 @@ IF (DEFINED VERNUMBER) SET(TD_VER_NUMBER ${VERNUMBER}) ELSE () - SET(TD_VER_NUMBER "3.0.2.5") + SET(TD_VER_NUMBER "3.0.2.6") ENDIF () IF (DEFINED VERCOMPATIBLE) diff --git a/cmake/taostools_CMakeLists.txt.in b/cmake/taostools_CMakeLists.txt.in index 94ed46e5e2..db2ae92f6e 100644 --- a/cmake/taostools_CMakeLists.txt.in +++ b/cmake/taostools_CMakeLists.txt.in @@ -2,7 +2,7 @@ # taos-tools ExternalProject_Add(taos-tools GIT_REPOSITORY https://github.com/taosdata/taos-tools.git - GIT_TAG 634399d + GIT_TAG 1e15545 SOURCE_DIR "${TD_SOURCE_DIR}/tools/taos-tools" BINARY_DIR "" #BUILD_IN_SOURCE TRUE diff --git a/docs/en/07-develop/07-tmq.mdx b/docs/en/07-develop/07-tmq.mdx index 92db7d4cbf..c85109d3c5 100644 --- a/docs/en/07-develop/07-tmq.mdx +++ b/docs/en/07-develop/07-tmq.mdx @@ -222,7 +222,7 @@ A database including one supertable and two subtables is created as follows: ```sql DROP DATABASE IF EXISTS tmqdb; CREATE DATABASE tmqdb; -CREATE TABLE tmqdb.stb (ts TIMESTAMP, c1 INT, c2 FLOAT, c3 VARCHAR(16) TAGS(t1 INT, t3 VARCHAR(16)); +CREATE TABLE tmqdb.stb (ts TIMESTAMP, c1 INT, c2 FLOAT, c3 VARCHAR(16)) TAGS(t1 INT, t3 VARCHAR(16)); CREATE TABLE tmqdb.ctb0 USING tmqdb.stb TAGS(0, "subtable0"); CREATE TABLE tmqdb.ctb1 USING tmqdb.stb TAGS(1, "subtable1"); INSERT INTO tmqdb.ctb0 VALUES(now, 0, 0, 'a0')(now+1s, 0, 0, 'a00'); diff --git a/docs/en/07-develop/_sub_java.mdx b/docs/en/07-develop/_sub_java.mdx index d14b5fd609..965161651c 100644 --- a/docs/en/07-develop/_sub_java.mdx +++ b/docs/en/07-develop/_sub_java.mdx @@ -1,11 +1,31 @@ -```java -{{#include docs/examples/java/src/main/java/com/taos/example/SubscribeDemo.java}} -{{#include docs/examples/java/src/main/java/com/taos/example/MetersDeserializer.java}} -{{#include docs/examples/java/src/main/java/com/taos/example/Meters.java}} -``` -```java -{{#include docs/examples/java/src/main/java/com/taos/example/MetersDeserializer.java}} -``` -```java -{{#include docs/examples/java/src/main/java/com/taos/example/Meters.java}} -``` \ No newline at end of file +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + + + + ```java + {{#include docs/examples/java/src/main/java/com/taos/example/SubscribeDemo.java}} + ``` + ```java + {{#include docs/examples/java/src/main/java/com/taos/example/MetersDeserializer.java}} + ``` + ```java + {{#include docs/examples/java/src/main/java/com/taos/example/Meters.java}} + ``` + + + + + ```java + {{#include docs/examples/java/src/main/java/com/taos/example/WebsocketSubscribeDemo.java}} + ``` + ```java + {{#include docs/examples/java/src/main/java/com/taos/example/MetersDeserializer.java}} + ``` + ```java + {{#include docs/examples/java/src/main/java/com/taos/example/Meters.java}} + ``` + + + diff --git a/docs/en/12-taos-sql/10-function.md b/docs/en/12-taos-sql/10-function.md index 2eb4bba309..b32d2af5bb 100644 --- a/docs/en/12-taos-sql/10-function.md +++ b/docs/en/12-taos-sql/10-function.md @@ -796,19 +796,23 @@ HISTOGRAM(expr,bin_type, bin_description, normalized) ### PERCENTILE ```sql -PERCENTILE(expr, p) +PERCENTILE(expr, p [, p1] ...) ``` **Description**: The value whose rank in a specific column matches the specified percentage. If such a value matching the specified percentage doesn't exist in the column, an interpolation value will be returned. -**Return value type**: DOUBLE +**Return value type**: This function takes 2 minumum and 11 maximum parameters, and it can simultaneously return 10 percentiles at most. If 2 parameters are given, a single percentile is returned and the value type is DOUBLE. + If more than 2 parameters are given, the return value type is a VARCHAR string, the format of which is a JSON ARRAY containing all return values. **Applicable column types**: Numeric **Applicable table types**: table only -**More explanations**: _p_ is in range [0,100], when _p_ is 0, the result is same as using function MIN; when _p_ is 100, the result is same as function MAX. +**More explanations**: +- _p_ is in range [0,100], when _p_ is 0, the result is same as using function MIN; when _p_ is 100, the result is same as function MAX. +- When calculating multiple percentiles of a specific column, a single PERCENTILE function with multiple parameters is adviced, as this can largely reduce the query response time. + For example, using SELECT percentile(col, 90, 95, 99) FROM table will perform better than SELECT percentile(col, 90), percentile(col, 95), percentile(col, 99) from table. ## Selection Functions diff --git a/docs/en/14-reference/03-connector/04-java.mdx b/docs/en/14-reference/03-connector/04-java.mdx index 61ce166069..36992da636 100644 --- a/docs/en/14-reference/03-connector/04-java.mdx +++ b/docs/en/14-reference/03-connector/04-java.mdx @@ -696,6 +696,9 @@ TaosConsumer consumer = new TaosConsumer<>(config); - enable.auto.commit: Specifies whether to commit automatically. - group.id: consumer: Specifies the group that the consumer is in. - value.deserializer: To deserialize the results, you can inherit `com.taosdata.jdbc.tmq.ReferenceDeserializer` and specify the result set bean. You can also inherit `com.taosdata.jdbc.tmq.Deserializer` and perform custom deserialization based on the SQL result set. +- td.connect.type: Specifies the type connect with TDengine, `jni` or `WebSocket`. default is `jni` +- httpConnectTimeout:WebSocket connection timeout in milliseconds, the default value is 5000 ms. It only takes effect when using WebSocket type. +- messageWaitTimeout:socket timeout in milliseconds, the default value is 10000 ms. It only takes effect when using WebSocket type. - For more information, see [Consumer Parameters](../../../develop/tmq). #### Subscribe to consume data @@ -724,6 +727,11 @@ For more information, see [Data Subscription](../../../develop/tmq). ### Usage examples + + + +In addition to the native connection, the Java Connector also supports subscribing via websocket. + ```java public abstract class ConsumerLoop { private final TaosConsumer consumer; @@ -795,6 +803,87 @@ public abstract class ConsumerLoop { } ``` + + + +```java +public abstract class ConsumerLoop { + private final TaosConsumer consumer; + private final List topics; + private final AtomicBoolean shutdown; + private final CountDownLatch shutdownLatch; + + public ConsumerLoop() throws SQLException { + Properties config = new Properties(); + config.setProperty("bootstrap.servers", "localhost:6041"); + config.setProperty("td.connect.type", "ws"); + config.setProperty("msg.with.table.name", "true"); + config.setProperty("enable.auto.commit", "true"); + config.setProperty("group.id", "group2"); + config.setProperty("value.deserializer", "com.taosdata.jdbc.tmq.ConsumerTest.ConsumerLoop$ResultDeserializer"); + + this.consumer = new TaosConsumer<>(config); + this.topics = Collections.singletonList("topic_speed"); + this.shutdown = new AtomicBoolean(false); + this.shutdownLatch = new CountDownLatch(1); + } + + public abstract void process(ResultBean result); + + public void pollData() throws SQLException { + try { + consumer.subscribe(topics); + + while (!shutdown.get()) { + ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); + for (ResultBean record : records) { + process(record); + } + } + consumer.unsubscribe(); + } finally { + consumer.close(); + shutdownLatch.countDown(); + } + } + + public void shutdown() throws InterruptedException { + shutdown.set(true); + shutdownLatch.await(); + } + + public static class ResultDeserializer extends ReferenceDeserializer { + + } + + public static class ResultBean { + private Timestamp ts; + private int speed; + + public Timestamp getTs() { + return ts; + } + + public void setTs(Timestamp ts) { + this.ts = ts; + } + + public int getSpeed() { + return speed; + } + + public void setSpeed(int speed) { + this.speed = speed; + } + } +} +``` + + + + +> **Note**: The value of value.deserializer should be adjusted based on the package path of the test environment. + ### Use with connection pool #### HikariCP @@ -878,8 +967,8 @@ The source code of the sample application is under `TDengine/examples/JDBC`: | taos-jdbcdriver version | major changes | | :---------------------: | :--------------------------------------------: | -| 3.0.3 | fix timestamp resolution error for REST connection in jdk17+ version | -| 3.0.1 - 3.0.2 | fix the resultSet data is parsed incorrectly sometimes. 3.0.1 is compiled on JDK 11, you are advised to use 3.0.2 in the JDK 8 environment | +| 3.1.0 | JDBC REST connection supports subscription over WebSocket | +| 3.0.1 - 3.0.4 | fix the resultSet data is parsed incorrectly sometimes. 3.0.1 is compiled on JDK 11, you are advised to use other version in the JDK 8 environment | | 3.0.0 | Support for TDengine 3.0 | | 2.0.42 | fix wasNull interface return value in WebSocket connection | | 2.0.41 | fix decode method of username and password in REST connection | diff --git a/docs/en/14-reference/11-docker/index.md b/docs/en/14-reference/11-docker/index.md index b9278c6961..5a48f2e4b1 100644 --- a/docs/en/14-reference/11-docker/index.md +++ b/docs/en/14-reference/11-docker/index.md @@ -273,49 +273,48 @@ password: taosdata ## Start the TDengine cluster with docker-compose -1. The following docker-compose file starts a TDengine cluster with two replicas, two management nodes, two data nodes, and one arbitrator. +1. The following docker-compose file starts a TDengine cluster with three nodes. - ```docker - version: "3" - services: - arbitrator: - image: tdengine/tdengine:$VERSION - command: tarbitrator - td-1: - image: tdengine/tdengine:$VERSION - environment: - TAOS_FQDN: "td-1" - TAOS_FIRST_EP: "td-1" - TAOS_NUM_OF_MNODES: "2" - TAOS_REPLICA: "2" - TAOS_ARBITRATOR: arbitrator:6042 - volumes: - - taosdata-td1:/var/lib/taos/ - - taoslog-td1:/var/log/taos/ - td-2: - image: tdengine/tdengine:$VERSION - environment: - TAOS_FQDN: "td-2" - TAOS_FIRST_EP: "td-1" - TAOS_NUM_OF_MNODES: "2" - TAOS_REPLICA: "2" - TAOS_ARBITRATOR: arbitrator:6042 - volumes: - - taosdata-td2:/var/lib/taos/ - - taoslog-td2:/var/log/taos/ - volumes: - taosdata-td1: - taoslog-td1: - taosdata-td2: - taoslog-td2: - ``` +```yml +version: "3" +services: + td-1: + image: tdengine/tdengine:$VERSION + environment: + TAOS_FQDN: "td-1" + TAOS_FIRST_EP: "td-1" + volumes: + - taosdata-td1:/var/lib/taos/ + - taoslog-td1:/var/log/taos/ + td-2: + image: tdengine/tdengine:$VERSION + environment: + TAOS_FQDN: "td-2" + TAOS_FIRST_EP: "td-1" + volumes: + - taosdata-td2:/var/lib/taos/ + - taoslog-td2:/var/log/taos/ + td-3: + image: tdengine/tdengine:$VERSION + environment: + TAOS_FQDN: "td-3" + TAOS_FIRST_EP: "td-1" + volumes: + - taosdata-td3:/var/lib/taos/ + - taoslog-td3:/var/log/taos/ +volumes: + taosdata-td1: + taoslog-td1: + taosdata-td2: + taoslog-td2: + taosdata-td3: + taoslog-td3: +``` :::note - The `VERSION` environment variable is used to set the tdengine image tag - `TAOS_FIRST_EP` must be set on the newly created instance so that it can join the TDengine cluster; if there is a high availability requirement, `TAOS_SECOND_EP` needs to be used at the same time -- `TAOS_REPLICA` is used to set the default number of database replicas. Its value range is [1,3] - We recommend setting it with `TAOS_ARBITRATOR` to use arbitrator in a two-nodes environment. ::: 2. Start the cluster @@ -345,17 +344,18 @@ password: taosdata 4. Show dnodes via TDengine CLI - ```shell - $ docker-compose exec td-1 taos -s "show dnodes" +```shell +$ docker-compose exec td-1 taos -s "show dnodes" - taos> show dnodes - id | end_point | vnodes | cores | status | role | create_time | offline reason | - ====================================================================================================================================== - 1 | td-1:6030 | 1 | 8 | ready | any | 2022-01-18 02:47:42.871 | | - 2 | td-2:6030 | 0 | 8 | ready | any | 2022-01-18 02:47:43.518 | | - 0 | arbitrator:6042 | 0 | 0 | ready | arb | 2022-01-18 02:47:43.633 | - | - Query OK, 3 row(s) in set (0.000811s) - ``` +taos> show dnodes + id | endpoint | vnodes | support_vnodes | status | create_time | note | +====================================================================================================================================== + 1 | td-1:6030 | 0 | 32 | ready | 2022-08-19 07:57:29.971 | | + 2 | td-2:6030 | 0 | 32 | ready | 2022-08-19 07:57:31.415 | | + 3 | td-3:6030 | 0 | 32 | ready | 2022-08-19 07:57:31.417 | | +Query OK, 3 rows in database (0.021262s) + +``` ## taosAdapter @@ -373,83 +373,70 @@ password: taosdata Suppose you want to deploy multiple taosAdapters to improve throughput and provide high availability. In that case, the recommended configuration method uses a reverse proxy such as Nginx to offer a unified access entry. For specific configuration methods, please refer to the official documentation of Nginx. Here is an example: - ```docker - version: "3" +```yml +version: "3" - networks: - inter: - api: +networks: + inter: - services: - arbitrator: - image: tdengine/tdengine:$VERSION - command: tarbitrator - networks: - - inter - td-1: - image: tdengine/tdengine:$VERSION - networks: - - inter - environment: - TAOS_FQDN: "td-1" - TAOS_FIRST_EP: "td-1" - TAOS_NUM_OF_MNODES: "2" - TAOS_REPLICA: "2" - TAOS_ARBITRATOR: arbitrator:6042 - volumes: - - taosdata-td1:/var/lib/taos/ - - taoslog-td1:/var/log/taos/ - td-2: - image: tdengine/tdengine:$VERSION - networks: - - inter - environment: - TAOS_FQDN: "td-2" - TAOS_FIRST_EP: "td-1" - TAOS_NUM_OF_MNODES: "2" - TAOS_REPLICA: "2" - TAOS_ARBITRATOR: arbitrator:6042 - volumes: - - taosdata-td2:/var/lib/taos/ - - taoslog-td2:/var/log/taos/ - adapter: - image: tdengine/tdengine:$VERSION - command: taosadapter - networks: - - inter - environment: - TAOS_FIRST_EP: "td-1" - TAOS_SECOND_EP: "td-2" - deploy: - replicas: 4 - nginx: - image: nginx - depends_on: - - adapter - networks: - - inter - - api - ports: - - 6041:6041 - - 6044:6044/udp - command: [ - "sh", - "-c", - "while true; - do curl -s http://adapter:6041/-/ping >/dev/null && break; - done; - printf 'server{listen 6041;location /{proxy_pass http://adapter:6041;}}' - > /etc/nginx/conf.d/rest.conf; - printf 'stream{server{listen 6044 udp;proxy_pass adapter:6044;}}' - >> /etc/nginx/nginx.conf;cat /etc/nginx/nginx.conf; - nginx -g 'daemon off;'", - ] - volumes: - taosdata-td1: - taoslog-td1: - taosdata-td2: - taoslog-td2: - ``` +services: + td-1: + image: tdengine/tdengine:$VERSION + networks: + - inter + environment: + TAOS_FQDN: "td-1" + TAOS_FIRST_EP: "td-1" + volumes: + - taosdata-td1:/var/lib/taos/ + - taoslog-td1:/var/log/taos/ + td-2: + image: tdengine/tdengine:$VERSION + networks: + - inter + environment: + TAOS_FQDN: "td-2" + TAOS_FIRST_EP: "td-1" + volumes: + - taosdata-td2:/var/lib/taos/ + - taoslog-td2:/var/log/taos/ + adapter: + image: tdengine/tdengine:$VERSION + entrypoint: "taosadapter" + networks: + - inter + environment: + TAOS_FIRST_EP: "td-1" + TAOS_SECOND_EP: "td-2" + deploy: + replicas: 4 + nginx: + image: nginx + depends_on: + - adapter + networks: + - inter + ports: + - 6041:6041 + - 6044:6044/udp + command: [ + "sh", + "-c", + "while true; + do curl -s http://adapter:6041/-/ping >/dev/null && break; + done; + printf 'server{listen 6041;location /{proxy_pass http://adapter:6041;}}' + > /etc/nginx/conf.d/rest.conf; + printf 'stream{server{listen 6044 udp;proxy_pass adapter:6044;}}' + >> /etc/nginx/nginx.conf;cat /etc/nginx/nginx.conf; + nginx -g 'daemon off;'", + ] +volumes: + taosdata-td1: + taoslog-td1: + taosdata-td2: + taoslog-td2: +``` ## Deploy with docker swarm diff --git a/docs/en/25-application/03-immigrate.md b/docs/en/25-application/_03-immigrate.md similarity index 99% rename from docs/en/25-application/03-immigrate.md rename to docs/en/25-application/_03-immigrate.md index 30d069e4e2..5f4a86937e 100644 --- a/docs/en/25-application/03-immigrate.md +++ b/docs/en/25-application/_03-immigrate.md @@ -184,7 +184,7 @@ TDengine supports the standard JDBC 3.0 interface for manipulating databases, bu To facilitate historical data migration, we provide a plug-in for the data synchronization tool DataX, which can automatically write data into TDengine.The automatic data migration of DataX can only support the data migration process of a single value model. -For the specific usage of DataX and how to use DataX to write data to TDengine, please refer to [DataX-based TDengine Data Migration Tool](https://www.taosdata.com/blog/2021/10/26/3156.html). +For the specific usage of DataX and how to use DataX to write data to TDengine, please refer to [DataX-based TDengine Data Migration Tool](https://www.taosdata.com/engineering/16401.html). After migrating via DataX, we found that we can significantly improve the efficiency of migrating historical data by starting multiple processes and migrating numerous metrics simultaneously. The following are some records of the migration process. We provide these as a reference for application migration. diff --git a/docs/en/28-releases/01-tdengine.md b/docs/en/28-releases/01-tdengine.md index 0c5ccf3aef..6a62108062 100644 --- a/docs/en/28-releases/01-tdengine.md +++ b/docs/en/28-releases/01-tdengine.md @@ -10,6 +10,10 @@ For TDengine 2.x installation packages by version, please visit [here](https://w import Release from "/components/ReleaseV3"; +## 3.0.2.6 + + + ## 3.0.2.5 diff --git a/docs/en/28-releases/02-tools.md b/docs/en/28-releases/02-tools.md index 29dd605c8c..91eb0c9b8d 100644 --- a/docs/en/28-releases/02-tools.md +++ b/docs/en/28-releases/02-tools.md @@ -10,6 +10,10 @@ For other historical version installers, please visit [here](https://www.taosdat import Release from "/components/ReleaseV3"; +## 2.4.6 + + + ## 2.4.3 diff --git a/docs/examples/java/pom.xml b/docs/examples/java/pom.xml index 634c3f75a8..01d0ce936c 100644 --- a/docs/examples/java/pom.xml +++ b/docs/examples/java/pom.xml @@ -1,6 +1,7 @@ - 4.0.0 @@ -17,13 +18,13 @@ - + com.taosdata.jdbc taos-jdbcdriver - 3.0.0 + 3.1.0 - + junit junit @@ -32,4 +33,4 @@ - + \ No newline at end of file diff --git a/docs/examples/java/src/main/java/com/taos/example/WebsocketSubscribeDemo.java b/docs/examples/java/src/main/java/com/taos/example/WebsocketSubscribeDemo.java new file mode 100644 index 0000000000..d953a73641 --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/WebsocketSubscribeDemo.java @@ -0,0 +1,79 @@ +package com.taos.example; + +import com.taosdata.jdbc.tmq.ConsumerRecords; +import com.taosdata.jdbc.tmq.TMQConstants; +import com.taosdata.jdbc.tmq.TaosConsumer; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Duration; +import java.util.Collections; +import java.util.Properties; +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.atomic.AtomicBoolean; + +public class WebsocketSubscribeDemo { + private static final String TOPIC = "tmq_topic_ws"; + private static final String DB_NAME = "meters_ws"; + private static final AtomicBoolean shutdown = new AtomicBoolean(false); + + public static void main(String[] args) { + Timer timer = new Timer(); + timer.schedule(new TimerTask() { + public void run() { + shutdown.set(true); + } + }, 3_000); + try { + // prepare + Class.forName("com.taosdata.jdbc.rs.RestfulDriver"); + String jdbcUrl = "jdbc:TAOS-RS://127.0.0.1:6041/?user=root&password=taosdata&batchfetch=true"; + try (Connection connection = DriverManager.getConnection(jdbcUrl); + Statement statement = connection.createStatement()) { + statement.executeUpdate("drop topic if exists " + TOPIC); + statement.executeUpdate("drop database if exists " + DB_NAME); + statement.executeUpdate("create database " + DB_NAME); + statement.executeUpdate("use " + DB_NAME); + statement.executeUpdate( + "CREATE TABLE `meters` (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT) TAGS (`groupid` INT, `location` BINARY(24))"); + statement.executeUpdate("CREATE TABLE `d0` USING `meters` TAGS(0, 'California.LosAngles')"); + statement.executeUpdate("INSERT INTO `d0` values(now - 10s, 0.32, 116)"); + statement.executeUpdate("INSERT INTO `d0` values(now - 8s, NULL, NULL)"); + statement.executeUpdate( + "INSERT INTO `d1` USING `meters` TAGS(1, 'California.SanFrancisco') values(now - 9s, 10.1, 119)"); + statement.executeUpdate( + "INSERT INTO `d1` values (now-8s, 10, 120) (now - 6s, 10, 119) (now - 4s, 11.2, 118)"); + // create topic + statement.executeUpdate("create topic " + TOPIC + " as select * from meters"); + } + + // create consumer + Properties properties = new Properties(); + properties.setProperty(TMQConstants.BOOTSTRAP_SERVERS, "127.0.0.1:6041"); + properties.setProperty(TMQConstants.CONNECT_TYPE, "ws"); + properties.setProperty(TMQConstants.MSG_WITH_TABLE_NAME, "true"); + properties.setProperty(TMQConstants.ENABLE_AUTO_COMMIT, "true"); + properties.setProperty(TMQConstants.GROUP_ID, "test"); + properties.setProperty(TMQConstants.VALUE_DESERIALIZER, + "com.taos.example.MetersDeserializer"); + + // poll data + try (TaosConsumer consumer = new TaosConsumer<>(properties)) { + consumer.subscribe(Collections.singletonList(TOPIC)); + while (!shutdown.get()) { + ConsumerRecords meters = consumer.poll(Duration.ofMillis(100)); + for (Meters meter : meters) { + System.out.println(meter); + } + } + consumer.unsubscribe(); + } + } catch (ClassNotFoundException | SQLException e) { + e.printStackTrace(); + } + timer.cancel(); + } +} diff --git a/docs/examples/java/src/test/java/com/taos/test/TestAll.java b/docs/examples/java/src/test/java/com/taos/test/TestAll.java index 8d201da074..f24156d8b1 100644 --- a/docs/examples/java/src/test/java/com/taos/test/TestAll.java +++ b/docs/examples/java/src/test/java/com/taos/test/TestAll.java @@ -64,21 +64,15 @@ public class TestAll { @Test public void testSubscribe() { - - Thread thread = new Thread(() -> { - try { - Thread.sleep(1000); - insertData(); - } catch (SQLException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - }); - thread.start(); SubscribeDemo.main(args); } + + @Test + public void testSubscribeOverWebsocket() { + WebsocketSubscribeDemo.main(args); + } + @Test public void testSchemaless() throws SQLException { LineProtocolExample.main(args); diff --git a/docs/zh/07-develop/_sub_java.mdx b/docs/zh/07-develop/_sub_java.mdx index e7de158cc8..a0505dabad 100644 --- a/docs/zh/07-develop/_sub_java.mdx +++ b/docs/zh/07-develop/_sub_java.mdx @@ -1,3 +1,9 @@ +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + + + ```java {{#include docs/examples/java/src/main/java/com/taos/example/SubscribeDemo.java}} ``` @@ -6,4 +12,20 @@ ``` ```java {{#include docs/examples/java/src/main/java/com/taos/example/Meters.java}} -``` \ No newline at end of file +``` + + + + +```java +{{#include docs/examples/java/src/main/java/com/taos/example/WebsocketSubscribeDemo.java}} +``` +```java +{{#include docs/examples/java/src/main/java/com/taos/example/MetersDeserializer.java}} +``` +```java +{{#include docs/examples/java/src/main/java/com/taos/example/Meters.java}} +``` + + + diff --git a/docs/zh/08-connector/14-java.mdx b/docs/zh/08-connector/14-java.mdx index fc6dc57138..061475f51e 100644 --- a/docs/zh/08-connector/14-java.mdx +++ b/docs/zh/08-connector/14-java.mdx @@ -699,7 +699,10 @@ TaosConsumer consumer = new TaosConsumer<>(config); - enable.auto.commit: 是否允许自动提交。 - group.id: consumer: 所在的 group。 - value.deserializer: 结果集反序列化方法,可以继承 `com.taosdata.jdbc.tmq.ReferenceDeserializer`,并指定结果集 bean,实现反序列化。也可以继承 `com.taosdata.jdbc.tmq.Deserializer`,根据 SQL 的 resultSet 自定义反序列化方式。 -- 其他参数请参考:[Consumer 参数列表](../../../develop/tmq#创建-consumer-以及consumer-group) +- td.connect.type: 连接方式。jni:表示使用动态库连接的方式,ws/WebSocket:表示使用 WebSocket 进行数据通信。默认为 jni 方式。 +- httpConnectTimeout:创建连接超时参数,单位 ms,默认为 5000 ms。仅在 WebSocket 连接下有效。 +- messageWaitTimeout:数据传输超时参数,单位 ms,默认为 10000 ms。仅在 WebSocket 连接下有效。 +其他参数请参考:[Consumer 参数列表](../../../develop/tmq#创建-consumer-以及consumer-group) #### 订阅消费数据 @@ -727,6 +730,9 @@ consumer.close() ### 使用示例如下: + + + ```java public abstract class ConsumerLoop { private final TaosConsumer consumer; @@ -798,6 +804,89 @@ public abstract class ConsumerLoop { } ``` + + + +除了原生的连接方式,Java 连接器还支持通过 WebSocket 订阅数据。 + +```java +public abstract class ConsumerLoop { + private final TaosConsumer consumer; + private final List topics; + private final AtomicBoolean shutdown; + private final CountDownLatch shutdownLatch; + + public ConsumerLoop() throws SQLException { + Properties config = new Properties(); + config.setProperty("bootstrap.servers", "localhost:6041"); + config.setProperty("td.connect.type", "ws"); + config.setProperty("msg.with.table.name", "true"); + config.setProperty("enable.auto.commit", "true"); + config.setProperty("group.id", "group2"); + config.setProperty("value.deserializer", "com.taosdata.jdbc.tmq.ConsumerTest.ConsumerLoop$ResultDeserializer"); + + this.consumer = new TaosConsumer<>(config); + this.topics = Collections.singletonList("topic_speed"); + this.shutdown = new AtomicBoolean(false); + this.shutdownLatch = new CountDownLatch(1); + } + + public abstract void process(ResultBean result); + + public void pollData() throws SQLException { + try { + consumer.subscribe(topics); + + while (!shutdown.get()) { + ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); + for (ResultBean record : records) { + process(record); + } + } + consumer.unsubscribe(); + } finally { + consumer.close(); + shutdownLatch.countDown(); + } + } + + public void shutdown() throws InterruptedException { + shutdown.set(true); + shutdownLatch.await(); + } + + public static class ResultDeserializer extends ReferenceDeserializer { + + } + + public static class ResultBean { + private Timestamp ts; + private int speed; + + public Timestamp getTs() { + return ts; + } + + public void setTs(Timestamp ts) { + this.ts = ts; + } + + public int getSpeed() { + return speed; + } + + public void setSpeed(int speed) { + this.speed = speed; + } + } +} +``` + + + + +> **注意**:这里的 value.deserializer 配置参数值应该根据测试环境的包路径做相应的调整。 + ### 与连接池使用 #### HikariCP @@ -881,8 +970,8 @@ public static void main(String[] args) throws Exception { | taos-jdbcdriver 版本 | 主要变化 | | :------------------: | :----------------------------: | -| 3.0.3 | 修复 REST 连接在 jdk17+ 版本时间戳解析错误问题 | -| 3.0.1 - 3.0.2 | 修复一些情况下结果集数据解析错误的问题。3.0.1 在 JDK 11 环境编译,JDK 8 环境下建议使用 3.0.2 版本 | +| 3.1.0 | WebSocket 连接支持订阅功能 | +| 3.0.1 - 3.0.4 | 修复一些情况下结果集数据解析错误的问题。3.0.1 在 JDK 11 环境编译,JDK 8 环境下建议使用其他版本 | | 3.0.0 | 支持 TDengine 3.0 | | 2.0.42 | 修在 WebSocket 连接中 wasNull 接口返回值 | | 2.0.41 | 修正 REST 连接中用户名和密码转码方式 | diff --git a/docs/zh/12-taos-sql/10-function.md b/docs/zh/12-taos-sql/10-function.md index 647f917422..94f8052051 100644 --- a/docs/zh/12-taos-sql/10-function.md +++ b/docs/zh/12-taos-sql/10-function.md @@ -798,18 +798,22 @@ HISTOGRAM(expr,bin_type, bin_description, normalized) ### PERCENTILE ```sql -PERCENTILE(expr, p) +PERCENTILE(expr, p [, p1] ... ) ``` **功能说明**:统计表中某列的值百分比分位数。 -**返回数据类型**: DOUBLE。 +**返回数据类型**: 该函数最小参数个数为 2 个,最大参数个数为 11 个。可以最多同时返回 10 个百分比分位数。当参数个数为 2 时, 返回一个分位数, 类型为DOUBLE,当参数个数大于 2 时,返回类型为VARCHAR, 格式为包含多个返回值的JSON数组。 **应用字段**:数值类型。 **适用于**:表。 -**使用说明**:*P*值取值范围 0≤*P*≤100,为 0 的时候等同于 MIN,为 100 的时候等同于 MAX。 +**使用说明**: + +- *P*值取值范围 0≤*P*≤100,为 0 的时候等同于 MIN,为 100 的时候等同于 MAX; +- 同时计算针对同一列的多个分位数时,建议使用一个PERCENTILE函数和多个参数的方式,能很大程度上降低查询的响应时间。 + 比如,使用查询SELECT percentile(col, 90, 95, 99) FROM table, 性能会优于SELECT percentile(col, 90), percentile(col, 95), percentile(col, 99) from table。 ## 选择函数 diff --git a/docs/zh/12-taos-sql/24-show.md b/docs/zh/12-taos-sql/24-show.md index 0a326729f2..901548e132 100644 --- a/docs/zh/12-taos-sql/24-show.md +++ b/docs/zh/12-taos-sql/24-show.md @@ -191,37 +191,39 @@ SHOW TABLE DISTRIBUTED table_name; _block_dist: Total_Blocks=[5] Total_Size=[93.65 Kb] Average_size=[18.73 Kb] Compression_Ratio=[23.98 %] -Total_Blocks : 表d0 占用的 block 个数为 5 个 +Total_Blocks: 表 d0 占用的 block 个数为 5 个 -Total_Size. : 表 d0 所有 block 在文件中占用的大小为 93.65 KB +Total_Size: 表 d0 所有 block 在文件中占用的大小为 93.65 KB Average_size: 平均每个 block 在文件中占用的空间大小为 18.73 KB -Compression_Ratio: 数据压缩率为 23.98% +Compression_Ratio: 数据压缩率 23.98% *************************** 2.row *************************** _block_dist: Total_Rows=[20000] Inmem_Rows=[0] MinRows=[3616] MaxRows=[4096] Average_Rows=[4000] -Total_Rows: 统计表 d0 的所有行数 为20000 行 +Total_Rows: 统计表 d0 的所有行数 为20000 行(该数值仅供参考,不是精确的行数。获得精确的行数需要使用 count 函数) -Inmem_Rows: 表示仍然还存放在内存中的行数,即没有落盘的行数,为 0行,表示没有 +Inmem_Rows: 存储在写缓存中的数据行数(没有落盘),0 行表示内存缓存中没有数据 -MinRows: BLOCK 中最小的行数,为 3616 行 +MinRows: BLOCK 中最小的行数,为 3616 行 -MaxRows: BLOCK 中最大的行数,为 4096行 +MaxRows: BLOCK 中最大的行数,为 4096 行 -Average_Rows: BLOCK 中的平均行数,为4000 行 +Average_Rows: 每个 BLOCK 中的平均行数,此时为 4000 行 *************************** 3.row *************************** -_block_dist: Total_Tables=[1] Total_Files=[2] +_block_dist: Total_Tables=[1] Total_Files=[2] Total_Vgroups=[1] -Total_Tables: 表示子表的个数,这里为1 +Total_Tables: 子表的个数,这里为 1 -Total_Files: 表数据保存在几个文件中,这里保存在 2 个文件中 +Total_Files: 表数据被分别保存的数据文件数量,这里是 2 个文件 + +Total_Vgroups: 表数据分布的虚拟节点(vnode)数量 *************************** 5.row *************************** diff --git a/docs/zh/14-reference/11-docker/index.md b/docs/zh/14-reference/11-docker/index.md index 086d72940c..a6696977f9 100644 --- a/docs/zh/14-reference/11-docker/index.md +++ b/docs/zh/14-reference/11-docker/index.md @@ -309,7 +309,7 @@ services: TAOS_FIRST_EP: "td-1" volumes: - taosdata-td3:/var/lib/taos/ - - taoslog-td3:/var/log/taos/ + - taoslog-td3:/var/log/taos/ volumes: taosdata-td1: taoslog-td1: @@ -473,18 +473,18 @@ Creating service taos_adapter ```shell $ docker stack ps taos ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS -7m3sbf532bqp taos_adapter.1 tdengine/tdengine:3.0.0.0 vm98 Running Running about a minute ago -pj403n6ofmmh taos_adapter.2 tdengine/tdengine:3.0.0.0 vm98 Running Running about a minute ago -rxqfwsyk5q1h taos_adapter.3 tdengine/tdengine:3.0.0.0 vm98 Running Running about a minute ago -qj40lpxr40oc taos_adapter.4 tdengine/tdengine:3.0.0.0 vm98 Running Running about a minute ago -oe3455ulxpze taos_nginx.1 nginx:latest vm98 Running Running about a minute ago -o0tsg70nrrc6 taos_td-1.1 tdengine/tdengine:3.0.0.0 vm98 Running Running about a minute ago +7m3sbf532bqp taos_adapter.1 tdengine/tdengine:3.0.0.0 vm98 Running Running about a minute ago +pj403n6ofmmh taos_adapter.2 tdengine/tdengine:3.0.0.0 vm98 Running Running about a minute ago +rxqfwsyk5q1h taos_adapter.3 tdengine/tdengine:3.0.0.0 vm98 Running Running about a minute ago +qj40lpxr40oc taos_adapter.4 tdengine/tdengine:3.0.0.0 vm98 Running Running about a minute ago +oe3455ulxpze taos_nginx.1 nginx:latest vm98 Running Running about a minute ago +o0tsg70nrrc6 taos_td-1.1 tdengine/tdengine:3.0.0.0 vm98 Running Running about a minute ago q5m1oxs589cp taos_td-2.1 tdengine/tdengine:3.0.0.0 vm98 Running Running about a minute ago $ docker service ls ID NAME MODE REPLICAS IMAGE PORTS -ozuklorgl8bs taos_adapter replicated 4/4 tdengine/tdengine:3.0.0.0 +ozuklorgl8bs taos_adapter replicated 4/4 tdengine/tdengine:3.0.0.0 crmhdjw6vxw0 taos_nginx replicated 1/1 nginx:latest *:6041->6041/tcp, *:6044->6044/udp -o86ngy7csv5n taos_td-1 replicated 1/1 tdengine/tdengine:3.0.0.0 +o86ngy7csv5n taos_td-1 replicated 1/1 tdengine/tdengine:3.0.0.0 rma040ny4tb0 taos_td-2 replicated 1/1 tdengine/tdengine:3.0.0.0 ``` @@ -495,11 +495,11 @@ rma040ny4tb0 taos_td-2 replicated 1/1 tdengine/tdengine:3.0.0.0 ```shell $ docker service scale taos_adapter=1 taos_adapter scaled to 1 -overall progress: 1 out of 1 tasks -1/1: running [==================================================>] +overall progress: 1 out of 1 tasks +1/1: running [==================================================>] verify: Service converged $ docker service ls -f name=taos_adapter ID NAME MODE REPLICAS IMAGE PORTS -ozuklorgl8bs taos_adapter replicated 1/1 tdengine/tdengine:3.0.0.0 +ozuklorgl8bs taos_adapter replicated 1/1 tdengine/tdengine:3.0.0.0 ``` diff --git a/docs/zh/25-application/_03-immigrate.md b/docs/zh/25-application/03-immigrate.md similarity index 70% rename from docs/zh/25-application/_03-immigrate.md rename to docs/zh/25-application/03-immigrate.md index d1c9caea09..75788c0cc7 100644 --- a/docs/zh/25-application/_03-immigrate.md +++ b/docs/zh/25-application/03-immigrate.md @@ -18,82 +18,15 @@ title: OpenTSDB 应用迁移到 TDengine 的最佳实践 如果我们将原本运行在 OpenTSDB 上的应用迁移到 TDengine 上,不仅可以有效地降低计算和存储资源的占用、减少部署服务器的规模,还能够极大减少运行维护的成本的输出,让运维管理工作更简单、更轻松,大幅降低总拥有成本。与 OpenTSDB 一样,TDengine 也已经进行了开源,不同的是,除了单机版,后者还实现了集群版开源,被厂商绑定的顾虑一扫而空。 -在下文中我们将就“使用最典型并广泛应用的运维监控(DevOps)场景”来说明,如何在不编码的情况下将 OpenTSDB 的应用快速、安全、可靠地迁移到 TDengine 之上。后续的章节会做更深度的介绍,以便于进行非 DevOps 场景的迁移。 +在下文中我们将说明如何在不编码的情况下将 OpenTSDB 的应用快速、安全、可靠地迁移到 TDengine 之上。 -## DevOps 应用快速迁移 +## TDengine 与 OpenTSDB 的差异 -### 1、典型应用场景 - -一个典型的 DevOps 应用场景的系统整体的架构如下图(图 1) 所示。 - -**图 1. DevOps 场景中典型架构** -![TDengine Database IT-DevOps-Solutions-Immigrate-OpenTSDB-Arch](./IT-DevOps-Solutions-Immigrate-OpenTSDB-Arch.webp "图1. DevOps 场景中典型架构") - -在该应用场景中,包含了部署在应用环境中负责收集机器度量(Metrics)、网络度量(Metrics)以及应用度量(Metrics)的 Agent 工具、汇聚 Agent 收集信息的数据收集器,数据持久化存储和管理的系统以及监控数据可视化工具(例如:Grafana 等)。 - -其中,部署在应用节点的 Agents 负责向 collectd/Statsd 提供不同来源的运行指标,collectd/StatsD 则负责将汇聚的数据推送到 OpenTSDB 集群系统,然后使用可视化看板 Grafana 将数据可视化呈现出来。 - -### 2、迁移服务 - -- **TDengine 安装部署** - -首先是 TDengine 的安装,从官网上下载 TDengine 最新稳定版进行安装。各种安装包的使用帮助请参见博客[《TDengine 多种安装包的安装和卸载》](https://www.taosdata.com/blog/2019/08/09/566.html)。 - -注意,安装完成以后,不要立即启动 `taosd` 服务,在正确配置完成参数以后再启动。 - -- **调整数据收集器配置** - -在 TDengine 2.4 版本中,包含一个组件 taosAdapter。taosAdapter 是一个无状态、可快速弹性伸缩的组件,它可以兼容 Influxdb 的 Line Protocol 和 OpenTSDB 的 telnet/JSON 写入协议规范,提供了丰富的数据接入能力,有效的节省用户迁移成本,降低用户应用迁移的难度。 - -用户可以根据需求弹性部署 taosAdapter 实例,结合场景的需要,快速提升数据写入的吞吐量,为不同应用场景下的数据写入提供保障。 - -通过 taosAdapter,用户可以将 collectd 或 StatsD 收集的数据直接推送到 TDengine ,实现应用场景的无缝迁移,非常的轻松便捷。taosAdapter 还支持 Telegraf、Icinga、TCollector 、node_exporter 的数据接入,使用详情参考[taosAdapter](/reference/taosadapter/)。 - -如果使用 collectd,修改其默认位置 `/etc/collectd/collectd.conf` 的配置文件为指向 taosAdapter 部署的节点 IP 地址和端口。假设 taosAdapter 的 IP 地址为 192.168.1.130,端口为 6046,配置如下: - -```html -LoadPlugin write_tsdb - - - Host "192.168.1.130" Port "6046" HostTags "status=production" StoreRates - false AlwaysAppendDS false - - -``` - -即可让 collectd 将数据使用推送到 OpenTSDB 的插件方式推送到 taosAdapter, taosAdapter 将调用 API 将数据写入到 TDengine 中,从而完成数据的写入工作。如果你使用的是 StatsD 相应地调整配置文件信息。 - -- **调整看板(Dashboard)系统** - -在数据能够正常写入 TDengine 后,可以调整适配 Grafana 将写入 TDengine 的数据可视化呈现出来。获取和使用 TDengine 提供的 Grafana 插件请参考[与其他工具的连接](/third-party/grafana)。 - -TDengine 提供了默认的两套 Dashboard 模板,用户只需要将 Grafana 目录下的模板导入到 Grafana 中即可激活使用。 - -**图 2. 导入 Grafana 模板** -![TDengine Database IT-DevOps-Solutions-Immigrate-OpenTSDB-Dashboard](./IT-DevOps-Solutions-Immigrate-OpenTSDB-Dashboard.webp "图2. 导入 Grafana 模板") - -操作完以上步骤后,就完成了将 OpenTSDB 替换成为 TDengine 的迁移工作。可以看到整个流程非常简单,不需要写代码,只需要对某些配置文件进行调整即可完成全部的迁移工作。 - -### 3、迁移后架构 - -完成迁移以后,此时的系统整体的架构如下图(图 3)所示,而整个过程中采集端、数据写入端、以及监控呈现端均保持了稳定,除了极少的配置调整外,不涉及任何重要的更改和变动。OpenTSDB 大量的应用场景均为 DevOps ,这种场景下,简单的参数设置即可完成 OpenTSDB 到 TDengine 迁移动作,使用上 TDengine 更加强大的处理能力和查询性能。 - -在绝大多数的 DevOps 场景中,如果你拥有一个小规模的 OpenTSDB 集群(3 台及以下的节点)作为 DevOps 的存储端,依赖于 OpenTSDB 为系统持久化层提供数据存储和查询功能,那么你可以安全地将其替换为 TDengine,并节约更多的计算和存储资源。在同等计算资源配置情况下,单台 TDengine 即可满足 3 ~ 5 台 OpenTSDB 节点提供的服务能力。如果规模比较大,那便需要采用 TDengine 集群。 - -如果你的应用特别复杂,或者应用领域并不是 DevOps 场景,你可以继续阅读后续的章节,更加全面深入地了解将 OpenTSDB 的应用迁移到 TDengine 的高级话题。 - -**图 3. 迁移完成后的系统架构** -![TDengine Database IT-DevOps-Solutions-Immigrate-TDengine-Arch](./IT-DevOps-Solutions-Immigrate-TDengine-Arch.webp "图 3. 迁移完成后的系统架构") - -## 其他场景的迁移评估与策略 - -### 1、TDengine 与 OpenTSDB 的差异 - -本章将详细介绍 OpenTSDB 与 TDengine 在系统功能层面上存在的差异。阅读完本章的内容,你可以全面地评估是否能够将某些基于 OpenTSDB 的复杂应用迁移到 TDengine 上,以及迁移之后应该注意的问题。 +本节将详细介绍 OpenTSDB 与 TDengine 在系统功能层面上存在的差异。阅读完本节的内容,你可以全面地评估是否能够将某些基于 OpenTSDB 的复杂应用迁移到 TDengine 上,以及迁移之后应该注意的问题。 TDengine 当前只支持 Grafana 的可视化看板呈现,所以如果你的应用中使用了 Grafana 以外的前端看板(例如[TSDash](https://github.com/facebook/tsdash)、[Status Wolf](https://github.com/box/StatusWolf)等),那么前端看板将无法直接迁移到 TDengine,需要将前端看板重新适配到 Grafana 才可以正常运行。 -在 2.3.0.x 版本中,TDengine 只能够支持 collectd 和 StatsD 作为数据收集汇聚软件,当然后面会陆续提供更多的数据收集聚合软件的接入支持。如果您的收集端使用了其他类型的数据汇聚器,您的应用需要适配到这两个数据汇聚端系统,才能够将数据正常写入。除了上述两个数据汇聚端软件协议以外,TDengine 还支持通过 InfluxDB 的行协议和 OpenTSDB 的数据写入协议、JSON 格式将数据直接写入,您可以重写数据推送端的逻辑,使用 TDengine 支持的行协议来写入数据。 +如果您的收集端使用了像 collectd 和 StatsD 这样的数据采集工具,要重新配置这些数据采集工具将数据写入到 TDengine。TDengine 还支持通过 InfluxDB 的行协议和 OpenTSDB 的数据写入协议、JSON 格式将数据直接写入,您可以重写数据推送端的逻辑,使用 TDengine 支持的行协议来写入数据。 此外,如果你的应用中使用了 OpenTSDB 以下特性,在将应用迁移到 TDengine 之前你还需要了解以下注意事项: @@ -104,11 +37,11 @@ TDengine 当前只支持 Grafana 的可视化看板呈现,所以如果你的 通过上面的介绍,相信你应该能够了解 OpenTSDB 迁移到 TDengine 带来的变化,这些信息也有助于你正确地判断是否可以接受将应用 迁移到 TDengine 之上,体验 TDengine 提供的强大的时序数据处理能力和便捷的使用体验。 -### 2、迁移策略 +## 迁移策略 首先将基于 OpenTSDB 的系统进行迁移涉及到的数据模式设计、系统规模估算、数据写入端改造,进行数据分流、应用适配工作;之后将两个系统并行运行一段时间,再将历史数据迁移到 TDengine 中。当然如果你的应用中有部分功能强依赖于上述 OpenTSDB 特性,同时又不希望停止使用,可以考虑保持原有的 OpenTSDB 系统运行,同时启动 TDengine 来提供主要的服务。 -## 数据模型设计 +### 数据模型设计 一方面,TDengine 要求其入库的数据具有严格的模式定义。另一方面,TDengine 的数据模型相对于 OpenTSDB 来说又更加丰富,多值模型能够兼容全部的单值模型的建立需求。 @@ -150,7 +83,7 @@ insert into memory_vm130_memory_buffered_collectd using memory tags(‘vm130’ 如果你想要利用 TDengine 的多值模型能力,需要首先满足以下要求:不同的采集量具有相同的采集频率,且能够通过消息队列**同时到达**数据写入端,从而确保使用 SQL 语句将多个指标一次性写入。将度量的名称作为超级表的名称,建立具有相同采集频率且能够同时到达的数据多列模型。子表的表名采用具有固定规则的方式进行命名。上述每个度量均只包含一个测量值,因此无法将其转化为多值模型。 -## 数据分流与应用适配 +### 数据分流与应用适配 从消息队列中订阅数据,并启动调整后的写入程序写入数据。 @@ -166,15 +99,128 @@ TDengine 不支持采用 OpenTSDB 的查询语法进行查询或数据获取处 TDengine 支持标准的 JDBC 3.0 接口操纵数据库,你也可以使用其他类型的高级语言的连接器来查询读取数据,以适配你的应用。具体的操作和使用帮助也请参阅用户手册。 -## 历史数据迁移 -### 1、使用工具自动迁移数据 +## 使用 DataX 迁移数据 -为了方便历史数据的迁移工作,我们为数据同步工具 DataX 提供了插件,能够将数据自动写入到 TDengine 中,需要注意的是 DataX 的自动化数据迁移只能够支持单值模型的数据迁移过程。 +为了方便历史数据的迁移工作,我们为数据同步工具 DataX 提供了适配 TDengine 3.0 的插件,能够将数据自动写入到 TDengine 中,需要注意的是 DataX 的自动化数据迁移只能够支持单值模型的数据迁移过程。 -DataX 具体的使用方式及如何使用 DataX 将数据写入 TDengine 请参见[基于 DataX 的 TDengine 数据迁移工具](https://www.taosdata.com/blog/2021/10/26/3156.html)。 +### 安装和部署 TDengine -在对 DataX 进行迁移实践后,我们发现通过启动多个进程,同时迁移多个 metric 的方式,可以大幅度的提高迁移历史数据的效率,下面是迁移过程中的部分记录,希望这些能为应用迁移工作带来参考。 +在进行数据迁移之前,要有一个正确运行的 TDengine 集群。首先是 TDengine 的安装,从官网上下载 TDengine 最新稳定版进行安装。各种安装包的使用帮助请参考 [安装指南](../../get-started/package) + +安装完成后,请根据 [部署指南](../../deployment/deploy) 配置集群。 + +### 插件功能介绍 + +1. TDengine30Reader 提供的功能: + 1. 支持通过 SQL 进行数据筛选; + 2. 根据时间间隔进行任务切分; + 3. 支持 TDengine 的全部数据类型; + 4. 支持批量读取,通过 batchSize 参数控制批量拉取结果集的大小,提高读取性能。 +2. TDengine30Writer 支持的功能: + 1. 支持 OpenTSDB 的 json 格式的行协议,使用 TDengine 的 schemaless 方式写入 TDengine。 + 2. 支持批量写入,通过 batchSize 参数控制批量写入的数量,提高写入性能。 + +### DataX 安装环境准备 + +1. 需要安装 TDengine 客户端 +2. 需要安装 JDK 1.8 环境(运行 DataX) +3. 需要安装 Python 环境(运行 DataX) +4. 需要 maven 编译环境(如果不编译 DataX 则可以不安装 maven) + +### 安装 + +1. 下载源码 +~~~ +git clone https://github.com/taosdata/DataX.git +~~~ +2. 编译打包 +~~~ +cd DataX +mvn -U clean package assembly:assembly -Dmaven.test.skip=true +~~~ +3. 安装 +~~~ +cp target/datax.tar.gz your_install_dir +cd your_install_dir +tar -zxvf dataX.tar.gz +~~~ + +### 数据迁移 Job 的配置 + +以一个从 OpenTSDB 到 TDengine 3.0 版本的数据迁移任务为例,配置文件 opentsdb2tdengine.json 如下: +~~~ +{ + "job":{ + "content":[{ + "reader": { + "name": "opentsdbreader", + "parameter": { + "endpoint": "http://192.168.1.180:4242", + "column": ["weather_temperature"], + "beginDateTime": "2021-01-01 00:00:00", + "endDateTime": "2021-01-01 01:00:00" + } + }, + "writer": { + "name": "tdengine30writer", + "parameter": { + "username": "root", + "password": "taosdata", + "connection": [ + { + "table": [ + "matric1" + ], + "jdbcUrl": "jdbc:TAOS://192.168.1.101:6030/test?timestampFormat=TIMESTAMP" + } + ], + "batchSize": 1000, + "ignoreTagsUnmatched": true + } + } + }], + "setting": { + "speed": { + "channel": 1 + } + } + } + } +~~~ +配置说明: +1. 上面的配置表示,从 192.168.1.180 的 OpenTSDB,到 192.168.1.101 的 TDengine 的迁移。迁移 metric 为 weather_temperature,时间从 2021-01-01 00:00:00 开始,到 2021-01-01 01:00:00 结束的数据。 +2. reader 使用 datax 的 opentsdbreader,parameter 的配置请参考:[opentsdbreader.md#配置参数](https://github.com/taosdata/DataX/blob/master/opentsdbreader/doc/opentsdbreader.md) +3. tdengine30writer 的 parameter 中,user,password 为必须项,没有默认值。batchSize 不是必须项,默认值为 1。详细参考:[tdengine30writer.md#配置参数](https://github.com/taosdata/DataX/blob/master/tdengine30writer/doc/tdengine30writer-CN.md) +4. TDengine 中,如果 dbname 指定的 database 不存在,则需要在迁移前创建数据库。 + +### 执行迁移任务 + +~~~ +python bin/datax.py job/opentsdb2tdengine.json +~~~ + +### 限制条件 + +1. 目前,DataX 自带的 opentsdbreader 仅支持 OpenTSDB-2.3.X 版本。详细参考:[opentsdbreader#约束限制](https://github.com/alibaba/DataX/blob/master/opentsdbreader/doc/opentsdbreader.md#5-%E7%BA%A6%E6%9D%9F%E9%99%90%E5%88%B6) +2. 数据迁移工具依赖 TDengine 客户端中的 `libtaos.so/taos.dll/libtaos.dylib`,需要与服务端对应版本的 TDengine-client。 + +### FAQ + +1. 如何估算一个数据迁移任务所需要的资源 + DataX 的每个 reader 按照自己的 task 切分策略进行任务划分,具体请参考 DataX 的任务调度规则。在估算资源是,需要按照数据迁移的数据量,任务切分规则和网络带宽限制等综合考虑,最好以实际数据迁移测试结果为准。 +2. TDengine30Writer 的 batchSize 设置多大效率最高? + batchSize 是控制批量写入的参数,在获取 batchSize 行纪录后,TDengineWriter 会向 TDengine 发送一次写入请求,这减少了与 TDengine 交互次数,从而提高了性能。从测试结果来看,batchSize 在 500-1000 范围内效率最高。 +3. job 的配置中 channel 数为多少合适? + job 中的 channel 数为流量控制的参数,每个 channel 都需要开辟一块内存,用来缓存数据。如果 channel 设置过大,会引起 OOM,所以 channel 数并不是越大越好。增加 channel 数后,需要提高 JVM 内存大小。从测试结果来看,channel 在 1~6 的范围内都是合适,能够保证 DataX 的流量最大化即可。 +4. java.sql.SQLException: TDengine ERROR (8000060b): Invalid client value + 配置文件中 column 中没有配置 tbname,此时会触发行协议数据写入(行协议写入只会自动创建子表名,但需要提前创建好超级表),行协议写入的情况下不支持 TAG 数据类型为非 NCHAR,所以此种情况有两种解决方案:1.将 TAG 全部修改为 NCHAR 类型;2.在 Column 中配置好表名称这样不会触发行协议写入。 +5. java.sql.SQLException: TDengine ERROR (8000060b): Timestamp data out of range + 配置文件中 column 中没有配置 tbname,此时会触发行协议数据写入,且 TAG 全部为 NCHAR 类型,此时需要保证时间戳的一列名称为 _ts,而不能是其他名称(行协议写入下,默认将最后的时间戳写入到 _ts 一列,且不能随意命名)。若想避免请使用 tbname 指定表名以避免触发行协议写入。 + +### 提升性能 + + 在对 DataX 进行迁移实践后,我们发现通过启动多个进程,同时迁移多个 metric 的方式,可以大幅度的提高迁移历史数据的效率,下面是迁移过程中的部分记录,希望这些能为应用迁移工作带来参考。 | DataX 实例个数 (并发进程个数) | 迁移记录速度 (条/秒) | | ----------------------------- | --------------------- | @@ -184,9 +230,9 @@ DataX 具体的使用方式及如何使用 DataX 将数据写入 TDengine 请参 | 5 | 约 29.5 万 | | 10 | 约 33 万 | -
(注:测试数据源自 单节点 Intel(R) Core(TM) i7-10700 CPU@2.90GHz 16 核 64G 硬件设备,channel 和 batchSize 分别为 8 和 1000,每条记录包含 10 个 tag) +(注:测试数据源自 单节点 Intel(R) Core(TM) i7-10700 CPU@2.90GHz 16 核 64G 硬件设备,channel 和 batchSize 分别为 8 和 1000,每条记录包含 10 个 tag) -### 2、手动迁移数据 +## 手动迁移数据 如果你需要使用多值模型进行数据写入,就需要自行开发一个将数据从 OpenTSDB 导出的工具,然后确认哪些时间线能够合并导入到同一个时间线,再将可以同时导入的时间通过 SQL 语句的写入到数据库中。 @@ -393,31 +439,11 @@ WHERE ts>=1510560000 AND ts<=1515000009 综上所述,可使用单台 16 核 32GB 的机器,或者使用 2 台 8 核 16GB 机器构成的集群。 -## 附录 3: 集群部署及启动 - -TDengine 提供了丰富的帮助文档说明集群安装、部署的诸多方面的内容,这里提供相应的文档列表,供你参考。 - -### 集群部署 - -首先是安装 TDengine,从官网上下载 TDengine 最新稳定版,解压缩后运行 install.sh 进行安装。各种安装包的使用帮助请参见博客[《TDengine 多种安装包的安装和卸载》](https://www.taosdata.com/blog/2019/08/09/566.html)。 - -注意安装完成以后,不要立即启动 `taosd` 服务,在正确配置完成参数以后才启动 `taosd` 服务。 - -### 设置运行参数并启动服务 - -为确保系统能够正常获取运行的必要信息。请在服务端正确设置以下关键参数: - -FQDN、firstEp、secondEP、dataDir、logDir、tmpDir、serverPort。各参数的具体含义及设置的要求,可参见文档《[TDengine 集群安装、管理](/cluster/)》 - -按照相同的步骤,在需要运行的节点上设置参数,并启动 `taosd` 服务,然后添加 Dnode 到集群中。 - -最后启动 `taos` 命令行程序,执行命令 `show dnodes`,如果能看到所有的加入集群的节点,那么集群顺利搭建完成。具体的操作流程及注意事项,请参阅文档《[TDengine 集群安装、管理](/cluster/)》 - -## 附录 4: 超级表名称 +## 附录 3: 超级表名称 由于 OpenTSDB 的 metric 名称中带有点号(“.”),例如“cpu.usage_user”这种名称的 metric。但是点号在 TDengine 中具有特殊含义,是用来分隔数据库和表名称的分隔符。TDengine 也提供转义符,以允许用户在(超级)表名称中使用关键词或特殊分隔符(如:点号)。为了使用特殊字符,需要采用转义字符将表的名称括起来,例如:`cpu.usage_user`这样就是合法的(超级)表名称。 -## 附录 5:参考文章 +## 附录 4:参考文章 -1. [使用 TDengine + collectd/StatsD + Grafana 快速搭建 IT 运维监控系统](/application/collectd/) -2. [通过 collectd 将采集数据直接写入 TDengine](/third-party/collectd/) +1. [使用 TDengine + collectd/StatsD + Grafana 快速搭建 IT 运维监控系统](../collectd/) +2. [通过 collectd 将采集数据直接写入 TDengine](../../third-party/collectd/) diff --git a/docs/zh/28-releases/01-tdengine.md b/docs/zh/28-releases/01-tdengine.md index cf7bf83164..c9505d95a5 100644 --- a/docs/zh/28-releases/01-tdengine.md +++ b/docs/zh/28-releases/01-tdengine.md @@ -10,6 +10,10 @@ TDengine 2.x 各版本安装包请访问[这里](https://www.taosdata.com/all-do import Release from "/components/ReleaseV3"; +## 3.0.2.6 + + + ## 3.0.2.5 diff --git a/docs/zh/28-releases/02-tools.md b/docs/zh/28-releases/02-tools.md index 5f277b4873..69d35f95c8 100644 --- a/docs/zh/28-releases/02-tools.md +++ b/docs/zh/28-releases/02-tools.md @@ -10,6 +10,10 @@ taosTools 各版本安装包下载链接如下: import Release from "/components/ReleaseV3"; +## 2.4.6 + + + ## 2.4.3 diff --git a/examples/c/asyncdemo.c b/examples/c/asyncdemo.c index c86cd44354..91ec6f24b1 100644 --- a/examples/c/asyncdemo.c +++ b/examples/c/asyncdemo.c @@ -92,7 +92,7 @@ int main(int argc, char *argv[]) } // a simple way to parse input parameters - if (argc >= 3) strcpy(db, argv[2]); + if (argc >= 3) strncpy(db, argv[2], sizeof(db) - 1); if (argc >= 4) points = atoi(argv[3]); if (argc >= 5) numOfTables = atoi(argv[4]); diff --git a/examples/c/tmq.c b/examples/c/tmq.c index eb41ad039a..83b40c4f20 100644 --- a/examples/c/tmq.c +++ b/examples/c/tmq.c @@ -61,7 +61,7 @@ static int32_t init_env() { printf("create database\n"); pRes = taos_query(pConn, "drop topic topicname"); if (taos_errno(pRes) != 0) { - printf("error in drop tmqdb, reason:%s\n", taos_errstr(pRes)); + printf("error in drop topicname, reason:%s\n", taos_errstr(pRes)); } taos_free_result(pRes); @@ -189,27 +189,54 @@ void tmq_commit_cb_print(tmq_t* tmq, int32_t code, void* param) { tmq_t* build_consumer() { tmq_conf_res_t code; - tmq_conf_t* conf = tmq_conf_new(); + tmq_t* tmq = NULL; + + tmq_conf_t* conf = tmq_conf_new(); code = tmq_conf_set(conf, "enable.auto.commit", "true"); - if (TMQ_CONF_OK != code) return NULL; + if (TMQ_CONF_OK != code) { + tmq_conf_destroy(conf); + return NULL; + } code = tmq_conf_set(conf, "auto.commit.interval.ms", "1000"); - if (TMQ_CONF_OK != code) return NULL; + if (TMQ_CONF_OK != code) { + tmq_conf_destroy(conf); + return NULL; + } code = tmq_conf_set(conf, "group.id", "cgrpName"); - if (TMQ_CONF_OK != code) return NULL; + if (TMQ_CONF_OK != code) { + tmq_conf_destroy(conf); + return NULL; + } code = tmq_conf_set(conf, "client.id", "user defined name"); - if (TMQ_CONF_OK != code) return NULL; + if (TMQ_CONF_OK != code) { + tmq_conf_destroy(conf); + return NULL; + } code = tmq_conf_set(conf, "td.connect.user", "root"); - if (TMQ_CONF_OK != code) return NULL; + if (TMQ_CONF_OK != code) { + tmq_conf_destroy(conf); + return NULL; + } code = tmq_conf_set(conf, "td.connect.pass", "taosdata"); - if (TMQ_CONF_OK != code) return NULL; + if (TMQ_CONF_OK != code) { + tmq_conf_destroy(conf); + return NULL; + } code = tmq_conf_set(conf, "auto.offset.reset", "earliest"); - if (TMQ_CONF_OK != code) return NULL; + if (TMQ_CONF_OK != code) { + tmq_conf_destroy(conf); + return NULL; + } code = tmq_conf_set(conf, "experimental.snapshot.enable", "false"); - if (TMQ_CONF_OK != code) return NULL; + if (TMQ_CONF_OK != code) { + tmq_conf_destroy(conf); + return NULL; + } tmq_conf_set_auto_commit_cb(conf, tmq_commit_cb_print, NULL); + tmq = tmq_consumer_new(conf, NULL, 0); - tmq_t* tmq = tmq_consumer_new(conf, NULL, 0); +_end: tmq_conf_destroy(conf); return tmq; } diff --git a/include/common/systable.h b/include/common/systable.h index 9b5f66f64c..558a1ca297 100644 --- a/include/common/systable.h +++ b/include/common/systable.h @@ -12,6 +12,9 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ + +#ifndef TDENGINE_SYSTABLE_H +#define TDENGINE_SYSTABLE_H #ifdef __cplusplus extern "C" { @@ -19,9 +22,6 @@ extern "C" { #include "os.h" -#ifndef TDENGINE_SYSTABLE_H -#define TDENGINE_SYSTABLE_H - #define TSDB_INFORMATION_SCHEMA_DB "information_schema" #define TSDB_INS_TABLE_DNODES "ins_dnodes" #define TSDB_INS_TABLE_MNODES "ins_mnodes" diff --git a/include/common/tcommon.h b/include/common/tcommon.h index f4e13509c2..2a40976a8b 100644 --- a/include/common/tcommon.h +++ b/include/common/tcommon.h @@ -205,7 +205,7 @@ typedef struct SDataBlockInfo { STimeWindow calWin; // used for stream, do not serialize TSKEY watermark; // used for stream - char parTbName[TSDB_TABLE_NAME_LEN]; // used for stream partition + char parTbName[TSDB_TABLE_NAME_LEN]; // used for stream partition } SDataBlockInfo; typedef struct SSDataBlock { @@ -291,7 +291,6 @@ typedef struct STableBlockDistInfo { uint16_t numOfFiles; uint32_t numOfTables; uint32_t numOfBlocks; - uint32_t numOfVgroups; uint64_t totalSize; uint64_t totalRows; int32_t maxRows; @@ -301,6 +300,7 @@ typedef struct STableBlockDistInfo { int32_t firstSeekTimeUs; uint32_t numOfInmemRows; uint32_t numOfSmallBlocks; + uint32_t numOfVgroups; int32_t blockRowsHisto[20]; } STableBlockDistInfo; @@ -341,7 +341,7 @@ typedef struct SExprInfo { typedef struct { const char* key; - size_t keyLen; + size_t keyLen; uint8_t type; union { const char* value; @@ -385,9 +385,9 @@ typedef struct STUidTagInfo { #define TABLE_NAME_COLUMN_INDEX 6 // stream create table block column -#define UD_TABLE_NAME_COLUMN_INDEX 0 -#define UD_GROUPID_COLUMN_INDEX 1 -#define UD_TAG_COLUMN_INDEX 2 +#define UD_TABLE_NAME_COLUMN_INDEX 0 +#define UD_GROUPID_COLUMN_INDEX 1 +#define UD_TAG_COLUMN_INDEX 2 #ifdef __cplusplus } diff --git a/include/common/tdatablock.h b/include/common/tdatablock.h index 20ffb48ab0..84d696e518 100644 --- a/include/common/tdatablock.h +++ b/include/common/tdatablock.h @@ -58,7 +58,6 @@ typedef struct SBlockOrderInfo { #define BitmapLen(_n) (((_n) + ((1 << NBIT) - 1)) >> NBIT) #define colDataGetVarData(p1_, r_) ((p1_)->pData + (p1_)->varmeta.offset[(r_)]) - #define colDataGetNumData(p1_, r_) ((p1_)->pData + ((r_) * (p1_)->info.bytes)) // SColumnInfoData, rowNumber #define colDataGetData(p1_, r_) \ @@ -83,33 +82,6 @@ static FORCE_INLINE bool colDataIsNull_s(const SColumnInfoData* pColumnInfoData, } } -static FORCE_INLINE bool colDataIsNNull_s(const SColumnInfoData* pColumnInfoData, int32_t startIndex, - uint32_t nRows) { - if (!pColumnInfoData->hasNull) { - return false; - } - - if (IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) { - for (int32_t i = startIndex; i < nRows; ++i) { - if (!colDataIsNull_var(pColumnInfoData, i)) { - return false; - } - } - } else { - if (pColumnInfoData->nullbitmap == NULL) { - return false; - } - - for (int32_t i = startIndex; i < nRows; ++i) { - if (!colDataIsNull_f(pColumnInfoData->nullbitmap, i)) { - return false; - } - } - } - - return true; -} - static FORCE_INLINE bool colDataIsNull(const SColumnInfoData* pColumnInfoData, uint32_t totalRows, uint32_t row, SColumnDataAgg* pColAgg) { if (!pColumnInfoData->hasNull) { @@ -137,18 +109,18 @@ static FORCE_INLINE bool colDataIsNull(const SColumnInfoData* pColumnInfoData, u } } -static FORCE_INLINE void colDataAppendNULL(SColumnInfoData* pColumnInfoData, uint32_t currentRow) { +static FORCE_INLINE void colDataSetNULL(SColumnInfoData* pColumnInfoData, uint32_t rowIndex) { // There is a placehold for each NULL value of binary or nchar type. if (IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) { - colDataSetNull_var(pColumnInfoData, currentRow); // it is a null value of VAR type. + colDataSetNull_var(pColumnInfoData, rowIndex); // it is a null value of VAR type. } else { - colDataSetNull_f_s(pColumnInfoData, currentRow); + colDataSetNull_f_s(pColumnInfoData, rowIndex); } pColumnInfoData->hasNull = true; } -static FORCE_INLINE void colDataAppendNNULL(SColumnInfoData* pColumnInfoData, uint32_t start, size_t nRows) { +static FORCE_INLINE void colDataSetNNULL(SColumnInfoData* pColumnInfoData, uint32_t start, size_t nRows) { if (IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) { for (int32_t i = start; i < start + nRows; ++i) { colDataSetNull_var(pColumnInfoData, i); // it is a null value of VAR type. @@ -163,50 +135,50 @@ static FORCE_INLINE void colDataAppendNNULL(SColumnInfoData* pColumnInfoData, ui pColumnInfoData->hasNull = true; } -static FORCE_INLINE void colDataAppendInt8(SColumnInfoData* pColumnInfoData, uint32_t currentRow, int8_t* v) { +static FORCE_INLINE void colDataSetInt8(SColumnInfoData* pColumnInfoData, uint32_t rowIndex, int8_t* v) { ASSERT(pColumnInfoData->info.type == TSDB_DATA_TYPE_TINYINT || pColumnInfoData->info.type == TSDB_DATA_TYPE_UTINYINT || pColumnInfoData->info.type == TSDB_DATA_TYPE_BOOL); - char* p = pColumnInfoData->pData + pColumnInfoData->info.bytes * currentRow; + char* p = pColumnInfoData->pData + pColumnInfoData->info.bytes * rowIndex; *(int8_t*)p = *(int8_t*)v; } -static FORCE_INLINE void colDataAppendInt16(SColumnInfoData* pColumnInfoData, uint32_t currentRow, int16_t* v) { +static FORCE_INLINE void colDataSetInt16(SColumnInfoData* pColumnInfoData, uint32_t rowIndex, int16_t* v) { ASSERT(pColumnInfoData->info.type == TSDB_DATA_TYPE_SMALLINT || pColumnInfoData->info.type == TSDB_DATA_TYPE_USMALLINT); - char* p = pColumnInfoData->pData + pColumnInfoData->info.bytes * currentRow; + char* p = pColumnInfoData->pData + pColumnInfoData->info.bytes * rowIndex; *(int16_t*)p = *(int16_t*)v; } -static FORCE_INLINE void colDataAppendInt32(SColumnInfoData* pColumnInfoData, uint32_t currentRow, int32_t* v) { +static FORCE_INLINE void colDataSetInt32(SColumnInfoData* pColumnInfoData, uint32_t rowIndex, int32_t* v) { ASSERT(pColumnInfoData->info.type == TSDB_DATA_TYPE_INT || pColumnInfoData->info.type == TSDB_DATA_TYPE_UINT); - char* p = pColumnInfoData->pData + pColumnInfoData->info.bytes * currentRow; + char* p = pColumnInfoData->pData + pColumnInfoData->info.bytes * rowIndex; *(int32_t*)p = *(int32_t*)v; } -static FORCE_INLINE void colDataAppendInt64(SColumnInfoData* pColumnInfoData, uint32_t currentRow, int64_t* v) { +static FORCE_INLINE void colDataSetInt64(SColumnInfoData* pColumnInfoData, uint32_t rowIndex, int64_t* v) { int32_t type = pColumnInfoData->info.type; ASSERT(type == TSDB_DATA_TYPE_BIGINT || type == TSDB_DATA_TYPE_UBIGINT || type == TSDB_DATA_TYPE_TIMESTAMP); - char* p = pColumnInfoData->pData + pColumnInfoData->info.bytes * currentRow; + char* p = pColumnInfoData->pData + pColumnInfoData->info.bytes * rowIndex; *(int64_t*)p = *(int64_t*)v; } -static FORCE_INLINE void colDataAppendFloat(SColumnInfoData* pColumnInfoData, uint32_t currentRow, float* v) { +static FORCE_INLINE void colDataSetFloat(SColumnInfoData* pColumnInfoData, uint32_t rowIndex, float* v) { ASSERT(pColumnInfoData->info.type == TSDB_DATA_TYPE_FLOAT); - char* p = pColumnInfoData->pData + pColumnInfoData->info.bytes * currentRow; + char* p = pColumnInfoData->pData + pColumnInfoData->info.bytes * rowIndex; *(float*)p = *(float*)v; } -static FORCE_INLINE void colDataAppendDouble(SColumnInfoData* pColumnInfoData, uint32_t currentRow, double* v) { +static FORCE_INLINE void colDataSetDouble(SColumnInfoData* pColumnInfoData, uint32_t rowIndex, double* v) { ASSERT(pColumnInfoData->info.type == TSDB_DATA_TYPE_DOUBLE); - char* p = pColumnInfoData->pData + pColumnInfoData->info.bytes * currentRow; + char* p = pColumnInfoData->pData + pColumnInfoData->info.bytes * rowIndex; *(double*)p = *(double*)v; } int32_t getJsonValueLen(const char* data); -int32_t colDataAppend(SColumnInfoData* pColumnInfoData, uint32_t currentRow, const char* pData, bool isNull); -int32_t colDataAppendNItems(SColumnInfoData* pColumnInfoData, uint32_t currentRow, const char* pData, - uint32_t numOfRows); +int32_t colDataSetVal(SColumnInfoData* pColumnInfoData, uint32_t rowIndex, const char* pData, bool isNull); +int32_t colDataAppend(SColumnInfoData* pColumnInfoData, uint32_t rowIndex, const char* pData, bool isNull); +int32_t colDataSetNItems(SColumnInfoData* pColumnInfoData, uint32_t rowIndex, const char* pData, uint32_t numOfRows); int32_t colDataMergeCol(SColumnInfoData* pColumnInfoData, int32_t numOfRow1, int32_t* capacity, const SColumnInfoData* pSource, int32_t numOfRow2); int32_t colDataAssign(SColumnInfoData* pColumnInfoData, const SColumnInfoData* pSource, int32_t numOfRows, @@ -245,7 +217,7 @@ void blockDataEmpty(SSDataBlock* pDataBlock); size_t blockDataGetCapacityInRow(const SSDataBlock* pBlock, size_t pageSize); -int32_t blockDataTrimFirstNRows(SSDataBlock* pBlock, size_t n); +int32_t blockDataTrimFirstRows(SSDataBlock* pBlock, size_t n); int32_t blockDataKeepFirstNRows(SSDataBlock* pBlock, size_t n); int32_t assignOneDataBlock(SSDataBlock* dst, const SSDataBlock* src); @@ -280,13 +252,6 @@ static FORCE_INLINE int32_t blockGetEncodeSize(const SSDataBlock* pBlock) { return blockDataGetSerialMetaSize(taosArrayGetSize(pBlock->pDataBlock)) + blockDataGetSize(pBlock); } -static FORCE_INLINE int32_t blockCompressColData(SColumnInfoData* pColRes, int32_t numOfRows, char* data, - int8_t compressed) { - int32_t colSize = colDataGetLength(pColRes, numOfRows); - return (*(tDataTypes[pColRes->info.type].compFunc))(pColRes->pData, colSize, numOfRows, data, - colSize + COMP_OVERFLOW_BYTES, compressed, NULL, 0); -} - #ifdef __cplusplus } #endif diff --git a/include/common/tdataformat.h b/include/common/tdataformat.h index 0bfb057f20..8be5cb4d41 100644 --- a/include/common/tdataformat.h +++ b/include/common/tdataformat.h @@ -106,7 +106,7 @@ int32_t tBufferReserve(SBuffer *pBuffer, int64_t nData, void **ppData); // SRow ================================ int32_t tRowBuild(SArray *aColVal, const STSchema *pTSchema, SRow **ppRow); -void tRowGet(SRow *pRow, STSchema *pTSchema, int32_t iCol, SColVal *pColVal); +int32_t tRowGet(SRow *pRow, STSchema *pTSchema, int32_t iCol, SColVal *pColVal); void tRowDestroy(SRow *pRow); void tRowSort(SArray *aRowP); int32_t tRowMerge(SArray *aRowP, STSchema *pTSchema, int8_t flag); diff --git a/include/common/tmisce.h b/include/common/tmisce.h index b9f5cf5b91..bc6558900c 100644 --- a/include/common/tmisce.h +++ b/include/common/tmisce.h @@ -27,13 +27,14 @@ typedef struct SCorEpSet { SEpSet epSet; } SCorEpSet; +#define GET_ACTIVE_EP(_eps) (&((_eps)->eps[(_eps)->inUse])) int32_t taosGetFqdnPortFromEp(const char* ep, SEp* pEp); void addEpIntoEpSet(SEpSet* pEpSet, const char* fqdn, uint16_t port); -bool isEpsetEqual(const SEpSet* s1, const SEpSet* s2); - -void updateEpSet_s(SCorEpSet* pEpSet, SEpSet* pNewEpSet); -SEpSet getEpSet_s(SCorEpSet* pEpSet); +bool isEpsetEqual(const SEpSet* s1, const SEpSet* s2); +void epsetAssign(SEpSet* dst, const SEpSet* pSrc); +void updateEpSet_s(SCorEpSet* pEpSet, SEpSet* pNewEpSet); +SEpSet getEpSet_s(SCorEpSet* pEpSet); #ifdef __cplusplus } diff --git a/include/common/tmsg.h b/include/common/tmsg.h index 77b9d2d681..cd63f7d278 100644 --- a/include/common/tmsg.h +++ b/include/common/tmsg.h @@ -1904,10 +1904,10 @@ typedef struct { } SMqConsumerLostMsg, SMqConsumerRecoverMsg, SMqConsumerClearMsg; typedef struct { - int64_t consumerId; - char cgroup[TSDB_CGROUP_LEN]; - char clientId[256]; - SArray* topicNames; // SArray + int64_t consumerId; + char cgroup[TSDB_CGROUP_LEN]; + char clientId[256]; + SArray* topicNames; // SArray } SCMSubscribeReq; static FORCE_INLINE int32_t tSerializeSCMSubscribeReq(void** buf, const SCMSubscribeReq* pReq) { @@ -2850,7 +2850,7 @@ typedef struct { char dbFName[TSDB_DB_FNAME_LEN]; char stbName[TSDB_TABLE_NAME_LEN]; char colName[TSDB_COL_NAME_LEN]; - char idxName[TSDB_COL_NAME_LEN]; + char idxName[TSDB_INDEX_FNAME_LEN]; int8_t idxType; } SCreateTagIndexReq; diff --git a/include/common/tmsgdef.h b/include/common/tmsgdef.h index 7aae38f7ba..46ca814e50 100644 --- a/include/common/tmsgdef.h +++ b/include/common/tmsgdef.h @@ -172,8 +172,8 @@ enum { TD_DEF_MSG_TYPE(TDMT_MND_SERVER_VERSION, "server-version", NULL, NULL) TD_DEF_MSG_TYPE(TDMT_MND_UPTIME_TIMER, "uptime-timer", NULL, NULL) TD_DEF_MSG_TYPE(TDMT_MND_TMQ_LOST_CONSUMER_CLEAR, "lost-consumer-clear", NULL, NULL) - TD_DEF_MSG_TYPE(TDMT_MND_STREAM_CHECKPOINT_TIMER, "stream-checkpoint-tmr", NULL, NULL) - TD_DEF_MSG_TYPE(TDMT_MND_STREAM_BEGIN_CHECKPOINT, "stream-begin-checkpoint", NULL, NULL) + // TD_DEF_MSG_TYPE(TDMT_MND_STREAM_CHECKPOINT_TIMER, "stream-checkpoint-tmr", NULL, NULL) + // TD_DEF_MSG_TYPE(TDMT_MND_STREAM_BEGIN_CHECKPOINT, "stream-begin-checkpoint", NULL, NULL) TD_DEF_MSG_TYPE(TDMT_MND_MAX_MSG, "mnd-max", NULL, NULL) TD_NEW_MSG_SEG(TDMT_VND_MSG) diff --git a/include/common/ttime.h b/include/common/ttime.h index eaf44c2771..4a7c47d172 100644 --- a/include/common/ttime.h +++ b/include/common/ttime.h @@ -80,15 +80,15 @@ int32_t taosTimeCountInterval(int64_t skey, int64_t ekey, int64_t interval, char int32_t parseAbsoluteDuration(const char* token, int32_t tokenlen, int64_t* ts, char* unit, int32_t timePrecision); int32_t parseNatualDuration(const char* token, int32_t tokenLen, int64_t* duration, char* unit, int32_t timePrecision); -int32_t taosParseTime(const char* timestr, int64_t* time, int32_t len, int32_t timePrec, int8_t dayligth); +int32_t taosParseTime(const char* timestr, int64_t* pTime, int32_t len, int32_t timePrec, int8_t dayligth); void deltaToUtcInitOnce(); char getPrecisionUnit(int32_t precision); -int64_t convertTimePrecision(int64_t time, int32_t fromPrecision, int32_t toPrecision); -int64_t convertTimeFromPrecisionToUnit(int64_t time, int32_t fromPrecision, char toUnit); +int64_t convertTimePrecision(int64_t ts, int32_t fromPrecision, int32_t toPrecision); +int64_t convertTimeFromPrecisionToUnit(int64_t ts, int32_t fromPrecision, char toUnit); int32_t convertStringToTimestamp(int16_t type, char* inputData, int64_t timePrec, int64_t* timeVal); -void taosFormatUtcTime(char* buf, int32_t bufLen, int64_t time, int32_t precision); +void taosFormatUtcTime(char* buf, int32_t bufLen, int64_t ts, int32_t precision); #ifdef __cplusplus } diff --git a/include/libs/function/function.h b/include/libs/function/function.h index c44ad12759..fb6ef26a8a 100644 --- a/include/libs/function/function.h +++ b/include/libs/function/function.h @@ -76,7 +76,7 @@ enum { enum { MAIN_SCAN = 0x0u, REVERSE_SCAN = 0x1u, // todo remove it - REPEAT_SCAN = 0x2u, // repeat scan belongs to the master scan + PRE_SCAN = 0x2u, // pre-scan belongs to the main scan and occurs before main scan }; typedef struct SPoint1 { diff --git a/include/libs/qcom/query.h b/include/libs/qcom/query.h index bbf332c4d4..cb547ee6b3 100644 --- a/include/libs/qcom/query.h +++ b/include/libs/qcom/query.h @@ -26,6 +26,7 @@ extern "C" { #include "tlog.h" #include "tmsg.h" #include "tmsgcb.h" +#include "systable.h" typedef enum { JOB_TASK_STATUS_NULL = 0, @@ -302,9 +303,10 @@ extern int32_t (*queryProcessMsgRsp[TDMT_MAX])(void* output, char* msg, int32_t #define REQUEST_TOTAL_EXEC_TIMES 2 -#define IS_SYS_DBNAME(_dbname) \ - (((*(_dbname) == 'i') && (0 == strcmp(_dbname, TSDB_INFORMATION_SCHEMA_DB))) || \ - ((*(_dbname) == 'p') && (0 == strcmp(_dbname, TSDB_PERFORMANCE_SCHEMA_DB)))) +#define IS_INFORMATION_SCHEMA_DB(_name) ((*(_name) == 'i') && (0 == strcmp(_name, TSDB_INFORMATION_SCHEMA_DB))) +#define IS_PERFORMANCE_SCHEMA_DB(_name) ((*(_name) == 'p') && (0 == strcmp(_name, TSDB_PERFORMANCE_SCHEMA_DB))) + +#define IS_SYS_DBNAME(_dbname) (IS_INFORMATION_SCHEMA_DB(_dbname) || IS_PERFORMANCE_SCHEMA_DB(_dbname)) #define qFatal(...) \ do { \ diff --git a/include/libs/stream/tstream.h b/include/libs/stream/tstream.h index 77a4384c30..1d301623b1 100644 --- a/include/libs/stream/tstream.h +++ b/include/libs/stream/tstream.h @@ -175,20 +175,24 @@ typedef struct { void streamFreeQitem(SStreamQueueItem* data); +#if 0 bool streamQueueResEmpty(const SStreamQueueRes* pRes); int64_t streamQueueResSize(const SStreamQueueRes* pRes); SStreamQueueNode* streamQueueResFront(SStreamQueueRes* pRes); SStreamQueueNode* streamQueueResPop(SStreamQueueRes* pRes); void streamQueueResClear(SStreamQueueRes* pRes); SStreamQueueRes streamQueueBuildRes(SStreamQueueNode* pNode); +#endif typedef struct { SStreamQueueNode* pHead; } SStreamQueue1; +#if 0 bool streamQueueHasTask(const SStreamQueue1* pQueue); int32_t streamQueuePush(SStreamQueue1* pQueue, SStreamQueueItem* pItem); SStreamQueueRes streamQueueGetRes(SStreamQueue1* pQueue); +#endif typedef struct { STaosQueue* queue; @@ -636,7 +640,7 @@ void streamMetaClose(SStreamMeta* streamMeta); int32_t streamMetaSaveTask(SStreamMeta* pMeta, SStreamTask* pTask); int32_t streamMetaAddTask(SStreamMeta* pMeta, int64_t ver, SStreamTask* pTask); int32_t streamMetaAddSerializedTask(SStreamMeta* pMeta, int64_t startVer, char* msg, int32_t msgLen); -SStreamTask* streamMetaGetTask(SStreamMeta* pMeta, int32_t taskId); +// SStreamTask* streamMetaGetTask(SStreamMeta* pMeta, int32_t taskId); SStreamTask* streamMetaAcquireTask(SStreamMeta* pMeta, int32_t taskId); void streamMetaReleaseTask(SStreamMeta* pMeta, SStreamTask* pTask); diff --git a/include/libs/wal/wal.h b/include/libs/wal/wal.h index 1eed342f8c..014ed518a3 100644 --- a/include/libs/wal/wal.h +++ b/include/libs/wal/wal.h @@ -66,6 +66,7 @@ typedef struct { int64_t commitVer; int64_t appliedVer; int64_t lastVer; + int64_t logRetention; } SWalVer; #pragma pack(push, 1) @@ -126,7 +127,7 @@ typedef struct SWal { typedef struct { int64_t refId; int64_t refVer; - int64_t refFile; +// int64_t refFile; SWal *pWal; } SWalRef; @@ -180,7 +181,7 @@ void walFsync(SWal *, bool force); int32_t walCommit(SWal *, int64_t ver); int32_t walRollback(SWal *, int64_t ver); // notify that previous logs can be pruned safely -int32_t walBeginSnapshot(SWal *, int64_t ver); +int32_t walBeginSnapshot(SWal *, int64_t ver, int64_t logRetention); int32_t walEndSnapshot(SWal *); int32_t walRestoreFromSnapshot(SWal *, int64_t ver); // for tq diff --git a/include/os/osMemory.h b/include/os/osMemory.h index 3b9c0fe94b..3f57c72933 100644 --- a/include/os/osMemory.h +++ b/include/os/osMemory.h @@ -29,6 +29,7 @@ extern "C" { #define calloc CALLOC_FUNC_TAOS_FORBID #define realloc REALLOC_FUNC_TAOS_FORBID #define free FREE_FUNC_TAOS_FORBID +#define strdup STRDUP_FUNC_TAOS_FORBID #endif // ifndef ALLOW_FORBID_FUNC #endif // if !defined(WINDOWS) @@ -38,7 +39,7 @@ int32_t taosMemoryDbgInitRestore(); void *taosMemoryMalloc(int64_t size); void *taosMemoryCalloc(int64_t num, int64_t size); void *taosMemoryRealloc(void *ptr, int64_t size); -void *taosMemoryStrDup(const char *ptr); +char *taosStrdup(const char *ptr); void taosMemoryFree(void *ptr); int64_t taosMemorySize(void *ptr); void taosPrintBackTrace(); diff --git a/include/util/taoserror.h b/include/util/taoserror.h index 56c10f2463..75860a4b1e 100644 --- a/include/util/taoserror.h +++ b/include/util/taoserror.h @@ -119,6 +119,7 @@ int32_t* taosGetErrno(); #define TSDB_CODE_APP_IS_STARTING TAOS_DEF_ERROR_CODE(0, 0x0130) // #define TSDB_CODE_APP_IS_STOPPING TAOS_DEF_ERROR_CODE(0, 0x0131) // +#define TSDB_CODE_IVLD_DATA_FMT TAOS_DEF_ERROR_CODE(0, 0x0132) // //client #define TSDB_CODE_TSC_INVALID_OPERATION TAOS_DEF_ERROR_CODE(0, 0x0200) diff --git a/include/util/tarray.h b/include/util/tarray.h index 5b36bc4d0e..a8510e4bc8 100644 --- a/include/util/tarray.h +++ b/include/util/tarray.h @@ -43,7 +43,7 @@ typedef struct SArray { * @return */ SArray* taosArrayInit(size_t size, size_t elemSize); -SArray* taosArrayInit_s(size_t size, size_t elemSize, size_t initialSize); +SArray* taosArrayInit_s(size_t elemSize, size_t initialSize); /** * diff --git a/include/util/tlog.h b/include/util/tlog.h index 4311719ca5..0071b3d32c 100644 --- a/include/util/tlog.h +++ b/include/util/tlog.h @@ -89,20 +89,20 @@ bool taosAssertRelease(bool condition); // Disable all asserts that may compromise the performance. #if defined DISABLE_ASSERT #define ASSERT(condition) -#define ASSERTS(condition, ...) (0) +#define ASSERTS(condition, ...) (0) #else -#define ASSERTS(condition, ...) taosAssertDebug(condition, __FILE__, __LINE__, __VA_ARGS__) +#define ASSERTS(condition, ...) ((condition) ? false : taosAssertDebug(condition, __FILE__, __LINE__, __VA_ARGS__)) #ifdef NDEBUG #define ASSERT(condition) taosAssertRelease(condition) #else -#define ASSERT(condition) taosAssertDebug(condition, __FILE__, __LINE__, "assert info not provided") +#define ASSERT(condition) ASSERTS(condition, "assert info not provided") #endif #endif -void taosLogCrashInfo(char* nodeType, char* pMsg, int64_t msgLen, int signum, void *sigInfo); -void taosReadCrashInfo(char* filepath, char** pMsg, int64_t* pMsgLen, TdFilePtr* pFd); -void taosReleaseCrashLogFile(TdFilePtr pFile, bool truncateFile); -int32_t taosGenCrashJsonMsg(int signum, char** pMsg, int64_t clusterId, int64_t startTime); +void taosLogCrashInfo(char *nodeType, char *pMsg, int64_t msgLen, int signum, void *sigInfo); +void taosReadCrashInfo(char *filepath, char **pMsg, int64_t *pMsgLen, TdFilePtr *pFd); +void taosReleaseCrashLogFile(TdFilePtr pFile, bool truncateFile); +int32_t taosGenCrashJsonMsg(int signum, char **pMsg, int64_t clusterId, int64_t startTime); // clang-format off #define uFatal(...) { if (uDebugFlag & DEBUG_FATAL) { taosPrintLog("UTL FATAL", DEBUG_FATAL, tsLogEmbedded ? 255 : uDebugFlag, __VA_ARGS__); }} @@ -116,7 +116,7 @@ int32_t taosGenCrashJsonMsg(int signum, char** pMsg, int64_t clusterId, int64_t #define pError(...) { taosPrintLog("APP ERROR ", DEBUG_ERROR, 255, __VA_ARGS__); } #define pPrint(...) { taosPrintLog("APP ", DEBUG_INFO, 255, __VA_ARGS__); } // clang-format on -//#define BUF_PAGE_DEBUG +// #define BUF_PAGE_DEBUG #ifdef __cplusplus } #endif diff --git a/include/util/tworker.h b/include/util/tworker.h index 0636f16dbb..8508adf052 100644 --- a/include/util/tworker.h +++ b/include/util/tworker.h @@ -26,12 +26,12 @@ extern "C" { typedef struct SQWorkerPool SQWorkerPool; typedef struct SWWorkerPool SWWorkerPool; -typedef struct SQWorker { +typedef struct SQueueWorker { int32_t id; // worker id int64_t pid; // thread pid TdThread thread; // thread id void *pool; -} SQWorker; +} SQueueWorker; typedef struct SQWorkerPool { int32_t max; // max number of workers @@ -39,7 +39,7 @@ typedef struct SQWorkerPool { int32_t num; // current number of workers STaosQset *qset; const char *name; - SQWorker *workers; + SQueueWorker *workers; TdThreadMutex mutex; } SQWorkerPool; diff --git a/include/util/xxhash.h b/include/util/xxhash.h deleted file mode 100644 index d6bad94335..0000000000 --- a/include/util/xxhash.h +++ /dev/null @@ -1,328 +0,0 @@ -/* - xxHash - Extremely Fast Hash algorithm - Header File - Copyright (C) 2012-2016, Yann Collet. - - BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - You can contact the author at : - - xxHash source repository : https://github.com/Cyan4973/xxHash -*/ - -/* Notice extracted from xxHash homepage : - -xxHash is an extremely fast Hash algorithm, running at RAM speed limits. -It also successfully passes all tests from the SMHasher suite. - -Comparison (single thread, Windows Seven 32 bits, using SMHasher on a Core 2 Duo @3GHz) - -Name Speed Q.Score Author -xxHash 5.4 GB/s 10 -CrapWow 3.2 GB/s 2 Andrew -MumurHash 3a 2.7 GB/s 10 Austin Appleby -SpookyHash 2.0 GB/s 10 Bob Jenkins -SBox 1.4 GB/s 9 Bret Mulvey -Lookup3 1.2 GB/s 9 Bob Jenkins -SuperFastHash 1.2 GB/s 1 Paul Hsieh -CityHash64 1.05 GB/s 10 Pike & Alakuijala -FNV 0.55 GB/s 5 Fowler, Noll, Vo -CRC32 0.43 GB/s 9 -MD5-32 0.33 GB/s 10 Ronald L. Rivest -SHA1-32 0.28 GB/s 10 - -Q.Score is a measure of quality of the hash function. -It depends on successfully passing SMHasher test set. -10 is a perfect score. - -A 64-bit version, named XXH64, is available since r35. -It offers much better speed, but for 64-bit applications only. -Name Speed on 64 bits Speed on 32 bits -XXH64 13.8 GB/s 1.9 GB/s -XXH32 6.8 GB/s 6.0 GB/s -*/ - -#ifndef XXHASH_H_5627135585666179 -#define XXHASH_H_5627135585666179 1 - -#if defined (__cplusplus) -extern "C" { -#endif - - -/* **************************** -* Definitions -******************************/ -#include /* size_t */ -typedef enum { XXH_OK=0, XXH_ERROR } XXH_errorcode; - - -/* **************************** - * API modifier - ******************************/ -/** XXH_INLINE_ALL (and XXH_PRIVATE_API) - * This is useful to include xxhash functions in `static` mode - * in order to inline them, and remove their symbol from the public list. - * Inlining can offer dramatic performance improvement on small keys. - * Methodology : - * #define XXH_INLINE_ALL - * #include "xxhash.h" - * `xxhash.c` is automatically included. - * It's not useful to compile and link it as a separate module. - */ -#if defined(XXH_INLINE_ALL) || defined(XXH_PRIVATE_API) -# ifndef XXH_STATIC_LINKING_ONLY -# define XXH_STATIC_LINKING_ONLY -# endif -# if defined(__GNUC__) -# define XXH_PUBLIC_API static __inline __attribute__((unused)) -# elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) -# define XXH_PUBLIC_API static inline -# elif defined(_MSC_VER) -# define XXH_PUBLIC_API static __inline -# else - /* this version may generate warnings for unused static functions */ -# define XXH_PUBLIC_API static -# endif -#else -# define XXH_PUBLIC_API /* do nothing */ -#endif /* XXH_INLINE_ALL || XXH_PRIVATE_API */ - -/*! XXH_NAMESPACE, aka Namespace Emulation : - * - * If you want to include _and expose_ xxHash functions from within your own library, - * but also want to avoid symbol collisions with other libraries which may also include xxHash, - * - * you can use XXH_NAMESPACE, to automatically prefix any public symbol from xxhash library - * with the value of XXH_NAMESPACE (therefore, avoid NULL and numeric values). - * - * Note that no change is required within the calling program as long as it includes `xxhash.h` : - * regular symbol name will be automatically translated by this header. - */ -#ifdef XXH_NAMESPACE -# define XXH_CAT(A,B) A##B -# define XXH_NAME2(A,B) XXH_CAT(A,B) -# define XXH_versionNumber XXH_NAME2(XXH_NAMESPACE, XXH_versionNumber) -# define XXH32 XXH_NAME2(XXH_NAMESPACE, XXH32) -# define XXH32_createState XXH_NAME2(XXH_NAMESPACE, XXH32_createState) -# define XXH32_freeState XXH_NAME2(XXH_NAMESPACE, XXH32_freeState) -# define XXH32_reset XXH_NAME2(XXH_NAMESPACE, XXH32_reset) -# define XXH32_update XXH_NAME2(XXH_NAMESPACE, XXH32_update) -# define XXH32_digest XXH_NAME2(XXH_NAMESPACE, XXH32_digest) -# define XXH32_copyState XXH_NAME2(XXH_NAMESPACE, XXH32_copyState) -# define XXH32_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH32_canonicalFromHash) -# define XXH32_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH32_hashFromCanonical) -# define XXH64 XXH_NAME2(XXH_NAMESPACE, XXH64) -# define XXH64_createState XXH_NAME2(XXH_NAMESPACE, XXH64_createState) -# define XXH64_freeState XXH_NAME2(XXH_NAMESPACE, XXH64_freeState) -# define XXH64_reset XXH_NAME2(XXH_NAMESPACE, XXH64_reset) -# define XXH64_update XXH_NAME2(XXH_NAMESPACE, XXH64_update) -# define XXH64_digest XXH_NAME2(XXH_NAMESPACE, XXH64_digest) -# define XXH64_copyState XXH_NAME2(XXH_NAMESPACE, XXH64_copyState) -# define XXH64_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH64_canonicalFromHash) -# define XXH64_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH64_hashFromCanonical) -#endif - - -/* ************************************* -* Version -***************************************/ -#define XXH_VERSION_MAJOR 0 -#define XXH_VERSION_MINOR 6 -#define XXH_VERSION_RELEASE 5 -#define XXH_VERSION_NUMBER (XXH_VERSION_MAJOR *100*100 + XXH_VERSION_MINOR *100 + XXH_VERSION_RELEASE) -XXH_PUBLIC_API unsigned XXH_versionNumber (void); - - -/*-********************************************************************** -* 32-bit hash -************************************************************************/ -typedef unsigned int XXH32_hash_t; - -/*! XXH32() : - Calculate the 32-bit hash of sequence "length" bytes stored at memory address "input". - The memory between input & input+length must be valid (allocated and read-accessible). - "seed" can be used to alter the result predictably. - Speed on Core 2 Duo @ 3 GHz (single thread, SMHasher benchmark) : 5.4 GB/s */ -XXH_PUBLIC_API XXH32_hash_t XXH32 (const void* input, size_t length, unsigned int seed); - -/*====== Streaming ======*/ -typedef struct XXH32_state_s XXH32_state_t; /* incomplete type */ -XXH_PUBLIC_API XXH32_state_t* XXH32_createState(void); -XXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr); -XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* dst_state, const XXH32_state_t* src_state); - -XXH_PUBLIC_API XXH_errorcode XXH32_reset (XXH32_state_t* statePtr, unsigned int seed); -XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* statePtr, const void* input, size_t length); -XXH_PUBLIC_API XXH32_hash_t XXH32_digest (const XXH32_state_t* statePtr); - -/* - * Streaming functions generate the xxHash of an input provided in multiple segments. - * Note that, for small input, they are slower than single-call functions, due to state management. - * For small inputs, prefer `XXH32()` and `XXH64()`, which are better optimized. - * - * XXH state must first be allocated, using XXH*_createState() . - * - * Start a new hash by initializing state with a seed, using XXH*_reset(). - * - * Then, feed the hash state by calling XXH*_update() as many times as necessary. - * The function returns an error code, with 0 meaning OK, and any other value meaning there is an error. - * - * Finally, a hash value can be produced anytime, by using XXH*_digest(). - * This function returns the nn-bits hash as an int or long long. - * - * It's still possible to continue inserting input into the hash state after a digest, - * and generate some new hashes later on, by calling again XXH*_digest(). - * - * When done, free XXH state space if it was allocated dynamically. - */ - -/*====== Canonical representation ======*/ - -typedef struct { unsigned char digest[4]; } XXH32_canonical_t; -XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash); -XXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src); - -/* Default result type for XXH functions are primitive unsigned 32 and 64 bits. - * The canonical representation uses human-readable write convention, aka big-endian (large digits first). - * These functions allow transformation of hash result into and from its canonical format. - * This way, hash values can be written into a file / memory, and remain comparable on different systems and programs. - */ - - -#ifndef XXH_NO_LONG_LONG -/*-********************************************************************** -* 64-bit hash -************************************************************************/ -typedef unsigned long long XXH64_hash_t; - -/*! XXH64() : - Calculate the 64-bit hash of sequence of length "len" stored at memory address "input". - "seed" can be used to alter the result predictably. - This function runs faster on 64-bit systems, but slower on 32-bit systems (see benchmark). -*/ -XXH_PUBLIC_API XXH64_hash_t XXH64 (const void* input, size_t length, unsigned long long seed); - -/*====== Streaming ======*/ -typedef struct XXH64_state_s XXH64_state_t; /* incomplete type */ -XXH_PUBLIC_API XXH64_state_t* XXH64_createState(void); -XXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr); -XXH_PUBLIC_API void XXH64_copyState(XXH64_state_t* dst_state, const XXH64_state_t* src_state); - -XXH_PUBLIC_API XXH_errorcode XXH64_reset (XXH64_state_t* statePtr, unsigned long long seed); -XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH64_state_t* statePtr, const void* input, size_t length); -XXH_PUBLIC_API XXH64_hash_t XXH64_digest (const XXH64_state_t* statePtr); - -/*====== Canonical representation ======*/ -typedef struct { unsigned char digest[8]; } XXH64_canonical_t; -XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH64_canonical_t* dst, XXH64_hash_t hash); -XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src); -#endif /* XXH_NO_LONG_LONG */ - - - -#ifdef XXH_STATIC_LINKING_ONLY - -/* ================================================================================================ - This section contains declarations which are not guaranteed to remain stable. - They may change in future versions, becoming incompatible with a different version of the library. - These declarations should only be used with static linking. - Never use them in association with dynamic linking ! -=================================================================================================== */ - -/* These definitions are only present to allow - * static allocation of XXH state, on stack or in a struct for example. - * Never **ever** use members directly. */ - -#if !defined (__VMS) \ - && (defined (__cplusplus) \ - || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) -# include - -struct XXH32_state_s { - uint32_t total_len_32; - uint32_t large_len; - uint32_t v1; - uint32_t v2; - uint32_t v3; - uint32_t v4; - uint32_t mem32[4]; - uint32_t memsize; - uint32_t reserved; /* never read nor write, might be removed in a future version */ -}; /* typedef'd to XXH32_state_t */ - -struct XXH64_state_s { - uint64_t total_len; - uint64_t v1; - uint64_t v2; - uint64_t v3; - uint64_t v4; - uint64_t mem64[4]; - uint32_t memsize; - uint32_t reserved[2]; /* never read nor write, might be removed in a future version */ -}; /* typedef'd to XXH64_state_t */ - -# else - -struct XXH32_state_s { - unsigned total_len_32; - unsigned large_len; - unsigned v1; - unsigned v2; - unsigned v3; - unsigned v4; - unsigned mem32[4]; - unsigned memsize; - unsigned reserved; /* never read nor write, might be removed in a future version */ -}; /* typedef'd to XXH32_state_t */ - -# ifndef XXH_NO_LONG_LONG /* remove 64-bit support */ -struct XXH64_state_s { - unsigned long long total_len; - unsigned long long v1; - unsigned long long v2; - unsigned long long v3; - unsigned long long v4; - unsigned long long mem64[4]; - unsigned memsize; - unsigned reserved[2]; /* never read nor write, might be removed in a future version */ -}; /* typedef'd to XXH64_state_t */ -# endif - -# endif - - -#if defined(XXH_INLINE_ALL) || defined(XXH_PRIVATE_API) -# include "xxhash.c" /* include xxhash function bodies as `static`, for inlining */ -#endif - -#endif /* XXH_STATIC_LINKING_ONLY */ - - -#if defined (__cplusplus) -} -#endif - -#endif /* XXHASH_H_5627135585666179 */ diff --git a/packaging/docker/DockerfileCloud b/packaging/docker/DockerfileCloud deleted file mode 100644 index fa8fcabf34..0000000000 --- a/packaging/docker/DockerfileCloud +++ /dev/null @@ -1,30 +0,0 @@ -FROM ubuntu:18.04 - -WORKDIR /root - -ARG pkgFile -ARG dirName -ARG cpuType -RUN echo ${pkgFile} && echo ${dirName} - -RUN apt update -RUN apt install -y curl - -COPY ${pkgFile} /root/ -ENV TINI_VERSION v0.19.0 -ENV TAOS_DISABLE_ADAPTER 1 -ADD https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini-${cpuType} /tini -ENV DEBIAN_FRONTEND=noninteractive -WORKDIR /root/ -RUN tar -zxf ${pkgFile} && cd /root/${dirName}/ && /bin/bash install.sh -e no && cd /root && rm /root/${pkgFile} && rm -rf /root/${dirName} && apt-get update && apt-get install -y locales tzdata netcat && locale-gen en_US.UTF-8 && apt-get clean && rm -rf /var/lib/apt/lists/ && chmod +x /tini - -ENV LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/usr/lib" \ - LC_CTYPE=en_US.UTF-8 \ - LANG=en_US.UTF-8 \ - LC_ALL=en_US.UTF-8 -COPY ./run.sh /usr/bin/ -COPY ./bin/* /usr/bin/ - -ENTRYPOINT ["/tini", "--", "/usr/bin/entrypoint.sh"] -CMD ["bash", "-c", "/usr/bin/run.sh"] -VOLUME [ "/var/lib/taos", "/var/log/taos" ] diff --git a/packaging/docker/README.md b/packaging/docker/README.md index 763ab73724..4509a7a1a9 100644 --- a/packaging/docker/README.md +++ b/packaging/docker/README.md @@ -18,65 +18,58 @@ TDengine is an open-sourced big data platform under [GNU AGPL v3.0](http://www.g ## How to use this image -### Start a TDengine instance with RESTful API exposed +### Starting TDengine -Simply, you can use `docker run` to start a TDengine instance and connect it with restful connectors(eg. [JDBC-RESTful](https://www.taosdata.com/cn/documentation/connector/java)). +The TDengine image starts with the HTTP service activated by default, using the following command: -```bash +```shell docker run -d --name tdengine -p 6041:6041 tdengine/tdengine ``` -This command starts a docker container by name `tdengine` with TDengine server running, and maps the container's HTTP port 6041 to the host's port 6041. If you have `curl` in your host, you can list the databases by the command: +The above command starts a container named "tdengine" and maps the HTTP service port 6041 to the host port 6041. You can verify that the HTTP service provided in this container is available using the following command. -```bash +```shell curl -u root:taosdata -d "show databases" localhost:6041/rest/sql ``` -You can execute the `taos` shell command in the container: +The TDengine client taos can be executed in this container to access TDengine using the following command. -```bash +```shell $ docker exec -it tdengine taos -Welcome to the TDengine shell from Linux, Client Version:2.4.0.0 -Copyright (c) 2020 by TAOS Data, Inc. All rights reserved. - taos> show databases; - name | created_time | ntables | vgroups | replica | quorum | days | keep | cache(MB) | blocks | minrows | maxrows | wallevel | fsync | comp | cachelast | precision | update | status | -==================================================================================================================================================================================================================================================================================== - log | 2022-01-17 13:57:22.270 | 10 | 1 | 1 | 1 | 10 | 30 | 1 | 3 | 100 | 4096 | 1 | 3000 | 2 | 0 | us | 0 | ready | -Query OK, 1 row(s) in set (0.002843s) + name | +================================= + information_schema | + performance_schema | +Query OK, 2 row(s) in set (0.002843s) ``` -Since TDengine use container hostname to establish connections, it's a bit more complex to use TDengine CLI and native connectors(such as JDBC-JNI) with TDengine container instance. This is the recommended way to expose ports and use TDengine with docker in simple cases. If you want to use TDengine CLI or taosc/connectors smoothly outside the `tdengine` container, see next use cases that match you need. +The TDengine server running in the container uses the container's hostname to establish a connection. Using TDengine CLI or various connectors (such as JDBC-JNI) to access the TDengine inside the container from outside the container is more complicated. So the above is the simplest way to access the TDengine service in the container and is suitable for some simple scenarios. Please refer to the next section if you want to access the TDengine service in the container from outside the container using TDengine CLI or various connectors for complex scenarios. -### Start with host network +### Start TDengine on the host network -```bash +```shell docker run -d --name tdengine --network host tdengine/tdengine ``` -Starts container with `host` network will use host's hostname as fqdn instead of container id. It's much like starting natively with `systemd` in host. After installing the client, you can use `taos` shell as normal in host path. +The above command starts TDengine on the host network and uses the host's FQDN to establish a connection instead of the container's hostname. It is the equivalent of using `systemctl` to start TDengine on the host. If the TDengine client is already installed on the host, you can access it directly with the following command. -```bash +```shell $ taos -Welcome to the TDengine shell from Linux, Client Version:2.4.0.0 -Copyright (c) 2020 by TAOS Data, Inc. All rights reserved. - taos> show dnodes; id | end_point | vnodes | cores | status | role | create_time | offline reason | ====================================================================================================================================== - 1 | host:6030 | 1 | 8 | ready | any | 2022-01-17 22:10:32.619 | | + 1 | myhost:6030 | 1 | 8 | ready | any | 2022-01-17 22:10:32.619 | | Query OK, 1 row(s) in set (0.003233s) ``` -### Start with exposed ports and specified hostname +### Start TDengine with the specified hostname and port -Set the fqdn explicitly will help you to use in other environment or applications. We provide environment variable `TAOS_FQDN` or `fqdn` config option to explicitly set the hostname used by TDengine container instance(s). +The `TAOS_FQDN` environment variable or the `fqdn` configuration item in `taos.cfg` allows TDengine to establish a connection at the specified hostname. This approach provides greater flexibility for deployment. -Use `TAOS_FQDN` variable within `docker run` command: - -```bash +```shell docker run -d \ --name tdengine \ -e TAOS_FQDN=tdengine \ @@ -85,79 +78,58 @@ docker run -d \ tdengine/tdengine ``` -This command starts a docker container with TDengine server running and maps the container's TCP ports from 6030 to 6049 to the host's ports from 6030 to 6049 with TCP protocol and UDP ports range 6030-6039 to the host's UDP ports 6030-6039. If the host is already running TDengine server and occupying the same port(s), you need to map the container's port to a different unused port segment. (Please see TDengine 2.0 Port Description for details). In order to support TDengine clients accessing TDengine server services, both TCP and UDP ports need to be exposed by default(unless `rpcForceTcp` is set to `1`). +The above command starts a TDengine service in the container, which listens to the hostname tdengine, and maps the container's port segment 6030 to 6049 to the host's port segment 6030 to 6049 (both TCP and UDP ports need to be mapped). If the port segment is already occupied on the host, you can modify the above command to specify a free port segment on the host. If `rpcForceTcp` is set to `1`, you can map only the TCP protocol. -If you want to use TDengine CLI or native connectors([JDBC-JNI](https://www.taosdata.com/cn/documentation/connector/java), or [driver-go](https://github.com/taosdata/driver-go)), you need to make sure the `TAOS_FQDN` is resolvable at `/etc/hosts` or with custom DNS service. +Next, ensure the hostname "tdengine" is resolvable in `/etc/hosts`. -If you set the `TAOS_FQDN` to host's hostname, it will works as using `hosts` network like previous use case. Otherwise, like in `-e TAOS_FQDN=tdengine`, you can add the hostname record `tdengine` into `/etc/hosts` (use `127.0.0.1` here in host path, if use TDengine client/application in other hosts, you should set the right ip to the host eg. `192.168.10.1`(check the real ip in host with `hostname -i` or `ip route list default`) to make the TDengine endpoint resolvable): - -```bash +```shell echo 127.0.0.1 tdengine |sudo tee -a /etc/hosts ``` -Then you can use `taos` with the host `tdengine`: +Finally, the TDengine service can be accessed from the TDengine CLI or any connector with "tdengine" as the server address. -```bash -taos -h tdengine +```shell +taos -h tdengine -P 6030 ``` -Or develop/test applications with native connectors. As in python: +If set `TAOS_FQDN` to the same hostname, the effect is the same as "Start TDengine on host network". -```python -import taos; -conn = taos.connect(host = "tdengine") -res = conn.query("show databases") -for row in res.fetch_all_into_dict(): - print(row) -``` +### Start TDengine on the specified network -See the results: +You can also start TDengine on a specific network. Perform the following steps: -```bash -Python 3.8.10 (default, Nov 26 2021, 20:14:08) -[GCC 9.3.0] on linux -Type "help", "copyright", "credits" or "license" for more information. ->>> import taos; ->>> conn = taos.connect(host = "tdengine") ->>> res = conn.query("show databases") ->>> for row in res.fetch_all_into_dict(): -... print(row) -... -{'name': 'log', 'created_time': datetime.datetime(2022, 1, 17, 22, 56, 2, 490000), 'ntables': 11, 'vgroups': 1, 'replica': 1, 'quorum': 1, 'days': 10, 'keep': '30', 'cache(MB)': 1, 'blocks': 3, 'minrows': 100, 'maxrows': 4096, 'wallevel': 1, 'fsync': 3000, 'comp': 2, 'cachelast': 0, 'precision': 'us', 'update': 0, 'status': 'ready'} -``` +1. First, create a docker network named `td-net` -### Start with specific network + ```shell + docker network create td-net + ``` -Alternatively, you can use TDengine natively by using specific network. +2. Start TDengine -First, create network for TDengine server and client/application. + Start the TDengine service on the `td-net` network with the following command: -```bash -docker network create td-net -``` + ```shell + docker run -d --name tdengine --network td-net \ + -e TAOS_FQDN=tdengine \ + tdengine/tdengine + ``` -Start TDengine instance with service name as fqdn (explicitly set with `TAOS_FQDN`): +3. Start the TDengine client in another container on the same network -```bash -docker run -d --name tdengine --network td-net \ - -e TAOS_FQDN=tdengine \ - tdengine/tdengine -``` + ```shell + docker run --rm -it --network td-net -e TAOS_FIRST_EP=tdengine tdengine/tdengine taos + # or + #docker run --rm -it --network td-net -e tdengine/tdengine taos -h tdengine + ``` -Start TDengine client in another container with the specific network: +### Launching a client application in a container -```bash -docker run --rm -it --network td-net -e TAOS_FIRST_EP=tdengine tdengine/tdengine taos -# or -docker run --rm -it --network td-net -e tdengine/tdengine taos -h tdengine -``` +If you want to start your application in a container, you need to add the corresponding dependencies on TDengine to the image as well, e.g. -When you build your application with docker, you should add the TDengine client in the dockerfile, as based on `ubuntu:20.04` image, install the client like this: - -```dockerfile +```docker FROM ubuntu:20.04 RUN apt-get update && apt-get install -y wget -ENV TDENGINE_VERSION=2.4.0.0 +ENV TDENGINE_VERSION=3.0.0.0 RUN wget -c https://www.taosdata.com/assets-download/3.0/TDengine-client-${TDENGINE_VERSION}-Linux-x64.tar.gz \ && tar xvf TDengine-client-${TDENGINE_VERSION}-Linux-x64.tar.gz \ && cd TDengine-client-${TDENGINE_VERSION} \ @@ -169,10 +141,7 @@ RUN wget -c https://www.taosdata.com/assets-download/3.0/TDengine-client-${TDENG #CMD ["app"] ``` -Here is an Go example app: - - - +Here is an example GO program: ```go /* @@ -181,19 +150,19 @@ Here is an Go example app: package main import ( - "database/sql" - "flag" - "fmt" - "time" + "database/sql" + "flag" + "fmt" + "time" - _ "github.com/taosdata/driver-go/v2/taosSql" + _ "github.com/taosdata/driver-go/v3/taosSql" ) type config struct { - hostName string - serverPort string - user string - password string + hostName string + serverPort string + user string + password string } var configPara config @@ -201,70 +170,67 @@ var taosDriverName = "taosSql" var url string func init() { - flag.StringVar(&configPara.hostName, "h", "", "The host to connect to TDengine server.") - flag.StringVar(&configPara.serverPort, "p", "", "The TCP/IP port number to use for the connection to TDengine server.") - flag.StringVar(&configPara.user, "u", "root", "The TDengine user name to use when connecting to the server.") - flag.StringVar(&configPara.password, "P", "taosdata", "The password to use when connecting to the server.") - flag.Parse() + flag.StringVar(&configPara.hostName, "h", "", "The host to connect to TDengine server.") + flag.StringVar(&configPara.serverPort, "p", "", "The TCP/IP port number to use for the connection to TDengine server.") + flag.StringVar(&configPara.user, "u", "root", "The TDengine user name to use when connecting to the server.") + flag.StringVar(&configPara.password, "P", "taosdata", "The password to use when connecting to the server.") + flag.Parse() } func printAllArgs() { - fmt.Printf("============= args parse result: =============\n") - fmt.Printf("hostName: %v\n", configPara.hostName) - fmt.Printf("serverPort: %v\n", configPara.serverPort) - fmt.Printf("usr: %v\n", configPara.user) - fmt.Printf("password: %v\n", configPara.password) - fmt.Printf("================================================\n") + fmt.Printf("============= args parse result: =============\n") + fmt.Printf("hostName: %v\n", configPara.hostName) + fmt.Printf("serverPort: %v\n", configPara.serverPort) + fmt.Printf("usr: %v\n", configPara.user) + fmt.Printf("password: %v\n", configPara.password) + fmt.Printf("================================================\n") } func main() { - printAllArgs() + printAllArgs() - url = "root:taosdata@/tcp(" + configPara.hostName + ":" + configPara.serverPort + ")/" + url = "root:taosdata@/tcp(" + configPara.hostName + ":" + configPara.serverPort + ")/" - taos, err := sql.Open(taosDriverName, url) - checkErr(err, "open database error") - defer taos.Close() + taos, err := sql.Open(taosDriverName, url) + checkErr(err, "open database error") + defer taos.Close() - taos.Exec("create database if not exists test") - taos.Exec("use test") - taos.Exec("create table if not exists tb1 (ts timestamp, a int)") - _, err = taos.Exec("insert into tb1 values(now, 0)(now+1s,1)(now+2s,2)(now+3s,3)") - checkErr(err, "failed to insert") - rows, err := taos.Query("select * from tb1") - checkErr(err, "failed to select") + taos.Exec("create database if not exists test") + taos.Exec("use test") + taos.Exec("create table if not exists tb1 (ts timestamp, a int)") + _, err = taos.Exec("insert into tb1 values(now, 0)(now+1s,1)(now+2s,2)(now+3s,3)") + checkErr(err, "failed to insert") + rows, err := taos.Query("select * from tb1") + checkErr(err, "failed to select") - defer rows.Close() - for rows.Next() { - var r struct { - ts time.Time - a int - } - err := rows.Scan(&r.ts, &r.a) - if err != nil { - fmt.Println("scan error:\n", err) - return - } - fmt.Println(r.ts, r.a) - } + defer rows.Close() + for rows.Next() { + var r struct { + ts time.Time + a int + } + err := rows.Scan(&r.ts, &r.a) + if err != nil { + fmt.Println("scan error:\n", err) + return + } + fmt.Println(r.ts, r.a) + } } func checkErr(err error, prompt string) { - if err != nil { - fmt.Println("ERROR: %s\n", prompt) - panic(err) - } + if err != nil { + fmt.Println("ERROR: %s\n", prompt) + panic(err) + } } ``` - - +Here is the full Dockerfile: -Full version of dockerfile could be: - -```dockerfile +```docker FROM golang:1.17.6-buster as builder -ENV TDENGINE_VERSION=2.4.0.0 +ENV TDENGINE_VERSION=3.0.0.0 RUN wget -c https://www.taosdata.com/assets-download/3.0/TDengine-client-${TDENGINE_VERSION}-Linux-x64.tar.gz \ && tar xvf TDengine-client-${TDENGINE_VERSION}-Linux-x64.tar.gz \ && cd TDengine-client-${TDENGINE_VERSION} \ @@ -274,11 +240,13 @@ RUN wget -c https://www.taosdata.com/assets-download/3.0/TDengine-client-${TDENG WORKDIR /usr/src/app/ ENV GOPROXY="https://goproxy.io,direct" COPY ./main.go ./go.mod ./go.sum /usr/src/app/ -RUN go env && go mod tidy && go build +RUN go env +RUN go mod tidy +RUN go build FROM ubuntu:20.04 RUN apt-get update && apt-get install -y wget -ENV TDENGINE_VERSION=2.4.0.0 +ENV TDENGINE_VERSION=3.0.0.0 RUN wget -c https://www.taosdata.com/assets-download/3.0/TDengine-client-${TDENGINE_VERSION}-Linux-x64.tar.gz \ && tar xvf TDengine-client-${TDENGINE_VERSION}-Linux-x64.tar.gz \ && cd TDengine-client-${TDENGINE_VERSION} \ @@ -291,9 +259,9 @@ COPY --from=builder /usr/src/app/app /usr/bin/ CMD ["app"] ``` -Suppose you have `main.go`, `go.mod` `go.sum`, `app.dockerfile`, build the app and run it with network `td-net`: +Now that we have `main.go`, `go.mod`, `go.sum`, `app.dockerfile`, we can build the application and start it on the `td-net` network. -```bash +```shell $ docker build -t app -f app.dockerfile $ docker run --rm --network td-net app -h tdengine -p 6030 ============= args parse result: ============= @@ -316,26 +284,18 @@ password: taosdata 2022-01-18 01:43:51.029 +0000 UTC 3 ``` -Now you must be much familiar with developing and testing with TDengine, let's see some more complex cases. +### Start the TDengine cluster with docker-compose -### Start with docker-compose with multiple nodes(instances) +1. The following docker-compose file starts a TDengine cluster with three nodes. -Start a 2-replicas-2-mnodes-2-dnodes-1-arbitrator TDengine cluster with `docker-compose` is quite simple. Save the file as `docker-compose.yml`: - -```yaml +```yml version: "3" services: - arbitrator: - image: tdengine/tdengine:$VERSION - command: tarbitrator td-1: image: tdengine/tdengine:$VERSION environment: TAOS_FQDN: "td-1" TAOS_FIRST_EP: "td-1" - TAOS_NUM_OF_MNODES: "2" - TAOS_REPLICA: "2" - TAOS_ARBITRATOR: arbitrator:6042 volumes: - taosdata-td1:/var/lib/taos/ - taoslog-td1:/var/log/taos/ @@ -344,101 +304,95 @@ services: environment: TAOS_FQDN: "td-2" TAOS_FIRST_EP: "td-1" - TAOS_NUM_OF_MNODES: "2" - TAOS_REPLICA: "2" - TAOS_ARBITRATOR: arbitrator:6042 volumes: - taosdata-td2:/var/lib/taos/ - taoslog-td2:/var/log/taos/ + td-3: + image: tdengine/tdengine:$VERSION + environment: + TAOS_FQDN: "td-3" + TAOS_FIRST_EP: "td-1" + volumes: + - taosdata-td3:/var/lib/taos/ + - taoslog-td3:/var/log/taos/ volumes: taosdata-td1: taoslog-td1: taosdata-td2: taoslog-td2: + taosdata-td3: + taoslog-td3: ``` -You may notice that: +:::note -- We use `VERSION` environment variable to set `tdengine` image tag version once. -- **`TAOS_FIRST_EP`** **MUST** be set to join the newly created instances into an existing TDengine cluster. If you want more instances, use `TAOS_SECOND_EP` in case of HA(High Availability) concerns. -- `TAOS_NUM_OF_MNODES` is for setting number of mnodes for the cluster. -- `TAOS_REPLICA` set the default database replicas, `2` means there're one master and one slave copy of data. The `replica` option should be `1 <= replica <= 3`, and not greater than dnodes number. -- `TAOS_ARBITRATOR` set the arbitrator entrypoint of the cluster for failover/election stuff. It's better to use arbitrator in a two nodes cluster. -- The way to start an arbitrator service is as easy as abc: just add command name `tarbitrator`(which is the binary name of arbitrator daemon) in docker-compose service option: `command: tarbitrator`, and everything is ok now. +- The `VERSION` environment variable is used to set the tdengine image tag +- `TAOS_FIRST_EP` must be set on the newly created instance so that it can join the TDengine cluster; if there is a high availability requirement, `TAOS_SECOND_EP` needs to be used at the same time + ::: -Now run `docker-compose up -d` with version specified: +2. Start the cluster -```bash -$ VERSION=2.4.0.0 docker-compose up -d -Creating network "test_default" with the default driver -Creating volume "test_taosdata-td1" with default driver -Creating volume "test_taoslog-td1" with default driver -Creating volume "test_taosdata-td2" with default driver -Creating volume "test_taoslog-td2" with default driver -Creating test_td-1_1 ... done -Creating test_arbitrator_1 ... done -Creating test_td-2_1 ... done -``` + ```shell + $ VERSION=3.0.0.0 docker-compose up -d + Creating network "test_default" with the default driver + Creating volume "test_taosdata-td1" with default driver + Creating volume "test_taoslog-td1" with default driver + Creating volume "test_taosdata-td2" with default driver + Creating volume "test_taoslog-td2" with default driver + Creating test_td-1_1 ... done + Creating test_arbitrator_1 ... done + Creating test_td-2_1 ... done + ``` -Check the status: +3. Check the status of each node -```bash -$ docker-compose ps - Name Command State Ports ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -test_arbitrator_1 /usr/bin/entrypoint.sh tar ... Up 6030/tcp, 6031/tcp, 6032/tcp, 6033/tcp, 6034/tcp, 6035/tcp, 6036/tcp, 6037/tcp, 6038/tcp, 6039/tcp, 6040/tcp, 6041/tcp, 6042/tcp -test_td-1_1 /usr/bin/entrypoint.sh taosd Up 6030/tcp, 6031/tcp, 6032/tcp, 6033/tcp, 6034/tcp, 6035/tcp, 6036/tcp, 6037/tcp, 6038/tcp, 6039/tcp, 6040/tcp, 6041/tcp, 6042/tcp -test_td-2_1 /usr/bin/entrypoint.sh taosd Up 6030/tcp, 6031/tcp, 6032/tcp, 6033/tcp, 6034/tcp, 6035/tcp, 6036/tcp, 6037/tcp, 6038/tcp, 6039/tcp, 6040/tcp, 6041/tcp, 6042/tcp -``` + ```shell + $ docker-compose ps + Name Command State Ports + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + test_arbitrator_1 /usr/bin/entrypoint.sh tar ... Up 6030/tcp, 6031/tcp, 6032/tcp, 6033/tcp, 6034/tcp, 6035/tcp, 6036/tcp, 6037/tcp, 6038/tcp, 6039/tcp, 6040/tcp, 6041/tcp, 6042/tcp + test_td-1_1 /usr/bin/entrypoint.sh taosd Up 6030/tcp, 6031/tcp, 6032/tcp, 6033/tcp, 6034/tcp, 6035/tcp, 6036/tcp, 6037/tcp, 6038/tcp, 6039/tcp, 6040/tcp, 6041/tcp, 6042/tcp + test_td-2_1 /usr/bin/entrypoint.sh taosd Up 6030/tcp, 6031/tcp, 6032/tcp, 6033/tcp, 6034/tcp, 6035/tcp, 6036/tcp, 6037/tcp, 6038/tcp, 6039/tcp, 6040/tcp, 6041/tcp, 6042/tcp + ``` -Check dnodes with TDengine CLI: +4. Show dnodes via TDengine CLI -```bash +```shell $ docker-compose exec td-1 taos -s "show dnodes" -Welcome to the TDengine shell from Linux, Client Version:2.4.0.0 -Copyright (c) 2020 by TAOS Data, Inc. All rights reserved. - taos> show dnodes - id | end_point | vnodes | cores | status | role | create_time | offline reason | + id | endpoint | vnodes | support_vnodes | status | create_time | note | ====================================================================================================================================== - 1 | td-1:6030 | 1 | 8 | ready | any | 2022-01-18 02:47:42.871 | | - 2 | td-2:6030 | 0 | 8 | ready | any | 2022-01-18 02:47:43.518 | | - 0 | arbitrator:6042 | 0 | 0 | ready | arb | 2022-01-18 02:47:43.633 | - | -Query OK, 3 row(s) in set (0.000811s) + 1 | td-1:6030 | 0 | 32 | ready | 2022-08-19 07:57:29.971 | | + 2 | td-2:6030 | 0 | 32 | ready | 2022-08-19 07:57:31.415 | | + 3 | td-3:6030 | 0 | 32 | ready | 2022-08-19 07:57:31.417 | | +Query OK, 3 rows in database (0.021262s) + ``` -### Start a TDengine cluster with scaled taosadapter service +## taosAdapter -In previous use case, you could see the way to start other services built with TDengine(`taosd` as the default command). There's another important service you should know: +1. taosAdapter is enabled by default in the TDengine container. If you want to disable it, specify the environment variable `TAOS_DISABLE_ADAPTER=true` at startup -> **taosAdapter** is a TDengine’s companion tool and is a bridge/adapter between TDengine cluster and application. It provides an easy-to-use and efficient way to ingest data from data collections agents(like Telegraf, StatsD, CollectD) directly. It also provides InfluxDB/OpenTSDB compatible data ingestion interface to allow InfluxDB/OpenTSDB applications to immigrate to TDengine seamlessly. +2. At the same time, for flexible deployment, taosAdapter can be started in a separate container -`taosadapter` is running inside `tdengine` image by default, you can disable it by `TAOS_DISABLE_ADAPTER=true`. Running `taosadapter` in a separate container is like how `arbitrator` does: + ```docker + services: + # ... + adapter: + image: tdengine/tdengine:$VERSION + command: taosadapter + ``` -```yaml -services: - # ... - adapter: - image: tdengine/tdengine:$VERSION - command: taosadapter -``` + Suppose you want to deploy multiple taosAdapters to improve throughput and provide high availability. In that case, the recommended configuration method uses a reverse proxy such as Nginx to offer a unified access entry. For specific configuration methods, please refer to the official documentation of Nginx. Here is an example: -`taosadapter` could be scaled with docker-compose, so that you can manage the `taosadapter` nodes easily. Here is an example shows 4-`taosadapter` instances in a TDengine cluster(much like previous use cases): - -```yaml +```yml version: "3" networks: inter: - api: services: - arbitrator: - image: tdengine/tdengine:$VERSION - command: tarbitrator - networks: - - inter td-1: image: tdengine/tdengine:$VERSION networks: @@ -446,9 +400,6 @@ services: environment: TAOS_FQDN: "td-1" TAOS_FIRST_EP: "td-1" - TAOS_NUM_OF_MNODES: "2" - TAOS_REPLICA: "2" - TAOS_ARBITRATOR: arbitrator:6042 volumes: - taosdata-td1:/var/lib/taos/ - taoslog-td1:/var/log/taos/ @@ -459,15 +410,12 @@ services: environment: TAOS_FQDN: "td-2" TAOS_FIRST_EP: "td-1" - TAOS_NUM_OF_MNODES: "2" - TAOS_REPLICA: "2" - TAOS_ARBITRATOR: arbitrator:6042 volumes: - taosdata-td2:/var/lib/taos/ - taoslog-td2:/var/log/taos/ adapter: image: tdengine/tdengine:$VERSION - command: taosadapter + entrypoint: "taosadapter" networks: - inter environment: @@ -481,7 +429,6 @@ services: - adapter networks: - inter - - api ports: - 6041:6041 - 6044:6044/udp @@ -504,100 +451,14 @@ volumes: taoslog-td2: ``` -Start the cluster: +## Deploy with docker swarm -```bash -$ VERSION=2.4.0.0 docker-compose up -d -Creating network "docker_inter" with the default driver -Creating network "docker_api" with the default driver -Creating volume "docker_taosdata-td1" with default driver -Creating volume "docker_taoslog-td1" with default driver -Creating volume "docker_taosdata-td2" with default driver -Creating volume "docker_taoslog-td2" with default driver -Creating docker_td-2_1 ... done -Creating docker_arbitrator_1 ... done -Creating docker_td-1_1 ... done -Creating docker_adapter_1 ... done -Creating docker_adapter_2 ... done -Creating docker_adapter_3 ... done -``` +If you want to deploy a container-based TDengine cluster on multiple hosts, you can use docker swarm. First, to establish a docker swarm cluster on these hosts, please refer to the official docker documentation. -It will start a TDengine cluster with two dnodes and four taosadapter instances, expose ports 6041/tcp and 6044/udp to host. +The docker-compose file can refer to the previous section. Here is the command to start TDengine with docker swarm: -`6041` is the RESTful API endpoint port, you can verify that the RESTful interface taosAdapter provides working using the `curl` command. - -```bash -$ curl -H 'Authorization: Basic cm9vdDp0YW9zZGF0YQ==' -d 'show databases;' 127.0.0.1:6041/rest/sql -{"status":"succ","head":["name","created_time","ntables","vgroups","replica","quorum","days","keep","cache(MB)","blocks","minrows","maxrows","wallevel","fsync","comp","cachelast","precision","update","status"],"column_meta":[["name",8,32],["created_time",9,8],["ntables",4,4],["vgroups",4,4],["replica",3,2],["quorum",3,2],["days",3,2],["keep",8,24],["cache(MB)",4,4],["blocks",4,4],["minrows",4,4],["maxrows",4,4],["wallevel",2,1],["fsync",4,4],["comp",2,1],["cachelast",2,1],["precision",8,3],["update",2,1],["status",8,10]],"data":[["log","2022-01-18 04:37:42.902",16,1,1,1,10,"30",1,3,100,4096,1,3000,2,0,"us",0,"ready"]],"rows":1} -``` - -If you run curl in batch(here we use [hyperfine](https://github.com/sharkdp/hyperfine) - a command-line benchmarking tool), the requests are balanced into 4 adapter instances. - -```bash -hyperfine -m10 'curl -u root:taosdata localhost:6041/rest/sql -d "describe log.log"' -``` - -View the logs with `docker-compose logs`: - -```bash -$ docker-compose logs adapter -# some logs skipped -adapter_2 | 01/18 04:57:44.616529 00000039 TAOS_ADAPTER info "| 200 | 162.185µs | 172.21.0.9 | POST | /rest/sql " model=web sessionID=18 -adapter_1 | 01/18 04:57:44.627695 00000039 TAOS_ADAPTER info "| 200 | 145.485µs | 172.21.0.9 | POST | /rest/sql " model=web sessionID=17 -adapter_3 | 01/18 04:57:44.639165 00000040 TAOS_ADAPTER info "| 200 | 146.913µs | 172.21.0.9 | POST | /rest/sql " sessionID=17 model=web -adapter_4 | 01/18 04:57:44.650829 00000039 TAOS_ADAPTER info "| 200 | 153.201µs | 172.21.0.9 | POST | /rest/sql " sessionID=17 model=web -adapter_2 | 01/18 04:57:44.662422 00000039 TAOS_ADAPTER info "| 200 | 211.393µs | 172.21.0.9 | POST | /rest/sql " model=web sessionID=19 -adapter_1 | 01/18 04:57:44.673426 00000039 TAOS_ADAPTER info "| 200 | 154.714µs | 172.21.0.9 | POST | /rest/sql " model=web sessionID=18 -adapter_3 | 01/18 04:57:44.684788 00000040 TAOS_ADAPTER info "| 200 | 131.876µs | 172.21.0.9 | POST | /rest/sql " model=web sessionID=18 -adapter_4 | 01/18 04:57:44.696261 00000039 TAOS_ADAPTER info "| 200 | 162.173µs | 172.21.0.9 | POST | /rest/sql " model=web sessionID=18 -adapter_2 | 01/18 04:57:44.707414 00000039 TAOS_ADAPTER info "| 200 | 164.419µs | 172.21.0.9 | POST | /rest/sql " model=web sessionID=20 -adapter_1 | 01/18 04:57:44.720842 00000039 TAOS_ADAPTER info "| 200 | 179.374µs | 172.21.0.9 | POST | /rest/sql " model=web sessionID=19 -adapter_3 | 01/18 04:57:44.732184 00000040 TAOS_ADAPTER info "| 200 | 141.174µs | 172.21.0.9 | POST | /rest/sql " sessionID=19 model=web -adapter_4 | 01/18 04:57:44.744024 00000039 TAOS_ADAPTER info "| 200 | 159.774µs | 172.21.0.9 | POST | /rest/sql " model=web sessionID=19 -adapter_2 | 01/18 04:57:44.773732 00000039 TAOS_ADAPTER info "| 200 | 178.993µs | 172.21.0.9 | POST | /rest/sql " model=web sessionID=21 -adapter_1 | 01/18 04:57:44.796518 00000039 TAOS_ADAPTER info "| 200 | 238.24µs | 172.21.0.9 | POST | /rest/sql " model=web sessionID=20 -adapter_3 | 01/18 04:57:44.810744 00000040 TAOS_ADAPTER info "| 200 | 176.133µs | 172.21.0.9 | POST | /rest/sql " model=web sessionID=20 -adapter_4 | 01/18 04:57:44.826395 00000039 TAOS_ADAPTER info "| 200 | 149.215µs | 172.21.0.9 | POST | /rest/sql " model=web sessionID=20 -``` - -`6044/udp` is the [StatsD](https://github.com/statsd/statsd)-compatible port, you can verify this feature with `nc` command(usually provided by `netcat` package). - -```bash -echo "foo:1|c" | nc -u -w0 127.0.0.1 6044 -``` - -Check the result in `taos` shell with `docker-compose exec`: - -```bash -$ dc exec td-1 taos - -Welcome to the TDengine shell from Linux, Client Version:2.4.0.0 -Copyright (c) 2020 by TAOS Data, Inc. All rights reserved. - -taos> show databases; - name | created_time | ntables | vgroups | replica | quorum | days | keep | cache(MB) | blocks | minrows | maxrows | wallevel | fsync | comp | cachelast | precision | update | status | -==================================================================================================================================================================================================================================================================================== - log | 2022-01-18 04:37:42.902 | 17 | 1 | 1 | 1 | 10 | 30 | 1 | 3 | 100 | 4096 | 1 | 3000 | 2 | 0 | us | 0 | ready | - statsd | 2022-01-18 04:45:02.563 | 1 | 1 | 2 | 1 | 10 | 3650 | 16 | 6 | 100 | 4096 | 1 | 3000 | 2 | 0 | ns | 2 | ready | -Query OK, 2 row(s) in set (0.001838s) - -taos> select * from statsd.foo; - ts | value | metric_type | -======================================================================================= - 2022-01-18 04:45:02.563422822 | 1 | counter | -Query OK, 1 row(s) in set (0.003854s) -``` - -Use `docker-compose up -d adapter=1 to reduce the instances to 1 - -### Deploy TDengine cluster in Docker Swarm with `docker-compose.yml` - -If you use docker swarm mode, it will schedule arbitrator/taosd/taosadapter services into different hosts automatically. If you've no experience with k8s/kubernetes, this is the most convenient way to scale out the TDengine cluster with multiple hosts/servers. - -Use the `docker-compose.yml` file in previous use case, and deploy with `docker stack` or `docker deploy`: - -```bash -$ VERSION=2.4.0 docker stack deploy -c docker-compose.yml taos +```shell +$ VERSION=3.0.0.0 docker stack deploy -c docker-compose.yml taos Creating network taos_inter Creating network taos_api Creating service taos_arbitrator @@ -607,58 +468,40 @@ Creating service taos_adapter Creating service taos_nginx ``` -Now you've created a TDengine cluster with multiple host servers. +Checking status: -Use `docker service` or `docker stack` to manage the cluster: - - - -```bash +```shell $ docker stack ps taos ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS -79ni8temw59n taos_nginx.1 nginx:latest TM1701 Running Running about a minute ago -3e94u72msiyg taos_adapter.1 tdengine/tdengine:2.4.0 TM1702 Running Running 56 seconds ago -100amjkwzsc6 taos_td-2.1 tdengine/tdengine:2.4.0 TM1703 Running Running about a minute ago -pkjehr2vvaaa taos_td-1.1 tdengine/tdengine:2.4.0 TM1704 Running Running 2 minutes ago -tpzvgpsr1qkt taos_arbitrator.1 tdengine/tdengine:2.4.0 TM1705 Running Running 2 minutes ago -rvss3g5yg6fa taos_adapter.2 tdengine/tdengine:2.4.0 TM1706 Running Running 56 seconds ago -i2augxamfllf taos_adapter.3 tdengine/tdengine:2.4.0 TM1707 Running Running 56 seconds ago -lmjyhzccpvpg taos_adapter.4 tdengine/tdengine:2.4.0 TM1708 Running Running 56 seconds ago +79ni8temw59n taos_nginx.1 nginx:latest TM1701 Running Running about a minute ago +3e94u72msiyg taos_adapter.1 tdengine/tdengine:3.0.0.0 TM1702 Running Running 56 seconds ago +100amjkwzsc6 taos_td-2.1 tdengine/tdengine:3.0.0.0 TM1703 Running Running about a minute ago +pkjehr2vvaaa taos_td-1.1 tdengine/tdengine:3.0.0.0 TM1704 Running Running 2 minutes ago +tpzvgpsr1qkt taos_arbitrator.1 tdengine/tdengine:3.0.0.0 TM1705 Running Running 2 minutes ago +rvss3g5yg6fa taos_adapter.2 tdengine/tdengine:3.0.0.0 TM1706 Running Running 56 seconds ago +i2augxamfllf taos_adapter.3 tdengine/tdengine:3.0.0.0 TM1707 Running Running 56 seconds ago +lmjyhzccpvpg taos_adapter.4 tdengine/tdengine:3.0.0.0 TM1708 Running Running 56 seconds ago $ docker service ls ID NAME MODE REPLICAS IMAGE PORTS -561t4lu6nfw6 taos_adapter replicated 4/4 tdengine/tdengine:2.4.0 -3hk5ct3q90sm taos_arbitrator replicated 1/1 tdengine/tdengine:2.4.0 +561t4lu6nfw6 taos_adapter replicated 4/4 tdengine/tdengine:3.0.0.0 +3hk5ct3q90sm taos_arbitrator replicated 1/1 tdengine/tdengine:3.0.0.0 d8qr52envqzu taos_nginx replicated 1/1 nginx:latest *:6041->6041/tcp, *:6044->6044/udp -2isssfvjk747 taos_td-1 replicated 1/1 tdengine/tdengine:2.4.0 -9pzw7u02ichv taos_td-2 replicated 1/1 tdengine/tdengine:2.4.0 +2isssfvjk747 taos_td-1 replicated 1/1 tdengine/tdengine:3.0.0.0 +9pzw7u02ichv taos_td-2 replicated 1/1 tdengine/tdengine:3.0.0.0 ``` - +From the above output, you can see two dnodes, two taosAdapters, and one Nginx reverse proxy service. -It shows that there are two dnodes, one arbitrator, four taosadapter and one nginx reverse-forward service in this cluster. +Next, we can reduce the number of taosAdapter services. -You can scale down the taosadapter replicas to `1` by `docker service`: - -```bash +```shell $ docker service scale taos_adapter=1 taos_adapter scaled to 1 -overall progress: 1 out of 1 tasks -1/1: running [==================================================>] +overall progress: 1 out of 1 tasks +1/1: running [==================================================>] verify: Service converged $ docker service ls -f name=taos_adapter ID NAME MODE REPLICAS IMAGE PORTS -561t4lu6nfw6 taos_adapter replicated 1/1 tdengine/tdengine:2.4.0 +561t4lu6nfw6 taos_adapter replicated 1/1 tdengine/tdengine:3.0.0.0 ``` - -Now it remains only 1 taosadapter instance in the cluster. - -When you want to remove the cluster, just type: - -```bash -docker stack rm taos -``` - -### Environment Variables - -When you start `tdengine` image, you can adjust the configuration of TDengine by passing environment variables on the `docker run` command line or in the docker compose file. You can use all of the environment variables that passed to taosd or taosadapter. diff --git a/packaging/docker/docker-compose.yml b/packaging/docker/docker-compose.yml deleted file mode 100644 index 301b41e7d4..0000000000 --- a/packaging/docker/docker-compose.yml +++ /dev/null @@ -1,77 +0,0 @@ -version: "3" - -networks: - inter: - api: - -services: - arbitrator: - image: tdengine/tdengine:$VERSION - command: tarbitrator - networks: - - inter - td-1: - image: tdengine/tdengine:$VERSION - networks: - - inter - environment: - TAOS_FQDN: "td-1" - TAOS_FIRST_EP: "td-1" - TAOS_NUM_OF_MNODES: "2" - TAOS_REPLICA: "2" - TAOS_ARBITRATOR: arbitrator:6042 - volumes: - - taosdata-td1:/var/lib/taos/ - - taoslog-td1:/var/log/taos/ - td-2: - image: tdengine/tdengine:$VERSION - networks: - - inter - environment: - TAOS_FQDN: "td-2" - TAOS_FIRST_EP: "td-1" - TAOS_NUM_OF_MNODES: "2" - TAOS_REPLICA: "2" - TAOS_ARBITRATOR: arbitrator:6042 - volumes: - - taosdata-td2:/var/lib/taos/ - - taoslog-td2:/var/log/taos/ - adapter: - image: tdengine/tdengine:$VERSION - command: taosadapter - networks: - - inter - environment: - TAOS_FIRST_EP: "td-1" - TOAS_SECOND_EP: "td-2" - deploy: - replicas: 4 - update_config: - parallelism: 4 - nginx: - image: nginx - depends_on: - - adapter - networks: - - inter - - api - ports: - - 6041:6041 - - 6044:6044/udp - command: [ - "sh", - "-c", - "while true; - do curl -s http://adapter:6041/-/ping >/dev/null && break; - done; - printf 'server{listen 6041;location /{proxy_pass http://adapter:6041;}}' - > /etc/nginx/conf.d/rest.conf; - printf 'stream{server{listen 6044 udp;proxy_pass adapter:6044;}}' - >> /etc/nginx/nginx.conf;cat /etc/nginx/nginx.conf; - nginx -g 'daemon off;'", - ] -volumes: - taosdata-td1: - taoslog-td1: - taosdata-td2: - taoslog-td2: diff --git a/packaging/docker/dockerManifest.sh b/packaging/docker/dockerManifest.sh index 8f71e30fbd..db71bf8833 100755 --- a/packaging/docker/dockerManifest.sh +++ b/packaging/docker/dockerManifest.sh @@ -1,9 +1,9 @@ #!/bin/bash set -e #set -x -set -v +set -v -# dockerbuild.sh +# dockerbuild.sh # -n [version number] # -p [xxxx] # -V [stable | beta] @@ -28,7 +28,7 @@ do V) #echo "verType=$OPTARG" verType=$(echo $OPTARG) - ;; + ;; h) echo "Usage: `basename $0` -n [version number] " echo " -p [password for docker hub] " @@ -39,8 +39,8 @@ do a) #echo "dockerLatest=$OPTARG" dockerLatest=$(echo $OPTARG) - ;; - ?) #unknow option + ;; + ?) #unknow option echo "unkonw argument" exit 1 ;; @@ -60,7 +60,7 @@ if [ "$verType" == "stable" ]; then elif [ "$verType" == "beta" ];then verType=beta tagVal=ver-${version}-beta - dockerinput=TDengine-server-${version}-${verType}-Linux-$cpuType.tar.gz + dockerinput=TDengine-server-${version}-${verType}-Linux-$cpuType.tar.gz dockerinput_x64=TDengine-server-${version}-${verType}-Linux-amd64.tar.gz dockerim=tdengine/tdengine-beta dockeramd64=tdengine/tdengine-amd64-beta @@ -73,30 +73,30 @@ fi username="tdengine" -# generate docker verison +# generate docker version echo "generate ${dockerim}:${version}" docker manifest create -a ${dockerim}:${version} ${dockeramd64}:${version} ${dockeraarch64}:${version} docker manifest inspect ${dockerim}:${version} docker manifest rm ${dockerim}:${version} docker manifest create -a ${dockerim}:${version} ${dockeramd64}:${version} ${dockeraarch64}:${version} docker manifest inspect ${dockerim}:${version} -docker login -u ${username} -p ${passWord} +docker login -u ${username} -p ${passWord} docker manifest push ${dockerim}:${version} -# generate docker latest +# generate docker latest echo "generate ${dockerim}:latest " if [ ${dockerLatest} == 'y' ] ;then echo "docker manifest create -a ${dockerim}:latest ${dockeramd64}:latest ${dockeraarch64}:latest" docker manifest create -a ${dockerim}:latest ${dockeramd64}:latest ${dockeraarch64}:latest - docker manifest inspect ${dockerim}:latest - docker manifest rm ${dockerim}:latest + docker manifest inspect ${dockerim}:latest + docker manifest rm ${dockerim}:latest docker manifest create -a ${dockerim}:latest ${dockeramd64}:latest ${dockeraarch64}:latest docker manifest inspect ${dockerim}:latest docker login -u tdengine -p ${passWord} #replace the docker registry username and password docker manifest push ${dockerim}:latest - docker pull tdengine/tdengine:latest + docker pull tdengine/tdengine:latest fi diff --git a/packaging/docker/dockerbuild.sh b/packaging/docker/dockerbuild.sh index b02387a3d1..4b6fc8576b 100755 --- a/packaging/docker/dockerbuild.sh +++ b/packaging/docker/dockerbuild.sh @@ -74,7 +74,7 @@ do done -# Check_verison() +# Check_version() # { # } @@ -102,14 +102,14 @@ scriptDir=$(dirname $(readlink -f $0)) communityDir=${scriptDir}/../../../community DockerfilePath=${communityDir}/packaging/docker/ if [ "$cloudBuild" == "y" ]; then - comunityArchiveDir=/nas/TDengine/v$version/cloud + communityArchiveDir=/nas/TDengine/v$version/cloud Dockerfile=${communityDir}/packaging/docker/DockerfileCloud else - comunityArchiveDir=/nas/TDengine/v$version/community + communityArchiveDir=/nas/TDengine/v$version/community Dockerfile=${communityDir}/packaging/docker/Dockerfile fi cd ${scriptDir} -cp -f ${comunityArchiveDir}/${pkgFile} . +cp -f ${communityArchiveDir}/${pkgFile} . echo "dirName=${dirName}" diff --git a/packaging/tools/post.sh b/packaging/tools/post.sh index 6755ed40e5..78eb7f7587 100755 --- a/packaging/tools/post.sh +++ b/packaging/tools/post.sh @@ -627,9 +627,16 @@ function install_app() { fi } -function install_TDengine() { - echo -e "${GREEN}Start to install TDengine...${NC}" - log_print "start to install TDengine" +function checkDirectory() { + if [ ! -d "${bin_link_dir}" ]; then + ${csudo}mkdir -p ${bin_link_dir} + log_print "${bin_link_dir} directory created" + fi + + if [ ! -d "${lib_link_dir}" ]; then + ${csudo}mkdir -p ${lib_link_dir} + log_print "${lib_link_dir} directory created" + fi #install log and data dir , then ln to /usr/local/taos ${csudo}mkdir -p ${log_dir} && ${csudo}chmod 777 ${log_dir} @@ -640,6 +647,13 @@ function install_TDengine() { ${csudo}ln -s ${log_dir} ${log_link_dir} || : ${csudo}ln -s ${data_dir} ${data_link_dir} || : +} + +function install_TDengine() { + echo -e "${GREEN}Start to install TDengine...${NC}" + log_print "start to install TDengine" + + checkDirectory # Install include, lib, binary and service install_include && diff --git a/source/client/src/clientHb.c b/source/client/src/clientHb.c index 3cb8a2e1bd..b5838386db 100644 --- a/source/client/src/clientHb.c +++ b/source/client/src/clientHb.c @@ -49,6 +49,48 @@ static int32_t hbProcessUserAuthInfoRsp(void *value, int32_t valueLen, struct SC return TSDB_CODE_SUCCESS; } +static int32_t hbGenerateVgInfoFromRsp(SDBVgInfo **pInfo, SUseDbRsp *rsp) { + int32_t code = 0; + SDBVgInfo *vgInfo = taosMemoryCalloc(1, sizeof(SDBVgInfo)); + if (NULL == vgInfo) { + code = TSDB_CODE_OUT_OF_MEMORY; + return code; + } + + vgInfo->vgVersion = rsp->vgVersion; + vgInfo->stateTs = rsp->stateTs; + vgInfo->hashMethod = rsp->hashMethod; + vgInfo->hashPrefix = rsp->hashPrefix; + vgInfo->hashSuffix = rsp->hashSuffix; + vgInfo->vgHash = taosHashInit(rsp->vgNum, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), true, HASH_ENTRY_LOCK); + if (NULL == vgInfo->vgHash) { + taosMemoryFree(vgInfo); + tscError("hash init[%d] failed", rsp->vgNum); + code = TSDB_CODE_OUT_OF_MEMORY; + goto _return; + } + + for (int32_t j = 0; j < rsp->vgNum; ++j) { + SVgroupInfo *pInfo = taosArrayGet(rsp->pVgroupInfos, j); + if (taosHashPut(vgInfo->vgHash, &pInfo->vgId, sizeof(int32_t), pInfo, sizeof(SVgroupInfo)) != 0) { + tscError("hash push failed, errno:%d", errno); + taosHashCleanup(vgInfo->vgHash); + taosMemoryFree(vgInfo); + code = TSDB_CODE_OUT_OF_MEMORY; + goto _return; + } + } + +_return: + if (code) { + taosHashCleanup(vgInfo->vgHash); + taosMemoryFreeClear(vgInfo); + } + + *pInfo = vgInfo; + return code; +} + static int32_t hbProcessDBInfoRsp(void *value, int32_t valueLen, struct SCatalog *pCatalog) { int32_t code = 0; @@ -67,37 +109,22 @@ static int32_t hbProcessDBInfoRsp(void *value, int32_t valueLen, struct SCatalog if (rsp->vgVersion < 0) { code = catalogRemoveDB(pCatalog, rsp->db, rsp->uid); } else { - SDBVgInfo *vgInfo = taosMemoryCalloc(1, sizeof(SDBVgInfo)); - if (NULL == vgInfo) { - code = TSDB_CODE_OUT_OF_MEMORY; + SDBVgInfo *vgInfo = NULL; + code = hbGenerateVgInfoFromRsp(&vgInfo, rsp); + if (TSDB_CODE_SUCCESS != code) { goto _return; } - vgInfo->vgVersion = rsp->vgVersion; - vgInfo->stateTs = rsp->stateTs; - vgInfo->hashMethod = rsp->hashMethod; - vgInfo->hashPrefix = rsp->hashPrefix; - vgInfo->hashSuffix = rsp->hashSuffix; - vgInfo->vgHash = taosHashInit(rsp->vgNum, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), true, HASH_ENTRY_LOCK); - if (NULL == vgInfo->vgHash) { - taosMemoryFree(vgInfo); - tscError("hash init[%d] failed", rsp->vgNum); - code = TSDB_CODE_OUT_OF_MEMORY; - goto _return; - } - - for (int32_t j = 0; j < rsp->vgNum; ++j) { - SVgroupInfo *pInfo = taosArrayGet(rsp->pVgroupInfos, j); - if (taosHashPut(vgInfo->vgHash, &pInfo->vgId, sizeof(int32_t), pInfo, sizeof(SVgroupInfo)) != 0) { - tscError("hash push failed, errno:%d", errno); - taosHashCleanup(vgInfo->vgHash); - taosMemoryFree(vgInfo); - code = TSDB_CODE_OUT_OF_MEMORY; - goto _return; - } - } - catalogUpdateDBVgInfo(pCatalog, rsp->db, rsp->uid, vgInfo); + + if (IS_SYS_DBNAME(rsp->db)) { + code = hbGenerateVgInfoFromRsp(&vgInfo, rsp); + if (TSDB_CODE_SUCCESS != code) { + goto _return; + } + + catalogUpdateDBVgInfo(pCatalog, (rsp->db[0] == 'i') ? TSDB_PERFORMANCE_SCHEMA_DB : TSDB_INFORMATION_SCHEMA_DB, rsp->uid, vgInfo); + } } if (code) { @@ -347,7 +374,7 @@ int32_t hbBuildQueryDesc(SQueryHbReqBasic *hbBasic, STscObj *pObj) { continue; } - if (pRequest->killed) { + if (pRequest->killed || 0 == pRequest->body.queryJob) { releaseRequest(*rid); pIter = taosHashIterate(pObj->pRequests, pIter); continue; @@ -491,6 +518,9 @@ int32_t hbGetExpiredDBInfo(SClientHbKey *connKey, struct SCatalog *pCatalog, SCl for (int32_t i = 0; i < dbNum; ++i) { SDbVgVersion *db = &dbs[i]; + tscDebug("the %dth expired dbFName:%s, dbId:%" PRId64 ", vgVersion:%d, numOfTable:%d, startTs:%" PRId64, + i, db->dbFName, db->dbId, db->vgVersion, db->numOfTable, db->stateTs); + db->dbId = htobe64(db->dbId); db->vgVersion = htonl(db->vgVersion); db->numOfTable = htonl(db->numOfTable); @@ -758,7 +788,7 @@ static void *hbThreadFunc(void *param) { pInfo->msgInfo.pData = buf; pInfo->msgInfo.len = tlen; pInfo->msgType = TDMT_MND_HEARTBEAT; - pInfo->param = strdup(pAppHbMgr->key); + pInfo->param = taosStrdup(pAppHbMgr->key); pInfo->paramFreeFp = taosMemoryFree; pInfo->requestId = generateRequestId(); pInfo->requestObjRefId = 0; @@ -826,7 +856,7 @@ SAppHbMgr *appHbMgrInit(SAppInstInfo *pAppInstInfo, char *key) { pAppHbMgr->connKeyCnt = 0; pAppHbMgr->reportCnt = 0; pAppHbMgr->reportBytes = 0; - pAppHbMgr->key = strdup(key); + pAppHbMgr->key = taosStrdup(key); // init app info pAppHbMgr->pAppInstInfo = pAppInstInfo; diff --git a/source/client/src/clientImpl.c b/source/client/src/clientImpl.c index f63069d08b..a6d2fad816 100644 --- a/source/client/src/clientImpl.c +++ b/source/client/src/clientImpl.c @@ -52,7 +52,7 @@ static bool validateDbName(const char* db) { return stringLengthCheck(db, TSDB_D static char* getClusterKey(const char* user, const char* auth, const char* ip, int32_t port) { char key[512] = {0}; snprintf(key, sizeof(key), "%s:%s:%s:%d", user, auth, ip, port); - return strdup(key); + return taosStrdup(key); } bool chkRequestKilled(void* param) { diff --git a/source/client/src/clientMsgHandler.c b/source/client/src/clientMsgHandler.c index 2191c54315..a5f963a956 100644 --- a/source/client/src/clientMsgHandler.c +++ b/source/client/src/clientMsgHandler.c @@ -162,6 +162,22 @@ int32_t processCreateDbRsp(void* param, SDataBuf* pMsg, int32_t code) { taosMemoryFree(pMsg->pEpSet); if (code != TSDB_CODE_SUCCESS) { setErrno(pRequest, code); + } else { + struct SCatalog* pCatalog = NULL; + int32_t code = catalogGetHandle(pRequest->pTscObj->pAppInfo->clusterId, &pCatalog); + if (TSDB_CODE_SUCCESS == code) { + STscObj* pTscObj = pRequest->pTscObj; + + SRequestConnInfo conn = {.pTrans = pTscObj->pAppInfo->pTransporter, + .requestId = pRequest->requestId, + .requestObjRefId = pRequest->self, + .mgmtEps = getEpSet_s(&pTscObj->pAppInfo->mgmtEp)}; + char dbFName[TSDB_DB_FNAME_LEN]; + snprintf(dbFName, sizeof(dbFName) - 1, "%d.%s", pTscObj->acctId, TSDB_INFORMATION_SCHEMA_DB); + catalogRefreshDBVgInfo(pCatalog, &conn, dbFName); + snprintf(dbFName, sizeof(dbFName) - 1, "%d.%s", pTscObj->acctId, TSDB_PERFORMANCE_SCHEMA_DB); + catalogRefreshDBVgInfo(pCatalog, &conn, dbFName); + } } if (pRequest->body.queryFp) { @@ -418,12 +434,12 @@ static int32_t buildShowVariablesBlock(SArray* pVars, SSDataBlock** block) { char name[TSDB_CONFIG_OPTION_LEN + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(name, pInfo->name, TSDB_CONFIG_OPTION_LEN + VARSTR_HEADER_SIZE); SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, c++); - colDataAppend(pColInfo, i, name, false); + colDataSetVal(pColInfo, i, name, false); char value[TSDB_CONFIG_VALUE_LEN + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(value, pInfo->value, TSDB_CONFIG_VALUE_LEN + VARSTR_HEADER_SIZE); pColInfo = taosArrayGet(pBlock->pDataBlock, c++); - colDataAppend(pColInfo, i, value, false); + colDataSetVal(pColInfo, i, value, false); } pBlock->info.rows = numOfCfg; @@ -456,12 +472,13 @@ static int32_t buildShowVariablesRsp(SArray* pVars, SRetrieveTableRsp** pRsp) { (*pRsp)->numOfCols = htonl(SHOW_VARIABLES_RESULT_COLS); int32_t len = blockEncode(pBlock, (*pRsp)->data, SHOW_VARIABLES_RESULT_COLS); + blockDataDestroy(pBlock); + if(len != rspSize - sizeof(SRetrieveTableRsp)){ uError("buildShowVariablesRsp error, len:%d != rspSize - sizeof(SRetrieveTableRsp):%" PRIu64, len, (uint64_t) (rspSize - sizeof(SRetrieveTableRsp))); return TSDB_CODE_TSC_INVALID_INPUT; } - blockDataDestroy(pBlock); return TSDB_CODE_SUCCESS; } diff --git a/source/client/src/clientSmlLine.c b/source/client/src/clientSmlLine.c index f2c212928e..a2f752edb9 100644 --- a/source/client/src/clientSmlLine.c +++ b/source/client/src/clientSmlLine.c @@ -544,7 +544,7 @@ static int32_t smlParseColKv(SSmlHandle *info, char **sql, char *sqlEnd, SSmlLin } } else { if (currElement->colArray == NULL) { - currElement->colArray = taosArrayInit_s(16, sizeof(SSmlKv), 1); + currElement->colArray = taosArrayInit_s(sizeof(SSmlKv), 1); } taosArrayPush(currElement->colArray, &kv); // reserve for timestamp } diff --git a/source/client/src/clientTmq.c b/source/client/src/clientTmq.c index 540cec1de3..d913b32642 100644 --- a/source/client/src/clientTmq.c +++ b/source/client/src/clientTmq.c @@ -58,15 +58,14 @@ struct tmq_list_t { }; struct tmq_conf_t { - char clientId[256]; - char groupId[TSDB_CGROUP_LEN]; - int8_t autoCommit; - int8_t resetOffset; - int8_t withTbName; - int8_t snapEnable; - int32_t snapBatchSize; - bool hbBgEnable; - + char clientId[256]; + char groupId[TSDB_CGROUP_LEN]; + int8_t autoCommit; + int8_t resetOffset; + int8_t withTbName; + int8_t snapEnable; + int32_t snapBatchSize; + bool hbBgEnable; uint16_t port; int32_t autoCommitInterval; char* ip; @@ -213,6 +212,7 @@ typedef struct { typedef struct { SMqCommitCbParamSet* params; STqOffset* pOffset; + SMqClientVg* pMqVg; /*char topicName[TSDB_TOPIC_FNAME_LEN];*/ /*int32_t vgId;*/ } SMqCommitCbParam; @@ -330,15 +330,15 @@ tmq_conf_res_t tmq_conf_set(tmq_conf_t* conf, const char* key, const char* value } if (strcmp(key, "td.connect.ip") == 0) { - conf->ip = strdup(value); + conf->ip = taosStrdup(value); return TMQ_CONF_OK; } if (strcmp(key, "td.connect.user") == 0) { - conf->user = strdup(value); + conf->user = taosStrdup(value); return TMQ_CONF_OK; } if (strcmp(key, "td.connect.pass") == 0) { - conf->pass = strdup(value); + conf->pass = taosStrdup(value); return TMQ_CONF_OK; } if (strcmp(key, "td.connect.port") == 0) { @@ -346,7 +346,7 @@ tmq_conf_res_t tmq_conf_set(tmq_conf_t* conf, const char* key, const char* value return TMQ_CONF_OK; } if (strcmp(key, "td.connect.db") == 0) { - /*conf->db = strdup(value);*/ + /*conf->db = taosStrdup(value);*/ return TMQ_CONF_OK; } @@ -361,7 +361,7 @@ tmq_list_t* tmq_list_new() { int32_t tmq_list_append(tmq_list_t* list, const char* src) { SArray* container = &list->container; if (src == NULL || src[0] == 0) return -1; - char* topic = strdup(src); + char* topic = taosStrdup(src); if (topic[0] != '`') { strtolower(topic, src); } @@ -422,10 +422,6 @@ int32_t tmqCommitDone(SMqCommitCbParamSet* pParamSet) { static void tmqCommitRspCountDown(SMqCommitCbParamSet* pParamSet) { int32_t waitingRspNum = atomic_sub_fetch_32(&pParamSet->waitingRspNum, 1); - if (ASSERT(waitingRspNum >= 0)) { - tscError("tmqCommitRspCountDown error:%d", waitingRspNum); - return; - } if (waitingRspNum == 0) { tmqCommitDone(pParamSet); } @@ -443,6 +439,17 @@ int32_t tmqCommitCb(void* param, SDataBuf* pBuf, int32_t code) { } #endif + // there may be race condition. fix it + if (pBuf->pEpSet != NULL && pParam->pMqVg != NULL) { + SMqClientVg* pMqVg = pParam->pMqVg; + + SEp* pEp = GET_ACTIVE_EP(pBuf->pEpSet); + SEp* pOld = GET_ACTIVE_EP(&(pMqVg->epSet)); + uDebug("subKey:%s update the epset vgId:%d, ep:%s:%d, old ep:%s:%d", pParam->pOffset->subKey, pMqVg->vgId, + pEp->fqdn, pEp->port, pOld->fqdn, pOld->port); + pParam->pMqVg->epSet = *pBuf->pEpSet; + } + taosMemoryFree(pParam->pOffset); taosMemoryFree(pBuf->pData); taosMemoryFree(pBuf->pEpSet); @@ -451,7 +458,6 @@ int32_t tmqCommitCb(void* param, SDataBuf* pBuf, int32_t code) { * pOffset->version);*/ tmqCommitRspCountDown(pParamSet); - return 0; } @@ -461,6 +467,7 @@ static int32_t tmqSendCommitReq(tmq_t* tmq, SMqClientVg* pVg, SMqClientTopic* pT terrno = TSDB_CODE_OUT_OF_MEMORY; return -1; } + pOffset->val = pVg->currentOffset; int32_t groupLen = strlen(tmq->groupId); @@ -474,11 +481,13 @@ static int32_t tmqSendCommitReq(tmq_t* tmq, SMqClientVg* pVg, SMqClientTopic* pT if (code < 0) { return -1; } + void* buf = taosMemoryCalloc(1, sizeof(SMsgHead) + len); if (buf == NULL) { taosMemoryFree(pOffset); return -1; } + ((SMsgHead*)buf)->vgId = htonl(pVg->vgId); void* abuf = POINTER_SHIFT(buf, sizeof(SMsgHead)); @@ -495,8 +504,10 @@ static int32_t tmqSendCommitReq(tmq_t* tmq, SMqClientVg* pVg, SMqClientTopic* pT taosMemoryFree(buf); return -1; } + pParam->params = pParamSet; pParam->pOffset = pOffset; + pParam->pMqVg = pVg; // there may be an race condition // build send info SMsgSendInfo* pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo)); @@ -506,16 +517,18 @@ static int32_t tmqSendCommitReq(tmq_t* tmq, SMqClientVg* pVg, SMqClientTopic* pT taosMemoryFree(pParam); return -1; } + pMsgSendInfo->msgInfo = (SDataBuf){ .pData = buf, .len = sizeof(SMsgHead) + len, .handle = NULL, }; - tscDebug("consumer:0x%" PRIx64 " topic:%s on vgId:%d offset:%" PRId64, tmq->consumerId, pOffset->subKey, pVg->vgId, - pOffset->val.version); + SEp* pEp = &pVg->epSet.eps[pVg->epSet.inUse]; + tscDebug("consumer:0x%" PRIx64 " topic:%s on vgId:%d offset:%" PRId64 " prev:%" PRId64 ", ep:%s:%d", tmq->consumerId, + pOffset->subKey, pVg->vgId, pOffset->val.version, pVg->committedOffset.version, pEp->fqdn, pEp->port); - // TODO: put into cb + // TODO: put into cb, the commit offset should be move to the callback function pVg->committedOffset = pVg->currentOffset; pMsgSendInfo->requestId = generateRequestId(); @@ -639,15 +652,16 @@ static int32_t tmqCommitConsumerImpl(tmq_t* tmq, int8_t automatic, int8_t async, // init as 1 to prevent concurrency issue pParamSet->waitingRspNum = 1; - for (int32_t i = 0; i < taosArrayGetSize(tmq->clientTopics); i++) { + int32_t numOfTopics = taosArrayGetSize(tmq->clientTopics); + tscDebug("consumer:0x%" PRIx64 " start to commit offset for %d topics", tmq->consumerId, numOfTopics); + + for (int32_t i = 0; i < numOfTopics; i++) { SMqClientTopic* pTopic = taosArrayGet(tmq->clientTopics, i); int32_t numOfVgroups = taosArrayGetSize(pTopic->vgs); for (int32_t j = 0; j < numOfVgroups; j++) { SMqClientVg* pVg = taosArrayGet(pTopic->vgs, j); if (pVg->currentOffset.type > 0 && !tOffsetEqual(&pVg->currentOffset, &pVg->committedOffset)) { - tscDebug("consumer:0x%" PRIx64 " topic:%s vgId:%d, current %" PRId64 ", committed %" PRId64, tmq->consumerId, - pTopic->topicName, pVg->vgId, pVg->currentOffset.version, pVg->committedOffset.version); if (tmqSendCommitReq(tmq, pVg, pTopic, pParamSet) < 0) { continue; } @@ -809,7 +823,7 @@ int32_t tmqHandleAllDelayedTask(tmq_t* pTmq) { int64_t* pRefId = taosMemoryMalloc(sizeof(int64_t)); *pRefId = pTmq->refId; - tscDebug("consumer:0x%" PRIx64 " next retrieve ep from mnode in 1s", pTmq->consumerId); + tscDebug("consumer:0x%" PRIx64 " retrieve ep from mnode in 1s", pTmq->consumerId); taosTmrReset(tmqAssignAskEpTask, 1000, pRefId, tmqMgmt.timer, &pTmq->epTimer); } else if (*pTaskType == TMQ_DELAYED_TASK__COMMIT) { tmqCommitInner(pTmq, NULL, 1, 1, pTmq->commitCb, pTmq->commitCbUserParam); @@ -817,7 +831,7 @@ int32_t tmqHandleAllDelayedTask(tmq_t* pTmq) { int64_t* pRefId = taosMemoryMalloc(sizeof(int64_t)); *pRefId = pTmq->refId; - tscDebug("consumer:0x%" PRIx64 " next commit to mnode in %.2fs", pTmq->consumerId, + tscDebug("consumer:0x%" PRIx64 " commit to vnode(s) in %.2fs", pTmq->consumerId, pTmq->autoCommitInterval / 1000.0); taosTmrReset(tmqAssignDelayedCommitTask, pTmq->autoCommitInterval, pRefId, tmqMgmt.timer, &pTmq->commitTimer); } else if (*pTaskType == TMQ_DELAYED_TASK__REPORT) { @@ -981,7 +995,8 @@ tmq_t* tmq_consumer_new(tmq_conf_t* conf, char* errstr, int32_t errstrLen) { pTmq->qall = taosAllocateQall(); pTmq->delayedTask = taosOpenQueue(); - if (pTmq->clientTopics == NULL || pTmq->mqueue == NULL || pTmq->qall == NULL || pTmq->delayedTask == NULL) { + if (pTmq->clientTopics == NULL || pTmq->mqueue == NULL || pTmq->qall == NULL || pTmq->delayedTask == NULL || + conf->groupId[0] == 0) { terrno = TSDB_CODE_OUT_OF_MEMORY; tscError("consumer:0x%" PRIx64 " setup failed since %s, consumer group %s", pTmq->consumerId, terrstr(), pTmq->groupId); @@ -1060,7 +1075,7 @@ int32_t tmq_subscribe(tmq_t* tmq, const tmq_list_t* topic_list) { SCMSubscribeReq req = {0}; int32_t code = 0; - tscDebug("consumer:0x%" PRIx64 " tmq subscribe start, numOfTopic %d", tmq->consumerId, sz); + tscDebug("consumer:0x%" PRIx64 " subscribe %d topics", tmq->consumerId, sz); req.consumerId = tmq->consumerId; tstrncpy(req.clientId, tmq->clientId, 256); @@ -1083,7 +1098,7 @@ int32_t tmq_subscribe(tmq_t* tmq, const tmq_list_t* topic_list) { } tNameExtractFullName(&name, topicFName); - tscDebug("consumer:0x%" PRIx64 ", subscribe topic: %s", tmq->consumerId, topicFName); + tscDebug("consumer:0x%" PRIx64 " subscribe topic:%s", tmq->consumerId, topicFName); taosArrayPush(req.topicNames, &topicFName); } @@ -1394,7 +1409,7 @@ bool tmqUpdateEp(tmq_t* tmq, int32_t epoch, const SMqAskEpRsp* pRsp) { } atomic_store_32(&tmq->epoch, epoch); - tscDebug("consumer:0x%" PRIx64 ", update topic info completed", tmq->consumerId); + tscDebug("consumer:0x%" PRIx64 " update topic info completed", tmq->consumerId); return set; } @@ -1544,7 +1559,8 @@ int32_t tmqAskEp(tmq_t* tmq, bool async) { sendInfo->msgType = TDMT_MND_TMQ_ASK_EP; SEpSet epSet = getEpSet_s(&tmq->pTscObj->pAppInfo->mgmtEp); - tscDebug("consumer:0x%" PRIx64 " ask ep from mnode, async:%d", tmq->consumerId, async); + tscDebug("consumer:0x%" PRIx64 " ask ep from mnode, async:%d, reqId:0x%" PRIx64, tmq->consumerId, async, + tmq->consumerId); int64_t transporterId = 0; asyncSendMsgToServer(tmq->pTscObj->pAppInfo->pTransporter, &epSet, &transporterId, sendInfo); @@ -1559,25 +1575,20 @@ int32_t tmqAskEp(tmq_t* tmq, bool async) { } void tmqBuildConsumeReqImpl(SMqPollReq* pReq, tmq_t* tmq, int64_t timeout, SMqClientTopic* pTopic, SMqClientVg* pVg) { - /*strcpy(pReq->topic, pTopic->topicName);*/ - /*strcpy(pReq->cgroup, tmq->groupId);*/ - int32_t groupLen = strlen(tmq->groupId); memcpy(pReq->subKey, tmq->groupId, groupLen); pReq->subKey[groupLen] = TMQ_SEPARATOR; strcpy(pReq->subKey + groupLen + 1, pTopic->topicName); pReq->withTbName = tmq->withTbName; - pReq->timeout = timeout; pReq->consumerId = tmq->consumerId; + pReq->timeout = timeout; pReq->epoch = tmq->epoch; /*pReq->currentOffset = reqOffset;*/ pReq->reqOffset = pVg->currentOffset; - pReq->reqId = generateRequestId(); - - pReq->useSnapshot = tmq->useSnapshot; - pReq->head.vgId = pVg->vgId; + pReq->useSnapshot = tmq->useSnapshot; + pReq->reqId = generateRequestId(); } SMqMetaRspObj* tmqBuildMetaRspFromWrapper(SMqPollRspWrapper* pWrapper) { @@ -1627,6 +1638,76 @@ SMqTaosxRspObj* tmqBuildTaosxRspFromWrapper(SMqPollRspWrapper* pWrapper) { return pRspObj; } +static int32_t handleErrorBeforePoll(SMqClientVg* pVg, tmq_t* pTmq) { + atomic_store_32(&pVg->vgStatus, TMQ_VG_STATUS__IDLE); + tsem_post(&pTmq->rspSem); + return -1; +} + +static int32_t doTmqPollImpl(tmq_t* pTmq, SMqClientTopic* pTopic, SMqClientVg* pVg, int64_t timeout) { + SMqPollReq req = {0}; + tmqBuildConsumeReqImpl(&req, pTmq, timeout, pTopic, pVg); + + int32_t msgSize = tSerializeSMqPollReq(NULL, 0, &req); + if (msgSize < 0) { + return handleErrorBeforePoll(pVg, pTmq); + } + + char* msg = taosMemoryCalloc(1, msgSize); + if (NULL == msg) { + return handleErrorBeforePoll(pVg, pTmq); + } + + if (tSerializeSMqPollReq(msg, msgSize, &req) < 0) { + taosMemoryFree(msg); + return handleErrorBeforePoll(pVg, pTmq); + } + + SMqPollCbParam* pParam = taosMemoryMalloc(sizeof(SMqPollCbParam)); + if (pParam == NULL) { + taosMemoryFree(msg); + return handleErrorBeforePoll(pVg, pTmq); + } + + pParam->refId = pTmq->refId; + pParam->epoch = pTmq->epoch; + pParam->pVg = pVg; // pVg may be released,fix it + pParam->pTopic = pTopic; + pParam->vgId = pVg->vgId; + + SMsgSendInfo* sendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo)); + if (sendInfo == NULL) { + taosMemoryFree(pParam); + taosMemoryFree(msg); + return handleErrorBeforePoll(pVg, pTmq); + } + + sendInfo->msgInfo = (SDataBuf){ + .pData = msg, + .len = msgSize, + .handle = NULL, + }; + + sendInfo->requestId = req.reqId; + sendInfo->requestObjRefId = 0; + sendInfo->param = pParam; + sendInfo->fp = tmqPollCb; + sendInfo->msgType = TDMT_VND_TMQ_CONSUME; + + int64_t transporterId = 0; + char offsetFormatBuf[80]; + tFormatOffset(offsetFormatBuf, tListLen(offsetFormatBuf), &pVg->currentOffset); + + tscDebug("consumer:0x%" PRIx64 " send poll to %s vgId:%d, epoch %d, req offset:%s, reqId:0x%" PRIx64, + pTmq->consumerId, pTopic->topicName, pVg->vgId, pTmq->epoch, offsetFormatBuf, req.reqId); + asyncSendMsgToServer(pTmq->pTscObj->pAppInfo->pTransporter, &pVg->epSet, &transporterId, sendInfo); + + pVg->pollCnt++; + pTmq->pollCnt++; + + return TSDB_CODE_SUCCESS; +} + // broadcast the poll request to all related vnodes int32_t tmqPollImpl(tmq_t* tmq, int64_t timeout) { int32_t numOfTopics = taosArrayGetSize(tmq->clientTopics); @@ -1634,7 +1715,9 @@ int32_t tmqPollImpl(tmq_t* tmq, int64_t timeout) { for (int i = 0; i < numOfTopics; i++) { SMqClientTopic* pTopic = taosArrayGet(tmq->clientTopics, i); - for (int j = 0; j < taosArrayGetSize(pTopic->vgs); j++) { + int32_t numOfVg = taosArrayGetSize(pTopic->vgs); + + for (int j = 0; j < numOfVg; j++) { SMqClientVg* pVg = taosArrayGet(pTopic->vgs, j); int32_t vgStatus = atomic_val_compare_exchange_32(&pVg->vgStatus, TMQ_VG_STATUS__IDLE, TMQ_VG_STATUS__WAIT); if (vgStatus == TMQ_VG_STATUS__WAIT) { @@ -1653,77 +1736,10 @@ int32_t tmqPollImpl(tmq_t* tmq, int64_t timeout) { } atomic_store_32(&pVg->vgSkipCnt, 0); - - SMqPollReq req = {0}; - tmqBuildConsumeReqImpl(&req, tmq, timeout, pTopic, pVg); - int32_t msgSize = tSerializeSMqPollReq(NULL, 0, &req); - if (msgSize < 0) { - atomic_store_32(&pVg->vgStatus, TMQ_VG_STATUS__IDLE); - tsem_post(&tmq->rspSem); - return -1; + int32_t code = doTmqPollImpl(tmq, pTopic, pVg, timeout); + if (code != TSDB_CODE_SUCCESS) { + return code; } - - char* msg = taosMemoryCalloc(1, msgSize); - if (NULL == msg) { - atomic_store_32(&pVg->vgStatus, TMQ_VG_STATUS__IDLE); - tsem_post(&tmq->rspSem); - return -1; - } - - if (tSerializeSMqPollReq(msg, msgSize, &req) < 0) { - taosMemoryFree(msg); - atomic_store_32(&pVg->vgStatus, TMQ_VG_STATUS__IDLE); - tsem_post(&tmq->rspSem); - return -1; - } - - SMqPollCbParam* pParam = taosMemoryMalloc(sizeof(SMqPollCbParam)); - if (pParam == NULL) { - taosMemoryFree(msg); - atomic_store_32(&pVg->vgStatus, TMQ_VG_STATUS__IDLE); - tsem_post(&tmq->rspSem); - return -1; - } - - pParam->refId = tmq->refId; - pParam->epoch = tmq->epoch; - - pParam->pVg = pVg; - pParam->pTopic = pTopic; - pParam->vgId = pVg->vgId; - - SMsgSendInfo* sendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo)); - if (sendInfo == NULL) { - taosMemoryFree(msg); - taosMemoryFree(pParam); - atomic_store_32(&pVg->vgStatus, TMQ_VG_STATUS__IDLE); - tsem_post(&tmq->rspSem); - return -1; - } - - sendInfo->msgInfo = (SDataBuf){ - .pData = msg, - .len = msgSize, - .handle = NULL, - }; - - sendInfo->requestId = req.reqId; - sendInfo->requestObjRefId = 0; - sendInfo->param = pParam; - sendInfo->fp = tmqPollCb; - sendInfo->msgType = TDMT_VND_TMQ_CONSUME; - - int64_t transporterId = 0; - - char offsetFormatBuf[80]; - tFormatOffset(offsetFormatBuf, 80, &pVg->currentOffset); - - tscDebug("consumer:0x%" PRIx64 ", send poll to %s vgId:%d, epoch %d, req offset:%s, reqId:0x%" PRIx64, - tmq->consumerId, pTopic->topicName, pVg->vgId, tmq->epoch, offsetFormatBuf, req.reqId); - asyncSendMsgToServer(tmq->pTscObj->pAppInfo->pTransporter, &pVg->epSet, &transporterId, sendInfo); - - pVg->pollCnt++; - tmq->pollCnt++; } } @@ -1751,28 +1767,28 @@ int32_t tmqHandleNoPollRsp(tmq_t* tmq, SMqRspWrapper* rspWrapper, bool* pReset) } void* tmqHandleAllRsp(tmq_t* tmq, int64_t timeout, bool pollIfReset) { + tscDebug("consumer:0x%" PRIx64 " start to handle the rsp", tmq->consumerId); + while (1) { SMqRspWrapper* rspWrapper = NULL; taosGetQitem(tmq->qall, (void**)&rspWrapper); + if (rspWrapper == NULL) { taosReadAllQitems(tmq->mqueue, tmq->qall); taosGetQitem(tmq->qall, (void**)&rspWrapper); if (rspWrapper == NULL) { - /*tscDebug("consumer %" PRId64 " mqueue empty", tmq->consumerId);*/ return NULL; } } - tscDebug("consumer:0x%" PRIx64 " handle rsp %p", tmq->consumerId, rspWrapper); - if (rspWrapper->tmqRspType == TMQ_MSG_TYPE__END_RSP) { taosFreeQitem(rspWrapper); terrno = TSDB_CODE_TQ_NO_COMMITTED_OFFSET; return NULL; } else if (rspWrapper->tmqRspType == TMQ_MSG_TYPE__POLL_RSP) { SMqPollRspWrapper* pollRspWrapper = (SMqPollRspWrapper*)rspWrapper; - tscDebug("consumer:0x%" PRIx64 " actual process poll rsp", tmq->consumerId); + tscDebug("consumer:0x%" PRIx64 " process poll rsp", tmq->consumerId); /*atomic_sub_fetch_32(&tmq->readyRequest, 1);*/ int32_t consumerEpoch = atomic_load_32(&tmq->epoch); if (pollRspWrapper->dataRsp.head.epoch == consumerEpoch) { @@ -1799,6 +1815,9 @@ void* tmqHandleAllRsp(tmq_t* tmq, int64_t timeout, bool pollIfReset) { } else if (rspWrapper->tmqRspType == TMQ_MSG_TYPE__POLL_META_RSP) { SMqPollRspWrapper* pollRspWrapper = (SMqPollRspWrapper*)rspWrapper; int32_t consumerEpoch = atomic_load_32(&tmq->epoch); + + tscDebug("consumer:0x%" PRIx64 " process meta rsp", tmq->consumerId); + if (pollRspWrapper->metaRsp.head.epoch == consumerEpoch) { SMqClientVg* pVg = pollRspWrapper->vgHandle; /*printf("vgId:%d, offset %" PRId64 " up to %" PRId64 "\n", pVg->vgId, pVg->currentOffset, @@ -1863,7 +1882,7 @@ TAOS_RES* tmq_consumer_poll(tmq_t* tmq, int64_t timeout) { void* rspObj; int64_t startTime = taosGetTimestampMs(); - tscDebug("consumer:0x%" PRIx64 ", start poll at %" PRId64, tmq->consumerId, startTime); + tscDebug("consumer:0x%" PRIx64 " start to poll at %" PRId64, tmq->consumerId, startTime); #if 0 tmqHandleAllDelayedTask(tmq); @@ -1876,7 +1895,7 @@ TAOS_RES* tmq_consumer_poll(tmq_t* tmq, int64_t timeout) { // in no topic status, delayed task also need to be processed if (atomic_load_8(&tmq->status) == TMQ_CONSUMER_STATUS__INIT) { - tscDebug("consumer:0x%" PRIx64 ", poll return since consumer status is init", tmq->consumerId); + tscDebug("consumer:0x%" PRIx64 " poll return since consumer is init", tmq->consumerId); return NULL; } @@ -1902,25 +1921,25 @@ TAOS_RES* tmq_consumer_poll(tmq_t* tmq, int64_t timeout) { rspObj = tmqHandleAllRsp(tmq, timeout, false); if (rspObj) { - tscDebug("consumer:0x%" PRIx64 ", return rsp %p", tmq->consumerId, rspObj); + tscDebug("consumer:0x%" PRIx64 " return rsp %p", tmq->consumerId, rspObj); return (TAOS_RES*)rspObj; } else if (terrno == TSDB_CODE_TQ_NO_COMMITTED_OFFSET) { - tscDebug("consumer:0x%" PRIx64 ", return null since no committed offset", tmq->consumerId); + tscDebug("consumer:0x%" PRIx64 " return null since no committed offset", tmq->consumerId); return NULL; } if (timeout != -1) { int64_t currentTime = taosGetTimestampMs(); - int64_t passedTime = currentTime - startTime; - if (passedTime > timeout) { - tscDebug("consumer:0x%" PRIx64 ", (epoch %d) timeout, no rsp, start time %" PRId64 ", current time %" PRId64, + int64_t elapsedTime = currentTime - startTime; + if (elapsedTime > timeout) { + tscDebug("consumer:0x%" PRIx64 " (epoch %d) timeout, no rsp, start time %" PRId64 ", current time %" PRId64, tmq->consumerId, tmq->epoch, startTime, currentTime); return NULL; } /*tscInfo("consumer:0x%" PRIx64 ", (epoch %d) wait, start time %" PRId64 ", current time %" PRId64*/ /*", left time %" PRId64,*/ - /*tmq->consumerId, tmq->epoch, startTime, currentTime, (timeout - passedTime));*/ - tsem_timewait(&tmq->rspSem, (timeout - passedTime)); + /*tmq->consumerId, tmq->epoch, startTime, currentTime, (timeout - elapsedTime));*/ + tsem_timewait(&tmq->rspSem, (timeout - elapsedTime)); } else { // use tsem_timewait instead of tsem_wait to avoid unexpected stuck tsem_timewait(&tmq->rspSem, 1000); diff --git a/source/client/test/clientTests.cpp b/source/client/test/clientTests.cpp index cb3c2f8c68..59c931d9aa 100644 --- a/source/client/test/clientTests.cpp +++ b/source/client/test/clientTests.cpp @@ -912,7 +912,7 @@ TEST(clientCase, subscription_test) { tmq_conf_t* conf = tmq_conf_new(); tmq_conf_set(conf, "enable.auto.commit", "true"); tmq_conf_set(conf, "auto.commit.interval.ms", "1000"); - tmq_conf_set(conf, "group.id", "newabcdefgjhijlm__"); + tmq_conf_set(conf, "group.id", "cgrpName"); tmq_conf_set(conf, "td.connect.user", "root"); tmq_conf_set(conf, "td.connect.pass", "taosdata"); tmq_conf_set(conf, "auto.offset.reset", "earliest"); diff --git a/source/common/src/tdatablock.c b/source/common/src/tdatablock.c index e866203372..88eb3bdb97 100644 --- a/source/common/src/tdatablock.c +++ b/source/common/src/tdatablock.c @@ -64,13 +64,17 @@ int32_t getJsonValueLen(const char* data) { return dataLen; } -int32_t colDataAppend(SColumnInfoData* pColumnInfoData, uint32_t currentRow, const char* pData, bool isNull) { +int32_t colDataAppend(SColumnInfoData* pColumnInfoData, uint32_t rowIndex, const char* pData, bool isNull) { + return colDataSetVal(pColumnInfoData, rowIndex, pData, isNull); +} + +int32_t colDataSetVal(SColumnInfoData* pColumnInfoData, uint32_t rowIndex, const char* pData, bool isNull) { if (isNull) { // There is a placehold for each NULL value of binary or nchar type. if (IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) { - pColumnInfoData->varmeta.offset[currentRow] = -1; // it is a null value of VAR type. + pColumnInfoData->varmeta.offset[rowIndex] = -1; // it is a null value of VAR type. } else { - colDataSetNull_f_s(pColumnInfoData, currentRow); + colDataSetNull_f_s(pColumnInfoData, rowIndex); } pColumnInfoData->hasNull = true; @@ -95,6 +99,9 @@ int32_t colDataAppend(SColumnInfoData* pColumnInfoData, uint32_t currentRow, con while (newSize < pAttr->length + dataLen) { newSize = newSize * 1.5; + if (newSize > UINT32_MAX) { + return TSDB_CODE_OUT_OF_MEMORY; + } } char* buf = taosMemoryRealloc(pColumnInfoData->pData, newSize); @@ -107,12 +114,12 @@ int32_t colDataAppend(SColumnInfoData* pColumnInfoData, uint32_t currentRow, con } uint32_t len = pColumnInfoData->varmeta.length; - pColumnInfoData->varmeta.offset[currentRow] = len; + pColumnInfoData->varmeta.offset[rowIndex] = len; memmove(pColumnInfoData->pData + len, pData, dataLen); pColumnInfoData->varmeta.length += dataLen; } else { - memcpy(pColumnInfoData->pData + pColumnInfoData->info.bytes * currentRow, pData, pColumnInfoData->info.bytes); + memcpy(pColumnInfoData->pData + pColumnInfoData->info.bytes * rowIndex, pData, pColumnInfoData->info.bytes); } return 0; @@ -173,7 +180,7 @@ static void doCopyNItems(struct SColumnInfoData* pColumnInfoData, int32_t curren } } -int32_t colDataAppendNItems(SColumnInfoData* pColumnInfoData, uint32_t currentRow, const char* pData, +int32_t colDataSetNItems(SColumnInfoData* pColumnInfoData, uint32_t currentRow, const char* pData, uint32_t numOfRows) { int32_t len = pColumnInfoData->info.bytes; if (IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) { @@ -513,10 +520,10 @@ SSDataBlock* blockDataExtractBlock(SSDataBlock* pBlock, int32_t startIndex, int3 } if (isNull) { - colDataAppendNULL(pDstCol, j - startIndex); + colDataSetNULL(pDstCol, j - startIndex); } else { char* p = colDataGetData(pColData, j); - colDataAppend(pDstCol, j - startIndex, p, false); + colDataSetVal(pDstCol, j - startIndex, p, false); } } } @@ -619,6 +626,33 @@ int32_t blockDataFromBuf(SSDataBlock* pBlock, const char* buf) { return TSDB_CODE_SUCCESS; } +static bool colDataIsNNull(const SColumnInfoData* pColumnInfoData, int32_t startIndex, + uint32_t nRows) { + if (!pColumnInfoData->hasNull) { + return false; + } + + if (IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) { + for (int32_t i = startIndex; i < nRows; ++i) { + if (!colDataIsNull_var(pColumnInfoData, i)) { + return false; + } + } + } else { + if (pColumnInfoData->nullbitmap == NULL) { + return false; + } + + for (int32_t i = startIndex; i < nRows; ++i) { + if (!colDataIsNull_f(pColumnInfoData->nullbitmap, i)) { + return false; + } + } + } + + return true; +} + // todo remove this int32_t blockDataFromBuf1(SSDataBlock* pBlock, const char* buf, size_t capacity) { pBlock->info.rows = *(int32_t*)buf; @@ -661,7 +695,7 @@ int32_t blockDataFromBuf1(SSDataBlock* pBlock, const char* buf, size_t capacity) } } - if (!colDataIsNNull_s(pCol, 0, pBlock->info.rows)) { + if (!colDataIsNNull(pCol, 0, pBlock->info.rows)) { memcpy(pCol->pData, pStart, colLength); } @@ -783,13 +817,13 @@ static int32_t doAssignOneTuple(SColumnInfoData* pDstCols, int32_t numOfRows, co SColumnInfoData* pSrc = taosArrayGet(pSrcBlock->pDataBlock, i); if (pSrc->hasNull && colDataIsNull(pSrc, pSrcBlock->info.rows, tupleIndex, pSrcBlock->pBlockAgg[i])) { - code = colDataAppend(pDst, numOfRows, NULL, true); + code = colDataSetVal(pDst, numOfRows, NULL, true); if (code != TSDB_CODE_SUCCESS) { return code; } } else { char* p = colDataGetData(pSrc, tupleIndex); - code = colDataAppend(pDst, numOfRows, p, false); + code = colDataSetVal(pDst, numOfRows, p, false); if (code != TSDB_CODE_SUCCESS) { return code; } @@ -1033,6 +1067,7 @@ SHelper* createTupleIndex_rv(int32_t numOfRows, SArray* pOrderInfo, SSDataBlock* offset += pInfo->pColData->info.bytes; } + taosMemoryFree(buf); return phelper; } @@ -1413,7 +1448,7 @@ SSDataBlock* blockCopyOneRow(const SSDataBlock* pDataBlock, int32_t rowIdx) { SColumnInfoData* pSrc = taosArrayGet(pDataBlock->pDataBlock, i); void* pData = colDataGetData(pSrc, rowIdx); bool isNull = colDataIsNull(pSrc, pDataBlock->info.rows, rowIdx, NULL); - colDataAppend(pDst, 0, pData, isNull); + colDataSetVal(pDst, 0, pData, isNull); } pBlock->info.rows = 1; @@ -1644,7 +1679,7 @@ static void colDataTrimFirstNRows(SColumnInfoData* pColInfoData, size_t n, size_ } } -int32_t blockDataTrimFirstNRows(SSDataBlock* pBlock, size_t n) { +int32_t blockDataTrimFirstRows(SSDataBlock* pBlock, size_t n) { if (n == 0) { return TSDB_CODE_SUCCESS; } @@ -2370,7 +2405,11 @@ _end: taosArrayDestroy(pVals); if (terrno != 0) { *ppReq = NULL; - if (pReq) tDestroySSubmitReq2(pReq, TSDB_MSG_FLG_ENCODE); + if (pReq) { + tDestroySSubmitReq2(pReq, TSDB_MSG_FLG_ENCODE); + taosMemoryFreeClear(pReq); + } + return TSDB_CODE_FAILED; } *ppReq = pReq; @@ -2528,7 +2567,7 @@ const char* blockDecode(SSDataBlock* pBlock, const char* pData) { pStart += sizeof(uint64_t); if (pBlock->pDataBlock == NULL) { - pBlock->pDataBlock = taosArrayInit_s(numOfCols, sizeof(SColumnInfoData), numOfCols); + pBlock->pDataBlock = taosArrayInit_s(sizeof(SColumnInfoData), numOfCols); } for (int32_t i = 0; i < numOfCols; ++i) { diff --git a/source/common/src/tdataformat.c b/source/common/src/tdataformat.c index 7c0de3d6f0..2bb8708372 100644 --- a/source/common/src/tdataformat.c +++ b/source/common/src/tdataformat.c @@ -139,7 +139,10 @@ int32_t tRowBuild(SArray *aColVal, const STSchema *pTSchema, SRow **ppRow) { nkv += tPutI16v(NULL, -pTColumn->colId); nIdx++; } else { - ASSERT(0); + if (ASSERTS(0, "invalid input")) { + code = TSDB_CODE_INVALID_PARA; + goto _exit; + } } pTColumn = (++iTColumn < pTSchema->numOfCols) ? pTSchema->columns + iTColumn : NULL; @@ -176,8 +179,10 @@ int32_t tRowBuild(SArray *aColVal, const STSchema *pTSchema, SRow **ppRow) { ntp = sizeof(SRow) + BIT2_SIZE(pTSchema->numOfCols - 1) + pTSchema->flen + ntp; break; default: - ASSERT(0); - break; + if (ASSERTS(0, "impossible")) { + code = TSDB_CODE_INVALID_PARA; + goto _exit; + } } if (maxIdx <= UINT8_MAX) { nkv = sizeof(SRow) + sizeof(SKVIdx) + nIdx + nkv; @@ -306,8 +311,10 @@ int32_t tRowBuild(SArray *aColVal, const STSchema *pTSchema, SRow **ppRow) { pv = pf + pTSchema->flen; break; default: - ASSERT(0); - break; + if (ASSERTS(0, "impossible")) { + code = TSDB_CODE_INVALID_PARA; + goto _exit; + } } if (pb) { @@ -370,7 +377,7 @@ _exit: return code; } -void tRowGet(SRow *pRow, STSchema *pTSchema, int32_t iCol, SColVal *pColVal) { +int32_t tRowGet(SRow *pRow, STSchema *pTSchema, int32_t iCol, SColVal *pColVal) { ASSERT(iCol < pTSchema->numOfCols); ASSERT(pRow->sver == pTSchema->version); @@ -381,17 +388,17 @@ void tRowGet(SRow *pRow, STSchema *pTSchema, int32_t iCol, SColVal *pColVal) { pColVal->type = pTColumn->type; pColVal->flag = CV_FLAG_VALUE; memcpy(&pColVal->value.val, &pRow->ts, sizeof(TSKEY)); - return; + return 0; } if (pRow->flag == HAS_NONE) { *pColVal = COL_VAL_NONE(pTColumn->colId, pTColumn->type); - return; + return 0; } if (pRow->flag == HAS_NULL) { *pColVal = COL_VAL_NULL(pTColumn->colId, pTColumn->type); - return; + return 0; } if (pRow->flag >> 4) { // KV Row @@ -440,7 +447,7 @@ void tRowGet(SRow *pRow, STSchema *pTSchema, int32_t iCol, SColVal *pColVal) { memcpy(&pColVal->value.val, pData, pTColumn->bytes); } } - return; + return 0; } else if (TABS(cid) < pTColumn->colId) { lidx = mid + 1; } else { @@ -492,16 +499,16 @@ void tRowGet(SRow *pRow, STSchema *pTSchema, int32_t iCol, SColVal *pColVal) { pv = pf + pTSchema->flen; break; default: - ASSERT(0); - break; + ASSERTS(0, "invalid row format"); + return TSDB_CODE_IVLD_DATA_FMT; } if (bv == BIT_FLG_NONE) { *pColVal = COL_VAL_NONE(pTColumn->colId, pTColumn->type); - return; + return 0; } else if (bv == BIT_FLG_NULL) { *pColVal = COL_VAL_NULL(pTColumn->colId, pTColumn->type); - return; + return 0; } pColVal->cid = pTColumn->colId; @@ -520,6 +527,8 @@ void tRowGet(SRow *pRow, STSchema *pTSchema, int32_t iCol, SColVal *pColVal) { } } } + + return 0; } void tRowDestroy(SRow *pRow) { @@ -710,7 +719,6 @@ int32_t tRowIterOpen(SRow *pRow, STSchema *pTSchema, SRowIter **ppIter) { _exit: if (code) { *ppIter = NULL; - if (pIter) taosMemoryFree(pIter); } else { *ppIter = pIter; } @@ -929,8 +937,8 @@ static int32_t tRowTupleUpsertColData(SRow *pRow, STSchema *pTSchema, SColData * pv = pf + pTSchema->flen; break; default: - ASSERT(0); - break; + ASSERTS(0, "Invalid row flag"); + return TSDB_CODE_IVLD_DATA_FMT; } while (pColData) { @@ -954,8 +962,8 @@ static int32_t tRowTupleUpsertColData(SRow *pRow, STSchema *pTSchema, SColData * bv = GET_BIT2(pb, iTColumn - 1); break; default: - ASSERT(0); - break; + ASSERTS(0, "Invalid row flag"); + return TSDB_CODE_IVLD_DATA_FMT; } if (bv == BIT_FLG_NONE) { @@ -1045,7 +1053,8 @@ static int32_t tRowKVUpsertColData(SRow *pRow, STSchema *pTSchema, SColData *aCo } else if (pRow->flag & KV_FLG_BIG) { pData = pv + ((uint32_t *)pKVIdx->idx)[iCol]; } else { - ASSERT(0); + ASSERTS(0, "Invalid KV row format"); + return TSDB_CODE_IVLD_DATA_FMT; } int16_t cid; @@ -1579,7 +1588,7 @@ static FORCE_INLINE int32_t tColDataPutValue(SColData *pColData, uint8_t *pData, int32_t code = 0; if (IS_VAR_DATA_TYPE(pColData->type)) { - code = tRealloc((uint8_t **)(&pColData->aOffset), (pColData->nVal + 1) << 2); + code = tRealloc((uint8_t **)(&pColData->aOffset), ((int64_t)(pColData->nVal + 1)) << 2); if (code) goto _exit; pColData->aOffset[pColData->nVal] = pColData->nData; @@ -1980,8 +1989,7 @@ static FORCE_INLINE int32_t tColDataUpdateValue20(SColData *pColData, uint8_t *p return 0; } static FORCE_INLINE int32_t tColDataUpdateValue30(SColData *pColData, uint8_t *pData, uint32_t nData, bool forward) { - uint8_t bv = GET_BIT1(pColData->pBitMap, pColData->nVal - 1); - if (bv == 0) { // NONE == > VALUE + if (GET_BIT1(pColData->pBitMap, pColData->nVal - 1) == 0) { // NONE ==> VALUE pColData->numOfNone--; pColData->nVal--; if (pColData->numOfNone) { @@ -1990,7 +1998,7 @@ static FORCE_INLINE int32_t tColDataUpdateValue30(SColData *pColData, uint8_t *p pColData->flag = HAS_NULL; return tColDataAppendValue20(pColData, pData, nData); } - } else if (forward) { // NULL == > VALUE + } else if (forward) { // NULL ==> VALUE pColData->numOfNull--; pColData->nVal--; if (pColData->numOfNull) { @@ -2015,36 +2023,43 @@ static FORCE_INLINE int32_t tColDataUpdateValue32(SColData *pColData, uint8_t *p return 0; } static FORCE_INLINE int32_t tColDataUpdateValue40(SColData *pColData, uint8_t *pData, uint32_t nData, bool forward) { - if (forward) { - pColData->numOfValue--; + if (forward) { // VALUE ==> VALUE pColData->nVal--; - if (pColData->numOfValue) { - return tColDataAppendValue40(pColData, pData, nData); + if (IS_VAR_DATA_TYPE(pColData->type)) { + pColData->nData = pColData->aOffset[pColData->nVal]; } else { - pColData->flag = 0; - return tColDataAppendValue00(pColData, pData, nData); + pColData->nData -= TYPE_BYTES[pColData->type]; } + return tColDataPutValue(pColData, pData, nData); } return 0; } static FORCE_INLINE int32_t tColDataUpdateValue42(SColData *pColData, uint8_t *pData, uint32_t nData, bool forward) { - if (forward) { + if (forward) { // VALUE ==> NULL pColData->numOfValue--; pColData->nVal--; if (pColData->numOfValue) { + if (IS_VAR_DATA_TYPE(pColData->type)) { + pColData->nData = pColData->aOffset[pColData->nVal]; + } else { + pColData->nData -= TYPE_BYTES[pColData->type]; + } return tColDataAppendValue42(pColData, pData, nData); } else { pColData->flag = 0; + pColData->nData = 0; return tColDataAppendValue02(pColData, pData, nData); } } return 0; } static FORCE_INLINE int32_t tColDataUpdateValue50(SColData *pColData, uint8_t *pData, uint32_t nData, bool forward) { - uint8_t bv = GET_BIT1(pColData->pBitMap, pColData->nVal - 1); - if (bv == 0) { // NONE ==> VALUE + if (GET_BIT1(pColData->pBitMap, pColData->nVal - 1) == 0) { // NONE ==> VALUE pColData->numOfNone--; pColData->nVal--; + if (!IS_VAR_DATA_TYPE(pColData->type)) { + pColData->nData -= TYPE_BYTES[pColData->type]; + } if (pColData->numOfNone) { return tColDataAppendValue50(pColData, pData, nData); } else { @@ -2052,35 +2067,42 @@ static FORCE_INLINE int32_t tColDataUpdateValue50(SColData *pColData, uint8_t *p return tColDataAppendValue40(pColData, pData, nData); } } else if (forward) { // VALUE ==> VALUE - pColData->numOfValue--; pColData->nVal--; - if (pColData->numOfValue) { - return tColDataAppendValue50(pColData, pData, nData); + if (IS_VAR_DATA_TYPE(pColData->type)) { + pColData->nData = pColData->aOffset[pColData->nVal]; } else { - pColData->flag = HAS_NONE; - return tColDataAppendValue10(pColData, pData, nData); + pColData->nData -= TYPE_BYTES[pColData->type]; } + return tColDataPutValue(pColData, pData, nData); } return 0; } static FORCE_INLINE int32_t tColDataUpdateValue52(SColData *pColData, uint8_t *pData, uint32_t nData, bool forward) { - uint8_t bv = GET_BIT1(pColData->pBitMap, pColData->nVal - 1); - if (bv == 0) { // NONE ==> NULL + if (GET_BIT1(pColData->pBitMap, pColData->nVal - 1) == 0) { // NONE ==> NULL pColData->numOfNone--; pColData->nVal--; + if (!IS_VAR_DATA_TYPE(pColData->type)) { + pColData->nData -= TYPE_BYTES[pColData->type]; + } if (pColData->numOfNone) { return tColDataAppendValue52(pColData, pData, nData); } else { - pColData->flag &= ~HAS_NONE; + pColData->flag = HAS_VALUE; return tColDataAppendValue42(pColData, pData, nData); } } else if (forward) { // VALUE ==> NULL pColData->numOfValue--; pColData->nVal--; if (pColData->numOfValue) { + if (IS_VAR_DATA_TYPE(pColData->type)) { + pColData->nData = pColData->aOffset[pColData->nVal]; + } else { + pColData->nData -= TYPE_BYTES[pColData->type]; + } return tColDataAppendValue52(pColData, pData, nData); } else { - pColData->flag &= ~HAS_VALUE; + pColData->flag = HAS_NONE; + pColData->nData = 0; return tColDataAppendValue12(pColData, pData, nData); } } @@ -2091,6 +2113,9 @@ static FORCE_INLINE int32_t tColDataUpdateValue60(SColData *pColData, uint8_t *p if (GET_BIT1(pColData->pBitMap, pColData->nVal - 1) == 0) { // NULL ==> VALUE pColData->numOfNull--; pColData->nVal--; + if (!IS_VAR_DATA_TYPE(pColData->type)) { + pColData->nData -= TYPE_BYTES[pColData->type]; + } if (pColData->numOfNull) { return tColDataAppendValue60(pColData, pData, nData); } else { @@ -2098,14 +2123,13 @@ static FORCE_INLINE int32_t tColDataUpdateValue60(SColData *pColData, uint8_t *p return tColDataAppendValue40(pColData, pData, nData); } } else { // VALUE ==> VALUE - pColData->numOfValue--; pColData->nVal--; - if (pColData->numOfValue) { - return tColDataAppendValue60(pColData, pData, nData); + if (IS_VAR_DATA_TYPE(pColData->type)) { + pColData->nData = pColData->aOffset[pColData->nVal]; } else { - pColData->flag = HAS_NULL; - return tColDataAppendValue20(pColData, pData, nData); + pColData->nData -= TYPE_BYTES[pColData->type]; } + return tColDataPutValue(pColData, pData, nData); } } return 0; @@ -2115,9 +2139,15 @@ static FORCE_INLINE int32_t tColDataUpdateValue62(SColData *pColData, uint8_t *p pColData->numOfValue--; pColData->nVal--; if (pColData->numOfValue) { + if (IS_VAR_DATA_TYPE(pColData->type)) { + pColData->nData = pColData->aOffset[pColData->nVal]; + } else { + pColData->nData -= TYPE_BYTES[pColData->type]; + } return tColDataAppendValue62(pColData, pData, nData); } else { pColData->flag = HAS_NULL; + pColData->nData = 0; return tColDataAppendValue20(pColData, pData, nData); } } @@ -2130,38 +2160,44 @@ static FORCE_INLINE int32_t tColDataUpdateValue70(SColData *pColData, uint8_t *p if (bv == 0) { // NONE ==> VALUE pColData->numOfNone--; pColData->nVal--; + if (!IS_VAR_DATA_TYPE(pColData->type)) { + pColData->nData -= TYPE_BYTES[pColData->type]; + } if (pColData->numOfNone) { return tColDataAppendValue70(pColData, pData, nData); } else { for (int32_t iVal = 0; iVal < pColData->nVal; ++iVal) { SET_BIT1(pColData->pBitMap, iVal, GET_BIT2(pColData->pBitMap, iVal) - 1); } - pColData->flag &= ~HAS_NONE; + pColData->flag = (HAS_VALUE | HAS_NULL); return tColDataAppendValue60(pColData, pData, nData); } } else if (bv == 1) { // NULL ==> VALUE if (forward) { pColData->numOfNull--; pColData->nVal--; + if (!IS_VAR_DATA_TYPE(pColData->type)) { + pColData->nData -= TYPE_BYTES[pColData->type]; + } if (pColData->numOfNull) { return tColDataAppendValue70(pColData, pData, nData); } else { for (int32_t iVal = 0; iVal < pColData->nVal; ++iVal) { SET_BIT1(pColData->pBitMap, iVal, GET_BIT2(pColData->pBitMap, iVal) ? 1 : 0); } - pColData->flag &= ~HAS_NULL; + pColData->flag = (HAS_VALUE | HAS_NONE); return tColDataAppendValue50(pColData, pData, nData); } } } else if (bv == 2) { // VALUE ==> VALUE if (forward) { - pColData->numOfValue--; pColData->nVal--; - if (pColData->numOfValue) { - return tColDataAppendValue70(pColData, pData, nData); + if (IS_VAR_DATA_TYPE(pColData->type)) { + pColData->nData = pColData->aOffset[pColData->nVal]; } else { - return tColDataPutValue(pColData, pData, nData); + pColData->nData -= TYPE_BYTES[pColData->type]; } + return tColDataPutValue(pColData, pData, nData); } } else { ASSERT(0); @@ -2170,29 +2206,37 @@ static FORCE_INLINE int32_t tColDataUpdateValue70(SColData *pColData, uint8_t *p } static int32_t tColDataUpdateValue72(SColData *pColData, uint8_t *pData, uint32_t nData, bool forward) { uint8_t bv = GET_BIT2(pColData->pBitMap, pColData->nVal - 1); - ASSERT(bv < 3); if (bv == 0) { // NONE ==> NULL pColData->numOfNone--; pColData->nVal--; + if (!IS_VAR_DATA_TYPE(pColData->type)) { + pColData->nData -= TYPE_BYTES[pColData->type]; + } if (pColData->numOfNone) { return tColDataAppendValue72(pColData, pData, nData); } else { for (int32_t iVal = 0; iVal < pColData->nVal; ++iVal) { SET_BIT1(pColData->pBitMap, iVal, GET_BIT2(pColData->pBitMap, iVal) - 1); } - pColData->flag &= ~HAS_NONE; + pColData->flag = (HAS_VALUE | HAS_NULL); return tColDataAppendValue62(pColData, pData, nData); } } else if (bv == 2 && forward) { // VALUE ==> NULL pColData->numOfValue--; pColData->nVal--; if (pColData->numOfValue) { + if (IS_STR_DATA_TYPE(pColData->type)) { + pColData->nData = pColData->aOffset[pColData->nVal]; + } else { + pColData->nData -= TYPE_BYTES[pColData->type]; + } return tColDataAppendValue72(pColData, pData, nData); } else { for (int32_t iVal = 0; iVal < pColData->nVal; ++iVal) { SET_BIT1(pColData->pBitMap, iVal, GET_BIT2(pColData->pBitMap, iVal)); } - pColData->flag &= ~HAS_VALUE; + pColData->flag = (HAS_NULL | HAS_NONE); + pColData->nData = 0; return tColDataAppendValue32(pColData, pData, nData); } } @@ -2312,35 +2356,25 @@ void tColDataGetValue(SColData *pColData, int32_t iVal, SColVal *pColVal) { } uint8_t tColDataGetBitValue(const SColData *pColData, int32_t iVal) { - uint8_t v; switch (pColData->flag) { case HAS_NONE: - v = 0; - break; + return 0; case HAS_NULL: - v = 1; - break; + return 1; case (HAS_NULL | HAS_NONE): - v = GET_BIT1(pColData->pBitMap, iVal); - break; + return GET_BIT1(pColData->pBitMap, iVal); case HAS_VALUE: - v = 2; - break; + return 2; case (HAS_VALUE | HAS_NONE): - v = GET_BIT1(pColData->pBitMap, iVal); - if (v) v = 2; - break; + return (GET_BIT1(pColData->pBitMap, iVal)) ? 2 : 0; case (HAS_VALUE | HAS_NULL): - v = GET_BIT1(pColData->pBitMap, iVal) + 1; - break; + return GET_BIT1(pColData->pBitMap, iVal) + 1; case (HAS_VALUE | HAS_NULL | HAS_NONE): - v = GET_BIT2(pColData->pBitMap, iVal); - break; + return GET_BIT2(pColData->pBitMap, iVal); default: - ASSERT(0); - break; + ASSERTS(0, "not possible"); + return 0; } - return v; } int32_t tColDataCopy(SColData *pColDataFrom, SColData *pColData, xMallocFn xMalloc, void *arg) { diff --git a/source/common/src/tglobal.c b/source/common/src/tglobal.c index e64646dd03..02d83af3a7 100644 --- a/source/common/src/tglobal.c +++ b/source/common/src/tglobal.c @@ -61,7 +61,7 @@ int32_t tsHeartbeatInterval = 1000; int32_t tsHeartbeatTimeout = 20 * 1000; // vnode -int64_t tsVndCommitMaxIntervalMs = 60 * 1000; +int64_t tsVndCommitMaxIntervalMs = 600 * 1000; // monitor bool tsEnableMonitor = true; diff --git a/source/common/src/tmisce.c b/source/common/src/tmisce.c index dfb1917fcf..59afce1bbb 100644 --- a/source/common/src/tmisce.c +++ b/source/common/src/tmisce.c @@ -60,6 +60,19 @@ bool isEpsetEqual(const SEpSet* s1, const SEpSet* s2) { return true; } +void epsetAssign(SEpSet* pDst, const SEpSet* pSrc) { + if (pSrc == NULL || pDst == NULL) { + return; + } + + pDst->inUse = pSrc->inUse; + pDst->numOfEps = pSrc->numOfEps; + for (int32_t i = 0; i < pSrc->numOfEps; ++i) { + pDst->eps[i].port = pSrc->eps[i].port; + tstrncpy(pDst->eps[i].fqdn, pSrc->eps[i].fqdn, tListLen(pSrc->eps[i].fqdn)); + } +} + void updateEpSet_s(SCorEpSet* pEpSet, SEpSet* pNewEpSet) { taosCorBeginWrite(&pEpSet->version); pEpSet->epSet = *pNewEpSet; diff --git a/source/common/src/ttime.c b/source/common/src/ttime.c index 559ffd2aaf..7996498d45 100644 --- a/source/common/src/ttime.c +++ b/source/common/src/ttime.c @@ -68,12 +68,12 @@ static int64_t user_mktime64(const uint32_t year0, const uint32_t mon0, const ui // ==== mktime() kernel code =================// static int64_t m_deltaUtc = 0; -void deltaToUtcInitOnce() { - struct tm tm = {0}; - (void)taosStrpTime("1970-01-01 00:00:00", (const char*)("%Y-%m-%d %H:%M:%S"), &tm); - m_deltaUtc = (int64_t)taosMktime(&tm); - // printf("====delta:%lld\n\n", seconds); +void deltaToUtcInitOnce() { + struct tm tm = {0}; + (void)taosStrpTime("1970-01-01 00:00:00", (const char*)("%Y-%m-%d %H:%M:%S"), &tm); + m_deltaUtc = (int64_t)taosMktime(&tm); + // printf("====delta:%lld\n\n", seconds); } static int64_t parseFraction(char* str, char** end, int32_t timePrec); diff --git a/source/common/src/tvariant.c b/source/common/src/tvariant.c index de225581a6..b42c88ac97 100644 --- a/source/common/src/tvariant.c +++ b/source/common/src/tvariant.c @@ -185,7 +185,7 @@ void taosVariantAssign(SVariant *pDst, const SVariant *pSrc) { pDst->arr = taosArrayInit(num, sizeof(char *)); for (size_t i = 0; i < num; i++) { char *p = (char *)taosArrayGetP(pSrc->arr, i); - char *n = strdup(p); + char *n = taosStrdup(p); taosArrayPush(pDst->arr, &n); } } else if (pSrc->nType == TSDB_DATA_TYPE_VALUE_ARRAY) { diff --git a/source/common/test/commonTests.cpp b/source/common/test/commonTests.cpp index 8460d71e56..8a77087d23 100644 --- a/source/common/test/commonTests.cpp +++ b/source/common/test/commonTests.cpp @@ -109,14 +109,14 @@ TEST(testCase, Datablock_test) { if (i & 0x01) { int32_t len = sprintf(buf, str, i); STR_TO_VARSTR(varbuf, buf) - colDataAppend(p0, i, (const char*)&i, false); - colDataAppend(p1, i, (const char*)varbuf, false); + colDataSetVal(p0, i, (const char*)&i, false); + colDataSetVal(p1, i, (const char*)varbuf, false); memset(varbuf, 0, sizeof(varbuf)); memset(buf, 0, sizeof(buf)); } else { - colDataAppend(p0, i, (const char*)&i, true); - colDataAppend(p1, i, (const char*)varbuf, true); + colDataSetVal(p0, i, (const char*)&i, true); + colDataSetVal(p1, i, (const char*)varbuf, true); } b->info.rows++; @@ -185,8 +185,8 @@ TEST(testCase, non_var_dataBlock_split_test) { SColumnInfoData* p1 = (SColumnInfoData*)taosArrayGet(b->pDataBlock, 1); int8_t v = i; - colDataAppend(p0, i, (const char*)&i, false); - colDataAppend(p1, i, (const char*)&v, false); + colDataSetVal(p0, i, (const char*)&i, false); + colDataSetVal(p1, i, (const char*)&v, false); b->info.rows++; } @@ -231,12 +231,12 @@ TEST(testCase, var_dataBlock_split_test) { SColumnInfoData* p1 = (SColumnInfoData*)taosArrayGet(b->pDataBlock, 1); int8_t v = i; - colDataAppend(p0, i, (const char*)&i, false); + colDataSetVal(p0, i, (const char*)&i, false); sprintf(buf, "the number of row:%d", i); int32_t len = sprintf(buf1, buf, i); STR_TO_VARSTR(buf1, buf) - colDataAppend(p1, i, buf1, false); + colDataSetVal(p1, i, buf1, false); b->info.rows++; memset(buf, 0, sizeof(buf)); diff --git a/source/dnode/mgmt/mgmt_dnode/src/dmHandle.c b/source/dnode/mgmt/mgmt_dnode/src/dmHandle.c index 3e9084bd11..0724fcc63a 100644 --- a/source/dnode/mgmt/mgmt_dnode/src/dmHandle.c +++ b/source/dnode/mgmt/mgmt_dnode/src/dmHandle.c @@ -242,19 +242,19 @@ int32_t dmAppendVariablesToBlock(SSDataBlock *pBlock, int32_t dnodeId) { GRANT_CFG_SKIP; SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, c++); - colDataAppend(pColInfo, i, (const char *)&dnodeId, false); + colDataSetVal(pColInfo, i, (const char *)&dnodeId, false); char name[TSDB_CONFIG_OPTION_LEN + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(name, pItem->name, TSDB_CONFIG_OPTION_LEN + VARSTR_HEADER_SIZE); pColInfo = taosArrayGet(pBlock->pDataBlock, c++); - colDataAppend(pColInfo, i, name, false); + colDataSetVal(pColInfo, i, name, false); char value[TSDB_CONFIG_VALUE_LEN + VARSTR_HEADER_SIZE] = {0}; int32_t valueLen = 0; cfgDumpItemValue(pItem, &value[VARSTR_HEADER_SIZE], TSDB_CONFIG_VALUE_LEN, &valueLen); varDataSetLen(value, valueLen); pColInfo = taosArrayGet(pBlock->pDataBlock, c++); - colDataAppend(pColInfo, i, value, false); + colDataSetVal(pColInfo, i, value, false); numOfRows++; } diff --git a/source/dnode/mgmt/mgmt_vnode/src/vmInt.c b/source/dnode/mgmt/mgmt_vnode/src/vmInt.c index 8049db9c78..8008e5f810 100644 --- a/source/dnode/mgmt/mgmt_vnode/src/vmInt.c +++ b/source/dnode/mgmt/mgmt_vnode/src/vmInt.c @@ -53,7 +53,7 @@ int32_t vmOpenVnode(SVnodeMgmt *pMgmt, SWrapperCfg *pCfg, SVnode *pImpl) { pVnode->vgVersion = pCfg->vgVersion; pVnode->refCount = 0; pVnode->dropped = 0; - pVnode->path = tstrdup(pCfg->path); + pVnode->path = taosStrdup(pCfg->path); pVnode->pImpl = pImpl; if (pVnode->path == NULL) { diff --git a/source/dnode/mgmt/mgmt_vnode/src/vmWorker.c b/source/dnode/mgmt/mgmt_vnode/src/vmWorker.c index 027b9b7d48..c1b3cde9ea 100644 --- a/source/dnode/mgmt/mgmt_vnode/src/vmWorker.c +++ b/source/dnode/mgmt/mgmt_vnode/src/vmWorker.c @@ -166,7 +166,6 @@ static int32_t vmPutMsgToQueue(SVnodeMgmt *pMgmt, SRpcMsg *pMsg, EQueueType qtyp dGError("vgId:%d, msg:%p failed to put into vnode queue since %s, type:%s qtype:%d contLen:%d", pHead->vgId, pMsg, terrstr(), TMSG_INFO(pMsg->msgType), qtype, pHead->contLen); terrno = (terrno != 0) ? terrno : -1; - vmSendResponse(pMsg); return terrno; } diff --git a/source/dnode/mgmt/node_mgmt/src/dmMgmt.c b/source/dnode/mgmt/node_mgmt/src/dmMgmt.c index 3dd8a19d92..d884120147 100644 --- a/source/dnode/mgmt/node_mgmt/src/dmMgmt.c +++ b/source/dnode/mgmt/node_mgmt/src/dmMgmt.c @@ -124,7 +124,7 @@ int32_t dmInitDnode(SDnode *pDnode) { taosThreadRwlockInit(&pWrapper->lock, NULL); snprintf(path, sizeof(path), "%s%s%s", tsDataDir, TD_DIRSEP, pWrapper->name); - pWrapper->path = strdup(path); + pWrapper->path = taosStrdup(path); if (pWrapper->path == NULL) { terrno = TSDB_CODE_OUT_OF_MEMORY; goto _OVER; diff --git a/source/dnode/mgmt/node_mgmt/src/dmTransport.c b/source/dnode/mgmt/node_mgmt/src/dmTransport.c index 8abce50cf0..23a047d49a 100644 --- a/source/dnode/mgmt/node_mgmt/src/dmTransport.c +++ b/source/dnode/mgmt/node_mgmt/src/dmTransport.c @@ -93,18 +93,30 @@ static void dmProcessRpcMsg(SDnode *pDnode, SRpcMsg *pRpc, SEpSet *pEpSet) { break; } - if (pDnode->status != DND_STAT_RUNNING) { - if (pRpc->msgType == TDMT_DND_SERVER_STATUS) { - dmProcessServerStartupStatus(pDnode, pRpc); - return; - } else { - if (pDnode->status == DND_STAT_INIT) { - terrno = TSDB_CODE_APP_IS_STARTING; +/* +pDnode is null, TD-22618 +at trans.c line 91 +before this line, dmProcessRpcMsg callback is set +after this line, parent is set +so when dmProcessRpcMsg is called, pDonde is still null. +*/ + if (pDnode != NULL){ + if(pDnode->status != DND_STAT_RUNNING) { + if (pRpc->msgType == TDMT_DND_SERVER_STATUS) { + dmProcessServerStartupStatus(pDnode, pRpc); + return; } else { - terrno = TSDB_CODE_APP_IS_STOPPING; + if (pDnode->status == DND_STAT_INIT) { + terrno = TSDB_CODE_APP_IS_STARTING; + } else { + terrno = TSDB_CODE_APP_IS_STOPPING; + } + goto _OVER; } - goto _OVER; - } + } + } else { + terrno = TSDB_CODE_APP_IS_STARTING; + goto _OVER; } if (pRpc->pCont == NULL && (IsReq(pRpc) || pRpc->contLen != 0)) { diff --git a/source/dnode/mgmt/node_util/src/dmEps.c b/source/dnode/mgmt/node_util/src/dmEps.c index a7a5b8b999..e9ab8a0460 100644 --- a/source/dnode/mgmt/node_util/src/dmEps.c +++ b/source/dnode/mgmt/node_util/src/dmEps.c @@ -402,7 +402,7 @@ static int32_t dmDecodeEpPairs(SJson *pJson, SDnodeData *pData) { int32_t code = 0; SJson *dnodes = tjsonGetObjectItem(pJson, "dnodes"); - if (dnodes == NULL) return 0; + if (dnodes == NULL) return -1; int32_t numOfDnodes = tjsonGetArraySize(dnodes); for (int32_t i = 0; i < numOfDnodes; ++i) { diff --git a/source/dnode/mnode/impl/inc/mndInt.h b/source/dnode/mnode/impl/inc/mndInt.h index 785ecc2bf5..d851578a74 100644 --- a/source/dnode/mnode/impl/inc/mndInt.h +++ b/source/dnode/mnode/impl/inc/mndInt.h @@ -58,7 +58,7 @@ typedef int32_t (*MndInitFp)(SMnode *pMnode); typedef void (*MndCleanupFp)(SMnode *pMnode); typedef int32_t (*ShowRetrieveFp)(SRpcMsg *pMsg, SShowObj *pShow, SSDataBlock *pBlock, int32_t rows); typedef void (*ShowFreeIterFp)(SMnode *pMnode, void *pIter); -typedef struct SQWorker SQHandle; +typedef struct SQueueWorker SQHandle; typedef struct { const char *name; diff --git a/source/dnode/mnode/impl/inc/mndTopic.h b/source/dnode/mnode/impl/inc/mndTopic.h index 8cd669c769..8ed7fc6a11 100644 --- a/source/dnode/mnode/impl/inc/mndTopic.h +++ b/source/dnode/mnode/impl/inc/mndTopic.h @@ -27,14 +27,9 @@ void mndCleanupTopic(SMnode *pMnode); SMqTopicObj *mndAcquireTopic(SMnode *pMnode, const char *topicName); void mndReleaseTopic(SMnode *pMnode, SMqTopicObj *pTopic); - -SSdbRaw *mndTopicActionEncode(SMqTopicObj *pTopic); -SSdbRow *mndTopicActionDecode(SSdbRaw *pRaw); - -int32_t mndDropTopicByDB(SMnode *pMnode, STrans *pTrans, SDbObj *pDb); -int32_t mndCheckTopicExist(SMnode *pMnode, SDbObj *pDb); - -const char *mndTopicGetShowName(const char topic[TSDB_TOPIC_FNAME_LEN]); +int32_t mndDropTopicByDB(SMnode *pMnode, STrans *pTrans, SDbObj *pDb); +bool mndTopicExistsForDb(SMnode *pMnode, SDbObj *pDb); +const char *mndTopicGetShowName(const char topic[TSDB_TOPIC_FNAME_LEN]); int32_t mndSetTopicCommitLogs(SMnode *pMnode, STrans *pTrans, SMqTopicObj *pTopic); diff --git a/source/dnode/mnode/impl/src/mndCluster.c b/source/dnode/mnode/impl/src/mndCluster.c index e0d8ecb3eb..94584dfe58 100644 --- a/source/dnode/mnode/impl/src/mndCluster.c +++ b/source/dnode/mnode/impl/src/mndCluster.c @@ -278,31 +278,31 @@ static int32_t mndRetrieveClusters(SRpcMsg *pMsg, SShowObj *pShow, SSDataBlock * cols = 0; SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pCluster->id, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pCluster->id, false); char buf[tListLen(pCluster->name) + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(buf, pCluster->name, pShow->pMeta->pSchemas[cols].bytes); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, buf, false); + colDataSetVal(pColInfo, numOfRows, buf, false); int32_t upTime = mndGetClusterUpTimeImp(pCluster); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&upTime, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&upTime, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pCluster->createdTime, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pCluster->createdTime, false); char ver[12] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(ver, tsVersionName, pShow->pMeta->pSchemas[cols].bytes); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)ver, false); + colDataSetVal(pColInfo, numOfRows, (const char *)ver, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); if (tsExpireTime <= 0) { - colDataAppendNULL(pColInfo, numOfRows); + colDataSetNULL(pColInfo, numOfRows); } else { - colDataAppend(pColInfo, numOfRows, (const char *)&tsExpireTime, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&tsExpireTime, false); } sdbRelease(pSdb, pCluster); diff --git a/source/dnode/mnode/impl/src/mndConsumer.c b/source/dnode/mnode/impl/src/mndConsumer.c index eb4fc3cdad..6621b6a3f9 100644 --- a/source/dnode/mnode/impl/src/mndConsumer.c +++ b/source/dnode/mnode/impl/src/mndConsumer.c @@ -100,7 +100,7 @@ static int32_t mndProcessConsumerLostMsg(SRpcMsg *pMsg) { return 0; } - mInfo("receive consumer lost msg, consumer id %" PRId64 ", status %s", pLostMsg->consumerId, + mInfo("process consumer lost msg, consumer:0x%" PRIx64 " status:%d(%s)", pLostMsg->consumerId, pConsumer->status, mndConsumerStatusName(pConsumer->status)); if (pConsumer->status != MQ_CONSUMER_STATUS__READY) { @@ -114,9 +114,17 @@ static int32_t mndProcessConsumerLostMsg(SRpcMsg *pMsg) { mndReleaseConsumer(pMnode, pConsumer); STrans *pTrans = mndTransCreate(pMnode, TRN_POLICY_ROLLBACK, TRN_CONFLICT_NOTHING, pMsg, "lost-csm"); - if (pTrans == NULL) goto FAIL; - if (mndSetConsumerCommitLogs(pMnode, pTrans, pConsumerNew) != 0) goto FAIL; - if (mndTransPrepare(pMnode, pTrans) != 0) goto FAIL; + if (pTrans == NULL) { + goto FAIL; + } + + if (mndSetConsumerCommitLogs(pMnode, pTrans, pConsumerNew) != 0) { + goto FAIL; + } + + if (mndTransPrepare(pMnode, pTrans) != 0) { + goto FAIL; + } tDeleteSMqConsumerObj(pConsumerNew); taosMemoryFree(pConsumerNew); @@ -138,8 +146,8 @@ static int32_t mndProcessConsumerRecoverMsg(SRpcMsg *pMsg) { return -1; } - mInfo("receive consumer recover msg, consumer id %" PRId64 ", status %s", pRecoverMsg->consumerId, - mndConsumerStatusName(pConsumer->status)); + mInfo("receive consumer recover msg, consumer:0x%" PRIx64 " status:%d(%s)", pRecoverMsg->consumerId, + pConsumer->status, mndConsumerStatusName(pConsumer->status)); if (pConsumer->status != MQ_CONSUMER_STATUS__LOST_REBD) { mndReleaseConsumer(pMnode, pConsumer); @@ -153,7 +161,10 @@ static int32_t mndProcessConsumerRecoverMsg(SRpcMsg *pMsg) { mndReleaseConsumer(pMnode, pConsumer); STrans *pTrans = mndTransCreate(pMnode, TRN_POLICY_RETRY, TRN_CONFLICT_NOTHING, pMsg, "recover-csm"); - if (pTrans == NULL) goto FAIL; + if (pTrans == NULL) { + goto FAIL; + } + if (mndSetConsumerCommitLogs(pMnode, pTrans, pConsumerNew) != 0) goto FAIL; if (mndTransPrepare(pMnode, pTrans) != 0) goto FAIL; @@ -241,25 +252,32 @@ static int32_t mndProcessMqTimerMsg(SRpcMsg *pMsg) { // iterate all consumers, find all modification while (1) { pIter = sdbFetch(pSdb, SDB_CONSUMER, pIter, (void **)&pConsumer); - if (pIter == NULL) break; + if (pIter == NULL) { + break; + } int32_t hbStatus = atomic_add_fetch_32(&pConsumer->hbStatus, 1); int32_t status = atomic_load_32(&pConsumer->status); - if (status == MQ_CONSUMER_STATUS__READY && hbStatus > MND_CONSUMER_LOST_HB_CNT) { - SMqConsumerLostMsg *pLostMsg = rpcMallocCont(sizeof(SMqConsumerLostMsg)); - pLostMsg->consumerId = pConsumer->consumerId; - SRpcMsg rpcMsg = { - .msgType = TDMT_MND_TMQ_CONSUMER_LOST, - .pCont = pLostMsg, - .contLen = sizeof(SMqConsumerLostMsg), - }; - tmsgPutToQueue(&pMnode->msgCb, WRITE_QUEUE, &rpcMsg); - } + mDebug("check for consumer:0x%" PRIx64 " status:%d(%s), sub-time:%" PRId64 ", uptime:%" PRId64 ", hbstatus:%d", + pConsumer->consumerId, status, mndConsumerStatusName(status), pConsumer->subscribeTime, pConsumer->upTime, + hbStatus); if (status == MQ_CONSUMER_STATUS__READY) { - // do nothing + if (hbStatus > MND_CONSUMER_LOST_HB_CNT) { + SMqConsumerLostMsg *pLostMsg = rpcMallocCont(sizeof(SMqConsumerLostMsg)); + + pLostMsg->consumerId = pConsumer->consumerId; + SRpcMsg rpcMsg = { + .msgType = TDMT_MND_TMQ_CONSUMER_LOST, + .pCont = pLostMsg, + .contLen = sizeof(SMqConsumerLostMsg), + }; + + tmsgPutToQueue(&pMnode->msgCb, WRITE_QUEUE, &rpcMsg); + } } else if (status == MQ_CONSUMER_STATUS__LOST_REBD) { + // if the client is lost longer than one day, clear it. Otherwise, do nothing about the lost consumers. if (hbStatus > MND_CONSUMER_LOST_CLEAR_THRESHOLD) { SMqConsumerClearMsg *pClearMsg = rpcMallocCont(sizeof(SMqConsumerClearMsg)); @@ -269,6 +287,7 @@ static int32_t mndProcessMqTimerMsg(SRpcMsg *pMsg) { .pCont = pClearMsg, .contLen = sizeof(SMqConsumerClearMsg), }; + tmsgPutToQueue(&pMnode->msgCb, WRITE_QUEUE, &rpcMsg); } } else if (status == MQ_CONSUMER_STATUS__LOST) { @@ -338,7 +357,7 @@ static int32_t mndProcessMqHbReq(SRpcMsg *pMsg) { int64_t consumerId = req.consumerId; SMqConsumerObj *pConsumer = mndAcquireConsumer(pMnode, consumerId); if (pConsumer == NULL) { - mError("consumer %" PRId64 " not exist", consumerId); + mError("consumer:0x%" PRIx64 " not exist", consumerId); terrno = TSDB_CODE_MND_CONSUMER_NOT_EXIST; return -1; } @@ -348,7 +367,7 @@ static int32_t mndProcessMqHbReq(SRpcMsg *pMsg) { int32_t status = atomic_load_32(&pConsumer->status); if (status == MQ_CONSUMER_STATUS__LOST_REBD) { - mInfo("try to recover consumer %" PRId64 "", consumerId); + mInfo("try to recover consumer:0x%" PRIx64 "", consumerId); SMqConsumerRecoverMsg *pRecoverMsg = rpcMallocCont(sizeof(SMqConsumerRecoverMsg)); pRecoverMsg->consumerId = consumerId; @@ -380,6 +399,15 @@ static int32_t mndProcessAskEpReq(SRpcMsg *pMsg) { SMqConsumerObj *pConsumer = mndAcquireConsumer(pMnode, consumerId); if (pConsumer == NULL) { + mError("consumer:0x%" PRIx64 " group:%s not exists in sdb", consumerId, req.cgroup); + terrno = TSDB_CODE_MND_CONSUMER_NOT_EXIST; + return -1; + } + + int32_t ret = strncmp(req.cgroup, pConsumer->cgroup, tListLen(pConsumer->cgroup)); + if (ret != 0) { + mError("consumer:0x%" PRIx64 " group:%s not consistent with data in sdb, saved cgroup:%s", consumerId, req.cgroup, + pConsumer->cgroup); terrno = TSDB_CODE_MND_CONSUMER_NOT_EXIST; return -1; } @@ -391,7 +419,7 @@ static int32_t mndProcessAskEpReq(SRpcMsg *pMsg) { #if 1 if (status == MQ_CONSUMER_STATUS__LOST_REBD) { - mInfo("try to recover consumer %" PRId64 "", consumerId); + mInfo("try to recover consumer:0x%" PRIx64, consumerId); SMqConsumerRecoverMsg *pRecoverMsg = rpcMallocCont(sizeof(SMqConsumerRecoverMsg)); pRecoverMsg->consumerId = consumerId; @@ -400,22 +428,24 @@ static int32_t mndProcessAskEpReq(SRpcMsg *pMsg) { .pCont = pRecoverMsg, .contLen = sizeof(SMqConsumerRecoverMsg), }; + tmsgPutToQueue(&pMnode->msgCb, WRITE_QUEUE, &pRpcMsg); } #endif if (status != MQ_CONSUMER_STATUS__READY) { - mInfo("consumer %" PRId64 " not ready, status: %s", consumerId, mndConsumerStatusName(status)); + mInfo("consumer:0x%" PRIx64 " not ready, status: %s", consumerId, mndConsumerStatusName(status)); terrno = TSDB_CODE_MND_CONSUMER_NOT_READY; return -1; } int32_t serverEpoch = atomic_load_32(&pConsumer->epoch); - // 2. check epoch, only send ep info when epoches do not match + // 2. check epoch, only send ep info when epochs do not match if (epoch != serverEpoch) { taosRLockLatch(&pConsumer->lock); - mInfo("process ask ep, consumer:%" PRId64 "(epoch %d), server epoch %d", consumerId, epoch, serverEpoch); + mInfo("process ask ep, consumer:0x%" PRIx64 "(epoch %d) update with server epoch %d", consumerId, epoch, + serverEpoch); int32_t numOfTopics = taosArrayGetSize(pConsumer->currentTopics); rsp.topics = taosArrayInit(numOfTopics, sizeof(SMqSubTopicEp)); @@ -425,7 +455,7 @@ static int32_t mndProcessAskEpReq(SRpcMsg *pMsg) { goto FAIL; } - // handle all topic subscribed by the consumer + // handle all topics subscribed by this consumer for (int32_t i = 0; i < numOfTopics; i++) { char *topic = taosArrayGetP(pConsumer->currentTopics, i); SMqSubscribeObj *pSub = mndAcquireSubscribe(pMnode, pConsumer->cgroup, topic); @@ -452,6 +482,7 @@ static int32_t mndProcessAskEpReq(SRpcMsg *pMsg) { SMqConsumerEp *pConsumerEp = taosHashGet(pSub->consumerHash, &consumerId, sizeof(int64_t)); int32_t vgNum = taosArrayGetSize(pConsumerEp->vgs); + // this customer assigned vgroups topicEp.vgs = taosArrayInit(vgNum, sizeof(SMqSubVgEp)); if (topicEp.vgs == NULL) { terrno = TSDB_CODE_OUT_OF_MEMORY; @@ -481,6 +512,7 @@ static int32_t mndProcessAskEpReq(SRpcMsg *pMsg) { } taosRUnLockLatch(&pConsumer->lock); } + // encode rsp int32_t tlen = sizeof(SMqRspHead) + tEncodeSMqAskEpRsp(NULL, &rsp); void *buf = rpcMallocCont(tlen); @@ -488,6 +520,7 @@ static int32_t mndProcessAskEpReq(SRpcMsg *pMsg) { terrno = TSDB_CODE_OUT_OF_MEMORY; return -1; } + ((SMqRspHead *)buf)->mqMsgType = TMQ_MSG_TYPE__EP_RSP; ((SMqRspHead *)buf)->epoch = serverEpoch; ((SMqRspHead *)buf)->consumerId = pConsumer->consumerId; @@ -503,6 +536,7 @@ static int32_t mndProcessAskEpReq(SRpcMsg *pMsg) { pMsg->info.rsp = buf; pMsg->info.rspLen = tlen; return 0; + FAIL: tDeleteSMqAskEpRsp(&rsp); mndReleaseConsumer(pMnode, pConsumer); @@ -525,122 +559,132 @@ int32_t mndSetConsumerCommitLogs(SMnode *pMnode, STrans *pTrans, SMqConsumerObj return 0; } -static int32_t mndProcessSubscribeReq(SRpcMsg *pMsg) { - SMnode *pMnode = pMsg->info.node; - char *msgStr = pMsg->pCont; - SCMSubscribeReq subscribe = {0}; - tDeserializeSCMSubscribeReq(msgStr, &subscribe); - int64_t consumerId = subscribe.consumerId; - char *cgroup = subscribe.cgroup; - SMqConsumerObj *pConsumerOld = NULL; - SMqConsumerObj *pConsumerNew = NULL; +static int32_t validateTopics(const SArray* pTopicList, SMnode* pMnode, const char* pUser) { + int32_t numOfTopics = taosArrayGetSize(pTopicList); - int32_t code = -1; - SArray *newSub = subscribe.topicNames; - taosArraySort(newSub, taosArrayCompareString); - taosArrayRemoveDuplicateP(newSub, taosArrayCompareString, taosMemoryFree); - - int32_t newTopicNum = taosArrayGetSize(newSub); - // check topic existance - STrans *pTrans = mndTransCreate(pMnode, TRN_POLICY_RETRY, TRN_CONFLICT_NOTHING, pMsg, "subscribe"); - if (pTrans == NULL) goto SUBSCRIBE_OVER; - - for (int32_t i = 0; i < newTopicNum; i++) { - char *topic = taosArrayGetP(newSub, i); - SMqTopicObj *pTopic = mndAcquireTopic(pMnode, topic); - if (pTopic == NULL) { - terrno = TSDB_CODE_MND_TOPIC_NOT_EXIST; - goto SUBSCRIBE_OVER; + for (int32_t i = 0; i < numOfTopics; i++) { + char *pOneTopic = taosArrayGetP(pTopicList, i); + SMqTopicObj *pTopic = mndAcquireTopic(pMnode, pOneTopic); + if (pTopic == NULL) { // terrno has been set by callee function + return -1; } - if (mndCheckTopicPrivilege(pMnode, pMsg->info.conn.user, MND_OPER_SUBSCRIBE, pTopic) != 0) { + if (mndCheckTopicPrivilege(pMnode, pUser, MND_OPER_SUBSCRIBE, pTopic) != 0) { mndReleaseTopic(pMnode, pTopic); - goto SUBSCRIBE_OVER; - } - - if (mndCheckTopicPrivilege(pMnode, pMsg->info.conn.user, MND_OPER_SUBSCRIBE, pTopic) != 0) { - goto SUBSCRIBE_OVER; + return -1; } mndReleaseTopic(pMnode, pTopic); } - pConsumerOld = mndAcquireConsumer(pMnode, consumerId); - if (pConsumerOld == NULL) { - mInfo("receive subscribe request from new consumer:%" PRId64, consumerId); + return 0; +} + +int32_t mndProcessSubscribeReq(SRpcMsg *pMsg) { + SMnode *pMnode = pMsg->info.node; + char *msgStr = pMsg->pCont; + + SCMSubscribeReq subscribe = {0}; + tDeserializeSCMSubscribeReq(msgStr, &subscribe); + + uint64_t consumerId = subscribe.consumerId; + char *cgroup = subscribe.cgroup; + SMqConsumerObj *pExistedConsumer = NULL; + SMqConsumerObj *pConsumerNew = NULL; + + int32_t code = -1; + SArray *pTopicList = subscribe.topicNames; + taosArraySort(pTopicList, taosArrayCompareString); + taosArrayRemoveDuplicateP(pTopicList, taosArrayCompareString, taosMemoryFree); + + int32_t newTopicNum = taosArrayGetSize(pTopicList); + + // check topic existence + STrans *pTrans = mndTransCreate(pMnode, TRN_POLICY_RETRY, TRN_CONFLICT_NOTHING, pMsg, "subscribe"); + if (pTrans == NULL) { + goto _over; + } + + code = validateTopics(pTopicList, pMnode, pMsg->info.conn.user); + if (code != TSDB_CODE_SUCCESS) { + goto _over; + } + + pExistedConsumer = mndAcquireConsumer(pMnode, consumerId); + if (pExistedConsumer == NULL) { + mInfo("receive subscribe request from new consumer:0x%" PRIx64" cgroup:%s", consumerId, subscribe.cgroup); pConsumerNew = tNewSMqConsumerObj(consumerId, cgroup); tstrncpy(pConsumerNew->clientId, subscribe.clientId, 256); pConsumerNew->updateType = CONSUMER_UPDATE__MODIFY; taosArrayDestroy(pConsumerNew->rebNewTopics); - pConsumerNew->rebNewTopics = newSub; + pConsumerNew->rebNewTopics = pTopicList; // all subscribe topics should re-balance. subscribe.topicNames = NULL; for (int32_t i = 0; i < newTopicNum; i++) { - char *newTopicCopy = strdup(taosArrayGetP(newSub, i)); + char *newTopicCopy = taosStrdup(taosArrayGetP(pTopicList, i)); taosArrayPush(pConsumerNew->assignedTopics, &newTopicCopy); } - if (mndSetConsumerCommitLogs(pMnode, pTrans, pConsumerNew) != 0) goto SUBSCRIBE_OVER; - if (mndTransPrepare(pMnode, pTrans) != 0) goto SUBSCRIBE_OVER; + if (mndSetConsumerCommitLogs(pMnode, pTrans, pConsumerNew) != 0) goto _over; + if (mndTransPrepare(pMnode, pTrans) != 0) goto _over; } else { - /*taosRLockLatch(&pConsumerOld->lock);*/ + /*taosRLockLatch(&pExistedConsumer->lock);*/ + int32_t status = atomic_load_32(&pExistedConsumer->status); - int32_t status = atomic_load_32(&pConsumerOld->status); - - mInfo("receive subscribe request from existing consumer:%" PRId64 ", current status: %s, subscribe topic num: %d", - consumerId, mndConsumerStatusName(status), newTopicNum); + mInfo("receive subscribe request from existed consumer:0x%" PRIx64 " cgroup:%s, current status:%d(%s), subscribe topic num: %d", + consumerId, subscribe.cgroup, status,mndConsumerStatusName(status), newTopicNum); if (status != MQ_CONSUMER_STATUS__READY) { terrno = TSDB_CODE_MND_CONSUMER_NOT_READY; - goto SUBSCRIBE_OVER; + goto _over; } pConsumerNew = tNewSMqConsumerObj(consumerId, cgroup); if (pConsumerNew == NULL) { - terrno = TSDB_CODE_OUT_OF_MEMORY; - goto SUBSCRIBE_OVER; + goto _over; } + pConsumerNew->updateType = CONSUMER_UPDATE__MODIFY; for (int32_t i = 0; i < newTopicNum; i++) { - char *newTopicCopy = strdup(taosArrayGetP(newSub, i)); + char *newTopicCopy = taosStrdup(taosArrayGetP(pTopicList, i)); taosArrayPush(pConsumerNew->assignedTopics, &newTopicCopy); } int32_t oldTopicNum = 0; - if (pConsumerOld->currentTopics) { - oldTopicNum = taosArrayGetSize(pConsumerOld->currentTopics); + if (pExistedConsumer->currentTopics) { + oldTopicNum = taosArrayGetSize(pExistedConsumer->currentTopics); } int32_t i = 0, j = 0; while (i < oldTopicNum || j < newTopicNum) { if (i >= oldTopicNum) { - char *newTopicCopy = strdup(taosArrayGetP(newSub, j)); + char *newTopicCopy = taosStrdup(taosArrayGetP(pTopicList, j)); taosArrayPush(pConsumerNew->rebNewTopics, &newTopicCopy); j++; continue; } else if (j >= newTopicNum) { - char *oldTopicCopy = strdup(taosArrayGetP(pConsumerOld->currentTopics, i)); + char *oldTopicCopy = taosStrdup(taosArrayGetP(pExistedConsumer->currentTopics, i)); taosArrayPush(pConsumerNew->rebRemovedTopics, &oldTopicCopy); i++; continue; } else { - char *oldTopic = taosArrayGetP(pConsumerOld->currentTopics, i); - char *newTopic = taosArrayGetP(newSub, j); - int comp = compareLenPrefixedStr(oldTopic, newTopic); + char *oldTopic = taosArrayGetP(pExistedConsumer->currentTopics, i); + char *newTopic = taosArrayGetP(pTopicList, j); + int comp = strcmp(oldTopic, newTopic); if (comp == 0) { i++; j++; continue; } else if (comp < 0) { - char *oldTopicCopy = strdup(oldTopic); + char *oldTopicCopy = taosStrdup(oldTopic); taosArrayPush(pConsumerNew->rebRemovedTopics, &oldTopicCopy); i++; continue; } else { - char *newTopicCopy = strdup(newTopic); + char *newTopicCopy = taosStrdup(newTopic); taosArrayPush(pConsumerNew->rebNewTopics, &newTopicCopy); j++; continue; @@ -648,27 +692,28 @@ static int32_t mndProcessSubscribeReq(SRpcMsg *pMsg) { } } - if (pConsumerOld && taosArrayGetSize(pConsumerNew->rebNewTopics) == 0 && + if (pExistedConsumer && taosArrayGetSize(pConsumerNew->rebNewTopics) == 0 && taosArrayGetSize(pConsumerNew->rebRemovedTopics) == 0) { /*if (taosArrayGetSize(pConsumerNew->assignedTopics) == 0) {*/ /*pConsumerNew->updateType = */ /*}*/ - goto SUBSCRIBE_OVER; + goto _over; } - if (mndSetConsumerCommitLogs(pMnode, pTrans, pConsumerNew) != 0) goto SUBSCRIBE_OVER; - if (mndTransPrepare(pMnode, pTrans) != 0) goto SUBSCRIBE_OVER; + if (mndSetConsumerCommitLogs(pMnode, pTrans, pConsumerNew) != 0) goto _over; + if (mndTransPrepare(pMnode, pTrans) != 0) goto _over; } code = TSDB_CODE_ACTION_IN_PROGRESS; -SUBSCRIBE_OVER: +_over: mndTransDrop(pTrans); - if (pConsumerOld) { - /*taosRUnLockLatch(&pConsumerOld->lock);*/ - mndReleaseConsumer(pMnode, pConsumerOld); + if (pExistedConsumer) { + /*taosRUnLockLatch(&pExistedConsumer->lock);*/ + mndReleaseConsumer(pMnode, pExistedConsumer); } + if (pConsumerNew) { tDeleteSMqConsumerObj(pConsumerNew); taosMemoryFree(pConsumerNew); @@ -715,13 +760,14 @@ CM_ENCODE_OVER: } SSdbRow *mndConsumerActionDecode(SSdbRaw *pRaw) { - terrno = TSDB_CODE_OUT_OF_MEMORY; SSdbRow *pRow = NULL; SMqConsumerObj *pConsumer = NULL; void *buf = NULL; int8_t sver = 0; - if (sdbGetRawSoftVer(pRaw, &sver) != 0) goto CM_DECODE_OVER; + if (sdbGetRawSoftVer(pRaw, &sver) != 0) { + goto CM_DECODE_OVER; + } if (sver != MND_CONSUMER_VER_NUMBER) { terrno = TSDB_CODE_SDB_INVALID_DATA_VER; @@ -729,52 +775,63 @@ SSdbRow *mndConsumerActionDecode(SSdbRaw *pRaw) { } pRow = sdbAllocRow(sizeof(SMqConsumerObj)); - if (pRow == NULL) goto CM_DECODE_OVER; + if (pRow == NULL) { + goto CM_DECODE_OVER; + } pConsumer = sdbGetRowObj(pRow); - if (pConsumer == NULL) goto CM_DECODE_OVER; + if (pConsumer == NULL) { + goto CM_DECODE_OVER; + } int32_t dataPos = 0; int32_t len; SDB_GET_INT32(pRaw, dataPos, &len, CM_DECODE_OVER); buf = taosMemoryMalloc(len); - if (buf == NULL) goto CM_DECODE_OVER; + if (buf == NULL) { + terrno = TSDB_CODE_OUT_OF_MEMORY; + goto CM_DECODE_OVER; + } + SDB_GET_BINARY(pRaw, dataPos, buf, len, CM_DECODE_OVER); SDB_GET_RESERVE(pRaw, dataPos, MND_CONSUMER_RESERVE_SIZE, CM_DECODE_OVER); if (tDecodeSMqConsumerObj(buf, pConsumer) == NULL) { + terrno = TSDB_CODE_OUT_OF_MEMORY; // TODO set correct error code goto CM_DECODE_OVER; } - tmsgUpdateDnodeEpSet(&pConsumer->ep); - terrno = TSDB_CODE_SUCCESS; + tmsgUpdateDnodeEpSet(&pConsumer->ep); CM_DECODE_OVER: taosMemoryFreeClear(buf); if (terrno != TSDB_CODE_SUCCESS) { - mError("consumer:%" PRId64 ", failed to decode from raw:%p since %s", pConsumer == NULL ? 0 : pConsumer->consumerId, - pRaw, terrstr()); + mError("consumer:0x%" PRIx64 " failed to decode from raw:%p since %s", + pConsumer == NULL ? 0 : pConsumer->consumerId, pRaw, terrstr()); taosMemoryFreeClear(pRow); - return NULL; } return pRow; } static int32_t mndConsumerActionInsert(SSdb *pSdb, SMqConsumerObj *pConsumer) { - mTrace("consumer:%" PRId64 ", perform insert action", pConsumer->consumerId); + mDebug("consumer:0x%" PRIx64 " cgroup:%s status:%d(%s) epoch:%d load from sdb, perform insert action", + pConsumer->consumerId, pConsumer->cgroup, pConsumer->status, mndConsumerStatusName(pConsumer->status), + pConsumer->epoch); pConsumer->subscribeTime = pConsumer->upTime; return 0; } static int32_t mndConsumerActionDelete(SSdb *pSdb, SMqConsumerObj *pConsumer) { - mTrace("consumer:%" PRId64 ", perform delete action", pConsumer->consumerId); + mDebug("consumer:0x%" PRIx64 " perform delete action, status:%s", pConsumer->consumerId, + mndConsumerStatusName(pConsumer->status)); tDeleteSMqConsumerObj(pConsumer); return 0; } static int32_t mndConsumerActionUpdate(SSdb *pSdb, SMqConsumerObj *pOldConsumer, SMqConsumerObj *pNewConsumer) { - mTrace("consumer:%" PRId64 ", perform update action", pOldConsumer->consumerId); + mDebug("consumer:0x%" PRIx64 " perform update action, update type:%d, subscribe-time:%" PRId64 ", uptime:%" PRId64, + pOldConsumer->consumerId, pNewConsumer->updateType, pOldConsumer->subscribeTime, pOldConsumer->upTime); taosWLockLatch(&pOldConsumer->lock); @@ -808,20 +865,24 @@ static int32_t mndConsumerActionUpdate(SSdb *pSdb, SMqConsumerObj *pOldConsumer, int32_t sz = taosArrayGetSize(pOldConsumer->currentTopics); /*pOldConsumer->rebRemovedTopics = taosArrayInit(sz, sizeof(void *));*/ for (int32_t i = 0; i < sz; i++) { - char *topic = strdup(taosArrayGetP(pOldConsumer->currentTopics, i)); + char *topic = taosStrdup(taosArrayGetP(pOldConsumer->currentTopics, i)); taosArrayPush(pOldConsumer->rebRemovedTopics, &topic); } pOldConsumer->rebalanceTime = pNewConsumer->upTime; + int32_t status = pOldConsumer->status; pOldConsumer->status = MQ_CONSUMER_STATUS__LOST; + mDebug("consumer:0x%" PRIx64 " state %s -> %s, reb-time:%" PRId64 ", reb-removed-topics:%d", + pOldConsumer->consumerId, mndConsumerStatusName(status), mndConsumerStatusName(pOldConsumer->status), + pOldConsumer->rebalanceTime, (int)taosArrayGetSize(pOldConsumer->rebRemovedTopics)); } else if (pNewConsumer->updateType == CONSUMER_UPDATE__RECOVER) { /*A(taosArrayGetSize(pOldConsumer->currentTopics) == 0);*/ /*A(taosArrayGetSize(pOldConsumer->rebNewTopics) == 0);*/ int32_t sz = taosArrayGetSize(pOldConsumer->assignedTopics); for (int32_t i = 0; i < sz; i++) { - char *topic = strdup(taosArrayGetP(pOldConsumer->assignedTopics, i)); + char *topic = taosStrdup(taosArrayGetP(pOldConsumer->assignedTopics, i)); taosArrayPush(pOldConsumer->rebNewTopics, &topic); } @@ -837,12 +898,13 @@ static int32_t mndConsumerActionUpdate(SSdb *pSdb, SMqConsumerObj *pOldConsumer, /*A(taosArrayGetSize(pNewConsumer->rebNewTopics) == 1);*/ /*A(taosArrayGetSize(pNewConsumer->rebRemovedTopics) == 0);*/ - char *addedTopic = strdup(taosArrayGetP(pNewConsumer->rebNewTopics, 0)); + char *addedTopic = taosStrdup(taosArrayGetP(pNewConsumer->rebNewTopics, 0)); // not exist in current topic bool existing = false; #if 1 - for (int32_t i = 0; i < taosArrayGetSize(pOldConsumer->currentTopics); i++) { + int32_t numOfExistedTopics = taosArrayGetSize(pOldConsumer->currentTopics); + for (int32_t i = 0; i < numOfExistedTopics; i++) { char *topic = taosArrayGetP(pOldConsumer->currentTopics, i); if (strcmp(topic, addedTopic) == 0) { existing = true; @@ -864,30 +926,33 @@ static int32_t mndConsumerActionUpdate(SSdb *pSdb, SMqConsumerObj *pOldConsumer, if (!existing) { taosArrayPush(pOldConsumer->currentTopics, &addedTopic); taosArraySort(pOldConsumer->currentTopics, taosArrayCompareString); + } else { + taosMemoryFree(addedTopic); } // set status + int32_t status = pOldConsumer->status; if (taosArrayGetSize(pOldConsumer->rebNewTopics) == 0 && taosArrayGetSize(pOldConsumer->rebRemovedTopics) == 0) { - if (pOldConsumer->status == MQ_CONSUMER_STATUS__MODIFY || - pOldConsumer->status == MQ_CONSUMER_STATUS__MODIFY_IN_REB) { + if (status == MQ_CONSUMER_STATUS__MODIFY || status == MQ_CONSUMER_STATUS__MODIFY_IN_REB) { pOldConsumer->status = MQ_CONSUMER_STATUS__READY; - } else if (pOldConsumer->status == MQ_CONSUMER_STATUS__LOST_IN_REB || - pOldConsumer->status == MQ_CONSUMER_STATUS__LOST) { + } else if (status == MQ_CONSUMER_STATUS__LOST_IN_REB || status == MQ_CONSUMER_STATUS__LOST) { pOldConsumer->status = MQ_CONSUMER_STATUS__LOST_REBD; } } else { - if (pOldConsumer->status == MQ_CONSUMER_STATUS__MODIFY || - pOldConsumer->status == MQ_CONSUMER_STATUS__MODIFY_IN_REB) { + if (status == MQ_CONSUMER_STATUS__MODIFY || status == MQ_CONSUMER_STATUS__MODIFY_IN_REB) { pOldConsumer->status = MQ_CONSUMER_STATUS__MODIFY_IN_REB; - } else if (pOldConsumer->status == MQ_CONSUMER_STATUS__LOST || - pOldConsumer->status == MQ_CONSUMER_STATUS__LOST_IN_REB) { + } else if (status == MQ_CONSUMER_STATUS__LOST || status == MQ_CONSUMER_STATUS__LOST_IN_REB) { pOldConsumer->status = MQ_CONSUMER_STATUS__LOST_IN_REB; } } + // the re-balance is triggered when the new consumer is launched. pOldConsumer->rebalanceTime = pNewConsumer->upTime; atomic_add_fetch_32(&pOldConsumer->epoch, 1); + mDebug("consumer:0x%" PRIx64 " state %s -> %s, new epoch:%d, reb-time:%" PRId64 ", current topics:%d", + pOldConsumer->consumerId, mndConsumerStatusName(status), mndConsumerStatusName(pOldConsumer->status), + pOldConsumer->epoch, pOldConsumer->rebalanceTime, (int)taosArrayGetSize(pOldConsumer->currentTopics)); } else if (pNewConsumer->updateType == CONSUMER_UPDATE__REMOVE) { /*A(taosArrayGetSize(pNewConsumer->rebNewTopics) == 0);*/ /*A(taosArrayGetSize(pNewConsumer->rebRemovedTopics) == 1);*/ @@ -926,27 +991,27 @@ static int32_t mndConsumerActionUpdate(SSdb *pSdb, SMqConsumerObj *pOldConsumer, /*A(i < sz);*/ // set status + int32_t status = pOldConsumer->status; if (taosArrayGetSize(pOldConsumer->rebNewTopics) == 0 && taosArrayGetSize(pOldConsumer->rebRemovedTopics) == 0) { - if (pOldConsumer->status == MQ_CONSUMER_STATUS__MODIFY || - pOldConsumer->status == MQ_CONSUMER_STATUS__MODIFY_IN_REB) { + if (status == MQ_CONSUMER_STATUS__MODIFY || status == MQ_CONSUMER_STATUS__MODIFY_IN_REB) { pOldConsumer->status = MQ_CONSUMER_STATUS__READY; - } else if (pOldConsumer->status == MQ_CONSUMER_STATUS__LOST_IN_REB || - pOldConsumer->status == MQ_CONSUMER_STATUS__LOST) { + } else if (status == MQ_CONSUMER_STATUS__LOST_IN_REB || status == MQ_CONSUMER_STATUS__LOST) { pOldConsumer->status = MQ_CONSUMER_STATUS__LOST_REBD; } } else { - if (pOldConsumer->status == MQ_CONSUMER_STATUS__MODIFY || - pOldConsumer->status == MQ_CONSUMER_STATUS__MODIFY_IN_REB) { + if (status == MQ_CONSUMER_STATUS__MODIFY || status == MQ_CONSUMER_STATUS__MODIFY_IN_REB) { pOldConsumer->status = MQ_CONSUMER_STATUS__MODIFY_IN_REB; - } else if (pOldConsumer->status == MQ_CONSUMER_STATUS__LOST || - pOldConsumer->status == MQ_CONSUMER_STATUS__LOST_IN_REB) { + } else if (status == MQ_CONSUMER_STATUS__LOST || status == MQ_CONSUMER_STATUS__LOST_IN_REB) { pOldConsumer->status = MQ_CONSUMER_STATUS__LOST_IN_REB; } } pOldConsumer->rebalanceTime = pNewConsumer->upTime; - atomic_add_fetch_32(&pOldConsumer->epoch, 1); + + mDebug("consumer:0x%" PRIx64 " state %s -> %s, new epoch:%d, reb-time:%" PRId64 ", current topics:%d", + pOldConsumer->consumerId, mndConsumerStatusName(status), mndConsumerStatusName(pOldConsumer->status), + pOldConsumer->epoch, pOldConsumer->rebalanceTime, (int)taosArrayGetSize(pOldConsumer->currentTopics)); } taosWUnLockLatch(&pOldConsumer->lock); @@ -975,16 +1040,19 @@ static int32_t mndRetrieveConsumer(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock * while (numOfRows < rowsCapacity) { pShow->pIter = sdbFetch(pSdb, SDB_CONSUMER, pShow->pIter, (void **)&pConsumer); - if (pShow->pIter == NULL) break; + if (pShow->pIter == NULL) { + break; + } + if (taosArrayGetSize(pConsumer->assignedTopics) == 0) { - mDebug("showing consumer %" PRId64 " no assigned topic, skip", pConsumer->consumerId); + mDebug("showing consumer:0x%" PRIx64 " no assigned topic, skip", pConsumer->consumerId); sdbRelease(pSdb, pConsumer); continue; } taosRLockLatch(&pConsumer->lock); - mDebug("showing consumer %" PRId64, pConsumer->consumerId); + mDebug("showing consumer:0x%" PRIx64, pConsumer->consumerId); int32_t topicSz = taosArrayGetSize(pConsumer->assignedTopics); bool hasTopic = true; @@ -1003,56 +1071,55 @@ static int32_t mndRetrieveConsumer(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock * // consumer id pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pConsumer->consumerId, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pConsumer->consumerId, false); // consumer group char cgroup[TSDB_CGROUP_LEN + VARSTR_HEADER_SIZE] = {0}; tstrncpy(varDataVal(cgroup), pConsumer->cgroup, TSDB_CGROUP_LEN); varDataSetLen(cgroup, strlen(varDataVal(cgroup))); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)cgroup, false); + colDataSetVal(pColInfo, numOfRows, (const char *)cgroup, false); // client id char clientId[256 + VARSTR_HEADER_SIZE] = {0}; tstrncpy(varDataVal(clientId), pConsumer->clientId, 256); varDataSetLen(clientId, strlen(varDataVal(clientId))); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)clientId, false); + colDataSetVal(pColInfo, numOfRows, (const char *)clientId, false); // status char status[20 + VARSTR_HEADER_SIZE] = {0}; tstrncpy(varDataVal(status), mndConsumerStatusName(pConsumer->status), 20); varDataSetLen(status, strlen(varDataVal(status))); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)status, false); + colDataSetVal(pColInfo, numOfRows, (const char *)status, false); // one subscribed topic pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); if (hasTopic) { char topic[TSDB_TOPIC_FNAME_LEN + VARSTR_HEADER_SIZE] = {0}; const char *topicName = mndTopicGetShowName(taosArrayGetP(pConsumer->assignedTopics, i)); - tstrncpy(varDataVal(topic), topicName, TSDB_TOPIC_FNAME_LEN); - varDataSetLen(topic, strlen(varDataVal(topic))); - colDataAppend(pColInfo, numOfRows, (const char *)topic, false); + STR_TO_VARSTR(topic, topicName); + colDataSetVal(pColInfo, numOfRows, (const char *)topic, false); } else { - colDataAppend(pColInfo, numOfRows, NULL, true); + colDataSetVal(pColInfo, numOfRows, NULL, true); } // end point /*pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);*/ - /*colDataAppend(pColInfo, numOfRows, (const char *)&pConsumer->ep, true);*/ + /*colDataSetVal(pColInfo, numOfRows, (const char *)&pConsumer->ep, true);*/ // up time pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pConsumer->upTime, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pConsumer->upTime, false); // subscribe time pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pConsumer->subscribeTime, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pConsumer->subscribeTime, false); // rebalance time pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pConsumer->rebalanceTime, pConsumer->rebalanceTime == 0); + colDataSetVal(pColInfo, numOfRows, (const char *)&pConsumer->rebalanceTime, pConsumer->rebalanceTime == 0); numOfRows++; } diff --git a/source/dnode/mnode/impl/src/mndDb.c b/source/dnode/mnode/impl/src/mndDb.c index 2f7fa26a87..3efd8fb249 100644 --- a/source/dnode/mnode/impl/src/mndDb.c +++ b/source/dnode/mnode/impl/src/mndDb.c @@ -1039,13 +1039,23 @@ static int32_t mndBuildDropDbRsp(SDbObj *pDb, int32_t *pRspLen, void **ppRsp, bo static int32_t mndDropDb(SMnode *pMnode, SRpcMsg *pReq, SDbObj *pDb) { int32_t code = -1; - STrans *pTrans = mndTransCreate(pMnode, TRN_POLICY_RETRY, TRN_CONFLICT_DB, pReq, "drop-db"); - if (pTrans == NULL) goto _OVER; - mInfo("trans:%d, used to drop db:%s", pTrans->id, pDb->name); + STrans *pTrans = mndTransCreate(pMnode, TRN_POLICY_RETRY, TRN_CONFLICT_DB, pReq, "drop-db"); + if (pTrans == NULL) { + goto _OVER; + } + + mInfo("trans:%d start to drop db:%s", pTrans->id, pDb->name); + mndTransSetDbName(pTrans, pDb->name, NULL); - if (mndTrancCheckConflict(pMnode, pTrans) != 0) goto _OVER; - if (mndCheckTopicExist(pMnode, pDb) < 0) goto _OVER; + if (mndTrancCheckConflict(pMnode, pTrans) != 0) { + goto _OVER; + } + + if (mndTopicExistsForDb(pMnode, pDb)) { + terrno = TSDB_CODE_MND_TOPIC_MUST_BE_DELETED; + goto _OVER; + } if (mndSetDropDbRedoLogs(pMnode, pTrans, pDb) != 0) goto _OVER; if (mndSetDropDbCommitLogs(pMnode, pTrans, pDb) != 0) goto _OVER; @@ -1097,10 +1107,12 @@ static int32_t mndProcessDropDbReq(SRpcMsg *pReq) { } code = mndDropDb(pMnode, pReq, pDb); - if (code == 0) code = TSDB_CODE_ACTION_IN_PROGRESS; + if (code == TSDB_CODE_SUCCESS) { + code = TSDB_CODE_ACTION_IN_PROGRESS; + } _OVER: - if (code != 0 && code != TSDB_CODE_ACTION_IN_PROGRESS) { + if (code != TSDB_CODE_SUCCESS && code != TSDB_CODE_ACTION_IN_PROGRESS) { mError("db:%s, failed to drop since %s", dropReq.db, terrstr()); } @@ -1703,46 +1715,46 @@ static void mndDumpDbInfoData(SMnode *pMnode, SSDataBlock *pBlock, SDbObj *pDb, for (int32_t i = 0; i < pShow->numOfColumns; ++i) { SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, i); if (i == 0) { - colDataAppend(pColInfo, rows, buf, false); + colDataSetVal(pColInfo, rows, buf, false); } else if (i == 1) { - colDataAppend(pColInfo, rows, (const char *)&pDb->createdTime, false); + colDataSetVal(pColInfo, rows, (const char *)&pDb->createdTime, false); } else if (i == 3) { - colDataAppend(pColInfo, rows, (const char *)&numOfTables, false); + colDataSetVal(pColInfo, rows, (const char *)&numOfTables, false); } else if (i == 14) { - colDataAppend(pColInfo, rows, precVstr, false); + colDataSetVal(pColInfo, rows, precVstr, false); } else if (i == 15) { - colDataAppend(pColInfo, rows, statusVstr, false); + colDataSetVal(pColInfo, rows, statusVstr, false); } else { - colDataAppendNULL(pColInfo, rows); + colDataSetNULL(pColInfo, rows); } } } else { SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, buf, false); + colDataSetVal(pColInfo, rows, buf, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)&pDb->createdTime, false); + colDataSetVal(pColInfo, rows, (const char *)&pDb->createdTime, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)&pDb->cfg.numOfVgroups, false); + colDataSetVal(pColInfo, rows, (const char *)&pDb->cfg.numOfVgroups, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)&numOfTables, false); + colDataSetVal(pColInfo, rows, (const char *)&numOfTables, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)&pDb->cfg.replications, false); + colDataSetVal(pColInfo, rows, (const char *)&pDb->cfg.replications, false); const char *strictStr = pDb->cfg.strict ? "on" : "off"; char strictVstr[24] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(strictVstr, strictStr, 24); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)strictVstr, false); + colDataSetVal(pColInfo, rows, (const char *)strictVstr, false); char durationVstr[128] = {0}; int32_t len = sprintf(&durationVstr[VARSTR_HEADER_SIZE], "%dm", pDb->cfg.daysPerFile); varDataSetLen(durationVstr, len); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)durationVstr, false); + colDataSetVal(pColInfo, rows, (const char *)durationVstr, false); char keepVstr[128] = {0}; if (pDb->cfg.daysToKeep0 > pDb->cfg.daysToKeep1 || pDb->cfg.daysToKeep0 > pDb->cfg.daysToKeep2) { @@ -1754,86 +1766,86 @@ static void mndDumpDbInfoData(SMnode *pMnode, SSDataBlock *pBlock, SDbObj *pDb, } varDataSetLen(keepVstr, len); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)keepVstr, false); + colDataSetVal(pColInfo, rows, (const char *)keepVstr, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)&pDb->cfg.buffer, false); + colDataSetVal(pColInfo, rows, (const char *)&pDb->cfg.buffer, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)&pDb->cfg.pageSize, false); + colDataSetVal(pColInfo, rows, (const char *)&pDb->cfg.pageSize, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)&pDb->cfg.pages, false); + colDataSetVal(pColInfo, rows, (const char *)&pDb->cfg.pages, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)&pDb->cfg.minRows, false); + colDataSetVal(pColInfo, rows, (const char *)&pDb->cfg.minRows, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)&pDb->cfg.maxRows, false); + colDataSetVal(pColInfo, rows, (const char *)&pDb->cfg.maxRows, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)&pDb->cfg.compression, false); + colDataSetVal(pColInfo, rows, (const char *)&pDb->cfg.compression, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)precVstr, false); + colDataSetVal(pColInfo, rows, (const char *)precVstr, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)statusVstr, false); + colDataSetVal(pColInfo, rows, (const char *)statusVstr, false); char *rentensionVstr = buildRetension(pDb->cfg.pRetensions); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); if (rentensionVstr == NULL) { - colDataAppendNULL(pColInfo, rows); + colDataSetNULL(pColInfo, rows); } else { - colDataAppend(pColInfo, rows, (const char *)rentensionVstr, false); + colDataSetVal(pColInfo, rows, (const char *)rentensionVstr, false); taosMemoryFree(rentensionVstr); } pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)&pDb->cfg.numOfStables, false); + colDataSetVal(pColInfo, rows, (const char *)&pDb->cfg.numOfStables, false); const char *cacheModelStr = getCacheModelStr(pDb->cfg.cacheLast); char cacheModelVstr[24] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(cacheModelVstr, cacheModelStr, 24); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)cacheModelVstr, false); + colDataSetVal(pColInfo, rows, (const char *)cacheModelVstr, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)&pDb->cfg.cacheLastSize, false); + colDataSetVal(pColInfo, rows, (const char *)&pDb->cfg.cacheLastSize, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)&pDb->cfg.walLevel, false); + colDataSetVal(pColInfo, rows, (const char *)&pDb->cfg.walLevel, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)&pDb->cfg.walFsyncPeriod, false); + colDataSetVal(pColInfo, rows, (const char *)&pDb->cfg.walFsyncPeriod, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)&pDb->cfg.walRetentionPeriod, false); + colDataSetVal(pColInfo, rows, (const char *)&pDb->cfg.walRetentionPeriod, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)&pDb->cfg.walRetentionSize, false); + colDataSetVal(pColInfo, rows, (const char *)&pDb->cfg.walRetentionSize, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)&pDb->cfg.walRollPeriod, false); + colDataSetVal(pColInfo, rows, (const char *)&pDb->cfg.walRollPeriod, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)&pDb->cfg.walSegmentSize, false); + colDataSetVal(pColInfo, rows, (const char *)&pDb->cfg.walSegmentSize, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)&pDb->cfg.sstTrigger, false); + colDataSetVal(pColInfo, rows, (const char *)&pDb->cfg.sstTrigger, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); int16_t hashPrefix = pDb->cfg.hashPrefix; if (hashPrefix > 0) { hashPrefix = pDb->cfg.hashPrefix - strlen(pDb->name) - 1; } - colDataAppend(pColInfo, rows, (const char *)&hashPrefix, false); + colDataSetVal(pColInfo, rows, (const char *)&hashPrefix, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)&pDb->cfg.hashSuffix, false); + colDataSetVal(pColInfo, rows, (const char *)&pDb->cfg.hashSuffix, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, rows, (const char *)&pDb->cfg.tsdbPageSize, false); + colDataSetVal(pColInfo, rows, (const char *)&pDb->cfg.tsdbPageSize, false); } taosMemoryFree(buf); diff --git a/source/dnode/mnode/impl/src/mndDef.c b/source/dnode/mnode/impl/src/mndDef.c index 38001a97bb..fb81a764f1 100644 --- a/source/dnode/mnode/impl/src/mndDef.c +++ b/source/dnode/mnode/impl/src/mndDef.c @@ -181,7 +181,7 @@ SMqVgEp *tCloneSMqVgEp(const SMqVgEp *pVgEp) { SMqVgEp *pVgEpNew = taosMemoryMalloc(sizeof(SMqVgEp)); if (pVgEpNew == NULL) return NULL; pVgEpNew->vgId = pVgEp->vgId; - pVgEpNew->qmsg = strdup(pVgEp->qmsg); + pVgEpNew->qmsg = taosStrdup(pVgEp->qmsg); pVgEpNew->epSet = pVgEp->epSet; return pVgEpNew; } diff --git a/source/dnode/mnode/impl/src/mndDnode.c b/source/dnode/mnode/impl/src/mndDnode.c index 7f95774ea0..5dd1742e5e 100644 --- a/source/dnode/mnode/impl/src/mndDnode.c +++ b/source/dnode/mnode/impl/src/mndDnode.c @@ -1007,11 +1007,11 @@ static int32_t mndRetrieveConfigs(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *p STR_WITH_MAXSIZE_TO_VARSTR(buf, cfgOpts[i], TSDB_CONFIG_OPTION_LEN); SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)buf, false); + colDataSetVal(pColInfo, numOfRows, (const char *)buf, false); STR_WITH_MAXSIZE_TO_VARSTR(bufVal, cfgVals[i], TSDB_CONFIG_VALUE_LEN); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)bufVal, false); + colDataSetVal(pColInfo, numOfRows, (const char *)bufVal, false); numOfRows++; } @@ -1039,20 +1039,20 @@ static int32_t mndRetrieveDnodes(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pB cols = 0; SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pDnode->id, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pDnode->id, false); char buf[tListLen(pDnode->ep) + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(buf, pDnode->ep, pShow->pMeta->pSchemas[cols].bytes); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, buf, false); + colDataSetVal(pColInfo, numOfRows, buf, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); int16_t id = mndGetVnodesNum(pMnode, pDnode->id); - colDataAppend(pColInfo, numOfRows, (const char *)&id, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&id, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pDnode->numOfSupportVnodes, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pDnode->numOfSupportVnodes, false); const char *status = "ready"; if (objStatus == SDB_STATUS_CREATING) status = "creating"; @@ -1069,16 +1069,16 @@ static int32_t mndRetrieveDnodes(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pB char b1[16] = {0}; STR_TO_VARSTR(b1, status); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, b1, false); + colDataSetVal(pColInfo, numOfRows, b1, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pDnode->createdTime, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pDnode->createdTime, false); char *b = taosMemoryCalloc(VARSTR_HEADER_SIZE + strlen(offlineReason[pDnode->offlineReason]) + 1, 1); STR_TO_VARSTR(b, online ? "" : offlineReason[pDnode->offlineReason]); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, b, false); + colDataSetVal(pColInfo, numOfRows, b, false); taosMemoryFreeClear(b); numOfRows++; diff --git a/source/dnode/mnode/impl/src/mndDump.c b/source/dnode/mnode/impl/src/mndDump.c index 7d0f5742f8..44a7d49fff 100644 --- a/source/dnode/mnode/impl/src/mndDump.c +++ b/source/dnode/mnode/impl/src/mndDump.c @@ -629,7 +629,7 @@ void mndDumpSdb() { } taosWriteFile(pFile, pCont, contLen); taosWriteFile(pFile, "\n", 1); - taosFsyncFile(pFile); + UNUSED(taosFsyncFile(pFile)); taosCloseFile(&pFile); tjsonDelete(json); taosMemoryFree(pCont); diff --git a/source/dnode/mnode/impl/src/mndFunc.c b/source/dnode/mnode/impl/src/mndFunc.c index 244e6058d4..8d006f1029 100644 --- a/source/dnode/mnode/impl/src/mndFunc.c +++ b/source/dnode/mnode/impl/src/mndFunc.c @@ -511,39 +511,39 @@ static int32_t mndRetrieveFuncs(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBl STR_WITH_MAXSIZE_TO_VARSTR(b1, pFunc->name, pShow->pMeta->pSchemas[cols].bytes); SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)b1, false); + colDataSetVal(pColInfo, numOfRows, (const char *)b1, false); if (pFunc->pComment) { char *b2 = taosMemoryCalloc(1, pShow->pMeta->pSchemas[cols].bytes); STR_WITH_MAXSIZE_TO_VARSTR(b2, pFunc->pComment, pShow->pMeta->pSchemas[cols].bytes); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)b2, false); + colDataSetVal(pColInfo, numOfRows, (const char *)b2, false); } else { pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, NULL, true); + colDataSetVal(pColInfo, numOfRows, NULL, true); } int32_t isAgg = (pFunc->funcType == TSDB_FUNC_TYPE_AGGREGATE) ? 1 : 0; pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&isAgg, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&isAgg, false); char b3[TSDB_TYPE_STR_MAX_LEN + 1] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(b3, mnodeGenTypeStr(buf, TSDB_TYPE_STR_MAX_LEN, pFunc->outputType, pFunc->outputLen), pShow->pMeta->pSchemas[cols].bytes); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)b3, false); + colDataSetVal(pColInfo, numOfRows, (const char *)b3, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pFunc->createdTime, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pFunc->createdTime, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pFunc->codeSize, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pFunc->codeSize, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pFunc->bufSize, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pFunc->bufSize, false); numOfRows++; sdbRelease(pSdb, pFunc); diff --git a/source/dnode/mnode/impl/src/mndGrant.c b/source/dnode/mnode/impl/src/mndGrant.c index 42851bd16a..1b46e16961 100644 --- a/source/dnode/mnode/impl/src/mndGrant.c +++ b/source/dnode/mnode/impl/src/mndGrant.c @@ -29,85 +29,85 @@ static int32_t mndRetrieveGrant(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBl SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols); const char *src = "community"; STR_WITH_MAXSIZE_TO_VARSTR(tmp, src, 32); - colDataAppend(pColInfo, numOfRows, tmp, false); + colDataSetVal(pColInfo, numOfRows, tmp, false); cols++; pColInfo = taosArrayGet(pBlock->pDataBlock, cols); src = "unlimited"; STR_WITH_MAXSIZE_TO_VARSTR(tmp, src, 32); - colDataAppend(pColInfo, numOfRows, tmp, false); + colDataSetVal(pColInfo, numOfRows, tmp, false); cols++; pColInfo = taosArrayGet(pBlock->pDataBlock, cols); src = "false"; STR_WITH_MAXSIZE_TO_VARSTR(tmp, src, 32); - colDataAppend(pColInfo, numOfRows, tmp, false); + colDataSetVal(pColInfo, numOfRows, tmp, false); cols++; pColInfo = taosArrayGet(pBlock->pDataBlock, cols); src = "unlimited"; STR_WITH_MAXSIZE_TO_VARSTR(tmp, src, 32); - colDataAppend(pColInfo, numOfRows, tmp, false); + colDataSetVal(pColInfo, numOfRows, tmp, false); cols++; pColInfo = taosArrayGet(pBlock->pDataBlock, cols); src = "unlimited"; STR_WITH_MAXSIZE_TO_VARSTR(tmp, src, 32); - colDataAppend(pColInfo, numOfRows, tmp, false); + colDataSetVal(pColInfo, numOfRows, tmp, false); cols++; pColInfo = taosArrayGet(pBlock->pDataBlock, cols); src = "unlimited"; STR_WITH_MAXSIZE_TO_VARSTR(tmp, src, 32); - colDataAppend(pColInfo, numOfRows, tmp, false); + colDataSetVal(pColInfo, numOfRows, tmp, false); cols++; pColInfo = taosArrayGet(pBlock->pDataBlock, cols); src = "unlimited"; STR_WITH_MAXSIZE_TO_VARSTR(tmp, src, 32); - colDataAppend(pColInfo, numOfRows, tmp, false); + colDataSetVal(pColInfo, numOfRows, tmp, false); cols++; pColInfo = taosArrayGet(pBlock->pDataBlock, cols); src = "unlimited"; STR_WITH_MAXSIZE_TO_VARSTR(tmp, src, 32); - colDataAppend(pColInfo, numOfRows, tmp, false); + colDataSetVal(pColInfo, numOfRows, tmp, false); cols++; pColInfo = taosArrayGet(pBlock->pDataBlock, cols); src = "unlimited"; STR_WITH_MAXSIZE_TO_VARSTR(tmp, src, 32); - colDataAppend(pColInfo, numOfRows, tmp, false); + colDataSetVal(pColInfo, numOfRows, tmp, false); cols++; pColInfo = taosArrayGet(pBlock->pDataBlock, cols); src = "unlimited"; STR_WITH_MAXSIZE_TO_VARSTR(tmp, src, 32); - colDataAppend(pColInfo, numOfRows, tmp, false); + colDataSetVal(pColInfo, numOfRows, tmp, false); cols++; pColInfo = taosArrayGet(pBlock->pDataBlock, cols); src = "unlimited"; STR_WITH_MAXSIZE_TO_VARSTR(tmp, src, 32); - colDataAppend(pColInfo, numOfRows, tmp, false); + colDataSetVal(pColInfo, numOfRows, tmp, false); cols++; pColInfo = taosArrayGet(pBlock->pDataBlock, cols); src = "unlimited"; STR_WITH_MAXSIZE_TO_VARSTR(tmp, src, 32); - colDataAppend(pColInfo, numOfRows, tmp, false); + colDataSetVal(pColInfo, numOfRows, tmp, false); cols++; pColInfo = taosArrayGet(pBlock->pDataBlock, cols); src = "unlimited"; STR_WITH_MAXSIZE_TO_VARSTR(tmp, src, 32); - colDataAppend(pColInfo, numOfRows, tmp, false); + colDataSetVal(pColInfo, numOfRows, tmp, false); cols++; pColInfo = taosArrayGet(pBlock->pDataBlock, cols); src = "unlimited"; STR_WITH_MAXSIZE_TO_VARSTR(tmp, src, 32); - colDataAppend(pColInfo, numOfRows, tmp, false); + colDataSetVal(pColInfo, numOfRows, tmp, false); numOfRows++; } diff --git a/source/dnode/mnode/impl/src/mndIndex.c b/source/dnode/mnode/impl/src/mndIndex.c index 016f01b032..8782fd823f 100644 --- a/source/dnode/mnode/impl/src/mndIndex.c +++ b/source/dnode/mnode/impl/src/mndIndex.c @@ -638,7 +638,7 @@ static int32_t mndSetUpdateIdxStbCommitLogs(SMnode *pMnode, STrans *pTrans, SStb } int32_t mndAddIndexImpl(SMnode *pMnode, SRpcMsg *pReq, SDbObj *pDb, SStbObj *pStb, SIdxObj *pIdx) { // impl later - int32_t code = 0; + int32_t code = -1; SStbObj newStb = {0}; STrans *pTrans = mndTransCreate(pMnode, TRN_POLICY_RETRY, TRN_CONFLICT_DB_INSIDE, pReq, "create-stb-index"); if (pTrans == NULL) goto _OVER; @@ -670,6 +670,7 @@ _OVER: } static int32_t mndAddIndex(SMnode *pMnode, SRpcMsg *pReq, SCreateTagIndexReq *req, SDbObj *pDb, SStbObj *pStb) { + int32_t code = -1; SIdxObj idxObj = {0}; memcpy(idxObj.name, req->idxName, TSDB_TABLE_FNAME_LEN); memcpy(idxObj.stb, pStb->name, TSDB_TABLE_FNAME_LEN); @@ -681,21 +682,6 @@ static int32_t mndAddIndex(SMnode *pMnode, SRpcMsg *pReq, SCreateTagIndexReq *re idxObj.stbUid = pStb->uid; idxObj.dbUid = pStb->dbUid; - int32_t code = -1; - // SField *pField0 = NULL; - - // SStbObj stbObj = {0}; - // SStbObj *pNew = &stbObj; - - // taosRLockLatch(&pOld->lock); - // memcpy(&stbObj, pOld, sizeof(SStbObj)); - // taosRUnLockLatch(&pOld->lock); - - // stbObj.pColumns = NULL; - // stbObj.pTags = NULL; - // stbObj.updateTime = taosGetTimestampMs(); - // stbObj.lock = 0; - int32_t tag = mndFindSuperTableTagId(pStb, req->colName); if (tag < 0) { terrno = TSDB_CODE_MND_TAG_NOT_EXIST; diff --git a/source/dnode/mnode/impl/src/mndMain.c b/source/dnode/mnode/impl/src/mndMain.c index 75411f6089..53a5548b2f 100644 --- a/source/dnode/mnode/impl/src/mndMain.c +++ b/source/dnode/mnode/impl/src/mndMain.c @@ -133,6 +133,7 @@ static void mndCalMqRebalance(SMnode *pMnode) { } } +#if 0 static void mndStreamCheckpointTick(SMnode *pMnode, int64_t sec) { int32_t contLen = 0; void *pReq = mndBuildCheckpointTickMsg(&contLen, sec); @@ -145,6 +146,7 @@ static void mndStreamCheckpointTick(SMnode *pMnode, int64_t sec) { tmsgPutToQueue(&pMnode->msgCb, READ_QUEUE, &rpcMsg); } } +#endif static void mndPullupTelem(SMnode *pMnode) { mTrace("pullup telem msg"); @@ -320,7 +322,7 @@ static void mndCleanupTimer(SMnode *pMnode) { } static int32_t mndCreateDir(SMnode *pMnode, const char *path) { - pMnode->path = strdup(path); + pMnode->path = taosStrdup(path); if (pMnode->path == NULL) { terrno = TSDB_CODE_OUT_OF_MEMORY; return -1; @@ -714,7 +716,7 @@ int32_t mndProcessRpcMsg(SRpcMsg *pMsg) { } else if (code == 0) { mGTrace("msg:%p, successfully processed", pMsg); } else { - mGError("msg:%p, failed to process since %s, app:%p type:%s", pMsg, terrstr(), pMsg->info.ahandle, + mGError("msg:%p, failed to process since %s, app:%p type:%s", pMsg, tstrerror(code), pMsg->info.ahandle, TMSG_INFO(pMsg->msgType)); } diff --git a/source/dnode/mnode/impl/src/mndMnode.c b/source/dnode/mnode/impl/src/mndMnode.c index add32fd335..aada00296e 100644 --- a/source/dnode/mnode/impl/src/mndMnode.c +++ b/source/dnode/mnode/impl/src/mndMnode.c @@ -608,13 +608,13 @@ static int32_t mndRetrieveMnodes(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pB cols = 0; SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pObj->id, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pObj->id, false); char b1[TSDB_EP_LEN + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(b1, pObj->pDnode->ep, TSDB_EP_LEN + VARSTR_HEADER_SIZE); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, b1, false); + colDataSetVal(pColInfo, numOfRows, b1, false); char role[20] = "offline"; if (pObj->id == pMnode->selfDnodeId) { @@ -630,7 +630,7 @@ static int32_t mndRetrieveMnodes(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pB char b2[12 + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(b2, role, pShow->pMeta->pSchemas[cols].bytes); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)b2, false); + colDataSetVal(pColInfo, numOfRows, (const char *)b2, false); const char *status = "ready"; if (objStatus == SDB_STATUS_CREATING) status = "creating"; @@ -639,10 +639,10 @@ static int32_t mndRetrieveMnodes(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pB char b3[9 + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(b3, status, pShow->pMeta->pSchemas[cols].bytes); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)b3, false); + colDataSetVal(pColInfo, numOfRows, (const char *)b3, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pObj->createdTime, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pObj->createdTime, false); numOfRows++; sdbRelease(pSdb, pObj); diff --git a/source/dnode/mnode/impl/src/mndProfile.c b/source/dnode/mnode/impl/src/mndProfile.c index ffc357b2e8..41dc57f32e 100644 --- a/source/dnode/mnode/impl/src/mndProfile.c +++ b/source/dnode/mnode/impl/src/mndProfile.c @@ -709,32 +709,32 @@ static int32_t mndRetrieveConns(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBl cols = 0; SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pConn->id, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pConn->id, false); char user[TSDB_USER_LEN + VARSTR_HEADER_SIZE] = {0}; STR_TO_VARSTR(user, pConn->user); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)user, false); + colDataSetVal(pColInfo, numOfRows, (const char *)user, false); char app[TSDB_APP_NAME_LEN + VARSTR_HEADER_SIZE]; STR_TO_VARSTR(app, pConn->app); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)app, false); + colDataSetVal(pColInfo, numOfRows, (const char *)app, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pConn->pid, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pConn->pid, false); char endpoint[TSDB_IPv4ADDR_LEN + 6 + VARSTR_HEADER_SIZE] = {0}; sprintf(&endpoint[VARSTR_HEADER_SIZE], "%s:%d", taosIpStr(pConn->ip), pConn->port); varDataLen(endpoint) = strlen(&endpoint[VARSTR_HEADER_SIZE]); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)endpoint, false); + colDataSetVal(pColInfo, numOfRows, (const char *)endpoint, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pConn->loginTimeMs, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pConn->loginTimeMs, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pConn->lastAccessTimeMs, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pConn->lastAccessTimeMs, false); numOfRows++; } @@ -777,44 +777,44 @@ static int32_t mndRetrieveQueries(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *p sprintf(&queryId[VARSTR_HEADER_SIZE], "%x:%" PRIx64, pConn->id, pQuery->reqRid); varDataLen(queryId) = strlen(&queryId[VARSTR_HEADER_SIZE]); SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)queryId, false); + colDataSetVal(pColInfo, numOfRows, (const char *)queryId, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pQuery->queryId, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pQuery->queryId, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pConn->id, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pConn->id, false); char app[TSDB_APP_NAME_LEN + VARSTR_HEADER_SIZE]; STR_TO_VARSTR(app, pConn->app); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)app, false); + colDataSetVal(pColInfo, numOfRows, (const char *)app, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pConn->pid, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pConn->pid, false); char user[TSDB_USER_LEN + VARSTR_HEADER_SIZE] = {0}; STR_TO_VARSTR(user, pConn->user); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)user, false); + colDataSetVal(pColInfo, numOfRows, (const char *)user, false); char endpoint[TSDB_IPv4ADDR_LEN + 6 + VARSTR_HEADER_SIZE] = {0}; sprintf(&endpoint[VARSTR_HEADER_SIZE], "%s:%d", taosIpStr(pConn->ip), pConn->port); varDataLen(endpoint) = strlen(&endpoint[VARSTR_HEADER_SIZE]); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)endpoint, false); + colDataSetVal(pColInfo, numOfRows, (const char *)endpoint, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pQuery->stime, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pQuery->stime, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pQuery->useconds, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pQuery->useconds, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pQuery->stableQuery, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pQuery->stableQuery, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pQuery->subPlanNum, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pQuery->subPlanNum, false); char subStatus[TSDB_SHOW_SUBQUERY_LEN + VARSTR_HEADER_SIZE] = {0}; int32_t strSize = sizeof(subStatus); @@ -828,12 +828,12 @@ static int32_t mndRetrieveQueries(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *p } varDataLen(subStatus) = strlen(&subStatus[VARSTR_HEADER_SIZE]); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, subStatus, false); + colDataSetVal(pColInfo, numOfRows, subStatus, false); char sql[TSDB_SHOW_SQL_LEN + VARSTR_HEADER_SIZE] = {0}; STR_TO_VARSTR(sql, pQuery->sql); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)sql, false); + colDataSetVal(pColInfo, numOfRows, (const char *)sql, false); numOfRows++; } @@ -867,55 +867,55 @@ static int32_t mndRetrieveApps(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBlo cols = 0; SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pApp->appId, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pApp->appId, false); char ip[TSDB_IPv4ADDR_LEN + 6 + VARSTR_HEADER_SIZE] = {0}; sprintf(&ip[VARSTR_HEADER_SIZE], "%s", taosIpStr(pApp->ip)); varDataLen(ip) = strlen(&ip[VARSTR_HEADER_SIZE]); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)ip, false); + colDataSetVal(pColInfo, numOfRows, (const char *)ip, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pApp->pid, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pApp->pid, false); char name[TSDB_APP_NAME_LEN + 6 + VARSTR_HEADER_SIZE] = {0}; sprintf(&name[VARSTR_HEADER_SIZE], "%s", pApp->name); varDataLen(name) = strlen(&name[VARSTR_HEADER_SIZE]); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)name, false); + colDataSetVal(pColInfo, numOfRows, (const char *)name, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pApp->startTime, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pApp->startTime, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pApp->summary.numOfInsertsReq, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pApp->summary.numOfInsertsReq, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pApp->summary.numOfInsertRows, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pApp->summary.numOfInsertRows, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pApp->summary.insertElapsedTime, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pApp->summary.insertElapsedTime, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pApp->summary.insertBytes, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pApp->summary.insertBytes, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pApp->summary.fetchBytes, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pApp->summary.fetchBytes, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pApp->summary.queryElapsedTime, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pApp->summary.queryElapsedTime, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pApp->summary.numOfSlowQueries, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pApp->summary.numOfSlowQueries, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pApp->summary.totalRequests, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pApp->summary.totalRequests, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pApp->summary.currentRequests, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pApp->summary.currentRequests, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pApp->lastAccessTimeMs, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pApp->lastAccessTimeMs, false); numOfRows++; } diff --git a/source/dnode/mnode/impl/src/mndQnode.c b/source/dnode/mnode/impl/src/mndQnode.c index 28a5dee2db..a8b2d5f4bb 100644 --- a/source/dnode/mnode/impl/src/mndQnode.c +++ b/source/dnode/mnode/impl/src/mndQnode.c @@ -507,15 +507,15 @@ static int32_t mndRetrieveQnodes(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pB cols = 0; SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pObj->id, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pObj->id, false); char ep[TSDB_EP_LEN + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(ep, pObj->pDnode->ep, pShow->pMeta->pSchemas[cols].bytes); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)ep, false); + colDataSetVal(pColInfo, numOfRows, (const char *)ep, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pObj->createdTime, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pObj->createdTime, false); numOfRows++; sdbRelease(pSdb, pObj); diff --git a/source/dnode/mnode/impl/src/mndScheduler.c b/source/dnode/mnode/impl/src/mndScheduler.c index bdef8000bd..39ee443e51 100644 --- a/source/dnode/mnode/impl/src/mndScheduler.c +++ b/source/dnode/mnode/impl/src/mndScheduler.c @@ -529,7 +529,7 @@ int32_t mndSchedInitSubEp(SMnode* pMnode, const SMqTopicObj* pTopic, SMqSubscrib SSdb* pSdb = pMnode->pSdb; SVgObj* pVgroup = NULL; SQueryPlan* pPlan = NULL; - SSubplan* plan = NULL; + SSubplan* pSubplan = NULL; if (pTopic->subType == TOPIC_SUB_TYPE__COLUMN) { pPlan = qStringToQueryPlan(pTopic->physicalPlan); @@ -545,21 +545,25 @@ int32_t mndSchedInitSubEp(SMnode* pMnode, const SMqTopicObj* pTopic, SMqSubscrib return -1; } - SNodeListNode* inner = (SNodeListNode*)nodesListGetNode(pPlan->pSubplans, 0); + SNodeListNode* pNodeListNode = (SNodeListNode*)nodesListGetNode(pPlan->pSubplans, 0); - int32_t opNum = LIST_LENGTH(inner->pNodeList); + int32_t opNum = LIST_LENGTH(pNodeListNode->pNodeList); if (opNum != 1) { qDestroyQueryPlan(pPlan); terrno = TSDB_CODE_MND_INVALID_TOPIC_QUERY; return -1; } - plan = (SSubplan*)nodesListGetNode(inner->pNodeList, 0); + + pSubplan = (SSubplan*)nodesListGetNode(pNodeListNode->pNodeList, 0); } void* pIter = NULL; while (1) { pIter = sdbFetch(pSdb, SDB_VGROUP, pIter, (void**)&pVgroup); - if (pIter == NULL) break; + if (pIter == NULL) { + break; + } + if (!mndVgroupInDb(pVgroup, pTopic->dbUid)) { sdbRelease(pSdb, pVgroup); continue; @@ -572,28 +576,27 @@ int32_t mndSchedInitSubEp(SMnode* pMnode, const SMqTopicObj* pTopic, SMqSubscrib pVgEp->vgId = pVgroup->vgId; taosArrayPush(pSub->unassignedVgs, &pVgEp); - mDebug("init subscription %s, assign vg: %d", pSub->key, pVgEp->vgId); + mDebug("init subscription %s for topic:%s assign vgId:%d", pSub->key, pTopic->name, pVgEp->vgId); if (pTopic->subType == TOPIC_SUB_TYPE__COLUMN) { int32_t msgLen; - plan->execNode.epSet = pVgEp->epSet; - plan->execNode.nodeId = pVgEp->vgId; + pSubplan->execNode.epSet = pVgEp->epSet; + pSubplan->execNode.nodeId = pVgEp->vgId; - if (qSubPlanToString(plan, &pVgEp->qmsg, &msgLen) < 0) { + if (qSubPlanToString(pSubplan, &pVgEp->qmsg, &msgLen) < 0) { sdbRelease(pSdb, pVgroup); qDestroyQueryPlan(pPlan); terrno = TSDB_CODE_QRY_INVALID_INPUT; return -1; } } else { - pVgEp->qmsg = strdup(""); + pVgEp->qmsg = taosStrdup(""); } sdbRelease(pSdb, pVgroup); } qDestroyQueryPlan(pPlan); - return 0; } diff --git a/source/dnode/mnode/impl/src/mndSma.c b/source/dnode/mnode/impl/src/mndSma.c index c10851cfad..09aef2cd96 100644 --- a/source/dnode/mnode/impl/src/mndSma.c +++ b/source/dnode/mnode/impl/src/mndSma.c @@ -552,14 +552,14 @@ static int32_t mndCreateSma(SMnode *pMnode, SRpcMsg *pReq, SMCreateSmaReq *pCrea streamObj.sourceDbUid = pDb->uid; streamObj.targetDbUid = pDb->uid; streamObj.version = 1; - streamObj.sql = strdup(pCreate->sql); + streamObj.sql = taosStrdup(pCreate->sql); streamObj.smaId = smaObj.uid; streamObj.watermark = pCreate->watermark; streamObj.deleteMark = pCreate->deleteMark; streamObj.fillHistory = STREAM_FILL_HISTORY_ON; streamObj.trigger = STREAM_TRIGGER_WINDOW_CLOSE; streamObj.triggerParam = pCreate->maxDelay; - streamObj.ast = strdup(smaObj.ast); + streamObj.ast = taosStrdup(smaObj.ast); // check the maxDelay if (streamObj.triggerParam < TSDB_MIN_ROLLUP_MAX_DELAY) { @@ -1256,19 +1256,19 @@ static int32_t mndRetrieveSma(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBloc STR_TO_VARSTR(n3, (char *)tNameGetTableName(&stbName)); SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)n1, false); + colDataSetVal(pColInfo, numOfRows, (const char *)n1, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)n2, false); + colDataSetVal(pColInfo, numOfRows, (const char *)n2, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)n3, false); + colDataSetVal(pColInfo, numOfRows, (const char *)n3, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pSma->dstVgId, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pSma->dstVgId, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pSma->createdTime, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pSma->createdTime, false); char col[TSDB_TABLE_FNAME_LEN + VARSTR_HEADER_SIZE] = {0}; STR_TO_VARSTR(col, (char *)""); diff --git a/source/dnode/mnode/impl/src/mndSnode.c b/source/dnode/mnode/impl/src/mndSnode.c index e6a253bcc0..5e98380a08 100644 --- a/source/dnode/mnode/impl/src/mndSnode.c +++ b/source/dnode/mnode/impl/src/mndSnode.c @@ -441,16 +441,16 @@ static int32_t mndRetrieveSnodes(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pB cols = 0; SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pObj->id, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pObj->id, false); char ep[TSDB_EP_LEN + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(ep, pObj->pDnode->ep, pShow->pMeta->pSchemas[cols].bytes); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)ep, false); + colDataSetVal(pColInfo, numOfRows, (const char *)ep, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pObj->createdTime, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pObj->createdTime, false); numOfRows++; sdbRelease(pSdb, pObj); diff --git a/source/dnode/mnode/impl/src/mndStb.c b/source/dnode/mnode/impl/src/mndStb.c index 499136084e..2a369a863a 100644 --- a/source/dnode/mnode/impl/src/mndStb.c +++ b/source/dnode/mnode/impl/src/mndStb.c @@ -893,7 +893,7 @@ static int32_t mndProcessTtlTimer(SRpcMsg *pReq) { static int32_t mndFindSuperTableTagIndex(const SStbObj *pStb, const char *tagName) { for (int32_t tag = 0; tag < pStb->numOfTags; tag++) { - if (strcasecmp(pStb->pTags[tag].name, tagName) == 0) { + if (strcmp(pStb->pTags[tag].name, tagName) == 0) { return tag; } } @@ -903,7 +903,7 @@ static int32_t mndFindSuperTableTagIndex(const SStbObj *pStb, const char *tagNam static int32_t mndFindSuperTableColumnIndex(const SStbObj *pStb, const char *colName) { for (int32_t col = 0; col < pStb->numOfColumns; col++) { - if (strcasecmp(pStb->pColumns[col].name, colName) == 0) { + if (strcmp(pStb->pColumns[col].name, colName) == 0) { return col; } } @@ -1734,7 +1734,7 @@ static int32_t mndBuildStbCfgImp(SDbObj *pDb, SStbObj *pStb, const char *tbName, pRsp->ttl = pStb->ttl; pRsp->commentLen = pStb->commentLen; if (pStb->commentLen > 0) { - pRsp->pComment = strdup(pStb->comment); + pRsp->pComment = taosStrdup(pStb->comment); } for (int32_t i = 0; i < pStb->numOfColumns; ++i) { @@ -2743,7 +2743,7 @@ void mndExtractTbNameFromStbFullName(const char *stbFullName, char *dst, int32_t // STR_TO_VARSTR(comment, ""); // colDataAppend(pColInfo, numOfRows, comment, false); // } else { -// colDataAppendNULL(pColInfo, numOfRows); +// colDataSetNULL(pColInfo, numOfRows); // } // // char watermark[64 + VARSTR_HEADER_SIZE] = {0}; @@ -2932,7 +2932,7 @@ static int32_t mndRetrieveStb(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBloc varDataSetLen(stbName, strlen(&stbName[VARSTR_HEADER_SIZE])); SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)stbName, false); + colDataSetVal(pColInfo, numOfRows, (const char *)stbName, false); char db[TSDB_DB_NAME_LEN + VARSTR_HEADER_SIZE] = {0}; tNameFromString(&name, pStb->db, T_NAME_ACCT | T_NAME_DB); @@ -2940,31 +2940,31 @@ static int32_t mndRetrieveStb(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBloc varDataSetLen(db, strlen(varDataVal(db))); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)db, false); + colDataSetVal(pColInfo, numOfRows, (const char *)db, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pStb->createdTime, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pStb->createdTime, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pStb->numOfColumns, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pStb->numOfColumns, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pStb->numOfTags, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pStb->numOfTags, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pStb->updateTime, false); // number of tables + colDataSetVal(pColInfo, numOfRows, (const char *)&pStb->updateTime, false); // number of tables pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); if (pStb->commentLen > 0) { char comment[TSDB_TB_COMMENT_LEN + VARSTR_HEADER_SIZE] = {0}; STR_TO_VARSTR(comment, pStb->comment); - colDataAppend(pColInfo, numOfRows, comment, false); + colDataSetVal(pColInfo, numOfRows, comment, false); } else if (pStb->commentLen == 0) { char comment[VARSTR_HEADER_SIZE + VARSTR_HEADER_SIZE] = {0}; STR_TO_VARSTR(comment, ""); - colDataAppend(pColInfo, numOfRows, comment, false); + colDataSetVal(pColInfo, numOfRows, comment, false); } else { - colDataAppendNULL(pColInfo, numOfRows); + colDataSetNULL(pColInfo, numOfRows); } char watermark[64 + VARSTR_HEADER_SIZE] = {0}; @@ -2972,14 +2972,14 @@ static int32_t mndRetrieveStb(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBloc varDataSetLen(watermark, strlen(varDataVal(watermark))); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)watermark, false); + colDataSetVal(pColInfo, numOfRows, (const char *)watermark, false); char maxDelay[64 + VARSTR_HEADER_SIZE] = {0}; sprintf(varDataVal(maxDelay), "%" PRId64 "a,%" PRId64 "a", pStb->maxdelay[0], pStb->maxdelay[1]); varDataSetLen(maxDelay, strlen(varDataVal(maxDelay))); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)maxDelay, false); + colDataSetVal(pColInfo, numOfRows, (const char *)maxDelay, false); char rollup[160 + VARSTR_HEADER_SIZE] = {0}; int32_t rollupNum = (int32_t)taosArrayGetSize(pStb->pFuncs); @@ -2998,7 +2998,7 @@ static int32_t mndRetrieveStb(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBloc varDataSetLen(rollup, strlen(varDataVal(rollup))); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)rollup, false); + colDataSetVal(pColInfo, numOfRows, (const char *)rollup, false); numOfRows++; sdbRelease(pSdb, pStb); @@ -3070,7 +3070,7 @@ static int32_t buildDbColsInfoBlock(const SSDataBlock *p, const SSysTableMeta *p colDataAppend(pColInfoData, numOfRows, (const char *)&pm->schema[j].bytes, false); for (int32_t k = 6; k <= 8; ++k) { pColInfoData = taosArrayGet(p->pDataBlock, k); - colDataAppendNULL(pColInfoData, numOfRows); + colDataSetNULL(pColInfoData, numOfRows); } numOfRows += 1; @@ -3174,7 +3174,7 @@ static int32_t mndRetrieveStbCol(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pB colDataAppend(pColInfo, numOfRows, (const char *)&pStb->pColumns[i].bytes, false); while (cols < pShow->numOfColumns) { pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppendNULL(pColInfo, numOfRows); + colDataSetNULL(pColInfo, numOfRows); } numOfRows++; } diff --git a/source/dnode/mnode/impl/src/mndStream.c b/source/dnode/mnode/impl/src/mndStream.c index 199266cd17..2a05511134 100644 --- a/source/dnode/mnode/impl/src/mndStream.c +++ b/source/dnode/mnode/impl/src/mndStream.c @@ -39,7 +39,7 @@ static int32_t mndStreamActionUpdate(SSdb *pSdb, SStreamObj *pStream, SStreamObj static int32_t mndProcessCreateStreamReq(SRpcMsg *pReq); static int32_t mndProcessDropStreamReq(SRpcMsg *pReq); static int32_t mndProcessStreamCheckpointTmr(SRpcMsg *pReq); -static int32_t mndProcessStreamDoCheckpoint(SRpcMsg *pReq); +// static int32_t mndProcessStreamDoCheckpoint(SRpcMsg *pReq); /*static int32_t mndProcessRecoverStreamReq(SRpcMsg *pReq);*/ static int32_t mndProcessStreamMetaReq(SRpcMsg *pReq); static int32_t mndGetStreamMeta(SRpcMsg *pReq, SShowObj *pShow, STableMetaRsp *pMeta); @@ -66,8 +66,8 @@ int32_t mndInitStream(SMnode *pMnode) { mndSetMsgHandle(pMnode, TDMT_STREAM_TASK_DEPLOY_RSP, mndTransProcessRsp); mndSetMsgHandle(pMnode, TDMT_STREAM_TASK_DROP_RSP, mndTransProcessRsp); - mndSetMsgHandle(pMnode, TDMT_MND_STREAM_CHECKPOINT_TIMER, mndProcessStreamCheckpointTmr); - mndSetMsgHandle(pMnode, TDMT_MND_STREAM_BEGIN_CHECKPOINT, mndProcessStreamDoCheckpoint); + // mndSetMsgHandle(pMnode, TDMT_MND_STREAM_CHECKPOINT_TIMER, mndProcessStreamCheckpointTmr); + // mndSetMsgHandle(pMnode, TDMT_MND_STREAM_BEGIN_CHECKPOINT, mndProcessStreamDoCheckpoint); mndSetMsgHandle(pMnode, TDMT_STREAM_TASK_REPORT_CHECKPOINT, mndTransProcessRsp); mndAddShowRetrieveHandle(pMnode, TSDB_MGMT_TABLE_STREAMS, mndRetrieveStream); @@ -354,7 +354,7 @@ static int32_t mndBuildStreamObjFromCreateReq(SMnode *pMnode, SStreamObj *pObj, int32_t dataIndex = 0; for (int16_t i = 0; i < pObj->outputSchema.nCols; i++) { SColLocation *pos = taosArrayGet(pCreate->fillNullCols, nullIndex); - if (i < pos->slotId) { + if (nullIndex >= numOfNULL || i < pos->slotId) { pFullSchema[i].bytes = pObj->outputSchema.pSchema[dataIndex].bytes; pFullSchema[i].colId = i + 1; // pObj->outputSchema.pSchema[dataIndex].colId; pFullSchema[i].flags = pObj->outputSchema.pSchema[dataIndex].flags; @@ -507,7 +507,8 @@ static int32_t mndCreateStbForStream(SMnode *pMnode, STrans *pTrans, const SStre SMCreateStbReq createReq = {0}; tstrncpy(createReq.name, pStream->targetSTbName, TSDB_TABLE_FNAME_LEN); createReq.numOfColumns = pStream->outputSchema.nCols; - createReq.pColumns = taosArrayInit_s(createReq.numOfColumns, sizeof(SField), createReq.numOfColumns); + createReq.numOfTags = 1; // group id + createReq.pColumns = taosArrayInit_s(sizeof(SField), createReq.numOfColumns); // build fields for (int32_t i = 0; i < createReq.numOfColumns; i++) { SField *pField = taosArrayGet(createReq.pColumns, i); @@ -519,7 +520,7 @@ static int32_t mndCreateStbForStream(SMnode *pMnode, STrans *pTrans, const SStre if (pStream->tagSchema.nCols == 0) { createReq.numOfTags = 1; - createReq.pTags = taosArrayInit_s(createReq.numOfTags, sizeof(SField), 1); + createReq.pTags = taosArrayInit_s(sizeof(SField), 1); // build tags SField *pField = taosArrayGet(createReq.pTags, 0); strcpy(pField->name, "group_id"); @@ -528,7 +529,7 @@ static int32_t mndCreateStbForStream(SMnode *pMnode, STrans *pTrans, const SStre pField->bytes = 8; } else { createReq.numOfTags = pStream->tagSchema.nCols; - createReq.pTags = taosArrayInit_s(createReq.numOfTags, sizeof(SField), createReq.numOfTags); + createReq.pTags = taosArrayInit_s(sizeof(SField), createReq.numOfTags); for (int32_t i = 0; i < createReq.numOfTags; i++) { SField *pField = taosArrayGet(createReq.pTags, i); pField->bytes = pStream->tagSchema.pSchema[i].bytes; @@ -722,8 +723,10 @@ static int32_t mndProcessCreateStreamReq(SRpcMsg *pReq) { mInfo("trans:%d, used to create stream:%s", pTrans->id, createStreamReq.name); mndTransSetDbName(pTrans, createStreamReq.sourceDB, streamObj.targetDb); - if (mndTrancCheckConflict(pMnode, pTrans) != 0) goto _OVER; - + if (mndTrancCheckConflict(pMnode, pTrans) != 0) { + mndTransDrop(pTrans); + goto _OVER; + } // create stb for stream if (createStreamReq.createStb == STREAM_CREATE_STABLE_TRUE && mndCreateStbForStream(pMnode, pTrans, &streamObj, pReq->info.conn.user) < 0) { @@ -778,6 +781,9 @@ _OVER: tFreeStreamObj(&streamObj); return code; } + +#if 0 + static int32_t mndProcessStreamCheckpointTmr(SRpcMsg *pReq) { SMnode *pMnode = pReq->info.node; SSdb *pSdb = pMnode->pSdb; @@ -942,6 +948,8 @@ static int32_t mndProcessStreamDoCheckpoint(SRpcMsg *pReq) { return 0; } +#endif + static int32_t mndProcessDropStreamReq(SRpcMsg *pReq) { SMnode *pMnode = pReq->info.node; SStreamObj *pStream = NULL; @@ -1099,52 +1107,52 @@ static int32_t mndRetrieveStream(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pB char streamName[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(streamName, mndGetDbStr(pStream->name), sizeof(streamName)); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)streamName, false); + colDataSetVal(pColInfo, numOfRows, (const char *)streamName, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pStream->createTime, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pStream->createTime, false); char sql[TSDB_SHOW_SQL_LEN + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(sql, pStream->sql, sizeof(sql)); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)sql, false); + colDataSetVal(pColInfo, numOfRows, (const char *)sql, false); char status[20 + VARSTR_HEADER_SIZE] = {0}; char status2[20] = {0}; mndShowStreamStatus(status2, pStream); STR_WITH_MAXSIZE_TO_VARSTR(status, status2, sizeof(status)); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&status, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&status, false); char sourceDB[TSDB_DB_NAME_LEN + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(sourceDB, mndGetDbStr(pStream->sourceDb), sizeof(sourceDB)); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&sourceDB, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&sourceDB, false); char targetDB[TSDB_DB_NAME_LEN + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(targetDB, mndGetDbStr(pStream->targetDb), sizeof(targetDB)); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&targetDB, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&targetDB, false); if (pStream->targetSTbName[0] == 0) { pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, NULL, true); + colDataSetVal(pColInfo, numOfRows, NULL, true); } else { char targetSTB[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(targetSTB, mndGetStbStr(pStream->targetSTbName), sizeof(targetSTB)); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&targetSTB, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&targetSTB, false); } pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pStream->watermark, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pStream->watermark, false); char trigger[20 + VARSTR_HEADER_SIZE] = {0}; char trigger2[20] = {0}; mndShowStreamTrigger(trigger2, pStream); STR_WITH_MAXSIZE_TO_VARSTR(trigger, trigger2, sizeof(trigger)); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&trigger, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&trigger, false); numOfRows++; sdbRelease(pSdb, pStream); @@ -1196,11 +1204,11 @@ static int32_t mndRetrieveStreamTask(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock char streamName[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(streamName, mndGetDbStr(pStream->name), sizeof(streamName)); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)streamName, false); + colDataSetVal(pColInfo, numOfRows, (const char *)streamName, false); // task id pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pTask->taskId, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pTask->taskId, false); // node type char nodeType[20 + VARSTR_HEADER_SIZE] = {0}; @@ -1211,12 +1219,12 @@ static int32_t mndRetrieveStreamTask(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock } else { memcpy(varDataVal(nodeType), "snode", 5); } - colDataAppend(pColInfo, numOfRows, nodeType, false); + colDataSetVal(pColInfo, numOfRows, nodeType, false); // node id pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); int32_t nodeId = TMAX(pTask->nodeId, 0); - colDataAppend(pColInfo, numOfRows, (const char *)&nodeId, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&nodeId, false); // level char level[20 + VARSTR_HEADER_SIZE] = {0}; @@ -1232,7 +1240,7 @@ static int32_t mndRetrieveStreamTask(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock } else if (pTask->taskLevel == TASK_LEVEL__SINK) { } pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&level, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&level, false); // status char status[20 + VARSTR_HEADER_SIZE] = {0}; @@ -1240,7 +1248,7 @@ static int32_t mndRetrieveStreamTask(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock strcpy(status, "normal"); STR_WITH_MAXSIZE_TO_VARSTR(status, status2, sizeof(status)); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&status, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&status, false); numOfRows++; } diff --git a/source/dnode/mnode/impl/src/mndSubscribe.c b/source/dnode/mnode/impl/src/mndSubscribe.c index d127ceacf5..8d8fd1b9b5 100644 --- a/source/dnode/mnode/impl/src/mndSubscribe.c +++ b/source/dnode/mnode/impl/src/mndSubscribe.c @@ -39,12 +39,10 @@ static SSdbRow *mndSubActionDecode(SSdbRaw *pRaw); static int32_t mndSubActionInsert(SSdb *pSdb, SMqSubscribeObj *); static int32_t mndSubActionDelete(SSdb *pSdb, SMqSubscribeObj *); static int32_t mndSubActionUpdate(SSdb *pSdb, SMqSubscribeObj *pOldSub, SMqSubscribeObj *pNewSub); - -static int32_t mndProcessRebalanceReq(SRpcMsg *pMsg); -static int32_t mndProcessDropCgroupReq(SRpcMsg *pMsg); - -static int32_t mndRetrieveSubscribe(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBlock, int32_t rows); -static void mndCancelGetNextSubscribe(SMnode *pMnode, void *pIter); +static int32_t mndProcessRebalanceReq(SRpcMsg *pMsg); +static int32_t mndProcessDropCgroupReq(SRpcMsg *pMsg); +static int32_t mndRetrieveSubscribe(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBlock, int32_t rows); +static void mndCancelGetNextSubscribe(SMnode *pMnode, void *pIter); static int32_t mndSetSubRedoLogs(SMnode *pMnode, STrans *pTrans, SMqSubscribeObj *pSub) { SSdbRaw *pRedoRaw = mndSubActionEncode(pSub); @@ -85,12 +83,13 @@ int32_t mndInitSubscribe(SMnode *pMnode) { return sdbSetTable(pMnode->pSdb, table); } -static SMqSubscribeObj *mndCreateSub(SMnode *pMnode, const SMqTopicObj *pTopic, const char *subKey) { +static SMqSubscribeObj *mndCreateSubscription(SMnode *pMnode, const SMqTopicObj *pTopic, const char *subKey) { SMqSubscribeObj *pSub = tNewSubscribeObj(subKey); if (pSub == NULL) { terrno = TSDB_CODE_OUT_OF_MEMORY; return NULL; } + pSub->dbUid = pTopic->dbUid; pSub->stbUid = pTopic->stbUid; pSub->subType = pTopic->subType; @@ -123,6 +122,7 @@ static int32_t mndBuildSubChangeReq(void **pBuf, int32_t *pLen, const SMqSubscri terrno = TSDB_CODE_OUT_OF_MEMORY; return -1; } + SMsgHead *pMsgHead = (SMsgHead *)buf; pMsgHead->contLen = htonl(tlen); @@ -205,7 +205,7 @@ static SMqRebInfo *mndGetOrCreateRebSub(SHashObj *pHash, const char *key) { static int32_t mndDoRebalance(SMnode *pMnode, const SMqRebInputObj *pInput, SMqRebOutputObj *pOutput) { int32_t totalVgNum = pOutput->pSub->vgNum; const char *sub = pOutput->pSub->key; - mInfo("sub:%s, mq rebalance vgNum:%d", sub, pOutput->pSub->vgNum); + mInfo("sub:%s mq re-balance %d vgroups", sub, pOutput->pSub->vgNum); // 1. build temporary hash(vgId -> SMqRebOutputVg) to store modified vg SHashObj *pHash = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), false, HASH_NO_LOCK); @@ -214,7 +214,7 @@ static int32_t mndDoRebalance(SMnode *pMnode, const SMqRebInputObj *pInput, SMqR int32_t removedNum = taosArrayGetSize(pInput->pRebInfo->removedConsumers); int32_t actualRemoved = 0; for (int32_t i = 0; i < removedNum; i++) { - int64_t consumerId = *(int64_t *)taosArrayGet(pInput->pRebInfo->removedConsumers, i); + uint64_t consumerId = *(uint64_t *)taosArrayGet(pInput->pRebInfo->removedConsumers, i); SMqConsumerEp *pConsumerEp = taosHashGet(pOutput->pSub->consumerHash, &consumerId, sizeof(int64_t)); @@ -229,7 +229,7 @@ static int32_t mndDoRebalance(SMnode *pMnode, const SMqRebInputObj *pInput, SMqR .pVgEp = pVgEp, }; taosHashPut(pHash, &pVgEp->vgId, sizeof(int32_t), &outputVg, sizeof(SMqRebOutputVg)); - mInfo("sub:%s, mq rebalance remove vgId:%d from consumer:%" PRId64, sub, pVgEp->vgId, consumerId); + mInfo("sub:%s mq re-balance remove vgId:%d from consumer:%" PRId64, sub, pVgEp->vgId, consumerId); } taosArrayDestroy(pConsumerEp->vgs); taosHashRemove(pOutput->pSub->consumerHash, &consumerId, sizeof(int64_t)); @@ -239,7 +239,7 @@ static int32_t mndDoRebalance(SMnode *pMnode, const SMqRebInputObj *pInput, SMqR } if (removedNum != actualRemoved) { - mError("sub:%s, mq rebalance removedNum:%d not matched with actual:%d", sub, removedNum, actualRemoved); + mError("sub:%s mq re-balance removedNum:%d not matched with actual:%d", sub, removedNum, actualRemoved); } // if previously no consumer, there are vgs not assigned @@ -253,7 +253,7 @@ static int32_t mndDoRebalance(SMnode *pMnode, const SMqRebInputObj *pInput, SMqR .pVgEp = pVgEp, }; taosHashPut(pHash, &pVgEp->vgId, sizeof(int32_t), &rebOutput, sizeof(SMqRebOutputVg)); - mInfo("sub:%s, mq rebalance remove vgId:%d from unassigned", sub, pVgEp->vgId); + mInfo("sub:%s mq re-balance remove vgId:%d from unassigned", sub, pVgEp->vgId); } } @@ -267,7 +267,8 @@ static int32_t mndDoRebalance(SMnode *pMnode, const SMqRebInputObj *pInput, SMqR minVgCnt = totalVgNum / afterRebConsumerNum; imbConsumerNum = totalVgNum % afterRebConsumerNum; } - mInfo("sub:%s, mq rebalance %d consumer after rebalance, at least %d vg each, %d consumer has more vg", sub, + + mInfo("sub:%s mq re-balance %d consumers: at least %d vg each, %d consumer has more vg", sub, afterRebConsumerNum, minVgCnt, imbConsumerNum); // 4. first scan: remove consumer more than wanted, put to remove hash @@ -275,7 +276,10 @@ static int32_t mndDoRebalance(SMnode *pMnode, const SMqRebInputObj *pInput, SMqR void *pIter = NULL; while (1) { pIter = taosHashIterate(pOutput->pSub->consumerHash, pIter); - if (pIter == NULL) break; + if (pIter == NULL) { + break; + } + SMqConsumerEp *pConsumerEp = (SMqConsumerEp *)pIter; int32_t consumerVgNum = taosArrayGetSize(pConsumerEp->vgs); @@ -297,7 +301,7 @@ static int32_t mndDoRebalance(SMnode *pMnode, const SMqRebInputObj *pInput, SMqR .pVgEp = pVgEp, }; taosHashPut(pHash, &pVgEp->vgId, sizeof(int32_t), &outputVg, sizeof(SMqRebOutputVg)); - mInfo("sub:%s, mq rebalance remove vgId:%d from consumer:%" PRId64 ",(first scan)", sub, pVgEp->vgId, + mInfo("sub:%s mq rebalance remove vgId:%d from consumer:%" PRId64 ",(first scan)", sub, pVgEp->vgId, pConsumerEp->consumerId); } imbCnt++; @@ -312,7 +316,7 @@ static int32_t mndDoRebalance(SMnode *pMnode, const SMqRebInputObj *pInput, SMqR .pVgEp = pVgEp, }; taosHashPut(pHash, &pVgEp->vgId, sizeof(int32_t), &outputVg, sizeof(SMqRebOutputVg)); - mInfo("sub:%s, mq rebalance remove vgId:%d from consumer:%" PRId64 ",(first scan)", sub, pVgEp->vgId, + mInfo("sub:%s mq rebalance remove vgId:%d from consumer:%" PRId64 ",(first scan)", sub, pVgEp->vgId, pConsumerEp->consumerId); } } @@ -330,7 +334,7 @@ static int32_t mndDoRebalance(SMnode *pMnode, const SMqRebInputObj *pInput, SMqR newConsumerEp.vgs = taosArrayInit(0, sizeof(void *)); taosHashPut(pOutput->pSub->consumerHash, &consumerId, sizeof(int64_t), &newConsumerEp, sizeof(SMqConsumerEp)); taosArrayPush(pOutput->newConsumers, &consumerId); - mInfo("sub:%s, mq rebalance add new consumer:%" PRId64, sub, consumerId); + mInfo("sub:%s mq rebalance add new consumer:%" PRId64, sub, consumerId); } } @@ -349,7 +353,7 @@ static int32_t mndDoRebalance(SMnode *pMnode, const SMqRebInputObj *pInput, SMqR // iter hash and find one vg pRemovedIter = taosHashIterate(pHash, pRemovedIter); if (pRemovedIter == NULL) { - mError("sub:%s, removed iter is null", sub); + mError("sub:%s removed iter is null", sub); continue; } @@ -402,33 +406,36 @@ static int32_t mndDoRebalance(SMnode *pMnode, const SMqRebInputObj *pInput, SMqR SMqRebOutputVg *pRebOutput = NULL; while (1) { pIter = taosHashIterate(pHash, pIter); - if (pIter == NULL) break; + if (pIter == NULL) { + break; + } + pRebOutput = (SMqRebOutputVg *)pIter; taosArrayPush(pOutput->pSub->unassignedVgs, &pRebOutput->pVgEp); taosArrayPush(pOutput->rebVgs, pRebOutput); - mInfo("sub:%s, mq rebalance unassign vgId:%d (second scan)", sub, pRebOutput->pVgEp->vgId); + mInfo("sub:%s mq re-balance unassign vgId:%d (second scan)", sub, pRebOutput->pVgEp->vgId); } } // 8. generate logs - mInfo("sub:%s, mq rebalance calculation completed, rebalanced vg", sub); + mInfo("sub:%s mq re-balance calculation completed, re-balanced vg", sub); for (int32_t i = 0; i < taosArrayGetSize(pOutput->rebVgs); i++) { SMqRebOutputVg *pOutputRebVg = taosArrayGet(pOutput->rebVgs, i); - mInfo("sub:%s, mq rebalance vgId:%d, moved from consumer:%" PRId64 ", to consumer:%" PRId64, sub, + mInfo("sub:%s mq re-balance vgId:%d, moved from consumer:0x%" PRIx64 ", to consumer:0x%" PRIx64, sub, pOutputRebVg->pVgEp->vgId, pOutputRebVg->oldConsumerId, pOutputRebVg->newConsumerId); } { - void *pIter = NULL; + pIter = NULL; while (1) { pIter = taosHashIterate(pOutput->pSub->consumerHash, pIter); if (pIter == NULL) break; SMqConsumerEp *pConsumerEp = (SMqConsumerEp *)pIter; int32_t sz = taosArrayGetSize(pConsumerEp->vgs); - mInfo("sub:%s, mq rebalance final cfg: consumer %" PRId64 " has %d vg", sub, pConsumerEp->consumerId, sz); + mInfo("sub:%s mq re-balance final cfg: consumer:0x%" PRId64 " has %d vg", sub, pConsumerEp->consumerId, sz); for (int32_t i = 0; i < sz; i++) { SMqVgEp *pVgEp = taosArrayGetP(pConsumerEp->vgs, i); - mInfo("sub:%s, mq rebalance final cfg: vg %d to consumer %" PRId64 "", sub, pVgEp->vgId, + mInfo("sub:%s mq re-balance final cfg: vg %d to consumer:0x%" PRId64, sub, pVgEp->vgId, pConsumerEp->consumerId); } } @@ -552,11 +559,14 @@ static int32_t mndProcessRebalanceReq(SRpcMsg *pMsg) { SMqDoRebalanceMsg *pReq = pMsg->pCont; void *pIter = NULL; - mInfo("mq rebalance start"); + mInfo("mq re-balance start"); while (1) { pIter = taosHashIterate(pReq->rebSubHash, pIter); - if (pIter == NULL) break; + if (pIter == NULL) { + break; + } + SMqRebInputObj rebInput = {0}; SMqRebOutputObj rebOutput = {0}; @@ -577,12 +587,13 @@ static int32_t mndProcessRebalanceReq(SRpcMsg *pMsg) { mndSplitSubscribeKey(pRebInfo->key, topic, cgroup, true); SMqTopicObj *pTopic = mndAcquireTopic(pMnode, topic); if (pTopic == NULL) { - mError("mq rebalance %s failed since topic %s not exist, abort", pRebInfo->key, topic); + mError("mq re-balance %s ignored since topic %s not exist", pRebInfo->key, topic); continue; } + taosRLockLatch(&pTopic->lock); - rebOutput.pSub = mndCreateSub(pMnode, pTopic, pRebInfo->key); + rebOutput.pSub = mndCreateSubscription(pMnode, pTopic, pRebInfo->key); if (rebOutput.pSub == NULL) { mError("mq rebalance %s failed create sub since %s, abort", pRebInfo->key, terrstr()); @@ -605,15 +616,16 @@ static int32_t mndProcessRebalanceReq(SRpcMsg *pMsg) { } if (mndDoRebalance(pMnode, &rebInput, &rebOutput) < 0) { - mError("mq rebalance internal error"); + mError("mq re-balance internal error"); } // if add more consumer to balanced subscribe, // possibly no vg is changed if (mndPersistRebResult(pMnode, pMsg, &rebOutput) < 0) { - mError("mq rebalance persist rebalance output error, possibly vnode splitted or dropped"); + mError("mq re-balance persist re-balance output error, possibly vnode splitted or dropped"); } + taosArrayDestroy(pRebInfo->lostConsumers); taosArrayDestroy(pRebInfo->newConsumers); taosArrayDestroy(pRebInfo->removedConsumers); @@ -627,19 +639,18 @@ static int32_t mndProcessRebalanceReq(SRpcMsg *pMsg) { } // reset flag - mInfo("mq rebalance completed successfully"); + mInfo("mq re-balance completed successfully"); taosHashCleanup(pReq->rebSubHash); mndRebEnd(); return 0; } -static int32_t mndProcessDropCgroupReq(SRpcMsg *pReq) { - SMnode *pMnode = pReq->info.node; - SSdb *pSdb = pMnode->pSdb; +static int32_t mndProcessDropCgroupReq(SRpcMsg *pMsg) { + SMnode *pMnode = pMsg->info.node; SMDropCgroupReq dropReq = {0}; - if (tDeserializeSMDropCgroupReq(pReq->pCont, pReq->contLen, &dropReq) != 0) { + if (tDeserializeSMDropCgroupReq(pMsg->pCont, pMsg->contLen, &dropReq) != 0) { terrno = TSDB_CODE_INVALID_MSG; return -1; } @@ -663,7 +674,7 @@ static int32_t mndProcessDropCgroupReq(SRpcMsg *pReq) { return -1; } - STrans *pTrans = mndTransCreate(pMnode, TRN_POLICY_ROLLBACK, TRN_CONFLICT_NOTHING, pReq, "drop-cgroup"); + STrans *pTrans = mndTransCreate(pMnode, TRN_POLICY_ROLLBACK, TRN_CONFLICT_NOTHING, pMsg, "drop-cgroup"); if (pTrans == NULL) { mError("cgroup: %s on topic:%s, failed to drop since %s", dropReq.cgroup, dropReq.topic, terrstr()); mndReleaseSubscribe(pMnode, pSub); @@ -956,7 +967,7 @@ END: return code; } -static int32_t mndRetrieveSubscribe(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBlock, int32_t rowsCapacity) { +int32_t mndRetrieveSubscribe(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBlock, int32_t rowsCapacity) { SMnode *pMnode = pReq->info.node; SSdb *pSdb = pMnode->pSdb; int32_t numOfRows = 0; @@ -998,18 +1009,18 @@ static int32_t mndRetrieveSubscribe(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock varDataSetLen(cgroup, strlen(varDataVal(cgroup))); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)topic, false); + colDataSetVal(pColInfo, numOfRows, (const char *)topic, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)cgroup, false); + colDataSetVal(pColInfo, numOfRows, (const char *)cgroup, false); // vg id pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pVgEp->vgId, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pVgEp->vgId, false); // consumer id pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pConsumerEp->consumerId, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pConsumerEp->consumerId, false); mDebug("mnd show subscriptions: topic %s, consumer %" PRId64 " cgroup %s vgid %d", varDataVal(topic), pConsumerEp->consumerId, varDataVal(cgroup), pVgEp->vgId); @@ -1018,11 +1029,11 @@ static int32_t mndRetrieveSubscribe(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock #if 0 // subscribe time pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pSub->subscribeTime, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pSub->subscribeTime, false); // rebalance time pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pSub->rebalanceTime, pConsumer->rebalanceTime == 0); + colDataSetVal(pColInfo, numOfRows, (const char *)&pSub->rebalanceTime, pConsumer->rebalanceTime == 0); #endif numOfRows++; @@ -1046,18 +1057,18 @@ static int32_t mndRetrieveSubscribe(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock varDataSetLen(cgroup, strlen(varDataVal(cgroup))); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)topic, false); + colDataSetVal(pColInfo, numOfRows, (const char *)topic, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)cgroup, false); + colDataSetVal(pColInfo, numOfRows, (const char *)cgroup, false); // vg id pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pVgEp->vgId, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pVgEp->vgId, false); // consumer id pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, NULL, true); + colDataSetVal(pColInfo, numOfRows, NULL, true); mDebug("mnd show subscriptions(unassigned): topic %s, cgroup %s vgid %d", varDataVal(topic), varDataVal(cgroup), pVgEp->vgId); @@ -1066,11 +1077,11 @@ static int32_t mndRetrieveSubscribe(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock #if 0 // subscribe time pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pSub->subscribeTime, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pSub->subscribeTime, false); // rebalance time pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pSub->rebalanceTime, pConsumer->rebalanceTime == 0); + colDataSetVal(pColInfo, numOfRows, (const char *)&pSub->rebalanceTime, pConsumer->rebalanceTime == 0); #endif numOfRows++; @@ -1090,7 +1101,7 @@ static int32_t mndRetrieveSubscribe(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock return numOfRows; } -static void mndCancelGetNextSubscribe(SMnode *pMnode, void *pIter) { +void mndCancelGetNextSubscribe(SMnode *pMnode, void *pIter) { SSdb *pSdb = pMnode->pSdb; sdbCancelFetch(pSdb, pIter); } diff --git a/source/dnode/mnode/impl/src/mndTopic.c b/source/dnode/mnode/impl/src/mndTopic.c index 96dba24566..991f1099a6 100644 --- a/source/dnode/mnode/impl/src/mndTopic.c +++ b/source/dnode/mnode/impl/src/mndTopic.c @@ -31,9 +31,12 @@ #define MND_TOPIC_VER_NUMBER 2 #define MND_TOPIC_RESERVE_SIZE 64 +SSdbRaw *mndTopicActionEncode(SMqTopicObj *pTopic); +SSdbRow *mndTopicActionDecode(SSdbRaw *pRaw); + static int32_t mndTopicActionInsert(SSdb *pSdb, SMqTopicObj *pTopic); static int32_t mndTopicActionDelete(SSdb *pSdb, SMqTopicObj *pTopic); -static int32_t mndTopicActionUpdate(SSdb *pSdb, SMqTopicObj *pTopic, SMqTopicObj *pNewTopic); +static int32_t mndTopicActionUpdate(SSdb *pSdb, SMqTopicObj *pOldTopic, SMqTopicObj *pNewTopic); static int32_t mndProcessCreateTopicReq(SRpcMsg *pReq); static int32_t mndProcessDropTopicReq(SRpcMsg *pReq); @@ -79,6 +82,7 @@ SSdbRaw *mndTopicActionEncode(SMqTopicObj *pTopic) { if (pTopic->physicalPlan) { physicalPlanLen = strlen(pTopic->physicalPlan) + 1; } + int32_t schemaLen = 0; if (pTopic->schema.nCols) { schemaLen = taosEncodeSSchemaWrapper(NULL, &pTopic->schema); @@ -88,7 +92,9 @@ SSdbRaw *mndTopicActionEncode(SMqTopicObj *pTopic) { int32_t size = sizeof(SMqTopicObj) + physicalPlanLen + pTopic->sqlLen + pTopic->astLen + schemaLen + ntbColLen + MND_TOPIC_RESERVE_SIZE; SSdbRaw *pRaw = sdbAllocRaw(SDB_TOPIC, MND_TOPIC_VER_NUMBER, size); - if (pRaw == NULL) goto TOPIC_ENCODE_OVER; + if (pRaw == NULL) { + goto TOPIC_ENCODE_OVER; + } int32_t dataPos = 0; SDB_SET_BINARY(pRaw, dataPos, pTopic->name, TSDB_TOPIC_FNAME_LEN, TOPIC_ENCODE_OVER); @@ -106,6 +112,7 @@ SSdbRaw *mndTopicActionEncode(SMqTopicObj *pTopic) { SDB_SET_INT32(pRaw, dataPos, pTopic->sqlLen, TOPIC_ENCODE_OVER); SDB_SET_BINARY(pRaw, dataPos, pTopic->sql, pTopic->sqlLen, TOPIC_ENCODE_OVER); SDB_SET_INT32(pRaw, dataPos, pTopic->astLen, TOPIC_ENCODE_OVER); + if (pTopic->astLen) { SDB_SET_BINARY(pRaw, dataPos, pTopic->ast, pTopic->astLen, TOPIC_ENCODE_OVER); } @@ -123,6 +130,7 @@ SSdbRaw *mndTopicActionEncode(SMqTopicObj *pTopic) { taosEncodeSSchemaWrapper(&aswBuf, &pTopic->schema); SDB_SET_BINARY(pRaw, dataPos, swBuf, schemaLen, TOPIC_ENCODE_OVER); } + SDB_SET_INT64(pRaw, dataPos, pTopic->ntbUid, TOPIC_ENCODE_OVER); if (pTopic->ntbUid != 0) { int32_t sz = taosArrayGetSize(pTopic->ntbColIds); @@ -132,6 +140,7 @@ SSdbRaw *mndTopicActionEncode(SMqTopicObj *pTopic) { SDB_SET_INT16(pRaw, dataPos, colId, TOPIC_ENCODE_OVER); } } + SDB_SET_INT64(pRaw, dataPos, pTopic->ctbStbUid, TOPIC_ENCODE_OVER); SDB_SET_RESERVE(pRaw, dataPos, MND_TOPIC_RESERVE_SIZE, TOPIC_ENCODE_OVER); @@ -247,10 +256,9 @@ SSdbRow *mndTopicActionDecode(SSdbRaw *pRaw) { SDB_GET_INT16(pRaw, dataPos, &colId, TOPIC_DECODE_OVER); taosArrayPush(pTopic->ntbColIds, &colId); } + SDB_GET_INT64(pRaw, dataPos, &pTopic->ctbStbUid, TOPIC_DECODE_OVER); - SDB_GET_RESERVE(pRaw, dataPos, MND_TOPIC_RESERVE_SIZE, TOPIC_DECODE_OVER); - terrno = TSDB_CODE_SUCCESS; TOPIC_DECODE_OVER: @@ -266,12 +274,12 @@ TOPIC_DECODE_OVER: } static int32_t mndTopicActionInsert(SSdb *pSdb, SMqTopicObj *pTopic) { - mTrace("topic:%s, perform insert action", pTopic->name); + mTrace("topic:%s perform insert action", pTopic->name); return 0; } static int32_t mndTopicActionDelete(SSdb *pSdb, SMqTopicObj *pTopic) { - mTrace("topic:%s, perform delete action", pTopic->name); + mTrace("topic:%s perform delete action", pTopic->name); taosMemoryFreeClear(pTopic->sql); taosMemoryFreeClear(pTopic->ast); taosMemoryFreeClear(pTopic->physicalPlan); @@ -281,7 +289,7 @@ static int32_t mndTopicActionDelete(SSdb *pSdb, SMqTopicObj *pTopic) { } static int32_t mndTopicActionUpdate(SSdb *pSdb, SMqTopicObj *pOldTopic, SMqTopicObj *pNewTopic) { - mTrace("topic:%s, perform update action", pOldTopic->name); + mTrace("topic:%s perform update action", pOldTopic->name); atomic_exchange_64(&pOldTopic->updateTime, pNewTopic->updateTime); atomic_exchange_32(&pOldTopic->version, pNewTopic->version); @@ -364,7 +372,8 @@ static int32_t extractTopicTbInfo(SNode *pAst, SMqTopicObj *pTopic) { static int32_t mndCreateTopic(SMnode *pMnode, SRpcMsg *pReq, SCMCreateTopicReq *pCreate, SDbObj *pDb, const char *userName) { - mInfo("topic:%s to create", pCreate->name); + mInfo("start to create topic:%s", pCreate->name); + SMqTopicObj topicObj = {0}; tstrncpy(topicObj.name, pCreate->name, TSDB_TOPIC_FNAME_LEN); tstrncpy(topicObj.db, pDb->name, TSDB_DB_FNAME_LEN); @@ -379,23 +388,22 @@ static int32_t mndCreateTopic(SMnode *pMnode, SRpcMsg *pReq, SCMCreateTopicReq * topicObj.uid = mndGenerateUid(pCreate->name, strlen(pCreate->name)); topicObj.dbUid = pDb->uid; topicObj.version = 1; - topicObj.sql = strdup(pCreate->sql); + topicObj.sql = taosStrdup(pCreate->sql); topicObj.sqlLen = strlen(pCreate->sql) + 1; topicObj.subType = pCreate->subType; topicObj.withMeta = pCreate->withMeta; - if (topicObj.withMeta) { - if (topicObj.subType == TOPIC_SUB_TYPE__COLUMN) { + + if (pCreate->subType == TOPIC_SUB_TYPE__COLUMN) { + if (pCreate->withMeta) { terrno = TSDB_CODE_MND_INVALID_TOPIC_OPTION; mError("topic:%s, failed to create since %s", pCreate->name, terrstr()); return -1; } - } - if (pCreate->subType == TOPIC_SUB_TYPE__COLUMN) { - topicObj.ast = strdup(pCreate->ast); + topicObj.ast = taosStrdup(pCreate->ast); topicObj.astLen = strlen(pCreate->ast) + 1; - qDebugL("ast %s", topicObj.ast); + qDebugL("topic:%s ast %s", topicObj.name, topicObj.ast); SNode *pAst = NULL; if (nodesStringToNode(pCreate->ast, &pAst) != 0) { @@ -409,18 +417,20 @@ static int32_t mndCreateTopic(SMnode *pMnode, SRpcMsg *pReq, SCMCreateTopicReq * SPlanContext cxt = {.pAstRoot = pAst, .topicQuery = true}; if (qCreateQueryPlan(&cxt, &pPlan, NULL) != 0) { - mError("topic:%s, failed to create since %s", pCreate->name, terrstr()); + mError("failed to create topic:%s since %s", pCreate->name, terrstr()); taosMemoryFree(topicObj.ast); taosMemoryFree(topicObj.sql); return -1; } - int64_t ntbUid; topicObj.ntbColIds = taosArrayInit(0, sizeof(int16_t)); if (topicObj.ntbColIds == NULL) { + taosMemoryFree(topicObj.ast); + taosMemoryFree(topicObj.sql); terrno = TSDB_CODE_OUT_OF_MEMORY; return -1; } + extractTopicTbInfo(pAst, &topicObj); if (topicObj.ntbUid == 0) { @@ -449,6 +459,7 @@ static int32_t mndCreateTopic(SMnode *pMnode, SRpcMsg *pReq, SCMCreateTopicReq * terrno = TSDB_CODE_MND_STB_NOT_EXIST; return -1; } + topicObj.stbUid = pStb->uid; mndReleaseStb(pMnode, pStb); } @@ -467,7 +478,8 @@ static int32_t mndCreateTopic(SMnode *pMnode, SRpcMsg *pReq, SCMCreateTopicReq * taosMemoryFreeClear(topicObj.physicalPlan); return -1; } - mInfo("trans:%d, used to create topic:%s", pTrans->id, pCreate->name); + + mInfo("trans:%d to create topic:%s", pTrans->id, pCreate->name); SSdbRaw *pCommitRaw = mndTopicActionEncode(&topicObj); if (pCommitRaw == NULL || mndTransAppendCommitlog(pTrans, pCommitRaw) != 0) { @@ -476,6 +488,7 @@ static int32_t mndCreateTopic(SMnode *pMnode, SRpcMsg *pReq, SCMCreateTopicReq * mndTransDrop(pTrans); return -1; } + (void)sdbSetRawStatus(pCommitRaw, SDB_STATUS_READY); if (topicObj.ntbUid != 0) { @@ -544,7 +557,11 @@ static int32_t mndCreateTopic(SMnode *pMnode, SRpcMsg *pReq, SCMCreateTopicReq * taosMemoryFreeClear(topicObj.sql); taosMemoryFreeClear(topicObj.ast); taosArrayDestroy(topicObj.ntbColIds); - if (topicObj.schema.nCols) taosMemoryFreeClear(topicObj.schema.pSchema); + + if (topicObj.schema.nCols) { + taosMemoryFreeClear(topicObj.schema.pSchema); + } + mndTransDrop(pTrans); return TSDB_CODE_ACTION_IN_PROGRESS; } @@ -561,17 +578,17 @@ static int32_t mndProcessCreateTopicReq(SRpcMsg *pReq) { goto _OVER; } - mInfo("topic:%s, start to create, sql:%s", createTopicReq.name, createTopicReq.sql); + mInfo("topic:%s start to create, sql:%s", createTopicReq.name, createTopicReq.sql); if (mndCheckCreateTopicReq(&createTopicReq) != 0) { - mError("topic:%s, failed to create since %s", createTopicReq.name, terrstr()); + mError("topic:%s failed to create since %s", createTopicReq.name, terrstr()); goto _OVER; } pTopic = mndAcquireTopic(pMnode, createTopicReq.name); if (pTopic != NULL) { if (createTopicReq.igExists) { - mInfo("topic:%s, already exist, ignore exist is set", createTopicReq.name); + mInfo("topic:%s already exist, ignore exist is set", createTopicReq.name); code = 0; goto _OVER; } else { @@ -589,11 +606,13 @@ static int32_t mndProcessCreateTopicReq(SRpcMsg *pReq) { } code = mndCreateTopic(pMnode, pReq, &createTopicReq, pDb, pReq->info.conn.user); - if (code == 0) code = TSDB_CODE_ACTION_IN_PROGRESS; + if (code == 0) { + code = TSDB_CODE_ACTION_IN_PROGRESS; + } _OVER: if (code != 0 && code != TSDB_CODE_ACTION_IN_PROGRESS) { - mError("topic:%s, failed to create since %s", createTopicReq.name, terrstr()); + mError("failed to create topic:%s since %s", createTopicReq.name, terrstr()); } mndReleaseTopic(pMnode, pTopic); @@ -605,13 +624,18 @@ _OVER: static int32_t mndDropTopic(SMnode *pMnode, STrans *pTrans, SRpcMsg *pReq, SMqTopicObj *pTopic) { int32_t code = -1; - if (mndUserRemoveTopic(pMnode, pTrans, pTopic->name) != 0) goto _OVER; + if (mndUserRemoveTopic(pMnode, pTrans, pTopic->name) != 0) { + goto _OVER; + } SSdbRaw *pCommitRaw = mndTopicActionEncode(pTopic); if (pCommitRaw == NULL || mndTransAppendCommitlog(pTrans, pCommitRaw) != 0) goto _OVER; (void)sdbSetRawStatus(pCommitRaw, SDB_STATUS_DROPPED); - if (mndTransPrepare(pMnode, pTrans) != 0) goto _OVER; + if (mndTransPrepare(pMnode, pTrans) != 0) { + goto _OVER; + } + code = 0; _OVER: @@ -650,7 +674,9 @@ static int32_t mndProcessDropTopicReq(SRpcMsg *pReq) { SMqConsumerObj *pConsumer; while (1) { pIter = sdbFetch(pSdb, SDB_CONSUMER, pIter, (void **)&pConsumer); - if (pIter == NULL) break; + if (pIter == NULL) { + break; + } if (pConsumer->status == MQ_CONSUMER_STATUS__LOST_REBD) continue; @@ -661,8 +687,8 @@ static int32_t mndProcessDropTopicReq(SRpcMsg *pReq) { mndReleaseConsumer(pMnode, pConsumer); mndReleaseTopic(pMnode, pTopic); terrno = TSDB_CODE_MND_TOPIC_SUBSCRIBED; - mError("topic:%s, failed to drop since subscribed by consumer:%" PRId64 ", in consumer group %s", dropReq.name, - pConsumer->consumerId, pConsumer->cgroup); + mError("topic:%s, failed to drop since subscribed by consumer:0x%" PRIx64 ", in consumer group %s", + dropReq.name, pConsumer->consumerId, pConsumer->cgroup); return -1; } } @@ -726,8 +752,9 @@ static int32_t mndProcessDropTopicReq(SRpcMsg *pReq) { if (pTopic->ntbUid != 0) { // broadcast to all vnode - void *pIter = NULL; + pIter = NULL; SVgObj *pVgroup = NULL; + while (1) { pIter = sdbFetch(pSdb, SDB_VGROUP, pIter, (void **)&pVgroup); if (pIter == NULL) break; @@ -767,6 +794,8 @@ static int32_t mndProcessDropTopicReq(SRpcMsg *pReq) { } static int32_t mndGetNumOfTopics(SMnode *pMnode, char *dbName, int32_t *pNumOfTopics) { + *pNumOfTopics = 0; + SSdb *pSdb = pMnode->pSdb; SDbObj *pDb = mndAcquireDb(pMnode, dbName); if (pDb == NULL) { @@ -779,7 +808,9 @@ static int32_t mndGetNumOfTopics(SMnode *pMnode, char *dbName, int32_t *pNumOfTo while (1) { SMqTopicObj *pTopic = NULL; pIter = sdbFetch(pSdb, SDB_TOPIC, pIter, (void **)&pTopic); - if (pIter == NULL) break; + if (pIter == NULL) { + break; + } if (pTopic->dbUid == pDb->uid) { numOfTopics++; @@ -807,29 +838,29 @@ static int32_t mndRetrieveTopic(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBl SName n; int32_t cols = 0; - char topicName[TSDB_TOPIC_NAME_LEN + VARSTR_HEADER_SIZE + 5] = {0}; - tstrncpy(varDataVal(topicName), mndGetDbStr(pTopic->name), sizeof(topicName) - 2); - /*tNameFromString(&n, pTopic->name, T_NAME_ACCT | T_NAME_DB);*/ - /*tNameGetDbName(&n, varDataVal(topicName));*/ - varDataSetLen(topicName, strlen(varDataVal(topicName))); + char topicName[TSDB_TOPIC_NAME_LEN + VARSTR_HEADER_SIZE + 5] = {0}; + const char *pName = mndGetDbStr(pTopic->name); + STR_TO_VARSTR(topicName, pName); + pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)topicName, false); + colDataSetVal(pColInfo, numOfRows, (const char *)topicName, false); char dbName[TSDB_DB_NAME_LEN + VARSTR_HEADER_SIZE] = {0}; tNameFromString(&n, pTopic->db, T_NAME_ACCT | T_NAME_DB); tNameGetDbName(&n, varDataVal(dbName)); varDataSetLen(dbName, strlen(varDataVal(dbName))); - pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)dbName, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pTopic->createTime, false); + colDataSetVal(pColInfo, numOfRows, (const char *)dbName, false); + + pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); + colDataSetVal(pColInfo, numOfRows, (const char *)&pTopic->createTime, false); char sql[TSDB_SHOW_SQL_LEN + VARSTR_HEADER_SIZE] = {0}; - tstrncpy(&sql[VARSTR_HEADER_SIZE], pTopic->sql, TSDB_SHOW_SQL_LEN); - varDataSetLen(sql, strlen(&sql[VARSTR_HEADER_SIZE])); + STR_TO_VARSTR(sql, pTopic->sql); + pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)sql, false); + colDataSetVal(pColInfo, numOfRows, (const char *)sql, false); numOfRows++; sdbRelease(pSdb, pTopic); @@ -862,24 +893,26 @@ static void mndCancelGetNextTopic(SMnode *pMnode, void *pIter) { sdbCancelFetch(pSdb, pIter); } -int32_t mndCheckTopicExist(SMnode *pMnode, SDbObj *pDb) { - SSdb *pSdb = pMnode->pSdb; - +bool mndTopicExistsForDb(SMnode *pMnode, SDbObj *pDb) { + SSdb *pSdb = pMnode->pSdb; void *pIter = NULL; SMqTopicObj *pTopic = NULL; + while (1) { pIter = sdbFetch(pSdb, SDB_TOPIC, pIter, (void **)&pTopic); - if (pIter == NULL) break; + if (pIter == NULL) { + break; + } if (pTopic->dbUid == pDb->uid) { sdbRelease(pSdb, pTopic); - terrno = TSDB_CODE_MND_TOPIC_MUST_BE_DELETED; - return -1; + return true; } sdbRelease(pSdb, pTopic); } - return 0; + + return false; } #if 0 diff --git a/source/dnode/mnode/impl/src/mndTrans.c b/source/dnode/mnode/impl/src/mndTrans.c index 5776d8a559..a34dfff4d6 100644 --- a/source/dnode/mnode/impl/src/mndTrans.c +++ b/source/dnode/mnode/impl/src/mndTrans.c @@ -655,6 +655,7 @@ STrans *mndTransCreate(SMnode *pMnode, ETrnPolicy policy, ETrnConflct conflict, taosArrayPush(pTrans->pRpcArray, &pReq->info); pTrans->originRpcType = pReq->msgType; } + mTrace("trans:%d, local object is created, data:%p", pTrans->id, pTrans); return pTrans; } @@ -1664,36 +1665,36 @@ static int32_t mndRetrieveTrans(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBl cols = 0; SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pTrans->id, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pTrans->id, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pTrans->createdTime, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pTrans->createdTime, false); char stage[TSDB_TRANS_STAGE_LEN + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(stage, mndTransStr(pTrans->stage), pShow->pMeta->pSchemas[cols].bytes); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)stage, false); + colDataSetVal(pColInfo, numOfRows, (const char *)stage, false); char opername[TSDB_TRANS_OPER_LEN + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(opername, pTrans->opername, pShow->pMeta->pSchemas[cols].bytes); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)opername, false); + colDataSetVal(pColInfo, numOfRows, (const char *)opername, false); char dbname[TSDB_DB_NAME_LEN + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(dbname, mndGetDbStr(pTrans->dbname), pShow->pMeta->pSchemas[cols].bytes); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)dbname, false); + colDataSetVal(pColInfo, numOfRows, (const char *)dbname, false); char stbname[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(stbname, mndGetDbStr(pTrans->stbname), pShow->pMeta->pSchemas[cols].bytes); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)stbname, false); + colDataSetVal(pColInfo, numOfRows, (const char *)stbname, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pTrans->failedTimes, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pTrans->failedTimes, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pTrans->lastExecTime, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pTrans->lastExecTime, false); char lastInfo[TSDB_TRANS_ERROR_LEN + VARSTR_HEADER_SIZE] = {0}; char detail[TSDB_TRANS_ERROR_LEN + 1] = {0}; @@ -1709,7 +1710,7 @@ static int32_t mndRetrieveTrans(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBl } STR_WITH_MAXSIZE_TO_VARSTR(lastInfo, detail, pShow->pMeta->pSchemas[cols].bytes); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)lastInfo, false); + colDataSetVal(pColInfo, numOfRows, (const char *)lastInfo, false); numOfRows++; sdbRelease(pSdb, pTrans); diff --git a/source/dnode/mnode/impl/src/mndUser.c b/source/dnode/mnode/impl/src/mndUser.c index b965e13316..23822c8f20 100644 --- a/source/dnode/mnode/impl/src/mndUser.c +++ b/source/dnode/mnode/impl/src/mndUser.c @@ -795,23 +795,23 @@ static int32_t mndRetrieveUsers(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBl SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols); char name[TSDB_USER_LEN + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(name, pUser->user, pShow->pMeta->pSchemas[cols].bytes); - colDataAppend(pColInfo, numOfRows, (const char *)name, false); + colDataSetVal(pColInfo, numOfRows, (const char *)name, false); cols++; pColInfo = taosArrayGet(pBlock->pDataBlock, cols); - colDataAppend(pColInfo, numOfRows, (const char *)&pUser->superUser, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pUser->superUser, false); cols++; pColInfo = taosArrayGet(pBlock->pDataBlock, cols); - colDataAppend(pColInfo, numOfRows, (const char *)&pUser->enable, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pUser->enable, false); cols++; pColInfo = taosArrayGet(pBlock->pDataBlock, cols); - colDataAppend(pColInfo, numOfRows, (const char *)&pUser->sysInfo, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pUser->sysInfo, false); cols++; pColInfo = taosArrayGet(pBlock->pDataBlock, cols); - colDataAppend(pColInfo, numOfRows, (const char *)&pUser->createdTime, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pUser->createdTime, false); numOfRows++; sdbRelease(pSdb, pUser); @@ -848,17 +848,17 @@ static int32_t mndRetrievePrivileges(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock char userName[TSDB_USER_LEN + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(userName, pUser->user, pShow->pMeta->pSchemas[cols].bytes); SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)userName, false); + colDataSetVal(pColInfo, numOfRows, (const char *)userName, false); char privilege[20] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(privilege, "all", pShow->pMeta->pSchemas[cols].bytes); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)privilege, false); + colDataSetVal(pColInfo, numOfRows, (const char *)privilege, false); char objName[20] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(objName, "all", pShow->pMeta->pSchemas[cols].bytes); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)objName, false); + colDataSetVal(pColInfo, numOfRows, (const char *)objName, false); numOfRows++; } @@ -869,12 +869,12 @@ static int32_t mndRetrievePrivileges(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock char userName[TSDB_USER_LEN + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(userName, pUser->user, pShow->pMeta->pSchemas[cols].bytes); SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)userName, false); + colDataSetVal(pColInfo, numOfRows, (const char *)userName, false); char privilege[20] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(privilege, "read", pShow->pMeta->pSchemas[cols].bytes); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)privilege, false); + colDataSetVal(pColInfo, numOfRows, (const char *)privilege, false); SName name = {0}; char objName[TSDB_DB_NAME_LEN + VARSTR_HEADER_SIZE] = {0}; @@ -882,7 +882,7 @@ static int32_t mndRetrievePrivileges(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock tNameGetDbName(&name, varDataVal(objName)); varDataSetLen(objName, strlen(varDataVal(objName))); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)objName, false); + colDataSetVal(pColInfo, numOfRows, (const char *)objName, false); numOfRows++; db = taosHashIterate(pUser->readDbs, db); @@ -894,12 +894,12 @@ static int32_t mndRetrievePrivileges(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock char userName[TSDB_USER_LEN + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(userName, pUser->user, pShow->pMeta->pSchemas[cols].bytes); SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)userName, false); + colDataSetVal(pColInfo, numOfRows, (const char *)userName, false); char privilege[20] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(privilege, "write", pShow->pMeta->pSchemas[cols].bytes); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)privilege, false); + colDataSetVal(pColInfo, numOfRows, (const char *)privilege, false); SName name = {0}; char objName[TSDB_DB_NAME_LEN + VARSTR_HEADER_SIZE] = {0}; @@ -907,7 +907,7 @@ static int32_t mndRetrievePrivileges(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock tNameGetDbName(&name, varDataVal(objName)); varDataSetLen(objName, strlen(varDataVal(objName))); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)objName, false); + colDataSetVal(pColInfo, numOfRows, (const char *)objName, false); numOfRows++; db = taosHashIterate(pUser->writeDbs, db); @@ -919,18 +919,18 @@ static int32_t mndRetrievePrivileges(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock char userName[TSDB_USER_LEN + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(userName, pUser->user, pShow->pMeta->pSchemas[cols].bytes); SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)userName, false); + colDataSetVal(pColInfo, numOfRows, (const char *)userName, false); char privilege[20] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(privilege, "subscribe", pShow->pMeta->pSchemas[cols].bytes); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)privilege, false); + colDataSetVal(pColInfo, numOfRows, (const char *)privilege, false); char topicName[TSDB_TOPIC_NAME_LEN + VARSTR_HEADER_SIZE + 5] = {0}; tstrncpy(varDataVal(topicName), mndGetDbStr(topic), TSDB_TOPIC_NAME_LEN - 2); varDataSetLen(topicName, strlen(varDataVal(topicName))); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)topicName, false); + colDataSetVal(pColInfo, numOfRows, (const char *)topicName, false); numOfRows++; topic = taosHashIterate(pUser->topics, topic); @@ -1062,10 +1062,14 @@ int32_t mndUserRemoveTopic(SMnode *pMnode, STrans *pTrans, char *topic) { while (1) { pIter = sdbFetch(pSdb, SDB_USER, pIter, (void **)&pUser); - if (pIter == NULL) break; + if (pIter == NULL) { + break; + } code = -1; - if (mndUserDupObj(pUser, &newUser) != 0) break; + if (mndUserDupObj(pUser, &newUser) != 0) { + break; + } bool inTopic = (taosHashGet(newUser.topics, topic, len) != NULL); if (inTopic) { diff --git a/source/dnode/mnode/impl/src/mndVgroup.c b/source/dnode/mnode/impl/src/mndVgroup.c index 171916b637..b7bcaf41fd 100644 --- a/source/dnode/mnode/impl/src/mndVgroup.c +++ b/source/dnode/mnode/impl/src/mndVgroup.c @@ -529,10 +529,10 @@ SArray *mndBuildDnodesArray(SMnode *pMnode, int32_t exceptDnodeId) { } static int32_t mndCompareDnodeId(int32_t *dnode1Id, int32_t *dnode2Id) { - if (*dnode1Id == *dnode2Id) { - return 0; - } - return *dnode1Id > *dnode2Id ? 1 : -1; + if (*dnode1Id == *dnode2Id) { + return 0; + } + return *dnode1Id > *dnode2Id ? 1 : -1; } static float mndGetDnodeScore(SDnodeObj *pDnode, int32_t additionDnodes, float ratio) { @@ -541,12 +541,12 @@ static float mndGetDnodeScore(SDnodeObj *pDnode, int32_t additionDnodes, float r } static int32_t mndCompareDnodeVnodes(SDnodeObj *pDnode1, SDnodeObj *pDnode2) { - float d1Score = mndGetDnodeScore(pDnode1, 0, 0.9); - float d2Score = mndGetDnodeScore(pDnode2, 0, 0.9); - if (d1Score == d2Score) { - return 0; - } - return d1Score > d2Score ? 1 : -1; + float d1Score = mndGetDnodeScore(pDnode1, 0, 0.9); + float d2Score = mndGetDnodeScore(pDnode2, 0, 0.9); + if (d1Score == d2Score) { + return 0; + } + return d1Score > d2Score ? 1 : -1; } void mndSortVnodeGid(SVgObj *pVgroup) { @@ -739,7 +739,7 @@ static int32_t mndRetrieveVgroups(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *p cols = 0; SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pVgroup->vgId, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pVgroup->vgId, false); SName name = {0}; char db[TSDB_DB_NAME_LEN + VARSTR_HEADER_SIZE] = {0}; @@ -748,17 +748,17 @@ static int32_t mndRetrieveVgroups(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *p varDataSetLen(db, strlen(varDataVal(db))); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)db, false); + colDataSetVal(pColInfo, numOfRows, (const char *)db, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pVgroup->numOfTables, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pVgroup->numOfTables, false); // default 3 replica, add 1 replica if move vnode for (int32_t i = 0; i < 4; ++i) { pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); if (i < pVgroup->replica) { int16_t dnodeId = (int16_t)pVgroup->vnodeGid[i].dnodeId; - colDataAppend(pColInfo, numOfRows, (const char *)&dnodeId, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&dnodeId, false); bool exist = false; bool online = false; @@ -789,24 +789,24 @@ static int32_t mndRetrieveVgroups(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *p STR_WITH_MAXSIZE_TO_VARSTR(buf1, role, pShow->pMeta->pSchemas[cols].bytes); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)buf1, false); + colDataSetVal(pColInfo, numOfRows, (const char *)buf1, false); } else { - colDataAppendNULL(pColInfo, numOfRows); + colDataSetNULL(pColInfo, numOfRows); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppendNULL(pColInfo, numOfRows); + colDataSetNULL(pColInfo, numOfRows); } } pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); int32_t cacheUsage = (int32_t)pVgroup->cacheUsage; - colDataAppend(pColInfo, numOfRows, (const char *)&cacheUsage, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&cacheUsage, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pVgroup->isTsma, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pVgroup->isTsma, false); // pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); // if (pDb == NULL || pDb->compactStartTime <= 0) { - // colDataAppendNULL(pColInfo, numOfRows); + // colDataSetNULL(pColInfo, numOfRows); // } else { // colDataAppend(pColInfo, numOfRows, (const char *)&pDb->compactStartTime, false); // } @@ -905,15 +905,15 @@ static int32_t mndRetrieveVnodes(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pB cols = 0; pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pVgroup->vgId, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pVgroup->vgId, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pVgroup->replica, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pVgroup->replica, false); char buf[20] = {0}; STR_TO_VARSTR(buf, syncStr(pVgid->syncState)); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)buf, false); + colDataSetVal(pColInfo, numOfRows, (const char *)buf, false); const char *dbname = mndGetDbStr(pVgroup->dbName); char b1[TSDB_DB_NAME_LEN + VARSTR_HEADER_SIZE] = {0}; @@ -923,10 +923,10 @@ static int32_t mndRetrieveVnodes(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pB STR_WITH_MAXSIZE_TO_VARSTR(b1, "NULL", TSDB_DB_NAME_LEN + VARSTR_HEADER_SIZE); } pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)b1, false); + colDataSetVal(pColInfo, numOfRows, (const char *)b1, false); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)&pVgid->dnodeId, false); + colDataSetVal(pColInfo, numOfRows, (const char *)&pVgid->dnodeId, false); SDnodeObj *pDnode = mndAcquireDnode(pMnode, pVgid->dnodeId); char b2[TSDB_EP_LEN + VARSTR_HEADER_SIZE] = {0}; @@ -936,7 +936,7 @@ static int32_t mndRetrieveVnodes(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pB STR_WITH_MAXSIZE_TO_VARSTR(b2, "NULL", TSDB_EP_LEN + VARSTR_HEADER_SIZE); } pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); - colDataAppend(pColInfo, numOfRows, (const char *)b2, false); + colDataSetVal(pColInfo, numOfRows, (const char *)b2, false); numOfRows++; } diff --git a/source/dnode/mnode/impl/test/trans/trans2.cpp b/source/dnode/mnode/impl/test/trans/trans2.cpp index 89c2b6931a..2d03631a37 100644 --- a/source/dnode/mnode/impl/test/trans/trans2.cpp +++ b/source/dnode/mnode/impl/test/trans/trans2.cpp @@ -124,7 +124,7 @@ class MndTestTrans2 : public ::testing::Test { mndTransAppendUndolog(pTrans, pUndoRaw); sdbSetRawStatus(pUndoRaw, SDB_STATUS_DROPPED); - char *param = strdup("====> test log <====="); + char *param = taosStrdup("====> test log <====="); mndTransSetCb(pTrans, TRANS_START_FUNC_TEST, TRANS_STOP_FUNC_TEST, param, strlen(param) + 1); if (pDb != NULL) { @@ -157,7 +157,7 @@ class MndTestTrans2 : public ::testing::Test { mndTransAppendUndolog(pTrans, pUndoRaw); sdbSetRawStatus(pUndoRaw, SDB_STATUS_DROPPED); - char *param = strdup("====> test action <====="); + char *param = taosStrdup("====> test action <====="); mndTransSetCb(pTrans, TRANS_START_FUNC_TEST, TRANS_STOP_FUNC_TEST, param, strlen(param) + 1); { @@ -229,7 +229,7 @@ class MndTestTrans2 : public ::testing::Test { mndTransAppendUndolog(pTrans, pUndoRaw); sdbSetRawStatus(pUndoRaw, SDB_STATUS_DROPPED); - char *param = strdup("====> test log <====="); + char *param = taosStrdup("====> test log <====="); mndTransSetCb(pTrans, TRANS_START_FUNC_TEST, TRANS_STOP_FUNC_TEST, param, strlen(param) + 1); int32_t code = mndTransPrepare(pMnode, pTrans); diff --git a/source/dnode/mnode/sdb/src/sdb.c b/source/dnode/mnode/sdb/src/sdb.c index 648ccff432..bb8040da07 100644 --- a/source/dnode/mnode/sdb/src/sdb.c +++ b/source/dnode/mnode/sdb/src/sdb.c @@ -30,9 +30,9 @@ SSdb *sdbInit(SSdbOpt *pOption) { char path[PATH_MAX + 100] = {0}; snprintf(path, sizeof(path), "%s%sdata", pOption->path, TD_DIRSEP); - pSdb->currDir = strdup(path); + pSdb->currDir = taosStrdup(path); snprintf(path, sizeof(path), "%s%stmp", pOption->path, TD_DIRSEP); - pSdb->tmpDir = strdup(path); + pSdb->tmpDir = taosStrdup(path); if (pSdb->currDir == NULL || pSdb->tmpDir == NULL) { sdbCleanup(pSdb); terrno = TSDB_CODE_OUT_OF_MEMORY; diff --git a/source/dnode/mnode/sdb/src/sdbFile.c b/source/dnode/mnode/sdb/src/sdbFile.c index c2d7a9757a..c2d27ad713 100644 --- a/source/dnode/mnode/sdb/src/sdbFile.c +++ b/source/dnode/mnode/sdb/src/sdbFile.c @@ -472,7 +472,7 @@ int32_t sdbWriteFile(SSdb *pSdb, int32_t delta) { taosThreadMutexLock(&pSdb->filelock); if (pSdb->pWal != NULL) { - // code = walBeginSnapshot(pSdb->pWal, pSdb->applyIndex); + // code = walBeginSnapshot(pSdb->pWal, pSdb->applyIndex, 0); if (pSdb->sync == 0) { code = 0; } else { @@ -521,7 +521,7 @@ static SSdbIter *sdbCreateIter(SSdb *pSdb) { char name[PATH_MAX + 100] = {0}; snprintf(name, sizeof(name), "%s%ssdb.data.%" PRIu64, pSdb->tmpDir, TD_DIRSEP, (uint64_t)pIter); - pIter->name = strdup(name); + pIter->name = taosStrdup(name); if (pIter->name == NULL) { taosMemoryFree(pIter); terrno = TSDB_CODE_OUT_OF_MEMORY; diff --git a/source/dnode/qnode/inc/qndInt.h b/source/dnode/qnode/inc/qndInt.h index e8ccb75040..86deda52ad 100644 --- a/source/dnode/qnode/inc/qndInt.h +++ b/source/dnode/qnode/inc/qndInt.h @@ -29,7 +29,7 @@ extern "C" { #endif -typedef struct SQWorker SQHandle; +typedef struct SQueueWorker SQHandle; typedef struct SQnode { int32_t qndId; diff --git a/source/dnode/snode/src/snode.c b/source/dnode/snode/src/snode.c index 1d2f4da26b..d4ca81a6a9 100644 --- a/source/dnode/snode/src/snode.c +++ b/source/dnode/snode/src/snode.c @@ -104,7 +104,7 @@ SSnode *sndOpen(const char *path, const SSnodeOpt *pOption) { terrno = TSDB_CODE_OUT_OF_MEMORY; return NULL; } - pSnode->path = strdup(path); + pSnode->path = taosStrdup(path); if (pSnode->path == NULL) { terrno = TSDB_CODE_OUT_OF_MEMORY; goto FAIL; diff --git a/source/dnode/vnode/src/inc/vnodeInt.h b/source/dnode/vnode/src/inc/vnodeInt.h index eda47bf5de..93e611e870 100644 --- a/source/dnode/vnode/src/inc/vnodeInt.h +++ b/source/dnode/vnode/src/inc/vnodeInt.h @@ -58,7 +58,7 @@ typedef struct STQ STQ; typedef struct SVState SVState; typedef struct SVStatis SVStatis; typedef struct SVBufPool SVBufPool; -typedef struct SQWorker SQHandle; +typedef struct SQueueWorker SQHandle; typedef struct STsdbKeepCfg STsdbKeepCfg; typedef struct SMetaSnapReader SMetaSnapReader; typedef struct SMetaSnapWriter SMetaSnapWriter; diff --git a/source/dnode/vnode/src/meta/metaQuery.c b/source/dnode/vnode/src/meta/metaQuery.c index 91518f7a0b..4b1163bb11 100644 --- a/source/dnode/vnode/src/meta/metaQuery.c +++ b/source/dnode/vnode/src/meta/metaQuery.c @@ -706,7 +706,7 @@ int32_t metaGetTbTSchemaEx(SMeta *pMeta, tb_uid_t suid, tb_uid_t uid, int32_t sv } } - if (ASSERTS(sver > 0, __FILE__, __LINE__, "failed to get table schema version: %d", sver)) { + if (ASSERTS(sver > 0, "failed to get table schema version: %d", sver)) { code = TSDB_CODE_NOT_FOUND; goto _exit; } diff --git a/source/dnode/vnode/src/meta/metaSnapshot.c b/source/dnode/vnode/src/meta/metaSnapshot.c index 6e505dfde5..67ade45732 100644 --- a/source/dnode/vnode/src/meta/metaSnapshot.c +++ b/source/dnode/vnode/src/meta/metaSnapshot.c @@ -252,7 +252,7 @@ static void saveSuperTableInfoForChildTable(SMetaEntry* me, SHashObj* suidInfo) return; } STableInfoForChildTable dataTmp = {0}; - dataTmp.tableName = strdup(me->name); + dataTmp.tableName = taosStrdup(me->name); dataTmp.schemaRow = tCloneSSchemaWrapper(&me->stbEntry.schemaRow); dataTmp.tagRow = tCloneSSchemaWrapper(&me->stbEntry.schemaTag); diff --git a/source/dnode/vnode/src/sma/smaEnv.c b/source/dnode/vnode/src/sma/smaEnv.c index a980b653a9..02766c8076 100644 --- a/source/dnode/vnode/src/sma/smaEnv.c +++ b/source/dnode/vnode/src/sma/smaEnv.c @@ -291,10 +291,7 @@ static void tdDestroyRSmaStat(void *pRSmaStat) { // step 1: set rsma trigger stat cancelled atomic_store_8(RSMA_TRIGGER_STAT(pStat), TASK_TRIGGER_STAT_CANCELLED); - // step 2: destroy the rsma info and associated fetch tasks - taosHashCleanup(RSMA_INFO_HASH(pStat)); - - // step 3: wait for all triggered fetch tasks to finish + // step 2: wait for all triggered fetch tasks to finish int32_t nLoops = 0; while (1) { if (T_REF_VAL_GET((SSmaStat *)pStat) == 0) { @@ -310,9 +307,12 @@ static void tdDestroyRSmaStat(void *pRSmaStat) { } } - // step 4: + // step 3: tdRsmaStopExecutor(pSma); + // step 4: destroy the rsma info and associated fetch tasks + taosHashCleanup(RSMA_INFO_HASH(pStat)); + // step 5: tdRSmaFSClose(RSMA_FS(pStat)); diff --git a/source/dnode/vnode/src/sma/smaFS.c b/source/dnode/vnode/src/sma/smaFS.c index 5dbe91f836..1211ef9405 100644 --- a/source/dnode/vnode/src/sma/smaFS.c +++ b/source/dnode/vnode/src/sma/smaFS.c @@ -559,7 +559,7 @@ int32_t tdRSmaFSRef(SSma *pSma, SRSmaFS *pFS) { SRSmaFS *qFS = RSMA_FS(pStat); int32_t size = taosArrayGetSize(qFS->aQTaskInf); - pFS->aQTaskInf = taosArrayInit_s(size, sizeof(SQTaskFile), size); + pFS->aQTaskInf = taosArrayInit_s(sizeof(SQTaskFile), size); if (pFS->aQTaskInf == NULL) { code = TSDB_CODE_OUT_OF_MEMORY; TSDB_CHECK_CODE(code, lino, _exit); diff --git a/source/dnode/vnode/src/sma/smaRollup.c b/source/dnode/vnode/src/sma/smaRollup.c index 809e553ab6..37ae7d895e 100644 --- a/source/dnode/vnode/src/sma/smaRollup.c +++ b/source/dnode/vnode/src/sma/smaRollup.c @@ -262,7 +262,7 @@ static int32_t tdSetRSmaInfoItemParams(SSma *pSma, SRSmaParam *param, SRSmaStat // set the backend of stream state tdRSmaQTaskInfoGetFullPathEx(TD_VID(pVnode), pRSmaInfo->suid, idx + 1, tfsGetPrimaryPath(pVnode->pTfs), taskInfDir); if (!taosCheckExistFile(taskInfDir)) { - char *s = strdup(taskInfDir); + char *s = taosStrdup(taskInfDir); if (taosMulMkDir(taosDirName(s)) != 0) { terrno = TAOS_SYSTEM_ERROR(errno); taosMemoryFree(s); diff --git a/source/dnode/vnode/src/sma/smaTimeRange.c b/source/dnode/vnode/src/sma/smaTimeRange.c index e7f03d668e..5058a7fc76 100644 --- a/source/dnode/vnode/src/sma/smaTimeRange.c +++ b/source/dnode/vnode/src/sma/smaTimeRange.c @@ -208,7 +208,7 @@ int32_t smaBlockToSubmit(SVnode *pVnode, const SArray *pBlocks, const STSchema * // set super table name SName name = {0}; tNameFromString(&name, stbFullName, T_NAME_ACCT | T_NAME_DB | T_NAME_TABLE); - pCreateTbReq->ctb.stbName = strdup((char *)tNameGetTableName(&name)); // strdup(stbFullName); + pCreateTbReq->ctb.stbName = taosStrdup((char *)tNameGetTableName(&name)); // taosStrdup(stbFullName); // set tag content taosArrayClear(tagArray); @@ -237,7 +237,7 @@ int32_t smaBlockToSubmit(SVnode *pVnode, const SArray *pBlocks, const STSchema * // set table name if (pDataBlock->info.parTbName[0]) { - pCreateTbReq->name = strdup(pDataBlock->info.parTbName); + pCreateTbReq->name = taosStrdup(pDataBlock->info.parTbName); } else { pCreateTbReq->name = buildCtbNameByGroupId(stbFullName, pDataBlock->info.id.groupId); } diff --git a/source/dnode/vnode/src/tq/tq.c b/source/dnode/vnode/src/tq/tq.c index 9bdd8f4bdf..c9bbb30380 100644 --- a/source/dnode/vnode/src/tq/tq.c +++ b/source/dnode/vnode/src/tq/tq.c @@ -78,7 +78,7 @@ STQ* tqOpen(const char* path, SVnode* pVnode) { terrno = TSDB_CODE_OUT_OF_MEMORY; return NULL; } - pTq->path = strdup(path); + pTq->path = taosStrdup(path); pTq->pVnode = pVnode; pTq->walLogLastVer = pVnode->pWal->vers.lastVer; @@ -114,16 +114,18 @@ STQ* tqOpen(const char* path, SVnode* pVnode) { } void tqClose(STQ* pTq) { - if (pTq) { - tqOffsetClose(pTq->pOffsetStore); - taosHashCleanup(pTq->pHandle); - taosHashCleanup(pTq->pPushMgr); - taosHashCleanup(pTq->pCheckInfo); - taosMemoryFree(pTq->path); - tqMetaClose(pTq); - streamMetaClose(pTq->pStreamMeta); - taosMemoryFree(pTq); + if (pTq == NULL) { + return; } + + tqOffsetClose(pTq->pOffsetStore); + taosHashCleanup(pTq->pHandle); + taosHashCleanup(pTq->pPushMgr); + taosHashCleanup(pTq->pCheckInfo); + taosMemoryFree(pTq->path); + tqMetaClose(pTq); + streamMetaClose(pTq->pStreamMeta); + taosMemoryFree(pTq); } int32_t tqSendMetaPollRsp(STQ* pTq, const SRpcMsg* pMsg, const SMqPollReq* pReq, const SMqMetaRsp* pRsp) { @@ -158,7 +160,7 @@ int32_t tqSendMetaPollRsp(STQ* pTq, const SRpcMsg* pMsg, const SMqPollReq* pReq, }; tmsgSendRsp(&resp); - tqDebug("vgId:%d, from consumer:%" PRId64 ", (epoch %d) send rsp, res msg type %d, offset type:%d", + tqDebug("vgId:%d, from consumer:0x%" PRIx64 " (epoch %d) send rsp, res msg type %d, offset type:%d", TD_VID(pTq->pVnode), pReq->consumerId, pReq->epoch, pRsp->resMsgType, pRsp->rspOffset.type); return 0; @@ -213,9 +215,9 @@ int32_t tqPushDataRsp(STQ* pTq, STqPushEntry* pPushEntry) { char buf1[80] = {0}; char buf2[80] = {0}; - tFormatOffset(buf1, 80, &pRsp->reqOffset); - tFormatOffset(buf2, 80, &pRsp->rspOffset); - tqDebug("vgId:%d, from consumer:%" PRId64 ", (epoch %d) push rsp, block num: %d, reqOffset:%s, rspOffset:%s", + tFormatOffset(buf1, tListLen(buf1), &pRsp->reqOffset); + tFormatOffset(buf2, tListLen(buf2), &pRsp->rspOffset); + tqDebug("vgId:%d, from consumer:0x%" PRIx64 " (epoch %d) push rsp, block num: %d, reqOffset:%s, rspOffset:%s", TD_VID(pTq->pVnode), pRsp->head.consumerId, pRsp->head.epoch, pRsp->blockNum, buf1, buf2); return 0; @@ -273,7 +275,7 @@ int32_t tqSendDataRsp(STQ* pTq, const SRpcMsg* pMsg, const SMqPollReq* pReq, con char buf2[80] = {0}; tFormatOffset(buf1, 80, &pRsp->reqOffset); tFormatOffset(buf2, 80, &pRsp->rspOffset); - tqDebug("vgId:%d, from consumer:%" PRId64 ", (epoch %d) send rsp, block num: %d, reqOffset:%s, rspOffset:%s", + tqDebug("vgId:%d consumer:0x%" PRIx64 " (epoch %d), block num:%d, reqOffset:%s, rspOffset:%s", TD_VID(pTq->pVnode), pReq->consumerId, pReq->epoch, pRsp->blockNum, buf1, buf2); return 0; @@ -334,8 +336,7 @@ int32_t tqSendTaosxRsp(STQ* pTq, const SRpcMsg* pMsg, const SMqPollReq* pReq, co char buf2[80] = {0}; tFormatOffset(buf1, 80, &pRsp->reqOffset); tFormatOffset(buf2, 80, &pRsp->rspOffset); - tqDebug("taosx rsp, vgId:%d, from consumer:%" PRId64 - ", (epoch %d) send rsp, block num: %d, reqOffset:%s, rspOffset:%s", + tqDebug("taosx rsp, vgId:%d, from consumer:0x%" PRIx64 " (epoch %d) send rsp, numOfBlks:%d, req:%s, rsp:%s", TD_VID(pTq->pVnode), pReq->consumerId, pReq->epoch, pRsp->blockNum, buf1, buf2); return 0; @@ -346,13 +347,15 @@ static FORCE_INLINE bool tqOffsetLessOrEqual(const STqOffset* pLeft, const STqOf pLeft->val.version <= pRight->val.version; } -int32_t tqProcessOffsetCommitReq(STQ* pTq, int64_t version, char* msg, int32_t msgLen) { +int32_t tqProcessOffsetCommitReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) { STqOffset offset = {0}; - SDecoder decoder; - tDecoderInit(&decoder, msg, msgLen); + + SDecoder decoder; + tDecoderInit(&decoder, (uint8_t*)msg, msgLen); if (tDecodeSTqOffset(&decoder, &offset) < 0) { return -1; } + tDecoderClear(&decoder); if (offset.val.type == TMQ_OFFSET__SNAPSHOT_DATA || offset.val.type == TMQ_OFFSET__SNAPSHOT_META) { @@ -361,44 +364,45 @@ int32_t tqProcessOffsetCommitReq(STQ* pTq, int64_t version, char* msg, int32_t m } else if (offset.val.type == TMQ_OFFSET__LOG) { tqDebug("receive offset commit msg to %s on vgId:%d, offset(type:log) version:%" PRId64, offset.subKey, TD_VID(pTq->pVnode), offset.val.version); - if (offset.val.version + 1 == version) { + if (offset.val.version + 1 == sversion) { offset.val.version += 1; } - /*} else {*/ - /*A(0);*/ - } - STqOffset* pOffset = tqOffsetRead(pTq->pOffsetStore, offset.subKey); - if (pOffset != NULL && tqOffsetLessOrEqual(&offset, pOffset)) { - return 0; + } else { + tqError("invalid commit offset type:%d", offset.val.type); + return -1; } + STqOffset* pSavedOffset = tqOffsetRead(pTq->pOffsetStore, offset.subKey); + if (pSavedOffset != NULL && tqOffsetLessOrEqual(&offset, pSavedOffset)) { + return 0; // no need to update the offset value + } + + // save the new offset value if (tqOffsetWrite(pTq->pOffsetStore, &offset) < 0) { return -1; } if (offset.val.type == TMQ_OFFSET__LOG) { STqHandle* pHandle = taosHashGet(pTq->pHandle, offset.subKey, strlen(offset.subKey)); - if (pHandle) { - if (walRefVer(pHandle->pRef, offset.val.version) < 0) { - return -1; - } + if (pHandle && (walRefVer(pHandle->pRef, offset.val.version) < 0)) { + return -1; } } - // rsp - - /*}*/ - /*}*/ - return 0; } int32_t tqCheckColModifiable(STQ* pTq, int64_t tbUid, int32_t colId) { void* pIter = NULL; + while (1) { pIter = taosHashIterate(pTq->pCheckInfo, pIter); - if (pIter == NULL) break; + if (pIter == NULL) { + break; + } + STqCheckInfo* pCheck = (STqCheckInfo*)pIter; + if (pCheck->ntbUid == tbUid) { int32_t sz = taosArrayGetSize(pCheck->colIdList); for (int32_t i = 0; i < sz; i++) { @@ -410,6 +414,7 @@ int32_t tqCheckColModifiable(STQ* pTq, int64_t tbUid, int32_t colId) { } } } + return 0; } @@ -454,6 +459,7 @@ static int32_t tqInitTaosxRsp(STaosxRsp* pRsp, const SMqPollReq* pReq) { if (pRsp->blockData == NULL || pRsp->blockDataLen == NULL || pRsp->blockTbName == NULL || pRsp->blockSchema == NULL) { return -1; } + return 0; } @@ -472,32 +478,32 @@ int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg) { int32_t reqEpoch = req.epoch; STqOffsetVal reqOffset = req.reqOffset; - // 1.find handle + // 1. find handle STqHandle* pHandle = taosHashGet(pTq->pHandle, req.subKey, strlen(req.subKey)); if (pHandle == NULL) { - tqError("tmq poll: no consumer handle for consumer:%" PRId64 ", in vgId:%d, subkey %s", consumerId, - TD_VID(pTq->pVnode), req.subKey); + tqError("tmq poll: consumer:0x%" PRIx64 " vgId:%d, subkey %s not found", consumerId, TD_VID(pTq->pVnode), + req.subKey); return -1; } - // check rebalance + // 2. check rebalance if (pHandle->consumerId != consumerId) { - tqError("tmq poll: consumer handle mismatch for consumer:%" PRId64 - ", in vgId:%d, subkey %s, handle consumer id %" PRId64, + tqError("tmq poll: consumer:0x%" PRIx64 " vgId:%d, subkey %s, mismatch for saved handle consumer:0x%" PRIx64, consumerId, TD_VID(pTq->pVnode), req.subKey, pHandle->consumerId); terrno = TSDB_CODE_TMQ_CONSUMER_MISMATCH; return -1; } // update epoch if need - int32_t consumerEpoch = atomic_load_32(&pHandle->epoch); - while (consumerEpoch < reqEpoch) { - consumerEpoch = atomic_val_compare_exchange_32(&pHandle->epoch, consumerEpoch, reqEpoch); + int32_t savedEpoch = atomic_load_32(&pHandle->epoch); + while (savedEpoch < reqEpoch) { + tqDebug("tmq poll: consumer:0x%"PRIx64 " epoch update from %d to %d by poll req", consumerId, savedEpoch, reqEpoch); + savedEpoch = atomic_val_compare_exchange_32(&pHandle->epoch, savedEpoch, reqEpoch); } char buf[80]; tFormatOffset(buf, 80, &reqOffset); - tqDebug("tmq poll: consumer %" PRId64 " (epoch %d), subkey %s, recv poll req in vg %d, req offset %s", consumerId, + tqDebug("tmq poll: consumer:0x%" PRIx64 " (epoch %d), subkey %s, recv poll req vgId:%d, req:%s", consumerId, req.epoch, pHandle->subKey, TD_VID(pTq->pVnode), buf); // 2.reset offset if needed @@ -509,7 +515,7 @@ int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg) { fetchOffsetNew = pOffset->val; char formatBuf[80]; tFormatOffset(formatBuf, 80, &fetchOffsetNew); - tqDebug("tmq poll: consumer %" PRId64 ", subkey %s, vg %d, offset reset to %s", consumerId, pHandle->subKey, + tqDebug("tmq poll: consumer:0x%" PRIx64 ", subkey %s, vg %d, offset reset to %s", consumerId, pHandle->subKey, TD_VID(pTq->pVnode), formatBuf); } else { if (reqOffset.type == TMQ_OFFSET__RESET_EARLIEAST) { @@ -533,7 +539,7 @@ int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg) { tqInitDataRsp(&dataRsp, &req, pHandle->execHandle.subType); tqOffsetResetToLog(&dataRsp.rspOffset, walGetLastVer(pTq->pVnode->pWal)); - tqDebug("tmq poll: consumer %" PRId64 ", subkey %s, vg %d, offset reset to %" PRId64, consumerId, + tqDebug("tmq poll: consumer:0x%" PRIx64 ", subkey %s, vgId:%d, offset reset to %" PRId64, consumerId, pHandle->subKey, TD_VID(pTq->pVnode), dataRsp.rspOffset.version); if (tqSendDataRsp(pTq, pMsg, &req, &dataRsp) < 0) { code = -1; @@ -551,7 +557,7 @@ int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg) { return code; } } else if (reqOffset.type == TMQ_OFFSET__RESET_NONE) { - tqError("tmq poll: subkey %s, no offset committed for consumer %" PRId64 + tqError("tmq poll: subkey %s, no offset committed for consumer:0x%" PRIx64 " in vg %d, subkey %s, reset none failed", pHandle->subKey, consumerId, TD_VID(pTq->pVnode), req.subKey); terrno = TSDB_CODE_TQ_NO_COMMITTED_OFFSET; @@ -570,6 +576,7 @@ int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg) { } #if 1 + // till now, all data has been rsp to consumer, new data needs to push client once arrived. if (dataRsp.blockNum == 0 && dataRsp.reqOffset.type == TMQ_OFFSET__LOG && dataRsp.reqOffset.version == dataRsp.rspOffset.version) { STqPushEntry* pPushEntry = taosMemoryCalloc(1, sizeof(STqPushEntry)); @@ -582,8 +589,9 @@ int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg) { pPushEntry->dataRsp.head.epoch = reqEpoch; pPushEntry->dataRsp.head.mqMsgType = TMQ_MSG_TYPE__POLL_RSP; taosHashPut(pTq->pPushMgr, pHandle->subKey, strlen(pHandle->subKey) + 1, &pPushEntry, sizeof(void*)); - tqDebug("tmq poll: consumer %" PRId64 ", subkey %s, vg %d save handle to push mgr", consumerId, pHandle->subKey, - TD_VID(pTq->pVnode)); + + tqDebug("tmq poll: consumer:0x%" PRIx64 ", subkey %s offset:%" PRId64 ", vgId:%d save handle to push mgr", + consumerId, pHandle->subKey, dataRsp.reqOffset.version, TD_VID(pTq->pVnode)); // unlock taosWUnLockLatch(&pTq->pushLock); return 0; @@ -596,8 +604,7 @@ int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg) { code = -1; } - tqDebug("tmq poll: consumer %" PRId64 - ", subkey %s, vg %d, send data blockNum:%d, offset type:%d, uid/version:%" PRId64 ", ts:%" PRId64 "", + tqDebug("tmq poll: consumer:0x%" PRIx64 ", subkey %s, vgId:%d, rsp data block:%d, offset type:%d, uid/version:%" PRId64 ", ts:%" PRId64 "", consumerId, pHandle->subKey, TD_VID(pTq->pVnode), dataRsp.blockNum, dataRsp.rspOffset.type, dataRsp.rspOffset.uid, dataRsp.rspOffset.ts); @@ -622,8 +629,8 @@ int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg) { if (tqSendMetaPollRsp(pTq, pMsg, &req, &metaRsp) < 0) { code = -1; } - tqDebug("tmq poll: consumer %" PRId64 ", subkey %s, vg %d, send meta offset type:%d,uid:%" PRId64 - ",version:%" PRId64 "", + tqDebug("tmq poll: consumer:0x%" PRIx64 " subkey %s, vg %d, send meta offset type:%d,uid:%" PRId64 + ",version:%" PRId64, consumerId, pHandle->subKey, TD_VID(pTq->pVnode), metaRsp.rspOffset.type, metaRsp.rspOffset.uid, metaRsp.rspOffset.version); taosMemoryFree(metaRsp.metaRsp); @@ -641,8 +648,8 @@ int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg) { fetchOffsetNew = taosxRsp.rspOffset; } - tqDebug("taosx poll: consumer %" PRId64 ", subkey %s, vg %d, send data blockNum:%d, offset type:%d,uid:%" PRId64 - ",version:%" PRId64 "", + tqDebug("taosx poll: consumer:0x%" PRIx64 " subkey %s, vg %d, send data blockNum:%d, offset type:%d,uid:%" PRId64 + ",version:%" PRId64, consumerId, pHandle->subKey, TD_VID(pTq->pVnode), taosxRsp.blockNum, taosxRsp.rspOffset.type, taosxRsp.rspOffset.uid, taosxRsp.rspOffset.version); } @@ -658,11 +665,11 @@ int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg) { walSetReaderCapacity(pHandle->pWalReader, 2048); while (1) { - consumerEpoch = atomic_load_32(&pHandle->epoch); - if (consumerEpoch > reqEpoch) { - tqWarn("tmq poll: consumer %" PRId64 " (epoch %d), subkey %s, vg %d offset %" PRId64 + savedEpoch = atomic_load_32(&pHandle->epoch); + if (savedEpoch > reqEpoch) { + tqWarn("tmq poll: consumer:0x%" PRIx64 " (epoch %d), subkey %s, vg %d offset %" PRId64 ", found new consumer epoch %d, discard req epoch %d", - consumerId, req.epoch, pHandle->subKey, TD_VID(pTq->pVnode), fetchVer, consumerEpoch, reqEpoch); + consumerId, req.epoch, pHandle->subKey, TD_VID(pTq->pVnode), fetchVer, savedEpoch, reqEpoch); break; } @@ -678,7 +685,7 @@ int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg) { SWalCont* pHead = &pCkHead->head; - tqDebug("tmq poll: consumer:%" PRId64 ", (epoch %d) iter log, vgId:%d offset %" PRId64 " msgType %d", consumerId, + tqDebug("tmq poll: consumer:0x%" PRIx64 " (epoch %d) iter log, vgId:%d offset %" PRId64 " msgType %d", consumerId, req.epoch, TD_VID(pTq->pVnode), fetchVer, pHead->msgType); if (pHead->msgType == TDMT_VND_SUBMIT) { @@ -725,12 +732,13 @@ int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg) { } } } + tDeleteSTaosxRsp(&taosxRsp); taosMemoryFreeClear(pCkHead); return 0; } -int32_t tqProcessDeleteSubReq(STQ* pTq, int64_t version, char* msg, int32_t msgLen) { +int32_t tqProcessDeleteSubReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) { SMqVDeleteReq* pReq = (SMqVDeleteReq*)msg; tqDebug("vgId:%d, tq process delete sub req %s", pTq->pVnode->config.vgId, pReq->subKey); @@ -765,10 +773,10 @@ int32_t tqProcessDeleteSubReq(STQ* pTq, int64_t version, char* msg, int32_t msgL return 0; } -int32_t tqProcessAddCheckInfoReq(STQ* pTq, int64_t version, char* msg, int32_t msgLen) { +int32_t tqProcessAddCheckInfoReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) { STqCheckInfo info = {0}; SDecoder decoder; - tDecoderInit(&decoder, msg, msgLen); + tDecoderInit(&decoder, (uint8_t*)msg, msgLen); if (tDecodeSTqCheckInfo(&decoder, &info) < 0) { terrno = TSDB_CODE_OUT_OF_MEMORY; return -1; @@ -785,7 +793,7 @@ int32_t tqProcessAddCheckInfoReq(STQ* pTq, int64_t version, char* msg, int32_t m return 0; } -int32_t tqProcessDelCheckInfoReq(STQ* pTq, int64_t version, char* msg, int32_t msgLen) { +int32_t tqProcessDelCheckInfoReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) { if (taosHashRemove(pTq->pCheckInfo, msg, strlen(msg)) < 0) { terrno = TSDB_CODE_OUT_OF_MEMORY; return -1; @@ -797,7 +805,7 @@ int32_t tqProcessDelCheckInfoReq(STQ* pTq, int64_t version, char* msg, int32_t m return 0; } -int32_t tqProcessSubscribeReq(STQ* pTq, int64_t version, char* msg, int32_t msgLen) { +int32_t tqProcessSubscribeReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) { SMqRebVgReq req = {0}; tDecodeSMqRebVgReq(msg, &req); // todo lock @@ -807,7 +815,7 @@ int32_t tqProcessSubscribeReq(STQ* pTq, int64_t version, char* msg, int32_t msgL STqHandle* pHandle = taosHashGet(pTq->pHandle, req.subKey, strlen(req.subKey)); if (pHandle == NULL) { if (req.oldConsumerId != -1) { - tqError("vgId:%d, build new consumer handle %s for consumer %" PRId64 ", but old consumerId is %" PRId64 "", + tqError("vgId:%d, build new consumer handle %s for consumer:0x%" PRIx64 ", but old consumerId is %" PRId64 "", req.vgId, req.subKey, req.newConsumerId, req.oldConsumerId); } if (req.newConsumerId == -1) { @@ -882,7 +890,7 @@ int32_t tqProcessSubscribeReq(STQ* pTq, int64_t version, char* msg, int32_t msgL pHandle->execHandle.task = qCreateQueueExecTaskInfo(NULL, &handle, NULL, NULL); } taosHashPut(pTq->pHandle, req.subKey, strlen(req.subKey), pHandle, sizeof(STqHandle)); - tqDebug("try to persist handle %s consumer %" PRId64, req.subKey, pHandle->consumerId); + tqDebug("try to persist handle %s consumer:0x%" PRIx64, req.subKey, pHandle->consumerId); if (tqMetaSaveHandle(pTq, req.subKey, pHandle) < 0) { return -1; } @@ -996,7 +1004,7 @@ int32_t tqProcessStreamTaskCheckReq(STQ* pTq, SRpcMsg* pMsg) { int32_t msgLen = pMsg->contLen - sizeof(SMsgHead); SStreamTaskCheckReq req; SDecoder decoder; - tDecoderInit(&decoder, msgBody, msgLen); + tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen); tDecodeSStreamTaskCheckReq(&decoder, &req); tDecoderClear(&decoder); int32_t taskId = req.downstreamTaskId; @@ -1018,7 +1026,7 @@ int32_t tqProcessStreamTaskCheckReq(STQ* pTq, SRpcMsg* pMsg) { if (pTask) streamMetaReleaseTask(pTq->pStreamMeta, pTask); - tqDebug("tq recv task check req(reqId: %" PRId64 ") %d at node %d check req from task %d at node %d, status %d", + tqDebug("tq recv task check req(reqId:0x%" PRIx64 ") %d at node %d check req from task %d at node %d, status %d", rsp.reqId, rsp.downstreamTaskId, rsp.downstreamNodeId, rsp.upstreamTaskId, rsp.upstreamNodeId, rsp.status); SEncoder encoder; @@ -1049,7 +1057,7 @@ int32_t tqProcessStreamTaskCheckReq(STQ* pTq, SRpcMsg* pMsg) { return 0; } -int32_t tqProcessStreamTaskCheckRsp(STQ* pTq, int64_t version, char* msg, int32_t msgLen) { +int32_t tqProcessStreamTaskCheckRsp(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) { int32_t code; SStreamTaskCheckRsp rsp; @@ -1062,7 +1070,7 @@ int32_t tqProcessStreamTaskCheckRsp(STQ* pTq, int64_t version, char* msg, int32_ } tDecoderClear(&decoder); - tqDebug("tq recv task check rsp(reqId: %" PRId64 ") %d at node %d check req from task %d at node %d, status %d", + tqDebug("tq recv task check rsp(reqId:0x%" PRIx64 ") %d at node %d check req from task %d at node %d, status %d", rsp.reqId, rsp.downstreamTaskId, rsp.downstreamNodeId, rsp.upstreamTaskId, rsp.upstreamNodeId, rsp.status); SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, rsp.upstreamTaskId); @@ -1070,23 +1078,27 @@ int32_t tqProcessStreamTaskCheckRsp(STQ* pTq, int64_t version, char* msg, int32_ return -1; } - code = streamProcessTaskCheckRsp(pTask, &rsp, version); + code = streamProcessTaskCheckRsp(pTask, &rsp, sversion); streamMetaReleaseTask(pTq->pStreamMeta, pTask); return code; } -int32_t tqProcessTaskDeployReq(STQ* pTq, int64_t version, char* msg, int32_t msgLen) { +int32_t tqProcessTaskDeployReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) { int32_t code; #if 0 code = streamMetaAddSerializedTask(pTq->pStreamMeta, version, msg, msgLen); if (code < 0) return code; #endif + if (tsDisableStream) { + return 0; + } // 1.deserialize msg and build task SStreamTask* pTask = taosMemoryCalloc(1, sizeof(SStreamTask)); if (pTask == NULL) { return -1; } + SDecoder decoder; tDecoderInit(&decoder, (uint8_t*)msg, msgLen); code = tDecodeSStreamTask(&decoder, pTask); @@ -1098,14 +1110,14 @@ int32_t tqProcessTaskDeployReq(STQ* pTq, int64_t version, char* msg, int32_t msg tDecoderClear(&decoder); // 2.save task - code = streamMetaAddTask(pTq->pStreamMeta, version, pTask); + code = streamMetaAddTask(pTq->pStreamMeta, sversion, pTask); if (code < 0) { return -1; } // 3.go through recover steps to fill history if (pTask->fillHistory) { - streamTaskCheckDownstream(pTask, version); + streamTaskCheckDownstream(pTask, sversion); } return 0; @@ -1174,7 +1186,7 @@ int32_t tqProcessTaskRecover1Req(STQ* pTq, SRpcMsg* pMsg) { return 0; } -int32_t tqProcessTaskRecover2Req(STQ* pTq, int64_t version, char* msg, int32_t msgLen) { +int32_t tqProcessTaskRecover2Req(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) { int32_t code; SStreamRecoverStep2Req* pReq = (SStreamRecoverStep2Req*)msg; SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, pReq->taskId); @@ -1183,7 +1195,7 @@ int32_t tqProcessTaskRecover2Req(STQ* pTq, int64_t version, char* msg, int32_t m } // do recovery step 2 - code = streamSourceRecoverScanStep2(pTask, version); + code = streamSourceRecoverScanStep2(pTask, sversion); if (code < 0) { streamMetaReleaseTask(pTq->pStreamMeta, pTask); return -1; @@ -1231,7 +1243,7 @@ int32_t tqProcessTaskRecoverFinishReq(STQ* pTq, SRpcMsg* pMsg) { SStreamRecoverFinishReq req; SDecoder decoder; - tDecoderInit(&decoder, msg, msgLen); + tDecoderInit(&decoder, (uint8_t*)msg, msgLen); tDecodeSStreamRecoverFinishReq(&decoder, &req); tDecoderClear(&decoder); @@ -1283,17 +1295,17 @@ int32_t tqProcessDelReq(STQ* pTq, void* pReq, int32_t len, int64_t ver) { for (int32_t i = 0; i < sz; i++) { // start key column SColumnInfoData* pStartCol = taosArrayGet(pDelBlock->pDataBlock, START_TS_COLUMN_INDEX); - colDataAppend(pStartCol, i, (const char*)&pRes->skey, false); // end key column + colDataSetVal(pStartCol, i, (const char*)&pRes->skey, false); // end key column SColumnInfoData* pEndCol = taosArrayGet(pDelBlock->pDataBlock, END_TS_COLUMN_INDEX); - colDataAppend(pEndCol, i, (const char*)&pRes->ekey, false); + colDataSetVal(pEndCol, i, (const char*)&pRes->ekey, false); // uid column SColumnInfoData* pUidCol = taosArrayGet(pDelBlock->pDataBlock, UID_COLUMN_INDEX); int64_t* pUid = taosArrayGet(pRes->uidList, i); - colDataAppend(pUidCol, i, (const char*)pUid, false); + colDataSetVal(pUidCol, i, (const char*)pUid, false); - colDataAppendNULL(taosArrayGet(pDelBlock->pDataBlock, GROUPID_COLUMN_INDEX), i); - colDataAppendNULL(taosArrayGet(pDelBlock->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX), i); - colDataAppendNULL(taosArrayGet(pDelBlock->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX), i); + colDataSetNULL(taosArrayGet(pDelBlock->pDataBlock, GROUPID_COLUMN_INDEX), i); + colDataSetNULL(taosArrayGet(pDelBlock->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX), i); + colDataSetNULL(taosArrayGet(pDelBlock->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX), i); } taosArrayDestroy(pRes->uidList); @@ -1385,7 +1397,10 @@ int32_t tqProcessSubmitReq(STQ* pTq, SPackedData submit) { while (1) { pIter = taosHashIterate(pTq->pStreamMeta->pTasks, pIter); - if (pIter == NULL) break; + if (pIter == NULL) { + break; + } + SStreamTask* pTask = *(SStreamTask**)pIter; if (pTask->taskLevel != TASK_LEVEL__SOURCE) continue; if (pTask->taskStatus == TASK_STATUS__RECOVER_PREPARE || pTask->taskStatus == TASK_STATUS__WAIT_DOWNSTREAM) { @@ -1469,7 +1484,7 @@ int32_t tqProcessTaskDispatchRsp(STQ* pTq, SRpcMsg* pMsg) { } } -int32_t tqProcessTaskDropReq(STQ* pTq, int64_t version, char* msg, int32_t msgLen) { +int32_t tqProcessTaskDropReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) { SVDropStreamTaskReq* pReq = (SVDropStreamTaskReq*)msg; streamMetaRemoveTask(pTq->pStreamMeta, pReq->taskId); return 0; @@ -1481,7 +1496,7 @@ int32_t tqProcessTaskRetrieveReq(STQ* pTq, SRpcMsg* pMsg) { int32_t msgLen = pMsg->contLen - sizeof(SMsgHead); SStreamRetrieveReq req; SDecoder decoder; - tDecoderInit(&decoder, msgBody, msgLen); + tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen); tDecodeStreamRetrieveReq(&decoder, &req); tDecoderClear(&decoder); int32_t taskId = req.dstTaskId; @@ -1514,7 +1529,7 @@ int32_t vnodeEnqueueStreamMsg(SVnode* pVnode, SRpcMsg* pMsg) { SStreamDispatchReq req; SDecoder decoder; - tDecoderInit(&decoder, msgBody, msgLen); + tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen); if (tDecodeStreamDispatchReq(&decoder, &req) < 0) { code = TSDB_CODE_MSG_DECODE_ERROR; tDecoderClear(&decoder); @@ -1577,4 +1592,4 @@ FAIL: return -1; } -int32_t tqCheckLogInWal(STQ* pTq, int64_t version) { return version <= pTq->walLogLastVer; } +int32_t tqCheckLogInWal(STQ* pTq, int64_t sversion) { return sversion <= pTq->walLogLastVer; } diff --git a/source/dnode/vnode/src/tq/tqExec.c b/source/dnode/vnode/src/tq/tqExec.c index 7896b931dc..e92da7668a 100644 --- a/source/dnode/vnode/src/tq/tqExec.c +++ b/source/dnode/vnode/src/tq/tqExec.c @@ -52,7 +52,7 @@ static int32_t tqAddTbNameToRsp(const STQ* pTq, int64_t uid, STaosxRsp* pRsp, in return -1; } for (int32_t i = 0; i < n; i++) { - char* tbName = strdup(mr.me.name); + char* tbName = taosStrdup(mr.me.name); taosArrayPush(pRsp->blockTbName, &tbName); } metaReaderClear(&mr); @@ -157,7 +157,7 @@ int32_t tqScanTaosx(STQ* pTq, const STqHandle* pHandle, STaosxRsp* pRsp, SMqMeta continue; } } else { - char* tbName = strdup(qExtractTbnameFromTask(task)); + char* tbName = taosStrdup(qExtractTbnameFromTask(task)); taosArrayPush(pRsp->blockTbName, &tbName); } } diff --git a/source/dnode/vnode/src/tq/tqMeta.c b/source/dnode/vnode/src/tq/tqMeta.c index c505a7d0ae..12fd15c63a 100644 --- a/source/dnode/vnode/src/tq/tqMeta.c +++ b/source/dnode/vnode/src/tq/tqMeta.c @@ -197,8 +197,8 @@ int32_t tqMetaSaveHandle(STQ* pTq, const char* key, const STqHandle* pHandle) { return -1; } - tqDebug("tq save %s(%d) consumer %" PRId64 " vgId:%d", pHandle->subKey, (int32_t)strlen(pHandle->subKey), - pHandle->consumerId, TD_VID(pTq->pVnode)); + tqDebug("tq save %s(%d) handle consumer:0x%" PRIx64 "epoch:%d vgId:%d", pHandle->subKey, + (int32_t)strlen(pHandle->subKey), pHandle->consumerId, pHandle->epoch, TD_VID(pTq->pVnode)); void* buf = taosMemoryCalloc(1, vlen); if (buf == NULL) { diff --git a/source/dnode/vnode/src/tq/tqPush.c b/source/dnode/vnode/src/tq/tqPush.c index cc1f147ac2..e747262277 100644 --- a/source/dnode/vnode/src/tq/tqPush.c +++ b/source/dnode/vnode/src/tq/tqPush.c @@ -193,7 +193,7 @@ int32_t tqPushMsgNew(STQ* pTq, void* msg, int32_t msgLen, tmsg_t msgType, int64_ memset(&pHandle->pushHandle.rpcInfo, 0, sizeof(SRpcHandleInfo)); taosWUnLockLatch(&pHandle->pushHandle.lock); - tqDebug("vgId:%d, offset %" PRId64 " from consumer:%" PRId64 ", (epoch %d) send rsp, block num: %d, reqOffset:%" PRId64 ", rspOffset:%" PRId64, + tqDebug("vgId:%d offset %" PRId64 " from consumer:%" PRId64 ", (epoch %d) send rsp, block num: %d, reqOffset:%" PRId64 ", rspOffset:%" PRId64, TD_VID(pTq->pVnode), fetchOffset, pHandle->pushHandle.consumerId, pHandle->pushHandle.epoch, rsp.blockNum, rsp.reqOffset, rsp.rspOffset); @@ -210,14 +210,15 @@ int tqPushMsg(STQ* pTq, void* msg, int32_t msgLen, tmsg_t msgType, int64_t ver) void* pReq = POINTER_SHIFT(msg, sizeof(SSubmitReq2Msg)); int32_t len = msgLen - sizeof(SSubmitReq2Msg); - tqDebug("vgId:%d, tq push msg ver %" PRId64 ", type: %s, p head %p, p body %p, len %d", pTq->pVnode->config.vgId, ver, + tqDebug("vgId:%d tq push msg version:%" PRId64 " type: %s, p head %p, p body %p, len %d", pTq->pVnode->config.vgId, ver, TMSG_INFO(msgType), msg, pReq, len); if (msgType == TDMT_VND_SUBMIT) { // lock push mgr to avoid potential msg lost taosWLockLatch(&pTq->pushLock); - tqDebug("vgId:%d, push handle num %d", pTq->pVnode->config.vgId, taosHashGetSize(pTq->pPushMgr)); if (taosHashGetSize(pTq->pPushMgr) != 0) { + + tqDebug("vgId:%d, push handle num %d", pTq->pVnode->config.vgId, taosHashGetSize(pTq->pPushMgr)); SArray* cachedKeys = taosArrayInit(0, sizeof(void*)); SArray* cachedKeyLens = taosArrayInit(0, sizeof(size_t)); void* data = taosMemoryMalloc(len); @@ -241,11 +242,13 @@ int tqPushMsg(STQ* pTq, void* msg, int32_t msgLen, tmsg_t msgType, int64_t ver) tqDebug("vgId:%d, cannot find handle %s", pTq->pVnode->config.vgId, pPushEntry->subKey); continue; } + if (pPushEntry->dataRsp.reqOffset.version >= ver) { tqDebug("vgId:%d, push entry req version %" PRId64 ", while push version %" PRId64 ", skip", pTq->pVnode->config.vgId, pPushEntry->dataRsp.reqOffset.version, ver); continue; } + STqExecHandle* pExec = &pHandle->execHandle; qTaskInfo_t task = pExec->task; diff --git a/source/dnode/vnode/src/tq/tqRead.c b/source/dnode/vnode/src/tq/tqRead.c index 414ffda544..2c8f20d8cd 100644 --- a/source/dnode/vnode/src/tq/tqRead.c +++ b/source/dnode/vnode/src/tq/tqRead.c @@ -355,11 +355,13 @@ int32_t tqNextBlock(STqReader* pReader, SFetchRet* ret) { int32_t tqReaderSetDataMsg(STqReader* pReader, const SSubmitReq* pMsg, int64_t ver) { pReader->pMsg = pMsg; - if (tInitSubmitMsgIter(pMsg, &pReader->msgIter) < 0) return -1; - while (true) { - if (tGetSubmitMsgNext(&pReader->msgIter, &pReader->pBlock) < 0) return -1; - if (pReader->pBlock == NULL) break; - } +// if (tInitSubmitMsgIter(pMsg, &pReader->msgIter) < 0) return -1; +// while (true) { +// if (tGetSubmitMsgNext(&pReader->msgIter, &pReader->pBlock) < 0) return -1; +// tqDebug("submitnext vgId:%d, block:%p, dataLen:%d, len:%d, uid:%"PRId64, pReader->pWalReader->pWal->cfg.vgId, pReader->pBlock, pReader->msgIter.dataLen, +// pReader->msgIter.len, pReader->msgIter.uid); +// if (pReader->pBlock == NULL) break; +// } if (tInitSubmitMsgIter(pMsg, &pReader->msgIter) < 0) return -1; pReader->ver = ver; @@ -693,7 +695,7 @@ int32_t tqRetrieveDataBlock2(SSDataBlock* pBlock, STqReader* pReader, SSubmitTbD goto FAIL; } } else { - colDataAppendNULL(pColData, i); + colDataSetNULL(pColData, i); } } else { if (colDataAppend(pColData, i, (void*)&colVal.value.val, !COL_VAL_IS_VALUE(&colVal)) < 0) { @@ -734,7 +736,7 @@ int32_t tqRetrieveDataBlock2(SSDataBlock* pBlock, STqReader* pReader, SSubmitTbD goto FAIL; } } else { - colDataAppendNULL(pColData, i); + colDataSetNULL(pColData, i); } /*val = colVal.value.pData;*/ } else { @@ -861,7 +863,7 @@ int32_t tqRetrieveDataBlock(SSDataBlock* pBlock, STqReader* pReader) { if (!tdSTSRowIterFetch(&iter, pColData->info.colId, pColData->info.type, &sVal)) { break; } - if (colDataAppend(pColData, curRow, sVal.val, sVal.valType != TD_VTYPE_NORM) < 0) { + if (colDataSetVal(pColData, curRow, sVal.val, sVal.valType != TD_VTYPE_NORM) < 0) { goto FAIL; } } @@ -986,7 +988,9 @@ int32_t tqRetrieveTaosxBlock(STqReader* pReader, SArray* blocks, SArray* schemas break; } - if (colDataAppend(pColData, curRow, sVal.val, sVal.valType == TD_VTYPE_NULL) < 0) { + ASSERT(sVal.valType != TD_VTYPE_NONE); + + if (colDataSetVal(pColData, curRow, sVal.val, sVal.valType == TD_VTYPE_NULL) < 0) { goto FAIL; } tqDebug("vgId:%d, row %d col %d append %d", pReader->pWalReader->pWal->cfg.vgId, curRow, i, @@ -1141,7 +1145,7 @@ int32_t tqRetrieveTaosxBlock2(STqReader* pReader, SArray* blocks, SArray* schema goto FAIL; } } else { - colDataAppendNULL(pColData, curRow - lastRow); + colDataSetNULL(pColData, curRow - lastRow); } } else { if (colDataAppend(pColData, curRow - lastRow, (void*)&colVal.value.val, !COL_VAL_IS_VALUE(&colVal)) < 0) { @@ -1235,7 +1239,7 @@ int32_t tqRetrieveTaosxBlock2(STqReader* pReader, SArray* blocks, SArray* schema goto FAIL; } } else { - colDataAppendNULL(pColData, curRow - lastRow); + colDataSetNULL(pColData, curRow - lastRow); } } else { if (colDataAppend(pColData, curRow - lastRow, (void*)&colVal.value.val, !COL_VAL_IS_VALUE(&colVal)) < 0) { @@ -1313,7 +1317,10 @@ int32_t tqUpdateTbUidList(STQ* pTq, const SArray* tbUidList, bool isAdd) { void* pIter = NULL; while (1) { pIter = taosHashIterate(pTq->pHandle, pIter); - if (pIter == NULL) break; + if (pIter == NULL) { + break; + } + STqHandle* pExec = (STqHandle*)pIter; if (pExec->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) { int32_t code = qUpdateQualifiedTableId(pExec->execHandle.task, tbUidList, isAdd); diff --git a/source/dnode/vnode/src/tq/tqSink.c b/source/dnode/vnode/src/tq/tqSink.c index 7a8d899a19..56684b691b 100644 --- a/source/dnode/vnode/src/tq/tqSink.c +++ b/source/dnode/vnode/src/tq/tqSink.c @@ -130,7 +130,7 @@ void tqSinkToTablePipeline(SStreamTask* pTask, void* vnode, int64_t ver, void* d char* ctbName = NULL; // set child table name if (pDataBlock->info.parTbName[0]) { - ctbName = strdup(pDataBlock->info.parTbName); + ctbName = taosStrdup(pDataBlock->info.parTbName); } else { ctbName = buildCtbNameByGroupId(stbFullName, pDataBlock->info.id.groupId); } @@ -155,7 +155,7 @@ void tqSinkToTablePipeline(SStreamTask* pTask, void* vnode, int64_t ver, void* d // set super table name SName name = {0}; tNameFromString(&name, stbFullName, T_NAME_ACCT | T_NAME_DB | T_NAME_TABLE); - createTbReq.ctb.stbName = strdup((char*)tNameGetTableName(&name)); // strdup(stbFullName); + createTbReq.ctb.stbName = taosStrdup((char*)tNameGetTableName(&name)); // taosStrdup(stbFullName); createTbReq.name = ctbName; ctbName = NULL; @@ -453,7 +453,7 @@ void tqSinkToTablePipeline2(SStreamTask* pTask, void* vnode, int64_t ver, void* // set super table name SName name = {0}; tNameFromString(&name, stbFullName, T_NAME_ACCT | T_NAME_DB | T_NAME_TABLE); - pCreateTbReq->ctb.stbName = strdup((char*)tNameGetTableName(&name)); // strdup(stbFullName); + pCreateTbReq->ctb.stbName = taosStrdup((char*)tNameGetTableName(&name)); // taosStrdup(stbFullName); // set tag content int32_t size = taosArrayGetSize(pDataBlock->pDataBlock); @@ -497,7 +497,7 @@ void tqSinkToTablePipeline2(SStreamTask* pTask, void* vnode, int64_t ver, void* taosArrayPush(tagArray, &tagVal); } } - pCreateTbReq->ctb.tagNum = size; + pCreateTbReq->ctb.tagNum = TMAX(size - UD_TAG_COLUMN_INDEX, 1); STag* pTag = NULL; tTagNew(tagArray, 1, false, &pTag); @@ -507,18 +507,16 @@ void tqSinkToTablePipeline2(SStreamTask* pTask, void* vnode, int64_t ver, void* goto _end; } + pCreateTbReq->ctb.pTag = (uint8_t*)pTag; // set table name - SColumnInfoData* pTbColInfo = taosArrayGet(pDataBlock->pDataBlock, UD_TABLE_NAME_COLUMN_INDEX); - if (colDataIsNull_s(pTbColInfo, rowId)) { + if (!pDataBlock->info.parTbName[0]) { SColumnInfoData* pGpIdColInfo = taosArrayGet(pDataBlock->pDataBlock, UD_GROUPID_COLUMN_INDEX); void* pGpIdData = colDataGetData(pGpIdColInfo, rowId); pCreateTbReq->name = buildCtbNameByGroupId(stbFullName, *(uint64_t*)pGpIdData); } else { - void* pTbData = colDataGetData(pTbColInfo, rowId); - pCreateTbReq->name = taosMemoryCalloc(1, varDataLen(pTbData) + 1); - memcpy(pCreateTbReq->name, varDataVal(pTbData), varDataLen(pTbData)); + pCreateTbReq->name = taosStrdup(pDataBlock->info.parTbName); } taosArrayPush(reqs.pArray, pCreateTbReq); } @@ -544,7 +542,7 @@ void tqSinkToTablePipeline2(SStreamTask* pTask, void* vnode, int64_t ver, void* char* ctbName = NULL; tqDebug("vgId:%d, stream write into %s, table auto created", TD_VID(pVnode), pDataBlock->info.parTbName); if (pDataBlock->info.parTbName[0]) { - ctbName = strdup(pDataBlock->info.parTbName); + ctbName = taosStrdup(pDataBlock->info.parTbName); } else { ctbName = buildCtbNameByGroupId(stbFullName, pDataBlock->info.id.groupId); } @@ -569,7 +567,7 @@ void tqSinkToTablePipeline2(SStreamTask* pTask, void* vnode, int64_t ver, void* // set super table name SName name = {0}; tNameFromString(&name, stbFullName, T_NAME_ACCT | T_NAME_DB | T_NAME_TABLE); - pCreateTbReq->ctb.stbName = strdup((char*)tNameGetTableName(&name)); // strdup(stbFullName); + pCreateTbReq->ctb.stbName = taosStrdup((char*)tNameGetTableName(&name)); // taosStrdup(stbFullName); // set tag content tagArray = taosArrayInit(1, sizeof(STagVal)); diff --git a/source/dnode/vnode/src/tsdb/tsdbCache.c b/source/dnode/vnode/src/tsdb/tsdbCache.c index 7f3c142f37..79e0ccc3e3 100644 --- a/source/dnode/vnode/src/tsdb/tsdbCache.c +++ b/source/dnode/vnode/src/tsdb/tsdbCache.c @@ -779,12 +779,11 @@ static int32_t getNextRowFromFS(void *iter, TSDBROW **ppRow) { code = tsdbReadBlockIdx(*state->pDataFReader, state->aBlockIdx); if (code) goto _err; */ - int32_t code = - tsdbCacheGetBlockIdx((*state->pDataFReader)->pTsdb->biCache, *state->pDataFReader, &state->aBlockIdxHandle); + int32_t code = tsdbCacheGetBlockIdx(state->pTsdb->biCache, *state->pDataFReader, &state->aBlockIdxHandle); if (code != TSDB_CODE_SUCCESS || state->aBlockIdxHandle == NULL) { goto _err; } - state->aBlockIdx = (SArray *)taosLRUCacheValue((*state->pDataFReader)->pTsdb->biCache, state->aBlockIdxHandle); + state->aBlockIdx = (SArray *)taosLRUCacheValue(state->pTsdb->biCache, state->aBlockIdxHandle); /* if (state->pBlockIdx) { */ /* } */ @@ -814,7 +813,8 @@ static int32_t getNextRowFromFS(void *iter, TSDBROW **ppRow) { if (!state->pBlockData) { state->pBlockData = &state->blockData; - tBlockDataCreate(&state->blockData); + code = tBlockDataCreate(&state->blockData); + if (code) goto _err; } } case SFSNEXTROW_BLOCKDATA: @@ -855,7 +855,7 @@ static int32_t getNextRowFromFS(void *iter, TSDBROW **ppRow) { if (state->aBlockIdx) { // taosArrayDestroy(state->aBlockIdx); - tsdbBICacheRelease((*state->pDataFReader)->pTsdb->biCache, state->aBlockIdxHandle); + tsdbBICacheRelease(state->pTsdb->biCache, state->aBlockIdxHandle); state->aBlockIdxHandle = NULL; state->aBlockIdx = NULL; @@ -881,7 +881,7 @@ _err: }*/ if (state->aBlockIdx) { // taosArrayDestroy(state->aBlockIdx); - tsdbBICacheRelease((*state->pDataFReader)->pTsdb->biCache, state->aBlockIdxHandle); + tsdbBICacheRelease(state->pTsdb->biCache, state->aBlockIdxHandle); state->aBlockIdxHandle = NULL; state->aBlockIdx = NULL; @@ -910,7 +910,7 @@ int32_t clearNextRowFromFS(void *iter) { }*/ if (state->aBlockIdx) { // taosArrayDestroy(state->aBlockIdx); - tsdbBICacheRelease((*state->pDataFReader)->pTsdb->biCache, state->aBlockIdxHandle); + tsdbBICacheRelease(state->pTsdb->biCache, state->aBlockIdxHandle); state->aBlockIdxHandle = NULL; state->aBlockIdx = NULL; diff --git a/source/dnode/vnode/src/tsdb/tsdbCacheRead.c b/source/dnode/vnode/src/tsdb/tsdbCacheRead.c index 6ea169a5e3..97b13a3c37 100644 --- a/source/dnode/vnode/src/tsdb/tsdbCacheRead.c +++ b/source/dnode/vnode/src/tsdb/tsdbCacheRead.c @@ -67,7 +67,7 @@ static int32_t saveOneRow(SArray* pRow, SSDataBlock* pBlock, SCacheRowsReader* p // pColInfoData->info.bytes includes the VARSTR_HEADER_SIZE, need to substruct it p->hasResult = true; varDataSetLen(pRes[i], pColInfoData->info.bytes - VARSTR_HEADER_SIZE); - colDataAppend(pColInfoData, numOfRows, (const char*)pRes[i], false); + colDataSetVal(pColInfoData, numOfRows, (const char*)pRes[i], false); } pBlock->info.rows += allNullRow ? 0 : 1; @@ -77,7 +77,7 @@ static int32_t saveOneRow(SArray* pRow, SSDataBlock* pBlock, SCacheRowsReader* p if (slotIds[i] == -1) { SLastCol* pColVal = (SLastCol*)taosArrayGet(pRow, 0); - colDataAppend(pColInfoData, numOfRows, (const char*)&pColVal->ts, false); + colDataSetVal(pColInfoData, numOfRows, (const char*)&pColVal->ts, false); } else { int32_t slotId = slotIds[i]; SLastCol* pColVal = (SLastCol*)taosArrayGet(pRow, slotId); @@ -85,14 +85,14 @@ static int32_t saveOneRow(SArray* pRow, SSDataBlock* pBlock, SCacheRowsReader* p if (IS_VAR_DATA_TYPE(pColVal->colVal.type)) { if (!COL_VAL_IS_VALUE(&pColVal->colVal)) { - colDataAppendNULL(pColInfoData, numOfRows); + colDataSetNULL(pColInfoData, numOfRows); } else { varDataSetLen(pReader->transferBuf[slotId], pVal->value.nData); memcpy(varDataVal(pReader->transferBuf[slotId]), pVal->value.pData, pVal->value.nData); - colDataAppend(pColInfoData, numOfRows, pReader->transferBuf[slotId], false); + colDataSetVal(pColInfoData, numOfRows, pReader->transferBuf[slotId], false); } } else { - colDataAppend(pColInfoData, numOfRows, (const char*)&pVal->value.val, !COL_VAL_IS_VALUE(pVal)); + colDataSetVal(pColInfoData, numOfRows, (const char*)&pVal->value.val, !COL_VAL_IS_VALUE(pVal)); } } } @@ -190,7 +190,7 @@ int32_t tsdbCacherowsReaderOpen(void* pVnode, int32_t type, void* pTableIdList, return TSDB_CODE_OUT_OF_MEMORY; } - p->idstr = taosMemoryStrDup(idstr); + p->idstr = taosStrdup(idstr); taosThreadMutexInit(&p->readerMutex, NULL); *pReader = p; @@ -433,8 +433,10 @@ _end: tsdbUntakeReadSnap((STsdbReader*)pr, pr->pReadSnap, true); taosThreadMutexUnlock(&pr->readerMutex); - for (int32_t j = 0; j < pr->numOfCols; ++j) { - taosMemoryFree(pRes[j]); + if (pRes != NULL) { + for (int32_t j = 0; j < pr->numOfCols; ++j) { + taosMemoryFree(pRes[j]); + } } taosMemoryFree(pRes); diff --git a/source/dnode/vnode/src/tsdb/tsdbDataIter.c b/source/dnode/vnode/src/tsdb/tsdbDataIter.c index 2f49781276..3299a2f497 100644 --- a/source/dnode/vnode/src/tsdb/tsdbDataIter.c +++ b/source/dnode/vnode/src/tsdb/tsdbDataIter.c @@ -219,7 +219,7 @@ static int32_t tsdbDataFileDataIterNext(STsdbDataIter2* pIter, STsdbFilterInfo* } ASSERT(pIter->rowInfo.suid == pIter->dIter.bData.suid); - ASSERT(pIter->rowInfo.uid = pIter->dIter.bData.uid); + ASSERT(pIter->rowInfo.uid == pIter->dIter.bData.uid); pIter->rowInfo.row = tsdbRowFromBlockData(&pIter->dIter.bData, pIter->dIter.iRow); pIter->dIter.iRow++; goto _exit; diff --git a/source/dnode/vnode/src/tsdb/tsdbFile.c b/source/dnode/vnode/src/tsdb/tsdbFile.c index 42728be657..d91475376b 100644 --- a/source/dnode/vnode/src/tsdb/tsdbFile.c +++ b/source/dnode/vnode/src/tsdb/tsdbFile.c @@ -148,10 +148,10 @@ bool tsdbDelFileIsSame(SDelFile *pDelFile1, SDelFile *pDelFile2) { return pDelFi int32_t tsdbDFileRollback(STsdb *pTsdb, SDFileSet *pSet, EDataFileT ftype) { int32_t code = 0; - int64_t size; + int64_t size = 0; int64_t n; TdFilePtr pFD; - char fname[TSDB_FILENAME_LEN]; + char fname[TSDB_FILENAME_LEN] = {0}; char hdr[TSDB_FHDR_SIZE] = {0}; // truncate @@ -167,7 +167,7 @@ int32_t tsdbDFileRollback(STsdb *pTsdb, SDFileSet *pSet, EDataFileT ftype) { tPutSmaFile(hdr, pSet->pSmaF); break; default: - ASSERT(0); + goto _err; // make the coverity scan happy } taosCalcChecksumAppend(0, hdr, TSDB_FHDR_SIZE); diff --git a/source/dnode/vnode/src/tsdb/tsdbMemTable.c b/source/dnode/vnode/src/tsdb/tsdbMemTable.c index 3db9ff2b42..d34af9acae 100644 --- a/source/dnode/vnode/src/tsdb/tsdbMemTable.c +++ b/source/dnode/vnode/src/tsdb/tsdbMemTable.c @@ -190,9 +190,9 @@ int32_t tsdbDeleteTableData(STsdb *pTsdb, int64_t version, tb_uid_t suid, tb_uid tsdbCacheDeleteLast(pTsdb->lruCache, pTbData->uid, eKey); } - tsdbInfo("vgId:%d, delete data from table suid:%" PRId64 " uid:%" PRId64 " skey:%" PRId64 " eKey:%" PRId64 - " at version %" PRId64 " since %s", - TD_VID(pTsdb->pVnode), suid, uid, sKey, eKey, version, tstrerror(code)); + tsdbTrace("vgId:%d, delete data from table suid:%" PRId64 " uid:%" PRId64 " skey:%" PRId64 " eKey:%" PRId64 + " at version %" PRId64, + TD_VID(pTsdb->pVnode), suid, uid, sKey, eKey, version); return code; _err: @@ -473,7 +473,7 @@ static int32_t tbDataDoPut(SMemTable *pMemTable, STbData *pTbData, SMemSkipListN int8_t forward) { int32_t code = 0; int8_t level; - SMemSkipListNode *pNode; + SMemSkipListNode *pNode = NULL; SVBufPool *pPool = pMemTable->pTsdb->pVnode->inUse; int64_t nSize; @@ -591,7 +591,9 @@ static int32_t tsdbInsertColDataToTable(SMemTable *pMemTable, STbData *pTbData, pBlockData->aColData = vnodeBufPoolMalloc(pPool, sizeof(SColData) * pBlockData->nColData); if (pBlockData->aColData == NULL) { code = TSDB_CODE_OUT_OF_MEMORY; + goto _exit; } + for (int32_t iColData = 0; iColData < pBlockData->nColData; ++iColData) { code = tColDataCopy(&aColData[iColData + 1], &pBlockData->aColData[iColData], (xMallocFn)vnodeBufPoolMalloc, pPool); if (code) goto _exit; diff --git a/source/dnode/vnode/src/tsdb/tsdbRead.c b/source/dnode/vnode/src/tsdb/tsdbRead.c index 64a450a7b1..a158bbfa8d 100644 --- a/source/dnode/vnode/src/tsdb/tsdbRead.c +++ b/source/dnode/vnode/src/tsdb/tsdbRead.c @@ -155,6 +155,7 @@ typedef struct SBlockInfoBuf { int32_t currentIndex; SArray* pData; int32_t numPerBucket; + int32_t numOfTables; } SBlockInfoBuf; struct STsdbReader { @@ -222,6 +223,8 @@ static bool hasDataInFileBlock(const SBlockData* pBlockData, const SFil static void initBlockDumpInfo(STsdbReader* pReader, SDataBlockIter* pBlockIter); static int32_t getInitialDelIndex(const SArray* pDelSkyline, int32_t order); +static STableBlockScanInfo* getTableBlockScanInfo(SHashObj* pTableMap, uint64_t uid, const char* id); + static FORCE_INLINE STSchema* getLatestTableSchema(STsdbReader* pReader, uint64_t uid); static bool outOfTimeWindow(int64_t ts, STimeWindow* pWindow) { return (ts > pWindow->ekey) || (ts < pWindow->skey); } @@ -300,6 +303,47 @@ static int32_t initBlockScanInfoBuf(SBlockInfoBuf* pBuf, int32_t numOfTables) { taosArrayPush(pBuf->pData, &p); } + pBuf->numOfTables = numOfTables; + + return TSDB_CODE_SUCCESS; +} + +static int32_t ensureBlockScanInfoBuf(SBlockInfoBuf* pBuf, int32_t numOfTables) { + if (numOfTables <= pBuf->numOfTables) { + return TSDB_CODE_SUCCESS; + } + + if (pBuf->numOfTables > 0) { + STableBlockScanInfo **p = (STableBlockScanInfo**)taosArrayPop(pBuf->pData); + taosMemoryFree(*p); + pBuf->numOfTables /= pBuf->numPerBucket; + } + + int32_t num = (numOfTables - pBuf->numOfTables) / pBuf->numPerBucket; + int32_t remainder = (numOfTables - pBuf->numOfTables) % pBuf->numPerBucket; + if (pBuf->pData == NULL) { + pBuf->pData = taosArrayInit(num + 1, POINTER_BYTES); + } + + for (int32_t i = 0; i < num; ++i) { + char* p = taosMemoryCalloc(pBuf->numPerBucket, sizeof(STableBlockScanInfo)); + if (p == NULL) { + return TSDB_CODE_OUT_OF_MEMORY; + } + + taosArrayPush(pBuf->pData, &p); + } + + if (remainder > 0) { + char* p = taosMemoryCalloc(remainder, sizeof(STableBlockScanInfo)); + if (p == NULL) { + return TSDB_CODE_OUT_OF_MEMORY; + } + taosArrayPush(pBuf->pData, &p); + } + + pBuf->numOfTables = numOfTables; + return TSDB_CODE_SUCCESS; } @@ -488,13 +532,15 @@ static int32_t initFilesetIterator(SFilesetIter* pIter, SArray* aDFileSet, STsdb return TSDB_CODE_SUCCESS; } -static bool filesetIteratorNext(SFilesetIter* pIter, STsdbReader* pReader) { +static int32_t filesetIteratorNext(SFilesetIter* pIter, STsdbReader* pReader, bool* hasNext) { bool asc = ASCENDING_TRAVERSE(pIter->order); int32_t step = asc ? 1 : -1; pIter->index += step; + int32_t code = 0; if ((asc && pIter->index >= pIter->numOfFiles) || ((!asc) && pIter->index < 0)) { - return false; + *hasNext = false; + return TSDB_CODE_SUCCESS; } SIOCostSummary* pSum = &pReader->cost; @@ -514,7 +560,7 @@ static bool filesetIteratorNext(SFilesetIter* pIter, STsdbReader* pReader) { pReader->status.pCurrentFileset = (SDFileSet*)taosArrayGet(pIter->pFileList, pIter->index); - int32_t code = tsdbDataFReaderOpen(&pReader->pFileReader, pReader->pTsdb, pReader->status.pCurrentFileset); + code = tsdbDataFReaderOpen(&pReader->pFileReader, pReader->pTsdb, pReader->status.pCurrentFileset); if (code != TSDB_CODE_SUCCESS) { goto _err; } @@ -528,24 +574,28 @@ static bool filesetIteratorNext(SFilesetIter* pIter, STsdbReader* pReader) { if ((asc && win.skey > pReader->window.ekey) || (!asc && win.ekey < pReader->window.skey)) { tsdbDebug("%p remain files are not qualified for qrange:%" PRId64 "-%" PRId64 ", ignore, %s", pReader, pReader->window.skey, pReader->window.ekey, pReader->idStr); - return false; + *hasNext = false; + return TSDB_CODE_SUCCESS; } if ((asc && (win.ekey < pReader->window.skey)) || ((!asc) && (win.skey > pReader->window.ekey))) { pIter->index += step; if ((asc && pIter->index >= pIter->numOfFiles) || ((!asc) && pIter->index < 0)) { - return false; + *hasNext = false; + return TSDB_CODE_SUCCESS; } continue; } tsdbDebug("%p file found fid:%d for qrange:%" PRId64 "-%" PRId64 ", %s", pReader, fid, pReader->window.skey, pReader->window.ekey, pReader->idStr); - return true; + *hasNext = true; + return TSDB_CODE_SUCCESS; } _err: - return false; + *hasNext = false; + return code; } static void resetDataBlockIterator(SDataBlockIter* pIter, int32_t order) { @@ -671,7 +721,7 @@ static int32_t tsdbReaderCreate(SVnode* pVnode, SQueryTableDataCond* pCond, STsd pReader->order = pCond->order; pReader->capacity = capacity; pReader->pResBlock = pResBlock; - pReader->idStr = (idstr != NULL) ? strdup(idstr) : NULL; + pReader->idStr = (idstr != NULL) ? taosStrdup(idstr) : NULL; pReader->verRange = getQueryVerRange(pVnode, pCond, level); pReader->type = pCond->type; pReader->window = updateQueryTimeWindow(pReader->pTsdb, &pCond->twindows); @@ -764,14 +814,11 @@ static int32_t doLoadBlockIndex(STsdbReader* pReader, SDataFReader* pFileReader, if (pBlockIdx->uid == pList->tableUidList[j]) { // this block belongs to a table that is not queried. - void* p = taosHashGet(pReader->status.pTableMap, &pBlockIdx->uid, sizeof(uint64_t)); - if (p == NULL) { - tsdbError("failed to locate the tableBlockScan Info in hashmap, uid:%" PRIu64 ", %s", pBlockIdx->uid, - pReader->idStr); - return TSDB_CODE_APP_ERROR; + STableBlockScanInfo* pScanInfo = getTableBlockScanInfo(pReader->status.pTableMap, pBlockIdx->uid, pReader->idStr); + if (pScanInfo == NULL) { + return terrno; } - STableBlockScanInfo* pScanInfo = *(STableBlockScanInfo**)p; if (pScanInfo->pBlockList == NULL) { pScanInfo->pBlockList = taosArrayInit(4, sizeof(SBlockIndex)); } @@ -818,10 +865,11 @@ static int32_t doLoadFileBlock(STsdbReader* pReader, SArray* pIndexList, SBlockN cleanupTableScanInfo(pReader->status.pTableMap); for (int32_t i = 0; i < numOfTables; ++i) { - SBlockIdx* pBlockIdx = taosArrayGet(pIndexList, i); - - STableBlockScanInfo* pScanInfo = - *(STableBlockScanInfo**)taosHashGet(pReader->status.pTableMap, &pBlockIdx->uid, sizeof(int64_t)); + SBlockIdx* pBlockIdx = taosArrayGet(pIndexList, i); + STableBlockScanInfo* pScanInfo = getTableBlockScanInfo(pReader->status.pTableMap, pBlockIdx->uid, pReader->idStr); + if (pScanInfo == NULL) { + return terrno; + } tMapDataReset(&pScanInfo->mapData); tsdbReadDataBlk(pReader->pFileReader, pBlockIdx, &pScanInfo->mapData); @@ -868,7 +916,7 @@ static int32_t doLoadFileBlock(STsdbReader* pReader, SArray* pIndexList, SBlockN pBlockNum->numOfBlocks += 1; } - if (pScanInfo->pBlockList != NULL && taosArrayGetSize(pScanInfo->pBlockList) > 0) { + if ((pScanInfo->pBlockList != NULL )&& (taosArrayGetSize(pScanInfo->pBlockList) > 0)) { numOfQTable += 1; } } @@ -899,7 +947,7 @@ static void doCopyColVal(SColumnInfoData* pColInfoData, int32_t rowIndex, int32_ SBlockLoadSuppInfo* pSup) { if (IS_VAR_DATA_TYPE(pColVal->type)) { if (!COL_VAL_IS_VALUE(pColVal)) { - colDataAppendNULL(pColInfoData, rowIndex); + colDataSetNULL(pColInfoData, rowIndex); } else { varDataSetLen(pSup->buildBuf[colIndex], pColVal->value.nData); ASSERT(pColVal->value.nData <= pColInfoData->info.bytes); @@ -907,10 +955,10 @@ static void doCopyColVal(SColumnInfoData* pColInfoData, int32_t rowIndex, int32_ memcpy(varDataVal(pSup->buildBuf[colIndex]), pColVal->value.pData, pColVal->value.nData); } - colDataAppend(pColInfoData, rowIndex, pSup->buildBuf[colIndex], false); + colDataSetVal(pColInfoData, rowIndex, pSup->buildBuf[colIndex], false); } } else { - colDataAppend(pColInfoData, rowIndex, (const char*)&pColVal->value, !COL_VAL_IS_VALUE(pColVal)); + colDataSetVal(pColInfoData, rowIndex, (const char*)&pColVal->value, !COL_VAL_IS_VALUE(pColVal)); } } @@ -933,9 +981,7 @@ static int doBinarySearchKey(TSKEY* keyList, int num, int pos, TSKEY key, int or s = pos; // check - assert(pos >= 0 && pos < num); - assert(num > 0); - + ASSERT(pos >= 0 && pos < num && num > 0); if (order == TSDB_ORDER_ASC) { // find the first position which is smaller than the key e = num - 1; @@ -1185,7 +1231,7 @@ static int32_t copyBlockDataToSDataBlock(STsdbReader* pReader) { pColData = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]); if (pData->flag == HAS_NONE || pData->flag == HAS_NULL || pData->flag == (HAS_NULL | HAS_NONE)) { - colDataAppendNNULL(pColData, 0, dumpedRows); + colDataSetNNULL(pColData, 0, dumpedRows); } else { if (IS_MATHABLE_TYPE(pColData->info.type)) { copyNumericCols(pData, pDumpInfo, pColData, dumpedRows, asc); @@ -1201,7 +1247,7 @@ static int32_t copyBlockDataToSDataBlock(STsdbReader* pReader) { i += 1; } else { // the specified column does not exist in file block, fill with null data pColData = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]); - colDataAppendNNULL(pColData, 0, dumpedRows); + colDataSetNNULL(pColData, 0, dumpedRows); i += 1; } } @@ -1209,7 +1255,7 @@ static int32_t copyBlockDataToSDataBlock(STsdbReader* pReader) { // fill the mis-matched columns with null value while (i < numOfOutputCols) { pColData = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]); - colDataAppendNNULL(pColData, 0, dumpedRows); + colDataSetNNULL(pColData, 0, dumpedRows); i += 1; } @@ -1336,14 +1382,13 @@ static int32_t fileDataBlockOrderCompar(const void* pLeft, const void* pRight, v static int32_t doSetCurrentBlock(SDataBlockIter* pBlockIter, const char* idStr) { SFileDataBlockInfo* pBlockInfo = getCurrentBlockInfo(pBlockIter); if (pBlockInfo != NULL) { - STableBlockScanInfo** pScanInfo = taosHashGet(pBlockIter->pTableMap, &pBlockInfo->uid, sizeof(pBlockInfo->uid)); + STableBlockScanInfo* pScanInfo = getTableBlockScanInfo(pBlockIter->pTableMap, pBlockInfo->uid, idStr); if (pScanInfo == NULL) { - tsdbError("failed to locate the uid:%" PRIu64 " in query table uid list, %s", pBlockInfo->uid, idStr); - return TSDB_CODE_INVALID_PARA; + return terrno; } - SBlockIndex* pIndex = taosArrayGet((*pScanInfo)->pBlockList, pBlockInfo->tbBlockIdx); - tMapDataGetItemByIdx(&(*pScanInfo)->mapData, pIndex->ordinalIndex, &pBlockIter->block, tGetDataBlk); + SBlockIndex* pIndex = taosArrayGet(pScanInfo->pBlockList, pBlockInfo->tbBlockIdx); + tMapDataGetItemByIdx(&pScanInfo->mapData, pIndex->ordinalIndex, &pBlockIter->block, tGetDataBlk); } #if 0 @@ -2590,16 +2635,11 @@ static int32_t buildComposedDataBlock(STsdbReader* pReader) { STableBlockScanInfo* pBlockScanInfo = NULL; if (pBlockInfo != NULL) { - void* p = taosHashGet(pReader->status.pTableMap, &pBlockInfo->uid, sizeof(pBlockInfo->uid)); - if (p == NULL) { - code = TSDB_CODE_INVALID_PARA; - tsdbError("failed to locate the uid:%" PRIu64 " in query table uid list, total tables:%d, %s", pBlockInfo->uid, - taosHashGetSize(pReader->status.pTableMap), pReader->idStr); + pBlockScanInfo = getTableBlockScanInfo(pReader->status.pTableMap, pBlockInfo->uid, pReader->idStr); + if (pBlockScanInfo == NULL) { goto _end; } - pBlockScanInfo = *(STableBlockScanInfo**)p; - SDataBlk* pBlock = getCurrentBlock(&pReader->status.blockIter); TSDBKEY keyInBuf = getCurrentKeyInBuf(pBlockScanInfo, pReader); @@ -2796,13 +2836,19 @@ static int32_t moveToNextFile(STsdbReader* pReader, SBlockNumber* pBlockNum) { SArray* pIndexList = taosArrayInit(numOfTables, sizeof(SBlockIdx)); while (1) { - bool hasNext = filesetIteratorNext(&pStatus->fileIter, pReader); + bool hasNext = false; + int32_t code = filesetIteratorNext(&pStatus->fileIter, pReader, &hasNext); + if (code) { + taosArrayDestroy(pIndexList); + return code; + } + if (!hasNext) { // no data files on disk break; } taosArrayClear(pIndexList); - int32_t code = doLoadBlockIndex(pReader, pReader->pFileReader, pIndexList); + code = doLoadBlockIndex(pReader, pReader->pFileReader, pIndexList); if (code != TSDB_CODE_SUCCESS) { taosArrayDestroy(pIndexList); return code; @@ -2939,13 +2985,9 @@ static int32_t doBuildDataBlock(STsdbReader* pReader) { SFileDataBlockInfo* pBlockInfo = getCurrentBlockInfo(pBlockIter); SLastBlockReader* pLastBlockReader = pReader->status.fileIter.pLastBlockReader; - ASSERT(pBlockInfo != NULL); - - pScanInfo = *(STableBlockScanInfo**)taosHashGet(pReader->status.pTableMap, &pBlockInfo->uid, sizeof(pBlockInfo->uid)); + pScanInfo = getTableBlockScanInfo(pReader->status.pTableMap, pBlockInfo->uid, pReader->idStr); if (pScanInfo == NULL) { - tsdbError("failed to get table scan-info, %s", pReader->idStr); - code = TSDB_CODE_INVALID_PARA; - return code; + return terrno; } pBlock = getCurrentBlock(pBlockIter); @@ -3764,7 +3806,7 @@ int32_t doAppendRowFromTSRow(SSDataBlock* pBlock, STsdbReader* pReader, SRow* pT } else if (colId < pSchema->columns[j].colId) { SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, pSupInfo->slotId[i]); - colDataAppendNULL(pColInfoData, outputRowIndex); + colDataSetNULL(pColInfoData, outputRowIndex); i += 1; } else if (colId > pSchema->columns[j].colId) { j += 1; @@ -3774,7 +3816,7 @@ int32_t doAppendRowFromTSRow(SSDataBlock* pBlock, STsdbReader* pReader, SRow* pT // set null value since current column does not exist in the "pSchema" while (i < pSupInfo->numOfCols) { SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, pSupInfo->slotId[i]); - colDataAppendNULL(pColInfoData, outputRowIndex); + colDataSetNULL(pColInfoData, outputRowIndex); i += 1; } @@ -3814,7 +3856,7 @@ int32_t doAppendRowFromFileBlock(SSDataBlock* pResBlock, STsdbReader* pReader, S j += 1; } else if (pData->cid > pCol->info.colId) { // the specified column does not exist in file block, fill with null data - colDataAppendNULL(pCol, outputRowIndex); + colDataSetNULL(pCol, outputRowIndex); } i += 1; @@ -3822,7 +3864,7 @@ int32_t doAppendRowFromFileBlock(SSDataBlock* pResBlock, STsdbReader* pReader, S while (i < numOfOutputCols) { SColumnInfoData* pCol = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]); - colDataAppendNULL(pCol, outputRowIndex); + colDataSetNULL(pCol, outputRowIndex); i += 1; } @@ -3876,8 +3918,13 @@ int32_t tsdbSetTableList(STsdbReader* pReader, const void* pTableList, int32_t n clearBlockScanInfo(*p); } - // todo handle the case where size is less than the value of num - ASSERT(size >= num); + if (size < num) { + int32_t code = ensureBlockScanInfoBuf(&pReader->blockInfoBuf, num); + if (code) { + return code; + } + pReader->status.uidList.tableUidList = (uint64_t*)taosMemoryRealloc(pReader->status.uidList.tableUidList, sizeof(uint64_t) * num); + } taosHashClear(pReader->status.pTableMap); STableUidList* pUidList = &pReader->status.uidList; @@ -4520,7 +4567,7 @@ int32_t tsdbRetrieveDatablockSMA(STsdbReader* pReader, SSDataBlock* pDataBlock, SSDataBlock* pResBlock = pReader->pResBlock; if (pResBlock->pBlockAgg == NULL) { size_t num = taosArrayGetSize(pResBlock->pDataBlock); - pResBlock->pBlockAgg = taosMemoryCalloc(num, sizeof(SColumnDataAgg)); + pResBlock->pBlockAgg = taosMemoryCalloc(num, POINTER_BYTES); } // do fill all null column value SMA info @@ -4550,15 +4597,23 @@ int32_t tsdbRetrieveDatablockSMA(STsdbReader* pReader, SSDataBlock* pDataBlock, return code; } +STableBlockScanInfo* getTableBlockScanInfo(SHashObj* pTableMap, uint64_t uid, const char* id) { + STableBlockScanInfo** p = taosHashGet(pTableMap, &uid, sizeof(uid)); + if (p == NULL || *p == NULL) { + terrno = TSDB_CODE_INVALID_PARA; + int32_t size = taosHashGetSize(pTableMap); + tsdbError("failed to locate the uid:%" PRIu64 " in query table uid list, total tables:%d, %s", uid, size, id); + return NULL; + } + + return *p; +} + static SSDataBlock* doRetrieveDataBlock(STsdbReader* pReader) { SReaderStatus* pStatus = &pReader->status; SFileDataBlockInfo* pBlockInfo = getCurrentBlockInfo(&pStatus->blockIter); - STableBlockScanInfo* pBlockScanInfo = - *(STableBlockScanInfo**)taosHashGet(pStatus->pTableMap, &pBlockInfo->uid, sizeof(pBlockInfo->uid)); + STableBlockScanInfo* pBlockScanInfo = getTableBlockScanInfo(pStatus->pTableMap, pBlockInfo->uid, pReader->idStr); if (pBlockScanInfo == NULL) { - terrno = TSDB_CODE_INVALID_PARA; - tsdbError("failed to locate the uid:%" PRIu64 " in query table uid list, total tables:%d, %s", pBlockInfo->uid, - taosHashGetSize(pReader->status.pTableMap), pReader->idStr); return NULL; } @@ -4676,6 +4731,11 @@ int32_t tsdbGetFileBlocksDistInfo(STsdbReader* pReader, STableBlockDistInfo* pTa pTableBlockInfo->numOfVgroups = 1; // find the start data block in file + + tsdbAcquireReader(pReader); + if (pReader->suspended) { + tsdbReaderResume(pReader); + } SReaderStatus* pStatus = &pReader->status; STsdbCfg* pc = &pReader->pTsdb->pVnode->config.tsdbCfg; @@ -4737,7 +4797,7 @@ int32_t tsdbGetFileBlocksDistInfo(STsdbReader* pReader, STableBlockDistInfo* pTa // tsdbDebug("%p %d blocks found in file for %d table(s), fid:%d, %s", pReader, numOfBlocks, numOfTables, // pReader->pFileGroup->fid, pReader->idStr); } - + tsdbReleaseReader(pReader); return code; } diff --git a/source/dnode/vnode/src/tsdb/tsdbSnapshot.c b/source/dnode/vnode/src/tsdb/tsdbSnapshot.c index 9f57887d48..1a98134d70 100644 --- a/source/dnode/vnode/src/tsdb/tsdbSnapshot.c +++ b/source/dnode/vnode/src/tsdb/tsdbSnapshot.c @@ -328,10 +328,6 @@ static int32_t tsdbSnapCmprTombData(STsdbSnapReader* pReader, uint8_t** ppData) _exit: if (code) { tsdbError("vgId:%d %s failed at line %d since %s", TD_VID(pReader->pTsdb->pVnode), __func__, lino, tstrerror(code)); - if (pData) { - taosMemoryFree(pData); - pData = NULL; - } } *ppData = pData; return code; @@ -404,7 +400,7 @@ static int32_t tsdbSnapReadTombData(STsdbSnapReader* pReader, uint8_t** ppData) } while (pDelInfo && pDelInfo->suid == pReader->tbid.suid && pDelInfo->uid == pReader->tbid.uid) { - if (taosArrayPush(pReader->aDelData, &pDelInfo->delData) < 0) { + if (taosArrayPush(pReader->aDelData, &pDelInfo->delData) == NULL) { code = TSDB_CODE_OUT_OF_MEMORY; TSDB_CHECK_CODE(code, lino, _exit); } @@ -1252,7 +1248,7 @@ static int32_t tsdbSnapWriteDelTableData(STsdbSnapWriter* pWriter, TABLEID* pId, SDelData delData; n += tGetDelData(pData + n, &delData); - if (taosArrayPush(pWriter->aDelData, &delData) < 0) { + if (taosArrayPush(pWriter->aDelData, &delData) == NULL) { code = TSDB_CODE_OUT_OF_MEMORY; TSDB_CHECK_CODE(code, lino, _exit); } @@ -1420,6 +1416,7 @@ _exit: tBlockDataDestroy(&pWriter->bData); tBlockDataDestroy(&pWriter->inData); tsdbFSDestroy(&pWriter->fs); + taosMemoryFree(pWriter); pWriter = NULL; } } else { diff --git a/source/dnode/vnode/src/tsdb/tsdbUtil.c b/source/dnode/vnode/src/tsdb/tsdbUtil.c index 44887b40b7..c323ae1532 100644 --- a/source/dnode/vnode/src/tsdb/tsdbUtil.c +++ b/source/dnode/vnode/src/tsdb/tsdbUtil.c @@ -116,12 +116,7 @@ int32_t tMapDataToArray(SMapData *pMapData, int32_t itemSize, int32_t (*tGetItem } _exit: - if (code) { - *ppArray = NULL; - if (pArray) taosArrayDestroy(pArray); - } else { - *ppArray = pArray; - } + *ppArray = pArray; return code; } @@ -1101,6 +1096,7 @@ int32_t tsdbBuildDeleteSkyline(SArray *aDelData, int32_t sidx, int32_t eidx, SAr SArray *aTmpSkyline = taosArrayInit(dataNum * 2, sizeof(TSDBKEY)); SArray *pSkyline = taosArrayInit(dataNum * 2, POINTER_BYTES); + taosArrayClear(aSkyline); for (int32_t i = sidx; i <= eidx; ++i) { pDelData = (SDelData *)taosArrayGet(aDelData, i); taosArrayPush(aTmpSkyline, &(TSDBKEY){.ts = pDelData->sKey, .version = pDelData->version}); @@ -1233,14 +1229,22 @@ int32_t tBlockDataInit(SBlockData *pBlockData, TABLEID *pId, STSchema *pTSchema, int32_t iColumn = 1; STColumn *pTColumn = &pTSchema->columns[iColumn]; for (int32_t iCid = 0; iCid < nCid; iCid++) { - ASSERT(pTColumn); + if (ASSERTS(pTColumn != NULL, "invalid input param")) { + code = TSDB_CODE_INVALID_PARA; + goto _exit; + } + while (pTColumn->colId < aCid[iCid]) { iColumn++; ASSERT(iColumn < pTSchema->numOfCols); pTColumn = &pTSchema->columns[iColumn]; } - ASSERT(pTColumn->colId == aCid[iCid]); + if (ASSERTS(pTColumn->colId == aCid[iCid], "invalid input param")) { + code = TSDB_CODE_INVALID_PARA; + goto _exit; + } + tColDataInit(&pBlockData->aColData[iCid], pTColumn->colId, pTColumn->type, (pTColumn->flags & COL_SMA_ON) ? 1 : 0); diff --git a/source/dnode/vnode/src/tsdb/tsdbWrite.c b/source/dnode/vnode/src/tsdb/tsdbWrite.c index 301b504346..bd2d263804 100644 --- a/source/dnode/vnode/src/tsdb/tsdbWrite.c +++ b/source/dnode/vnode/src/tsdb/tsdbWrite.c @@ -31,7 +31,9 @@ int tsdbInsertData(STsdb *pTsdb, int64_t version, SSubmitReq2 *pMsg, SSubmitRsp2 int32_t affectedrows = 0; int32_t numOfRows = 0; - ASSERT(pTsdb->mem != NULL); + if (ASSERTS(pTsdb->mem != NULL, "vgId:%d, mem is NULL", TD_VID(pTsdb->pVnode))) { + return -1; + } if (pMsg) { arrSize = taosArrayGetSize(pMsg->aSubmitTbData); diff --git a/source/dnode/vnode/src/vnd/vnodeCommit.c b/source/dnode/vnode/src/vnd/vnodeCommit.c index b075c3d835..0779388ba9 100644 --- a/source/dnode/vnode/src/vnd/vnodeCommit.c +++ b/source/dnode/vnode/src/vnd/vnodeCommit.c @@ -150,22 +150,21 @@ void vnodeUpdCommitSched(SVnode *pVnode) { } int vnodeShouldCommit(SVnode *pVnode) { - if (!pVnode->inUse || !osDataSpaceAvailable()) { - return false; - } - SVCommitSched *pSched = &pVnode->commitSched; int64_t nowMs = taosGetMonoTimestampMs(); + bool diskAvail = osDataSpaceAvailable(); + bool needCommit = false; - return (((pVnode->inUse->size > pVnode->inUse->node.size) && (pSched->commitMs + SYNC_VND_COMMIT_MIN_MS < nowMs)) || - (pVnode->inUse->size > 0 && pSched->commitMs + pSched->maxWaitMs < nowMs)); -} - -int vnodeShouldCommitOld(SVnode *pVnode) { - if (pVnode->inUse) { - return osDataSpaceAvailable() && (pVnode->inUse->size > pVnode->inUse->node.size); + taosThreadMutexLock(&pVnode->mutex); + if (!pVnode->inUse || !diskAvail) { + goto _out; } - return false; + needCommit = + (((pVnode->inUse->size > pVnode->inUse->node.size) && (pSched->commitMs + SYNC_VND_COMMIT_MIN_MS < nowMs)) || + (pVnode->inUse->size > 0 && pSched->commitMs + pSched->maxWaitMs < nowMs)); +_out: + taosThreadMutexUnlock(&pVnode->mutex); + return needCommit; } int vnodeSaveInfo(const char *dir, const SVnodeInfo *pInfo) { diff --git a/source/dnode/vnode/src/vnd/vnodeCompact.c b/source/dnode/vnode/src/vnd/vnodeCompact.c index 14d893042d..16e39d75dc 100644 --- a/source/dnode/vnode/src/vnd/vnodeCompact.c +++ b/source/dnode/vnode/src/vnd/vnodeCompact.c @@ -36,8 +36,8 @@ static int32_t vnodeCompactTask(void *param) { vnodeCommitInfo(dir); _exit: - taosMemoryFree(pInfo); tsem_post(&pInfo->pVnode->canCommit); + taosMemoryFree(pInfo); return code; } static int32_t vnodePrepareCompact(SVnode *pVnode, SCompactInfo *pInfo) { @@ -59,9 +59,17 @@ static int32_t vnodePrepareCompact(SVnode *pVnode, SCompactInfo *pInfo) { snprintf(dir, TSDB_FILENAME_LEN, "%s", pVnode->path); } - vnodeLoadInfo(dir, &info); + if (vnodeLoadInfo(dir, &info) < 0) { + code = terrno; + goto _exit; + } + info.state.commitID = pInfo->commitID; - vnodeSaveInfo(dir, &info); + + if (vnodeSaveInfo(dir, &info) < 0) { + code = terrno; + goto _exit; + } _exit: if (code) { diff --git a/source/dnode/vnode/src/vnd/vnodeOpen.c b/source/dnode/vnode/src/vnd/vnodeOpen.c index 68ee50a14f..c7d155be0d 100644 --- a/source/dnode/vnode/src/vnd/vnodeOpen.c +++ b/source/dnode/vnode/src/vnd/vnodeOpen.c @@ -48,7 +48,7 @@ int32_t vnodeCreate(const char *path, SVnodeCfg *pCfg, STfs *pTfs) { info.state.applied = -1; info.state.commitID = 0; - vInfo("vgId:%d, save config while create", pCfg->vgId); + vInfo("vgId:%d, save config while create", info.config.vgId); if (vnodeSaveInfo(dir, &info) < 0 || vnodeCommitInfo(dir) < 0) { vError("vgId:%d, failed to save vnode config since %s", pCfg ? pCfg->vgId : 0, tstrerror(terrno)); return -1; @@ -124,7 +124,7 @@ int32_t vnodeRenameVgroupId(const char *srcPath, const char *dstPath, int32_t sr while (1) { const STfsFile *tsdbFile = tfsReaddir(tsdbDir); if (tsdbFile == NULL) break; - if (tsdbFile->rname == NULL) continue; + if (tsdbFile->rname[0] == '\0') continue; tstrncpy(oldRname, tsdbFile->rname, TSDB_FILENAME_LEN); char *tsdbFilePrefixPos = strstr(oldRname, tsdbFilePrefix); diff --git a/source/dnode/vnode/src/vnd/vnodeQuery.c b/source/dnode/vnode/src/vnd/vnodeQuery.c index dac712b4e9..c017266839 100644 --- a/source/dnode/vnode/src/vnd/vnodeQuery.c +++ b/source/dnode/vnode/src/vnd/vnodeQuery.c @@ -197,7 +197,7 @@ int vnodeGetTableCfg(SVnode *pVnode, SRpcMsg *pMsg, bool direct) { cfgRsp.ttl = mer1.me.ctbEntry.ttlDays; cfgRsp.commentLen = mer1.me.ctbEntry.commentLen; if (mer1.me.ctbEntry.commentLen > 0) { - cfgRsp.pComment = strdup(mer1.me.ctbEntry.comment); + cfgRsp.pComment = taosStrdup(mer1.me.ctbEntry.comment); } STag *pTag = (STag *)mer1.me.ctbEntry.pTags; cfgRsp.tagsLen = pTag->len; @@ -208,7 +208,7 @@ int vnodeGetTableCfg(SVnode *pVnode, SRpcMsg *pMsg, bool direct) { cfgRsp.ttl = mer1.me.ntbEntry.ttlDays; cfgRsp.commentLen = mer1.me.ntbEntry.commentLen; if (mer1.me.ntbEntry.commentLen > 0) { - cfgRsp.pComment = strdup(mer1.me.ntbEntry.comment); + cfgRsp.pComment = taosStrdup(mer1.me.ntbEntry.comment); } } else { ASSERT(0); diff --git a/source/dnode/vnode/src/vnd/vnodeSvr.c b/source/dnode/vnode/src/vnd/vnodeSvr.c index e57b200ab6..8651478afa 100644 --- a/source/dnode/vnode/src/vnd/vnodeSvr.c +++ b/source/dnode/vnode/src/vnd/vnodeSvr.c @@ -141,7 +141,10 @@ static int32_t vnodePreProcessSubmitTbData(SVnode *pVnode, SDecoder *pCoder, int *(int64_t *)(pCoder->data + pCoder->pos) = uid; pCoder->pos += sizeof(int64_t); } else { - tDecodeI64(pCoder, &submitTbData.uid); + if (tDecodeI64(pCoder, &submitTbData.uid) < 0) { + code = TSDB_CODE_INVALID_MSG; + TSDB_CHECK_CODE(code, lino, _exit); + } } if (tDecodeI32v(pCoder, &submitTbData.sver) < 0) { @@ -168,6 +171,11 @@ static int32_t vnodePreProcessSubmitTbData(SVnode *pVnode, SDecoder *pCoder, int SColData colData = {0}; pCoder->pos += tGetColData(pCoder->data + pCoder->pos, &colData); + if (colData.flag != HAS_VALUE) { + code = TSDB_CODE_INVALID_MSG; + goto _exit; + } + for (int32_t iRow = 0; iRow < colData.nVal; iRow++) { if (((TSKEY *)colData.pData)[iRow] < minKey || ((TSKEY *)colData.pData)[iRow] > maxKey) { code = TSDB_CODE_TDB_TIMESTAMP_OUT_OF_RANGE; @@ -620,12 +628,14 @@ static int32_t vnodeProcessDropTtlTbReq(SVnode *pVnode, int64_t version, void *p tqUpdateTbUidList(pVnode->pTq, tbUids, false); } +#if 0 // process ret = tsdbDoRetention(pVnode->pTsdb, ttlReq.timestamp); if (ret) goto end; ret = smaDoRetention(pVnode->pSma, ttlReq.timestamp); if (ret) goto end; +#endif end: taosArrayDestroy(tbUids); diff --git a/source/libs/catalog/src/ctgAsync.c b/source/libs/catalog/src/ctgAsync.c index fca7a17a36..2eb82324c1 100644 --- a/source/libs/catalog/src/ctgAsync.c +++ b/source/libs/catalog/src/ctgAsync.c @@ -1707,7 +1707,7 @@ int32_t ctgLaunchGetTbMetasTask(SCtgTask* pTask) { return TSDB_CODE_SUCCESS; } - pTask->msgCtxs = taosArrayInit_s(pCtx->fetchNum, sizeof(SCtgMsgCtx), pCtx->fetchNum); + pTask->msgCtxs = taosArrayInit_s(sizeof(SCtgMsgCtx), pCtx->fetchNum); for (int32_t i = 0; i < pCtx->fetchNum; ++i) { SCtgFetch* pFetch = taosArrayGet(pCtx->pFetchs, i); SName* pName = ctgGetFetchName(pCtx->pNames, pFetch); @@ -1857,7 +1857,7 @@ int32_t ctgLaunchGetTbHashsTask(SCtgTask* pTask) { return TSDB_CODE_SUCCESS; } - pTask->msgCtxs = taosArrayInit_s(pCtx->fetchNum, sizeof(SCtgMsgCtx), pCtx->fetchNum); + pTask->msgCtxs = taosArrayInit_s(sizeof(SCtgMsgCtx), pCtx->fetchNum); for (int32_t i = 0; i < pCtx->fetchNum; ++i) { SCtgFetch* pFetch = taosArrayGet(pCtx->pFetchs, i); diff --git a/source/libs/catalog/src/ctgCache.c b/source/libs/catalog/src/ctgCache.c index 5d71ab20cb..c6a7979ff7 100644 --- a/source/libs/catalog/src/ctgCache.c +++ b/source/libs/catalog/src/ctgCache.c @@ -496,11 +496,9 @@ int32_t ctgCopyTbMeta(SCatalog *pCtg, SCtgTbMetaCtx *ctx, SCtgDBCache **pDb, SCt //ctgReleaseTbMetaToCache(pCtg, dbCache, tbCache); - if (tbCache) { - CTG_UNLOCK(CTG_READ, &tbCache->metaLock); - taosHashRelease(dbCache->tbCache, tbCache); - *pTb = NULL; - } + CTG_UNLOCK(CTG_READ, &tbCache->metaLock); + taosHashRelease(dbCache->tbCache, tbCache); + *pTb = NULL; ctgDebug("Got ctb %s meta from cache, will continue to get its stb meta, type:%d, dbFName:%s", ctx->pName->tname, ctx->tbInfo.tbType, dbFName); @@ -1557,8 +1555,8 @@ int32_t ctgWriteTbMetaToCache(SCatalog *pCtg, SCtgDBCache *dbCache, char *dbFNam SCtgTbCache cache = {0}; cache.pMeta = meta; if (taosHashPut(dbCache->tbCache, tbName, strlen(tbName), &cache, sizeof(SCtgTbCache)) != 0) { - taosMemoryFree(meta); ctgError("taosHashPut new tbCache failed, dbFName:%s, tbName:%s, tbType:%d", dbFName, tbName, meta->tableType); + taosMemoryFree(meta); CTG_ERR_RET(TSDB_CODE_OUT_OF_MEMORY); } diff --git a/source/libs/catalog/src/ctgDbg.c b/source/libs/catalog/src/ctgDbg.c index a6c0d1c401..6b870232c7 100644 --- a/source/libs/catalog/src/ctgDbg.c +++ b/source/libs/catalog/src/ctgDbg.c @@ -281,7 +281,7 @@ int32_t ctgdHandleDbgCommand(char *command) { CTG_RET(TSDB_CODE_INVALID_PARA); } - char *dup = strdup(command); + char *dup = taosStrdup(command); char *option = NULL; char *param = NULL; diff --git a/source/libs/catalog/src/ctgUtil.c b/source/libs/catalog/src/ctgUtil.c index 45aa95436e..b0aa673a5e 100644 --- a/source/libs/catalog/src/ctgUtil.c +++ b/source/libs/catalog/src/ctgUtil.c @@ -743,7 +743,7 @@ int32_t ctgUpdateMsgCtx(SCtgMsgCtx* pCtx, int32_t reqType, void* out, char* targ pCtx->reqType = reqType; pCtx->out = out; if (target) { - pCtx->target = strdup(target); + pCtx->target = taosStrdup(target); if (NULL == pCtx->target) { CTG_ERR_RET(TSDB_CODE_OUT_OF_MEMORY); } @@ -760,7 +760,7 @@ int32_t ctgAddMsgCtx(SArray* pCtxs, int32_t reqType, void* out, char* target) { ctx.reqType = reqType; ctx.out = out; if (target) { - ctx.target = strdup(target); + ctx.target = taosStrdup(target); if (NULL == ctx.target) { CTG_ERR_RET(TSDB_CODE_OUT_OF_MEMORY); } @@ -1170,7 +1170,7 @@ int32_t ctgCloneTableIndex(SArray* pIndex, SArray** pRes) { for (int32_t i = 0; i < num; ++i) { STableIndexInfo* pInfo = taosArrayGet(pIndex, i); pInfo = taosArrayPush(*pRes, pInfo); - pInfo->expr = strdup(pInfo->expr); + pInfo->expr = taosStrdup(pInfo->expr); } return TSDB_CODE_SUCCESS; @@ -1180,7 +1180,7 @@ int32_t ctgUpdateSendTargetInfo(SMsgSendInfo* pMsgSendInfo, int32_t msgType, cha if (msgType == TDMT_VND_TABLE_META || msgType == TDMT_VND_TABLE_CFG || msgType == TDMT_VND_BATCH_META) { pMsgSendInfo->target.type = TARGET_TYPE_VNODE; pMsgSendInfo->target.vgId = vgId; - pMsgSendInfo->target.dbFName = strdup(dbFName); + pMsgSendInfo->target.dbFName = taosStrdup(dbFName); } else { pMsgSendInfo->target.type = TARGET_TYPE_MNODE; } diff --git a/source/libs/command/src/command.c b/source/libs/command/src/command.c index 886eb8f387..f88701afe2 100644 --- a/source/libs/command/src/command.c +++ b/source/libs/command/src/command.c @@ -104,13 +104,13 @@ static void setDescResultIntoDataBlock(bool sysInfoUser, SSDataBlock* pBlock, in continue; } STR_TO_VARSTR(buf, pMeta->schema[i].name); - colDataAppend(pCol1, pBlock->info.rows, buf, false); + colDataSetVal(pCol1, pBlock->info.rows, buf, false); STR_TO_VARSTR(buf, tDataTypes[pMeta->schema[i].type].name); - colDataAppend(pCol2, pBlock->info.rows, buf, false); + colDataSetVal(pCol2, pBlock->info.rows, buf, false); int32_t bytes = getSchemaBytes(pMeta->schema + i); - colDataAppend(pCol3, pBlock->info.rows, (const char*)&bytes, false); + colDataSetVal(pCol3, pBlock->info.rows, (const char*)&bytes, false); STR_TO_VARSTR(buf, i >= pMeta->tableInfo.numOfColumns ? "TAG" : ""); - colDataAppend(pCol4, pBlock->info.rows, buf, false); + colDataSetVal(pCol4, pBlock->info.rows, buf, false); ++(pBlock->info.rows); } } @@ -255,7 +255,7 @@ static void setCreateDBResultIntoDataBlock(SSDataBlock* pBlock, char* dbFName, S SColumnInfoData* pCol1 = taosArrayGet(pBlock->pDataBlock, 0); char buf1[SHOW_CREATE_DB_RESULT_FIELD1_LEN] = {0}; STR_TO_VARSTR(buf1, dbFName); - colDataAppend(pCol1, 0, buf1, false); + colDataSetVal(pCol1, 0, buf1, false); SColumnInfoData* pCol2 = taosArrayGet(pBlock->pDataBlock, 1); char buf2[SHOW_CREATE_DB_RESULT_FIELD2_LEN] = {0}; @@ -295,7 +295,7 @@ static void setCreateDBResultIntoDataBlock(SSDataBlock* pBlock, char* dbFName, S (varDataLen(buf2)) = len; - colDataAppend(pCol2, 0, buf2, false); + colDataSetVal(pCol2, 0, buf2, false); } #define CHECK_LEADER(n) (row[n] && (fields[n].type == TSDB_DATA_TYPE_VARCHAR && strncasecmp(row[n], "leader", varDataLen((char *)row[n] - VARSTR_HEADER_SIZE)) == 0)) @@ -607,7 +607,7 @@ static int32_t setCreateTBResultIntoDataBlock(SSDataBlock* pBlock, SDbCfgInfo* p SColumnInfoData* pCol1 = taosArrayGet(pBlock->pDataBlock, 0); char buf1[SHOW_CREATE_TB_RESULT_FIELD1_LEN] = {0}; STR_TO_VARSTR(buf1, tbName); - colDataAppend(pCol1, 0, buf1, false); + colDataSetVal(pCol1, 0, buf1, false); SColumnInfoData* pCol2 = taosArrayGet(pBlock->pDataBlock, 1); char* buf2 = taosMemoryMalloc(SHOW_CREATE_TB_RESULT_FIELD2_LEN); @@ -645,7 +645,7 @@ static int32_t setCreateTBResultIntoDataBlock(SSDataBlock* pBlock, SDbCfgInfo* p varDataLen(buf2) = (len > 65535) ? 65535 : len; - colDataAppend(pCol2, 0, buf2, false); + colDataSetVal(pCol2, 0, buf2, false); taosMemoryFree(buf2); @@ -783,14 +783,14 @@ int32_t setLocalVariablesResultIntoDataBlock(SSDataBlock* pBlock) { char name[TSDB_CONFIG_OPTION_LEN + VARSTR_HEADER_SIZE] = {0}; STR_WITH_MAXSIZE_TO_VARSTR(name, pItem->name, TSDB_CONFIG_OPTION_LEN + VARSTR_HEADER_SIZE); SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, c++); - colDataAppend(pColInfo, i, name, false); + colDataSetVal(pColInfo, i, name, false); char value[TSDB_CONFIG_VALUE_LEN + VARSTR_HEADER_SIZE] = {0}; int32_t valueLen = 0; cfgDumpItemValue(pItem, &value[VARSTR_HEADER_SIZE], TSDB_CONFIG_VALUE_LEN, &valueLen); varDataSetLen(value, valueLen); pColInfo = taosArrayGet(pBlock->pDataBlock, c++); - colDataAppend(pColInfo, i, value, false); + colDataSetVal(pColInfo, i, value, false); numOfRows++; } @@ -846,9 +846,9 @@ int32_t buildSelectResultDataBlock(SNodeList* pProjects, SSDataBlock* pBlock) { return TSDB_CODE_PAR_INVALID_SELECTED_EXPR; } else { if (((SValueNode*)pProj)->isNull) { - colDataAppend(taosArrayGet(pBlock->pDataBlock, index++), 0, NULL, true); + colDataSetVal(taosArrayGet(pBlock->pDataBlock, index++), 0, NULL, true); } else { - colDataAppend(taosArrayGet(pBlock->pDataBlock, index++), 0, nodesGetValueFromNode((SValueNode*)pProj), false); + colDataSetVal(taosArrayGet(pBlock->pDataBlock, index++), 0, nodesGetValueFromNode((SValueNode*)pProj), false); } } } diff --git a/source/libs/command/src/explain.c b/source/libs/command/src/explain.c index fdbbcad968..4302302d7a 100644 --- a/source/libs/command/src/explain.c +++ b/source/libs/command/src/explain.c @@ -1556,7 +1556,7 @@ int32_t qExplainGetRspFromCtx(void *ctx, SRetrieveTableRsp **pRsp) { for (int32_t i = 0; i < rowNum; ++i) { SQueryExplainRowInfo *row = taosArrayGet(pCtx->rows, i); - colDataAppend(pInfoData, i, row->buf, false); + colDataSetVal(pInfoData, i, row->buf, false); } pBlock->info.rows = rowNum; diff --git a/source/libs/executor/src/cachescanoperator.c b/source/libs/executor/src/cachescanoperator.c index 60e4e85fb8..d42b348fd8 100644 --- a/source/libs/executor/src/cachescanoperator.c +++ b/source/libs/executor/src/cachescanoperator.c @@ -182,10 +182,10 @@ SSDataBlock* doScanCache(SOperatorInfo* pOperator) { SColumnInfoData* pDst = taosArrayGet(pRes->pDataBlock, slotId); if (colDataIsNull_s(pSrc, pInfo->indexOfBufferedRes)) { - colDataAppendNULL(pDst, 0); + colDataSetNULL(pDst, 0); } else { char* p = colDataGetData(pSrc, pInfo->indexOfBufferedRes); - colDataAppend(pDst, 0, p, false); + colDataSetVal(pDst, 0, p, false); } } diff --git a/source/libs/executor/src/dataDeleter.c b/source/libs/executor/src/dataDeleter.c index 184b9e0148..dc3bf83a91 100644 --- a/source/libs/executor/src/dataDeleter.c +++ b/source/libs/executor/src/dataDeleter.c @@ -62,9 +62,6 @@ static void toDataCacheEntry(SDataDeleterHandle* pHandle, const SInputData* pInp pEntry->numOfCols = taosArrayGetSize(pInput->pData->pDataBlock); pEntry->dataLen = sizeof(SDeleterRes); - // ASSERT(1 == pEntry->numOfRows); - // ASSERT(3 == pEntry->numOfCols); - pBuf->useSize = sizeof(SDataCacheEntry); SColumnInfoData* pColRes = (SColumnInfoData*)taosArrayGet(pInput->pData->pDataBlock, 0); diff --git a/source/libs/executor/src/dataInserter.c b/source/libs/executor/src/dataInserter.c index 16b43b560c..e9c46843c0 100644 --- a/source/libs/executor/src/dataInserter.c +++ b/source/libs/executor/src/dataInserter.c @@ -230,12 +230,19 @@ int32_t buildSubmitReqFromBlock(SDataInserterHandle* pInserter, SSubmitReq2** pp case TSDB_DATA_TYPE_BLOB: case TSDB_DATA_TYPE_JSON: case TSDB_DATA_TYPE_MEDIUMBLOB: - uError("the column type %" PRIi16 " is defined but not implemented yet", pColInfoData->info.type); - ASSERT(0); + qError("the column type %" PRIi16 " is defined but not implemented yet", pColInfoData->info.type); + terrno = TSDB_CODE_APP_ERROR; + goto _end; break; default: if (pColInfoData->info.type < TSDB_DATA_TYPE_MAX && pColInfoData->info.type > TSDB_DATA_TYPE_NULL) { if (colDataIsNull_s(pColInfoData, j)) { + if (PRIMARYKEY_TIMESTAMP_COL_ID == pCol->colId) { + qError("NULL value for primary key"); + terrno = TSDB_CODE_PAR_INCORRECT_TIMESTAMP_VAL; + goto _end; + } + SColVal cv = COL_VAL_NULL(pCol->colId, pCol->type); // should use pCol->type taosArrayPush(pVals, &cv); } else { @@ -256,7 +263,8 @@ int32_t buildSubmitReqFromBlock(SDataInserterHandle* pInserter, SSubmitReq2** pp } } else { uError("the column type %" PRIi16 " is undefined\n", pColInfoData->info.type); - ASSERT(0); + terrno = TSDB_CODE_APP_ERROR; + goto _end; } break; } @@ -296,7 +304,7 @@ _end: tDestroySSubmitReq2(pReq, TSDB_MSG_FLG_ENCODE); taosMemoryFree(pReq); } - return TSDB_CODE_FAILED; + return terrno; } *ppReq = pReq; return TSDB_CODE_SUCCESS; diff --git a/source/libs/executor/src/executil.c b/source/libs/executor/src/executil.c index 639adb7ec6..6b6f5cfe93 100644 --- a/source/libs/executor/src/executil.c +++ b/source/libs/executor/src/executil.c @@ -176,7 +176,6 @@ void initGroupedResultInfo(SGroupResInfo* pGroupResInfo, SSHashObj* pHashmap, in } pGroupResInfo->index = 0; - assert(pGroupResInfo->index <= getNumOfTotalRes(pGroupResInfo)); } void initMultiResInfoFromArrayList(SGroupResInfo* pGroupResInfo, SArray* pArrayList) { @@ -340,10 +339,7 @@ int32_t isQualifiedTable(STableKeyInfo* info, SNode* pTagCond, void* metaHandle, return code; } - ASSERT(nodeType(pNew) == QUERY_NODE_VALUE); SValueNode* pValue = (SValueNode*)pNew; - - ASSERT(pValue->node.resType.type == TSDB_DATA_TYPE_BOOL); *pQualified = pValue->datum.b; nodesDestroyNode(pNew); @@ -845,7 +841,7 @@ static SSDataBlock* createTagValBlockForFilter(SArray* pColList, int32_t numOfTa metaGetTableNameByUid(metaHandle, p1->uid, str); } - colDataAppend(pColInfo, i, str, false); + colDataSetVal(pColInfo, i, str, false); #if TAG_FILTER_DEBUG qDebug("tagfilter uid:%ld, tbname:%s", *uid, str + 2); #endif @@ -853,25 +849,26 @@ static SSDataBlock* createTagValBlockForFilter(SArray* pColList, int32_t numOfTa STagVal tagVal = {0}; tagVal.cid = pColInfo->info.colId; if (p1->pTagVal == NULL) { - colDataAppendNULL(pColInfo, i); + colDataSetNULL(pColInfo, i); } const char* p = metaGetTableTagVal(p1->pTagVal, pColInfo->info.type, &tagVal); if (p == NULL || (pColInfo->info.type == TSDB_DATA_TYPE_JSON && ((STag*)p)->nTag == 0)) { - colDataAppendNULL(pColInfo, i); + colDataSetNULL(pColInfo, i); } else if (pColInfo->info.type == TSDB_DATA_TYPE_JSON) { - colDataAppend(pColInfo, i, p, false); + colDataSetVal(pColInfo, i, p, false); } else if (IS_VAR_DATA_TYPE(pColInfo->info.type)) { - char* tmp = alloca(tagVal.nData + VARSTR_HEADER_SIZE + 1); + char* tmp = taosMemoryMalloc(tagVal.nData + VARSTR_HEADER_SIZE + 1); varDataSetLen(tmp, tagVal.nData); memcpy(tmp + VARSTR_HEADER_SIZE, tagVal.pData, tagVal.nData); - colDataAppend(pColInfo, i, tmp, false); + colDataSetVal(pColInfo, i, tmp, false); #if TAG_FILTER_DEBUG qDebug("tagfilter varch:%s", tmp + 2); #endif + taosMemoryFree(tmp); } else { - colDataAppend(pColInfo, i, (const char*)&tagVal.i64, false); + colDataSetVal(pColInfo, i, (const char*)&tagVal.i64, false); #if TAG_FILTER_DEBUG if (pColInfo->info.type == TSDB_DATA_TYPE_INT) { qDebug("tagfilter int:%d", *(int*)(&tagVal.i64)); @@ -1054,7 +1051,6 @@ int32_t getTableList(void* metaHandle, void* pVnode, SScanPhysiNode* pScanNode, } if (!pTagCond) { // no tag filter condition exists, let's fetch all tables of this super table - ASSERT(pTagIndexCond == NULL); vnodeGetCtbIdList(pVnode, pScanNode->suid, pUidList); } else { // failed to find the result in the cache, let try to calculate the results @@ -1148,7 +1144,6 @@ int32_t getGroupIdFromTagsVal(void* pMeta, uint64_t uid, SNodeList* pGroupNode, if (TSDB_CODE_SUCCESS == code) { REPLACE_NODE(pNew); } else { - taosMemoryFree(keyBuf); nodesDestroyList(groupNew); metaReaderClear(&mr); return code; @@ -1166,7 +1161,6 @@ int32_t getGroupIdFromTagsVal(void* pMeta, uint64_t uid, SNodeList* pGroupNode, if (pValue->node.resType.type == TSDB_DATA_TYPE_JSON) { if (tTagIsJson(data)) { terrno = TSDB_CODE_QRY_JSON_IN_GROUP_ERROR; - taosMemoryFree(keyBuf); nodesDestroyList(groupNew); metaReaderClear(&mr); return terrno; @@ -1368,7 +1362,6 @@ void createExprFromOneNode(SExprInfo* pExp, SNode* pNode, int16_t slotId) { if (!pFuncNode->pParameterList && (memcmp(pExprNode->_function.functionName, name, len) == 0) && pExprNode->_function.functionName[len] == 0) { pFuncNode->pParameterList = nodesMakeList(); - ASSERT(LIST_LENGTH(pFuncNode->pParameterList) == 0); SValueNode* res = (SValueNode*)nodesMakeNode(QUERY_NODE_VALUE); if (NULL == res) { // todo handle error } else { @@ -1531,7 +1524,7 @@ SqlFunctionCtx* createSqlFunctionCtx(SExprInfo* pExprInfo, int32_t numOfOutput, fmGetFuncExecFuncs(pCtx->functionId, &pCtx->fpSet); } else { char* udfName = pExpr->pExpr->_function.pFunctNode->functionName; - pCtx->udfName = strdup(udfName); + pCtx->udfName = taosStrdup(udfName); fmGetUdafExecFuncs(pCtx->functionId, &pCtx->fpSet); } pCtx->fpSet.getEnv(pExpr->pExpr->_function.pFunctNode, &env); @@ -1708,7 +1701,7 @@ static void getInitialStartTimeWindow(SInterval* pInterval, TSKEY ts, STimeWindo int64_t key = w->skey; while (key < ts) { // moving towards end key = taosTimeAdd(key, pInterval->sliding, pInterval->slidingUnit, pInterval->precision); - if (key >= ts) { + if (key > ts) { break; } @@ -1820,7 +1813,6 @@ uint64_t getTableGroupId(const STableListInfo* pTableList, uint64_t tableUid) { // TODO handle the group offset info, fix it, the rule of group output will be broken by this function int32_t tableListAddTableInfo(STableListInfo* pTableList, uint64_t uid, uint64_t gid) { if (pTableList->map == NULL) { - ASSERT(taosArrayGetSize(pTableList->pTableList) == 0); pTableList->map = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_ENTRY_LOCK); } @@ -1970,7 +1962,6 @@ static int32_t sortTableGroup(STableListInfo* pTableListInfo) { int32_t buildGroupIdMapForAllTables(STableListInfo* pTableListInfo, SReadHandle* pHandle, SNodeList* group, bool groupSort) { int32_t code = TSDB_CODE_SUCCESS; - ASSERT(pTableListInfo->map != NULL); bool groupByTbname = groupbyTbname(group); size_t numOfTables = taosArrayGetSize(pTableListInfo->pTableList); @@ -2027,7 +2018,6 @@ int32_t createScanTableListInfo(SScanPhysiNode* pScanNode, SNodeList* pGroupTags } int32_t numOfTables = taosArrayGetSize(pTableListInfo->pTableList); - ASSERT(pTableListInfo->numOfOuputGroups == 1); int64_t st1 = taosGetTimestampUs(); pTaskInfo->cost.extractListTime = (st1 - st) / 1000.0; diff --git a/source/libs/executor/src/executor.c b/source/libs/executor/src/executor.c index c599b479e6..347ac369d8 100644 --- a/source/libs/executor/src/executor.c +++ b/source/libs/executor/src/executor.c @@ -35,7 +35,6 @@ static void initRefPool() { } static int32_t doSetSMABlock(SOperatorInfo* pOperator, void* input, size_t numOfBlocks, int32_t type, char* id) { - ASSERT(pOperator != NULL); if (pOperator->operatorType != QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN) { if (pOperator->numOfDownstream == 0) { qError("failed to find stream scan operator to set the input data block, %s" PRIx64, id); @@ -78,27 +77,23 @@ static int32_t doSetSMABlock(SOperatorInfo* pOperator, void* input, size_t numOf } static int32_t doSetStreamOpOpen(SOperatorInfo* pOperator, char* id) { - { - ASSERT(pOperator != NULL); - if (pOperator->operatorType != QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN) { - if (pOperator->numOfDownstream == 0) { - qError("failed to find stream scan operator to set the input data block, %s" PRIx64, id); - return TSDB_CODE_APP_ERROR; - } - - if (pOperator->numOfDownstream > 1) { // not handle this in join query - qError("join not supported for stream block scan, %s" PRIx64, id); - return TSDB_CODE_APP_ERROR; - } - pOperator->status = OP_NOT_OPENED; - return doSetStreamOpOpen(pOperator->pDownstream[0], id); + if (pOperator->operatorType != QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN) { + if (pOperator->numOfDownstream == 0) { + qError("failed to find stream scan operator to set the input data block, %s" PRIx64, id); + return TSDB_CODE_APP_ERROR; } + + if (pOperator->numOfDownstream > 1) { // not handle this in join query + qError("join not supported for stream block scan, %s" PRIx64, id); + return TSDB_CODE_APP_ERROR; + } + pOperator->status = OP_NOT_OPENED; + return doSetStreamOpOpen(pOperator->pDownstream[0], id); } return 0; } static int32_t doSetStreamBlock(SOperatorInfo* pOperator, void* input, size_t numOfBlocks, int32_t type, char* id) { - ASSERT(pOperator != NULL); if (pOperator->operatorType != QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN) { if (pOperator->numOfDownstream == 0) { qError("failed to find stream scan operator to set the input data block, %s" PRIx64, id); @@ -115,7 +110,7 @@ static int32_t doSetStreamBlock(SOperatorInfo* pOperator, void* input, size_t nu pOperator->status = OP_NOT_OPENED; SStreamScanInfo* pInfo = pOperator->info; - + qDebug("stream set total blocks:%d, task id:%s" PRIx64, (int32_t)numOfBlocks, id); ASSERT(pInfo->validBlockIndex == 0); ASSERT(taosArrayGetSize(pInfo->pBlockLists) == 0); @@ -290,11 +285,15 @@ qTaskInfo_t qCreateStreamExecTaskInfo(void* msg, SReadHandle* readers) { static SArray* filterUnqualifiedTables(const SStreamScanInfo* pScanInfo, const SArray* tableIdList, const char* idstr) { SArray* qa = taosArrayInit(4, sizeof(tb_uid_t)); + int32_t numOfUids = taosArrayGetSize(tableIdList); + if (numOfUids == 0) { + return qa; + } // let's discard the tables those are not created according to the queried super table. SMetaReader mr = {0}; metaReaderInit(&mr, pScanInfo->readHandle.meta, 0); - for (int32_t i = 0; i < taosArrayGetSize(tableIdList); ++i) { + for (int32_t i = 0; i < numOfUids; ++i) { uint64_t* id = (uint64_t*)taosArrayGet(tableIdList, i); int32_t code = metaGetTableEntryByUid(&mr, *id); @@ -359,7 +358,6 @@ int32_t qUpdateQualifiedTableId(qTaskInfo_t tinfo, const SArray* tableIdList, bo return code; } - // todo refactor STableList bool assignUid = false; size_t bufLen = (pScanInfo->pGroupTags != NULL) ? getTableTagsBufLen(pScanInfo->pGroupTags) : 0; char* keyBuf = NULL; @@ -1066,18 +1064,9 @@ int32_t qStreamPrepareScan(qTaskInfo_t tinfo, STqOffsetVal* pOffset, int8_t subT STableScanInfo* pTSInfo = pInfo->pTableScanOp->info; tsdbReaderClose(pTSInfo->base.dataReader); pTSInfo->base.dataReader = NULL; -#if 0 - if (tOffsetEqual(pOffset, &pTaskInfo->streamInfo.lastStatus) && - pInfo->tqReader->pWalReader->curVersion != pOffset->version) { - qError("prepare scan ver %" PRId64 " actual ver %" PRId64 ", last %" PRId64, pOffset->version, - pInfo->tqReader->pWalReader->curVersion, pTaskInfo->streamInfo.lastStatus.version); - ASSERT(0); - } -#endif if (tqSeekVer(pInfo->tqReader, pOffset->version + 1) < 0) { return -1; } - ASSERT(pInfo->tqReader->pWalReader->curVersion == pOffset->version + 1); } else if (pOffset->type == TMQ_OFFSET__SNAPSHOT_DATA) { /*pInfo->blockType = STREAM_INPUT__TABLE_SCAN;*/ int64_t uid = pOffset->uid; diff --git a/source/libs/executor/src/executorimpl.c b/source/libs/executor/src/executorimpl.c index eb4a2cba52..89e0dd363c 100644 --- a/source/libs/executor/src/executorimpl.c +++ b/source/libs/executor/src/executorimpl.c @@ -177,7 +177,7 @@ SResultRow* getNewResultRow(SDiskbasedBuf* pResultBuf, int32_t* currentPageId, i // set the number of rows in current disk page SResultRow* pResultRow = (SResultRow*)((char*)pData + pData->num); - memset((char*) pResultRow, 0, interBufSize); + memset((char*)pResultRow, 0, interBufSize); pResultRow->pageId = pageId; pResultRow->offset = (int32_t)pData->num; @@ -240,7 +240,6 @@ SResultRow* doSetResultOutBufByKey(SDiskbasedBuf* pResultBuf, SResultRowInfo* pR // allocate a new buffer page if (pResult == NULL) { - ASSERT(pSup->resultRowSize > 0); pResult = getNewResultRow(pResultBuf, &pSup->currentPageId, pSup->resultRowSize); if (pResult == NULL) { T_LONG_JMP(pTaskInfo->env, terrno); @@ -310,7 +309,6 @@ static int32_t addNewWindowResultBuf(SResultRow* pWindowRes, SDiskbasedBuf* pRes pWindowRes->offset = (int32_t)pData->num; pData->num += size; - assert(pWindowRes->pageId >= 0); } return 0; @@ -322,13 +320,13 @@ void initExecTimeWindowInfo(SColumnInfoData* pColData, STimeWindow* pQueryWindow pColData->info.bytes = sizeof(int64_t); colInfoDataEnsureCapacity(pColData, 5, false); - colDataAppendInt64(pColData, 0, &pQueryWindow->skey); - colDataAppendInt64(pColData, 1, &pQueryWindow->ekey); + colDataSetInt64(pColData, 0, &pQueryWindow->skey); + colDataSetInt64(pColData, 1, &pQueryWindow->ekey); int64_t interval = 0; - colDataAppendInt64(pColData, 2, &interval); // this value may be variable in case of 'n' and 'y'. - colDataAppendInt64(pColData, 3, &pQueryWindow->skey); - colDataAppendInt64(pColData, 4, &pQueryWindow->ekey); + colDataSetInt64(pColData, 2, &interval); // this value may be variable in case of 'n' and 'y'. + colDataSetInt64(pColData, 3, &pQueryWindow->skey); + colDataSetInt64(pColData, 4, &pQueryWindow->ekey); } typedef struct { @@ -397,19 +395,20 @@ void applyAggFunctionOnPartialTuples(SExecTaskInfo* taskInfo, SqlFunctionCtx* pC } } -static void doSetInputDataBlockInfo(SExprSupp* pExprSup, SSDataBlock* pBlock, int32_t order) { +static void doSetInputDataBlockInfo(SExprSupp* pExprSup, SSDataBlock* pBlock, int32_t order, int32_t scanFlag) { SqlFunctionCtx* pCtx = pExprSup->pCtx; for (int32_t i = 0; i < pExprSup->numOfExprs; ++i) { pCtx[i].order = order; pCtx[i].input.numOfRows = pBlock->info.rows; setBlockSMAInfo(&pCtx[i], &pExprSup->pExprInfo[i], pBlock); pCtx[i].pSrcBlock = pBlock; + pCtx[i].scanFlag = scanFlag; } } void setInputDataBlock(SExprSupp* pExprSup, SSDataBlock* pBlock, int32_t order, int32_t scanFlag, bool createDummyCol) { if (pBlock->pBlockAgg != NULL) { - doSetInputDataBlockInfo(pExprSup, pBlock, order); + doSetInputDataBlockInfo(pExprSup, pBlock, order, scanFlag); } else { doSetInputDataBlock(pExprSup, pBlock, order, scanFlag, createDummyCol); } @@ -439,18 +438,18 @@ static int32_t doCreateConstantValColumnInfo(SInputColumnInfoData* pInput, SFunc if (type == TSDB_DATA_TYPE_BIGINT || type == TSDB_DATA_TYPE_UBIGINT) { int64_t v = pFuncParam->param.i; for (int32_t i = 0; i < numOfRows; ++i) { - colDataAppendInt64(pColInfo, i, &v); + colDataSetInt64(pColInfo, i, &v); } } else if (type == TSDB_DATA_TYPE_DOUBLE) { double v = pFuncParam->param.d; for (int32_t i = 0; i < numOfRows; ++i) { - colDataAppendDouble(pColInfo, i, &v); + colDataSetDouble(pColInfo, i, &v); } } else if (type == TSDB_DATA_TYPE_VARCHAR) { char* tmp = taosMemoryMalloc(pFuncParam->param.nLen + VARSTR_HEADER_SIZE); STR_WITH_SIZE_TO_VARSTR(tmp, pFuncParam->param.pz, pFuncParam->param.nLen); for (int32_t i = 0; i < numOfRows; ++i) { - colDataAppend(pColInfo, i, tmp, false); + colDataSetVal(pColInfo, i, tmp, false); } taosMemoryFree(tmp); } @@ -488,7 +487,6 @@ static int32_t doSetInputDataBlock(SExprSupp* pExprSup, SSDataBlock* pBlock, int // todo: refactor this if (fmIsImplicitTsFunc(pCtx[i].functionId) && (j == pOneExpr->base.numOfParams - 1)) { pInput->pPTS = pInput->pData[j]; // in case of merge function, this is not always the ts column data. - // ASSERT(pInput->pPTS->info.type == TSDB_DATA_TYPE_TIMESTAMP); } ASSERT(pInput->pData[j] != NULL); } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) { @@ -539,7 +537,7 @@ bool functionNeedToExecute(SqlFunctionCtx* pCtx) { return false; } - if (pCtx->scanFlag == REPEAT_SCAN) { + if (pCtx->scanFlag == PRE_SCAN) { return fmIsRepeatScanFunc(pCtx->functionId); } @@ -922,7 +920,7 @@ void extractQualifiedTupleByFilterResult(SSDataBlock* pBlock, const SColumnInfoD colDataSetNull_var(pDst, numOfRows); } else { char* p1 = colDataGetVarData(pDst, j); - colDataAppend(pDst, numOfRows, p1, false); + colDataSetVal(pDst, numOfRows, p1, false); } numOfRows += 1; j += 1; @@ -1037,8 +1035,6 @@ void doSetTableGroupOutputBuf(SOperatorInfo* pOperator, int32_t numOfOutput, uin SResultRow* pResultRow = doSetResultOutBufByKey(pAggInfo->aggSup.pResultBuf, pResultRowInfo, (char*)&groupId, sizeof(groupId), true, groupId, pTaskInfo, false, &pAggInfo->aggSup); - assert(pResultRow != NULL); - /* * not assign result buffer yet, add new result buffer * all group belong to one result set, and each group result has different group id so set the id to be one @@ -1116,7 +1112,7 @@ void copyResultrowToDataBlock(SExprInfo* pExprInfo, int32_t numOfExprs, SResultR SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, slotId); char* in = GET_ROWCELL_INTERBUF(pCtx[j].resultInfo); for (int32_t k = 0; k < pRow->numOfRows; ++k) { - colDataAppend(pColInfoData, pBlock->info.rows + k, in, pCtx[j].resultInfo->isNullRes); + colDataSetVal(pColInfoData, pBlock->info.rows + k, in, pCtx[j].resultInfo->isNullRes); } } } @@ -1201,13 +1197,14 @@ int32_t doCopyToSDataBlock(SExecTaskInfo* pTaskInfo, SSDataBlock* pBlock, SExprS } if (pBlock->info.rows + pRow->numOfRows > pBlock->info.capacity) { - releaseBufPage(pBuf, page); - - if (pBlock->info.rows <= 0 || pRow->numOfRows > pBlock->info.capacity) { - qError("error in copy data to ssdatablock, existed rows in block:%d, rows in pRow:%d, capacity:%d, %s", - pBlock->info.rows, pRow->numOfRows, pBlock->info.capacity, GET_TASKID(pTaskInfo)); - T_LONG_JMP(pTaskInfo->env, TSDB_CODE_APP_ERROR); + // expand the result datablock capacity + if (pRow->numOfRows > pBlock->info.capacity) { + blockDataEnsureCapacity(pBlock, pRow->numOfRows); + qDebug("datablock capacity not sufficient, expand to requried:%d, current capacity:%d, %s", pRow->numOfRows, + pBlock->info.capacity, GET_TASKID(pTaskInfo)); + // todo set the pOperator->resultInfo size } else { + releaseBufPage(pBuf, page); break; } } @@ -1291,7 +1288,6 @@ void doBuildResultDatablock(SOperatorInfo* pOperator, SOptrBasicInfo* pbInfo, SG // STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr; // SResultRowInfo *pWindowResInfo = &pRuntimeEnv->resultRowInfo; // -// assert(pQueryAttr->limit.offset == 0); // STimeWindow tw = *win; // getNextTimeWindow(pQueryAttr, &tw); // @@ -1306,7 +1302,6 @@ void doBuildResultDatablock(SOperatorInfo* pOperator, SOptrBasicInfo* pbInfo, SG // tw = *win; // int32_t startPos = // getNextQualifiedWindow(pQueryAttr, &tw, pBlockInfo, pColInfoData->pData, binarySearchForKey, -1); -// assert(startPos >= 0); // // // set the abort info // pQueryAttr->pos = startPos; @@ -1341,11 +1336,6 @@ void doBuildResultDatablock(SOperatorInfo* pOperator, SOptrBasicInfo* pbInfo, SG // static bool skipTimeInterval(STaskRuntimeEnv *pRuntimeEnv, TSKEY* start) { // STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr; -// if (QUERY_IS_ASC_QUERY(pQueryAttr)) { -// assert(*start <= pRuntimeEnv->current->lastKey); -// } else { -// assert(*start >= pRuntimeEnv->current->lastKey); -// } // // // if queried with value filter, do NOT forward query start position // if (pQueryAttr->limit.offset <= 0 || pQueryAttr->numOfFilterCols > 0 || pRuntimeEnv->pTsBuf != NULL || @@ -1359,8 +1349,6 @@ void doBuildResultDatablock(SOperatorInfo* pOperator, SOptrBasicInfo* pbInfo, SG // value is // * not valid. otherwise, we only forward pQueryAttr->limit.offset number of points // */ -// assert(pRuntimeEnv->resultRowInfo.prevSKey == TSKEY_INITIAL_VAL); -// // STimeWindow w = TSWINDOW_INITIALIZER; // bool ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr); // @@ -1430,8 +1418,6 @@ void doBuildResultDatablock(SOperatorInfo* pOperator, SOptrBasicInfo* pbInfo, SG // tw = win; // int32_t startPos = // getNextQualifiedWindow(pQueryAttr, &tw, &blockInfo, pColInfoData->pData, binarySearchForKey, -1); -// assert(startPos >= 0); -// // // set the abort info // pQueryAttr->pos = startPos; // pTableQueryInfo->lastKey = ((TSKEY *)pColInfoData->pData)[startPos]; @@ -1453,10 +1439,6 @@ void doBuildResultDatablock(SOperatorInfo* pOperator, SOptrBasicInfo* pbInfo, SG // } int32_t appendDownstream(SOperatorInfo* p, SOperatorInfo** pDownstream, int32_t num) { - if (p->pDownstream == NULL) { - assert(p->numOfDownstream == 0); - } - p->pDownstream = taosMemoryCalloc(1, num * POINTER_BYTES); if (p->pDownstream == NULL) { return TSDB_CODE_OUT_OF_MEMORY; @@ -1749,8 +1731,8 @@ int32_t getBufferPgSize(int32_t rowSize, uint32_t* defaultPgsz, uint32_t* defaul int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t keyBufSize, const char* pKey) { - int32_t code = 0; -// _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY); + int32_t code = 0; + // _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY); pAggSup->currentPageId = -1; pAggSup->resultRowSize = getResultRowSize(pCtx, numOfOutput); @@ -1812,7 +1794,10 @@ int32_t initAggSup(SExprSupp* pSup, SAggSupporter* pAggSup, SExprInfo* pExprInfo } void initResultSizeInfo(SResultInfo* pResultInfo, int32_t numOfRows) { - ASSERT(numOfRows != 0); + if (numOfRows == 0) { + numOfRows = 4096; + } + pResultInfo->capacity = numOfRows; pResultInfo->threshold = numOfRows * 0.75; @@ -1952,10 +1937,7 @@ _error: return NULL; } -void cleanupBasicInfo(SOptrBasicInfo* pInfo) { - assert(pInfo != NULL); - pInfo->pRes = blockDataDestroy(pInfo->pRes); -} +void cleanupBasicInfo(SOptrBasicInfo* pInfo) { pInfo->pRes = blockDataDestroy(pInfo->pRes); } static void freeItem(void* pItem) { void** p = pItem; @@ -1999,7 +1981,7 @@ static SExecTaskInfo* createExecTaskInfo(uint64_t queryId, uint64_t taskId, EOPT setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED); - pTaskInfo->schemaInfo.dbname = strdup(dbFName); + pTaskInfo->schemaInfo.dbname = taosStrdup(dbFName); pTaskInfo->execModel = model; pTaskInfo->pTableInfoList = tableListCreate(); pTaskInfo->stopInfo.pStopInfo = taosArrayInit(4, sizeof(SExchangeOpStopInfo)); @@ -2025,7 +2007,7 @@ int32_t extractTableSchemaInfo(SReadHandle* pHandle, SScanPhysiNode* pScanNode, } SSchemaInfo* pSchemaInfo = &pTaskInfo->schemaInfo; - pSchemaInfo->tablename = strdup(mr.me.name); + pSchemaInfo->tablename = taosStrdup(mr.me.name); if (mr.me.type == TSDB_SUPER_TABLE) { pSchemaInfo->sw = tCloneSSchemaWrapper(&mr.me.stbEntry.schemaRow); @@ -2034,7 +2016,12 @@ int32_t extractTableSchemaInfo(SReadHandle* pHandle, SScanPhysiNode* pScanNode, tDecoderClear(&mr.coder); tb_uid_t suid = mr.me.ctbEntry.suid; - metaGetTableEntryByUidCache(&mr, suid); + code = metaGetTableEntryByUidCache(&mr, suid); + if (code != TSDB_CODE_SUCCESS) { + metaReaderClear(&mr); + return terrno; + } + pSchemaInfo->sw = tCloneSSchemaWrapper(&mr.me.stbEntry.schemaRow); pSchemaInfo->tversion = mr.me.stbEntry.schemaTag.version; } else { @@ -2259,6 +2246,9 @@ SOperatorInfo* createOperatorTree(SPhysiNode* pPhyNode, SExecTaskInfo* pTaskInfo pOperator = createCacherowsScanOperator(pScanNode, pHandle, pTaskInfo); } else if (QUERY_NODE_PHYSICAL_PLAN_PROJECT == type) { pOperator = createProjectOperatorInfo(NULL, (SProjectPhysiNode*)pPhyNode, pTaskInfo); + } else { + terrno = TSDB_CODE_INVALID_PARA; + return NULL; } if (pOperator != NULL) { @@ -2349,6 +2339,9 @@ SOperatorInfo* createOperatorTree(SPhysiNode* pPhyNode, SExecTaskInfo* pTaskInfo pOptr = createTimeSliceOperatorInfo(ops[0], pPhyNode, pTaskInfo); } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_EVENT == type) { pOptr = createEventwindowOperatorInfo(ops[0], pPhyNode, pTaskInfo); + } else { + terrno = TSDB_CODE_INVALID_PARA; + return NULL; } taosMemoryFree(ops); @@ -2586,7 +2579,6 @@ int32_t setOutputBuf(SStreamState* pState, STimeWindow* win, SResultRow** pResul return TSDB_CODE_OUT_OF_MEMORY; } *pResult = (SResultRow*)value; - ASSERT(*pResult); // set time window for current result (*pResult)->win = (*win); setResultRowInitCtx(*pResult, pCtx, numOfOutput, rowEntryInfoOffset); @@ -2615,9 +2607,9 @@ int32_t buildDataBlockFromGroupRes(SOperatorInfo* pOperator, SStreamState* pStat for (int32_t i = pGroupResInfo->index; i < numOfRows; i += 1) { SWinKey* pKey = taosArrayGet(pGroupResInfo->pRows, i); - int32_t size = 0; - void* pVal = NULL; - int32_t code = streamStateGet(pState, pKey, &pVal, &size); + int32_t size = 0; + void* pVal = NULL; + int32_t code = streamStateGet(pState, pKey, &pVal, &size); ASSERT(code == 0); SResultRow* pRow = (SResultRow*)pVal; doUpdateNumOfRows(pCtx, pRow, numOfExprs, rowEntryOffset); @@ -2671,7 +2663,7 @@ int32_t buildDataBlockFromGroupRes(SOperatorInfo* pOperator, SStreamState* pStat SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, slotId); char* in = GET_ROWCELL_INTERBUF(pCtx[j].resultInfo); for (int32_t k = 0; k < pRow->numOfRows; ++k) { - colDataAppend(pColInfoData, pBlock->info.rows + k, in, pCtx[j].resultInfo->isNullRes); + colDataSetVal(pColInfoData, pBlock->info.rows + k, in, pCtx[j].resultInfo->isNullRes); } } } @@ -2764,7 +2756,7 @@ int32_t buildSessionResultDataBlock(SOperatorInfo* pOperator, SStreamState* pSta SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, slotId); char* in = GET_ROWCELL_INTERBUF(pCtx[j].resultInfo); for (int32_t k = 0; k < pRow->numOfRows; ++k) { - colDataAppend(pColInfoData, pBlock->info.rows + k, in, pCtx[j].resultInfo->isNullRes); + colDataSetVal(pColInfoData, pBlock->info.rows + k, in, pCtx[j].resultInfo->isNullRes); } } } diff --git a/source/libs/executor/src/filloperator.c b/source/libs/executor/src/filloperator.c index 483d94e8b1..adb045a69f 100644 --- a/source/libs/executor/src/filloperator.c +++ b/source/libs/executor/src/filloperator.c @@ -193,8 +193,6 @@ static SSDataBlock* doFillImpl(SOperatorInfo* pOperator) { return pResBlock; } } else if (pInfo->existNewGroupBlock) { // try next group - assert(pBlock != NULL); - blockDataCleanup(pResBlock); doHandleRemainBlockForNewGroupImpl(pOperator, pInfo, pResultInfo, pTaskInfo); @@ -411,7 +409,7 @@ TSKEY getPrevWindowTs(TSKEY ts, SInterval* pInterval) { } void setRowCell(SColumnInfoData* pCol, int32_t rowId, const SResultCellData* pCell) { - colDataAppend(pCol, rowId, pCell->pData, pCell->isNull); + colDataSetVal(pCol, rowId, pCell->pData, pCell->isNull); } SResultCellData* getResultCell(SResultRowData* pRaw, int32_t index) { @@ -905,7 +903,7 @@ static void doStreamFillLinear(SStreamFillSupporter* pFillSup, SStreamFillInfo* } } else { if (IS_VAR_DATA_TYPE(type) || type == TSDB_DATA_TYPE_BOOL || pCell->isNull) { - colDataAppendNULL(pColData, index); + colDataSetNULL(pColData, index); continue; } double* pDelta = taosArrayGet(pFillInfo->pLinearInfo->pDeltaVal, slotId); @@ -914,7 +912,7 @@ static void doStreamFillLinear(SStreamFillSupporter* pFillSup, SStreamFillInfo* vCell += (*pDelta) * pFillInfo->pLinearInfo->winIndex; int64_t result = 0; SET_TYPED_DATA(&result, pCell->type, vCell); - colDataAppend(pColData, index, (const char*)&result, false); + colDataSetVal(pColData, index, (const char*)&result, false); } } pFillInfo->current = taosTimeAdd(pFillInfo->current, pFillSup->interval.sliding, pFillSup->interval.slidingUnit, @@ -926,6 +924,7 @@ static void doStreamFillLinear(SStreamFillSupporter* pFillSup, SStreamFillInfo* static void keepResultInDiscBuf(SOperatorInfo* pOperator, uint64_t groupId, SResultRowData* pRow, int32_t len) { SWinKey key = {.groupId = groupId, .ts = pRow->key}; int32_t code = streamStateFillPut(pOperator->pTaskInfo->streamInfo.pState, &key, pRow->pRowVal, len); + qDebug("===stream===fill operator save key ts:%" PRId64 " group id:%" PRIu64 " code:%d", key.ts, key.groupId, code); ASSERT(code == TSDB_CODE_SUCCESS); } @@ -1033,23 +1032,23 @@ static void buildDeleteRange(SOperatorInfo* pOp, TSKEY start, TSKEY end, uint64_ SColumnInfoData* pCalStartCol = taosArrayGet(pBlock->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX); SColumnInfoData* pCalEndCol = taosArrayGet(pBlock->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX); SColumnInfoData* pTbNameCol = taosArrayGet(pBlock->pDataBlock, TABLE_NAME_COLUMN_INDEX); - colDataAppend(pStartCol, pBlock->info.rows, (const char*)&start, false); - colDataAppend(pEndCol, pBlock->info.rows, (const char*)&end, false); - colDataAppendNULL(pUidCol, pBlock->info.rows); - colDataAppend(pGroupCol, pBlock->info.rows, (const char*)&groupId, false); - colDataAppendNULL(pCalStartCol, pBlock->info.rows); - colDataAppendNULL(pCalEndCol, pBlock->info.rows); + colDataSetVal(pStartCol, pBlock->info.rows, (const char*)&start, false); + colDataSetVal(pEndCol, pBlock->info.rows, (const char*)&end, false); + colDataSetNULL(pUidCol, pBlock->info.rows); + colDataSetVal(pGroupCol, pBlock->info.rows, (const char*)&groupId, false); + colDataSetNULL(pCalStartCol, pBlock->info.rows); + colDataSetNULL(pCalEndCol, pBlock->info.rows); SColumnInfoData* pTableCol = taosArrayGet(pBlock->pDataBlock, TABLE_NAME_COLUMN_INDEX); void* tbname = NULL; streamStateGetParName(pOp->pTaskInfo->streamInfo.pState, groupId, &tbname); if (tbname == NULL) { - colDataAppendNULL(pTableCol, pBlock->info.rows); + colDataSetNULL(pTableCol, pBlock->info.rows); } else { char parTbName[VARSTR_HEADER_SIZE + TSDB_TABLE_NAME_LEN]; STR_WITH_MAXSIZE_TO_VARSTR(parTbName, tbname, sizeof(parTbName)); - colDataAppend(pTableCol, pBlock->info.rows, (const char*)parTbName, false); + colDataSetVal(pTableCol, pBlock->info.rows, (const char*)parTbName, false); tdbFree(tbname); } diff --git a/source/libs/executor/src/groupoperator.c b/source/libs/executor/src/groupoperator.c index 9fd8f7d3a2..8f5c3786e0 100644 --- a/source/libs/executor/src/groupoperator.c +++ b/source/libs/executor/src/groupoperator.c @@ -204,7 +204,6 @@ static void recordNewGroupKeys(SArray* pGroupCols, SArray* pGroupColVals, SSData } static int32_t buildGroupKeys(void* pKey, const SArray* pGroupColVals) { - ASSERT(pKey != NULL); size_t numOfGroupCols = taosArrayGetSize(pGroupColVals); char* isNull = (char*)pKey; @@ -572,7 +571,6 @@ static void doHashPartition(SOperatorInfo* pOperator, SSDataBlock* pBlock) { } (*columnLen) += contentLen; - ASSERT(*columnLen >= 0); } (*rows) += 1; @@ -683,7 +681,6 @@ static int compareDataGroupInfo(const void* group1, const void* group2) { const SDataGroupInfo* pGroupInfo2 = group2; if (pGroupInfo1->groupId == pGroupInfo2->groupId) { - ASSERT(0); return 0; } @@ -960,7 +957,7 @@ static SSDataBlock* buildStreamPartitionResult(SOperatorInfo* pOperator) { SColumnInfoData* pDestCol = taosArrayGet(pDest->pDataBlock, j); bool isNull = colDataIsNull(pSrcCol, pSrc->info.rows, rowIndex, NULL); char* pSrcData = colDataGetData(pSrcCol, rowIndex); - colDataAppend(pDestCol, pDest->info.rows, pSrcData, isNull); + colDataSetVal(pDestCol, pDest->info.rows, pSrcData, isNull); } pDest->info.rows++; } @@ -992,32 +989,42 @@ void appendCreateTableRow(SStreamState* pState, SExprSupp* pTableSup, SExprSupp* SSDataBlock* pTmpBlock = blockCopyOneRow(pSrcBlock, rowId); memset(pTmpBlock->info.parTbName, 0, TSDB_TABLE_NAME_LEN); pTmpBlock->info.id.groupId = groupId; + char* tbName = pSrcBlock->info.parTbName; if (pTableSup->numOfExprs > 0) { projectApplyFunctions(pTableSup->pExprInfo, pDestBlock, pTmpBlock, pTableSup->pCtx, pTableSup->numOfExprs, NULL); SColumnInfoData* pTbCol = taosArrayGet(pDestBlock->pDataBlock, UD_TABLE_NAME_COLUMN_INDEX); - void* pData = colDataGetVarData(pTbCol, pDestBlock->info.rows - 1); - char* tbName = pSrcBlock->info.parTbName; memset(tbName, 0, TSDB_TABLE_NAME_LEN); - int32_t len = TMIN(varDataLen(pData), TSDB_TABLE_NAME_LEN - 1); - memcpy(tbName, varDataVal(pData), len); + int32_t len = 0; + if (colDataIsNull_s(pTbCol, pDestBlock->info.rows - 1)) { + len = TMIN(sizeof(TSDB_DATA_NULL_STR), TSDB_TABLE_NAME_LEN - 1); + memcpy(tbName, TSDB_DATA_NULL_STR, len); + } else { + void* pData = colDataGetData(pTbCol, pDestBlock->info.rows - 1); + len = TMIN(varDataLen(pData), TSDB_TABLE_NAME_LEN - 1); + memcpy(tbName, varDataVal(pData), len); + } streamStatePutParName(pState, groupId, tbName); memcpy(pTmpBlock->info.parTbName, tbName, len); pDestBlock->info.rows--; } else { void* pTbNameCol = taosArrayGet(pDestBlock->pDataBlock, UD_TABLE_NAME_COLUMN_INDEX); - colDataAppendNULL(pTbNameCol, pDestBlock->info.rows); - pSrcBlock->info.parTbName[0] = 0; + colDataSetNULL(pTbNameCol, pDestBlock->info.rows); + tbName[0] = 0; } if (pTagSup->numOfExprs > 0) { projectApplyFunctions(pTagSup->pExprInfo, pDestBlock, pTmpBlock, pTagSup->pCtx, pTagSup->numOfExprs, NULL); pDestBlock->info.rows--; + } else { + memcpy(pDestBlock->info.parTbName, pTmpBlock->info.parTbName, TSDB_TABLE_NAME_LEN); } void* pGpIdCol = taosArrayGet(pDestBlock->pDataBlock, UD_GROUPID_COLUMN_INDEX); colDataAppend(pGpIdCol, pDestBlock->info.rows, (const char*)&groupId, false); pDestBlock->info.rows++; blockDataDestroy(pTmpBlock); + } else { + memcpy(pSrcBlock->info.parTbName, pValue, TSDB_TABLE_NAME_LEN); } streamStateReleaseBuf(pState, NULL, pValue); } @@ -1110,11 +1117,8 @@ static SSDataBlock* doStreamHashPartition(SOperatorInfo* pOperator) { // there is an scalar expression that needs to be calculated right before apply the group aggregation. if (pInfo->scalarSup.pExprInfo != NULL) { - pTaskInfo->code = projectApplyFunctions(pInfo->scalarSup.pExprInfo, pBlock, pBlock, pInfo->scalarSup.pCtx, + projectApplyFunctions(pInfo->scalarSup.pExprInfo, pBlock, pBlock, pInfo->scalarSup.pCtx, pInfo->scalarSup.numOfExprs, NULL); - if (pTaskInfo->code != TSDB_CODE_SUCCESS) { - longjmp(pTaskInfo->env, pTaskInfo->code); - } } taosHashClear(pInfo->pPartitions); doStreamHashPartitionImpl(pInfo, pBlock); diff --git a/source/libs/executor/src/joinoperator.c b/source/libs/executor/src/joinoperator.c index 88ed9eccb3..31ff11eec5 100644 --- a/source/libs/executor/src/joinoperator.c +++ b/source/libs/executor/src/joinoperator.c @@ -24,6 +24,17 @@ #include "tmsg.h" #include "ttypes.h" +typedef struct SJoinRowCtx { + bool rowRemains; + int64_t ts; + SArray* leftRowLocations; + SArray* rightRowLocations; + SArray* leftCreatedBlocks; + SArray* rightCreatedBlocks; + int32_t leftRowIdx; + int32_t rightRowIdx; +} SJoinRowCtx; + typedef struct SJoinOperatorInfo { SSDataBlock* pRes; int32_t joinType; @@ -37,6 +48,8 @@ typedef struct SJoinOperatorInfo { int32_t rightPos; SColumnInfo rightCol; SNode* pCondAfterMerge; + + SJoinRowCtx rowCtx; } SJoinOperatorInfo; static void setJoinColumnInfo(SColumnInfo* pColumn, const SColumnNode* pColumnNode); @@ -196,10 +209,10 @@ static void mergeJoinJoinLeftRight(struct SOperatorInfo* pOperator, SSDataBlock* } if (colDataIsNull_s(pSrc, rowIndex)) { - colDataAppendNULL(pDst, currRow); + colDataSetNULL(pDst, currRow); } else { char* p = colDataGetData(pSrc, rowIndex); - colDataAppend(pDst, currRow, p, false); + colDataSetVal(pDst, currRow, p, false); } } } @@ -287,49 +300,107 @@ static int32_t mergeJoinGetDownStreamRowsEqualTimeStamp(SOperatorInfo* pOperator static int32_t mergeJoinJoinDownstreamTsRanges(SOperatorInfo* pOperator, int64_t timestamp, SSDataBlock* pRes, int32_t* nRows) { - SJoinOperatorInfo* pJoinInfo = pOperator->info; - SArray* leftRowLocations = taosArrayInit(8, sizeof(SRowLocation)); - SArray* leftCreatedBlocks = taosArrayInit(8, POINTER_BYTES); - - SArray* rightRowLocations = taosArrayInit(8, sizeof(SRowLocation)); - SArray* rightCreatedBlocks = taosArrayInit(8, POINTER_BYTES); int32_t code = TSDB_CODE_SUCCESS; - mergeJoinGetDownStreamRowsEqualTimeStamp(pOperator, 0, pJoinInfo->leftCol.slotId, pJoinInfo->pLeft, - pJoinInfo->leftPos, timestamp, leftRowLocations, leftCreatedBlocks); - mergeJoinGetDownStreamRowsEqualTimeStamp(pOperator, 1, pJoinInfo->rightCol.slotId, pJoinInfo->pRight, - pJoinInfo->rightPos, timestamp, rightRowLocations, rightCreatedBlocks); + SJoinOperatorInfo* pJoinInfo = pOperator->info; + SArray* leftRowLocations = NULL; + SArray* leftCreatedBlocks = NULL; + SArray* rightRowLocations = NULL; + SArray* rightCreatedBlocks = NULL; + int32_t leftRowIdx = 0; + int32_t rightRowIdx = 0; + int32_t i, j; + + if (pJoinInfo->rowCtx.rowRemains) { + leftRowLocations = pJoinInfo->rowCtx.leftRowLocations; + leftCreatedBlocks = pJoinInfo->rowCtx.leftCreatedBlocks; + rightRowLocations = pJoinInfo->rowCtx.rightRowLocations; + rightCreatedBlocks = pJoinInfo->rowCtx.rightCreatedBlocks; + leftRowIdx = pJoinInfo->rowCtx.leftRowIdx; + rightRowIdx = pJoinInfo->rowCtx.rightRowIdx; + } else { + leftRowLocations = taosArrayInit(8, sizeof(SRowLocation)); + leftCreatedBlocks = taosArrayInit(8, POINTER_BYTES); + rightRowLocations = taosArrayInit(8, sizeof(SRowLocation)); + rightCreatedBlocks = taosArrayInit(8, POINTER_BYTES); + + mergeJoinGetDownStreamRowsEqualTimeStamp(pOperator, 0, pJoinInfo->leftCol.slotId, pJoinInfo->pLeft, + pJoinInfo->leftPos, timestamp, leftRowLocations, leftCreatedBlocks); + mergeJoinGetDownStreamRowsEqualTimeStamp(pOperator, 1, pJoinInfo->rightCol.slotId, pJoinInfo->pRight, + pJoinInfo->rightPos, timestamp, rightRowLocations, rightCreatedBlocks); + } + size_t leftNumJoin = taosArrayGetSize(leftRowLocations); size_t rightNumJoin = taosArrayGetSize(rightRowLocations); - code = blockDataEnsureCapacity(pRes, *nRows + leftNumJoin * rightNumJoin); + uint32_t maxRowNum = *nRows + (leftNumJoin - leftRowIdx - 1) * rightNumJoin + rightNumJoin - rightRowIdx; + uint32_t limitRowNum = maxRowNum; + if (maxRowNum > pOperator->resultInfo.threshold) { + limitRowNum = pOperator->resultInfo.threshold; + if (!pJoinInfo->rowCtx.rowRemains) { + pJoinInfo->rowCtx.rowRemains = true; + pJoinInfo->rowCtx.ts = timestamp; + pJoinInfo->rowCtx.leftRowLocations = leftRowLocations; + pJoinInfo->rowCtx.rightRowLocations = rightRowLocations; + pJoinInfo->rowCtx.leftCreatedBlocks = leftCreatedBlocks; + pJoinInfo->rowCtx.rightCreatedBlocks = rightCreatedBlocks; + } + } + + code = blockDataEnsureCapacity(pRes, limitRowNum); if (code != TSDB_CODE_SUCCESS) { qError("%s can not ensure block capacity for join. left: %zu, right: %zu", GET_TASKID(pOperator->pTaskInfo), leftNumJoin, rightNumJoin); } + + if (code == TSDB_CODE_SUCCESS) { - for (int32_t i = 0; i < leftNumJoin; ++i) { - for (int32_t j = 0; j < rightNumJoin; ++j) { + bool done = false; + for (i = leftRowIdx; i < leftNumJoin; ++i, rightRowIdx = 0) { + for (j = rightRowIdx; j < rightNumJoin; ++j) { + if (*nRows >= limitRowNum) { + done = true; + break; + } + SRowLocation* leftRow = taosArrayGet(leftRowLocations, i); SRowLocation* rightRow = taosArrayGet(rightRowLocations, j); mergeJoinJoinLeftRight(pOperator, pRes, *nRows, leftRow->pDataBlock, leftRow->pos, rightRow->pDataBlock, rightRow->pos); ++*nRows; } + if (done) { + break; + } + } + + if (maxRowNum > pOperator->resultInfo.threshold) { + pJoinInfo->rowCtx.leftRowIdx = i; + pJoinInfo->rowCtx.rightRowIdx = j; } } - for (int i = 0; i < taosArrayGetSize(rightCreatedBlocks); ++i) { - SSDataBlock* pBlock = taosArrayGetP(rightCreatedBlocks, i); - blockDataDestroy(pBlock); + if (maxRowNum <= pOperator->resultInfo.threshold) { + for (int i = 0; i < taosArrayGetSize(rightCreatedBlocks); ++i) { + SSDataBlock* pBlock = taosArrayGetP(rightCreatedBlocks, i); + blockDataDestroy(pBlock); + } + taosArrayDestroy(rightCreatedBlocks); + taosArrayDestroy(rightRowLocations); + for (int i = 0; i < taosArrayGetSize(leftCreatedBlocks); ++i) { + SSDataBlock* pBlock = taosArrayGetP(leftCreatedBlocks, i); + blockDataDestroy(pBlock); + } + taosArrayDestroy(leftCreatedBlocks); + taosArrayDestroy(leftRowLocations); + + if (pJoinInfo->rowCtx.rowRemains) { + pJoinInfo->rowCtx.rowRemains = false; + pJoinInfo->rowCtx.leftRowLocations = NULL; + pJoinInfo->rowCtx.rightRowLocations = NULL; + pJoinInfo->rowCtx.leftCreatedBlocks = NULL; + pJoinInfo->rowCtx.rightCreatedBlocks = NULL; + } } - taosArrayDestroy(rightCreatedBlocks); - taosArrayDestroy(rightRowLocations); - for (int i = 0; i < taosArrayGetSize(leftCreatedBlocks); ++i) { - SSDataBlock* pBlock = taosArrayGetP(leftCreatedBlocks, i); - blockDataDestroy(pBlock); - } - taosArrayDestroy(leftCreatedBlocks); - taosArrayDestroy(leftRowLocations); return TSDB_CODE_SUCCESS; } @@ -379,9 +450,14 @@ static void doMergeJoinImpl(struct SOperatorInfo* pOperator, SSDataBlock* pRes) while (1) { int64_t leftTs = 0; int64_t rightTs = 0; - bool hasNextTs = mergeJoinGetNextTimestamp(pOperator, &leftTs, &rightTs); - if (!hasNextTs) { - break; + if (pJoinInfo->rowCtx.rowRemains) { + leftTs = pJoinInfo->rowCtx.ts; + rightTs = pJoinInfo->rowCtx.ts; + } else { + bool hasNextTs = mergeJoinGetNextTimestamp(pOperator, &leftTs, &rightTs); + if (!hasNextTs) { + break; + } } if (leftTs == rightTs) { @@ -389,12 +465,12 @@ static void doMergeJoinImpl(struct SOperatorInfo* pOperator, SSDataBlock* pRes) } else if ((asc && leftTs < rightTs) || (!asc && leftTs > rightTs)) { pJoinInfo->leftPos += 1; - if (pJoinInfo->leftPos >= pJoinInfo->pLeft->info.rows) { + if (pJoinInfo->leftPos >= pJoinInfo->pLeft->info.rows && pRes->info.rows < pOperator->resultInfo.threshold) { continue; } } else if ((asc && leftTs > rightTs) || (!asc && leftTs < rightTs)) { pJoinInfo->rightPos += 1; - if (pJoinInfo->rightPos >= pJoinInfo->pRight->info.rows) { + if (pJoinInfo->rightPos >= pJoinInfo->pRight->info.rows && pRes->info.rows < pOperator->resultInfo.threshold) { continue; } } diff --git a/source/libs/executor/src/projectoperator.c b/source/libs/executor/src/projectoperator.c index 5a221a0fbd..3ae114c656 100644 --- a/source/libs/executor/src/projectoperator.c +++ b/source/libs/executor/src/projectoperator.c @@ -275,7 +275,6 @@ SSDataBlock* doProjectOperation(SOperatorInfo* pOperator) { // for stream interval if (pBlock->info.type == STREAM_RETRIEVE || pBlock->info.type == STREAM_DELETE_RESULT || pBlock->info.type == STREAM_DELETE_DATA || pBlock->info.type == STREAM_CREATE_CHILD_TABLE) { - // printDataBlock1(pBlock, "project1"); return pBlock; } @@ -624,9 +623,9 @@ SSDataBlock* doGenerateSourceData(SOperatorInfo* pOperator) { int32_t type = pExpr[k].base.pParam[0].param.nType; if (TSDB_DATA_TYPE_NULL == type) { - colDataAppendNNULL(pColInfoData, 0, 1); + colDataSetNNULL(pColInfoData, 0, 1); } else { - colDataAppend(pColInfoData, 0, taosVariantGet(&pExpr[k].base.pParam[0].param, type), false); + colDataSetVal(pColInfoData, 0, taosVariantGet(&pExpr[k].base.pParam[0].param, type), false); } } @@ -666,9 +665,9 @@ int32_t projectApplyFunctions(SExprInfo* pExpr, SSDataBlock* pResult, SSDataBloc int32_t type = pExpr[k].base.pParam[0].param.nType; if (TSDB_DATA_TYPE_NULL == type) { - colDataAppendNNULL(pColInfoData, 0, 1); + colDataSetNNULL(pColInfoData, 0, 1); } else { - colDataAppend(pColInfoData, 0, taosVariantGet(&pExpr[k].base.pParam[0].param, type), false); + colDataSetVal(pColInfoData, 0, taosVariantGet(&pExpr[k].base.pParam[0].param, type), false); } } @@ -729,11 +728,11 @@ int32_t projectApplyFunctions(SExprInfo* pExpr, SSDataBlock* pResult, SSDataBloc int32_t type = pExpr[k].base.pParam[0].param.nType; if (TSDB_DATA_TYPE_NULL == type) { - colDataAppendNNULL(pColInfoData, offset, pSrcBlock->info.rows); + colDataSetNNULL(pColInfoData, offset, pSrcBlock->info.rows); } else { char* p = taosVariantGet(&pExpr[k].base.pParam[0].param, type); for (int32_t i = 0; i < pSrcBlock->info.rows; ++i) { - colDataAppend(pColInfoData, i + offset, p, false); + colDataSetVal(pColInfoData, i + offset, p, false); } } @@ -801,10 +800,10 @@ int32_t projectApplyFunctions(SExprInfo* pExpr, SSDataBlock* pResult, SSDataBloc for (int32_t f = 0; f < pSrcBlock->info.rows; ++f) { bool isNull = colDataIsNull_s(pInput, f); if (isNull) { - colDataAppendNULL(pOutput, pResult->info.rows + f); + colDataSetNULL(pOutput, pResult->info.rows + f); } else { char* data = colDataGetData(pInput, f); - colDataAppend(pOutput, pResult->info.rows + f, data, isNull); + colDataSetVal(pOutput, pResult->info.rows + f, data, isNull); } } diff --git a/source/libs/executor/src/scanoperator.c b/source/libs/executor/src/scanoperator.c index 0af9cee2d6..a238b84993 100644 --- a/source/libs/executor/src/scanoperator.c +++ b/source/libs/executor/src/scanoperator.c @@ -267,7 +267,7 @@ bool applyLimitOffset(SLimitInfo* pLimitInfo, SSDataBlock* pBlock, SExecTaskInfo qDebug("current block ignore due to offset, current:%" PRId64 ", %s", pLimitInfo->remainOffset, id); return false; } else { - blockDataTrimFirstNRows(pBlock, pLimitInfo->remainOffset); + blockDataTrimFirstRows(pBlock, pLimitInfo->remainOffset); pLimitInfo->remainOffset = 0; } } @@ -434,7 +434,7 @@ static void freeTableCachedVal(void* param) { static STableCachedVal* createTableCacheVal(const SMetaReader* pMetaReader) { STableCachedVal* pVal = taosMemoryMalloc(sizeof(STableCachedVal)); - pVal->pName = strdup(pMetaReader->me.name); + pVal->pName = taosStrdup(pMetaReader->me.name); pVal->pTags = NULL; // only child table has tag value @@ -455,7 +455,7 @@ static void doSetNullValue(SSDataBlock* pBlock, const SExprInfo* pExpr, int32_t int32_t dstSlotId = pExpr[j].base.resSchema.slotId; SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, dstSlotId); - colDataAppendNNULL(pColInfoData, 0, pBlock->info.rows); + colDataSetNNULL(pColInfoData, 0, pBlock->info.rows); } } @@ -579,15 +579,15 @@ int32_t addTagPseudoColumnData(SReadHandle* pHandle, const SExprInfo* pExpr, int bool isNullVal = (data == NULL) || (pColInfoData->info.type == TSDB_DATA_TYPE_JSON && tTagIsJsonNull(data)); if (isNullVal) { - colDataAppendNNULL(pColInfoData, 0, pBlock->info.rows); + colDataSetNNULL(pColInfoData, 0, pBlock->info.rows); } else if (pColInfoData->info.type != TSDB_DATA_TYPE_JSON) { - colDataAppendNItems(pColInfoData, 0, data, pBlock->info.rows); + colDataSetNItems(pColInfoData, 0, data, pBlock->info.rows); if (IS_VAR_DATA_TYPE(((const STagVal*)p)->type)) { taosMemoryFree(data); } } else { // todo opt for json tag for (int32_t i = 0; i < pBlock->info.rows; ++i) { - colDataAppend(pColInfoData, i, data, false); + colDataSetVal(pColInfoData, i, data, false); } } } @@ -613,7 +613,7 @@ void setTbNameColData(const SSDataBlock* pBlock, SColumnInfoData* pColInfoData, SColumnInfoData infoData = createColumnInfoData(TSDB_DATA_TYPE_VARCHAR, len, 1); colInfoDataEnsureCapacity(&infoData, 1, false); - colDataAppend(&infoData, 0, buf, false); + colDataSetVal(&infoData, 0, buf, false); SScalarParam srcParam = {.numOfRows = pBlock->info.rows, .columnData = &infoData}; SScalarParam param = {.columnData = pColInfoData}; @@ -703,7 +703,8 @@ static SSDataBlock* doGroupedTableScan(SOperatorInfo* pOperator) { if (pTableScanInfo->scanTimes < pTableScanInfo->scanInfo.numOfAsc) { setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED); - pTableScanInfo->base.scanFlag = REPEAT_SCAN; + pTableScanInfo->base.scanFlag = MAIN_SCAN; + pTableScanInfo->base.dataBlockLoadFlag = FUNC_DATA_REQUIRED_DATA_LOAD; qDebug("start to repeat ascending order scan data blocks due to query func required, %s", GET_TASKID(pTaskInfo)); // do prepare for the next round table scan operation @@ -729,7 +730,7 @@ static SSDataBlock* doGroupedTableScan(SOperatorInfo* pOperator) { if (pTableScanInfo->scanTimes < total) { setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED); - pTableScanInfo->base.scanFlag = REPEAT_SCAN; + pTableScanInfo->base.scanFlag = MAIN_SCAN; qDebug("%s start to repeat descending order scan data blocks", GET_TASKID(pTaskInfo)); tsdbReaderReset(pTableScanInfo->base.dataReader, &pTableScanInfo->base.cond); @@ -881,8 +882,8 @@ SOperatorInfo* createTableScanOperatorInfo(STableScanPhysiNode* pTableScanNode, } pInfo->scanInfo = (SScanInfo){.numOfAsc = pTableScanNode->scanSeq[0], .numOfDesc = pTableScanNode->scanSeq[1]}; + pInfo->base.scanFlag = (pInfo->scanInfo.numOfAsc > 1) ? PRE_SCAN : MAIN_SCAN; - pInfo->base.scanFlag = MAIN_SCAN; pInfo->base.pdInfo.interval = extractIntervalInfo(pTableScanNode); pInfo->base.readHandle = *readHandle; pInfo->base.dataBlockLoadFlag = pTableScanNode->dataRequired; @@ -1160,7 +1161,7 @@ static SSDataBlock* doRangeScan(SStreamScanInfo* pInfo, SSDataBlock* pSDB, int32 SColumnInfoData* pDestCol = taosArrayGet(pResult->pDataBlock, j); bool isNull = colDataIsNull(pSrcCol, tmpBlock->info.rows, i, NULL); char* pSrcData = colDataGetData(pSrcCol, i); - colDataAppend(pDestCol, pResult->info.rows, pSrcData, isNull); + colDataSetVal(pDestCol, pResult->info.rows, pSrcData, isNull); } pResult->info.rows++; } @@ -1236,13 +1237,13 @@ static int32_t generateSessionScanRange(SStreamScanInfo* pInfo, SSDataBlock* pSr qError("generate session scan range failed. rang start:%" PRIx64 ", end:%" PRIx64, startData[i], endData[i]); continue; } - colDataAppend(pDestStartCol, i, (const char*)&startWin.win.skey, false); - colDataAppend(pDestEndCol, i, (const char*)&endWin.win.ekey, false); + colDataSetVal(pDestStartCol, i, (const char*)&startWin.win.skey, false); + colDataSetVal(pDestEndCol, i, (const char*)&endWin.win.ekey, false); - colDataAppendNULL(pDestUidCol, i); - colDataAppend(pDestGpCol, i, (const char*)&groupId, false); - colDataAppendNULL(pDestCalStartTsCol, i); - colDataAppendNULL(pDestCalEndTsCol, i); + colDataSetNULL(pDestUidCol, i); + colDataSetVal(pDestGpCol, i, (const char*)&groupId, false); + colDataSetNULL(pDestCalStartTsCol, i); + colDataSetNULL(pDestCalEndTsCol, i); pDestBlock->info.rows++; } return TSDB_CODE_SUCCESS; @@ -1311,15 +1312,15 @@ static int32_t generateIntervalScanRange(SStreamScanInfo* pInfo, SSDataBlock* pS groupId = getGroupIdByData(pInfo, srcUid, srcStartTsCol[i], version); } TSKEY calStartTs = srcStartTsCol[i]; - colDataAppend(pCalStartTsCol, pDestBlock->info.rows, (const char*)(&calStartTs), false); + colDataSetVal(pCalStartTsCol, pDestBlock->info.rows, (const char*)(&calStartTs), false); STimeWindow win = getSlidingWindow(srcStartTsCol, srcEndTsCol, srcGp, &pInfo->interval, &pSrcBlock->info, &i, pInfo->partitionSup.needCalc); TSKEY calEndTs = srcStartTsCol[i - 1]; - colDataAppend(pCalEndTsCol, pDestBlock->info.rows, (const char*)(&calEndTs), false); - colDataAppend(pDeUidCol, pDestBlock->info.rows, (const char*)(&srcUid), false); - colDataAppend(pStartTsCol, pDestBlock->info.rows, (const char*)(&win.skey), false); - colDataAppend(pEndTsCol, pDestBlock->info.rows, (const char*)(&win.ekey), false); - colDataAppend(pGpCol, pDestBlock->info.rows, (const char*)(&groupId), false); + colDataSetVal(pCalEndTsCol, pDestBlock->info.rows, (const char*)(&calEndTs), false); + colDataSetVal(pDeUidCol, pDestBlock->info.rows, (const char*)(&srcUid), false); + colDataSetVal(pStartTsCol, pDestBlock->info.rows, (const char*)(&win.skey), false); + colDataSetVal(pEndTsCol, pDestBlock->info.rows, (const char*)(&win.ekey), false); + colDataSetVal(pGpCol, pDestBlock->info.rows, (const char*)(&groupId), false); pDestBlock->info.rows++; } return TSDB_CODE_SUCCESS; @@ -1434,13 +1435,13 @@ void appendOneRowToStreamSpecialBlock(SSDataBlock* pBlock, TSKEY* pStartTs, TSKE SColumnInfoData* pCalStartCol = taosArrayGet(pBlock->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX); SColumnInfoData* pCalEndCol = taosArrayGet(pBlock->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX); SColumnInfoData* pTableCol = taosArrayGet(pBlock->pDataBlock, TABLE_NAME_COLUMN_INDEX); - colDataAppend(pStartTsCol, pBlock->info.rows, (const char*)pStartTs, false); - colDataAppend(pEndTsCol, pBlock->info.rows, (const char*)pEndTs, false); - colDataAppend(pUidCol, pBlock->info.rows, (const char*)pUid, false); - colDataAppend(pGpCol, pBlock->info.rows, (const char*)pGp, false); - colDataAppend(pCalStartCol, pBlock->info.rows, (const char*)pStartTs, false); - colDataAppend(pCalEndCol, pBlock->info.rows, (const char*)pEndTs, false); - colDataAppend(pTableCol, pBlock->info.rows, (const char*)pTbName, pTbName == NULL); + colDataSetVal(pStartTsCol, pBlock->info.rows, (const char*)pStartTs, false); + colDataSetVal(pEndTsCol, pBlock->info.rows, (const char*)pEndTs, false); + colDataSetVal(pUidCol, pBlock->info.rows, (const char*)pUid, false); + colDataSetVal(pGpCol, pBlock->info.rows, (const char*)pGp, false); + colDataSetVal(pCalStartCol, pBlock->info.rows, (const char*)pStartTs, false); + colDataSetVal(pCalEndCol, pBlock->info.rows, (const char*)pEndTs, false); + colDataSetVal(pTableCol, pBlock->info.rows, (const char*)pTbName, pTbName == NULL); pBlock->info.rows++; } @@ -1527,7 +1528,7 @@ static int32_t setBlockIntoRes(SStreamScanInfo* pInfo, const SSDataBlock* pBlock // the required column does not exists in submit block, let's set it to be all null value if (!colExists) { SColumnInfoData* pDst = taosArrayGet(pInfo->pRes->pDataBlock, pColMatchInfo->dstSlotId); - colDataAppendNNULL(pDst, 0, pBlockInfo->rows); + colDataSetNNULL(pDst, 0, pBlockInfo->rows); } } @@ -1622,7 +1623,6 @@ static SSDataBlock* doQueueScan(SOperatorInfo* pOperator) { tqOffsetResetToLog(&pTaskInfo->streamInfo.lastStatus, pTaskInfo->streamInfo.snapshotVer); return NULL; } - ASSERT(pInfo->tqReader->pWalReader->curVersion == pTaskInfo->streamInfo.snapshotVer + 1); } else { return NULL; } @@ -1695,13 +1695,13 @@ static int32_t filterDelBlockByUid(SSDataBlock* pDst, const SSDataBlock* pSrc, S int32_t j = 0; for (int32_t i = 0; i < rows; i++) { if (taosHashGet(pReader->tbIdHash, &uidCol[i], sizeof(uint64_t))) { - colDataAppend(pDstStartCol, j, (const char*)&startCol[i], false); - colDataAppend(pDstEndCol, j, (const char*)&endCol[i], false); - colDataAppend(pDstUidCol, j, (const char*)&uidCol[i], false); + colDataSetVal(pDstStartCol, j, (const char*)&startCol[i], false); + colDataSetVal(pDstEndCol, j, (const char*)&endCol[i], false); + colDataSetVal(pDstUidCol, j, (const char*)&uidCol[i], false); - colDataAppendNULL(taosArrayGet(pDst->pDataBlock, GROUPID_COLUMN_INDEX), j); - colDataAppendNULL(taosArrayGet(pDst->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX), j); - colDataAppendNULL(taosArrayGet(pDst->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX), j); + colDataSetNULL(taosArrayGet(pDst->pDataBlock, GROUPID_COLUMN_INDEX), j); + colDataSetNULL(taosArrayGet(pDst->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX), j); + colDataSetNULL(taosArrayGet(pDst->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX), j); j++; } } @@ -1725,7 +1725,7 @@ static void setBlockGroupIdByUid(SStreamScanInfo* pInfo, SSDataBlock* pBlock) { if (!pInfo->partitionSup.needCalc) { for (int32_t i = 0; i < rows; i++) { uint64_t groupId = getGroupIdByUid(pInfo, uidCol[i]); - colDataAppend(pGpCol, i, (const char*)&groupId, false); + colDataSetVal(pGpCol, i, (const char*)&groupId, false); } } } @@ -2459,7 +2459,7 @@ static SSDataBlock* doTagScan(SOperatorInfo* pOperator) { // refactor later if (fmIsScanPseudoColumnFunc(pExprInfo[j].pExpr->_function.functionId)) { STR_TO_VARSTR(str, mr.me.name); - colDataAppend(pDst, count, str, false); + colDataSetVal(pDst, count, str, false); } else { // it is a tag value STagVal val = {0}; val.cid = pExprInfo[j].base.pParam[0].pCol->colId; @@ -2471,7 +2471,7 @@ static SSDataBlock* doTagScan(SOperatorInfo* pOperator) { } else { data = (char*)p; } - colDataAppend(pDst, count, data, + colDataSetVal(pDst, count, data, (data == NULL) || (pDst->info.type == TSDB_DATA_TYPE_JSON && tTagIsJsonNull(data))); if (pDst->info.type != TSDB_DATA_TYPE_JSON && p != NULL && IS_VAR_DATA_TYPE(((const STagVal*)p)->type) && @@ -3049,8 +3049,8 @@ int32_t tblCountScanGetInputs(SNodeList* groupTags, SName* tableName, STableCoun } } } else { - strncpy(supp->dbNameFilter, tNameGetDbNameP(tableName), TSDB_DB_NAME_LEN); - strncpy(supp->stbNameFilter, tNameGetTableName(tableName), TSDB_TABLE_NAME_LEN); + tstrncpy(supp->dbNameFilter, tNameGetDbNameP(tableName), TSDB_DB_NAME_LEN); + tstrncpy(supp->stbNameFilter, tNameGetTableName(tableName), TSDB_TABLE_NAME_LEN); } return TSDB_CODE_SUCCESS; } @@ -3128,7 +3128,7 @@ void fillTableCountScanDataBlock(STableCountScanSupp* pSupp, char* dbName, char* tstrncpy(varDataVal(varDbName), dbName, TSDB_DB_NAME_LEN); varDataSetLen(varDbName, strlen(dbName)); - colDataAppend(colInfoData, 0, varDbName, false); + colDataSetVal(colInfoData, 0, varDbName, false); } if (pSupp->stbNameSlotId != -1) { @@ -3137,15 +3137,15 @@ void fillTableCountScanDataBlock(STableCountScanSupp* pSupp, char* dbName, char* char varStbName[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0}; strncpy(varDataVal(varStbName), stbName, TSDB_TABLE_NAME_LEN); varDataSetLen(varStbName, strlen(stbName)); - colDataAppend(colInfoData, 0, varStbName, false); + colDataSetVal(colInfoData, 0, varStbName, false); } else { - colDataAppendNULL(colInfoData, 0); + colDataSetNULL(colInfoData, 0); } } if (pSupp->tbCountSlotId != -1) { SColumnInfoData* colInfoData = taosArrayGet(pRes->pDataBlock, pSupp->tbCountSlotId); - colDataAppend(colInfoData, 0, (char*)&count, false); + colDataSetVal(colInfoData, 0, (char*)&count, false); } pRes->info.rows = 1; } diff --git a/source/libs/executor/src/sortoperator.c b/source/libs/executor/src/sortoperator.c index 98ef6b8a36..90c7fa10ca 100644 --- a/source/libs/executor/src/sortoperator.c +++ b/source/libs/executor/src/sortoperator.c @@ -46,8 +46,9 @@ SOperatorInfo* createSortOperatorInfo(SOperatorInfo* downstream, SSortPhysiNode* pOperator->pTaskInfo = pTaskInfo; SDataBlockDescNode* pDescNode = pSortNode->node.pOutputDataBlockDesc; - int32_t numOfCols = 0; - SExprInfo* pExprInfo = createExprInfo(pSortNode->pExprs, NULL, &numOfCols); + int32_t numOfCols = 0; + pOperator->exprSupp.pExprInfo = createExprInfo(pSortNode->pExprs, NULL, &numOfCols); + pOperator->exprSupp.numOfExprs = numOfCols; int32_t numOfOutputCols = 0; int32_t code = @@ -56,7 +57,8 @@ SOperatorInfo* createSortOperatorInfo(SOperatorInfo* downstream, SSortPhysiNode* goto _error; } - pOperator->exprSupp.pCtx = createSqlFunctionCtx(pExprInfo, numOfCols, &pOperator->exprSupp.rowEntryInfoOffset); + pOperator->exprSupp.pCtx = + createSqlFunctionCtx(pOperator->exprSupp.pExprInfo, numOfCols, &pOperator->exprSupp.rowEntryInfoOffset); initResultSizeInfo(&pOperator->resultInfo, 1024); code = filterInitFromNode((SNode*)pSortNode->node.pConditions, &pOperator->exprSupp.pFilterInfo, 0); if (code != TSDB_CODE_SUCCESS) { @@ -68,8 +70,7 @@ SOperatorInfo* createSortOperatorInfo(SOperatorInfo* downstream, SSortPhysiNode* initLimitInfo(pSortNode->node.pLimit, pSortNode->node.pSlimit, &pInfo->limitInfo); setOperatorInfo(pOperator, "SortOperator", QUERY_NODE_PHYSICAL_PLAN_SORT, true, OP_NOT_OPENED, pInfo, pTaskInfo); - pOperator->exprSupp.pExprInfo = pExprInfo; - pOperator->exprSupp.numOfExprs = numOfCols; + // lazy evaluation for the following parameter since the input datablock is not known till now. // pInfo->bufPageSize = rowSize < 1024 ? 1024 * 2 : rowSize * 2; @@ -101,11 +102,11 @@ void appendOneRowToDataBlock(SSDataBlock* pBlock, STupleHandle* pTupleHandle) { SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, i); bool isNull = tsortIsNullVal(pTupleHandle, i); if (isNull) { - colDataAppendNULL(pColInfo, pBlock->info.rows); + colDataSetNULL(pColInfo, pBlock->info.rows); } else { char* pData = tsortGetValue(pTupleHandle, i); if (pData != NULL) { - colDataAppend(pColInfo, pBlock->info.rows, pData, false); + colDataSetVal(pColInfo, pBlock->info.rows, pData, false); } } } @@ -671,7 +672,9 @@ SSDataBlock* getMultiwaySortedBlockData(SSortHandle* pHandle, SSDataBlock* pData } bool limitReached = applyLimitOffset(&pInfo->limitInfo, p, pTaskInfo); - if (limitReached) { + // if limit is reached within a group, do not clear limiInfo otherwise the next block + // will be processed. + if (newgroup && limitReached) { resetLimitInfoForNextGroup(&pInfo->limitInfo); } @@ -768,8 +771,6 @@ SOperatorInfo* createMultiwayMergeOperatorInfo(SOperatorInfo** downStreams, size pInfo->binfo.pRes = createDataBlockFromDescNode(pDescNode); int32_t rowSize = pInfo->binfo.pRes->info.rowSize; - ASSERT(rowSize < 100 * 1024 * 1024); - int32_t numOfOutputCols = 0; code = extractColMatchInfo(pMergePhyNode->pTargets, pDescNode, &numOfOutputCols, COL_MATCH_FROM_SLOT_ID, &pInfo->matchInfo); diff --git a/source/libs/executor/src/sysscanoperator.c b/source/libs/executor/src/sysscanoperator.c index 1b2f135064..24f42ff178 100644 --- a/source/libs/executor/src/sysscanoperator.c +++ b/source/libs/executor/src/sysscanoperator.c @@ -133,7 +133,6 @@ static int32_t buildSysDbTableInfo(const SSysTableScanInfo* pInfo, int32_ static SSDataBlock* buildInfoSchemaTableMetaBlock(char* tableName); static void destroySysScanOperator(void* param); static int32_t loadSysTableCallback(void* param, SDataBuf* pMsg, int32_t code); -static SSDataBlock* doFilterResult(SSDataBlock* pDataBlock, SFilterInfo* pFilterInfo); static __optSysFilter optSysGetFilterFunc(int32_t ctype, bool* reverse, bool* equal); static int32_t sysTableUserTagsFillOneTableTags(const SSysTableScanInfo* pInfo, SMetaReader* smrSuperTable, @@ -838,21 +837,21 @@ static int32_t sysTableUserTagsFillOneTableTags(const SSysTableScanInfo* pInfo, // table name pColInfoData = taosArrayGet(dataBlock->pDataBlock, 0); - colDataAppend(pColInfoData, numOfRows, tableName, false); + colDataSetVal(pColInfoData, numOfRows, tableName, false); // database name pColInfoData = taosArrayGet(dataBlock->pDataBlock, 1); - colDataAppend(pColInfoData, numOfRows, dbname, false); + colDataSetVal(pColInfoData, numOfRows, dbname, false); // super table name pColInfoData = taosArrayGet(dataBlock->pDataBlock, 2); - colDataAppend(pColInfoData, numOfRows, stableName, false); + colDataSetVal(pColInfoData, numOfRows, stableName, false); // tag name char tagName[TSDB_COL_NAME_LEN + VARSTR_HEADER_SIZE] = {0}; STR_TO_VARSTR(tagName, (*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].name); pColInfoData = taosArrayGet(dataBlock->pDataBlock, 3); - colDataAppend(pColInfoData, numOfRows, tagName, false); + colDataSetVal(pColInfoData, numOfRows, tagName, false); // tag type int8_t tagType = (*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].type; @@ -868,7 +867,7 @@ static int32_t sysTableUserTagsFillOneTableTags(const SSysTableScanInfo* pInfo, (int32_t)(((*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].bytes - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE)); } varDataSetLen(tagTypeStr, tagTypeLen); - colDataAppend(pColInfoData, numOfRows, (char*)tagTypeStr, false); + colDataSetVal(pColInfoData, numOfRows, (char*)tagTypeStr, false); STagVal tagVal = {0}; tagVal.cid = (*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].colId; @@ -908,7 +907,7 @@ static int32_t sysTableUserTagsFillOneTableTags(const SSysTableScanInfo* pInfo, } } pColInfoData = taosArrayGet(dataBlock->pDataBlock, 5); - colDataAppend(pColInfoData, numOfRows, tagVarChar, + colDataSetVal(pColInfoData, numOfRows, tagVarChar, (tagData == NULL) || (tagType == TSDB_DATA_TYPE_JSON && tTagIsJsonNull(tagData))); taosMemoryFree(tagVarChar); ++numOfRows; @@ -969,7 +968,7 @@ static int32_t sysTableUserColsFillOneTableCols(const SSysTableScanInfo* pInfo, for (int32_t j = 6; j <= 8; ++j) { pColInfoData = taosArrayGet(dataBlock->pDataBlock, j); - colDataAppendNULL(pColInfoData, numOfRows); + colDataSetNULL(pColInfoData, numOfRows); } ++numOfRows; } @@ -1016,30 +1015,30 @@ int32_t buildDbTableInfoBlock(bool sysInfo, const SSDataBlock* p, const SSysTabl SColumnInfoData* pColInfoData = taosArrayGet(p->pDataBlock, 0); STR_TO_VARSTR(n, pm->name); - colDataAppend(pColInfoData, numOfRows, n, false); + colDataSetVal(pColInfoData, numOfRows, n, false); // database name STR_TO_VARSTR(n, dbName); pColInfoData = taosArrayGet(p->pDataBlock, 1); - colDataAppend(pColInfoData, numOfRows, n, false); + colDataSetVal(pColInfoData, numOfRows, n, false); // create time pColInfoData = taosArrayGet(p->pDataBlock, 2); - colDataAppendNULL(pColInfoData, numOfRows); + colDataSetNULL(pColInfoData, numOfRows); // number of columns pColInfoData = taosArrayGet(p->pDataBlock, 3); - colDataAppend(pColInfoData, numOfRows, (char*)&pm->colNum, false); + colDataSetVal(pColInfoData, numOfRows, (char*)&pm->colNum, false); for (int32_t j = 4; j <= 8; ++j) { pColInfoData = taosArrayGet(p->pDataBlock, j); - colDataAppendNULL(pColInfoData, numOfRows); + colDataSetNULL(pColInfoData, numOfRows); } STR_TO_VARSTR(n, "SYSTEM_TABLE"); pColInfoData = taosArrayGet(p->pDataBlock, 9); - colDataAppend(pColInfoData, numOfRows, n, false); + colDataSetVal(pColInfoData, numOfRows, n, false); numOfRows += 1; } @@ -1107,22 +1106,22 @@ static SSDataBlock* sysTableBuildUserTablesByUids(SOperatorInfo* pOperator) { // table name SColumnInfoData* pColInfoData = taosArrayGet(p->pDataBlock, 0); - colDataAppend(pColInfoData, numOfRows, n, false); + colDataSetVal(pColInfoData, numOfRows, n, false); // database name pColInfoData = taosArrayGet(p->pDataBlock, 1); - colDataAppend(pColInfoData, numOfRows, dbname, false); + colDataSetVal(pColInfoData, numOfRows, dbname, false); // vgId pColInfoData = taosArrayGet(p->pDataBlock, 6); - colDataAppend(pColInfoData, numOfRows, (char*)&vgId, false); + colDataSetVal(pColInfoData, numOfRows, (char*)&vgId, false); int32_t tableType = mr.me.type; if (tableType == TSDB_CHILD_TABLE) { // create time int64_t ts = mr.me.ctbEntry.ctime; pColInfoData = taosArrayGet(p->pDataBlock, 2); - colDataAppend(pColInfoData, numOfRows, (char*)&ts, false); + colDataSetVal(pColInfoData, numOfRows, (char*)&ts, false); SMetaReader mr1 = {0}; metaReaderInit(&mr1, pInfo->readHandle.meta, META_READER_NOLOCK); @@ -1137,12 +1136,12 @@ static SSDataBlock* sysTableBuildUserTablesByUids(SOperatorInfo* pOperator) { T_LONG_JMP(pTaskInfo->env, terrno); } pColInfoData = taosArrayGet(p->pDataBlock, 3); - colDataAppend(pColInfoData, numOfRows, (char*)&mr1.me.stbEntry.schemaRow.nCols, false); + colDataSetVal(pColInfoData, numOfRows, (char*)&mr1.me.stbEntry.schemaRow.nCols, false); // super table name STR_TO_VARSTR(n, mr1.me.name); pColInfoData = taosArrayGet(p->pDataBlock, 4); - colDataAppend(pColInfoData, numOfRows, n, false); + colDataSetVal(pColInfoData, numOfRows, n, false); metaReaderClear(&mr1); // table comment @@ -1150,59 +1149,59 @@ static SSDataBlock* sysTableBuildUserTablesByUids(SOperatorInfo* pOperator) { if (mr.me.ctbEntry.commentLen > 0) { char comment[TSDB_TB_COMMENT_LEN + VARSTR_HEADER_SIZE] = {0}; STR_TO_VARSTR(comment, mr.me.ctbEntry.comment); - colDataAppend(pColInfoData, numOfRows, comment, false); + colDataSetVal(pColInfoData, numOfRows, comment, false); } else if (mr.me.ctbEntry.commentLen == 0) { char comment[VARSTR_HEADER_SIZE + VARSTR_HEADER_SIZE] = {0}; STR_TO_VARSTR(comment, ""); - colDataAppend(pColInfoData, numOfRows, comment, false); + colDataSetVal(pColInfoData, numOfRows, comment, false); } else { - colDataAppendNULL(pColInfoData, numOfRows); + colDataSetNULL(pColInfoData, numOfRows); } // uid pColInfoData = taosArrayGet(p->pDataBlock, 5); - colDataAppend(pColInfoData, numOfRows, (char*)&mr.me.uid, false); + colDataSetVal(pColInfoData, numOfRows, (char*)&mr.me.uid, false); // ttl pColInfoData = taosArrayGet(p->pDataBlock, 7); - colDataAppend(pColInfoData, numOfRows, (char*)&mr.me.ctbEntry.ttlDays, false); + colDataSetVal(pColInfoData, numOfRows, (char*)&mr.me.ctbEntry.ttlDays, false); STR_TO_VARSTR(n, "CHILD_TABLE"); } else if (tableType == TSDB_NORMAL_TABLE) { // create time pColInfoData = taosArrayGet(p->pDataBlock, 2); - colDataAppend(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.ntbEntry.ctime, false); + colDataSetVal(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.ntbEntry.ctime, false); // number of columns pColInfoData = taosArrayGet(p->pDataBlock, 3); - colDataAppend(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.ntbEntry.schemaRow.nCols, false); + colDataSetVal(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.ntbEntry.schemaRow.nCols, false); // super table name pColInfoData = taosArrayGet(p->pDataBlock, 4); - colDataAppendNULL(pColInfoData, numOfRows); + colDataSetNULL(pColInfoData, numOfRows); // table comment pColInfoData = taosArrayGet(p->pDataBlock, 8); if (mr.me.ntbEntry.commentLen > 0) { char comment[TSDB_TB_COMMENT_LEN + VARSTR_HEADER_SIZE] = {0}; STR_TO_VARSTR(comment, mr.me.ntbEntry.comment); - colDataAppend(pColInfoData, numOfRows, comment, false); + colDataSetVal(pColInfoData, numOfRows, comment, false); } else if (mr.me.ntbEntry.commentLen == 0) { char comment[VARSTR_HEADER_SIZE + VARSTR_HEADER_SIZE] = {0}; STR_TO_VARSTR(comment, ""); - colDataAppend(pColInfoData, numOfRows, comment, false); + colDataSetVal(pColInfoData, numOfRows, comment, false); } else { - colDataAppendNULL(pColInfoData, numOfRows); + colDataSetNULL(pColInfoData, numOfRows); } // uid pColInfoData = taosArrayGet(p->pDataBlock, 5); - colDataAppend(pColInfoData, numOfRows, (char*)&mr.me.uid, false); + colDataSetVal(pColInfoData, numOfRows, (char*)&mr.me.uid, false); // ttl pColInfoData = taosArrayGet(p->pDataBlock, 7); - colDataAppend(pColInfoData, numOfRows, (char*)&mr.me.ntbEntry.ttlDays, false); + colDataSetVal(pColInfoData, numOfRows, (char*)&mr.me.ntbEntry.ttlDays, false); STR_TO_VARSTR(n, "NORMAL_TABLE"); // impl later @@ -1211,7 +1210,7 @@ static SSDataBlock* sysTableBuildUserTablesByUids(SOperatorInfo* pOperator) { metaReaderClear(&mr); pColInfoData = taosArrayGet(p->pDataBlock, 9); - colDataAppend(pColInfoData, numOfRows, n, false); + colDataSetVal(pColInfoData, numOfRows, n, false); if (++numOfRows >= pOperator->resultInfo.capacity) { p->info.rows = numOfRows; @@ -1285,22 +1284,22 @@ static SSDataBlock* sysTableBuildUserTables(SOperatorInfo* pOperator) { // table name SColumnInfoData* pColInfoData = taosArrayGet(p->pDataBlock, 0); - colDataAppend(pColInfoData, numOfRows, n, false); + colDataSetVal(pColInfoData, numOfRows, n, false); // database name pColInfoData = taosArrayGet(p->pDataBlock, 1); - colDataAppend(pColInfoData, numOfRows, dbname, false); + colDataSetVal(pColInfoData, numOfRows, dbname, false); // vgId pColInfoData = taosArrayGet(p->pDataBlock, 6); - colDataAppend(pColInfoData, numOfRows, (char*)&vgId, false); + colDataSetVal(pColInfoData, numOfRows, (char*)&vgId, false); int32_t tableType = pInfo->pCur->mr.me.type; if (tableType == TSDB_CHILD_TABLE) { // create time int64_t ts = pInfo->pCur->mr.me.ctbEntry.ctime; pColInfoData = taosArrayGet(p->pDataBlock, 2); - colDataAppend(pColInfoData, numOfRows, (char*)&ts, false); + colDataSetVal(pColInfoData, numOfRows, (char*)&ts, false); SMetaReader mr = {0}; metaReaderInit(&mr, pInfo->readHandle.meta, META_READER_NOLOCK); @@ -1318,12 +1317,12 @@ static SSDataBlock* sysTableBuildUserTables(SOperatorInfo* pOperator) { // number of columns pColInfoData = taosArrayGet(p->pDataBlock, 3); - colDataAppend(pColInfoData, numOfRows, (char*)&mr.me.stbEntry.schemaRow.nCols, false); + colDataSetVal(pColInfoData, numOfRows, (char*)&mr.me.stbEntry.schemaRow.nCols, false); // super table name STR_TO_VARSTR(n, mr.me.name); pColInfoData = taosArrayGet(p->pDataBlock, 4); - colDataAppend(pColInfoData, numOfRows, n, false); + colDataSetVal(pColInfoData, numOfRows, n, false); metaReaderClear(&mr); // table comment @@ -1331,64 +1330,64 @@ static SSDataBlock* sysTableBuildUserTables(SOperatorInfo* pOperator) { if (pInfo->pCur->mr.me.ctbEntry.commentLen > 0) { char comment[TSDB_TB_COMMENT_LEN + VARSTR_HEADER_SIZE] = {0}; STR_TO_VARSTR(comment, pInfo->pCur->mr.me.ctbEntry.comment); - colDataAppend(pColInfoData, numOfRows, comment, false); + colDataSetVal(pColInfoData, numOfRows, comment, false); } else if (pInfo->pCur->mr.me.ctbEntry.commentLen == 0) { char comment[VARSTR_HEADER_SIZE + VARSTR_HEADER_SIZE] = {0}; STR_TO_VARSTR(comment, ""); - colDataAppend(pColInfoData, numOfRows, comment, false); + colDataSetVal(pColInfoData, numOfRows, comment, false); } else { - colDataAppendNULL(pColInfoData, numOfRows); + colDataSetNULL(pColInfoData, numOfRows); } // uid pColInfoData = taosArrayGet(p->pDataBlock, 5); - colDataAppend(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.uid, false); + colDataSetVal(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.uid, false); // ttl pColInfoData = taosArrayGet(p->pDataBlock, 7); - colDataAppend(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.ctbEntry.ttlDays, false); + colDataSetVal(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.ctbEntry.ttlDays, false); STR_TO_VARSTR(n, "CHILD_TABLE"); } else if (tableType == TSDB_NORMAL_TABLE) { // create time pColInfoData = taosArrayGet(p->pDataBlock, 2); - colDataAppend(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.ntbEntry.ctime, false); + colDataSetVal(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.ntbEntry.ctime, false); // number of columns pColInfoData = taosArrayGet(p->pDataBlock, 3); - colDataAppend(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.ntbEntry.schemaRow.nCols, false); + colDataSetVal(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.ntbEntry.schemaRow.nCols, false); // super table name pColInfoData = taosArrayGet(p->pDataBlock, 4); - colDataAppendNULL(pColInfoData, numOfRows); + colDataSetNULL(pColInfoData, numOfRows); // table comment pColInfoData = taosArrayGet(p->pDataBlock, 8); if (pInfo->pCur->mr.me.ntbEntry.commentLen > 0) { char comment[TSDB_TB_COMMENT_LEN + VARSTR_HEADER_SIZE] = {0}; STR_TO_VARSTR(comment, pInfo->pCur->mr.me.ntbEntry.comment); - colDataAppend(pColInfoData, numOfRows, comment, false); + colDataSetVal(pColInfoData, numOfRows, comment, false); } else if (pInfo->pCur->mr.me.ntbEntry.commentLen == 0) { char comment[VARSTR_HEADER_SIZE + VARSTR_HEADER_SIZE] = {0}; STR_TO_VARSTR(comment, ""); - colDataAppend(pColInfoData, numOfRows, comment, false); + colDataSetVal(pColInfoData, numOfRows, comment, false); } else { - colDataAppendNULL(pColInfoData, numOfRows); + colDataSetNULL(pColInfoData, numOfRows); } // uid pColInfoData = taosArrayGet(p->pDataBlock, 5); - colDataAppend(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.uid, false); + colDataSetVal(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.uid, false); // ttl pColInfoData = taosArrayGet(p->pDataBlock, 7); - colDataAppend(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.ntbEntry.ttlDays, false); + colDataSetVal(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.ntbEntry.ttlDays, false); STR_TO_VARSTR(n, "NORMAL_TABLE"); } pColInfoData = taosArrayGet(p->pDataBlock, 9); - colDataAppend(pColInfoData, numOfRows, n, false); + colDataSetVal(pColInfoData, numOfRows, n, false); if (++numOfRows >= pOperator->resultInfo.capacity) { p->info.rows = numOfRows; @@ -1608,10 +1607,9 @@ static void sysTableScanFillTbName(SOperatorInfo* pOperator, const SSysTableScan if (pInfo->tbnameSlotId != -1) { SColumnInfoData* pColumnInfoData = (SColumnInfoData*)taosArrayGet(pBlock->pDataBlock, pInfo->tbnameSlotId); char varTbName[TSDB_TABLE_FNAME_LEN - 1 + VARSTR_HEADER_SIZE] = {0}; - memcpy(varDataVal(varTbName), name, strlen(name)); - varDataSetLen(varTbName, strlen(name)); + STR_TO_VARSTR(varTbName, name); - colDataAppendNItems(pColumnInfoData, 0, varTbName, pBlock->info.rows); + colDataSetNItems(pColumnInfoData, 0, varTbName, pBlock->info.rows); } doFilter(pBlock, pOperator->exprSupp.pFilterInfo, NULL); @@ -1711,7 +1709,7 @@ SOperatorInfo* createSysTableScanOperatorInfo(void* readHandle, SSystemTableScan extractTbnameSlotId(pInfo, pScanNode); pInfo->accountId = pScanPhyNode->accountId; - pInfo->pUser = taosMemoryStrDup((void*)pUser); + pInfo->pUser = taosStrdup((void*)pUser); pInfo->sysInfo = pScanPhyNode->sysInfo; pInfo->showRewrite = pScanPhyNode->showRewrite; pInfo->pRes = createDataBlockFromDescNode(pDescNode); @@ -2174,14 +2172,14 @@ static SSDataBlock* doBlockInfoScan(SOperatorInfo* pOperator) { tSerializeBlockDistInfo(varDataVal(p), len, &blockDistInfo); varDataSetLen(p, len); - colDataAppend(pColInfo, 0, p, false); + colDataSetVal(pColInfo, 0, p, false); taosMemoryFree(p); // make the valgrind happy that all memory buffer has been initialized already. if (slotId != 0) { SColumnInfoData* p1 = taosArrayGet(pBlock->pDataBlock, 0); int64_t v = 0; - colDataAppendInt64(p1, 0, &v); + colDataSetInt64(p1, 0, &v); } pBlock->info.rows = 1; @@ -2254,7 +2252,7 @@ SOperatorInfo* createDataBlockInfoScanOperator(SReadHandle* readHandle, SBlockDi } pInfo->readHandle = *readHandle; - pInfo->uid = (pBlockScanNode->suid != 0)? pBlockScanNode->suid:pBlockScanNode->uid; + pInfo->uid = (pBlockScanNode->suid != 0) ? pBlockScanNode->suid : pBlockScanNode->uid; int32_t numOfCols = 0; SExprInfo* pExprInfo = createExprInfo(pBlockScanNode->pScanPseudoCols, NULL, &numOfCols); diff --git a/source/libs/executor/src/tfill.c b/source/libs/executor/src/tfill.c index 778281f9b4..f4c8521b94 100644 --- a/source/libs/executor/src/tfill.c +++ b/source/libs/executor/src/tfill.c @@ -60,7 +60,7 @@ static void setNullRow(SSDataBlock* pBlock, SFillInfo* pFillInfo, int32_t rowInd setNotFillColumn(pFillInfo, pDstColInfo, rowIndex, i); } } else { - colDataAppendNULL(pDstColInfo, rowIndex); + colDataSetNULL(pDstColInfo, rowIndex); } } } @@ -69,19 +69,19 @@ static void doSetUserSpecifiedValue(SColumnInfoData* pDst, SVariant* pVar, int32 if (pDst->info.type == TSDB_DATA_TYPE_FLOAT) { float v = 0; GET_TYPED_DATA(v, float, pVar->nType, &pVar->i); - colDataAppend(pDst, rowIndex, (char*)&v, false); + colDataSetVal(pDst, rowIndex, (char*)&v, false); } else if (pDst->info.type == TSDB_DATA_TYPE_DOUBLE) { double v = 0; GET_TYPED_DATA(v, double, pVar->nType, &pVar->i); - colDataAppend(pDst, rowIndex, (char*)&v, false); + colDataSetVal(pDst, rowIndex, (char*)&v, false); } else if (IS_SIGNED_NUMERIC_TYPE(pDst->info.type)) { int64_t v = 0; GET_TYPED_DATA(v, int64_t, pVar->nType, &pVar->i); - colDataAppend(pDst, rowIndex, (char*)&v, false); + colDataSetVal(pDst, rowIndex, (char*)&v, false); } else if (pDst->info.type == TSDB_DATA_TYPE_TIMESTAMP) { - colDataAppend(pDst, rowIndex, (const char*)¤tKey, false); + colDataSetVal(pDst, rowIndex, (const char*)¤tKey, false); } else { // varchar/nchar data - colDataAppendNULL(pDst, rowIndex); + colDataSetNULL(pDst, rowIndex); } } @@ -96,18 +96,18 @@ bool fillIfWindowPseudoColumn(SFillInfo* pFillInfo, SFillColInfo* pCol, SColumnI return false; } if (pCol->pExpr->base.pParam[0].pCol->colType == COLUMN_TYPE_WINDOW_START) { - colDataAppend(pDstColInfoData, rowIndex, (const char*)&pFillInfo->currentKey, false); + colDataSetVal(pDstColInfoData, rowIndex, (const char*)&pFillInfo->currentKey, false); return true; } else if (pCol->pExpr->base.pParam[0].pCol->colType == COLUMN_TYPE_WINDOW_END) { // TODO: include endpoint SInterval* pInterval = &pFillInfo->interval; int64_t windowEnd = taosTimeAdd(pFillInfo->currentKey, pInterval->interval, pInterval->intervalUnit, pInterval->precision); - colDataAppend(pDstColInfoData, rowIndex, (const char*)&windowEnd, false); + colDataSetVal(pDstColInfoData, rowIndex, (const char*)&windowEnd, false); return true; } else if (pCol->pExpr->base.pParam[0].pCol->colType == COLUMN_TYPE_WINDOW_DURATION) { // TODO: include endpoint - colDataAppend(pDstColInfoData, rowIndex, (const char*)&pFillInfo->interval.sliding, false); + colDataSetVal(pDstColInfoData, rowIndex, (const char*)&pFillInfo->interval.sliding, false); return true; } } @@ -163,7 +163,7 @@ static void doFillOneRow(SFillInfo* pFillInfo, SSDataBlock* pBlock, SSDataBlock* } else { SGroupKeys* pKey = taosArrayGet(pFillInfo->prev.pRowVal, i); if (IS_VAR_DATA_TYPE(type) || type == TSDB_DATA_TYPE_BOOL || pKey->isNull) { - colDataAppendNULL(pDstCol, index); + colDataSetNULL(pDstCol, index); continue; } @@ -182,7 +182,7 @@ static void doFillOneRow(SFillInfo* pFillInfo, SSDataBlock* pBlock, SSDataBlock* point = (SPoint){.key = pFillInfo->currentKey, .val = &out}; taosGetLinearInterpolationVal(&point, type, &point1, &point2, type); - colDataAppend(pDstCol, index, (const char*)&out, false); + colDataSetVal(pDstCol, index, (const char*)&out, false); } } } @@ -217,9 +217,9 @@ static void doFillOneRow(SFillInfo* pFillInfo, SSDataBlock* pBlock, SSDataBlock* void doSetVal(SColumnInfoData* pDstCol, int32_t rowIndex, const SGroupKeys* pKey) { if (pKey->isNull) { - colDataAppendNULL(pDstCol, rowIndex); + colDataSetNULL(pDstCol, rowIndex); } else { - colDataAppend(pDstCol, rowIndex, pKey->pData, false); + colDataSetVal(pDstCol, rowIndex, pKey->pData, false); } } @@ -332,14 +332,14 @@ static int32_t fillResultImpl(SFillInfo* pFillInfo, SSDataBlock* pBlock, int32_t char* src = colDataGetData(pSrc, pFillInfo->index); if (!colDataIsNull_s(pSrc, pFillInfo->index)) { - colDataAppend(pDst, index, src, false); + colDataSetVal(pDst, index, src, false); saveColData(pFillInfo->prev.pRowVal, i, src, false); if (pFillInfo->srcTsSlotId == dstSlotId) { pFillInfo->prev.key = *(int64_t*)src; } } else { // the value is null if (pDst->info.type == TSDB_DATA_TYPE_TIMESTAMP) { - colDataAppend(pDst, index, (const char*)&pFillInfo->currentKey, false); + colDataSetVal(pDst, index, (const char*)&pFillInfo->currentKey, false); } else { // i > 0 and data is null , do interpolation if (pFillInfo->type == TSDB_FILL_PREV) { SArray* p = FILL_IS_ASC_FILL(pFillInfo) ? pFillInfo->prev.pRowVal : pFillInfo->next.pRowVal; @@ -347,10 +347,10 @@ static int32_t fillResultImpl(SFillInfo* pFillInfo, SSDataBlock* pBlock, int32_t doSetVal(pDst, index, pKey); } else if (pFillInfo->type == TSDB_FILL_LINEAR) { bool isNull = colDataIsNull_s(pSrc, pFillInfo->index); - colDataAppend(pDst, index, src, isNull); + colDataSetVal(pDst, index, src, isNull); saveColData(pFillInfo->prev.pRowVal, i, src, isNull); // todo: } else if (pFillInfo->type == TSDB_FILL_NULL || pFillInfo->type == TSDB_FILL_NULL_F) { - colDataAppendNULL(pDst, index); + colDataSetNULL(pDst, index); } else if (pFillInfo->type == TSDB_FILL_NEXT) { SArray* p = FILL_IS_ASC_FILL(pFillInfo) ? pFillInfo->next.pRowVal : pFillInfo->prev.pRowVal; SGroupKeys* pKey = taosArrayGet(p, i); diff --git a/source/libs/executor/src/timesliceoperator.c b/source/libs/executor/src/timesliceoperator.c index bce8443353..911700be85 100644 --- a/source/libs/executor/src/timesliceoperator.c +++ b/source/libs/executor/src/timesliceoperator.c @@ -91,7 +91,6 @@ static void doKeepLinearInfo(STimeSliceOperatorInfo* pSliceInfo, const SSDataBlo SColumnInfoData* pTsCol = taosArrayGet(pBlock->pDataBlock, pSliceInfo->tsCol.slotId); SFillLinearInfo* pLinearInfo = taosArrayGet(pSliceInfo->pLinearInfo, i); - if (!IS_MATHABLE_TYPE(pColInfoData->info.type)) { continue; } @@ -100,7 +99,6 @@ static void doKeepLinearInfo(STimeSliceOperatorInfo* pSliceInfo, const SSDataBlo // TODO: optimize to ignore null values for linear interpolation. if (!pLinearInfo->isStartSet) { if (!colDataIsNull_s(pColInfoData, rowIndex)) { - pLinearInfo->start.key = *(int64_t*)colDataGetData(pTsCol, rowIndex); char* p = colDataGetData(pColInfoData, rowIndex); if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) { @@ -144,10 +142,8 @@ static void doKeepLinearInfo(STimeSliceOperatorInfo* pSliceInfo, const SSDataBlo } } } - } - static FORCE_INLINE int32_t timeSliceEnsureBlockCapacity(STimeSliceOperatorInfo* pSliceInfo, SSDataBlock* pBlock) { if (pBlock->info.rows < pBlock->info.capacity) { return TSDB_CODE_SUCCESS; @@ -160,8 +156,8 @@ static FORCE_INLINE int32_t timeSliceEnsureBlockCapacity(STimeSliceOperatorInfo* return TSDB_CODE_SUCCESS; } - -static bool genInterpolationResult(STimeSliceOperatorInfo* pSliceInfo, SExprSupp* pExprSup, SSDataBlock* pResBlock, bool beforeTs) { +static bool genInterpolationResult(STimeSliceOperatorInfo* pSliceInfo, SExprSupp* pExprSup, SSDataBlock* pResBlock, + bool beforeTs) { int32_t rows = pResBlock->info.rows; timeSliceEnsureBlockCapacity(pSliceInfo, pResBlock); // todo set the correct primary timestamp column @@ -175,7 +171,7 @@ static bool genInterpolationResult(STimeSliceOperatorInfo* pSliceInfo, SExprSupp SColumnInfoData* pDst = taosArrayGet(pResBlock->pDataBlock, dstSlot); if (IS_TIMESTAMP_TYPE(pExprInfo->base.resSchema.type)) { - colDataAppend(pDst, rows, (char*)&pSliceInfo->current, false); + colDataSetVal(pDst, rows, (char*)&pSliceInfo->current, false); continue; } else if (IS_BOOLEAN_TYPE(pExprInfo->base.resSchema.type)) { bool isFilled = true; @@ -187,7 +183,7 @@ static bool genInterpolationResult(STimeSliceOperatorInfo* pSliceInfo, SExprSupp switch (pSliceInfo->fillType) { case TSDB_FILL_NULL: case TSDB_FILL_NULL_F: { - colDataAppendNULL(pDst, rows); + colDataSetNULL(pDst, rows); break; } @@ -198,15 +194,15 @@ static bool genInterpolationResult(STimeSliceOperatorInfo* pSliceInfo, SExprSupp if (pDst->info.type == TSDB_DATA_TYPE_FLOAT) { float v = 0; GET_TYPED_DATA(v, float, pVar->nType, &pVar->i); - colDataAppend(pDst, rows, (char*)&v, false); + colDataSetVal(pDst, rows, (char*)&v, false); } else if (pDst->info.type == TSDB_DATA_TYPE_DOUBLE) { double v = 0; GET_TYPED_DATA(v, double, pVar->nType, &pVar->i); - colDataAppend(pDst, rows, (char*)&v, false); + colDataSetVal(pDst, rows, (char*)&v, false); } else if (IS_SIGNED_NUMERIC_TYPE(pDst->info.type)) { int64_t v = 0; GET_TYPED_DATA(v, int64_t, pVar->nType, &pVar->i); - colDataAppend(pDst, rows, (char*)&v, false); + colDataSetVal(pDst, rows, (char*)&v, false); } break; } @@ -229,13 +225,13 @@ static bool genInterpolationResult(STimeSliceOperatorInfo* pSliceInfo, SExprSupp } if (start.key == INT64_MIN || end.key == INT64_MIN) { - colDataAppendNULL(pDst, rows); + colDataSetNULL(pDst, rows); break; } current.val = taosMemoryCalloc(pLinearInfo->bytes, 1); taosGetLinearInterpolationVal(¤t, pLinearInfo->type, &start, &end, pLinearInfo->type); - colDataAppend(pDst, rows, (char*)current.val, false); + colDataSetVal(pDst, rows, (char*)current.val, false); taosMemoryFree(current.val); break; @@ -248,9 +244,9 @@ static bool genInterpolationResult(STimeSliceOperatorInfo* pSliceInfo, SExprSupp SGroupKeys* pkey = taosArrayGet(pSliceInfo->pPrevRow, srcSlot); if (pkey->isNull == false) { - colDataAppend(pDst, rows, pkey->pData, false); + colDataSetVal(pDst, rows, pkey->pData, false); } else { - colDataAppendNULL(pDst, rows); + colDataSetNULL(pDst, rows); } break; } @@ -263,9 +259,9 @@ static bool genInterpolationResult(STimeSliceOperatorInfo* pSliceInfo, SExprSupp SGroupKeys* pkey = taosArrayGet(pSliceInfo->pNextRow, srcSlot); if (pkey->isNull == false) { - colDataAppend(pDst, rows, pkey->pData, false); + colDataSetVal(pDst, rows, pkey->pData, false); } else { - colDataAppendNULL(pDst, rows); + colDataSetNULL(pDst, rows); } break; } @@ -293,21 +289,21 @@ static void addCurrentRowToResult(STimeSliceOperatorInfo* pSliceInfo, SExprSupp* SColumnInfoData* pDst = taosArrayGet(pResBlock->pDataBlock, dstSlot); if (IS_TIMESTAMP_TYPE(pExprInfo->base.resSchema.type)) { - colDataAppend(pDst, pResBlock->info.rows, (char*)&pSliceInfo->current, false); + colDataSetVal(pDst, pResBlock->info.rows, (char*)&pSliceInfo->current, false); } else if (IS_BOOLEAN_TYPE(pExprInfo->base.resSchema.type)) { bool isFilled = false; - colDataAppend(pDst, pResBlock->info.rows, (char*)&isFilled, false); + colDataSetVal(pDst, pResBlock->info.rows, (char*)&isFilled, false); } else { int32_t srcSlot = pExprInfo->base.pParam[0].pCol->slotId; SColumnInfoData* pSrc = taosArrayGet(pSrcBlock->pDataBlock, srcSlot); if (colDataIsNull_s(pSrc, index)) { - colDataAppendNULL(pDst, pResBlock->info.rows); + colDataSetNULL(pDst, pResBlock->info.rows); continue; } char* v = colDataGetData(pSrc, index); - colDataAppend(pDst, pResBlock->info.rows, v, false); + colDataSetVal(pDst, pResBlock->info.rows, v, false); } } @@ -315,7 +311,6 @@ static void addCurrentRowToResult(STimeSliceOperatorInfo* pSliceInfo, SExprSupp* return; } - static int32_t initPrevRowsKeeper(STimeSliceOperatorInfo* pInfo, SSDataBlock* pBlock) { if (pInfo->pPrevRow != NULL) { return TSDB_CODE_SUCCESS; @@ -487,11 +482,12 @@ static SSDataBlock* doTimeslice(SOperatorInfo* pOperator) { int64_t nextTs = *(int64_t*)colDataGetData(pTsCol, i + 1); if (nextTs > pSliceInfo->current) { while (pSliceInfo->current < nextTs && pSliceInfo->current <= pSliceInfo->win.ekey) { - if (!genInterpolationResult(pSliceInfo, &pOperator->exprSupp, pResBlock, false) && pSliceInfo->fillType == TSDB_FILL_LINEAR) { + if (!genInterpolationResult(pSliceInfo, &pOperator->exprSupp, pResBlock, false) && + pSliceInfo->fillType == TSDB_FILL_LINEAR) { break; } else { - pSliceInfo->current = - taosTimeAdd(pSliceInfo->current, pInterval->interval, pInterval->intervalUnit, pInterval->precision); + pSliceInfo->current = taosTimeAdd(pSliceInfo->current, pInterval->interval, pInterval->intervalUnit, + pInterval->precision); } } @@ -511,7 +507,8 @@ static SSDataBlock* doTimeslice(SOperatorInfo* pOperator) { doKeepLinearInfo(pSliceInfo, pBlock, i); while (pSliceInfo->current < ts && pSliceInfo->current <= pSliceInfo->win.ekey) { - if (!genInterpolationResult(pSliceInfo, &pOperator->exprSupp, pResBlock, true) && pSliceInfo->fillType == TSDB_FILL_LINEAR) { + if (!genInterpolationResult(pSliceInfo, &pOperator->exprSupp, pResBlock, true) && + pSliceInfo->fillType == TSDB_FILL_LINEAR) { break; } else { pSliceInfo->current = @@ -606,14 +603,15 @@ SOperatorInfo* createTimeSliceOperatorInfo(SOperatorInfo* downstream, SPhysiNode setOperatorInfo(pOperator, "TimeSliceOperator", QUERY_NODE_PHYSICAL_PLAN_INTERP_FUNC, false, OP_NOT_OPENED, pInfo, pTaskInfo); - pOperator->fpSet = createOperatorFpSet(optrDummyOpenFn, doTimeslice, NULL, destroyTimeSliceOperatorInfo, optrDefaultBufFn, NULL); + pOperator->fpSet = + createOperatorFpSet(optrDummyOpenFn, doTimeslice, NULL, destroyTimeSliceOperatorInfo, optrDefaultBufFn, NULL); blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity); code = appendDownstream(pOperator, &downstream, 1); return pOperator; - _error: +_error: taosMemoryFree(pInfo); taosMemoryFree(pOperator); pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY; diff --git a/source/libs/executor/src/timewindowoperator.c b/source/libs/executor/src/timewindowoperator.c index d379b9dfeb..20d4f46eaf 100644 --- a/source/libs/executor/src/timewindowoperator.c +++ b/source/libs/executor/src/timewindowoperator.c @@ -1502,16 +1502,16 @@ static void deleteIntervalDiscBuf(SStreamState* pState, SHashObj* pPullDataMap, code = streamStateGetKVByCur(pCur, &tmpKey, NULL, 0); if (code == TSDB_CODE_SUCCESS) { STimeWindow tw = getFinalTimeWindow(tmpKey.ts, pInterval); - qDebug("===stream===error stream state first key:%" PRId64 "-%" PRId64 ",%" PRId64 ",mark %" PRId64, tw.skey, + qDebug("===stream===error stream state first key:%" PRId64 "-%" PRId64 ",%" PRIu64 ",mark %" PRId64, tw.skey, tw.ekey, tmpKey.groupId, mark); } else { STimeWindow tw = getFinalTimeWindow(key->ts, pInterval); - qDebug("===stream===stream state first key:%" PRId64 "-%" PRId64 ",%" PRId64 ",mark %" PRId64, tw.skey, tw.ekey, + qDebug("===stream===stream state first key:%" PRId64 "-%" PRId64 ",%" PRIu64 ",mark %" PRId64, tw.skey, tw.ekey, key->groupId, mark); } } else { STimeWindow tw = getFinalTimeWindow(key->ts, pInterval); - qDebug("===stream===stream state first key:%" PRId64 "-%" PRId64 ",%" PRId64 ",mark %" PRId64, tw.skey, tw.ekey, + qDebug("===stream===stream state first key:%" PRId64 "-%" PRId64 ",%" PRIu64 ",mark %" PRId64, tw.skey, tw.ekey, key->groupId, mark); } streamStateFreeCur(pCur); @@ -2237,11 +2237,11 @@ static void doBuildPullDataBlock(SArray* array, int32_t* pIndex, SSDataBlock* pB SColumnInfoData* pCalEndTs = (SColumnInfoData*)taosArrayGet(pBlock->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX); for (; (*pIndex) < size; (*pIndex)++) { SPullWindowInfo* pWin = taosArrayGet(array, (*pIndex)); - colDataAppend(pStartTs, pBlock->info.rows, (const char*)&pWin->window.skey, false); - colDataAppend(pEndTs, pBlock->info.rows, (const char*)&pWin->window.ekey, false); - colDataAppend(pGroupId, pBlock->info.rows, (const char*)&pWin->groupId, false); - colDataAppend(pCalStartTs, pBlock->info.rows, (const char*)&pWin->calWin.skey, false); - colDataAppend(pCalEndTs, pBlock->info.rows, (const char*)&pWin->calWin.ekey, false); + colDataSetVal(pStartTs, pBlock->info.rows, (const char*)&pWin->window.skey, false); + colDataSetVal(pEndTs, pBlock->info.rows, (const char*)&pWin->window.ekey, false); + colDataSetVal(pGroupId, pBlock->info.rows, (const char*)&pWin->groupId, false); + colDataSetVal(pCalStartTs, pBlock->info.rows, (const char*)&pWin->calWin.skey, false); + colDataSetVal(pCalEndTs, pBlock->info.rows, (const char*)&pWin->calWin.ekey, false); pBlock->info.rows++; } if ((*pIndex) == size) { @@ -3244,28 +3244,28 @@ void doBuildDeleteDataBlock(SOperatorInfo* pOp, SSHashObj* pStDeleted, SSDataBlo } SSessionKey* res = tSimpleHashGetKey(*Ite, NULL); SColumnInfoData* pStartTsCol = taosArrayGet(pBlock->pDataBlock, START_TS_COLUMN_INDEX); - colDataAppend(pStartTsCol, pBlock->info.rows, (const char*)&res->win.skey, false); + colDataSetVal(pStartTsCol, pBlock->info.rows, (const char*)&res->win.skey, false); SColumnInfoData* pEndTsCol = taosArrayGet(pBlock->pDataBlock, END_TS_COLUMN_INDEX); - colDataAppend(pEndTsCol, pBlock->info.rows, (const char*)&res->win.skey, false); + colDataSetVal(pEndTsCol, pBlock->info.rows, (const char*)&res->win.skey, false); SColumnInfoData* pUidCol = taosArrayGet(pBlock->pDataBlock, UID_COLUMN_INDEX); - colDataAppendNULL(pUidCol, pBlock->info.rows); + colDataSetNULL(pUidCol, pBlock->info.rows); SColumnInfoData* pGpCol = taosArrayGet(pBlock->pDataBlock, GROUPID_COLUMN_INDEX); - colDataAppend(pGpCol, pBlock->info.rows, (const char*)&res->groupId, false); + colDataSetVal(pGpCol, pBlock->info.rows, (const char*)&res->groupId, false); SColumnInfoData* pCalStCol = taosArrayGet(pBlock->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX); - colDataAppendNULL(pCalStCol, pBlock->info.rows); + colDataSetNULL(pCalStCol, pBlock->info.rows); SColumnInfoData* pCalEdCol = taosArrayGet(pBlock->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX); - colDataAppendNULL(pCalEdCol, pBlock->info.rows); + colDataSetNULL(pCalEdCol, pBlock->info.rows); SColumnInfoData* pTableCol = taosArrayGet(pBlock->pDataBlock, TABLE_NAME_COLUMN_INDEX); void* tbname = NULL; streamStateGetParName(pOp->pTaskInfo->streamInfo.pState, res->groupId, &tbname); if (tbname == NULL) { - colDataAppendNULL(pTableCol, pBlock->info.rows); + colDataSetNULL(pTableCol, pBlock->info.rows); } else { char parTbName[VARSTR_HEADER_SIZE + TSDB_TABLE_NAME_LEN]; STR_WITH_MAXSIZE_TO_VARSTR(parTbName, tbname, sizeof(parTbName)); - colDataAppend(pTableCol, pBlock->info.rows, (const char*)parTbName, false); + colDataSetVal(pTableCol, pBlock->info.rows, (const char*)parTbName, false); tdbFree(tbname); } pBlock->info.rows += 1; diff --git a/source/libs/executor/src/tsort.c b/source/libs/executor/src/tsort.c index 90f20f40b8..6d734901ab 100644 --- a/source/libs/executor/src/tsort.c +++ b/source/libs/executor/src/tsort.c @@ -90,7 +90,7 @@ SSortHandle* tsortCreateSortHandle(SArray* pSortInfo, int32_t type, int32_t page tsortSetComparFp(pSortHandle, msortComparFn); if (idstr != NULL) { - pSortHandle->idStr = strdup(idstr); + pSortHandle->idStr = taosStrdup(idstr); } return pSortHandle; @@ -212,7 +212,9 @@ static int32_t doAddToBuf(SSDataBlock* pDataBlock, SSortHandle* pHandle) { int32_t pageId = -1; void* pPage = getNewBufPage(pHandle->pBuf, &pageId); if (pPage == NULL) { + taosArrayDestroy(pPageIdList); blockDataDestroy(p); + taosArrayDestroy(pPageIdList); return terrno; } @@ -320,10 +322,10 @@ static void appendOneRowToDataBlock(SSDataBlock* pBlock, const SSDataBlock* pSou bool isNull = colDataIsNull(pSrcColInfo, pSource->info.rows, *rowIndex, NULL); if (isNull) { - colDataAppend(pColInfo, pBlock->info.rows, NULL, true); + colDataSetVal(pColInfo, pBlock->info.rows, NULL, true); } else { char* pData = colDataGetData(pSrcColInfo, *rowIndex); - colDataAppend(pColInfo, pBlock->info.rows, pData, false); + colDataSetVal(pColInfo, pBlock->info.rows, pData, false); } } diff --git a/source/libs/executor/test/executorTests.cpp b/source/libs/executor/test/executorTests.cpp index 913aae6cc3..b9a696170a 100644 --- a/source/libs/executor/test/executorTests.cpp +++ b/source/libs/executor/test/executorTests.cpp @@ -110,13 +110,13 @@ SSDataBlock* getDummyBlock(SOperatorInfo* pOperator) { v = taosRand(); } - colDataAppend(pColInfo, i, reinterpret_cast(&v), false); + colDataSetVal(pColInfo, i, reinterpret_cast(&v), false); // sprintf(buf, "this is %d row", i); // STR_TO_VARSTR(b1, buf); // // SColumnInfoData* pColInfo2 = static_cast(TARRAY_GET_ELEM(pBlock->pDataBlock, 1)); - // colDataAppend(pColInfo2, i, b1, false); + // colDataSetVal(pColInfo2, i, b1, false); } pBlock->info.rows = pInfo->numOfRowsPerPage; @@ -155,7 +155,7 @@ SSDataBlock* get2ColsDummyBlock(SOperatorInfo* pOperator) { SColumnInfoData* pColInfo = static_cast(TARRAY_GET_ELEM(pBlock->pDataBlock, 0)); ts = (++pInfo->tsStart); - colDataAppend(pColInfo, i, reinterpret_cast(&ts), false); + colDataSetVal(pColInfo, i, reinterpret_cast(&ts), false); SColumnInfoData* pColInfo1 = static_cast(TARRAY_GET_ELEM(pBlock->pDataBlock, 1)); if (pInfo->type == data_desc) { @@ -166,13 +166,13 @@ SSDataBlock* get2ColsDummyBlock(SOperatorInfo* pOperator) { v = taosRand(); } - colDataAppend(pColInfo1, i, reinterpret_cast(&v), false); + colDataSetVal(pColInfo1, i, reinterpret_cast(&v), false); // sprintf(buf, "this is %d row", i); // STR_TO_VARSTR(b1, buf); // // SColumnInfoData* pColInfo2 = static_cast(TARRAY_GET_ELEM(pBlock->pDataBlock, 1)); - // colDataAppend(pColInfo2, i, b1, false); + // colDataSetVal(pColInfo2, i, b1, false); } pBlock->info.rows = pInfo->numOfRowsPerPage; diff --git a/source/libs/executor/test/sortTests.cpp b/source/libs/executor/test/sortTests.cpp index 62813453a1..f35d07804e 100644 --- a/source/libs/executor/test/sortTests.cpp +++ b/source/libs/executor/test/sortTests.cpp @@ -91,7 +91,7 @@ SSDataBlock* getSingleColDummyBlock(void* param) { return NULL; } varDataSetLen(str, len); - colDataAppend(pColInfo, i, reinterpret_cast(str), false); + colDataSetVal(pColInfo, i, reinterpret_cast(str), false); pBlock->info.hasVarCol = true; printf("nchar: %s\n", strOri); } else if (pInfo->type == TSDB_DATA_TYPE_BINARY) { @@ -99,12 +99,12 @@ SSDataBlock* getSingleColDummyBlock(void* param) { char str[64] = {0}; taosRandStr(varDataVal(str), size); varDataSetLen(str, size); - colDataAppend(pColInfo, i, reinterpret_cast(str), false); + colDataSetVal(pColInfo, i, reinterpret_cast(str), false); pBlock->info.hasVarCol = true; printf("binary: %s\n", varDataVal(str)); } else if (pInfo->type == TSDB_DATA_TYPE_DOUBLE || pInfo->type == TSDB_DATA_TYPE_FLOAT) { double v = rand_f2(); - colDataAppend(pColInfo, i, reinterpret_cast(&v), false); + colDataSetVal(pColInfo, i, reinterpret_cast(&v), false); printf("float: %f\n", v); } else { int64_t v = ++pInfo->startVal; @@ -115,7 +115,7 @@ SSDataBlock* getSingleColDummyBlock(void* param) { memcpy(result, (char*)(&v) + sizeof(int64_t) - tDataTypes[pInfo->type].bytes, tDataTypes[pInfo->type].bytes); } - colDataAppend(pColInfo, i, result, false); + colDataSetVal(pColInfo, i, result, false); printf("int: %" PRId64 "\n", v); taosMemoryFree(result); } diff --git a/source/libs/function/src/builtins.c b/source/libs/function/src/builtins.c index 1a0437c26a..0257b3d5e6 100644 --- a/source/libs/function/src/builtins.c +++ b/source/libs/function/src/builtins.c @@ -504,27 +504,45 @@ static int32_t translateTimezone(SFunctionNode* pFunc, char* pErrBuf, int32_t le } static int32_t translatePercentile(SFunctionNode* pFunc, char* pErrBuf, int32_t len) { - if (2 != LIST_LENGTH(pFunc->pParameterList)) { + int32_t numOfParams = LIST_LENGTH(pFunc->pParameterList); + if (numOfParams < 2 || numOfParams > 11) { return invaildFuncParaNumErrMsg(pErrBuf, len, pFunc->functionName); } - // param1 - SValueNode* pValue = (SValueNode*)nodesListGetNode(pFunc->pParameterList, 1); - - if (pValue->datum.i < 0 || pValue->datum.i > 100) { - return invaildFuncParaValueErrMsg(pErrBuf, len, pFunc->functionName); - } - - pValue->notReserved = true; uint8_t para1Type = ((SExprNode*)nodesListGetNode(pFunc->pParameterList, 0))->resType.type; - uint8_t para2Type = ((SExprNode*)nodesListGetNode(pFunc->pParameterList, 1))->resType.type; - if (!IS_NUMERIC_TYPE(para1Type) || (!IS_SIGNED_NUMERIC_TYPE(para2Type) && !IS_UNSIGNED_NUMERIC_TYPE(para2Type))) { + if (!IS_NUMERIC_TYPE(para1Type)) { return invaildFuncParaTypeErrMsg(pErrBuf, len, pFunc->functionName); } + + for (int32_t i = 1; i < numOfParams; ++i) { + SValueNode* pValue = (SValueNode*)nodesListGetNode(pFunc->pParameterList, i); + pValue->notReserved = true; + + uint8_t paraType = ((SExprNode*)nodesListGetNode(pFunc->pParameterList, i))->resType.type; + if (!IS_NUMERIC_TYPE(paraType)) { + return invaildFuncParaTypeErrMsg(pErrBuf, len, pFunc->functionName); + } + + double v = 0; + if (IS_INTEGER_TYPE(paraType)) { + v = (double)pValue->datum.i; + } else { + v = pValue->datum.d; + } + + if (v < 0 || v > 100) { + return invaildFuncParaValueErrMsg(pErrBuf, len, pFunc->functionName); + } + } + // set result type - pFunc->node.resType = (SDataType){.bytes = tDataTypes[TSDB_DATA_TYPE_DOUBLE].bytes, .type = TSDB_DATA_TYPE_DOUBLE}; + if (numOfParams > 2) { + pFunc->node.resType = (SDataType){.bytes = 512, .type = TSDB_DATA_TYPE_VARCHAR}; + } else { + pFunc->node.resType = (SDataType){.bytes = tDataTypes[TSDB_DATA_TYPE_DOUBLE].bytes, .type = TSDB_DATA_TYPE_DOUBLE}; + } return TSDB_CODE_SUCCESS; } @@ -2273,8 +2291,9 @@ const SBuiltinFuncDefinition funcMgtBuiltins[] = { { .name = "percentile", .type = FUNCTION_TYPE_PERCENTILE, - .classification = FUNC_MGT_AGG_FUNC | FUNC_MGT_REPEAT_SCAN_FUNC | FUNC_MGT_FORBID_STREAM_FUNC, + .classification = FUNC_MGT_AGG_FUNC | FUNC_MGT_REPEAT_SCAN_FUNC | FUNC_MGT_SPECIAL_DATA_REQUIRED | FUNC_MGT_FORBID_STREAM_FUNC, .translateFunc = translatePercentile, + .dataRequiredFunc = statisDataRequired, .getEnvFunc = getPercentileFuncEnv, .initFunc = percentileFunctionSetup, .processFunc = percentileFunction, diff --git a/source/libs/function/src/builtinsimpl.c b/source/libs/function/src/builtinsimpl.c index 100f90f1db..9986af1691 100644 --- a/source/libs/function/src/builtinsimpl.c +++ b/source/libs/function/src/builtinsimpl.c @@ -446,7 +446,7 @@ int32_t functionFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0; char* in = GET_ROWCELL_INTERBUF(pResInfo); - colDataAppend(pCol, pBlock->info.rows, in, pResInfo->isNullRes); + colDataSetVal(pCol, pBlock->info.rows, in, pResInfo->isNullRes); return pResInfo->numOfRes; } @@ -476,7 +476,7 @@ int32_t functionFinalizeWithResultBuf(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0; char* in = finalResult; - colDataAppend(pCol, pBlock->info.rows, in, pResInfo->isNullRes); + colDataSetVal(pCol, pBlock->info.rows, in, pResInfo->isNullRes); return pResInfo->numOfRes; } @@ -775,13 +775,13 @@ int32_t maxFunction(SqlFunctionCtx* pCtx) { static int32_t setNullSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t rowIndex); static int32_t setSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, const STuplePos* pTuplePos, - int32_t rowIndex); + int32_t rowIndex); int32_t minmaxFunctionFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { int32_t code = TSDB_CODE_SUCCESS; SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx); - SMinmaxResInfo* pRes = GET_ROWCELL_INTERBUF(pEntryInfo); + SMinmaxResInfo* pRes = GET_ROWCELL_INTERBUF(pEntryInfo); int32_t slotId = pCtx->pExpr->base.resSchema.slotId; int32_t currentRow = pBlock->info.rows; @@ -795,32 +795,31 @@ int32_t minmaxFunctionFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { case TSDB_DATA_TYPE_UBIGINT: case TSDB_DATA_TYPE_BIGINT: ((int64_t*)pCol->pData)[currentRow] = pRes->v; -// colDataAppendInt64(pCol, currentRow, &pRes->v); break; case TSDB_DATA_TYPE_UINT: case TSDB_DATA_TYPE_INT: - colDataAppendInt32(pCol, currentRow, (int32_t*)&pRes->v); + colDataSetInt32(pCol, currentRow, (int32_t*)&pRes->v); break; case TSDB_DATA_TYPE_USMALLINT: case TSDB_DATA_TYPE_SMALLINT: - colDataAppendInt16(pCol, currentRow, (int16_t*)&pRes->v); + colDataSetInt16(pCol, currentRow, (int16_t*)&pRes->v); break; case TSDB_DATA_TYPE_BOOL: case TSDB_DATA_TYPE_UTINYINT: case TSDB_DATA_TYPE_TINYINT: - colDataAppendInt8(pCol, currentRow, (int8_t*)&pRes->v); + colDataSetInt8(pCol, currentRow, (int8_t*)&pRes->v); break; case TSDB_DATA_TYPE_DOUBLE: - colDataAppendDouble(pCol, currentRow, (double*)&pRes->v); + colDataSetDouble(pCol, currentRow, (double*)&pRes->v); break; case TSDB_DATA_TYPE_FLOAT: { float v = GET_FLOAT_VAL(&pRes->v); - colDataAppendFloat(pCol, currentRow, &v); + colDataSetFloat(pCol, currentRow, &v); break; } } } else { - colDataAppendNULL(pCol, currentRow); + colDataSetNULL(pCol, currentRow); } if (pCtx->subsidiaries.num > 0) { @@ -844,7 +843,7 @@ int32_t setNullSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32 int32_t dstSlotId = pc->pExpr->base.resSchema.slotId; SColumnInfoData* pDstCol = taosArrayGet(pBlock->pDataBlock, dstSlotId); - colDataAppendNULL(pDstCol, rowIndex); + colDataSetNULL(pDstCol, rowIndex); } return TSDB_CODE_SUCCESS; @@ -874,9 +873,9 @@ int32_t setSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, const STu SColumnInfoData* pDstCol = taosArrayGet(pBlock->pDataBlock, dstSlotId); if (nullList[j]) { - colDataAppendNULL(pDstCol, rowIndex); + colDataSetNULL(pDstCol, rowIndex); } else { - colDataAppend(pDstCol, rowIndex, pStart, false); + colDataSetVal(pDstCol, rowIndex, pStart, false); } pStart += pDstCol->info.bytes; } @@ -913,16 +912,14 @@ void appendSelectivityValue(SqlFunctionCtx* pCtx, int32_t rowIndex, int32_t pos) SColumnInfoData* pDstCol = taosArrayGet(pCtx->pDstBlock->pDataBlock, dstSlotId); if (colDataIsNull_s(pSrcCol, rowIndex) == true) { - colDataAppendNULL(pDstCol, pos); + colDataSetNULL(pDstCol, pos); } else { - colDataAppend(pDstCol, pos, pData, false); + colDataSetVal(pDstCol, pos, pData, false); } } } -void replaceTupleData(STuplePos* pDestPos, STuplePos* pSourcePos) { - *pDestPos = *pSourcePos; -} +void replaceTupleData(STuplePos* pDestPos, STuplePos* pSourcePos) { *pDestPos = *pSourcePos; } int32_t minMaxCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx, int32_t isMinFunc) { SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx); @@ -1301,7 +1298,7 @@ int32_t stddevPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { int32_t slotId = pCtx->pExpr->base.resSchema.slotId; SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId); - colDataAppend(pCol, pBlock->info.rows, res, false); + colDataSetVal(pCol, pBlock->info.rows, res, false); taosMemoryFree(res); return pResInfo->numOfRes; @@ -1508,7 +1505,7 @@ int32_t leastSQRFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { int32_t currentRow = pBlock->info.rows; if (0 == pInfo->num) { - colDataAppendNULL(pCol, currentRow); + colDataSetNULL(pCol, currentRow); return 0; } @@ -1521,7 +1518,7 @@ int32_t leastSQRFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { double param02 = param[0][2] - param[1][2] * (param[0][1] / param[1][1]); if (0 == param00) { - colDataAppendNULL(pCol, currentRow); + colDataSetNULL(pCol, currentRow); return 0; } @@ -1537,7 +1534,7 @@ int32_t leastSQRFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { snprintf(varDataVal(buf), sizeof(buf) - VARSTR_HEADER_SIZE, "{slop:%.6lf, intercept:%.6lf}", param02, param12); varDataSetLen(buf, len); - colDataAppend(pCol, currentRow, buf, pResInfo->isNullRes); + colDataSetVal(pCol, currentRow, buf, pResInfo->isNullRes); return pResInfo->numOfRes; } @@ -1599,7 +1596,7 @@ int32_t percentileFunction(SqlFunctionCtx* pCtx) { int32_t type = pCol->info.type; SPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo); - if (pCtx->scanFlag == REPEAT_SCAN && pInfo->stage == 0) { + if (pCtx->scanFlag == MAIN_SCAN && pInfo->stage == 0) { pInfo->stage += 1; // all data are null, set it completed @@ -1682,26 +1679,63 @@ int32_t percentileFunction(SqlFunctionCtx* pCtx) { } int32_t percentileFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { - SVariant* pVal = &pCtx->param[1].param; - int32_t code = 0; - double v = 0; - - GET_TYPED_DATA(v, double, pVal->nType, &pVal->i); - SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx); SPercentileInfo* ppInfo = (SPercentileInfo*)GET_ROWCELL_INTERBUF(pResInfo); + int32_t code = 0; + double v = 0; + tMemBucket* pMemBucket = ppInfo->pMemBucket; if (pMemBucket != NULL && pMemBucket->total > 0) { // check for null - code = getPercentile(pMemBucket, v, &ppInfo->result); + if (pCtx->numOfParams > 2) { + char buf[512] = {0}; + size_t len = 1; + + varDataVal(buf)[0] = '['; + for (int32_t i = 1; i < pCtx->numOfParams; ++i) { + SVariant* pVal = &pCtx->param[i].param; + + GET_TYPED_DATA(v, double, pVal->nType, &pVal->i); + + int32_t code = getPercentile(pMemBucket, v, &ppInfo->result); + if (code != TSDB_CODE_SUCCESS) { + goto _fin_error; + } + + if (i == pCtx->numOfParams - 1) { + len += snprintf(varDataVal(buf) + len, sizeof(buf) - VARSTR_HEADER_SIZE - len, "%.6lf]", ppInfo->result); + } else { + len += snprintf(varDataVal(buf) + len, sizeof(buf) - VARSTR_HEADER_SIZE - len, "%.6lf, ", ppInfo->result); + } + } + + int32_t slotId = pCtx->pExpr->base.resSchema.slotId; + SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId); + + varDataSetLen(buf, len); + colDataAppend(pCol, pBlock->info.rows, buf, false); + + tMemBucketDestroy(pMemBucket); + return pResInfo->numOfRes; + } else { + SVariant* pVal = &pCtx->param[1].param; + + GET_TYPED_DATA(v, double, pVal->nType, &pVal->i); + + code = getPercentile(pMemBucket, v, &ppInfo->result); + if (code != TSDB_CODE_SUCCESS) { + goto _fin_error; + } + + tMemBucketDestroy(pMemBucket); + return functionFinalize(pCtx, pBlock); + } } +_fin_error: + tMemBucketDestroy(pMemBucket); - if (code != TSDB_CODE_SUCCESS) { - return code; - } - - return functionFinalize(pCtx, pBlock); + return code; } bool getApercentileFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) { @@ -1967,7 +2001,7 @@ int32_t apercentilePartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { int32_t slotId = pCtx->pExpr->base.resSchema.slotId; SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId); - colDataAppend(pCol, pBlock->info.rows, res, false); + colDataSetVal(pCol, pBlock->info.rows, res, false); taosMemoryFree(res); return pResInfo->numOfRes; @@ -2062,7 +2096,7 @@ static void prepareBuf(SqlFunctionCtx* pCtx) { } static int32_t firstlastSaveTupleData(const SSDataBlock* pSrcBlock, int32_t rowIndex, SqlFunctionCtx* pCtx, - SFirstLastRes* pInfo) { + SFirstLastRes* pInfo) { int32_t code = TSDB_CODE_SUCCESS; if (pCtx->subsidiaries.num <= 0) { @@ -2115,7 +2149,8 @@ int32_t firstFunction(SqlFunctionCtx* pCtx) { } // All null data column, return directly. - if (pInput->colDataSMAIsSet && (pInput->pColumnDataAgg[0]->numOfNull == pInput->totalRows) && pInputCol->hasNull == true) { + if (pInput->colDataSMAIsSet && (pInput->pColumnDataAgg[0]->numOfNull == pInput->totalRows) && + pInputCol->hasNull == true) { // save selectivity value for column consisted of all null values int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo); if (code != TSDB_CODE_SUCCESS) { @@ -2231,7 +2266,8 @@ int32_t lastFunction(SqlFunctionCtx* pCtx) { } // All null data column, return directly. - if (pInput->colDataSMAIsSet && (pInput->pColumnDataAgg[0]->numOfNull == pInput->totalRows) && pInputCol->hasNull == true) { + if (pInput->colDataSMAIsSet && (pInput->pColumnDataAgg[0]->numOfNull == pInput->totalRows) && + pInputCol->hasNull == true) { // save selectivity value for column consisted of all null values int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo); if (code != TSDB_CODE_SUCCESS) { @@ -2325,7 +2361,7 @@ int32_t lastFunction(SqlFunctionCtx* pCtx) { } if (pResInfo->numOfRes == 0 || pInfo->ts < cts) { - char* data = colDataGetData(pInputCol, chosen); + char* data = colDataGetData(pInputCol, chosen); int32_t code = doSaveCurrentVal(pCtx, i, cts, type, data); if (code != TSDB_CODE_SUCCESS) { return code; @@ -2336,7 +2372,7 @@ int32_t lastFunction(SqlFunctionCtx* pCtx) { for (int32_t i = pInput->startRowIndex + round * 4; i < pInput->startRowIndex + pInput->numOfRows; ++i) { if (pResInfo->numOfRes == 0 || pInfo->ts < pts[i]) { - char* data = colDataGetData(pInputCol, i); + char* data = colDataGetData(pInputCol, i); int32_t code = doSaveCurrentVal(pCtx, i, pts[i], type, data); if (code != TSDB_CODE_SUCCESS) { return code; @@ -2353,7 +2389,7 @@ int32_t lastFunction(SqlFunctionCtx* pCtx) { numOfElems++; if (pResInfo->numOfRes == 0 || pInfo->ts < pts[i]) { - char* data = colDataGetData(pInputCol, i); + char* data = colDataGetData(pInputCol, i); int32_t code = doSaveCurrentVal(pCtx, i, pts[i], type, data); if (code != TSDB_CODE_SUCCESS) { return code; @@ -2400,7 +2436,7 @@ static int32_t firstLastTransferInfoImpl(SFirstLastRes* pInput, SFirstLastRes* p } static int32_t firstLastTransferInfo(SqlFunctionCtx* pCtx, SFirstLastRes* pInput, SFirstLastRes* pOutput, bool isFirst, - int32_t rowIndex) { + int32_t rowIndex) { if (TSDB_CODE_SUCCESS == firstLastTransferInfoImpl(pInput, pOutput, isFirst)) { int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, rowIndex, pCtx, pOutput); if (code != TSDB_CODE_SUCCESS) { @@ -2427,7 +2463,7 @@ static int32_t firstLastFunctionMergeImpl(SqlFunctionCtx* pCtx, bool isFirstQuer for (int32_t i = start; i < start + pInput->numOfRows; ++i) { char* data = colDataGetData(pCol, i); SFirstLastRes* pInputInfo = (SFirstLastRes*)varDataVal(data); - int32_t code = firstLastTransferInfo(pCtx, pInputInfo, pInfo, isFirstQuery, i); + int32_t code = firstLastTransferInfo(pCtx, pInputInfo, pInfo, isFirstQuery, i); if (code != TSDB_CODE_SUCCESS) { return code; } @@ -2453,7 +2489,7 @@ int32_t firstLastFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0; SFirstLastRes* pRes = GET_ROWCELL_INTERBUF(pResInfo); - colDataAppend(pCol, pBlock->info.rows, pRes->buf, pRes->isNull || pResInfo->isNullRes); + colDataSetVal(pCol, pBlock->info.rows, pRes->buf, pRes->isNull || pResInfo->isNullRes); // handle selectivity code = setSelectivityValue(pCtx, pBlock, &pRes->pos, pBlock->info.rows); @@ -2478,7 +2514,7 @@ int32_t firstLastPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { int32_t slotId = pCtx->pExpr->base.resSchema.slotId; SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId); - colDataAppend(pCol, pBlock->info.rows, res, false); + colDataSetVal(pCol, pBlock->info.rows, res, false); code = setSelectivityValue(pCtx, pBlock, &pRes->pos, pBlock->info.rows); taosMemoryFree(res); @@ -2659,7 +2695,7 @@ static int32_t doSetPrevVal(SDiffInfo* pDiffInfo, int32_t type, const char* pv, } static int32_t doHandleDiff(SDiffInfo* pDiffInfo, int32_t type, const char* pv, SColumnInfoData* pOutput, int32_t pos, - int32_t order, int64_t ts) { + int32_t order, int64_t ts) { int32_t factor = (order == TSDB_ORDER_ASC) ? 1 : -1; pDiffInfo->prevTs = ts; switch (type) { @@ -2669,7 +2705,7 @@ static int32_t doHandleDiff(SDiffInfo* pDiffInfo, int32_t type, const char* pv, if (delta < 0 && pDiffInfo->ignoreNegative) { colDataSetNull_f_s(pOutput, pos); } else { - colDataAppendInt64(pOutput, pos, &delta); + colDataSetInt64(pOutput, pos, &delta); } pDiffInfo->prev.i64 = v; @@ -2682,7 +2718,7 @@ static int32_t doHandleDiff(SDiffInfo* pDiffInfo, int32_t type, const char* pv, if (delta < 0 && pDiffInfo->ignoreNegative) { colDataSetNull_f_s(pOutput, pos); } else { - colDataAppendInt64(pOutput, pos, &delta); + colDataSetInt64(pOutput, pos, &delta); } pDiffInfo->prev.i64 = v; break; @@ -2693,7 +2729,7 @@ static int32_t doHandleDiff(SDiffInfo* pDiffInfo, int32_t type, const char* pv, if (delta < 0 && pDiffInfo->ignoreNegative) { colDataSetNull_f_s(pOutput, pos); } else { - colDataAppendInt64(pOutput, pos, &delta); + colDataSetInt64(pOutput, pos, &delta); } pDiffInfo->prev.i64 = v; break; @@ -2705,7 +2741,7 @@ static int32_t doHandleDiff(SDiffInfo* pDiffInfo, int32_t type, const char* pv, if (delta < 0 && pDiffInfo->ignoreNegative) { colDataSetNull_f_s(pOutput, pos); } else { - colDataAppendInt64(pOutput, pos, &delta); + colDataSetInt64(pOutput, pos, &delta); } pDiffInfo->prev.i64 = v; break; @@ -2716,7 +2752,7 @@ static int32_t doHandleDiff(SDiffInfo* pDiffInfo, int32_t type, const char* pv, if ((delta < 0 && pDiffInfo->ignoreNegative) || isinf(delta) || isnan(delta)) { // check for overflow colDataSetNull_f_s(pOutput, pos); } else { - colDataAppendDouble(pOutput, pos, &delta); + colDataSetDouble(pOutput, pos, &delta); } pDiffInfo->prev.d64 = v; break; @@ -2727,7 +2763,7 @@ static int32_t doHandleDiff(SDiffInfo* pDiffInfo, int32_t type, const char* pv, if ((delta < 0 && pDiffInfo->ignoreNegative) || isinf(delta) || isnan(delta)) { // check for overflow colDataSetNull_f_s(pOutput, pos); } else { - colDataAppendDouble(pOutput, pos, &delta); + colDataSetDouble(pOutput, pos, &delta); } pDiffInfo->prev.d64 = v; break; @@ -2867,8 +2903,8 @@ static STopBotRes* getTopBotOutputInfo(SqlFunctionCtx* pCtx) { return pRes; } -static int32_t doAddIntoResult(SqlFunctionCtx* pCtx, void* pData, int32_t rowIndex, SSDataBlock* pSrcBlock, uint16_t type, - uint64_t uid, SResultRowEntryInfo* pEntryInfo, bool isTopQuery); +static int32_t doAddIntoResult(SqlFunctionCtx* pCtx, void* pData, int32_t rowIndex, SSDataBlock* pSrcBlock, + uint16_t type, uint64_t uid, SResultRowEntryInfo* pEntryInfo, bool isTopQuery); static void addResult(SqlFunctionCtx* pCtx, STopBotResItem* pSourceItem, int16_t type, bool isTopQuery); @@ -2889,7 +2925,7 @@ int32_t topFunction(SqlFunctionCtx* pCtx) { } numOfElems++; - char* data = colDataGetData(pCol, i); + char* data = colDataGetData(pCol, i); int32_t code = doAddIntoResult(pCtx, data, i, pCtx->pSrcBlock, pRes->type, pInput->uid, pResInfo, true); if (code != TSDB_CODE_SUCCESS) { return code; @@ -2923,7 +2959,7 @@ int32_t bottomFunction(SqlFunctionCtx* pCtx) { } numOfElems++; - char* data = colDataGetData(pCol, i); + char* data = colDataGetData(pCol, i); int32_t code = doAddIntoResult(pCtx, data, i, pCtx->pSrcBlock, pRes->type, pInput->uid, pResInfo, false); if (code != TSDB_CODE_SUCCESS) { return code; @@ -2975,7 +3011,7 @@ static int32_t topBotResComparFn(const void* p1, const void* p2, const void* par } int32_t doAddIntoResult(SqlFunctionCtx* pCtx, void* pData, int32_t rowIndex, SSDataBlock* pSrcBlock, uint16_t type, - uint64_t uid, SResultRowEntryInfo* pEntryInfo, bool isTopQuery) { + uint64_t uid, SResultRowEntryInfo* pEntryInfo, bool isTopQuery) { STopBotRes* pRes = getTopBotOutputInfo(pCtx); SVariant val = {0}; @@ -3166,7 +3202,7 @@ static char* doLoadTupleData(SSerializeDataHandle* pHandle, const STuplePos* pPo if (pPage == NULL) { return NULL; } - char* p = pPage->data + pPos->offset; + char* p = pPage->data + pPos->offset; releaseBufPage(pHandle->pBuf, pPage); return p; } else { @@ -3195,13 +3231,13 @@ int32_t topBotFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { // todo assign the tag value and the corresponding row data int32_t currentRow = pBlock->info.rows; if (pEntryInfo->numOfRes <= 0) { - colDataAppendNULL(pCol, currentRow); + colDataSetNULL(pCol, currentRow); code = setSelectivityValue(pCtx, pBlock, &pRes->nullTuplePos, currentRow); return code; } for (int32_t i = 0; i < pEntryInfo->numOfRes; ++i) { STopBotResItem* pItem = &pRes->pItems[i]; - colDataAppend(pCol, currentRow, (const char*)&pItem->v.i, false); + colDataSetVal(pCol, currentRow, (const char*)&pItem->v.i, false); #ifdef BUF_PAGE_DEBUG qDebug("page_finalize i:%d,item:%p,pageId:%d, offset:%d\n", i, pItem, pItem->tuplePos.pageId, pItem->tuplePos.offset); @@ -3418,7 +3454,7 @@ int32_t spreadPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { int32_t slotId = pCtx->pExpr->base.resSchema.slotId; SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId); - colDataAppend(pCol, pBlock->info.rows, res, false); + colDataSetVal(pCol, pBlock->info.rows, res, false); taosMemoryFree(res); return pResInfo->numOfRes; @@ -3593,7 +3629,7 @@ int32_t elapsedPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { int32_t slotId = pCtx->pExpr->base.resSchema.slotId; SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId); - colDataAppend(pCol, pBlock->info.rows, res, false); + colDataSetVal(pCol, pBlock->info.rows, res, false); taosMemoryFree(res); return pResInfo->numOfRes; @@ -3919,7 +3955,7 @@ int32_t histogramFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { pInfo->bins[i].upper, pInfo->bins[i].percentage); } varDataSetLen(buf, len); - colDataAppend(pCol, currentRow, buf, false); + colDataSetVal(pCol, currentRow, buf, false); currentRow++; } @@ -3938,7 +3974,7 @@ int32_t histogramPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { int32_t slotId = pCtx->pExpr->base.resSchema.slotId; SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId); - colDataAppend(pCol, pBlock->info.rows, res, false); + colDataSetVal(pCol, pBlock->info.rows, res, false); taosMemoryFree(res); return pResInfo->numOfRes; @@ -4157,7 +4193,7 @@ int32_t hllPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { int32_t slotId = pCtx->pExpr->base.resSchema.slotId; SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId); - colDataAppend(pCol, pBlock->info.rows, res, false); + colDataSetVal(pCol, pBlock->info.rows, res, false); taosMemoryFree(res); return pResInfo->numOfRes; @@ -4290,7 +4326,7 @@ int32_t stateCountFunction(SqlFunctionCtx* pCtx) { numOfElems++; if (colDataIsNull_f(pInputCol->nullbitmap, i)) { - colDataAppendNULL(pOutput, i); + colDataSetNULL(pOutput, i); // handle selectivity if (pCtx->subsidiaries.num > 0) { appendSelectivityValue(pCtx, i, pCtx->offset + numOfElems - 1); @@ -4306,7 +4342,7 @@ int32_t stateCountFunction(SqlFunctionCtx* pCtx) { } else { pInfo->count = 0; } - colDataAppend(pOutput, pCtx->offset + numOfElems - 1, (char*)&output, false); + colDataSetVal(pOutput, pCtx->offset + numOfElems - 1, (char*)&output, false); // handle selectivity if (pCtx->subsidiaries.num > 0) { @@ -4352,7 +4388,7 @@ int32_t stateDurationFunction(SqlFunctionCtx* pCtx) { numOfElems++; if (colDataIsNull_f(pInputCol->nullbitmap, i)) { - colDataAppendNULL(pOutput, i); + colDataSetNULL(pOutput, i); // handle selectivity if (pCtx->subsidiaries.num > 0) { appendSelectivityValue(pCtx, i, pCtx->offset + numOfElems - 1); @@ -4372,7 +4408,7 @@ int32_t stateDurationFunction(SqlFunctionCtx* pCtx) { } else { pInfo->durationStart = 0; } - colDataAppend(pOutput, pCtx->offset + numOfElems - 1, (char*)&output, false); + colDataSetVal(pOutput, pCtx->offset + numOfElems - 1, (char*)&output, false); // handle selectivity if (pCtx->subsidiaries.num > 0) { @@ -4412,7 +4448,7 @@ int32_t csumFunction(SqlFunctionCtx* pCtx) { int32_t pos = startOffset + numOfElems; if (colDataIsNull_f(pInputCol->nullbitmap, i)) { - // colDataAppendNULL(pOutput, i); + // colDataSetNULL(pOutput, i); continue; } @@ -4421,21 +4457,21 @@ int32_t csumFunction(SqlFunctionCtx* pCtx) { int64_t v; GET_TYPED_DATA(v, int64_t, type, data); pSumRes->isum += v; - colDataAppend(pOutput, pos, (char*)&pSumRes->isum, false); + colDataSetVal(pOutput, pos, (char*)&pSumRes->isum, false); } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) { uint64_t v; GET_TYPED_DATA(v, uint64_t, type, data); pSumRes->usum += v; - colDataAppend(pOutput, pos, (char*)&pSumRes->usum, false); + colDataSetVal(pOutput, pos, (char*)&pSumRes->usum, false); } else if (IS_FLOAT_TYPE(type)) { double v; GET_TYPED_DATA(v, double, type, data); pSumRes->dsum += v; // check for overflow if (isinf(pSumRes->dsum) || isnan(pSumRes->dsum)) { - colDataAppendNULL(pOutput, pos); + colDataSetNULL(pOutput, pos); } else { - colDataAppend(pOutput, pos, (char*)&pSumRes->dsum, false); + colDataSetVal(pOutput, pos, (char*)&pSumRes->dsum, false); } } @@ -4499,7 +4535,7 @@ int32_t mavgFunction(SqlFunctionCtx* pCtx) { int32_t pos = startOffset + numOfElems; if (colDataIsNull_f(pInputCol->nullbitmap, i)) { - // colDataAppendNULL(pOutput, i); + // colDataSetNULL(pOutput, i); continue; } @@ -4522,9 +4558,9 @@ int32_t mavgFunction(SqlFunctionCtx* pCtx) { double result = pInfo->sum / pInfo->numOfPoints; // check for overflow if (isinf(result) || isnan(result)) { - colDataAppendNULL(pOutput, pos); + colDataSetNULL(pOutput, pos); } else { - colDataAppend(pOutput, pos, (char*)&result, false); + colDataSetVal(pOutput, pos, (char*)&result, false); } // handle selectivity @@ -4627,7 +4663,7 @@ int32_t sampleFunction(SqlFunctionCtx* pCtx) { continue; } - char* data = colDataGetData(pInputCol, i); + char* data = colDataGetData(pInputCol, i); int32_t code = doReservoirSample(pCtx, pInfo, data, i); if (code != TSDB_CODE_SUCCESS) { return code; @@ -4647,7 +4683,7 @@ int32_t sampleFunction(SqlFunctionCtx* pCtx) { } int32_t sampleFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { - int32_t code = TSDB_CODE_SUCCESS; + int32_t code = TSDB_CODE_SUCCESS; SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx); SSampleInfo* pInfo = getSampleOutputInfo(pCtx); @@ -4658,12 +4694,12 @@ int32_t sampleFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { int32_t currentRow = pBlock->info.rows; if (pInfo->numSampled == 0) { - colDataAppendNULL(pCol, currentRow); + colDataSetNULL(pCol, currentRow); code = setSelectivityValue(pCtx, pBlock, &pInfo->nullTuplePos, currentRow); return code; } for (int32_t i = 0; i < pInfo->numSampled; ++i) { - colDataAppend(pCol, currentRow + i, pInfo->data + i * pInfo->colBytes, false); + colDataSetVal(pCol, currentRow + i, pInfo->data + i * pInfo->colBytes, false); code = setSelectivityValue(pCtx, pBlock, &pInfo->tuplePos[i], currentRow + i); } @@ -4774,9 +4810,9 @@ int32_t tailFunction(SqlFunctionCtx* pCtx) { int32_t pos = startOffset + i; STailItem* pItem = pInfo->pItems[i]; if (pItem->isNull) { - colDataAppendNULL(pOutput, pos); + colDataSetNULL(pOutput, pos); } else { - colDataAppend(pOutput, pos, pItem->data, false); + colDataSetVal(pOutput, pos, pItem->data, false); } } @@ -4800,7 +4836,7 @@ int32_t tailFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { int32_t currentRow = pBlock->info.rows; for (int32_t i = 0; i < pEntryInfo->numOfRes; ++i) { STailItem* pItem = pInfo->pItems[i]; - colDataAppend(pCol, currentRow, pItem->data, false); + colDataSetVal(pCol, currentRow, pItem->data, false); currentRow += 1; } @@ -4894,12 +4930,12 @@ int32_t uniqueFunction(SqlFunctionCtx* pCtx) { for (int32_t i = 0; i < pInfo->numOfPoints; ++i) { SUniqueItem* pItem = (SUniqueItem*)(pInfo->pItems + i * (sizeof(SUniqueItem) + pInfo->colBytes)); if (pItem->isNull == true) { - colDataAppendNULL(pOutput, i); + colDataSetNULL(pOutput, i); } else { - colDataAppend(pOutput, i, pItem->data, false); + colDataSetVal(pOutput, i, pItem->data, false); } if (pTsOutput != NULL) { - colDataAppendInt64(pTsOutput, i, &pItem->timestamp); + colDataSetInt64(pTsOutput, i, &pItem->timestamp); } } @@ -4981,7 +5017,7 @@ int32_t modeFunction(SqlFunctionCtx* pCtx) { } numOfElems++; - char* data = colDataGetData(pInputCol, i); + char* data = colDataGetData(pInputCol, i); int32_t code = doModeAdd(pInfo, i, pCtx, data); if (code != TSDB_CODE_SUCCESS) { return code; @@ -5026,10 +5062,10 @@ int32_t modeFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { if (maxCount != 0) { SModeItem* pResItem = (SModeItem*)(pInfo->pItems + resIndex * (sizeof(SModeItem) + pInfo->colBytes)); - colDataAppend(pCol, currentRow, pResItem->data, false); + colDataSetVal(pCol, currentRow, pResItem->data, false); code = setSelectivityValue(pCtx, pBlock, &pResItem->tuplePos, currentRow); } else { - colDataAppendNULL(pCol, currentRow); + colDataSetNULL(pCol, currentRow); code = setSelectivityValue(pCtx, pBlock, &pInfo->nullTuplePos, currentRow); } @@ -5387,7 +5423,6 @@ int32_t blockDistFunction(SqlFunctionCtx* pCtx) { pDistInfo->numOfBlocks += p1.numOfBlocks; pDistInfo->numOfTables += p1.numOfTables; pDistInfo->numOfInmemRows += p1.numOfInmemRows; - pDistInfo->numOfVgroups += p1.numOfVgroups; pDistInfo->totalSize += p1.totalSize; pDistInfo->totalRows += p1.totalRows; pDistInfo->numOfFiles += p1.numOfFiles; @@ -5403,7 +5438,9 @@ int32_t blockDistFunction(SqlFunctionCtx* pCtx) { if (pDistInfo->maxRows < p1.maxRows) { pDistInfo->maxRows = p1.maxRows; } + pDistInfo->numOfVgroups += (p1.numOfTables != 0 ? 1 : 0); + pDistInfo->numOfVgroups += (p1.numOfTables != 0 ? 1 : 0); for (int32_t i = 0; i < tListLen(pDistInfo->blockRowsHisto); ++i) { pDistInfo->blockRowsHisto[i] += p1.blockRowsHisto[i]; } @@ -5422,7 +5459,6 @@ int32_t tSerializeBlockDistInfo(void* buf, int32_t bufLen, const STableBlockDist if (tEncodeU16(&encoder, pInfo->numOfFiles) < 0) return -1; if (tEncodeU32(&encoder, pInfo->numOfBlocks) < 0) return -1; if (tEncodeU32(&encoder, pInfo->numOfTables) < 0) return -1; - if (tEncodeU32(&encoder, pInfo->numOfVgroups) < 0) return -1; if (tEncodeU64(&encoder, pInfo->totalSize) < 0) return -1; if (tEncodeU64(&encoder, pInfo->totalRows) < 0) return -1; @@ -5432,6 +5468,7 @@ int32_t tSerializeBlockDistInfo(void* buf, int32_t bufLen, const STableBlockDist if (tEncodeI32(&encoder, pInfo->defMinRows) < 0) return -1; if (tEncodeU32(&encoder, pInfo->numOfInmemRows) < 0) return -1; if (tEncodeU32(&encoder, pInfo->numOfSmallBlocks) < 0) return -1; + if (tEncodeU32(&encoder, pInfo->numOfVgroups) < 0) return -1; for (int32_t i = 0; i < tListLen(pInfo->blockRowsHisto); ++i) { if (tEncodeI32(&encoder, pInfo->blockRowsHisto[i]) < 0) return -1; @@ -5454,7 +5491,6 @@ int32_t tDeserializeBlockDistInfo(void* buf, int32_t bufLen, STableBlockDistInfo if (tDecodeU16(&decoder, &pInfo->numOfFiles) < 0) return -1; if (tDecodeU32(&decoder, &pInfo->numOfBlocks) < 0) return -1; if (tDecodeU32(&decoder, &pInfo->numOfTables) < 0) return -1; - if (tDecodeU32(&decoder, &pInfo->numOfVgroups) < 0) return -1; if (tDecodeU64(&decoder, &pInfo->totalSize) < 0) return -1; if (tDecodeU64(&decoder, &pInfo->totalRows) < 0) return -1; @@ -5464,6 +5500,7 @@ int32_t tDeserializeBlockDistInfo(void* buf, int32_t bufLen, STableBlockDistInfo if (tDecodeI32(&decoder, &pInfo->defMinRows) < 0) return -1; if (tDecodeU32(&decoder, &pInfo->numOfInmemRows) < 0) return -1; if (tDecodeU32(&decoder, &pInfo->numOfSmallBlocks) < 0) return -1; + if (tDecodeU32(&decoder, &pInfo->numOfVgroups) < 0) return -1; for (int32_t i = 0; i < tListLen(pInfo->blockRowsHisto); ++i) { if (tDecodeI32(&decoder, &pInfo->blockRowsHisto[i]) < 0) return -1; @@ -5500,7 +5537,7 @@ int32_t blockDistFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { pData->numOfBlocks, pData->totalSize / 1024.0, averageSize / 1024.0, compRatio, '%'); varDataSetLen(st, len); - colDataAppend(pColInfo, row++, st, false); + colDataSetVal(pColInfo, row++, st, false); int64_t avgRows = 0; if (pData->numOfBlocks > 0) { @@ -5512,18 +5549,18 @@ int32_t blockDistFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { pData->totalRows, pData->numOfInmemRows, pData->minRows, pData->maxRows, avgRows); varDataSetLen(st, len); - colDataAppend(pColInfo, row++, st, false); + colDataSetVal(pColInfo, row++, st, false); len = sprintf(st + VARSTR_HEADER_SIZE, "Total_Tables=[%d] Total_Files=[%d] Total_Vgroups=[%d]", pData->numOfTables, pData->numOfFiles, pData->numOfVgroups); varDataSetLen(st, len); - colDataAppend(pColInfo, row++, st, false); + colDataSetVal(pColInfo, row++, st, false); len = sprintf(st + VARSTR_HEADER_SIZE, "--------------------------------------------------------------------------------"); varDataSetLen(st, len); - colDataAppend(pColInfo, row++, st, false); + colDataSetVal(pColInfo, row++, st, false); int32_t maxVal = 0; int32_t minVal = INT32_MAX; @@ -5562,7 +5599,7 @@ int32_t blockDistFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { } varDataSetLen(st, len); - colDataAppend(pColInfo, row++, st, false); + colDataSetVal(pColInfo, row++, st, false); } return TSDB_CODE_SUCCESS; @@ -5623,13 +5660,13 @@ int32_t derivativeFunction(SqlFunctionCtx* pCtx) { if (pDerivInfo->ignoreNegative && r < 0) { } else { if (isinf(r) || isnan(r)) { - colDataAppendNULL(pOutput, pos); + colDataSetNULL(pOutput, pos); } else { - colDataAppend(pOutput, pos, (const char*)&r, false); + colDataSetVal(pOutput, pos, (const char*)&r, false); } if (pTsOutput != NULL) { - colDataAppendInt64(pTsOutput, pos, &tsList[i]); + colDataSetInt64(pTsOutput, pos, &tsList[i]); } // handle selectivity @@ -5664,13 +5701,13 @@ int32_t derivativeFunction(SqlFunctionCtx* pCtx) { if (pDerivInfo->ignoreNegative && r < 0) { } else { if (isinf(r) || isnan(r)) { - colDataAppendNULL(pOutput, pos); + colDataSetNULL(pOutput, pos); } else { - colDataAppend(pOutput, pos, (const char*)&r, false); + colDataSetVal(pOutput, pos, (const char*)&r, false); } if (pTsOutput != NULL) { - colDataAppendInt64(pTsOutput, pos, &pDerivInfo->prevTs); + colDataSetInt64(pTsOutput, pos, &pDerivInfo->prevTs); } // handle selectivity @@ -5801,7 +5838,7 @@ int32_t irateFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { SRateInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo); double result = doCalcRate(pInfo, (double)TSDB_TICK_PER_SECOND(pCtx->param[1].param.i)); - colDataAppend(pCol, pBlock->info.rows, (const char*)&result, pResInfo->isNullRes); + colDataSetVal(pCol, pBlock->info.rows, (const char*)&result, pResInfo->isNullRes); return pResInfo->numOfRes; } @@ -5852,7 +5889,7 @@ int32_t groupKeyFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { if (pInfo->hasResult) { int32_t currentRow = pBlock->info.rows; for (; currentRow < pBlock->info.rows + pResInfo->numOfRes; ++currentRow) { - colDataAppend(pCol, currentRow, pInfo->data, pInfo->isNull ? true : false); + colDataSetVal(pCol, currentRow, pInfo->data, pInfo->isNull ? true : false); } } else { pResInfo->numOfRes = 0; diff --git a/source/libs/function/src/detail/tavgfunction.c b/source/libs/function/src/detail/tavgfunction.c index 3a70a65ec4..50df1b5067 100644 --- a/source/libs/function/src/detail/tavgfunction.c +++ b/source/libs/function/src/detail/tavgfunction.c @@ -847,7 +847,7 @@ int32_t avgPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { int32_t slotId = pCtx->pExpr->base.resSchema.slotId; SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId); - colDataAppend(pCol, pBlock->info.rows, res, false); + colDataSetVal(pCol, pBlock->info.rows, res, false); taosMemoryFree(res); return pResInfo->numOfRes; diff --git a/source/libs/function/src/tfunctionInt.c b/source/libs/function/src/tfunctionInt.c index edfd866010..e8041d1704 100644 --- a/source/libs/function/src/tfunctionInt.c +++ b/source/libs/function/src/tfunctionInt.c @@ -47,11 +47,11 @@ int32_t getNumOfResult(SqlFunctionCtx* pCtx, int32_t num, SSDataBlock* pResBlock SResultRowEntryInfo* pResInfo = GET_RES_INFO(&pCtx[i]); if (pResInfo->numOfRes == 0) { for (int32_t j = 0; j < pResInfo->numOfRes; ++j) { - colDataAppend(pCol, j, NULL, true); // TODO add set null data api + colDataSetVal(pCol, j, NULL, true); // TODO add set null data api } } else { for (int32_t j = 0; j < pResInfo->numOfRes; ++j) { - colDataAppend(pCol, j, GET_ROWCELL_INTERBUF(pResInfo), false); + colDataSetVal(pCol, j, GET_ROWCELL_INTERBUF(pResInfo), false); } } } diff --git a/source/libs/function/src/tudf.c b/source/libs/function/src/tudf.c index b9e72847a1..8f5cd070dc 100644 --- a/source/libs/function/src/tudf.c +++ b/source/libs/function/src/tudf.c @@ -864,13 +864,13 @@ int32_t convertScalarParamToDataBlock(SScalarParam *input, int32_t numOfCols, SS int expandRows = numOfRows - startRow; bool isNull = colDataIsNull_s(pColInfoData, (input+i)->numOfRows - 1); if (isNull) { - colDataAppendNNULL(pDest, startRow, expandRows); + colDataSetNNULL(pDest, startRow, expandRows); } else { char* src = colDataGetData(pColInfoData, (input + i)->numOfRows - 1); for (int j = 0; j < expandRows; ++j) { - colDataAppend(pDest, startRow+j, src, false); + colDataSetVal(pDest, startRow+j, src, false); } - //colDataAppendNItems(pColInfoData, startRow, data, expandRows); + //colDataSetNItems(pColInfoData, startRow, data, expandRows); } } } diff --git a/source/libs/function/test/runUdf.c b/source/libs/function/test/runUdf.c index b5d1b1576b..aa8b88b738 100644 --- a/source/libs/function/test/runUdf.c +++ b/source/libs/function/test/runUdf.c @@ -55,7 +55,7 @@ int scalarFuncTest() { SColumnInfoData *pCol = taosArrayGet(pBlock->pDataBlock, 0); for (int32_t j = 0; j < pBlock->info.rows; ++j) { - colDataAppendInt32(pCol, j, &j); + colDataSetInt32(pCol, j, &j); } SScalarParam input = {0}; @@ -99,7 +99,7 @@ int aggregateFuncTest() { SColumnInfoData *pColInfo = bdGetColumnInfoData(pBlock, 0); for (int32_t j = 0; j < pBlock->info.rows; ++j) { - colDataAppendInt32(pColInfo, j, &j); + colDataSetInt32(pColInfo, j, &j); } SUdfInterBuf buf = {0}; diff --git a/source/libs/index/src/index.c b/source/libs/index/src/index.c index a99c87b7f9..3ed66956e8 100644 --- a/source/libs/index/src/index.c +++ b/source/libs/index/src/index.c @@ -126,7 +126,7 @@ int indexOpen(SIndexOpts* opts, const char* path, SIndex** index) { idx->colObj = taosHashInit(8, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_ENTRY_LOCK); idx->version = 1; - idx->path = tstrdup(path); + idx->path = taosStrdup(path); taosThreadMutexInit(&idx->mtx, NULL); tsem_init(&idx->sem, 0, 0); diff --git a/source/libs/index/src/indexCache.c b/source/libs/index/src/indexCache.c index ffca6ad97f..8b0e712553 100644 --- a/source/libs/index/src/indexCache.c +++ b/source/libs/index/src/indexCache.c @@ -340,7 +340,7 @@ IndexCache* idxCacheCreate(SIndex* idx, uint64_t suid, const char* colName, int8 cache->mem = idxInternalCacheCreate(type); cache->mem->pCache = cache; - cache->colName = IDX_TYPE_CONTAIN_EXTERN_TYPE(type, TSDB_DATA_TYPE_JSON) ? tstrdup(JSON_COLUMN) : tstrdup(colName); + cache->colName = IDX_TYPE_CONTAIN_EXTERN_TYPE(type, TSDB_DATA_TYPE_JSON) ? taosStrdup(JSON_COLUMN) : taosStrdup(colName); cache->type = type; cache->index = idx; cache->version = 0; @@ -767,7 +767,7 @@ static bool idxCacheIteratorNext(Iterate* itera) { iv->type = ct->operaType; iv->ver = ct->version; - iv->colVal = tstrdup(ct->colVal); + iv->colVal = taosStrdup(ct->colVal); taosArrayPush(iv->val, &ct->uid); } return next; diff --git a/source/libs/index/src/indexFstAutomation.c b/source/libs/index/src/indexFstAutomation.c index 385e832763..0c96d1aa0a 100644 --- a/source/libs/index/src/indexFstAutomation.c +++ b/source/libs/index/src/indexFstAutomation.c @@ -164,7 +164,7 @@ FAutoCtx* automCtxCreate(void* data, AutomationType atype) { // add more search type } - ctx->data = (data != NULL ? strdup((char*)data) : NULL); + ctx->data = (data != NULL ? taosStrdup((char*)data) : NULL); ctx->type = atype; ctx->stdata = (void*)sv; return ctx; diff --git a/source/libs/index/src/indexFstRegex.c b/source/libs/index/src/indexFstRegex.c index e148f211f2..8b513bfb2b 100644 --- a/source/libs/index/src/indexFstRegex.c +++ b/source/libs/index/src/indexFstRegex.c @@ -23,7 +23,7 @@ FstRegex *regexCreate(const char *str) { return NULL; } - regex->orig = tstrdup(str); + regex->orig = taosStrdup(str); // construct insts based on str SArray *insts = taosArrayInit(256, sizeof(uint8_t)); diff --git a/source/libs/index/src/indexTfile.c b/source/libs/index/src/indexTfile.c index d921ca7103..cdd1cc7386 100644 --- a/source/libs/index/src/indexTfile.c +++ b/source/libs/index/src/indexTfile.c @@ -804,7 +804,7 @@ TFileValue* tfileValueCreate(char* val) { if (tf == NULL) { return NULL; } - tf->colVal = tstrdup(val); + tf->colVal = taosStrdup(val); tf->tableId = taosArrayInit(32, sizeof(uint64_t)); return tf; } diff --git a/source/libs/index/test/fstTest.cc b/source/libs/index/test/fstTest.cc index 4e9a853302..b889a2209a 100644 --- a/source/libs/index/test/fstTest.cc +++ b/source/libs/index/test/fstTest.cc @@ -599,7 +599,7 @@ void validateTFile(char* arg) { std::thread threads[NUM_OF_THREAD]; // std::vector threads; SIndex* index = (SIndex*)taosMemoryCalloc(1, sizeof(SIndex)); - index->path = strdup(arg); + index->path = taosStrdup(arg); TFileReader* reader = tfileReaderOpen(index, 0, 20000000, "tag1"); for (int i = 0; i < NUM_OF_THREAD; i++) { diff --git a/source/libs/nodes/src/nodesCloneFuncs.c b/source/libs/nodes/src/nodesCloneFuncs.c index 185f4428f2..b4f7ea866a 100644 --- a/source/libs/nodes/src/nodesCloneFuncs.c +++ b/source/libs/nodes/src/nodesCloneFuncs.c @@ -40,7 +40,7 @@ if (NULL == (pSrc)->fldname) { \ break; \ } \ - (pDst)->fldname = strdup((pSrc)->fldname); \ + (pDst)->fldname = taosStrdup((pSrc)->fldname); \ if (NULL == (pDst)->fldname) { \ return TSDB_CODE_OUT_OF_MEMORY; \ } \ diff --git a/source/libs/nodes/test/nodesTestMain.cpp b/source/libs/nodes/test/nodesTestMain.cpp index 0515e8bbc0..a7f9a06611 100644 --- a/source/libs/nodes/test/nodesTestMain.cpp +++ b/source/libs/nodes/test/nodesTestMain.cpp @@ -28,7 +28,7 @@ static EDealRes rewriterTest(SNode** pNode, void* pContext) { } SValueNode* pVal = (SValueNode*)nodesMakeNode(QUERY_NODE_VALUE); string tmp = to_string(stoi(((SValueNode*)(pOp->pLeft))->literal) + stoi(((SValueNode*)(pOp->pRight))->literal)); - pVal->literal = strdup(tmp.c_str()); + pVal->literal = taosStrdup(tmp.c_str()); nodesDestroyNode(*pNode); *pNode = (SNode*)pVal; } @@ -40,12 +40,12 @@ TEST(NodesTest, traverseTest) { SOperatorNode* pOp = (SOperatorNode*)pRoot; SOperatorNode* pLeft = (SOperatorNode*)nodesMakeNode(QUERY_NODE_OPERATOR); pLeft->pLeft = (SNode*)nodesMakeNode(QUERY_NODE_VALUE); - ((SValueNode*)(pLeft->pLeft))->literal = strdup("10"); + ((SValueNode*)(pLeft->pLeft))->literal = taosStrdup("10"); pLeft->pRight = (SNode*)nodesMakeNode(QUERY_NODE_VALUE); - ((SValueNode*)(pLeft->pRight))->literal = strdup("5"); + ((SValueNode*)(pLeft->pRight))->literal = taosStrdup("5"); pOp->pLeft = (SNode*)pLeft; pOp->pRight = (SNode*)nodesMakeNode(QUERY_NODE_VALUE); - ((SValueNode*)(pOp->pRight))->literal = strdup("3"); + ((SValueNode*)(pOp->pRight))->literal = taosStrdup("3"); EXPECT_EQ(nodeType(pRoot), QUERY_NODE_OPERATOR); EDealRes res = DEAL_RES_CONTINUE; diff --git a/source/libs/parser/inc/sql.y b/source/libs/parser/inc/sql.y index b7f3465a4a..fb6d3bfdd9 100644 --- a/source/libs/parser/inc/sql.y +++ b/source/libs/parser/inc/sql.y @@ -301,7 +301,7 @@ create_subtable_clause(A) ::= %type multi_drop_clause { SNodeList* } %destructor multi_drop_clause { nodesDestroyList($$); } multi_drop_clause(A) ::= drop_table_clause(B). { A = createNodeList(pCxt, B); } -multi_drop_clause(A) ::= multi_drop_clause(B) drop_table_clause(C). { A = addNodeToList(pCxt, B, C); } +multi_drop_clause(A) ::= multi_drop_clause(B) NK_COMMA drop_table_clause(C). { A = addNodeToList(pCxt, B, C); } drop_table_clause(A) ::= exists_opt(B) full_table_name(C). { A = createDropTableClause(pCxt, B, C); } diff --git a/source/libs/parser/src/parAstCreater.c b/source/libs/parser/src/parAstCreater.c index 15a796e086..f613b1bd3d 100644 --- a/source/libs/parser/src/parAstCreater.c +++ b/source/libs/parser/src/parAstCreater.c @@ -355,7 +355,7 @@ SNode* createDefaultDatabaseCondValue(SAstCreateContext* pCxt) { SValueNode* val = (SValueNode*)nodesMakeNode(QUERY_NODE_VALUE); CHECK_OUT_OF_MEM(val); - val->literal = strdup(pCxt->pQueryCxt->db); + val->literal = taosStrdup(pCxt->pQueryCxt->db); CHECK_OUT_OF_MEM(val->literal); val->isDuration = false; val->translate = false; diff --git a/source/libs/parser/src/parInsertSql.c b/source/libs/parser/src/parInsertSql.c index e82b1edee1..3fbe23592a 100644 --- a/source/libs/parser/src/parInsertSql.c +++ b/source/libs/parser/src/parInsertSql.c @@ -449,7 +449,7 @@ static int32_t parseTagToken(const char** end, SToken* pToken, SSchema* pSchema, if (pToken->n + VARSTR_HEADER_SIZE > pSchema->bytes) { return generateSyntaxErrMsg(pMsgBuf, TSDB_CODE_PAR_VALUE_TOO_LONG, pSchema->name); } - val->pData = strdup(pToken->z); + val->pData = taosStrdup(pToken->z); val->nData = pToken->n; break; } diff --git a/source/libs/parser/src/parInsertUtil.c b/source/libs/parser/src/parInsertUtil.c index 602d82cb38..52d3569dcd 100644 --- a/source/libs/parser/src/parInsertUtil.c +++ b/source/libs/parser/src/parInsertUtil.c @@ -144,10 +144,10 @@ int16_t insFindCol(SToken* pColname, int16_t start, int16_t end, SSchema* pSchem void insBuildCreateTbReq(SVCreateTbReq* pTbReq, const char* tname, STag* pTag, int64_t suid, const char* sname, SArray* tagName, uint8_t tagNum, int32_t ttl) { pTbReq->type = TD_CHILD_TABLE; - pTbReq->name = strdup(tname); + pTbReq->name = taosStrdup(tname); pTbReq->ctb.suid = suid; pTbReq->ctb.tagNum = tagNum; - if (sname) pTbReq->ctb.stbName = strdup(sname); + if (sname) pTbReq->ctb.stbName = taosStrdup(sname); pTbReq->ctb.pTag = (uint8_t*)pTag; pTbReq->ctb.tagName = taosArrayDup(tagName, NULL); pTbReq->ttl = ttl; diff --git a/source/libs/parser/src/parTranslater.c b/source/libs/parser/src/parTranslater.c index f3bd91f786..8c5b41a7ee 100644 --- a/source/libs/parser/src/parTranslater.c +++ b/source/libs/parser/src/parTranslater.c @@ -1470,8 +1470,8 @@ static int32_t translateInterpFunc(STranslateContext* pCxt, SFunctionNode* pFunc SNode* pTable = pSelect->pFromTable; if ((NULL != pTable && (QUERY_NODE_REAL_TABLE != nodeType(pTable) || - (TSDB_CHILD_TABLE != ((SRealTableNode*)pTable)->pMeta->tableType && - TSDB_NORMAL_TABLE != ((SRealTableNode*)pTable)->pMeta->tableType)))) { + (TSDB_CHILD_TABLE != ((SRealTableNode*)pTable)->pMeta->tableType && + TSDB_NORMAL_TABLE != ((SRealTableNode*)pTable)->pMeta->tableType)))) { return generateSyntaxErrMsgExt(&pCxt->msgBuf, TSDB_CODE_PAR_ONLY_SUPPORT_SINGLE_TABLE, "%s is only supported in single table query", pFunc->functionName); } @@ -1692,7 +1692,7 @@ static int32_t rewriteFuncToValue(STranslateContext* pCxt, char* pLiteral, SNode static int32_t rewriteDatabaseFunc(STranslateContext* pCxt, SNode** pNode) { char* pCurrDb = NULL; if (NULL != pCxt->pParseCxt->db) { - pCurrDb = taosMemoryStrDup((void*)pCxt->pParseCxt->db); + pCurrDb = taosStrdup((void*)pCxt->pParseCxt->db); if (NULL == pCurrDb) { return TSDB_CODE_OUT_OF_MEMORY; } @@ -1701,7 +1701,7 @@ static int32_t rewriteDatabaseFunc(STranslateContext* pCxt, SNode** pNode) { } static int32_t rewriteClentVersionFunc(STranslateContext* pCxt, SNode** pNode) { - char* pVer = taosMemoryStrDup((void*)version); + char* pVer = taosStrdup((void*)version); if (NULL == pVer) { return TSDB_CODE_OUT_OF_MEMORY; } @@ -1709,7 +1709,7 @@ static int32_t rewriteClentVersionFunc(STranslateContext* pCxt, SNode** pNode) { } static int32_t rewriteServerVersionFunc(STranslateContext* pCxt, SNode** pNode) { - char* pVer = taosMemoryStrDup((void*)pCxt->pParseCxt->svrVer); + char* pVer = taosStrdup((void*)pCxt->pParseCxt->svrVer); if (NULL == pVer) { return TSDB_CODE_OUT_OF_MEMORY; } @@ -1720,7 +1720,7 @@ static int32_t rewriteServerStatusFunc(STranslateContext* pCxt, SNode** pNode) { if (pCxt->pParseCxt->nodeOffline) { return TSDB_CODE_RPC_NETWORK_UNAVAIL; } - char* pStatus = taosMemoryStrDup((void*)"1"); + char* pStatus = taosStrdup((void*)"1"); return rewriteFuncToValue(pCxt, pStatus, pNode); } @@ -1728,7 +1728,7 @@ static int32_t rewriteUserFunc(STranslateContext* pCxt, SNode** pNode) { char userConn[TSDB_USER_LEN + 1 + TSDB_FQDN_LEN] = {0}; // format 'user@host' int32_t len = snprintf(userConn, sizeof(userConn), "%s@", pCxt->pParseCxt->pUser); taosGetFqdn(userConn + len); - char* pUserConn = taosMemoryStrDup((void*)userConn); + char* pUserConn = taosStrdup((void*)userConn); if (NULL == pUserConn) { return TSDB_CODE_OUT_OF_MEMORY; } @@ -4910,7 +4910,7 @@ static int32_t buildCreateStbReq(STranslateContext* pCxt, SCreateTableStmt* pStm pReq->numOfColumns = LIST_LENGTH(pStmt->pCols); pReq->numOfTags = LIST_LENGTH(pStmt->pTags); if (pStmt->pOptions->commentNull == false) { - pReq->pComment = strdup(pStmt->pOptions->comment); + pReq->pComment = taosStrdup(pStmt->pOptions->comment); if (NULL == pReq->pComment) { return TSDB_CODE_OUT_OF_MEMORY; } @@ -4978,7 +4978,7 @@ static int32_t buildAlterSuperTableReq(STranslateContext* pCxt, SAlterTableStmt* if (TSDB_ALTER_TABLE_UPDATE_OPTIONS == pStmt->alterType) { // pAlterReq->ttl = pStmt->pOptions->ttl; if (pStmt->pOptions->commentNull == false) { - pAlterReq->comment = strdup(pStmt->pOptions->comment); + pAlterReq->comment = taosStrdup(pStmt->pOptions->comment); if (NULL == pAlterReq->comment) { return TSDB_CODE_OUT_OF_MEMORY; } @@ -5092,14 +5092,24 @@ static int32_t checkAlterSuperTableBySchema(STranslateContext* pCxt, SAlterTable return generateSyntaxErrMsg(&pCxt->msgBuf, TSDB_CODE_PAR_INVALID_MODIFY_COL); } - if (TSDB_ALTER_TABLE_UPDATE_COLUMN_BYTES == pStmt->alterType && - pTableMeta->tableInfo.rowSize + calcTypeBytes(pStmt->dataType) - pSchema->bytes > TSDB_MAX_BYTES_PER_ROW) { - return generateSyntaxErrMsg(&pCxt->msgBuf, TSDB_CODE_PAR_INVALID_ROW_LENGTH, TSDB_MAX_BYTES_PER_ROW); + if (TSDB_ALTER_TABLE_UPDATE_COLUMN_BYTES == pStmt->alterType) { + if (calcTypeBytes(pStmt->dataType) > TSDB_MAX_FIELD_LEN) { + return generateSyntaxErrMsg(&pCxt->msgBuf, TSDB_CODE_PAR_INVALID_VAR_COLUMN_LEN); + } + + if (pTableMeta->tableInfo.rowSize + calcTypeBytes(pStmt->dataType) - pSchema->bytes > TSDB_MAX_BYTES_PER_ROW) { + return generateSyntaxErrMsg(&pCxt->msgBuf, TSDB_CODE_PAR_INVALID_ROW_LENGTH, TSDB_MAX_BYTES_PER_ROW); + } } - if (TSDB_ALTER_TABLE_UPDATE_TAG_BYTES == pStmt->alterType && - tagsLen + calcTypeBytes(pStmt->dataType) - pSchema->bytes > TSDB_MAX_TAGS_LEN) { - return generateSyntaxErrMsg(&pCxt->msgBuf, TSDB_CODE_PAR_INVALID_TAGS_LENGTH, TSDB_MAX_TAGS_LEN); + if (TSDB_ALTER_TABLE_UPDATE_TAG_BYTES == pStmt->alterType) { + if (calcTypeBytes(pStmt->dataType) > TSDB_MAX_FIELD_LEN) { + return generateSyntaxErrMsg(&pCxt->msgBuf, TSDB_CODE_PAR_INVALID_VAR_COLUMN_LEN); + } + + if (tagsLen + calcTypeBytes(pStmt->dataType) - pSchema->bytes > TSDB_MAX_TAGS_LEN) { + return generateSyntaxErrMsg(&pCxt->msgBuf, TSDB_CODE_PAR_INVALID_TAGS_LENGTH, TSDB_MAX_TAGS_LEN); + } } } @@ -5267,7 +5277,7 @@ static int32_t getSmaIndexDstVgId(STranslateContext* pCxt, const char* pDbName, } static int32_t getSmaIndexSql(STranslateContext* pCxt, char** pSql, int32_t* pLen) { - *pSql = strdup(pCxt->pParseCxt->pSql); + *pSql = taosStrdup(pCxt->pParseCxt->pSql); if (NULL == *pSql) { return TSDB_CODE_OUT_OF_MEMORY; } @@ -5505,7 +5515,7 @@ static int32_t buildCreateTopicReq(STranslateContext* pCxt, SCreateTopicStmt* pS pReq->igExists = pStmt->ignoreExists; pReq->withMeta = pStmt->withMeta; - pReq->sql = strdup(pCxt->pParseCxt->pSql); + pReq->sql = taosStrdup(pCxt->pParseCxt->pSql); if (NULL == pReq->sql) { return TSDB_CODE_OUT_OF_MEMORY; } @@ -5953,6 +5963,7 @@ static int32_t adjustOrderOfProjections(STranslateContext* pCxt, SNodeList* pCol } int32_t code = TSDB_CODE_SUCCESS; + bool hasPrimaryKey = false; SNode* pCol = NULL; SNode* pProj = NULL; FORBOTH(pCol, pCols, pProj, *pProjections) { @@ -5966,6 +5977,14 @@ static int32_t adjustOrderOfProjections(STranslateContext* pCxt, SNodeList* pCol if (TSDB_CODE_SUCCESS != code) { break; } + if (PRIMARYKEY_TIMESTAMP_COL_ID == pSchema->colId) { + hasPrimaryKey = true; + } + } + + if (TSDB_CODE_SUCCESS == code && !hasPrimaryKey) { + code = generateSyntaxErrMsgExt(&pCxt->msgBuf, TSDB_CODE_PAR_INVALID_COLUMNS_NUM, + "primary timestamp column can not be null"); } SNodeList* pNewProjections = NULL; @@ -6008,7 +6027,15 @@ static int32_t adjustProjectionsForExistTable(STranslateContext* pCxt, SCreateSt return adjustOrderOfProjections(pCxt, pStmt->pCols, pMeta, &pSelect->pProjectionList, pReq); } +static bool isGroupIdTagStream(const STableMeta* pMeta, SNodeList* pTags) { + return (NULL == pTags && 1 == pMeta->tableInfo.numOfTags && TSDB_DATA_TYPE_UBIGINT == getTableTagSchema(pMeta)->type); +} + static int32_t adjustDataTypeOfTags(STranslateContext* pCxt, const STableMeta* pMeta, SNodeList* pTags) { + if (isGroupIdTagStream(pMeta, pTags)) { + return TSDB_CODE_SUCCESS; + } + if (getNumOfTags(pMeta) != LIST_LENGTH(pTags)) { return generateSyntaxErrMsgExt(&pCxt->msgBuf, TSDB_CODE_PAR_INVALID_COLUMNS_NUM, "Illegal number of tags"); } @@ -6235,7 +6262,7 @@ static int32_t buildCreateStreamReq(STranslateContext* pCxt, SCreateStreamStmt* int32_t code = buildCreateStreamQuery(pCxt, pStmt, pReq); if (TSDB_CODE_SUCCESS == code) { - pReq->sql = strdup(pCxt->pParseCxt->pSql); + pReq->sql = taosStrdup(pCxt->pParseCxt->pSql); if (NULL == pReq->sql) { code = TSDB_CODE_OUT_OF_MEMORY; } @@ -7127,10 +7154,10 @@ static int32_t buildNormalTableBatchReq(int32_t acctId, const SCreateTableStmt* SVCreateTbReq req = {0}; req.type = TD_NORMAL_TABLE; - req.name = strdup(pStmt->tableName); + req.name = taosStrdup(pStmt->tableName); req.ttl = pStmt->pOptions->ttl; if (pStmt->pOptions->commentNull == false) { - req.comment = strdup(pStmt->pOptions->comment); + req.comment = taosStrdup(pStmt->pOptions->comment); if (NULL == req.comment) { tdDestroySVCreateTbReq(&req); return TSDB_CODE_OUT_OF_MEMORY; @@ -7289,17 +7316,17 @@ static void addCreateTbReqIntoVgroup(int32_t acctId, SHashObj* pVgroupHashmap, S struct SVCreateTbReq req = {0}; req.type = TD_CHILD_TABLE; - req.name = strdup(pStmt->tableName); + req.name = taosStrdup(pStmt->tableName); req.ttl = pStmt->pOptions->ttl; if (pStmt->pOptions->commentNull == false) { - req.comment = strdup(pStmt->pOptions->comment); + req.comment = taosStrdup(pStmt->pOptions->comment); req.commentLen = strlen(pStmt->pOptions->comment); } else { req.commentLen = -1; } req.ctb.suid = suid; req.ctb.tagNum = tagNum; - req.ctb.stbName = strdup(sTableNmae); + req.ctb.stbName = taosStrdup(sTableNmae); req.ctb.pTag = (uint8_t*)pTag; req.ctb.tagName = taosArrayDup(tagName, NULL); if (pStmt->ignoreExists) { @@ -7781,7 +7808,7 @@ static int32_t buildUpdateTagValReq(STranslateContext* pCxt, SAlterTableStmt* pS pStmt->colName); } - pReq->tagName = strdup(pStmt->colName); + pReq->tagName = taosStrdup(pStmt->colName); if (NULL == pReq->tagName) { return TSDB_CODE_OUT_OF_MEMORY; } @@ -7854,7 +7881,7 @@ static int32_t buildAddColReq(STranslateContext* pCxt, SAlterTableStmt* pStmt, S return generateSyntaxErrMsg(&pCxt->msgBuf, TSDB_CODE_PAR_INVALID_ROW_LENGTH, TSDB_MAX_BYTES_PER_ROW); } - pReq->colName = strdup(pStmt->colName); + pReq->colName = taosStrdup(pStmt->colName); if (NULL == pReq->colName) { return TSDB_CODE_OUT_OF_MEMORY; } @@ -7877,7 +7904,7 @@ static int32_t buildDropColReq(STranslateContext* pCxt, SAlterTableStmt* pStmt, return generateSyntaxErrMsg(&pCxt->msgBuf, TSDB_CODE_PAR_CANNOT_DROP_PRIMARY_KEY); } - pReq->colName = strdup(pStmt->colName); + pReq->colName = taosStrdup(pStmt->colName); if (NULL == pReq->colName) { return TSDB_CODE_OUT_OF_MEMORY; } @@ -7902,7 +7929,7 @@ static int32_t buildUpdateColReq(STranslateContext* pCxt, SAlterTableStmt* pStmt return generateSyntaxErrMsg(&pCxt->msgBuf, TSDB_CODE_PAR_INVALID_ROW_LENGTH, TSDB_MAX_BYTES_PER_ROW); } - pReq->colName = strdup(pStmt->colName); + pReq->colName = taosStrdup(pStmt->colName); if (NULL == pReq->colName) { return TSDB_CODE_OUT_OF_MEMORY; } @@ -7920,8 +7947,8 @@ static int32_t buildRenameColReq(STranslateContext* pCxt, SAlterTableStmt* pStmt return generateSyntaxErrMsg(&pCxt->msgBuf, TSDB_CODE_PAR_DUPLICATED_COLUMN); } - pReq->colName = strdup(pStmt->colName); - pReq->colNewName = strdup(pStmt->newColName); + pReq->colName = taosStrdup(pStmt->colName); + pReq->colNewName = taosStrdup(pStmt->newColName); if (NULL == pReq->colName || NULL == pReq->colNewName) { return TSDB_CODE_OUT_OF_MEMORY; } @@ -7938,7 +7965,7 @@ static int32_t buildUpdateOptionsReq(STranslateContext* pCxt, SAlterTableStmt* p if (TSDB_CODE_SUCCESS == code) { if (pStmt->pOptions->commentNull == false) { - pReq->newComment = strdup(pStmt->pOptions->comment); + pReq->newComment = taosStrdup(pStmt->pOptions->comment); if (NULL == pReq->newComment) { code = TSDB_CODE_OUT_OF_MEMORY; } else { @@ -7954,7 +7981,7 @@ static int32_t buildUpdateOptionsReq(STranslateContext* pCxt, SAlterTableStmt* p static int32_t buildAlterTbReq(STranslateContext* pCxt, SAlterTableStmt* pStmt, STableMeta* pTableMeta, SVAlterTbReq* pReq) { - pReq->tbName = strdup(pStmt->tableName); + pReq->tbName = taosStrdup(pStmt->tableName); if (NULL == pReq->tbName) { return TSDB_CODE_OUT_OF_MEMORY; } diff --git a/source/libs/parser/src/parUtil.c b/source/libs/parser/src/parUtil.c index fa091901b6..89a42cb03c 100644 --- a/source/libs/parser/src/parUtil.c +++ b/source/libs/parser/src/parUtil.c @@ -971,7 +971,7 @@ static SArray* smaIndexesDup(SArray* pSrc) { } for (int32_t i = 0; i < size; ++i) { STableIndexInfo* pIndex = taosArrayGet(pDst, i); - pIndex->expr = taosMemoryStrDup(((STableIndexInfo*)taosArrayGet(pSrc, i))->expr); + pIndex->expr = taosStrdup(((STableIndexInfo*)taosArrayGet(pSrc, i))->expr); if (NULL == pIndex->expr) { taosArrayDestroyEx(pDst, destroySmaIndex); return NULL; diff --git a/source/libs/parser/src/sql.c b/source/libs/parser/src/sql.c index f38233aa76..b6940f8395 100644 --- a/source/libs/parser/src/sql.c +++ b/source/libs/parser/src/sql.c @@ -139,17 +139,17 @@ typedef union { #define ParseCTX_FETCH #define ParseCTX_STORE #define YYFALLBACK 1 -#define YYNSTATE 742 +#define YYNSTATE 743 #define YYNRULE 563 #define YYNTOKEN 328 -#define YY_MAX_SHIFT 741 -#define YY_MIN_SHIFTREDUCE 1101 -#define YY_MAX_SHIFTREDUCE 1663 -#define YY_ERROR_ACTION 1664 -#define YY_ACCEPT_ACTION 1665 -#define YY_NO_ACTION 1666 -#define YY_MIN_REDUCE 1667 -#define YY_MAX_REDUCE 2229 +#define YY_MAX_SHIFT 742 +#define YY_MIN_SHIFTREDUCE 1102 +#define YY_MAX_SHIFTREDUCE 1664 +#define YY_ERROR_ACTION 1665 +#define YY_ACCEPT_ACTION 1666 +#define YY_NO_ACTION 1667 +#define YY_MIN_REDUCE 1668 +#define YY_MAX_REDUCE 2230 /************* End control #defines *******************************************/ #define YY_NLOOKAHEAD ((int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0]))) @@ -218,281 +218,281 @@ typedef union { *********** Begin parsing tables **********************************************/ #define YY_ACTTAB_COUNT (2749) static const YYACTIONTYPE yy_action[] = { - /* 0 */ 1940, 2205, 1799, 606, 481, 2200, 482, 1703, 490, 1810, - /* 10 */ 482, 1703, 45, 43, 1591, 1938, 618, 31, 176, 178, - /* 20 */ 379, 2204, 1440, 38, 37, 2201, 2203, 44, 42, 41, - /* 30 */ 40, 39, 1861, 1521, 140, 1438, 1465, 2041, 1874, 347, - /* 40 */ 1923, 2027, 38, 37, 612, 357, 44, 42, 41, 40, - /* 50 */ 39, 424, 2023, 2205, 1872, 38, 37, 2200, 1516, 44, - /* 60 */ 42, 41, 40, 39, 18, 499, 384, 1468, 2059, 1867, - /* 70 */ 1869, 1446, 1665, 2204, 167, 606, 645, 2201, 2202, 1775, - /* 80 */ 1153, 2009, 1152, 647, 45, 43, 2019, 2025, 360, 569, - /* 90 */ 1134, 330, 379, 2200, 1440, 220, 14, 641, 340, 181, - /* 100 */ 2137, 2138, 549, 138, 2142, 1521, 140, 1438, 2206, 182, - /* 110 */ 601, 1154, 2040, 2201, 595, 547, 2076, 545, 738, 324, - /* 120 */ 2042, 651, 2044, 2045, 646, 644, 641, 632, 2094, 1136, - /* 130 */ 1516, 1139, 1140, 1523, 1524, 630, 18, 480, 392, 1550, - /* 140 */ 485, 1709, 391, 1446, 1690, 1261, 673, 672, 671, 1265, - /* 150 */ 670, 1267, 1268, 669, 1270, 666, 176, 1276, 663, 1278, - /* 160 */ 1279, 660, 657, 1496, 1506, 1940, 606, 616, 14, 1522, - /* 170 */ 1525, 267, 2137, 605, 382, 133, 604, 370, 1924, 2200, - /* 180 */ 1937, 618, 161, 569, 1441, 617, 1439, 2200, 2009, 358, - /* 190 */ 738, 1823, 630, 270, 593, 182, 1551, 140, 1872, 2201, - /* 200 */ 595, 499, 2206, 182, 630, 1523, 1524, 2201, 595, 589, - /* 210 */ 1444, 1445, 247, 1495, 1498, 1499, 1500, 1501, 1502, 1503, - /* 220 */ 1504, 1505, 643, 639, 1514, 1515, 1517, 1518, 1519, 1520, - /* 230 */ 2, 61, 497, 92, 1933, 1496, 1506, 584, 106, 685, - /* 240 */ 122, 1522, 1525, 121, 120, 119, 118, 117, 116, 115, - /* 250 */ 114, 113, 141, 1595, 351, 166, 1441, 1679, 1439, 1465, - /* 260 */ 1813, 608, 180, 2137, 2138, 1464, 138, 2142, 48, 34, - /* 270 */ 377, 1545, 1546, 1547, 1548, 1549, 1553, 1554, 1555, 1556, - /* 280 */ 48, 61, 1444, 1445, 1221, 1495, 1498, 1499, 1500, 1501, - /* 290 */ 1502, 1503, 1504, 1505, 643, 639, 1514, 1515, 1517, 1518, - /* 300 */ 1519, 1520, 2, 2027, 11, 45, 43, 44, 42, 41, - /* 310 */ 40, 39, 1465, 379, 2023, 1440, 352, 741, 350, 349, - /* 320 */ 1223, 522, 590, 585, 578, 524, 1521, 1465, 1438, 489, - /* 330 */ 2041, 295, 485, 1709, 606, 35, 288, 38, 37, 602, - /* 340 */ 411, 44, 42, 41, 40, 39, 175, 523, 2019, 2025, - /* 350 */ 361, 1516, 731, 727, 723, 719, 293, 18, 86, 641, - /* 360 */ 487, 2059, 413, 409, 1446, 140, 483, 558, 416, 648, - /* 370 */ 415, 2144, 136, 1153, 2009, 1152, 647, 45, 43, 1526, - /* 380 */ 1466, 1816, 2205, 185, 11, 379, 9, 1440, 61, 14, - /* 390 */ 279, 280, 65, 107, 414, 278, 286, 2141, 1521, 1467, - /* 400 */ 1438, 633, 1497, 2101, 1154, 2040, 1736, 631, 1689, 2076, - /* 410 */ 631, 738, 168, 2042, 651, 2044, 2045, 646, 1668, 641, - /* 420 */ 185, 132, 677, 1516, 187, 1865, 1523, 1524, 520, 627, - /* 430 */ 183, 2137, 2138, 185, 138, 2142, 1446, 631, 1821, 122, - /* 440 */ 11, 1821, 121, 120, 119, 118, 117, 116, 115, 114, - /* 450 */ 113, 132, 2009, 570, 2166, 194, 1496, 1506, 525, 1874, - /* 460 */ 100, 46, 1522, 1525, 273, 635, 367, 2101, 1821, 272, - /* 470 */ 1359, 1360, 535, 534, 533, 1872, 1653, 1441, 1797, 1439, - /* 480 */ 137, 529, 1814, 738, 61, 528, 1403, 462, 241, 1904, - /* 490 */ 527, 532, 83, 1304, 1305, 82, 526, 237, 1523, 1524, - /* 500 */ 1868, 1869, 1466, 1444, 1445, 1660, 1495, 1498, 1499, 1500, - /* 510 */ 1501, 1502, 1503, 1504, 1505, 643, 639, 1514, 1515, 1517, - /* 520 */ 1518, 1519, 1520, 2, 535, 534, 533, 1446, 1496, 1506, - /* 530 */ 1667, 1874, 137, 529, 1522, 1525, 631, 528, 345, 631, - /* 540 */ 185, 685, 527, 532, 269, 198, 197, 1872, 526, 1441, - /* 550 */ 54, 1439, 617, 422, 131, 130, 129, 128, 127, 126, - /* 560 */ 125, 124, 123, 1414, 1415, 418, 676, 1821, 461, 417, - /* 570 */ 1821, 41, 40, 39, 2041, 1444, 1445, 617, 1495, 1498, - /* 580 */ 1499, 1500, 1501, 1502, 1503, 1504, 1505, 643, 639, 1514, - /* 590 */ 1515, 1517, 1518, 1519, 1520, 2, 45, 43, 1467, 615, - /* 600 */ 1919, 1933, 86, 1659, 379, 2059, 1440, 631, 594, 631, - /* 610 */ 569, 190, 2200, 648, 2200, 1376, 1377, 1521, 2009, 1438, - /* 620 */ 647, 423, 221, 432, 626, 1817, 1933, 593, 182, 2206, - /* 630 */ 182, 61, 2201, 595, 2201, 595, 185, 171, 1821, 1688, - /* 640 */ 1821, 442, 1516, 516, 512, 508, 504, 218, 631, 2040, - /* 650 */ 441, 1375, 1378, 2076, 1619, 1446, 110, 2042, 651, 2044, - /* 660 */ 2045, 646, 447, 641, 49, 371, 1531, 1687, 45, 43, - /* 670 */ 2129, 2204, 1465, 164, 2128, 2125, 379, 697, 1440, 1821, - /* 680 */ 46, 540, 1823, 2009, 87, 1686, 2144, 216, 1806, 1521, - /* 690 */ 1685, 1438, 142, 38, 37, 2100, 550, 44, 42, 41, - /* 700 */ 40, 39, 738, 581, 580, 1617, 1618, 1620, 1621, 1622, - /* 710 */ 234, 2009, 2140, 1684, 1516, 38, 37, 1523, 1524, 44, - /* 720 */ 42, 41, 40, 39, 236, 543, 33, 1446, 235, 2009, - /* 730 */ 537, 1798, 38, 37, 2009, 233, 44, 42, 41, 40, - /* 740 */ 39, 1683, 594, 269, 1552, 2144, 2200, 1496, 1506, 1874, - /* 750 */ 631, 27, 14, 1522, 1525, 215, 209, 2009, 13, 12, - /* 760 */ 214, 593, 182, 495, 448, 1873, 2201, 595, 1441, 382, - /* 770 */ 1439, 2139, 69, 1588, 738, 68, 2059, 164, 1682, 207, - /* 780 */ 1808, 1821, 1630, 185, 588, 2009, 1823, 89, 335, 1523, - /* 790 */ 1524, 356, 1977, 551, 1444, 1445, 1468, 1495, 1498, 1499, - /* 800 */ 1500, 1501, 1502, 1503, 1504, 1505, 643, 639, 1514, 1515, - /* 810 */ 1517, 1518, 1519, 1520, 2, 1497, 185, 32, 1804, 1496, - /* 820 */ 1506, 333, 2009, 1463, 683, 1522, 1525, 1557, 164, 587, - /* 830 */ 455, 709, 707, 469, 1874, 152, 468, 1824, 238, 683, - /* 840 */ 1441, 372, 1439, 154, 153, 680, 679, 678, 151, 1681, - /* 850 */ 1872, 438, 1678, 470, 1564, 675, 440, 1919, 154, 153, - /* 860 */ 680, 679, 678, 151, 531, 530, 1444, 1445, 192, 1495, - /* 870 */ 1498, 1499, 1500, 1501, 1502, 1503, 1504, 1505, 643, 639, - /* 880 */ 1514, 1515, 1517, 1518, 1519, 1520, 2, 698, 53, 1791, - /* 890 */ 631, 681, 165, 2009, 1865, 1677, 2009, 308, 348, 1733, - /* 900 */ 631, 38, 37, 1796, 498, 44, 42, 41, 40, 39, - /* 910 */ 428, 306, 72, 242, 1818, 71, 1676, 1919, 642, 38, - /* 920 */ 37, 1821, 1874, 44, 42, 41, 40, 39, 196, 383, - /* 930 */ 51, 1821, 3, 203, 477, 475, 472, 597, 1872, 2009, - /* 940 */ 466, 191, 524, 460, 459, 458, 457, 454, 453, 452, - /* 950 */ 451, 450, 446, 445, 444, 443, 332, 435, 434, 433, - /* 960 */ 2009, 430, 429, 346, 523, 715, 714, 713, 712, 389, - /* 970 */ 61, 711, 710, 144, 705, 704, 703, 702, 701, 700, - /* 980 */ 699, 156, 695, 694, 693, 388, 387, 690, 689, 688, - /* 990 */ 687, 686, 631, 631, 1675, 38, 37, 564, 2002, 44, - /* 1000 */ 42, 41, 40, 39, 1440, 631, 239, 565, 1607, 108, - /* 1010 */ 2041, 683, 1995, 631, 631, 631, 1468, 1438, 1587, 628, - /* 1020 */ 8, 1674, 1673, 1821, 1821, 1672, 1671, 629, 610, 614, - /* 1030 */ 154, 153, 680, 679, 678, 151, 1821, 682, 2009, 1465, - /* 1040 */ 1865, 2059, 1670, 569, 1821, 1821, 1821, 2200, 152, 609, - /* 1050 */ 80, 79, 421, 1446, 2009, 189, 647, 631, 163, 2041, - /* 1060 */ 399, 302, 2206, 182, 1851, 2009, 2009, 2201, 595, 2009, - /* 1070 */ 2009, 283, 598, 2027, 331, 1139, 1140, 407, 1449, 405, - /* 1080 */ 401, 397, 394, 414, 2023, 2040, 2009, 1680, 1821, 2076, - /* 1090 */ 2059, 1812, 109, 2042, 651, 2044, 2045, 646, 648, 641, - /* 1100 */ 738, 1409, 2023, 2009, 179, 647, 2129, 1776, 385, 631, - /* 1110 */ 373, 2125, 2149, 1584, 425, 638, 164, 2028, 2019, 2025, - /* 1120 */ 374, 631, 185, 386, 184, 1823, 2041, 426, 2023, 641, - /* 1130 */ 2003, 146, 2155, 134, 2040, 289, 2019, 2025, 2076, 1710, - /* 1140 */ 1821, 109, 2042, 651, 2044, 2045, 646, 641, 641, 2169, - /* 1150 */ 152, 143, 1821, 149, 2100, 2129, 245, 2059, 2041, 373, - /* 1160 */ 2125, 246, 2019, 2025, 73, 609, 1441, 2030, 1439, 1723, - /* 1170 */ 2009, 226, 647, 641, 224, 569, 1716, 228, 230, 2200, - /* 1180 */ 227, 229, 1497, 232, 1714, 553, 231, 552, 733, 2059, - /* 1190 */ 264, 536, 1444, 1445, 2206, 182, 90, 648, 538, 2201, - /* 1200 */ 595, 2040, 2009, 1412, 647, 2076, 541, 2041, 109, 2042, - /* 1210 */ 651, 2044, 2045, 646, 81, 641, 2032, 63, 63, 251, - /* 1220 */ 179, 152, 2129, 1662, 1663, 52, 373, 2125, 1584, 1452, - /* 1230 */ 47, 276, 568, 2040, 70, 13, 12, 2076, 2059, 1448, - /* 1240 */ 109, 2042, 651, 2044, 2045, 646, 648, 641, 2156, 1183, - /* 1250 */ 582, 2009, 2220, 647, 2129, 105, 150, 556, 373, 2125, - /* 1260 */ 152, 1542, 63, 47, 47, 102, 2041, 219, 258, 2163, - /* 1270 */ 1616, 1615, 253, 691, 613, 655, 150, 152, 2060, 135, - /* 1280 */ 150, 390, 2040, 1373, 281, 1184, 2076, 623, 1704, 109, - /* 1290 */ 2042, 651, 2044, 2045, 646, 1202, 641, 2059, 692, 599, - /* 1300 */ 2041, 2220, 569, 2129, 1928, 648, 2200, 373, 2125, 285, - /* 1310 */ 2009, 1862, 647, 1254, 2159, 1558, 1507, 301, 2176, 607, - /* 1320 */ 1200, 2206, 182, 263, 266, 1, 2201, 595, 1282, 1286, - /* 1330 */ 1293, 2059, 1291, 155, 4, 393, 398, 344, 1396, 648, - /* 1340 */ 296, 2040, 195, 427, 2009, 2076, 647, 1468, 109, 2042, - /* 1350 */ 651, 2044, 2045, 646, 431, 641, 1929, 464, 436, 1463, - /* 1360 */ 2220, 449, 2129, 1921, 463, 456, 373, 2125, 465, 473, - /* 1370 */ 471, 200, 474, 2041, 476, 2040, 478, 576, 1469, 2076, - /* 1380 */ 479, 488, 109, 2042, 651, 2044, 2045, 646, 1471, 641, - /* 1390 */ 1451, 491, 376, 375, 2220, 206, 2129, 1466, 492, 208, - /* 1400 */ 373, 2125, 1454, 1470, 2059, 493, 1472, 211, 494, 496, - /* 1410 */ 517, 2194, 648, 1521, 1156, 1447, 518, 2009, 213, 647, - /* 1420 */ 84, 85, 2041, 521, 500, 217, 519, 1986, 1811, 223, - /* 1430 */ 334, 1983, 1807, 112, 225, 297, 555, 88, 1516, 1982, - /* 1440 */ 559, 157, 148, 158, 1809, 557, 240, 243, 2040, 1805, - /* 1450 */ 159, 1446, 2076, 2059, 566, 109, 2042, 651, 2044, 2045, - /* 1460 */ 646, 648, 641, 160, 583, 2175, 2009, 2220, 647, 2129, - /* 1470 */ 621, 2160, 2174, 373, 2125, 573, 563, 7, 2151, 592, - /* 1480 */ 579, 2170, 362, 586, 2148, 574, 2041, 257, 572, 571, - /* 1490 */ 172, 260, 249, 259, 603, 560, 600, 2040, 637, 252, - /* 1500 */ 363, 2076, 1584, 139, 109, 2042, 651, 2044, 2045, 646, - /* 1510 */ 265, 641, 1467, 271, 2223, 2199, 2104, 2059, 2129, 262, - /* 1520 */ 611, 95, 373, 2125, 2145, 648, 1473, 298, 366, 1934, - /* 1530 */ 2009, 624, 647, 619, 299, 620, 1948, 1947, 1946, 369, - /* 1540 */ 625, 97, 99, 300, 60, 101, 2110, 1866, 653, 1822, - /* 1550 */ 292, 734, 1792, 327, 2041, 2001, 261, 336, 337, 312, - /* 1560 */ 737, 2040, 735, 303, 1455, 2076, 1450, 2000, 109, 2042, - /* 1570 */ 651, 2044, 2045, 646, 305, 641, 307, 50, 1999, 77, - /* 1580 */ 2102, 1996, 2129, 395, 2041, 2059, 373, 2125, 396, 1431, - /* 1590 */ 1458, 1460, 1432, 648, 188, 326, 316, 400, 2009, 1994, - /* 1600 */ 647, 404, 1993, 639, 1514, 1515, 1517, 1518, 1519, 1520, - /* 1610 */ 402, 403, 406, 1992, 2041, 2059, 1991, 408, 410, 1990, - /* 1620 */ 412, 78, 1399, 648, 1398, 1960, 1959, 1958, 2009, 2040, - /* 1630 */ 647, 419, 420, 2076, 1957, 1956, 109, 2042, 651, 2044, - /* 1640 */ 2045, 646, 1350, 641, 2041, 2059, 1912, 1911, 634, 1909, - /* 1650 */ 2129, 145, 1908, 648, 373, 2125, 1907, 1910, 2009, 2040, - /* 1660 */ 647, 1906, 1905, 2076, 193, 437, 110, 2042, 651, 2044, - /* 1670 */ 2045, 646, 1903, 641, 1902, 2059, 1901, 1900, 2041, 439, - /* 1680 */ 2129, 1914, 1899, 648, 636, 2125, 1898, 1897, 2009, 649, - /* 1690 */ 647, 1896, 1895, 2076, 1894, 1893, 110, 2042, 651, 2044, - /* 1700 */ 2045, 646, 1892, 641, 1891, 2041, 1890, 1889, 1888, 2059, - /* 1710 */ 2129, 1887, 1886, 1885, 339, 2125, 1884, 648, 1883, 2040, - /* 1720 */ 147, 1882, 2009, 2076, 647, 1913, 169, 2042, 651, 2044, - /* 1730 */ 2045, 646, 1881, 641, 1880, 1879, 2059, 1352, 1878, 1877, - /* 1740 */ 467, 1876, 1875, 1739, 648, 1229, 199, 1738, 201, 2009, - /* 1750 */ 1737, 647, 2029, 2040, 2041, 202, 1735, 2076, 1699, 204, - /* 1760 */ 168, 2042, 651, 2044, 2045, 646, 75, 641, 177, 1142, - /* 1770 */ 484, 1141, 1698, 486, 1973, 1967, 205, 1955, 596, 2221, - /* 1780 */ 2040, 212, 1954, 76, 2076, 2059, 1932, 110, 2042, 651, - /* 1790 */ 2044, 2045, 646, 648, 641, 1800, 1176, 1734, 2009, 210, - /* 1800 */ 647, 2129, 2167, 1732, 501, 503, 2126, 502, 1730, 506, - /* 1810 */ 507, 505, 1728, 509, 1726, 510, 2041, 1713, 513, 511, - /* 1820 */ 515, 514, 1712, 1695, 1802, 62, 1298, 1297, 1801, 2040, - /* 1830 */ 1724, 222, 706, 2076, 1220, 1219, 318, 2042, 651, 2044, - /* 1840 */ 2045, 646, 1218, 641, 1217, 1214, 708, 2059, 2041, 1212, - /* 1850 */ 1213, 1211, 1717, 353, 354, 648, 539, 1715, 355, 1694, - /* 1860 */ 2009, 542, 647, 1693, 544, 1692, 548, 111, 546, 1419, - /* 1870 */ 1421, 1972, 1418, 1405, 55, 1966, 561, 1953, 1951, 2059, - /* 1880 */ 591, 1423, 2205, 26, 368, 66, 162, 648, 16, 244, - /* 1890 */ 19, 2040, 2009, 1632, 647, 2076, 575, 2041, 169, 2042, - /* 1900 */ 651, 2044, 2045, 646, 577, 641, 567, 28, 58, 248, - /* 1910 */ 562, 359, 5, 59, 2041, 250, 1614, 170, 255, 256, - /* 1920 */ 6, 254, 20, 2040, 30, 64, 1647, 2076, 2059, 2030, - /* 1930 */ 325, 2042, 651, 2044, 2045, 646, 645, 641, 29, 21, - /* 1940 */ 1606, 2009, 1652, 647, 91, 2059, 2041, 1653, 17, 1646, - /* 1950 */ 378, 2222, 364, 648, 1651, 1650, 365, 1581, 2009, 1580, - /* 1960 */ 647, 1952, 57, 268, 1950, 56, 1949, 1931, 94, 93, - /* 1970 */ 173, 2041, 2040, 274, 1930, 96, 2076, 2059, 287, 324, - /* 1980 */ 2042, 651, 2044, 2045, 646, 648, 641, 275, 2095, 2040, - /* 1990 */ 2009, 1612, 647, 2076, 102, 2041, 325, 2042, 651, 2044, - /* 2000 */ 2045, 646, 2059, 641, 22, 277, 282, 380, 622, 67, - /* 2010 */ 648, 12, 23, 1456, 1543, 2009, 1533, 647, 174, 284, - /* 2020 */ 2041, 554, 1511, 98, 1532, 2076, 2059, 10, 320, 2042, - /* 2030 */ 651, 2044, 2045, 646, 648, 641, 2079, 640, 36, 2009, - /* 2040 */ 1509, 647, 1508, 1480, 15, 24, 2040, 186, 1488, 25, - /* 2050 */ 2076, 2059, 654, 325, 2042, 651, 2044, 2045, 646, 648, - /* 2060 */ 641, 650, 652, 381, 2009, 656, 647, 1283, 658, 659, - /* 2070 */ 2040, 661, 1280, 1277, 2076, 662, 664, 309, 2042, 651, - /* 2080 */ 2044, 2045, 646, 2041, 641, 1271, 665, 667, 1260, 1269, - /* 2090 */ 668, 674, 290, 103, 104, 2040, 1292, 1275, 1274, 2076, - /* 2100 */ 1273, 1272, 310, 2042, 651, 2044, 2045, 646, 74, 641, - /* 2110 */ 2041, 1288, 1174, 684, 2059, 1208, 1207, 1206, 1205, 291, - /* 2120 */ 1204, 1203, 648, 1201, 1227, 1199, 1198, 2009, 1197, 647, - /* 2130 */ 696, 1195, 2041, 1194, 1193, 1192, 1191, 1190, 1189, 1224, - /* 2140 */ 1222, 2059, 1186, 1185, 1182, 1181, 1180, 1179, 1731, 648, - /* 2150 */ 716, 1729, 717, 718, 2009, 720, 647, 722, 2040, 1727, - /* 2160 */ 724, 726, 2076, 2059, 721, 311, 2042, 651, 2044, 2045, - /* 2170 */ 646, 648, 641, 1725, 725, 728, 2009, 729, 647, 1711, - /* 2180 */ 730, 732, 1131, 1691, 294, 2040, 736, 740, 1442, 2076, - /* 2190 */ 304, 739, 317, 2042, 651, 2044, 2045, 646, 1666, 641, - /* 2200 */ 1666, 1666, 1666, 1666, 1666, 1666, 1666, 2040, 1666, 1666, - /* 2210 */ 1666, 2076, 2041, 1666, 321, 2042, 651, 2044, 2045, 646, - /* 2220 */ 1666, 641, 1666, 1666, 1666, 1666, 1666, 1666, 1666, 2041, - /* 2230 */ 1666, 1666, 1666, 1666, 1666, 1666, 1666, 1666, 1666, 1666, - /* 2240 */ 1666, 1666, 1666, 2059, 1666, 1666, 2041, 1666, 1666, 1666, - /* 2250 */ 1666, 648, 1666, 1666, 1666, 1666, 2009, 1666, 647, 1666, - /* 2260 */ 2059, 1666, 1666, 1666, 1666, 1666, 1666, 1666, 648, 1666, - /* 2270 */ 1666, 1666, 1666, 2009, 1666, 647, 1666, 2059, 2041, 1666, - /* 2280 */ 1666, 1666, 1666, 1666, 1666, 648, 1666, 2040, 1666, 1666, - /* 2290 */ 2009, 2076, 647, 1666, 313, 2042, 651, 2044, 2045, 646, - /* 2300 */ 1666, 641, 1666, 2041, 2040, 1666, 1666, 1666, 2076, 2059, - /* 2310 */ 1666, 322, 2042, 651, 2044, 2045, 646, 648, 641, 1666, - /* 2320 */ 1666, 2040, 2009, 1666, 647, 2076, 1666, 2041, 314, 2042, - /* 2330 */ 651, 2044, 2045, 646, 2059, 641, 1666, 1666, 1666, 1666, - /* 2340 */ 1666, 1666, 648, 1666, 1666, 1666, 1666, 2009, 1666, 647, - /* 2350 */ 1666, 1666, 2041, 2040, 1666, 1666, 1666, 2076, 2059, 1666, - /* 2360 */ 323, 2042, 651, 2044, 2045, 646, 648, 641, 1666, 1666, - /* 2370 */ 1666, 2009, 1666, 647, 1666, 1666, 1666, 1666, 2040, 1666, - /* 2380 */ 1666, 1666, 2076, 2059, 1666, 315, 2042, 651, 2044, 2045, - /* 2390 */ 646, 648, 641, 1666, 1666, 1666, 2009, 1666, 647, 1666, - /* 2400 */ 1666, 1666, 2040, 1666, 1666, 1666, 2076, 1666, 1666, 328, - /* 2410 */ 2042, 651, 2044, 2045, 646, 2041, 641, 1666, 1666, 1666, - /* 2420 */ 1666, 1666, 1666, 1666, 1666, 1666, 1666, 2040, 1666, 1666, - /* 2430 */ 1666, 2076, 1666, 1666, 329, 2042, 651, 2044, 2045, 646, - /* 2440 */ 1666, 641, 2041, 1666, 1666, 1666, 2059, 1666, 1666, 1666, - /* 2450 */ 1666, 1666, 1666, 1666, 648, 1666, 1666, 1666, 1666, 2009, - /* 2460 */ 1666, 647, 1666, 1666, 2041, 1666, 1666, 1666, 1666, 1666, - /* 2470 */ 1666, 1666, 1666, 2059, 1666, 1666, 1666, 1666, 1666, 1666, - /* 2480 */ 1666, 648, 1666, 1666, 1666, 1666, 2009, 1666, 647, 1666, - /* 2490 */ 2040, 1666, 1666, 1666, 2076, 2059, 1666, 2053, 2042, 651, - /* 2500 */ 2044, 2045, 646, 648, 641, 1666, 1666, 1666, 2009, 1666, - /* 2510 */ 647, 1666, 1666, 1666, 1666, 1666, 1666, 2040, 1666, 1666, - /* 2520 */ 1666, 2076, 1666, 1666, 2052, 2042, 651, 2044, 2045, 646, - /* 2530 */ 1666, 641, 1666, 1666, 1666, 1666, 1666, 1666, 1666, 2040, - /* 2540 */ 1666, 1666, 1666, 2076, 2041, 1666, 2051, 2042, 651, 2044, - /* 2550 */ 2045, 646, 1666, 641, 1666, 1666, 1666, 1666, 1666, 1666, - /* 2560 */ 1666, 2041, 1666, 1666, 1666, 1666, 1666, 1666, 1666, 1666, - /* 2570 */ 1666, 1666, 1666, 1666, 1666, 2059, 1666, 1666, 2041, 1666, - /* 2580 */ 1666, 1666, 1666, 648, 1666, 1666, 1666, 1666, 2009, 1666, - /* 2590 */ 647, 1666, 2059, 1666, 1666, 1666, 1666, 1666, 1666, 1666, - /* 2600 */ 648, 1666, 1666, 1666, 1666, 2009, 1666, 647, 1666, 2059, - /* 2610 */ 2041, 1666, 1666, 1666, 1666, 1666, 1666, 648, 1666, 2040, - /* 2620 */ 1666, 1666, 2009, 2076, 647, 1666, 341, 2042, 651, 2044, - /* 2630 */ 2045, 646, 1666, 641, 1666, 2041, 2040, 1666, 1666, 1666, - /* 2640 */ 2076, 2059, 1666, 342, 2042, 651, 2044, 2045, 646, 648, - /* 2650 */ 641, 1666, 1666, 2040, 2009, 1666, 647, 2076, 1666, 2041, - /* 2660 */ 338, 2042, 651, 2044, 2045, 646, 2059, 641, 1666, 1666, - /* 2670 */ 1666, 1666, 1666, 1666, 648, 1666, 1666, 1666, 1666, 2009, - /* 2680 */ 1666, 647, 1666, 1666, 1666, 2040, 1666, 1666, 1666, 2076, - /* 2690 */ 2059, 1666, 343, 2042, 651, 2044, 2045, 646, 648, 641, - /* 2700 */ 1666, 1666, 1666, 2009, 1666, 647, 1666, 1666, 1666, 1666, - /* 2710 */ 649, 1666, 1666, 1666, 2076, 1666, 1666, 320, 2042, 651, - /* 2720 */ 2044, 2045, 646, 1666, 641, 1666, 1666, 1666, 1666, 1666, - /* 2730 */ 1666, 1666, 1666, 1666, 2040, 1666, 1666, 1666, 2076, 1666, - /* 2740 */ 1666, 319, 2042, 651, 2044, 2045, 646, 1666, 641, + /* 0 */ 1941, 2206, 1798, 607, 482, 2201, 483, 1704, 491, 1811, + /* 10 */ 483, 1704, 45, 43, 1592, 1939, 619, 31, 176, 178, + /* 20 */ 380, 2205, 1441, 38, 37, 2202, 2204, 44, 42, 41, + /* 30 */ 40, 39, 1862, 1522, 139, 1439, 1466, 2042, 1875, 347, + /* 40 */ 1924, 2028, 38, 37, 613, 358, 44, 42, 41, 40, + /* 50 */ 39, 425, 2024, 2206, 1873, 38, 37, 2201, 1517, 44, + /* 60 */ 42, 41, 40, 39, 18, 686, 385, 1469, 2060, 1868, + /* 70 */ 1870, 1447, 1666, 2205, 167, 607, 646, 2202, 2203, 1776, + /* 80 */ 1154, 2010, 1153, 648, 45, 43, 2020, 2026, 361, 570, + /* 90 */ 1135, 330, 380, 2201, 1441, 220, 14, 642, 340, 181, + /* 100 */ 2138, 2139, 550, 137, 2143, 1522, 139, 1439, 2207, 182, + /* 110 */ 602, 1155, 2041, 2202, 596, 548, 2077, 546, 739, 324, + /* 120 */ 2043, 652, 2045, 2046, 647, 645, 642, 633, 2095, 1137, + /* 130 */ 1517, 1140, 1141, 1524, 1525, 631, 18, 481, 393, 1551, + /* 140 */ 486, 1710, 392, 1447, 1691, 1262, 674, 673, 672, 1266, + /* 150 */ 671, 1268, 1269, 670, 1271, 667, 176, 1277, 664, 1279, + /* 160 */ 1280, 661, 658, 1497, 1507, 1941, 607, 617, 14, 1523, + /* 170 */ 1526, 267, 2138, 606, 383, 133, 605, 371, 1925, 2201, + /* 180 */ 1938, 619, 161, 570, 1442, 618, 1440, 2201, 2010, 359, + /* 190 */ 739, 1824, 631, 270, 594, 182, 1552, 139, 1873, 2202, + /* 200 */ 596, 500, 2207, 182, 631, 1524, 1525, 2202, 596, 590, + /* 210 */ 1445, 1446, 247, 1496, 1499, 1500, 1501, 1502, 1503, 1504, + /* 220 */ 1505, 1506, 644, 640, 1515, 1516, 1518, 1519, 1520, 1521, + /* 230 */ 2, 61, 498, 92, 1934, 1497, 1507, 585, 106, 686, + /* 240 */ 122, 1523, 1526, 121, 120, 119, 118, 117, 116, 115, + /* 250 */ 114, 113, 140, 1596, 352, 166, 1442, 1680, 1440, 1466, + /* 260 */ 1814, 609, 180, 2138, 2139, 1465, 137, 2143, 48, 34, + /* 270 */ 378, 1546, 1547, 1548, 1549, 1550, 1554, 1555, 1556, 1557, + /* 280 */ 48, 61, 1445, 1446, 1222, 1496, 1499, 1500, 1501, 1502, + /* 290 */ 1503, 1504, 1505, 1506, 644, 640, 1515, 1516, 1518, 1519, + /* 300 */ 1520, 1521, 2, 2028, 11, 45, 43, 44, 42, 41, + /* 310 */ 40, 39, 1466, 380, 2024, 1441, 353, 742, 351, 350, + /* 320 */ 1224, 523, 591, 586, 579, 525, 1522, 1466, 1439, 490, + /* 330 */ 2042, 295, 486, 1710, 607, 35, 288, 38, 37, 603, + /* 340 */ 412, 44, 42, 41, 40, 39, 175, 524, 2020, 2026, + /* 350 */ 362, 1517, 732, 728, 724, 720, 293, 18, 86, 642, + /* 360 */ 488, 2060, 414, 410, 1447, 139, 484, 559, 417, 649, + /* 370 */ 416, 2145, 349, 1154, 2010, 1153, 648, 45, 43, 1527, + /* 380 */ 1467, 1817, 2206, 185, 11, 380, 9, 1441, 61, 14, + /* 390 */ 279, 280, 65, 107, 415, 278, 286, 2142, 1522, 1468, + /* 400 */ 1439, 634, 1498, 2102, 1155, 2041, 1737, 632, 1690, 2077, + /* 410 */ 632, 739, 168, 2043, 652, 2045, 2046, 647, 1669, 642, + /* 420 */ 185, 132, 678, 1517, 187, 1866, 1524, 1525, 521, 628, + /* 430 */ 183, 2138, 2139, 185, 137, 2143, 1447, 632, 1822, 122, + /* 440 */ 11, 1822, 121, 120, 119, 118, 117, 116, 115, 114, + /* 450 */ 113, 132, 2010, 571, 2167, 194, 1497, 1507, 526, 1875, + /* 460 */ 100, 46, 1523, 1526, 273, 636, 368, 2102, 1822, 272, + /* 470 */ 1360, 1361, 536, 535, 534, 1873, 1654, 1442, 2031, 1440, + /* 480 */ 136, 530, 1815, 739, 61, 529, 1404, 463, 241, 1905, + /* 490 */ 528, 533, 83, 1305, 1306, 82, 527, 237, 1524, 1525, + /* 500 */ 1869, 1870, 1467, 1445, 1446, 1661, 1496, 1499, 1500, 1501, + /* 510 */ 1502, 1503, 1504, 1505, 1506, 644, 640, 1515, 1516, 1518, + /* 520 */ 1519, 1520, 1521, 2, 536, 535, 534, 2033, 1497, 1507, + /* 530 */ 1668, 1875, 136, 530, 1523, 1526, 632, 529, 345, 632, + /* 540 */ 185, 1447, 528, 533, 269, 198, 197, 1873, 527, 1442, + /* 550 */ 54, 1440, 618, 423, 131, 130, 129, 128, 127, 126, + /* 560 */ 125, 124, 123, 1415, 1416, 419, 677, 1822, 462, 418, + /* 570 */ 1822, 41, 40, 39, 2042, 1445, 1446, 618, 1496, 1499, + /* 580 */ 1500, 1501, 1502, 1503, 1504, 1505, 1506, 644, 640, 1515, + /* 590 */ 1516, 1518, 1519, 1520, 1521, 2, 45, 43, 1468, 616, + /* 600 */ 1920, 1934, 86, 1660, 380, 2060, 1441, 632, 595, 632, + /* 610 */ 570, 190, 2201, 649, 2201, 1377, 1378, 1522, 2010, 1439, + /* 620 */ 648, 424, 221, 433, 627, 1818, 1934, 594, 182, 2207, + /* 630 */ 182, 61, 2202, 596, 2202, 596, 185, 171, 1822, 1689, + /* 640 */ 1822, 443, 1517, 517, 513, 509, 505, 218, 632, 2041, + /* 650 */ 442, 1376, 1379, 2077, 1620, 1447, 110, 2043, 652, 2045, + /* 660 */ 2046, 647, 448, 642, 49, 372, 1532, 1688, 45, 43, + /* 670 */ 2130, 2205, 1466, 164, 2129, 2126, 380, 698, 1441, 1822, + /* 680 */ 46, 541, 1824, 2010, 87, 1687, 2145, 216, 1807, 1522, + /* 690 */ 1686, 1439, 141, 38, 37, 2101, 551, 44, 42, 41, + /* 700 */ 40, 39, 739, 582, 581, 1618, 1619, 1621, 1622, 1623, + /* 710 */ 234, 2010, 2141, 1685, 1517, 38, 37, 1524, 1525, 44, + /* 720 */ 42, 41, 40, 39, 236, 544, 33, 1447, 235, 2010, + /* 730 */ 538, 1799, 38, 37, 2010, 233, 44, 42, 41, 40, + /* 740 */ 39, 1684, 595, 269, 1553, 2145, 2201, 1497, 1507, 1875, + /* 750 */ 632, 27, 14, 1523, 1526, 215, 209, 2010, 13, 12, + /* 760 */ 214, 594, 182, 496, 449, 1874, 2202, 596, 1442, 383, + /* 770 */ 1440, 2140, 69, 1589, 739, 68, 2060, 164, 1683, 207, + /* 780 */ 1809, 1822, 1631, 185, 589, 2010, 1824, 89, 335, 1524, + /* 790 */ 1525, 357, 1978, 552, 1445, 1446, 1469, 1496, 1499, 1500, + /* 800 */ 1501, 1502, 1503, 1504, 1505, 1506, 644, 640, 1515, 1516, + /* 810 */ 1518, 1519, 1520, 1521, 2, 1498, 185, 32, 1805, 1497, + /* 820 */ 1507, 333, 2010, 1464, 684, 1523, 1526, 1558, 164, 588, + /* 830 */ 456, 710, 708, 470, 1875, 152, 469, 1825, 238, 684, + /* 840 */ 1442, 373, 1440, 154, 153, 681, 680, 679, 151, 1682, + /* 850 */ 1873, 439, 1679, 471, 1565, 676, 441, 1920, 154, 153, + /* 860 */ 681, 680, 679, 151, 532, 531, 1445, 1446, 192, 1496, + /* 870 */ 1499, 1500, 1501, 1502, 1503, 1504, 1505, 1506, 644, 640, + /* 880 */ 1515, 1516, 1518, 1519, 1520, 1521, 2, 699, 53, 1792, + /* 890 */ 632, 682, 165, 2010, 1866, 1678, 2010, 308, 348, 1734, + /* 900 */ 632, 38, 37, 1797, 499, 44, 42, 41, 40, 39, + /* 910 */ 429, 306, 72, 242, 1819, 71, 1677, 1920, 643, 38, + /* 920 */ 37, 1822, 1875, 44, 42, 41, 40, 39, 196, 384, + /* 930 */ 51, 1822, 3, 203, 478, 476, 473, 598, 1873, 2010, + /* 940 */ 467, 191, 525, 461, 460, 459, 458, 455, 454, 453, + /* 950 */ 452, 451, 447, 446, 445, 444, 332, 436, 435, 434, + /* 960 */ 2010, 431, 430, 346, 524, 716, 715, 714, 713, 390, + /* 970 */ 61, 712, 711, 143, 706, 705, 704, 703, 702, 701, + /* 980 */ 700, 156, 696, 695, 694, 389, 388, 691, 690, 689, + /* 990 */ 688, 687, 632, 632, 1676, 38, 37, 565, 2003, 44, + /* 1000 */ 42, 41, 40, 39, 1441, 632, 239, 566, 1608, 108, + /* 1010 */ 2042, 684, 1996, 632, 632, 632, 1469, 1439, 1588, 629, + /* 1020 */ 8, 1675, 1674, 1822, 1822, 1673, 1672, 630, 611, 615, + /* 1030 */ 154, 153, 681, 680, 679, 151, 1822, 683, 2010, 1466, + /* 1040 */ 1866, 2060, 1671, 570, 1822, 1822, 1822, 2201, 152, 610, + /* 1050 */ 80, 79, 422, 1447, 2010, 189, 648, 632, 163, 2042, + /* 1060 */ 400, 302, 2207, 182, 1852, 2010, 2010, 2202, 596, 2010, + /* 1070 */ 2010, 283, 599, 2028, 331, 1140, 1141, 408, 1450, 406, + /* 1080 */ 402, 398, 395, 415, 2024, 2041, 2010, 1681, 1822, 2077, + /* 1090 */ 2060, 1813, 109, 2043, 652, 2045, 2046, 647, 649, 642, + /* 1100 */ 739, 1410, 2024, 2010, 179, 648, 2130, 1777, 386, 632, + /* 1110 */ 374, 2126, 2150, 1585, 426, 639, 164, 2029, 2020, 2026, + /* 1120 */ 375, 632, 185, 387, 184, 1824, 2042, 427, 2024, 642, + /* 1130 */ 2004, 145, 2156, 134, 2041, 289, 2020, 2026, 2077, 1800, + /* 1140 */ 1822, 109, 2043, 652, 2045, 2046, 647, 642, 642, 52, + /* 1150 */ 152, 142, 1822, 149, 2101, 2130, 569, 2060, 2042, 374, + /* 1160 */ 2126, 246, 2020, 2026, 73, 610, 1442, 1711, 1440, 1724, + /* 1170 */ 2010, 226, 648, 642, 224, 570, 1717, 228, 230, 2201, + /* 1180 */ 227, 229, 1498, 147, 232, 245, 554, 231, 553, 2060, + /* 1190 */ 2170, 537, 1445, 1446, 2207, 182, 1715, 649, 539, 2202, + /* 1200 */ 596, 2041, 2010, 1413, 648, 2077, 1449, 2042, 109, 2043, + /* 1210 */ 652, 2045, 2046, 647, 81, 642, 734, 63, 542, 63, + /* 1220 */ 179, 251, 2130, 1663, 1664, 90, 374, 2126, 1585, 1453, + /* 1230 */ 152, 47, 276, 2041, 70, 13, 12, 2077, 2060, 105, + /* 1240 */ 109, 2043, 652, 2045, 2046, 647, 649, 642, 2157, 102, + /* 1250 */ 264, 2010, 2221, 648, 2130, 583, 150, 557, 374, 2126, + /* 1260 */ 152, 1543, 63, 47, 47, 219, 2042, 258, 2061, 2164, + /* 1270 */ 1617, 656, 1616, 692, 253, 150, 152, 135, 1184, 150, + /* 1280 */ 391, 1929, 2041, 614, 1374, 281, 2077, 624, 1705, 109, + /* 1290 */ 2043, 652, 2045, 2046, 647, 1203, 642, 2060, 693, 600, + /* 1300 */ 2042, 2221, 570, 2130, 1863, 649, 2201, 374, 2126, 285, + /* 1310 */ 2010, 2160, 648, 1255, 1185, 1559, 1508, 301, 2177, 608, + /* 1320 */ 1201, 2207, 182, 263, 1283, 266, 2202, 596, 1287, 1294, + /* 1330 */ 1292, 2060, 155, 1, 399, 4, 394, 296, 344, 649, + /* 1340 */ 1397, 2041, 195, 428, 2010, 2077, 648, 1469, 109, 2043, + /* 1350 */ 652, 2045, 2046, 647, 432, 642, 1930, 1452, 437, 465, + /* 1360 */ 2221, 1464, 2130, 450, 1922, 457, 374, 2126, 464, 466, + /* 1370 */ 472, 474, 200, 2042, 475, 2041, 477, 577, 479, 2077, + /* 1380 */ 1470, 480, 109, 2043, 652, 2045, 2046, 647, 489, 642, + /* 1390 */ 1472, 206, 377, 376, 2221, 492, 2130, 1467, 493, 208, + /* 1400 */ 374, 2126, 1455, 1471, 2060, 494, 1473, 211, 495, 497, + /* 1410 */ 1157, 2195, 649, 1522, 518, 1448, 519, 2010, 213, 648, + /* 1420 */ 84, 85, 2042, 522, 217, 501, 520, 1987, 1812, 223, + /* 1430 */ 1808, 334, 225, 112, 1984, 1983, 556, 558, 1517, 88, + /* 1440 */ 240, 148, 157, 158, 1810, 1806, 297, 560, 2041, 159, + /* 1450 */ 160, 1447, 2077, 2060, 243, 109, 2043, 652, 2045, 2046, + /* 1460 */ 647, 649, 642, 561, 567, 584, 2010, 2221, 648, 2130, + /* 1470 */ 622, 2176, 564, 374, 2126, 2175, 574, 580, 593, 363, + /* 1480 */ 587, 2161, 575, 7, 2149, 2171, 2042, 2152, 573, 249, + /* 1490 */ 172, 257, 259, 252, 260, 572, 261, 2041, 638, 364, + /* 1500 */ 604, 2077, 2224, 1585, 109, 2043, 652, 2045, 2046, 647, + /* 1510 */ 601, 642, 138, 1468, 265, 262, 2105, 2060, 2130, 612, + /* 1520 */ 2200, 2146, 374, 2126, 367, 649, 271, 1474, 95, 1935, + /* 1530 */ 2010, 620, 648, 625, 298, 621, 1949, 1948, 1947, 299, + /* 1540 */ 370, 626, 97, 99, 1823, 60, 2111, 300, 101, 303, + /* 1550 */ 1793, 292, 735, 1867, 2042, 327, 736, 654, 738, 336, + /* 1560 */ 312, 2041, 326, 50, 1456, 2077, 1451, 316, 109, 2043, + /* 1570 */ 652, 2045, 2046, 647, 305, 642, 307, 2002, 2001, 2000, + /* 1580 */ 2103, 77, 2130, 337, 2042, 2060, 374, 2126, 1997, 396, + /* 1590 */ 1459, 1461, 397, 649, 1432, 1433, 188, 401, 2010, 1995, + /* 1600 */ 648, 405, 403, 640, 1515, 1516, 1518, 1519, 1520, 1521, + /* 1610 */ 404, 1994, 407, 1993, 2042, 2060, 409, 1992, 411, 1991, + /* 1620 */ 413, 78, 1400, 649, 1399, 1961, 1960, 1959, 2010, 2041, + /* 1630 */ 648, 420, 421, 2077, 1958, 1957, 109, 2043, 652, 2045, + /* 1640 */ 2046, 647, 1351, 642, 2042, 2060, 1913, 1912, 635, 1910, + /* 1650 */ 2130, 144, 1909, 649, 374, 2126, 1908, 1911, 2010, 2041, + /* 1660 */ 648, 1907, 1906, 2077, 193, 438, 110, 2043, 652, 2045, + /* 1670 */ 2046, 647, 1904, 642, 1903, 2060, 1902, 1901, 2042, 440, + /* 1680 */ 2130, 1915, 1900, 649, 637, 2126, 1899, 1898, 2010, 650, + /* 1690 */ 648, 1897, 1896, 2077, 1895, 1894, 110, 2043, 652, 2045, + /* 1700 */ 2046, 647, 1893, 642, 1892, 2042, 1891, 1890, 1889, 2060, + /* 1710 */ 2130, 1888, 1887, 1886, 339, 2126, 1885, 649, 1884, 2041, + /* 1720 */ 146, 1883, 2010, 2077, 648, 1914, 169, 2043, 652, 2045, + /* 1730 */ 2046, 647, 1882, 642, 1881, 1880, 2060, 1353, 1879, 1878, + /* 1740 */ 468, 1877, 1876, 1740, 649, 1230, 199, 1739, 201, 2010, + /* 1750 */ 1738, 648, 2030, 2041, 2042, 202, 1736, 2077, 1700, 204, + /* 1760 */ 168, 2043, 652, 2045, 2046, 647, 75, 642, 177, 1143, + /* 1770 */ 485, 1142, 1699, 487, 1974, 1968, 205, 1956, 597, 2222, + /* 1780 */ 2041, 212, 1955, 76, 2077, 2060, 1933, 110, 2043, 652, + /* 1790 */ 2045, 2046, 647, 649, 642, 1801, 1177, 1735, 2010, 210, + /* 1800 */ 648, 2130, 2168, 1733, 502, 504, 2127, 503, 1731, 507, + /* 1810 */ 508, 506, 1729, 510, 1727, 511, 2042, 1714, 514, 512, + /* 1820 */ 516, 515, 1713, 1696, 1803, 62, 1299, 1298, 1802, 2041, + /* 1830 */ 1725, 222, 707, 2077, 1221, 1220, 318, 2043, 652, 2045, + /* 1840 */ 2046, 647, 1219, 642, 1218, 1215, 709, 2060, 2042, 1213, + /* 1850 */ 1214, 1212, 1718, 354, 355, 649, 540, 1716, 356, 1695, + /* 1860 */ 2010, 543, 648, 1694, 545, 1693, 549, 111, 547, 1420, + /* 1870 */ 1422, 1973, 1419, 1406, 55, 1967, 562, 1954, 1952, 2060, + /* 1880 */ 592, 1424, 2206, 26, 369, 66, 162, 649, 16, 244, + /* 1890 */ 19, 2041, 2010, 1633, 648, 2077, 576, 2042, 169, 2043, + /* 1900 */ 652, 2045, 2046, 647, 578, 642, 568, 28, 58, 248, + /* 1910 */ 563, 360, 5, 59, 2042, 250, 1615, 170, 255, 256, + /* 1920 */ 6, 254, 20, 2041, 30, 64, 1648, 2077, 2060, 2031, + /* 1930 */ 325, 2043, 652, 2045, 2046, 647, 646, 642, 29, 21, + /* 1940 */ 1607, 2010, 1653, 648, 91, 2060, 2042, 1654, 17, 1647, + /* 1950 */ 379, 2223, 365, 649, 1652, 1651, 366, 1582, 2010, 1581, + /* 1960 */ 648, 1953, 57, 268, 1951, 56, 1950, 1932, 94, 93, + /* 1970 */ 173, 2042, 2041, 274, 1931, 96, 2077, 2060, 287, 324, + /* 1980 */ 2043, 652, 2045, 2046, 647, 649, 642, 275, 2096, 2041, + /* 1990 */ 2010, 1613, 648, 2077, 102, 2042, 325, 2043, 652, 2045, + /* 2000 */ 2046, 647, 2060, 642, 22, 277, 282, 381, 623, 67, + /* 2010 */ 649, 12, 23, 1457, 1544, 2010, 1534, 648, 174, 284, + /* 2020 */ 2042, 555, 1512, 98, 1533, 2077, 2060, 10, 320, 2043, + /* 2030 */ 652, 2045, 2046, 647, 649, 642, 2080, 641, 36, 2010, + /* 2040 */ 1510, 648, 1509, 1481, 15, 24, 2041, 186, 1489, 25, + /* 2050 */ 2077, 2060, 655, 325, 2043, 652, 2045, 2046, 647, 649, + /* 2060 */ 642, 651, 653, 382, 2010, 657, 648, 1284, 659, 660, + /* 2070 */ 2041, 662, 1281, 1278, 2077, 663, 665, 309, 2043, 652, + /* 2080 */ 2045, 2046, 647, 2042, 642, 1272, 666, 668, 1261, 1270, + /* 2090 */ 669, 675, 290, 103, 104, 2041, 1293, 1276, 1275, 2077, + /* 2100 */ 1274, 1273, 310, 2043, 652, 2045, 2046, 647, 74, 642, + /* 2110 */ 2042, 1289, 1175, 685, 2060, 1209, 1208, 1207, 1206, 291, + /* 2120 */ 1205, 1204, 649, 1202, 1228, 1200, 1199, 2010, 1198, 648, + /* 2130 */ 697, 1196, 2042, 1195, 1194, 1193, 1192, 1191, 1190, 1225, + /* 2140 */ 1223, 2060, 1187, 1186, 1183, 1182, 1181, 1180, 1732, 649, + /* 2150 */ 717, 1730, 718, 719, 2010, 721, 648, 723, 2041, 1728, + /* 2160 */ 725, 727, 2077, 2060, 722, 311, 2043, 652, 2045, 2046, + /* 2170 */ 647, 649, 642, 1726, 726, 729, 2010, 730, 648, 1712, + /* 2180 */ 731, 733, 1132, 1692, 294, 2041, 737, 741, 1443, 2077, + /* 2190 */ 304, 740, 317, 2043, 652, 2045, 2046, 647, 1667, 642, + /* 2200 */ 1667, 1667, 1667, 1667, 1667, 1667, 1667, 2041, 1667, 1667, + /* 2210 */ 1667, 2077, 2042, 1667, 321, 2043, 652, 2045, 2046, 647, + /* 2220 */ 1667, 642, 1667, 1667, 1667, 1667, 1667, 1667, 1667, 2042, + /* 2230 */ 1667, 1667, 1667, 1667, 1667, 1667, 1667, 1667, 1667, 1667, + /* 2240 */ 1667, 1667, 1667, 2060, 1667, 1667, 2042, 1667, 1667, 1667, + /* 2250 */ 1667, 649, 1667, 1667, 1667, 1667, 2010, 1667, 648, 1667, + /* 2260 */ 2060, 1667, 1667, 1667, 1667, 1667, 1667, 1667, 649, 1667, + /* 2270 */ 1667, 1667, 1667, 2010, 1667, 648, 1667, 2060, 2042, 1667, + /* 2280 */ 1667, 1667, 1667, 1667, 1667, 649, 1667, 2041, 1667, 1667, + /* 2290 */ 2010, 2077, 648, 1667, 313, 2043, 652, 2045, 2046, 647, + /* 2300 */ 1667, 642, 1667, 2042, 2041, 1667, 1667, 1667, 2077, 2060, + /* 2310 */ 1667, 322, 2043, 652, 2045, 2046, 647, 649, 642, 1667, + /* 2320 */ 1667, 2041, 2010, 1667, 648, 2077, 1667, 2042, 314, 2043, + /* 2330 */ 652, 2045, 2046, 647, 2060, 642, 1667, 1667, 1667, 1667, + /* 2340 */ 1667, 1667, 649, 1667, 1667, 1667, 1667, 2010, 1667, 648, + /* 2350 */ 1667, 1667, 2042, 2041, 1667, 1667, 1667, 2077, 2060, 1667, + /* 2360 */ 323, 2043, 652, 2045, 2046, 647, 649, 642, 1667, 1667, + /* 2370 */ 1667, 2010, 1667, 648, 1667, 1667, 1667, 1667, 2041, 1667, + /* 2380 */ 1667, 1667, 2077, 2060, 1667, 315, 2043, 652, 2045, 2046, + /* 2390 */ 647, 649, 642, 1667, 1667, 1667, 2010, 1667, 648, 1667, + /* 2400 */ 1667, 1667, 2041, 1667, 1667, 1667, 2077, 1667, 1667, 328, + /* 2410 */ 2043, 652, 2045, 2046, 647, 2042, 642, 1667, 1667, 1667, + /* 2420 */ 1667, 1667, 1667, 1667, 1667, 1667, 1667, 2041, 1667, 1667, + /* 2430 */ 1667, 2077, 1667, 1667, 329, 2043, 652, 2045, 2046, 647, + /* 2440 */ 1667, 642, 2042, 1667, 1667, 1667, 2060, 1667, 1667, 1667, + /* 2450 */ 1667, 1667, 1667, 1667, 649, 1667, 1667, 1667, 1667, 2010, + /* 2460 */ 1667, 648, 1667, 1667, 2042, 1667, 1667, 1667, 1667, 1667, + /* 2470 */ 1667, 1667, 1667, 2060, 1667, 1667, 1667, 1667, 1667, 1667, + /* 2480 */ 1667, 649, 1667, 1667, 1667, 1667, 2010, 1667, 648, 1667, + /* 2490 */ 2041, 1667, 1667, 1667, 2077, 2060, 1667, 2054, 2043, 652, + /* 2500 */ 2045, 2046, 647, 649, 642, 1667, 1667, 1667, 2010, 1667, + /* 2510 */ 648, 1667, 1667, 1667, 1667, 1667, 1667, 2041, 1667, 1667, + /* 2520 */ 1667, 2077, 1667, 1667, 2053, 2043, 652, 2045, 2046, 647, + /* 2530 */ 1667, 642, 1667, 1667, 1667, 1667, 1667, 1667, 1667, 2041, + /* 2540 */ 1667, 1667, 1667, 2077, 2042, 1667, 2052, 2043, 652, 2045, + /* 2550 */ 2046, 647, 1667, 642, 1667, 1667, 1667, 1667, 1667, 1667, + /* 2560 */ 1667, 2042, 1667, 1667, 1667, 1667, 1667, 1667, 1667, 1667, + /* 2570 */ 1667, 1667, 1667, 1667, 1667, 2060, 1667, 1667, 2042, 1667, + /* 2580 */ 1667, 1667, 1667, 649, 1667, 1667, 1667, 1667, 2010, 1667, + /* 2590 */ 648, 1667, 2060, 1667, 1667, 1667, 1667, 1667, 1667, 1667, + /* 2600 */ 649, 1667, 1667, 1667, 1667, 2010, 1667, 648, 1667, 2060, + /* 2610 */ 2042, 1667, 1667, 1667, 1667, 1667, 1667, 649, 1667, 2041, + /* 2620 */ 1667, 1667, 2010, 2077, 648, 1667, 341, 2043, 652, 2045, + /* 2630 */ 2046, 647, 1667, 642, 1667, 2042, 2041, 1667, 1667, 1667, + /* 2640 */ 2077, 2060, 1667, 342, 2043, 652, 2045, 2046, 647, 649, + /* 2650 */ 642, 1667, 1667, 2041, 2010, 1667, 648, 2077, 1667, 2042, + /* 2660 */ 338, 2043, 652, 2045, 2046, 647, 2060, 642, 1667, 1667, + /* 2670 */ 1667, 1667, 1667, 1667, 649, 1667, 1667, 1667, 1667, 2010, + /* 2680 */ 1667, 648, 1667, 1667, 1667, 2041, 1667, 1667, 1667, 2077, + /* 2690 */ 2060, 1667, 343, 2043, 652, 2045, 2046, 647, 649, 642, + /* 2700 */ 1667, 1667, 1667, 2010, 1667, 648, 1667, 1667, 1667, 1667, + /* 2710 */ 650, 1667, 1667, 1667, 2077, 1667, 1667, 320, 2043, 652, + /* 2720 */ 2045, 2046, 647, 1667, 642, 1667, 1667, 1667, 1667, 1667, + /* 2730 */ 1667, 1667, 1667, 1667, 2041, 1667, 1667, 1667, 2077, 1667, + /* 2740 */ 1667, 319, 2043, 652, 2045, 2046, 647, 1667, 642, }; static const YYCODETYPE yy_lookahead[] = { /* 0 */ 377, 439, 0, 339, 335, 443, 337, 338, 335, 363, @@ -542,14 +542,14 @@ static const YYCODETYPE yy_lookahead[] = { /* 440 */ 232, 370, 24, 25, 26, 27, 28, 29, 30, 31, /* 450 */ 32, 353, 375, 454, 455, 58, 163, 164, 360, 362, /* 460 */ 343, 96, 169, 170, 166, 424, 369, 426, 370, 171, - /* 470 */ 163, 164, 66, 67, 68, 378, 97, 184, 0, 186, + /* 470 */ 163, 164, 66, 67, 68, 378, 97, 184, 47, 186, /* 480 */ 74, 75, 365, 118, 96, 79, 188, 80, 190, 0, /* 490 */ 84, 85, 95, 133, 134, 98, 90, 127, 133, 134, /* 500 */ 376, 377, 20, 210, 211, 176, 213, 214, 215, 216, /* 510 */ 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, - /* 520 */ 227, 228, 229, 230, 66, 67, 68, 71, 163, 164, + /* 520 */ 227, 228, 229, 230, 66, 67, 68, 96, 163, 164, /* 530 */ 0, 362, 74, 75, 169, 170, 339, 79, 369, 339, - /* 540 */ 248, 63, 84, 85, 165, 138, 139, 378, 90, 184, + /* 540 */ 248, 71, 84, 85, 165, 138, 139, 378, 90, 184, /* 550 */ 353, 186, 339, 353, 24, 25, 26, 27, 28, 29, /* 560 */ 30, 31, 32, 193, 194, 394, 107, 370, 161, 398, /* 570 */ 370, 14, 15, 16, 331, 210, 211, 339, 213, 214, @@ -609,54 +609,54 @@ static const YYCODETYPE yy_lookahead[] = { /* 1110 */ 431, 432, 246, 247, 22, 64, 362, 364, 409, 410, /* 1120 */ 411, 339, 248, 353, 445, 371, 331, 35, 375, 420, /* 1130 */ 394, 42, 453, 44, 406, 353, 409, 410, 410, 0, - /* 1140 */ 370, 413, 414, 415, 416, 417, 418, 420, 420, 385, - /* 1150 */ 44, 423, 370, 425, 426, 427, 58, 362, 331, 431, - /* 1160 */ 432, 165, 409, 410, 107, 370, 184, 47, 186, 0, + /* 1140 */ 370, 413, 414, 415, 416, 417, 418, 420, 420, 165, + /* 1150 */ 44, 423, 370, 425, 426, 427, 172, 362, 331, 431, + /* 1160 */ 432, 165, 409, 410, 107, 370, 184, 0, 186, 0, /* 1170 */ 375, 100, 377, 420, 103, 439, 0, 100, 100, 443, - /* 1180 */ 103, 103, 163, 100, 0, 196, 103, 198, 49, 362, - /* 1190 */ 467, 22, 210, 211, 458, 459, 98, 370, 22, 463, - /* 1200 */ 464, 406, 375, 97, 377, 410, 22, 331, 413, 414, - /* 1210 */ 415, 416, 417, 418, 157, 420, 96, 44, 44, 44, - /* 1220 */ 425, 44, 427, 133, 134, 165, 431, 432, 247, 186, - /* 1230 */ 44, 44, 172, 406, 44, 1, 2, 410, 362, 35, - /* 1240 */ 413, 414, 415, 416, 417, 418, 370, 420, 453, 35, - /* 1250 */ 456, 375, 425, 377, 427, 96, 44, 394, 431, 432, - /* 1260 */ 44, 210, 44, 44, 44, 106, 331, 341, 450, 442, - /* 1270 */ 97, 97, 97, 13, 97, 44, 44, 44, 362, 44, - /* 1280 */ 44, 341, 406, 97, 97, 71, 410, 97, 338, 413, + /* 1180 */ 103, 103, 163, 44, 100, 58, 196, 103, 198, 362, + /* 1190 */ 385, 22, 210, 211, 458, 459, 0, 370, 22, 463, + /* 1200 */ 464, 406, 375, 97, 377, 410, 35, 331, 413, 414, + /* 1210 */ 415, 416, 417, 418, 157, 420, 49, 44, 22, 44, + /* 1220 */ 425, 44, 427, 133, 134, 98, 431, 432, 247, 186, + /* 1230 */ 44, 44, 44, 406, 44, 1, 2, 410, 362, 96, + /* 1240 */ 413, 414, 415, 416, 417, 418, 370, 420, 453, 106, + /* 1250 */ 467, 375, 425, 377, 427, 456, 44, 394, 431, 432, + /* 1260 */ 44, 210, 44, 44, 44, 341, 331, 450, 362, 442, + /* 1270 */ 97, 44, 97, 13, 97, 44, 44, 44, 35, 44, + /* 1280 */ 341, 385, 406, 97, 97, 97, 410, 97, 338, 413, /* 1290 */ 414, 415, 416, 417, 418, 35, 420, 362, 13, 271, - /* 1300 */ 331, 425, 439, 427, 385, 370, 443, 431, 432, 97, - /* 1310 */ 375, 374, 377, 97, 385, 97, 97, 97, 442, 441, - /* 1320 */ 35, 458, 459, 433, 460, 444, 463, 464, 97, 97, - /* 1330 */ 97, 362, 97, 97, 250, 408, 48, 407, 182, 370, - /* 1340 */ 396, 406, 42, 382, 375, 410, 377, 20, 413, 414, - /* 1350 */ 415, 416, 417, 418, 382, 420, 385, 162, 380, 20, - /* 1360 */ 425, 339, 427, 339, 380, 382, 431, 432, 380, 94, - /* 1370 */ 339, 339, 347, 331, 339, 406, 339, 442, 20, 410, - /* 1380 */ 333, 333, 413, 414, 415, 416, 417, 418, 20, 420, - /* 1390 */ 186, 401, 12, 13, 425, 345, 427, 20, 377, 345, + /* 1300 */ 331, 425, 439, 427, 374, 370, 443, 431, 432, 97, + /* 1310 */ 375, 385, 377, 97, 71, 97, 97, 97, 442, 441, + /* 1320 */ 35, 458, 459, 433, 97, 460, 463, 464, 97, 97, + /* 1330 */ 97, 362, 97, 444, 48, 250, 408, 396, 407, 370, + /* 1340 */ 182, 406, 42, 382, 375, 410, 377, 20, 413, 414, + /* 1350 */ 415, 416, 417, 418, 382, 420, 385, 186, 380, 162, + /* 1360 */ 425, 20, 427, 339, 339, 382, 431, 432, 380, 380, + /* 1370 */ 339, 94, 339, 331, 347, 406, 339, 442, 339, 410, + /* 1380 */ 20, 333, 413, 414, 415, 416, 417, 418, 333, 420, + /* 1390 */ 20, 345, 12, 13, 425, 401, 427, 20, 377, 345, /* 1400 */ 431, 432, 22, 20, 362, 340, 20, 345, 395, 340, - /* 1410 */ 342, 442, 370, 33, 52, 35, 342, 375, 345, 377, - /* 1420 */ 345, 345, 331, 362, 339, 345, 333, 375, 362, 362, - /* 1430 */ 333, 375, 362, 339, 362, 401, 199, 96, 58, 375, - /* 1440 */ 189, 362, 403, 362, 362, 405, 343, 343, 406, 362, - /* 1450 */ 362, 71, 410, 362, 339, 413, 414, 415, 416, 417, - /* 1460 */ 418, 370, 420, 362, 258, 449, 375, 425, 377, 427, - /* 1470 */ 257, 385, 449, 431, 432, 375, 377, 266, 452, 175, - /* 1480 */ 375, 385, 375, 375, 442, 268, 331, 451, 267, 251, - /* 1490 */ 449, 447, 390, 448, 272, 400, 270, 406, 118, 390, - /* 1500 */ 275, 410, 247, 370, 413, 414, 415, 416, 417, 418, - /* 1510 */ 461, 420, 20, 343, 468, 462, 425, 362, 427, 408, - /* 1520 */ 339, 343, 431, 432, 412, 370, 20, 390, 340, 388, - /* 1530 */ 375, 167, 377, 375, 390, 375, 375, 375, 375, 375, - /* 1540 */ 387, 343, 343, 358, 96, 96, 430, 375, 366, 370, - /* 1550 */ 343, 36, 352, 402, 331, 0, 446, 391, 391, 356, - /* 1560 */ 333, 406, 334, 339, 184, 410, 186, 0, 413, 414, - /* 1570 */ 415, 416, 417, 418, 344, 420, 329, 397, 0, 42, - /* 1580 */ 425, 0, 427, 35, 331, 362, 431, 432, 204, 35, - /* 1590 */ 210, 211, 35, 370, 35, 356, 356, 204, 375, 0, - /* 1600 */ 377, 204, 0, 223, 224, 225, 226, 227, 228, 229, - /* 1610 */ 35, 35, 204, 0, 331, 362, 0, 35, 22, 0, + /* 1410 */ 52, 442, 370, 33, 342, 35, 342, 375, 345, 377, + /* 1420 */ 345, 345, 331, 362, 345, 339, 333, 375, 362, 362, + /* 1430 */ 362, 333, 362, 339, 375, 375, 199, 405, 58, 96, + /* 1440 */ 343, 403, 362, 362, 362, 362, 401, 189, 406, 362, + /* 1450 */ 362, 71, 410, 362, 343, 413, 414, 415, 416, 417, + /* 1460 */ 418, 370, 420, 400, 339, 258, 375, 425, 377, 427, + /* 1470 */ 257, 449, 377, 431, 432, 449, 375, 375, 175, 375, + /* 1480 */ 375, 385, 268, 266, 442, 385, 331, 452, 267, 390, + /* 1490 */ 449, 451, 448, 390, 447, 251, 446, 406, 118, 275, + /* 1500 */ 272, 410, 468, 247, 413, 414, 415, 416, 417, 418, + /* 1510 */ 270, 420, 370, 20, 461, 408, 425, 362, 427, 339, + /* 1520 */ 462, 412, 431, 432, 340, 370, 343, 20, 343, 388, + /* 1530 */ 375, 375, 377, 167, 390, 375, 375, 375, 375, 390, + /* 1540 */ 375, 387, 343, 343, 370, 96, 430, 358, 96, 339, + /* 1550 */ 352, 343, 36, 375, 331, 402, 334, 366, 333, 391, + /* 1560 */ 356, 406, 356, 397, 184, 410, 186, 356, 413, 414, + /* 1570 */ 415, 416, 417, 418, 344, 420, 329, 0, 0, 0, + /* 1580 */ 425, 42, 427, 391, 331, 362, 431, 432, 0, 35, + /* 1590 */ 210, 211, 204, 370, 35, 35, 35, 204, 375, 0, + /* 1600 */ 377, 204, 35, 223, 224, 225, 226, 227, 228, 229, + /* 1610 */ 35, 0, 204, 0, 331, 362, 35, 0, 22, 0, /* 1620 */ 35, 191, 186, 370, 184, 0, 0, 0, 375, 406, /* 1630 */ 377, 180, 179, 410, 0, 0, 413, 414, 415, 416, /* 1640 */ 417, 418, 47, 420, 331, 362, 0, 0, 425, 0, @@ -771,7 +771,7 @@ static const YYCODETYPE yy_lookahead[] = { /* 2730 */ 469, 469, 469, 469, 406, 469, 469, 469, 410, 469, /* 2740 */ 469, 413, 414, 415, 416, 417, 418, 469, 420, }; -#define YY_SHIFT_COUNT (741) +#define YY_SHIFT_COUNT (742) #define YY_SHIFT_MIN (0) #define YY_SHIFT_MAX (2183) static const unsigned short int yy_shift_ofst[] = { @@ -788,68 +788,68 @@ static const unsigned short int yy_shift_ofst[] = { /* 100 */ 115, 16, 115, 16, 16, 16, 115, 176, 803, 34, /* 110 */ 34, 219, 458, 982, 982, 982, 982, 982, 982, 982, /* 120 */ 982, 982, 982, 982, 982, 982, 982, 982, 982, 982, - /* 130 */ 982, 982, 217, 379, 307, 360, 2, 249, 578, 578, - /* 140 */ 578, 478, 152, 152, 249, 245, 245, 245, 260, 208, - /* 150 */ 16, 456, 16, 456, 456, 459, 606, 36, 36, 36, + /* 130 */ 982, 982, 217, 379, 307, 360, 249, 578, 578, 578, + /* 140 */ 2, 152, 152, 249, 245, 245, 245, 138, 260, 208, + /* 150 */ 16, 470, 16, 470, 470, 459, 606, 36, 36, 36, /* 160 */ 36, 36, 36, 36, 36, 298, 418, 406, 47, 329, /* 170 */ 444, 60, 69, 239, 652, 353, 776, 1030, 834, 996, - /* 180 */ 866, 981, 668, 866, 888, 769, 1019, 1084, 1288, 1156, - /* 190 */ 1300, 1327, 1300, 1195, 1339, 1339, 1300, 1195, 1195, 1339, - /* 200 */ 1275, 1339, 1339, 1339, 1358, 1358, 1368, 138, 1377, 138, - /* 210 */ 1383, 1386, 138, 1383, 138, 138, 138, 1339, 138, 1362, - /* 220 */ 1362, 1358, 16, 16, 16, 16, 16, 16, 16, 16, - /* 230 */ 16, 16, 16, 1339, 1358, 456, 456, 456, 1237, 1341, - /* 240 */ 1368, 176, 1251, 1377, 176, 1339, 1327, 1327, 456, 1206, - /* 250 */ 1213, 456, 1206, 1213, 456, 456, 16, 1211, 1304, 1206, - /* 260 */ 1217, 1221, 1238, 1084, 1225, 1222, 1226, 1255, 245, 1492, - /* 270 */ 1339, 1383, 176, 176, 1506, 1213, 456, 456, 456, 456, - /* 280 */ 456, 1213, 456, 1364, 176, 459, 176, 245, 1448, 1449, - /* 290 */ 456, 606, 1339, 176, 1515, 1358, 2749, 2749, 2749, 2749, + /* 180 */ 866, 981, 668, 866, 888, 769, 1019, 1085, 1286, 1158, + /* 190 */ 1300, 1327, 1300, 1197, 1341, 1341, 1300, 1197, 1197, 1341, + /* 200 */ 1277, 1341, 1341, 1341, 1360, 1360, 1370, 138, 1377, 138, + /* 210 */ 1383, 1386, 138, 1383, 138, 138, 138, 1341, 138, 1358, + /* 220 */ 1358, 1360, 16, 16, 16, 16, 16, 16, 16, 16, + /* 230 */ 16, 16, 16, 1341, 1360, 470, 470, 470, 1237, 1343, + /* 240 */ 1370, 176, 1258, 1377, 176, 1341, 1327, 1327, 470, 1207, + /* 250 */ 1213, 470, 1207, 1213, 470, 470, 16, 1217, 1303, 1207, + /* 260 */ 1214, 1221, 1244, 1085, 1224, 1228, 1240, 1256, 245, 1493, + /* 270 */ 1341, 1383, 176, 176, 1507, 1213, 470, 470, 470, 470, + /* 280 */ 470, 1213, 470, 1366, 176, 459, 176, 245, 1449, 1452, + /* 290 */ 470, 606, 1341, 176, 1516, 1360, 2749, 2749, 2749, 2749, /* 300 */ 2749, 2749, 2749, 2749, 2749, 899, 589, 530, 677, 685, /* 310 */ 707, 911, 731, 15, 724, 893, 903, 987, 987, 987, /* 320 */ 987, 987, 987, 987, 987, 987, 716, 596, 295, 295, /* 330 */ 407, 161, 489, 397, 81, 370, 263, 263, 557, 757, - /* 340 */ 582, 557, 557, 557, 1012, 791, 1092, 1089, 1057, 1071, - /* 350 */ 1077, 1078, 1083, 1169, 1176, 1184, 989, 1004, 1106, 1098, - /* 360 */ 1173, 1174, 1175, 1090, 1028, 66, 1060, 1177, 1186, 1187, - /* 370 */ 1190, 1212, 1216, 1234, 1218, 1043, 1204, 1051, 1219, 1120, - /* 380 */ 1220, 1231, 1232, 1233, 1235, 1236, 1159, 1260, 1285, 1214, - /* 390 */ 1139, 1555, 1567, 1578, 1537, 1581, 1548, 1384, 1554, 1557, - /* 400 */ 1559, 1393, 1599, 1575, 1576, 1397, 1602, 1408, 1613, 1582, - /* 410 */ 1616, 1596, 1619, 1585, 1430, 1436, 1440, 1625, 1626, 1627, - /* 420 */ 1451, 1453, 1634, 1635, 1595, 1646, 1647, 1649, 1609, 1652, - /* 430 */ 1656, 1657, 1661, 1662, 1672, 1674, 1676, 1512, 1630, 1677, - /* 440 */ 1527, 1681, 1682, 1686, 1687, 1691, 1692, 1694, 1695, 1702, - /* 450 */ 1704, 1706, 1707, 1708, 1711, 1712, 1713, 1678, 1716, 1718, - /* 460 */ 1721, 1725, 1732, 1734, 1715, 1735, 1738, 1739, 1604, 1741, - /* 470 */ 1742, 1743, 1688, 1710, 1747, 1690, 1750, 1697, 1756, 1758, - /* 480 */ 1717, 1727, 1724, 1705, 1755, 1723, 1757, 1726, 1772, 1736, - /* 490 */ 1744, 1774, 1775, 1777, 1760, 1606, 1782, 1786, 1795, 1731, - /* 500 */ 1797, 1803, 1769, 1759, 1766, 1808, 1776, 1761, 1771, 1812, - /* 510 */ 1778, 1767, 1780, 1814, 1783, 1773, 1781, 1817, 1822, 1823, - /* 520 */ 1824, 1720, 1728, 1791, 1805, 1828, 1799, 1800, 1807, 1809, - /* 530 */ 1788, 1802, 1810, 1815, 1827, 1816, 1830, 1831, 1852, 1832, - /* 540 */ 1806, 1857, 1836, 1826, 1859, 1829, 1863, 1833, 1865, 1844, - /* 550 */ 1847, 1834, 1835, 1837, 1784, 1787, 1871, 1709, 1789, 1838, - /* 560 */ 1875, 1699, 1854, 1745, 1722, 1877, 1878, 1746, 1733, 1879, - /* 570 */ 1846, 1636, 1811, 1796, 1813, 1740, 1665, 1748, 1648, 1818, - /* 580 */ 1864, 1869, 1819, 1821, 1825, 1842, 1843, 1874, 1872, 1882, - /* 590 */ 1848, 1880, 1670, 1845, 1850, 1922, 1895, 1696, 1891, 1914, - /* 600 */ 1917, 1919, 1920, 1921, 1860, 1862, 1916, 1719, 1918, 1923, - /* 610 */ 1961, 1964, 1966, 1967, 1873, 1929, 1705, 1926, 1908, 1890, - /* 620 */ 1894, 1909, 1910, 1840, 1913, 1974, 1936, 1853, 1927, 1888, - /* 630 */ 1705, 1931, 1968, 1785, 1794, 1793, 2009, 1991, 1804, 1940, - /* 640 */ 1925, 1941, 1943, 1942, 1945, 1971, 1948, 1949, 2000, 1946, - /* 650 */ 2026, 1849, 1953, 1955, 1970, 2017, 2028, 1969, 1975, 2033, - /* 660 */ 1973, 1976, 2036, 1979, 1988, 2041, 1990, 1992, 2052, 1994, - /* 670 */ 1977, 1978, 1980, 1981, 2066, 1983, 1997, 2048, 1998, 2061, - /* 680 */ 2012, 2048, 2048, 2089, 2047, 2049, 2080, 2081, 2082, 2083, - /* 690 */ 2085, 2086, 2088, 2090, 2091, 2093, 2053, 2037, 2075, 2096, - /* 700 */ 2098, 2099, 2113, 2101, 2102, 2103, 2068, 1788, 2105, 1802, - /* 710 */ 2107, 2108, 2109, 2110, 2124, 2112, 2148, 2115, 2104, 2114, - /* 720 */ 2151, 2120, 2116, 2118, 2159, 2125, 2126, 2122, 2173, 2140, - /* 730 */ 2129, 2141, 2179, 2146, 2147, 2183, 2162, 2165, 2166, 2168, - /* 740 */ 2170, 2167, + /* 340 */ 582, 557, 557, 557, 1012, 791, 1092, 1089, 1057, 1139, + /* 350 */ 1071, 1077, 1078, 1084, 1169, 1176, 1196, 990, 1004, 1106, + /* 360 */ 1127, 1173, 1175, 1177, 1090, 1028, 66, 984, 1186, 1187, + /* 370 */ 1188, 1190, 1212, 1216, 1234, 1218, 1043, 1171, 1051, 1219, + /* 380 */ 431, 1220, 1227, 1231, 1232, 1233, 1235, 1143, 1260, 1285, + /* 390 */ 1243, 1167, 1577, 1578, 1579, 1539, 1588, 1554, 1388, 1559, + /* 400 */ 1560, 1561, 1393, 1599, 1567, 1575, 1397, 1611, 1408, 1613, + /* 410 */ 1581, 1617, 1596, 1619, 1585, 1430, 1436, 1440, 1625, 1626, + /* 420 */ 1627, 1451, 1453, 1634, 1635, 1595, 1646, 1647, 1649, 1609, + /* 430 */ 1652, 1656, 1657, 1661, 1662, 1672, 1674, 1676, 1512, 1630, + /* 440 */ 1677, 1527, 1681, 1682, 1686, 1687, 1691, 1692, 1694, 1695, + /* 450 */ 1702, 1704, 1706, 1707, 1708, 1711, 1712, 1713, 1678, 1716, + /* 460 */ 1718, 1721, 1725, 1732, 1734, 1715, 1735, 1738, 1739, 1604, + /* 470 */ 1741, 1742, 1743, 1688, 1710, 1747, 1690, 1750, 1697, 1756, + /* 480 */ 1758, 1717, 1727, 1724, 1705, 1755, 1723, 1757, 1726, 1772, + /* 490 */ 1736, 1744, 1774, 1775, 1777, 1760, 1606, 1782, 1786, 1795, + /* 500 */ 1731, 1797, 1803, 1769, 1759, 1766, 1808, 1776, 1761, 1771, + /* 510 */ 1812, 1778, 1767, 1780, 1814, 1783, 1773, 1781, 1817, 1822, + /* 520 */ 1823, 1824, 1720, 1728, 1791, 1805, 1828, 1799, 1800, 1807, + /* 530 */ 1809, 1788, 1802, 1810, 1815, 1827, 1816, 1830, 1831, 1852, + /* 540 */ 1832, 1806, 1857, 1836, 1826, 1859, 1829, 1863, 1833, 1865, + /* 550 */ 1844, 1847, 1834, 1835, 1837, 1784, 1787, 1871, 1709, 1789, + /* 560 */ 1838, 1875, 1699, 1854, 1745, 1722, 1877, 1878, 1746, 1733, + /* 570 */ 1879, 1846, 1636, 1811, 1796, 1813, 1740, 1665, 1748, 1648, + /* 580 */ 1818, 1864, 1869, 1819, 1821, 1825, 1842, 1843, 1874, 1872, + /* 590 */ 1882, 1848, 1880, 1670, 1845, 1850, 1922, 1895, 1696, 1891, + /* 600 */ 1914, 1917, 1919, 1920, 1921, 1860, 1862, 1916, 1719, 1918, + /* 610 */ 1923, 1961, 1964, 1966, 1967, 1873, 1929, 1705, 1926, 1908, + /* 620 */ 1890, 1894, 1909, 1910, 1840, 1913, 1974, 1936, 1853, 1927, + /* 630 */ 1888, 1705, 1931, 1968, 1785, 1794, 1793, 2009, 1991, 1804, + /* 640 */ 1940, 1925, 1941, 1943, 1942, 1945, 1971, 1948, 1949, 2000, + /* 650 */ 1946, 2026, 1849, 1953, 1955, 1970, 2017, 2028, 1969, 1975, + /* 660 */ 2033, 1973, 1976, 2036, 1979, 1988, 2041, 1990, 1992, 2052, + /* 670 */ 1994, 1977, 1978, 1980, 1981, 2066, 1983, 1997, 2048, 1998, + /* 680 */ 2061, 2012, 2048, 2048, 2089, 2047, 2049, 2080, 2081, 2082, + /* 690 */ 2083, 2085, 2086, 2088, 2090, 2091, 2093, 2053, 2037, 2075, + /* 700 */ 2096, 2098, 2099, 2113, 2101, 2102, 2103, 2068, 1788, 2105, + /* 710 */ 1802, 2107, 2108, 2109, 2110, 2124, 2112, 2148, 2115, 2104, + /* 720 */ 2114, 2151, 2120, 2116, 2118, 2159, 2125, 2126, 2122, 2173, + /* 730 */ 2140, 2129, 2141, 2179, 2146, 2147, 2183, 2162, 2165, 2166, + /* 740 */ 2168, 2170, 2167, }; #define YY_REDUCE_COUNT (304) #define YY_REDUCE_MIN (-438) @@ -868,101 +868,101 @@ static const short yy_reduce_ofst[] = { /* 100 */ 674, 472, 782, 415, 560, 754, 770, -105, -288, -93, /* 110 */ -93, -75, -272, -187, 77, 308, 336, 354, 359, 382, /* 120 */ 410, 447, 518, 521, 564, 585, 663, 690, 691, 694, - /* 130 */ 695, 711, -342, -41, -206, 124, 257, 516, -41, 274, - /* 140 */ 333, 117, -23, 41, 483, 230, 487, 547, 434, 269, + /* 130 */ 695, 711, -342, -41, -206, 124, 516, -41, 274, 333, + /* 140 */ 117, -23, 41, 483, 230, 487, 547, 257, 434, 269, /* 150 */ 466, 50, 387, 519, 665, 706, 537, -354, 325, 417, - /* 160 */ 455, 492, 550, 555, 492, 598, 755, 756, 764, 723, - /* 170 */ 794, 926, 818, 916, 916, 940, 919, 950, 937, 929, - /* 180 */ 878, 878, 864, 878, 890, 881, 916, 927, 930, 944, - /* 190 */ 961, 971, 972, 978, 1022, 1024, 983, 984, 988, 1031, - /* 200 */ 1025, 1032, 1035, 1037, 1047, 1048, 990, 1050, 1021, 1054, - /* 210 */ 1065, 1013, 1062, 1069, 1073, 1075, 1076, 1085, 1080, 1068, - /* 220 */ 1074, 1093, 1061, 1066, 1067, 1070, 1072, 1079, 1081, 1082, - /* 230 */ 1087, 1088, 1101, 1094, 1097, 1052, 1056, 1064, 1040, 1039, - /* 240 */ 1034, 1103, 1095, 1099, 1104, 1115, 1086, 1096, 1100, 1016, - /* 250 */ 1102, 1105, 1023, 1109, 1107, 1108, 916, 1026, 1036, 1041, - /* 260 */ 1045, 1044, 1110, 1111, 1046, 1053, 1049, 878, 1133, 1112, - /* 270 */ 1181, 1188, 1170, 1178, 1141, 1137, 1158, 1160, 1161, 1162, - /* 280 */ 1163, 1144, 1164, 1153, 1198, 1185, 1199, 1179, 1116, 1182, - /* 290 */ 1172, 1200, 1224, 1207, 1228, 1227, 1180, 1151, 1166, 1167, - /* 300 */ 1203, 1239, 1240, 1230, 1247, + /* 160 */ 455, 492, 550, 555, 492, 598, 755, 756, 805, 783, + /* 170 */ 799, 924, 817, 906, 906, 939, 896, 950, 930, 926, + /* 180 */ 878, 878, 865, 878, 890, 889, 906, 928, 931, 941, + /* 190 */ 961, 971, 972, 978, 1024, 1025, 983, 988, 989, 1031, + /* 200 */ 1027, 1033, 1037, 1039, 1048, 1055, 994, 1046, 1021, 1054, + /* 210 */ 1065, 1013, 1062, 1069, 1073, 1075, 1076, 1086, 1079, 1072, + /* 220 */ 1074, 1093, 1061, 1066, 1067, 1068, 1070, 1080, 1081, 1082, + /* 230 */ 1083, 1087, 1088, 1094, 1098, 1052, 1059, 1060, 1032, 1038, + /* 240 */ 1045, 1097, 1063, 1095, 1111, 1125, 1096, 1100, 1101, 1022, + /* 250 */ 1099, 1102, 1026, 1103, 1104, 1105, 906, 1035, 1040, 1041, + /* 260 */ 1044, 1047, 1050, 1107, 1034, 1058, 1053, 878, 1142, 1109, + /* 270 */ 1180, 1184, 1183, 1185, 1141, 1144, 1156, 1160, 1161, 1162, + /* 280 */ 1163, 1149, 1165, 1154, 1199, 1189, 1200, 1174, 1116, 1191, + /* 290 */ 1178, 1198, 1210, 1208, 1222, 1225, 1166, 1153, 1168, 1192, + /* 300 */ 1204, 1206, 1211, 1230, 1247, }; static const YYACTIONTYPE yy_default[] = { - /* 0 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 10 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 20 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 30 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 40 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 50 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 60 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 70 */ 1664, 1664, 1664, 1922, 1664, 1664, 1664, 1664, 1664, 1664, - /* 80 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1743, 1664, 1664, - /* 90 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 100 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1741, 1915, 2131, - /* 110 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 120 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 130 */ 1664, 1664, 1664, 2143, 1664, 1664, 1743, 1664, 2143, 2143, - /* 140 */ 2143, 1741, 2103, 2103, 1664, 1664, 1664, 1664, 1976, 1664, - /* 150 */ 1664, 1664, 1664, 1664, 1664, 1850, 1664, 1664, 1664, 1664, - /* 160 */ 1664, 1874, 1664, 1664, 1664, 1968, 1664, 1664, 2168, 2224, - /* 170 */ 1664, 1664, 2171, 1664, 1664, 1664, 1927, 1664, 1803, 2158, - /* 180 */ 2135, 2149, 2208, 2136, 2133, 2152, 1664, 2162, 1664, 1961, - /* 190 */ 1920, 1664, 1920, 1917, 1664, 1664, 1920, 1917, 1917, 1664, - /* 200 */ 1794, 1664, 1664, 1664, 1664, 1664, 1664, 1743, 1664, 1743, - /* 210 */ 1664, 1664, 1743, 1664, 1743, 1743, 1743, 1664, 1743, 1721, - /* 220 */ 1721, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 230 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1988, 1974, - /* 240 */ 1664, 1741, 1970, 1664, 1741, 1664, 1664, 1664, 1664, 2179, - /* 250 */ 2177, 1664, 2179, 2177, 1664, 1664, 1664, 2193, 2189, 2179, - /* 260 */ 2197, 2195, 2164, 2162, 2227, 2214, 2210, 2149, 1664, 1664, - /* 270 */ 1664, 1664, 1741, 1741, 1664, 2177, 1664, 1664, 1664, 1664, - /* 280 */ 1664, 2177, 1664, 1664, 1741, 1664, 1741, 1664, 1664, 1819, - /* 290 */ 1664, 1664, 1664, 1741, 1696, 1664, 1963, 1979, 1945, 1945, - /* 300 */ 1853, 1853, 1853, 1744, 1669, 1664, 1664, 1664, 1664, 1664, - /* 310 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 2192, 2191, 2058, - /* 320 */ 1664, 2107, 2106, 2105, 2096, 2057, 1815, 1664, 2056, 2055, - /* 330 */ 1664, 1664, 1664, 1664, 1664, 1664, 1936, 1935, 2049, 1664, - /* 340 */ 1664, 2050, 2048, 2047, 1664, 1664, 1664, 1664, 1664, 1664, - /* 350 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 360 */ 1664, 1664, 1664, 1664, 2211, 2215, 1664, 1664, 1664, 1664, - /* 370 */ 1664, 1664, 1664, 2132, 1664, 1664, 1664, 1664, 1664, 2031, - /* 380 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 390 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 400 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 410 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 420 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 430 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 440 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 450 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 460 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 470 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 480 */ 1664, 1664, 1701, 2036, 1664, 1664, 1664, 1664, 1664, 1664, - /* 490 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 500 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 510 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 520 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 530 */ 1782, 1781, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 540 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 550 */ 1664, 1664, 1664, 1664, 2040, 1664, 1664, 1664, 1664, 1664, - /* 560 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 2207, - /* 570 */ 2165, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 580 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 2031, - /* 590 */ 1664, 2190, 1664, 1664, 2205, 1664, 2209, 1664, 1664, 1664, - /* 600 */ 1664, 1664, 1664, 1664, 2142, 2138, 1664, 1664, 2134, 1664, - /* 610 */ 1664, 1664, 1664, 1664, 1664, 1664, 2039, 1664, 1664, 1664, - /* 620 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 630 */ 2030, 1664, 2093, 1664, 1664, 1664, 2127, 1664, 1664, 2078, - /* 640 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 2040, - /* 650 */ 1664, 2043, 1664, 1664, 1664, 1664, 1664, 1847, 1664, 1664, - /* 660 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 670 */ 1832, 1830, 1829, 1828, 1664, 1825, 1664, 1860, 1664, 1664, - /* 680 */ 1664, 1856, 1855, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 690 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1762, 1664, - /* 700 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1754, 1664, 1753, - /* 710 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 720 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 730 */ 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, 1664, - /* 740 */ 1664, 1664, + /* 0 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 10 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 20 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 30 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 40 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 50 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 60 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 70 */ 1665, 1665, 1665, 1923, 1665, 1665, 1665, 1665, 1665, 1665, + /* 80 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1744, 1665, 1665, + /* 90 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 100 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1742, 1916, 2132, + /* 110 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 120 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 130 */ 1665, 1665, 1665, 2144, 1665, 1665, 1665, 2144, 2144, 2144, + /* 140 */ 1742, 2104, 2104, 1665, 1665, 1665, 1665, 1744, 1977, 1665, + /* 150 */ 1665, 1665, 1665, 1665, 1665, 1851, 1665, 1665, 1665, 1665, + /* 160 */ 1665, 1875, 1665, 1665, 1665, 1969, 1665, 1665, 2169, 2225, + /* 170 */ 1665, 1665, 2172, 1665, 1665, 1665, 1928, 1665, 1804, 2159, + /* 180 */ 2136, 2150, 2209, 2137, 2134, 2153, 1665, 2163, 1665, 1962, + /* 190 */ 1921, 1665, 1921, 1918, 1665, 1665, 1921, 1918, 1918, 1665, + /* 200 */ 1795, 1665, 1665, 1665, 1665, 1665, 1665, 1744, 1665, 1744, + /* 210 */ 1665, 1665, 1744, 1665, 1744, 1744, 1744, 1665, 1744, 1722, + /* 220 */ 1722, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 230 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1989, 1975, + /* 240 */ 1665, 1742, 1971, 1665, 1742, 1665, 1665, 1665, 1665, 2180, + /* 250 */ 2178, 1665, 2180, 2178, 1665, 1665, 1665, 2194, 2190, 2180, + /* 260 */ 2198, 2196, 2165, 2163, 2228, 2215, 2211, 2150, 1665, 1665, + /* 270 */ 1665, 1665, 1742, 1742, 1665, 2178, 1665, 1665, 1665, 1665, + /* 280 */ 1665, 2178, 1665, 1665, 1742, 1665, 1742, 1665, 1665, 1820, + /* 290 */ 1665, 1665, 1665, 1742, 1697, 1665, 1964, 1980, 1946, 1946, + /* 300 */ 1854, 1854, 1854, 1745, 1670, 1665, 1665, 1665, 1665, 1665, + /* 310 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 2193, 2192, 2059, + /* 320 */ 1665, 2108, 2107, 2106, 2097, 2058, 1816, 1665, 2057, 2056, + /* 330 */ 1665, 1665, 1665, 1665, 1665, 1665, 1937, 1936, 2050, 1665, + /* 340 */ 1665, 2051, 2049, 2048, 1665, 1665, 1665, 1665, 1665, 1665, + /* 350 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 360 */ 1665, 1665, 1665, 1665, 1665, 2212, 2216, 1665, 1665, 1665, + /* 370 */ 1665, 1665, 1665, 1665, 2133, 1665, 1665, 1665, 1665, 1665, + /* 380 */ 2032, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 390 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 400 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 410 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 420 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 430 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 440 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 450 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 460 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 470 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 480 */ 1665, 1665, 1665, 1702, 2037, 1665, 1665, 1665, 1665, 1665, + /* 490 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 500 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 510 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 520 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 530 */ 1665, 1783, 1782, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 540 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 550 */ 1665, 1665, 1665, 1665, 1665, 2041, 1665, 1665, 1665, 1665, + /* 560 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 570 */ 2208, 2166, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 580 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 590 */ 2032, 1665, 2191, 1665, 1665, 2206, 1665, 2210, 1665, 1665, + /* 600 */ 1665, 1665, 1665, 1665, 1665, 2143, 2139, 1665, 1665, 2135, + /* 610 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 2040, 1665, 1665, + /* 620 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 630 */ 1665, 2031, 1665, 2094, 1665, 1665, 1665, 2128, 1665, 1665, + /* 640 */ 2079, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 650 */ 2041, 1665, 2044, 1665, 1665, 1665, 1665, 1665, 1848, 1665, + /* 660 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 670 */ 1665, 1833, 1831, 1830, 1829, 1665, 1826, 1665, 1861, 1665, + /* 680 */ 1665, 1665, 1857, 1856, 1665, 1665, 1665, 1665, 1665, 1665, + /* 690 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1763, + /* 700 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1755, 1665, + /* 710 */ 1754, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 720 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 730 */ 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, 1665, + /* 740 */ 1665, 1665, 1665, }; /********** End of lemon-generated parsing tables *****************************/ @@ -2023,7 +2023,7 @@ static const char *const yyRuleName[] = { /* 147 */ "multi_create_clause ::= multi_create_clause create_subtable_clause", /* 148 */ "create_subtable_clause ::= not_exists_opt full_table_name USING full_table_name specific_cols_opt TAGS NK_LP expression_list NK_RP table_options", /* 149 */ "multi_drop_clause ::= drop_table_clause", - /* 150 */ "multi_drop_clause ::= multi_drop_clause drop_table_clause", + /* 150 */ "multi_drop_clause ::= multi_drop_clause NK_COMMA drop_table_clause", /* 151 */ "drop_table_clause ::= exists_opt full_table_name", /* 152 */ "specific_cols_opt ::=", /* 153 */ "specific_cols_opt ::= NK_LP col_name_list NK_RP", @@ -3203,7 +3203,7 @@ static const struct { { 357, -2 }, /* (147) multi_create_clause ::= multi_create_clause create_subtable_clause */ { 365, -10 }, /* (148) create_subtable_clause ::= not_exists_opt full_table_name USING full_table_name specific_cols_opt TAGS NK_LP expression_list NK_RP table_options */ { 359, -1 }, /* (149) multi_drop_clause ::= drop_table_clause */ - { 359, -2 }, /* (150) multi_drop_clause ::= multi_drop_clause drop_table_clause */ + { 359, -3 }, /* (150) multi_drop_clause ::= multi_drop_clause NK_COMMA drop_table_clause */ { 368, -2 }, /* (151) drop_table_clause ::= exists_opt full_table_name */ { 366, 0 }, /* (152) specific_cols_opt ::= */ { 366, -3 }, /* (153) specific_cols_opt ::= NK_LP col_name_list NK_RP */ @@ -4138,6 +4138,7 @@ static YYACTIONTYPE yy_reduce( yymsp[0].minor.yy110 = yylhsminor.yy110; break; case 125: /* retention_list ::= retention_list NK_COMMA retention */ + case 150: /* multi_drop_clause ::= multi_drop_clause NK_COMMA drop_table_clause */ yytestcase(yyruleno==150); case 157: /* column_def_list ::= column_def_list NK_COMMA column_def */ yytestcase(yyruleno==157); case 201: /* rollup_func_list ::= rollup_func_list NK_COMMA rollup_func_name */ yytestcase(yyruleno==201); case 206: /* col_name_list ::= col_name_list NK_COMMA col_name */ yytestcase(yyruleno==206); @@ -4225,7 +4226,6 @@ static YYACTIONTYPE yy_reduce( yymsp[-5].minor.yy42 = yylhsminor.yy42; break; case 147: /* multi_create_clause ::= multi_create_clause create_subtable_clause */ - case 150: /* multi_drop_clause ::= multi_drop_clause drop_table_clause */ yytestcase(yyruleno==150); case 434: /* when_then_list ::= when_then_list when_then_expr */ yytestcase(yyruleno==434); { yylhsminor.yy110 = addNodeToList(pCxt, yymsp[-1].minor.yy110, yymsp[0].minor.yy42); } yymsp[-1].minor.yy110 = yylhsminor.yy110; diff --git a/source/libs/parser/test/mockCatalogService.cpp b/source/libs/parser/test/mockCatalogService.cpp index 0d46b63278..71b7c1a678 100644 --- a/source/libs/parser/test/mockCatalogService.cpp +++ b/source/libs/parser/test/mockCatalogService.cpp @@ -331,7 +331,7 @@ class MockCatalogServiceImpl { info.dstTbUid = getNextId(); info.dstVgId = pReq->dstVgId; genEpSet(&info.epSet); - info.expr = strdup(pReq->expr); + info.expr = taosStrdup(pReq->expr); auto it = index_.find(pReq->stb); if (index_.end() == it) { index_.insert(std::make_pair(string(pReq->stb), std::vector{info})); @@ -374,7 +374,7 @@ class MockCatalogServiceImpl { STableIndexInfo* copyTableIndexInfo(STableIndexInfo* pDst, const STableIndexInfo* pSrc) const { memcpy(pDst, pSrc, sizeof(STableIndexInfo)); - pDst->expr = strdup(pSrc->expr); + pDst->expr = taosStrdup(pSrc->expr); return pDst; } diff --git a/source/libs/parser/test/parAlterToBalanceTest.cpp b/source/libs/parser/test/parAlterToBalanceTest.cpp index a0de93782d..bfcf6ec27e 100644 --- a/source/libs/parser/test/parAlterToBalanceTest.cpp +++ b/source/libs/parser/test/parAlterToBalanceTest.cpp @@ -382,7 +382,7 @@ TEST_F(ParserInitialATest, alterSTable) { expect.name[len] = '\0'; expect.alterType = alterType; if (nullptr != pComment) { - expect.comment = strdup(pComment); + expect.comment = taosStrdup(pComment); expect.commentLen = strlen(pComment); } diff --git a/source/libs/parser/test/parInitialCTest.cpp b/source/libs/parser/test/parInitialCTest.cpp index fab1fc4919..8ba5802ad6 100644 --- a/source/libs/parser/test/parInitialCTest.cpp +++ b/source/libs/parser/test/parInitialCTest.cpp @@ -603,7 +603,7 @@ TEST_F(ParserInitialCTest, createStable) { expect.deleteMark2 = deleteMark2; // expect.ttl = ttl; if (nullptr != pComment) { - expect.pComment = strdup(pComment); + expect.pComment = taosStrdup(pComment); expect.commentLen = strlen(pComment); } }; @@ -780,7 +780,7 @@ TEST_F(ParserInitialCTest, createStream) { snprintf(expect.sourceDB, sizeof(expect.sourceDB), "0.%s", pSrcDb); snprintf(expect.targetStbFullName, sizeof(expect.targetStbFullName), "0.test.%s", pDstStb); expect.igExists = igExists; - expect.sql = strdup(pSql); + expect.sql = taosStrdup(pSql); expect.createStb = STREAM_CREATE_STABLE_TRUE; expect.triggerType = STREAM_TRIGGER_AT_ONCE; expect.maxDelay = 0; @@ -934,13 +934,13 @@ TEST_F(ParserInitialCTest, createTable) { auto addCreateTbReq = [&](const char* pName, bool ignoreExists = false, int32_t ttl = TSDB_DEFAULT_TABLE_TTL, const char* pComment = nullptr) { SVCreateTbReq req = {0}; - req.name = strdup(pName); + req.name = taosStrdup(pName); if (ignoreExists) { req.flags |= TD_CREATE_IF_NOT_EXISTS; } req.ttl = ttl; if (nullptr != pComment) { - req.comment = strdup(pComment); + req.comment = taosStrdup(pComment); req.commentLen = strlen(pComment); } ++expect.nReqs; diff --git a/source/libs/parser/test/parInitialDTest.cpp b/source/libs/parser/test/parInitialDTest.cpp index 3d773d3510..203156ec88 100644 --- a/source/libs/parser/test/parInitialDTest.cpp +++ b/source/libs/parser/test/parInitialDTest.cpp @@ -245,6 +245,7 @@ TEST_F(ParserInitialDTest, dropTable) { useDb("root", "test"); run("DROP TABLE t1"); + run("DROP TABLE t1, st1s1, st1s2"); } TEST_F(ParserInitialDTest, dropTopic) { diff --git a/source/libs/qcom/src/queryUtil.c b/source/libs/qcom/src/queryUtil.c index d8cd5f4e75..c68a08682c 100644 --- a/source/libs/qcom/src/queryUtil.c +++ b/source/libs/qcom/src/queryUtil.c @@ -420,7 +420,7 @@ end: cJSON_Delete(json); taosArrayDestroy(pTagVals); if (string == NULL) { - string = strdup(TSDB_DATA_NULL_STR_L); + string = taosStrdup(TSDB_DATA_NULL_STR_L); } return string; } @@ -510,20 +510,20 @@ int32_t cloneSVreateTbReq(SVCreateTbReq* pSrc, SVCreateTbReq** pDst) { (*pDst)->flags = pSrc->flags; if (pSrc->name) { - (*pDst)->name = strdup(pSrc->name); + (*pDst)->name = taosStrdup(pSrc->name); } (*pDst)->uid = pSrc->uid; (*pDst)->ctime = pSrc->ctime; (*pDst)->ttl = pSrc->ttl; (*pDst)->commentLen = pSrc->commentLen; if (pSrc->comment) { - (*pDst)->comment = strdup(pSrc->comment); + (*pDst)->comment = taosStrdup(pSrc->comment); } (*pDst)->type = pSrc->type; if (pSrc->type == TSDB_CHILD_TABLE) { if (pSrc->ctb.stbName) { - (*pDst)->ctb.stbName = strdup(pSrc->ctb.stbName); + (*pDst)->ctb.stbName = taosStrdup(pSrc->ctb.stbName); } (*pDst)->ctb.tagNum = pSrc->ctb.tagNum; (*pDst)->ctb.suid = pSrc->ctb.suid; diff --git a/source/libs/qcom/src/querymsg.c b/source/libs/qcom/src/querymsg.c index 2e4b000761..d2934e1ff8 100644 --- a/source/libs/qcom/src/querymsg.c +++ b/source/libs/qcom/src/querymsg.c @@ -527,7 +527,7 @@ int32_t queryProcessGetSerVerRsp(void *output, char *msg, int32_t msgSize) { return code; } - *(char **)output = strdup(out.ver); + *(char **)output = taosStrdup(out.ver); return code; } diff --git a/source/libs/qworker/inc/qwInt.h b/source/libs/qworker/inc/qwInt.h index bd06572cb4..f198b73c7d 100644 --- a/source/libs/qworker/inc/qwInt.h +++ b/source/libs/qworker/inc/qwInt.h @@ -76,6 +76,7 @@ typedef struct SQWDebug { bool lockEnable; bool statusEnable; bool dumpEnable; + bool forceStop; bool sleepSimulate; bool deadSimulate; bool redirectSimulate; @@ -248,6 +249,7 @@ typedef struct SQWorkerMgmt { #define QW_QUERY_RUNNING(ctx) (QW_GET_PHASE(ctx) == QW_PHASE_PRE_QUERY || QW_GET_PHASE(ctx) == QW_PHASE_PRE_CQUERY) #define QW_FETCH_RUNNING(ctx) ((ctx)->inFetch) +#define QW_QUERY_NOT_STARTED(ctx) (QW_GET_PHASE(ctx) == -1) #define QW_SET_QTID(id, qId, tId, eId) \ do { \ diff --git a/source/libs/qworker/src/qwDbg.c b/source/libs/qworker/src/qwDbg.c index 7a755cd36f..0ab501ddd5 100644 --- a/source/libs/qworker/src/qwDbg.c +++ b/source/libs/qworker/src/qwDbg.c @@ -9,11 +9,13 @@ #include "tmsg.h" #include "tname.h" -SQWDebug gQWDebug = {.statusEnable = true, +SQWDebug gQWDebug = {.lockEnable = false, + .statusEnable = true, .dumpEnable = false, .redirectSimulate = false, .deadSimulate = false, - .sleepSimulate = false}; + .sleepSimulate = false, + .forceStop = false}; int32_t qwDbgValidateStatus(QW_FPARAMS_DEF, int8_t oriStatus, int8_t newStatus, bool *ignore) { if (!gQWDebug.statusEnable) { @@ -306,6 +308,12 @@ int32_t qwDbgEnableDebug(char *option) { return TSDB_CODE_SUCCESS; } + if (0 == strcasecmp(option, "forceStop")) { + gQWDebug.forceStop = true; + qError("qw forceStop debug enabled"); + return TSDB_CODE_SUCCESS; + } + qError("invalid qw debug option:%s", option); return TSDB_CODE_APP_ERROR; diff --git a/source/libs/qworker/src/qworker.c b/source/libs/qworker/src/qworker.c index 66acadc23b..ec4049a3eb 100644 --- a/source/libs/qworker/src/qworker.c +++ b/source/libs/qworker/src/qworker.c @@ -18,6 +18,50 @@ SQWorkerMgmt gQwMgmt = { .qwNum = 0, }; +int32_t qwStopAllTasks(SQWorker *mgmt) { + uint64_t qId, tId, sId; + int32_t eId; + int64_t rId = 0; + + void *pIter = taosHashIterate(mgmt->ctxHash, NULL); + while (pIter) { + SQWTaskCtx *ctx = (SQWTaskCtx *)pIter; + void *key = taosHashGetKey(pIter, NULL); + QW_GET_QTID(key, qId, tId, eId); + + QW_LOCK(QW_WRITE, &ctx->lock); + + sId = ctx->sId; + + QW_TASK_DLOG_E("start to force stop task"); + + if (QW_EVENT_RECEIVED(ctx, QW_EVENT_DROP) || QW_EVENT_PROCESSED(ctx, QW_EVENT_DROP)) { + QW_TASK_WLOG_E("task already dropping"); + QW_UNLOCK(QW_WRITE, &ctx->lock); + + pIter = taosHashIterate(mgmt->ctxHash, pIter); + continue; + } + + if (QW_QUERY_RUNNING(ctx)) { + qwKillTaskHandle(ctx, TSDB_CODE_VND_STOPPED); + QW_TASK_DLOG_E("task running, async killed"); + } else if (QW_FETCH_RUNNING(ctx)) { + QW_UPDATE_RSP_CODE(ctx, TSDB_CODE_VND_STOPPED); + QW_SET_EVENT_RECEIVED(ctx, QW_EVENT_DROP); + QW_TASK_DLOG_E("task fetching, update drop received"); + } else { + qwDropTask(QW_FPARAMS()); + } + + QW_UNLOCK(QW_WRITE, &ctx->lock); + + pIter = taosHashIterate(mgmt->ctxHash, pIter); + } + + return TSDB_CODE_SUCCESS; +} + int32_t qwProcessHbLinkBroken(SQWorker *mgmt, SQWMsg *qwMsg, SSchedulerHbReq *req) { int32_t code = 0; SSchedulerHbRsp rsp = {0}; @@ -202,7 +246,7 @@ _return: } bool qwTaskNotInExec(SQWTaskCtx *ctx) { - qTaskInfo_t taskHandle = ctx->taskHandle; + qTaskInfo_t taskHandle = ctx->taskHandle; if (NULL == taskHandle || !qTaskIsExecuting(taskHandle)) { return true; } @@ -758,7 +802,8 @@ int32_t qwProcessCQuery(QW_FPARAMS_DEF, SQWMsg *qwMsg) { } QW_LOCK(QW_WRITE, &ctx->lock); - if (atomic_load_8((int8_t*)&ctx->queryEnd) || (queryStop && (0 == atomic_load_8((int8_t *)&ctx->queryContinue))) || code) { + if (atomic_load_8((int8_t *)&ctx->queryEnd) || (queryStop && (0 == atomic_load_8((int8_t *)&ctx->queryContinue))) || + code) { // Note: query is not running anymore QW_SET_PHASE(ctx, QW_PHASE_POST_CQUERY); QW_UNLOCK(QW_WRITE, &ctx->lock); @@ -847,6 +892,9 @@ _return: qwBuildAndSendFetchRsp(qwMsg->msgType + 1, &qwMsg->connInfo, rsp, dataLen, code); QW_TASK_DLOG("%s send, handle:%p, code:%x - %s, dataLen:%d", TMSG_INFO(qwMsg->msgType + 1), qwMsg->connInfo.handle, code, tstrerror(code), dataLen); + } else { + qwFreeFetchRsp(rsp); + rsp = NULL; } } @@ -972,6 +1020,10 @@ void qwProcessHbTimerEvent(void *param, void *tmrId) { qwDbgDumpMgmtInfo(mgmt); + if (gQWDebug.forceStop) { + (void)qwStopAllTasks(mgmt); + } + QW_LOCK(QW_READ, &mgmt->schLock); int32_t schNum = taosHashGetSize(mgmt->schHash); @@ -1185,45 +1237,9 @@ void qWorkerStopAllTasks(void *qWorkerMgmt) { QW_DLOG("start to stop all tasks, taskNum:%d", taosHashGetSize(mgmt->ctxHash)); - uint64_t qId, tId, sId; - int32_t eId; - int64_t rId = 0; - atomic_store_8(&mgmt->nodeStopped, 1); - void *pIter = taosHashIterate(mgmt->ctxHash, NULL); - while (pIter) { - SQWTaskCtx *ctx = (SQWTaskCtx *)pIter; - void *key = taosHashGetKey(pIter, NULL); - QW_GET_QTID(key, qId, tId, eId); - - QW_LOCK(QW_WRITE, &ctx->lock); - - sId = ctx->sId; - - QW_TASK_DLOG_E("start to force stop task"); - - if (QW_EVENT_RECEIVED(ctx, QW_EVENT_DROP) || QW_EVENT_PROCESSED(ctx, QW_EVENT_DROP)) { - QW_TASK_WLOG_E("task already dropping"); - QW_UNLOCK(QW_WRITE, &ctx->lock); - - pIter = taosHashIterate(mgmt->ctxHash, pIter); - continue; - } - - if (QW_QUERY_RUNNING(ctx)) { - qwKillTaskHandle(ctx, TSDB_CODE_VND_STOPPED); - } else if (QW_FETCH_RUNNING(ctx)) { - QW_UPDATE_RSP_CODE(ctx, TSDB_CODE_VND_STOPPED); - QW_SET_EVENT_RECEIVED(ctx, QW_EVENT_DROP); - } else { - qwDropTask(QW_FPARAMS()); - } - - QW_UNLOCK(QW_WRITE, &ctx->lock); - - pIter = taosHashIterate(mgmt->ctxHash, pIter); - } + (void)qwStopAllTasks(mgmt); } void qWorkerDestroy(void **qWorkerMgmt) { diff --git a/source/libs/scalar/src/filter.c b/source/libs/scalar/src/filter.c index 25e65d2588..144a9536b9 100644 --- a/source/libs/scalar/src/filter.c +++ b/source/libs/scalar/src/filter.c @@ -15,7 +15,7 @@ #include #include "os.h" #include "thash.h" -//#include "queryLog.h" +// #include "queryLog.h" #include "filter.h" #include "filterInt.h" #include "functionMgt.h" @@ -123,36 +123,16 @@ int8_t filterGetRangeCompFuncFromOptrs(uint8_t optr, uint8_t optr2) { return -1; } -__compar_fn_t gDataCompare[] = {compareInt32Val, - compareInt8Val, - compareInt16Val, - compareInt64Val, - compareFloatVal, - compareDoubleVal, - compareLenPrefixedStr, - comparestrPatternMatch, - compareChkInString, - comparewcsPatternMatch, - compareLenPrefixedWStr, - compareUint8Val, - compareUint16Val, - compareUint32Val, - compareUint64Val, - setChkInBytes1, - setChkInBytes2, - setChkInBytes4, - setChkInBytes8, - comparestrRegexMatch, - comparestrRegexNMatch, - setChkNotInBytes1, - setChkNotInBytes2, - setChkNotInBytes4, - setChkNotInBytes8, - compareChkNotInString, - comparestrPatternNMatch, - comparewcsPatternNMatch, - comparewcsRegexMatch, - comparewcsRegexNMatch,}; +__compar_fn_t gDataCompare[] = { + compareInt32Val, compareInt8Val, compareInt16Val, compareInt64Val, + compareFloatVal, compareDoubleVal, compareLenPrefixedStr, comparestrPatternMatch, + compareChkInString, comparewcsPatternMatch, compareLenPrefixedWStr, compareUint8Val, + compareUint16Val, compareUint32Val, compareUint64Val, setChkInBytes1, + setChkInBytes2, setChkInBytes4, setChkInBytes8, comparestrRegexMatch, + comparestrRegexNMatch, setChkNotInBytes1, setChkNotInBytes2, setChkNotInBytes4, + setChkNotInBytes8, compareChkNotInString, comparestrPatternNMatch, comparewcsPatternNMatch, + comparewcsRegexMatch, comparewcsRegexNMatch, +}; __compar_fn_t gInt8SignCompare[] = {compareInt8Val, compareInt8Int16, compareInt8Int32, compareInt8Int64, compareInt8Float, compareInt8Double}; @@ -341,7 +321,7 @@ __compar_fn_t filterGetCompFuncEx(int32_t lType, int32_t rType, int32_t optr) { if (TSDB_DATA_TYPE_NULL == rType || TSDB_DATA_TYPE_JSON == rType) { return NULL; } - + switch (lType) { case TSDB_DATA_TYPE_TINYINT: { if (IS_SIGNED_NUMERIC_TYPE(rType) || IS_FLOAT_TYPE(rType)) { @@ -519,7 +499,7 @@ int32_t filterReuseRangeCtx(SFilterRangeCtx *ctx, int32_t type, int32_t options) int32_t filterConvertRange(SFilterRangeCtx *cur, SFilterRange *ra, bool *notNull) { int64_t tmp = 0; - + if (!FILTER_GET_FLAG(ra->sflag, RANGE_FLG_NULL)) { int32_t sr = cur->pCompareFunc(&ra->s, getDataMin(cur->type, &tmp)); if (sr == 0) { @@ -704,7 +684,7 @@ int32_t filterAddRangeImpl(void *h, SFilterRange *ra, int32_t optr) { int32_t filterAddRange(void *h, SFilterRange *ra, int32_t optr) { SFilterRangeCtx *ctx = (SFilterRangeCtx *)h; - int64_t tmp = 0; + int64_t tmp = 0; if (FILTER_GET_FLAG(ra->sflag, RANGE_FLG_NULL)) { SIMPLE_COPY_VALUES(&ra->s, getDataMin(ctx->type, &tmp)); @@ -991,7 +971,7 @@ int32_t filterAddField(SFilterInfo *info, void *desc, void **data, int32_t type, bool freeIfExists, int16_t *srcFlag) { int32_t idx = -1; uint32_t *num; - bool sameBuf = false; + bool sameBuf = false; num = &info->fields[type].num; @@ -1251,13 +1231,13 @@ int32_t filterAddUnitFromUnit(SFilterInfo *dst, SFilterInfo *src, SFilterUnit *u SFilterField *t = FILTER_UNIT_LEFT_FIELD(src, u); if (u->right.type == FLD_TYPE_VALUE) { - void *data = FILTER_UNIT_VAL_DATA(src, u); + void *data = FILTER_UNIT_VAL_DATA(src, u); SFilterField *rField = FILTER_UNIT_RIGHT_FIELD(src, u); if (IS_VAR_DATA_TYPE(type)) { if (FILTER_UNIT_OPTR(u) == OP_TYPE_IN) { - filterAddField(dst, NULL, &data, FLD_TYPE_VALUE, &right, POINTER_BYTES, - false, &rField->flag); // POINTER_BYTES should be sizeof(SHashObj), but POINTER_BYTES is also right. + filterAddField(dst, NULL, &data, FLD_TYPE_VALUE, &right, POINTER_BYTES, false, + &rField->flag); // POINTER_BYTES should be sizeof(SHashObj), but POINTER_BYTES is also right. t = FILTER_GET_FIELD(dst, right); FILTER_SET_FLAG(t->flag, FLD_DATA_IS_HASH); @@ -3120,9 +3100,8 @@ static FORCE_INLINE bool filterExecuteImplIsNull(void *pinfo, int32_t numOfRows, for (int32_t i = 0; i < numOfRows; ++i) { uint32_t uidx = info->groups[0].unitIdxs[0]; - void *colData = colDataGetData((SColumnInfoData *)info->cunits[uidx].colData, i); - p[i] = ((colData == NULL) || colDataIsNull((SColumnInfoData *)info->cunits[uidx].colData, 0, i, NULL)); + p[i] = colDataIsNull((SColumnInfoData *)info->cunits[uidx].colData, 0, i, NULL); if (p[i] == 0) { all = false; } else { @@ -3146,9 +3125,8 @@ static FORCE_INLINE bool filterExecuteImplNotNull(void *pinfo, int32_t numOfRows for (int32_t i = 0; i < numOfRows; ++i) { uint32_t uidx = info->groups[0].unitIdxs[0]; - void *colData = colDataGetData((SColumnInfoData *)info->cunits[uidx].colData, i); - p[i] = ((colData != NULL) && !colDataIsNull((SColumnInfoData *)info->cunits[uidx].colData, 0, i, NULL)); + p[i] = !colDataIsNull((SColumnInfoData *)info->cunits[uidx].colData, 0, i, NULL); if (p[i] == 0) { all = false; } else { @@ -3178,13 +3156,13 @@ bool filterExecuteImplRange(void *pinfo, int32_t numOfRows, SColumnInfoData *pRe for (int32_t i = 0; i < numOfRows; ++i) { SColumnInfoData *pData = info->cunits[0].colData; - void *colData = colDataGetData(pData, i); - if (colData == NULL || colDataIsNull_s(pData, i)) { + if (colDataIsNull_s(pData, i)) { all = false; p[i] = 0; continue; } + void *colData = colDataGetData(pData, i); p[i] = (*rfunc)(colData, colData, valData, valData2, func); if (p[i] == 0) { @@ -3210,13 +3188,13 @@ bool filterExecuteImplMisc(void *pinfo, int32_t numOfRows, SColumnInfoData *pRes for (int32_t i = 0; i < numOfRows; ++i) { uint32_t uidx = info->groups[0].unitIdxs[0]; - void *colData = colDataGetData((SColumnInfoData *)info->cunits[uidx].colData, i); - if (colData == NULL || colDataIsNull_s((SColumnInfoData *)info->cunits[uidx].colData, i)) { + if (colDataIsNull_s((SColumnInfoData *)info->cunits[uidx].colData, i)) { p[i] = 0; all = false; continue; } + void *colData = colDataGetData((SColumnInfoData *)info->cunits[uidx].colData, i); // match/nmatch for nchar type need convert from ucs4 to mbs if (info->cunits[uidx].dataType == TSDB_DATA_TYPE_NCHAR && (info->cunits[uidx].optr == OP_TYPE_MATCH || info->cunits[uidx].optr == OP_TYPE_NMATCH)) { @@ -3274,7 +3252,7 @@ bool filterExecuteImpl(void *pinfo, int32_t numOfRows, SColumnInfoData *pRes, SC if (!isNull) { colData = colDataGetData((SColumnInfoData *)(cunit->colData), i); } - + if (colData == NULL || isNull) { p[i] = optr == OP_TYPE_IS_NULL ? true : false; } else { @@ -3771,31 +3749,31 @@ EDealRes fltReviseRewriter(SNode **pNode, void *pContext) { return DEAL_RES_CONTINUE; } -/* - if (!FILTER_GET_FLAG(stat->info->options, FLT_OPTION_TIMESTAMP)) { - return DEAL_RES_CONTINUE; - } + /* + if (!FILTER_GET_FLAG(stat->info->options, FLT_OPTION_TIMESTAMP)) { + return DEAL_RES_CONTINUE; + } - if (TSDB_DATA_TYPE_BINARY != valueNode->node.resType.type && TSDB_DATA_TYPE_NCHAR != valueNode->node.resType.type) { - return DEAL_RES_CONTINUE; - } + if (TSDB_DATA_TYPE_BINARY != valueNode->node.resType.type && TSDB_DATA_TYPE_NCHAR != + valueNode->node.resType.type) { return DEAL_RES_CONTINUE; + } - if (stat->precision < 0) { - int32_t code = fltAddValueNodeToConverList(stat, valueNode); - if (code) { - stat->code = code; - return DEAL_RES_ERROR; - } + if (stat->precision < 0) { + int32_t code = fltAddValueNodeToConverList(stat, valueNode); + if (code) { + stat->code = code; + return DEAL_RES_ERROR; + } - return DEAL_RES_CONTINUE; - } + return DEAL_RES_CONTINUE; + } - int32_t code = sclConvertToTsValueNode(stat->precision, valueNode); - if (code) { - stat->code = code; - return DEAL_RES_ERROR; - } -*/ + int32_t code = sclConvertToTsValueNode(stat->precision, valueNode); + if (code) { + stat->code = code; + return DEAL_RES_ERROR; + } + */ return DEAL_RES_CONTINUE; } @@ -3941,7 +3919,7 @@ EDealRes fltReviseRewriter(SNode **pNode, void *pContext) { stat->scalarMode = true; return DEAL_RES_CONTINUE; } - int32_t type = vectorGetConvertType(refNode->node.resType.type, listNode->node.resType.type); + int32_t type = vectorGetConvertType(refNode->node.resType.type, listNode->node.resType.type); if (0 != type && type != refNode->node.resType.type) { stat->scalarMode = true; return DEAL_RES_CONTINUE; @@ -3965,14 +3943,14 @@ int32_t fltReviseNodes(SFilterInfo *pInfo, SNode **pNode, SFltTreeStat *pStat) { FLT_ERR_JRET(pStat->code); -/* - int32_t nodeNum = taosArrayGetSize(pStat->nodeList); - for (int32_t i = 0; i < nodeNum; ++i) { - SValueNode *valueNode = *(SValueNode **)taosArrayGet(pStat->nodeList, i); + /* + int32_t nodeNum = taosArrayGetSize(pStat->nodeList); + for (int32_t i = 0; i < nodeNum; ++i) { + SValueNode *valueNode = *(SValueNode **)taosArrayGet(pStat->nodeList, i); - FLT_ERR_JRET(sclConvertToTsValueNode(pStat->precision, valueNode)); - } -*/ + FLT_ERR_JRET(sclConvertToTsValueNode(pStat->precision, valueNode)); + } + */ _return: diff --git a/source/libs/scalar/src/scalar.c b/source/libs/scalar/src/scalar.c index c1e958b055..25938a7678 100644 --- a/source/libs/scalar/src/scalar.c +++ b/source/libs/scalar/src/scalar.c @@ -69,7 +69,7 @@ int32_t sclConvertValueToSclParam(SValueNode *pValueNode, SScalarParam *out, int return code; } - colDataAppend(in.columnData, 0, nodesGetValueFromNode(pValueNode), false); + colDataSetVal(in.columnData, 0, nodesGetValueFromNode(pValueNode), false); colInfoDataEnsureCapacity(out->columnData, 1, true); code = vectorConvertSingleColImpl(&in, out, overflow, -1, -1); @@ -337,9 +337,9 @@ int32_t sclInitParam(SNode *node, SScalarParam *param, SScalarCtx *ctx, int32_t SCL_RET(TSDB_CODE_OUT_OF_MEMORY); } if (TSDB_DATA_TYPE_NULL == valueNode->node.resType.type || valueNode->isNull) { - colDataAppendNULL(param->columnData, 0); + colDataSetNULL(param->columnData, 0); } else { - colDataAppend(param->columnData, 0, nodesGetValueFromNode(valueNode), false); + colDataSetVal(param->columnData, 0, nodesGetValueFromNode(valueNode), false); } break; } @@ -605,7 +605,7 @@ int32_t sclWalkCaseWhenList(SScalarCtx *ctx, SNodeList *pList, struct SListCell if (*equal) { bool isNull = colDataIsNull_s(pThen->columnData, (pThen->numOfRows > 1 ? rowIdx : 0)); char *pData = isNull ? NULL : colDataGetData(pThen->columnData, (pThen->numOfRows > 1 ? rowIdx : 0)); - colDataAppend(output->columnData, rowIdx, pData, isNull); + colDataSetVal(output->columnData, rowIdx, pData, isNull); if (0 == rowIdx && 1 == pCase->numOfRows && 1 == pWhen->numOfRows && 1 == pThen->numOfRows && totalRows > 1) { SCL_ERR_JRET(sclExtendResRows(output, output, ctx->pBlockList)); @@ -619,7 +619,7 @@ int32_t sclWalkCaseWhenList(SScalarCtx *ctx, SNodeList *pList, struct SListCell if (pElse) { bool isNull = colDataIsNull_s(pElse->columnData, (pElse->numOfRows > 1 ? rowIdx : 0)); char *pData = isNull ? NULL : colDataGetData(pElse->columnData, (pElse->numOfRows > 1 ? rowIdx : 0)); - colDataAppend(output->columnData, rowIdx, pData, isNull); + colDataSetVal(output->columnData, rowIdx, pData, isNull); if (0 == rowIdx && 1 == pCase->numOfRows && 1 == pElse->numOfRows && totalRows > 1) { SCL_ERR_JRET(sclExtendResRows(output, output, ctx->pBlockList)); @@ -629,7 +629,7 @@ int32_t sclWalkCaseWhenList(SScalarCtx *ctx, SNodeList *pList, struct SListCell goto _return; } - colDataAppend(output->columnData, rowIdx, NULL, true); + colDataSetVal(output->columnData, rowIdx, NULL, true); if (0 == rowIdx && 1 == pCase->numOfRows && totalRows > 1) { SCL_ERR_JRET(sclExtendResRows(output, output, ctx->pBlockList)); @@ -668,7 +668,7 @@ int32_t sclWalkWhenList(SScalarCtx *ctx, SNodeList *pList, struct SListCell *pCe if (*whenValue) { bool isNull = colDataIsNull_s(pThen->columnData, (pThen->numOfRows > 1 ? rowIdx : 0)); char *pData = isNull ? NULL : colDataGetData(pThen->columnData, (pThen->numOfRows > 1 ? rowIdx : 0)); - colDataAppend(output->columnData, rowIdx, pData, isNull); + colDataSetVal(output->columnData, rowIdx, pData, isNull); if (preSingle && 0 == rowIdx && 1 == pWhen->numOfRows && 1 == pThen->numOfRows && totalRows > 1) { SCL_ERR_JRET(sclExtendResRows(output, output, ctx->pBlockList)); @@ -687,7 +687,7 @@ int32_t sclWalkWhenList(SScalarCtx *ctx, SNodeList *pList, struct SListCell *pCe if (pElse) { bool isNull = colDataIsNull_s(pElse->columnData, (pElse->numOfRows > 1 ? rowIdx : 0)); char *pData = isNull ? NULL : colDataGetData(pElse->columnData, (pElse->numOfRows > 1 ? rowIdx : 0)); - colDataAppend(output->columnData, rowIdx, pData, isNull); + colDataSetVal(output->columnData, rowIdx, pData, isNull); if (preSingle && 0 == rowIdx && 1 == pElse->numOfRows && totalRows > 1) { SCL_ERR_JRET(sclExtendResRows(output, output, ctx->pBlockList)); @@ -697,7 +697,7 @@ int32_t sclWalkWhenList(SScalarCtx *ctx, SNodeList *pList, struct SListCell *pCe goto _return; } - colDataAppend(output->columnData, rowIdx, NULL, true); + colDataSetVal(output->columnData, rowIdx, NULL, true); if (preSingle && 0 == rowIdx && totalRows > 1) { SCL_ERR_JRET(sclExtendResRows(output, output, ctx->pBlockList)); @@ -815,7 +815,7 @@ int32_t sclExecLogic(SLogicConditionNode *node, SScalarCtx *ctx, SScalarParam *o } if (complete) { - colDataAppend(output->columnData, i, (char *)&value, false); + colDataSetVal(output->columnData, i, (char *)&value, false); if (value) { numOfQualified++; } @@ -920,7 +920,7 @@ int32_t sclExecCaseWhen(SCaseWhenNode *node, SScalarCtx *ctx, SScalarParam *outp for (int32_t i = 0; i < rowNum; ++i) { bool *equal = (bool *)colDataGetData(comp.columnData, (comp.numOfRows > 1 ? i : 0)); if (*equal) { - colDataAppend(output->columnData, i, colDataGetData(pThen->columnData, (pThen->numOfRows > 1 ? i : 0)), + colDataSetVal(output->columnData, i, colDataGetData(pThen->columnData, (pThen->numOfRows > 1 ? i : 0)), colDataIsNull_s(pThen->columnData, (pThen->numOfRows > 1 ? i : 0))); if (0 == i && 1 == pCase->numOfRows && 1 == pWhen->numOfRows && 1 == pThen->numOfRows && rowNum > 1) { SCL_ERR_JRET(sclExtendResRows(output, output, ctx->pBlockList)); @@ -938,7 +938,7 @@ int32_t sclExecCaseWhen(SCaseWhenNode *node, SScalarCtx *ctx, SScalarParam *outp for (int32_t i = 0; i < rowNum; ++i) { bool *whenValue = (bool *)colDataGetData(pWhen->columnData, (pWhen->numOfRows > 1 ? i : 0)); if (*whenValue) { - colDataAppend(output->columnData, i, colDataGetData(pThen->columnData, (pThen->numOfRows > 1 ? i : 0)), + colDataSetVal(output->columnData, i, colDataGetData(pThen->columnData, (pThen->numOfRows > 1 ? i : 0)), colDataIsNull_s(pThen->columnData, (pThen->numOfRows > 1 ? i : 0))); if (0 == i && 1 == pWhen->numOfRows && 1 == pThen->numOfRows && rowNum > 1) { SCL_ERR_JRET(sclExtendResRows(output, output, ctx->pBlockList)); diff --git a/source/libs/scalar/src/sclfunc.c b/source/libs/scalar/src/sclfunc.c index 411b9b7ab5..f4c3669574 100644 --- a/source/libs/scalar/src/sclfunc.c +++ b/source/libs/scalar/src/sclfunc.c @@ -43,7 +43,7 @@ int32_t absFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutpu float *out = (float *)pOutputData->pData; for (int32_t i = 0; i < pInput->numOfRows; ++i) { if (colDataIsNull_s(pInputData, i)) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); continue; } out[i] = (in[i] >= 0) ? in[i] : -in[i]; @@ -56,7 +56,7 @@ int32_t absFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutpu double *out = (double *)pOutputData->pData; for (int32_t i = 0; i < pInput->numOfRows; ++i) { if (colDataIsNull_s(pInputData, i)) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); continue; } out[i] = (in[i] >= 0) ? in[i] : -in[i]; @@ -69,7 +69,7 @@ int32_t absFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutpu int8_t *out = (int8_t *)pOutputData->pData; for (int32_t i = 0; i < pInput->numOfRows; ++i) { if (colDataIsNull_s(pInputData, i)) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); continue; } out[i] = (in[i] >= 0) ? in[i] : -in[i]; @@ -82,7 +82,7 @@ int32_t absFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutpu int16_t *out = (int16_t *)pOutputData->pData; for (int32_t i = 0; i < pInput->numOfRows; ++i) { if (colDataIsNull_s(pInputData, i)) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); continue; } out[i] = (in[i] >= 0) ? in[i] : -in[i]; @@ -95,7 +95,7 @@ int32_t absFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutpu int32_t *out = (int32_t *)pOutputData->pData; for (int32_t i = 0; i < pInput->numOfRows; ++i) { if (colDataIsNull_s(pInputData, i)) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); continue; } out[i] = (in[i] >= 0) ? in[i] : -in[i]; @@ -108,7 +108,7 @@ int32_t absFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutpu int64_t *out = (int64_t *)pOutputData->pData; for (int32_t i = 0; i < pInput->numOfRows; ++i) { if (colDataIsNull_s(pInputData, i)) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); continue; } out[i] = (in[i] >= 0) ? in[i] : -in[i]; @@ -118,7 +118,7 @@ int32_t absFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutpu case TSDB_DATA_TYPE_NULL: { for (int32_t i = 0; i < pInput->numOfRows; ++i) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); } break; } @@ -144,12 +144,12 @@ static int32_t doScalarFunctionUnique(SScalarParam *pInput, int32_t inputNum, SS for (int32_t i = 0; i < pInput->numOfRows; ++i) { if (colDataIsNull_s(pInputData, i) || IS_NULL_TYPE(type)) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); continue; } double result = valFn(getValueFn(pInputData->pData, i)); if (isinf(result) || isnan(result)) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); } else { out[i] = result; } @@ -179,29 +179,29 @@ static int32_t doScalarFunctionUnique2(SScalarParam *pInput, int32_t inputNum, S if (pInput[0].numOfRows == pInput[1].numOfRows) { for (int32_t i = 0; i < numOfRows; ++i) { if (colDataIsNull_s(pInputData[0], i) || colDataIsNull_s(pInputData[1], i) || hasNullType) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); continue; } result = valFn(getValueFn[0](pInputData[0]->pData, i), getValueFn[1](pInputData[1]->pData, i)); if (isinf(result) || isnan(result)) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); } else { out[i] = result; } } } else if (pInput[0].numOfRows == 1) { // left operand is constant if (colDataIsNull_s(pInputData[0], 0) || hasNullType) { - colDataAppendNNULL(pOutputData, 0, pInput[1].numOfRows); + colDataSetNNULL(pOutputData, 0, pInput[1].numOfRows); } else { for (int32_t i = 0; i < numOfRows; ++i) { if (colDataIsNull_s(pInputData[1], i)) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); continue; } result = valFn(getValueFn[0](pInputData[0]->pData, 0), getValueFn[1](pInputData[1]->pData, i)); if (isinf(result) || isnan(result)) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); continue; } @@ -210,17 +210,17 @@ static int32_t doScalarFunctionUnique2(SScalarParam *pInput, int32_t inputNum, S } } else if (pInput[1].numOfRows == 1) { if (colDataIsNull_s(pInputData[1], 0) || hasNullType) { - colDataAppendNNULL(pOutputData, 0, pInput[0].numOfRows); + colDataSetNNULL(pOutputData, 0, pInput[0].numOfRows); } else { for (int32_t i = 0; i < numOfRows; ++i) { if (colDataIsNull_s(pInputData[0], i)) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); continue; } result = valFn(getValueFn[0](pInputData[0]->pData, i), getValueFn[1](pInputData[1]->pData, 0)); if (isinf(result) || isnan(result)) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); continue; } @@ -247,7 +247,7 @@ static int32_t doScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarP for (int32_t i = 0; i < pInput->numOfRows; ++i) { if (colDataIsNull_s(pInputData, i)) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); continue; } out[i] = f1(in[i]); @@ -261,7 +261,7 @@ static int32_t doScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarP for (int32_t i = 0; i < pInput->numOfRows; ++i) { if (colDataIsNull_s(pInputData, i)) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); continue; } out[i] = d1(in[i]); @@ -271,7 +271,7 @@ static int32_t doScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarP case TSDB_DATA_TYPE_NULL: { for (int32_t i = 0; i < pInput->numOfRows; ++i) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); } break; } @@ -365,7 +365,7 @@ static int32_t doLengthFunction(SScalarParam *pInput, int32_t inputNum, SScalarP for (int32_t i = 0; i < pInput->numOfRows; ++i) { if (colDataIsNull_s(pInputData, i)) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); continue; } @@ -447,7 +447,7 @@ int32_t concatFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOu bool hasNull = false; for (int32_t i = 0; i < inputNum; ++i) { if (colDataIsNull_s(pInputData[i], k) || IS_NULL_TYPE(GET_PARAM_TYPE(&pInput[i]))) { - colDataAppendNULL(pOutputData, k); + colDataSetNULL(pOutputData, k); hasNull = true; break; } @@ -468,7 +468,7 @@ int32_t concatFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOu } } varDataSetLen(output, dataLen); - colDataAppend(pOutputData, k, output, false); + colDataSetVal(pOutputData, k, output, false); output += varDataTLen(output); } @@ -522,7 +522,7 @@ int32_t concatWsFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *p for (int32_t k = 0; k < numOfRows; ++k) { if (colDataIsNull_s(pInputData[0], k) || IS_NULL_TYPE(GET_PARAM_TYPE(&pInput[0]))) { - colDataAppendNULL(pOutputData, k); + colDataSetNULL(pOutputData, k); continue; } @@ -553,11 +553,11 @@ int32_t concatWsFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *p } if (hasNull) { - colDataAppendNULL(pOutputData, k); + colDataSetNULL(pOutputData, k); memset(output, 0, dataLen); } else { varDataSetLen(output, dataLen); - colDataAppend(pOutputData, k, output, false); + colDataSetVal(pOutputData, k, output, false); output += varDataTLen(output); } } @@ -584,7 +584,7 @@ static int32_t doCaseConvFunction(SScalarParam *pInput, int32_t inputNum, SScala for (int32_t i = 0; i < pInput->numOfRows; ++i) { if (colDataIsNull_s(pInputData, i)) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); continue; } @@ -600,7 +600,7 @@ static int32_t doCaseConvFunction(SScalarParam *pInput, int32_t inputNum, SScala } } varDataSetLen(output, len); - colDataAppend(pOutputData, i, output, false); + colDataSetVal(pOutputData, i, output, false); output += varDataTLen(output); } @@ -622,7 +622,7 @@ static int32_t doTrimFunction(SScalarParam *pInput, int32_t inputNum, SScalarPar for (int32_t i = 0; i < pInput->numOfRows; ++i) { if (colDataIsNull_s(pInputData, i)) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); continue; } @@ -631,7 +631,7 @@ static int32_t doTrimFunction(SScalarParam *pInput, int32_t inputNum, SScalarPar int32_t charLen = (type == TSDB_DATA_TYPE_VARCHAR) ? len : len / TSDB_NCHAR_SIZE; trimFn(input, output, type, charLen); - colDataAppend(pOutputData, i, output, false); + colDataSetVal(pOutputData, i, output, false); output += varDataTLen(output); } @@ -660,7 +660,7 @@ int32_t substrFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOu for (int32_t i = 0; i < pInput->numOfRows; ++i) { if (colDataIsNull_s(pInputData, i)) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); continue; } char *input = colDataGetData(pInput[0].columnData, i); @@ -682,7 +682,7 @@ int32_t substrFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOu } varDataSetLen(output, resLen); - colDataAppend(pOutputData, i, output, false); + colDataSetVal(pOutputData, i, output, false); output += varDataTLen(output); } @@ -711,7 +711,7 @@ int32_t castFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutp for (int32_t i = 0; i < pInput[0].numOfRows; ++i) { if (colDataIsNull_s(pInput[0].columnData, i)) { - colDataAppendNULL(pOutput->columnData, i); + colDataSetNULL(pOutput->columnData, i); continue; } @@ -1014,7 +1014,7 @@ int32_t castFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutp } } - colDataAppend(pOutput->columnData, i, output, false); + colDataSetVal(pOutput->columnData, i, output, false); } pOutput->numOfRows = pInput->numOfRows; @@ -1038,7 +1038,7 @@ int32_t toISO8601Function(SScalarParam *pInput, int32_t inputNum, SScalarParam * for (int32_t i = 0; i < pInput[0].numOfRows; ++i) { if (colDataIsNull_s(pInput[0].columnData, i)) { - colDataAppendNULL(pOutput->columnData, i); + colDataSetNULL(pOutput->columnData, i); continue; } @@ -1059,7 +1059,7 @@ int32_t toISO8601Function(SScalarParam *pInput, int32_t inputNum, SScalarParam * } else if (tsDigits == TSDB_TIME_PRECISION_NANO_DIGITS) { timeVal = timeVal / (1000 * 1000 * 1000); } else { - colDataAppendNULL(pOutput->columnData, i); + colDataSetNULL(pOutput->columnData, i); continue; } hasFraction = true; @@ -1106,7 +1106,7 @@ int32_t toISO8601Function(SScalarParam *pInput, int32_t inputNum, SScalarParam * memmove(buf + VARSTR_HEADER_SIZE, buf, len); varDataSetLen(buf, len); - colDataAppend(pOutput->columnData, i, buf, false); + colDataSetVal(pOutput->columnData, i, buf, false); } pOutput->numOfRows = pInput->numOfRows; @@ -1121,7 +1121,7 @@ int32_t toUnixtimestampFunction(SScalarParam *pInput, int32_t inputNum, SScalarP for (int32_t i = 0; i < pInput[0].numOfRows; ++i) { if (colDataIsNull_s(pInput[0].columnData, i)) { - colDataAppendNULL(pOutput->columnData, i); + colDataSetNULL(pOutput->columnData, i); continue; } char *input = colDataGetData(pInput[0].columnData, i); @@ -1129,9 +1129,9 @@ int32_t toUnixtimestampFunction(SScalarParam *pInput, int32_t inputNum, SScalarP int64_t timeVal = 0; int32_t ret = convertStringToTimestamp(type, input, timePrec, &timeVal); if (ret != TSDB_CODE_SUCCESS) { - colDataAppendNULL(pOutput->columnData, i); + colDataSetNULL(pOutput->columnData, i); } else { - colDataAppend(pOutput->columnData, i, (char *)&timeVal, false); + colDataSetVal(pOutput->columnData, i, (char *)&timeVal, false); } } @@ -1163,7 +1163,7 @@ int32_t toJsonFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOu } } - colDataAppend(pOutput->columnData, i, (const char *)pTag, false); + colDataSetVal(pOutput->columnData, i, (const char *)pTag, false); tTagFree(pTag); taosArrayDestroy(pTagVals); } @@ -1208,7 +1208,7 @@ int32_t timeTruncateFunction(SScalarParam *pInput, int32_t inputNum, SScalarPara for (int32_t i = 0; i < pInput[0].numOfRows; ++i) { if (colDataIsNull_s(pInput[0].columnData, i)) { - colDataAppendNULL(pOutput->columnData, i); + colDataSetNULL(pOutput->columnData, i); continue; } @@ -1217,7 +1217,7 @@ int32_t timeTruncateFunction(SScalarParam *pInput, int32_t inputNum, SScalarPara if (IS_VAR_DATA_TYPE(type)) { /* datetime format strings */ int32_t ret = convertStringToTimestamp(type, input, TSDB_TIME_PRECISION_NANO, &timeVal); if (ret != TSDB_CODE_SUCCESS) { - colDataAppendNULL(pOutput->columnData, i); + colDataSetNULL(pOutput->columnData, i); continue; } // If converted value is less than 10digits in second, use value in second instead @@ -1264,7 +1264,7 @@ int32_t timeTruncateFunction(SScalarParam *pInput, int32_t inputNum, SScalarPara } else if (tsDigits <= TSDB_TIME_PRECISION_SEC_DIGITS) { timeVal = timeVal * factor; } else { - colDataAppendNULL(pOutput->columnData, i); + colDataSetNULL(pOutput->columnData, i); continue; } break; @@ -1279,7 +1279,7 @@ int32_t timeTruncateFunction(SScalarParam *pInput, int32_t inputNum, SScalarPara } else if (tsDigits <= TSDB_TIME_PRECISION_SEC_DIGITS) { timeVal = timeVal * factor; } else { - colDataAppendNULL(pOutput->columnData, i); + colDataSetNULL(pOutput->columnData, i); continue; } break; @@ -1294,7 +1294,7 @@ int32_t timeTruncateFunction(SScalarParam *pInput, int32_t inputNum, SScalarPara } else if (tsDigits <= TSDB_TIME_PRECISION_SEC_DIGITS) { timeVal = timeVal * factor / factor / 60 * 60 * factor; } else { - colDataAppendNULL(pOutput->columnData, i); + colDataSetNULL(pOutput->columnData, i); continue; } break; @@ -1309,7 +1309,7 @@ int32_t timeTruncateFunction(SScalarParam *pInput, int32_t inputNum, SScalarPara } else if (tsDigits <= TSDB_TIME_PRECISION_SEC_DIGITS) { timeVal = timeVal * factor / factor / 3600 * 3600 * factor; } else { - colDataAppendNULL(pOutput->columnData, i); + colDataSetNULL(pOutput->columnData, i); continue; } break; @@ -1340,7 +1340,7 @@ int32_t timeTruncateFunction(SScalarParam *pInput, int32_t inputNum, SScalarPara timeVal = timeVal * factor / factor / 86400 * 86400 * factor; } } else { - colDataAppendNULL(pOutput->columnData, i); + colDataSetNULL(pOutput->columnData, i); continue; } break; @@ -1355,7 +1355,7 @@ int32_t timeTruncateFunction(SScalarParam *pInput, int32_t inputNum, SScalarPara } else if (tsDigits <= TSDB_TIME_PRECISION_SEC_DIGITS) { timeVal = timeVal * factor / factor / 604800 * 604800 * factor; } else { - colDataAppendNULL(pOutput->columnData, i); + colDataSetNULL(pOutput->columnData, i); continue; } break; @@ -1394,7 +1394,7 @@ int32_t timeTruncateFunction(SScalarParam *pInput, int32_t inputNum, SScalarPara } } - colDataAppend(pOutput->columnData, i, (char *)&timeVal, false); + colDataSetVal(pOutput->columnData, i, (char *)&timeVal, false); } pOutput->numOfRows = pInput->numOfRows; @@ -1466,7 +1466,7 @@ int32_t timeDiffFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *p } if (hasNull) { - colDataAppendNULL(pOutput->columnData, i); + colDataSetNULL(pOutput->columnData, i); continue; } @@ -1528,7 +1528,7 @@ int32_t timeDiffFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *p } } - colDataAppend(pOutput->columnData, i, (char *)&result, false); + colDataSetVal(pOutput->columnData, i, (char *)&result, false); } pOutput->numOfRows = numOfRows; @@ -1542,7 +1542,7 @@ int32_t nowFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutpu int64_t ts = taosGetTimestamp(timePrec); for (int32_t i = 0; i < pInput->numOfRows; ++i) { - colDataAppendInt64(pOutput->columnData, i, &ts); + colDataSetInt64(pOutput->columnData, i, &ts); } pOutput->numOfRows = pInput->numOfRows; return TSDB_CODE_SUCCESS; @@ -1554,7 +1554,7 @@ int32_t todayFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOut int64_t ts = taosGetTimestampToday(timePrec); for (int32_t i = 0; i < pInput->numOfRows; ++i) { - colDataAppendInt64(pOutput->columnData, i, &ts); + colDataSetInt64(pOutput->columnData, i, &ts); } pOutput->numOfRows = pInput->numOfRows; return TSDB_CODE_SUCCESS; @@ -1565,7 +1565,7 @@ int32_t timezoneFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *p memcpy(varDataVal(output), tsTimezoneStr, TD_TIMEZONE_LEN); varDataSetLen(output, strlen(tsTimezoneStr)); for (int32_t i = 0; i < pInput->numOfRows; ++i) { - colDataAppend(pOutput->columnData, i, output, false); + colDataSetVal(pOutput->columnData, i, output, false); } pOutput->numOfRows = pInput->numOfRows; return TSDB_CODE_SUCCESS; @@ -1728,34 +1728,34 @@ bool getTimePseudoFuncEnv(SFunctionNode *UNUSED_PARAM(pFunc), SFuncExecEnv *pEnv } int32_t qStartTsFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) { - colDataAppendInt64(pOutput->columnData, pOutput->numOfRows, (int64_t *)colDataGetData(pInput->columnData, 0)); + colDataSetInt64(pOutput->columnData, pOutput->numOfRows, (int64_t *)colDataGetData(pInput->columnData, 0)); return TSDB_CODE_SUCCESS; } int32_t qEndTsFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) { - colDataAppendInt64(pOutput->columnData, pOutput->numOfRows, (int64_t *)colDataGetData(pInput->columnData, 1)); + colDataSetInt64(pOutput->columnData, pOutput->numOfRows, (int64_t *)colDataGetData(pInput->columnData, 1)); return TSDB_CODE_SUCCESS; } int32_t winDurFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) { - colDataAppendInt64(pOutput->columnData, pOutput->numOfRows, (int64_t *)colDataGetData(pInput->columnData, 2)); + colDataSetInt64(pOutput->columnData, pOutput->numOfRows, (int64_t *)colDataGetData(pInput->columnData, 2)); return TSDB_CODE_SUCCESS; } int32_t winStartTsFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) { - colDataAppendInt64(pOutput->columnData, pOutput->numOfRows, (int64_t *)colDataGetData(pInput->columnData, 3)); + colDataSetInt64(pOutput->columnData, pOutput->numOfRows, (int64_t *)colDataGetData(pInput->columnData, 3)); return TSDB_CODE_SUCCESS; } int32_t winEndTsFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) { - colDataAppendInt64(pOutput->columnData, pOutput->numOfRows, (int64_t *)colDataGetData(pInput->columnData, 4)); + colDataSetInt64(pOutput->columnData, pOutput->numOfRows, (int64_t *)colDataGetData(pInput->columnData, 4)); return TSDB_CODE_SUCCESS; } int32_t qTbnameFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) { char* p = colDataGetVarData(pInput->columnData, 0); - colDataAppendNItems(pOutput->columnData, pOutput->numOfRows, p, pInput->numOfRows); + colDataSetNItems(pOutput->columnData, pOutput->numOfRows, p, pInput->numOfRows); pOutput->numOfRows += pInput->numOfRows; return TSDB_CODE_SUCCESS; } @@ -1833,7 +1833,7 @@ int32_t sumScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam * } if (hasNull) { - colDataAppendNULL(pOutputData, 0); + colDataSetNULL(pOutputData, 0); } pOutput->numOfRows = 1; @@ -1945,7 +1945,7 @@ static int32_t doMinMaxScalarFunction(SScalarParam *pInput, int32_t inputNum, SS } if (hasNull) { - colDataAppendNULL(pOutputData, 0); + colDataSetNULL(pOutputData, 0); } pOutput->numOfRows = 1; @@ -2049,7 +2049,7 @@ int32_t avgScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam * } if (hasNull || (count == 0)) { - colDataAppendNULL(pOutputData, 0); + colDataSetNULL(pOutputData, 0); } else { if (IS_SIGNED_NUMERIC_TYPE(type)) { int64_t *out = (int64_t *)pOutputData->pData; @@ -2158,7 +2158,7 @@ int32_t stddevScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarPara double *out = (double *)pOutputData->pData; if (hasNull) { - colDataAppendNULL(pOutputData, 0); + colDataSetNULL(pOutputData, 0); } else { *out = 0; #if 0 @@ -2325,7 +2325,7 @@ int32_t leastSQRScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarPa } if (count == 0) { - colDataAppendNULL(pOutputData, 0); + colDataSetNULL(pOutputData, 0); } else { matrix[1][1] = (double)count; matrix[1][0] = matrix[0][1]; @@ -2341,7 +2341,7 @@ int32_t leastSQRScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarPa size_t len = snprintf(varDataVal(buf), sizeof(buf) - VARSTR_HEADER_SIZE, "{slop:%.6lf, intercept:%.6lf}", matrix02, matrix12); varDataSetLen(buf, len); - colDataAppend(pOutputData, 0, buf, false); + colDataSetVal(pOutputData, 0, buf, false); } pOutput->numOfRows = 1; @@ -2366,9 +2366,9 @@ int32_t percentileScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalar } if (hasNull) { - colDataAppendNULL(pOutputData, 0); + colDataSetNULL(pOutputData, 0); } else { - colDataAppend(pOutputData, 0, (char *)&val, false); + colDataSetVal(pOutputData, 0, (char *)&val, false); } pOutput->numOfRows = 1; @@ -2411,10 +2411,10 @@ int32_t spreadScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarPara } if (hasNull) { - colDataAppendNULL(pOutputData, 0); + colDataSetNULL(pOutputData, 0); } else { double result = max - min; - colDataAppend(pOutputData, 0, (char *)&result, false); + colDataSetVal(pOutputData, 0, (char *)&result, false); } pOutput->numOfRows = 1; @@ -2437,7 +2437,7 @@ int32_t nonCalcScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarPar double *out = (double *)pOutputData->pData; if (hasNull) { - colDataAppendNULL(pOutputData, 0); + colDataSetNULL(pOutputData, 0); } else { *out = 0; } @@ -2606,7 +2606,7 @@ int32_t stateCountScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalar for (int32_t i = 0; i < pInput->numOfRows; ++i) { if (colDataIsNull_s(pInputData, i)) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); continue; } @@ -2617,7 +2617,7 @@ int32_t stateCountScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalar } else { count = 0; } - colDataAppend(pOutputData, i, (char *)&out, false); + colDataSetVal(pOutputData, i, (char *)&out, false); } pOutput->numOfRows = pInput->numOfRows; @@ -2632,7 +2632,7 @@ int32_t stateDurationScalarFunction(SScalarParam *pInput, int32_t inputNum, SSca for (int32_t i = 0; i < pInput->numOfRows; ++i) { if (colDataIsNull_s(pInputData, i)) { - colDataAppendNULL(pOutputData, i); + colDataSetNULL(pOutputData, i); continue; } @@ -2641,7 +2641,7 @@ int32_t stateDurationScalarFunction(SScalarParam *pInput, int32_t inputNum, SSca if (ret) { out = 0; } - colDataAppend(pOutputData, i, (char *)&out, false); + colDataSetVal(pOutputData, i, (char *)&out, false); } pOutput->numOfRows = pInput->numOfRows; @@ -2882,7 +2882,7 @@ int32_t histogramScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarP bins[k].upper, bins[k].percentage); } varDataSetLen(buf, len); - colDataAppend(pOutputData, k, buf, false); + colDataSetVal(pOutputData, k, buf, false); } taosMemoryFree(bins); @@ -2898,12 +2898,12 @@ int32_t selectScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarPara for (int32_t i = 0; i < pInput->numOfRows; ++i) { if (colDataIsNull_s(pInputData, i)) { - colDataAppendNULL(pOutputData, 0); + colDataSetNULL(pOutputData, 0); continue; } char *data = colDataGetData(pInputData, i); - colDataAppend(pOutputData, i, data, false); + colDataSetVal(pOutputData, i, data, false); } pOutput->numOfRows = 1; diff --git a/source/libs/scalar/src/sclvector.c b/source/libs/scalar/src/sclvector.c index e9f345215e..3fe016d444 100644 --- a/source/libs/scalar/src/sclvector.c +++ b/source/libs/scalar/src/sclvector.c @@ -242,7 +242,7 @@ static FORCE_INLINE void varToTimestamp(char *buf, SScalarParam *pOut, int32_t r value = 0; } - colDataAppendInt64(pOut->columnData, rowIndex, &value); + colDataSetInt64(pOut->columnData, rowIndex, &value); } static FORCE_INLINE void varToSigned(char *buf, SScalarParam *pOut, int32_t rowIndex, int32_t *overflow) { @@ -265,22 +265,22 @@ static FORCE_INLINE void varToSigned(char *buf, SScalarParam *pOut, int32_t rowI case TSDB_DATA_TYPE_TINYINT: { int8_t value = (int8_t)taosStr2Int8(buf, NULL, 10); - colDataAppendInt8(pOut->columnData, rowIndex, (int8_t *)&value); + colDataSetInt8(pOut->columnData, rowIndex, (int8_t *)&value); break; } case TSDB_DATA_TYPE_SMALLINT: { int16_t value = (int16_t)taosStr2Int16(buf, NULL, 10); - colDataAppendInt16(pOut->columnData, rowIndex, (int16_t *)&value); + colDataSetInt16(pOut->columnData, rowIndex, (int16_t *)&value); break; } case TSDB_DATA_TYPE_INT: { int32_t value = (int32_t)taosStr2Int32(buf, NULL, 10); - colDataAppendInt32(pOut->columnData, rowIndex, (int32_t *)&value); + colDataSetInt32(pOut->columnData, rowIndex, (int32_t *)&value); break; } case TSDB_DATA_TYPE_BIGINT: { int64_t value = (int64_t)taosStr2Int64(buf, NULL, 10); - colDataAppendInt64(pOut->columnData, rowIndex, (int64_t *)&value); + colDataSetInt64(pOut->columnData, rowIndex, (int64_t *)&value); break; } } @@ -305,22 +305,22 @@ static FORCE_INLINE void varToUnsigned(char *buf, SScalarParam *pOut, int32_t ro switch (pOut->columnData->info.type) { case TSDB_DATA_TYPE_UTINYINT: { uint8_t value = (uint8_t)taosStr2UInt8(buf, NULL, 10); - colDataAppendInt8(pOut->columnData, rowIndex, (int8_t *)&value); + colDataSetInt8(pOut->columnData, rowIndex, (int8_t *)&value); break; } case TSDB_DATA_TYPE_USMALLINT: { uint16_t value = (uint16_t)taosStr2UInt16(buf, NULL, 10); - colDataAppendInt16(pOut->columnData, rowIndex, (int16_t *)&value); + colDataSetInt16(pOut->columnData, rowIndex, (int16_t *)&value); break; } case TSDB_DATA_TYPE_UINT: { uint32_t value = (uint32_t)taosStr2UInt32(buf, NULL, 10); - colDataAppendInt32(pOut->columnData, rowIndex, (int32_t *)&value); + colDataSetInt32(pOut->columnData, rowIndex, (int32_t *)&value); break; } case TSDB_DATA_TYPE_UBIGINT: { uint64_t value = (uint64_t)taosStr2UInt64(buf, NULL, 10); - colDataAppendInt64(pOut->columnData, rowIndex, (int64_t *)&value); + colDataSetInt64(pOut->columnData, rowIndex, (int64_t *)&value); break; } } @@ -329,18 +329,18 @@ static FORCE_INLINE void varToUnsigned(char *buf, SScalarParam *pOut, int32_t ro static FORCE_INLINE void varToFloat(char *buf, SScalarParam *pOut, int32_t rowIndex, int32_t *overflow) { if (TSDB_DATA_TYPE_FLOAT == pOut->columnData->info.type) { float value = taosStr2Float(buf, NULL); - colDataAppendFloat(pOut->columnData, rowIndex, &value); + colDataSetFloat(pOut->columnData, rowIndex, &value); return; } double value = taosStr2Double(buf, NULL); - colDataAppendDouble(pOut->columnData, rowIndex, &value); + colDataSetDouble(pOut->columnData, rowIndex, &value); } static FORCE_INLINE void varToBool(char *buf, SScalarParam *pOut, int32_t rowIndex, int32_t *overflow) { int64_t value = taosStr2Int64(buf, NULL, 10); bool v = (value != 0) ? true : false; - colDataAppendInt8(pOut->columnData, rowIndex, (int8_t *)&v); + colDataSetInt8(pOut->columnData, rowIndex, (int8_t *)&v); } // todo remove this malloc @@ -357,7 +357,7 @@ static FORCE_INLINE void varToNchar(char *buf, SScalarParam *pOut, int32_t rowIn } varDataSetLen(t, len); - colDataAppend(pOut->columnData, rowIndex, t, false); + colDataSetVal(pOut->columnData, rowIndex, t, false); taosMemoryFree(t); } @@ -372,7 +372,7 @@ static FORCE_INLINE void ncharToVar(char *buf, SScalarParam *pOut, int32_t rowIn } varDataSetLen(t, len); - colDataAppend(pOut->columnData, rowIndex, t, false); + colDataSetVal(pOut->columnData, rowIndex, t, false); taosMemoryFree(t); } @@ -409,7 +409,7 @@ int32_t vectorConvertFromVarData(SSclVectorConvCtx *pCtx, int32_t *overflow) { for (int32_t i = pCtx->startIndex; i <= pCtx->endIndex; ++i) { if (IS_HELPER_NULL(pCtx->pIn->columnData, i)) { - colDataAppendNULL(pCtx->pOut->columnData, i); + colDataSetNULL(pCtx->pOut->columnData, i); continue; } @@ -599,7 +599,7 @@ int32_t vectorConvertToVarData(SSclVectorConvCtx *pCtx) { pCtx->inType == TSDB_DATA_TYPE_TIMESTAMP) { for (int32_t i = pCtx->startIndex; i <= pCtx->endIndex; ++i) { if (colDataIsNull_f(pInputCol->nullbitmap, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } @@ -610,13 +610,13 @@ int32_t vectorConvertToVarData(SSclVectorConvCtx *pCtx) { if (pCtx->outType == TSDB_DATA_TYPE_NCHAR) { varToNchar(tmp, pCtx->pOut, i, NULL); } else { - colDataAppend(pOutputCol, i, (char *)tmp, false); + colDataSetVal(pOutputCol, i, (char *)tmp, false); } } } else if (IS_UNSIGNED_NUMERIC_TYPE(pCtx->inType)) { for (int32_t i = pCtx->startIndex; i <= pCtx->endIndex; ++i) { if (colDataIsNull_f(pInputCol->nullbitmap, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } @@ -627,13 +627,13 @@ int32_t vectorConvertToVarData(SSclVectorConvCtx *pCtx) { if (pCtx->outType == TSDB_DATA_TYPE_NCHAR) { varToNchar(tmp, pCtx->pOut, i, NULL); } else { - colDataAppend(pOutputCol, i, (char *)tmp, false); + colDataSetVal(pOutputCol, i, (char *)tmp, false); } } } else if (IS_FLOAT_TYPE(pCtx->inType)) { for (int32_t i = pCtx->startIndex; i <= pCtx->endIndex; ++i) { if (colDataIsNull_f(pInputCol->nullbitmap, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } @@ -644,7 +644,7 @@ int32_t vectorConvertToVarData(SSclVectorConvCtx *pCtx) { if (pCtx->outType == TSDB_DATA_TYPE_NCHAR) { varToNchar(tmp, pCtx->pOut, i, NULL); } else { - colDataAppend(pOutputCol, i, (char *)tmp, false); + colDataSetVal(pOutputCol, i, (char *)tmp, false); } } } else { @@ -722,52 +722,52 @@ int32_t vectorConvertSingleColImpl(const SScalarParam *pIn, SScalarParam *pOut, case TSDB_DATA_TYPE_BOOL: { for (int32_t i = cCtx.startIndex; i <= cCtx.endIndex; ++i) { if (colDataIsNull_f(pInputCol->nullbitmap, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } bool value = 0; GET_TYPED_DATA(value, bool, cCtx.inType, colDataGetData(pInputCol, i)); - colDataAppendInt8(pOutputCol, i, (int8_t *)&value); + colDataSetInt8(pOutputCol, i, (int8_t *)&value); } break; } case TSDB_DATA_TYPE_TINYINT: { for (int32_t i = cCtx.startIndex; i <= cCtx.endIndex; ++i) { if (colDataIsNull_f(pInputCol->nullbitmap, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } int8_t value = 0; GET_TYPED_DATA(value, int8_t, cCtx.inType, colDataGetData(pInputCol, i)); - colDataAppendInt8(pOutputCol, i, (int8_t *)&value); + colDataSetInt8(pOutputCol, i, (int8_t *)&value); } break; } case TSDB_DATA_TYPE_SMALLINT: { for (int32_t i = cCtx.startIndex; i <= cCtx.endIndex; ++i) { if (colDataIsNull_f(pInputCol->nullbitmap, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } int16_t value = 0; GET_TYPED_DATA(value, int16_t, cCtx.inType, colDataGetData(pInputCol, i)); - colDataAppendInt16(pOutputCol, i, (int16_t *)&value); + colDataSetInt16(pOutputCol, i, (int16_t *)&value); } break; } case TSDB_DATA_TYPE_INT: { for (int32_t i = cCtx.startIndex; i <= cCtx.endIndex; ++i) { if (colDataIsNull_f(pInputCol->nullbitmap, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } int32_t value = 0; GET_TYPED_DATA(value, int32_t, cCtx.inType, colDataGetData(pInputCol, i)); - colDataAppendInt32(pOutputCol, i, (int32_t *)&value); + colDataSetInt32(pOutputCol, i, (int32_t *)&value); } break; } @@ -775,91 +775,91 @@ int32_t vectorConvertSingleColImpl(const SScalarParam *pIn, SScalarParam *pOut, case TSDB_DATA_TYPE_TIMESTAMP: { for (int32_t i = cCtx.startIndex; i <= cCtx.endIndex; ++i) { if (colDataIsNull_f(pInputCol->nullbitmap, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } int64_t value = 0; GET_TYPED_DATA(value, int64_t, cCtx.inType, colDataGetData(pInputCol, i)); - colDataAppendInt64(pOutputCol, i, (int64_t *)&value); + colDataSetInt64(pOutputCol, i, (int64_t *)&value); } break; } case TSDB_DATA_TYPE_UTINYINT: { for (int32_t i = cCtx.startIndex; i <= cCtx.endIndex; ++i) { if (colDataIsNull_f(pInputCol->nullbitmap, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } uint8_t value = 0; GET_TYPED_DATA(value, uint8_t, cCtx.inType, colDataGetData(pInputCol, i)); - colDataAppendInt8(pOutputCol, i, (int8_t *)&value); + colDataSetInt8(pOutputCol, i, (int8_t *)&value); } break; } case TSDB_DATA_TYPE_USMALLINT: { for (int32_t i = cCtx.startIndex; i <= cCtx.endIndex; ++i) { if (colDataIsNull_f(pInputCol->nullbitmap, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } uint16_t value = 0; GET_TYPED_DATA(value, uint16_t, cCtx.inType, colDataGetData(pInputCol, i)); - colDataAppendInt16(pOutputCol, i, (int16_t *)&value); + colDataSetInt16(pOutputCol, i, (int16_t *)&value); } break; } case TSDB_DATA_TYPE_UINT: { for (int32_t i = cCtx.startIndex; i <= cCtx.endIndex; ++i) { if (colDataIsNull_f(pInputCol->nullbitmap, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } uint32_t value = 0; GET_TYPED_DATA(value, uint32_t, cCtx.inType, colDataGetData(pInputCol, i)); - colDataAppendInt32(pOutputCol, i, (int32_t *)&value); + colDataSetInt32(pOutputCol, i, (int32_t *)&value); } break; } case TSDB_DATA_TYPE_UBIGINT: { for (int32_t i = cCtx.startIndex; i <= cCtx.endIndex; ++i) { if (colDataIsNull_f(pInputCol->nullbitmap, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } uint64_t value = 0; GET_TYPED_DATA(value, uint64_t, cCtx.inType, colDataGetData(pInputCol, i)); - colDataAppendInt64(pOutputCol, i, (int64_t *)&value); + colDataSetInt64(pOutputCol, i, (int64_t *)&value); } break; } case TSDB_DATA_TYPE_FLOAT: { for (int32_t i = cCtx.startIndex; i <= cCtx.endIndex; ++i) { if (colDataIsNull_f(pInputCol->nullbitmap, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } float value = 0; GET_TYPED_DATA(value, float, cCtx.inType, colDataGetData(pInputCol, i)); - colDataAppendFloat(pOutputCol, i, (float *)&value); + colDataSetFloat(pOutputCol, i, (float *)&value); } break; } case TSDB_DATA_TYPE_DOUBLE: { for (int32_t i = cCtx.startIndex; i <= cCtx.endIndex; ++i) { if (colDataIsNull_f(pInputCol->nullbitmap, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } double value = 0; GET_TYPED_DATA(value, double, cCtx.inType, colDataGetData(pInputCol, i)); - colDataAppendDouble(pOutputCol, i, (double *)&value); + colDataSetDouble(pOutputCol, i, (double *)&value); } break; } @@ -1007,11 +1007,11 @@ static void vectorMathAddHelper(SColumnInfoData *pLeftCol, SColumnInfoData *pRig double *output = (double *)pOutputCol->pData; if (IS_HELPER_NULL(pRightCol, 0)) { // Set pLeft->numOfRows NULL value - colDataAppendNNULL(pOutputCol, 0, numOfRows); + colDataSetNNULL(pOutputCol, 0, numOfRows); } else { for (; i >= 0 && i < numOfRows; i += step, output += 1) { if (IS_HELPER_NULL(pLeftCol, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; // TODO set null or ignore } *output = getVectorDoubleValueFnLeft(LEFT_COL, i) + getVectorDoubleValueFnRight(RIGHT_COL, 0); @@ -1027,11 +1027,11 @@ static void vectorMathTsAddHelper(SColumnInfoData *pLeftCol, SColumnInfoData *pR int64_t *output = (int64_t *)pOutputCol->pData; if (IS_HELPER_NULL(pRightCol, 0)) { // Set pLeft->numOfRows NULL value - colDataAppendNNULL(pOutputCol, 0, numOfRows); + colDataSetNNULL(pOutputCol, 0, numOfRows); } else { for (; i >= 0 && i < numOfRows; i += step, output += 1) { if (IS_HELPER_NULL(pLeftCol, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; // TODO set null or ignore } *output = @@ -1103,7 +1103,7 @@ void vectorMathAdd(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam *pOut } else if (pLeft->numOfRows == pRight->numOfRows) { for (; i < pRight->numOfRows && i >= 0; i += step, output += 1) { if (IS_NULL) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; // TODO set null or ignore } *output = getVectorBigintValueFnLeft(pLeftCol->pData, i) + getVectorBigintValueFnRight(pRightCol->pData, i); @@ -1117,7 +1117,7 @@ void vectorMathAdd(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam *pOut if (pLeft->numOfRows == pRight->numOfRows) { for (; i < pRight->numOfRows && i >= 0; i += step, output += 1) { if (IS_NULL) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; // TODO set null or ignore } *output = getVectorDoubleValueFnLeft(LEFT_COL, i) + getVectorDoubleValueFnRight(RIGHT_COL, i); @@ -1142,11 +1142,11 @@ static void vectorMathSubHelper(SColumnInfoData *pLeftCol, SColumnInfoData *pRig double *output = (double *)pOutputCol->pData; if (IS_HELPER_NULL(pRightCol, 0)) { // Set pLeft->numOfRows NULL value - colDataAppendNNULL(pOutputCol, 0, numOfRows); + colDataSetNNULL(pOutputCol, 0, numOfRows); } else { for (; i >= 0 && i < numOfRows; i += step, output += 1) { if (IS_HELPER_NULL(pLeftCol, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; // TODO set null or ignore } *output = (getVectorDoubleValueFnLeft(LEFT_COL, i) - getVectorDoubleValueFnRight(RIGHT_COL, 0)) * factor; @@ -1162,11 +1162,11 @@ static void vectorMathTsSubHelper(SColumnInfoData *pLeftCol, SColumnInfoData *pR int64_t *output = (int64_t *)pOutputCol->pData; if (IS_HELPER_NULL(pRightCol, 0)) { // Set pLeft->numOfRows NULL value - colDataAppendNNULL(pOutputCol, 0, numOfRows); + colDataSetNNULL(pOutputCol, 0, numOfRows); } else { for (; i >= 0 && i < numOfRows; i += step, output += 1) { if (IS_HELPER_NULL(pLeftCol, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; // TODO set null or ignore } *output = @@ -1204,7 +1204,7 @@ void vectorMathSub(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam *pOut } else if (pLeft->numOfRows == pRight->numOfRows) { for (; i < pRight->numOfRows && i >= 0; i += step, output += 1) { if (IS_NULL) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; // TODO set null or ignore } *output = getVectorBigintValueFnLeft(pLeftCol->pData, i) - getVectorBigintValueFnRight(pRightCol->pData, i); @@ -1218,7 +1218,7 @@ void vectorMathSub(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam *pOut if (pLeft->numOfRows == pRight->numOfRows) { for (; i < pRight->numOfRows && i >= 0; i += step, output += 1) { if (IS_NULL) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; // TODO set null or ignore } *output = getVectorDoubleValueFnLeft(LEFT_COL, i) - getVectorDoubleValueFnRight(RIGHT_COL, i); @@ -1243,11 +1243,11 @@ static void vectorMathMultiplyHelper(SColumnInfoData *pLeftCol, SColumnInfoData double *output = (double *)pOutputCol->pData; if (IS_HELPER_NULL(pRightCol, 0)) { // Set pLeft->numOfRows NULL value - colDataAppendNNULL(pOutputCol, 0, numOfRows); + colDataSetNNULL(pOutputCol, 0, numOfRows); } else { for (; i >= 0 && i < numOfRows; i += step, output += 1) { if (IS_HELPER_NULL(pLeftCol, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; // TODO set null or ignore } *output = getVectorDoubleValueFnLeft(LEFT_COL, i) * getVectorDoubleValueFnRight(RIGHT_COL, 0); @@ -1273,7 +1273,7 @@ void vectorMathMultiply(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam if (pLeft->numOfRows == pRight->numOfRows) { for (; i < pRight->numOfRows && i >= 0; i += step, output += 1) { if (IS_NULL) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; // TODO set null or ignore } *output = getVectorDoubleValueFnLeft(LEFT_COL, i) * getVectorDoubleValueFnRight(RIGHT_COL, i); @@ -1306,18 +1306,18 @@ void vectorMathDivide(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam *p if (pLeft->numOfRows == pRight->numOfRows) { for (; i < pRight->numOfRows && i >= 0; i += step, output += 1) { if (IS_NULL || (getVectorDoubleValueFnRight(RIGHT_COL, i) == 0)) { // divide by 0 check - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } *output = getVectorDoubleValueFnLeft(LEFT_COL, i) / getVectorDoubleValueFnRight(RIGHT_COL, i); } } else if (pLeft->numOfRows == 1) { if (IS_HELPER_NULL(pLeftCol, 0)) { // Set pLeft->numOfRows NULL value - colDataAppendNNULL(pOutputCol, 0, pRight->numOfRows); + colDataSetNNULL(pOutputCol, 0, pRight->numOfRows); } else { for (; i >= 0 && i < pRight->numOfRows; i += step, output += 1) { if (IS_HELPER_NULL(pRightCol, i) || (getVectorDoubleValueFnRight(RIGHT_COL, i) == 0)) { // divide by 0 check - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } *output = getVectorDoubleValueFnLeft(LEFT_COL, 0) / getVectorDoubleValueFnRight(RIGHT_COL, i); @@ -1326,11 +1326,11 @@ void vectorMathDivide(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam *p } else if (pRight->numOfRows == 1) { if (IS_HELPER_NULL(pRightCol, 0) || (getVectorDoubleValueFnRight(RIGHT_COL, 0) == 0)) { // Set pLeft->numOfRows NULL value (divde by 0 check) - colDataAppendNNULL(pOutputCol, 0, pLeft->numOfRows); + colDataSetNNULL(pOutputCol, 0, pLeft->numOfRows); } else { for (; i >= 0 && i < pLeft->numOfRows; i += step, output += 1) { if (IS_HELPER_NULL(pLeftCol, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } *output = getVectorDoubleValueFnLeft(LEFT_COL, i) / getVectorDoubleValueFnRight(RIGHT_COL, 0); @@ -1361,14 +1361,14 @@ void vectorMathRemainder(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam if (pLeft->numOfRows == pRight->numOfRows) { for (; i < pRight->numOfRows && i >= 0; i += step, output += 1) { if (IS_NULL) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } double lx = getVectorDoubleValueFnLeft(LEFT_COL, i); double rx = getVectorDoubleValueFnRight(RIGHT_COL, i); if (isnan(lx) || isinf(lx) || isnan(rx) || isinf(rx) || FLT_EQUAL(rx, 0)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } @@ -1377,17 +1377,17 @@ void vectorMathRemainder(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam } else if (pLeft->numOfRows == 1) { double lx = getVectorDoubleValueFnLeft(LEFT_COL, 0); if (IS_HELPER_NULL(pLeftCol, 0)) { // Set pLeft->numOfRows NULL value - colDataAppendNNULL(pOutputCol, 0, pRight->numOfRows); + colDataSetNNULL(pOutputCol, 0, pRight->numOfRows); } else { for (; i >= 0 && i < pRight->numOfRows; i += step, output += 1) { if (IS_HELPER_NULL(pRightCol, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } double rx = getVectorDoubleValueFnRight(RIGHT_COL, i); if (isnan(rx) || isinf(rx) || FLT_EQUAL(rx, 0)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } @@ -1397,17 +1397,17 @@ void vectorMathRemainder(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam } else if (pRight->numOfRows == 1) { double rx = getVectorDoubleValueFnRight(RIGHT_COL, 0); if (IS_HELPER_NULL(pRightCol, 0) || FLT_EQUAL(rx, 0)) { // Set pLeft->numOfRows NULL value - colDataAppendNNULL(pOutputCol, 0, pLeft->numOfRows); + colDataSetNNULL(pOutputCol, 0, pLeft->numOfRows); } else { for (; i >= 0 && i < pLeft->numOfRows; i += step, output += 1) { if (IS_HELPER_NULL(pLeftCol, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } double lx = getVectorDoubleValueFnLeft(LEFT_COL, i); if (isnan(lx) || isinf(lx)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } @@ -1436,7 +1436,7 @@ void vectorMathMinus(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam *pO double *output = (double *)pOutputCol->pData; for (; i < pLeft->numOfRows && i >= 0; i += step, output += 1) { if (IS_HELPER_NULL(pLeftCol, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; } double result = getVectorDoubleValueFnLeft(LEFT_COL, i); @@ -1451,11 +1451,11 @@ void vectorAssign(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam *pOut, pOut->numOfRows = pLeft->numOfRows; if (colDataIsNull_s(pRight->columnData, 0)) { - colDataAppendNNULL(pOutputCol, 0, pOut->numOfRows); + colDataSetNNULL(pOutputCol, 0, pOut->numOfRows); } else { char *d = colDataGetData(pRight->columnData, 0); for (int32_t i = 0; i < pOut->numOfRows; ++i) { - colDataAppend(pOutputCol, i, d, false); + colDataSetVal(pOutputCol, i, d, false); } } @@ -1471,11 +1471,11 @@ static void vectorBitAndHelper(SColumnInfoData *pLeftCol, SColumnInfoData *pRigh int64_t *output = (int64_t *)pOutputCol->pData; if (IS_HELPER_NULL(pRightCol, 0)) { // Set pLeft->numOfRows NULL value - colDataAppendNNULL(pOutputCol, 0, numOfRows); + colDataSetNNULL(pOutputCol, 0, numOfRows); } else { for (; i >= 0 && i < numOfRows; i += step, output += 1) { if (IS_HELPER_NULL(pLeftCol, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; // TODO set null or ignore } *output = getVectorBigintValueFnLeft(LEFT_COL, i) & getVectorBigintValueFnRight(RIGHT_COL, 0); @@ -1501,7 +1501,7 @@ void vectorBitAnd(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam *pOut, if (pLeft->numOfRows == pRight->numOfRows) { for (; i < pRight->numOfRows && i >= 0; i += step, output += 1) { if (IS_NULL) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; // TODO set null or ignore } *output = getVectorBigintValueFnLeft(LEFT_COL, i) & getVectorBigintValueFnRight(RIGHT_COL, i); @@ -1524,12 +1524,12 @@ static void vectorBitOrHelper(SColumnInfoData *pLeftCol, SColumnInfoData *pRight int64_t *output = (int64_t *)pOutputCol->pData; if (IS_HELPER_NULL(pRightCol, 0)) { // Set pLeft->numOfRows NULL value - colDataAppendNNULL(pOutputCol, 0, numOfRows); + colDataSetNNULL(pOutputCol, 0, numOfRows); } else { int64_t rx = getVectorBigintValueFnRight(RIGHT_COL, 0); for (; i >= 0 && i < numOfRows; i += step, output += 1) { if (IS_HELPER_NULL(pLeftCol, i)) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; // TODO set null or ignore } *output = getVectorBigintValueFnLeft(LEFT_COL, i) | rx; @@ -1555,7 +1555,7 @@ void vectorBitOr(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam *pOut, if (pLeft->numOfRows == pRight->numOfRows) { for (; i < pRight->numOfRows && i >= 0; i += step, output += 1) { if (IS_NULL) { - colDataAppendNULL(pOutputCol, i); + colDataSetNULL(pOutputCol, i); continue; // TODO set null or ignore } *output = getVectorBigintValueFnLeft(LEFT_COL, i) | getVectorBigintValueFnRight(RIGHT_COL, i); @@ -1617,7 +1617,7 @@ int32_t doVectorCompareImpl(SScalarParam *pLeft, SScalarParam *pRight, SScalarPa if (IS_HELPER_NULL(pLeft->columnData, leftIndex) || IS_HELPER_NULL(pRight->columnData, rightIndex)) { bool res = false; - colDataAppendInt8(pOut->columnData, i, (int8_t *)&res); + colDataSetInt8(pOut->columnData, i, (int8_t *)&res); continue; } @@ -1640,10 +1640,10 @@ int32_t doVectorCompareImpl(SScalarParam *pLeft, SScalarParam *pRight, SScalarPa } if (!result) { - colDataAppendInt8(pOut->columnData, i, (int8_t *)&result); + colDataSetInt8(pOut->columnData, i, (int8_t *)&result); } else { bool res = filterDoCompare(fp, optr, pLeftData, pRightData); - colDataAppendInt8(pOut->columnData, i, (int8_t *)&res); + colDataSetInt8(pOut->columnData, i, (int8_t *)&res); if (res) { ++num; } @@ -1690,13 +1690,13 @@ void doVectorCompare(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam *pO for (; i >= 0 && i < pLeft->numOfRows; i += step) { if (IS_HELPER_NULL(pLeft->columnData, i)) { bool res = false; - colDataAppendInt8(pOut->columnData, i, (int8_t *)&res); + colDataSetInt8(pOut->columnData, i, (int8_t *)&res); continue; } char *pLeftData = colDataGetData(pLeft->columnData, i); bool res = filterDoCompare(fp, optr, pLeftData, pRight->pHashFilter); - colDataAppendInt8(pOut->columnData, i, (int8_t *)&res); + colDataSetInt8(pOut->columnData, i, (int8_t *)&res); if (res) { pOut->numOfQualified++; } @@ -1783,7 +1783,7 @@ void vectorNotMatch(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam *pOu void vectorIsNull(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam *pOut, int32_t _ord) { for (int32_t i = 0; i < pLeft->numOfRows; ++i) { int8_t v = IS_HELPER_NULL(pLeft->columnData, i) ? 1 : 0; - colDataAppendInt8(pOut->columnData, i, &v); + colDataSetInt8(pOut->columnData, i, &v); } pOut->numOfRows = pLeft->numOfRows; } @@ -1791,7 +1791,7 @@ void vectorIsNull(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam *pOut, void vectorNotNull(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam *pOut, int32_t _ord) { for (int32_t i = 0; i < pLeft->numOfRows; ++i) { int8_t v = IS_HELPER_NULL(pLeft->columnData, i) ? 0 : 1; - colDataAppendInt8(pOut->columnData, i, &v); + colDataSetInt8(pOut->columnData, i, &v); } pOut->numOfRows = pLeft->numOfRows; } @@ -1801,7 +1801,7 @@ void vectorIsTrue(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam *pOut, for (int32_t i = 0; i < pOut->numOfRows; ++i) { if (colDataIsNull_s(pOut->columnData, i)) { int8_t v = 0; - colDataAppendInt8(pOut->columnData, i, &v); + colDataSetInt8(pOut->columnData, i, &v); colDataClearNull_f(pOut->columnData->nullbitmap, i); } } @@ -1844,7 +1844,7 @@ void vectorJsonContains(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam getJsonValue(pLeftData, jsonKey, &isExist); } - colDataAppend(pOutputCol, i, (const char *)(&isExist), false); + colDataSetVal(pOutputCol, i, (const char *)(&isExist), false); } taosMemoryFree(jsonKey); } @@ -1870,7 +1870,7 @@ void vectorJsonArrow(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam *pO bool isExist = false; STagVal value = getJsonValue(pLeftData, jsonKey, &isExist); char *data = isExist ? tTagValToData(&value, true) : NULL; - colDataAppend(pOutputCol, i, data, data == NULL); + colDataSetVal(pOutputCol, i, data, data == NULL); if (isExist && IS_VAR_DATA_TYPE(value.type) && data) { taosMemoryFree(data); } diff --git a/source/libs/scalar/test/filter/filterTests.cpp b/source/libs/scalar/test/filter/filterTests.cpp index 2f518e2e59..b59e89fe0d 100644 --- a/source/libs/scalar/test/filter/filterTests.cpp +++ b/source/libs/scalar/test/filter/filterTests.cpp @@ -111,7 +111,7 @@ void flttMakeColumnNode(SNode **pNode, SSDataBlock **block, int32_t dataType, in SColumnInfoData *pColumn = (SColumnInfoData *)taosArrayGetLast(res->pDataBlock); for (int32_t i = 0; i < rowNum; ++i) { - colDataAppend(pColumn, i, (const char *)value, false); + colDataSetVal(pColumn, i, (const char *)value, false); if (IS_VAR_DATA_TYPE(dataType)) { value = (char *)value + varDataTLen(value); } else { @@ -135,7 +135,7 @@ void flttMakeColumnNode(SNode **pNode, SSDataBlock **block, int32_t dataType, in SColumnInfoData *pColumn = (SColumnInfoData *)taosArrayGetLast(res->pDataBlock); for (int32_t i = 0; i < rowNum; ++i) { - colDataAppend(pColumn, i, (const char *)value, false); + colDataSetVal(pColumn, i, (const char *)value, false); if (IS_VAR_DATA_TYPE(dataType)) { value = (char *)value + varDataTLen(value); } else { @@ -634,8 +634,8 @@ TEST(columnTest, binary_column_is_null) { flttMakeColumnNode(&pLeft, &src, TSDB_DATA_TYPE_BINARY, 3, rowNum, leftv); SColumnInfoData *pcolumn = (SColumnInfoData *)taosArrayGetLast(src->pDataBlock); - colDataAppend(pcolumn, 2, NULL, true); - colDataAppend(pcolumn, 4, NULL, true); + colDataSetVal(pcolumn, 2, NULL, true); + colDataSetVal(pcolumn, 4, NULL, true); flttMakeOpNode(&opNode, OP_TYPE_IS_NULL, TSDB_DATA_TYPE_BOOL, pLeft, NULL); SFilterInfo *filter = NULL; @@ -682,7 +682,7 @@ TEST(columnTest, binary_column_is_not_null) { flttMakeColumnNode(&pLeft, &src, TSDB_DATA_TYPE_BINARY, 3, rowNum, leftv); SColumnInfoData *pcolumn = (SColumnInfoData *)taosArrayGetLast(src->pDataBlock); - colDataAppend(pcolumn, 4, NULL, true); + colDataSetVal(pcolumn, 4, NULL, true); flttMakeOpNode(&opNode, OP_TYPE_IS_NOT_NULL, TSDB_DATA_TYPE_BOOL, pLeft, NULL); diff --git a/source/libs/scalar/test/scalar/scalarTests.cpp b/source/libs/scalar/test/scalar/scalarTests.cpp index 97002ed9bf..fe86e18ce3 100644 --- a/source/libs/scalar/test/scalar/scalarTests.cpp +++ b/source/libs/scalar/test/scalar/scalarTests.cpp @@ -158,7 +158,7 @@ void scltMakeColumnNode(SNode **pNode, SSDataBlock **block, int32_t dataType, in res->info.rows = rowNum; SColumnInfoData *pColumn = (SColumnInfoData *)taosArrayGetLast(res->pDataBlock); for (int32_t i = 0; i < rowNum; ++i) { - colDataAppend(pColumn, i, (const char *)value, false); + colDataSetVal(pColumn, i, (const char *)value, false); if (IS_VAR_DATA_TYPE(dataType)) { value = (char *)value + varDataTLen(value); } else { @@ -183,7 +183,7 @@ void scltMakeColumnNode(SNode **pNode, SSDataBlock **block, int32_t dataType, in SColumnInfoData *pColumn = (SColumnInfoData *)taosArrayGetLast(res->pDataBlock); for (int32_t i = 0; i < rowNum; ++i) { - colDataAppend(pColumn, i, (const char *)value, false); + colDataSetVal(pColumn, i, (const char *)value, false); if (IS_VAR_DATA_TYPE(dataType)) { value = (char *)value + varDataTLen(value); } else { @@ -1880,8 +1880,8 @@ TEST(columnTest, binary_column_is_null) { scltMakeColumnNode(&pLeft, &src, TSDB_DATA_TYPE_BINARY, 3, rowNum, leftv); SColumnInfoData *pcolumn = (SColumnInfoData *)taosArrayGetLast(src->pDataBlock); - colDataAppend(pcolumn, 2, NULL, true); - colDataAppend(pcolumn, 4, NULL, true); + colDataSetVal(pcolumn, 2, NULL, true); + colDataSetVal(pcolumn, 4, NULL, true); scltMakeOpNode(&opNode, OP_TYPE_IS_NULL, TSDB_DATA_TYPE_BOOL, pLeft, NULL); @@ -1924,7 +1924,7 @@ TEST(columnTest, binary_column_is_not_null) { scltMakeColumnNode(&pLeft, &src, TSDB_DATA_TYPE_BINARY, 3, rowNum, leftv); SColumnInfoData *pcolumn = (SColumnInfoData *)taosArrayGetLast(src->pDataBlock); - colDataAppend(pcolumn, 4, NULL, true); + colDataSetVal(pcolumn, 4, NULL, true); scltMakeOpNode(&opNode, OP_TYPE_IS_NOT_NULL, TSDB_DATA_TYPE_BOOL, pLeft, NULL); @@ -2030,7 +2030,7 @@ void scltMakeDataBlock(SScalarParam **pInput, int32_t type, void *pVal, int32_t if (setVal) { for (int32_t i = 0; i < num; ++i) { - colDataAppend(input->columnData, i, (const char *)pVal, false); + colDataSetVal(input->columnData, i, (const char *)pVal, false); } } else { // memset(input->data, 0, num * bytes); @@ -2225,7 +2225,7 @@ TEST(ScalarFunctionTest, absFunction_column) { scltMakeDataBlock(&pOutput, type, 0, rowNum, false); for (int32_t i = 0; i < rowNum; ++i) { int8_t v = val_tinyint + i; - colDataAppend(pInput->columnData, i, (const char *)&v, false); + colDataSetVal(pInput->columnData, i, (const char *)&v, false); PRINTF("tiny_int before ABS:%d\n", v); } @@ -2243,7 +2243,7 @@ TEST(ScalarFunctionTest, absFunction_column) { scltMakeDataBlock(&pOutput, type, 0, rowNum, false); for (int32_t i = 0; i < rowNum; ++i) { int8_t v = val_tinyint + i; - colDataAppend(pInput->columnData, i, (const char *)&v, false); + colDataSetVal(pInput->columnData, i, (const char *)&v, false); PRINTF("tiny_int before ABS:%d\n", v); } @@ -2263,7 +2263,7 @@ TEST(ScalarFunctionTest, absFunction_column) { scltMakeDataBlock(&pOutput, type, 0, rowNum, false); for (int32_t i = 0; i < rowNum; ++i) { int16_t v = val_smallint + i; - colDataAppend(pInput->columnData, i, (const char *)&v, false); + colDataSetVal(pInput->columnData, i, (const char *)&v, false); PRINTF("small_int before ABS:%d\n", v); } @@ -2281,7 +2281,7 @@ TEST(ScalarFunctionTest, absFunction_column) { scltMakeDataBlock(&pOutput, type, 0, rowNum, false); for (int32_t i = 0; i < rowNum; ++i) { int16_t v = val_smallint + i; - colDataAppend(pInput->columnData, i, (const char *)&v, false); + colDataSetVal(pInput->columnData, i, (const char *)&v, false); PRINTF("small_int before ABS:%d\n", v); } @@ -2301,7 +2301,7 @@ TEST(ScalarFunctionTest, absFunction_column) { scltMakeDataBlock(&pOutput, type, 0, rowNum, false); for (int32_t i = 0; i < rowNum; ++i) { int32_t v = val_int + i; - colDataAppend(pInput->columnData, i, (const char *)&v, false); + colDataSetVal(pInput->columnData, i, (const char *)&v, false); PRINTF("int before ABS:%d\n", v); } @@ -2319,7 +2319,7 @@ TEST(ScalarFunctionTest, absFunction_column) { scltMakeDataBlock(&pOutput, type, 0, rowNum, false); for (int32_t i = 0; i < rowNum; ++i) { int32_t v = val_int + i; - colDataAppend(pInput->columnData, i, (const char *)&v, false); + colDataSetVal(pInput->columnData, i, (const char *)&v, false); PRINTF("int before ABS:%d\n", v); } @@ -2339,7 +2339,7 @@ TEST(ScalarFunctionTest, absFunction_column) { scltMakeDataBlock(&pOutput, type, 0, rowNum, false); for (int32_t i = 0; i < rowNum; ++i) { float v = val_float + i; - colDataAppend(pInput->columnData, i, (const char *)&v, false); + colDataSetVal(pInput->columnData, i, (const char *)&v, false); PRINTF("float before ABS:%f\n", v); } @@ -2357,7 +2357,7 @@ TEST(ScalarFunctionTest, absFunction_column) { scltMakeDataBlock(&pOutput, type, 0, rowNum, false); for (int32_t i = 0; i < rowNum; ++i) { float v = val_float + i; - colDataAppend(pInput->columnData, i, (const char *)&v, false); + colDataSetVal(pInput->columnData, i, (const char *)&v, false); PRINTF("float before ABS:%f\n", v); } @@ -2377,7 +2377,7 @@ TEST(ScalarFunctionTest, absFunction_column) { scltMakeDataBlock(&pOutput, type, 0, rowNum, false); for (int32_t i = 0; i < rowNum; ++i) { double v = val_double + i; - colDataAppend(pInput->columnData, i, (const char *)&v, false); + colDataSetVal(pInput->columnData, i, (const char *)&v, false); PRINTF("double before ABS:%f\n", v); } @@ -2395,7 +2395,7 @@ TEST(ScalarFunctionTest, absFunction_column) { scltMakeDataBlock(&pOutput, type, 0, rowNum, false); for (int32_t i = 0; i < rowNum; ++i) { double v = val_double + i; - colDataAppend(pInput->columnData, i, (const char *)&v, false); + colDataSetVal(pInput->columnData, i, (const char *)&v, false); PRINTF("double before ABS:%f\n", v); } @@ -2466,7 +2466,7 @@ TEST(ScalarFunctionTest, sinFunction_column) { scltMakeDataBlock(&pInput, type, 0, rowNum, false); scltMakeDataBlock(&pOutput, otype, 0, rowNum, false); for (int32_t i = 0; i < rowNum; ++i) { - colDataAppend(pInput->columnData, i, (const char *)&val_tinyint[i], false); + colDataSetVal(pInput->columnData, i, (const char *)&val_tinyint[i], false); PRINTF("tiny_int before SIN:%d\n", *(int8_t *)colDataGetData(pInput->columnData, i)); } @@ -2485,7 +2485,7 @@ TEST(ScalarFunctionTest, sinFunction_column) { scltMakeDataBlock(&pInput, type, 0, rowNum, false); scltMakeDataBlock(&pOutput, otype, 0, rowNum, false); for (int32_t i = 0; i < rowNum; ++i) { - colDataAppend(pInput->columnData, i, (const char *)&val_float[i], false); + colDataSetVal(pInput->columnData, i, (const char *)&val_float[i], false); PRINTF("float before SIN:%f\n", *((float *)colDataGetData(pInput->columnData, i))); } @@ -2556,7 +2556,7 @@ TEST(ScalarFunctionTest, cosFunction_column) { scltMakeDataBlock(&pInput, type, 0, rowNum, false); scltMakeDataBlock(&pOutput, otype, 0, rowNum, false); for (int32_t i = 0; i < rowNum; ++i) { - colDataAppend(pInput->columnData, i, (const char *)&val_tinyint[i], false); + colDataSetVal(pInput->columnData, i, (const char *)&val_tinyint[i], false); PRINTF("tiny_int before COS:%d\n", *(int8_t *)colDataGetData(pInput->columnData, i)); } @@ -2575,7 +2575,7 @@ TEST(ScalarFunctionTest, cosFunction_column) { scltMakeDataBlock(&pInput, type, 0, rowNum, false); scltMakeDataBlock(&pOutput, otype, 0, rowNum, false); for (int32_t i = 0; i < rowNum; ++i) { - colDataAppend(pInput->columnData, i, (const char *)&val_float[i], false); + colDataSetVal(pInput->columnData, i, (const char *)&val_float[i], false); PRINTF("float before COS:%f\n", *(float *)colDataGetData(pInput->columnData, i)); } @@ -2646,7 +2646,7 @@ TEST(ScalarFunctionTest, tanFunction_column) { scltMakeDataBlock(&pInput, type, 0, rowNum, false); scltMakeDataBlock(&pOutput, otype, 0, rowNum, false); for (int32_t i = 0; i < rowNum; ++i) { - colDataAppend(pInput->columnData, i, (const char *)&val_tinyint[i], false); + colDataSetVal(pInput->columnData, i, (const char *)&val_tinyint[i], false); PRINTF("tiny_int before TAN:%d\n", *((int8_t *)colDataGetData(pInput->columnData, i))); } @@ -2665,7 +2665,7 @@ TEST(ScalarFunctionTest, tanFunction_column) { scltMakeDataBlock(&pInput, type, 0, rowNum, false); scltMakeDataBlock(&pOutput, otype, 0, rowNum, false); for (int32_t i = 0; i < rowNum; ++i) { - colDataAppend(pInput->columnData, i, (const char *)&val_float[i], false); + colDataSetVal(pInput->columnData, i, (const char *)&val_float[i], false); PRINTF("float before TAN:%f\n", *((float *)colDataGetData(pInput->columnData, i))); } @@ -2736,7 +2736,7 @@ TEST(ScalarFunctionTest, asinFunction_column) { scltMakeDataBlock(&pInput, type, 0, rowNum, false); scltMakeDataBlock(&pOutput, otype, 0, rowNum, false); for (int32_t i = 0; i < rowNum; ++i) { - colDataAppend(pInput->columnData, i, (const char *)&val_tinyint[i], false); + colDataSetVal(pInput->columnData, i, (const char *)&val_tinyint[i], false); PRINTF("tiny_int before ASIN:%d\n", *((int8_t *)colDataGetData(pInput->columnData, i))); } @@ -3395,7 +3395,7 @@ TEST(ScalarFunctionTest, logFunction_column) { scltMakeDataBlock(&input[i], type, 0, rowNum, false); pInput[i] = *input[i]; for (int32_t j = 0; j < rowNum; ++j) { - colDataAppend(pInput[i].columnData, j, (const char *)&val_tinyint[i][j], false); + colDataSetVal(pInput[i].columnData, j, (const char *)&val_tinyint[i][j], false); } PRINTF("tiny_int before LOG:%d,%d,%d\n", *((int8_t *)pInput[i].data + 0), *((int8_t *)pInput[i].data + 1), *((int8_t *)pInput[i].data + 2)); @@ -3419,7 +3419,7 @@ TEST(ScalarFunctionTest, logFunction_column) { scltMakeDataBlock(&input[i], type, 0, rowNum, false); pInput[i] = *input[i]; for (int32_t j = 0; j < rowNum; ++j) { - colDataAppend(pInput[i].columnData, j, (const char *)&val_float[i][j], false); + colDataSetVal(pInput[i].columnData, j, (const char *)&val_float[i][j], false); } PRINTF("float before LOG:%f,%f,%f\n", *((float *)colDataGetData(pInput[i], 0)), *((float *)colDataGetData(pInput[i], 1)), *((float *)colDataGetData(pInput[i], 2))); @@ -3442,12 +3442,12 @@ TEST(ScalarFunctionTest, logFunction_column) { scltMakeDataBlock(&input[0], TSDB_DATA_TYPE_TINYINT, 0, rowNum, false); pInput[0] = *input[0]; for (int32_t i = 0; i < rowNum; ++i) { - colDataAppend(pInput[0].columnData, i, (const char *)¶m0[i], false); + colDataSetVal(pInput[0].columnData, i, (const char *)¶m0[i], false); } scltMakeDataBlock(&input[1], TSDB_DATA_TYPE_FLOAT, 0, rowNum, false); pInput[1] = *input[1]; for (int32_t i = 0; i < rowNum; ++i) { - colDataAppend(pInput[1].columnData, i, (const char *)¶m1[i], false); + colDataSetVal(pInput[1].columnData, i, (const char *)¶m1[i], false); } PRINTF("tiny_int, float before LOG:{%d,%f}, {%d,%f}, {%d,%f}\n", *((int8_t *)pInput[0].data + 0), *((float *)pInput[1].data + 0), *((int8_t *)pInput[0].data + 1), *((float *)pInput[1].data + 1), @@ -3558,7 +3558,7 @@ TEST(ScalarFunctionTest, powFunction_column) { scltMakeDataBlock(&input[i], type, 0, rowNum, false); pInput[i] = *input[i]; for (int32_t j = 0; j < rowNum; ++j) { - colDataAppend(pInput[i].columnData, j, (const char *)&val_tinyint[i][j], false); + colDataSetVal(pInput[i].columnData, j, (const char *)&val_tinyint[i][j], false); } PRINTF("tiny_int before POW:%d,%d,%d\n", *((int8_t *)pInput[i].data + 0), *((int8_t *)pInput[i].data + 1), *((int8_t *)pInput[i].data + 2)); @@ -3583,7 +3583,7 @@ TEST(ScalarFunctionTest, powFunction_column) { scltMakeDataBlock(&input[i], type, 0, rowNum, false); pInput[i] = *input[i]; for (int32_t j = 0; j < rowNum; ++j) { - colDataAppend(pInput[i].columnData, j, (const char *)&val_float[i][j], false); + colDataSetVal(pInput[i].columnData, j, (const char *)&val_float[i][j], false); } PRINTF("float before POW:%f,%f,%f\n", *((float *)pInput[i].data + 0), *((float *)pInput[i].data + 1), *((float *)pInput[i].data + 2)); @@ -3606,12 +3606,12 @@ TEST(ScalarFunctionTest, powFunction_column) { scltMakeDataBlock(&input[0], TSDB_DATA_TYPE_TINYINT, 0, rowNum, false); pInput[0] = *input[0]; for (int32_t i = 0; i < rowNum; ++i) { - colDataAppend(pInput[0].columnData, i, (const char *)¶m0[i], false); + colDataSetVal(pInput[0].columnData, i, (const char *)¶m0[i], false); } scltMakeDataBlock(&input[1], TSDB_DATA_TYPE_FLOAT, 0, rowNum, false); pInput[1] = *input[1]; for (int32_t i = 0; i < rowNum; ++i) { - colDataAppend(pInput[1].columnData, i, (const char *)¶m1[i], false); + colDataSetVal(pInput[1].columnData, i, (const char *)¶m1[i], false); } PRINTF("tiny_int, float before POW:{%d,%f}, {%d,%f}, {%d,%f}\n", *((int8_t *)pInput[0].data + 0), *((float *)pInput[1].data + 0), *((int8_t *)pInput[0].data + 1), *((float *)pInput[1].data + 1), diff --git a/source/libs/scheduler/src/schJob.c b/source/libs/scheduler/src/schJob.c index fb8a7a42ba..980a8ac6a1 100644 --- a/source/libs/scheduler/src/schJob.c +++ b/source/libs/scheduler/src/schJob.c @@ -716,7 +716,7 @@ int32_t schInitJob(int64_t *pJobId, SSchedulerReq *pReq) { pJob->attr.localExec = pReq->localReq; pJob->conn = *pReq->pConn; if (pReq->sql) { - pJob->sql = strdup(pReq->sql); + pJob->sql = taosStrdup(pReq->sql); } pJob->pDag = pReq->pDag; pJob->allocatorRefId = nodesMakeAllocatorWeakRef(pReq->allocatorRefId); diff --git a/source/libs/scheduler/src/schRemote.c b/source/libs/scheduler/src/schRemote.c index 4e05e22474..6f4130fd9f 100644 --- a/source/libs/scheduler/src/schRemote.c +++ b/source/libs/scheduler/src/schRemote.c @@ -887,7 +887,7 @@ int32_t schUpdateSendTargetInfo(SMsgSendInfo *pMsgSendInfo, SQueryNodeAddr *addr } else { pMsgSendInfo->target.type = TARGET_TYPE_VNODE; pMsgSendInfo->target.vgId = addr->nodeId; - pMsgSendInfo->target.dbFName = strdup(pTask->plan->dbFName); + pMsgSendInfo->target.dbFName = taosStrdup(pTask->plan->dbFName); } return TSDB_CODE_SUCCESS; diff --git a/source/libs/stream/src/streamCheckpoint.c b/source/libs/stream/src/streamCheckpoint.c index efd19074da..670cfbead1 100644 --- a/source/libs/stream/src/streamCheckpoint.c +++ b/source/libs/stream/src/streamCheckpoint.c @@ -13,6 +13,7 @@ * along with this program. If not, see . */ +#if 0 #include "streamInc.h" int32_t tEncodeSStreamCheckpointSourceReq(SEncoder* pEncoder, const SStreamCheckpointSourceReq* pReq) { @@ -192,3 +193,4 @@ int32_t streamProcessCheckpointRsp(SStreamMeta* pMeta, SStreamTask* pTask, SStre // set status normal return 0; } +#endif diff --git a/source/libs/stream/src/streamData.c b/source/libs/stream/src/streamData.c index 8a2e940563..8baebaee42 100644 --- a/source/libs/stream/src/streamData.c +++ b/source/libs/stream/src/streamData.c @@ -17,7 +17,7 @@ int32_t streamDispatchReqToData(const SStreamDispatchReq* pReq, SStreamDataBlock* pData) { int32_t blockNum = pReq->blockNum; - SArray* pArray = taosArrayInit_s(blockNum, sizeof(SSDataBlock), blockNum); + SArray* pArray = taosArrayInit_s(sizeof(SSDataBlock), blockNum); if (pArray == NULL) { return -1; } @@ -26,7 +26,7 @@ int32_t streamDispatchReqToData(const SStreamDispatchReq* pReq, SStreamDataBlock ASSERT(pReq->blockNum == taosArrayGetSize(pReq->dataLen)); for (int32_t i = 0; i < blockNum; i++) { - SRetrieveTableRsp* pRetrieve = taosArrayGetP(pReq->data, i); + SRetrieveTableRsp* pRetrieve = (SRetrieveTableRsp*) taosArrayGetP(pReq->data, i); SSDataBlock* pDataBlock = taosArrayGet(pArray, i); blockDecode(pDataBlock, pRetrieve->data); // TODO: refactor diff --git a/source/libs/stream/src/streamExec.c b/source/libs/stream/src/streamExec.c index 5bbd60bf0d..9226d6ebb8 100644 --- a/source/libs/stream/src/streamExec.c +++ b/source/libs/stream/src/streamExec.c @@ -114,12 +114,14 @@ int32_t streamScanExec(SStreamTask* pTask, int32_t batchSz) { int32_t batchCnt = 0; while (1) { if (atomic_load_8(&pTask->taskStatus) == TASK_STATUS__DROPPING) { + taosArrayDestroy(pRes); return 0; } SSDataBlock* output = NULL; uint64_t ts = 0; if (qExecTask(exec, &output, &ts) < 0) { + taosArrayDestroy(pRes); return -1; } if (output == NULL) { diff --git a/source/libs/stream/src/streamMeta.c b/source/libs/stream/src/streamMeta.c index 63527e2b1c..66d98e90bf 100644 --- a/source/libs/stream/src/streamMeta.c +++ b/source/libs/stream/src/streamMeta.c @@ -26,7 +26,7 @@ SStreamMeta* streamMetaOpen(const char* path, void* ahandle, FTaskExpand expandF int32_t len = strlen(path) + 20; char* streamPath = taosMemoryCalloc(1, len); sprintf(streamPath, "%s/%s", path, "stream"); - pMeta->path = strdup(streamPath); + pMeta->path = taosStrdup(streamPath); if (tdbOpen(pMeta->path, 16 * 1024, 1, &pMeta->db, 0) < 0) { taosMemoryFree(streamPath); goto _err; @@ -171,6 +171,7 @@ int32_t streamMetaAddTask(SStreamMeta* pMeta, int64_t ver, SStreamTask* pTask) { } #endif +#if 0 SStreamTask* streamMetaGetTask(SStreamMeta* pMeta, int32_t taskId) { SStreamTask** ppTask = (SStreamTask**)taosHashGet(pMeta->pTasks, &taskId, sizeof(int32_t)); if (ppTask) { @@ -180,6 +181,7 @@ SStreamTask* streamMetaGetTask(SStreamMeta* pMeta, int32_t taskId) { return NULL; } } +#endif SStreamTask* streamMetaAcquireTask(SStreamMeta* pMeta, int32_t taskId) { taosRLockLatch(&pMeta->lock); diff --git a/source/libs/stream/src/streamQueue.c b/source/libs/stream/src/streamQueue.c index 7eafcdc93e..882fba718b 100644 --- a/source/libs/stream/src/streamQueue.c +++ b/source/libs/stream/src/streamQueue.c @@ -46,6 +46,7 @@ void streamQueueClose(SStreamQueue* queue) { taosMemoryFree(queue); } +#if 0 bool streamQueueResEmpty(const SStreamQueueRes* pRes) { // return true; @@ -101,3 +102,4 @@ SStreamQueueRes streamQueueGetRes(SStreamQueue1* pQueue) { if (pNode) return streamQueueBuildRes(pNode); return (SStreamQueueRes){0}; } +#endif diff --git a/source/libs/sync/inc/syncPipeline.h b/source/libs/sync/inc/syncPipeline.h index 504a9f0bd7..a1de2ee71a 100644 --- a/source/libs/sync/inc/syncPipeline.h +++ b/source/libs/sync/inc/syncPipeline.h @@ -68,7 +68,7 @@ void syncNodeLogReplMgrDestroy(SSyncNode* pNode); // access static FORCE_INLINE int64_t syncLogGetRetryBackoffTimeMs(SSyncLogReplMgr* pMgr) { - return (1 << pMgr->retryBackoff) * SYNC_LOG_REPL_RETRY_WAIT_MS; + return ((int64_t)1 << pMgr->retryBackoff) * SYNC_LOG_REPL_RETRY_WAIT_MS; } static FORCE_INLINE int32_t syncLogGetNextRetryBackoff(SSyncLogReplMgr* pMgr) { @@ -99,6 +99,7 @@ int32_t syncLogBufferReInit(SSyncLogBuffer* pBuf, SSyncNode* pNode); // access int64_t syncLogBufferGetEndIndex(SSyncLogBuffer* pBuf); SyncTerm syncLogBufferGetLastMatchTerm(SSyncLogBuffer* pBuf); +bool syncLogBufferIsEmpty(SSyncLogBuffer* pBuf); int32_t syncLogBufferAppend(SSyncLogBuffer* pBuf, SSyncNode* pNode, SSyncRaftEntry* pEntry); int32_t syncLogBufferAccept(SSyncLogBuffer* pBuf, SSyncNode* pNode, SSyncRaftEntry* pEntry, SyncTerm prevTerm); int64_t syncLogBufferProceed(SSyncLogBuffer* pBuf, SSyncNode* pNode, SyncTerm* pMatchTerm); diff --git a/source/libs/sync/inc/syncRaftEntry.h b/source/libs/sync/inc/syncRaftEntry.h index 58944eb08c..a39e043c52 100644 --- a/source/libs/sync/inc/syncRaftEntry.h +++ b/source/libs/sync/inc/syncRaftEntry.h @@ -49,39 +49,6 @@ static FORCE_INLINE bool syncLogIsReplicationBarrier(SSyncRaftEntry* pEntry) { return pEntry->originalRpcType == TDMT_SYNC_NOOP; } -typedef struct SRaftEntryHashCache { - SHashObj* pEntryHash; - int32_t maxCount; - int32_t currentCount; - TdThreadMutex mutex; - SSyncNode* pSyncNode; -} SRaftEntryHashCache; - -SRaftEntryHashCache* raftCacheCreate(SSyncNode* pSyncNode, int32_t maxCount); -void raftCacheDestroy(SRaftEntryHashCache* pCache); -int32_t raftCachePutEntry(struct SRaftEntryHashCache* pCache, SSyncRaftEntry* pEntry); -int32_t raftCacheGetEntry(struct SRaftEntryHashCache* pCache, SyncIndex index, SSyncRaftEntry** ppEntry); -int32_t raftCacheGetEntryP(struct SRaftEntryHashCache* pCache, SyncIndex index, SSyncRaftEntry** ppEntry); -int32_t raftCacheDelEntry(struct SRaftEntryHashCache* pCache, SyncIndex index); -int32_t raftCacheGetAndDel(struct SRaftEntryHashCache* pCache, SyncIndex index, SSyncRaftEntry** ppEntry); -int32_t raftCacheClear(struct SRaftEntryHashCache* pCache); - -typedef struct SRaftEntryCache { - SSkipList* pSkipList; - int32_t maxCount; - int32_t currentCount; - int32_t refMgr; - TdThreadMutex mutex; - SSyncNode* pSyncNode; -} SRaftEntryCache; - -SRaftEntryCache* raftEntryCacheCreate(SSyncNode* pSyncNode, int32_t maxCount); -void raftEntryCacheDestroy(SRaftEntryCache* pCache); -int32_t raftEntryCachePutEntry(struct SRaftEntryCache* pCache, SSyncRaftEntry* pEntry); -int32_t raftEntryCacheGetEntry(struct SRaftEntryCache* pCache, SyncIndex index, SSyncRaftEntry** ppEntry); -int32_t raftEntryCacheGetEntryP(struct SRaftEntryCache* pCache, SyncIndex index, SSyncRaftEntry** ppEntry); -int32_t raftEntryCacheClear(struct SRaftEntryCache* pCache, int32_t count); - #ifdef __cplusplus } #endif diff --git a/source/libs/sync/src/syncAppendEntries.c b/source/libs/sync/src/syncAppendEntries.c index b04bcb86c6..bd1dae54d9 100644 --- a/source/libs/sync/src/syncAppendEntries.c +++ b/source/libs/sync/src/syncAppendEntries.c @@ -104,6 +104,8 @@ int32_t syncNodeOnAppendEntries(SSyncNode* ths, const SRpcMsg* pRpcMsg) { SyncAppendEntries* pMsg = pRpcMsg->pCont; SRpcMsg rpcRsp = {0}; bool accepted = false; + SSyncRaftEntry* pEntry = NULL; + // if already drop replica, do not process if (!syncNodeInRaftGroup(ths, &(pMsg->srcId))) { syncLogRecvAppendEntries(ths, pMsg, "not in my config"); @@ -137,14 +139,13 @@ int32_t syncNodeOnAppendEntries(SSyncNode* ths, const SRpcMsg* pRpcMsg) { syncNodeStepDown(ths, pMsg->term); syncNodeResetElectTimer(ths); - if (pMsg->dataLen < (int32_t)sizeof(SSyncRaftEntry)) { + if (pMsg->dataLen < sizeof(SSyncRaftEntry)) { sError("vgId:%d, incomplete append entries received. prev index:%" PRId64 ", term:%" PRId64 ", datalen:%d", ths->vgId, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->dataLen); goto _IGNORE; } - SSyncRaftEntry* pEntry = syncBuildRaftEntryFromAppendEntries(pMsg); - + pEntry = syncBuildRaftEntryFromAppendEntries(pMsg); if (pEntry == NULL) { sError("vgId:%d, failed to get raft entry from append entries since %s", ths->vgId, terrstr()); goto _IGNORE; @@ -191,5 +192,6 @@ _out: _IGNORE: rpcFreeCont(rpcRsp.pCont); + syncEntryDestroy(pEntry); return 0; } diff --git a/source/libs/sync/src/syncAppendEntriesReply.c b/source/libs/sync/src/syncAppendEntriesReply.c index f81699b9f6..a60f43cd5e 100644 --- a/source/libs/sync/src/syncAppendEntriesReply.c +++ b/source/libs/sync/src/syncAppendEntriesReply.c @@ -40,7 +40,7 @@ // int32_t syncNodeOnAppendEntriesReply(SSyncNode* ths, const SRpcMsg* pRpcMsg) { - SyncAppendEntriesReply* pMsg = pRpcMsg->pCont; + SyncAppendEntriesReply* pMsg = (SyncAppendEntriesReply*)pRpcMsg->pCont; int32_t ret = 0; // if already drop replica, do not process diff --git a/source/libs/sync/src/syncMain.c b/source/libs/sync/src/syncMain.c index 5935f8393a..b07c05dcfe 100644 --- a/source/libs/sync/src/syncMain.c +++ b/source/libs/sync/src/syncMain.c @@ -270,88 +270,40 @@ int32_t syncBeginSnapshot(int64_t rid, int64_t lastApplyIndex) { return -1; } + SyncIndex beginIndex = pSyncNode->pLogStore->syncLogBeginIndex(pSyncNode->pLogStore); + SyncIndex endIndex = pSyncNode->pLogStore->syncLogEndIndex(pSyncNode->pLogStore); + bool isEmpty = pSyncNode->pLogStore->syncLogIsEmpty(pSyncNode->pLogStore); + + if (isEmpty || !(lastApplyIndex >= beginIndex && lastApplyIndex <= endIndex)) { + sNTrace(pSyncNode, "new-snapshot-index:%" PRId64 ", empty:%d, do not delete wal", lastApplyIndex, isEmpty); + syncNodeRelease(pSyncNode); + return 0; + } + int32_t code = 0; + int64_t logRetention = 0; if (syncNodeIsMnode(pSyncNode)) { // mnode - int64_t logRetention = SYNC_MNODE_LOG_RETENTION; - - SyncIndex beginIndex = pSyncNode->pLogStore->syncLogBeginIndex(pSyncNode->pLogStore); - SyncIndex endIndex = pSyncNode->pLogStore->syncLogEndIndex(pSyncNode->pLogStore); - int64_t logNum = endIndex - beginIndex; - bool isEmpty = pSyncNode->pLogStore->syncLogIsEmpty(pSyncNode->pLogStore); - - if (isEmpty || (!isEmpty && logNum < logRetention)) { - sNTrace(pSyncNode, "new-snapshot-index:%" PRId64 ", log-num:%" PRId64 ", empty:%d, do not delete wal", - lastApplyIndex, logNum, isEmpty); - syncNodeRelease(pSyncNode); - return 0; - } - - goto _DEL_WAL; - + logRetention = SYNC_MNODE_LOG_RETENTION; } else { - SyncIndex beginIndex = pSyncNode->pLogStore->syncLogBeginIndex(pSyncNode->pLogStore); - SyncIndex endIndex = pSyncNode->pLogStore->syncLogEndIndex(pSyncNode->pLogStore); - bool isEmpty = pSyncNode->pLogStore->syncLogIsEmpty(pSyncNode->pLogStore); - - if (isEmpty || !(lastApplyIndex >= beginIndex && lastApplyIndex <= endIndex)) { - sNTrace(pSyncNode, "new-snapshot-index:%" PRId64 ", empty:%d, do not delete wal", lastApplyIndex, isEmpty); - syncNodeRelease(pSyncNode); - return 0; - } - // vnode if (pSyncNode->replicaNum > 1) { // multi replicas - - lastApplyIndex = TMAX(lastApplyIndex - SYNC_VNODE_LOG_RETENTION, beginIndex - 1); - - if (pSyncNode->state == TAOS_SYNC_STATE_LEADER) { - pSyncNode->minMatchIndex = syncMinMatchIndex(pSyncNode); - - for (int32_t i = 0; i < pSyncNode->peersNum; ++i) { - int64_t matchIndex = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId[i])); - if (lastApplyIndex > matchIndex) { - sNTrace(pSyncNode, - "new-snapshot-index:%" PRId64 " is greater than match-index:%" PRId64 - " of dnode:%d, do not delete wal", - lastApplyIndex, matchIndex, DID(&pSyncNode->peersId[i])); - - syncNodeRelease(pSyncNode); - return 0; - } - } - - } else if (pSyncNode->state == TAOS_SYNC_STATE_FOLLOWER) { - if (lastApplyIndex > pSyncNode->minMatchIndex) { - sNTrace(pSyncNode, - "new-snapshot-index:%" PRId64 " is greater than min-match-index:%" PRId64 ", do not delete wal", - lastApplyIndex, pSyncNode->minMatchIndex); - syncNodeRelease(pSyncNode); - return 0; - } - - } else if (pSyncNode->state == TAOS_SYNC_STATE_CANDIDATE) { - sNTrace(pSyncNode, "new-snapshot-index:%" PRId64 " candidate, do not delete wal", lastApplyIndex); - syncNodeRelease(pSyncNode); - return 0; - - } else { - sNTrace(pSyncNode, "new-snapshot-index:%" PRId64 " unknown state, do not delete wal", lastApplyIndex); - syncNodeRelease(pSyncNode); - return 0; - } - - goto _DEL_WAL; - - } else { - // one replica - - goto _DEL_WAL; + logRetention = SYNC_VNODE_LOG_RETENTION; } } + if (pSyncNode->replicaNum > 1) { + if (pSyncNode->state != TAOS_SYNC_STATE_LEADER && pSyncNode->state != TAOS_SYNC_STATE_FOLLOWER) { + sNTrace(pSyncNode, "new-snapshot-index:%" PRId64 " candidate or unknown state, do not delete wal", + lastApplyIndex); + syncNodeRelease(pSyncNode); + return 0; + } + logRetention = TMAX(logRetention, lastApplyIndex - pSyncNode->minMatchIndex); + } + _DEL_WAL: do { @@ -366,7 +318,7 @@ _DEL_WAL: atomic_store_64(&pSyncNode->snapshottingIndex, lastApplyIndex); pSyncNode->snapshottingTime = taosGetTimestampMs(); - code = walBeginSnapshot(pData->pWal, lastApplyIndex); + code = walBeginSnapshot(pData->pWal, lastApplyIndex, logRetention); if (code == 0) { sNTrace(pSyncNode, "wal snapshot begin, index:%" PRId64 ", last apply index:%" PRId64, pSyncNode->snapshottingIndex, lastApplyIndex); @@ -1126,29 +1078,18 @@ int32_t syncNodeStartStandBy(SSyncNode* pSyncNode) { } void syncNodePreClose(SSyncNode* pSyncNode) { - if (pSyncNode != NULL && pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpApplyQueueItems != NULL) { - while (1) { - int32_t aqItems = pSyncNode->pFsm->FpApplyQueueItems(pSyncNode->pFsm); - sTrace("vgId:%d, pre close, %d items in apply queue", pSyncNode->vgId, aqItems); - if (aqItems == 0 || aqItems == -1) { - break; - } - taosMsleep(20); - } - } + ASSERT(pSyncNode != NULL); + ASSERT(pSyncNode->pFsm != NULL); + ASSERT(pSyncNode->pFsm->FpApplyQueueItems != NULL); -#if 0 - if (pSyncNode->pNewNodeReceiver != NULL) { - if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) { - snapshotReceiverStop(pSyncNode->pNewNodeReceiver); + while (1) { + int32_t aqItems = pSyncNode->pFsm->FpApplyQueueItems(pSyncNode->pFsm); + sTrace("vgId:%d, pre close, %d items in apply queue", pSyncNode->vgId, aqItems); + if (aqItems == 0 || aqItems == -1) { + break; } - - sDebug("vgId:%d, snapshot receiver destroy while preclose sync node, data:%p", pSyncNode->vgId, - pSyncNode->pNewNodeReceiver); - snapshotReceiverDestroy(pSyncNode->pNewNodeReceiver); - pSyncNode->pNewNodeReceiver = NULL; + taosMsleep(20); } -#endif // stop elect timer syncNodeStopElectTimer(pSyncNode); @@ -1461,7 +1402,7 @@ void syncNodeDoConfigChange(SSyncNode* pSyncNode, SSyncCfg* pNewConfig, SyncInde } // log begin config change - sNInfo(pSyncNode, "begin do config change, from %d to %d", pSyncNode->vgId, oldConfig.replicaNum, + sNInfo(pSyncNode, "begin do config change, from %d to %d, replicas:%d", pSyncNode->vgId, oldConfig.replicaNum, pNewConfig->replicaNum); if (IamInNew) { @@ -1742,8 +1683,7 @@ void syncNodeBecomeLeader(SSyncNode* pSyncNode, const char* debugStr) { #endif // close receiver - if (pSyncNode != NULL && pSyncNode->pNewNodeReceiver != NULL && - snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) { + if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) { snapshotReceiverStop(pSyncNode->pNewNodeReceiver); } @@ -2153,24 +2093,19 @@ static void syncNodeEqPeerHeartbeatTimer(void* param, void* tmrId) { if (timerLogicClock == msgLogicClock) { if (tsNow > pData->execTime) { -#if 0 - sTrace( - "vgId:%d, hbDataRid:%ld, EXECUTE this step-------- heartbeat tsNow:%ld, exec:%ld, tsNow-exec:%ld, " - "---------", - pSyncNode->vgId, hbDataRid, tsNow, pData->execTime, tsNow - pData->execTime); -#endif - pData->execTime += pSyncTimer->timerMS; SRpcMsg rpcMsg = {0}; (void)syncBuildHeartbeat(&rpcMsg, pSyncNode->vgId); + pSyncNode->minMatchIndex = syncMinMatchIndex(pSyncNode); + SyncHeartbeat* pSyncMsg = rpcMsg.pCont; pSyncMsg->srcId = pSyncNode->myRaftId; pSyncMsg->destId = pData->destId; pSyncMsg->term = raftStoreGetTerm(pSyncNode); pSyncMsg->commitIndex = pSyncNode->commitIndex; - pSyncMsg->minMatchIndex = syncMinMatchIndex(pSyncNode); + pSyncMsg->minMatchIndex = pSyncNode->minMatchIndex; pSyncMsg->privateTerm = 0; pSyncMsg->timeStamp = tsNow; @@ -2182,11 +2117,6 @@ static void syncNodeEqPeerHeartbeatTimer(void* param, void* tmrId) { syncLogSendHeartbeat(pSyncNode, pSyncMsg, false, timerElapsed, pData->execTime); syncNodeSendHeartbeat(pSyncNode, &pSyncMsg->destId, &rpcMsg); } else { -#if 0 - sTrace( - "vgId:%d, hbDataRid:%ld, pass this step-------- heartbeat tsNow:%ld, exec:%ld, tsNow-exec:%ld, ---------", - pSyncNode->vgId, hbDataRid, tsNow, pData->execTime, tsNow - pData->execTime); -#endif } if (syncIsInit()) { @@ -2479,6 +2409,10 @@ int32_t syncNodeOnLocalCmd(SSyncNode* ths, const SRpcMsg* pRpcMsg) { syncNodeStepDown(ths, pMsg->currentTerm); } else if (pMsg->cmd == SYNC_LOCAL_CMD_FOLLOWER_CMT) { + if (syncLogBufferIsEmpty(ths->pLogBuf)) { + sError("vgId:%d, sync log buffer is empty.", ths->vgId); + return 0; + } SyncTerm matchTerm = syncLogBufferGetLastMatchTerm(ths->pLogBuf); if (pMsg->currentTerm == matchTerm) { (void)syncNodeUpdateCommitIndex(ths, pMsg->commitIndex); diff --git a/source/libs/sync/src/syncPipeline.c b/source/libs/sync/src/syncPipeline.c index c9ff2d2dcc..faa44a626c 100644 --- a/source/libs/sync/src/syncPipeline.c +++ b/source/libs/sync/src/syncPipeline.c @@ -253,6 +253,7 @@ int32_t syncLogBufferInit(SSyncLogBuffer* pBuf, SSyncNode* pNode) { int32_t syncLogBufferReInit(SSyncLogBuffer* pBuf, SSyncNode* pNode) { taosThreadMutexLock(&pBuf->mutex); + syncLogBufferValidate(pBuf); for (SyncIndex index = pBuf->startIndex; index < pBuf->endIndex; index++) { SSyncRaftEntry* pEntry = pBuf->entries[(index + pBuf->size) % pBuf->size].pItem; if (pEntry == NULL) continue; @@ -265,6 +266,7 @@ int32_t syncLogBufferReInit(SSyncLogBuffer* pBuf, SSyncNode* pNode) { if (ret < 0) { sError("vgId:%d, failed to re-initialize sync log buffer since %s.", pNode->vgId, terrstr()); } + syncLogBufferValidate(pBuf); taosThreadMutexUnlock(&pBuf->mutex); return ret; } @@ -283,6 +285,13 @@ SyncTerm syncLogBufferGetLastMatchTerm(SSyncLogBuffer* pBuf) { return term; } +bool syncLogBufferIsEmpty(SSyncLogBuffer* pBuf) { + taosThreadMutexLock(&pBuf->mutex); + bool empty = (pBuf->endIndex <= pBuf->startIndex); + taosThreadMutexUnlock(&pBuf->mutex); + return empty; +} + int32_t syncLogBufferAccept(SSyncLogBuffer* pBuf, SSyncNode* pNode, SSyncRaftEntry* pEntry, SyncTerm prevTerm) { taosThreadMutexLock(&pBuf->mutex); syncLogBufferValidate(pBuf); @@ -901,7 +910,7 @@ int32_t syncLogReplMgrProcessReplyAsNormal(SSyncLogReplMgr* pMgr, SSyncNode* pNo int64_t firstSentMs = pMgr->states[pMgr->startIndex % pMgr->size].timeMs; int64_t lastSentMs = pMgr->states[(pMgr->endIndex - 1) % pMgr->size].timeMs; int64_t timeDiffMs = lastSentMs - firstSentMs; - if (timeDiffMs > 0 && timeDiffMs < (SYNC_LOG_REPL_RETRY_WAIT_MS << (pMgr->retryBackoff - 1))) { + if (timeDiffMs > 0 && timeDiffMs < ((int64_t)SYNC_LOG_REPL_RETRY_WAIT_MS << (pMgr->retryBackoff - 1))) { pMgr->retryBackoff -= 1; } } @@ -928,10 +937,6 @@ SSyncLogReplMgr* syncLogReplMgrCreate() { ASSERT(pMgr->size == TSDB_SYNC_LOG_BUFFER_SIZE); return pMgr; - -_err: - taosMemoryFree(pMgr); - return NULL; } void syncLogReplMgrDestroy(SSyncLogReplMgr* pMgr) { @@ -1073,6 +1078,7 @@ int32_t syncLogBufferRollback(SSyncLogBuffer* pBuf, SSyncNode* pNode, SyncIndex int32_t syncLogBufferReset(SSyncLogBuffer* pBuf, SSyncNode* pNode) { taosThreadMutexLock(&pBuf->mutex); + syncLogBufferValidate(pBuf); SyncIndex lastVer = pNode->pLogStore->syncLogLastIndex(pNode->pLogStore); ASSERT(lastVer == pBuf->matchIndex); SyncIndex index = pBuf->endIndex - 1; @@ -1089,6 +1095,7 @@ int32_t syncLogBufferReset(SSyncLogBuffer* pBuf, SSyncNode* pNode) { SSyncLogReplMgr* pMgr = pNode->logReplMgrs[i]; syncLogReplMgrReset(pMgr); } + syncLogBufferValidate(pBuf); taosThreadMutexUnlock(&pBuf->mutex); return 0; } diff --git a/source/libs/sync/src/syncRaftCfg.c b/source/libs/sync/src/syncRaftCfg.c index 806949c81e..f780e255ce 100644 --- a/source/libs/sync/src/syncRaftCfg.c +++ b/source/libs/sync/src/syncRaftCfg.c @@ -224,7 +224,7 @@ _OVER: int32_t syncAddCfgIndex(SSyncNode *pNode, SyncIndex cfgIndex) { SRaftCfg *pCfg = &pNode->raftCfg; - if (pCfg->configIndexCount <= MAX_CONFIG_INDEX_COUNT) { + if (pCfg->configIndexCount < MAX_CONFIG_INDEX_COUNT) { return -1; } diff --git a/source/libs/sync/src/syncRaftEntry.c b/source/libs/sync/src/syncRaftEntry.c index 623f1b77a4..3e63e2fb8e 100644 --- a/source/libs/sync/src/syncRaftEntry.c +++ b/source/libs/sync/src/syncRaftEntry.c @@ -102,344 +102,3 @@ void syncEntry2OriginalRpc(const SSyncRaftEntry* pEntry, SRpcMsg* pRpcMsg) { pRpcMsg->pCont = rpcMallocCont(pRpcMsg->contLen); memcpy(pRpcMsg->pCont, pEntry->data, pRpcMsg->contLen); } - -SRaftEntryHashCache* raftCacheCreate(SSyncNode* pSyncNode, int32_t maxCount) { - SRaftEntryHashCache* pCache = taosMemoryMalloc(sizeof(SRaftEntryHashCache)); - if (pCache == NULL) { - sError("vgId:%d, raft cache create error", pSyncNode->vgId); - return NULL; - } - - pCache->pEntryHash = - taosHashInit(sizeof(SyncIndex), taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK); - if (pCache->pEntryHash == NULL) { - sError("vgId:%d, raft cache create hash error", pSyncNode->vgId); - return NULL; - } - - taosThreadMutexInit(&(pCache->mutex), NULL); - pCache->maxCount = maxCount; - pCache->currentCount = 0; - pCache->pSyncNode = pSyncNode; - - return pCache; -} - -void raftCacheDestroy(SRaftEntryHashCache* pCache) { - if (pCache != NULL) { - taosThreadMutexLock(&pCache->mutex); - taosHashCleanup(pCache->pEntryHash); - taosThreadMutexUnlock(&pCache->mutex); - taosThreadMutexDestroy(&(pCache->mutex)); - taosMemoryFree(pCache); - } -} - -// success, return 1 -// max count, return 0 -// error, return -1 -int32_t raftCachePutEntry(struct SRaftEntryHashCache* pCache, SSyncRaftEntry* pEntry) { - taosThreadMutexLock(&pCache->mutex); - - if (pCache->currentCount >= pCache->maxCount) { - taosThreadMutexUnlock(&pCache->mutex); - return 0; - } - - taosHashPut(pCache->pEntryHash, &(pEntry->index), sizeof(pEntry->index), pEntry, pEntry->bytes); - ++(pCache->currentCount); - - sNTrace(pCache->pSyncNode, "raft cache add, type:%s,%d, type2:%s,%d, index:%" PRId64 ", bytes:%d", - TMSG_INFO(pEntry->msgType), pEntry->msgType, TMSG_INFO(pEntry->originalRpcType), pEntry->originalRpcType, - pEntry->index, pEntry->bytes); - taosThreadMutexUnlock(&pCache->mutex); - return 1; -} - -// success, return 0 -// error, return -1 -// not exist, return -1, terrno = TSDB_CODE_WAL_LOG_NOT_EXIST -int32_t raftCacheGetEntry(struct SRaftEntryHashCache* pCache, SyncIndex index, SSyncRaftEntry** ppEntry) { - if (ppEntry == NULL) { - return -1; - } - *ppEntry = NULL; - - taosThreadMutexLock(&pCache->mutex); - void* pTmp = taosHashGet(pCache->pEntryHash, &index, sizeof(index)); - if (pTmp != NULL) { - SSyncRaftEntry* pEntry = pTmp; - *ppEntry = taosMemoryMalloc(pEntry->bytes); - memcpy(*ppEntry, pTmp, pEntry->bytes); - - sNTrace(pCache->pSyncNode, "raft cache get, type:%s,%d, type2:%s,%d, index:%" PRId64, - TMSG_INFO((*ppEntry)->msgType), (*ppEntry)->msgType, TMSG_INFO((*ppEntry)->originalRpcType), - (*ppEntry)->originalRpcType, (*ppEntry)->index); - taosThreadMutexUnlock(&pCache->mutex); - return 0; - } - - taosThreadMutexUnlock(&pCache->mutex); - terrno = TSDB_CODE_WAL_LOG_NOT_EXIST; - return -1; -} - -// success, return 0 -// error, return -1 -// not exist, return -1, terrno = TSDB_CODE_WAL_LOG_NOT_EXIST -int32_t raftCacheGetEntryP(struct SRaftEntryHashCache* pCache, SyncIndex index, SSyncRaftEntry** ppEntry) { - if (ppEntry == NULL) { - return -1; - } - *ppEntry = NULL; - - taosThreadMutexLock(&pCache->mutex); - void* pTmp = taosHashGet(pCache->pEntryHash, &index, sizeof(index)); - if (pTmp != NULL) { - SSyncRaftEntry* pEntry = pTmp; - *ppEntry = pEntry; - - sNTrace(pCache->pSyncNode, "raft cache get, type:%s,%d, type2:%s,%d, index:%" PRId64, - TMSG_INFO((*ppEntry)->msgType), (*ppEntry)->msgType, TMSG_INFO((*ppEntry)->originalRpcType), - (*ppEntry)->originalRpcType, (*ppEntry)->index); - taosThreadMutexUnlock(&pCache->mutex); - return 0; - } - - taosThreadMutexUnlock(&pCache->mutex); - terrno = TSDB_CODE_WAL_LOG_NOT_EXIST; - return -1; -} - -int32_t raftCacheDelEntry(struct SRaftEntryHashCache* pCache, SyncIndex index) { - taosThreadMutexLock(&pCache->mutex); - taosHashRemove(pCache->pEntryHash, &index, sizeof(index)); - --(pCache->currentCount); - taosThreadMutexUnlock(&pCache->mutex); - return 0; -} - -int32_t raftCacheGetAndDel(struct SRaftEntryHashCache* pCache, SyncIndex index, SSyncRaftEntry** ppEntry) { - if (ppEntry == NULL) { - return -1; - } - *ppEntry = NULL; - - taosThreadMutexLock(&pCache->mutex); - void* pTmp = taosHashGet(pCache->pEntryHash, &index, sizeof(index)); - if (pTmp != NULL) { - SSyncRaftEntry* pEntry = pTmp; - *ppEntry = taosMemoryMalloc(pEntry->bytes); - memcpy(*ppEntry, pTmp, pEntry->bytes); - - sNTrace(pCache->pSyncNode, "raft cache get-and-del, type:%s,%d, type2:%s,%d, index:%" PRId64, - TMSG_INFO((*ppEntry)->msgType), (*ppEntry)->msgType, TMSG_INFO((*ppEntry)->originalRpcType), - (*ppEntry)->originalRpcType, (*ppEntry)->index); - - taosHashRemove(pCache->pEntryHash, &index, sizeof(index)); - --(pCache->currentCount); - - taosThreadMutexUnlock(&pCache->mutex); - return 0; - } - - taosThreadMutexUnlock(&pCache->mutex); - terrno = TSDB_CODE_WAL_LOG_NOT_EXIST; - return -1; -} - -int32_t raftCacheClear(struct SRaftEntryHashCache* pCache) { - taosThreadMutexLock(&pCache->mutex); - taosHashClear(pCache->pEntryHash); - pCache->currentCount = 0; - taosThreadMutexUnlock(&pCache->mutex); - return 0; -} - -static char* keyFn(const void* pData) { - SSyncRaftEntry* pEntry = (SSyncRaftEntry*)pData; - return (char*)(&(pEntry->index)); -} - -static int cmpFn(const void* p1, const void* p2) { return memcmp(p1, p2, sizeof(SyncIndex)); } - -static void freeRaftEntry(void* param) { - SSyncRaftEntry* pEntry = (SSyncRaftEntry*)param; - syncEntryDestroy(pEntry); -} - -SRaftEntryCache* raftEntryCacheCreate(SSyncNode* pSyncNode, int32_t maxCount) { - SRaftEntryCache* pCache = taosMemoryMalloc(sizeof(SRaftEntryCache)); - if (pCache == NULL) { - sError("vgId:%d, raft cache create error", pSyncNode->vgId); - return NULL; - } - - pCache->pSkipList = - tSkipListCreate(MAX_SKIP_LIST_LEVEL, TSDB_DATA_TYPE_BINARY, sizeof(SyncIndex), cmpFn, SL_ALLOW_DUP_KEY, keyFn); - if (pCache->pSkipList == NULL) { - sError("vgId:%d, raft cache create hash error", pSyncNode->vgId); - return NULL; - } - - taosThreadMutexInit(&(pCache->mutex), NULL); - pCache->refMgr = taosOpenRef(10, freeRaftEntry); - pCache->maxCount = maxCount; - pCache->currentCount = 0; - pCache->pSyncNode = pSyncNode; - - return pCache; -} - -void raftEntryCacheDestroy(SRaftEntryCache* pCache) { - if (pCache != NULL) { - taosThreadMutexLock(&pCache->mutex); - tSkipListDestroy(pCache->pSkipList); - if (pCache->refMgr != -1) { - taosCloseRef(pCache->refMgr); - pCache->refMgr = -1; - } - taosThreadMutexUnlock(&pCache->mutex); - taosThreadMutexDestroy(&(pCache->mutex)); - taosMemoryFree(pCache); - } -} - -// success, return 1 -// max count, return 0 -// error, return -1 -int32_t raftEntryCachePutEntry(struct SRaftEntryCache* pCache, SSyncRaftEntry* pEntry) { - taosThreadMutexLock(&pCache->mutex); - - if (pCache->currentCount >= pCache->maxCount) { - taosThreadMutexUnlock(&pCache->mutex); - return 0; - } - - SSkipListNode* pSkipListNode = tSkipListPut(pCache->pSkipList, pEntry); - ASSERT(pSkipListNode != NULL); - ++(pCache->currentCount); - - pEntry->rid = taosAddRef(pCache->refMgr, pEntry); - ASSERT(pEntry->rid >= 0); - - sNTrace(pCache->pSyncNode, "raft cache add, type:%s,%d, type2:%s,%d, index:%" PRId64 ", bytes:%d", - TMSG_INFO(pEntry->msgType), pEntry->msgType, TMSG_INFO(pEntry->originalRpcType), pEntry->originalRpcType, - pEntry->index, pEntry->bytes); - taosThreadMutexUnlock(&pCache->mutex); - return 1; -} - -// find one, return 1 -// not found, return 0 -// error, return -1 -int32_t raftEntryCacheGetEntry(struct SRaftEntryCache* pCache, SyncIndex index, SSyncRaftEntry** ppEntry) { - ASSERT(ppEntry != NULL); - SSyncRaftEntry* pEntry = NULL; - int32_t code = raftEntryCacheGetEntryP(pCache, index, &pEntry); - if (code == 1) { - int32_t bytes = (int32_t)pEntry->bytes; - *ppEntry = taosMemoryMalloc((int64_t)bytes); - memcpy(*ppEntry, pEntry, pEntry->bytes); - (*ppEntry)->rid = -1; - } else { - *ppEntry = NULL; - } - return code; -} - -// find one, return 1 -// not found, return 0 -// error, return -1 -int32_t raftEntryCacheGetEntryP(struct SRaftEntryCache* pCache, SyncIndex index, SSyncRaftEntry** ppEntry) { - taosThreadMutexLock(&pCache->mutex); - - SyncIndex index2 = index; - int32_t code = 0; - - SArray* entryPArray = tSkipListGet(pCache->pSkipList, (char*)(&index2)); - int32_t arraySize = taosArrayGetSize(entryPArray); - if (arraySize == 1) { - SSkipListNode** ppNode = (SSkipListNode**)taosArrayGet(entryPArray, 0); - ASSERT(*ppNode != NULL); - *ppEntry = (SSyncRaftEntry*)SL_GET_NODE_DATA(*ppNode); - taosAcquireRef(pCache->refMgr, (*ppEntry)->rid); - code = 1; - - } else if (arraySize == 0) { - code = 0; - - } else { - ASSERT(0); - - code = -1; - } - taosArrayDestroy(entryPArray); - - taosThreadMutexUnlock(&pCache->mutex); - return code; -} - -// count = -1, clear all -// count >= 0, clear count -// return -1, error -// return delete count -int32_t raftEntryCacheClear(struct SRaftEntryCache* pCache, int32_t count) { - taosThreadMutexLock(&pCache->mutex); - int32_t returnCnt = 0; - - if (count == -1) { - // clear all - SSkipListIterator* pIter = tSkipListCreateIter(pCache->pSkipList); - while (tSkipListIterNext(pIter)) { - SSkipListNode* pNode = tSkipListIterGet(pIter); - ASSERT(pNode != NULL); - SSyncRaftEntry* pEntry = (SSyncRaftEntry*)SL_GET_NODE_DATA(pNode); - syncEntryDestroy(pEntry); - ++returnCnt; - } - tSkipListDestroyIter(pIter); - - tSkipListDestroy(pCache->pSkipList); - pCache->pSkipList = - tSkipListCreate(MAX_SKIP_LIST_LEVEL, TSDB_DATA_TYPE_BINARY, sizeof(SyncIndex), cmpFn, SL_ALLOW_DUP_KEY, keyFn); - ASSERT(pCache->pSkipList != NULL); - - } else { - // clear count - int i = 0; - SSkipListIterator* pIter = tSkipListCreateIter(pCache->pSkipList); - SArray* delNodeArray = taosArrayInit(0, sizeof(SSkipListNode*)); - - // free entry - while (tSkipListIterNext(pIter)) { - SSkipListNode* pNode = tSkipListIterGet(pIter); - ASSERT(pNode != NULL); - if (i++ >= count) { - break; - } - - // sDebug("push pNode:%p", pNode); - taosArrayPush(delNodeArray, &pNode); - ++returnCnt; - SSyncRaftEntry* pEntry = (SSyncRaftEntry*)SL_GET_NODE_DATA(pNode); - - // syncEntryDestroy(pEntry); - taosRemoveRef(pCache->refMgr, pEntry->rid); - } - tSkipListDestroyIter(pIter); - - // delete skiplist node - int32_t arraySize = taosArrayGetSize(delNodeArray); - for (int32_t i = 0; i < arraySize; ++i) { - SSkipListNode** ppNode = taosArrayGet(delNodeArray, i); - // sDebug("get pNode:%p", *ppNode); - tSkipListRemoveNode(pCache->pSkipList, *ppNode); - } - taosArrayDestroy(delNodeArray); - } - - pCache->currentCount -= returnCnt; - taosThreadMutexUnlock(&pCache->mutex); - return returnCnt; -} diff --git a/source/libs/sync/src/syncSnapshot.c b/source/libs/sync/src/syncSnapshot.c index a83a19928e..381327d4d7 100644 --- a/source/libs/sync/src/syncSnapshot.c +++ b/source/libs/sync/src/syncSnapshot.c @@ -168,17 +168,19 @@ static int32_t snapshotSend(SSyncSnapshotSender *pSender) { if (pSender->blockLen > 0) { // has read data - sSDebug(pSender, "snapshot sender continue to read, blockLen:%d seq:%d", pSender->blockLen, pSender->seq); + sSDebug(pSender, "vgId:%d, snapshot sender continue to read, blockLen:%d seq:%d", pSender->pSyncNode->vgId, + pSender->blockLen, pSender->seq); } else { // read finish, update seq to end pSender->seq = SYNC_SNAPSHOT_SEQ_END; - sSInfo(pSender, "snapshot sender read to the end, blockLen:%d seq:%d", pSender->blockLen, pSender->seq); + sSInfo(pSender, "vgId:%d, snapshot sender read to the end, blockLen:%d seq:%d", pSender->pSyncNode->vgId, + pSender->blockLen, pSender->seq); } // build msg SRpcMsg rpcMsg = {0}; if (syncBuildSnapshotSend(&rpcMsg, pSender->blockLen, pSender->pSyncNode->vgId) != 0) { - sSError(pSender, "snapshot sender build msg failed since %s", pSender->pSyncNode->vgId, terrstr()); + sSError(pSender, "vgId:%d, snapshot sender build msg failed since %s", pSender->pSyncNode->vgId, terrstr()); return -1; } @@ -340,11 +342,13 @@ void snapshotReceiverDestroy(SSyncSnapshotReceiver *pReceiver) { taosMemoryFree(pReceiver); } -bool snapshotReceiverIsStart(SSyncSnapshotReceiver *pReceiver) { return pReceiver->start; } +bool snapshotReceiverIsStart(SSyncSnapshotReceiver *pReceiver) { + return (pReceiver != NULL ? pReceiver->start : false); +} static int32_t snapshotReceiverStartWriter(SSyncSnapshotReceiver *pReceiver, SyncSnapshotSend *pBeginMsg) { if (pReceiver->pWriter != NULL) { - sRError(pReceiver, "vgId:%d, snapshot receiver writer is not null"); + sRError(pReceiver, "vgId:%d, snapshot receiver writer is not null", pReceiver->pSyncNode->vgId); terrno = TSDB_CODE_SYN_INTERNAL_ERROR; return -1; } @@ -851,8 +855,8 @@ static int32_t syncNodeOnSnapshotPrepRsp(SSyncNode *pSyncNode, SSyncSnapshotSend pMsg->snapBeginIndex, snapshot.lastApplyIndex, snapshot.lastApplyTerm); if (pMsg->snapBeginIndex > snapshot.lastApplyIndex) { - sSError(pSender, "prepare snapshot failed since beginIndex:%d larger than applyIndex:%d", pMsg->snapBeginIndex, - snapshot.lastApplyIndex); + sSError(pSender, "prepare snapshot failed since beginIndex:%" PRId64 " larger than applyIndex:%" PRId64, + pMsg->snapBeginIndex, snapshot.lastApplyIndex); terrno = TSDB_CODE_SYN_INTERNAL_ERROR; return -1; } @@ -966,7 +970,8 @@ int32_t syncNodeOnSnapshotRsp(SSyncNode *pSyncNode, const SRpcMsg *pRpcMsg) { if (pSender->pReader == NULL || pSender->finish) { syncLogRecvSyncSnapshotRsp(pSyncNode, pMsg, "snapshot sender invalid"); - sSError(pSender, "snapshot sender invalid, pReader:%p finish:%d", pMsg->code, pSender->pReader, pSender->finish); + sSError(pSender, "snapshot sender invalid error:%s 0x%x, pReader:%p finish:%d", tstrerror(pMsg->code), pMsg->code, + pSender->pReader, pSender->finish); terrno = pMsg->code; goto _ERROR; } diff --git a/source/libs/tdb/src/db/tdbBtree.c b/source/libs/tdb/src/db/tdbBtree.c index 4cd6a39bfe..6df2b40000 100644 --- a/source/libs/tdb/src/db/tdbBtree.c +++ b/source/libs/tdb/src/db/tdbBtree.c @@ -260,7 +260,7 @@ int tdbBtreeDelete(SBTree *pBt, const void *pKey, int kLen, TXN *pTxn) { } int tdbBtreeUpsert(SBTree *pBt, const void *pKey, int nKey, const void *pData, int nData, TXN *pTxn) { - SBTC btc; + SBTC btc = {0}; int c; int ret; @@ -272,10 +272,17 @@ int tdbBtreeUpsert(SBTree *pBt, const void *pKey, int nKey, const void *pData, i ret = tdbBtcMoveTo(&btc, pKey, nKey, &c); if (ret < 0) { tdbError("tdb/btree-upsert: btc move to failed with ret: %d.", ret); + if (TDB_CELLDECODER_FREE_KEY(&btc.coder)) { + tdbFree(btc.coder.pKey); + } tdbBtcClose(&btc); return -1; } + if (TDB_CELLDECODER_FREE_KEY(&btc.coder)) { + tdbFree(btc.coder.pKey); + } + if (btc.idx == -1) { btc.idx = 0; c = 1; @@ -1442,15 +1449,19 @@ static int tdbBtreeDecodeCell(SPage *pPage, const SCell *pCell, SCellDecoder *pD // Clear the state of decoder if (TDB_CELLDECODER_FREE_VAL(pDecoder)) { tdbFree(pDecoder->pVal); + TDB_CELLDECODER_CLZ_FREE_VAL(pDecoder); + // tdbTrace("tdb btc decoder val set nil: %p/0x%x ", pDecoder, pDecoder->freeKV); + } + if (TDB_CELLDECODER_FREE_KEY(pDecoder)) { + tdbFree(pDecoder->pKey); + TDB_CELLDECODER_CLZ_FREE_KEY(pDecoder); + // tdbTrace("tdb btc decoder key set nil: %p/0x%x ", pDecoder, pDecoder->freeKV); } pDecoder->kLen = -1; pDecoder->pKey = NULL; pDecoder->vLen = -1; pDecoder->pVal = NULL; pDecoder->pgno = 0; - TDB_CELLDECODER_SET_FREE_NIL(pDecoder); - - // tdbTrace("tdb btc decoder set nil: %p/0x%x ", pDecoder, pDecoder->freeKV); // 1. Decode header part if (!leaf) { @@ -2270,7 +2281,6 @@ int tdbBtcMoveTo(SBTC *pBtc, const void *pKey, int kLen, int *pCRst) { } else { lidx = lidx + 1; } - // compare last cell if (lidx <= ridx) { pBtc->idx = ridx; diff --git a/source/libs/tdb/src/inc/tdbInt.h b/source/libs/tdb/src/inc/tdbInt.h index 62466e9c47..7a0bcc00a4 100644 --- a/source/libs/tdb/src/inc/tdbInt.h +++ b/source/libs/tdb/src/inc/tdbInt.h @@ -122,6 +122,8 @@ typedef struct SBtInfo { #define TDB_CELLD_F_VAL 0x2 #define TDB_CELLDECODER_SET_FREE_NIL(pCellDecoder) ((pCellDecoder)->freeKV = TDB_CELLD_F_NIL) +#define TDB_CELLDECODER_CLZ_FREE_KEY(pCellDecoder) ((pCellDecoder)->freeKV &= ~TDB_CELLD_F_KEY) +#define TDB_CELLDECODER_CLZ_FREE_VAL(pCellDecoder) ((pCellDecoder)->freeKV &= ~TDB_CELLD_F_VAL) #define TDB_CELLDECODER_SET_FREE_KEY(pCellDecoder) ((pCellDecoder)->freeKV |= TDB_CELLD_F_KEY) #define TDB_CELLDECODER_SET_FREE_VAL(pCellDecoder) ((pCellDecoder)->freeKV |= TDB_CELLD_F_VAL) diff --git a/source/libs/tfs/src/tfs.c b/source/libs/tfs/src/tfs.c index bbe8f3eeac..86b36b9b12 100644 --- a/source/libs/tfs/src/tfs.c +++ b/source/libs/tfs/src/tfs.c @@ -240,7 +240,7 @@ int32_t tfsMkdirRecurAt(STfs *pTfs, const char *rname, SDiskID diskId) { if (tfsMkdirAt(pTfs, rname, diskId) < 0) { if (errno == ENOENT) { // Try to create upper - char *s = strdup(rname); + char *s = taosStrdup(rname); // Make a copy of dirname(s) because the implementation of 'dirname' differs on different platforms. // Some platform may modify the contents of the string passed into dirname(). Others may return a pointer to @@ -248,7 +248,7 @@ int32_t tfsMkdirRecurAt(STfs *pTfs, const char *rname, SDiskID diskId) { // the pointer directly in this recursion. // See // https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/dirname.3.html - char *dir = strdup(taosDirName(s)); + char *dir = taosStrdup(taosDirName(s)); if (tfsMkdirRecurAt(pTfs, dir, diskId) < 0) { taosMemoryFree(s); diff --git a/source/libs/tfs/src/tfsDisk.c b/source/libs/tfs/src/tfsDisk.c index ff40529ab2..3717bf1a6d 100644 --- a/source/libs/tfs/src/tfsDisk.c +++ b/source/libs/tfs/src/tfsDisk.c @@ -23,7 +23,7 @@ STfsDisk *tfsNewDisk(int32_t level, int32_t id, const char *path) { return NULL; } - pDisk->path = strdup(path); + pDisk->path = taosStrdup(path); if (pDisk->path == NULL) { taosMemoryFree(pDisk); terrno = TSDB_CODE_OUT_OF_MEMORY; diff --git a/source/libs/transport/inc/transComm.h b/source/libs/transport/inc/transComm.h index a41cc0068c..5ff67c87ca 100644 --- a/source/libs/transport/inc/transComm.h +++ b/source/libs/transport/inc/transComm.h @@ -22,6 +22,7 @@ extern "C" { #include "os.h" #include "taoserror.h" #include "theap.h" +#include "tmisce.h" #include "transLog.h" #include "transportInt.h" #include "trpc.h" diff --git a/source/libs/transport/src/thttp.c b/source/libs/transport/src/thttp.c index 8e5f79137f..bab86948fa 100644 --- a/source/libs/transport/src/thttp.c +++ b/source/libs/transport/src/thttp.c @@ -298,8 +298,8 @@ int32_t httpSendQuit() { static int32_t taosSendHttpReportImpl(const char* server, const char* uri, uint16_t port, char* pCont, int32_t contLen, EHttpCompFlag flag) { SHttpMsg* msg = taosMemoryMalloc(sizeof(SHttpMsg)); - msg->server = strdup(server); - msg->uri = strdup(uri); + msg->server = taosStrdup(server); + msg->uri = taosStrdup(uri); msg->port = port; msg->cont = taosMemoryMalloc(contLen); memcpy(msg->cont, pCont, contLen); diff --git a/source/libs/transport/src/trans.c b/source/libs/transport/src/trans.c index 16ea25a41a..f5f3b52f50 100644 --- a/source/libs/transport/src/trans.c +++ b/source/libs/transport/src/trans.c @@ -13,8 +13,6 @@ * along with this program. If not, see . */ -#ifdef USE_UV - #include "transComm.h" void* (*taosInitHandle[])(uint32_t ip, uint32_t port, char* label, int32_t numOfThreads, void* fp, void* shandle) = { @@ -88,6 +86,11 @@ void* rpcOpen(const SRpcInit* pInit) { pRpc->connType = pInit->connType; pRpc->idleTime = pInit->idleTime; + pRpc->parent = pInit->parent; + if (pInit->user) { + tstrncpy(pRpc->user, pInit->user, sizeof(pRpc->user)); + } + pRpc->tcphandle = (*taosInitHandle[pRpc->connType])(ip, pInit->localPort, pRpc->label, pRpc->numOfThreads, NULL, pRpc); @@ -95,10 +98,6 @@ void* rpcOpen(const SRpcInit* pInit) { taosMemoryFree(pRpc); return NULL; } - pRpc->parent = pInit->parent; - if (pInit->user) { - tstrncpy(pRpc->user, pInit->user, sizeof(pRpc->user)); - } int64_t refId = transAddExHandle(transGetInstMgt(), pRpc); transAcquireExHandle(transGetInstMgt(), refId); @@ -188,5 +187,3 @@ void rpcCleanup(void) { return; } - -#endif diff --git a/source/libs/transport/src/transCli.c b/source/libs/transport/src/transCli.c index 7e1aeafaad..e008320222 100644 --- a/source/libs/transport/src/transCli.c +++ b/source/libs/transport/src/transCli.c @@ -11,7 +11,6 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ - #include "transComm.h" typedef struct SConnList { @@ -224,9 +223,13 @@ static void cliWalkCb(uv_handle_t* handle, void* arg); } while (0); // snprintf may cause performance problem -#define CONN_CONSTRUCT_HASH_KEY(key, ip, port) \ - do { \ - snprintf(key, sizeof(key), "%s:%d", ip, (int)port); \ +#define CONN_CONSTRUCT_HASH_KEY(key, ip, port) \ + do { \ + char* p = key; \ + int32_t len = strlen(ip); \ + if (p != NULL) memcpy(p, ip, len); \ + p[len] = ':'; \ + titoa(port, 10, &p[len + 1]); \ } while (0) #define CONN_PERSIST_TIME(para) ((para) <= 90000 ? 90000 : (para)) @@ -664,7 +667,7 @@ static int32_t specifyConnRef(SCliConn* conn, bool update, int64_t handle) { static void cliAllocRecvBufferCb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) { SCliConn* conn = handle->data; SConnBuffer* pBuf = &conn->readBuf; - tDebug("%s conn %p alloc read buf", CONN_GET_INST_LABEL(conn), conn); + tTrace("%s conn %p alloc read buf", CONN_GET_INST_LABEL(conn), conn); transAllocBuffer(pBuf, buf); } static void cliRecvCb(uv_stream_t* handle, ssize_t nread, const uv_buf_t* buf) { @@ -677,7 +680,7 @@ static void cliRecvCb(uv_stream_t* handle, ssize_t nread, const uv_buf_t* buf) { if (nread > 0) { pBuf->len += nread; while (transReadComplete(pBuf)) { - tDebug("%s conn %p read complete", CONN_GET_INST_LABEL(conn), conn); + tTrace("%s conn %p read complete", CONN_GET_INST_LABEL(conn), conn); if (pBuf->invalid) { cliHandleExcept(conn); break; @@ -727,7 +730,7 @@ static SCliConn* cliCreateConn(SCliThrd* pThrd) { QUEUE_INIT(&conn->q); conn->hostThrd = pThrd; conn->status = ConnNormal; - conn->broken = 0; + conn->broken = false; transRefCliHandle(conn); atomic_add_fetch_32(&pThrd->connCount, 1); @@ -985,6 +988,7 @@ _RETURN: } static void cliDestroyBatch(SCliBatch* pBatch) { + if (pBatch == NULL) return; while (!QUEUE_IS_EMPTY(&pBatch->wq)) { queue* h = QUEUE_HEAD(&pBatch->wq); QUEUE_REMOVE(h); @@ -997,6 +1001,11 @@ static void cliDestroyBatch(SCliBatch* pBatch) { taosMemoryFree(pBatch); } static void cliHandleBatchReq(SCliBatch* pBatch, SCliThrd* pThrd) { + if (pThrd->quit == true) { + cliDestroyBatch(pBatch); + return; + } + if (pBatch == NULL || pBatch->wLen == 0 || QUEUE_IS_EMPTY(&pBatch->wq)) { return; } @@ -1014,7 +1023,7 @@ static void cliHandleBatchReq(SCliBatch* pBatch, SCliThrd* pThrd) { if (conn == NULL) { conn = cliCreateConn(pThrd); conn->pBatch = pBatch; - conn->ip = strdup(pList->dst); + conn->ip = taosStrdup(pList->dst); uint32_t ipaddr = cliGetIpFromFqdnCache(pThrd->fqdn2ipCache, pList->ip); if (ipaddr == 0xffffffff) { @@ -1082,17 +1091,23 @@ static void cliSendBatchCb(uv_write_t* req, int status) { if (status != 0) { tDebug("%s conn %p failed to send batch msg, batch size:%d, msgLen:%d, reason:%s", CONN_GET_INST_LABEL(conn), conn, p->wLen, p->batchSize, uv_err_name(status)); - cliHandleExcept(conn); + + if (!uv_is_closing((uv_handle_t*)&conn->stream)) cliHandleExcept(conn); + cliHandleBatchReq(nxtBatch, thrd); } else { tDebug("%s conn %p succ to send batch msg, batch size:%d, msgLen:%d", CONN_GET_INST_LABEL(conn), conn, p->wLen, p->batchSize); - - if (nxtBatch != NULL) { - conn->pBatch = nxtBatch; - cliSendBatch(conn); + if (!uv_is_closing((uv_handle_t*)&conn->stream)) { + if (nxtBatch != NULL) { + conn->pBatch = nxtBatch; + cliSendBatch(conn); + } else { + addConnToPool(thrd->pool, conn); + } } else { - addConnToPool(thrd->pool, conn); + cliDestroyBatch(nxtBatch); + // conn release by other callback } } @@ -1391,7 +1406,7 @@ void cliHandleReq(SCliMsg* pMsg, SCliThrd* pThrd) { uint16_t port = EPSET_GET_INUSE_PORT(&pCtx->epSet); CONN_CONSTRUCT_HASH_KEY(key, fqdn, port); - conn->ip = strdup(key); + conn->ip = taosStrdup(key); uint32_t ipaddr = cliGetIpFromFqdnCache(pThrd->fqdn2ipCache, fqdn); if (ipaddr == 0xffffffff) { @@ -1454,6 +1469,11 @@ static void cliNoBatchDealReq(queue* wq, SCliThrd* pThrd) { QUEUE_REMOVE(h); SCliMsg* pMsg = QUEUE_DATA(h, SCliMsg, q); + + if (pMsg->type == Quit) { + pThrd->stopMsg = pMsg; + continue; + } (*cliAsyncHandle[pMsg->type])(pMsg, pThrd); count++; @@ -1485,6 +1505,12 @@ static void cliBatchDealReq(queue* wq, SCliThrd* pThrd) { QUEUE_REMOVE(h); SCliMsg* pMsg = QUEUE_DATA(h, SCliMsg, q); + + if (pMsg->type == Quit) { + pThrd->stopMsg = pMsg; + continue; + } + if (pMsg->type == Normal && REQUEST_NO_RESP(&pMsg->msg)) { STransConnCtx* pCtx = pMsg->ctx; @@ -1503,8 +1529,8 @@ static void cliBatchDealReq(queue* wq, SCliThrd* pThrd) { pBatchList->batchLenLimit = pInst->batchSize; pBatchList->len += 1; - pBatchList->ip = strdup(ip); - pBatchList->dst = strdup(key); + pBatchList->ip = taosStrdup(ip); + pBatchList->dst = taosStrdup(key); pBatchList->port = port; SCliBatch* pBatch = taosMemoryCalloc(1, sizeof(SCliBatch)); @@ -1582,7 +1608,6 @@ static void cliAsyncCb(uv_async_t* handle) { SCliThrd* pThrd = item->pThrd; STrans* pTransInst = pThrd->pTransInst; - SCliMsg* pMsg = NULL; // batch process to avoid to lock/unlock frequently queue wq; taosThreadMutexLock(&item->mtx); @@ -1927,11 +1952,13 @@ static void cliSchedMsgToNextNode(SCliMsg* pMsg, SCliThrd* pThrd) { STrans* pTransInst = pThrd->pTransInst; STransConnCtx* pCtx = pMsg->ctx; - STraceId* trace = &pMsg->msg.info.traceId; - char tbuf[256] = {0}; - EPSET_DEBUG_STR(&pCtx->epSet, tbuf); - tGDebug("%s retry on next node,use:%s, step: %d,timeout:%" PRId64 "", transLabel(pThrd->pTransInst), tbuf, - pCtx->retryStep, pCtx->retryNextInterval); + if (rpcDebugFlag & DEBUG_DEBUG) { + STraceId* trace = &pMsg->msg.info.traceId; + char tbuf[256] = {0}; + EPSET_DEBUG_STR(&pCtx->epSet, tbuf); + tGDebug("%s retry on next node,use:%s, step: %d,timeout:%" PRId64 "", transLabel(pThrd->pTransInst), tbuf, + pCtx->retryStep, pCtx->retryNextInterval); + } STaskArg* arg = taosMemoryMalloc(sizeof(STaskArg)); arg->param1 = pMsg; @@ -1968,7 +1995,7 @@ FORCE_INLINE bool cliTryExtractEpSet(STransMsg* pResp, SEpSet* dst) { pResp->pCont = buf; pResp->contLen = len; - *dst = epset; + epsetAssign(dst, &epset); return true; } bool cliResetEpset(STransConnCtx* pCtx, STransMsg* pResp, bool hasEpSet) { @@ -1993,7 +2020,7 @@ bool cliResetEpset(STransConnCtx* pCtx, STransMsg* pResp, bool hasEpSet) { } else { if (!transEpSetIsEqual(&pCtx->epSet, &epSet)) { tDebug("epset not equal, retry new epset"); - pCtx->epSet = epSet; + epsetAssign(&pCtx->epSet, &epSet); noDelay = false; } else { if (pCtx->epsetRetryCnt >= pCtx->epSet.numOfEps) { @@ -2018,7 +2045,7 @@ bool cliResetEpset(STransConnCtx* pCtx, STransMsg* pResp, bool hasEpSet) { } else { if (!transEpSetIsEqual(&pCtx->epSet, &epSet)) { tDebug("epset not equal, retry new epset"); - pCtx->epSet = epSet; + epsetAssign(&pCtx->epSet, &epSet); noDelay = false; } else { if (pCtx->epsetRetryCnt >= pCtx->epSet.numOfEps) { @@ -2108,10 +2135,6 @@ bool cliGenRetryRule(SCliConn* pConn, STransMsg* pResp, SCliMsg* pMsg) { if (pCtx->retryNextInterval >= pCtx->retryMaxInterval) { pCtx->retryNextInterval = pCtx->retryMaxInterval; } - - // if (-1 != pCtx->retryMaxTimeout && taosGetTimestampMs() - pCtx->retryInitTimestamp >= pCtx->retryMaxTimeout) { - // return false; - // } } else { pCtx->retryNextInterval = 0; pCtx->epsetRetryCnt++; @@ -2159,9 +2182,11 @@ int cliAppCb(SCliConn* pConn, STransMsg* pResp, SCliMsg* pMsg) { STraceId* trace = &pResp->info.traceId; bool hasEpSet = cliTryExtractEpSet(pResp, &pCtx->epSet); if (hasEpSet) { - char tbuf[256] = {0}; - EPSET_DEBUG_STR(&pCtx->epSet, tbuf); - tGTrace("%s conn %p extract epset from msg", CONN_GET_INST_LABEL(pConn), pConn); + if (rpcDebugFlag & DEBUG_TRACE) { + char tbuf[256] = {0}; + EPSET_DEBUG_STR(&pCtx->epSet, tbuf); + tGTrace("%s conn %p extract epset from msg", CONN_GET_INST_LABEL(pConn), pConn); + } } if (pCtx->pSem != NULL) { @@ -2285,24 +2310,12 @@ int transSendRequest(void* shandle, const SEpSet* pEpSet, STransMsg* pReq, STran transReleaseExHandle(transGetInstMgt(), (int64_t)shandle); return TSDB_CODE_RPC_BROKEN_LINK; } - /*if (pTransInst->connLimitNum > 0 && REQUEST_NO_RESP(pReq)) { - char key[TSDB_FQDN_LEN + 64] = {0}; - char* ip = EPSET_GET_INUSE_IP((SEpSet*)pEpSet); - uint16_t port = EPSET_GET_INUSE_PORT((SEpSet*)pEpSet); - CONN_CONSTRUCT_HASH_KEY(key, ip, port); - - int32_t* val = taosHashGet(pThrd->connLimitCache, key, strlen(key)); - if (val != NULL && *val >= pTransInst->connLimitNum) { - transFreeMsg(pReq->pCont); - transReleaseExHandle(transGetInstMgt(), (int64_t)shandle); - return TSDB_CODE_RPC_MAX_SESSIONS; - } - }*/ TRACE_SET_MSGID(&pReq->info.traceId, tGenIdPI64()); - STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx)); - pCtx->epSet = *pEpSet; + epsetAssign(&pCtx->epSet, pEpSet); + epsetAssign(&pCtx->origEpSet, pEpSet); + pCtx->ahandle = pReq->info.ahandle; pCtx->msgType = pReq->msgType; @@ -2347,8 +2360,8 @@ int transSendRecv(void* shandle, const SEpSet* pEpSet, STransMsg* pReq, STransMs TRACE_SET_MSGID(&pReq->info.traceId, tGenIdPI64()); STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx)); - pCtx->epSet = *pEpSet; - pCtx->origEpSet = *pEpSet; + epsetAssign(&pCtx->epSet, pEpSet); + epsetAssign(&pCtx->origEpSet, pEpSet); pCtx->ahandle = pReq->info.ahandle; pCtx->msgType = pReq->msgType; pCtx->pSem = sem; diff --git a/source/libs/transport/src/transComm.c b/source/libs/transport/src/transComm.c index 4c107a88f1..0dfc7677b3 100644 --- a/source/libs/transport/src/transComm.c +++ b/source/libs/transport/src/transComm.c @@ -12,7 +12,6 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ -#ifdef USE_UV #include "transComm.h" @@ -67,7 +66,7 @@ int32_t transDecompressMsg(char** msg, int32_t len) { char* buf = taosMemoryCalloc(1, oriLen + sizeof(STransMsgHead)); STransMsgHead* pNewHead = (STransMsgHead*)buf; - int32_t decompLen = LZ4_decompress_safe(pCont + sizeof(STransCompMsg), pNewHead->content, + int32_t decompLen = LZ4_decompress_safe(pCont + sizeof(STransCompMsg), (char*)pNewHead->content, len - sizeof(STransMsgHead) - sizeof(STransCompMsg), oriLen); memcpy((char*)pNewHead, (char*)pHead, sizeof(STransMsgHead)); @@ -655,4 +654,3 @@ void transDestoryExHandle(void* handle) { } taosMemoryFree(handle); } -#endif diff --git a/source/libs/wal/src/walMeta.c b/source/libs/wal/src/walMeta.c index ee56479a31..cda7e35b0f 100644 --- a/source/libs/wal/src/walMeta.c +++ b/source/libs/wal/src/walMeta.c @@ -913,7 +913,7 @@ int walLoadMeta(SWal* pWal) { int64_t fileSize = 0; taosStatFile(fnameStr, &fileSize, NULL); if (fileSize == 0) { - taosRemoveFile(fnameStr); + (void)taosRemoveFile(fnameStr); wDebug("vgId:%d, wal find empty meta ver %d", pWal->cfg.vgId, metaVer); return -1; } diff --git a/source/libs/wal/src/walRead.c b/source/libs/wal/src/walRead.c index e31616f53e..7bfd3df9e0 100644 --- a/source/libs/wal/src/walRead.c +++ b/source/libs/wal/src/walRead.c @@ -96,7 +96,7 @@ int32_t walNextValidMsg(SWalReader *pReader) { if (walSkipFetchBodyNew(pReader) < 0) { return -1; } - fetchVer++; + fetchVer = pReader->curVersion; } } pReader->curStopped = 1; @@ -142,7 +142,7 @@ static int64_t walReadSeekFilePos(SWalReader *pReader, int64_t fileFirstVer, int } static int32_t walReadChangeFile(SWalReader *pReader, int64_t fileFirstVer) { - char fnameStr[WAL_FILE_LEN]; + char fnameStr[WAL_FILE_LEN] = {0}; taosCloseFile(&pReader->pIdxFile); taosCloseFile(&pReader->pLogFile); @@ -299,14 +299,6 @@ static int32_t walFetchBodyNew(SWalReader *pReader) { return -1; } - if (pReadHead->version != ver) { - wError("vgId:%d, wal fetch body error:%" PRId64 ", read request index:%" PRId64, pReader->pWal->cfg.vgId, - pReader->pHead->head.version, ver); - pReader->curInvalid = 1; - terrno = TSDB_CODE_WAL_FILE_CORRUPTED; - return -1; - } - if (walValidBodyCksum(pReader->pHead) != 0) { wError("vgId:%d, wal fetch body error:%" PRId64 ", since body checksum not passed", pReader->pWal->cfg.vgId, ver); pReader->curInvalid = 1; diff --git a/source/libs/wal/src/walRef.c b/source/libs/wal/src/walRef.c index d3c03c335b..4d451db0c0 100644 --- a/source/libs/wal/src/walRef.c +++ b/source/libs/wal/src/walRef.c @@ -26,7 +26,7 @@ SWalRef *walOpenRef(SWal *pWal) { } pRef->refId = tGenIdPI64(); pRef->refVer = -1; - pRef->refFile = -1; + // pRef->refFile = -1; pRef->pWal = pWal; taosHashPut(pWal->pRefHash, &pRef->refId, sizeof(int64_t), &pRef, sizeof(void *)); return pRef; @@ -58,11 +58,11 @@ int32_t walRefVer(SWalRef *pRef, int64_t ver) { pRef->refVer = ver; // bsearch in fileSet - SWalFileInfo tmpInfo; - tmpInfo.firstVer = ver; - SWalFileInfo *pRet = taosArraySearch(pWal->fileInfoSet, &tmpInfo, compareWalFileInfo, TD_LE); - /*A(pRet != NULL);*/ - pRef->refFile = pRet->firstVer; + // SWalFileInfo tmpInfo; + // tmpInfo.firstVer = ver; + // SWalFileInfo *pRet = taosArraySearch(pWal->fileInfoSet, &tmpInfo, compareWalFileInfo, TD_LE); + // ASSERT(pRet != NULL); + // pRef->refFile = pRet->firstVer; taosThreadMutexUnlock(&pWal->mutex); } @@ -73,7 +73,7 @@ int32_t walRefVer(SWalRef *pRef, int64_t ver) { #if 1 void walUnrefVer(SWalRef *pRef) { pRef->refId = -1; - pRef->refFile = -1; + // pRef->refFile = -1; } #endif @@ -85,20 +85,18 @@ SWalRef *walRefFirstVer(SWal *pWal, SWalRef *pRef) { } } taosThreadMutexLock(&pWal->mutex); - int64_t ver = walGetFirstVer(pWal); - - wDebug("vgId:%d, wal ref version %" PRId64 " for first", pWal->cfg.vgId, ver); - pRef->refVer = ver; // bsearch in fileSet - SWalFileInfo tmpInfo; - tmpInfo.firstVer = ver; - SWalFileInfo *pRet = taosArraySearch(pWal->fileInfoSet, &tmpInfo, compareWalFileInfo, TD_LE); - ASSERT(pRet != NULL); - pRef->refFile = pRet->firstVer; + // SWalFileInfo tmpInfo; + // tmpInfo.firstVer = ver; + // SWalFileInfo *pRet = taosArraySearch(pWal->fileInfoSet, &tmpInfo, compareWalFileInfo, TD_LE); + // ASSERT(pRet != NULL); + // pRef->refFile = pRet->firstVer; taosThreadMutexUnlock(&pWal->mutex); + wDebug("vgId:%d, wal ref version %" PRId64 " for first", pWal->cfg.vgId, ver); + return pRef; } @@ -119,8 +117,8 @@ SWalRef *walRefCommittedVer(SWal *pWal) { SWalFileInfo tmpInfo; tmpInfo.firstVer = ver; SWalFileInfo *pRet = taosArraySearch(pWal->fileInfoSet, &tmpInfo, compareWalFileInfo, TD_LE); - /*A(pRet != NULL);*/ - pRef->refFile = pRet->firstVer; + ASSERT(pRet != NULL); + // pRef->refFile = pRet->firstVer; taosThreadMutexUnlock(&pWal->mutex); return pRef; diff --git a/source/libs/wal/src/walWrite.c b/source/libs/wal/src/walWrite.c index 958e7dc23d..a992c951fa 100644 --- a/source/libs/wal/src/walWrite.c +++ b/source/libs/wal/src/walWrite.c @@ -63,7 +63,7 @@ int32_t walRestoreFromSnapshot(SWal *pWal, int64_t ver) { wInfo("vgId:%d, restore from snapshot, remove file %s", pWal->cfg.vgId, fnameStr); } } - walRemoveMeta(pWal); + (void)walRemoveMeta(pWal); pWal->writeCur = -1; pWal->totSize = 0; @@ -247,21 +247,23 @@ static FORCE_INLINE int32_t walCheckAndRoll(SWal *pWal) { return 0; } -int32_t walBeginSnapshot(SWal *pWal, int64_t ver) { +int32_t walBeginSnapshot(SWal *pWal, int64_t ver, int64_t logRetention) { taosThreadMutexLock(&pWal->mutex); - + ASSERT(logRetention >= 0); pWal->vers.verInSnapshotting = ver; - wDebug("vgId:%d, wal begin snapshot for version %" PRId64 ", first ver %" PRId64 ", last ver %" PRId64, - pWal->cfg.vgId, ver, pWal->vers.firstVer, pWal->vers.lastVer); + pWal->vers.logRetention = logRetention; + + wDebug("vgId:%d, wal begin snapshot for version %" PRId64 ", log retention %" PRId64 " first ver %" PRId64 + ", last ver %" PRId64, + pWal->cfg.vgId, ver, pWal->vers.logRetention, pWal->vers.firstVer, pWal->vers.lastVer); // check file rolling - if (pWal->cfg.retentionPeriod == 0) { - if (walGetLastFileSize(pWal) != 0) { - if (walRollImpl(pWal) < 0) { - wError("vgId:%d, failed to roll wal files since %s", pWal->cfg.vgId, terrstr()); - goto _err; - } + if (walGetLastFileSize(pWal) != 0) { + if (walRollImpl(pWal) < 0) { + wError("vgId:%d, failed to roll wal files since %s", pWal->cfg.vgId, terrstr()); + goto _err; } } + taosThreadMutexUnlock(&pWal->mutex); return 0; @@ -275,8 +277,9 @@ int32_t walEndSnapshot(SWal *pWal) { taosThreadMutexLock(&pWal->mutex); int64_t ver = pWal->vers.verInSnapshotting; - wDebug("vgId:%d, wal end snapshot for version %" PRId64 ", first ver %" PRId64 ", last ver %" PRId64, pWal->cfg.vgId, - ver, pWal->vers.firstVer, pWal->vers.lastVer); + wDebug("vgId:%d, wal end snapshot for version %" PRId64 ", log retention %" PRId64 " first ver %" PRId64 + ", last ver %" PRId64, + pWal->cfg.vgId, ver, pWal->vers.logRetention, pWal->vers.firstVer, pWal->vers.lastVer); if (ver == -1) { code = -1; @@ -286,6 +289,7 @@ int32_t walEndSnapshot(SWal *pWal) { pWal->vers.snapshotVer = ver; int ts = taosGetTimestampSec(); + ver = TMAX(ver - pWal->vers.logRetention, pWal->vers.firstVer - 1); void *pIter = NULL; while (1) { pIter = taosHashIterate(pWal->pRefHash, pIter); diff --git a/source/libs/wal/test/walMetaTest.cpp b/source/libs/wal/test/walMetaTest.cpp index 891e7dcdae..0784db917a 100644 --- a/source/libs/wal/test/walMetaTest.cpp +++ b/source/libs/wal/test/walMetaTest.cpp @@ -264,7 +264,7 @@ TEST_F(WalCleanEnv, rollbackMultiFile) { ASSERT_EQ(code, 0); ASSERT_EQ(pWal->vers.lastVer, i); if (i == 5) { - walBeginSnapshot(pWal, i); + walBeginSnapshot(pWal, i, 0); walEndSnapshot(pWal); } } @@ -301,7 +301,7 @@ TEST_F(WalCleanDeleteEnv, roll) { ASSERT_EQ(pWal->vers.commitVer, i); } - walBeginSnapshot(pWal, i - 1); + walBeginSnapshot(pWal, i - 1, 0); ASSERT_EQ(pWal->vers.verInSnapshotting, i - 1); walEndSnapshot(pWal); ASSERT_EQ(pWal->vers.snapshotVer, i - 1); @@ -317,7 +317,7 @@ TEST_F(WalCleanDeleteEnv, roll) { ASSERT_EQ(pWal->vers.commitVer, i); } - code = walBeginSnapshot(pWal, i - 1); + code = walBeginSnapshot(pWal, i - 1, 0); ASSERT_EQ(code, 0); code = walEndSnapshot(pWal); ASSERT_EQ(code, 0); diff --git a/source/os/src/osDir.c b/source/os/src/osDir.c index 331d241745..3d63da7ba3 100644 --- a/source/os/src/osDir.c +++ b/source/os/src/osDir.c @@ -89,6 +89,8 @@ typedef struct dirent TdDirEntry; #endif +#define TDDIRMAXLEN 1024 + void taosRemoveDir(const char *dirname) { TdDirPtr pDir = taosOpenDir(dirname); if (pDir == NULL) return; @@ -133,8 +135,8 @@ int32_t taosMkDir(const char *dirname) { } int32_t taosMulMkDir(const char *dirname) { - if (dirname == NULL) return -1; - char temp[1024]; + if (dirname == NULL || strlen(dirname) >= TDDIRMAXLEN) return -1; + char temp[TDDIRMAXLEN]; char *pos = temp; int32_t code = 0; #ifdef WINDOWS @@ -192,8 +194,8 @@ int32_t taosMulMkDir(const char *dirname) { } int32_t taosMulModeMkDir(const char *dirname, int mode) { - if (dirname == NULL) return -1; - char temp[1024]; + if (dirname == NULL || strlen(dirname) >= TDDIRMAXLEN) return -1; + char temp[TDDIRMAXLEN]; char *pos = temp; int32_t code = 0; #ifdef WINDOWS @@ -204,8 +206,7 @@ int32_t taosMulModeMkDir(const char *dirname, int mode) { #endif if (taosDirExist(temp)) { - chmod(temp, mode); - return code; + return chmod(temp, mode); } if (strncmp(temp, TD_DIRSEP, 1) == 0) { @@ -247,12 +248,10 @@ int32_t taosMulModeMkDir(const char *dirname, int mode) { } if (code < 0 && errno == EEXIST) { - chmod(temp, mode); - return 0; + return chmod(temp, mode); } - chmod(temp, mode); - return code; + return chmod(temp, mode); } void taosRemoveOldFiles(const char *dirname, int32_t keepDays) { diff --git a/source/os/src/osFile.c b/source/os/src/osFile.c index 8cc9885adb..aab547223f 100644 --- a/source/os/src/osFile.c +++ b/source/os/src/osFile.c @@ -132,15 +132,20 @@ int64_t taosCopyFile(const char *from, const char *to) { if (bytes < sizeof(buffer)) break; } - taosFsyncFile(pFileTo); + int code = taosFsyncFile(pFileTo); taosCloseFile(&pFileFrom); taosCloseFile(&pFileTo); + + if (code != 0) { + return -1; + } return size; _err: if (pFileFrom != NULL) taosCloseFile(&pFileFrom); if (pFileTo != NULL) taosCloseFile(&pFileTo); + /* coverity[+retval] */ taosRemoveFile(to); return -1; #endif @@ -151,7 +156,7 @@ TdFilePtr taosCreateFile(const char *path, int32_t tdFileOptions) { if (!fp) { if (errno == ENOENT) { // Try to create directory recursively - char *s = strdup(path); + char *s = taosStrdup(path); if (taosMulMkDir(taosDirName(s)) != 0) { taosMemoryFree(s); return NULL; @@ -506,13 +511,13 @@ int64_t taosPWriteFile(TdFilePtr pFile, const void *buf, int64_t count, int64_t } int64_t taosLSeekFile(TdFilePtr pFile, int64_t offset, int32_t whence) { + if (pFile == NULL || pFile->fd < 0) { + return -1; + } #if FILE_WITH_LOCK taosThreadRwlockRdlock(&(pFile->rwlock)); #endif ASSERT(pFile->fd >= 0); // Please check if you have closed the file. - if (pFile->fd < 0) { - return -1; - } #ifdef WINDOWS int64_t ret = _lseeki64(pFile->fd, offset, whence); #else diff --git a/source/os/src/osLocale.c b/source/os/src/osLocale.c index b4a2845e96..7008c38576 100644 --- a/source/os/src/osLocale.c +++ b/source/os/src/osLocale.c @@ -59,11 +59,11 @@ char *taosCharsetReplace(char *charsetstr) { for (int32_t i = 0; i < tListLen(charsetRep); ++i) { if (strcasecmp(charsetRep[i].oldCharset, charsetstr) == 0) { - return strdup(charsetRep[i].newCharset); + return taosStrdup(charsetRep[i].newCharset); } } - return strdup(charsetstr); + return taosStrdup(charsetstr); } /** diff --git a/source/os/src/osMemory.c b/source/os/src/osMemory.c index c641d893a1..1ae4afe0e0 100644 --- a/source/os/src/osMemory.c +++ b/source/os/src/osMemory.c @@ -312,15 +312,15 @@ void *taosMemoryRealloc(void *ptr, int64_t size) { #endif } -void *taosMemoryStrDup(const char *ptr) { +char *taosStrdup(const char *ptr) { #ifdef USE_TD_MEMORY if (ptr == NULL) return NULL; TdMemoryInfoPtr pTdMemoryInfo = (TdMemoryInfoPtr)((char *)ptr - sizeof(TdMemoryInfo)); ASSERT(pTdMemoryInfo->symbol == TD_MEMORY_SYMBOL); if (pTdMemoryInfo->symbol != TD_MEMORY_SYMBOL) { -+ return NULL; -+ } + return NULL; + } void *tmp = tstrdup(pTdMemoryInfo); if (tmp == NULL) return NULL; diff --git a/source/os/src/osSemaphore.c b/source/os/src/osSemaphore.c index cc018bf842..c1ef57e9c5 100644 --- a/source/os/src/osSemaphore.c +++ b/source/os/src/osSemaphore.c @@ -132,7 +132,8 @@ int tsem_wait(tsem_t *psem) { int tsem_timewait(tsem_t *psem, int64_t milis) { if (psem == NULL || *psem == NULL) return -1; - dispatch_semaphore_wait(*psem, milis * 1000 * 1000); + dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(milis * USEC_PER_SEC)); + dispatch_semaphore_wait(*psem, time); return 0; } diff --git a/source/os/src/osSocket.c b/source/os/src/osSocket.c index fac547ca99..7d2c8aa4e5 100644 --- a/source/os/src/osSocket.c +++ b/source/os/src/osSocket.c @@ -745,8 +745,10 @@ bool taosValidIpAndPort(uint32_t ip, uint16_t port) { #endif serverAdd.sin_port = (uint16_t)htons(port); - if ((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) <= 2) { - // printf("failed to open TCP socket: %d (%s)", errno, strerror(errno)); + fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (fd < 0) { // exception + return false; + } else if (fd <= 2) { // in, out, err taosCloseSocketNoCheck1(fd); return false; } diff --git a/source/os/src/osSysinfo.c b/source/os/src/osSysinfo.c index 6471dad033..52309a7b35 100644 --- a/source/os/src/osSysinfo.c +++ b/source/os/src/osSysinfo.c @@ -439,11 +439,14 @@ int32_t taosGetCpuInfo(char *cpuModel, int32_t maxLen, float *numOfCores) { if (code != 0 && (done & 1) == 0) { TdFilePtr pFile1 = taosOpenFile("/proc/device-tree/model", TD_FILE_READ | TD_FILE_STREAM); - if (pFile1 == NULL) return code; - taosGetsFile(pFile1, maxLen, cpuModel); - taosCloseFile(&pFile1); - code = 0; - done |= 1; + if (pFile1 != NULL) { + ssize_t bytes = taosGetsFile(pFile1, maxLen, cpuModel); + taosCloseFile(&pFile); + if (bytes > 0) { + code = 0; + done |= 1; + } + } } if (code != 0 && (done & 1) == 0) { @@ -498,7 +501,7 @@ void taosGetCpuUsage(double *cpu_system, double *cpu_engine) { curSysTotal = curSysUsed + sysCpu.idle; curProcTotal = procCpu.utime + procCpu.stime + procCpu.cutime + procCpu.cstime; - if (curSysTotal > lastSysTotal && curSysUsed >= lastSysUsed && curProcTotal >= lastProcTotal) { + if (curSysTotal - lastSysTotal > 0 && curSysUsed >= lastSysUsed && curProcTotal >= lastProcTotal) { if (cpu_system != NULL) { *cpu_system = (curSysUsed - lastSysUsed) / (double)(curSysTotal - lastSysTotal) * 100; } @@ -610,12 +613,6 @@ int32_t taosGetProcMemory(int64_t *usedKB) { } } - if (strlen(line) < 0) { - // printf("read file:%s failed", tsProcMemFile); - taosCloseFile(&pFile); - return -1; - } - char tmp[10]; sscanf(line, "%s %" PRId64, tmp, usedKB); diff --git a/source/os/src/osTimezone.c b/source/os/src/osTimezone.c index ab5600744c..ad223bff27 100644 --- a/source/os/src/osTimezone.c +++ b/source/os/src/osTimezone.c @@ -909,7 +909,7 @@ void taosGetSystemTimezone(char *outTimezoneStr, enum TdTimezone *tsTimezone) { char buf[4096] = {0}; char *tz = NULL; { - int n = readlink("/etc/localtime", buf, sizeof(buf)); + int n = readlink("/etc/localtime", buf, sizeof(buf)-1); if (n < 0) { printf("read /etc/localtime error, reason:%s", strerror(errno)); diff --git a/source/util/src/tarray.c b/source/util/src/tarray.c index 0bae81f119..7467fa2948 100644 --- a/source/util/src/tarray.c +++ b/source/util/src/tarray.c @@ -48,7 +48,7 @@ SArray* taosArrayInit(size_t size, size_t elemSize) { return pArray; } -SArray* taosArrayInit_s(size_t size, size_t elemSize, size_t initialSize) { +SArray* taosArrayInit_s(size_t elemSize, size_t initialSize) { SArray* pArray = taosMemoryMalloc(sizeof(SArray)); if (pArray == NULL) { terrno = TSDB_CODE_OUT_OF_MEMORY; @@ -139,7 +139,8 @@ void taosArrayRemoveDuplicate(SArray* pArray, __compar_fn_t comparFn, void (*fp) } taosArraySet(pArray, pos + 1, p2); - pos += 1; + memset(TARRAY_GET_ELEM(pArray, i), 0, pArray->elemSize); + pos += 1; } else { pos += 1; } @@ -171,13 +172,14 @@ void taosArrayRemoveDuplicateP(SArray* pArray, __compar_fn_t comparFn, void (*fp // do nothing } else { if (pos + 1 != i) { - void* p = taosArrayGet(pArray, pos + 1); + void* p = taosArrayGetP(pArray, pos + 1); if (fp != NULL) { fp(p); } taosArraySet(pArray, pos + 1, p2); - pos += 1; + memset(TARRAY_GET_ELEM(pArray, i), 0, pArray->elemSize); + pos += 1; } else { pos += 1; } diff --git a/source/util/src/tcache.c b/source/util/src/tcache.c index 761da6986b..1d480e7beb 100644 --- a/source/util/src/tcache.c +++ b/source/util/src/tcache.c @@ -391,7 +391,7 @@ SCacheObj *taosCacheInit(int32_t keyType, int64_t refreshTimeInMs, bool extendLi return NULL; } - pCacheObj->name = strdup(cacheName); + pCacheObj->name = taosStrdup(cacheName); doRegisterCacheObj(pCacheObj); return pCacheObj; } diff --git a/source/util/src/tcompare.c b/source/util/src/tcompare.c index 75d6a43b24..f8f78ae6a5 100644 --- a/source/util/src/tcompare.c +++ b/source/util/src/tcompare.c @@ -1235,7 +1235,7 @@ int32_t taosArrayCompareString(const void *a, const void *b) { const char *x = *(const char **)a; const char *y = *(const char **)b; - return compareLenPrefixedStr(x, y); + return strcmp(x, y); } int32_t comparestrPatternMatch(const void *pLeft, const void *pRight) { diff --git a/source/util/src/tcompression.c b/source/util/src/tcompression.c index 695a83abb1..7631da1b56 100644 --- a/source/util/src/tcompression.c +++ b/source/util/src/tcompression.c @@ -327,23 +327,26 @@ int32_t tsDecompressINTImp(const char *const input, const int32_t nelements, cha // calculate the cumulative sum (prefix sum) for each number // decode[0] = prev_value + final[0] // decode[1] = decode[0] + final[1] -----> prev_value + final[0] + final[1] - // decode[2] = decode[1] + final[1] -----> prev_value + final[0] + final[1] + final[2] - // decode[3] = decode[2] + final[1] -----> prev_value + final[0] + final[1] + final[2] + final[3] + // decode[2] = decode[1] + final[2] -----> prev_value + final[0] + final[1] + final[2] + // decode[3] = decode[2] + final[3] -----> prev_value + final[0] + final[1] + final[2] + final[3] // 1, 2, 3, 4 - //+ 0, 1, 2, 3 - // 1, 3, 5, 7 + //+ 0, 1, 0, 3 + // 1, 3, 3, 7 // shift and add for the first round __m128i prev = _mm_set1_epi64x(prev_value); - delta = _mm256_add_epi64(delta, _mm256_slli_si256(delta, 8)); + __m256i x = _mm256_slli_si256(delta, 8); + + delta = _mm256_add_epi64(delta, x); _mm256_storeu_si256((__m256i *)&p[_pos], delta); - // 1, 3, 5, 7 - //+ 0, 0, 1, 3 + // 1, 3, 3, 7 + //+ 0, 0, 3, 3 // 1, 3, 6, 10 // shift and add operation for the second round __m128i firstPart = _mm_loadu_si128((__m128i *)&p[_pos]); - __m128i secPart = _mm_add_epi64(_mm_loadu_si128((__m128i *)&p[_pos + 2]), firstPart); + __m128i secondItem = _mm_set1_epi64x(p[_pos + 1]); + __m128i secPart = _mm_add_epi64(_mm_loadu_si128((__m128i *)&p[_pos + 2]), secondItem); firstPart = _mm_add_epi64(firstPart, prev); secPart = _mm_add_epi64(secPart, prev); @@ -353,15 +356,18 @@ int32_t tsDecompressINTImp(const char *const input, const int32_t nelements, cha shiftBits = _mm256_add_epi64(shiftBits, inc); prev_value = p[_pos + 3]; +// uDebug("_pos:%d %"PRId64", %"PRId64", %"PRId64", %"PRId64, _pos, p[_pos], p[_pos+1], p[_pos+2], p[_pos+3]); _pos += 4; } // handle the remain value for (int32_t i = 0; i < remain; i++) { - zigzag_value = ((w >> (v + (batch * bit))) & mask); + zigzag_value = ((w >> (v + (batch * bit * 4))) & mask); prev_value += ZIGZAG_DECODE(int64_t, zigzag_value); p[_pos++] = prev_value; +// uDebug("_pos:%d %"PRId64, _pos-1, p[_pos-1]); + v += bit; } } else { @@ -370,6 +376,8 @@ int32_t tsDecompressINTImp(const char *const input, const int32_t nelements, cha prev_value += ZIGZAG_DECODE(int64_t, zigzag_value); p[_pos++] = prev_value; +// uDebug("_pos:%d %"PRId64, _pos-1, p[_pos-1]); + v += bit; } } diff --git a/source/util/src/tconfig.c b/source/util/src/tconfig.c index 609a386367..c15bd96903 100644 --- a/source/util/src/tconfig.c +++ b/source/util/src/tconfig.c @@ -109,7 +109,7 @@ int32_t cfgGetSize(SConfig *pCfg) { return taosArrayGetSize(pCfg->array); } static int32_t cfgCheckAndSetTimezone(SConfigItem *pItem, const char *timezone) { cfgFreeItem(pItem); - pItem->str = strdup(timezone); + pItem->str = taosStrdup(timezone); if (pItem->str == NULL) { terrno = TSDB_CODE_OUT_OF_MEMORY; return -1; @@ -120,7 +120,7 @@ static int32_t cfgCheckAndSetTimezone(SConfigItem *pItem, const char *timezone) static int32_t cfgCheckAndSetCharset(SConfigItem *pItem, const char *charset) { cfgFreeItem(pItem); - pItem->str = strdup(charset); + pItem->str = taosStrdup(charset); if (pItem->str == NULL) { terrno = TSDB_CODE_OUT_OF_MEMORY; return -1; @@ -131,7 +131,7 @@ static int32_t cfgCheckAndSetCharset(SConfigItem *pItem, const char *charset) { static int32_t cfgCheckAndSetLocale(SConfigItem *pItem, const char *locale) { cfgFreeItem(pItem); - pItem->str = strdup(locale); + pItem->str = taosStrdup(locale); if (pItem->str == NULL) { terrno = TSDB_CODE_OUT_OF_MEMORY; return -1; @@ -149,7 +149,7 @@ static int32_t cfgCheckAndSetDir(SConfigItem *pItem, const char *inputDir) { } taosMemoryFreeClear(pItem->str); - pItem->str = strdup(fullDir); + pItem->str = taosStrdup(fullDir); if (pItem->str == NULL) { terrno = TSDB_CODE_OUT_OF_MEMORY; return -1; @@ -215,7 +215,7 @@ static int32_t cfgSetFloat(SConfigItem *pItem, const char *value, ECfgSrcType st } static int32_t cfgSetString(SConfigItem *pItem, const char *value, ECfgSrcType stype) { - char *tmp = strdup(value); + char *tmp = taosStrdup(value); if (tmp == NULL) { terrno = TSDB_CODE_OUT_OF_MEMORY; uError("cfg:%s, type:%s src:%s value:%s failed to dup since %s", pItem->name, cfgDtypeStr(pItem->dtype), @@ -358,7 +358,7 @@ SConfigItem *cfgGetItem(SConfig *pCfg, const char *name) { static int32_t cfgAddItem(SConfig *pCfg, SConfigItem *pItem, const char *name) { pItem->stype = CFG_STYPE_DEFAULT; - pItem->name = strdup(name); + pItem->name = taosStrdup(name); if (pItem->name == NULL) { terrno = TSDB_CODE_OUT_OF_MEMORY; return -1; @@ -417,7 +417,7 @@ int32_t cfgAddFloat(SConfig *pCfg, const char *name, float defaultVal, double mi int32_t cfgAddString(SConfig *pCfg, const char *name, const char *defaultVal, bool tsc) { SConfigItem item = {.dtype = CFG_DTYPE_STRING, .tsc = tsc}; - item.str = strdup(defaultVal); + item.str = taosStrdup(defaultVal); if (item.str == NULL) { terrno = TSDB_CODE_OUT_OF_MEMORY; return -1; diff --git a/source/util/src/terror.c b/source/util/src/terror.c index d03cfff022..4bb082800d 100644 --- a/source/util/src/terror.c +++ b/source/util/src/terror.c @@ -97,6 +97,7 @@ TAOS_DEFINE_ERROR(TSDB_CODE_TIMEOUT_ERROR, "Operation timeout") TAOS_DEFINE_ERROR(TSDB_CODE_APP_IS_STARTING, "Database is starting up") TAOS_DEFINE_ERROR(TSDB_CODE_APP_IS_STOPPING, "Database is closing down") +TAOS_DEFINE_ERROR(TSDB_CODE_IVLD_DATA_FMT, "Invalid data format") //client TAOS_DEFINE_ERROR(TSDB_CODE_TSC_INVALID_OPERATION, "Invalid operation") @@ -522,7 +523,7 @@ TAOS_DEFINE_ERROR(TSDB_CODE_PAR_INVALID_ROW_LENGTH, "Row length exceeds TAOS_DEFINE_ERROR(TSDB_CODE_PAR_INVALID_COLUMNS_NUM, "Illegal number of columns") TAOS_DEFINE_ERROR(TSDB_CODE_PAR_TOO_MANY_COLUMNS, "Too many columns") TAOS_DEFINE_ERROR(TSDB_CODE_PAR_INVALID_FIRST_COLUMN, "First column must be timestamp") -TAOS_DEFINE_ERROR(TSDB_CODE_PAR_INVALID_VAR_COLUMN_LEN, "Invalid binary/nchar column length") +TAOS_DEFINE_ERROR(TSDB_CODE_PAR_INVALID_VAR_COLUMN_LEN, "Invalid binary/nchar column/tag length") TAOS_DEFINE_ERROR(TSDB_CODE_PAR_INVALID_TAGS_NUM, "Invalid number of tag columns") TAOS_DEFINE_ERROR(TSDB_CODE_PAR_PERMISSION_DENIED, "Permission denied") TAOS_DEFINE_ERROR(TSDB_CODE_PAR_INVALID_STREAM_QUERY, "Invalid stream query") diff --git a/source/util/src/tjson.c b/source/util/src/tjson.c index 27d14d05b1..0b7ad330a7 100644 --- a/source/util/src/tjson.c +++ b/source/util/src/tjson.c @@ -192,7 +192,7 @@ int32_t tjsonDupStringValue(const SJson* pJson, const char* pName, char** pVal) if (NULL == p) { return TSDB_CODE_SUCCESS; } - *pVal = strdup(p); + *pVal = taosStrdup(p); return TSDB_CODE_SUCCESS; } @@ -325,7 +325,7 @@ int32_t tjsonToTArray(const SJson* pJson, const char* pName, FToObject func, SAr const cJSON* jArray = tjsonGetObjectItem(pJson, pName); int32_t size = tjsonGetArraySize(jArray); if (size > 0) { - *pArray = taosArrayInit_s(size, itemSize, size); + *pArray = taosArrayInit_s(itemSize, size); if (NULL == *pArray) { return TSDB_CODE_OUT_OF_MEMORY; } diff --git a/source/util/src/tpagedbuf.c b/source/util/src/tpagedbuf.c index 6bcf4ad39b..fa8b5d33b7 100644 --- a/source/util/src/tpagedbuf.c +++ b/source/util/src/tpagedbuf.c @@ -55,7 +55,7 @@ static int32_t createDiskFile(SDiskbasedBuf* pBuf) { if (pBuf->path == NULL) { // prepare the file name when needed it char path[PATH_MAX] = {0}; taosGetTmpfilePath(pBuf->prefix, "paged-buf", path); - pBuf->path = taosMemoryStrDup(path); + pBuf->path = taosStrdup(path); if (pBuf->path == NULL) { return TSDB_CODE_OUT_OF_MEMORY; } @@ -351,7 +351,7 @@ int32_t createDiskbasedBuf(SDiskbasedBuf** pBuf, int32_t pagesize, int32_t inMem pPBuf->totalBufSize = 0; pPBuf->allocateId = -1; pPBuf->pFile = NULL; - pPBuf->id = strdup(id); + pPBuf->id = taosStrdup(id); pPBuf->fileSize = 0; pPBuf->pFree = taosArrayInit(4, sizeof(SFreeListItem)); pPBuf->freePgList = tdListNew(POINTER_BYTES); @@ -391,7 +391,7 @@ _error: return TSDB_CODE_OUT_OF_MEMORY; } -static char* doExtractPage(SDiskbasedBuf* pBuf) { +static char* doExtractPage(SDiskbasedBuf* pBuf, bool* newPage) { char* availablePage = NULL; if (NO_IN_MEM_AVAILABLE_PAGES(pBuf)) { availablePage = evictBufPage(pBuf); @@ -405,6 +405,7 @@ static char* doExtractPage(SDiskbasedBuf* pBuf) { if (availablePage == NULL) { terrno = TSDB_CODE_OUT_OF_MEMORY; } + *newPage = true; } return availablePage; @@ -413,7 +414,8 @@ static char* doExtractPage(SDiskbasedBuf* pBuf) { void* getNewBufPage(SDiskbasedBuf* pBuf, int32_t* pageId) { pBuf->statis.getPages += 1; - char* availablePage = doExtractPage(pBuf); + bool newPage = false; + char* availablePage = doExtractPage(pBuf, &newPage); if (availablePage == NULL) { return NULL; } @@ -432,6 +434,9 @@ void* getNewBufPage(SDiskbasedBuf* pBuf, int32_t* pageId) { // register page id info pi = registerNewPageInfo(pBuf, *pageId); if (pi == NULL) { + if (newPage) { + taosMemoryFree(availablePage); + } return NULL; } @@ -492,7 +497,8 @@ void* getBufPage(SDiskbasedBuf* pBuf, int32_t id) { ASSERT((!BUF_PAGE_IN_MEM(*pi)) && (*pi)->pn == NULL && (((*pi)->length >= 0 && (*pi)->offset >= 0) || ((*pi)->length == -1 && (*pi)->offset == -1))); - (*pi)->pData = doExtractPage(pBuf); + bool newPage = false; + (*pi)->pData = doExtractPage(pBuf, &newPage); // failed to evict buffer page, return with error code. if ((*pi)->pData == NULL) { @@ -509,6 +515,10 @@ void* getBufPage(SDiskbasedBuf* pBuf, int32_t id) { if (HAS_DATA_IN_DISK(*pi)) { int32_t code = loadPageFromDisk(pBuf, *pi); if (code != 0) { + if (newPage) { + taosMemoryFree((*pi)->pData); + } + terrno = code; return NULL; } diff --git a/source/util/src/tutil.c b/source/util/src/tutil.c index 55d7d4f6e7..1f9ca7407e 100644 --- a/source/util/src/tutil.c +++ b/source/util/src/tutil.c @@ -118,7 +118,7 @@ char **strsplit(char *z, const char *delim, int32_t *num) { if ((*num) >= size) { size = (size << 1); split = taosMemoryRealloc(split, POINTER_BYTES * size); - ASSERTS(NULL != split, "realloc memory failed. size=%d", POINTER_BYTES * size); + ASSERTS(NULL != split, "realloc memory failed. size=%d", (int32_t) POINTER_BYTES * size); } } diff --git a/source/util/src/tworker.c b/source/util/src/tworker.c index 5581931178..631bcb443e 100644 --- a/source/util/src/tworker.c +++ b/source/util/src/tworker.c @@ -22,7 +22,7 @@ typedef void *(*ThreadFp)(void *param); int32_t tQWorkerInit(SQWorkerPool *pool) { pool->qset = taosOpenQset(); - pool->workers = taosMemoryCalloc(pool->max, sizeof(SQWorker)); + pool->workers = taosMemoryCalloc(pool->max, sizeof(SQueueWorker)); if (pool->workers == NULL) { terrno = TSDB_CODE_OUT_OF_MEMORY; return -1; @@ -31,7 +31,7 @@ int32_t tQWorkerInit(SQWorkerPool *pool) { (void)taosThreadMutexInit(&pool->mutex, NULL); for (int32_t i = 0; i < pool->max; ++i) { - SQWorker *worker = pool->workers + i; + SQueueWorker *worker = pool->workers + i; worker->id = i; worker->pool = pool; } @@ -42,14 +42,14 @@ int32_t tQWorkerInit(SQWorkerPool *pool) { void tQWorkerCleanup(SQWorkerPool *pool) { for (int32_t i = 0; i < pool->max; ++i) { - SQWorker *worker = pool->workers + i; + SQueueWorker *worker = pool->workers + i; if (taosCheckPthreadValid(worker->thread)) { taosQsetThreadResume(pool->qset); } } for (int32_t i = 0; i < pool->max; ++i) { - SQWorker *worker = pool->workers + i; + SQueueWorker *worker = pool->workers + i; if (taosCheckPthreadValid(worker->thread)) { uInfo("worker:%s:%d is stopping", pool->name, worker->id); taosThreadJoin(worker->thread, NULL); @@ -65,7 +65,7 @@ void tQWorkerCleanup(SQWorkerPool *pool) { uInfo("worker:%s is closed", pool->name); } -static void *tQWorkerThreadFp(SQWorker *worker) { +static void *tQWorkerThreadFp(SQueueWorker *worker) { SQWorkerPool *pool = worker->pool; SQueueInfo qinfo = {0}; void *msg = NULL; @@ -106,7 +106,7 @@ STaosQueue *tQWorkerAllocQueue(SQWorkerPool *pool, void *ahandle, FItem fp) { // spawn a thread to process queue if (pool->num < pool->max) { do { - SQWorker *worker = pool->workers + pool->num; + SQueueWorker *worker = pool->workers + pool->num; TdThreadAttr thAttr; taosThreadAttrInit(&thAttr); @@ -138,7 +138,7 @@ void tQWorkerFreeQueue(SQWorkerPool *pool, STaosQueue *queue) { int32_t tAutoQWorkerInit(SAutoQWorkerPool *pool) { pool->qset = taosOpenQset(); - pool->workers = taosArrayInit(2, sizeof(SQWorker *)); + pool->workers = taosArrayInit(2, sizeof(SQueueWorker *)); if (pool->workers == NULL) { terrno = TSDB_CODE_OUT_OF_MEMORY; return -1; @@ -153,14 +153,14 @@ int32_t tAutoQWorkerInit(SAutoQWorkerPool *pool) { void tAutoQWorkerCleanup(SAutoQWorkerPool *pool) { int32_t size = taosArrayGetSize(pool->workers); for (int32_t i = 0; i < size; ++i) { - SQWorker *worker = taosArrayGetP(pool->workers, i); + SQueueWorker *worker = taosArrayGetP(pool->workers, i); if (taosCheckPthreadValid(worker->thread)) { taosQsetThreadResume(pool->qset); } } for (int32_t i = 0; i < size; ++i) { - SQWorker *worker = taosArrayGetP(pool->workers, i); + SQueueWorker *worker = taosArrayGetP(pool->workers, i); if (taosCheckPthreadValid(worker->thread)) { uInfo("worker:%s:%d is stopping", pool->name, worker->id); taosThreadJoin(worker->thread, NULL); @@ -177,7 +177,7 @@ void tAutoQWorkerCleanup(SAutoQWorkerPool *pool) { uInfo("worker:%s is closed", pool->name); } -static void *tAutoQWorkerThreadFp(SQWorker *worker) { +static void *tAutoQWorkerThreadFp(SQueueWorker *worker) { SAutoQWorkerPool *pool = worker->pool; SQueueInfo qinfo = {0}; void *msg = NULL; @@ -222,7 +222,7 @@ STaosQueue *tAutoQWorkerAllocQueue(SAutoQWorkerPool *pool, void *ahandle, FItem // spawn a thread to process queue while (curWorkerNum < dstWorkerNum) { - SQWorker *worker = taosMemoryCalloc(1, sizeof(SQWorker)); + SQueueWorker *worker = taosMemoryCalloc(1, sizeof(SQueueWorker)); if (worker == NULL || taosArrayPush(pool->workers, &worker) == NULL) { uError("worker:%s:%d failed to create", pool->name, curWorkerNum); taosMemoryFree(worker); diff --git a/source/util/src/xxhash.c b/source/util/src/xxhash.c deleted file mode 100644 index ff28749e31..0000000000 --- a/source/util/src/xxhash.c +++ /dev/null @@ -1,1030 +0,0 @@ -/* -* xxHash - Fast Hash algorithm -* Copyright (C) 2012-2016, Yann Collet -* -* BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are -* met: -* -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above -* copyright notice, this list of conditions and the following disclaimer -* in the documentation and/or other materials provided with the -* distribution. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -* You can contact the author at : -* - xxHash homepage: http://www.xxhash.com -* - xxHash source repository : https://github.com/Cyan4973/xxHash -*/ - - -/* ************************************* -* Tuning parameters -***************************************/ -/*!XXH_FORCE_MEMORY_ACCESS : - * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable. - * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal. - * The below switch allow to select different access method for improved performance. - * Method 0 (default) : use `memcpy()`. Safe and portable. - * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable). - * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`. - * Method 2 : direct access. This method doesn't depend on compiler but violate C standard. - * It can generate buggy code on targets which do not support unaligned memory accesses. - * But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6) - * See http://stackoverflow.com/a/32095106/646947 for details. - * Prefer these methods in priority order (0 > 1 > 2) - */ -#ifndef XXH_FORCE_MEMORY_ACCESS /* can be defined externally, on command line for example */ -# if defined(__GNUC__) && ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) \ - || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) \ - || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) ) -# define XXH_FORCE_MEMORY_ACCESS 2 -# elif (defined(__INTEL_COMPILER) && !defined(_WIN32)) || \ - (defined(__GNUC__) && ( defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) \ - || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) \ - || defined(__ARM_ARCH_7S__) )) -# define XXH_FORCE_MEMORY_ACCESS 1 -# endif -#endif - -/*!XXH_ACCEPT_NULL_INPUT_POINTER : - * If input pointer is NULL, xxHash default behavior is to dereference it, triggering a segfault. - * When this macro is enabled, xxHash actively checks input for null pointer. - * It it is, result for null input pointers is the same as a null-length input. - */ -#ifndef XXH_ACCEPT_NULL_INPUT_POINTER /* can be defined externally */ -# define XXH_ACCEPT_NULL_INPUT_POINTER 0 -#endif - -/*!XXH_FORCE_NATIVE_FORMAT : - * By default, xxHash library provides endian-independent Hash values, based on little-endian convention. - * Results are therefore identical for little-endian and big-endian CPU. - * This comes at a performance cost for big-endian CPU, since some swapping is required to emulate little-endian format. - * Should endian-independence be of no importance for your application, you may set the #define below to 1, - * to improve speed for Big-endian CPU. - * This option has no impact on Little_Endian CPU. - */ -#ifndef XXH_FORCE_NATIVE_FORMAT /* can be defined externally */ -# define XXH_FORCE_NATIVE_FORMAT 0 -#endif - -/*!XXH_FORCE_ALIGN_CHECK : - * This is a minor performance trick, only useful with lots of very small keys. - * It means : check for aligned/unaligned input. - * The check costs one initial branch per hash; - * set it to 0 when the input is guaranteed to be aligned, - * or when alignment doesn't matter for performance. - */ -#ifndef XXH_FORCE_ALIGN_CHECK /* can be defined externally */ -# if defined(__i386) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64) -# define XXH_FORCE_ALIGN_CHECK 0 -# else -# define XXH_FORCE_ALIGN_CHECK 1 -# endif -#endif - - -/* ************************************* -* Includes & Memory related functions -***************************************/ -/*! Modify the local functions below should you wish to use some other memory routines -* for malloc(), free() */ -#include -static void* XXH_malloc(size_t s) { return malloc(s); } -static void XXH_free (void* p) { free(p); } -/*! and for memcpy() */ -#include -static void* XXH_memcpy(void* dest, const void* src, size_t size) { return memcpy(dest,src,size); } - -#include /* assert */ - -#define XXH_STATIC_LINKING_ONLY -#include "xxhash.h" - - -/* ************************************* -* Compiler Specific Options -***************************************/ -#ifdef _MSC_VER /* Visual Studio */ -# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ -# define FORCE_INLINE static __forceinline -#else -# if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */ -# ifdef __GNUC__ -# define FORCE_INLINE static inline __attribute__((always_inline)) -# else -# define FORCE_INLINE static inline -# endif -# else -# define FORCE_INLINE static -# endif /* __STDC_VERSION__ */ -#endif - - -/* ************************************* -* Basic Types -***************************************/ -#ifndef MEM_MODULE -# if !defined (__VMS) \ - && (defined (__cplusplus) \ - || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) -# include - typedef uint8_t BYTE; - typedef uint16_t U16; - typedef uint32_t U32; -# else - typedef unsigned char BYTE; - typedef unsigned short U16; - typedef unsigned int U32; -# endif -#endif - -#if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==2)) - -/* Force direct memory access. Only works on CPU which support unaligned memory access in hardware */ -static U32 XXH_read32(const void* memPtr) { return *(const U32*) memPtr; } - -#elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==1)) - -/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */ -/* currently only defined for gcc and icc */ -typedef union { U32 u32; } __attribute__((packed)) unalign; -static U32 XXH_read32(const void* ptr) { return ((const unalign*)ptr)->u32; } - -#else - -/* portable and safe solution. Generally efficient. - * see : http://stackoverflow.com/a/32095106/646947 - */ -static U32 XXH_read32(const void* memPtr) -{ - U32 val; - memcpy(&val, memPtr, sizeof(val)); - return val; -} - -#endif /* XXH_FORCE_DIRECT_MEMORY_ACCESS */ - - -/* **************************************** -* Compiler-specific Functions and Macros -******************************************/ -#define XXH_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) - -/* Note : although _rotl exists for minGW (GCC under windows), performance seems poor */ -#if defined(_MSC_VER) -# define XXH_rotl32(x,r) _rotl(x,r) -# define XXH_rotl64(x,r) _rotl64(x,r) -#else -# define XXH_rotl32(x,r) ((x << r) | (x >> (32 - r))) -# define XXH_rotl64(x,r) ((x << r) | (x >> (64 - r))) -#endif - -#if defined(_MSC_VER) /* Visual Studio */ -# define XXH_swap32 _byteswap_ulong -#elif XXH_GCC_VERSION >= 403 -# define XXH_swap32 __builtin_bswap32 -#else -static U32 XXH_swap32 (U32 x) -{ - return ((x << 24) & 0xff000000 ) | - ((x << 8) & 0x00ff0000 ) | - ((x >> 8) & 0x0000ff00 ) | - ((x >> 24) & 0x000000ff ); -} -#endif - - -/* ************************************* -* Architecture Macros -***************************************/ -typedef enum { XXH_bigEndian=0, XXH_littleEndian=1 } XXH_endianess; - -/* XXH_CPU_LITTLE_ENDIAN can be defined externally, for example on the compiler command line */ -#ifndef XXH_CPU_LITTLE_ENDIAN -static int XXH_isLittleEndian(void) -{ - const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */ - return one.c[0]; -} -# define XXH_CPU_LITTLE_ENDIAN XXH_isLittleEndian() -#endif - - -/* *************************** -* Memory reads -*****************************/ -typedef enum { XXH_aligned, XXH_unaligned } XXH_alignment; - -FORCE_INLINE U32 XXH_readLE32_align(const void* ptr, XXH_endianess endian, XXH_alignment align) -{ - if (align==XXH_unaligned) - return endian==XXH_littleEndian ? XXH_read32(ptr) : XXH_swap32(XXH_read32(ptr)); - else - return endian==XXH_littleEndian ? *(const U32*)ptr : XXH_swap32(*(const U32*)ptr); -} - -FORCE_INLINE U32 XXH_readLE32(const void* ptr, XXH_endianess endian) -{ - return XXH_readLE32_align(ptr, endian, XXH_unaligned); -} - -static U32 XXH_readBE32(const void* ptr) -{ - return XXH_CPU_LITTLE_ENDIAN ? XXH_swap32(XXH_read32(ptr)) : XXH_read32(ptr); -} - - -/* ************************************* -* Macros -***************************************/ -#define XXH_STATIC_ASSERT(c) { enum { XXH_sa = 1/(int)(!!(c)) }; } /* use after variable declarations */ -XXH_PUBLIC_API unsigned XXH_versionNumber (void) { return XXH_VERSION_NUMBER; } - - -/* ******************************************************************* -* 32-bit hash functions -*********************************************************************/ -static const U32 PRIME32_1 = 2654435761U; -static const U32 PRIME32_2 = 2246822519U; -static const U32 PRIME32_3 = 3266489917U; -static const U32 PRIME32_4 = 668265263U; -static const U32 PRIME32_5 = 374761393U; - -static U32 XXH32_round(U32 seed, U32 input) -{ - seed += input * PRIME32_2; - seed = XXH_rotl32(seed, 13); - seed *= PRIME32_1; - return seed; -} - -/* mix all bits */ -static U32 XXH32_avalanche(U32 h32) -{ - h32 ^= h32 >> 15; - h32 *= PRIME32_2; - h32 ^= h32 >> 13; - h32 *= PRIME32_3; - h32 ^= h32 >> 16; - return(h32); -} - -#define XXH_get32bits(p) XXH_readLE32_align(p, endian, align) - -static U32 -XXH32_finalize(U32 h32, const void* ptr, size_t len, - XXH_endianess endian, XXH_alignment align) - -{ - const BYTE* p = (const BYTE*)ptr; - -#define PROCESS1 \ - h32 += (*p++) * PRIME32_5; \ - h32 = XXH_rotl32(h32, 11) * PRIME32_1 ; - -#define PROCESS4 \ - h32 += XXH_get32bits(p) * PRIME32_3; \ - p+=4; \ - h32 = XXH_rotl32(h32, 17) * PRIME32_4 ; - - switch(len&15) /* or switch(bEnd - p) */ - { - case 12: PROCESS4; - /* fallthrough */ - case 8: PROCESS4; - /* fallthrough */ - case 4: PROCESS4; - return XXH32_avalanche(h32); - - case 13: PROCESS4; - /* fallthrough */ - case 9: PROCESS4; - /* fallthrough */ - case 5: PROCESS4; - PROCESS1; - return XXH32_avalanche(h32); - - case 14: PROCESS4; - /* fallthrough */ - case 10: PROCESS4; - /* fallthrough */ - case 6: PROCESS4; - PROCESS1; - PROCESS1; - return XXH32_avalanche(h32); - - case 15: PROCESS4; - /* fallthrough */ - case 11: PROCESS4; - /* fallthrough */ - case 7: PROCESS4; - /* fallthrough */ - case 3: PROCESS1; - /* fallthrough */ - case 2: PROCESS1; - /* fallthrough */ - case 1: PROCESS1; - /* fallthrough */ - case 0: return XXH32_avalanche(h32); - } - assert(0); - return h32; /* reaching this point is deemed impossible */ -} - - -FORCE_INLINE U32 -XXH32_endian_align(const void* input, size_t len, U32 seed, - XXH_endianess endian, XXH_alignment align) -{ - const BYTE* p = (const BYTE*)input; - const BYTE* bEnd = p + len; - U32 h32; - -#if defined(XXH_ACCEPT_NULL_INPUT_POINTER) && (XXH_ACCEPT_NULL_INPUT_POINTER>=1) - if (p==NULL) { - len=0; - bEnd=p=(const BYTE*)(size_t)16; - } -#endif - - if (len>=16) { - const BYTE* const limit = bEnd - 15; - U32 v1 = seed + PRIME32_1 + PRIME32_2; - U32 v2 = seed + PRIME32_2; - U32 v3 = seed + 0; - U32 v4 = seed - PRIME32_1; - - do { - v1 = XXH32_round(v1, XXH_get32bits(p)); p+=4; - v2 = XXH32_round(v2, XXH_get32bits(p)); p+=4; - v3 = XXH32_round(v3, XXH_get32bits(p)); p+=4; - v4 = XXH32_round(v4, XXH_get32bits(p)); p+=4; - } while (p < limit); - - h32 = XXH_rotl32(v1, 1) + XXH_rotl32(v2, 7) - + XXH_rotl32(v3, 12) + XXH_rotl32(v4, 18); - } else { - h32 = seed + PRIME32_5; - } - - h32 += (U32)len; - - return XXH32_finalize(h32, p, len&15, endian, align); -} - - -XXH_PUBLIC_API unsigned int XXH32 (const void* input, size_t len, unsigned int seed) -{ -#if 0 - /* Simple version, good for code maintenance, but unfortunately slow for small inputs */ - XXH32_state_t state; - XXH32_reset(&state, seed); - XXH32_update(&state, input, len); - return XXH32_digest(&state); -#else - XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; - - if (XXH_FORCE_ALIGN_CHECK) { - if ((((size_t)input) & 3) == 0) { /* Input is 4-bytes aligned, leverage the speed benefit */ - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned); - else - return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned); - } } - - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned); - else - return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned); -#endif -} - - - -/*====== Hash streaming ======*/ - -XXH_PUBLIC_API XXH32_state_t* XXH32_createState(void) -{ - return (XXH32_state_t*)XXH_malloc(sizeof(XXH32_state_t)); -} -XXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr) -{ - XXH_free(statePtr); - return XXH_OK; -} - -XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* dstState, const XXH32_state_t* srcState) -{ - memcpy(dstState, srcState, sizeof(*dstState)); -} - -XXH_PUBLIC_API XXH_errorcode XXH32_reset(XXH32_state_t* statePtr, unsigned int seed) -{ - XXH32_state_t state; /* using a local state to memcpy() in order to avoid strict-aliasing warnings */ - memset(&state, 0, sizeof(state)); - state.v1 = seed + PRIME32_1 + PRIME32_2; - state.v2 = seed + PRIME32_2; - state.v3 = seed + 0; - state.v4 = seed - PRIME32_1; - /* do not write into reserved, planned to be removed in a future version */ - memcpy(statePtr, &state, sizeof(state) - sizeof(state.reserved)); - return XXH_OK; -} - - -FORCE_INLINE XXH_errorcode -XXH32_update_endian(XXH32_state_t* state, const void* input, size_t len, XXH_endianess endian) -{ - if (input==NULL) -#if defined(XXH_ACCEPT_NULL_INPUT_POINTER) && (XXH_ACCEPT_NULL_INPUT_POINTER>=1) - return XXH_OK; -#else - return XXH_ERROR; -#endif - - { const BYTE* p = (const BYTE*)input; - const BYTE* const bEnd = p + len; - - state->total_len_32 += (unsigned)len; - state->large_len |= (len>=16) | (state->total_len_32>=16); - - if (state->memsize + len < 16) { /* fill in tmp buffer */ - XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, len); - state->memsize += (unsigned)len; - return XXH_OK; - } - - if (state->memsize) { /* some data left from previous update */ - XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, 16-state->memsize); - { const U32* p32 = state->mem32; - state->v1 = XXH32_round(state->v1, XXH_readLE32(p32, endian)); p32++; - state->v2 = XXH32_round(state->v2, XXH_readLE32(p32, endian)); p32++; - state->v3 = XXH32_round(state->v3, XXH_readLE32(p32, endian)); p32++; - state->v4 = XXH32_round(state->v4, XXH_readLE32(p32, endian)); - } - p += 16-state->memsize; - state->memsize = 0; - } - - if (p <= bEnd-16) { - const BYTE* const limit = bEnd - 16; - U32 v1 = state->v1; - U32 v2 = state->v2; - U32 v3 = state->v3; - U32 v4 = state->v4; - - do { - v1 = XXH32_round(v1, XXH_readLE32(p, endian)); p+=4; - v2 = XXH32_round(v2, XXH_readLE32(p, endian)); p+=4; - v3 = XXH32_round(v3, XXH_readLE32(p, endian)); p+=4; - v4 = XXH32_round(v4, XXH_readLE32(p, endian)); p+=4; - } while (p<=limit); - - state->v1 = v1; - state->v2 = v2; - state->v3 = v3; - state->v4 = v4; - } - - if (p < bEnd) { - XXH_memcpy(state->mem32, p, (size_t)(bEnd-p)); - state->memsize = (unsigned)(bEnd-p); - } - } - - return XXH_OK; -} - - -XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* state_in, const void* input, size_t len) -{ - XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; - - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH32_update_endian(state_in, input, len, XXH_littleEndian); - else - return XXH32_update_endian(state_in, input, len, XXH_bigEndian); -} - - -FORCE_INLINE U32 -XXH32_digest_endian (const XXH32_state_t* state, XXH_endianess endian) -{ - U32 h32; - - if (state->large_len) { - h32 = XXH_rotl32(state->v1, 1) - + XXH_rotl32(state->v2, 7) - + XXH_rotl32(state->v3, 12) - + XXH_rotl32(state->v4, 18); - } else { - h32 = state->v3 /* == seed */ + PRIME32_5; - } - - h32 += state->total_len_32; - - return XXH32_finalize(h32, state->mem32, state->memsize, endian, XXH_aligned); -} - - -XXH_PUBLIC_API unsigned int XXH32_digest (const XXH32_state_t* state_in) -{ - XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; - - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH32_digest_endian(state_in, XXH_littleEndian); - else - return XXH32_digest_endian(state_in, XXH_bigEndian); -} - - -/*====== Canonical representation ======*/ - -/*! Default XXH result types are basic unsigned 32 and 64 bits. -* The canonical representation follows human-readable write convention, aka big-endian (large digits first). -* These functions allow transformation of hash result into and from its canonical format. -* This way, hash values can be written into a file or buffer, remaining comparable across different systems. -*/ - -XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash) -{ - XXH_STATIC_ASSERT(sizeof(XXH32_canonical_t) == sizeof(XXH32_hash_t)); - if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap32(hash); - memcpy(dst, &hash, sizeof(*dst)); -} - -XXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src) -{ - return XXH_readBE32(src); -} - - -#ifndef XXH_NO_LONG_LONG - -/* ******************************************************************* -* 64-bit hash functions -*********************************************************************/ - -/*====== Memory access ======*/ - -#ifndef MEM_MODULE -# define MEM_MODULE -# if !defined (__VMS) \ - && (defined (__cplusplus) \ - || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) -# include - typedef uint64_t U64; -# else - /* if compiler doesn't support unsigned long long, replace by another 64-bit type */ - typedef unsigned long long U64; -# endif -#endif - - -#if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==2)) - -/* Force direct memory access. Only works on CPU which support unaligned memory access in hardware */ -static U64 XXH_read64(const void* memPtr) { return *(const U64*) memPtr; } - -#elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==1)) - -/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */ -/* currently only defined for gcc and icc */ -typedef union { U32 u32; U64 u64; } __attribute__((packed)) unalign64; -static U64 XXH_read64(const void* ptr) { return ((const unalign64*)ptr)->u64; } - -#else - -/* portable and safe solution. Generally efficient. - * see : http://stackoverflow.com/a/32095106/646947 - */ - -static U64 XXH_read64(const void* memPtr) -{ - U64 val; - memcpy(&val, memPtr, sizeof(val)); - return val; -} - -#endif /* XXH_FORCE_DIRECT_MEMORY_ACCESS */ - -#if defined(_MSC_VER) /* Visual Studio */ -# define XXH_swap64 _byteswap_uint64 -#elif XXH_GCC_VERSION >= 403 -# define XXH_swap64 __builtin_bswap64 -#else -static U64 XXH_swap64 (U64 x) -{ - return ((x << 56) & 0xff00000000000000ULL) | - ((x << 40) & 0x00ff000000000000ULL) | - ((x << 24) & 0x0000ff0000000000ULL) | - ((x << 8) & 0x000000ff00000000ULL) | - ((x >> 8) & 0x00000000ff000000ULL) | - ((x >> 24) & 0x0000000000ff0000ULL) | - ((x >> 40) & 0x000000000000ff00ULL) | - ((x >> 56) & 0x00000000000000ffULL); -} -#endif - -FORCE_INLINE U64 XXH_readLE64_align(const void* ptr, XXH_endianess endian, XXH_alignment align) -{ - if (align==XXH_unaligned) - return endian==XXH_littleEndian ? XXH_read64(ptr) : XXH_swap64(XXH_read64(ptr)); - else - return endian==XXH_littleEndian ? *(const U64*)ptr : XXH_swap64(*(const U64*)ptr); -} - -FORCE_INLINE U64 XXH_readLE64(const void* ptr, XXH_endianess endian) -{ - return XXH_readLE64_align(ptr, endian, XXH_unaligned); -} - -static U64 XXH_readBE64(const void* ptr) -{ - return XXH_CPU_LITTLE_ENDIAN ? XXH_swap64(XXH_read64(ptr)) : XXH_read64(ptr); -} - - -/*====== xxh64 ======*/ - -static const U64 PRIME64_1 = 11400714785074694791ULL; -static const U64 PRIME64_2 = 14029467366897019727ULL; -static const U64 PRIME64_3 = 1609587929392839161ULL; -static const U64 PRIME64_4 = 9650029242287828579ULL; -static const U64 PRIME64_5 = 2870177450012600261ULL; - -static U64 XXH64_round(U64 acc, U64 input) -{ - acc += input * PRIME64_2; - acc = XXH_rotl64(acc, 31); - acc *= PRIME64_1; - return acc; -} - -static U64 XXH64_mergeRound(U64 acc, U64 val) -{ - val = XXH64_round(0, val); - acc ^= val; - acc = acc * PRIME64_1 + PRIME64_4; - return acc; -} - -static U64 XXH64_avalanche(U64 h64) -{ - h64 ^= h64 >> 33; - h64 *= PRIME64_2; - h64 ^= h64 >> 29; - h64 *= PRIME64_3; - h64 ^= h64 >> 32; - return h64; -} - - -#define XXH_get64bits(p) XXH_readLE64_align(p, endian, align) - -static U64 -XXH64_finalize(U64 h64, const void* ptr, size_t len, - XXH_endianess endian, XXH_alignment align) -{ - const BYTE* p = (const BYTE*)ptr; - -#define PROCESS1_64 \ - h64 ^= (*p++) * PRIME64_5; \ - h64 = XXH_rotl64(h64, 11) * PRIME64_1; - -#define PROCESS4_64 \ - h64 ^= (U64)(XXH_get32bits(p)) * PRIME64_1; \ - p+=4; \ - h64 = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3; - -#define PROCESS8_64 { \ - U64 const k1 = XXH64_round(0, XXH_get64bits(p)); \ - p+=8; \ - h64 ^= k1; \ - h64 = XXH_rotl64(h64,27) * PRIME64_1 + PRIME64_4; \ -} - - switch(len&31) { - case 24: PROCESS8_64; - /* fallthrough */ - case 16: PROCESS8_64; - /* fallthrough */ - case 8: PROCESS8_64; - return XXH64_avalanche(h64); - - case 28: PROCESS8_64; - /* fallthrough */ - case 20: PROCESS8_64; - /* fallthrough */ - case 12: PROCESS8_64; - /* fallthrough */ - case 4: PROCESS4_64; - return XXH64_avalanche(h64); - - case 25: PROCESS8_64; - /* fallthrough */ - case 17: PROCESS8_64; - /* fallthrough */ - case 9: PROCESS8_64; - PROCESS1_64; - return XXH64_avalanche(h64); - - case 29: PROCESS8_64; - /* fallthrough */ - case 21: PROCESS8_64; - /* fallthrough */ - case 13: PROCESS8_64; - /* fallthrough */ - case 5: PROCESS4_64; - PROCESS1_64; - return XXH64_avalanche(h64); - - case 26: PROCESS8_64; - /* fallthrough */ - case 18: PROCESS8_64; - /* fallthrough */ - case 10: PROCESS8_64; - PROCESS1_64; - PROCESS1_64; - return XXH64_avalanche(h64); - - case 30: PROCESS8_64; - /* fallthrough */ - case 22: PROCESS8_64; - /* fallthrough */ - case 14: PROCESS8_64; - /* fallthrough */ - case 6: PROCESS4_64; - PROCESS1_64; - PROCESS1_64; - return XXH64_avalanche(h64); - - case 27: PROCESS8_64; - /* fallthrough */ - case 19: PROCESS8_64; - /* fallthrough */ - case 11: PROCESS8_64; - PROCESS1_64; - PROCESS1_64; - PROCESS1_64; - return XXH64_avalanche(h64); - - case 31: PROCESS8_64; - /* fallthrough */ - case 23: PROCESS8_64; - /* fallthrough */ - case 15: PROCESS8_64; - /* fallthrough */ - case 7: PROCESS4_64; - /* fallthrough */ - case 3: PROCESS1_64; - /* fallthrough */ - case 2: PROCESS1_64; - /* fallthrough */ - case 1: PROCESS1_64; - /* fallthrough */ - case 0: return XXH64_avalanche(h64); - } - - /* impossible to reach */ - assert(0); - return 0; /* unreachable, but some compilers complain without it */ -} - -FORCE_INLINE U64 -XXH64_endian_align(const void* input, size_t len, U64 seed, - XXH_endianess endian, XXH_alignment align) -{ - const BYTE* p = (const BYTE*)input; - const BYTE* bEnd = p + len; - U64 h64; - -#if defined(XXH_ACCEPT_NULL_INPUT_POINTER) && (XXH_ACCEPT_NULL_INPUT_POINTER>=1) - if (p==NULL) { - len=0; - bEnd=p=(const BYTE*)(size_t)32; - } -#endif - - if (len>=32) { - const BYTE* const limit = bEnd - 32; - U64 v1 = seed + PRIME64_1 + PRIME64_2; - U64 v2 = seed + PRIME64_2; - U64 v3 = seed + 0; - U64 v4 = seed - PRIME64_1; - - do { - v1 = XXH64_round(v1, XXH_get64bits(p)); p+=8; - v2 = XXH64_round(v2, XXH_get64bits(p)); p+=8; - v3 = XXH64_round(v3, XXH_get64bits(p)); p+=8; - v4 = XXH64_round(v4, XXH_get64bits(p)); p+=8; - } while (p<=limit); - - h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18); - h64 = XXH64_mergeRound(h64, v1); - h64 = XXH64_mergeRound(h64, v2); - h64 = XXH64_mergeRound(h64, v3); - h64 = XXH64_mergeRound(h64, v4); - - } else { - h64 = seed + PRIME64_5; - } - - h64 += (U64) len; - - return XXH64_finalize(h64, p, len, endian, align); -} - - -XXH_PUBLIC_API unsigned long long XXH64 (const void* input, size_t len, unsigned long long seed) -{ -#if 0 - /* Simple version, good for code maintenance, but unfortunately slow for small inputs */ - XXH64_state_t state; - XXH64_reset(&state, seed); - XXH64_update(&state, input, len); - return XXH64_digest(&state); -#else - XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; - - if (XXH_FORCE_ALIGN_CHECK) { - if ((((size_t)input) & 7)==0) { /* Input is aligned, let's leverage the speed advantage */ - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned); - else - return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned); - } } - - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned); - else - return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned); -#endif -} - -/*====== Hash Streaming ======*/ - -XXH_PUBLIC_API XXH64_state_t* XXH64_createState(void) -{ - return (XXH64_state_t*)XXH_malloc(sizeof(XXH64_state_t)); -} -XXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr) -{ - XXH_free(statePtr); - return XXH_OK; -} - -XXH_PUBLIC_API void XXH64_copyState(XXH64_state_t* dstState, const XXH64_state_t* srcState) -{ - memcpy(dstState, srcState, sizeof(*dstState)); -} - -XXH_PUBLIC_API XXH_errorcode XXH64_reset(XXH64_state_t* statePtr, unsigned long long seed) -{ - XXH64_state_t state; /* using a local state to memcpy() in order to avoid strict-aliasing warnings */ - memset(&state, 0, sizeof(state)); - state.v1 = seed + PRIME64_1 + PRIME64_2; - state.v2 = seed + PRIME64_2; - state.v3 = seed + 0; - state.v4 = seed - PRIME64_1; - /* do not write into reserved, planned to be removed in a future version */ - memcpy(statePtr, &state, sizeof(state) - sizeof(state.reserved)); - return XXH_OK; -} - -FORCE_INLINE XXH_errorcode -XXH64_update_endian (XXH64_state_t* state, const void* input, size_t len, XXH_endianess endian) -{ - if (input==NULL) -#if defined(XXH_ACCEPT_NULL_INPUT_POINTER) && (XXH_ACCEPT_NULL_INPUT_POINTER>=1) - return XXH_OK; -#else - return XXH_ERROR; -#endif - - { const BYTE* p = (const BYTE*)input; - const BYTE* const bEnd = p + len; - - state->total_len += len; - - if (state->memsize + len < 32) { /* fill in tmp buffer */ - XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, len); - state->memsize += (U32)len; - return XXH_OK; - } - - if (state->memsize) { /* tmp buffer is full */ - XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, 32-state->memsize); - state->v1 = XXH64_round(state->v1, XXH_readLE64(state->mem64+0, endian)); - state->v2 = XXH64_round(state->v2, XXH_readLE64(state->mem64+1, endian)); - state->v3 = XXH64_round(state->v3, XXH_readLE64(state->mem64+2, endian)); - state->v4 = XXH64_round(state->v4, XXH_readLE64(state->mem64+3, endian)); - p += 32-state->memsize; - state->memsize = 0; - } - - if (p+32 <= bEnd) { - const BYTE* const limit = bEnd - 32; - U64 v1 = state->v1; - U64 v2 = state->v2; - U64 v3 = state->v3; - U64 v4 = state->v4; - - do { - v1 = XXH64_round(v1, XXH_readLE64(p, endian)); p+=8; - v2 = XXH64_round(v2, XXH_readLE64(p, endian)); p+=8; - v3 = XXH64_round(v3, XXH_readLE64(p, endian)); p+=8; - v4 = XXH64_round(v4, XXH_readLE64(p, endian)); p+=8; - } while (p<=limit); - - state->v1 = v1; - state->v2 = v2; - state->v3 = v3; - state->v4 = v4; - } - - if (p < bEnd) { - XXH_memcpy(state->mem64, p, (size_t)(bEnd-p)); - state->memsize = (unsigned)(bEnd-p); - } - } - - return XXH_OK; -} - -XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH64_state_t* state_in, const void* input, size_t len) -{ - XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; - - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH64_update_endian(state_in, input, len, XXH_littleEndian); - else - return XXH64_update_endian(state_in, input, len, XXH_bigEndian); -} - -FORCE_INLINE U64 XXH64_digest_endian (const XXH64_state_t* state, XXH_endianess endian) -{ - U64 h64; - - if (state->total_len >= 32) { - U64 const v1 = state->v1; - U64 const v2 = state->v2; - U64 const v3 = state->v3; - U64 const v4 = state->v4; - - h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18); - h64 = XXH64_mergeRound(h64, v1); - h64 = XXH64_mergeRound(h64, v2); - h64 = XXH64_mergeRound(h64, v3); - h64 = XXH64_mergeRound(h64, v4); - } else { - h64 = state->v3 /*seed*/ + PRIME64_5; - } - - h64 += (U64) state->total_len; - - return XXH64_finalize(h64, state->mem64, (size_t)state->total_len, endian, XXH_aligned); -} - -XXH_PUBLIC_API unsigned long long XXH64_digest (const XXH64_state_t* state_in) -{ - XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; - - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH64_digest_endian(state_in, XXH_littleEndian); - else - return XXH64_digest_endian(state_in, XXH_bigEndian); -} - - -/*====== Canonical representation ======*/ - -XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH64_canonical_t* dst, XXH64_hash_t hash) -{ - XXH_STATIC_ASSERT(sizeof(XXH64_canonical_t) == sizeof(XXH64_hash_t)); - if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap64(hash); - memcpy(dst, &hash, sizeof(*dst)); -} - -XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src) -{ - return XXH_readBE64(src); -} - -#endif /* XXH_NO_LONG_LONG */ diff --git a/tests/develop-test/5-taos-tools/taosdump/taosdumpTestInspect.py b/tests/develop-test/5-taos-tools/taosdump/taosdumpTestInspect.py index a6c2062d6c..1ccbb1f7d6 100644 --- a/tests/develop-test/5-taos-tools/taosdump/taosdumpTestInspect.py +++ b/tests/develop-test/5-taos-tools/taosdump/taosdumpTestInspect.py @@ -11,24 +11,20 @@ # -*- coding: utf-8 -*- -import sys import os from util.log import * from util.cases import * from util.sql import * from util.dnodes import * -import subprocess class TDTestCase: def caseDescription(self): - ''' + """ case1: [TD-14544] taosdump data inspect - ''' - return + """ def init(self, conn, logSql, replicaVar=1): - self.replicaVar = int(replicaVar) tdLog.debug("start to execute %s" % __file__) tdSql.init(conn.cursor(), logSql) self.tmpdir = "tmp" @@ -36,44 +32,56 @@ class TDTestCase: def getPath(self, tool="taosdump"): selfPath = os.path.dirname(os.path.realpath(__file__)) - if ("community" in selfPath): - projPath = selfPath[:selfPath.find("community")] + if "community" in selfPath: + projPath = selfPath[: selfPath.find("community")] + elif "src" in selfPath: + projPath = selfPath[: selfPath.find("src")] + elif "/tools/" in selfPath: + projPath = selfPath[: selfPath.find("/tools/")] + elif "/tests/" in selfPath: + projPath = selfPath[: selfPath.find("/tests/")] else: - projPath = selfPath[:selfPath.find("tests")] + tdLog.info("cannot found %s in path: %s, use system's" % (tool, selfPath)) + projPath = "/usr/local/taos/bin" paths = [] - for root, dirs, files in os.walk(projPath): - if ((tool) in files): + for root, dummy, files in os.walk(projPath): + if (tool) in files: rootRealPath = os.path.dirname(os.path.realpath(root)) - if ("packaging" not in rootRealPath): + if "packaging" not in rootRealPath: paths.append(os.path.join(root, tool)) break - if (len(paths) == 0): + if len(paths) == 0: return "" return paths[0] def run(self): - tdSql.prepare(replica=f"{self.replicaVar}") + tdSql.prepare() tdSql.execute("drop database if exists db") - tdSql.execute("create database db days 11 keep 3649 blocks 8 ") + tdSql.execute("create database db keep 3649 ") tdSql.execute("use db") tdSql.execute( - "create table st(ts timestamp, c1 INT, c2 BOOL, c3 TINYINT, c4 SMALLINT, c5 BIGINT, c6 FLOAT, c7 DOUBLE, c8 TIMESTAMP, c9 BINARY(10), c10 NCHAR(10), c11 TINYINT UNSIGNED, c12 SMALLINT UNSIGNED, c13 INT UNSIGNED, c14 BIGINT UNSIGNED) tags(n1 INT, w2 BOOL, t3 TINYINT, t4 SMALLINT, t5 BIGINT, t6 FLOAT, t7 DOUBLE, t8 TIMESTAMP, t9 BINARY(10), t10 NCHAR(10), t11 TINYINT UNSIGNED, t12 SMALLINT UNSIGNED, t13 INT UNSIGNED, t14 BIGINT UNSIGNED)") + "create table st(ts timestamp, c1 INT, c2 BOOL, c3 TINYINT, c4 SMALLINT, c5 BIGINT, c6 FLOAT, c7 DOUBLE, c8 TIMESTAMP, c9 BINARY(10), c10 NCHAR(10), c11 TINYINT UNSIGNED, c12 SMALLINT UNSIGNED, c13 INT UNSIGNED, c14 BIGINT UNSIGNED) tags(n1 INT, w2 BOOL, t3 TINYINT, t4 SMALLINT, t5 BIGINT, t6 FLOAT, t7 DOUBLE, t8 TIMESTAMP, t9 BINARY(10), t10 NCHAR(10), t11 TINYINT UNSIGNED, t12 SMALLINT UNSIGNED, t13 INT UNSIGNED, t14 BIGINT UNSIGNED)" + ) tdSql.execute( - "create table t1 using st tags(1, true, 1, 1, 1, 1.0, 1.0, 1, '1', '一', 1, 1, 1, 1)") + "create table t1 using st tags(1, true, 1, 1, 1, 1.0, 1.0, 1, '1', '一', 1, 1, 1, 1)" + ) tdSql.execute( - "insert into t1 values(1640000000000, 1, true, 1, 1, 1, 1.0, 1.0, 1, '1', '一', 1, 1, 1, 1)") + "insert into t1 values(1640000000000, 1, true, 1, 1, 1, 1.0, 1.0, 1, '1', '一', 1, 1, 1, 1)" + ) tdSql.execute( - "create table t2 using st tags(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)") + "create table t2 using st tags(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)" + ) tdSql.execute( - "insert into t2 values(1640000000000, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)") + "insert into t2 values(1640000000000, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)" + ) -# sys.exit(1) + # sys.exit(1) - binPath = self.getPath("taosdump") - if (binPath == ""): + binPath = self.getPath() + if binPath == "": tdLog.exit("taosdump not found!") else: tdLog.info("taosdump found in %s" % binPath) @@ -85,35 +93,73 @@ class TDTestCase: os.system("rm -rf %s" % self.tmpdir) os.makedirs(self.tmpdir) - os.system( - "%s --databases db -o %s -T 1" % - (binPath, self.tmpdir)) + os.system("%s --databases db -o %s -T 1" % (binPath, self.tmpdir)) -# sys.exit(1) + # sys.exit(1) - taosdumpInspectCmd = "%s -I %s/*.avro* -s | grep 'Schema:'|wc -l" % ( - binPath, self.tmpdir) - schemaTimes = subprocess.check_output( - taosdumpInspectCmd, shell=True).decode("utf-8") + taosdumpInspectCmd = "%s -I %s/taosdump.*/*.avro* -s | grep 'Schema:'|wc -l" % ( + binPath, + self.tmpdir, + ) + schemaTimes = subprocess.check_output(taosdumpInspectCmd, shell=True).decode( + "utf-8" + ) print("schema found times: %d" % int(schemaTimes)) - if (int(schemaTimes) != 3): + if int(schemaTimes) != 1: caller = inspect.getframeinfo(inspect.stack()[0][0]) tdLog.exit( - "%s(%d) failed: expected schema found times 3, actual %d" % - (caller.filename, caller.lineno, int(schemaTimes))) + "%s(%d) failed: expected schema found times 1, actual %d" + % (caller.filename, caller.lineno, int(schemaTimes)) + ) - taosdumpInspectCmd = "%s -I %s/*.avro* | grep '=== Records:'|wc -l" % ( - binPath, self.tmpdir) - recordsTimes = subprocess.check_output( - taosdumpInspectCmd, shell=True).decode("utf-8") + taosdumpInspectCmd = ( + "%s -I %s/taosdump*/data*/*.avro* -s | grep 'Schema:'|wc -l" + % (binPath, self.tmpdir) + ) + schemaTimes = subprocess.check_output(taosdumpInspectCmd, shell=True).decode( + "utf-8" + ) + print("schema found times: %d" % int(schemaTimes)) + + if int(schemaTimes) != 2: + caller = inspect.getframeinfo(inspect.stack()[0][0]) + tdLog.exit( + "%s(%d) failed: expected schema found times 2, actual %d" + % (caller.filename, caller.lineno, int(schemaTimes)) + ) + + taosdumpInspectCmd = ( + "%s -I %s/taosdump*/*.avro* | grep '=== Records:'|wc -l" + % (binPath, self.tmpdir) + ) + recordsTimes = subprocess.check_output(taosdumpInspectCmd, shell=True).decode( + "utf-8" + ) print("records found times: %d" % int(recordsTimes)) - if (int(recordsTimes) != 3): + if int(recordsTimes) != 1: caller = inspect.getframeinfo(inspect.stack()[0][0]) tdLog.exit( - "%s(%d) failed: expected records found times 3, actual %d" % - (caller.filename, caller.lineno, int(recordsTimes))) + "%s(%d) failed: expected records found times 1, actual %d" + % (caller.filename, caller.lineno, int(recordsTimes)) + ) + + taosdumpInspectCmd = ( + "%s -I %s/taosdump*/data*/*.avro* | grep '=== Records:'|wc -l" + % (binPath, self.tmpdir) + ) + recordsTimes = subprocess.check_output(taosdumpInspectCmd, shell=True).decode( + "utf-8" + ) + print("records found times: %d" % int(recordsTimes)) + + if int(recordsTimes) != 2: + caller = inspect.getframeinfo(inspect.stack()[0][0]) + tdLog.exit( + "%s(%d) failed: expected records found times 2, actual %d" + % (caller.filename, caller.lineno, int(recordsTimes)) + ) def stop(self): tdSql.close() diff --git a/tests/parallel_test/cases.task b/tests/parallel_test/cases.task index 205270e91c..c7b5e97234 100644 --- a/tests/parallel_test/cases.task +++ b/tests/parallel_test/cases.task @@ -181,6 +181,7 @@ ,,y,script,./test.sh -f tsim/query/groupby.sim ,,y,script,./test.sh -f tsim/query/event.sim ,,y,script,./test.sh -f tsim/query/forceFill.sim +,,y,script,./test.sh -f tsim/query/partitionby.sim ,,y,script,./test.sh -f tsim/qnode/basic1.sim ,,y,script,./test.sh -f tsim/snode/basic1.sim ,,y,script,./test.sh -f tsim/mnode/basic1.sim @@ -429,6 +430,7 @@ ,,y,system-test,./pytest.sh python3 ./test.py -f 0-others/user_manage.py ,,y,system-test,./pytest.sh python3 ./test.py -f 0-others/fsync.py ,,n,system-test,python3 ./test.py -f 0-others/compatibility.py +,,n,system-test,python3 ./test.py -f 0-others/tag_index_basic.py ,,y,system-test,./pytest.sh python3 ./test.py -f 1-insert/alter_database.py ,,y,system-test,./pytest.sh python3 ./test.py -f 1-insert/influxdb_line_taosc_insert.py ,,y,system-test,./pytest.sh python3 ./test.py -f 1-insert/opentsdb_telnet_line_taosc_insert.py @@ -650,6 +652,7 @@ ,,y,system-test,./pytest.sh python3 ./test.py -f 2-query/elapsed.py ,,y,system-test,./pytest.sh python3 ./test.py -f 2-query/csum.py ,,y,system-test,./pytest.sh python3 ./test.py -f 2-query/function_diff.py +,,y,system-test,./pytest.sh python3 ./test.py -f 2-query/tagFilter.py ,,n,system-test,python3 ./test.py -f 2-query/queryQnode.py ,,y,system-test,./pytest.sh python3 ./test.py -f 6-cluster/5dnode1mnode.py ,,y,system-test,./pytest.sh python3 ./test.py -f 6-cluster/5dnode2mnode.py -N 5 diff --git a/tests/parallel_test/container_build.sh b/tests/parallel_test/container_build.sh index ff854449bb..d0086c733e 100755 --- a/tests/parallel_test/container_build.sh +++ b/tests/parallel_test/container_build.sh @@ -55,7 +55,7 @@ fi date docker run \ -v $REP_MOUNT_PARAM \ - --rm --ulimit core=-1 taos_test:v1.0 sh -c "cd $REP_DIR;rm -rf debug;mkdir -p debug;cd debug;cmake .. -DBUILD_HTTP=false -DBUILD_TOOLS=true -DBUILD_TEST=true -DWEBSOCKET=true -DBUILD_TAOSX=true;make -j || exit 1" + --rm --ulimit core=-1 taos_test:v1.0 sh -c "pip uninstall taospy -y;pip3 install taospy==2.7.2;cd $REP_DIR;rm -rf debug;mkdir -p debug;cd debug;cmake .. -DBUILD_HTTP=false -DBUILD_TOOLS=true -DBUILD_TEST=true -DWEBSOCKET=true -DBUILD_TAOSX=true;make -j || exit 1" if [[ -d ${WORKDIR}/debugNoSan ]] ;then echo "delete ${WORKDIR}/debugNoSan" @@ -70,7 +70,7 @@ mv ${REP_REAL_PATH}/debug ${WORKDIR}/debugNoSan date docker run \ -v $REP_MOUNT_PARAM \ - --rm --ulimit core=-1 taos_test:v1.0 sh -c "cd $REP_DIR;rm -rf debug;mkdir -p debug;cd debug;cmake .. -DBUILD_HTTP=false -DBUILD_TOOLS=true -DBUILD_TEST=true -DWEBSOCKET=true -DBUILD_SANITIZER=1 -DTOOLS_SANITIZE=true -DTOOLS_BUILD_TYPE=Debug -DBUILD_TAOSX=true;make -j || exit 1 " + --rm --ulimit core=-1 taos_test:v1.0 sh -c "pip uninstall taospy -y;pip3 install taospy==2.7.2;cd $REP_DIR;rm -rf debug;mkdir -p debug;cd debug;cmake .. -DBUILD_HTTP=false -DBUILD_TOOLS=true -DBUILD_TEST=true -DWEBSOCKET=true -DBUILD_SANITIZER=1 -DTOOLS_SANITIZE=true -DTOOLS_BUILD_TYPE=Debug -DBUILD_TAOSX=true;make -j || exit 1 " mv ${REP_REAL_PATH}/debug ${WORKDIR}/debugSan diff --git a/tests/pytest/crash_gen/crash_gen_main.py b/tests/pytest/crash_gen/crash_gen_main.py index 3c39b05e69..ec588659e9 100755 --- a/tests/pytest/crash_gen/crash_gen_main.py +++ b/tests/pytest/crash_gen/crash_gen_main.py @@ -18,7 +18,8 @@ from __future__ import annotations from typing import Any, Set, Tuple from typing import Dict from typing import List -from typing import Optional # Type hinting, ref: https://stackoverflow.com/questions/19202633/python-3-type-hinting-for-none +from typing import \ + Optional # Type hinting, ref: https://stackoverflow.com/questions/19202633/python-3-type-hinting-for-none import textwrap import time @@ -39,7 +40,6 @@ import gc import taos from taos.tmq import * - from .shared.types import TdColumns, TdTags # from crash_gen import ServiceManager, TdeInstance, TdeSubProcess @@ -65,10 +65,11 @@ if sys.version_info[0] < 3: # Command-line/Environment Configurations, will set a bit later # ConfigNameSpace = argparse.Namespace # gConfig: argparse.Namespace -gSvcMgr: Optional[ServiceManager] # TODO: refactor this hack, use dep injection +gSvcMgr: Optional[ServiceManager] # TODO: refactor this hack, use dep injection # logger: logging.Logger gContainer: Container + # def runThread(wt: WorkerThread): # wt.run() @@ -77,7 +78,7 @@ class WorkerThread: def __init__(self, pool: ThreadPool, tid, tc: ThreadCoordinator): """ Note: this runs in the main thread context - """ + """ # self._curStep = -1 self._pool = pool self._tid = tid @@ -91,15 +92,15 @@ class WorkerThread: if (Config.getConfig().per_thread_db_connection): # type: ignore # print("connector_type = {}".format(gConfig.connector_type)) tInst = gContainer.defTdeInstance - if Config.getConfig().connector_type == 'native': - self._dbConn = DbConn.createNative(tInst.getDbTarget()) + if Config.getConfig().connector_type == 'native': + self._dbConn = DbConn.createNative(tInst.getDbTarget()) elif Config.getConfig().connector_type == 'rest': - self._dbConn = DbConn.createRest(tInst.getDbTarget()) + self._dbConn = DbConn.createRest(tInst.getDbTarget()) elif Config.getConfig().connector_type == 'mixed': - if Dice.throw(2) == 0: # 1/2 chance - self._dbConn = DbConn.createNative(tInst.getDbTarget()) + if Dice.throw(2) == 0: # 1/2 chance + self._dbConn = DbConn.createNative(tInst.getDbTarget()) else: - self._dbConn = DbConn.createRest(tInst.getDbTarget()) + self._dbConn = DbConn.createRest(tInst.getDbTarget()) else: raise RuntimeError("Unexpected connector type: {}".format(Config.getConfig().connector_type)) @@ -138,7 +139,7 @@ class WorkerThread: # clean up if (Config.getConfig().per_thread_db_connection): # type: ignore - if self._dbConn.isOpen: #sometimes it is not open + if self._dbConn.isOpen: # sometimes it is not open self._dbConn.close() else: Logging.warning("Cleaning up worker thread, dbConn already closed") @@ -150,20 +151,19 @@ class WorkerThread: tc = self._tc # Thread Coordinator, the overall master try: tc.crossStepBarrier() # shared barrier first, INCLUDING the last one - except threading.BrokenBarrierError as err: # main thread timed out + except threading.BrokenBarrierError as err: # main thread timed out print("_bto", end="") Logging.debug("[TRD] Worker thread exiting due to main thread barrier time-out") break Logging.debug("[TRD] Worker thread [{}] exited barrier...".format(self._tid)) - self.crossStepGate() # then per-thread gate, after being tapped + self.crossStepGate() # then per-thread gate, after being tapped Logging.debug("[TRD] Worker thread [{}] exited step gate...".format(self._tid)) if not self._tc.isRunning(): print("_wts", end="") Logging.debug("[TRD] Thread Coordinator not running any more, worker thread now stopping...") break - # Before we fetch the task and run it, let's ensure we properly "use" the database (not needed any more) try: if (Config.getConfig().per_thread_db_connection): # most likely TRUE @@ -172,7 +172,8 @@ class WorkerThread: # self.useDb() # might encounter exceptions. TODO: catch except taos.error.ProgrammingError as err: errno = Helper.convertErrno(err.errno) - if errno in [0x383, 0x386, 0x00B, 0x014] : # invalid database, dropping, Unable to establish connection, Database not ready + if errno in [0x383, 0x386, 0x00B, + 0x014]: # invalid database, dropping, Unable to establish connection, Database not ready # ignore dummy = 0 else: @@ -180,12 +181,12 @@ class WorkerThread: raise # Fetch a task from the Thread Coordinator - Logging.debug( "[TRD] Worker thread [{}] about to fetch task".format(self._tid)) + Logging.debug("[TRD] Worker thread [{}] about to fetch task".format(self._tid)) task = tc.fetchTask() # Execute such a task Logging.debug("[TRD] Worker thread [{}] about to execute task: {}".format( - self._tid, task.__class__.__name__)) + self._tid, task.__class__.__name__)) task.execute(self) tc.saveExecutedTask(task) Logging.debug("[TRD] Worker thread [{}] finished executing task".format(self._tid)) @@ -228,7 +229,7 @@ class WorkerThread: self._stepGate.set() # wake up! time.sleep(0) # let the released thread run a bit else: - print("_tad", end="") # Thread already dead + print("_tad", end="") # Thread already dead def execSql(self, sql): # TODO: expose DbConn directly return self.getDbConn().execute(sql) @@ -239,7 +240,7 @@ class WorkerThread: def getQueryResult(self): return self.getDbConn().getQueryResult() - def getDbConn(self) -> DbConn : + def getDbConn(self) -> DbConn: if (Config.getConfig().per_thread_db_connection): return self._dbConn else: @@ -251,6 +252,7 @@ class WorkerThread: # else: # return self._tc.getDbState().getDbConn().query(sql) + # The coordinator of all worker threads, mostly running in main thread @@ -262,7 +264,7 @@ class ThreadCoordinator: self._pool = pool # self._wd = wd self._te = None # prepare for every new step - self._dbManager = dbManager # type: Optional[DbManager] # may be freed + self._dbManager = dbManager # type: Optional[DbManager] # may be freed self._executedTasks: List[Task] = [] # in a given step self._lock = threading.RLock() # sync access for a few things @@ -284,7 +286,7 @@ class ThreadCoordinator: return self._dbManager def crossStepBarrier(self, timeout=None): - self._stepBarrier.wait(timeout) + self._stepBarrier.wait(timeout) def requestToStop(self): self._runStatus = Status.STATUS_STOPPING @@ -292,7 +294,7 @@ class ThreadCoordinator: def _runShouldEnd(self, transitionFailed, hasAbortedTask, workerTimeout): maxSteps = Config.getConfig().max_steps # type: ignore - if self._curStep >= (maxSteps - 1): # maxStep==10, last curStep should be 9 + if self._curStep >= (maxSteps - 1): # maxStep==10, last curStep should be 9 return True if self._runStatus != Status.STATUS_RUNNING: return True @@ -304,7 +306,7 @@ class ThreadCoordinator: return True return False - def _hasAbortedTask(self): # from execution of previous step + def _hasAbortedTask(self): # from execution of previous step for task in self._executedTasks: if task.isAborted(): # print("Task aborted: {}".format(task)) @@ -319,17 +321,17 @@ class ThreadCoordinator: "--\r\n\n--> Step {} starts with main thread waking up".format(self._curStep)) # A new TE for the new step - self._te = None # set to empty first, to signal worker thread to stop + self._te = None # set to empty first, to signal worker thread to stop if not transitionFailed: # only if not failed self._te = TaskExecutor(self._curStep) Logging.debug("[TRD] Main thread waking up at step {}, tapping worker threads".format( - self._curStep)) # Now not all threads had time to go to sleep + self._curStep)) # Now not all threads had time to go to sleep # Worker threads will wake up at this point, and each execute it's own task - self.tapAllThreads() # release all worker thread from their "gates" + self.tapAllThreads() # release all worker thread from their "gates" def _syncAtBarrier(self): - # Now main thread (that's us) is ready to enter a step + # Now main thread (that's us) is ready to enter a step # let other threads go past the pool barrier, but wait at the # thread gate Logging.debug("[TRD] Main thread about to cross the barrier") @@ -341,7 +343,7 @@ class ThreadCoordinator: transitionFailed = False try: for x in self._dbs: - db = x # type: Database + db = x # type: Database sm = db.getStateMachine() Logging.debug("[STT] starting transitions for DB: {}".format(db.getName())) # at end of step, transiton the DB state @@ -357,8 +359,8 @@ class ThreadCoordinator: # for t in self._pool.threadList: # Logging.debug("[DB] use db for all worker threads") # t.useDb() - # t.execSql("use db") # main thread executing "use - # db" on behalf of every worker thread + # t.execSql("use db") # main thread executing "use + # db" on behalf of every worker thread except taos.error.ProgrammingError as err: if (err.msg == 'network unavailable'): # broken DB connection @@ -369,12 +371,13 @@ class ThreadCoordinator: self._execStats.registerFailure("Broken DB Connection") # continue # don't do that, need to tap all threads at # end, and maybe signal them to stop - if isinstance(err, CrashGenError): # our own transition failure + if isinstance(err, CrashGenError): # our own transition failure Logging.info("State transition error") # TODO: saw an error here once, let's print out stack info for err? - traceback.print_stack() # Stack frame to here. + traceback.print_stack() # Stack frame to here. Logging.info("Caused by:") - traceback.print_exception(*sys.exc_info()) # Ref: https://www.geeksforgeeks.org/how-to-print-exception-stack-trace-in-python/ + traceback.print_exception( + *sys.exc_info()) # Ref: https://www.geeksforgeeks.org/how-to-print-exception-stack-trace-in-python/ transitionFailed = True self._te = None # Not running any more self._execStats.registerFailure("State transition error: {}".format(err)) @@ -392,14 +395,14 @@ class ThreadCoordinator: # Coordinate all threads step by step self._curStep = -1 # not started yet - + self._execStats.startExec() # start the stop watch transitionFailed = False hasAbortedTask = False workerTimeout = False while not self._runShouldEnd(transitionFailed, hasAbortedTask, workerTimeout): - if not Config.getConfig().debug: # print this only if we are not in debug mode - Progress.emit(Progress.STEP_BOUNDARY) + if not Config.getConfig().debug: # print this only if we are not in debug mode + Progress.emit(Progress.STEP_BOUNDARY) # print(".", end="", flush=True) # if (self._curStep % 2) == 0: # print memory usage once every 10 steps # memUsage = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss @@ -408,15 +411,14 @@ class ThreadCoordinator: # h = hpy() # print("\n") # print(h.heap()) - - + try: - self._syncAtBarrier() # For now just cross the barrier + self._syncAtBarrier() # For now just cross the barrier Progress.emit(Progress.END_THREAD_STEP) - if self._stepStartTime : + if self._stepStartTime: stepExecTime = time.time() - self._stepStartTime Progress.emitStr('{:.3f}s/{}'.format(stepExecTime, DbConnNative.totalRequests)) - DbConnNative.resetTotalRequests() # reset to zero + DbConnNative.resetTotalRequests() # reset to zero except threading.BrokenBarrierError as err: self._execStats.registerFailure("Aborted due to worker thread timeout") Logging.error("\n") @@ -439,15 +441,15 @@ class ThreadCoordinator: # At this point, all threads should be pass the overall "barrier" and before the per-thread "gate" # We use this period to do house keeping work, when all worker # threads are QUIET. - hasAbortedTask = self._hasAbortedTask() # from previous step - if hasAbortedTask: + hasAbortedTask = self._hasAbortedTask() # from previous step + if hasAbortedTask: Logging.info("Aborted task encountered, exiting test program") self._execStats.registerFailure("Aborted Task Encountered") - break # do transition only if tasks are error free + break # do transition only if tasks are error free # Ending previous step try: - transitionFailed = self._doTransition() # To start, we end step -1 first + transitionFailed = self._doTransition() # To start, we end step -1 first except taos.error.ProgrammingError as err: transitionFailed = True errno2 = Helper.convertErrno(err.errno) # correct error scheme @@ -459,32 +461,32 @@ class ThreadCoordinator: # Then we move on to the next step Progress.emit(Progress.BEGIN_THREAD_STEP) self._stepStartTime = time.time() - self._releaseAllWorkerThreads(transitionFailed) + self._releaseAllWorkerThreads(transitionFailed) - if hasAbortedTask or transitionFailed : # abnormal ending, workers waiting at "gate" + if hasAbortedTask or transitionFailed: # abnormal ending, workers waiting at "gate" Logging.debug("Abnormal ending of main thraed") elif workerTimeout: Logging.debug("Abnormal ending of main thread, due to worker timeout") - else: # regular ending, workers waiting at "barrier" + else: # regular ending, workers waiting at "barrier" Logging.debug("Regular ending, main thread waiting for all worker threads to stop...") self._syncAtBarrier() self._te = None # No more executor, time to end Logging.debug("Main thread tapping all threads one last time...") self.tapAllThreads() # Let the threads run one last time - #TODO: looks like we are not capturing the failures for the last step yet (i.e. calling registerFailure if neccessary) + # TODO: looks like we are not capturing the failures for the last step yet (i.e. calling registerFailure if neccessary) Logging.debug("\r\n\n--> Main thread ready to finish up...") Logging.debug("Main thread joining all threads") self._pool.joinAll() # Get all threads to finish - Logging.info(". . . All worker threads finished") # No CR/LF before + Logging.info(". . . All worker threads finished") # No CR/LF before self._execStats.endExec() - def cleanup(self): # free resources + def cleanup(self): # free resources self._pool.cleanup() self._pool = None - self._te = None + self._te = None self._dbManager = None self._executedTasks = [] self._lock = None @@ -492,7 +494,6 @@ class ThreadCoordinator: self._execStats = None self._runStatus = None - def printStats(self): self._execStats.printStats() @@ -523,21 +524,21 @@ class ThreadCoordinator: def _initDbs(self): ''' Initialize multiple databases, invoked at __ini__() time ''' - self._dbs = [] # type: List[Database] + self._dbs = [] # type: List[Database] dbc = self.getDbManager().getDbConn() if Config.getConfig().max_dbs == 0: self._dbs.append(Database(0, dbc)) - else: - baseDbNumber = int(datetime.datetime.now().timestamp( # Don't use Dice/random, as they are deterministic - )*333) % 888 if Config.getConfig().dynamic_db_table_names else 0 + else: + baseDbNumber = int(datetime.datetime.now().timestamp( # Don't use Dice/random, as they are deterministic + ) * 333) % 888 if Config.getConfig().dynamic_db_table_names else 0 for i in range(Config.getConfig().max_dbs): self._dbs.append(Database(baseDbNumber + i, dbc)) def pickDatabase(self): idxDb = 0 - if Config.getConfig().max_dbs != 0 : - idxDb = Dice.throw(Config.getConfig().max_dbs) # 0 to N-1 - db = self._dbs[idxDb] # type: Database + if Config.getConfig().max_dbs != 0: + idxDb = Dice.throw(Config.getConfig().max_dbs) # 0 to N-1 + db = self._dbs[idxDb] # type: Database return db def fetchTask(self) -> Task: @@ -549,12 +550,12 @@ class ThreadCoordinator: # pick a task type for current state db = self.pickDatabase() - if Dice.throw(2)==1: - taskType = db.getStateMachine().pickTaskType() # dynamic name of class + if Dice.throw(2) == 1: + taskType = db.getStateMachine().pickTaskType() # dynamic name of class else: - taskType = db.getStateMachine().balance_pickTaskType() # and an method can get balance task types + taskType = db.getStateMachine().balance_pickTaskType() # and an method can get balance task types pass - + return taskType(self._execStats, db) # create a task from it def resetExecutedTasks(self): @@ -564,6 +565,7 @@ class ThreadCoordinator: with self._lock: self._executedTasks.append(task) + class ThreadPool: def __init__(self, numThreads, maxSteps): self.numThreads = numThreads @@ -585,7 +587,8 @@ class ThreadPool: workerThread._thread.join() def cleanup(self): - self.threadList = [] # maybe clean up each? + self.threadList = [] # maybe clean up each? + # A queue of continguous POSITIVE integers, used by DbManager to generate continuous numbers # for new table names @@ -680,11 +683,11 @@ class AnyState: CAN_CREATE_DB = 1 # For below, if we can "drop the DB", but strictly speaking # only "under normal circumstances", as we may override it with the -b option - CAN_DROP_DB = 2 + CAN_DROP_DB = 2 CAN_CREATE_FIXED_SUPER_TABLE = 3 CAN_CREATE_STREAM = 3 # super table must exists CAN_CREATE_TOPIC = 3 # super table must exists - CAN_CREATE_CONSUMERS = 3 + CAN_CREATE_CONSUMERS = 3 CAN_DROP_FIXED_SUPER_TABLE = 4 CAN_DROP_TOPIC = 4 CAN_DROP_STREAM = 4 @@ -729,7 +732,7 @@ class AnyState: def canDropDb(self): # If user requests to run up to a number of DBs, # we'd then not do drop_db operations any more - if Config.getConfig().max_dbs > 0 or Config.getConfig().use_shadow_db : + if Config.getConfig().max_dbs > 0 or Config.getConfig().use_shadow_db: return False return self._info[self.CAN_DROP_DB] @@ -737,19 +740,19 @@ class AnyState: return self._info[self.CAN_CREATE_FIXED_SUPER_TABLE] def canDropFixedSuperTable(self): - if Config.getConfig().use_shadow_db: # duplicate writes to shaddow DB, in which case let's disable dropping s-table + if Config.getConfig().use_shadow_db: # duplicate writes to shaddow DB, in which case let's disable dropping s-table return False return self._info[self.CAN_DROP_FIXED_SUPER_TABLE] def canCreateTopic(self): return self._info[self.CAN_CREATE_TOPIC] - + def canDropTopic(self): return self._info[self.CAN_DROP_TOPIC] def canCreateConsumers(self): return self._info[self.CAN_CREATE_CONSUMERS] - + def canCreateStreams(self): return self._info[self.CAN_CREATE_STREAM] @@ -777,7 +780,7 @@ class AnyState: raise CrashGenError( "Unexpected more than 1 success at state: {}, with task: {}, in task set: {}".format( self.__class__.__name__, - cls.__name__, # verified just now that isinstance(task, cls) + cls.__name__, # verified just now that isinstance(task, cls) [c.__class__.__name__ for c in tasks] )) @@ -792,16 +795,17 @@ class AnyState: sCnt += 1 if (exists and sCnt <= 0): raise CrashGenError("Unexpected zero success at state: {}, with task: {}, in task set: {}".format( - self.__class__.__name__, - cls.__name__, # verified just now that isinstance(task, cls) - [c.__class__.__name__ for c in tasks] - )) + self.__class__.__name__, + cls.__name__, # verified just now that isinstance(task, cls) + [c.__class__.__name__ for c in tasks] + )) def assertNoTask(self, tasks, cls): for task in tasks: if isinstance(task, cls): raise CrashGenError( - "This task: {}, is not expected to be present, given the success/failure of others".format(cls.__name__)) + "This task: {}, is not expected to be present, given the success/failure of others".format( + cls.__name__)) def assertNoSuccess(self, tasks, cls): for task in tasks: @@ -848,7 +852,7 @@ class StateEmpty(AnyState): def verifyTasksToState(self, tasks, newState): if (self.hasSuccess(tasks, TaskCreateDb) - ): # at EMPTY, if there's succes in creating DB + ): # at EMPTY, if there's succes in creating DB if (not self.hasTask(tasks, TaskDropDb)): # and no drop_db tasks # we must have at most one. TODO: compare numbers self.assertAtMostOneSuccess(tasks, TaskCreateDb) @@ -885,19 +889,19 @@ class StateSuperTableOnly(AnyState): def verifyTasksToState(self, tasks, newState): if (self.hasSuccess(tasks, TaskDropSuperTable) - ): # we are able to drop the table - #self.assertAtMostOneSuccess(tasks, TaskDropSuperTable) + ): # we are able to drop the table + # self.assertAtMostOneSuccess(tasks, TaskDropSuperTable) # we must have had recreted it self.hasSuccess(tasks, TaskCreateSuperTable) # self._state = self.STATE_DB_ONLY # elif ( self.hasSuccess(tasks, AddFixedDataTask) ): # no success dropping the table, but added data # self.assertNoTask(tasks, DropFixedTableTask) # not true in massively parrallel cases - # self._state = self.STATE_HAS_DATA + # self._state = self.STATE_HAS_DATA # elif ( self.hasSuccess(tasks, ReadFixedDataTask) ): # no success in prev cases, but was able to read data - # self.assertNoTask(tasks, DropFixedTableTask) - # self.assertNoTask(tasks, AddFixedDataTask) - # self._state = self.STATE_TABLE_ONLY # no change + # self.assertNoTask(tasks, DropFixedTableTask) + # self.assertNoTask(tasks, AddFixedDataTask) + # self._state = self.STATE_TABLE_ONLY # no change # else: # did not drop table, did not insert data, did not read successfully, that is impossible # raise RuntimeError("Unexpected no-success scenarios") # TODO: need to revamp!! @@ -919,41 +923,41 @@ class StateHasData(AnyState): self.assertAtMostOneSuccess(tasks, TaskDropDb) # TODO: dicy elif (newState.equals(AnyState.STATE_DB_ONLY)): # in DB only if (not self.hasTask(tasks, TaskCreateDb) - ): # without a create_db task + ): # without a create_db task # we must have drop_db task self.assertNoTask(tasks, TaskDropDb) self.hasSuccess(tasks, TaskDropSuperTable) # self.assertAtMostOneSuccess(tasks, DropFixedSuperTableTask) # TODO: dicy # elif ( newState.equals(AnyState.STATE_TABLE_ONLY) ): # data deleted - # self.assertNoTask(tasks, TaskDropDb) - # self.assertNoTask(tasks, TaskDropSuperTable) - # self.assertNoTask(tasks, TaskAddData) - # self.hasSuccess(tasks, DeleteDataTasks) + # self.assertNoTask(tasks, TaskDropDb) + # self.assertNoTask(tasks, TaskDropSuperTable) + # self.assertNoTask(tasks, TaskAddData) + # self.hasSuccess(tasks, DeleteDataTasks) else: # should be STATE_HAS_DATA if (not self.hasTask(tasks, TaskCreateDb) - ): # only if we didn't create one + ): # only if we didn't create one # we shouldn't have dropped it self.assertNoTask(tasks, TaskDropDb) - if not( self.hasTask(tasks, TaskCreateSuperTable) - ): # if we didn't create the table + if not (self.hasTask(tasks, TaskCreateSuperTable) + ): # if we didn't create the table # we should not have a task that drops it self.assertNoTask(tasks, TaskDropSuperTable) # self.assertIfExistThenSuccess(tasks, ReadFixedDataTask) class StateMechine: - def __init__(self, db: Database): + def __init__(self, db: Database): self._db = db # transitition target probabilities, indexed with value of STATE_EMPTY, STATE_DB_ONLY, etc. self._stateWeights = [1, 2, 10, 40] - def init(self, dbc: DbConn): # late initailization, don't save the dbConn + def init(self, dbc: DbConn): # late initailization, don't save the dbConn try: self._curState = self._findCurrentState(dbc) # starting state - except taos.error.ProgrammingError as err: + except taos.error.ProgrammingError as err: Logging.error("Failed to initialized state machine, cannot find current state: {}".format(err)) traceback.print_stack() - raise # re-throw + raise # re-throw # TODO: seems no lnoger used, remove? def getCurrentState(self): @@ -999,28 +1003,27 @@ class StateMechine: def _findCurrentState(self, dbc: DbConn): ts = time.time() # we use this to debug how fast/slow it is to do the various queries to find the current DB state - dbName =self._db.getName() - if not dbc.existsDatabase(dbName): # dbc.hasDatabases(): # no database?! - Logging.debug( "[STT] empty database found, between {} and {}".format(ts, time.time())) + dbName = self._db.getName() + if not dbc.existsDatabase(dbName): # dbc.hasDatabases(): # no database?! + Logging.debug("[STT] empty database found, between {} and {}".format(ts, time.time())) return StateEmpty() # did not do this when openning connection, and this is NOT the worker # thread, which does this on their own dbc.use(dbName) - + if not dbc.hasTables(): # no tables - + Logging.debug("[STT] DB_ONLY found, between {} and {}".format(ts, time.time())) return StateDbOnly() # For sure we have tables, which means we must have the super table. # TODO: are we sure? - + sTable = self._db.getFixedSuperTable() - if sTable.hasRegTables(dbc): # no regular tables # print("debug=====*\n"*100) Logging.debug("[STT] SUPER_TABLE_ONLY found, between {} and {}".format(ts, time.time())) - + return StateSuperTableOnly() else: # has actual tables Logging.debug("[STT] HAS_DATA found, between {} and {}".format(ts, time.time())) @@ -1029,7 +1032,7 @@ class StateMechine: # We transition the system to a new state by examining the current state itself def transition(self, tasks, dbc: DbConn): global gSvcMgr - + if (len(tasks) == 0): # before 1st step, or otherwise empty Logging.debug("[STT] Starting State: {}".format(self._curState)) return # do nothing @@ -1038,39 +1041,39 @@ class StateMechine: dbc.execute("select * from information_schema.ins_dnodes") # Generic Checks, first based on the start state - if not Config.getConfig().ignore_errors: # verify state, only if we are asked not to ignore certain errors. + if not Config.getConfig().ignore_errors: # verify state, only if we are asked not to ignore certain errors. if self._curState.canCreateDb(): self._curState.assertIfExistThenSuccess(tasks, TaskCreateDb) # self.assertAtMostOneSuccess(tasks, CreateDbTask) # not really, in # case of multiple creation and drops if self._curState.canDropDb(): - if gSvcMgr == None: # only if we are running as client-only + if gSvcMgr == None: # only if we are running as client-only self._curState.assertIfExistThenSuccess(tasks, TaskDropDb) # self.assertAtMostOneSuccess(tasks, DropDbTask) # not really in # case of drop-create-drop # if self._state.canCreateFixedTable(): - # self.assertIfExistThenSuccess(tasks, CreateFixedTableTask) # Not true, DB may be dropped - # self.assertAtMostOneSuccess(tasks, CreateFixedTableTask) # not - # really, in case of create-drop-create + # self.assertIfExistThenSuccess(tasks, CreateFixedTableTask) # Not true, DB may be dropped + # self.assertAtMostOneSuccess(tasks, CreateFixedTableTask) # not + # really, in case of create-drop-create # if self._state.canDropFixedTable(): - # self.assertIfExistThenSuccess(tasks, DropFixedTableTask) # Not True, the whole DB may be dropped - # self.assertAtMostOneSuccess(tasks, DropFixedTableTask) # not - # really in case of drop-create-drop + # self.assertIfExistThenSuccess(tasks, DropFixedTableTask) # Not True, the whole DB may be dropped + # self.assertAtMostOneSuccess(tasks, DropFixedTableTask) # not + # really in case of drop-create-drop # if self._state.canAddData(): # self.assertIfExistThenSuccess(tasks, AddFixedDataTask) # not true # actually # if self._state.canReadData(): - # Nothing for sure + # Nothing for sure newState = self._findCurrentState(dbc) Logging.debug("[STT] New DB state determined: {}".format(newState)) # can old state move to new state through the tasks? - if not Config.getConfig().ignore_errors: # verify state, only if we are asked not to ignore certain errors. + if not Config.getConfig().ignore_errors: # verify state, only if we are asked not to ignore certain errors. self._curState.verifyTasksToState(tasks, newState) self._curState = newState @@ -1096,22 +1099,24 @@ class StateMechine: weightsTypes = BasicTypes.copy() # this matrixs can balance the Frequency of TaskTypes - balance_TaskType_matrixs = {'TaskDropDb': 5 , 'TaskDropTopics': 20 , 'TaskDropStreams':10 , 'TaskDropStreamTables':10 , - 'TaskReadData':50 , 'TaskDropSuperTable':5 , 'TaskAlterTags':3 , 'TaskAddData':10, - 'TaskDeleteData':10 , 'TaskCreateDb':10 , 'TaskCreateStream': 3, 'TaskCreateTopic' :3, - 'TaskCreateConsumers':10, 'TaskCreateSuperTable': 10 } # TaskType : balance_matrixs of task - - for task , weights in balance_TaskType_matrixs.items(): - + balance_TaskType_matrixs = {'TaskDropDb': 5, 'TaskDropTopics': 20, 'TaskDropStreams': 10, + 'TaskDropStreamTables': 10, + 'TaskReadData': 50, 'TaskDropSuperTable': 5, 'TaskAlterTags': 3, 'TaskAddData': 10, + 'TaskDeleteData': 10, 'TaskCreateDb': 10, 'TaskCreateStream': 3, + 'TaskCreateTopic': 3, + 'TaskCreateConsumers': 10, + 'TaskCreateSuperTable': 10} # TaskType : balance_matrixs of task + + for task, weights in balance_TaskType_matrixs.items(): + for basicType in BasicTypes: if basicType.__name__ == task: for _ in range(weights): weightsTypes.append(basicType) - task = random.sample(weightsTypes,1) + task = random.sample(weightsTypes, 1) return task[0] - # ref: # https://eli.thegreenplace.net/2010/01/22/weighted-random-generation-in-python/ def _weighted_choice_sub(self, weights) -> int: @@ -1123,6 +1128,7 @@ class StateMechine: return i raise CrashGenError("Unexpected no choice") + class Database: ''' We use this to represent an actual TDengine database inside a service instance, possibly in a cluster environment. @@ -1131,16 +1137,16 @@ class Database: TODO: consider moving, but keep in mind it contains "StateMachine" ''' - _clsLock = threading.Lock() # class wide lock + _clsLock = threading.Lock() # class wide lock _lastInt = 101 # next one is initial integer - _lastTick = None # Optional[datetime] - _lastLaggingTick = None # Optional[datetime] # lagging tick, for out-of-sequence (oos) data insertions + _lastTick = None # Optional[datetime] + _lastLaggingTick = None # Optional[datetime] # lagging tick, for out-of-sequence (oos) data insertions - def __init__(self, dbNum: int, dbc: DbConn): # TODO: remove dbc - self._dbNum = dbNum # we assign a number to databases, for our testing purpose + def __init__(self, dbNum: int, dbc: DbConn): # TODO: remove dbc + self._dbNum = dbNum # we assign a number to databases, for our testing purpose self._stateMachine = StateMechine(self) self._stateMachine.init(dbc) - + self._lock = threading.RLock() def getStateMachine(self) -> StateMechine: @@ -1152,7 +1158,7 @@ class Database: def getName(self): return "db_{}".format(self._dbNum) - def filterTasks(self, inTasks: List[Task]): # Pick out those belonging to us + def filterTasks(self, inTasks: List[Task]): # Pick out those belonging to us outTasks = [] for task in inTasks: if task.getDb().isSame(self): @@ -1184,38 +1190,42 @@ class Database: # start time will be auto generated , start at 10 years ago local time local_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-16] local_epoch_time = [int(i) for i in local_time.split("-")] - #local_epoch_time will be such as : [2022, 7, 18] + # local_epoch_time will be such as : [2022, 7, 18] - t1 = datetime.datetime(local_epoch_time[0]-5, local_epoch_time[1], local_epoch_time[2]) + t1 = datetime.datetime(local_epoch_time[0] - 5, local_epoch_time[1], local_epoch_time[2]) t2 = datetime.datetime.now() # maybe a very large number, takes 69 years to exceed Python int range elSec = int(t2.timestamp() - t1.timestamp()) elSec2 = (elSec % (8 * 12 * 30 * 24 * 60 * 60 / 500)) * \ - 500 # a number representing seconds within 10 years + 500 # a number representing seconds within 10 years # print("elSec = {}".format(elSec)) - t3 = datetime.datetime(local_epoch_time[0]-10, local_epoch_time[1], local_epoch_time[2]) # default "keep" is 10 years + t3 = datetime.datetime(local_epoch_time[0] - 10, local_epoch_time[1], + local_epoch_time[2]) # default "keep" is 10 years t4 = datetime.datetime.fromtimestamp( t3.timestamp() + elSec2) # see explanation above Logging.debug("Setting up TICKS to start from: {}".format(t4)) return t4 @classmethod - def getNextTick(cls): + def getNextTick(cls): ''' Fetch a timestamp tick, with some random factor, may not be unique. - ''' + ''' with cls._clsLock: # prevent duplicate tick - if cls._lastLaggingTick is None or cls._lastTick is None : # not initialized + if cls._lastLaggingTick is None or cls._lastTick is None: # not initialized # 10k at 1/20 chance, should be enough to avoid overlaps tick = cls.setupLastTick() cls._lastTick = tick - cls._lastLaggingTick = tick + datetime.timedelta(0, -60*2) # lagging behind 2 minutes, should catch up fast + cls._lastLaggingTick = tick + datetime.timedelta(0, + -60 * 2) # lagging behind 2 minutes, should catch up fast # if : # should be quite a bit into the future - if Config.isSet('mix_oos_data') and Dice.throw(20) == 0: # if asked to do so, and 1 in 20 chance, return lagging tick - cls._lastLaggingTick += datetime.timedelta(0, 1) # pick the next sequence from the lagging tick sequence - return cls._lastLaggingTick + if Config.isSet('mix_oos_data') and Dice.throw( + 20) == 0: # if asked to do so, and 1 in 20 chance, return lagging tick + cls._lastLaggingTick += datetime.timedelta(0, + 1) # pick the next sequence from the lagging tick sequence + return cls._lastLaggingTick else: # regular # add one second to it cls._lastTick += datetime.timedelta(0, 1) @@ -1332,9 +1342,7 @@ class Task(): # Logging.debug("Creating new task {}...".format(self._taskNum)) self._execStats = execStats - self._db = db # A task is always associated/for a specific DB - - + self._db = db # A task is always associated/for a specific DB def isSuccess(self): return self._err is None @@ -1367,82 +1375,78 @@ class Task(): def _isServiceStable(self): if not gSvcMgr: return True # we don't run service, so let's assume it's stable - return gSvcMgr.isStable() # otherwise let's examine the service + return gSvcMgr.isStable() # otherwise let's examine the service def _isErrAcceptable(self, errno, msg): if errno in [ - # TDengine 2.x Error Codes: - 0x05, # TSDB_CODE_RPC_NOT_READY - 0x0B, # Unable to establish connection, more details in TD-1648 - # 0x200, # invalid SQL, TODO: re-examine with TD-934 - 0x20F, # query terminated, possibly due to vnoding being dropped, see TD-1776 - 0x213, # "Disconnected from service", result of "kill connection ???" - 0x217, # "db not selected", client side defined error code - # 0x218, # "Table does not exist" client side defined error code - 0x360, # Table already exists - 0x362, - # 0x369, # tag already exists - 0x36A, 0x36B, 0x36D, - 0x381, - 0x380, # "db not selected" - 0x383, - 0x386, # DB is being dropped?! - 0x503, - 0x510, # vnode not in ready state - 0x14, # db not ready, errno changed - 0x600, # Invalid table ID, why? - 0x218, # Table does not exist + # TDengine 2.x Error Codes: + 0x05, # TSDB_CODE_RPC_NOT_READY + 0x0B, # Unable to establish connection, more details in TD-1648 + # 0x200, # invalid SQL, TODO: re-examine with TD-934 + 0x20F, # query terminated, possibly due to vnoding being dropped, see TD-1776 + 0x213, # "Disconnected from service", result of "kill connection ???" + 0x217, # "db not selected", client side defined error code + # 0x218, # "Table does not exist" client side defined error code + 0x360, # Table already exists + 0x362, + # 0x369, # tag already exists + 0x36A, 0x36B, 0x36D, + 0x381, + 0x380, # "db not selected" + 0x383, + 0x386, # DB is being dropped?! + 0x503, + 0x510, # vnode not in ready state + 0x14, # db not ready, errno changed + 0x600, # Invalid table ID, why? + 0x218, # Table does not exist - # TDengine 3.0 Error Codes: - 0x0333, # Object is creating # TODO: this really is NOT an acceptable error - 0x0369, # Tag already exists - 0x0388, # Database not exist - 0x03A0, # STable already exists - 0x03A1, # STable [does] not exist - 0x03AA, # Tag already exists - 0x0603, # Table already exists - 0x2603, # Table does not exist, replaced by 2662 below - 0x260d, # Tags number not matched - 0x2662, # Table does not exist #TODO: what about 2603 above? - 0x2600, # database not specified, SQL: show stables , database droped , and show tables - 0x032C, # Object is creating - 0x032D, # Object is dropping - 0x03D3, # Conflict transaction not completed - 0x0707, # Query not ready , it always occur at replica 3 - 0x707, # Query not ready - 0x396, # Database in creating status - 0x386, # Database in droping status - 0x03E1, # failed on tmq_subscribe ,topic not exist - 0x03ed , # Topic must be dropped first, SQL: drop database db_0 - 0x0203 , # Invalid value - 0x03f0 , # Stream already exist , topic already exists + # TDengine 3.0 Error Codes: + 0x0333, # Object is creating # TODO: this really is NOT an acceptable error + 0x0369, # Tag already exists + 0x0388, # Database not exist + 0x03A0, # STable already exists + 0x03A1, # STable [does] not exist + 0x03AA, # Tag already exists + 0x0603, # Table already exists + 0x2603, # Table does not exist, replaced by 2662 below + 0x260d, # Tags number not matched + 0x2662, # Table does not exist #TODO: what about 2603 above? + 0x2600, # database not specified, SQL: show stables , database droped , and show tables + 0x032C, # Object is creating + 0x032D, # Object is dropping + 0x03D3, # Conflict transaction not completed + 0x0707, # Query not ready , it always occur at replica 3 + 0x707, # Query not ready + 0x396, # Database in creating status + 0x386, # Database in droping status + 0x03E1, # failed on tmq_subscribe ,topic not exist + 0x03ed, # Topic must be dropped first, SQL: drop database db_0 + 0x0203, # Invalid value + 0x03f0, # Stream already exist , topic already exists - - - - 1000 # REST catch-all error - ]: - return True # These are the ALWAYS-ACCEPTABLE ones + 1000 # REST catch-all error + ]: + return True # These are the ALWAYS-ACCEPTABLE ones # This case handled below already. # elif (errno in [ 0x0B ]) and Settings.getConfig().auto_start_service: # return True # We may get "network unavilable" when restarting service - elif Config.getConfig().ignore_errors: # something is specified on command line + elif Config.getConfig().ignore_errors: # something is specified on command line moreErrnos = [int(v, 0) for v in Config.getConfig().ignore_errors.split(',')] if errno in moreErrnos: return True - elif errno == 0x200 : # invalid SQL, we need to div in a bit more + elif errno == 0x200: # invalid SQL, we need to div in a bit more if msg.find("invalid column name") != -1: - return True - elif msg.find("tags number not matched") != -1: # mismatched tags after modification return True - elif msg.find("duplicated column names") != -1: # also alter table tag issues + elif msg.find("tags number not matched") != -1: # mismatched tags after modification return True - elif not self._isServiceStable(): # We are managing service, and ... + elif msg.find("duplicated column names") != -1: # also alter table tag issues + return True + elif not self._isServiceStable(): # We are managing service, and ... Logging.info("Ignoring error when service starting/stopping: errno = {}, msg = {}".format(errno, msg)) return True - - return False # Not an acceptable error + return False # Not an acceptable error def execute(self, wt: WorkerThread): wt.verifyThreadSelf() @@ -1453,7 +1457,7 @@ class Task(): self.logDebug( "[-] executing task {}...".format(self.__class__.__name__)) - self._err = None # TODO: type hint mess up? + self._err = None # TODO: type hint mess up? self._execStats.beginTaskType(self.__class__.__name__) # mark beginning errno2 = None @@ -1465,19 +1469,19 @@ class Task(): errno2 = Helper.convertErrno(err.errno) if (Config.getConfig().continue_on_exception): # user choose to continue self.logDebug("[=] Continue after TAOS exception: errno=0x{:X}, msg: {}, SQL: {}".format( - errno2, err, wt.getDbConn().getLastSql())) + errno2, err, wt.getDbConn().getLastSql())) self._err = err elif self._isErrAcceptable(errno2, err.__str__()): self.logDebug("[=] Acceptable Taos library exception: errno=0x{:X}, msg: {}, SQL: {}".format( - errno2, err, wt.getDbConn().getLastSql())) + errno2, err, wt.getDbConn().getLastSql())) # print("_", end="", flush=True) Progress.emit(Progress.ACCEPTABLE_ERROR) self._err = err - else: # not an acceptable error + else: # not an acceptable error shortTid = threading.get_ident() % 10000 errMsg = "[=] Unexpected Taos library exception ({}): errno=0x{:X}, thread={}, msg: {}, SQL: {}".format( self.__class__.__name__, - errno2, + errno2, shortTid, err, wt.getDbConn().getLastSql()) self.logDebug(errMsg) @@ -1485,7 +1489,8 @@ class Task(): # raise # so that we see full stack traceback.print_exc() print( - "\n\n----------------------------\nProgram ABORTED Due to Unexpected TAOS Error: \n\n{}\n".format(errMsg) + + "\n\n----------------------------\nProgram ABORTED Due to Unexpected TAOS Error: \n\n{}\n".format( + errMsg) + "----------------------------\n") # sys.exit(-1) self._err = err @@ -1502,10 +1507,10 @@ class Task(): traceback.print_exc() # except BaseException: # TODO: what is this again??!! # raise RuntimeError("Punt") - # self.logDebug( - # "[=] Unexpected exception, SQL: {}".format( - # wt.getDbConn().getLastSql())) - # raise + # self.logDebug( + # "[=] Unexpected exception, SQL: {}".format( + # wt.getDbConn().getLastSql())) + # raise self._execStats.endTaskType(self.__class__.__name__, self.isSuccess()) self.logDebug("[X] task execution completed, {}, status: {}".format( @@ -1524,12 +1529,12 @@ class Task(): def getQueryResult(self, wt: WorkerThread): # execute an SQL on the worker thread return wt.getQueryResult() - def lockTable(self, ftName): # full table name + def lockTable(self, ftName): # full table name # print(" <<" + ftName + '_', end="", flush=True) - with Task._lock: # SHORT lock! so we only protect lock creation - if not ftName in Task._tableLocks: # Create new lock and add to list, if needed + with Task._lock: # SHORT lock! so we only protect lock creation + if not ftName in Task._tableLocks: # Create new lock and add to list, if needed Task._tableLocks[ftName] = threading.Lock() - + # No lock protection, anybody can do this any time lock = Task._tableLocks[ftName] # Logging.info("Acquiring lock: {}, {}".format(ftName, lock)) @@ -1538,7 +1543,7 @@ class Task(): def unlockTable(self, ftName): # print('_' + ftName + ">> ", end="", flush=True) - with Task._lock: + with Task._lock: if not ftName in self._tableLocks: raise RuntimeError("Corrupt state, no such lock") lock = Task._tableLocks[ftName] @@ -1588,11 +1593,11 @@ class ExecutionStats: t[0] += 1 # index 0 has the "total" execution times if isSuccess: t[1] += 1 # index 1 has the "success" execution times - if eno != None: + if eno != None: if klassName not in self._errors: self._errors[klassName] = {} errors = self._errors[klassName] - errors[eno] = errors[eno]+1 if eno in errors else 1 + errors[eno] = errors[eno] + 1 if eno in errors else 1 def beginTaskType(self, klassName): with self._lock: @@ -1615,7 +1620,7 @@ class ExecutionStats: Logging.info( "----------------------------------------------------------------------") Logging.info( - "| Crash_Gen test {}, with the following stats:". format( + "| Crash_Gen test {}, with the following stats:".format( "FAILED (reason: {})".format( self._failureReason) if self._failed else "SUCCEEDED")) Logging.info("| Task Execution Times (success/total):") @@ -1628,7 +1633,7 @@ class ExecutionStats: # print("errors = {}".format(errors)) errStrs = ["0x{:X}:{}".format(eno, n) for (eno, n) in errors.items()] # print("error strings = {}".format(errStrs)) - errStr = ", ".join(errStrs) + errStr = ", ".join(errStrs) Logging.info("| {0:<24}: {1}/{2} (Errors: {3})".format(k, n[1], n[0], errStr)) Logging.info( @@ -1647,8 +1652,8 @@ class ExecutionStats: Logging.info("| Top numbers written: {}".format(TaskExecutor.getBoundedList())) Logging.info("| Active DB Native Connections (now): {}".format(DbConnNative.totalConnections)) Logging.info("| Longest native query time: {:.3f} seconds, started: {}". - format(MyTDSql.longestQueryTime, - time.strftime("%x %X", time.localtime(MyTDSql.lqStartTime))) ) + format(MyTDSql.longestQueryTime, + time.strftime("%x %X", time.localtime(MyTDSql.lqStartTime)))) Logging.info("| Longest native query: {}".format(MyTDSql.longestQuery)) Logging.info( "----------------------------------------------------------------------") @@ -1662,12 +1667,12 @@ class StateTransitionTask(Task): _baseTableNumber = None - _endState = None # TODO: no longter used? + _endState = None # TODO: no longter used? @classmethod def getInfo(cls): # each sub class should supply their own information raise RuntimeError("Overriding method expected") - + @classmethod def getEndState(cls): # TODO: optimize by calling it fewer times raise RuntimeError("Overriding method expected") @@ -1687,7 +1692,7 @@ class StateTransitionTask(Task): @classmethod def getRegTableName(cls, i): - if ( StateTransitionTask._baseTableNumber is None): # Set it one time + if (StateTransitionTask._baseTableNumber is None): # Set it one time StateTransitionTask._baseTableNumber = Dice.throw( 999) if Config.getConfig().dynamic_db_table_names else 0 return "reg_table_{}".format(StateTransitionTask._baseTableNumber + i) @@ -1711,16 +1716,21 @@ class TaskCreateDb(StateTransitionTask): repStr = "" if Config.getConfig().num_replicas != 1: # numReplica = Dice.throw(Settings.getConfig().max_replicas) + 1 # 1,2 ... N - numReplica = Config.getConfig().num_replicas # fixed, always + numReplica = Config.getConfig().num_replicas # fixed, always repStr = "replica {}".format(numReplica) - updatePostfix = "" if Config.getConfig().verify_data else "" # allow update only when "verify data" is active , 3.0 version default is update 1 - vg_nums = random.randint(1,8) - cache_model = Dice.choice(['none' , 'last_row' , 'last_value' , 'both']) - buffer = random.randint(3,128) + updatePostfix = "" if Config.getConfig().verify_data else "" # allow update only when "verify data" is active , 3.0 version default is update 1 + vg_nums = random.randint(1, 8) + cache_model = Dice.choice(['none', 'last_row', 'last_value', 'both']) + buffer = random.randint(3, 128) dbName = self._db.getName() - self.execWtSql(wt, "create database {} {} {} vgroups {} cachemodel '{}' buffer {} ".format(dbName, repStr, updatePostfix, vg_nums, cache_model,buffer ) ) + self.execWtSql(wt, "create database {} {} {} vgroups {} cachemodel '{}' buffer {} ".format(dbName, repStr, + updatePostfix, + vg_nums, + cache_model, + buffer)) if dbName == "db_0" and Config.getConfig().use_shadow_db: - self.execWtSql(wt, "create database {} {} {} ".format("db_s", repStr, updatePostfix ) ) + self.execWtSql(wt, "create database {} {} {} ".format("db_s", repStr, updatePostfix)) + class TaskDropDb(StateTransitionTask): @classmethod @@ -1732,19 +1742,20 @@ class TaskDropDb(StateTransitionTask): return state.canDropDb() def _executeInternal(self, te: TaskExecutor, wt: WorkerThread): - + try: - self.queryWtSql(wt, "drop database {}".format(self._db.getName())) # drop database maybe failed ,because topic exists + self.queryWtSql(wt, "drop database {}".format( + self._db.getName())) # drop database maybe failed ,because topic exists except taos.error.ProgrammingError as err: errno = Helper.convertErrno(err.errno) - if errno in [0x0203]: # drop maybe failed + if errno in [0x0203]: # drop maybe failed pass Logging.debug("[OPS] database dropped at {}".format(time.time())) class TaskCreateStream(StateTransitionTask): - + @classmethod def getEndState(cls): return StateHasData() @@ -1755,39 +1766,40 @@ class TaskCreateStream(StateTransitionTask): def _executeInternal(self, te: TaskExecutor, wt: WorkerThread): dbname = self._db.getName() - - sub_stream_name = dbname+ '_sub_stream' + + sub_stream_name = dbname + '_sub_stream' sub_stream_tb_name = 'stream_tb_sub' - super_stream_name = dbname+ '_super_stream' + super_stream_name = dbname + '_super_stream' super_stream_tb_name = 'stream_tb_super' if not self._db.exists(wt.getDbConn()): Logging.debug("Skipping task, no DB yet") return - sTable = self._db.getFixedSuperTable() # type: TdSuperTable + sTable = self._db.getFixedSuperTable() # type: TdSuperTable # wt.execSql("use db") # should always be in place - stbname =sTable.getName() + stbname = sTable.getName() sub_tables = sTable.getRegTables(wt.getDbConn()) - aggExpr = Dice.choice([ - 'count(*)', 'avg(speed)', 'sum(speed)', 'stddev(speed)','min(speed)', 'max(speed)', 'first(speed)', 'last(speed)', - 'apercentile(speed, 10)', 'last_row(*)', 'twa(speed)']) - - stream_sql = '' # set default value + aggExpr = Dice.choice([ + 'count(*)', 'avg(speed)', 'sum(speed)', 'stddev(speed)', 'min(speed)', 'max(speed)', 'first(speed)', + 'last(speed)', + 'apercentile(speed, 10)', 'last_row(*)', 'twa(speed)']) + + stream_sql = '' # set default value if sub_tables: sub_tbname = sub_tables[0] # create stream with query above sub_table - stream_sql = 'create stream {} into {}.{} as select {}, avg(speed) FROM {}.{} PARTITION BY tbname INTERVAL(5s) SLIDING(3s) '.\ - format(sub_stream_name,dbname,sub_stream_tb_name ,aggExpr,dbname,sub_tbname) + stream_sql = 'create stream {} into {}.{} as select {}, avg(speed) FROM {}.{} PARTITION BY tbname INTERVAL(5s) SLIDING(3s) '. \ + format(sub_stream_name, dbname, sub_stream_tb_name, aggExpr, dbname, sub_tbname) else: - stream_sql = 'create stream {} into {}.{} as select {}, avg(speed) FROM {}.{} PARTITION BY tbname INTERVAL(5s) SLIDING(3s) '.\ - format(super_stream_name,dbname,super_stream_tb_name,aggExpr, dbname,stbname) + stream_sql = 'create stream {} into {}.{} as select {}, avg(speed) FROM {}.{} PARTITION BY tbname INTERVAL(5s) SLIDING(3s) '. \ + format(super_stream_name, dbname, super_stream_tb_name, aggExpr, dbname, stbname) self.execWtSql(wt, stream_sql) Logging.debug("[OPS] stream is creating at {}".format(time.time())) class TaskCreateTopic(StateTransitionTask): - + @classmethod def getEndState(cls): return StateHasData() @@ -1798,40 +1810,46 @@ class TaskCreateTopic(StateTransitionTask): def _executeInternal(self, te: TaskExecutor, wt: WorkerThread): dbname = self._db.getName() - - sub_topic_name = dbname+ '_sub_topic' - super_topic_name = dbname+ '_super_topic' - stable_topic = dbname+ '_stable_topic' - db_topic = 'database_' + dbname+ '_topics' + + sub_topic_name = dbname + '_sub_topic' + super_topic_name = dbname + '_super_topic' + stable_topic = dbname + '_stable_topic' + db_topic = 'database_' + dbname + '_topics' if not self._db.exists(wt.getDbConn()): Logging.debug("Skipping task, no DB yet") return - sTable = self._db.getFixedSuperTable() # type: TdSuperTable + sTable = self._db.getFixedSuperTable() # type: TdSuperTable # wt.execSql("use db") # should always be in place # create topic if not exists topic_ctb_column as select ts, c1, c2, c3 from stb1; - stbname =sTable.getName() + stbname = sTable.getName() sub_tables = sTable.getRegTables(wt.getDbConn()) - scalarExpr = Dice.choice([ '*','speed','color','abs(speed)','acos(speed)','asin(speed)','atan(speed)','ceil(speed)','cos(speed)','cos(speed)', - 'floor(speed)','log(speed,2)','pow(speed,2)','round(speed)','sin(speed)','sqrt(speed)','char_length(color)','concat(color,color)', - 'concat_ws(" ", color,color," ")','length(color)', 'lower(color)', 'ltrim(color)','substr(color , 2)','upper(color)','cast(speed as double)', - 'cast(ts as bigint)']) + scalarExpr = Dice.choice( + ['*', 'speed', 'color', 'abs(speed)', 'acos(speed)', 'asin(speed)', 'atan(speed)', 'ceil(speed)', + 'cos(speed)', 'cos(speed)', + 'floor(speed)', 'log(speed,2)', 'pow(speed,2)', 'round(speed)', 'sin(speed)', 'sqrt(speed)', + 'char_length(color)', 'concat(color,color)', + 'concat_ws(" ", color,color," ")', 'length(color)', 'lower(color)', 'ltrim(color)', 'substr(color , 2)', + 'upper(color)', 'cast(speed as double)', + 'cast(ts as bigint)']) topic_sql = '' # set default value - if Dice.throw(3)==0: # create topic : source data from sub query - if sub_tables: # if not empty + if Dice.throw(3) == 0: # create topic : source data from sub query + if sub_tables: # if not empty sub_tbname = sub_tables[0] # create topic : source data from sub query of sub stable - topic_sql = 'create topic {} as select {} FROM {}.{} ; '.format(sub_topic_name,scalarExpr,dbname,sub_tbname) - + topic_sql = 'create topic {} as select {} FROM {}.{} ; '.format(sub_topic_name, scalarExpr, dbname, + sub_tbname) + else: # create topic : source data from sub query of stable - topic_sql = 'create topic {} as select {} FROM {}.{} '.format(super_topic_name,scalarExpr, dbname,stbname) - elif Dice.throw(3)==1: # create topic : source data from super table - topic_sql = 'create topic {} AS STABLE {}.{} '.format(stable_topic,dbname,stbname) - - elif Dice.throw(3)==2: # create topic : source data from whole database - topic_sql = 'create topic {} AS DATABASE {} '.format(db_topic,dbname) + topic_sql = 'create topic {} as select {} FROM {}.{} '.format(super_topic_name, scalarExpr, dbname, + stbname) + elif Dice.throw(3) == 1: # create topic : source data from super table + topic_sql = 'create topic {} AS STABLE {}.{} '.format(stable_topic, dbname, stbname) + + elif Dice.throw(3) == 2: # create topic : source data from whole database + topic_sql = 'create topic {} AS DATABASE {} '.format(db_topic, dbname) else: pass @@ -1840,8 +1858,9 @@ class TaskCreateTopic(StateTransitionTask): self.execWtSql(wt, topic_sql) Logging.debug("[OPS] db topic is creating at {}".format(time.time())) + class TaskDropTopics(StateTransitionTask): - + @classmethod def getEndState(cls): return StateHasData() @@ -1852,21 +1871,21 @@ class TaskDropTopics(StateTransitionTask): def _executeInternal(self, te: TaskExecutor, wt: WorkerThread): dbname = self._db.getName() - if not self._db.exists(wt.getDbConn()): Logging.debug("Skipping task, no DB yet") return - sTable = self._db.getFixedSuperTable() # type: TdSuperTable + sTable = self._db.getFixedSuperTable() # type: TdSuperTable # wt.execSql("use db") # should always be in place tblName = sTable.getName() if sTable.hasTopics(wt.getDbConn()): - sTable.dropTopics(wt.getDbConn(),dbname,None) # drop topics of database - sTable.dropTopics(wt.getDbConn(),dbname,tblName) # drop topics of stable + sTable.dropTopics(wt.getDbConn(), dbname, None) # drop topics of database + sTable.dropTopics(wt.getDbConn(), dbname, tblName) # drop topics of stable + class TaskDropStreams(StateTransitionTask): - + @classmethod def getEndState(cls): return StateHasData() @@ -1877,20 +1896,20 @@ class TaskDropStreams(StateTransitionTask): def _executeInternal(self, te: TaskExecutor, wt: WorkerThread): # dbname = self._db.getName() - if not self._db.exists(wt.getDbConn()): Logging.debug("Skipping task, no DB yet") return - sTable = self._db.getFixedSuperTable() # type: TdSuperTable + sTable = self._db.getFixedSuperTable() # type: TdSuperTable # wt.execSql("use db") # should always be in place # tblName = sTable.getName() if sTable.hasStreams(wt.getDbConn()): sTable.dropStreams(wt.getDbConn()) # drop stream of database + class TaskDropStreamTables(StateTransitionTask): - + @classmethod def getEndState(cls): return StateHasData() @@ -1901,42 +1920,42 @@ class TaskDropStreamTables(StateTransitionTask): def _executeInternal(self, te: TaskExecutor, wt: WorkerThread): # dbname = self._db.getName() - if not self._db.exists(wt.getDbConn()): Logging.debug("Skipping task, no DB yet") return - sTable = self._db.getFixedSuperTable() # type: TdSuperTable - wt.execSql("use db") # should always be in place + sTable = self._db.getFixedSuperTable() # type: TdSuperTable + wt.execSql("use db") # should always be in place # tblName = sTable.getName() if sTable.hasStreamTables(wt.getDbConn()): - sTable.dropStreamTables(wt.getDbConn()) # drop stream tables + sTable.dropStreamTables(wt.getDbConn()) # drop stream tables + class TaskCreateConsumers(StateTransitionTask): - + @classmethod def getEndState(cls): return StateHasData() @classmethod def canBeginFrom(cls, state: AnyState): - return state.canCreateConsumers() + return state.canCreateConsumers() def _executeInternal(self, te: TaskExecutor, wt: WorkerThread): - if Config.getConfig().connector_type == 'native': - - sTable = self._db.getFixedSuperTable() # type: TdSuperTable + if Config.getConfig().connector_type == 'native': + + sTable = self._db.getFixedSuperTable() # type: TdSuperTable # wt.execSql("use db") # should always be in place if sTable.hasTopics(wt.getDbConn()): - sTable.createConsumer(wt.getDbConn(),random.randint(1,10)) + sTable.createConsumer(wt.getDbConn(), random.randint(1, 10)) pass else: print(" restful not support tmq consumers") - return + return + - class TaskCreateSuperTable(StateTransitionTask): @classmethod def getEndState(cls): @@ -1951,9 +1970,9 @@ class TaskCreateSuperTable(StateTransitionTask): Logging.debug("Skipping task, no DB yet") return - sTable = self._db.getFixedSuperTable() # type: TdSuperTable + sTable = self._db.getFixedSuperTable() # type: TdSuperTable # wt.execSql("use db") # should always be in place - + sTable.create(wt.getDbConn(), {'ts': TdDataType.TIMESTAMP, 'speed': TdDataType.INT, 'color': TdDataType.BINARY16}, { 'b': TdDataType.BINARY200, 'f': TdDataType.FLOAT}, @@ -1974,11 +1993,10 @@ class TdSuperTable: def getName(self): return self._stName - - def drop(self, dbc, skipCheck = False): + def drop(self, dbc, skipCheck=False): dbName = self._dbName - if self.exists(dbc) : # if myself exists - fullTableName = dbName + '.' + self._stName + if self.exists(dbc): # if myself exists + fullTableName = dbName + '.' + self._stName dbc.execute("DROP TABLE {}".format(fullTableName)) else: if not skipCheck: @@ -1989,64 +2007,55 @@ class TdSuperTable: return dbc.existsSuperTable(self._stName) # TODO: odd semantic, create() method is usually static? - def create(self, dbc, cols: TdColumns, tags: TdTags, dropIfExists = False): + def create(self, dbc, cols: TdColumns, tags: TdTags, dropIfExists=False): '''Creating a super table''' dbName = self._dbName dbc.execute("USE " + dbName) - fullTableName = dbName + '.' + self._stName + fullTableName = dbName + '.' + self._stName if dbc.existsSuperTable(self._stName): - if dropIfExists: - dbc.execute("DROP TABLE {}".format(fullTableName)) - - else: # error + if dropIfExists: + dbc.execute("DROP TABLE {}".format(fullTableName)) + + else: # error raise CrashGenError("Cannot create super table, already exists: {}".format(self._stName)) # Now let's create sql = "CREATE TABLE {} ({})".format( fullTableName, - ",".join(['%s %s'%(k,v.value) for (k,v) in cols.items()])) - if tags : + ",".join(['%s %s' % (k, v.value) for (k, v) in cols.items()])) + if tags: sql += " TAGS ({})".format( - ",".join(['%s %s'%(k,v.value) for (k,v) in tags.items()]) - ) + ",".join(['%s %s' % (k, v.value) for (k, v) in tags.items()]) + ) else: sql += " TAGS (dummy int) " - dbc.execute(sql) + dbc.execute(sql) + + def createConsumer(self, dbc, Consumer_nums): - def createConsumer(self, dbc,Consumer_nums): - def generateConsumer(current_topic_list): - conf = TaosTmqConf() - conf.set("group.id", "tg2") - conf.set("td.connect.user", "root") - conf.set("td.connect.pass", "taosdata") -# conf.set("enable.auto.commit", "true") -# def tmq_commit_cb_print(tmq, resp, offset, param=None): -# print(f"commit: {resp}, tmq: {tmq}, offset: {offset}, param: {param}") -# conf.set_auto_commit_cb(tmq_commit_cb_print, None) - consumer = conf.new_consumer() - topic_list = TaosTmqList() + consumer = Consumer({"group.id": "tg2", "td.connect.user": "root", "td.connect.pass": "taosdata"}) + topic_list = [] for topic in current_topic_list: topic_list.append(topic) - try: - consumer.subscribe(topic_list) - except TmqError as e : - pass + + consumer.subscribe(topic_list) # consumer with random work life time_start = time.time() while 1: - res = consumer.poll(1000) - if time.time() - time_start >random.randint(5,50) : + res = consumer.poll(1) + consumer.commit(res) + if time.time() - time_start > random.randint(5, 50): break try: consumer.unsubscribe() - except TmqError as e : + except TmqError as e: pass return - + # mulit Consumer current_topic_list = self.getTopicLists(dbc) for i in range(Consumer_nums): @@ -2067,84 +2076,86 @@ class TdSuperTable: def getRegTables(self, dbc: DbConn): dbName = self._dbName try: - dbc.query("select distinct TBNAME from {}.{}".format(dbName, self._stName)) # TODO: analyze result set later - except taos.error.ProgrammingError as err: - errno2 = Helper.convertErrno(err.errno) + dbc.query("select distinct TBNAME from {}.{}".format(dbName, + self._stName)) # TODO: analyze result set later + except taos.error.ProgrammingError as err: + errno2 = Helper.convertErrno(err.errno) Logging.debug("[=] Failed to get tables from super table: errno=0x{:X}, msg: {}".format(errno2, err)) raise qr = dbc.getQueryResult() - return [v[0] for v in qr] # list transformation, ref: https://stackoverflow.com/questions/643823/python-list-transformation + return [v[0] for v in + qr] # list transformation, ref: https://stackoverflow.com/questions/643823/python-list-transformation def hasRegTables(self, dbc: DbConn): - + if dbc.existsSuperTable(self._stName): return dbc.query("SELECT * FROM {}.{}".format(self._dbName, self._stName)) > 0 else: return False - def hasStreamTables(self,dbc: DbConn): - + def hasStreamTables(self, dbc: DbConn): + return dbc.query("show {}.stables like 'stream_tb%'".format(self._dbName)) > 0 - def hasStreams(self,dbc: DbConn): + def hasStreams(self, dbc: DbConn): return dbc.query("show streams") > 0 - def hasTopics(self,dbc: DbConn): - + def hasTopics(self, dbc: DbConn): + return dbc.query("show topics") > 0 - def dropTopics(self,dbc: DbConn , dbname=None,stb_name=None): + def dropTopics(self, dbc: DbConn, dbname=None, stb_name=None): dbc.query("show topics ") topics = dbc.getQueryResult() - if dbname !=None and stb_name == None : - + if dbname != None and stb_name == None: + for topic in topics: if dbname in topic[0] and topic[0].startswith("database"): try: dbc.execute('drop topic {}'.format(topic[0])) - Logging.debug("[OPS] topic {} is droping at {}".format(topic,time.time())) - except taos.error.ProgrammingError as err: + Logging.debug("[OPS] topic {} is droping at {}".format(topic, time.time())) + except taos.error.ProgrammingError as err: errno = Helper.convertErrno(err.errno) - if errno in [0x03EB]: # Topic subscribed cannot be dropped - pass + if errno in [0x03EB]: # Topic subscribed cannot be dropped + pass # for subsript in subscriptions: - + else: pass pass return True - elif dbname !=None and stb_name!= None: + elif dbname != None and stb_name != None: for topic in topics: if topic[0].startswith(self._dbName) and topic[0].endswith('topic'): dbc.execute('drop topic {}'.format(topic[0])) - Logging.debug("[OPS] topic {} is droping at {}".format(topic,time.time())) + Logging.debug("[OPS] topic {} is droping at {}".format(topic, time.time())) return True else: return True pass - def dropStreams(self,dbc:DbConn): + def dropStreams(self, dbc: DbConn): dbc.query("show streams ") Streams = dbc.getQueryResult() for Stream in Streams: if Stream[0].startswith(self._dbName): dbc.execute('drop stream {}'.format(Stream[0])) - + return not dbc.query("show streams ") > 0 def dropStreamTables(self, dbc: DbConn): dbc.query("show {}.stables like 'stream_tb%'".format(self._dbName)) - + StreamTables = dbc.getQueryResult() - for StreamTable in StreamTables: + for StreamTable in StreamTables: if self.dropStreams(dbc): - dbc.execute('drop table {}.{}'.format(self._dbName,StreamTable[0])) - + dbc.execute('drop table {}.{}'.format(self._dbName, StreamTable[0])) + return not dbc.query("show {}.stables like 'stream_tb%'".format(self._dbName)) def ensureRegTable(self, task: Optional[Task], dbc: DbConn, regTableName: str): @@ -2155,16 +2166,16 @@ class TdSuperTable: ''' dbName = self._dbName sql = "select tbname from {}.{} where tbname in ('{}')".format(dbName, self._stName, regTableName) - if dbc.query(sql) >= 1 : # reg table exists already + if dbc.query(sql) >= 1: # reg table exists already return # acquire a lock first, so as to be able to *verify*. More details in TD-1471 - fullTableName = dbName + '.' + regTableName + fullTableName = dbName + '.' + regTableName if task is not None: # Somethime thie operation is requested on behalf of a "task" # Logging.info("Locking table for creation: {}".format(fullTableName)) - task.lockTable(fullTableName) # in which case we'll lock this table to ensure serialized access + task.lockTable(fullTableName) # in which case we'll lock this table to ensure serialized access # Logging.info("Table locked for creation".format(fullTableName)) - Progress.emit(Progress.CREATE_TABLE_ATTEMPT) # ATTEMPT to create a new table + Progress.emit(Progress.CREATE_TABLE_ATTEMPT) # ATTEMPT to create a new table # print("(" + fullTableName[-3:] + ")", end="", flush=True) try: sql = "CREATE TABLE {} USING {}.{} tags ({})".format( @@ -2176,17 +2187,17 @@ class TdSuperTable: finally: if task is not None: # Logging.info("Unlocking table after creation: {}".format(fullTableName)) - task.unlockTable(fullTableName) # no matter what + task.unlockTable(fullTableName) # no matter what # Logging.info("Table unlocked after creation: {}".format(fullTableName)) - def _getTagStrForSql(self, dbc) : + def _getTagStrForSql(self, dbc): tags = self._getTags(dbc) tagStrs = [] - for tagName in tags: + for tagName in tags: tagType = tags[tagName] if tagType == 'BINARY': tagStrs.append("'Beijing-Shanghai-LosAngeles'") - elif tagType== 'VARCHAR': + elif tagType == 'VARCHAR': tagStrs.append("'London-Paris-Berlin'") elif tagType == 'FLOAT': tagStrs.append('9.9') @@ -2200,12 +2211,12 @@ class TdSuperTable: dbc.query("DESCRIBE {}.{}".format(self._dbName, self._stName)) stCols = dbc.getQueryResult() # print(stCols) - ret = {row[0]:row[1] for row in stCols if row[3]=='TAG'} # name:type + ret = {row[0]: row[1] for row in stCols if row[3] == 'TAG'} # name:type # print("Tags retrieved: {}".format(ret)) return ret def addTag(self, dbc, tagName, tagType): - if tagName in self._getTags(dbc): # already + if tagName in self._getTags(dbc): # already return # sTable.addTag("extraTag", "int") sql = "alter table {}.{} add tag {} {}".format( @@ -2213,33 +2224,33 @@ class TdSuperTable: dbc.execute(sql) def dropTag(self, dbc, tagName): - if not tagName in self._getTags(dbc): # don't have this tag + if not tagName in self._getTags(dbc): # don't have this tag return sql = "alter table {}.{} drop tag {}".format(self._dbName, self._stName, tagName) dbc.execute(sql) def changeTag(self, dbc, oldTag, newTag): tags = self._getTags(dbc) - if not oldTag in tags: # don't have this tag + if not oldTag in tags: # don't have this tag return - if newTag in tags: # already have this tag + if newTag in tags: # already have this tag return sql = "alter table {}.{} change tag {} {}".format(self._dbName, self._stName, oldTag, newTag) dbc.execute(sql) def generateQueries(self, dbc: DbConn) -> List[SqlQuery]: ''' Generate queries to test/exercise this super table ''' - ret = [] # type: List[SqlQuery] + ret = [] # type: List[SqlQuery] for rTbName in self.getRegTables(dbc): # regular tables - - filterExpr = Dice.choice([ # TODO: add various kind of WHERE conditions + + filterExpr = Dice.choice([ # TODO: add various kind of WHERE conditions None ]) # Run the query against the regular table first - doAggr = (Dice.throw(2) == 0) # 1 in 2 chance - if not doAggr: # don't do aggregate query, just simple one + doAggr = (Dice.throw(2) == 0) # 1 in 2 chance + if not doAggr: # don't do aggregate query, just simple one commonExpr = Dice.choice([ '*', 'abs(speed)', @@ -2256,7 +2267,7 @@ class TdSuperTable: 'sin(speed)', 'sqrt(speed)', 'char_length(color)', - 'concat(color,color)', + 'concat(color,color)', 'concat_ws(" ", color,color," ")', 'length(color)', 'lower(color)', @@ -2276,26 +2287,26 @@ class TdSuperTable: 'distinct(color)' ] ) - ret.append(SqlQuery( # reg table + ret.append(SqlQuery( # reg table "select {} from {}.{}".format(commonExpr, self._dbName, rTbName))) - ret.append(SqlQuery( # super table + ret.append(SqlQuery( # super table "select {} from {}.{}".format(commonExpr, self._dbName, self.getName()))) - else: # Aggregate query - aggExpr = Dice.choice([ + else: # Aggregate query + aggExpr = Dice.choice([ 'count(*)', 'avg(speed)', # 'twa(speed)', # TODO: this one REQUIRES a where statement, not reasonable - 'sum(speed)', - 'stddev(speed)', + 'sum(speed)', + 'stddev(speed)', # SELECTOR functions - 'min(speed)', - 'max(speed)', - 'first(speed)', + 'min(speed)', + 'max(speed)', + 'first(speed)', 'last(speed)', - 'top(speed, 50)', # TODO: not supported? - 'bottom(speed, 50)', # TODO: not supported? - 'apercentile(speed, 10)', # TODO: TD-1316 - 'last_row(*)', # TODO: commented out per TD-3231, we should re-create + 'top(speed, 50)', # TODO: not supported? + 'bottom(speed, 50)', # TODO: not supported? + 'apercentile(speed, 10)', # TODO: TD-1316 + 'last_row(*)', # TODO: commented out per TD-3231, we should re-create # Transformation Functions # 'diff(speed)', # TODO: no supported?! 'spread(speed)', @@ -2313,21 +2324,21 @@ class TdSuperTable: 'sample(speed,5)', 'STATECOUNT(speed,"LT",1)', 'STATEDURATION(speed,"LT",1)', - 'twa(speed)' - - ]) # TODO: add more from 'top' + 'twa(speed)' + + ]) # TODO: add more from 'top' - # if aggExpr not in ['stddev(speed)']: # STDDEV not valid for super tables?! (Done in TD-1049) sql = "select {} from {}.{}".format(aggExpr, self._dbName, self.getName()) - if Dice.throw(3) == 0: # 1 in X chance - partion_expr = Dice.choice(['color','tbname']) + if Dice.throw(3) == 0: # 1 in X chance + partion_expr = Dice.choice(['color', 'tbname']) sql = sql + ' partition BY ' + partion_expr + ' order by ' + partion_expr Progress.emit(Progress.QUERY_GROUP_BY) # Logging.info("Executing GROUP-BY query: " + sql) ret.append(SqlQuery(sql)) - return ret + return ret + class TaskReadData(StateTransitionTask): @classmethod @@ -2345,60 +2356,61 @@ class TaskReadData(StateTransitionTask): def _reconnectIfNeeded(self, wt): # 1 in 20 chance, simulate a broken connection, only if service stable (not restarting) - if random.randrange(20)==0: # and self._canRestartService(): # TODO: break connection in all situations + if random.randrange(20) == 0: # and self._canRestartService(): # TODO: break connection in all situations # Logging.info("Attempting to reconnect to server") # TODO: change to DEBUG - Progress.emit(Progress.SERVICE_RECONNECT_START) + Progress.emit(Progress.SERVICE_RECONNECT_START) try: wt.getDbConn().close() wt.getDbConn().open() - except ConnectionError as err: # may fail + except ConnectionError as err: # may fail if not gSvcMgr: Logging.error("Failed to reconnect in client-only mode") - raise # Not OK if we are running in client-only mode - if gSvcMgr.isRunning(): # may have race conditon, but low prob, due to + raise # Not OK if we are running in client-only mode + if gSvcMgr.isRunning(): # may have race conditon, but low prob, due to Logging.error("Failed to reconnect when managed server is running") - raise # Not OK if we are running normally + raise # Not OK if we are running normally - Progress.emit(Progress.SERVICE_RECONNECT_FAILURE) + Progress.emit(Progress.SERVICE_RECONNECT_FAILURE) # Logging.info("Ignoring DB reconnect error") # print("_r", end="", flush=True) - Progress.emit(Progress.SERVICE_RECONNECT_SUCCESS) + Progress.emit(Progress.SERVICE_RECONNECT_SUCCESS) # The above might have taken a lot of time, service might be running # by now, causing error below to be incorrectly handled due to timing issue - return # TODO: fix server restart status race condtion - + return # TODO: fix server restart status race condtion def _executeInternal(self, te: TaskExecutor, wt: WorkerThread): self._reconnectIfNeeded(wt) dbc = wt.getDbConn() sTable = self._db.getFixedSuperTable() - + for q in sTable.generateQueries(dbc): # regular tables try: sql = q.getSql() # if 'GROUP BY' in sql: # Logging.info("Executing GROUP-BY query: " + sql) dbc.execute(sql) - except taos.error.ProgrammingError as err: + except taos.error.ProgrammingError as err: errno2 = Helper.convertErrno(err.errno) Logging.debug("[=] Read Failure: errno=0x{:X}, msg: {}, SQL: {}".format(errno2, err, dbc.getLastSql())) raise + class SqlQuery: @classmethod def buildRandom(cls, db: Database): '''Build a random query against a certain database''' - + dbName = db.getName() - def __init__(self, sql:str = None): + def __init__(self, sql: str = None): self._sql = sql def getSql(self): return self._sql - + + class TaskDropSuperTable(StateTransitionTask): @classmethod def getEndState(cls): @@ -2421,7 +2433,7 @@ class TaskDropSuperTable(StateTransitionTask): regTableName = self.getRegTableName(i) # "db.reg_table_{}".format(i) try: self.execWtSql(wt, "drop table {}.{}". - format(self._db.getName(), regTableName)) # nRows always 0, like MySQL + format(self._db.getName(), regTableName)) # nRows always 0, like MySQL except taos.error.ProgrammingError as err: # correcting for strange error number scheme errno2 = Helper.convertErrno(err.errno) @@ -2429,7 +2441,6 @@ class TaskDropSuperTable(StateTransitionTask): isSuccess = False Logging.debug("[DB] Acceptable error when dropping a table") continue # try to delete next regular table - if (not tickOutput): tickOutput = True # Print only one time @@ -2441,8 +2452,6 @@ class TaskDropSuperTable(StateTransitionTask): # Drop the super table itself tblName = self._db.getFixedSuperTableName() self.execWtSql(wt, "drop table {}.{}".format(self._db.getName(), tblName)) - - class TaskAlterTags(StateTransitionTask): @@ -2472,6 +2481,7 @@ class TaskAlterTags(StateTransitionTask): sTable.changeTag(dbc, "extraTag", "newTag") # sql = "alter table db.{} change tag extraTag newTag".format(tblName) + class TaskRestartService(StateTransitionTask): _isRunning = False _classLock = threading.Lock() @@ -2484,11 +2494,12 @@ class TaskRestartService(StateTransitionTask): def canBeginFrom(cls, state: AnyState): if Config.getConfig().auto_start_service: return state.canDropFixedSuperTable() # Basicallly when we have the super table - return False # don't run this otherwise + return False # don't run this otherwise CHANCE_TO_RESTART_SERVICE = 200 + def _executeInternal(self, te: TaskExecutor, wt: WorkerThread): - if not Config.getConfig().auto_start_service: # only execute when we are in -a mode + if not Config.getConfig().auto_start_service: # only execute when we are in -a mode print("_a", end="", flush=True) return @@ -2498,20 +2509,22 @@ class TaskRestartService(StateTransitionTask): return self._isRunning = True - if Dice.throw(self.CHANCE_TO_RESTART_SERVICE) == 0: # 1 in N chance + if Dice.throw(self.CHANCE_TO_RESTART_SERVICE) == 0: # 1 in N chance dbc = wt.getDbConn() - dbc.execute("select * from information_schema.ins_databases") # simple delay, align timing with other workers + dbc.execute( + "select * from information_schema.ins_databases") # simple delay, align timing with other workers gSvcMgr.restart() self._isRunning = False + class TaskAddData(StateTransitionTask): # Track which table is being actively worked on activeTable: Set[int] = set() # We use these two files to record operations to DB, useful for power-off tests - fAddLogReady = None # type: Optional[io.TextIOWrapper] - fAddLogDone = None # type: Optional[io.TextIOWrapper] + fAddLogReady = None # type: Optional[io.TextIOWrapper] + fAddLogDone = None # type: Optional[io.TextIOWrapper] @classmethod def prepToRecordOps(cls): @@ -2532,12 +2545,12 @@ class TaskAddData(StateTransitionTask): def canBeginFrom(cls, state: AnyState): return state.canAddData() - def _lockTableIfNeeded(self, fullTableName, extraMsg = ''): + def _lockTableIfNeeded(self, fullTableName, extraMsg=''): if Config.getConfig().verify_data: # Logging.info("Locking table: {}".format(fullTableName)) - self.lockTable(fullTableName) + self.lockTable(fullTableName) # Logging.info("Table locked {}: {}".format(extraMsg, fullTableName)) - # print("_w" + str(nextInt % 100), end="", flush=True) # Trace what was written + # print("_w" + str(nextInt % 100), end="", flush=True) # Trace what was written else: # Logging.info("Skipping locking table") pass @@ -2545,15 +2558,15 @@ class TaskAddData(StateTransitionTask): def _unlockTableIfNeeded(self, fullTableName): if Config.getConfig().verify_data: # Logging.info("Unlocking table: {}".format(fullTableName)) - self.unlockTable(fullTableName) + self.unlockTable(fullTableName) # Logging.info("Table unlocked: {}".format(fullTableName)) else: pass # Logging.info("Skipping unlocking table") - def _addDataInBatch(self, db, dbc, regTableName, te: TaskExecutor): - numRecords = self.LARGE_NUMBER_OF_RECORDS if Config.getConfig().larger_data else self.SMALL_NUMBER_OF_RECORDS - + def _addDataInBatch(self, db, dbc, regTableName, te: TaskExecutor): + numRecords = self.LARGE_NUMBER_OF_RECORDS if Config.getConfig().larger_data else self.SMALL_NUMBER_OF_RECORDS + fullTableName = db.getName() + '.' + regTableName self._lockTableIfNeeded(fullTableName, 'batch') @@ -2571,10 +2584,8 @@ class TaskAddData(StateTransitionTask): # Logging.info("Data added in batch: {}".format(sql)) self._unlockTableIfNeeded(fullTableName) - - - def _addData(self, db: Database, dbc, regTableName, te: TaskExecutor): # implied: NOT in batches - numRecords = self.LARGE_NUMBER_OF_RECORDS if Config.getConfig().larger_data else self.SMALL_NUMBER_OF_RECORDS + def _addData(self, db: Database, dbc, regTableName, te: TaskExecutor): # implied: NOT in batches + numRecords = self.LARGE_NUMBER_OF_RECORDS if Config.getConfig().larger_data else self.SMALL_NUMBER_OF_RECORDS for j in range(numRecords): # number of records per table intToWrite = db.getNextInt() @@ -2587,13 +2598,14 @@ class TaskAddData(StateTransitionTask): self.fAddLogReady.write("Ready to write {} to {}\n".format(intToWrite, regTableName)) self.fAddLogReady.flush() os.fsync(self.fAddLogReady.fileno()) - + # TODO: too ugly trying to lock the table reliably, refactor... fullTableName = db.getName() + '.' + regTableName - self._lockTableIfNeeded(fullTableName) # so that we are verify read-back. TODO: deal with exceptions before unlock - + self._lockTableIfNeeded( + fullTableName) # so that we are verify read-back. TODO: deal with exceptions before unlock + try: - sql = "INSERT INTO {} VALUES ('{}', {}, '{}');".format( # removed: tags ('{}', {}) + sql = "INSERT INTO {} VALUES ('{}', {}, '{}');".format( # removed: tags ('{}', {}) fullTableName, # ds.getFixedSuperTableName(), # ds.getNextBinary(), ds.getNextFloat(), @@ -2604,55 +2616,56 @@ class TaskAddData(StateTransitionTask): intWrote = intToWrite # Quick hack, attach an update statement here. TODO: create an "update" task - if (not Config.getConfig().use_shadow_db) and Dice.throw(5) == 0: # 1 in N chance, plus not using shaddow DB - intToUpdate = db.getNextInt() # Updated, but should not succeed + if (not Config.getConfig().use_shadow_db) and Dice.throw( + 5) == 0: # 1 in N chance, plus not using shaddow DB + intToUpdate = db.getNextInt() # Updated, but should not succeed nextColor = db.getNextColor() - sql = "INSERt INTO {} VALUES ('{}', {}, '{}');".format( # "INSERt" means "update" here - fullTableName, - nextTick, intToUpdate, nextColor) + sql = "INSERt INTO {} VALUES ('{}', {}, '{}');".format( # "INSERt" means "update" here + fullTableName, + nextTick, intToUpdate, nextColor) # sql = "UPDATE {} set speed={}, color='{}' WHERE ts='{}'".format( # fullTableName, db.getNextInt(), db.getNextColor(), nextTick) dbc.execute(sql) - intWrote = intToUpdate # We updated, seems TDengine non-cluster accepts this. + intWrote = intToUpdate # We updated, seems TDengine non-cluster accepts this. - except: # Any exception at all - self._unlockTableIfNeeded(fullTableName) + except: # Any exception at all + self._unlockTableIfNeeded(fullTableName) raise # Now read it back and verify, we might encounter an error if table is dropped - if Config.getConfig().verify_data: # only if command line asks for it + if Config.getConfig().verify_data: # only if command line asks for it try: readBack = dbc.queryScalar("SELECT speed from {}.{} WHERE ts='{}'". - format(db.getName(), regTableName, nextTick)) - if readBack != intWrote : + format(db.getName(), regTableName, nextTick)) + if readBack != intWrote: raise taos.error.ProgrammingError( "Failed to read back same data, wrote: {}, read: {}" .format(intWrote, readBack), 0x999) except taos.error.ProgrammingError as err: errno = Helper.convertErrno(err.errno) - if errno == CrashGenError.INVALID_EMPTY_RESULT: # empty result + if errno == CrashGenError.INVALID_EMPTY_RESULT: # empty result raise taos.error.ProgrammingError( "Failed to read back same data for tick: {}, wrote: {}, read: EMPTY" .format(nextTick, intWrote), errno) - elif errno == CrashGenError.INVALID_MULTIPLE_RESULT : # multiple results + elif errno == CrashGenError.INVALID_MULTIPLE_RESULT: # multiple results raise taos.error.ProgrammingError( "Failed to read back same data for tick: {}, wrote: {}, read: MULTIPLE RESULTS" .format(nextTick, intWrote), errno) - elif errno in [0x218, 0x362]: # table doesn't exist + elif errno in [0x218, 0x362]: # table doesn't exist # do nothing pass else: # Re-throw otherwise raise finally: - self._unlockTableIfNeeded(fullTableName) # Quite ugly, refactor lock/unlock + self._unlockTableIfNeeded(fullTableName) # Quite ugly, refactor lock/unlock # Done with read-back verification, unlock the table now else: - self._unlockTableIfNeeded(fullTableName) + self._unlockTableIfNeeded(fullTableName) - # Successfully wrote the data into the DB, let's record it somehow + # Successfully wrote the data into the DB, let's record it somehow te.recordDataMark(intWrote) if Config.getConfig().record_ops: @@ -2666,17 +2679,17 @@ class TaskAddData(StateTransitionTask): # ds = self._dbManager # Quite DANGEROUS here, may result in multi-thread client access db = self._db dbc = wt.getDbConn() - numTables = self.LARGE_NUMBER_OF_TABLES if Config.getConfig().larger_data else self.SMALL_NUMBER_OF_TABLES + numTables = self.LARGE_NUMBER_OF_TABLES if Config.getConfig().larger_data else self.SMALL_NUMBER_OF_TABLES numRecords = self.LARGE_NUMBER_OF_RECORDS if Config.getConfig().larger_data else self.SMALL_NUMBER_OF_RECORDS - tblSeq = list(range(numTables )) - random.shuffle(tblSeq) # now we have random sequence + tblSeq = list(range(numTables)) + random.shuffle(tblSeq) # now we have random sequence for i in tblSeq: if (i in self.activeTable): # wow already active # print("x", end="", flush=True) # concurrent insertion Progress.emit(Progress.CONCURRENT_INSERTION) else: self.activeTable.add(i) # marking it active - + dbName = db.getName() sTable = db.getFixedSuperTable() regTableName = self.getRegTableName(i) # "db.reg_table_{}".format(i) @@ -2684,21 +2697,22 @@ class TaskAddData(StateTransitionTask): # self._lockTable(fullTableName) # "create table" below. Stop it if the table is "locked" sTable.ensureRegTable(self, wt.getDbConn(), regTableName) # Ensure the table exists # self._unlockTable(fullTableName) - - if Dice.throw(1) == 0: # 1 in 2 chance + + if Dice.throw(1) == 0: # 1 in 2 chance self._addData(db, dbc, regTableName, te) else: self._addDataInBatch(db, dbc, regTableName, te) self.activeTable.discard(i) # not raising an error, unlike remove + class TaskDeleteData(StateTransitionTask): # Track which table is being actively worked on activeTable: Set[int] = set() # We use these two files to record operations to DB, useful for power-off tests - fAddLogReady = None # type: Optional[io.TextIOWrapper] - fAddLogDone = None # type: Optional[io.TextIOWrapper] + fAddLogReady = None # type: Optional[io.TextIOWrapper] + fAddLogDone = None # type: Optional[io.TextIOWrapper] @classmethod def prepToRecordOps(cls): @@ -2719,12 +2733,12 @@ class TaskDeleteData(StateTransitionTask): def canBeginFrom(cls, state: AnyState): return state.canDeleteData() - def _lockTableIfNeeded(self, fullTableName, extraMsg = ''): + def _lockTableIfNeeded(self, fullTableName, extraMsg=''): if Config.getConfig().verify_data: # Logging.info("Locking table: {}".format(fullTableName)) - self.lockTable(fullTableName) + self.lockTable(fullTableName) # Logging.info("Table locked {}: {}".format(extraMsg, fullTableName)) - # print("_w" + str(nextInt % 100), end="", flush=True) # Trace what was written + # print("_w" + str(nextInt % 100), end="", flush=True) # Trace what was written else: # Logging.info("Skipping locking table") pass @@ -2732,15 +2746,15 @@ class TaskDeleteData(StateTransitionTask): def _unlockTableIfNeeded(self, fullTableName): if Config.getConfig().verify_data: # Logging.info("Unlocking table: {}".format(fullTableName)) - self.unlockTable(fullTableName) + self.unlockTable(fullTableName) # Logging.info("Table unlocked: {}".format(fullTableName)) else: pass # Logging.info("Skipping unlocking table") - def _deleteData(self, db: Database, dbc, regTableName, te: TaskExecutor): # implied: NOT in batches - numRecords = self.LARGE_NUMBER_OF_RECORDS if Config.getConfig().larger_data else self.SMALL_NUMBER_OF_RECORDS - del_Records = int(numRecords/5) + def _deleteData(self, db: Database, dbc, regTableName, te: TaskExecutor): # implied: NOT in batches + numRecords = self.LARGE_NUMBER_OF_RECORDS if Config.getConfig().larger_data else self.SMALL_NUMBER_OF_RECORDS + del_Records = int(numRecords / 5) if Dice.throw(2) == 0: for j in range(del_Records): # number of records per table intToWrite = db.getNextInt() @@ -2753,13 +2767,14 @@ class TaskDeleteData(StateTransitionTask): self.fAddLogReady.write("Ready to delete {} to {}\n".format(intToWrite, regTableName)) self.fAddLogReady.flush() os.fsync(self.fAddLogReady.fileno()) - + # TODO: too ugly trying to lock the table reliably, refactor... fullTableName = db.getName() + '.' + regTableName - self._lockTableIfNeeded(fullTableName) # so that we are verify read-back. TODO: deal with exceptions before unlock - + self._lockTableIfNeeded( + fullTableName) # so that we are verify read-back. TODO: deal with exceptions before unlock + try: - sql = "delete from {} where ts = '{}' ;".format( # removed: tags ('{}', {}) + sql = "delete from {} where ts = '{}' ;".format( # removed: tags ('{}', {}) fullTableName, # ds.getFixedSuperTableName(), # ds.getNextBinary(), ds.getNextFloat(), @@ -2772,45 +2787,46 @@ class TaskDeleteData(StateTransitionTask): intWrote = intToWrite # Quick hack, attach an update statement here. TODO: create an "update" task - if (not Config.getConfig().use_shadow_db) and Dice.throw(5) == 0: # 1 in N chance, plus not using shaddow DB - intToUpdate = db.getNextInt() # Updated, but should not succeed + if (not Config.getConfig().use_shadow_db) and Dice.throw( + 5) == 0: # 1 in N chance, plus not using shaddow DB + intToUpdate = db.getNextInt() # Updated, but should not succeed # nextColor = db.getNextColor() - sql = "delete from {} where ts = '{}' ;".format( # "INSERt" means "update" here - fullTableName, - nextTick) + sql = "delete from {} where ts = '{}' ;".format( # "INSERt" means "update" here + fullTableName, + nextTick) # sql = "UPDATE {} set speed={}, color='{}' WHERE ts='{}'".format( # fullTableName, db.getNextInt(), db.getNextColor(), nextTick) dbc.execute(sql) - intWrote = intToUpdate # We updated, seems TDengine non-cluster accepts this. + intWrote = intToUpdate # We updated, seems TDengine non-cluster accepts this. - except: # Any exception at all - self._unlockTableIfNeeded(fullTableName) + except: # Any exception at all + self._unlockTableIfNeeded(fullTableName) raise # Now read it back and verify, we might encounter an error if table is dropped - if Config.getConfig().verify_data: # only if command line asks for it + if Config.getConfig().verify_data: # only if command line asks for it try: dbc.query("SELECT * from {}.{} WHERE ts='{}'". - format(db.getName(), regTableName, nextTick)) + format(db.getName(), regTableName, nextTick)) result = dbc.getQueryResult() - if len(result)==0: + if len(result) == 0: # means data has been delete - print("D1",end="") # DF means delete failed + print("D1", end="") # DF means delete failed else: - print("DF",end="") # DF means delete failed + print("DF", end="") # DF means delete failed except taos.error.ProgrammingError as err: errno = Helper.convertErrno(err.errno) # if errno == CrashGenError.INVALID_EMPTY_RESULT: # empty result # print("D1",end="") # D1 means delete data success and only 1 record - if errno in [0x218, 0x362,0x2662]: # table doesn't exist + if errno in [0x218, 0x362, 0x2662]: # table doesn't exist # do nothing pass else: # Re-throw otherwise raise finally: - self._unlockTableIfNeeded(fullTableName) # Quite ugly, refactor lock/unlock + self._unlockTableIfNeeded(fullTableName) # Quite ugly, refactor lock/unlock # Done with read-back verification, unlock the table now # Successfully wrote the data into the DB, let's record it somehow te.recordDataMark(intWrote) @@ -2824,52 +2840,54 @@ class TaskDeleteData(StateTransitionTask): self.fAddLogReady.write("Ready to delete {} to {}\n".format(intToWrite, regTableName)) self.fAddLogReady.flush() os.fsync(self.fAddLogReady.fileno()) - + # TODO: too ugly trying to lock the table reliably, refactor... fullTableName = db.getName() + '.' + regTableName - self._lockTableIfNeeded(fullTableName) # so that we are verify read-back. TODO: deal with exceptions before unlock - + self._lockTableIfNeeded( + fullTableName) # so that we are verify read-back. TODO: deal with exceptions before unlock + try: - sql = "delete from {} ;".format( # removed: tags ('{}', {}) + sql = "delete from {} ;".format( # removed: tags ('{}', {}) fullTableName) # Logging.info("Adding data: {}".format(sql)) dbc.execute(sql) # Logging.info("Data added: {}".format(sql)) - + # Quick hack, attach an update statement here. TODO: create an "update" task - if (not Config.getConfig().use_shadow_db) and Dice.throw(5) == 0: # 1 in N chance, plus not using shaddow DB - sql = "delete from {} ;".format( # "INSERt" means "update" here - fullTableName) + if (not Config.getConfig().use_shadow_db) and Dice.throw( + 5) == 0: # 1 in N chance, plus not using shaddow DB + sql = "delete from {} ;".format( # "INSERt" means "update" here + fullTableName) dbc.execute(sql) - except: # Any exception at all - self._unlockTableIfNeeded(fullTableName) + except: # Any exception at all + self._unlockTableIfNeeded(fullTableName) raise # Now read it back and verify, we might encounter an error if table is dropped - if Config.getConfig().verify_data: # only if command line asks for it + if Config.getConfig().verify_data: # only if command line asks for it try: dbc.query("SELECT * from {}.{} WHERE ts='{}'". - format(db.getName(), regTableName, nextTick)) + format(db.getName(), regTableName, nextTick)) result = dbc.getQueryResult() - if len(result)==0: + if len(result) == 0: # means data has been delete - print("DA",end="") + print("DA", end="") else: - print("DF",end="") # DF means delete failed + print("DF", end="") # DF means delete failed except taos.error.ProgrammingError as err: errno = Helper.convertErrno(err.errno) # if errno == CrashGenError.INVALID_EMPTY_RESULT: # empty result # print("Da",end="") # Da means delete data success and for all datas - if errno in [0x218, 0x362,0x2662]: # table doesn't exist + if errno in [0x218, 0x362, 0x2662]: # table doesn't exist # do nothing pass else: # Re-throw otherwise raise finally: - self._unlockTableIfNeeded(fullTableName) # Quite ugly, refactor lock/unlock + self._unlockTableIfNeeded(fullTableName) # Quite ugly, refactor lock/unlock # Done with read-back verification, unlock the table now if Config.getConfig().record_ops: @@ -2883,17 +2901,17 @@ class TaskDeleteData(StateTransitionTask): # ds = self._dbManager # Quite DANGEROUS here, may result in multi-thread client access db = self._db dbc = wt.getDbConn() - numTables = self.LARGE_NUMBER_OF_TABLES if Config.getConfig().larger_data else self.SMALL_NUMBER_OF_TABLES + numTables = self.LARGE_NUMBER_OF_TABLES if Config.getConfig().larger_data else self.SMALL_NUMBER_OF_TABLES numRecords = self.LARGE_NUMBER_OF_RECORDS if Config.getConfig().larger_data else self.SMALL_NUMBER_OF_RECORDS - tblSeq = list(range(numTables )) - random.shuffle(tblSeq) # now we have random sequence + tblSeq = list(range(numTables)) + random.shuffle(tblSeq) # now we have random sequence for i in tblSeq: if (i in self.activeTable): # wow already active # print("x", end="", flush=True) # concurrent insertion Progress.emit(Progress.CONCURRENT_INSERTION) else: self.activeTable.add(i) # marking it active - + dbName = db.getName() sTable = db.getFixedSuperTable() regTableName = self.getRegTableName(i) # "db.reg_table_{}".format(i) @@ -2901,54 +2919,57 @@ class TaskDeleteData(StateTransitionTask): # self._lockTable(fullTableName) # "create table" below. Stop it if the table is "locked" sTable.ensureRegTable(self, wt.getDbConn(), regTableName) # Ensure the table exists # self._unlockTable(fullTableName) - + self._deleteData(db, dbc, regTableName, te) - + self.activeTable.discard(i) # not raising an error, unlike remove -class ThreadStacks: # stack info for all threads +class ThreadStacks: # stack info for all threads def __init__(self): self._allStacks = {} - allFrames = sys._current_frames() # All current stack frames, keyed with "ident" + allFrames = sys._current_frames() # All current stack frames, keyed with "ident" for th in threading.enumerate(): # For each thread - stack = traceback.extract_stack(allFrames[th.ident]) #type: ignore # Get stack for a thread - shortTid = th.native_id % 10000 #type: ignore - self._allStacks[shortTid] = stack # Was using th.native_id + stack = traceback.extract_stack(allFrames[th.ident]) # type: ignore # Get stack for a thread + shortTid = th.native_id % 10000 # type: ignore + self._allStacks[shortTid] = stack # Was using th.native_id - def record_current_time(self,current_time): + def record_current_time(self, current_time): self.current_time = current_time - def print(self, filteredEndName = None, filterInternal = False): - for shortTid, stack in self._allStacks.items(): # for each thread, stack frames top to bottom + def print(self, filteredEndName=None, filterInternal=False): + for shortTid, stack in self._allStacks.items(): # for each thread, stack frames top to bottom lastFrame = stack[-1] - if filteredEndName: # we need to filter out stacks that match this name - if lastFrame.name == filteredEndName : # end did not match + if filteredEndName: # we need to filter out stacks that match this name + if lastFrame.name == filteredEndName: # end did not match continue if filterInternal: - if lastFrame.name in ['wait', 'invoke_excepthook', - '_wait', # The Barrier exception - 'svcOutputReader', # the svcMgr thread - '__init__']: # the thread that extracted the stack - continue # ignore + if lastFrame.name in ['wait', 'invoke_excepthook', + '_wait', # The Barrier exception + 'svcOutputReader', # the svcMgr thread + '__init__']: # the thread that extracted the stack + continue # ignore # Now print print("\n<----- Thread Info for LWP/ID: {} (most recent call last) <-----".format(shortTid)) - + lastSqlForThread = DbConn.fetchSqlForThread(shortTid) last_sql_commit_time = DbConn.get_save_sql_time(shortTid) # time_cost = DbConn.get_time_cost() - print("Last SQL statement attempted from thread {} ({:.4f} sec ago) is: {}".format(shortTid, self.current_time-last_sql_commit_time ,lastSqlForThread)) + print("Last SQL statement attempted from thread {} ({:.4f} sec ago) is: {}".format(shortTid, + self.current_time - last_sql_commit_time, + lastSqlForThread)) stackFrame = 0 - for frame in stack: # was using: reversed(stack) + for frame in stack: # was using: reversed(stack) # print(frame) print("[{sf}] File {filename}, line {lineno}, in {name}".format( sf=stackFrame, filename=frame.filename, lineno=frame.lineno, name=frame.name)) print(" {}".format(frame.line)) stackFrame += 1 print("-----> End of Thread Info ----->\n") - if self.current_time-last_sql_commit_time >100: # dead lock occured + if self.current_time - last_sql_commit_time > 100: # dead lock occured print("maybe dead locked of thread {} ".format(shortTid)) + class ClientManager: def __init__(self): Logging.info("Starting service manager") @@ -3041,36 +3062,35 @@ class ClientManager: # time.sleep(2.0) # dbManager = None # release? - def run(self, svcMgr): + def run(self, svcMgr): # self._printLastNumbers() # global gConfig # Prepare Tde Instance global gContainer - tInst = gContainer.defTdeInstance = TdeInstance() # "subdir to hold the instance" + tInst = gContainer.defTdeInstance = TdeInstance() # "subdir to hold the instance" cfg = Config.getConfig() dbManager = DbManager(cfg.connector_type, tInst.getDbTarget()) # Regular function thPool = ThreadPool(cfg.num_threads, cfg.max_steps) self.tc = ThreadCoordinator(thPool, dbManager) - + Logging.info("Starting client instance: {}".format(tInst)) self.tc.run() # print("exec stats: {}".format(self.tc.getExecStats())) # print("TC failed = {}".format(self.tc.isFailed())) - if svcMgr: # gConfig.auto_start_service: + if svcMgr: # gConfig.auto_start_service: svcMgr.stopTaosServices() svcMgr = None - # Release global variables # gConfig = None Config.clearConfig() gSvcMgr = None logger = None - + thPool = None - dbManager.cleanUp() # destructor wouldn't run in time + dbManager.cleanUp() # destructor wouldn't run in time dbManager = None # Print exec status, etc., AFTER showing messages from the server @@ -3082,7 +3102,7 @@ class ClientManager: # Release variables here self.tc = None - gc.collect() # force garbage collection + gc.collect() # force garbage collection # h = hpy() # print("\n----- Final Python Heap -----\n") # print(h.heap()) @@ -3093,37 +3113,38 @@ class ClientManager: # self.tc.getDbManager().cleanUp() # clean up first, so we can show ZERO db connections self.tc.printStats() + class MainExec: - def __init__(self): + def __init__(self): self._clientMgr = None - self._svcMgr = None # type: Optional[ServiceManager] + self._svcMgr = None # type: Optional[ServiceManager] signal.signal(signal.SIGTERM, self.sigIntHandler) - signal.signal(signal.SIGINT, self.sigIntHandler) + signal.signal(signal.SIGINT, self.sigIntHandler) signal.signal(signal.SIGUSR1, self.sigUsrHandler) # different handler! def sigUsrHandler(self, signalNumber, frame): if self._clientMgr: self._clientMgr.sigUsrHandler(signalNumber, frame) - elif self._svcMgr: # Only if no client mgr, we are running alone + elif self._svcMgr: # Only if no client mgr, we are running alone self._svcMgr.sigUsrHandler(signalNumber, frame) - + def sigIntHandler(self, signalNumber, frame): - if self._svcMgr: + if self._svcMgr: self._svcMgr.sigIntHandler(signalNumber, frame) - if self._clientMgr: + if self._clientMgr: self._clientMgr.sigIntHandler(signalNumber, frame) def runClient(self): global gSvcMgr if Config.getConfig().auto_start_service: - gSvcMgr = self._svcMgr = ServiceManager(1) # hack alert - gSvcMgr.startTaosServices() # we start, don't run - + gSvcMgr = self._svcMgr = ServiceManager(1) # hack alert + gSvcMgr.startTaosServices() # we start, don't run + self._clientMgr = ClientManager() ret = None - try: - ret = self._clientMgr.run(self._svcMgr) # stop TAOS service inside + try: + ret = self._clientMgr.run(self._svcMgr) # stop TAOS service inside except requests.exceptions.ConnectionError as err: Logging.warning("Failed to open REST connection to DB: {}".format(err)) # don't raise @@ -3131,10 +3152,11 @@ class MainExec: def runService(self): global gSvcMgr - gSvcMgr = self._svcMgr = ServiceManager(Config.getConfig().num_dnodes) # save it in a global variable TODO: hack alert + gSvcMgr = self._svcMgr = ServiceManager( + Config.getConfig().num_dnodes) # save it in a global variable TODO: hack alert - gSvcMgr.run() # run to some end state - gSvcMgr = self._svcMgr = None + gSvcMgr.run() # run to some end state + gSvcMgr = self._svcMgr = None def _buildCmdLineParser(self): parser = argparse.ArgumentParser( @@ -3145,7 +3167,7 @@ class MainExec: 1. You build TDengine in the top level ./build directory, as described in offical docs 2. You run the server there before this script: ./build/bin/taosd -c test/cfg - ''')) + ''')) parser.add_argument( '-a', @@ -3209,7 +3231,7 @@ class MainExec: '-n', '--dynamic-db-table-names', action='store_true', - help='Use non-fixed names for dbs/tables, for -b, useful for multi-instance executions (default: false)') + help='Use non-fixed names for dbs/tables, for -b, useful for multi-instance executions (default: false)') parser.add_argument( '-o', '--num-dnodes', @@ -3259,19 +3281,18 @@ class MainExec: return parser - - def init(self): # TODO: refactor + def init(self): # TODO: refactor global gContainer - gContainer = Container() # micky-mouse DI + gContainer = Container() # micky-mouse DI - global gSvcMgr # TODO: refactor away + global gSvcMgr # TODO: refactor away gSvcMgr = None parser = self._buildCmdLineParser() Config.init(parser) # Sanity check for arguments - if Config.getConfig().use_shadow_db and Config.getConfig().max_dbs>1 : + if Config.getConfig().use_shadow_db and Config.getConfig().max_dbs > 1: raise CrashGenError("Cannot combine use-shadow-db with max-dbs of more than 1") Logging.clsInit(Config.getConfig().debug) @@ -3282,10 +3303,10 @@ class MainExec: if Config.getConfig().run_tdengine: # run server try: self.runService() - return 0 # success + return 0 # success except ConnectionError as err: Logging.error("Failed to make DB connection, please check DB instance manually") - return -1 # failure + return -1 # failure else: return self.runClient() @@ -3294,7 +3315,7 @@ class Container(): _propertyList = {'defTdeInstance'} def __init__(self): - self._cargo = {} # No cargo at the beginning + self._cargo = {} # No cargo at the beginning def _verifyValidProperty(self, name): if not name in self._propertyList: @@ -3303,10 +3324,10 @@ class Container(): # Called for an attribute, when other mechanisms fail (compare to __getattribute__) def __getattr__(self, name): self._verifyValidProperty(name) - return self._cargo[name] # just a simple lookup + return self._cargo[name] # just a simple lookup def __setattr__(self, name, value): - if name == '_cargo' : # reserved vars + if name == '_cargo': # reserved vars super().__setattr__(name, value) return self._verifyValidProperty(name) diff --git a/tests/script/sh/checkAsan.sh b/tests/script/sh/checkAsan.sh index 31fe80829f..b6cb4f6280 100755 --- a/tests/script/sh/checkAsan.sh +++ b/tests/script/sh/checkAsan.sh @@ -50,7 +50,11 @@ python_error=`cat ${LOG_DIR}/*.info | grep -w "stack" | wc -l` # /root/TDengine/source/libs/function/src/builtinsimpl.c:856:29: runtime error: signed integer overflow: 9223372036854775806 + 9223372036854775805 cannot be represented in type 'long int' # /root/TDengine/source/libs/scalar/src/sclvector.c:1075:66: runtime error: signed integer overflow: 9223372034707292160 + 1668838476672 cannot be represented in type 'long int' # /root/TDengine/source/common/src/tdataformat.c:1876:7: runtime error: signed integer overflow: 8252423483843671206 + 2406154664059062870 cannot be represented in type 'long int' +# /home/chr/TDengine/source/libs/scalar/src/filter.c:3149:14: runtime error: applying non-zero offset 18446744073709551615 to null pointer +# /home/chr/TDengine/source/libs/scalar/src/filter.c:3149:14: runtime error: applying non-zero offset 18446744073709551615 to null pointer +# /home/TDinternal/community/source/libs/scalar/src/sclvector.c:1109:66: runtime error: signed integer overflow: 9223372034707292160 + 1676867897049 cannot be represented in type 'long int' + runtime_error=`cat ${LOG_DIR}/*.asan | grep "runtime error" | grep -v "trees.c:873" | grep -v "sclfunc.c.*outside the range of representable values of type"| grep -v "signed integer overflow" |grep -v "strerror.c"| grep -v "asan_malloc_linux.cc" |wc -l` echo -e "\033[44;32;1m"asan error_num: $error_num"\033[0m" diff --git a/tests/script/tsim/catalog/alterInCurrent.sim b/tests/script/tsim/catalog/alterInCurrent.sim index 3cb337bbe1..521858c368 100644 --- a/tests/script/tsim/catalog/alterInCurrent.sim +++ b/tests/script/tsim/catalog/alterInCurrent.sim @@ -67,4 +67,19 @@ sql insert into t1 values (1591060628000, 1); sql alter table st1 drop tag t2; sql create table t2 using st1 tags(2); +print ======== drop tag in super table +sql create database if not exists aaa; +sql select table_name, db_name from information_schema.ins_tables t where t.db_name like 'aaa'; +if $rows != 0 then + return -1 +endi +sql drop database if exists foo; +sql create database if not exists foo; +sql create table foo.t(ts timestamp,name varchar(20)); +sql create table foo.xt(ts timestamp,name varchar(20)); +sql select table_name, db_name from information_schema.ins_tables t where t.db_name like 'foo'; +if $rows != 2 then + return -1 +endi + system sh/exec.sh -n dnode1 -s stop -x SIGINT diff --git a/tests/script/tsim/query/join.sim b/tests/script/tsim/query/join.sim new file mode 100644 index 0000000000..adb0338ef7 --- /dev/null +++ b/tests/script/tsim/query/join.sim @@ -0,0 +1,72 @@ +system sh/stop_dnodes.sh +system sh/deploy.sh -n dnode1 -i 1 +system sh/exec.sh -n dnode1 -s start +sql connect + +$dbPrefix = db +$tbPrefix1 = tba +$tbPrefix2 = tbb +$mtPrefix = stb +$tbNum = 10000 +$rowNum = 2 + +print =============== step1 +$i = 0 +$db = $dbPrefix . $i +$mt1 = $mtPrefix . $i +$i = 1 +$mt2 = $mtPrefix . $i + +sql drop database $db -x step1 +step1: +sql create database $db +sql use $db +sql create table $mt1 (ts timestamp, f1 int) TAGS(tag1 int, tag2 binary(500)) +sql create table $mt2 (ts timestamp, f1 int) TAGS(tag1 int, tag2 binary(500)) + +print ====== start create child tables and insert data +$i = 0 +while $i < $tbNum + $tb = $tbPrefix1 . $i + sql create table $tb using $mt1 tags( $i , 'aaaaaaaaaaaaaaaaaaaaaaaaaaa') + + $x = 0 + while $x < $rowNum + $cc = $x * 60000 + $ms = 1601481600000 + $cc + + sql insert into $tb values ($ms , $x ) + $x = $x + 1 + endw + + $i = $i + 1 +endw + +print =============== step2 +$i = 0 +while $i < $tbNum + $tb = $tbPrefix2 . $i + sql create table $tb using $mt2 tags( $i , 'aaaaaaaaaaaaaaaaaaaaaaaaaaa') + + $x = 0 + while $x < $rowNum + $cc = $x * 60000 + $ms = 1601481600000 + $cc + + sql insert into $tb values ($ms , $x ) + $x = $x + 1 + endw + + $i = $i + 1 +endw + +sql select * from tba0 t1, tbb0 t2 where t1.ts=t2.ts; +if $rows != 2 then + return -1 +endi +sql select * from stb0 t1, stb1 t2 where t1.ts=t2.ts and t1.tag2=t2.tag2; +if $rows != 200000000 then + return -1 +endi + +system sh/exec.sh -n dnode1 -s stop -x SIGINT diff --git a/tests/script/tsim/query/partitionby.sim b/tests/script/tsim/query/partitionby.sim new file mode 100644 index 0000000000..8babd1aa8d --- /dev/null +++ b/tests/script/tsim/query/partitionby.sim @@ -0,0 +1,39 @@ +system sh/stop_dnodes.sh +system sh/deploy.sh -n dnode1 -i 1 +system sh/exec.sh -n dnode1 -s start +sql connect + +$dbPrefix = db +$tbPrefix1 = tba +$tbPrefix2 = tbb +$mtPrefix = stb +$tbNum = 10 +$rowNum = 2 + +print =============== step1 +$i = 0 +$db = $dbPrefix . $i +$mt1 = $mtPrefix . $i +$i = 1 +$mt2 = $mtPrefix . $i + +sql drop database $db -x step1 +step1: +sql create database $db vgroups 3 +sql use $db +sql create table $mt1 (ts timestamp, f1 int) TAGS(tag1 int, tag2 binary(500)) +sql create table tb0 using $mt1 tags(0, 'a'); +sql create table tb1 using $mt1 tags(1, 'b'); +sql create table tb2 using $mt1 tags(1, 'a'); +sql create table tb3 using $mt1 tags(1, 'a'); +sql create table tb4 using $mt1 tags(3, 'b'); +sql create table tb5 using $mt1 tags(3, 'a'); +sql create table tb6 using $mt1 tags(3, 'b'); +sql create table tb7 using $mt1 tags(3, 'b'); + +sql select * from $mt1 partition by tag1,tag2 limit 1; +if $rows != 0 then + return -1 +endi + +system sh/exec.sh -n dnode1 -s stop -x SIGINT diff --git a/tests/script/tsim/stream/checkStreamSTable.sim b/tests/script/tsim/stream/checkStreamSTable.sim index fda78af621..288dd35cfe 100644 --- a/tests/script/tsim/stream/checkStreamSTable.sim +++ b/tests/script/tsim/stream/checkStreamSTable.sim @@ -301,7 +301,7 @@ print $data00, $data01, $data02, $data03 print $data10, $data11, $data12, $data13 print $data20, $data21, $data22, $data23 -loop2: +loop3: sleep 300 @@ -317,47 +317,182 @@ if $rows != 2 then print $data00, $data01, $data02, $data03 print $data10, $data11, $data12, $data13 print $data20, $data21, $data22, $data23 - goto loop2 + goto loop3 endi if $data01 != 10 then print =====data01=$data01 - goto loop2 + goto loop3 endi if $data02 != 20 then print =====data02=$data02 - goto loop2 + goto loop3 endi if $data03 != 1 then print =====data03=$data03 - goto loop2 + goto loop3 endi if $data04 != NULL then print =====data04=$data04 - goto loop2 + goto loop3 endi if $data11 != 40 then print =====data11=$data11 - goto loop2 + goto loop3 endi if $data12 != 50 then print =====data12=$data12 - goto loop2 + goto loop3 endi if $data13 != 1 then print =====data13=$data13 - goto loop2 + goto loop3 endi if $data14 != NULL then print =====data14=$data14 - goto loop2 + goto loop3 +endi + +print ===== step7 + +sql create database result5 vgroups 1; + +sql create database test5 vgroups 4; +sql use test5; + +sql create stable st(ts timestamp,a int,b int,c int) tags(ta int,tb int,tc int); +sql create table t1 using st tags(1,2,3); +sql create table t2 using st tags(4,5,6); + +sql create stable result5.streamt5(ts timestamp,a int,b int,c int, d int) tags(tg1 int,tg2 int,tg3 int); + +sql create stream streams5 trigger at_once into result5.streamt5(ts,c,a,b) tags(tg2, tg3, tg1) subtable( concat("tbl-", cast(tg3 as varchar(10)) ) ) as select _wstart, count(*) c1, max(a),min(b) c2 from st partition by ta+1 as tg1, cast(tb as bigint) as tg2, a as tg3 session(ts, 10s); + +sql insert into t1 values(1648791213000,NULL,NULL,NULL); + +$loop_count = 0 + +print select _wstart, count(*) c1, max(a),min(b) c2 from st partition by ta+1 as tg1, cast(tb as bigint) as tg2, a as tg3 session(ts, 10s); +sql select _wstart, count(*) c1, max(a),min(b) c2 from st partition by ta+1 as tg1, cast(tb as bigint) as tg2, a as tg3 session(ts, 10s); +print $data00, $data01, $data02, $data03 +print $data10, $data11, $data12, $data13 +print $data20, $data21, $data22, $data23 + +loop4: + +sleep 300 + +$loop_count = $loop_count + 1 +if $loop_count == 10 then + return -1 +endi + +print sql select * from result5.streamt5 order by tg1; +sql select * from result5.streamt5 order by tg1; +print $data00, $data01, $data02, $data03 $data04 $data05 $data06 $data07 +print $data10, $data11, $data12, $data13 +print $data20, $data21, $data22, $data23 + +if $rows != 1 then + print =====rows=$rows + goto loop4 +endi + +if $data01 != NULL then + print =====data01=$data01 + goto loop4 +endi + +if $data02 != NULL then + print =====data02=$data02 + goto loop4 +endi + +if $data03 != 1 then + print =====data03=$data03 + goto loop4 +endi + +if $data04 != NULL then + print =====data04=$data04 + goto loop4 +endi + +if $data05 != 2 then + print =====data05=$data05 + goto loop4 +endi + +if $data06 != 2 then + print =====data06=$data06 + goto loop4 +endi + +if $data07 != NULL then + print =====data07=$data07 + goto loop4 +endi + +sql drop stream if exists streams4; +sql drop stream if exists streams5; +sql drop database if exists test4; +sql drop database if exists test5; +sql drop database if exists result4; +sql drop database if exists result5; + +print ===== step8 + +sql drop stream if exists streams8; +sql drop database if exists test8; +sql create database test8 vgroups 1; +sql use test8; +sql create table t1(ts timestamp, a int, b int , c int, d double); +sql create stream streams8 trigger at_once into streamt8 as select _wstart as ts, count(*) c1, count(d) c2, count(c) c3 from t1 partition by tbname interval(10s) ; + +sql drop stream streams8; +sql create stream streams71 trigger at_once into streamt8(ts, c2) tags(group_id)as select _wstart, count(*) from t1 partition by tbname as group_id interval(10s); + +sql insert into t1 values(1648791233000,1,2,3,1.0); + +loop8: + +sleep 300 + +$loop_count = $loop_count + 1 +if $loop_count == 10 then + return -1 +endi + +sql select * from streamt8; +print $data00, $data01, $data02, $data03 +print $data10, $data11, $data12, $data13 +print $data20, $data21, $data22, $data23 + +if $rows != 1 then + print =====rows=$rows + goto loop8 +endi + +if $data01 != NULL then + print =====data01=$data01 + goto loop8 +endi + +if $data02 != 1 then + print =====data02=$data02 + goto loop8 +endi + +if $data03 != NULL then + print =====data03=$data03 + goto loop8 endi print ======over diff --git a/tests/script/tsim/stream/udTableAndTag0.sim b/tests/script/tsim/stream/udTableAndTag0.sim index bfc299df0f..8bf34dc54c 100644 --- a/tests/script/tsim/stream/udTableAndTag0.sim +++ b/tests/script/tsim/stream/udTableAndTag0.sim @@ -39,7 +39,10 @@ sql select table_name from information_schema.ins_tables where db_name="result" if $rows != 2 then print =====rows=$rows - print $data00 $data10 + print $data00 + print $data10 + print $data20 + print $data30 goto loop0 endi diff --git a/tests/system-test/0-others/tag_index_basic.py b/tests/system-test/0-others/tag_index_basic.py new file mode 100644 index 0000000000..195d8910e7 --- /dev/null +++ b/tests/system-test/0-others/tag_index_basic.py @@ -0,0 +1,214 @@ +################################################################### +# Copyright (c) 2016 by TAOS Technologies, Inc. +# All rights reserved. +# +# This file is proprietary and confidential to TAOS Technologies. +# No part of this file may be reproduced, stored, transmitted, +# disclosed or used in any form or by any means other than as +# expressly provided by the written permission from Jianhui Tao +# +################################################################### + +# -*- coding: utf-8 -*- + + +from util.log import * +from util.cases import * +from util.sql import * +from util.common import * +from util.sqlset import * +import random + + +class TDTestCase: + def init(self, conn, logSql, replicaVar=1): + self.replicaVar = int(replicaVar) + tdLog.debug("start to execute %s" % __file__) + tdSql.init(conn.cursor()) + self.setsql = TDSetSql() + self.column_dict = { + 'ts': 'timestamp', + 'col1': 'tinyint', + 'col2': 'smallint', + 'col3': 'int', + 'col4': 'bigint', + 'col5': 'tinyint unsigned', + 'col6': 'smallint unsigned', + 'col7': 'int unsigned', + 'col8': 'bigint unsigned', + 'col9': 'float', + 'col10': 'double', + 'col11': 'bool', + 'col12': 'varchar(20)', + 'col13': 'nchar(20)' + } + self.tag_dict = { + 't1': 'tinyint', + 't2': 'smallint', + 't3': 'int', + 't4': 'bigint', + 't5': 'tinyint unsigned', + 't6': 'smallint unsigned', + 't7': 'int unsigned', + 't8': 'bigint unsigned', + 't9': 'float', + 't10': 'double', + 't11': 'bool', + 't12': 'varchar(20)', + 't13': 'nchar(20)', + 't14': 'timestamp' + } + + + def set_stb_sql(self,stbname,column_dict,tag_dict): + column_sql = '' + tag_sql = '' + for k,v in column_dict.items(): + column_sql += f"{k} {v}, " + for k,v in tag_dict.items(): + tag_sql += f"{k} {v}, " + create_stb_sql = f'create stable {stbname} ({column_sql[:-2]}) tags ({tag_sql[:-2]})' + return create_stb_sql + + # create stable and child tables + def create_table(self, stbname, tbname, count): + tdSql.prepare() + tdSql.execute('use db') + + # create stable + create_table_sql = self.set_stb_sql(stbname, self.column_dict, self.tag_dict) + tdSql.execute(create_table_sql) + + # create child table + for i in range(count): + ti = i % 128 + tags = f'{ti},{ti},{i},{i},{ti},{ti},{i},{i},{i}.000{i},{i}.000{i},true,"var{i}","nch{i}",now' + sql = f'create table {tbname}{i} using {stbname} tags({tags})' + tdSql.execute(sql) + + tdLog.info(f" create {count} child tables ok.") + + + # create stable and child tables + def create_tagidx(self, stbname): + cnt = -1 + for key in self.tag_dict.keys(): + # first tag have default index, so skip + if cnt == -1: + cnt = 0 + continue; + sql = f'create index idx_{key} on {stbname} ({key})' + tdLog.info(f" sql={sql}") + tdSql.execute(sql) + cnt += 1 + tdLog.info(f' create {cnt} tag indexs ok.') + + # insert to child table d1 data + def insert_data(self, tbname): + # d1 insert 3 rows + for i in range(3): + sql = f'insert into {tbname}1(ts,col1) values(now,{i});' + tdSql.execute(sql) + # d20 insert 4 + for i in range(4): + sql = f'insert into {tbname}20(ts,col1) values(now,{i});' + tdSql.execute(sql) + + # check show indexs + def show_tagidx(self, stbname): + sql = f'select index_name,column_name from information_schema.ins_indexes where db_name="db"' + tdSql.query(sql) + rows = len(self.tag_dict.keys())-1 + tdSql.checkRows(rows) + + for i in range(rows): + col_name = tdSql.getData(i, 1) + idx_name = f'idx_{col_name}' + tdSql.checkData(i, 0, idx_name) + + tdLog.info(f' show {rows} tag indexs ok.') + + # query with tag idx + def query_tagidx(self, stbname): + sql = f'select * from meters where t1=1' + tdSql.query(sql) + tdSql.checkRows(3) + + sql = f'select * from meters where t2<10' + tdSql.query(sql) + tdSql.checkRows(3) + + sql = f'select * from meters where t2>10' + tdSql.query(sql) + tdSql.checkRows(4) + + sql = f'select * from meters where t3<30' + tdSql.query(sql) + tdSql.checkRows(7) + + sql = f'select * from meters where t12="11"' + tdSql.query(sql) + tdSql.checkRows(0) + + sql = f'select * from meters where (t4 < 10 or t5 = 20) and t6= 30' + tdSql.query(sql) + tdSql.checkRows(0) + + sql = f'select * from meters where (t7 < 20 and t8 = 20) or t4 = 20' + tdSql.query(sql) + tdSql.checkRows(4) + + # drop child table + def drop_tables(self, tbname, count): + # table d1 and d20 have verify data , so can not drop + start = random.randint(21, count/2) + end = random.randint(count/2 + 1, count - 1) + for i in range(start, end): + sql = f'drop table {tbname}{i}' + tdSql.execute(sql) + cnt = end - start + 1 + tdLog.info(f' drop table from {start} to {end} count={cnt}') + + # drop tag index + def drop_tagidx(self, stbname): + # drop index + cnt = -1 + for key in self.tag_dict.keys(): + # first tag have default index, so skip + if cnt == -1: + cnt = 0 + continue; + sql = f'drop index idx_{key}' + tdSql.execute(sql) + cnt += 1 + + # check idx result is 0 + sql = f'select index_name,column_name from information_schema.ins_indexes where db_name="db"' + tdSql.query(sql) + tdSql.checkRows(0) + tdLog.info(f' drop {cnt} tag indexs ok.') + + # run + def run(self): + # var + stable = "meters" + tbname = "d" + count = 1000 + # do + self.create_table(stable, tbname, count) + self.create_tagidx(stable) + self.insert_data(tbname) + self.show_tagidx(stable) + self.query_tagidx(stable) + self.drop_tables(tbname, count) + self.drop_tagidx(stable) + # query after delete , expect no crash + self.query_tagidx(stable) + + + def stop(self): + tdSql.close() + tdLog.success("%s successfully executed" % __file__) + +tdCases.addWindows(__file__, TDTestCase()) +tdCases.addLinux(__file__, TDTestCase()) \ No newline at end of file diff --git a/tests/system-test/0-others/taosShell.py b/tests/system-test/0-others/taosShell.py index 5c7bb0443a..1227378799 100644 --- a/tests/system-test/0-others/taosShell.py +++ b/tests/system-test/0-others/taosShell.py @@ -373,7 +373,7 @@ class TDTestCase: version = 'version: ' + version retVal = retVal.replace("\n", "") retVal = retVal.replace("\r", "") - if retVal != version: + if retVal.startswith(version) == False: print ("return version: [%s]"%retVal) print ("dict version: [%s]"%version) tdLog.exit("taos -V version not match") diff --git a/tests/system-test/0-others/user_manage.py b/tests/system-test/0-others/user_manage.py index 5148e26b39..6f90a2873a 100644 --- a/tests/system-test/0-others/user_manage.py +++ b/tests/system-test/0-others/user_manage.py @@ -12,12 +12,13 @@ # -*- coding: utf-8 -*- import taos -from util.log import * -from util.cases import * -from util.sql import * -from util.common import * -from util.sqlset import * from taos.tmq import * +from util.cases import * +from util.common import * +from util.log import * +from util.sql import * +from util.sqlset import * + class TDTestCase: def init(self, conn, logSql, replicaVar=1): @@ -26,10 +27,10 @@ class TDTestCase: tdSql.init(conn.cursor()) self.setsql = TDSetSql() self.stbname = 'stb' - self.binary_length = 20 # the length of binary for column_dict + self.binary_length = 20 # the length of binary for column_dict self.nchar_length = 20 # the length of nchar for column_dict self.column_dict = { - 'ts' : 'timestamp', + 'ts': 'timestamp', 'col1': 'tinyint', 'col2': 'smallint', 'col3': 'int', @@ -45,7 +46,7 @@ class TDTestCase: 'col13': f'nchar({self.nchar_length})' } self.tag_dict = { - 'ts_tag' : 'timestamp', + 'ts_tag': 'timestamp', 't1': 'tinyint', 't2': 'smallint', 't3': 'int', @@ -67,25 +68,28 @@ class TDTestCase: f'now,1,2,3,4,5,6,7,8,9.9,10.1,true,"abcd","涛思数据"' ] self.tbnum = 1 + def prepare_data(self): - tdSql.execute(self.setsql.set_create_stable_sql(self.stbname,self.column_dict,self.tag_dict)) + tdSql.execute(self.setsql.set_create_stable_sql(self.stbname, self.column_dict, self.tag_dict)) for i in range(self.tbnum): tdSql.execute(f'create table {self.stbname}_{i} using {self.stbname} tags({self.tag_list[i]})') for j in self.values_list: tdSql.execute(f'insert into {self.stbname}_{i} values({j})') + def create_user(self): - for user_name in ['jiacy1_all','jiacy1_read','jiacy1_write','jiacy1_none','jiacy0_all','jiacy0_read','jiacy0_write','jiacy0_none']: + for user_name in ['jiacy1_all', 'jiacy1_read', 'jiacy1_write', 'jiacy1_none', 'jiacy0_all', 'jiacy0_read', + 'jiacy0_write', 'jiacy0_none']: if 'jiacy1' in user_name.lower(): tdSql.execute(f'create user {user_name} pass "123" sysinfo 1') elif 'jiacy0' in user_name.lower(): tdSql.execute(f'create user {user_name} pass "123" sysinfo 0') - for user_name in ['jiacy1_all','jiacy1_read','jiacy0_all','jiacy0_read']: + for user_name in ['jiacy1_all', 'jiacy1_read', 'jiacy0_all', 'jiacy0_read']: tdSql.execute(f'grant read on db to {user_name}') - for user_name in ['jiacy1_all','jiacy1_write','jiacy0_all','jiacy0_write']: + for user_name in ['jiacy1_all', 'jiacy1_write', 'jiacy0_all', 'jiacy0_write']: tdSql.execute(f'grant write on db to {user_name}') def user_privilege_check(self): - jiacy1_read_conn = taos.connect(user='jiacy1_read',password='123') + jiacy1_read_conn = taos.connect(user='jiacy1_read', password='123') sql = "create table ntb (ts timestamp,c0 int)" expectErrNotOccured = True try: @@ -94,32 +98,34 @@ class TDTestCase: expectErrNotOccured = False if expectErrNotOccured: caller = inspect.getframeinfo(inspect.stack()[1][0]) - tdLog.exit(f"{caller.filename}({caller.lineno}) failed: sql:{sql}, expect error not occured" ) + tdLog.exit(f"{caller.filename}({caller.lineno}) failed: sql:{sql}, expect error not occured") else: self.queryRows = 0 self.queryCols = 0 self.queryResult = None tdLog.info(f"sql:{sql}, expect error occured") pass + def drop_topic(self): - jiacy1_all_conn = taos.connect(user='jiacy1_all',password='123') - jiacy1_read_conn = taos.connect(user='jiacy1_read',password='123') - jiacy1_write_conn = taos.connect(user='jiacy1_write',password='123') - jiacy1_none_conn = taos.connect(user='jiacy1_none',password='123') - jiacy0_all_conn = taos.connect(user='jiacy0_all',password='123') - jiacy0_read_conn = taos.connect(user='jiacy0_read',password='123') - jiacy0_write_conn = taos.connect(user='jiacy0_write',password='123') - jiacy0_none_conn = taos.connect(user='jiacy0_none',password='123') + jiacy1_all_conn = taos.connect(user='jiacy1_all', password='123') + jiacy1_read_conn = taos.connect(user='jiacy1_read', password='123') + jiacy1_write_conn = taos.connect(user='jiacy1_write', password='123') + jiacy1_none_conn = taos.connect(user='jiacy1_none', password='123') + jiacy0_all_conn = taos.connect(user='jiacy0_all', password='123') + jiacy0_read_conn = taos.connect(user='jiacy0_read', password='123') + jiacy0_write_conn = taos.connect(user='jiacy0_write', password='123') + jiacy0_none_conn = taos.connect(user='jiacy0_none', password='123') tdSql.execute('create topic root_db as select * from db.stb') - for user in [jiacy1_all_conn,jiacy1_read_conn,jiacy0_all_conn,jiacy0_read_conn]: + for user in [jiacy1_all_conn, jiacy1_read_conn, jiacy0_all_conn, jiacy0_read_conn]: user.execute(f'create topic db_jiacy as select * from db.stb') user.execute('drop topic db_jiacy') - for user in [jiacy1_write_conn,jiacy1_none_conn,jiacy0_write_conn,jiacy0_none_conn,jiacy1_all_conn,jiacy1_read_conn,jiacy0_all_conn,jiacy0_read_conn]: + for user in [jiacy1_write_conn, jiacy1_none_conn, jiacy0_write_conn, jiacy0_none_conn, jiacy1_all_conn, + jiacy1_read_conn, jiacy0_all_conn, jiacy0_read_conn]: sql_list = [] - if user in [jiacy1_all_conn,jiacy1_read_conn,jiacy0_all_conn,jiacy0_read_conn]: + if user in [jiacy1_all_conn, jiacy1_read_conn, jiacy0_all_conn, jiacy0_read_conn]: sql_list = ['drop topic root_db'] - elif user in [jiacy1_write_conn,jiacy1_none_conn,jiacy0_write_conn,jiacy0_none_conn]: - sql_list = ['drop topic root_db','create topic db_jiacy as select * from db.stb'] + elif user in [jiacy1_write_conn, jiacy1_none_conn, jiacy0_write_conn, jiacy0_none_conn]: + sql_list = ['drop topic root_db', 'create topic db_jiacy as select * from db.stb'] for sql in sql_list: expectErrNotOccured = True try: @@ -128,33 +134,26 @@ class TDTestCase: expectErrNotOccured = False if expectErrNotOccured: caller = inspect.getframeinfo(inspect.stack()[1][0]) - tdLog.exit(f"{caller.filename}({caller.lineno}) failed: sql:{sql}, expect error not occured" ) + tdLog.exit(f"{caller.filename}({caller.lineno}) failed: sql:{sql}, expect error not occured") else: self.queryRows = 0 self.queryCols = 0 self.queryResult = None tdLog.info(f"sql:{sql}, expect error occured") + def tmq_commit_cb_print(tmq, resp, param=None): print(f"commit: {resp}, tmq: {tmq}, param: {param}") + def subscribe_topic(self): print("create topic") tdSql.execute('create topic db_topic as select * from db.stb') tdSql.execute('grant subscribe on db_topic to jiacy1_all') print("build consumer") - conf = TaosTmqConf() - conf.set("group.id", "tg2") - conf.set("td.connect.user", "jiacy1_all") - conf.set("td.connect.pass", "123") - conf.set("enable.auto.commit", "true") - conf.set_auto_commit_cb(self.tmq_commit_cb_print, None) - tmq = conf.new_consumer() + tmq = Consumer({"group.id": "tg2", "td.connect.user": "jiacy1_all", "td.connect.pass": "123", + "enable.auto.commit": "true"}) print("build topic list") - topic_list = TaosTmqList() - topic_list.append("db_topic") + tmq.subscribe(["db_topic"]) print("basic consume loop") - tmq.subscribe(topic_list) - sub_list = tmq.subscription() - print("subscribed topics: ", sub_list) c = 0 l = 0 for i in range(10): @@ -163,20 +162,23 @@ class TDTestCase: res = tmq.poll(10) print(f"loop {l}") l += 1 - if res: - c += 1 - topic = res.get_topic_name() - vg = res.get_vgroup_id() - db = res.get_db_name() - print(f"topic: {topic}\nvgroup id: {vg}\ndb: {db}") - for row in res: - print(row) - print("* committed") - tmq.commit(res) - else: + if not res: print(f"received empty message at loop {l} (committed {c})") - pass - + continue + if res.error(): + print(f"consumer error at loop {l} (committed {c}) {res.error()}") + continue + + c += 1 + topic = res.topic() + db = res.database() + print(f"topic: {topic}\ndb: {db}") + + for row in res: + print(row.fetchall()) + print("* committed") + tmq.commit(res) + def run(self): tdSql.prepare() self.create_user() @@ -184,9 +186,11 @@ class TDTestCase: self.drop_topic() self.user_privilege_check() self.subscribe_topic() + def stop(self): tdSql.close() tdLog.success("%s successfully executed" % __file__) + tdCases.addWindows(__file__, TDTestCase()) -tdCases.addLinux(__file__, TDTestCase()) \ No newline at end of file +tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/system-test/2-query/out_of_order.py b/tests/system-test/2-query/out_of_order.py index 5b52661bae..148b89fc58 100644 --- a/tests/system-test/2-query/out_of_order.py +++ b/tests/system-test/2-query/out_of_order.py @@ -25,7 +25,7 @@ class TDTestCase: def init(self, conn, logSql, replicaVar): tdLog.debug("start to execute %s" % __file__) tdSql.init(conn.cursor(), logSql) - + def getBuildPath(self): selfPath = os.path.dirname(os.path.realpath(__file__)) @@ -41,9 +41,9 @@ class TDTestCase: buildPath = root[:len(root)-len("/build/bin")] break return buildPath - + def run_benchmark(self,dbname,tables,per_table_num,order,replica): - #O :Out of order + #O :Out of order #A :Repliaca buildPath = self.getBuildPath() if (buildPath == ""): @@ -53,135 +53,147 @@ class TDTestCase: binPath = buildPath+ "/build/bin/" os.system("%staosBenchmark -d %s -t %d -n %d -O %d -a %d -b float,double,nchar\(200\),binary\(50\) -T 50 -y " % (binPath,dbname,tables,per_table_num,order,replica)) - + def sql_base(self,dbname): self.check_sub(dbname) sql1 = "select count(*) from %s.meters" %dbname self.sql_base_check(sql1,sql1) - + self.check_sub(dbname) sql2 = "select count(ts) from %s.meters" %dbname self.sql_base_check(sql1,sql2) - + self.check_sub(dbname) sql2 = "select count(_c0) from %s.meters" %dbname self.sql_base_check(sql1,sql2) - + self.check_sub(dbname) sql2 = "select count(c0) from %s.meters" %dbname self.sql_base_check(sql1,sql2) - + self.check_sub(dbname) sql2 = "select count(c1) from %s.meters" %dbname self.sql_base_check(sql1,sql2) - + self.check_sub(dbname) sql2 = "select count(c2) from %s.meters" %dbname self.sql_base_check(sql1,sql2) - + self.check_sub(dbname) sql2 = "select count(c3) from %s.meters" %dbname self.sql_base_check(sql1,sql2) - + self.check_sub(dbname) sql2 = "select count(t0) from %s.meters" %dbname self.sql_base_check(sql1,sql2) - + self.check_sub(dbname) sql2 = "select count(t1) from %s.meters" %dbname self.sql_base_check(sql1,sql2) - - + + self.check_sub(dbname) sql2 = "select count(ts) from (select * from %s.meters)" %dbname self.sql_base_check(sql1,sql2) - + self.check_sub(dbname) sql2 = "select count(_c0) from (select * from %s.meters)" %dbname self.sql_base_check(sql1,sql2) - + self.check_sub(dbname) sql2 = "select count(c0) from (select * from %s.meters)" %dbname self.sql_base_check(sql1,sql2) - + self.check_sub(dbname) sql2 = "select count(c1) from (select * from %s.meters)" %dbname self.sql_base_check(sql1,sql2) - + self.check_sub(dbname) sql2 = "select count(c2) from (select * from %s.meters)" %dbname self.sql_base_check(sql1,sql2) - + self.check_sub(dbname) sql2 = "select count(c3) from (select * from %s.meters)" %dbname self.sql_base_check(sql1,sql2) - + self.check_sub(dbname) sql2 = "select count(t0) from (select * from %s.meters)" %dbname self.sql_base_check(sql1,sql2) - + self.check_sub(dbname) sql2 = "select count(t1) from (select * from %s.meters)" %dbname self.sql_base_check(sql1,sql2) - - + + # TD-22520 + tdSql.query("select tbname, ts from %s.meters where ts < '2017-07-14 10:40:00' order by ts asc limit 150;" %dbname) + tdSql.checkRows(150) + + tdSql.query("select tbname, ts from %s.meters where ts < '2017-07-14 10:40:00' order by ts asc limit 300;" %dbname) + tdSql.checkRows(300) + + tdSql.query("select tbname, ts from %s.meters where ts < '2017-07-14 10:40:00' order by ts desc limit 150;" %dbname) + tdSql.checkRows(150) + + tdSql.query("select tbname, ts from %s.meters where ts < '2017-07-14 10:40:00' order by ts desc limit 300;" %dbname) + tdSql.checkRows(300) + def sql_base_check(self,sql1,sql2): tdSql.query(sql1) sql1_result = tdSql.getData(0,0) tdLog.info("sql:%s , result: %s" %(sql1,sql1_result)) - + tdSql.query(sql2) sql2_result = tdSql.getData(0,0) tdLog.info("sql:%s , result: %s" %(sql2,sql2_result)) - + if sql1_result==sql2_result: - tdLog.info(f"checkEqual success, sql1_result={sql1_result},sql2_result={sql2_result}") + tdLog.info(f"checkEqual success, sql1_result={sql1_result},sql2_result={sql2_result}") else : - tdLog.exit(f"checkEqual error, sql1_result=={sql1_result},sql2_result={sql2_result}") - + tdLog.exit(f"checkEqual error, sql1_result=={sql1_result},sql2_result={sql2_result}") + def run_sql(self,dbname): self.sql_base(dbname) - + tdSql.execute(" flush database %s;" %dbname) - + self.sql_base(dbname) - + def check_sub(self,dbname): - + sql = "select count(*) from (select distinct(tbname) from %s.meters)" %dbname tdSql.query(sql) num = tdSql.getData(0,0) - + for i in range(0,num): sql1 = "select count(*) from %s.d%d" %(dbname,i) tdSql.query(sql1) sql1_result = tdSql.getData(0,0) tdLog.info("sql:%s , result: %s" %(sql1,sql1_result)) - + def check_out_of_order(self,dbname,tables,per_table_num,order,replica): self.run_benchmark(dbname,tables,per_table_num,order,replica) print("sleep 10 seconds") #time.sleep(10) print("sleep 10 seconds finish") - + self.run_sql(dbname) - + def run(self): - startTime = time.time() - - #self.check_out_of_order('db1',10,random.randint(10000,50000),random.randint(1,10),1) - self.check_out_of_order('db1',random.randint(50,200),random.randint(10000,20000),random.randint(1,5),1) - - # self.check_out_of_order('db2',random.randint(50,200),random.randint(10000,50000),random.randint(5,50),1) - - # self.check_out_of_order('db3',random.randint(50,200),random.randint(10000,50000),random.randint(50,100),1) - - # self.check_out_of_order('db4',random.randint(50,200),random.randint(10000,50000),100,1) - + startTime = time.time() + + #self.check_out_of_order('db1',10,random.randint(10000,50000),random.randint(1,10),1) + self.check_out_of_order('db1',random.randint(50,200),random.randint(10000,20000),random.randint(1,5),1) + + # self.check_out_of_order('db2',random.randint(50,200),random.randint(10000,50000),random.randint(5,50),1) + + # self.check_out_of_order('db3',random.randint(50,200),random.randint(10000,50000),random.randint(50,100),1) + + # self.check_out_of_order('db4',random.randint(50,200),random.randint(10000,50000),100,1) + endTime = time.time() print("total time %ds" % (endTime - startTime)) - - + + def stop(self): tdSql.close() tdLog.success("%s successfully executed" % __file__) diff --git a/tests/system-test/2-query/percentile.py b/tests/system-test/2-query/percentile.py index 935f55a8c2..e01aae97c0 100644 --- a/tests/system-test/2-query/percentile.py +++ b/tests/system-test/2-query/percentile.py @@ -50,7 +50,7 @@ class TDTestCase: 'col12': f'binary({self.binary_length})', 'col13': f'nchar({self.nchar_length})' } - + self.tag_dict = { 'ts_tag' : 'timestamp', 't1': 'tinyint', @@ -85,19 +85,19 @@ class TDTestCase: self.tag_values = [ f'{self.tag_ts},{self.tag_tinyint},{self.tag_smallint},{self.tag_int},{self.tag_bigint},\ {self.tag_utint},{self.tag_usint},{self.tag_uint},{self.tag_ubint},{self.tag_float},{self.tag_double},{self.tag_bool},"{self.binary_str}","{self.nchar_str}"' - + ] - + self.param = [1,50,100] - + def insert_data(self,column_dict,tbname,row_num): - intData = [] + intData = [] floatData = [] insert_sql = self.setsql.set_insertsql(column_dict,tbname,self.binary_str,self.nchar_str) for i in range(row_num): insert_list = [] self.setsql.insert_values(column_dict,i,insert_sql,insert_list,self.ts) - intData.append(i) + intData.append(i) floatData.append(i + 0.1) return intData,floatData def check_tags(self,tags,param,num,value): @@ -117,6 +117,20 @@ class TDTestCase: else: tdSql.query(f'select percentile({k}, {param}) from {self.ntbname}') tdSql.checkData(0, 0, np.percentile(floatData, param)) + + tdSql.query(f'select percentile(col1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100) from {self.ntbname}') + tdSql.checkData(0, 0, '[0.900000, 1.800000, 2.700000, 3.600000, 4.500000, 5.400000, 6.300000, 7.200000, 8.100000, 9.000000]') + + tdSql.query(f'select percentile(col1, 9.9, 19.9, 29.9, 39.9, 49.9, 59.9, 69.9, 79.9, 89.9, 99.9) from {self.ntbname}') + tdSql.checkData(0, 0, '[0.891000, 1.791000, 2.691000, 3.591000, 4.491000, 5.391000, 6.291000, 7.191000, 8.091000, 8.991000]') + + tdSql.error(f'select percentile(col1) from {self.ntbname}') + tdSql.error(f'select percentile(col1, -1) from {self.ntbname}') + tdSql.error(f'select percentile(col1, 101) from {self.ntbname}') + tdSql.error(f'select percentile(col1, col2) from {self.ntbname}') + tdSql.error(f'select percentile(1, col1) from {self.ntbname}') + tdSql.error(f'select percentile(col1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 101) from {self.ntbname}') + tdSql.execute(f'drop database {self.dbname}') def function_check_ctb(self): tdSql.execute(f'create database {self.dbname}') @@ -135,7 +149,7 @@ class TDTestCase: else: tdSql.query(f'select percentile({k}, {param}) from {self.stbname}_{i}') tdSql.checkData(0, 0, np.percentile(floatData, param)) - + for k,v in self.tag_dict.items(): for param in self.param: if v.lower() in ['timestamp','bool'] or 'binary' in v.lower() or 'nchar' in v.lower(): @@ -145,11 +159,25 @@ class TDTestCase: data_num = tdSql.queryResult[0][0] tdSql.query(f'select percentile({k},{param}) from {self.stbname}_{i}') tdSql.checkData(0,0,data_num) - tdSql.execute(f'drop database {self.dbname}') + + tdSql.query(f'select percentile(col1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100) from {self.stbname}_0') + tdSql.checkData(0, 0, '[0.900000, 1.800000, 2.700000, 3.600000, 4.500000, 5.400000, 6.300000, 7.200000, 8.100000, 9.000000]') + + tdSql.query(f'select percentile(col1, 9.9, 19.9, 29.9, 39.9, 49.9, 59.9, 69.9, 79.9, 89.9, 99.9) from {self.stbname}_0') + tdSql.checkData(0, 0, '[0.891000, 1.791000, 2.691000, 3.591000, 4.491000, 5.391000, 6.291000, 7.191000, 8.091000, 8.991000]') + + tdSql.error(f'select percentile(col1) from {self.stbname}_0') + tdSql.error(f'select percentile(col1, -1) from {self.stbname}_0') + tdSql.error(f'select percentile(col1, 101) from {self.stbname}_0') + tdSql.error(f'select percentile(col1, col2) from {self.stbname}_0') + tdSql.error(f'select percentile(1, col1) from {self.stbname}_0') + tdSql.error(f'select percentile(col1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 101) from {self.stbname}_0') + + tdSql.execute(f'drop database {self.dbname}') def run(self): self.function_check_ntb() self.function_check_ctb() - + def stop(self): tdSql.close() tdLog.success("%s successfully executed" % __file__) diff --git a/tests/system-test/2-query/tagFilter.py b/tests/system-test/2-query/tagFilter.py new file mode 100644 index 0000000000..b03776c31b --- /dev/null +++ b/tests/system-test/2-query/tagFilter.py @@ -0,0 +1,67 @@ +from util.log import * +from util.sql import * +from util.cases import * +from util.dnodes import * + + +INT_COL = "c1" +BINT_COL = "c2" +SINT_COL = "c3" +TINT_COL = "c4" +FLOAT_COL = "c5" +DOUBLE_COL = "c6" +BOOL_COL = "c7" + +BINARY_COL = "c8" +NCHAR_COL = "c9" +TS_COL = "c10" + +NUM_COL = [INT_COL, BINT_COL, SINT_COL, TINT_COL, FLOAT_COL, DOUBLE_COL, ] +UN_NUM_COL = [BOOL_COL, BINARY_COL, NCHAR_COL, ] +TS_TYPE_COL = [TS_COL] + +DBNAME = "db" + +class TDTestCase: + + def init(self, conn, logSql, replicaVar=1): + self.replicaVar = int(replicaVar) + tdLog.debug(f"start to excute {__file__}") + tdSql.init(conn.cursor()) + tdSql.execute(f'drop database if exists db') + tdSql.execute(f'create database if not exists db vgroups 1') + + def __create_tb(self, dbname="db"): + create_stb_sql = f'''create table {dbname}.stb1( + ts timestamp, f1 int + ) tags (tag1 binary(16300)) + ''' + tdSql.execute(create_stb_sql) + + tag_value = 'a' + for i in range(1200): + tag_value = tag_value + 'a' + + for i in range(8000): + tdSql.execute(f"create table {dbname}.ct{i+1} using {dbname}.stb1 tags ( '{tag_value}' )") + + def __query_data(self, rows, dbname="db"): + tdSql.execute( + f'''select count(*) from {dbname}.stb1 where tag1 like '%a' + ''' + ) + tdSql.checkRows(0) + + def run(self): + tdLog.printNoPrefix("==========step1:create table") + self.__create_tb() + + tdLog.printNoPrefix("==========step2:query data") + self.__query_data(10) + + def stop(self): + tdSql.close() + tdLog.success(f"{__file__} successfully executed") + +tdCases.addLinux(__file__, TDTestCase()) +tdCases.addWindows(__file__, TDTestCase()) diff --git a/tests/system-test/7-tmq/subscribeDb4.py b/tests/system-test/7-tmq/subscribeDb4.py index 7f5169361c..c14d3b27b1 100644 --- a/tests/system-test/7-tmq/subscribeDb4.py +++ b/tests/system-test/7-tmq/subscribeDb4.py @@ -31,7 +31,8 @@ class TDTestCase: 'startTs': 1640966400000, # 2022-01-01 00:00:00.000 'pollDelay': 20, 'showMsg': 1, - 'showRow': 1} + 'showRow': 1, + 'snapshot': 1} cdbName = 'cdb' # some parameter to consumer processor @@ -42,7 +43,7 @@ class TDTestCase: ifManualCommit = 1 groupId = 'group.id:cgrp1' autoCommit = 'enable.auto.commit:true' - autoCommitInterval = 'auto.commit.interval.ms:1000' + autoCommitInterval = 'auto.commit.interval.ms:100' autoOffset = 'auto.offset.reset:earliest' pollDelay = 20 @@ -86,7 +87,7 @@ class TDTestCase: tmqCom.insertConsumerInfo(self.consumerId, self.expectrowcnt,topicList,keyList,self.ifcheckdata,self.ifManualCommit) tdLog.info("start consume processor") - tmqCom.startTmqSimProcess(self.pollDelay,self.paraDict["dbName"],self.showMsg, self.showRow,self.cdbName) + tmqCom.startTmqSimProcess(self.pollDelay,self.paraDict["dbName"],self.showMsg, self.showRow,self.cdbName,0,0,self.paraDict["snapshot"]) tdLog.info("After waiting for a commit notify, drop one stable") #time.sleep(3) diff --git a/tests/system-test/7-tmq/tmqCommon.py b/tests/system-test/7-tmq/tmqCommon.py index 4cda062401..895da95e5d 100644 --- a/tests/system-test/7-tmq/tmqCommon.py +++ b/tests/system-test/7-tmq/tmqCommon.py @@ -151,7 +151,7 @@ class TMQCom: if tdSql.getData(i, 1) == 0: loopFlag = 0 break - time.sleep(0.1) + time.sleep(0.02) return def getStartCommitNotifyFromTmqsim(self,cdbName='cdb',rows=2): @@ -165,7 +165,7 @@ class TMQCom: if tdSql.getData(i, 1) == 1: loopFlag = 0 break - time.sleep(0.1) + time.sleep(0.02) return def create_database(self,tsql, dbName,dropFlag=1,vgroups=4,replica=1): diff --git a/tests/system-test/7-tmq/tmq_taosx.py b/tests/system-test/7-tmq/tmq_taosx.py index 593c91a470..c3ec4875ce 100644 --- a/tests/system-test/7-tmq/tmq_taosx.py +++ b/tests/system-test/7-tmq/tmq_taosx.py @@ -200,6 +200,7 @@ class TDTestCase: tdSql.checkData(1, 1, 1) tdSql.checkData(1, 2, '{"k1":1,"k2":"hello"}') + time.sleep(10) tdSql.query("select * from information_schema.ins_tables where table_name = 'stt4'") uid1 = tdSql.getData(0, 5) uid2 = tdSql.getData(1, 5) diff --git a/tools/shell/inc/shellInt.h b/tools/shell/inc/shellInt.h index 1fe09f5863..113853bd83 100644 --- a/tools/shell/inc/shellInt.h +++ b/tools/shell/inc/shellInt.h @@ -86,7 +86,7 @@ typedef struct { const char* promptContinue; const char* osname; int32_t promptSize; - char programVersion[32]; + char programVersion[256]; } SShellOsDetails; typedef struct { diff --git a/tools/shell/src/shellArguments.c b/tools/shell/src/shellArguments.c index 0612c2f455..19275cce82 100644 --- a/tools/shell/src/shellArguments.c +++ b/tools/shell/src/shellArguments.c @@ -413,7 +413,9 @@ int32_t shellParseArgs(int32_t argc, char *argv[]) { sprintf(shell.info.promptHeader, "%s> ", cusPrompt); shell.info.promptContinue = TAOS_CONSOLE_PROMPT_CONTINUE; shell.info.promptSize = strlen(shell.info.promptHeader); - snprintf(shell.info.programVersion, sizeof(shell.info.programVersion), "version: %s", version); + snprintf(shell.info.programVersion, sizeof(shell.info.programVersion), + "version: %s compatible_version: %s\ngitinfo: %s\nbuildInfo: %s", version, compatible_version, gitinfo, + buildinfo); #if defined(_TD_WINDOWS_64) || defined(_TD_WINDOWS_32) shell.info.osname = "Windows"; diff --git a/tools/shell/src/shellAuto.c b/tools/shell/src/shellAuto.c index 72386ba688..1d872e3f0d 100644 --- a/tools/shell/src/shellAuto.c +++ b/tools/shell/src/shellAuto.c @@ -911,7 +911,7 @@ char* matchNextPrefix(STire* tire, char* pre) { if (cursorVar == -1) { // first cursorVar = 0; - return strdup(match->head->word); + return taosStrdup(match->head->word); } // according to cursorVar , calculate next one @@ -927,7 +927,7 @@ char* matchNextPrefix(STire* tire, char* pre) { cursorVar = i; } - return strdup(item->word); + return taosStrdup(item->word); } // check end item @@ -935,7 +935,7 @@ char* matchNextPrefix(STire* tire, char* pre) { // if cursorVar > var list count, return last and reset cursorVar cursorVar = -1; - return strdup(item->word); + return taosStrdup(item->word); } // move next @@ -1536,7 +1536,7 @@ bool matchSelectQuery(TAOS* con, SShellCmd* cmd) { // if is input create fields or tags area, return true bool isCreateFieldsArea(char* p) { // put to while, support like create table st(ts timestamp, bin1 binary(16), bin2 + blank + TAB - char* p1 = strdup(p); + char* p1 = taosStrdup(p); bool ret = false; while (1) { char* left = strrchr(p1, '('); diff --git a/tools/shell/src/shellEngine.c b/tools/shell/src/shellEngine.c index 54d31cdb74..655fef383e 100644 --- a/tools/shell/src/shellEngine.c +++ b/tools/shell/src/shellEngine.c @@ -127,7 +127,7 @@ void shellRecordCommandToHistory(char *command) { if (pHistory->hist[pHistory->hend] != NULL) { taosMemoryFreeClear(pHistory->hist[pHistory->hend]); } - pHistory->hist[pHistory->hend] = strdup(command); + pHistory->hist[pHistory->hend] = taosStrdup(command); pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE; if (pHistory->hend == pHistory->hstart) { @@ -821,7 +821,7 @@ void shellReadHistory() { while ((read_size = taosGetsFile(pFile, TSDB_MAX_ALLOWED_SQL_LEN, line)) != -1) { line[read_size - 1] = '\0'; taosMemoryFree(pHistory->hist[pHistory->hend]); - pHistory->hist[pHistory->hend] = strdup(line); + pHistory->hist[pHistory->hend] = taosStrdup(line); pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE; @@ -845,6 +845,8 @@ void shellReadHistory() { i = (i + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE; } taosFprintfFile(pFile, "%s\n", pHistory->hist[endIndex]); + + /* coverity[+retval] */ taosFsyncFile(pFile); taosCloseFile(&pFile); } @@ -1105,7 +1107,7 @@ int32_t shellExecute() { if (runOnce) { if (pArgs->commands != NULL) { printf("%s%s\r\n", shell.info.promptHeader, pArgs->commands); - char *cmd = strdup(pArgs->commands); + char *cmd = taosStrdup(pArgs->commands); shellRunCommand(cmd, true); taosMemoryFree(cmd); } diff --git a/tools/shell/src/shellTire.c b/tools/shell/src/shellTire.c index 0ce0588cce..a8726f3126 100644 --- a/tools/shell/src/shellTire.c +++ b/tools/shell/src/shellTire.c @@ -75,7 +75,7 @@ void freeTire(STire* tire) { // insert a new word to list bool insertToList(STire* tire, char* word) { StrName* p = (StrName*)taosMemoryMalloc(sizeof(StrName)); - p->name = strdup(word); + p->name = taosStrdup(word); p->next = NULL; if (tire->head == NULL) { @@ -218,7 +218,7 @@ void addWordToMatch(SMatch* match, char* word) { // malloc new SMatchNode* node = (SMatchNode*)taosMemoryMalloc(sizeof(SMatchNode)); memset(node, 0, sizeof(SMatchNode)); - node->word = strdup(word); + node->word = taosStrdup(word); // append to match if (match->head == NULL) { diff --git a/utils/test/c/tmqSim.c b/utils/test/c/tmqSim.c index 9c1dc2e063..1acf50a7d8 100644 --- a/utils/test/c/tmqSim.c +++ b/utils/test/c/tmqSim.c @@ -400,7 +400,7 @@ TAOS* createNewTaosConnect() { int32_t retryCnt = 10; while (retryCnt--) { - TAOS* taos = taos_connect(NULL, "root", "taosdata", NULL, 0); + taos = taos_connect(NULL, "root", "taosdata", NULL, 0); if (NULL != taos) { return taos; } @@ -780,7 +780,8 @@ void loop_consume(SThreadInfo* pInfo) { if (pInfo->ifCheckData) { char filename[256] = {0}; - char tmpString[128]; + memset(tmpString, 0, tListLen(tmpString)); + // sprintf(filename, "%s/../log/consumerid_%d_%s.txt", configDir, pInfo->consumerId, // getCurrentTimeString(tmpString)); sprintf(filename, "%s/../log/consumerid_%d.txt", configDir, pInfo->consumerId); @@ -834,12 +835,12 @@ void loop_consume(SThreadInfo* pInfo) { } if ((totalRows >= pInfo->expectMsgCnt) || (totalMsgs >= pInfo->expectMsgCnt)) { - char tmpString[128]; + memset(tmpString, 0, tListLen(tmpString)); taosFprintfFile(g_fp, "%s over than expect rows, so break consume\n", getCurrentTimeString(tmpString)); break; } } else { - char tmpString[128]; + memset(tmpString, 0, tListLen(tmpString)); taosFprintfFile(g_fp, "%s no poll more msg when time over, break consume\n", getCurrentTimeString(tmpString)); break; } @@ -1113,7 +1114,7 @@ void omb_loop_consume(SThreadInfo* pInfo) { lastTotalLenOfMsg = totalLenOfMsg; } } else { - char tmpString[128]; + memset(tmpString, 0, tListLen(tmpString)); taosFprintfFile(g_fp, "%s no poll more msg when time over, break consume\n", getCurrentTimeString(tmpString)); printf("%s no poll more msg when time over, break consume\n", getCurrentTimeString(tmpString)); int64_t currentPrintTime = taosGetTimestampMs(); @@ -1381,7 +1382,7 @@ void startOmbConsume() { printf("SQL: %s\n", sql); queryDbExec(taos, sql, NO_INSERT_TYPE); - int32_t producerRate = ceil(g_stConfInfo.producerRate / g_stConfInfo.producers); + int32_t producerRate = ceil(((double)g_stConfInfo.producerRate) / g_stConfInfo.producers); printf("==== create %d produce thread ====\n", g_stConfInfo.producers); for (int32_t i = 0; i < g_stConfInfo.producers; ++i) { diff --git a/utils/test/c/tmq_taosx_ci.c b/utils/test/c/tmq_taosx_ci.c index fb05ae262b..3d458d90c1 100644 --- a/utils/test/c/tmq_taosx_ci.c +++ b/utils/test/c/tmq_taosx_ci.c @@ -21,20 +21,20 @@ #include "taos.h" #include "types.h" -static int running = 1; -TdFilePtr g_fp = NULL; -typedef struct{ +static int running = 1; +TdFilePtr g_fp = NULL; +typedef struct { bool snapShot; bool dropTable; bool subTable; int srcVgroups; int dstVgroups; char dir[64]; -}Config; +} Config; Config g_conf = {0}; -static TAOS* use_db(){ +static TAOS* use_db() { TAOS* pConn = taos_connect("localhost", "root", "taosdata", NULL, 0); if (pConn == NULL) { return NULL; @@ -53,12 +53,12 @@ static void msg_process(TAOS_RES* msg) { printf("-----------topic-------------: %s\n", tmq_get_topic_name(msg)); printf("db: %s\n", tmq_get_db_name(msg)); printf("vg: %d\n", tmq_get_vgroup_id(msg)); - TAOS *pConn = use_db(); + TAOS* pConn = use_db(); if (tmq_get_res_type(msg) == TMQ_RES_TABLE_META || tmq_get_res_type(msg) == TMQ_RES_METADATA) { char* result = tmq_get_json_meta(msg); if (result) { printf("meta result: %s\n", result); - if(g_fp && strcmp(result, "") != 0){ + if (g_fp && strcmp(result, "") != 0) { taosFprintfFile(g_fp, result); taosFprintfFile(g_fp, "\n"); } @@ -77,24 +77,23 @@ static void msg_process(TAOS_RES* msg) { taos_close(pConn); } -int buildDatabase(TAOS* pConn, TAOS_RES* pRes){ - +int buildDatabase(TAOS* pConn, TAOS_RES* pRes) { /* test for TD-20612 start*/ - pRes = taos_query(pConn,"create table tb1 (ts timestamp, c1 int, c2 int)"); + pRes = taos_query(pConn, "create table tb1 (ts timestamp, c1 int, c2 int)"); if (taos_errno(pRes) != 0) { printf("failed to create super table st1, reason:%s\n", taos_errstr(pRes)); return -1; } taos_free_result(pRes); - pRes = taos_query(pConn,"insert into tb1 (ts, c1) values(1669092069069, 0)"); + pRes = taos_query(pConn, "insert into tb1 (ts, c1) values(1669092069069, 0)"); if (taos_errno(pRes) != 0) { printf("failed to create super table st1, reason:%s\n", taos_errstr(pRes)); return -1; } taos_free_result(pRes); - pRes = taos_query(pConn,"insert into tb1 (ts, c2) values(1669092069069, 1)"); + pRes = taos_query(pConn, "insert into tb1 (ts, c2) values(1669092069069, 1)"); if (taos_errno(pRes) != 0) { printf("failed to create super table st1, reason:%s\n", taos_errstr(pRes)); return -1; @@ -154,7 +153,10 @@ int buildDatabase(TAOS* pConn, TAOS_RES* pRes){ } taos_free_result(pRes); - pRes = taos_query(pConn, "insert into ct3 values(1626006833600, 5, 6, 'c') ct1 values(1626006833601, 2, 3, 'sds') (1626006833602, 4, 5, 'ddd') ct0 values(1626006833603, 4, 3, 'hwj') ct1 values(now+5s, 23, 32, 's21ds')"); + pRes = taos_query( + pConn, + "insert into ct3 values(1626006833600, 5, 6, 'c') ct1 values(1626006833601, 2, 3, 'sds') (1626006833602, 4, 5, " + "'ddd') ct0 values(1626006833603, 4, 3, 'hwj') ct1 values(now+5s, 23, 32, 's21ds')"); if (taos_errno(pRes) != 0) { printf("failed to insert into ct3, reason:%s\n", taos_errstr(pRes)); return -1; @@ -175,7 +177,9 @@ int buildDatabase(TAOS* pConn, TAOS_RES* pRes){ } taos_free_result(pRes); - pRes = taos_query(pConn, "insert into ct3 values(1626006833605, 53, 63, 'cffffffffffffffffffffffffffff', 8989898899999) (1626006833609, 51, 62, 'c333', 940)"); + pRes = taos_query(pConn, + "insert into ct3 values(1626006833605, 53, 63, 'cffffffffffffffffffffffffffff', 8989898899999) " + "(1626006833609, 51, 62, 'c333', 940)"); if (taos_errno(pRes) != 0) { printf("failed to insert into ct3, reason:%s\n", taos_errstr(pRes)); return -1; @@ -210,8 +214,8 @@ int buildDatabase(TAOS* pConn, TAOS_RES* pRes){ } taos_free_result(pRes); - if(g_conf.dropTable){ - pRes = taos_query(pConn, "drop table ct3 ct1"); + if (g_conf.dropTable) { + pRes = taos_query(pConn, "drop table ct3, ct1"); if (taos_errno(pRes) != 0) { printf("failed to drop child table ct3, reason:%s\n", taos_errstr(pRes)); return -1; @@ -275,7 +279,7 @@ int buildDatabase(TAOS* pConn, TAOS_RES* pRes){ } taos_free_result(pRes); - if(g_conf.dropTable){ + if (g_conf.dropTable) { pRes = taos_query(pConn, "drop table n1"); if (taos_errno(pRes) != 0) { printf("failed to drop normal table n1, reason:%s\n", taos_errstr(pRes)); @@ -319,7 +323,7 @@ int buildDatabase(TAOS* pConn, TAOS_RES* pRes){ } taos_free_result(pRes); - if(g_conf.dropTable){ + if (g_conf.dropTable) { pRes = taos_query(pConn, "create stable if not exists st1 (ts timestamp, c1 int, c2 float, c3 binary(16)) tags(t1 int, t3 " "nchar(8), t4 bool)"); @@ -355,16 +359,22 @@ int buildDatabase(TAOS* pConn, TAOS_RES* pRes){ } taos_free_result(pRes); - pRes = taos_query(pConn, "create table if not exists stt1 using stt tags(2, \"stt1\", true) sttb1 using sttb tags(4, \"sttb1\", true) " - "stt2 using stt tags(43, \"stt2\", false) sttb2 using sttb tags(54, \"sttb2\", true)"); + pRes = taos_query( + pConn, + "create table if not exists stt1 using stt tags(2, \"stt1\", true) sttb1 using sttb tags(4, \"sttb1\", true) " + "stt2 using stt tags(43, \"stt2\", false) sttb2 using sttb tags(54, \"sttb2\", true)"); if (taos_errno(pRes) != 0) { printf("failed to create child table stt1, reason:%s\n", taos_errstr(pRes)); return -1; } taos_free_result(pRes); - pRes = taos_query(pConn, "insert into stt1 values(now + 2s, 3, 2, 'stt1') stt3 using stt tags(23, \"stt3\", true) values(now + 1s, 1, 2, 'stt3') sttb3 using sttb tags(4, \"sttb3\", true) values(now + 2s, 13, 22, 'sttb3') " - "stt4 using stt tags(433, \"stt4\", false) values(now + 3s, 21, 21, 'stt4') sttb4 using sttb tags(543, \"sttb4\", true) values(now + 4s, 16, 25, 'sttb4')"); + pRes = + taos_query(pConn, + "insert into stt1 values(now + 2s, 3, 2, 'stt1') stt3 using stt tags(23, \"stt3\", true) values(now + " + "1s, 1, 2, 'stt3') sttb3 using sttb tags(4, \"sttb3\", true) values(now + 2s, 13, 22, 'sttb3') " + "stt4 using stt tags(433, \"stt4\", false) values(now + 3s, 21, 21, 'stt4') sttb4 using sttb " + "tags(543, \"sttb4\", true) values(now + 4s, 16, 25, 'sttb4')"); if (taos_errno(pRes) != 0) { printf("failed to create child table stt1, reason:%s\n", taos_errstr(pRes)); return -1; @@ -374,8 +384,10 @@ int buildDatabase(TAOS* pConn, TAOS_RES* pRes){ return 0; } -int buildStable(TAOS* pConn, TAOS_RES* pRes){ - pRes = taos_query(pConn, "CREATE STABLE `meters` (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) TAGS (`groupid` INT, `location` VARCHAR(16))"); +int buildStable(TAOS* pConn, TAOS_RES* pRes) { + pRes = taos_query(pConn, + "CREATE STABLE `meters` (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) TAGS " + "(`groupid` INT, `location` VARCHAR(16))"); if (taos_errno(pRes) != 0) { printf("failed to create super table meters, reason:%s\n", taos_errstr(pRes)); return -1; @@ -396,7 +408,9 @@ int buildStable(TAOS* pConn, TAOS_RES* pRes){ } taos_free_result(pRes); - pRes = taos_query(pConn, "create stream meters_summary_s into meters_summary as select _wstart, max(current) as current, groupid, location from meters partition by groupid, location interval(10m)"); + pRes = taos_query(pConn, + "create stream meters_summary_s into meters_summary as select _wstart, max(current) as current, " + "groupid, location from meters partition by groupid, location interval(10m)"); if (taos_errno(pRes) != 0) { printf("failed to create super table meters_summary, reason:%s\n", taos_errstr(pRes)); return -1; @@ -471,9 +485,9 @@ int32_t init_env() { } taos_free_result(pRes); - if(g_conf.subTable){ + if (g_conf.subTable) { buildStable(pConn, pRes); - }else{ + } else { buildDatabase(pConn, pRes); } @@ -496,14 +510,14 @@ int32_t create_topic() { } taos_free_result(pRes); - if(g_conf.subTable){ + if (g_conf.subTable) { pRes = taos_query(pConn, "create topic meters_summary_t1 with meta as stable meters_summary"); if (taos_errno(pRes) != 0) { printf("failed to create topic meters_summary_t1, reason:%s\n", taos_errstr(pRes)); return -1; } taos_free_result(pRes); - }else{ + } else { pRes = taos_query(pConn, "create topic topic_db with meta as database abc1"); if (taos_errno(pRes) != 0) { printf("failed to create topic topic_db, reason:%s\n", taos_errstr(pRes)); @@ -530,7 +544,7 @@ tmq_t* build_consumer() { tmq_conf_set(conf, "enable.auto.commit", "true"); tmq_conf_set(conf, "enable.heartbeat.background", "true"); - if(g_conf.snapShot){ + if (g_conf.snapShot) { tmq_conf_set(conf, "experimental.snapshot.enable", "true"); } @@ -543,9 +557,9 @@ tmq_t* build_consumer() { tmq_list_t* build_topic_list() { tmq_list_t* topic_list = tmq_list_new(); - if(g_conf.subTable){ + if (g_conf.subTable) { tmq_list_append(topic_list, "meters_summary_t1"); - }else{ + } else { tmq_list_append(topic_list, "topic_db"); } return topic_list; @@ -566,7 +580,7 @@ void basic_consume_loop(tmq_t* tmq, tmq_list_t* topics) { cnt++; msg_process(tmqmessage); taos_free_result(tmqmessage); - }else{ + } else { break; } } @@ -582,10 +596,10 @@ void initLogFile() { char f1[256] = {0}; char f2[256] = {0}; - if(g_conf.snapShot){ + if (g_conf.snapShot) { sprintf(f1, "%s/../log/tmq_taosx_tmp_snapshot.source", g_conf.dir); sprintf(f2, "%s/../log/tmq_taosx_tmp_snapshot.result", g_conf.dir); - }else{ + } else { sprintf(f1, "%s/../log/tmq_taosx_tmp.source", g_conf.dir); sprintf(f2, "%s/../log/tmq_taosx_tmp.result", g_conf.dir); } @@ -603,84 +617,169 @@ void initLogFile() { exit(-1); } - if(g_conf.snapShot){ - if(g_conf.subTable){ - char *result[] = { - "{\"type\":\"create\",\"tableType\":\"super\",\"tableName\":\"meters_summary\",\"columns\":[{\"name\":\"_wstart\",\"type\":9},{\"name\":\"current\",\"type\":6},{\"name\":\"groupid\",\"type\":4},{\"name\":\"location\",\"type\":8,\"length\":16}],\"tags\":[{\"name\":\"group_id\",\"type\":14}]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"t_d2a450ee819dcf7576f0282d9ac22dbc\",\"using\":\"meters_summary\",\"tagNum\":1,\"tags\":[{\"name\":\"group_id\",\"type\":14,\"value\":1.313555008277358e+19}],\"createList\":[]}" - }; - for(int i = 0; i < sizeof(result)/sizeof(result[0]); i++){ + if (g_conf.snapShot) { + if (g_conf.subTable) { + char* result[] = { + "{\"type\":\"create\",\"tableType\":\"super\",\"tableName\":\"meters_summary\",\"columns\":[{\"name\":\"_" + "wstart\",\"type\":9},{\"name\":\"current\",\"type\":6},{\"name\":\"groupid\",\"type\":4},{\"name\":" + "\"location\",\"type\":8,\"length\":16}],\"tags\":[{\"name\":\"group_id\",\"type\":14}]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"t_d2a450ee819dcf7576f0282d9ac22dbc\",\"using\":" + "\"meters_summary\",\"tagNum\":1,\"tags\":[{\"name\":\"group_id\",\"type\":14,\"value\":1.313555008277358e+" + "19}],\"createList\":[]}"}; + for (int i = 0; i < sizeof(result) / sizeof(result[0]); i++) { taosFprintfFile(pFile2, result[i]); taosFprintfFile(pFile2, "\n"); } - }else{ - char *result[] = { - "{\"type\":\"create\",\"tableType\":\"normal\",\"tableName\":\"tb1\",\"columns\":[{\"name\":\"ts\",\"type\":9},{\"name\":\"c1\",\"type\":4},{\"name\":\"c2\",\"type\":4}],\"tags\":[]}", - "{\"type\":\"create\",\"tableType\":\"super\",\"tableName\":\"st1\",\"columns\":[{\"name\":\"ts\",\"type\":9},{\"name\":\"c1\",\"type\":4},{\"name\":\"c2\",\"type\":6},{\"name\":\"c3\",\"type\":8,\"length\":64},{\"name\":\"c4\",\"type\":5}],\"tags\":[{\"name\":\"t1\",\"type\":4},{\"name\":\"t3\",\"type\":10,\"length\":8},{\"name\":\"t4\",\"type\":1},{\"name\":\"t2\",\"type\":8,\"length\":64}]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"ct0\",\"using\":\"st1\",\"tagNum\":4,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":1000},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"ttt\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}],\"createList\":[]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"ct1\",\"using\":\"st1\",\"tagNum\":4,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":2000}],\"createList\":[]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"ct2\",\"using\":\"st1\",\"tagNum\":4,\"tags\":[],\"createList\":[]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"ct3\",\"using\":\"st1\",\"tagNum\":4,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":5000}],\"createList\":[]}", - "{\"type\":\"create\",\"tableType\":\"normal\",\"tableName\":\"n1\",\"columns\":[{\"name\":\"ts\",\"type\":9},{\"name\":\"c2\",\"type\":10,\"length\":8},{\"name\":\"cc3\",\"type\":5}],\"tags\":[]}", - "{\"type\":\"create\",\"tableType\":\"super\",\"tableName\":\"jt\",\"columns\":[{\"name\":\"ts\",\"type\":9},{\"name\":\"i\",\"type\":4}],\"tags\":[{\"name\":\"t\",\"type\":15}]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"jt1\",\"using\":\"jt\",\"tagNum\":1,\"tags\":[{\"name\":\"t\",\"type\":15,\"value\":\"{\\\"k1\\\":1,\\\"k2\\\":\\\"hello\\\"}\"}],\"createList\":[]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"jt2\",\"using\":\"jt\",\"tagNum\":1,\"tags\":[],\"createList\":[]}", - "{\"type\":\"create\",\"tableType\":\"super\",\"tableName\":\"stt\",\"columns\":[{\"name\":\"ts\",\"type\":9},{\"name\":\"c1\",\"type\":4},{\"name\":\"c2\",\"type\":6},{\"name\":\"c3\",\"type\":8,\"length\":16}],\"tags\":[{\"name\":\"t1\",\"type\":4},{\"name\":\"t3\",\"type\":10,\"length\":8},{\"name\":\"t4\",\"type\":1}]}", - "{\"type\":\"create\",\"tableType\":\"super\",\"tableName\":\"sttb\",\"columns\":[{\"name\":\"ts\",\"type\":9},{\"name\":\"c1\",\"type\":4},{\"name\":\"c2\",\"type\":6},{\"name\":\"c3\",\"type\":8,\"length\":16}],\"tags\":[{\"name\":\"t1\",\"type\":4},{\"name\":\"t3\",\"type\":10,\"length\":8},{\"name\":\"t4\",\"type\":1}]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"stt1\",\"using\":\"stt\",\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":2},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"stt1\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}],\"createList\":[]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"sttb1\",\"using\":\"sttb\",\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":4},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"sttb1\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}],\"createList\":[]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"stt2\",\"using\":\"stt\",\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":43},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"stt2\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":0}],\"createList\":[]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"sttb2\",\"using\":\"sttb\",\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":54},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"sttb2\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}],\"createList\":[]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"stt3\",\"using\":\"stt\",\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":23},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"stt3\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}],\"createList\":[]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"sttb3\",\"using\":\"sttb\",\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":4},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"sttb3\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}],\"createList\":[]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"stt4\",\"using\":\"stt\",\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":433},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"stt4\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":0}],\"createList\":[]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"sttb4\",\"using\":\"sttb\",\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":543},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"sttb4\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}],\"createList\":[]}" - }; - for(int i = 0; i < sizeof(result)/sizeof(result[0]); i++){ + } else { + char* result[] = { + "{\"type\":\"create\",\"tableType\":\"normal\",\"tableName\":\"tb1\",\"columns\":[{\"name\":\"ts\",\"type\":" + "9},{\"name\":\"c1\",\"type\":4},{\"name\":\"c2\",\"type\":4}],\"tags\":[]}", + "{\"type\":\"create\",\"tableType\":\"super\",\"tableName\":\"st1\",\"columns\":[{\"name\":\"ts\",\"type\":9}" + ",{\"name\":\"c1\",\"type\":4},{\"name\":\"c2\",\"type\":6},{\"name\":\"c3\",\"type\":8,\"length\":64},{" + "\"name\":\"c4\",\"type\":5}],\"tags\":[{\"name\":\"t1\",\"type\":4},{\"name\":\"t3\",\"type\":10,\"length\":" + "8},{\"name\":\"t4\",\"type\":1},{\"name\":\"t2\",\"type\":8,\"length\":64}]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"ct0\",\"using\":\"st1\",\"tagNum\":4,\"tags\":[" + "{\"name\":\"t1\",\"type\":4,\"value\":1000},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"ttt\\\"\"},{" + "\"name\":\"t4\",\"type\":1,\"value\":1}],\"createList\":[]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"ct1\",\"using\":\"st1\",\"tagNum\":4,\"tags\":[" + "{\"name\":\"t1\",\"type\":4,\"value\":2000}],\"createList\":[]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"ct2\",\"using\":\"st1\",\"tagNum\":4,\"tags\":[" + "],\"createList\":[]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"ct3\",\"using\":\"st1\",\"tagNum\":4,\"tags\":[" + "{\"name\":\"t1\",\"type\":4,\"value\":5000}],\"createList\":[]}", + "{\"type\":\"create\",\"tableType\":\"normal\",\"tableName\":\"n1\",\"columns\":[{\"name\":\"ts\",\"type\":9}" + ",{\"name\":\"c2\",\"type\":10,\"length\":8},{\"name\":\"cc3\",\"type\":5}],\"tags\":[]}", + "{\"type\":\"create\",\"tableType\":\"super\",\"tableName\":\"jt\",\"columns\":[{\"name\":\"ts\",\"type\":9}," + "{\"name\":\"i\",\"type\":4}],\"tags\":[{\"name\":\"t\",\"type\":15}]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"jt1\",\"using\":\"jt\",\"tagNum\":1,\"tags\":[{" + "\"name\":\"t\",\"type\":15,\"value\":\"{\\\"k1\\\":1,\\\"k2\\\":\\\"hello\\\"}\"}],\"createList\":[]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"jt2\",\"using\":\"jt\",\"tagNum\":1,\"tags\":[]" + ",\"createList\":[]}", + "{\"type\":\"create\",\"tableType\":\"super\",\"tableName\":\"stt\",\"columns\":[{\"name\":\"ts\",\"type\":9}" + ",{\"name\":\"c1\",\"type\":4},{\"name\":\"c2\",\"type\":6},{\"name\":\"c3\",\"type\":8,\"length\":16}]," + "\"tags\":[{\"name\":\"t1\",\"type\":4},{\"name\":\"t3\",\"type\":10,\"length\":8},{\"name\":\"t4\",\"type\":" + "1}]}", + "{\"type\":\"create\",\"tableType\":\"super\",\"tableName\":\"sttb\",\"columns\":[{\"name\":\"ts\",\"type\":" + "9},{\"name\":\"c1\",\"type\":4},{\"name\":\"c2\",\"type\":6},{\"name\":\"c3\",\"type\":8,\"length\":16}]," + "\"tags\":[{\"name\":\"t1\",\"type\":4},{\"name\":\"t3\",\"type\":10,\"length\":8},{\"name\":\"t4\",\"type\":" + "1}]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"stt1\",\"using\":\"stt\",\"tagNum\":3,\"tags\":" + "[{\"name\":\"t1\",\"type\":4,\"value\":2},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"stt1\\\"\"},{" + "\"name\":\"t4\",\"type\":1,\"value\":1}],\"createList\":[]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"sttb1\",\"using\":\"sttb\",\"tagNum\":3," + "\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":4},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"sttb1\\\"\"}" + ",{\"name\":\"t4\",\"type\":1,\"value\":1}],\"createList\":[]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"stt2\",\"using\":\"stt\",\"tagNum\":3,\"tags\":" + "[{\"name\":\"t1\",\"type\":4,\"value\":43},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"stt2\\\"\"},{" + "\"name\":\"t4\",\"type\":1,\"value\":0}],\"createList\":[]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"sttb2\",\"using\":\"sttb\",\"tagNum\":3," + "\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":54},{\"name\":\"t3\",\"type\":10,\"value\":" + "\"\\\"sttb2\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}],\"createList\":[]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"stt3\",\"using\":\"stt\",\"tagNum\":3,\"tags\":" + "[{\"name\":\"t1\",\"type\":4,\"value\":23},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"stt3\\\"\"},{" + "\"name\":\"t4\",\"type\":1,\"value\":1}],\"createList\":[]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"sttb3\",\"using\":\"sttb\",\"tagNum\":3," + "\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":4},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"sttb3\\\"\"}" + ",{\"name\":\"t4\",\"type\":1,\"value\":1}],\"createList\":[]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"stt4\",\"using\":\"stt\",\"tagNum\":3,\"tags\":" + "[{\"name\":\"t1\",\"type\":4,\"value\":433},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"stt4\\\"\"},{" + "\"name\":\"t4\",\"type\":1,\"value\":0}],\"createList\":[]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"sttb4\",\"using\":\"sttb\",\"tagNum\":3," + "\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":543},{\"name\":\"t3\",\"type\":10,\"value\":" + "\"\\\"sttb4\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}],\"createList\":[]}"}; + for (int i = 0; i < sizeof(result) / sizeof(result[0]); i++) { taosFprintfFile(pFile2, result[i]); taosFprintfFile(pFile2, "\n"); } } - }else{ - if(g_conf.subTable){ - char *result[] = { - "{\"type\":\"create\",\"tableType\":\"super\",\"tableName\":\"meters_summary\",\"columns\":[{\"name\":\"_wstart\",\"type\":9},{\"name\":\"current\",\"type\":6},{\"name\":\"groupid\",\"type\":4},{\"name\":\"location\",\"type\":8,\"length\":16}],\"tags\":[{\"name\":\"group_id\",\"type\":14}]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"t_d2a450ee819dcf7576f0282d9ac22dbc\",\"using\":\"meters_summary\",\"tagNum\":1,\"tags\":[{\"name\":\"group_id\",\"type\":14,\"value\":1.313555008277358e+19}],\"createList\":[]}" - }; + } else { + if (g_conf.subTable) { + char* result[] = { + "{\"type\":\"create\",\"tableType\":\"super\",\"tableName\":\"meters_summary\",\"columns\":[{\"name\":\"_" + "wstart\",\"type\":9},{\"name\":\"current\",\"type\":6},{\"name\":\"groupid\",\"type\":4},{\"name\":" + "\"location\",\"type\":8,\"length\":16}],\"tags\":[{\"name\":\"group_id\",\"type\":14}]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"t_d2a450ee819dcf7576f0282d9ac22dbc\",\"using\":" + "\"meters_summary\",\"tagNum\":1,\"tags\":[{\"name\":\"group_id\",\"type\":14,\"value\":1.313555008277358e+" + "19}],\"createList\":[]}"}; - for(int i = 0; i < sizeof(result)/sizeof(result[0]); i++){ + for (int i = 0; i < sizeof(result) / sizeof(result[0]); i++) { taosFprintfFile(pFile2, result[i]); taosFprintfFile(pFile2, "\n"); } - }else{ - char *result[] = { - "{\"type\":\"create\",\"tableType\":\"normal\",\"tableName\":\"tb1\",\"columns\":[{\"name\":\"ts\",\"type\":9},{\"name\":\"c1\",\"type\":4},{\"name\":\"c2\",\"type\":4}],\"tags\":[]}", - "{\"type\":\"create\",\"tableType\":\"super\",\"tableName\":\"st1\",\"columns\":[{\"name\":\"ts\",\"type\":9},{\"name\":\"c1\",\"type\":4},{\"name\":\"c2\",\"type\":6},{\"name\":\"c3\",\"type\":8,\"length\":16}],\"tags\":[{\"name\":\"t1\",\"type\":4},{\"name\":\"t3\",\"type\":10,\"length\":8},{\"name\":\"t4\",\"type\":1}]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"ct0\",\"using\":\"st1\",\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":1000},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"ttt\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}],\"createList\":[]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"ct1\",\"using\":\"st1\",\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":2000}],\"createList\":[]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"ct2\",\"using\":\"st1\",\"tagNum\":3,\"tags\":[],\"createList\":[]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"ct3\",\"using\":\"st1\",\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":3000}],\"createList\":[]}", - "{\"type\":\"alter\",\"tableType\":\"super\",\"tableName\":\"st1\",\"alterType\":5,\"colName\":\"c4\",\"colType\":5}", - "{\"type\":\"alter\",\"tableType\":\"super\",\"tableName\":\"st1\",\"alterType\":7,\"colName\":\"c3\",\"colType\":8,\"colLength\":64}", - "{\"type\":\"alter\",\"tableType\":\"super\",\"tableName\":\"st1\",\"alterType\":1,\"colName\":\"t2\",\"colType\":8,\"colLength\":64}", - "{\"type\":\"alter\",\"tableType\":\"child\",\"tableName\":\"ct3\",\"alterType\":4,\"colName\":\"t1\",\"colValue\":\"5000\",\"colValueNull\":false}", + } else { + char* result[] = { + "{\"type\":\"create\",\"tableType\":\"normal\",\"tableName\":\"tb1\",\"columns\":[{\"name\":\"ts\",\"type\":" + "9},{\"name\":\"c1\",\"type\":4},{\"name\":\"c2\",\"type\":4}],\"tags\":[]}", + "{\"type\":\"create\",\"tableType\":\"super\",\"tableName\":\"st1\",\"columns\":[{\"name\":\"ts\",\"type\":9}" + ",{\"name\":\"c1\",\"type\":4},{\"name\":\"c2\",\"type\":6},{\"name\":\"c3\",\"type\":8,\"length\":16}]," + "\"tags\":[{\"name\":\"t1\",\"type\":4},{\"name\":\"t3\",\"type\":10,\"length\":8},{\"name\":\"t4\",\"type\":" + "1}]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"ct0\",\"using\":\"st1\",\"tagNum\":3,\"tags\":[" + "{\"name\":\"t1\",\"type\":4,\"value\":1000},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"ttt\\\"\"},{" + "\"name\":\"t4\",\"type\":1,\"value\":1}],\"createList\":[]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"ct1\",\"using\":\"st1\",\"tagNum\":3,\"tags\":[" + "{\"name\":\"t1\",\"type\":4,\"value\":2000}],\"createList\":[]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"ct2\",\"using\":\"st1\",\"tagNum\":3,\"tags\":[" + "],\"createList\":[]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"ct3\",\"using\":\"st1\",\"tagNum\":3,\"tags\":[" + "{\"name\":\"t1\",\"type\":4,\"value\":3000}],\"createList\":[]}", + "{\"type\":\"alter\",\"tableType\":\"super\",\"tableName\":\"st1\",\"alterType\":5,\"colName\":\"c4\"," + "\"colType\":5}", + "{\"type\":\"alter\",\"tableType\":\"super\",\"tableName\":\"st1\",\"alterType\":7,\"colName\":\"c3\"," + "\"colType\":8,\"colLength\":64}", + "{\"type\":\"alter\",\"tableType\":\"super\",\"tableName\":\"st1\",\"alterType\":1,\"colName\":\"t2\"," + "\"colType\":8,\"colLength\":64}", + "{\"type\":\"alter\",\"tableType\":\"child\",\"tableName\":\"ct3\",\"alterType\":4,\"colName\":\"t1\"," + "\"colValue\":\"5000\",\"colValueNull\":false}", "{\"type\":\"delete\",\"sql\":\"delete from `ct3` where `ts` >= 1626006833600 and `ts` <= 1626006833605\"}", - "{\"type\":\"create\",\"tableType\":\"normal\",\"tableName\":\"n1\",\"columns\":[{\"name\":\"ts\",\"type\":9},{\"name\":\"c1\",\"type\":4},{\"name\":\"c2\",\"type\":10,\"length\":4}],\"tags\":[]}", - "{\"type\":\"alter\",\"tableType\":\"normal\",\"tableName\":\"n1\",\"alterType\":5,\"colName\":\"c3\",\"colType\":5}", - "{\"type\":\"alter\",\"tableType\":\"normal\",\"tableName\":\"n1\",\"alterType\":7,\"colName\":\"c2\",\"colType\":10,\"colLength\":8}", - "{\"type\":\"alter\",\"tableType\":\"normal\",\"tableName\":\"n1\",\"alterType\":10,\"colName\":\"c3\",\"colNewName\":\"cc3\"}", + "{\"type\":\"create\",\"tableType\":\"normal\",\"tableName\":\"n1\",\"columns\":[{\"name\":\"ts\",\"type\":9}" + ",{\"name\":\"c1\",\"type\":4},{\"name\":\"c2\",\"type\":10,\"length\":4}],\"tags\":[]}", + "{\"type\":\"alter\",\"tableType\":\"normal\",\"tableName\":\"n1\",\"alterType\":5,\"colName\":\"c3\"," + "\"colType\":5}", + "{\"type\":\"alter\",\"tableType\":\"normal\",\"tableName\":\"n1\",\"alterType\":7,\"colName\":\"c2\"," + "\"colType\":10,\"colLength\":8}", + "{\"type\":\"alter\",\"tableType\":\"normal\",\"tableName\":\"n1\",\"alterType\":10,\"colName\":\"c3\"," + "\"colNewName\":\"cc3\"}", "{\"type\":\"alter\",\"tableType\":\"normal\",\"tableName\":\"n1\",\"alterType\":9}", "{\"type\":\"alter\",\"tableType\":\"normal\",\"tableName\":\"n1\",\"alterType\":6,\"colName\":\"c1\"}", - "{\"type\":\"create\",\"tableType\":\"super\",\"tableName\":\"jt\",\"columns\":[{\"name\":\"ts\",\"type\":9},{\"name\":\"i\",\"type\":4}],\"tags\":[{\"name\":\"t\",\"type\":15}]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"jt1\",\"using\":\"jt\",\"tagNum\":1,\"tags\":[{\"name\":\"t\",\"type\":15,\"value\":\"{\\\"k1\\\":1,\\\"k2\\\":\\\"hello\\\"}\"}],\"createList\":[]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"jt2\",\"using\":\"jt\",\"tagNum\":1,\"tags\":[],\"createList\":[]}", - "{\"type\":\"create\",\"tableType\":\"super\",\"tableName\":\"stt\",\"columns\":[{\"name\":\"ts\",\"type\":9},{\"name\":\"c1\",\"type\":4},{\"name\":\"c2\",\"type\":6},{\"name\":\"c3\",\"type\":8,\"length\":16}],\"tags\":[{\"name\":\"t1\",\"type\":4},{\"name\":\"t3\",\"type\":10,\"length\":8},{\"name\":\"t4\",\"type\":1}]}", - "{\"type\":\"create\",\"tableType\":\"super\",\"tableName\":\"sttb\",\"columns\":[{\"name\":\"ts\",\"type\":9},{\"name\":\"c1\",\"type\":4},{\"name\":\"c2\",\"type\":6},{\"name\":\"c3\",\"type\":8,\"length\":16}],\"tags\":[{\"name\":\"t1\",\"type\":4},{\"name\":\"t3\",\"type\":10,\"length\":8},{\"name\":\"t4\",\"type\":1}]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"stt1\",\"using\":\"stt\",\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":2},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"stt1\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}],\"createList\":[{\"tableName\":\"stt1\",\"using\":\"stt\",\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":2},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"stt1\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}]},{\"tableName\":\"sttb1\",\"using\":\"sttb\",\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":4},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"sttb1\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}]},{\"tableName\":\"stt2\",\"using\":\"stt\",\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":43},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"stt2\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":0}]},{\"tableName\":\"sttb2\",\"using\":\"sttb\",\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":54},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"sttb2\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}]}]}", - "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"stt3\",\"using\":\"stt\",\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":23},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"stt3\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}],\"createList\":[{\"tableName\":\"stt3\",\"using\":\"stt\",\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":23},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"stt3\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}]},{\"tableName\":\"sttb3\",\"using\":\"sttb\",\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":4},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"sttb3\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}]},{\"tableName\":\"stt4\",\"using\":\"stt\",\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":433},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"stt4\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":0}]},{\"tableName\":\"sttb4\",\"using\":\"sttb\",\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":543},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"sttb4\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}]}]}" - }; + "{\"type\":\"create\",\"tableType\":\"super\",\"tableName\":\"jt\",\"columns\":[{\"name\":\"ts\",\"type\":9}," + "{\"name\":\"i\",\"type\":4}],\"tags\":[{\"name\":\"t\",\"type\":15}]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"jt1\",\"using\":\"jt\",\"tagNum\":1,\"tags\":[{" + "\"name\":\"t\",\"type\":15,\"value\":\"{\\\"k1\\\":1,\\\"k2\\\":\\\"hello\\\"}\"}],\"createList\":[]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"jt2\",\"using\":\"jt\",\"tagNum\":1,\"tags\":[]" + ",\"createList\":[]}", + "{\"type\":\"create\",\"tableType\":\"super\",\"tableName\":\"stt\",\"columns\":[{\"name\":\"ts\",\"type\":9}" + ",{\"name\":\"c1\",\"type\":4},{\"name\":\"c2\",\"type\":6},{\"name\":\"c3\",\"type\":8,\"length\":16}]," + "\"tags\":[{\"name\":\"t1\",\"type\":4},{\"name\":\"t3\",\"type\":10,\"length\":8},{\"name\":\"t4\",\"type\":" + "1}]}", + "{\"type\":\"create\",\"tableType\":\"super\",\"tableName\":\"sttb\",\"columns\":[{\"name\":\"ts\",\"type\":" + "9},{\"name\":\"c1\",\"type\":4},{\"name\":\"c2\",\"type\":6},{\"name\":\"c3\",\"type\":8,\"length\":16}]," + "\"tags\":[{\"name\":\"t1\",\"type\":4},{\"name\":\"t3\",\"type\":10,\"length\":8},{\"name\":\"t4\",\"type\":" + "1}]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"stt1\",\"using\":\"stt\",\"tagNum\":3,\"tags\":" + "[{\"name\":\"t1\",\"type\":4,\"value\":2},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"stt1\\\"\"},{" + "\"name\":\"t4\",\"type\":1,\"value\":1}],\"createList\":[{\"tableName\":\"stt1\",\"using\":\"stt\"," + "\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":2},{\"name\":\"t3\",\"type\":10,\"value\":" + "\"\\\"stt1\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}]},{\"tableName\":\"sttb1\",\"using\":\"sttb\"," + "\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":4},{\"name\":\"t3\",\"type\":10,\"value\":" + "\"\\\"sttb1\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}]},{\"tableName\":\"stt2\",\"using\":\"stt\"," + "\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":43},{\"name\":\"t3\",\"type\":10,\"value\":" + "\"\\\"stt2\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":0}]},{\"tableName\":\"sttb2\",\"using\":\"sttb\"," + "\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":54},{\"name\":\"t3\",\"type\":10,\"value\":" + "\"\\\"sttb2\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}]}]}", + "{\"type\":\"create\",\"tableType\":\"child\",\"tableName\":\"stt3\",\"using\":\"stt\",\"tagNum\":3,\"tags\":" + "[{\"name\":\"t1\",\"type\":4,\"value\":23},{\"name\":\"t3\",\"type\":10,\"value\":\"\\\"stt3\\\"\"},{" + "\"name\":\"t4\",\"type\":1,\"value\":1}],\"createList\":[{\"tableName\":\"stt3\",\"using\":\"stt\"," + "\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":23},{\"name\":\"t3\",\"type\":10,\"value\":" + "\"\\\"stt3\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}]},{\"tableName\":\"sttb3\",\"using\":\"sttb\"," + "\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":4},{\"name\":\"t3\",\"type\":10,\"value\":" + "\"\\\"sttb3\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}]},{\"tableName\":\"stt4\",\"using\":\"stt\"," + "\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":433},{\"name\":\"t3\",\"type\":10,\"value\":" + "\"\\\"stt4\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":0}]},{\"tableName\":\"sttb4\",\"using\":\"sttb\"," + "\"tagNum\":3,\"tags\":[{\"name\":\"t1\",\"type\":4,\"value\":543},{\"name\":\"t3\",\"type\":10,\"value\":" + "\"\\\"sttb4\\\"\"},{\"name\":\"t4\",\"type\":1,\"value\":1}]}]}"}; - for(int i = 0; i < sizeof(result)/sizeof(result[0]); i++){ + for (int i = 0; i < sizeof(result) / sizeof(result[0]); i++) { taosFprintfFile(pFile2, result[i]); taosFprintfFile(pFile2, "\n"); } @@ -692,23 +791,23 @@ void initLogFile() { int main(int argc, char* argv[]) { for (int32_t i = 1; i < argc; i++) { - if(strcmp(argv[i], "-c") == 0){ + if (strcmp(argv[i], "-c") == 0) { tstrncpy(g_conf.dir, argv[++i], sizeof(g_conf.dir)); - }else if(strcmp(argv[i], "-s") == 0){ + } else if (strcmp(argv[i], "-s") == 0) { g_conf.snapShot = true; - }else if(strcmp(argv[i], "-d") == 0){ + } else if (strcmp(argv[i], "-d") == 0) { g_conf.dropTable = true; - }else if(strcmp(argv[i], "-sv") == 0){ + } else if (strcmp(argv[i], "-sv") == 0) { g_conf.srcVgroups = atol(argv[++i]); - }else if(strcmp(argv[i], "-dv") == 0){ + } else if (strcmp(argv[i], "-dv") == 0) { g_conf.dstVgroups = atol(argv[++i]); - }else if(strcmp(argv[i], "-t") == 0){ + } else if (strcmp(argv[i], "-t") == 0) { g_conf.subTable = true; } } printf("env init\n"); - if(strlen(g_conf.dir) != 0){ + if (strlen(g_conf.dir) != 0) { initLogFile(); } diff --git a/utils/tsim/src/simExe.c b/utils/tsim/src/simExe.c index 258c611557..d82c948cf7 100644 --- a/utils/tsim/src/simExe.c +++ b/utils/tsim/src/simExe.c @@ -31,7 +31,7 @@ void simLogSql(char *sql, bool useSharp) { taosFprintfFile(pFile, "%s;\n", sql); } - taosFsyncFile(pFile); + UNUSED(taosFsyncFile(pFile)); } }