KiCad PCB EDA Suite
Loading...
Searching...
No Matches
api_e2e_utils.h
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * This program is free software: you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation, either version 3 of the License, or (at your
9 * option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20#ifndef QA_API_E2E_UTILS_H
21#define QA_API_E2E_UTILS_H
22
23#include <chrono>
24#include <functional>
25#include <string>
26#include <vector>
27
28#include <google/protobuf/any.pb.h>
29#include <magic_enum.hpp>
30#include <wx/filename.h>
31#include <wx/process.h>
32#include <wx/stream.h>
33#include <wx/utils.h>
34
35#ifdef __UNIX__
36#include <signal.h>
37#include <sys/wait.h>
38#include <unistd.h>
39#endif
40
41#include <api/api_client.h>
42#include <api/api_utils.h>
43#include <api/common/envelope.pb.h>
44#include <api/common/commands/base_commands.pb.h>
45#include <api/common/commands/editor_commands.pb.h>
46#include <api/common/commands/project_commands.pb.h>
47#include <api/common/types/base_types.pb.h>
48#include <api/common/types/enums.pb.h>
49#include <api/common/types/jobs.pb.h>
50#include <footprint.h>
53#include <wx/log.h>
54
55
56#ifndef QA_KICAD_CLI_PATH
57#define QA_KICAD_CLI_PATH "kicad-cli"
58#endif
59
60
61class API_SERVER_PROCESS : public wxProcess
62{
63public:
64 API_SERVER_PROCESS( std::function<void( int, const wxString&, const wxString& )> aCallback ) :
65 wxProcess(),
66 m_callback( std::move( aCallback ) )
67 {
68 }
69
70 void OnTerminate( int aPid, int aStatus ) override
71 {
72 wxString output;
73 wxString error;
74
75 drainStream( GetInputStream(), output );
76 drainStream( GetErrorStream(), error );
77
78 if( m_callback )
79 m_callback( aStatus, output, error );
80 }
81
82 static void drainStream( wxInputStream* aStream, wxString& aDest )
83 {
84 if( !aStream || !aStream->CanRead() )
85 return;
86
87 constexpr size_t chunkSize = 1024;
88 char buffer[chunkSize + 1] = { 0 };
89
90 while( aStream->CanRead() )
91 {
92 aStream->Read( buffer, chunkSize );
93 size_t bytesRead = aStream->LastRead();
94
95 if( bytesRead == 0 )
96 break;
97
98 buffer[bytesRead] = '\0';
99 aDest += wxString::FromUTF8( buffer );
100 }
101 }
102
103private:
104 std::function<void( int, const wxString&, const wxString& )> m_callback;
105};
106
107
109{
110public:
111 API_TEST_CLIENT() : m_client( 10000 ) {}
112
113 bool Connect( const wxString& aSocketUrl ) { return m_client.Connect( aSocketUrl ); }
114 void Disconnect() { m_client.Disconnect(); }
115
116 const wxString& LastError() const { return m_lastError; }
117
118 bool Ping( kiapi::common::ApiStatusCode* aStatusOut = nullptr )
119 {
120 kiapi::common::commands::Ping ping;
121 kiapi::common::ApiResponse response;
122
123 if( !send( ping, response ) )
124 return false;
125
126 if( aStatusOut )
127 *aStatusOut = response.status().status();
128
129 return true;
130 }
131
133 {
134 kiapi::common::commands::GetVersion request;
135 kiapi::common::ApiResponse response;
136
137 if( !send( request, response ) )
138 return false;
139
140 if( response.status().status() != kiapi::common::AS_OK )
141 {
142 m_lastError = response.status().error_message();
143 return false;
144 }
145
146 kiapi::common::commands::GetVersionResponse version;
147
148 if( !response.message().UnpackTo( &version ) )
149 {
150 m_lastError = wxS( "Failed to unpack GetVersionResponse" );
151 return false;
152 }
153
154 return true;
155 }
156
157 bool OpenDocument( const wxString& aPath, kiapi::common::types::DocumentType aType,
158 kiapi::common::types::DocumentSpecifier* aDocument = nullptr )
159 {
160 kiapi::common::commands::OpenDocument request;
161 request.set_type( aType );
162 request.set_path( aPath.ToStdString() );
163
164 kiapi::common::ApiResponse response;
165
166 if( !send( request, response ) )
167 return false;
168
169 if( response.status().status() != kiapi::common::AS_OK )
170 {
171 m_lastError = response.status().error_message();
172 return false;
173 }
174
175 kiapi::common::commands::OpenDocumentResponse openResponse;
176
177 if( !response.message().UnpackTo( &openResponse ) )
178 {
179 m_lastError = wxS( "Failed to unpack OpenDocumentResponse" );
180 return false;
181 }
182
183 if( aDocument )
184 *aDocument = openResponse.document();
185
186 return true;
187 }
188
189 bool CreateDocument( const wxString& aPath, kiapi::common::types::DocumentType aType,
190 kiapi::common::types::DocumentSpecifier* aDocument = nullptr )
191 {
192 kiapi::common::commands::CreateDocument request;
193 request.set_type( aType );
194 request.set_path( aPath.ToStdString() );
195
196 kiapi::common::ApiResponse response;
197
198 if( !send( request, response ) )
199 return false;
200
201 if( response.status().status() != kiapi::common::AS_OK )
202 {
203 m_lastError = response.status().error_message();
204 return false;
205 }
206
207 kiapi::common::commands::OpenDocumentResponse openResponse;
208
209 if( !response.message().UnpackTo( &openResponse ) )
210 {
211 m_lastError = wxS( "Failed to unpack OpenDocumentResponse" );
212 return false;
213 }
214
215 if( aDocument )
216 *aDocument = openResponse.document();
217
218 return true;
219 }
220
221 // Convenience overload for PCB documents (backward compatible)
222 bool OpenDocument( const wxString& aPath, kiapi::common::types::DocumentSpecifier* aDocument = nullptr )
223 {
224 return OpenDocument( aPath, kiapi::common::types::DOCTYPE_PCB, aDocument );
225 }
226
227 bool GetItemsCount( const kiapi::common::types::DocumentSpecifier& aDocument,
228 kiapi::common::types::KiCadObjectType aType, int* aCount )
229 {
230 kiapi::common::commands::GetItems request;
231 *request.mutable_header()->mutable_document() = aDocument;
232 request.add_types( aType );
233
234 kiapi::common::ApiResponse response;
235
236 if( !send( request, response ) )
237 return false;
238
239 if( response.status().status() != kiapi::common::AS_OK )
240 {
241 m_lastError = response.status().error_message();
242 return false;
243 }
244
245 kiapi::common::commands::GetItemsResponse itemsResponse;
246
247 if( !response.message().UnpackTo( &itemsResponse ) )
248 {
249 m_lastError = wxS( "Failed to unpack GetItemsResponse" );
250 return false;
251 }
252
253 if( itemsResponse.status() != kiapi::common::types::IRS_OK )
254 {
255 m_lastError = wxString::Format( wxS( "GetItems returned non-OK status: %d" ),
256 static_cast<int>( itemsResponse.status() ) );
257 return false;
258 }
259
260 *aCount = itemsResponse.items_size();
261 return true;
262 }
263
264 bool GetFirstFootprint( const kiapi::common::types::DocumentSpecifier& aDocument, FOOTPRINT* aFootprint )
265 {
266 wxCHECK( aFootprint, false );
267
268 kiapi::common::commands::GetItems request;
269 *request.mutable_header()->mutable_document() = aDocument;
270 request.add_types( kiapi::common::types::KOT_PCB_FOOTPRINT );
271
272 kiapi::common::ApiResponse response;
273
274 if( !send( request, response ) )
275 {
276 m_lastError = wxS( "Failed to send command" );
277 return false;
278 }
279
280 if( response.status().status() != kiapi::common::AS_OK )
281 {
282 m_lastError = response.status().error_message();
283 return false;
284 }
285
286 kiapi::common::commands::GetItemsResponse itemsResponse;
287
288 if( !response.message().UnpackTo( &itemsResponse ) )
289 {
290 m_lastError = wxS( "Failed to unpack GetItemsResponse" );
291 return false;
292 }
293
294 if( itemsResponse.status() != kiapi::common::types::IRS_OK )
295 {
296 m_lastError = wxString::Format( wxS( "GetItems returned non-OK status: %s" ),
297 magic_enum::enum_name( itemsResponse.status() ) );
298 return false;
299 }
300
301 if( itemsResponse.items_size() == 0 )
302 {
303 m_lastError = wxS( "GetItems returned no footprints" );
304 return false;
305 }
306
307 if( !aFootprint->Deserialize( itemsResponse.items( 0 ) ) )
308 {
309 m_lastError = wxS( "Failed to deserialize first footprint from GetItems response" );
310 return false;
311 }
312
313 return true;
314 }
315
316 bool CloseDocument( const kiapi::common::types::DocumentSpecifier* aDocument,
317 kiapi::common::ApiStatusCode* aStatus = nullptr )
318 {
319 kiapi::common::commands::CloseDocument request;
320
321 if( aDocument )
322 *request.mutable_document() = *aDocument;
323
324 kiapi::common::ApiResponse response;
325
326 if( !send( request, response ) )
327 {
328 m_lastError = wxS( "Failed to send command" );
329 return false;
330 }
331
332 if( aStatus )
333 *aStatus = response.status().status();
334
335 if( response.status().status() != kiapi::common::AS_OK )
336 m_lastError = response.status().error_message();
337
338 return true;
339 }
340
342 {
343 kiapi::common::commands::CloseAllDocuments request;
344 kiapi::common::ApiResponse response;
345
346 if( !send( request, response ) )
347 return false;
348
349 if( response.status().status() != kiapi::common::AS_OK )
350 {
351 m_lastError = response.status().error_message();
352 return false;
353 }
354
355 return true;
356 }
357
361 template <typename T>
362 bool RunJob( const T& aJobRequest, kiapi::common::types::RunJobResponse* aResponse )
363 {
364 kiapi::common::ApiResponse apiResponse;
365
366 if( !send( aJobRequest, apiResponse ) )
367 return false;
368
369 if( apiResponse.status().status() != kiapi::common::AS_OK )
370 {
371 m_lastError = apiResponse.status().error_message();
372 return false;
373 }
374
375 if( !apiResponse.message().UnpackTo( aResponse ) )
376 {
377 m_lastError = wxS( "Failed to unpack RunJobResponse" );
378 return false;
379 }
380
381 return true;
382 }
383
384 template <typename T>
385 bool SendCommand( const T& aMessage, kiapi::common::ApiResponse* aResponse )
386 {
387 return send( aMessage, *aResponse );
388 }
389
390private:
391 bool send( const google::protobuf::Message& aRequest, kiapi::common::ApiResponse& aResponse )
392 {
393 if( !m_client.Send( aRequest, aResponse, "kicad.qa" ) )
394 {
395 m_lastError = m_client.GetLastError();
396 return false;
397 }
398
399 return true;
400 }
401
403 wxString m_lastError;
404};
405
406
419{
420public:
422 {
423 static API_SERVER_MANAGER s_instance;
424 return s_instance;
425 }
426
430 bool EnsureReady( const wxString& aCliPath, wxString* aError )
431 {
432 if( m_ready )
433 {
434 if( isProcessAlive() )
435 {
436 // A new testcase is starting up, make sure old things are closed
438 return true;
439 }
440
441 m_ready = false;
442 }
443
444 BOOST_TEST_MESSAGE( "Starting API server with CLI path: " << aCliPath );
445
446 if( !startServerProcess( aCliPath, aError ) )
447 return false;
448
449 if( !connectAndWaitReady( aError ) )
450 return false;
451
452 m_ready = true;
453 return true;
454 }
455
457
461 void Reset()
462 {
463 m_ready = false;
464 m_client.Disconnect();
465
466 if( m_pid != 0 && isProcessAlive() )
467 {
468#ifdef __WXMAC__
469 wxProcess::Kill( m_pid, wxSIGKILL );
470#else
471 wxProcess::Kill( m_pid, wxSIGKILL, wxKILL_CHILDREN );
472#endif
473 }
474
475 m_pid = 0;
476 m_process = nullptr;
477
478 if( wxFileName::Exists( m_socketPath ) )
479 wxRemoveFile( m_socketPath );
480 }
481
482private:
484 {
485#ifdef __UNIX__
486 m_socketPath = wxString::Format( wxS( "/tmp/kicad-api-e2e-%ld.sock" ), wxGetProcessId() );
487#else
488 wxString tempPath = wxFileName::CreateTempFileName( wxS( "kicad-api-e2e" ) );
489
490 if( wxFileExists( tempPath ) )
491 wxRemoveFile( tempPath );
492
493 m_socketPath = tempPath + wxS( ".sock" );
494#endif
495
496 m_socketUrl = wxS( "ipc://" ) + m_socketPath;
497
498 if( wxFileName::Exists( m_socketPath ) )
499 wxRemoveFile( m_socketPath );
500 }
501
503 {
504 // Use POSIX primitives here because this destructor runs during static destruction
505 // when wxWidgets may already be partially torn down.
506#ifdef __UNIX__
507 if( m_pid != 0 )
508 {
509 kill( static_cast<pid_t>( m_pid ), SIGTERM );
510 usleep( 200000 );
511 kill( static_cast<pid_t>( m_pid ), SIGKILL );
512 }
513
514 if( !m_socketPath.IsEmpty() )
515 unlink( m_socketPath.ToUTF8().data() );
516#else
517 if( m_pid != 0 )
518 wxProcess::Kill( m_pid, wxSIGKILL, wxKILL_CHILDREN );
519
520 if( !m_socketPath.IsEmpty() && wxFileName::Exists( m_socketPath ) )
521 wxRemoveFile( m_socketPath );
522#endif
523 }
524
527
528 bool startServerProcess( const wxString& aCliPath, wxString* aError )
529 {
530 if( m_pid != 0 )
531 return true;
532
533 if( !wxFileExists( aCliPath ) )
534 {
535 if( aError )
536 *aError = wxS( "kicad-cli path does not exist: " ) + aCliPath;
537
538 return false;
539 }
540
541 m_stdout.clear();
542 m_stderr.clear();
543 m_exitCode = 0;
544
546 [this]( int aStatus, const wxString& aOutput, const wxString& aErrOutput )
547 {
548 m_exitCode = aStatus;
549 m_stdout += aOutput;
550 m_stderr += aErrOutput;
551 m_pid = 0;
552 m_process = nullptr;
553 m_ready = false;
554 } );
555
556 m_process->Redirect();
557
558 std::vector<const wchar_t*> args = { aCliPath.wc_str(), wxS( "api-server" ), wxS( "--socket" ),
559 m_socketPath.wc_str(), nullptr };
560
561 m_pid = wxExecute( args.data(), wxEXEC_ASYNC, m_process );
562
563 if( m_pid == 0 )
564 {
565 delete m_process;
566 m_process = nullptr;
567
568 if( aError )
569 *aError = wxS( "Failed to launch kicad-cli api-server" );
570
571 return false;
572 }
573
574 return true;
575 }
576
577 bool connectAndWaitReady( wxString* aError )
578 {
579 auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds( 15 );
580
581 while( std::chrono::steady_clock::now() < deadline )
582 {
583 wxMilliSleep( 100 );
585
586 if( !isProcessAlive() )
587 {
588 if( aError )
589 *aError = wxS( "kicad-cli process exited before ready" );
590
591 return false;
592 }
593
594 if( !m_client.Connect( m_socketUrl ) )
595 {
596 wxLogTrace( traceApi, "kicad-cli connect attempt failed, will retry" );
597 continue;
598 }
599
600 kiapi::common::ApiStatusCode pingStatus = kiapi::common::AS_UNKNOWN;
601
602 if( m_client.Ping( &pingStatus ) )
603 {
604 if( pingStatus == kiapi::common::AS_OK )
605 return true;
606
607 if( pingStatus != kiapi::common::AS_NOT_READY )
608 {
609 if( aError )
610 {
611 *aError = wxString::Format( wxS( "Ping returned unexpected status: %s" ),
612 magic_enum::enum_name( pingStatus ) );
613 }
614
615 return false;
616 }
617
618 wxLogTrace( traceApi, "kicad-cli connected but returned AS_NOT_READY, will retry" );
619 }
620 else
621 {
622 wxLogTrace( traceApi, "kicad-cli ping attempt failed, will retry" );
623 }
624 }
625
626 if( aError )
627 *aError = wxS( "Timed out waiting for kicad-cli to start up" );
628
629 return false;
630 }
631
633 {
634 if( !m_process )
635 return;
636
639 }
640
641 bool isProcessAlive() const
642 {
643 if( m_pid == 0 )
644 return false;
645
646#ifdef __UNIX__
647 int status = 0;
648 pid_t result = waitpid( static_cast<pid_t>( m_pid ), &status, WNOHANG );
649
650 if( result == 0 )
651 return true;
652
653 if( result > 0 )
654 {
655 if( WIFSIGNALED( status ) )
656 {
657 BOOST_TEST_MESSAGE( wxString::Format( "api-server killed by signal %d (%s)",
658 WTERMSIG( status ),
659 strsignal( WTERMSIG( status ) ) ) );
660 }
661 else if( WIFEXITED( status ) )
662 {
663 BOOST_TEST_MESSAGE( wxString::Format( "api-server exited with code %d",
664 WEXITSTATUS( status ) ) );
665 }
666
667 return false;
668 }
669#endif
670
671 return wxProcess::Exists( m_pid );
672 }
673
674 bool m_ready = false;
677 long m_pid = 0;
678 wxString m_socketPath;
679 wxString m_socketUrl;
680 wxString m_stdout;
681 wxString m_stderr;
682 mutable int m_exitCode = 0;
683};
684
685
696{
697public:
699 {
700 m_cliPath = wxString::FromUTF8( QA_KICAD_CLI_PATH );
701 }
702
707
709 bool Start( const wxString& aCliPathOverride = wxString() )
710 {
711 wxString cliPath = aCliPathOverride.IsEmpty() ? m_cliPath : aCliPathOverride;
712
714
715 if( manager.EnsureReady( cliPath, &m_lastError ) )
716 return true;
717
718 // First attempt failed. The server may have crashed during a previous test.
719 manager.Reset();
720
721 return manager.EnsureReady( cliPath, &m_lastError );
722 }
723
725
726 wxString CliPath() const { return m_cliPath; }
727
728 const wxString& LastError() const { return m_lastError; }
729
730private:
731 wxString m_cliPath;
732 wxString m_lastError;
733};
734
735#endif // QA_API_E2E_UTILS_H
#define QA_KICAD_CLI_PATH
General utilities for PCB file IO for QA programs.
bool Start(const wxString &aCliPathOverride=wxString())
Starts the API server if not already running. If running, closes any open documents.
const wxString & LastError() const
API_TEST_CLIENT & Client()
wxString CliPath() const
Manages a single shared kicad-cli api-server process and NNG client across all E2E tests.
API_TEST_CLIENT & Client()
API_SERVER_PROCESS * m_process
bool connectAndWaitReady(wxString *aError)
API_SERVER_MANAGER & operator=(const API_SERVER_MANAGER &)=delete
static API_SERVER_MANAGER & Instance()
bool isProcessAlive() const
API_SERVER_MANAGER(const API_SERVER_MANAGER &)=delete
API_TEST_CLIENT m_client
bool startServerProcess(const wxString &aCliPath, wxString *aError)
void Reset()
Kill the current server and reset state so EnsureReady() will start fresh.
bool EnsureReady(const wxString &aCliPath, wxString *aError)
Ensure the api-server is running and the shared client is connected and responsive.
void OnTerminate(int aPid, int aStatus) override
API_SERVER_PROCESS(std::function< void(int, const wxString &, const wxString &)> aCallback)
std::function< void(int, const wxString &, const wxString &)> m_callback
static void drainStream(wxInputStream *aStream, wxString &aDest)
bool GetItemsCount(const kiapi::common::types::DocumentSpecifier &aDocument, kiapi::common::types::KiCadObjectType aType, int *aCount)
bool send(const google::protobuf::Message &aRequest, kiapi::common::ApiResponse &aResponse)
bool CreateDocument(const wxString &aPath, kiapi::common::types::DocumentType aType, kiapi::common::types::DocumentSpecifier *aDocument=nullptr)
bool OpenDocument(const wxString &aPath, kiapi::common::types::DocumentType aType, kiapi::common::types::DocumentSpecifier *aDocument=nullptr)
bool RunJob(const T &aJobRequest, kiapi::common::types::RunJobResponse *aResponse)
Send an arbitrary job request and receive a RunJobResponse.
KICAD_API_CLIENT m_client
bool CloseDocument(const kiapi::common::types::DocumentSpecifier *aDocument, kiapi::common::ApiStatusCode *aStatus=nullptr)
bool Connect(const wxString &aSocketUrl)
const wxString & LastError() const
bool OpenDocument(const wxString &aPath, kiapi::common::types::DocumentSpecifier *aDocument=nullptr)
bool SendCommand(const T &aMessage, kiapi::common::ApiResponse *aResponse)
bool Ping(kiapi::common::ApiStatusCode *aStatusOut=nullptr)
bool GetFirstFootprint(const kiapi::common::types::DocumentSpecifier &aDocument, FOOTPRINT *aFootprint)
bool Deserialize(const google::protobuf::Any &aContainer) override
Deserializes the given protobuf message into this object.
const wxChar *const traceApi
Flag to enable debug output related to the IPC API and its plugin system.
Definition api_utils.cpp:33
STL namespace.
BOOST_TEST_MESSAGE("Polyline has "<< chain.PointCount()<< " points")
wxString result
Test unit parsing edge cases and error handling.