Read about our upcoming Code of Conduct on this issue

UProjectDeployerQt.cpp 65.6 KB
Newer Older
1
#include "UProjectDeployerQt.h"
2
#include "../UApplication.h"
3
4

namespace RDK{
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


static
size_t write_response(void *ptr, size_t size, size_t nmemb, void *data)
{
  FILE *writehere = (FILE *)data;
  char* str = static_cast<char*>(ptr);
  //std::string s(str);
  //std::cout<<str<<std::endl;
  return nmemb;
}


UProjectDeployProcessingThread::UProjectDeployProcessingThread()
{
    deploymentState = DeploymentState::DS_Unknown;

    connect(&zip_process, SIGNAL(readyReadStandardError()), this, SLOT(processReadyReadStandardError()));
    connect(&zip_process, SIGNAL(readyReadStandardOutput()), this, SLOT(processReadyReadStandardOutput()));

}

UProjectDeployProcessingThread::~UProjectDeployProcessingThread()
{

}


Aivan_2008's avatar
Aivan_2008 committed
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
void UProjectDeployProcessingThread::processReadyReadStandardError()
{
    //std::cout<<"Unzip process std_error: "<<zip_process.readAllStandardError();

}

void UProjectDeployProcessingThread::processReadyReadStandardOutput()
{
    /*QString s = zip_process.readAllStandardOutput();
    //TODO: ,        
    std::cout<<"Unzip process std_output: "<<s;*/
}

void UProjectDeployProcessingThread::SetDatabasePath(const QString& path)
{
 databasePath = path;
}

void UProjectDeployProcessingThread::SetDownloadTempPath(const QString& path)
{
    downloadTempPath = path;
}

void UProjectDeployProcessingThread::SetFtpRemoteBasePath(const QString& path)
{
    ftpRemoteBasePath = path;
}

void UProjectDeployProcessingThread::SetDeploymentState(const DeploymentState& state)
{
 QMutexLocker locker(&deploymentStateMutex);
 deploymentState = state;
}

void UProjectDeployProcessingThread::SetDeploymentProgress(const int &progress)
{
 QMutexLocker locker(&deploymentProgressMutex);
 deploymentProgress = progress;
}

void UProjectDeployProcessingThread::SetDeploymentProgressCap(const int &value)
{
 QMutexLocker locker(&deploymentProgressCapMutex);
 deploymentProgressCap = value;
}

void UProjectDeployProcessingThread::PrepareProjectDeployment(bool task_template_dr, const QString& task_template_path,
                                                              bool task_weights_dr, const QString& task_weights_path,
                                                              bool task_script_dr, const QString& task_script_path,
                                                               bool task_vsrc_dr, int task_vrc_type, const QString& task_vsrc_path)
{
    template_dr = task_template_dr;
    template_path = task_template_path;

    weights_dr = task_weights_dr;
    weights_path = task_weights_path;

    script_dr = task_script_dr;
    script_path = task_script_path;

    videosource_type = task_vrc_type;
    videosource_dr = task_vsrc_dr;
    videosource_path = task_vsrc_path;

    //   -        
}

void UProjectDeployProcessingThread::RunProjectDeployment()
{
    //  
    this->start();
}

///Get
QString UProjectDeployProcessingThread::GetDatabasePath()
{
 return databasePath;
}

QString UProjectDeployProcessingThread::GetFtpRemoteBasePath()
{
 return ftpRemoteBasePath;
}

QString UProjectDeployProcessingThread::GetDownloadTempPath()
{
 return downloadTempPath;
}

DeploymentState UProjectDeployProcessingThread::GetDeploymentState()
{
 return deploymentState;
}

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
std::string UProjectDeployProcessingThread::GetDeploymentStateString()
{
 std::string result;
 switch(deploymentState)
 {
    case DeploymentState::DS_UnpackData:
     result = "DS_UnpackData";
     break;
 case DeploymentState::DS_DownloadData:
      result = "DS_DownloadData";
      break;
 case DeploymentState::DS_UnpackTemplate:
      result = "DS_UnpackTemplate";
      break;
 case DeploymentState::DS_UnpackScripts:
      result = "DS_UnpackScripts";
      break;
 case DeploymentState::DS_UnpackWeights:
      result = "DS_UnpackWeights";
      break;
 case DeploymentState::DS_DownloadTemplate:
      result = "DS_DownloadTemplate";
      break;
 case DeploymentState::DS_DownloadScripts:
      result = "DS_DownloadScripts";
      break;
 case DeploymentState::DS_DownloadWeights:
      result = "DS_DownloadWeights";
      break;
 default:
     result="ERROR";
 }
 return result;
}
164
*/
165
166
167
168
169
170
171
172
173
174
175
176
177

int UProjectDeployProcessingThread::GetDeploymentProgress()
{
    QMutexLocker locker(&deploymentProgressMutex);
    return deploymentProgress;
}

int UProjectDeployProcessingThread::GetDeploymentProgressCap()
{
    QMutexLocker locker(&deploymentProgressCapMutex);
    return deploymentProgressCap;
}

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
void UProjectDeployProcessingThread::run()
{
    DeployTemplate();
    if(!VerifyTemplate())
    {


        // ,       
        // -  
        //   ,  
    }

    DeployScript();
    if(!VerifyScript())
    {
        // ,       
        // -  
        //   ,  
    }

    DeployWeights();
    if(!VerifyWeights())
    {
        // ,       
        // -  
        //   ,  
    }

    DeployData();
    if(!VerifyData())
    {
        // ,       
        // -  
        //   ,  
    }
215

Aivan_2008's avatar
Aivan_2008 committed
216
    deploymentState = DS_DeployFinished;
217
218
219
220
221

}

std::string UProjectDeployProcessingThread::GetLastError()
{
Aivan_2008's avatar
Aivan_2008 committed
222
    return lastError;
223
224
225
226
227
228
229
230
231
232
233
234
}

bool UProjectDeployProcessingThread::DownloadZip(const QString &remote_url, const QString& dst_zip_file)
{
    SetDeploymentProgressCap(100);
    SetDeploymentProgress(0);

    if(remote_url=="")
    {
        //8QMessageBox::information(this, "error", "Remote file path is empty");

        std::cout<<"Remote file path is empty";
Aivan_2008's avatar
Aivan_2008 committed
235
236
237

        std::stringstream ss;
        lastError = "Zip download file path was empty";
238
239
240
241
242
243
        return false;
    }
    if(dst_zip_file=="")
    {
        //QMessageBox::information(this, "error", "Path to receive file is empty");
        std::cout<<"Path to receive file is empty";
Aivan_2008's avatar
Aivan_2008 committed
244
        lastError = "Zip destination file path was empty";
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
        return false;
    }

    QString save_filename = "";
    bool rename = false;

    QFileInfo fi(dst_zip_file);
    if(!fi.isDir())
    {
     //std::cout<<"File name is not directory, so downloaded file will be renamed";
     //rename=true;
     if(fi.exists())
     {
      std::cout<<"File "<<fi.absoluteFilePath().toUtf8().constData()<< " already exists";
      //   ,    -  
      return true;
     }
     else
     {
      save_filename = fi.absoluteFilePath();
     }
    }
    else
    {
     if(!fi.exists())
     {
      std::cout<<"Directory to save file is not exists, create it before start";
Aivan_2008's avatar
Aivan_2008 committed
272
      lastError = "Attempt to download/unpack to inexistent directory";
273
274
275
276
277
278
279
      return false;
     }

     QStringList ls = dst_zip_file.split("/");
     if(ls.size()<2)
     {
         std::cout<<"Wrong remote file path '"<<dst_zip_file.toUtf8().constData();
Aivan_2008's avatar
Aivan_2008 committed
280
         lastError = "Wrong zip download remote file path";
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
         return false;
     }


     //     ,     
     //TODO: ,    ?
     QString fn = ls[ls.size()-1];
     QString filename = dst_zip_file+"/"+fn;
     QFileInfo fi2(filename);
     if(fi2.exists())
     {
      std::cout<<"Change save file name, current already exists: "<<fi2.absoluteFilePath().toUtf8().constData();
      return false;
     }
     save_filename = filename;
    }

    QString download_filename = save_filename;
    if(rename)
    {
     int id=0;
     QFileInfo fi(download_filename);
     do
     {
       download_filename = fi.path()+"/"+"temp_"+QString::number(id);
       id+=1;
     }
     while(QFileInfo(download_filename).exists());
    }

    std::string s = save_filename.toUtf8().constData();
    struct FtpFile ftp_file;
    ftp_file.stream=NULL;
    ftp_file.filename = s.c_str();

    curl = curl_easy_init();

    if(curl)
    {
        //     
        curl_easy_setopt(curl, CURLOPT_URL, remote_url.toUtf8().constData());

        //     
        curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, write_response);

        /* Define our callback to get called when there's data to be written */
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite);
        /* Set a pointer to our struct to pass to the callback */
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ftp_file);

        /* Switch on full protocol/debug output */
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

        res = curl_easy_perform(curl);

        /* always cleanup */
        curl_easy_cleanup(curl);

        if(CURLE_OK != res) {
          /* we failed */
          std::cerr<<"curl told us "<<res<<std::endl;
Aivan_2008's avatar
Aivan_2008 committed
342
343
344
345
          std::stringstream ss_curl;
          ss_curl<<"curl told us "<<res;
          lastError = ss_curl.str();
          return false;
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
        }
    }
    if(ftp_file.stream!=NULL)
    {
        fclose(ftp_file.stream);
    }

    SetDeploymentProgress(100);
    //  , ,   ??
   return true;
}

bool UProjectDeployProcessingThread::UnpackZipFolder(const QString &local_zip_folder, const QString& local_dst_folder)
{
    SetDeploymentProgressCap(100);
    SetDeploymentProgress(0);

    QDir dst_dir(local_dst_folder);
    if(!dst_dir.exists())
        dst_dir.mkpath(dst_dir.path());

    QString cmd = "unzip -o "+local_zip_folder+" -d " + local_dst_folder;

    zip_process.start(cmd);
    while(!zip_process.waitForFinished(2))
    {
        QCoreApplication::processEvents();
    }
    SetDeploymentProgress(100);
    return true;
}

bool UProjectDeployProcessingThread::UnpackZipFile(const QString &local_zip_folder, const QString& local_dst_folder)
{
    SetDeploymentProgressCap(100);
    SetDeploymentProgress(0);
    //TODO: ,       
    QString cmd = "unzip -o "+local_zip_folder+" -d " + local_dst_folder;

    zip_process.start(cmd);
    while(!zip_process.waitForFinished(2))
    {
        QCoreApplication::processEvents();
    }
    SetDeploymentProgress(100);
    return true;
}

void UProjectDeployProcessingThread::DeployTemplate()
{
    if(!template_dr)
    {
        std::cout<<"Template already exists";
        return;
    }

    //QString template_proj_path = template_path;

    QFileInfo tfi(template_path);

    QString project_dir_basic = tfi.path();

    QString ftp_project_path = project_dir_basic+".zip";
    ftp_project_path.replace("{Database}", ftpRemoteBasePath);

    QString download_zip_file = project_dir_basic+".zip";
    download_zip_file.replace("{Database}", downloadTempPath);

    QString unpack_zip_path = project_dir_basic;
    unpack_zip_path.replace("{Database}", databasePath);

    QFileInfo dwd_fi(download_zip_file);

    if(!dwd_fi.exists())
    {
        QDir dwd_fi_d(dwd_fi.absolutePath());
        if(!dwd_fi_d.exists())
        {
            dwd_fi_d.mkpath(dwd_fi_d.path());
        }
    }

    //   
    QDir du_d(unpack_zip_path);
    if(!du_d.exists())
    {
        du_d.mkpath(du_d.path());
    }

    //  1 - 
    // -     
    if(!dwd_fi.exists())
    {
        if(!DownloadZip(ftp_project_path, download_zip_file))
        {
            std::cout<<"Download ERROR";
Aivan_2008's avatar
Aivan_2008 committed
442
            lastError+=" Download Error";
443
444
445
446
447
448
449
450
451
452
453
454
            SetDeploymentState(DeploymentState::DS_Error);
            return;
        }
    }


    // 2 = 
    // 
    SetDeploymentState(DeploymentState::DS_UnpackData);
    if(!UnpackZipFolder(download_zip_file, du_d.path()))
    {
        std::cout<<"Unpack ERROR";
Aivan_2008's avatar
Aivan_2008 committed
455
        lastError+=" Unpack Error";
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
        SetDeploymentState(DeploymentState::DS_Error);
        return;
    }
    std::cout<<"Unpack SUCCESS";



    //template_proj_path.replace("{Database}", downloadTempPath);

    /*std::cout<<"Start deploy template";
    //,       :
    if(template_dr)
    {
        QString template_proj_path = template_path;
        template_proj_path.replace("{Database}", downloadTempPath);

        // 
        QFileInfo proj_file(template_proj_path);
        QString template_zip_path = proj_file.absolutePath()+".zip";

        //     
        QString ftp_zip_path = template_zip_path;
        ftp_zip_path.replace(downloadTempPath, ftpRemoteBasePath);

        //     , 
        QString unpackZipPath = proj_file.absolutePath();
        unpackZipPath.replace(downloadTempPath, databasePath);

        QFileInfo db_fi(unpackZipPath);

        std::cout<<"template_zip_path = "<<template_zip_path.toUtf8().constData()<<" ftp_zip_path="<<ftp_zip_path.toUtf8().constData();

        QFileInfo fi(template_zip_path);
        if(!fi.exists())
        {
            //:
            SetDeploymentState(DeploymentState::DS_DownloadTemplate);
            // 
            std::cout<<"Start download";
            QDir dwd_path(fi.absoluteDir());
            dwd_path.mkpath(dwd_path.path());
            if(!DownloadZip(ftp_zip_path, template_zip_path))
            {
                //   ... 
                SetDeploymentState(DeploymentState::DS_Error);
                return;
            }
        }
        else
        {
            //   ,    
        }

        std::cout<<"Downloaded file exists="<<fi.exists();
        if(fi.exists())
        {
            // 
            SetDeploymentState(DeploymentState::DS_UnpackData);

            //absolutePath() -    ,   
            if(!UnpackZipFolder(fi.absoluteFilePath(), db_fi.absolutePath()))
            {
                std::cout<<"Unpack ERROR";
                SetDeploymentState(DeploymentState::DS_Error);
                return;
            }
            std::cout<<"Unpack SUCCESS";
            //SetDeploymentState(DeploymentState::DS_);
        }
    }
    else
    {
        {
            //   ... 
            //SetDeploymentState(DeploymentState::DS_Error);
            std::cout<<"Template already exists";
            return;
        }
    }*/
}

bool UProjectDeployProcessingThread::VerifyTemplate()
{
    QString proj_file_path = template_path;
    proj_file_path.replace("{Database}", databasePath);

    QFileInfo fi(proj_file_path);
    if(!fi.exists())
    {
        //,     , ,  
        //     
        return false;
    }
    return true;
}

void UProjectDeployProcessingThread::DeployScript()
{
    if(!script_dr)
        return;


    QString simulated_abs_file_path = script_path;
    QFileInfo fi(simulated_abs_file_path);
    QString base_path = fi.dir().path();

    QString remote_ftp_zip_path = base_path+".zip";
    remote_ftp_zip_path.replace("{Database}", ftpRemoteBasePath);

    QString zip_download_path = base_path+".zip";
    zip_download_path.replace("{Database}", downloadTempPath);

    QString deployment_unpack_dir = base_path;
    deployment_unpack_dir.replace("{Database}", databasePath);

    //   
    QFileInfo zd_fi(zip_download_path);
    QDir zd_d(zd_fi.absoluteDir());
    if(!zd_d.exists())
    {
        zd_d.mkpath(zd_d.path());
    }

    //   
    QDir du_d(deployment_unpack_dir);
    if(!du_d.exists())
    {
        du_d.mkpath(du_d.path());
    }



    //remote_ftp_zip_path = "ftp://192.168.102.171/database/CloudFtpDatabase/Configs/Detection/SqueezeDetHH.zip";
    //zip_download_path = "/home/ivan/RTV-VideoAnalytics/ExpDatabase/Temp/Configs/Detection/SqueezeDetHH.zip";

    //  1 - 
    // -     
    if(!zd_fi.exists())
    {
        if(!DownloadZip(remote_ftp_zip_path, zip_download_path))
        {
            std::cout<<"Download ERROR";
Aivan_2008's avatar
Aivan_2008 committed
598
            lastError+=" Download Error";
599
600
601
602
603
604
605
606
607
608
609
610
            SetDeploymentState(DeploymentState::DS_Error);
            return;
        }
    }


    // 2 = 
    // 
    SetDeploymentState(DeploymentState::DS_UnpackData);
    if(!UnpackZipFolder(zip_download_path, du_d.path()))
    {
        std::cout<<"Unpack ERROR";
Aivan_2008's avatar
Aivan_2008 committed
611
        lastError+=" Unpack Error";
612
613
614
615
616
617
618
619
620
        SetDeploymentState(DeploymentState::DS_Error);
        return;
    }
    std::cout<<"Unpack SUCCESS";

}

bool UProjectDeployProcessingThread::VerifyScript()
{
621
 return true;
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
}

void UProjectDeployProcessingThread::DeployWeights()
{
    if(!weights_dr)
        return;

    QFileInfo fi(weights_path);
    QString weights_base_path = fi.dir().path()+"/"+fi.baseName();

    QString dwd_zip_file = weights_base_path+".zip";
    dwd_zip_file.replace("{Database}", downloadTempPath);

    QString ftp_zip_file = weights_base_path+".zip";
    ftp_zip_file.replace("{Database}", ftpRemoteBasePath);

    QString zip_unpack_dir = fi.dir().path();
    zip_unpack_dir.replace("{Database}", databasePath);

    QFileInfo dwd_zip_fi(dwd_zip_file);
    QDir dwd_d(dwd_zip_fi.absoluteDir());
    if(!dwd_d.exists())
    {
        dwd_d.mkpath(dwd_d.path());
    }

    QDir zud(zip_unpack_dir);
    if(!zud.exists())
    {
        zud.mkpath(zud.path());
    }

    if(!dwd_zip_fi.exists())
    {
        if(!DownloadZip(ftp_zip_file, dwd_zip_file))
        {
Aivan_2008's avatar
Aivan_2008 committed
658
659
660
           qDebug()<<"Download error";
            lastError+=" Download Error";
            SetDeploymentState(DeploymentState::DS_Error);
661
662
663
664
665
666
667
668
           return;
        }
    }
    if(dwd_zip_fi.exists())
    {
        if(!UnpackZipFolder(dwd_zip_file, zip_unpack_dir))
        {
            qDebug()<<"Unpack error";
Aivan_2008's avatar
Aivan_2008 committed
669
670
            lastError+=" Unpack Error";
            SetDeploymentState(DeploymentState::DS_Error);
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
            return;
        }
    }


}

bool UProjectDeployProcessingThread::VerifyWeights()
{
    return true;
}

void UProjectDeployProcessingThread::DeployData()
{
    if(!videosource_dr)
        return;

    QString data_base_path = videosource_path;

    QString dwd_zip_file = "";
    QString ftp_remote_path = "";
    QString unpack_zip_fiolder = "";

    if(videosource_type==0)
    {
        //:      + *.zip

        dwd_zip_file = data_base_path+".zip";
        dwd_zip_file.replace("{Database}", downloadTempPath);

        ftp_remote_path = data_base_path+".zip";
        ftp_remote_path.replace("{Database}", ftpRemoteBasePath);

        QFileInfo qfi(data_base_path);
        unpack_zip_fiolder = qfi.dir().path();
        unpack_zip_fiolder.replace("{Database}", databasePath);
    }
    else if(videosource_type==1)
    {
        // ,       
        //    ,    

        dwd_zip_file = data_base_path+".zip";
        dwd_zip_file.replace("{Database}", downloadTempPath);

        ftp_remote_path = data_base_path+".zip";
        ftp_remote_path.replace("{Database}", ftpRemoteBasePath);

        QFileInfo qfi(data_base_path);
        unpack_zip_fiolder = qfi.dir().path()+"/"+qfi.baseName();
        unpack_zip_fiolder.replace("{Database}", databasePath);
    }

    QFileInfo dwd_fi(dwd_zip_file);
    QDir dwd_d(dwd_fi.absolutePath());

    if(!dwd_d.exists())
        dwd_d.mkpath(dwd_d.path());

    QDir unp_dir(unpack_zip_fiolder);
    if(!unp_dir.exists())
    {
        unp_dir.mkpath(unp_dir.path());
    }

    //
    if(!DownloadZip(ftp_remote_path, dwd_zip_file))
    {
        qDebug()<<"Dowonlad error";
Aivan_2008's avatar
Aivan_2008 committed
740
741
        lastError+=" Download Error";
        SetDeploymentState(DeploymentState::DS_Error);
742
743
744
745
746
747
        return;
    }

    if(!dwd_fi.exists())
    {
        qDebug()<<"File "<<dwd_fi.absoluteFilePath()<<" not exists, cannot be unpacked";
Aivan_2008's avatar
Aivan_2008 committed
748
749
        lastError+=" Downloaded file not exists, cannot be unpacked";
        SetDeploymentState(DeploymentState::DS_Error);
750
751
752
753
754
755
        return;
    }

    if(!UnpackZipFolder(dwd_zip_file, unpack_zip_fiolder))
    {
        qDebug()<<"Zip file "+dwd_zip_file+" unpack error";
Aivan_2008's avatar
Aivan_2008 committed
756
757
        lastError+=" Unpack error";
        SetDeploymentState(DeploymentState::DS_Error);
758
759
760
761
762
763
        return;
    }
}

bool UProjectDeployProcessingThread::VerifyData()
{
764
 return true;
765
766
}

767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
//====================================================================
UProjectResultsUploadingThread::UProjectResultsUploadingThread()
{

}

UProjectResultsUploadingThread::~UProjectResultsUploadingThread()
{

}

void UProjectResultsUploadingThread::SetProjectResultsDirPath(const QString& results_dir)
{
    projectResultsDir = results_dir;
}

QString UProjectResultsUploadingThread::GetProjectResultsDirPath()
{
    return projectResultsDir;
}

void UProjectResultsUploadingThread::SetStorageResultsDirPath(const QString& results_dir)
{
    storageResultsDir = results_dir;
}

QString UProjectResultsUploadingThread::GetStorageResultsDirPath()
{
    return storageResultsDir;
}

void UProjectResultsUploadingThread::SetDatabasePath(const QString& database_path)
{
    databasePath = database_path;
}

QString UProjectResultsUploadingThread::GetDatabasePath()
{
    return databasePath;
}

void UProjectResultsUploadingThread::SetRemoteFtpPath(const QString& ftp_path)
{
    remoteFtpPath = ftp_path;
}

QString UProjectResultsUploadingThread::GetRemoteFtpPath()
{
    return remoteFtpPath;
}

QString UProjectResultsUploadingThread::GetLastError()
{
    return lastError;
}

DeploymentState UProjectResultsUploadingThread::GetUploadState()
{
    return uploadState;
}

void UProjectResultsUploadingThread::run()
{
830
    uploadState = DS_CopyResults;
831
832
833
834
835
    if(!CopyResultsToDestinationDir())
    {
        uploadState = DS_Error;
        return;
    }
836
    uploadState = DS_PackResults;
837
838
839
840
841
    if(!ZipResults())
    {
        uploadState = DS_Error;
        return;
    }
842
    uploadState = DS_UploadResults;
843
844
845
846
847
    if(!UploadResultsViaFtp())
    {
        uploadState = DS_Error;
        return;
    }
848
    uploadState = DS_UploadFinished;
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
}

bool UProjectResultsUploadingThread::CopyResultsToDestinationDir()
{
    //   
    if(projectResultsDir=="")
    {
        lastError = "projectResultsDir empty";
        return false;
    }

    QDir project_results_dir(projectResultsDir);
    if(!project_results_dir.exists())
    {
        lastError = "projectResultsDir not exists: "+projectResultsDir;
        return false;
    }

    if(storageResultsDir=="")
    {
        lastError = "storageResultsDir empty";
        return false;
    }

    if(databasePath=="")
    {
        lastError = "databasePath empty";
        return false;
    }

    QDir db_path_dir(databasePath);
    if(!db_path_dir.exists())
    {
        lastError = "databasePath not exists: "+databasePath;
        return false;
    }

    QString storage_dest_dir_path = storageResultsDir;
    storage_dest_dir_path.replace("{Database}", databasePath);

    QDir storage_dest_dir(storage_dest_dir_path);

    if(!storage_dest_dir.exists())
    {
        lastError = "storage_dest_dir not exists: "+storage_dest_dir.path();
        return false;
    }

    bool copy_res = RecursiveCopyFiles(projectResultsDir, storage_dest_dir.path());

    if(!copy_res)
        return false;

    return true;
}

bool UProjectResultsUploadingThread::RecursiveCopyFiles(const QString& src_dir_path, const QString& dts_dir_path)
{
    // 
    QDir src_dir(src_dir_path);
    QDir dst_dir(src_dir_path);

    // 
    if(!src_dir.exists())
    {
        lastError = "Copy err: source dir not exists "+src_dir_path;
        return false;
    }
    if(!dst_dir.exists())
    {
        if(!dst_dir.mkpath(dst_dir.path()))
        {
            lastError = "Error create dst dir: "+dst_dir.path();
            return false;
        }
    }

    //  
    QStringList src_dir_dirlist = src_dir.entryList(QDir::Filter::NoDotAndDotDot|QDir::Filter::Dirs);
    for(QString subdir_name: src_dir_dirlist)
    {
        QString src_subdir_path = src_dir_path+"/"+subdir_name;
        QString dst_subdir_path = dts_dir_path+"/"+subdir_name;

        QDir dst_subdir(dst_subdir_path);
        if(!dst_subdir.exists())
        {
            if(!dst_subdir.mkpath(dst_subdir.path()))
            {
                lastError = "Error create dst subdir: "+dst_dir.path();
                return false;
            }
        }
        if(!RecursiveCopyFiles(src_subdir_path, dst_subdir_path))
        {
            return false;
        }
    }

    // 
    // :
    QStringList src_dir_filelist = src_dir.entryList(QDir::Filter::NoDotAndDotDot|QDir::Filter::Files);
    for(QString src_file_name: src_dir_filelist)
    {
        QString src_file_path = src_dir_path+"/"+src_file_name;
        QFile src_file(src_file_path);
        if(!src_file.exists())
        {
            lastError = "Src file not exists: "+src_file_path;
            return false;
        }
        QString dst_file_path = dts_dir_path+"/"+src_file_name;
        if(!src_file.copy(dst_file_path))
        {
            lastError = "Error copy file "+src_file_path+" to "+dst_file_path;
            return false;
        }
    }

    return true;
}

bool UProjectResultsUploadingThread::ZipResults()
{
    return true;
}

void UProjectResultsUploadingThread::processReadyReadStandardError()
{

}

void UProjectResultsUploadingThread::processReadyReadStandardOutput()
{

}

bool UProjectResultsUploadingThread::UploadResultsViaFtp()
{
    return true;
}








//====================================================================
999
1000
1001
// --------------------------
//   
// --------------------------
1002
1003
UProjectDeployerQt::UProjectDeployerQt(void):
    db(NULL),
Aivan_2008's avatar
Aivan_2008 committed
1004
    deployProcessingThread(NULL),
1005
    projectResultsUploadingThread(NULL),
1006
1007
    deploymentState(DS_NULL),
    preparationResult(-1)
1008
{
1009
1010
1011
    // curl,      
    //      ?
    curl_global_init(CURL_GLOBAL_DEFAULT);
1012
1013
1014
1015
1016
1017

  MLlibDescr classification;
  classification.LibName = "TPyUBitmapClassifier";
  classification.LibConfigFileTagName = "";
  classification.LibScriptFileTagName = "PythonScriptFileName";
  classification.LibWeightFileTagName = "WeightsPath";
1018
  classification.LibClassCountTagName = "NumClasses";
1019
1020
1021
1022
1023
1024
1025
  file_tags["TPyUBitmapClassifier"] = classification;
  component_classes.push_back("TPyUBitmapClassifier");
  MLlibDescr sq_det;
  sq_det.LibName = "TPyObjectDetectorSqueezeDet";
  sq_det.LibConfigFileTagName="ConfigPath";
  sq_det.LibScriptFileTagName="PythonScriptFileName";
  sq_det.LibWeightFileTagName="WeightsPath";
1026
  sq_det.LibClassCountTagName = "";
1027
1028
1029
1030
1031
1032
1033
  file_tags["TPyObjectDetectorSqueezeDet"] = sq_det;
  component_classes.push_back("TPyObjectDetectorSqueezeDet");
  MLlibDescr det_yolo;
  det_yolo.LibName="TPyObjectDetector";
  det_yolo.LibConfigFileTagName="ConfigPathYOLO";
  det_yolo.LibScriptFileTagName="PythonScriptFileName";
  det_yolo.LibWeightFileTagName="WeightsPathYOLO";
1034
  det_yolo.LibClassCountTagName = "";
1035
1036
1037
1038
1039
1040
1041
  file_tags["TPyObjectDetector"] = det_yolo;
  component_classes.push_back("TPyObjectDetector");
  MLlibDescr protobuf;
  protobuf.LibName = "TPySegmentatorProtobuf";
  protobuf.LibConfigFileTagName = "JSONPath";
  protobuf.LibScriptFileTagName = "PythonScriptFileName";
  protobuf.LibWeightFileTagName = "ProtobufPath";
1042
  protobuf.LibClassCountTagName = "";
1043
1044
1045
1046
1047
1048
1049
  file_tags["TPySegmentatorProtobuf"] = protobuf;
  component_classes.push_back("TPySegmentatorProtobuf");
  MLlibDescr unet;
  unet.LibName = "TPySegmentatorUNet";
  unet.LibConfigFileTagName = "";
  unet.LibScriptFileTagName = "PythonScriptFileName";
  unet.LibWeightFileTagName = "WeightsPath";
1050
  unet.LibClassCountTagName = "";
1051
1052
  file_tags["TPySegmentatorUNet"] = unet;
  component_classes.push_back("TPySegmentatorUNet");
Aivan_2008's avatar
Aivan_2008 committed
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
  MLlibDescr classifier_opencv;
  classifier_opencv.LibName = "UOpenCvClassifier";
  classifier_opencv.LibConfigFileTagName = "";
  classifier_opencv.LibScriptFileTagName = "";
  classifier_opencv.LibWeightFileTagName = "ModelPath";
  classifier_opencv.LibClassCountTagName = "NumClasses";
  file_tags["UOpenCvClassifier"] = classifier_opencv;
  component_classes.push_back("UOpenCvClassifier");
  MLlibDescr detector_opencv;
  detector_opencv.LibName = "UOpenCvDetector";
  detector_opencv.LibConfigFileTagName = "ConfigPath";
  detector_opencv.LibScriptFileTagName = "";
  detector_opencv.LibWeightFileTagName = "ModelPath";
  detector_opencv.LibClassCountTagName = "";
  file_tags["UOpenCvDetector"] = detector_opencv;
  component_classes.push_back("UOpenCvDetector");


  CaptureLibDescr opencv_videocapture;
  opencv_videocapture.LibName = "TCaptureOpenCV";
  opencv_videocapture.LibFrameIdStateName = "FramePosition";
  opencv_videocapture.LibCaptureStateTagName = "CaptureState";
  capture_tags["TCaptureOpenCV"] = opencv_videocapture;

  CaptureLibDescr imseq_capture;
  imseq_capture.LibName = "TCaptureImageSequence";
  imseq_capture.LibFrameIdStateName = "FramePosition";
  imseq_capture.LibCaptureStateTagName = "CaptureState";
  capture_tags["TCaptureImageSequence"] = imseq_capture;

1083
1084
1085
}
UProjectDeployerQt::~UProjectDeployerQt(void)
{
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
    curl_global_cleanup();
    if(!DestroyProcessingThread())
    {
        std::cout<<"Force delete processing thread!";
        delete deployProcessingThread;
    }
    if(db!=NULL)
    {
        delete db;
    }
1096
1097
1098
}
// --------------------------

1099
1100
//    
bool UProjectDeployerQt::DestroyProcessingThread()
1101
{
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
    if(deployProcessingThread==NULL)
        return true;

    if(deployProcessingThread!=NULL)
    {
        if(deployProcessingThread->GetDeploymentState()==DeploymentState::DS_Error ||
           deployProcessingThread->GetDeploymentState()==DeploymentState::DS_Unknown)
        {
            delete deployProcessingThread;
            deployProcessingThread=NULL;
            return true;
        }
        else
        {
            if(!deployProcessingThread->isRunning())
            {
                delete deployProcessingThread;
                deployProcessingThread=NULL;
                return true;
            }
        }
    }
    return false;
}

1127
int UProjectDeployerQt::StartProjectDeployment(int deploy_task_id)
1128
{
1129
 task_id = deploy_task_id;
1130
1131
 int ds = GetDeploymentState();
 if(ds!=DeploymentState::DS_NULL)
1132
 {
Aivan_2008's avatar
Aivan_2008 committed
1133
    lastError = "Deployment thread exists and currently active";
1134
1135
1136
     return 20;
 }

Aivan_2008's avatar
Aivan_2008 committed
1137
1138
 deploymentState=DS_NULL;

1139
1140
 if(!DestroyProcessingThread())
 {
Aivan_2008's avatar
Aivan_2008 committed
1141
    lastError = "Deployment thread exists and cannot be destroyed";
1142
1143
1144
1145
     return 20;
 }

 if(task_id<0)
Aivan_2008's avatar
Aivan_2008 committed
1146
1147
1148
1149
1150
1151
 {
    std::stringstream ss;
    ss<<"Wrong task_id sent by server controller "<<task_id;
    lastError = ss.str();
    return 1;
 }
1152
1153

 if(!db)
Aivan_2008's avatar
Aivan_2008 committed
1154
1155
 {
    lastError = "Database pointer is NULL";
1156
     return 1;
Aivan_2008's avatar
Aivan_2008 committed
1157
 }
1158
 if(!db->isOpen()&&db->isValid())
Aivan_2008's avatar
Aivan_2008 committed
1159
1160
1161
1162
 {
    lastError = "Database connection is not opened or database connection is not valid";
    return 2;
 }
1163
1164
1165
1166
1167
1168
1169

 //    ( )
 QSqlQuery q(*db);
 q.prepare("SELECT task_name, task_template, task_weights, task_src_type, task_src_id FROM vid_an.task_list WHERE task_id="+QString::number(task_id)+";");
 q.exec();
 q.first();
 if(!q.isValid())
Aivan_2008's avatar
Aivan_2008 committed
1170
1171
 {
     lastError = "Task query by task id invalid";
1172
     return 3;
Aivan_2008's avatar
Aivan_2008 committed
1173
1174
 }

1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186

 task_name = q.value(0).toString();
 task_template_id = q.value(1).toInt();
 task_weights_id = q.value(2).toInt();
 task_src_type = q.value(3).toInt();
 task_src_id = q.value(4).toInt();

 q.finish();
 q.clear();

 //    ,     
 // 
1187
 q.prepare("SELECT project_name, project_file FROM vid_an.projects WHERE project_id="+QString::number(task_template_id)+";");
1188
1189
1190
 q.exec();
 q.first();
 if(!q.isValid())
Aivan_2008's avatar
Aivan_2008 committed
1191
1192
 {
    lastError = "Project query by project id invalid";
1193
     return 4;
Aivan_2008's avatar
Aivan_2008 committed
1194
 }
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206

 task_template_name = q.value(0).toString();
 task_template_path = q.value(1).toString();

 q.finish();
 q.clear();

 QString database_path = Application->GetDatabaseMainPath().c_str();

 QString abs_template_file = task_template_path;
 abs_template_file.replace("{Database}", database_path);

Aivan_2008's avatar
Aivan_2008 committed
1207
1208
1209
 QFileInfo t_file(abs_template_file);

 task_template_file_name = t_file.fileName();
1210

1211
 if(!t_file.exists())
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
 {
     task_template_download_required = true;
 }
 else
 {
     task_template_download_required = false;
 }

 q.prepare("SELECT weight_path, weight_confpath, weight_numcls, weight_in_W, weight_in_H, weight_out_format, weight_script FROM vid_an.weights WHERE weight_id="+QString::number(task_weights_id)+";");
 q.exec();
 q.first();

 if(!q.isValid())
Aivan_2008's avatar
Aivan_2008 committed
1225
1226
 {
    lastError = "Weights query by weights id invalid";
1227
     return 5;
Aivan_2008's avatar
Aivan_2008 committed
1228
 }
1229
1230
1231

 task_weights_path = q.value(0).toString();
 QString weights_conf_path = q.value(1).toString();
1232
 weights_classes_number = q.value(2).toInt();
1233
1234
1235
1236
1237
1238
1239
1240
 int weights_in_W = q.value(3).toInt();
 int weights_in_H = q.value(4).toInt();
 QString weights_out_format = q.value(5).toString();
 task_script_id = q.value(6).toInt();

 q.finish();
 q.clear();

1241
1242
1243
1244
 absolute_weights_file = task_weights_path;
 absolute_weights_file.replace("{Database}", database_path);
 absolute_config_file = weights_conf_path;
 absolute_config_file.replace("{Database}", database_path);
1245

1246
1247
 QFileInfo fi_weights_path(absolute_weights_file), fi_weights_conf_path(absolute_config_file);
 if(!fi_weights_path.exists() || ((weights_conf_path!="")&&(!fi_weights_conf_path.exists())))
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
 {
     task_weights_download_required = true;
     /*
     task_weights_zip_url = QString(fi_weights_path.filePath()+".zip").replace(database_path, ftp_main_path).toUtf8().constData();
     if(fi_weights_path.filePath()!=fi_weights_conf_path.filePath())
     {
         task_weights_conf_download_required = true;
         task_weights_conf_zip_url = QString(fi_weights_conf_path.filePath()+".zip").replace(database_path, ftp_main_path).toUtf8().constData();
     }*/
 }
 else
 {
     task_weights_download_required = false;
 }

Aivan_2008's avatar
Aivan_2008 committed
1263
 if(task_script_id==0 || task_script_id==-1)
1264
 {
Aivan_2008's avatar
Aivan_2008 committed
1265
1266
    task_script_download_required=false;
    task_script_path="";
1267
1268
1269
 }
 else
 {
Aivan_2008's avatar
Aivan_2008 committed
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
     q.prepare("SELECT script_path,script_name FROM vid_an.scripts WHERE script_id="+QString::number(task_script_id)+";");
     q.exec();
     q.first();
     if(!q.isValid())
     {
        lastError = "Script query by script id invalid";
        QString s = q.lastError().text();
         return 6;
     }
     task_script_path = q.value(0).toString();
     QString script_name = q.value(1).toString();

     //TODO: Do something if dummy id change
     if(task_script_id==2 && script_name=="NoScript")
     {
        task_script_download_required=false;
        task_script_path="";
     }
     else
     {
         absolute_script_file = task_script_path;
         absolute_script_file.replace("{Database}", database_path);
         QFileInfo fi_script_path(absolute_script_file);

         q.finish();
         q.clear();
1296

Aivan_2008's avatar
Aivan_2008 committed
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
         if(!fi_script_path.exists())
         {
             task_script_download_required=true;
             //task_script_zip_url = QString(fi_script_path.filePath()+".zip").replace(database_path, ftp_main_path).toUtf8().constData();
         }
         else
         {
             task_script_download_required=false;
         }
     }
 }
1308
1309
 if(task_src_type==0) //video file
 {
Aivan_2008's avatar
Aivan_2008 committed
1310
     q.prepare("SELECT video_relpath,video_frlen FROM vid_an.videos WHERE video_id="+QString::number(task_src_id)+";");
1311
1312
1313
1314
     q.exec();
     q.first();
     if(!q.isValid())
     {
Aivan_2008's avatar
Aivan_2008 committed
1315
        lastError = "Video query by video id invalid";
1316
1317
1318
         return 7;
     }
     task_src_path = q.value(0).toString();
Aivan_2008's avatar
Aivan_2008 committed
1319
     task_src_frame_length = q.value(0).toInt();
Aivan_2008's avatar
Aivan_2008 committed
1320
1321
1322
     task_src_fullpath = task_src_path;
     task_src_fullpath.replace("{Database}", database_path);
     QFileInfo qfi_src_file(task_src_fullpath);
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
     if(!qfi_src_file.exists())
     {
         task_src_download_required = true;
         //task_src_zip_url = QString(qfi_src_file.filePath()+".zip").replace(database_path, ftp_main_path).toUtf8().constData();
     }
     else
     {
         task_src_download_required = false;
     }
 }
 else if(task_src_type==1) //image sequence
 {
     q.prepare("SELECT seq_path,seq_frlen FROM vid_an.img_seqs WHERE seq_id="+QString::number(task_src_id)+";");
     q.exec();
     q.first();
     if(!q.isValid())
     {
Aivan_2008's avatar
Aivan_2008 committed
1340
        lastError = "Image sequence query by imseq id invalid";
1341
1342
1343
         return 8;
     }
     task_src_path = q.value(0).toString();
Aivan_2008's avatar
Aivan_2008 committed
1344
     task_src_frame_length = q.value(1).toInt();
Aivan_2008's avatar
Aivan_2008 committed
1345
1346
     task_src_fullpath = task_src_path;
     task_src_fullpath.replace("{Database}", database_path);
1347
     //QFileInfo qfi_src_file(abs_src_path);
Aivan_2008's avatar
Aivan_2008 committed
1348
     QDir seq_dir(task_src_fullpath);
1349
1350
1351
     if(seq_dir.exists())
     {
         QStringList ldr = seq_dir.entryList(QDir::Filter::NoDotAndDotDot|QDir::Filter::Files);
Aivan_2008's avatar
Aivan_2008 committed
1352
         if(ldr.size()>=task_src_frame_length)
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
         {
             task_src_download_required = false;
         }
         else
         {
             task_src_download_required = true;
         }
     }
     else
     {
         task_src_download_required = true;
     }
 }
 else
Aivan_2008's avatar
Aivan_2008 committed
1367
1368
 {
     lastError = "Invalid video source type index";
1369
     return 10;
Aivan_2008's avatar
Aivan_2008 committed
1370
 }
1371
1372
1373
1374
1375
1376
1377
1378
1379

 //  , , "/tmp/..."
 //  ,        {Database}/...
 download_temp_path = database_path+"/Temp";


 if(deployProcessingThread)
 {
     if(!DestroyProcessingThread())
Aivan_2008's avatar
Aivan_2008 committed
1380
1381
     {
         lastError = "Unable to destroy processing thread";
1382
         return 20;
Aivan_2008's avatar
Aivan_2008 committed
1383
     }
1384
1385
 }

Aivan_2008's avatar
Aivan_2008 committed
1386
1387
 if(task_template_download_required||task_weights_download_required||
    task_script_download_required||task_src_download_required)
1388
 {
Aivan_2008's avatar
Aivan_2008 committed
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
     deployProcessingThread = new UProjectDeployProcessingThread();

     deployProcessingThread->SetDatabasePath(database_path);
     deployProcessingThread->SetDeploymentState(DS_Unknown);
     deployProcessingThread->SetDownloadTempPath(download_temp_path);
     if(ftp_remote_path!="")
     {
        deployProcessingThread->SetFtpRemoteBasePath(QString(ftp_remote_path.c_str()));
     }
     else
     {
        qDebug("Empty ftp_remote_path on deploy processing stage");
     }

     std::cout<<"Initialize deployment thread: ttdr="<<task_template_download_required<<" atf="<<abs_template_file.toUtf8().constData()<<
            " twdr="<<task_weights_download_required<<" twp="<<task_weights_path.toUtf8().constData()<<" tsdr="<<task_script_download_required<<
            " tsp="<<task_script_path.toUtf8().constData()<<" tsrcdr="<<task_src_download_required<<" tst="<<task_src_type<<" tsp="<<task_src_path.toUtf8().constData();

     deployProcessingThread->PrepareProjectDeployment(task_template_download_required, task_template_path,
                                                      task_weights_download_required, task_weights_path,
                                                      task_script_download_required, task_script_path,
                                                      task_src_download_required, task_src_type, task_src_path);
     deployProcessingThread->RunProjectDeployment();
1412
1413
1414
 }
 else
 {
Aivan_2008's avatar
Aivan_2008 committed
1415
1416
    //     ,      ,    ?
    this->deploymentState = DS_DeployFinished;
1417
1418
 }

Aivan_2008's avatar
Aivan_2008 committed
1419
 lastError = "";
Aleksandr Bakhshiev's avatar
Aleksandr Bakhshiev committed
1420
 return 0;
1421
1422
}

1423
1424
1425
void UProjectDeployerQt::AConnectToDatabase()
{
    if(db==NULL)
Aivan_2008's avatar
Aivan_2008 committed
1426
    {
1427
        db=new QSqlDatabase();
Aivan_2008's avatar
Aivan_2008 committed
1428
1429
1430
1431
1432
1433
1434
1435
    }
    else
    {
        if(db->isOpen())
            db->close();
        delete db;
        db=new QSqlDatabase();
    }
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454

    *db = QSqlDatabase::addDatabase("QPSQL");

    db->setHostName(database_address.c_str());
    db->setDatabaseName(database_name.c_str());
    db->setUserName(database_login.c_str());
    db->setPassword(database_password.c_str());

    if(!db->open())
    {
        db->close();
        delete db;
        exit(1);
    }
}

/*
enum DeploymentState
{
1455
1456
1457
1458
    DS_NULL,
    DS_Unknown,
    DS_DownloadTemplate,
    DS_UnpackTemplate,
1459
1460
1461
1462
1463
    DS_DownloadWeights,
    DS_UnpackWeights,
    DS_DownloadScripts,
    DS_UnpackScripts,
    DS_DownloadData,
1464
1465
    DS_UnpackData,
    DS_Error
1466
1467
1468
};
*/

1469
1470
std::string UProjectDeployerQt::GetLastError()
{
Aivan_2008's avatar
Aivan_2008 committed
1471
1472
1473
    std::string le = "";
    if(lastError!="")
    {
Aivan_2008's avatar
Aivan_2008 committed
1474
        le = std::string("UProjectDeployerQt lastError=")+lastError+std::string(" ");
Aivan_2008's avatar
Aivan_2008 committed
1475
    }
1476
1477
    if(deployProcessingThread==NULL)
    {
Aivan_2008's avatar
Aivan_2008 committed
1478
1479
        if(le=="")
            le=le+std::string("DeployProcessingThread lastError: Deploy thread not exists. ");
1480
1481
1482
    }
    else
    {
Aivan_2008's avatar
Aivan_2008 committed
1483
1484
1485
        std::string dtle = deployProcessingThread->GetLastError();
        if(dtle!="")
            le=le+std::string("DeployProcessingThread lastError: ")+dtle;
1486
    }
Aivan_2008's avatar
Aivan_2008 committed
1487
    return le;
1488
}
1489

1490
int UProjectDeployerQt::GetDeploymentState()
1491
1492
1493
{
    if(deployProcessingThread==NULL)
    {
Aivan_2008's avatar
Aivan_2008 committed
1494
        return deploymentState;
1495
1496
1497
1498
    }
    else
    {
        bool t = deployProcessingThread->isRunning();
1499
        return deployProcessingThread->GetDeploymentState();
1500
1501
1502
    }
}

Aivan_2008's avatar
Aivan_2008 committed
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
std::string UProjectDeployerQt::GetProjectFileName()
{
    if(task_template_path!="")
    {
        QFileInfo fi(task_template_path);
        if(fi.exists())
        {
            return task_template_path.toUtf8().constData();
        }
        else
        {
            return std::string();
        }
    }
    else
    {
        return std::string();
    }
}

1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
int UProjectDeployerQt::GetStageCap()
{
    if(deployProcessingThread==NULL)
    {
        return -1;
    }
    else
    {
        return deployProcessingThread->GetDeploymentProgressCap();
    }
}

int UProjectDeployerQt::GetStageProgress()
{
    if(deployProcessingThread==NULL)
    {
        return -1;
    }
    else
    {
        return deployProcessingThread->GetDeploymentProgress();
    }
}

Aivan_2008's avatar
Aivan_2008 committed
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
///   :
/// 1.    
/// 2.         ?
/// 3. 
int UProjectDeployerQt::PrepareProject(std::string &response)
{
    lastError="";
    if(this->deploymentState!=DS_DeployFinished)
    {
        response = "Project deployment is not opened, can't start preparations";
        lastError=response;
1558
        preparationResult=1;
Aivan_2008's avatar
Aivan_2008 committed
1559
1560
1561
1562
1563
1564
1565
1566
        return 1;
    }
    this->deploymentState = DS_CopyProject;
    if(CopyProjectToTempFolder()!=0)
    {
        this->deploymentState=DS_Error;
        response = "error during copying";
        lastError=response;
1567
        preparationResult=1;
Aivan_2008's avatar
Aivan_2008 committed
1568
1569
1570
1571
1572
1573
1574
1575
        return 1;
    }
    this->deploymentState=DS_PrepareProject;
    if(OpenProjectMockMode()!=0)
    {
        this->deploymentState=DS_Error;
        response = "error during opening in mock mode";
        lastError=response;
1576
1577
1578
1579
1580
1581
1582
1583
        preparationResult=1;
        return 1;
    }
    std::string bug_string="";
    if(AnalyzeLogForErrors(bug_string)>=0)
    {
        lastError="Mock open error: "+bug_string;
        preparationResult=1;
Aivan_2008's avatar
Aivan_2008 committed
1584
1585
1586
1587
1588
1589
1590
        return 1;
    }
    if(SetupProjectMockParameters()!=0)
    {
        this->deploymentState=DS_Error;
        response = "error during mock parameters setup";
        lastError=response;
1591
        preparationResult=1;
Aivan_2008's avatar
Aivan_2008 committed
1592
1593
1594
1595
1596
1597
1598
        return 1;
    }
    if(CloseMockProject()!=0)
    {
        this->deploymentState=DS_Error;
        response = "error during mocked project closing";
        lastError=response;
1599
1600
1601
1602
1603
1604
1605
        preparationResult=1;
        return 1;
    }
    if(AnalyzeLogForErrors(bug_string)>=0)
    {
        lastError="Mock open error: "+bug_string;
        preparationResult=1;
Aivan_2008's avatar
Aivan_2008 committed
1606
1607
1608
1609
1610
        return 1;
    }
    this->deploymentState=DS_ProjectPrepared;
    response = "project prepared successfully";
    lastError=response;
1611
    preparationResult=0;
Aivan_2008's avatar
Aivan_2008 committed
1612
1613
1614
    return 0;
}

1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
int UProjectDeployerQt::AnalyzeLogForErrors(std::string &problem_string)
{
    std::list<std::string> gui_unsent_log = Application->GetEngineControl()->GetEngineStateThread()->ReadGuiUnsentLog();

    for(std::string log_entry: gui_unsent_log)
    {
        QString msg_line = log_entry.c_str();
        //Take string and split into parts
        int sys_info_end = msg_line.indexOf("] ", 0)+1;//index of first space of message

        if(sys_info_end>=0)
        {
            //Process line taking into account lines saved previously
            QString sys_info_line = msg_line.left(sys_info_end);
            QString message_data = msg_line.right(msg_line.length()-sys_info_end);
            QStringList str_parts = sys_info_line.split(" ");

            //QString src_info = str_parts[0];
            //src_info = src_info.replace(">", "").trimmed();
            //QString date_info = str_parts[1];
            //QString time_info = str_parts[2];
            QString error_level_i = str_parts[3];
            int error_level = error_level_i.replace(">", "").trimmed().toInt();
            //QString error_level_s = str_parts[4];
            //Unknown, Fatal, Error levels
            if(error_level>=0 && error_level<=2)
            {
                //std::cerr<<message_data.toUtf8().constData()<<"\n\n";
                problem_string = message_data.toUtf8().constData();
                //Found fatal error, nothing needed to read any longer
                return error_level;
            }
        }

    }

   //std::string log_path = Application->Get
   problem_string = "No error occured";
   return -1;
}

int UProjectDeployerQt::GetPreparationResult(std::string &response)
{
    response=lastError;
    return preparationResult;
}

Aivan_2008's avatar
Aivan_2008 committed
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
///  
int UProjectDeployerQt::OpenPreparedProject(std::string &response)
{
    if(this->deploymentState!=DS_ProjectPrepared)
    {
        response = "Project is not prepared yet";
        lastError=response;
        return 1;
    }
    deploymentState = DS_OpenProject;
    // -     
    //RDK::Sleep(3);
    Application->SetStorageBuildMode(1);
    QString pdpath = GetTempProjectDeploymentPath().c_str();
Aivan_2008's avatar
Aivan_2008 committed
1676
    QString project_path = pdpath+"/"+task_template_file_name;
Aivan_2008's avatar
Aivan_2008 committed
1677
1678
1679
    if(!Application->OpenProject(project_path.toUtf8().constData()))
    {
        lastError="UApplication OpenProject normally error";
Aivan_2008's avatar
Aivan_2008 committed
1680
1681
1682
1683
1684
1685
1686
        response = lastError;
        return 1;
    }

    if(AnalyzeLogForErrors(response)>=0)
    {
        lastError=response;
Aivan_2008's avatar
Aivan_2008 committed
1687
1688
1689
1690
1691
1692
1693
1694
1695
        return 1;
    }
    ////
    deploymentState = DS_ProjectOpened;
    response = "project opened successfully";
    lastError=response;
    return 0;
}

1696
1697
1698
1699
// --------------------------
//   
// --------------------------

Aivan_2008's avatar
Aivan_2008 committed
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
///    ,     
int UProjectDeployerQt::CopyProjectToTempFolder()
{
    QString pdpath = GetTempProjectDeploymentPath().c_str();
    if(pdpath=="")
    {
        lastError="project temporary deployment path empty - cannot copy";
        return 1;
    }
    QString abs_ttp = task_template_path;
    QString db_p = Application->GetDatabaseMainPath().c_str();
    abs_ttp.replace("{Database}", db_p);

    QFileInfo fi(abs_ttp);
    QDir src_dir(fi.absoluteDir());
    QStringList files_dirs = src_dir.entryList(QDir::Filter::NoDotAndDotDot|QDir::Filter::Files);
    //  
    for(QString fn:files_dirs)
    {
        QFile::copy(src_dir.path()+"/"+fn, pdpath+"/"+fn);
    }
    QDir pddir(pdpath);
    //   
    pddir.mkdir("EventsLog");
    //..   
    pddir.mkdir("Results");

    //RDK::Sleep(3);
    return 0;
}

///     
int UProjectDeployerQt::OpenProjectMockMode()
{
    //  
    Application->CreateSaveMockLibs();
    //     
    Application->SetStorageBuildMode(3);
    QString pdpath = GetTempProjectDeploymentPath().c_str();
Aivan_2008's avatar
Aivan_2008 committed
1739
    QString project_path = pdpath+"/"+task_template_file_name;
Aivan_2008's avatar
Aivan_2008 committed
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
    if(!Application->OpenProject(project_path.toUtf8().constData()))
    {
        lastError="UApplication OpenProject Mock Components error";
        return 1;
    }
    return 0;
}

///      
int UProjectDeployerQt::SetupProjectMockParameters()
{
    RDK::Sleep(3);

1753
    RDK::UELockPtr<RDK::UNet> model = RDK::GetModelLock<RDK::UNet>(0);
Aivan_2008's avatar
Aivan_2008 committed
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773

    if(!model) return 1;

    // 

    RDK::UEPtr<RDK::UContainer> video_cont;
    RDK::UEPtr<RDK::UContainer> imseq_cont;
    std::vector<std::string> vid_names;
    vid_names = model->GetComponentsNameByClassName("TCaptureOpenCV", vid_names);
    std::vector<std::string> imseq_names;
    imseq_names = model->GetComponentsNameByClassName("TCaptureImageSequence", imseq_names);

    if(task_src_type==0)//TODO:  - 
    {
        if(vid_names.empty())
        {
            // - 
            lastError="Model does not contain video data source, fix project file/task parameters";
            return 1;
        }
Aivan_2008's avatar
Aivan_2008 committed
1774
1775
        capture_class_name = "TCaptureOpenCV";
        capture_component_name = vid_names[0];
Aivan_2008's avatar
Aivan_2008 committed
1776
1777
1778
1779
        video_cont = model->GetComponentL(vid_names[0]);
        bool *video_Activity = video_cont->AccessPropertyData<bool>("Activity");
        bool *video_EnableCapture = video_cont->AccessPropertyData<bool>("EnableCapture");
        std::string *video_CameraPath = video_cont->AccessPropertyData<std::string>("CameraPath");
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
        bool *video_OneShotRun = video_cont->AccessPropertyData<bool>("OneShotRun");
        bool *video_ProcessEvenFrames = video_cont->AccessPropertyData<bool>("ProcessEvenFrames");
        int *video_ProcessEveryXFrame = video_cont->AccessPropertyData<int>("ProcessEveryXFrame");
        std::string *video_DllName = video_cont->AccessPropertyData<std::string>("DllName");

        //bool *video_RepeatFlag = video_cont->AccessPropertyData<bool>("RepeatFlag");
        int *video_RestartMode = video_cont->AccessPropertyData<int>("RestartMode");

        bool *video_UseRelativePathFromConfig = video_cont->AccessPropertyData<bool>("UseRelativePathFromConfig");
        bool *video_UseRelativePathFromDir = video_cont->AccessPropertyData<bool>("UseRelativePathFromDir");

Aivan_2008's avatar
Aivan_2008 committed
1791
1792
1793
        *video_Activity = true;
        *video_EnableCapture = true;
        *video_CameraPath = task_src_fullpath.toUtf8().constData();
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
        *video_DllName = "VideoCaptureOpenCVDll";
        *video_OneShotRun = true;
        *video_ProcessEvenFrames = true;
        *video_ProcessEveryXFrame = 1;
        if(video_UseRelativePathFromConfig!=NULL)
            *video_UseRelativePathFromConfig = false;
        if(video_UseRelativePathFromDir!=NULL)
            *video_UseRelativePathFromDir = false;
        //*video_RepeatFlag = false;
        *video_RestartMode = 0;
Aivan_2008's avatar
Aivan_2008 committed
1804
1805
1806
1807
1808

        if(!imseq_names.empty())
        {
            imseq_cont = model->GetComponentL(imseq_names[0]);
            bool *act = imseq_cont->AccessPropertyData<bool>("Activity");
1809
            //TODO: Brake wrong link
1810
            model->BreakAllOutgoingLinks(imseq_names[0]);
Aivan_2008's avatar
Aivan_2008 committed
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
            *act = false;
        }
    }
    else if(task_src_type==1)//TODO:  - 
    {
        if(imseq_names.empty())
        {
            //   - 
            lastError="Model does not contain image sequence data source, fix project file/task parameters";
            return 1;
        }
1822

Aivan_2008's avatar
Aivan_2008 committed
1823
1824
        capture_class_name = "TCaptureImageSequence";
        capture_component_name = imseq_names[0];
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
        imseq_cont = model->GetComponentL(imseq_names[0]);
        bool *imseq_Activity = imseq_cont->AccessPropertyData<bool>("Activity");
        std::string *imseq_Path = imseq_cont->AccessPropertyData<std::string>("Path");
        bool *imseq_EnableCapture = imseq_cont->AccessPropertyData<bool>("EnableCapture");
        double *imseq_DesiredFps = imseq_cont->AccessPropertyData<double>("DesiredFps");
        bool *imseq_RepeatFlag = imseq_cont->AccessPropertyData<bool>("RepeatFlag");
        int  *imseq_RestartMode = imseq_cont->AccessPropertyData<int>("RestartMode");
        bool *imseq_UseRelativePathFromConfig = imseq_cont->AccessPropertyData<bool>("UseRelativePathFromConfig");
        bool *imseq_UseRelativePathFromDir = imseq_cont->AccessPropertyData<bool>("UseRelativePathFromDir");

        *imseq_Activity = true;
        *imseq_Path = task_src_fullpath.toUtf8().constData();
        *imseq_EnableCapture = true;
        *imseq_DesiredFps = 0;
        *imseq_RepeatFlag = false;
        *imseq_RestartMode = 0;
        *imseq_UseRelativePathFromConfig = false;
        if(imseq_UseRelativePathFromDir)
            *imseq_UseRelativePathFromDir = false;

        if(!vid_names.empty())
        {
            video_cont = model->GetComponentL(vid_names[0]);
            bool *act = video_cont->AccessPropertyData<bool>("Activity");
            //TODO: Brake wrong link
1850
            model->BreakAllOutgoingLinks(vid_names[0]);
1851
1852
            *act = false;
        }
Aivan_2008's avatar
Aivan_2008 committed
1853
1854
1855
1856
1857
1858
1859
1860
    }
    else
    {
        //  ,   
        lastError="Video source type has undefined value";
        return 1;
    }

1861
1862
1863
1864
1865
    //   
    //std::vector<std::string> pipelineNames;
    /*RDK::UEPtr<RDK::UContainer> pipeline;
    pipeline = model->GetComponentL("Pipeline1");
    if(!pipeline.Get())
Aivan_2008's avatar
Aivan_2008 committed
1866
    {
1867
1868
1869
1870
1871
1872
        lastError="VideoAnalytics Pipeline1 class undetected";
        return 1;
    }*/
    std::vector<std::string> components_names;
    std::string class_name = "";
    for(std::string cls_name: component_classes)
Aivan_2008's avatar
Aivan_2008 committed
1873
    {
1874
1875
1876
1877
1878
1879
        components_names = model->GetComponentsNameByClassName(cls_name.c_str(), components_names, true);
        if(!components_names.empty())
        {
            class_name = cls_name;
            break;
        }
Aivan_2008's avatar
Aivan_2008 committed
1880
    }
1881
1882
1883
1884
1885
1886
1887
1888

    // !!! Here I do not take into account situation when      !!!
    // !!! more than one neural component present into project !!!
    if(components_names.empty() || class_name=="")
    {
        //No classes found
        lastError="No one neural network related component found";
        return 1;
Aivan_2008's avatar
Aivan_2008 committed
1889
    }
1890
1891
1892
1893
1894
1895

    //Here component class found
    RDK::UEPtr<RDK::UContainer> neural_cont;
    neural_cont = model->GetComponentL(components_names[0]);

    bool *nn_Activity = neural_cont->AccessPropertyData<bool>("Activity");
Aivan_2008's avatar
Aivan_2008 committed
1896
1897
1898
    std::string *nn_ScriptFile;
    if(file_tags[class_name].LibScriptFileTagName!="")
        nn_ScriptFile = neural_cont->AccessPropertyData<std::string>(file_tags[class_name].LibScriptFileTagName.c_str());
1899
1900
    std::string *nn_WeightsFile = neural_cont->AccessPropertyData<std::string>(file_tags[class_name].LibWeightFileTagName.c_str());
    std::string *nn_ConfigFile;
1901
    int *nn_ClassCount;
1902
1903
1904
    if(file_tags[class_name].LibConfigFileTagName!="")
        nn_ConfigFile = neural_cont->AccessPropertyData<std::string>(file_tags[class_name].LibConfigFileTagName.c_str());

1905
1906
    if(file_tags[class_name].LibClassCountTagName!="")
        nn_ClassCount = neural_cont->AccessPropertyData<int>(file_tags[class_name].LibClassCountTagName.c_str());
1907
    *nn_Activity = true;
Aivan_2008's avatar
Aivan_2008 committed
1908
1909
    if(file_tags[class_name].LibScriptFileTagName!="")
        *nn_ScriptFile = absolute_script_file.toUtf8().constData();
1910
1911
1912
    *nn_WeightsFile = absolute_weights_file.toUtf8().constData();
    if(file_tags[class_name].LibConfigFileTagName!="")
        *nn_ConfigFile = absolute_config_file.toUtf8().constData();
1913
1914
    if(file_tags[class_name].LibClassCountTagName!="")
        *nn_ClassCount = weights_classes_number;
Aivan_2008's avatar
Aivan_2008 committed
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927

    return 0;
}

///   
int UProjectDeployerQt::CloseMockProject()
{
    //RDK::Sleep(3);
    Application->SaveProject();
    Application->CloseProject();
    return 0;
}

1928
1929
1930
1931
1932
1933
1934
1935
QString UProjectDeployerQt::GetTimeStampInPSqlFormat(const QDateTime &now)
{
    QString datetime = now.toString("yyyy-MM-dd hh:mm:ss");
    int offset_secs = now.offsetFromUtc();
    int offset_hours = offset_secs/3600;
    QString offset = (offset_hours>0)?("+"+QString::number(offset_hours).rightJustified(2, '0')):(QString::number(offset_hours).rightJustified(2, '0'));
    return (datetime+offset);
}
Aivan_2008's avatar
Aivan_2008 committed
1936

Aivan_2008's avatar
Aivan_2008 committed
1937
1938
1939
1940
///