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 return send( request, response );
347 }
348
352 template <typename T>
353 bool RunJob( const T& aJobRequest, kiapi::common::types::RunJobResponse* aResponse )
354 {
355 kiapi::common::ApiResponse apiResponse;
356
357 if( !send( aJobRequest, apiResponse ) )
358 return false;
359
360 if( apiResponse.status().status() != kiapi::common::AS_OK )
361 {
362 m_lastError = apiResponse.status().error_message();
363 return false;
364 }
365
366 if( !apiResponse.message().UnpackTo( aResponse ) )
367 {
368 m_lastError = wxS( "Failed to unpack RunJobResponse" );
369 return false;
370 }
371
372 return true;
373 }
374
375 template <typename T>
376 bool SendCommand( const T& aMessage, kiapi::common::ApiResponse* aResponse )
377 {
378 return send( aMessage, *aResponse );
379 }
380
381private:
382 bool send( const google::protobuf::Message& aRequest, kiapi::common::ApiResponse& aResponse )
383 {
384 if( !m_client.Send( aRequest, aResponse, "kicad.qa" ) )
385 {
386 m_lastError = m_client.GetLastError();
387 return false;
388 }
389
390 return true;
391 }
392
394 wxString m_lastError;
395};
396
397
410{
411public:
413 {
414 static API_SERVER_MANAGER s_instance;
415 return s_instance;
416 }
417
421 bool EnsureReady( const wxString& aCliPath, wxString* aError )
422 {
423 if( m_ready )
424 {
425 if( isProcessAlive() )
426 return true;
427
428 m_ready = false;
429 }
430
431 BOOST_TEST_MESSAGE( "Starting API server with CLI path: " << aCliPath );
432
433 if( !startServerProcess( aCliPath, aError ) )
434 return false;
435
436 if( !connectAndWaitReady( aError ) )
437 return false;
438
439 m_ready = true;
440 return true;
441 }
442
444
448 void Reset()
449 {
450 m_ready = false;
451 m_client.Disconnect();
452
453 if( m_pid != 0 && isProcessAlive() )
454 {
455#ifdef __WXMAC__
456 wxProcess::Kill( m_pid, wxSIGKILL );
457#else
458 wxProcess::Kill( m_pid, wxSIGKILL, wxKILL_CHILDREN );
459#endif
460 }
461
462 m_pid = 0;
463 m_process = nullptr;
464
465 if( wxFileName::Exists( m_socketPath ) )
466 wxRemoveFile( m_socketPath );
467 }
468
469private:
471 {
472#ifdef __UNIX__
473 m_socketPath = wxString::Format( wxS( "/tmp/kicad-api-e2e-%ld.sock" ), wxGetProcessId() );
474#else
475 wxString tempPath = wxFileName::CreateTempFileName( wxS( "kicad-api-e2e" ) );
476
477 if( wxFileExists( tempPath ) )
478 wxRemoveFile( tempPath );
479
480 m_socketPath = tempPath + wxS( ".sock" );
481#endif
482
483 m_socketUrl = wxS( "ipc://" ) + m_socketPath;
484
485 if( wxFileName::Exists( m_socketPath ) )
486 wxRemoveFile( m_socketPath );
487 }
488
490 {
491 // Use POSIX primitives here because this destructor runs during static destruction
492 // when wxWidgets may already be partially torn down.
493#ifdef __UNIX__
494 if( m_pid != 0 )
495 {
496 kill( static_cast<pid_t>( m_pid ), SIGTERM );
497 usleep( 200000 );
498 kill( static_cast<pid_t>( m_pid ), SIGKILL );
499 }
500
501 if( !m_socketPath.IsEmpty() )
502 unlink( m_socketPath.ToUTF8().data() );
503#else
504 if( m_pid != 0 )
505 wxProcess::Kill( m_pid, wxSIGKILL, wxKILL_CHILDREN );
506
507 if( !m_socketPath.IsEmpty() && wxFileName::Exists( m_socketPath ) )
508 wxRemoveFile( m_socketPath );
509#endif
510 }
511
514
515 bool startServerProcess( const wxString& aCliPath, wxString* aError )
516 {
517 if( m_pid != 0 )
518 return true;
519
520 if( !wxFileExists( aCliPath ) )
521 {
522 if( aError )
523 *aError = wxS( "kicad-cli path does not exist: " ) + aCliPath;
524
525 return false;
526 }
527
528 m_stdout.clear();
529 m_stderr.clear();
530 m_exitCode = 0;
531
533 [this]( int aStatus, const wxString& aOutput, const wxString& aErrOutput )
534 {
535 m_exitCode = aStatus;
536 m_stdout += aOutput;
537 m_stderr += aErrOutput;
538 m_pid = 0;
539 m_process = nullptr;
540 m_ready = false;
541 } );
542
543 m_process->Redirect();
544
545 std::vector<const wchar_t*> args = { aCliPath.wc_str(), wxS( "api-server" ), wxS( "--socket" ),
546 m_socketPath.wc_str(), nullptr };
547
548 m_pid = wxExecute( args.data(), wxEXEC_ASYNC, m_process );
549
550 if( m_pid == 0 )
551 {
552 delete m_process;
553 m_process = nullptr;
554
555 if( aError )
556 *aError = wxS( "Failed to launch kicad-cli api-server" );
557
558 return false;
559 }
560
561 return true;
562 }
563
564 bool connectAndWaitReady( wxString* aError )
565 {
566 auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds( 15 );
567
568 while( std::chrono::steady_clock::now() < deadline )
569 {
570 wxMilliSleep( 100 );
572
573 if( !isProcessAlive() )
574 {
575 if( aError )
576 *aError = wxS( "kicad-cli process exited before ready" );
577
578 return false;
579 }
580
581 if( !m_client.Connect( m_socketUrl ) )
582 {
583 wxLogTrace( traceApi, "kicad-cli connect attempt failed, will retry" );
584 continue;
585 }
586
587 kiapi::common::ApiStatusCode pingStatus = kiapi::common::AS_UNKNOWN;
588
589 if( m_client.Ping( &pingStatus ) )
590 {
591 if( pingStatus == kiapi::common::AS_OK )
592 return true;
593
594 if( pingStatus != kiapi::common::AS_NOT_READY )
595 {
596 if( aError )
597 {
598 *aError = wxString::Format( wxS( "Ping returned unexpected status: %s" ),
599 magic_enum::enum_name( pingStatus ) );
600 }
601
602 return false;
603 }
604
605 wxLogTrace( traceApi, "kicad-cli connected but returned AS_NOT_READY, will retry" );
606 }
607 else
608 {
609 wxLogTrace( traceApi, "kicad-cli ping attempt failed, will retry" );
610 }
611 }
612
613 if( aError )
614 *aError = wxS( "Timed out waiting for kicad-cli to start up" );
615
616 return false;
617 }
618
620 {
621 if( !m_process )
622 return;
623
626 }
627
628 bool isProcessAlive() const
629 {
630 if( m_pid == 0 )
631 return false;
632
633#ifdef __UNIX__
634 int status = 0;
635 pid_t result = waitpid( static_cast<pid_t>( m_pid ), &status, WNOHANG );
636
637 if( result == 0 )
638 return true;
639
640 if( result > 0 )
641 {
642 if( WIFSIGNALED( status ) )
643 {
644 BOOST_TEST_MESSAGE( wxString::Format( "api-server killed by signal %d (%s)",
645 WTERMSIG( status ),
646 strsignal( WTERMSIG( status ) ) ) );
647 }
648 else if( WIFEXITED( status ) )
649 {
650 BOOST_TEST_MESSAGE( wxString::Format( "api-server exited with code %d",
651 WEXITSTATUS( status ) ) );
652 }
653
654 return false;
655 }
656#endif
657
658 return wxProcess::Exists( m_pid );
659 }
660
661 bool m_ready = false;
664 long m_pid = 0;
665 wxString m_socketPath;
666 wxString m_socketUrl;
667 wxString m_stdout;
668 wxString m_stderr;
669 mutable int m_exitCode = 0;
670};
671
672
683{
684public:
686 {
687 m_cliPath = wxString::FromUTF8( QA_KICAD_CLI_PATH );
688 }
689
694
695 bool Start( const wxString& aCliPathOverride = wxString() )
696 {
697 wxString cliPath = aCliPathOverride.IsEmpty() ? m_cliPath : aCliPathOverride;
698
700
701 if( manager.EnsureReady( cliPath, &m_lastError ) )
702 return true;
703
704 // First attempt failed. The server may have crashed during a previous test.
705 manager.Reset();
706
707 return manager.EnsureReady( cliPath, &m_lastError );
708 }
709
711
712 wxString CliPath() const { return m_cliPath; }
713
714 const wxString& LastError() const { return m_lastError; }
715
716private:
717 wxString m_cliPath;
718 wxString m_lastError;
719};
720
721#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())
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.