Fix some bugs when testing opensds ansible
[stor4nfv.git] / src / ceph / src / rgw / librgw.cc
1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
3 /*
4  * Ceph - scalable distributed file system
5  *
6  * Copyright (C) 2011 New Dream Network
7  *
8  * This is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License version 2.1, as published by the Free Software
11  * Foundation.  See file COPYING.
12  *
13  */
14 #include "include/compat.h"
15 #include <sys/types.h>
16 #include <string.h>
17 #include <chrono>
18
19 #include "include/types.h"
20 #include "include/rados/librgw.h"
21 #include "rgw/rgw_acl_s3.h"
22 #include "rgw_acl.h"
23
24 #include "include/str_list.h"
25 #include "include/stringify.h"
26 #include "global/global_init.h"
27 #include "common/config.h"
28 #include "common/errno.h"
29 #include "common/Timer.h"
30 #include "common/Throttle.h"
31 #include "common/WorkQueue.h"
32 #include "common/ceph_argparse.h"
33 #include "common/ceph_context.h"
34 #include "common/common_init.h"
35 #include "common/dout.h"
36
37 #include "rgw_rados.h"
38 #include "rgw_resolve.h"
39 #include "rgw_op.h"
40 #include "rgw_rest.h"
41 #include "rgw_frontend.h"
42 #include "rgw_request.h"
43 #include "rgw_process.h"
44 #include "rgw_rest_user.h"
45 #include "rgw_rest_s3.h"
46 #include "rgw_os_lib.h"
47 #include "rgw_auth.h"
48 #include "rgw_auth_s3.h"
49 #include "rgw_lib.h"
50 #include "rgw_lib_frontend.h"
51
52 #include <errno.h>
53 #include <chrono>
54 #include <thread>
55 #include <string>
56 #include <string.h>
57 #include <mutex>
58
59
60 #define dout_subsys ceph_subsys_rgw
61
62 bool global_stop = false;
63
64 namespace rgw {
65
66   using std::string;
67
68   static std::mutex librgw_mtx;
69
70   RGWLib rgwlib;
71
72   class C_InitTimeout : public Context {
73   public:
74     C_InitTimeout() {}
75     void finish(int r) override {
76       derr << "Initialization timeout, failed to initialize" << dendl;
77       exit(1);
78     }
79   };
80
81   void RGWLibProcess::checkpoint()
82   {
83     m_tp.drain(&req_wq);
84   }
85
86 #define MIN_EXPIRE_S 120
87
88   void RGWLibProcess::run()
89   {
90     /* write completion interval */
91     RGWLibFS::write_completion_interval_s =
92       cct->_conf->rgw_nfs_write_completion_interval_s;
93
94     /* start write timer */
95     RGWLibFS::write_timer.resume();
96
97     /* gc loop */
98     while (! shutdown) {
99       lsubdout(cct, rgw, 5) << "RGWLibProcess GC" << dendl;
100
101       /* dirent invalidate timeout--basically, the upper-bound on
102        * inconsistency with the S3 namespace */
103       auto expire_s = cct->_conf->rgw_nfs_namespace_expire_secs;
104
105       /* delay between gc cycles */
106       auto delay_s = std::max(int64_t(1), std::min(int64_t(MIN_EXPIRE_S), expire_s/2));
107
108       unique_lock uniq(mtx);
109     restart:
110       int cur_gen = gen;
111       for (auto iter = mounted_fs.begin(); iter != mounted_fs.end();
112            ++iter) {
113         RGWLibFS* fs = iter->first->ref();
114         uniq.unlock();
115         fs->gc();
116         fs->rele();
117         uniq.lock();
118         if (cur_gen != gen)
119           goto restart; /* invalidated */
120       }
121       uniq.unlock();
122       std::this_thread::sleep_for(std::chrono::seconds(delay_s));
123     }
124   }
125
126   void RGWLibProcess::handle_request(RGWRequest* r)
127   {
128     /*
129      * invariant: valid requests are derived from RGWLibRequst
130      */
131     RGWLibRequest* req = static_cast<RGWLibRequest*>(r);
132
133     // XXX move RGWLibIO and timing setup into process_request
134
135 #if 0 /* XXX */
136     utime_t tm = ceph_clock_now();
137 #endif
138
139     RGWLibIO io_ctx;
140
141     int ret = process_request(req, &io_ctx);
142     if (ret < 0) {
143       /* we don't really care about return code */
144       dout(20) << "process_request() returned " << ret << dendl;
145
146     }
147     delete req;
148   } /* handle_request */
149
150   int RGWLibProcess::process_request(RGWLibRequest* req)
151   {
152     // XXX move RGWLibIO and timing setup into process_request
153
154 #if 0 /* XXX */
155     utime_t tm = ceph_clock_now();
156 #endif
157
158     RGWLibIO io_ctx;
159
160     int ret = process_request(req, &io_ctx);
161     if (ret < 0) {
162       /* we don't really care about return code */
163       dout(20) << "process_request() returned " << ret << dendl;
164     }
165     return ret;
166   } /* process_request */
167
168   static inline void abort_req(struct req_state *s, RGWOp *op, int err_no)
169   {
170     if (!s)
171       return;
172
173     /* XXX the dump_errno and dump_bucket_from_state behaviors in
174      * the abort_early (rgw_rest.cc) might be valuable, but aren't
175      * safe to call presently as they return HTTP data */
176
177     perfcounter->inc(l_rgw_failed_req);
178   } /* abort_req */
179
180   int RGWLibProcess::process_request(RGWLibRequest* req, RGWLibIO* io)
181   {
182     int ret = 0;
183     bool should_log = true; // XXX
184
185     dout(1) << "====== " << __func__
186             << " starting new request req=" << hex << req << dec
187             << " ======" << dendl;
188
189     /*
190      * invariant: valid requests are derived from RGWOp--well-formed
191      * requests should have assigned RGWRequest::op in their descendant
192      * constructor--if not, the compiler can find it, at the cost of
193      * a runtime check
194      */
195     RGWOp *op = (req->op) ? req->op : dynamic_cast<RGWOp*>(req);
196     if (! op) {
197       dout(1) << "failed to derive cognate RGWOp (invalid op?)" << dendl;
198       return -EINVAL;
199     }
200
201     io->init(req->cct);
202
203     perfcounter->inc(l_rgw_req);
204
205     RGWEnv& rgw_env = io->get_env();
206
207     /* XXX
208      * until major refactoring of req_state and req_info, we need
209      * to build their RGWEnv boilerplate from the RGWLibRequest,
210      * pre-staging any strings (HTTP_HOST) that provoke a crash when
211      * not found
212      */
213
214     /* XXX for now, use "";  could be a legit hostname, or, in future,
215      * perhaps a tenant (Yehuda) */
216     rgw_env.set("HTTP_HOST", "");
217
218     /* XXX and -then- bloat up req_state with string copies from it */
219     struct req_state rstate(req->cct, &rgw_env, req->get_user());
220     struct req_state *s = &rstate;
221
222     // XXX fix this
223     s->cio = io;
224
225     RGWObjectCtx rados_ctx(store, s); // XXX holds std::map
226
227     /* XXX and -then- stash req_state pointers everywhere they are needed */
228     ret = req->init(rgw_env, &rados_ctx, io, s);
229     if (ret < 0) {
230       dout(10) << "failed to initialize request" << dendl;
231       abort_req(s, op, ret);
232       goto done;
233     }
234
235     /* req is-a RGWOp, currently initialized separately */
236     ret = req->op_init();
237     if (ret < 0) {
238       dout(10) << "failed to initialize RGWOp" << dendl;
239       abort_req(s, op, ret);
240       goto done;
241     }
242
243     /* XXX authorize does less here then in the REST path, e.g.,
244      * the user's info is cached, but still incomplete */
245     req->log(s, "authorizing");
246     ret = req->authorize();
247     if (ret < 0) {
248       dout(10) << "failed to authorize request" << dendl;
249       abort_req(s, op, ret);
250       goto done;
251     }
252
253     /* FIXME: remove this after switching all handlers to the new authentication
254      * infrastructure. */
255     if (! s->auth.identity) {
256       s->auth.identity = rgw::auth::transform_old_authinfo(s);
257     }
258
259     req->log(s, "reading op permissions");
260     ret = req->read_permissions(op);
261     if (ret < 0) {
262       abort_req(s, op, ret);
263       goto done;
264     }
265
266     req->log(s, "init op");
267     ret = op->init_processing();
268     if (ret < 0) {
269       abort_req(s, op, ret);
270       goto done;
271     }
272
273     req->log(s, "verifying op mask");
274     ret = op->verify_op_mask();
275     if (ret < 0) {
276       abort_req(s, op, ret);
277       goto done;
278     }
279
280     req->log(s, "verifying op permissions");
281     ret = op->verify_permission();
282     if (ret < 0) {
283       if (s->system_request) {
284         dout(2) << "overriding permissions due to system operation" << dendl;
285       } else if (s->auth.identity->is_admin_of(s->user->user_id)) {
286         dout(2) << "overriding permissions due to admin operation" << dendl;
287       } else {
288         abort_req(s, op, ret);
289         goto done;
290       }
291     }
292
293     req->log(s, "verifying op params");
294     ret = op->verify_params();
295     if (ret < 0) {
296       abort_req(s, op, ret);
297       goto done;
298     }
299
300     req->log(s, "executing");
301     op->pre_exec();
302     op->execute();
303     op->complete();
304
305   done:
306     try {
307       io->complete_request();
308     } catch (rgw::io::Exception& e) {
309       dout(0) << "ERROR: io->complete_request() returned "
310               << e.what() << dendl;
311     }
312     if (should_log) {
313       rgw_log_op(store, nullptr /* !rest */, s,
314                  (op ? op->name() : "unknown"), olog);
315     }
316
317     int http_ret = s->err.http_ret;
318
319     req->log_format(s, "http status=%d", http_ret);
320
321     dout(1) << "====== " << __func__
322             << " req done req=" << hex << req << dec << " http_status="
323             << http_ret
324             << " ======" << dendl;
325
326     return (ret < 0 ? ret : s->err.ret);
327   } /* process_request */
328
329   int RGWLibProcess::start_request(RGWLibContinuedReq* req)
330   {
331
332     dout(1) << "====== " << __func__
333             << " starting new continued request req=" << hex << req << dec
334             << " ======" << dendl;
335
336     /*
337      * invariant: valid requests are derived from RGWOp--well-formed
338      * requests should have assigned RGWRequest::op in their descendant
339      * constructor--if not, the compiler can find it, at the cost of
340      * a runtime check
341      */
342     RGWOp *op = (req->op) ? req->op : dynamic_cast<RGWOp*>(req);
343     if (! op) {
344       dout(1) << "failed to derive cognate RGWOp (invalid op?)" << dendl;
345       return -EINVAL;
346     }
347
348     struct req_state* s = req->get_state();
349
350     /* req is-a RGWOp, currently initialized separately */
351     int ret = req->op_init();
352     if (ret < 0) {
353       dout(10) << "failed to initialize RGWOp" << dendl;
354       abort_req(s, op, ret);
355       goto done;
356     }
357
358     /* XXX authorize does less here then in the REST path, e.g.,
359      * the user's info is cached, but still incomplete */
360     req->log(s, "authorizing");
361     ret = req->authorize();
362     if (ret < 0) {
363       dout(10) << "failed to authorize request" << dendl;
364       abort_req(s, op, ret);
365       goto done;
366     }
367
368     /* FIXME: remove this after switching all handlers to the new authentication
369      * infrastructure. */
370     if (! s->auth.identity) {
371       s->auth.identity = rgw::auth::transform_old_authinfo(s);
372     }
373
374     req->log(s, "reading op permissions");
375     ret = req->read_permissions(op);
376     if (ret < 0) {
377       abort_req(s, op, ret);
378       goto done;
379     }
380
381     req->log(s, "init op");
382     ret = op->init_processing();
383     if (ret < 0) {
384       abort_req(s, op, ret);
385       goto done;
386     }
387
388     req->log(s, "verifying op mask");
389     ret = op->verify_op_mask();
390     if (ret < 0) {
391       abort_req(s, op, ret);
392       goto done;
393     }
394
395     req->log(s, "verifying op permissions");
396     ret = op->verify_permission();
397     if (ret < 0) {
398       if (s->system_request) {
399         dout(2) << "overriding permissions due to system operation" << dendl;
400       } else if (s->auth.identity->is_admin_of(s->user->user_id)) {
401         dout(2) << "overriding permissions due to admin operation" << dendl;
402       } else {
403         abort_req(s, op, ret);
404         goto done;
405       }
406     }
407
408     req->log(s, "verifying op params");
409     ret = op->verify_params();
410     if (ret < 0) {
411       abort_req(s, op, ret);
412       goto done;
413     }
414
415     op->pre_exec();
416     req->exec_start();
417
418   done:
419     return (ret < 0 ? ret : s->err.ret);
420   }
421
422   int RGWLibProcess::finish_request(RGWLibContinuedReq* req)
423   {
424     RGWOp *op = (req->op) ? req->op : dynamic_cast<RGWOp*>(req);
425     if (! op) {
426       dout(1) << "failed to derive cognate RGWOp (invalid op?)" << dendl;
427       return -EINVAL;
428     }
429
430     int ret = req->exec_finish();
431     int op_ret = op->get_ret();
432
433     dout(1) << "====== " << __func__
434             << " finishing continued request req=" << hex << req << dec
435             << " op status=" << op_ret
436             << " ======" << dendl;
437
438     return ret;
439   }
440
441   int RGWLibFrontend::init()
442   {
443     pprocess = new RGWLibProcess(g_ceph_context, &env,
444                                  g_conf->rgw_thread_pool_size, conf);
445     return 0;
446   }
447
448   int RGWLib::init()
449   {
450     vector<const char*> args;
451     return init(args);
452   }
453
454   int RGWLib::init(vector<const char*>& args)
455   {
456     int r = 0;
457
458     /* alternative default for module */
459     vector<const char *> def_args;
460     def_args.push_back("--debug-rgw=1/5");
461     def_args.push_back("--keyring=$rgw_data/keyring");
462     def_args.push_back("--log-file=/var/log/radosgw/$cluster-$name.log");
463
464     cct = global_init(&def_args, args,
465                       CEPH_ENTITY_TYPE_CLIENT,
466                       CODE_ENVIRONMENT_DAEMON,
467                       CINIT_FLAG_UNPRIVILEGED_DAEMON_DEFAULTS);
468
469     Mutex mutex("main");
470     SafeTimer init_timer(g_ceph_context, mutex);
471     init_timer.init();
472     mutex.Lock();
473     init_timer.add_event_after(g_conf->rgw_init_timeout, new C_InitTimeout);
474     mutex.Unlock();
475
476     common_init_finish(g_ceph_context);
477
478     rgw_tools_init(g_ceph_context);
479
480     rgw_init_resolver();
481
482     store = RGWStoreManager::get_storage(g_ceph_context,
483                                          g_conf->rgw_enable_gc_threads,
484                                          g_conf->rgw_enable_lc_threads,
485                                          g_conf->rgw_enable_quota_threads,
486                                          g_conf->rgw_run_sync_thread,
487                                          g_conf->rgw_dynamic_resharding);
488
489     if (!store) {
490       mutex.Lock();
491       init_timer.cancel_all_events();
492       init_timer.shutdown();
493       mutex.Unlock();
494
495       derr << "Couldn't init storage provider (RADOS)" << dendl;
496       return -EIO;
497     }
498
499     r = rgw_perf_start(g_ceph_context);
500
501     rgw_rest_init(g_ceph_context, store, store->get_zonegroup());
502
503     mutex.Lock();
504     init_timer.cancel_all_events();
505     init_timer.shutdown();
506     mutex.Unlock();
507
508     if (r)
509       return -EIO;
510
511     const string& ldap_uri = store->ctx()->_conf->rgw_ldap_uri;
512     const string& ldap_binddn = store->ctx()->_conf->rgw_ldap_binddn;
513     const string& ldap_searchdn = store->ctx()->_conf->rgw_ldap_searchdn;
514     const string& ldap_searchfilter = store->ctx()->_conf->rgw_ldap_searchfilter;
515     const string& ldap_dnattr =
516       store->ctx()->_conf->rgw_ldap_dnattr;
517     std::string ldap_bindpw = parse_rgw_ldap_bindpw(store->ctx());
518
519     ldh = new rgw::LDAPHelper(ldap_uri, ldap_binddn, ldap_bindpw.c_str(),
520                               ldap_searchdn, ldap_searchfilter, ldap_dnattr);
521     ldh->init();
522     ldh->bind();
523
524     rgw_user_init(store);
525     rgw_bucket_init(store->meta_mgr);
526     rgw_log_usage_init(g_ceph_context, store);
527
528     // XXX ex-RGWRESTMgr_lib, mgr->set_logging(true)
529
530     if (!g_conf->rgw_ops_log_socket_path.empty()) {
531       olog = new OpsLogSocket(g_ceph_context, g_conf->rgw_ops_log_data_backlog);
532       olog->init(g_conf->rgw_ops_log_socket_path);
533     }
534
535     int port = 80;
536     RGWProcessEnv env = { store, &rest, olog, port };
537
538     string fe_count{"0"};
539     fec = new RGWFrontendConfig("rgwlib");
540     fe = new RGWLibFrontend(env, fec);
541
542     map<string, string> service_map_meta;
543     service_map_meta["pid"] = stringify(getpid());
544     service_map_meta["frontend_type#" + fe_count] = "rgw-nfs";
545     service_map_meta["frontend_config#" + fe_count] = fec->get_config();
546
547     fe->init();
548     if (r < 0) {
549       derr << "ERROR: failed initializing frontend" << dendl;
550       return r;
551     }
552
553     fe->run();
554
555     r = store->register_to_service_map("rgw-nfs", service_map_meta);
556     if (r < 0) {
557       derr << "ERROR: failed to register to service map: " << cpp_strerror(-r) << dendl;
558       /* ignore error */
559     }
560
561     return 0;
562   } /* RGWLib::init() */
563
564   int RGWLib::stop()
565   {
566     derr << "shutting down" << dendl;
567
568     fe->stop();
569
570     fe->join();
571
572     delete fe;
573     delete fec;
574     delete ldh;
575
576     rgw_log_usage_finalize();
577
578     delete olog;
579
580     RGWStoreManager::close_storage(store);
581
582     rgw_tools_cleanup();
583     rgw_shutdown_resolver();
584
585     rgw_perf_stop(g_ceph_context);
586
587     dout(1) << "final shutdown" << dendl;
588     cct.reset();
589
590     return 0;
591   } /* RGWLib::stop() */
592
593   int RGWLibIO::set_uid(RGWRados *store, const rgw_user& uid)
594   {
595     int ret = rgw_get_user_info_by_uid(store, uid, user_info, NULL);
596     if (ret < 0) {
597       derr << "ERROR: failed reading user info: uid=" << uid << " ret="
598            << ret << dendl;
599     }
600     return ret;
601   }
602
603   int RGWLibRequest::read_permissions(RGWOp* op) {
604     /* bucket and object ops */
605     int ret =
606       rgw_build_bucket_policies(rgwlib.get_store(), get_state());
607     if (ret < 0) {
608       ldout(get_state()->cct, 10) << "read_permissions (bucket policy) on "
609                                   << get_state()->bucket << ":"
610                                   << get_state()->object
611                                   << " only_bucket=" << only_bucket()
612                                   << " ret=" << ret << dendl;
613       if (ret == -ENODATA)
614         ret = -EACCES;
615     } else if (! only_bucket()) {
616       /* object ops */
617       ret = rgw_build_object_policies(rgwlib.get_store(), get_state(),
618                                       op->prefetch_data());
619       if (ret < 0) {
620         ldout(get_state()->cct, 10) << "read_permissions (object policy) on"
621                                     << get_state()->bucket << ":"
622                                     << get_state()->object
623                                     << " ret=" << ret << dendl;
624         if (ret == -ENODATA)
625           ret = -EACCES;
626       }
627     }
628     return ret;
629   } /* RGWLibRequest::read_permissions */
630
631   int RGWHandler_Lib::authorize()
632   {
633     /* TODO: handle
634      *  1. subusers
635      *  2. anonymous access
636      *  3. system access
637      *  4. ?
638      *
639      *  Much or all of this depends on handling the cached authorization
640      *  correctly (e.g., dealing with keystone) at mount time.
641      */
642     s->perm_mask = RGW_PERM_FULL_CONTROL;
643
644     // populate the owner info
645     s->owner.set_id(s->user->user_id);
646     s->owner.set_name(s->user->display_name);
647
648     return 0;
649   } /* RGWHandler_Lib::authorize */
650
651 } /* namespace rgw */
652
653 extern "C" {
654
655 int librgw_create(librgw_t* rgw, int argc, char **argv)
656 {
657   using namespace rgw;
658
659   int rc = -EINVAL;
660
661   if (! g_ceph_context) {
662     std::lock_guard<std::mutex> lg(librgw_mtx);
663     if (! g_ceph_context) {
664       vector<const char*> args;
665       std::vector<std::string> spl_args;
666       // last non-0 argument will be split and consumed
667       if (argc > 1) {
668         const std::string spl_arg{argv[(--argc)]};
669         get_str_vec(spl_arg, " \t", spl_args);
670       }
671       argv_to_vec(argc, const_cast<const char**>(argv), args);
672       // append split args, if any
673       for (const auto& elt : spl_args) {
674         args.push_back(elt.c_str());
675       }
676       env_to_vec(args);
677       rc = rgwlib.init(args);
678     }
679   }
680
681   *rgw = g_ceph_context->get();
682
683   return rc;
684 }
685
686 void librgw_shutdown(librgw_t rgw)
687 {
688   using namespace rgw;
689
690   CephContext* cct = static_cast<CephContext*>(rgw);
691   rgwlib.stop();
692   cct->put();
693 }
694
695 } /* extern "C" */