1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
/*
 * Sai server
 *
 * Copyright (C) 2019 - 2025 Andy Green <andy@warmcat.com>
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation:
 *  version 2.1 of the License.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *  MA  02110-1301  USA
 *
 * The same ws interface is connected-to by builders (on path /builder), and
 * provides the query transport for browsers (on path /browse).
 *
 * There's a single server slite3 database containing events, and a separate
 * sqlite3 database file for each event, it only contains tasks and logs for
 * the event and can be deleted when the event record associated with it is
 * deleted.  This is to keep is scalable when there may be thousands of events
 * and related tasks and logs stored.
 */

#include <libwebsockets.h>
#include <string.h>
#include <signal.h>
#include <time.h>
#include <stdio.h>
#include <fcntl.h>

#include "s-private.h"

#if 0
/*
 * (Structs and maps removed - now in common/include/private.h and common/struct-metadata.c)
 */

static int
sais_get_pcon_for_builder(struct vhd *vhd, const char *builder_name,
			  char *pcon_buf, size_t len)
{
	char q[256], esc[96];
	int r;

	lws_sql_purify(esc, builder_name, sizeof(esc));

	lws_snprintf(q, sizeof(q),
		     "SELECT pcon_name FROM pcon_builders WHERE builder_name = '%s'",
		     esc);

	r = sqlite3_exec(vhd->server.pdb, q, sql3_get_string_cb, pcon_buf, NULL);

	return r == SQLITE_OK;
}
#endif 
int
sais_power_rx(struct vhd *vhd, struct pss *pss, uint8_t *buf,
	      size_t bl, unsigned int ss_flags)
{
	lws_struct_args_t *a = &pss->a;
	sai_power_state_t *ps;
	const lws_struct_map_t lsm_schema_map_power[] = {
		LSM_SCHEMA(sai_power_state_t, NULL, lsm_power_state,
			   "com.warmcat.sai.powerstate"),
		LSM_SCHEMA(sai_power_managed_builders_t, NULL,
			   lsm_power_managed_builders_list,
			   "com.warmcat.sai.power_managed_builders"),
		LSM_SCHEMA(sai_stay_state_update_t, NULL,
			   lsm_stay_state_update,
			   "com.warmcat.sai.stay_state_update"),
		/* We just passthrough PCON energy reports to the web side */
		LSM_SCHEMA(sai_pcon_energy_report_t, NULL, /* Use correct struct/map */
			   lsm_pcon_energy_report,
			   "com.warmcat.sai.pcon_energy"),
	};
	int n;

	/* This is a message from sai-power */
	/* lwsl_notice("RX from sai-power: %.*s\n", (int)bl, (const char *)buf); */

	if (ss_flags & LWSSS_FLAG_SOM) {
		memset(a, 0, sizeof(*a));
		a->top_schema_index = -1;
		a->map_st[0] = lsm_schema_map_power;
		a->map_entries_st[0] = LWS_ARRAY_SIZE(lsm_schema_map_power);
		a->ac_block_size = 512;

		lws_struct_json_init_parse(&pss->ctx_power, NULL, a);
		lws_buflist_destroy_all_segments(&pss->power_rx_cache);
	}

	/* We always cache the fragment until we know what it is */
	if (lws_buflist_append_segment(&pss->power_rx_cache, buf, bl) < 0) {
		lwsl_err("%s: failed to append to power_rx_cache\n", __func__);
		return -1;
	}

	n = lejp_parse(&pss->ctx_power, buf, (int)bl);
	if (n < 0 && n != LEJP_CONTINUE) {
		lwsl_warn("Failed to parse msg from sai-power %s (schema idx %d)\n",
			  lejp_error_to_string(n), a->top_schema_index);
		goto bail;
	}

	if (a->top_schema_index == 3) /* com.warmcat.sai.pcon_energy */
		goto passthru;

	if (n == LEJP_CONTINUE)
		return 0;

	if (!a->dest)
		goto bail;

	switch (a->top_schema_index) {
	case 0: /* powerstate */
		ps = (sai_power_state_t *)a->dest;
		lwsl_notice("%s: powerstate received: %d %d\n", __func__, ps->powering_up, ps->powering_down);
		if (ps->powering_up) {
			lwsl_notice("sai-power is powering up: %s\n", ps->host);
			sais_set_builder_power_state(vhd, ps->host, 1, 0);
			break;
		}
		if (ps->powering_down) {
			lwsl_notice("sai-power is powering down: %s\n", ps->host);
			sais_set_builder_power_state(vhd, ps->host, 0, 1);
		}
		break;

	case 1: {
		sai_power_managed_builders_t *pmb = (sai_power_managed_builders_t *)a->dest;
		char q[256];

		/*
		 * We received the PCON topology and registered builders from sai-power.
		 *
		 * 1. Store PCONs in DB.
		 * 2. Update builders' PCON association (if we have a table or column for it).
		 */

		sai_sqlite3_statement(vhd->server.pdb, "BEGIN TRANSACTION", "txn begin");

		lws_start_foreach_dll(struct lws_dll2 *, p, pmb->power_controllers.head) {
			sai_power_controller_t *pc = lws_container_of(p, sai_power_controller_t, list);
			
			/* Insert PCON */
			lws_snprintf(q, sizeof(q),
				     "INSERT OR REPLACE INTO power_controllers (name, type, url, depends_on, state, manual_on) VALUES ('%s', '%s', '', '%s', %d, %d)",
				     pc->name, pc->type, pc->depends_on, pc->on, pc->manual_on);
			sai_sqlite3_statement(vhd->server.pdb, q, "insert pcon");

			/* Insert Controlled Builders */
			lws_start_foreach_dll(struct lws_dll2 *, pb, pc->controlled_builders_owner.head) {
				sai_controlled_builder_t *cb = lws_container_of(pb, sai_controlled_builder_t, list);
				lws_snprintf(q, sizeof(q),
					     "INSERT INTO pcon_builders (pcon_name, builder_name) SELECT '%s', '%s' WHERE NOT EXISTS (SELECT 1 FROM pcon_builders WHERE pcon_name = '%s' AND builder_name = '%s')",
					     pc->name, cb->name, pc->name, cb->name);
				lwsl_notice("%s: Inserting pcon_builder: pcon='%s', builder='%s'\n", __func__, pc->name, cb->name);
				sai_sqlite3_statement(vhd->server.pdb, q, "insert pcon_builder");

				/* Update builders table with pcon name */
				/* Note: builders table key is 'name'. */
				lws_snprintf(q, sizeof(q),
					     "UPDATE builders SET pcon = '%s' WHERE name = '%s' OR name LIKE '%s.%%'",
					     pc->name, cb->name, cb->name);
				sai_sqlite3_statement(vhd->server.pdb, q, "update builder pcon");

			} lws_end_foreach_dll(pb);

		} lws_end_foreach_dll(p);

		sai_sqlite3_statement(vhd->server.pdb, "COMMIT", "txn commit");

		sais_list_builders(vhd);

		break;
	}
	case 2:	{
		sai_stay_state_update_t *ssu = (sai_stay_state_update_t *)a->dest;
		sai_plat_t *sp;

		lwsl_notice("%s: Received stay_state_update for %s, stay_on=%d\n",
			    __func__, ssu->builder_name, ssu->stay_on);

		lws_start_foreach_dll(struct lws_dll2 *, p,
				vhd->server.builder_owner.head) {
			sp = lws_container_of(p, sai_plat_t,
					sai_plat_list);

			const char *dot = strchr(sp->name, '.');

			if (dot && !strncmp(sp->name, ssu->builder_name, (size_t)(dot - sp->name))) {
				lwsl_notice("%s: Updating builder %s stay_on from %d to %d\n",
					    __func__, sp->name, sp->stay_on, ssu->stay_on);
				sp->stay_on = ssu->stay_on;
				sais_list_builders(vhd);
				break;
			}
		} lws_end_foreach_dll(p);

		break;
	}
	case 3: /* com.warmcat.sai.pcon_energy */
passthru:
		/*
		 * This is an energy report from sai-power.
		 * We want to broadcast it to all connected web interfaces (sai-web).
		 * We have been buffering in pss->power_rx_cache until we identified the schema.
		 * Now we forward whatever is in the cache (which includes the current 'buf').
		 *
		 * Notice we wait until we have the WHOLE message in the cache before
		 * broadcasting it.  Since there is only one websrv channel, we can't
		 * allow interleaved fragments from different sources on it.
		 */

		if (!(ss_flags & LWSSS_FLAG_EOM))
			return 0;

		{
			lws_wsmsg_info_t info;
			uint8_t *p, *lin;
			size_t tlen = lws_buflist_total_len(&pss->power_rx_cache);

			/*
			 * We need to linearize the cache to send it out with LWS_PRE.
			 */
			p = malloc(LWS_PRE + tlen);
			if (!p) {
				lwsl_err("%s: OOM forwarding energy report\n", __func__);
				lws_buflist_destroy_all_segments(&pss->power_rx_cache);
				break;
			}

			lin = p + LWS_PRE;
			size_t copied = 0;

			/* Drain the buflist into our linear buffer */
			while (copied < tlen) {
				uint8_t *seg;
				size_t slen;

				slen = lws_buflist_next_segment_len(&pss->power_rx_cache, (uint8_t **)&seg);
				if (!slen)
					break;

				memcpy(lin + copied, seg, slen);
				copied += slen;
				lws_buflist_use_segment(&pss->power_rx_cache, slen);
			}

			memset(&info, 0, sizeof(info));
			info.private_source_idx = SAI_WEBSRV_PB__GENERATED;
			info.buf = p + LWS_PRE;
			info.len = tlen;
			info.ss_flags = LWSSS_FLAG_SOM | LWSSS_FLAG_EOM;

			/* Broadcast to all websrv connections (i.e. all sai-web instances) */
			sais_websrv_broadcast_REQUIRES_LWS_PRE(vhd->h_ss_websrv, &info);

			free(p);
		}

		if (n == LEJP_CONTINUE)
			return 0;

		break;
	default:
		lwsl_warn("%s: unknown schema\n", __func__);
		/* If it's not our schema, we must clear the cache so it doesn't leak into next message */
		lws_buflist_destroy_all_segments(&pss->power_rx_cache);
		break;
	}

bail:
	lwsac_free(&a->ac);
	
	return 0;
}

/*
 * (Structs and maps removed - now in common/include/private.h and common/struct-metadata.c)
 */

struct pcon_lookup_ctx {
	char *p;
	const char *end;
	int *n;
};

static int
cb_lookup_pcon(void *user, int cols, char **values, char **name)
{
	struct pcon_lookup_ctx *ctx = (struct pcon_lookup_ctx *)user;
	size_t m;

	if (cols < 1 || !values[0])
		return 0;

	m = strlen(values[0]);

	if (*ctx->n)
		*ctx->p++ = ',';

	if (lws_ptr_diff_size_t(ctx->end, ctx->p) < m + 2)
		return 1; /* abort */

	memcpy(ctx->p, values[0], m);
	ctx->p += m;
	*ctx->p = '\0';
	*ctx->n = 1;

	return 0;
}

int
sais_power_tx(struct vhd *vhd, struct pss *pss, uint8_t *buf, size_t bl)
{
	uint8_t *start = buf + LWS_PRE, *p = start, *end = buf + bl - 1;
	enum lws_write_protocol flags;
	size_t w;
	int n, diff = 0;

	if (pss->stay_owner.head) {
		/*
		 * Pending stay message to send to power
		 */
		sai_stay_t *s = lws_container_of(pss->stay_owner.head,
						   sai_stay_t, list);
		lws_struct_serialize_t *js;

		js = lws_struct_json_serialize_create(lsm_schema_stay,
				LWS_ARRAY_SIZE(lsm_schema_stay), 0, s);
		if (!js) {
			lwsl_warn("%s: failed to serialize stay\n", __func__);
			return 1;
		}

		n = (int)lws_struct_json_serialize(js, p, lws_ptr_diff_size_t(end, p), &w);
		lws_struct_json_serialize_destroy(&js);

		lwsl_wsi_notice(pss->wsi, "%s: server issuing stay notice\n", __func__);
		sai_dump_stderr(start, w);

		lws_dll2_remove(&s->list);
		free(s);

		flags = lws_write_ws_flags(LWS_WRITE_TEXT, 1, 1);

		if (lws_write(pss->wsi, start, w, flags) < 0)
			return -1;

		lws_callback_on_writable(pss->wsi);
		return 0;
	}

	if (pss->pcon_control_owner.head) {
		/*
		 * Pending PCON control message to send to power
		 */
		sai_pcon_control_t *s = lws_container_of(pss->pcon_control_owner.head,
						   sai_pcon_control_t, list);
		lws_struct_serialize_t *js;

		js = lws_struct_json_serialize_create(lsm_schema_pcon_control,
				LWS_ARRAY_SIZE(lsm_schema_pcon_control), 0, s);
		if (!js) {
			lwsl_warn("%s: failed to serialize pcon control\n", __func__);
			return 1;
		}

		n = (int)lws_struct_json_serialize(js, p, lws_ptr_diff_size_t(end, p), &w);
		lws_struct_json_serialize_destroy(&js);

		lwsl_wsi_notice(pss->wsi, "%s: server issuing pcon control notice\n", __func__);
		sai_dump_stderr(start, w);

		lws_dll2_remove(&s->list);
		free(s);

		flags = lws_write_ws_flags(LWS_WRITE_TEXT, 1, 1);

		if (lws_write(pss->wsi, start, w, flags) < 0)
			return -1;

		lws_callback_on_writable(pss->wsi);
		return 0;
	}

	n = 0;
	lws_start_foreach_dll(struct lws_dll2 *, px, vhd->pending_plats.head) {
		sais_plat_t *pl = lws_container_of(px, sais_plat_t, list);
		struct pcon_lookup_ctx ctx;
		char q[256], query[256];
		int r;

		ctx.p = (char *)p;
		ctx.end = (const char *)end;
		ctx.n = &n;

		lws_sql_purify(q, pl->plat, sizeof(q));
		lws_snprintf(query, sizeof(query),
			     "SELECT DISTINCT pcon FROM builders WHERE platform = '%s'",
			     q);

		r = sqlite3_exec(vhd->server.pdb, query, cb_lookup_pcon, &ctx, NULL);

		lwsl_info("%s: platform '%s' -> pcon query '%s': result %d\n",
			    __func__, pl->plat, query, r);

		if (r != SQLITE_OK)
			lwsl_err("%s: sqlite3 error: %s\n", __func__, sqlite3_errmsg(vhd->server.pdb));

		p = (uint8_t *)ctx.p;
		if (p >= (uint8_t *)end) /* buffer full */
			break;

	} lws_end_foreach_dll(px);

	lwsl_info("%s: final pcon list: '%.*s'\n", __func__,
		    (int)lws_ptr_diff_size_t(p, start), start);

	/*
	 * Don't resend the same status over and over
	 */

	if (strncmp(pss->last_power_report, (const char *)start, lws_ptr_diff_size_t(p, start) + 1)) {
		lwsl_notice("%s: pending plats changed: '%s' -> '%.*s'\n", __func__,
			    pss->last_power_report, (int)lws_ptr_diff_size_t(p, start), start);

		memcpy(pss->last_power_report, start, lws_ptr_diff_size_t(p, start) + 1);
                diff = 1;
        }

        if (diff) {
                lwsl_info("%s: ************* detected jobs for %.*s\n", __func__,
                                (int)lws_ptr_diff_size_t(p, start), start);

                if (lws_write(pss->wsi, start, lws_ptr_diff_size_t(p, start),
                                LWS_WRITE_TEXT) < 0)
                        return -1;

                lws_callback_on_writable(pss->wsi);
        }

	return 0;
}