DOCloudSolver.cc 29.9 KB
Newer Older
1
2
3
4
5
6
//=============================================================================
//
//  CLASS DOCloudSolver - IMPLEMENTATION
//
//=============================================================================

7
// TODO: this uses Cbc for the MPS file export; consider implementing our own 
8
9
10
11
12
13
14
15
16
17
// MPS/LP export to remove the dependency.

//== INCLUDES =================================================================

//== COMPILE-TIME PACKAGE REQUIREMENTS ========================================
#include <CoMISo/Config/config.hh>
#if COMISO_DOCLOUD_AVAILABLE

//=============================================================================
#include "DOCloudSolver.hh"
18
#include "DOCloudCache.hh"
19
20

#include <Base/Debug/DebTime.hh>
21
#include <Base/Debug/DebUtils.hh>
22
23
#include <Base/Utils/OutcomeUtils.hh>

24
25
26
27
#include <curl/curl.h>

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
28
29

#include <stdexcept>
30
31
32
33
34
#include <iostream>
#include <algorithm>
#include <thread>         
#include <chrono>         

35
#include <stdio.h>
36
37
#include <stdlib.h>
#include <io.h>
38
39
40
41
42
43
44
45
46

DEB_module("DOCloudSolver")

//== NAMESPACES ===============================================================

namespace COMISO {

//== IMPLEMENTATION ==========================================================

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
namespace cURLpp { // some classes to wrap around the libcurl C data

struct Session
{
  Session() { curl_global_init(CURL_GLOBAL_DEFAULT); }
  ~Session() { curl_global_cleanup(); }
};

// TODO: This inheritance could be restrictive in the future for now is OK
class Request
{
public:
  Request() : hnd_(curl_easy_init()), http_hdr_(nullptr) {}
  
  virtual ~Request() 
  { 
    curl_easy_cleanup(hnd_); 
    if (http_hdr_ != nullptr)
      curl_slist_free_all(http_hdr_);
  }

  //operator CURL*() { return hnd_; } 
  //operator const CURL*() const { return hnd_; } 

  bool valid() const { return hnd_ != nullptr; }

  void set_url(const char* _url)
  {
    curl_easy_setopt(hnd_, CURLOPT_URL, _url);
  }

  void add_http_header(const char* _hdr)
  {
    http_hdr_ = curl_slist_append(http_hdr_, _hdr);
  }

  // TODO: REMOVE this security hole!!
  void disable_ssl_verification()
  {
    /*
     * If you want to connect to a site who isn't using a certificate that is
     * signed by one of the certs in the CA bundle you have, you can skip the
     * verification of the server's certificate. This makes the connection
     * A LOT LESS SECURE.
     *
     * If you have a CA cert for the server stored someplace else than in the
     * default bundle, then the CURLOPT_CAPATH option might come handy for
     * you.
     */ 
    curl_easy_setopt(hnd_, CURLOPT_SSL_VERIFYPEER, 0L);
 
    /*
     * If the site you're connecting to uses a different host name that what
     * they have mentioned in their server certificate's commonName (or
     * subjectAltName) fields, libcurl will refuse to connect. You can skip
     * this check, but this will make the connection less secure.
     */ 
    curl_easy_setopt(hnd_, CURLOPT_SSL_VERIFYHOST, 0L);
  }

  void perform()
  {
    DEB_enter_func;

    prepare();

    // set the header we send to the server
    curl_easy_setopt(hnd_, CURLOPT_HTTPHEADER, http_hdr_);
    // set the write function to handle incoming data from the server
    curl_easy_setopt(hnd_, CURLOPT_WRITEFUNCTION, write_func);
    // set the string to store the incoming header data
    curl_easy_setopt(hnd_, CURLOPT_HEADERDATA, reinterpret_cast<void*>(&hdr_));
    // set the string to store the incoming main body (data)
    curl_easy_setopt(hnd_, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&bdy_));
    // do the transmission
122
    for (int try_nmbr = 0; ; ++try_nmbr) // test exit conditions below
123
    {
124
125
126
127
128
129
130
131
132
133
134
135
136
      auto res = curl_easy_perform(hnd_);
      // Various errors can occur while performing the request, but a single 
      // retry is usually sufficient to recover, we do up to 10 attempts.
      // CURLE_SSL_CONNECT_ERROR happens a lot with the DOcloud service
      // CURLE_COULDNT_CONNECT happens occasionally.
      if (res == CURLE_OK) 
        break; // success, exit here
      else if (try_nmbr < 10) // retry
        DEB_warning(1, "curl_easy_perform() try #" << try_nmbr << " failed "
          "with code: " << res << ", message: " << curl_easy_strerror(res))
      else 
        THROW_OUTCOME(TODO)
    }
137

138
139
    DEB_line(6, "Received Header: " << hdr_);
    DEB_line(6, "Received Body: " << bdy_);
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206

    finalize();
  }

  const std::string& header() const { return hdr_; }
  const std::string& body() const { return bdy_; }

protected:
  static size_t write_func(const char* _ptr, const size_t _size, 
    const size_t _nmemb, void* _str)
  {
    // TODO: not sure how much exception-safe (e.g. out of memory this is!)
    size_t n_add = _size * _nmemb;
    if (n_add == 0)
      return 0;

    auto& str = *reinterpret_cast<std::string*>(_str);
    str.append(_ptr, n_add);
    return n_add;
  }

  // Apparently read callback function is required with Windows libcurl DLL!?
  //static size_t read_func(void* _ptr, const size_t _size, 
  //  const size_t _nmemb, FILE* _file)
  //{
  //  return fread(_ptr, _size, _nmemb, _file);
  //}


protected:
  CURL* hnd_;

protected:
  //virtual functions to control the perform() behavior
  virtual void prepare() {}
  virtual void finalize() {}

private:
  curl_slist* http_hdr_;
  std::string hdr_;
  std::string bdy_;
};

class Post : public Request
{
public: 
  Post(const char* _post) : post_(_post) {}
  Post(const std::string& _post) : post_(_post) {}

protected:
    virtual void prepare()
    {
      // set the post fields
      curl_easy_setopt(hnd_, CURLOPT_POSTFIELDS, post_.data());
      curl_easy_setopt(hnd_, CURLOPT_POSTFIELDSIZE, post_.size());
    }

private:
  std::string post_;
};

class Upload : public Request
{
protected:
  virtual void prepare();
  virtual void finalize();

207
  virtual size_t send_data() = 0;
208
209
210
211
212
213
214
};

void Upload::prepare()
{
  /* tell it to "upload" to the URL */ 
  curl_easy_setopt(hnd_, CURLOPT_UPLOAD, 1L);

215
  size_t data_len = send_data();
216
  /* and give the size of the upload (optional) */ 
217
  curl_easy_setopt(hnd_, CURLOPT_INFILESIZE_LARGE, (curl_off_t)data_len);
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240

  /* we want to use our own read function */
  //curl_easy_setopt(hnd_, CURLOPT_READFUNCTION, read_func);

  /* enable verbose for easier tracing */ 
  //curl_easy_setopt(hnd_, CURLOPT_VERBOSE, 1L);
}

void Upload::finalize()
{
  DEB_enter_func;

  double rate, time;

  /* now extract transfer info */ 
  curl_easy_getinfo(hnd_, CURLINFO_SPEED_UPLOAD, &rate);
  curl_easy_getinfo(hnd_, CURLINFO_TOTAL_TIME, &time);

  DEB_double_format("%.2f");
  DEB_line(2, 
    "Upload speed: " << rate / 1024. << "Kbps; Time: " << time << "s.");
}

241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
class UploadFile : public Upload
{
public:
  UploadFile(const char* _filename) : filename_(_filename) {}
  UploadFile(const std::string& _filename) : filename_(_filename) {}

  virtual ~UploadFile()
  {
    if (file_ != nullptr)
      std::fclose(file_);
  }

protected:
  virtual size_t send_data()
  {
    /* set where to read from (on Windows you need to use READFUNCTION too) */ 
    file_ = std::fopen(filename_.data(), "rb");
    curl_easy_setopt(hnd_, CURLOPT_READDATA, file_);

    return  _filelength(fileno(file_));
  }

private:
  std::string filename_;
  FILE* file_;
};

class UploadData : public Upload
{
public:
  UploadData(const std::string& _data) : file_dat_(_data)  { }

protected:
  virtual size_t send_data()
  {
    curl_easy_setopt(hnd_, CURLOPT_READFUNCTION, Buffer::copy);
    curl_easy_setopt(hnd_, CURLOPT_READDATA, &file_dat_);
    return file_dat_.len_;
  }

private:
  class Buffer
  {
  public:
    Buffer(const std::string& _data)
      : ptr_(_data.c_str()), len_(_data.size()), pos_(0) {}
    static size_t copy(void* _target, const size_t _elem_size, 
      const size_t _n_elem, void* _from_buf);

    const char* ptr_;
    size_t len_;
  private:
    size_t pos_;
  };
  Buffer file_dat_;
};

size_t UploadData::Buffer::copy(void* _target, const size_t _elem_size, 
                                const size_t _n_elem, void* _from_buf)
{
  auto dat = reinterpret_cast<Buffer *>(_from_buf);
  size_t char_to_write = dat->len_ - dat->pos_;
  size_t buffer_len = _elem_size * _n_elem;
  if (char_to_write > buffer_len)
    char_to_write = buffer_len;
  std::copy(dat->ptr_ + dat->pos_, dat->ptr_ + dat->pos_ + char_to_write,
    (char*)_target);
  dat->pos_ += char_to_write;
  return char_to_write;
}

312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
class Get : public Request
{
protected:
    virtual void prepare() { curl_easy_setopt(hnd_, CURLOPT_HTTPGET, 1L); }
};

class Delete : public Request
{
protected:
    virtual void prepare() 
    { 
      curl_easy_setopt(hnd_, CURLOPT_CUSTOMREQUEST, "DELETE"); 
    }
};

327
328
} // namespace cURLpp 

329
330
331
332

namespace DOcloud {

static char* root_url__ = 
333
  "https://api-oaas.docloud.ibmcloud.com/job_manager/rest/v1/jobs";
334
static std::string api_key__ = 
335
  "X-IBM-Client-Id: api_0821c92f-0f2b-4ea5-be24-ecc9cd7695dd";
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
static char* app_type__ = "Content-Type: application/json";

class HeaderTokens
{
public:
  HeaderTokens(const std::string& _hdr)
  {
    // TODO: Performance can be improved by indexing, strtok_r(), etc ...
    //  ... but probably not worth the effort
    std::istringstream strm(_hdr);
    typedef std::istream_iterator<std::string> Iter;
    std::copy(Iter(strm), Iter(), std::back_inserter(tkns_));  
  }

  const std::string& operator[](const size_t _idx) const
  {
    return tkns_[_idx];
  }

  size_t number() const { return tkns_.size(); }

  // Find a token equal to the label and return its value (next token)
  bool find_value(const std::string& _lbl, std::string& _val) const
  {
    auto it = std::find(tkns_.begin(), tkns_.end(), _lbl);
    if (it == tkns_.end() || ++it == tkns_.end())
      return false;

    _val = *it;
    return true;
  }

  typedef std::vector<std::string>::const_iterator const_iterator;

  const_iterator begin() const { return tkns_.begin();}
  const_iterator end() const { return tkns_.end();}

private:
  std::vector<std::string> tkns_;
};

class JsonTokens
{
public:
  JsonTokens() {}
  JsonTokens(const std::string& _bdy) { set(_bdy); }

  void set(const std::string& _bdy)
  {
    ptree_.clear();
386
387
    if (_bdy.empty())
      return;
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
    std::istringstream strm(_bdy);
    boost::property_tree::json_parser::read_json(strm, ptree_);
  }

  //size_t number() const { return tkns_.size(); }

  // Find a token equal to the label and return its value
  bool find_value(const std::string& _lbl, std::string& _val) const
  {
    auto it = ptree_.find(_lbl);
    if (it == ptree_.not_found())
      return false;

    _val = it->second.get_value<std::string>();
    return true;
  }

  typedef boost::property_tree::ptree PTree;

  const PTree& ptree() const { return ptree_; }

private:
  PTree ptree_;
};

413
Debug::Stream& operator<<(Debug::Stream& _ds, const JsonTokens::PTree& _ptree)
414
415
{
  std::stringstream os;
416
  boost::property_tree::json_parser::write_json(os, _ptree);
417
418
419
420
  _ds << os.str();
  return _ds;
}

421
422
423
424
425
Debug::Stream& operator<<(Debug::Stream& _ds, const JsonTokens& _json_tkns)
{
  return _ds << _json_tkns.ptree();
}

426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
void throw_http_error(const int _err_code, const std::string& _bdy)
{
  DEB_enter_func;

  std::string err_msg;
  JsonTokens bdy_tkns(_bdy);
  bdy_tkns.find_value("message", err_msg);
  DEB_warning(1, "HTTP Status Code: " << _err_code << "; Message: " << err_msg);

  switch (_err_code)
  {
  case 400 : THROW_OUTCOME(TODO); // Invalid job creation data / status
  case 403 : THROW_OUTCOME(TODO); // Subscription limit exceeded
  case 404 : THROW_OUTCOME(TODO); // Requested job could not be found
  default : THROW_OUTCOME(TODO); // Unrecognized HTTP status code
  }
}

444
class HttpStatus
445
{
446
447
448
public:
  HttpStatus(const cURLpp::Request& _rqst)
    : rqst_(_rqst), hdr_tkns_(_rqst.header()), code_(0)
449
  {
450
451
452
453
454
455
456
457
458
459
460
461
462
    const std::string http_lbl = "HTTP/1.1";
    const int code_cntn = 100; // continue code, ignore

    for (auto it = hdr_tkns_.begin(), it_end = hdr_tkns_.end(); it != it_end; ++it)
    {
      if (*it != http_lbl) // search for the http label token
        continue; 
      THROW_OUTCOME_if(++it == it_end, TODO); // missing http code
      code_ = atoi(it->data());
      if (code_ != code_cntn)
        return;
    }
    THROW_OUTCOME(TODO); // final http code not found
463
464
  }

465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
  void check(int _code_ok) const
  {
    if (code_ != _code_ok)  // another code found, throw an error
      throw_http_error(code_, rqst_.body());
  }

  const int& code() const { return code_; }

  const HeaderTokens& header_tokens() const { return hdr_tkns_; }

private:
  const cURLpp::Request& rqst_;
  HeaderTokens hdr_tkns_;
  int code_;
};
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496

class Job : public cURLpp::Session
{
public:
  Job(const char* _filename) : filename_(_filename) {}
  Job(const std::string& _filename) : filename_(_filename) {}
  ~Job();

  void setup()
  {
    make();
    upload();
    start();
  }

  void wait();
  void sync_status();
497
  void sync_log();
498
  bool active() const; // requires synchronized status
499
500
501
502
503
504
505
506
  bool stalled() const 
  { 
    // exit quick if we have a solution, or wait 5 min if we don't have one
    return (sol_nmbr_ > 0 && stld_sec_nmbr_ >= 15) || 
      (sol_nmbr_ == 0 && stld_sec_nmbr_ >= 300);
  }

  void abort();
507
  double solution(std::vector<double>& _x) const;
508
509
510
511
512

private:
  const std::string filename_;
  std::string url_;
  JsonTokens stts_;
513
514
515
516
517
  // these variables are initialized in start() 
  int log_seq_idx_; // the log sequence number, used to get DOcloud log entires
  int sol_nmbr_; // number of solutions found so far, according to the log
  int sol_sec_nmbr_; // number of seconds at the last new solution 
  int stld_sec_nmbr_; // number of seconds since the last new solution 
518
  Base::StopWatch stop_wtch_; // time since last successful log synchronization.
519

520
protected:
521
522
  void make();
  void start();
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
  void upload_internal(cURLpp::Upload& _upload);

  virtual void upload()
  {
    cURLpp::UploadFile upl(filename_);
    upload_internal(upl);
  }
};

class JobWithDat : public Job
{
public:
  JobWithDat(const char* _filename, const std::string& _file_dat)
    : Job(_filename), file_dat_(_file_dat) {}

private:
  const std::string& file_dat_; // data to be sent as data attachment.

protected:
  virtual void upload()
  {
    cURLpp::UploadData upl_dat(file_dat_);
    upload_internal(upl_dat);
  }
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
};

Job::~Job()
{
  DEB_enter_func;

  if (url_.empty()) // not setup
    return;

  cURLpp::Delete del;
  if (!del.valid()) 
  {
    DEB_error("Failed to construct a delete request");
    return; // no point in throwing an exception here
  }

  del.set_url(url_.data());
564
  del.add_http_header(api_key__.c_str());
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
  del.perform();

  // no point in checking the return value either, we can't do much if the
  // delete request has failed
}

void Job::make()
{
  DEB_enter_func;

  cURLpp::Post post(std::string(
    "{\"attachments\" : [{\"name\" :\"" + filename_ + "\"}]}"));
  THROW_OUTCOME_if(!post.valid(), TODO); //Failed to initialize the request

  post.set_url(root_url__);
580
  post.add_http_header(api_key__.c_str());
581
582
583
  post.add_http_header(app_type__);
  post.perform();

584
585
  HttpStatus http_stat(post);
  http_stat.check(201);
586
  // TODO: DOcloud header is successful but no location value
587
588
  THROW_OUTCOME_if(!http_stat.header_tokens().find_value("Location:", url_),
    TODO); 
589
590
}

591
void Job::upload_internal(cURLpp::Upload& _upload)
592
{
593
  THROW_OUTCOME_if(!_upload.valid(), TODO); //Failed to initialize the request
594
595

  auto url = url_ + "/attachments/" + filename_ + "/blob";
596
597
598
  _upload.set_url(url.data());
  _upload.add_http_header(api_key__.c_str());
  _upload.perform();
599
600
  HttpStatus http_stat(_upload);
  http_stat.check(204);
601
602
603
604
605
606
607
608
609
}

void Job::start()
{
  cURLpp::Post post("");
  THROW_OUTCOME_if(!post.valid(), TODO); //Failed to initialize the request

  auto url = url_ + "/execute";
  post.set_url(url.data());
610
  post.add_http_header(api_key__.c_str());
611
612
  post.add_http_header(app_type__);
  post.perform();
613
614
  HttpStatus http_stat(post);
  http_stat.check(204);
615
616

  log_seq_idx_ = sol_nmbr_ = sol_sec_nmbr_ = stld_sec_nmbr_ = 0;
617
  stop_wtch_.start();
618
619
620
621
}

void Job::sync_status()
{
622
623
  DEB_enter_func;

624
625
626
  cURLpp::Get get;
  THROW_OUTCOME_if(!get.valid(), TODO); //Failed to initialize the request
  get.set_url(url_.data());
627
  get.add_http_header(api_key__.c_str());
628
  get.perform();
629
630
  HttpStatus http_stat(get);
  http_stat.check(200);
631
632

  stts_.set(get.body());
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
658
659
660
661
662
663
664
665
/*
  // The code below attempted to analyse the status data to find out the 
  // progress of the solver. This is an undocumented use and does not seem to 
  // work so far. Achieved here for potential use in the future.
  
  DEB_line(2, stts_);

  const auto& details = stts_.ptree().get_child_optional("details");
  if (!details)
    return;

  DEB_line(2, details.get());

  const auto& prg_gap = 
    details.get().get_child("PROGRESS_GAP").get_value<std::string>();
  std::string mip_gap;
  const auto mip_gap_it = details.get().find("cplex.mipabsgap");
  if (mip_gap_it != details.get().not_found())
    mip_gap = mip_gap_it->second.get_value<std::string>();

  DEB_line(2, "Status, MIP gap: " << mip_gap << "; Progress gap: " << prg_gap);
*/
}

void Job::sync_log()
{
  DEB_enter_func;

  cURLpp::Get get;
  THROW_OUTCOME_if(!get.valid(), TODO); //Failed to initialize the request
  const std::string url = url_ + "/log/items?start=" + 
    std::to_string(log_seq_idx_) + "&continuous=true";
  get.set_url(url.data());
666
  get.add_http_header(api_key__.c_str());
667
  get.perform();
668
669
  HttpStatus http_stat(get);
  http_stat.check(200);
670
671
672

  JsonTokens log(get.body());

673
  bool got_time_data = false;
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
  // iterate the log items, deb_out messages and analyze for solutions #
  for (const auto& log_item : log.ptree())
  {
    DEB_line_if(log_seq_idx_ == 0, 2, "**** DOcloud log ****");
    const auto& records = log_item.second.get_child("records");
    for (const auto& record : records)
    {// the message ends with \n
      const std::string msg = record.second.get_child("message").
        get_value<std::string>();
      DEB_out(2, record.second.get_child("level").get_value<std::string>() << 
        ": " << msg);

      const int time_str_len = 15;
      const char time_str[time_str_len + 1] = "Elapsed time = ";
      const auto time_str_idx = msg.find(time_str);
      if (time_str_idx == std::string::npos)
        continue;

      const int sec_nmbr = atoi(msg.data() + time_str_idx + time_str_len);
      //DEB_line(1, "# seconds elapsed : " << sec_nmbr);

      const int sol_str_len = 12;
      const char sol_str[sol_str_len + 1] = "solutions = ";
      const auto sol_str_idx = msg.find(sol_str);
      if (sol_str_idx == std::string::npos)
        continue;

701
      got_time_data = true;
702
703
704
705
706
707
708
709
      const int sol_nmbr = atoi(msg.data() + sol_str_idx + sol_str_len);
      //DEB_line(1, "# solutions found so far: " << sol_nmbr);
      if (sol_nmbr > sol_nmbr_) // new solution(s) found
      {// update the number of solutions and the time of the last solution found
        sol_nmbr_ = sol_nmbr;
        sol_sec_nmbr_ = sec_nmbr;
      }
      stld_sec_nmbr_ = sec_nmbr - sol_sec_nmbr_;
710
      stop_wtch_.restart();
711
712
713
    }
    log_seq_idx_ = log_item.second.get_child("seqid").get_value<int>() + 1; 
  }
714
715
716
717
718
719
  if (!got_time_data)
  {
    DEB_warning(2, "DOCloud did not provide time and solutions number-"
                   "using internal time counter.");
    stld_sec_nmbr_ += stop_wtch_.restart() / 1000;
  }
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
}

bool Job::active() const
{
  std::string exct_stts;
  stts_.find_value("executionStatus", exct_stts);
  
  // assume the job is not active if the status is not recognized
  return exct_stts == "CREATED" || exct_stts == "NOT_STARTED" || 
    exct_stts == "RUNNING" || exct_stts == "INTERRUPTING";

  /*
  Backup of old code converting execution status strings to enum value
  enum StatusType { ST_CREATED, ST_NOT_STARTED, ST_RUNNING, ST_INTERRUPTING, 
    ST_INTERRUPTED, ST_FAILED, ST_PROCESSED, ST_UNKNOWN };

  const int n_stts = (int)ST_UNKNOWN;
  const char stts_tbl[n_stts][16] = { "CREATED", "NOT_STARTED", "RUNNING", 
    "INTERRUPTING", "INTERRUPTED", "FAILED", "PROCESSED" };

  for (int i = 0; i < n_stts; ++i)
  {
    if (stts == stts_tbl[i])
      return (StatusType)i;
  }
  return ST_UNKNOWN;
  while (stts == ST_CREATED || stts == ST_NOT_STARTED || stts == ST_RUNNING ||
      stts == ST_INTERRUPTING);
  */
}

751
752
753
754
755
756
757
758
759
760
761
void Job::abort()
{
  std::string exct_stts;
  stts_.find_value("executionStatus", exct_stts);
  if (exct_stts != "RUNNING")
    return; // already aborted or aborting

  cURLpp::Delete del;
  THROW_OUTCOME_if(!del.valid(), TODO); //Failed to initialize the request
  const std::string url = url_ + "/execute";
  del.set_url(url.data());
762
  del.add_http_header(api_key__.c_str());
763
764
  del.perform();

765
766
  HttpStatus http_stat(del);
  http_stat.check(204);
767
768
}

769
770
771
772
773
774
void Job::wait()
{
  do 
  {
    std::this_thread::sleep_for(std::chrono::seconds(1));
    sync_status();
775
776
    sync_log();
    if (stalled())
777
778
      abort(); // The waiting loop must continue until the timer request has been
               // processed by the server.
779
780
781
  } while (active());
}

782
double Job::solution(std::vector<double>& _x) const
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
{
  DEB_enter_func;

  // check the solution status (assume it's synchronized already)

  // What are the possible values for this??
  std::string slv_stts;
  stts_.find_value("solveStatus", slv_stts);
  DEB_line(2, "solveStatus=" << slv_stts);
  
  cURLpp::Get get;
  THROW_OUTCOME_if(!get.valid(), TODO); //Failed to initialize the request

  auto url = url_ + "/attachments/solution.json/blob";
  get.set_url(url.data());
798
  get.add_http_header(api_key__.c_str());
799
800
  get.perform();

801
802
803
804
805
806
807
808
809
  HttpStatus http_stat(get);
  if (http_stat.code() == 404 &&
      get.body().find("CIVOC5102E") != std::string::npos)
  {
    // The mixed integer optimization has not found any solution.
    _x.clear();
    return 0;
  }
  http_stat.check(200);
810
811

  JsonTokens bdy_tkns(get.body());
812
  DEB_line(7, bdy_tkns);
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827

  const auto& vrbls = bdy_tkns.ptree().get_child("CPLEXSolution.variables");
  const auto n_vrbls = vrbls.size();
  THROW_OUTCOME_if(n_vrbls != _x.size(), TODO); // Solution variables number does not match
  
  size_t i = 0;
  for (const auto& v : vrbls)
  {
    // TODO: this way of conversion is rather hacky
    const std::string name = 
      v.second.get_child("name").get_value<std::string>(); // this is x#IDX
    const int idx = atoi(name.data() + 1);
    THROW_OUTCOME_if(idx < 0 || idx > n_vrbls, TODO);  // Invalid index
    _x[idx] = v.second.get_child("value").get_value<double>();

828
    DEB_out(7, "#" << idx << "=" << 
829
830
      v.second.get_child("value").get_value<std::string>() << "; ");
  }
831
832
  const auto obj_val = 
    bdy_tkns.ptree().get_child("CPLEXSolution.header.objectiveValue").get_value<double>();
833

834
  DEB_line(3, "X=" << _x);
835
  return obj_val;
836
837
}

838
namespace {
839

840
std::string lp_file_name()
841
{
842
843
844
845
846
847
848
  // TODO: This is not MT-safe, it's not even process-safe!
  static int n_mps = 0;
  std::string filename("DOcloud_problem_");
  filename += std::to_string(n_mps++);
  return filename + ".lp";
}

849
#define P(X) ((X).data())
850
851
852
853
854
855
856
857
858
859
#define XVAR(IDX) "x" << IDX

class WriteExpression
{
  // lp format allows a max line length = 560.
  // For simplicity we put end line when the number of written characters on the
  // same line exceeds LINE_TRESHOLD_LEN.
  enum { LINE_TRESHOLD_LEN = 100 };

public:
860
  WriteExpression(std::ostringstream& _out_str) : out_str_stream(_out_str)
861
862
863
864
865
866
  {
    start();
  }

  void start()
  {
867
    f_size_ = out_str_stream.tellp();
868
869
870
871
872
873
874
875
    at_start_ = true;
  }
  
  // Writes a monomial.
  void add_monomial(const double _coeff, const size_t _i_var)
  {
    if (_coeff == 0)
      return;
876
877
878
879
880
881
882
883
884
885
886
    add_monomial_internal(_coeff, _i_var);
    wrap_long_line();
  }

  // Writes a binomial.
  void add_binomial(const double _coeff, const size_t _i_var, const size_t _j_var)
  {
    if (_coeff == 0)
      return;
    add_monomial_internal(_coeff, _i_var);
    if (_j_var == _i_var)
887
      out_str_stream << "^2";
888
    else
889
      out_str_stream << " * " << XVAR(_j_var);
890
891
892
893
894
895
896
    wrap_long_line();
  }

private:

  void wrap_long_line()
  {
897
    const auto new_f_size = out_str_stream.tellp();
898
899
    if (new_f_size - f_size_ > LINE_TRESHOLD_LEN)
    {
900
      out_str_stream << std::endl;
901
902
903
904
905
906
      f_size_ = new_f_size;
    }
  }

  void add_monomial_internal(const double _coeff, const size_t _i_var)
  {
907
908
909
    if (_coeff == 1)
    {
      if (!at_start_)
910
        out_str_stream << " + ";
911
912
    }
    else if (_coeff == -1)
913
      out_str_stream << " - ";
914
915
916
917
918
    else
    {
      if (!at_start_)
      {
        if (_coeff > 0)
919
          out_str_stream << " + ";
920
        else
921
          out_str_stream << ' ';
922
      }
923
      out_str_stream << _coeff << ' ';
924
    }
925
    out_str_stream << XVAR(_i_var);
926
927
928
929
    at_start_ = false;
  }

private:
930
  std::ostringstream& out_str_stream;
931
932
933
  std::fstream::pos_type f_size_;
  bool at_start_;
};
934

935
936
937
// Create a lp file for the given constraints and object function.
// Here is the lp format specifications:
// http://www-01.ibm.com/support/knowledgecenter/SSSA5P_12.6.1/ilog.odms.cplex.help/CPLEX/FileFormats/topics/LP.html
938
std::string create_lp_string(
939
940
941
942
943
944
  NProblemInterface* _problem,
  const std::vector<NConstraintInterface*>& _constraints,
  const std::vector<PairIndexVtype>& _discrete_constraints,
  const std::vector<double>& _x
  )
{
945
946
  const int n_cols = _problem->n_unknowns(); // Unknowns #

947
  std::ostringstream lp_str_stream;
948

949
  // Set the ofstream options.
950
  lp_str_stream << std::setprecision(std::numeric_limits<double>::digits10 + 2);
951

952
953
  lp_str_stream << "\\Problem name: " << std::endl << std::endl;
  lp_str_stream << "Minimize" << std::endl;
954

955
  // Writes objective function.
956
  lp_str_stream << "obj: ";
957

958
  WriteExpression wrte_expr(lp_str_stream);
959
  // 1. Linear part.
960
961
962
963
964
  std::vector<double> objective(n_cols);
  _problem->eval_gradient(P(_x), P(objective));
  for (size_t i = 0; i < objective.size(); ++i)
    wrte_expr.add_monomial(objective[i], i);

965
966
967
968
969
  // 2. Quadratic part (if requested).
  if (!_problem->constant_gradient())
  {
    NProblemInterface::SMatrixNP H;
    _problem->eval_hessian(P(_x), H);
970
    lp_str_stream << " + [ ";
971
972
973
974
975
    for (int i = 0; i < H.outerSize(); ++i)
    {
      for (NProblemInterface::SMatrixNP::InnerIterator it(H, i); it; ++it)
        wrte_expr.add_binomial(it.value(), it.row(), it.col());
    }
976
    lp_str_stream << " ] / 2";
977
978
979
  }


980
  // Writes constraints.
981
  lp_str_stream << std::endl << "Subject To" << std::endl;
982
  for (const auto& cstr : _constraints)
983
984
  {
    NConstraintInterface::SVectorNC gc;
985
    cstr->eval_gradient(P(_x), gc);
986

987
    wrte_expr.start();
988
989
    for (NConstraintInterface::SVectorNC::InnerIterator v_it(gc); v_it; ++v_it)
    {
990
991
992
993
994
995
      auto coeff = v_it.value();
      wrte_expr.add_monomial(coeff, v_it.index());
    }
    switch (cstr->constraint_type())
    {
    case NConstraintInterface::NC_EQUAL:
996
      lp_str_stream << " = ";
997
      break;
998
    case NConstraintInterface::NC_GREATER_EQUAL:
999
      lp_str_stream << " >= ";
1000
      break;
1001
    case NConstraintInterface::NC_LESS_EQUAL:
1002
      lp_str_stream << " <= ";
1003
      break;
1004
1005
    default:
      THROW_OUTCOME(TODO); // Can not express current constraint.
1006
    }
1007
    lp_str_stream << -cstr->eval_constraint(P(_x)) << std::endl;
1008
1009
  }

1010
  // Writes the variables.
1011
  lp_str_stream << "Bounds" << std::endl;
1012
  for (size_t i = 0; i < n_cols; ++i)
1013
    lp_str_stream << XVAR(i) << " Free" << std::endl;
1014

1015
1016
1017
  // Integer and binary variables.
  std::vector<unsigned int> int_var, bin_var;
  for (const auto& dc : _discrete_constraints)
1018
  {
1019
1020
1021
1022
1023
    if (dc.second == Integer)
      int_var.push_back(dc.first);
    else if (dc.second == Binary)
      bin_var.push_back(dc.first);
  }
1024
  auto write_var_set = [&lp_str_stream](const std::vector<unsigned int>& _vars,
1025
1026
1027
1028
1029
    const char* _type)
  {
    if (_vars.empty())
      return;
    // Writes integer variables.
1030
    lp_str_stream << _type << std::endl;
1031
    auto var_it = _vars.begin();
1032
    lp_str_stream << XVAR(*var_it);
1033
1034
    size_t n_wrt_var = 1;
    while (++var_it != _vars.end())
1035
    {
1036
      if (n_wrt_var++ % 16) // 16 variables per line. Lines length must be < 560.
1037
        lp_str_stream << ' ';
1038
      else
1039
1040
        lp_str_stream << std::endl;
      lp_str_stream << XVAR(*var_it);
1041
    }
1042
    lp_str_stream << std::endl;
1043
1044
1045
1046
1047
1048
1049
1050

  };
  // Writes integer variables.
  write_var_set(int_var, "Integers");

  // Writes Binary variables.
  write_var_set(bin_var, "Binary");

1051
  lp_str_stream << "End";
1052

1053
  return std::string(lp_str_stream.str());
1054
1055
}

1056
#undef XVAR
1057

1058
} // namespace
1059

1060
} // namespace DOcloud
1061

1062
1063
1064
1065
void DOCloudSolver::set_api_key(const char* _api_key)
{
  DOcloud::api_key__ = std::string("X-IBM-Client-Id: ") + _api_key;
}
1066

1067
void DOCloudSolver::solve(
1068
1069
1070
  NProblemInterface*                        _problem,
  const std::vector<NConstraintInterface*>& _constraints,
  const std::vector<PairIndexVtype>&        _discrete_constraints,
1071
  const double                              _time_limit
1072
1073
1074
1075
1076
1077
1078
1079
1080
)
{
  DEB_enter_func;
  DEB_warning_if(!_problem->constant_hessian(), 1,
    "DOCloudSolver received a problem with non-constant hessian!");
  DEB_warning_if(!_problem->constant_gradient(), 1,
    "DOCloudSolver received a problem with non-constant gradient!");

  std::vector<double> x(_problem->n_unknowns(), 0.0); // solution
1081
1082
  std::string lp_prbl_str =
    DOcloud::create_lp_string(_problem, _constraints,  _discrete_constraints, x);
1083

1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
  double obj_val;
  DOcloud::Cache cache;
  if (cache.restore_result(lp_prbl_str, x, obj_val))
  {
    DEB_line(3, "DOCloudSolver uses cache data.");
  }
  else
  {
    DEB_line(1, "DOCloudSolver does NOT use cached data - computing optimization.");
    DOcloud::JobWithDat job("DoClouProblem.lp", cache.get_lp_content());
    job.setup();
    job.wait();
    obj_val = job.solution(x);
    cache.store_result(x, obj_val);
  }
1099
  THROW_OUTCOME_if(x.empty(), MIPS_NO_SOLUTION);
1100
1101
1102
1103
1104

  DEB_only(
  // The lp problem ignores the constant term in the objective function.
  const std::vector<double> x_zero(_problem->n_unknowns(), 0.0);
  const auto zero_val = _problem->eval_f(P(x_zero));
1105
1106
  const auto test_obj_val = _problem->eval_f(P(x));
  DEB_error_if(fabs(obj_val + zero_val - test_obj_val) > (1e-8 + zero_val * 0.01),
1107
1108
               "DOCloudSolver solved a wrong problem.");
  )
1109
1110
  
  _problem->store_result(P(x));
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
}

#undef P

//=============================================================================
} // namespace COMISO
//=============================================================================

#endif // COMISO_DOCLOUD_AVAILABLE
//=============================================================================