Fix some bugs when testing opensds ansible
[stor4nfv.git] / src / ceph / src / rgw / rgw_admin.cc
1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
3
4 #include <errno.h>
5 #include <iostream>
6 #include <sstream>
7 #include <string>
8
9 #include <boost/optional.hpp>
10
11 #include "auth/Crypto.h"
12 #include "compressor/Compressor.h"
13
14 #include "common/armor.h"
15 #include "common/ceph_json.h"
16 #include "common/config.h"
17 #include "common/ceph_argparse.h"
18 #include "common/Formatter.h"
19 #include "common/errno.h"
20 #include "common/safe_io.h"
21
22 #include "cls/rgw/cls_rgw_client.h"
23
24 #include "global/global_init.h"
25
26 #include "include/utime.h"
27 #include "include/str_list.h"
28
29 #include "rgw_user.h"
30 #include "rgw_bucket.h"
31 #include "rgw_rados.h"
32 #include "rgw_acl.h"
33 #include "rgw_acl_s3.h"
34 #include "rgw_lc.h"
35 #include "rgw_log.h"
36 #include "rgw_formats.h"
37 #include "rgw_usage.h"
38 #include "rgw_replica_log.h"
39 #include "rgw_orphan.h"
40 #include "rgw_sync.h"
41 #include "rgw_data_sync.h"
42 #include "rgw_rest_conn.h"
43 #include "rgw_realm_watcher.h"
44 #include "rgw_role.h"
45 #include "rgw_reshard.h"
46
47 using namespace std;
48
49 #define dout_context g_ceph_context
50 #define dout_subsys ceph_subsys_rgw
51
52 #define SECRET_KEY_LEN 40
53 #define PUBLIC_ID_LEN 20
54
55 static RGWRados *store = NULL;
56
57 void usage()
58 {
59   cout << "usage: radosgw-admin <cmd> [options...]" << std::endl;
60   cout << "commands:\n";
61   cout << "  user create                create a new user\n" ;
62   cout << "  user modify                modify user\n";
63   cout << "  user info                  get user info\n";
64   cout << "  user rm                    remove user\n";
65   cout << "  user suspend               suspend a user\n";
66   cout << "  user enable                re-enable user after suspension\n";
67   cout << "  user check                 check user info\n";
68   cout << "  user stats                 show user stats as accounted by quota subsystem\n";
69   cout << "  user list                  list users\n";
70   cout << "  caps add                   add user capabilities\n";
71   cout << "  caps rm                    remove user capabilities\n";
72   cout << "  subuser create             create a new subuser\n" ;
73   cout << "  subuser modify             modify subuser\n";
74   cout << "  subuser rm                 remove subuser\n";
75   cout << "  key create                 create access key\n";
76   cout << "  key rm                     remove access key\n";
77   cout << "  bucket list                list buckets\n";
78   cout << "  bucket limit check         show bucket sharding stats\n";
79   cout << "  bucket link                link bucket to specified user\n";
80   cout << "  bucket unlink              unlink bucket from specified user\n";
81   cout << "  bucket stats               returns bucket statistics\n";
82   cout << "  bucket rm                  remove bucket\n";
83   cout << "  bucket check               check bucket index\n";
84   cout << "  bucket reshard             reshard bucket\n";
85   cout << "  bucket sync disable        disable bucket sync\n";
86   cout << "  bucket sync enable         enable bucket sync\n";
87   cout << "  bi get                     retrieve bucket index object entries\n";
88   cout << "  bi put                     store bucket index object entries\n";
89   cout << "  bi list                    list raw bucket index entries\n";
90   cout << "  object rm                  remove object\n";
91   cout << "  object stat                stat an object for its metadata\n";
92   cout << "  object unlink              unlink object from bucket index\n";
93   cout << "  objects expire             run expired objects cleanup\n";
94   cout << "  period delete              delete a period\n";
95   cout << "  period get                 get period info\n";
96   cout << "  period get-current         get current period info\n";
97   cout << "  period pull                pull a period\n";
98   cout << "  period push                push a period\n";
99   cout << "  period list                list all periods\n";
100   cout << "  period update              update the staging period\n";
101   cout << "  period commit              commit the staging period\n";
102   cout << "  quota set                  set quota params\n";
103   cout << "  quota enable               enable quota\n";
104   cout << "  quota disable              disable quota\n";
105   cout << "  global quota get           view global quota params\n";
106   cout << "  global quota set           set global quota params\n";
107   cout << "  global quota enable        enable a global quota\n";
108   cout << "  global quota disable       disable a global quota\n";
109   cout << "  realm create               create a new realm\n";
110   cout << "  realm delete               delete a realm\n";
111   cout << "  realm get                  show realm info\n";
112   cout << "  realm get-default          get default realm name\n";
113   cout << "  realm list                 list realms\n";
114   cout << "  realm list-periods         list all realm periods\n";
115   cout << "  realm remove               remove a zonegroup from the realm\n";
116   cout << "  realm rename               rename a realm\n";
117   cout << "  realm set                  set realm info (requires infile)\n";
118   cout << "  realm default              set realm as default\n";
119   cout << "  realm pull                 pull a realm and its current period\n";
120   cout << "  zonegroup add              add a zone to a zonegroup\n";
121   cout << "  zonegroup create           create a new zone group info\n";
122   cout << "  zonegroup default          set default zone group\n";
123   cout << "  zonegroup delete           delete a zone group info\n";
124   cout << "  zonegroup get              show zone group info\n";
125   cout << "  zonegroup modify           modify an existing zonegroup\n";
126   cout << "  zonegroup set              set zone group info (requires infile)\n";
127   cout << "  zonegroup remove           remove a zone from a zonegroup\n";
128   cout << "  zonegroup rename           rename a zone group\n";
129   cout << "  zonegroup list             list all zone groups set on this cluster\n";
130   cout << "  zonegroup placement list   list zonegroup's placement targets\n";
131   cout << "  zonegroup placement add    add a placement target id to a zonegroup\n";
132   cout << "  zonegroup placement modify modify a placement target of a specific zonegroup\n";
133   cout << "  zonegroup placement rm     remove a placement target from a zonegroup\n";
134   cout << "  zonegroup placement default  set a zonegroup's default placement target\n";
135   cout << "  zone create                create a new zone\n";
136   cout << "  zone delete                delete a zone\n";
137   cout << "  zone get                   show zone cluster params\n";
138   cout << "  zone modify                modify an existing zone\n";
139   cout << "  zone set                   set zone cluster params (requires infile)\n";
140   cout << "  zone list                  list all zones set on this cluster\n";
141   cout << "  zone rename                rename a zone\n";
142   cout << "  zone placement list        list zone's placement targets\n";
143   cout << "  zone placement add         add a zone placement target\n";
144   cout << "  zone placement modify      modify a zone placement target\n";
145   cout << "  zone placement rm          remove a zone placement target\n";
146   cout << "  pool add                   add an existing pool for data placement\n";
147   cout << "  pool rm                    remove an existing pool from data placement set\n";
148   cout << "  pools list                 list placement active set\n";
149   cout << "  policy                     read bucket/object policy\n";
150   cout << "  log list                   list log objects\n";
151   cout << "  log show                   dump a log from specific object or (bucket + date\n";
152   cout << "                             + bucket-id)\n";
153   cout << "                             (NOTE: required to specify formatting of date\n";
154   cout << "                             to \"YYYY-MM-DD-hh\")\n";
155   cout << "  log rm                     remove log object\n";
156   cout << "  usage show                 show usage (by user, date range)\n";
157   cout << "  usage trim                 trim usage (by user, date range)\n";
158   cout << "  gc list                    dump expired garbage collection objects (specify\n";
159   cout << "                             --include-all to list all entries, including unexpired)\n";
160   cout << "  gc process                 manually process garbage\n";
161   cout << "  lc list                    list all bucket lifecycle progress\n";
162   cout << "  lc process                 manually process lifecycle\n";
163   cout << "  metadata get               get metadata info\n";
164   cout << "  metadata put               put metadata info\n";
165   cout << "  metadata rm                remove metadata info\n";
166   cout << "  metadata list              list metadata info\n";
167   cout << "  mdlog list                 list metadata log\n";
168   cout << "  mdlog trim                 trim metadata log (use start-date, end-date or\n";
169   cout << "                             start-marker, end-marker)\n";
170   cout << "  mdlog status               read metadata log status\n";
171   cout << "  bilog list                 list bucket index log\n";
172   cout << "  bilog trim                 trim bucket index log (use start-marker, end-marker)\n";
173   cout << "  datalog list               list data log\n";
174   cout << "  datalog trim               trim data log\n";
175   cout << "  datalog status             read data log status\n";
176   cout << "  opstate list               list stateful operations entries (use client_id,\n";
177   cout << "                             op_id, object)\n";
178   cout << "  opstate set                set state on an entry (use client_id, op_id, object, state)\n";
179   cout << "  opstate renew              renew state on an entry (use client_id, op_id, object)\n";
180   cout << "  opstate rm                 remove entry (use client_id, op_id, object)\n";
181   cout << "  replicalog get             get replica metadata log entry\n";
182   cout << "  replicalog update          update replica metadata log entry\n";
183   cout << "  replicalog delete          delete replica metadata log entry\n";
184   cout << "  orphans find               init and run search for leaked rados objects (use job-id, pool)\n";
185   cout << "  orphans finish             clean up search for leaked rados objects\n";
186   cout << "  orphans list-jobs          list the current job-ids for orphans search\n";
187   cout << "  role create                create a AWS role for use with STS\n";
188   cout << "  role delete                delete a role\n";
189   cout << "  role get                   get a role\n";
190   cout << "  role list                  list roles with specified path prefix\n";
191   cout << "  role modify                modify the assume role policy of an existing role\n";
192   cout << "  role-policy put            add/update permission policy to role\n";
193   cout << "  role-policy list           list policies attached to a role\n";
194   cout << "  role-policy get            get the specified inline policy document embedded with the given role\n";
195   cout << "  role-policy delete         delete policy attached to a role\n";
196   cout << "  reshard add                schedule a resharding of a bucket\n";
197   cout << "  reshard list               list all bucket resharding or scheduled to be reshared\n";
198   cout << "  reshard process            process of scheduled reshard jobs\n";
199   cout << "  reshard cancel             cancel resharding a bucket\n";
200   cout << "options:\n";
201   cout << "   --tenant=<tenant>         tenant name\n";
202   cout << "   --uid=<id>                user id\n";
203   cout << "   --subuser=<name>          subuser name\n";
204   cout << "   --access-key=<key>        S3 access key\n";
205   cout << "   --email=<email>\n";
206   cout << "   --secret/--secret-key=<key>\n";
207   cout << "                             specify secret key\n";
208   cout << "   --gen-access-key          generate random access key (for S3)\n";
209   cout << "   --gen-secret              generate random secret key\n";
210   cout << "   --key-type=<type>         key type, options are: swift, s3\n";
211   cout << "   --temp-url-key[-2]=<key>  temp url key\n";
212   cout << "   --access=<access>         Set access permissions for sub-user, should be one\n";
213   cout << "                             of read, write, readwrite, full\n";
214   cout << "   --display-name=<name>\n";
215   cout << "   --max-buckets             max number of buckets for a user\n";
216   cout << "   --admin                   set the admin flag on the user\n";
217   cout << "   --system                  set the system flag on the user\n";
218   cout << "   --bucket=<bucket>\n";
219   cout << "   --pool=<pool>\n";
220   cout << "   --object=<object>\n";
221   cout << "   --date=<date>\n";
222   cout << "   --start-date=<date>\n";
223   cout << "   --end-date=<date>\n";
224   cout << "   --bucket-id=<bucket-id>\n";
225   cout << "   --shard-id=<shard-id>     optional for mdlog list\n";
226   cout << "                             required for: \n";
227   cout << "                               mdlog trim\n";
228   cout << "                               replica mdlog get/delete\n";
229   cout << "                               replica datalog get/delete\n";
230   cout << "   --metadata-key=<key>      key to retrieve metadata from with metadata get\n";
231   cout << "   --remote=<remote>         zone or zonegroup id of remote gateway\n";
232   cout << "   --period=<id>             period id\n";
233   cout << "   --epoch=<number>          period epoch\n";
234   cout << "   --commit                  commit the period during 'period update'\n";
235   cout << "   --staging                 get staging period info\n";
236   cout << "   --master                  set as master\n";
237   cout << "   --master-url              master url\n";
238   cout << "   --master-zonegroup=<id>   master zonegroup id\n";
239   cout << "   --master-zone=<id>        master zone id\n";
240   cout << "   --rgw-realm=<name>        realm name\n";
241   cout << "   --realm-id=<id>           realm id\n";
242   cout << "   --realm-new-name=<name>   realm new name\n";
243   cout << "   --rgw-zonegroup=<name>    zonegroup name\n";
244   cout << "   --zonegroup-id=<id>       zonegroup id\n";
245   cout << "   --zonegroup-new-name=<name>\n";
246   cout << "                             zonegroup new name\n";
247   cout << "   --rgw-zone=<name>         name of zone in which radosgw is running\n";
248   cout << "   --zone-id=<id>            zone id\n";
249   cout << "   --zone-new-name=<name>    zone new name\n";
250   cout << "   --source-zone             specify the source zone (for data sync)\n";
251   cout << "   --default                 set entity (realm, zonegroup, zone) as default\n";
252   cout << "   --read-only               set zone as read-only (when adding to zonegroup)\n";
253   cout << "   --placement-id            placement id for zonegroup placement commands\n";
254   cout << "   --tags=<list>             list of tags for zonegroup placement add and modify commands\n";
255   cout << "   --tags-add=<list>         list of tags to add for zonegroup placement modify command\n";
256   cout << "   --tags-rm=<list>          list of tags to remove for zonegroup placement modify command\n";
257   cout << "   --endpoints=<list>        zone endpoints\n";
258   cout << "   --index-pool=<pool>       placement target index pool\n";
259   cout << "   --data-pool=<pool>        placement target data pool\n";
260   cout << "   --data-extra-pool=<pool>  placement target data extra (non-ec) pool\n";
261   cout << "   --placement-index-type=<type>\n";
262   cout << "                             placement target index type (normal, indexless, or #id)\n";
263   cout << "   --compression=<type>      placement target compression type (plugin name or empty/none)\n";
264   cout << "   --tier-type=<type>        zone tier type\n";
265   cout << "   --tier-config=<k>=<v>[,...]\n";
266   cout << "                             set zone tier config keys, values\n";
267   cout << "   --tier-config-rm=<k>[,...]\n";
268   cout << "                             unset zone tier config keys\n";
269   cout << "   --sync-from-all[=false]   set/reset whether zone syncs from all zonegroup peers\n";
270   cout << "   --sync-from=[zone-name][,...]\n";
271   cout << "                             set list of zones to sync from\n";
272   cout << "   --sync-from-rm=[zone-name][,...]\n";
273   cout << "                             remove zones from list of zones to sync from\n";
274   cout << "   --fix                     besides checking bucket index, will also fix it\n";
275   cout << "   --check-objects           bucket check: rebuilds bucket index according to\n";
276   cout << "                             actual objects state\n";
277   cout << "   --format=<format>         specify output format for certain operations: xml,\n";
278   cout << "                             json\n";
279   cout << "   --purge-data              when specified, user removal will also purge all the\n";
280   cout << "                             user data\n";
281   cout << "   --purge-keys              when specified, subuser removal will also purge all the\n";
282   cout << "                             subuser keys\n";
283   cout << "   --purge-objects           remove a bucket's objects before deleting it\n";
284   cout << "                             (NOTE: required to delete a non-empty bucket)\n";
285   cout << "   --sync-stats              option to 'user stats', update user stats with current\n";
286   cout << "                             stats reported by user's buckets indexes\n";
287   cout << "   --show-log-entries=<flag> enable/disable dump of log entries on log show\n";
288   cout << "   --show-log-sum=<flag>     enable/disable dump of log summation on log show\n";
289   cout << "   --skip-zero-entries       log show only dumps entries that don't have zero value\n";
290   cout << "                             in one of the numeric field\n";
291   cout << "   --infile=<file>           specify a file to read in when setting data\n";
292   cout << "   --state=<state string>    specify a state for the opstate set command\n";
293   cout << "   --replica-log-type        replica log type (metadata, data, bucket), required for\n";
294   cout << "                             replica log operations\n";
295   cout << "   --categories=<list>       comma separated list of categories, used in usage show\n";
296   cout << "   --caps=<caps>             list of caps (e.g., \"usage=read, write; user=read\")\n";
297   cout << "   --yes-i-really-mean-it    required for certain operations\n";
298   cout << "   --warnings-only           when specified with bucket limit check, list\n";
299   cout << "                             only buckets nearing or over the current max\n";
300   cout << "                             objects per shard value\n";
301   cout << "   --bypass-gc               when specified with bucket deletion, triggers\n";
302   cout << "                             object deletions by not involving GC\n";
303   cout << "   --inconsistent-index      when specified with bucket deletion and bypass-gc set to true,\n";
304   cout << "                             ignores bucket index consistency\n";
305   cout << "\n";
306   cout << "<date> := \"YYYY-MM-DD[ hh:mm:ss]\"\n";
307   cout << "\nQuota options:\n";
308   cout << "   --bucket                  specified bucket for quota command\n";
309   cout << "   --max-objects             specify max objects (negative value to disable)\n";
310   cout << "   --max-size                specify max size (in B/K/M/G/T, negative value to disable)\n";
311   cout << "   --quota-scope             scope of quota (bucket, user)\n";
312   cout << "\nOrphans search options:\n";
313   cout << "   --pool                    data pool to scan for leaked rados objects in\n";
314   cout << "   --num-shards              num of shards to use for keeping the temporary scan info\n";
315   cout << "   --orphan-stale-secs       num of seconds to wait before declaring an object to be an orphan (default: 86400)\n";
316   cout << "   --job-id                  set the job id (for orphans find)\n";
317   cout << "   --max-concurrent-ios      maximum concurrent ios for orphans find (default: 32)\n";
318   cout << "\nOrphans list-jobs options:\n";
319   cout << "   --extra-info              provide extra info in job list\n";
320   cout << "\nRole options:\n";
321   cout << "   --role-name               name of the role to create\n";
322   cout << "   --path                    path to the role\n";
323   cout << "   --assume-role-policy-doc  the trust relationship policy document that grants an entity permission to assume the role\n";
324   cout << "   --policy-name             name of the policy document\n";
325   cout << "   --policy-doc              permission policy document\n";
326   cout << "   --path-prefix             path prefix for filtering roles\n";
327   cout << "\n";
328   generic_client_usage();
329 }
330
331 enum {
332   OPT_NO_CMD = 0,
333   OPT_USER_CREATE,
334   OPT_USER_INFO,
335   OPT_USER_MODIFY,
336   OPT_USER_RM,
337   OPT_USER_SUSPEND,
338   OPT_USER_ENABLE,
339   OPT_USER_CHECK,
340   OPT_USER_STATS,
341   OPT_USER_LIST,
342   OPT_SUBUSER_CREATE,
343   OPT_SUBUSER_MODIFY,
344   OPT_SUBUSER_RM,
345   OPT_KEY_CREATE,
346   OPT_KEY_RM,
347   OPT_BUCKETS_LIST,
348   OPT_BUCKET_LIMIT_CHECK,
349   OPT_BUCKET_LINK,
350   OPT_BUCKET_UNLINK,
351   OPT_BUCKET_STATS,
352   OPT_BUCKET_CHECK,
353   OPT_BUCKET_SYNC_STATUS,
354   OPT_BUCKET_SYNC_INIT,
355   OPT_BUCKET_SYNC_RUN,
356   OPT_BUCKET_SYNC_DISABLE,
357   OPT_BUCKET_SYNC_ENABLE,
358   OPT_BUCKET_RM,
359   OPT_BUCKET_REWRITE,
360   OPT_BUCKET_RESHARD,
361   OPT_POLICY,
362   OPT_POOL_ADD,
363   OPT_POOL_RM,
364   OPT_POOLS_LIST,
365   OPT_LOG_LIST,
366   OPT_LOG_SHOW,
367   OPT_LOG_RM,
368   OPT_USAGE_SHOW,
369   OPT_USAGE_TRIM,
370   OPT_OBJECT_RM,
371   OPT_OBJECT_UNLINK,
372   OPT_OBJECT_STAT,
373   OPT_OBJECT_REWRITE,
374   OPT_OBJECTS_EXPIRE,
375   OPT_BI_GET,
376   OPT_BI_PUT,
377   OPT_BI_LIST,
378   OPT_BI_PURGE,
379   OPT_OLH_GET,
380   OPT_OLH_READLOG,
381   OPT_QUOTA_SET,
382   OPT_QUOTA_ENABLE,
383   OPT_QUOTA_DISABLE,
384   OPT_GC_LIST,
385   OPT_GC_PROCESS,
386   OPT_LC_LIST,
387   OPT_LC_PROCESS,
388   OPT_ORPHANS_FIND,
389   OPT_ORPHANS_FINISH,
390   OPT_ORPHANS_LIST_JOBS,
391   OPT_ZONEGROUP_ADD,
392   OPT_ZONEGROUP_CREATE,
393   OPT_ZONEGROUP_DEFAULT,
394   OPT_ZONEGROUP_DELETE,
395   OPT_ZONEGROUP_GET,
396   OPT_ZONEGROUP_MODIFY,
397   OPT_ZONEGROUP_SET,
398   OPT_ZONEGROUP_LIST,
399   OPT_ZONEGROUP_REMOVE,
400   OPT_ZONEGROUP_RENAME,
401   OPT_ZONEGROUP_PLACEMENT_ADD,
402   OPT_ZONEGROUP_PLACEMENT_MODIFY,
403   OPT_ZONEGROUP_PLACEMENT_RM,
404   OPT_ZONEGROUP_PLACEMENT_LIST,
405   OPT_ZONEGROUP_PLACEMENT_DEFAULT,
406   OPT_ZONE_CREATE,
407   OPT_ZONE_DELETE,
408   OPT_ZONE_GET,
409   OPT_ZONE_MODIFY,
410   OPT_ZONE_SET,
411   OPT_ZONE_LIST,
412   OPT_ZONE_RENAME,
413   OPT_ZONE_DEFAULT,
414   OPT_ZONE_PLACEMENT_ADD,
415   OPT_ZONE_PLACEMENT_MODIFY,
416   OPT_ZONE_PLACEMENT_RM,
417   OPT_ZONE_PLACEMENT_LIST,
418   OPT_CAPS_ADD,
419   OPT_CAPS_RM,
420   OPT_METADATA_GET,
421   OPT_METADATA_PUT,
422   OPT_METADATA_RM,
423   OPT_METADATA_LIST,
424   OPT_METADATA_SYNC_STATUS,
425   OPT_METADATA_SYNC_INIT,
426   OPT_METADATA_SYNC_RUN,
427   OPT_MDLOG_LIST,
428   OPT_MDLOG_AUTOTRIM,
429   OPT_MDLOG_TRIM,
430   OPT_MDLOG_FETCH,
431   OPT_MDLOG_STATUS,
432   OPT_SYNC_ERROR_LIST,
433   OPT_BILOG_LIST,
434   OPT_BILOG_TRIM,
435   OPT_BILOG_STATUS,
436   OPT_DATA_SYNC_STATUS,
437   OPT_DATA_SYNC_INIT,
438   OPT_DATA_SYNC_RUN,
439   OPT_DATALOG_LIST,
440   OPT_DATALOG_STATUS,
441   OPT_DATALOG_TRIM,
442   OPT_OPSTATE_LIST,
443   OPT_OPSTATE_SET,
444   OPT_OPSTATE_RENEW,
445   OPT_OPSTATE_RM,
446   OPT_REPLICALOG_GET,
447   OPT_REPLICALOG_UPDATE,
448   OPT_REPLICALOG_DELETE,
449   OPT_REALM_CREATE,
450   OPT_REALM_DELETE,
451   OPT_REALM_GET,
452   OPT_REALM_GET_DEFAULT,
453   OPT_REALM_LIST,
454   OPT_REALM_LIST_PERIODS,
455   OPT_REALM_REMOVE,
456   OPT_REALM_RENAME,
457   OPT_REALM_SET,
458   OPT_REALM_DEFAULT,
459   OPT_REALM_PULL,
460   OPT_PERIOD_DELETE,
461   OPT_PERIOD_GET,
462   OPT_PERIOD_GET_CURRENT,
463   OPT_PERIOD_PULL,
464   OPT_PERIOD_PUSH,
465   OPT_PERIOD_LIST,
466   OPT_PERIOD_UPDATE,
467   OPT_PERIOD_COMMIT,
468   OPT_GLOBAL_QUOTA_GET,
469   OPT_GLOBAL_QUOTA_SET,
470   OPT_GLOBAL_QUOTA_ENABLE,
471   OPT_GLOBAL_QUOTA_DISABLE,
472   OPT_SYNC_STATUS,
473   OPT_ROLE_CREATE,
474   OPT_ROLE_DELETE,
475   OPT_ROLE_GET,
476   OPT_ROLE_MODIFY,
477   OPT_ROLE_LIST,
478   OPT_ROLE_POLICY_PUT,
479   OPT_ROLE_POLICY_LIST,
480   OPT_ROLE_POLICY_GET,
481   OPT_ROLE_POLICY_DELETE,
482   OPT_RESHARD_ADD,
483   OPT_RESHARD_LIST,
484   OPT_RESHARD_STATUS,
485   OPT_RESHARD_PROCESS,
486   OPT_RESHARD_CANCEL,
487 };
488
489 static int get_cmd(const char *cmd, const char *prev_cmd, const char *prev_prev_cmd, bool *need_more)
490 {
491   *need_more = false;
492   // NOTE: please keep the checks in alphabetical order !!!
493   if (strcmp(cmd, "bi") == 0 ||
494       strcmp(cmd, "bilog") == 0 ||
495       strcmp(cmd, "buckets") == 0 ||
496       strcmp(cmd, "caps") == 0 ||
497       strcmp(cmd, "data") == 0 ||
498       strcmp(cmd, "datalog") == 0 ||
499       strcmp(cmd, "error") == 0 ||
500       strcmp(cmd, "gc") == 0 ||
501       strcmp(cmd, "global") == 0 ||
502       strcmp(cmd, "key") == 0 ||
503       strcmp(cmd, "log") == 0 ||
504       strcmp(cmd, "lc") == 0 ||
505       strcmp(cmd, "mdlog") == 0 ||
506       strcmp(cmd, "metadata") == 0 ||
507       strcmp(cmd, "object") == 0 ||
508       strcmp(cmd, "objects") == 0 ||
509       strcmp(cmd, "olh") == 0 ||
510       strcmp(cmd, "opstate") == 0 ||
511       strcmp(cmd, "orphans") == 0 ||
512       strcmp(cmd, "period") == 0 ||
513       strcmp(cmd, "placement") == 0 ||
514       strcmp(cmd, "pool") == 0 ||
515       strcmp(cmd, "pools") == 0 ||
516       strcmp(cmd, "quota") == 0 ||
517       strcmp(cmd, "realm") == 0 ||
518       strcmp(cmd, "replicalog") == 0 ||
519       strcmp(cmd, "role") == 0 ||
520       strcmp(cmd, "role-policy") == 0 ||
521       strcmp(cmd, "subuser") == 0 ||
522       strcmp(cmd, "sync") == 0 ||
523       strcmp(cmd, "usage") == 0 ||
524       strcmp(cmd, "user") == 0 ||
525       strcmp(cmd, "zone") == 0 ||
526       strcmp(cmd, "zonegroup") == 0 ||
527       strcmp(cmd, "zonegroups") == 0) {
528     *need_more = true;
529     return 0;
530   }
531
532   /*
533    * can do both radosgw-admin bucket reshard, and radosgw-admin reshard bucket
534    */
535   if (strcmp(cmd, "reshard") == 0 &&
536       !(prev_cmd && strcmp(prev_cmd, "bucket") == 0)) {
537     *need_more = true;
538     return 0;
539   }
540   if (strcmp(cmd, "bucket") == 0 &&
541       !(prev_cmd && strcmp(prev_cmd, "reshard") == 0)) {
542     *need_more = true;
543     return 0;
544   }
545
546   if (strcmp(cmd, "policy") == 0)
547     return OPT_POLICY;
548
549   if (!prev_cmd)
550     return -EINVAL;
551
552   if (strcmp(prev_cmd, "user") == 0) {
553     if (strcmp(cmd, "create") == 0)
554       return OPT_USER_CREATE;
555     if (strcmp(cmd, "info") == 0)
556       return OPT_USER_INFO;
557     if (strcmp(cmd, "modify") == 0)
558       return OPT_USER_MODIFY;
559     if (strcmp(cmd, "rm") == 0)
560       return OPT_USER_RM;
561     if (strcmp(cmd, "suspend") == 0)
562       return OPT_USER_SUSPEND;
563     if (strcmp(cmd, "enable") == 0)
564       return OPT_USER_ENABLE;
565     if (strcmp(cmd, "check") == 0)
566       return OPT_USER_CHECK;
567     if (strcmp(cmd, "stats") == 0)
568       return OPT_USER_STATS;
569     if (strcmp(cmd, "list") == 0)
570       return OPT_USER_LIST;
571   } else if (strcmp(prev_cmd, "subuser") == 0) {
572     if (strcmp(cmd, "create") == 0)
573       return OPT_SUBUSER_CREATE;
574     if (strcmp(cmd, "modify") == 0)
575       return OPT_SUBUSER_MODIFY;
576     if (strcmp(cmd, "rm") == 0)
577       return OPT_SUBUSER_RM;
578   } else if (strcmp(prev_cmd, "key") == 0) {
579     if (strcmp(cmd, "create") == 0)
580       return OPT_KEY_CREATE;
581     if (strcmp(cmd, "rm") == 0)
582       return OPT_KEY_RM;
583   } else if (strcmp(prev_cmd, "buckets") == 0) {
584     if (strcmp(cmd, "list") == 0)
585       return OPT_BUCKETS_LIST;
586   } else if (strcmp(prev_cmd, "bucket") == 0) {
587     if (strcmp(cmd, "list") == 0)
588       return OPT_BUCKETS_LIST;
589     if (strcmp(cmd, "link") == 0)
590       return OPT_BUCKET_LINK;
591     if (strcmp(cmd, "unlink") == 0)
592       return OPT_BUCKET_UNLINK;
593     if (strcmp(cmd, "stats") == 0)
594       return OPT_BUCKET_STATS;
595     if (strcmp(cmd, "rm") == 0)
596       return OPT_BUCKET_RM;
597     if (strcmp(cmd, "rewrite") == 0)
598       return OPT_BUCKET_REWRITE;
599     if (strcmp(cmd, "reshard") == 0)
600       return OPT_BUCKET_RESHARD;
601     if (strcmp(cmd, "check") == 0)
602       return OPT_BUCKET_CHECK;
603     if (strcmp(cmd, "sync") == 0) {
604       *need_more = true;
605       return 0;
606     }
607     if (strcmp(cmd, "limit") == 0) {
608       *need_more = true;
609       return 0;
610     }
611   } else if (prev_prev_cmd && strcmp(prev_prev_cmd, "bucket") == 0) {
612     if (strcmp(prev_cmd, "sync") == 0) {
613       if (strcmp(cmd, "status") == 0)
614         return OPT_BUCKET_SYNC_STATUS;
615       if (strcmp(cmd, "init") == 0)
616         return OPT_BUCKET_SYNC_INIT;
617       if (strcmp(cmd, "run") == 0)
618         return OPT_BUCKET_SYNC_RUN;
619       if (strcmp(cmd, "disable") == 0)
620         return OPT_BUCKET_SYNC_DISABLE;
621       if (strcmp(cmd, "enable") == 0)
622         return OPT_BUCKET_SYNC_ENABLE;
623     } else if ((strcmp(prev_cmd, "limit") == 0) &&
624                (strcmp(cmd, "check") == 0)) {
625       return OPT_BUCKET_LIMIT_CHECK;
626     }
627   } else if (strcmp(prev_cmd, "log") == 0) {
628     if (strcmp(cmd, "list") == 0)
629       return OPT_LOG_LIST;
630     if (strcmp(cmd, "show") == 0)
631       return OPT_LOG_SHOW;
632     if (strcmp(cmd, "rm") == 0)
633       return OPT_LOG_RM;
634   } else if (strcmp(prev_cmd, "usage") == 0) {
635     if (strcmp(cmd, "show") == 0)
636       return OPT_USAGE_SHOW;
637     if (strcmp(cmd, "trim") == 0)
638       return OPT_USAGE_TRIM;
639   } else if (strcmp(prev_cmd, "caps") == 0) {
640     if (strcmp(cmd, "add") == 0)
641       return OPT_CAPS_ADD;
642     if (strcmp(cmd, "rm") == 0)
643       return OPT_CAPS_RM;
644   } else if (strcmp(prev_cmd, "pool") == 0) {
645     if (strcmp(cmd, "add") == 0)
646       return OPT_POOL_ADD;
647     if (strcmp(cmd, "rm") == 0)
648       return OPT_POOL_RM;
649     if (strcmp(cmd, "list") == 0)
650       return OPT_POOLS_LIST;
651   } else if (strcmp(prev_cmd, "pools") == 0) {
652     if (strcmp(cmd, "list") == 0)
653       return OPT_POOLS_LIST;
654   } else if (strcmp(prev_cmd, "object") == 0) {
655     if (strcmp(cmd, "rm") == 0)
656       return OPT_OBJECT_RM;
657     if (strcmp(cmd, "unlink") == 0)
658       return OPT_OBJECT_UNLINK;
659     if (strcmp(cmd, "stat") == 0)
660       return OPT_OBJECT_STAT;
661     if (strcmp(cmd, "rewrite") == 0)
662       return OPT_OBJECT_REWRITE;
663   } else if (strcmp(prev_cmd, "objects") == 0) {
664     if (strcmp(cmd, "expire") == 0)
665       return OPT_OBJECTS_EXPIRE;
666   } else if (strcmp(prev_cmd, "olh") == 0) {
667     if (strcmp(cmd, "get") == 0)
668       return OPT_OLH_GET;
669     if (strcmp(cmd, "readlog") == 0)
670       return OPT_OLH_READLOG;
671   } else if (strcmp(prev_cmd, "bi") == 0) {
672     if (strcmp(cmd, "get") == 0)
673       return OPT_BI_GET;
674     if (strcmp(cmd, "put") == 0)
675       return OPT_BI_PUT;
676     if (strcmp(cmd, "list") == 0)
677       return OPT_BI_LIST;
678     if (strcmp(cmd, "purge") == 0)
679       return OPT_BI_PURGE;
680   } else if ((prev_prev_cmd && strcmp(prev_prev_cmd, "global") == 0) &&
681              (strcmp(prev_cmd, "quota") == 0)) {
682     if (strcmp(cmd, "get") == 0)
683       return OPT_GLOBAL_QUOTA_GET;
684     if (strcmp(cmd, "set") == 0)
685       return OPT_GLOBAL_QUOTA_SET;
686     if (strcmp(cmd, "enable") == 0)
687       return OPT_GLOBAL_QUOTA_ENABLE;
688     if (strcmp(cmd, "disable") == 0)
689       return OPT_GLOBAL_QUOTA_DISABLE;
690   } else if (strcmp(prev_cmd, "period") == 0) {
691     if (strcmp(cmd, "delete") == 0)
692       return OPT_PERIOD_DELETE;
693     if (strcmp(cmd, "get") == 0)
694       return OPT_PERIOD_GET;
695     if (strcmp(cmd, "get-current") == 0)
696       return OPT_PERIOD_GET_CURRENT;
697     if (strcmp(cmd, "pull") == 0)
698       return OPT_PERIOD_PULL;
699     if (strcmp(cmd, "push") == 0)
700       return OPT_PERIOD_PUSH;
701     if (strcmp(cmd, "list") == 0)
702       return OPT_PERIOD_LIST;
703     if (strcmp(cmd, "update") == 0)
704       return OPT_PERIOD_UPDATE;
705     if (strcmp(cmd, "commit") == 0)
706       return OPT_PERIOD_COMMIT;
707   } else if (strcmp(prev_cmd, "realm") == 0) {
708     if (strcmp(cmd, "create") == 0)
709       return OPT_REALM_CREATE;
710     if (strcmp(cmd, "delete") == 0)
711       return OPT_REALM_DELETE;
712     if (strcmp(cmd, "get") == 0)
713       return OPT_REALM_GET;
714     if (strcmp(cmd, "get-default") == 0)
715       return OPT_REALM_GET_DEFAULT;
716     if (strcmp(cmd, "list") == 0)
717       return OPT_REALM_LIST;
718     if (strcmp(cmd, "list-periods") == 0)
719       return OPT_REALM_LIST_PERIODS;
720     if (strcmp(cmd, "remove") == 0)
721       return OPT_REALM_REMOVE;
722     if (strcmp(cmd, "rename") == 0)
723       return OPT_REALM_RENAME;
724     if (strcmp(cmd, "set") == 0)
725       return OPT_REALM_SET;
726     if (strcmp(cmd, "default") == 0)
727       return OPT_REALM_DEFAULT;
728     if (strcmp(cmd, "pull") == 0)
729       return OPT_REALM_PULL;
730   } else if ((prev_prev_cmd && strcmp(prev_prev_cmd, "zonegroup") == 0) &&
731              (strcmp(prev_cmd, "placement") == 0)) {
732     if (strcmp(cmd, "add") == 0)
733       return OPT_ZONEGROUP_PLACEMENT_ADD;
734     if (strcmp(cmd, "modify") == 0)
735       return OPT_ZONEGROUP_PLACEMENT_MODIFY;
736     if (strcmp(cmd, "rm") == 0)
737       return OPT_ZONEGROUP_PLACEMENT_RM;
738     if (strcmp(cmd, "list") == 0)
739       return OPT_ZONEGROUP_PLACEMENT_LIST;
740     if (strcmp(cmd, "default") == 0)
741       return OPT_ZONEGROUP_PLACEMENT_DEFAULT;
742   } else if (strcmp(prev_cmd, "zonegroup") == 0) {
743     if (strcmp(cmd, "add") == 0)
744       return OPT_ZONEGROUP_ADD;
745     if (strcmp(cmd, "create")== 0)
746       return OPT_ZONEGROUP_CREATE;
747     if (strcmp(cmd, "default") == 0)
748       return OPT_ZONEGROUP_DEFAULT;
749     if (strcmp(cmd, "delete") == 0)
750       return OPT_ZONEGROUP_DELETE;
751     if (strcmp(cmd, "get") == 0)
752       return OPT_ZONEGROUP_GET;
753     if (strcmp(cmd, "modify") == 0)
754       return OPT_ZONEGROUP_MODIFY;
755     if (strcmp(cmd, "list") == 0)
756       return OPT_ZONEGROUP_LIST;
757     if (strcmp(cmd, "set") == 0)
758       return OPT_ZONEGROUP_SET;
759     if (strcmp(cmd, "remove") == 0)
760       return OPT_ZONEGROUP_REMOVE;
761     if (strcmp(cmd, "rename") == 0)
762       return OPT_ZONEGROUP_RENAME;
763   } else if (strcmp(prev_cmd, "quota") == 0) {
764     if (strcmp(cmd, "set") == 0)
765       return OPT_QUOTA_SET;
766     if (strcmp(cmd, "enable") == 0)
767       return OPT_QUOTA_ENABLE;
768     if (strcmp(cmd, "disable") == 0)
769       return OPT_QUOTA_DISABLE;
770   } else if (strcmp(prev_cmd, "zonegroups") == 0) {
771     if (strcmp(cmd, "list") == 0)
772       return OPT_ZONEGROUP_LIST;
773   } else if ((prev_prev_cmd && strcmp(prev_prev_cmd, "zone") == 0) &&
774              (strcmp(prev_cmd, "placement") == 0)) {
775     if (strcmp(cmd, "add") == 0)
776       return OPT_ZONE_PLACEMENT_ADD;
777     if (strcmp(cmd, "modify") == 0)
778       return OPT_ZONE_PLACEMENT_MODIFY;
779     if (strcmp(cmd, "rm") == 0)
780       return OPT_ZONE_PLACEMENT_RM;
781     if (strcmp(cmd, "list") == 0)
782       return OPT_ZONE_PLACEMENT_LIST;
783   } else if (strcmp(prev_cmd, "zone") == 0) {
784     if (strcmp(cmd, "delete") == 0)
785       return OPT_ZONE_DELETE;
786     if (strcmp(cmd, "create") == 0)
787       return OPT_ZONE_CREATE;
788     if (strcmp(cmd, "get") == 0)
789       return OPT_ZONE_GET;
790     if (strcmp(cmd, "set") == 0)
791       return OPT_ZONE_SET;
792     if (strcmp(cmd, "list") == 0)
793       return OPT_ZONE_LIST;
794     if (strcmp(cmd, "modify") == 0)
795       return OPT_ZONE_MODIFY;
796     if (strcmp(cmd, "rename") == 0)
797       return OPT_ZONE_RENAME;
798     if (strcmp(cmd, "default") == 0)
799       return OPT_ZONE_DEFAULT;
800   } else if (strcmp(prev_cmd, "zones") == 0) {
801     if (strcmp(cmd, "list") == 0)
802       return OPT_ZONE_LIST;
803   } else if (strcmp(prev_cmd, "gc") == 0) {
804     if (strcmp(cmd, "list") == 0)
805       return OPT_GC_LIST;
806     if (strcmp(cmd, "process") == 0)
807       return OPT_GC_PROCESS;
808   } else if (strcmp(prev_cmd, "lc") == 0) {
809     if (strcmp(cmd, "list") == 0)
810       return OPT_LC_LIST;
811     if (strcmp(cmd, "process") == 0)
812       return OPT_LC_PROCESS;
813   } else if (strcmp(prev_cmd, "orphans") == 0) {
814     if (strcmp(cmd, "find") == 0)
815       return OPT_ORPHANS_FIND;
816     if (strcmp(cmd, "finish") == 0)
817       return OPT_ORPHANS_FINISH;
818     if (strcmp(cmd, "list-jobs") == 0)
819       return OPT_ORPHANS_LIST_JOBS;
820   } else if (strcmp(prev_cmd, "metadata") == 0) {
821     if (strcmp(cmd, "get") == 0)
822       return OPT_METADATA_GET;
823     if (strcmp(cmd, "put") == 0)
824       return OPT_METADATA_PUT;
825     if (strcmp(cmd, "rm") == 0)
826       return OPT_METADATA_RM;
827     if (strcmp(cmd, "list") == 0)
828       return OPT_METADATA_LIST;
829     if (strcmp(cmd, "sync") == 0) {
830       *need_more = true;
831       return 0;
832     }
833   } else if ((prev_prev_cmd && strcmp(prev_prev_cmd, "metadata") == 0) &&
834              (strcmp(prev_cmd, "sync") == 0)) {
835     if (strcmp(cmd, "status") == 0)
836       return OPT_METADATA_SYNC_STATUS;
837     if (strcmp(cmd, "init") == 0)
838       return OPT_METADATA_SYNC_INIT;
839     if (strcmp(cmd, "run") == 0)
840       return OPT_METADATA_SYNC_RUN;
841   } else if ((prev_prev_cmd && strcmp(prev_prev_cmd, "sync") == 0) &&
842              (strcmp(prev_cmd, "error") == 0)) {
843     if (strcmp(cmd, "list") == 0)
844       return OPT_SYNC_ERROR_LIST;
845   } else if (strcmp(prev_cmd, "mdlog") == 0) {
846     if (strcmp(cmd, "list") == 0)
847       return OPT_MDLOG_LIST;
848     if (strcmp(cmd, "autotrim") == 0)
849       return OPT_MDLOG_AUTOTRIM;
850     if (strcmp(cmd, "trim") == 0)
851       return OPT_MDLOG_TRIM;
852     if (strcmp(cmd, "fetch") == 0)
853       return OPT_MDLOG_FETCH;
854     if (strcmp(cmd, "status") == 0)
855       return OPT_MDLOG_STATUS;
856   } else if (strcmp(prev_cmd, "bilog") == 0) {
857     if (strcmp(cmd, "list") == 0)
858       return OPT_BILOG_LIST;
859     if (strcmp(cmd, "trim") == 0)
860       return OPT_BILOG_TRIM;
861     if (strcmp(cmd, "status") == 0)
862       return OPT_BILOG_STATUS;
863   } else if (strcmp(prev_cmd, "data") == 0) {
864     if (strcmp(cmd, "sync") == 0) {
865       *need_more = true;
866       return 0;
867     }
868   } else if (strcmp(prev_cmd, "datalog") == 0) {
869     if (strcmp(cmd, "list") == 0)
870       return OPT_DATALOG_LIST;
871     if (strcmp(cmd, "trim") == 0)
872       return OPT_DATALOG_TRIM;
873     if (strcmp(cmd, "status") == 0)
874       return OPT_DATALOG_STATUS;
875   } else if ((prev_prev_cmd && strcmp(prev_prev_cmd, "data") == 0) &&
876              (strcmp(prev_cmd, "sync") == 0)) {
877     if (strcmp(cmd, "status") == 0)
878       return OPT_DATA_SYNC_STATUS;
879     if (strcmp(cmd, "init") == 0)
880       return OPT_DATA_SYNC_INIT;
881     if (strcmp(cmd, "run") == 0)
882       return OPT_DATA_SYNC_RUN;
883   } else if (strcmp(prev_cmd, "opstate") == 0) {
884     if (strcmp(cmd, "list") == 0)
885       return OPT_OPSTATE_LIST;
886     if (strcmp(cmd, "set") == 0)
887       return OPT_OPSTATE_SET;
888     if (strcmp(cmd, "renew") == 0)
889       return OPT_OPSTATE_RENEW;
890     if (strcmp(cmd, "rm") == 0)
891       return OPT_OPSTATE_RM;
892   } else if (strcmp(prev_cmd, "replicalog") == 0) {
893     if (strcmp(cmd, "get") == 0)
894       return OPT_REPLICALOG_GET;
895     if (strcmp(cmd, "update") == 0)
896       return OPT_REPLICALOG_UPDATE;
897     if (strcmp(cmd, "delete") == 0)
898       return OPT_REPLICALOG_DELETE;
899   } else if (strcmp(prev_cmd, "sync") == 0) {
900     if (strcmp(cmd, "status") == 0)
901       return OPT_SYNC_STATUS;
902   } else if (strcmp(prev_cmd, "role") == 0) {
903     if (strcmp(cmd, "create") == 0)
904       return OPT_ROLE_CREATE;
905     if (strcmp(cmd, "delete") == 0)
906       return OPT_ROLE_DELETE;
907     if (strcmp(cmd, "get") == 0)
908       return OPT_ROLE_GET;
909     if (strcmp(cmd, "modify") == 0)
910       return OPT_ROLE_MODIFY;
911     if (strcmp(cmd, "list") == 0)
912       return OPT_ROLE_LIST;
913   } else if (strcmp(prev_cmd, "role-policy") == 0) {
914     if (strcmp(cmd, "put") == 0)
915       return OPT_ROLE_POLICY_PUT;
916     if (strcmp(cmd, "list") == 0)
917       return OPT_ROLE_POLICY_LIST;
918     if (strcmp(cmd, "get") == 0)
919       return OPT_ROLE_POLICY_GET;
920     if (strcmp(cmd, "delete") == 0)
921       return OPT_ROLE_POLICY_DELETE;
922   } else if (strcmp(prev_cmd, "reshard") == 0) {
923     if (strcmp(cmd, "bucket") == 0)
924       return OPT_BUCKET_RESHARD;
925     if (strcmp(cmd, "add") == 0)
926       return OPT_RESHARD_ADD;
927     if (strcmp(cmd, "list") == 0)
928       return OPT_RESHARD_LIST;
929     if (strcmp(cmd, "status") == 0)
930       return OPT_RESHARD_STATUS;
931     if (strcmp(cmd, "execute") == 0)
932       return OPT_RESHARD_PROCESS;
933     if (strcmp(cmd, "cancel") == 0)
934       return OPT_RESHARD_CANCEL;
935   }
936
937   return -EINVAL;
938 }
939
940 enum ReplicaLogType {
941   ReplicaLog_Invalid = 0,
942   ReplicaLog_Metadata,
943   ReplicaLog_Data,
944   ReplicaLog_Bucket,
945 };
946
947 ReplicaLogType get_replicalog_type(const string& name) {
948   if (name == "md" || name == "meta" || name == "metadata")
949     return ReplicaLog_Metadata;
950   if (name == "data")
951     return ReplicaLog_Data;
952   if (name == "bucket")
953     return ReplicaLog_Bucket;
954
955   return ReplicaLog_Invalid;
956 }
957
958 BIIndexType get_bi_index_type(const string& type_str) {
959   if (type_str == "plain")
960     return PlainIdx;
961   if (type_str == "instance")
962     return InstanceIdx;
963   if (type_str == "olh")
964     return OLHIdx;
965
966   return InvalidIdx;
967 }
968
969 void dump_bi_entry(bufferlist& bl, BIIndexType index_type, Formatter *formatter)
970 {
971   bufferlist::iterator iter = bl.begin();
972   switch (index_type) {
973     case PlainIdx:
974     case InstanceIdx:
975       {
976         rgw_bucket_dir_entry entry;
977         ::decode(entry, iter);
978         encode_json("entry", entry, formatter);
979       }
980       break;
981     case OLHIdx:
982       {
983         rgw_bucket_olh_entry entry;
984         ::decode(entry, iter);
985         encode_json("entry", entry, formatter);
986       }
987       break;
988     default:
989       ceph_abort();
990       break;
991   }
992 }
993
994 static void show_user_info(RGWUserInfo& info, Formatter *formatter)
995 {
996   encode_json("user_info", info, formatter);
997   formatter->flush(cout);
998   cout << std::endl;
999 }
1000
1001 static void show_perm_policy(string perm_policy, Formatter* formatter)
1002 {
1003   formatter->open_object_section("role");
1004   formatter->dump_string("Permission policy", perm_policy);
1005   formatter->close_section();
1006   formatter->flush(cout);
1007 }
1008
1009 static void show_policy_names(std::vector<string> policy_names, Formatter* formatter)
1010 {
1011   formatter->open_array_section("PolicyNames");
1012   for (const auto& it : policy_names) {
1013     formatter->dump_string("policyname", it);
1014   }
1015   formatter->close_section();
1016   formatter->flush(cout);
1017 }
1018
1019 static void show_role_info(RGWRole& role, Formatter* formatter)
1020 {
1021   formatter->open_object_section("role");
1022   role.dump(formatter);
1023   formatter->close_section();
1024   formatter->flush(cout);
1025 }
1026
1027 static void show_roles_info(vector<RGWRole>& roles, Formatter* formatter)
1028 {
1029   formatter->open_array_section("Roles");
1030   for (const auto& it : roles) {
1031     formatter->open_object_section("role");
1032     it.dump(formatter);
1033     formatter->close_section();
1034   }
1035   formatter->close_section();
1036   formatter->flush(cout);
1037 }
1038
1039 class StoreDestructor {
1040   RGWRados *store;
1041 public:
1042   explicit StoreDestructor(RGWRados *_s) : store(_s) {}
1043   ~StoreDestructor() {
1044     RGWStoreManager::close_storage(store);
1045   }
1046 };
1047
1048 static int init_bucket(const string& tenant_name, const string& bucket_name, const string& bucket_id,
1049                        RGWBucketInfo& bucket_info, rgw_bucket& bucket, map<string, bufferlist> *pattrs = nullptr)
1050 {
1051   if (!bucket_name.empty()) {
1052     RGWObjectCtx obj_ctx(store);
1053     int r;
1054     if (bucket_id.empty()) {
1055       r = store->get_bucket_info(obj_ctx, tenant_name, bucket_name, bucket_info, nullptr, pattrs);
1056     } else {
1057       string bucket_instance_id = bucket_name + ":" + bucket_id;
1058       r = store->get_bucket_instance_info(obj_ctx, bucket_instance_id, bucket_info, NULL, pattrs);
1059     }
1060     if (r < 0) {
1061       cerr << "could not get bucket info for bucket=" << bucket_name << std::endl;
1062       return r;
1063     }
1064     bucket = bucket_info.bucket;
1065   }
1066   return 0;
1067 }
1068
1069 static int read_input(const string& infile, bufferlist& bl)
1070 {
1071   int fd = 0;
1072   if (infile.size()) {
1073     fd = open(infile.c_str(), O_RDONLY);
1074     if (fd < 0) {
1075       int err = -errno;
1076       cerr << "error reading input file " << infile << std::endl;
1077       return err;
1078     }
1079   }
1080
1081 #define READ_CHUNK 8196
1082   int r;
1083   int err;
1084
1085   do {
1086     char buf[READ_CHUNK];
1087
1088     r = safe_read(fd, buf, READ_CHUNK);
1089     if (r < 0) {
1090       err = -errno;
1091       cerr << "error while reading input" << std::endl;
1092       goto out;
1093     }
1094     bl.append(buf, r);
1095   } while (r > 0);
1096   err = 0;
1097
1098  out:
1099   if (infile.size()) {
1100     close(fd);
1101   }
1102   return err;
1103 }
1104
1105 template <class T>
1106 static int read_decode_json(const string& infile, T& t)
1107 {
1108   bufferlist bl;
1109   int ret = read_input(infile, bl);
1110   if (ret < 0) {
1111     cerr << "ERROR: failed to read input: " << cpp_strerror(-ret) << std::endl;
1112     return ret;
1113   }
1114   JSONParser p;
1115   if (!p.parse(bl.c_str(), bl.length())) {
1116     cout << "failed to parse JSON" << std::endl;
1117     return -EINVAL;
1118   }
1119
1120   try {
1121     decode_json_obj(t, &p);
1122   } catch (JSONDecoder::err& e) {
1123     cout << "failed to decode JSON input: " << e.message << std::endl;
1124     return -EINVAL;
1125   }
1126   return 0;
1127 }
1128
1129 template <class T, class K>
1130 static int read_decode_json(const string& infile, T& t, K *k)
1131 {
1132   bufferlist bl;
1133   int ret = read_input(infile, bl);
1134   if (ret < 0) {
1135     cerr << "ERROR: failed to read input: " << cpp_strerror(-ret) << std::endl;
1136     return ret;
1137   }
1138   JSONParser p;
1139   if (!p.parse(bl.c_str(), bl.length())) {
1140     cout << "failed to parse JSON" << std::endl;
1141     return -EINVAL;
1142   }
1143
1144   try {
1145     t.decode_json(&p, k);
1146   } catch (JSONDecoder::err& e) {
1147     cout << "failed to decode JSON input: " << e.message << std::endl;
1148     return -EINVAL;
1149   }
1150   return 0;
1151 }
1152
1153 static int parse_date_str(const string& date_str, utime_t& ut)
1154 {
1155   uint64_t epoch = 0;
1156   uint64_t nsec = 0;
1157
1158   if (!date_str.empty()) {
1159     int ret = utime_t::parse_date(date_str, &epoch, &nsec);
1160     if (ret < 0) {
1161       cerr << "ERROR: failed to parse date: " << date_str << std::endl;
1162       return -EINVAL;
1163     }
1164   }
1165
1166   ut = utime_t(epoch, nsec);
1167
1168   return 0;
1169 }
1170
1171 template <class T>
1172 static bool decode_dump(const char *field_name, bufferlist& bl, Formatter *f)
1173 {
1174   T t;
1175
1176   bufferlist::iterator iter = bl.begin();
1177
1178   try {
1179     ::decode(t, iter);
1180   } catch (buffer::error& err) {
1181     return false;
1182   }
1183
1184   encode_json(field_name, t, f);
1185
1186   return true;
1187 }
1188
1189 static bool dump_string(const char *field_name, bufferlist& bl, Formatter *f)
1190 {
1191   string val;
1192   if (bl.length() > 0) {
1193     val.assign(bl.c_str());
1194   }
1195   f->dump_string(field_name, val);
1196
1197   return true;
1198 }
1199
1200 void set_quota_info(RGWQuotaInfo& quota, int opt_cmd, int64_t max_size, int64_t max_objects,
1201                     bool have_max_size, bool have_max_objects)
1202 {
1203   switch (opt_cmd) {
1204     case OPT_QUOTA_ENABLE:
1205     case OPT_GLOBAL_QUOTA_ENABLE:
1206       quota.enabled = true;
1207
1208       // falling through on purpose
1209
1210     case OPT_QUOTA_SET:
1211     case OPT_GLOBAL_QUOTA_SET:
1212       if (have_max_objects) {
1213         if (max_objects < 0) {
1214           quota.max_objects = -1;
1215         } else {
1216           quota.max_objects = max_objects;
1217         }
1218       }
1219       if (have_max_size) {
1220         if (max_size < 0) {
1221           quota.max_size = -1;
1222         } else {
1223           quota.max_size = rgw_rounded_kb(max_size) * 1024;
1224         }
1225       }
1226       break;
1227     case OPT_QUOTA_DISABLE:
1228     case OPT_GLOBAL_QUOTA_DISABLE:
1229       quota.enabled = false;
1230       break;
1231   }
1232 }
1233
1234 int set_bucket_quota(RGWRados *store, int opt_cmd,
1235                      const string& tenant_name, const string& bucket_name,
1236                      int64_t max_size, int64_t max_objects,
1237                      bool have_max_size, bool have_max_objects)
1238 {
1239   RGWBucketInfo bucket_info;
1240   map<string, bufferlist> attrs;
1241   RGWObjectCtx obj_ctx(store);
1242   int r = store->get_bucket_info(obj_ctx, tenant_name, bucket_name, bucket_info, NULL, &attrs);
1243   if (r < 0) {
1244     cerr << "could not get bucket info for bucket=" << bucket_name << ": " << cpp_strerror(-r) << std::endl;
1245     return -r;
1246   }
1247
1248   set_quota_info(bucket_info.quota, opt_cmd, max_size, max_objects, have_max_size, have_max_objects);
1249
1250    r = store->put_bucket_instance_info(bucket_info, false, real_time(), &attrs);
1251   if (r < 0) {
1252     cerr << "ERROR: failed writing bucket instance info: " << cpp_strerror(-r) << std::endl;
1253     return -r;
1254   }
1255   return 0;
1256 }
1257
1258 int set_user_bucket_quota(int opt_cmd, RGWUser& user, RGWUserAdminOpState& op_state, int64_t max_size, int64_t max_objects,
1259                           bool have_max_size, bool have_max_objects)
1260 {
1261   RGWUserInfo& user_info = op_state.get_user_info();
1262
1263   set_quota_info(user_info.bucket_quota, opt_cmd, max_size, max_objects, have_max_size, have_max_objects);
1264
1265   op_state.set_bucket_quota(user_info.bucket_quota);
1266
1267   string err;
1268   int r = user.modify(op_state, &err);
1269   if (r < 0) {
1270     cerr << "ERROR: failed updating user info: " << cpp_strerror(-r) << ": " << err << std::endl;
1271     return -r;
1272   }
1273   return 0;
1274 }
1275
1276 int set_user_quota(int opt_cmd, RGWUser& user, RGWUserAdminOpState& op_state, int64_t max_size, int64_t max_objects,
1277                    bool have_max_size, bool have_max_objects)
1278 {
1279   RGWUserInfo& user_info = op_state.get_user_info();
1280
1281   set_quota_info(user_info.user_quota, opt_cmd, max_size, max_objects, have_max_size, have_max_objects);
1282
1283   op_state.set_user_quota(user_info.user_quota);
1284
1285   string err;
1286   int r = user.modify(op_state, &err);
1287   if (r < 0) {
1288     cerr << "ERROR: failed updating user info: " << cpp_strerror(-r) << ": " << err << std::endl;
1289     return -r;
1290   }
1291   return 0;
1292 }
1293
1294 static bool bucket_object_check_filter(const string& name)
1295 {
1296   rgw_obj_key k;
1297   string ns; /* empty namespace */
1298   return rgw_obj_key::oid_to_key_in_ns(name, &k, ns);
1299 }
1300
1301 int check_min_obj_stripe_size(RGWRados *store, RGWBucketInfo& bucket_info, rgw_obj& obj, uint64_t min_stripe_size, bool *need_rewrite)
1302 {
1303   map<string, bufferlist> attrs;
1304   uint64_t obj_size;
1305
1306   RGWObjectCtx obj_ctx(store);
1307   RGWRados::Object op_target(store, bucket_info, obj_ctx, obj);
1308   RGWRados::Object::Read read_op(&op_target);
1309
1310   read_op.params.attrs = &attrs;
1311   read_op.params.obj_size = &obj_size;
1312
1313   int ret = read_op.prepare();
1314   if (ret < 0) {
1315     lderr(store->ctx()) << "ERROR: failed to stat object, returned error: " << cpp_strerror(-ret) << dendl;
1316     return ret;
1317   }
1318
1319   map<string, bufferlist>::iterator iter;
1320   iter = attrs.find(RGW_ATTR_MANIFEST);
1321   if (iter == attrs.end()) {
1322     *need_rewrite = (obj_size >= min_stripe_size);
1323     return 0;
1324   }
1325
1326   RGWObjManifest manifest;
1327
1328   try {
1329     bufferlist& bl = iter->second;
1330     bufferlist::iterator biter = bl.begin();
1331     ::decode(manifest, biter);
1332   } catch (buffer::error& err) {
1333     ldout(store->ctx(), 0) << "ERROR: failed to decode manifest" << dendl;
1334     return -EIO;
1335   }
1336
1337   map<uint64_t, RGWObjManifestPart>& objs = manifest.get_explicit_objs();
1338   map<uint64_t, RGWObjManifestPart>::iterator oiter;
1339   for (oiter = objs.begin(); oiter != objs.end(); ++oiter) {
1340     RGWObjManifestPart& part = oiter->second;
1341
1342     if (part.size >= min_stripe_size) {
1343       *need_rewrite = true;
1344       return 0;
1345     }
1346   }
1347   *need_rewrite = false;
1348
1349   return 0;
1350 }
1351
1352
1353 int check_obj_locator_underscore(RGWBucketInfo& bucket_info, rgw_obj& obj, rgw_obj_key& key, bool fix, bool remove_bad, Formatter *f) {
1354   f->open_object_section("object");
1355   f->open_object_section("key");
1356   f->dump_string("type", "head");
1357   f->dump_string("name", key.name);
1358   f->dump_string("instance", key.instance);
1359   f->close_section();
1360
1361   string oid;
1362   string locator;
1363
1364   get_obj_bucket_and_oid_loc(obj, oid, locator);
1365
1366   f->dump_string("oid", oid);
1367   f->dump_string("locator", locator);
1368
1369
1370   RGWObjectCtx obj_ctx(store);
1371
1372   RGWRados::Object op_target(store, bucket_info, obj_ctx, obj);
1373   RGWRados::Object::Read read_op(&op_target);
1374
1375   int ret = read_op.prepare();
1376   bool needs_fixing = (ret == -ENOENT);
1377
1378   f->dump_bool("needs_fixing", needs_fixing);
1379
1380   string status = (needs_fixing ? "needs_fixing" : "ok");
1381
1382   if ((needs_fixing || remove_bad) && fix) {
1383     ret = store->fix_head_obj_locator(bucket_info, needs_fixing, remove_bad, key);
1384     if (ret < 0) {
1385       cerr << "ERROR: fix_head_object_locator() returned ret=" << ret << std::endl;
1386       goto done;
1387     }
1388     status = "fixed";
1389   }
1390
1391 done:
1392   f->dump_string("status", status);
1393
1394   f->close_section();
1395
1396   return 0;
1397 }
1398
1399 int check_obj_tail_locator_underscore(RGWBucketInfo& bucket_info, rgw_obj& obj, rgw_obj_key& key, bool fix, Formatter *f) {
1400   f->open_object_section("object");
1401   f->open_object_section("key");
1402   f->dump_string("type", "tail");
1403   f->dump_string("name", key.name);
1404   f->dump_string("instance", key.instance);
1405   f->close_section();
1406
1407   bool needs_fixing;
1408   string status;
1409
1410   int ret = store->fix_tail_obj_locator(bucket_info, key, fix, &needs_fixing);
1411   if (ret < 0) {
1412     cerr << "ERROR: fix_tail_object_locator_underscore() returned ret=" << ret << std::endl;
1413     status = "failed";
1414   } else {
1415     status = (needs_fixing && !fix ? "needs_fixing" : "ok");
1416   }
1417
1418   f->dump_bool("needs_fixing", needs_fixing);
1419   f->dump_string("status", status);
1420
1421   f->close_section();
1422
1423   return 0;
1424 }
1425
1426 int do_check_object_locator(const string& tenant_name, const string& bucket_name,
1427                             bool fix, bool remove_bad, Formatter *f)
1428 {
1429   if (remove_bad && !fix) {
1430     cerr << "ERROR: can't have remove_bad specified without fix" << std::endl;
1431     return -EINVAL;
1432   }
1433
1434   RGWBucketInfo bucket_info;
1435   rgw_bucket bucket;
1436   string bucket_id;
1437
1438   f->open_object_section("bucket");
1439   f->dump_string("bucket", bucket_name);
1440   int ret = init_bucket(tenant_name, bucket_name, bucket_id, bucket_info, bucket);
1441   if (ret < 0) {
1442     cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
1443     return ret;
1444   }
1445   bool truncated;
1446   int count = 0;
1447
1448   int max_entries = 1000;
1449
1450   string prefix;
1451   string delim;
1452   vector<rgw_bucket_dir_entry> result;
1453   map<string, bool> common_prefixes;
1454   string ns;
1455
1456   RGWRados::Bucket target(store, bucket_info);
1457   RGWRados::Bucket::List list_op(&target);
1458
1459   string marker;
1460
1461   list_op.params.prefix = prefix;
1462   list_op.params.delim = delim;
1463   list_op.params.marker = rgw_obj_key(marker);
1464   list_op.params.ns = ns;
1465   list_op.params.enforce_ns = true;
1466   list_op.params.list_versions = true;
1467
1468   f->open_array_section("check_objects");
1469   do {
1470     ret = list_op.list_objects(max_entries - count, &result, &common_prefixes, &truncated);
1471     if (ret < 0) {
1472       cerr << "ERROR: store->list_objects(): " << cpp_strerror(-ret) << std::endl;
1473       return -ret;
1474     }
1475
1476     count += result.size();
1477
1478     for (vector<rgw_bucket_dir_entry>::iterator iter = result.begin(); iter != result.end(); ++iter) {
1479       rgw_obj_key key = iter->key;
1480       rgw_obj obj(bucket, key);
1481
1482       if (key.name[0] == '_') {
1483         ret = check_obj_locator_underscore(bucket_info, obj, key, fix, remove_bad, f);
1484
1485         if (ret >= 0) {
1486           ret = check_obj_tail_locator_underscore(bucket_info, obj, key, fix, f);
1487         }
1488       }
1489     }
1490     f->flush(cout);
1491   } while (truncated && count < max_entries);
1492   f->close_section();
1493   f->close_section();
1494
1495   f->flush(cout);
1496
1497   return 0;
1498 }
1499
1500 int set_bucket_sync_enabled(RGWRados *store, int opt_cmd, const string& tenant_name, const string& bucket_name)
1501 {
1502   RGWBucketInfo bucket_info;
1503   map<string, bufferlist> attrs;
1504   RGWObjectCtx obj_ctx(store);
1505
1506   int r = store->get_bucket_info(obj_ctx, tenant_name, bucket_name, bucket_info, NULL, &attrs);
1507   if (r < 0) {
1508     cerr << "could not get bucket info for bucket=" << bucket_name << ": " << cpp_strerror(-r) << std::endl;
1509     return -r;
1510   }
1511
1512   if (opt_cmd == OPT_BUCKET_SYNC_ENABLE) {
1513     bucket_info.flags &= ~BUCKET_DATASYNC_DISABLED;
1514   } else if (opt_cmd == OPT_BUCKET_SYNC_DISABLE) {
1515     bucket_info.flags |= BUCKET_DATASYNC_DISABLED;
1516   }
1517
1518   r = store->put_bucket_instance_info(bucket_info, false, real_time(), &attrs);
1519   if (r < 0) {
1520     cerr << "ERROR: failed writing bucket instance info: " << cpp_strerror(-r) << std::endl;
1521     return -r;
1522   }
1523
1524   int shards_num = bucket_info.num_shards? bucket_info.num_shards : 1;
1525   int shard_id = bucket_info.num_shards? 0 : -1;
1526
1527   if (opt_cmd == OPT_BUCKET_SYNC_DISABLE) {
1528     r = store->stop_bi_log_entries(bucket_info, -1);
1529     if (r < 0) {
1530       lderr(store->ctx()) << "ERROR: failed writing stop bilog" << dendl;
1531       return r;
1532     }
1533   } else {
1534     r = store->resync_bi_log_entries(bucket_info, -1);
1535     if (r < 0) {
1536       lderr(store->ctx()) << "ERROR: failed writing resync bilog" << dendl;
1537       return r;
1538     }
1539   }
1540
1541   for (int i = 0; i < shards_num; ++i, ++shard_id) {
1542     r = store->data_log->add_entry(bucket_info.bucket, shard_id);
1543     if (r < 0) {
1544       lderr(store->ctx()) << "ERROR: failed writing data log" << dendl;
1545       return r;
1546     }
1547   }
1548
1549   return 0;
1550 }
1551
1552
1553 /// search for a matching zone/zonegroup id and return a connection if found
1554 static boost::optional<RGWRESTConn> get_remote_conn(RGWRados *store,
1555                                                     const RGWZoneGroup& zonegroup,
1556                                                     const std::string& remote)
1557 {
1558   boost::optional<RGWRESTConn> conn;
1559   if (remote == zonegroup.get_id()) {
1560     conn.emplace(store->ctx(), store, remote, zonegroup.endpoints);
1561   } else {
1562     for (const auto& z : zonegroup.zones) {
1563       const auto& zone = z.second;
1564       if (remote == zone.id) {
1565         conn.emplace(store->ctx(), store, remote, zone.endpoints);
1566         break;
1567       }
1568     }
1569   }
1570   return conn;
1571 }
1572
1573 /// search each zonegroup for a connection
1574 static boost::optional<RGWRESTConn> get_remote_conn(RGWRados *store,
1575                                                     const RGWPeriodMap& period_map,
1576                                                     const std::string& remote)
1577 {
1578   boost::optional<RGWRESTConn> conn;
1579   for (const auto& zg : period_map.zonegroups) {
1580     conn = get_remote_conn(store, zg.second, remote);
1581     if (conn) {
1582       break;
1583     }
1584   }
1585   return conn;
1586 }
1587
1588 // we expect a very small response
1589 static constexpr size_t MAX_REST_RESPONSE = 128 * 1024;
1590
1591 static int send_to_remote_gateway(RGWRESTConn* conn, req_info& info,
1592                                   bufferlist& in_data, JSONParser& parser)
1593 {
1594   if (!conn) {
1595     return -EINVAL;
1596   }
1597
1598   ceph::bufferlist response;
1599   rgw_user user;
1600   int ret = conn->forward(user, info, nullptr, MAX_REST_RESPONSE, &in_data, &response);
1601
1602   int parse_ret = parser.parse(response.c_str(), response.length());
1603   if (parse_ret < 0) {
1604     cerr << "failed to parse response" << std::endl;
1605     return parse_ret;
1606   }
1607   return ret;
1608 }
1609
1610 static int send_to_url(const string& url, const string& access,
1611                        const string& secret, req_info& info,
1612                        bufferlist& in_data, JSONParser& parser)
1613 {
1614   if (access.empty() || secret.empty()) {
1615     cerr << "An --access-key and --secret must be provided with --url." << std::endl;
1616     return -EINVAL;
1617   }
1618   RGWAccessKey key;
1619   key.id = access;
1620   key.key = secret;
1621
1622   param_vec_t params;
1623   RGWRESTSimpleRequest req(g_ceph_context, url, NULL, &params);
1624
1625   bufferlist response;
1626   int ret = req.forward_request(key, info, MAX_REST_RESPONSE, &in_data, &response);
1627
1628   int parse_ret = parser.parse(response.c_str(), response.length());
1629   if (parse_ret < 0) {
1630     cout << "failed to parse response" << std::endl;
1631     return parse_ret;
1632   }
1633   return ret;
1634 }
1635
1636 static int send_to_remote_or_url(RGWRESTConn *conn, const string& url,
1637                                  const string& access, const string& secret,
1638                                  req_info& info, bufferlist& in_data,
1639                                  JSONParser& parser)
1640 {
1641   if (url.empty()) {
1642     return send_to_remote_gateway(conn, info, in_data, parser);
1643   }
1644   return send_to_url(url, access, secret, info, in_data, parser);
1645 }
1646
1647 static int commit_period(RGWRealm& realm, RGWPeriod& period,
1648                          string remote, const string& url,
1649                          const string& access, const string& secret,
1650                          bool force)
1651 {
1652   const string& master_zone = period.get_master_zone();
1653   if (master_zone.empty()) {
1654     cerr << "cannot commit period: period does not have a master zone of a master zonegroup" << std::endl;
1655     return -EINVAL;
1656   }
1657   // are we the period's master zone?
1658   if (store->get_zone_params().get_id() == master_zone) {
1659     // read the current period
1660     RGWPeriod current_period;
1661     int ret = current_period.init(g_ceph_context, store, realm.get_id());
1662     if (ret < 0) {
1663       cerr << "Error initializing current period: "
1664           << cpp_strerror(-ret) << std::endl;
1665       return ret;
1666     }
1667     // the master zone can commit locally
1668     ret = period.commit(realm, current_period, cerr, force);
1669     if (ret < 0) {
1670       cerr << "failed to commit period: " << cpp_strerror(-ret) << std::endl;
1671     }
1672     return ret;
1673   }
1674
1675   if (remote.empty() && url.empty()) {
1676     // use the new master zone's connection
1677     remote = master_zone;
1678     cout << "Sending period to new master zone " << remote << std::endl;
1679   }
1680   boost::optional<RGWRESTConn> conn;
1681   RGWRESTConn *remote_conn = nullptr;
1682   if (!remote.empty()) {
1683     conn = get_remote_conn(store, period.get_map(), remote);
1684     if (!conn) {
1685       cerr << "failed to find a zone or zonegroup for remote "
1686           << remote << std::endl;
1687       return -ENOENT;
1688     }
1689     remote_conn = &*conn;
1690   }
1691
1692   // push period to the master with an empty period id
1693   period.set_id("");
1694
1695   RGWEnv env;
1696   req_info info(g_ceph_context, &env);
1697   info.method = "POST";
1698   info.request_uri = "/admin/realm/period";
1699
1700   // json format into a bufferlist
1701   JSONFormatter jf(false);
1702   encode_json("period", period, &jf);
1703   bufferlist bl;
1704   jf.flush(bl);
1705
1706   JSONParser p;
1707   int ret = send_to_remote_or_url(remote_conn, url, access, secret, info, bl, p);
1708   if (ret < 0) {
1709     cerr << "request failed: " << cpp_strerror(-ret) << std::endl;
1710
1711     // did we parse an error message?
1712     auto message = p.find_obj("Message");
1713     if (message) {
1714       cerr << "Reason: " << message->get_data() << std::endl;
1715     }
1716     return ret;
1717   }
1718
1719   // decode the response and store it back
1720   try {
1721     decode_json_obj(period, &p);
1722   } catch (JSONDecoder::err& e) {
1723     cout << "failed to decode JSON input: " << e.message << std::endl;
1724     return -EINVAL;
1725   }
1726   if (period.get_id().empty()) {
1727     cerr << "Period commit got back an empty period id" << std::endl;
1728     return -EINVAL;
1729   }
1730   // the master zone gave us back the period that it committed, so it's
1731   // safe to save it as our latest epoch
1732   ret = period.store_info(false);
1733   if (ret < 0) {
1734     cerr << "Error storing committed period " << period.get_id() << ": "
1735         << cpp_strerror(ret) << std::endl;
1736     return ret;
1737   }
1738   ret = period.set_latest_epoch(period.get_epoch());
1739   if (ret < 0) {
1740     cerr << "Error updating period epoch: " << cpp_strerror(ret) << std::endl;
1741     return ret;
1742   }
1743   ret = period.reflect();
1744   if (ret < 0) {
1745     cerr << "Error updating local objects: " << cpp_strerror(ret) << std::endl;
1746     return ret;
1747   }
1748   realm.notify_new_period(period);
1749   return ret;
1750 }
1751
1752 static int update_period(const string& realm_id, const string& realm_name,
1753                          const string& period_id, const string& period_epoch,
1754                          bool commit, const string& remote, const string& url,
1755                          const string& access, const string& secret,
1756                          Formatter *formatter, bool force)
1757 {
1758   RGWRealm realm(realm_id, realm_name);
1759   int ret = realm.init(g_ceph_context, store);
1760   if (ret < 0 ) {
1761     cerr << "Error initializing realm " << cpp_strerror(-ret) << std::endl;
1762     return ret;
1763   }
1764   epoch_t epoch = 0;
1765   if (!period_epoch.empty()) {
1766     epoch = atoi(period_epoch.c_str());
1767   }
1768   RGWPeriod period(period_id, epoch);
1769   ret = period.init(g_ceph_context, store, realm.get_id());
1770   if (ret < 0) {
1771     cerr << "period init failed: " << cpp_strerror(-ret) << std::endl;
1772     return ret;
1773   }
1774   period.fork();
1775   ret = period.update();
1776   if(ret < 0) {
1777     // Dropping the error message here, as both the ret codes were handled in
1778     // period.update()
1779     return ret;
1780   }
1781   ret = period.store_info(false);
1782   if (ret < 0) {
1783     cerr << "failed to store period: " << cpp_strerror(-ret) << std::endl;
1784     return ret;
1785   }
1786   if (commit) {
1787     ret = commit_period(realm, period, remote, url, access, secret, force);
1788     if (ret < 0) {
1789       cerr << "failed to commit period: " << cpp_strerror(-ret) << std::endl;
1790       return ret;
1791     }
1792   }
1793   encode_json("period", period, formatter);
1794   formatter->flush(cout);
1795   cout << std::endl;
1796   return 0;
1797 }
1798
1799 static int init_bucket_for_sync(const string& tenant, const string& bucket_name,
1800                                 const string& bucket_id, rgw_bucket& bucket)
1801 {
1802   RGWBucketInfo bucket_info;
1803
1804   int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
1805   if (ret < 0) {
1806     cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
1807     return ret;
1808   }
1809
1810   return 0;
1811 }
1812
1813 static int do_period_pull(RGWRESTConn *remote_conn, const string& url,
1814                           const string& access_key, const string& secret_key,
1815                           const string& realm_id, const string& realm_name,
1816                           const string& period_id, const string& period_epoch,
1817                           RGWPeriod *period)
1818 {
1819   RGWEnv env;
1820   req_info info(g_ceph_context, &env);
1821   info.method = "GET";
1822   info.request_uri = "/admin/realm/period";
1823
1824   map<string, string> &params = info.args.get_params();
1825   if (!realm_id.empty())
1826     params["realm_id"] = realm_id;
1827   if (!realm_name.empty())
1828     params["realm_name"] = realm_name;
1829   if (!period_id.empty())
1830     params["period_id"] = period_id;
1831   if (!period_epoch.empty())
1832     params["epoch"] = period_epoch;
1833
1834   bufferlist bl;
1835   JSONParser p;
1836   int ret = send_to_remote_or_url(remote_conn, url, access_key, secret_key,
1837                                   info, bl, p);
1838   if (ret < 0) {
1839     cerr << "request failed: " << cpp_strerror(-ret) << std::endl;
1840     return ret;
1841   }
1842   ret = period->init(g_ceph_context, store, false);
1843   if (ret < 0) {
1844     cerr << "faile to init period " << cpp_strerror(-ret) << std::endl;
1845     return ret;
1846   }
1847   try {
1848     decode_json_obj(*period, &p);
1849   } catch (JSONDecoder::err& e) {
1850     cout << "failed to decode JSON input: " << e.message << std::endl;
1851     return -EINVAL;
1852   }
1853   ret = period->store_info(false);
1854   if (ret < 0) {
1855     cerr << "Error storing period " << period->get_id() << ": " << cpp_strerror(ret) << std::endl;
1856   }
1857   // store latest epoch (ignore errors)
1858   period->update_latest_epoch(period->get_epoch());
1859   return 0;
1860 }
1861
1862 static int read_current_period_id(RGWRados* store, const std::string& realm_id,
1863                                   const std::string& realm_name,
1864                                   std::string* period_id)
1865 {
1866   RGWRealm realm(realm_id, realm_name);
1867   int ret = realm.init(g_ceph_context, store);
1868   if (ret < 0) {
1869     std::cerr << "failed to read realm: " << cpp_strerror(-ret) << std::endl;
1870     return ret;
1871   }
1872   *period_id = realm.get_current_period();
1873   return 0;
1874 }
1875
1876 void flush_ss(stringstream& ss, list<string>& l)
1877 {
1878   if (!ss.str().empty()) {
1879     l.push_back(ss.str());
1880   }
1881   ss.str("");
1882 }
1883
1884 stringstream& push_ss(stringstream& ss, list<string>& l, int tab = 0)
1885 {
1886   flush_ss(ss, l);
1887   if (tab > 0) {
1888     ss << setw(tab) << "" << setw(1);
1889   }
1890   return ss;
1891 }
1892
1893 static void get_md_sync_status(list<string>& status)
1894 {
1895   RGWMetaSyncStatusManager sync(store, store->get_async_rados());
1896
1897   int ret = sync.init();
1898   if (ret < 0) {
1899     status.push_back(string("failed to retrieve sync info: sync.init() failed: ") + cpp_strerror(-ret));
1900     return;
1901   }
1902
1903   rgw_meta_sync_status sync_status;
1904   ret = sync.read_sync_status(&sync_status);
1905   if (ret < 0) {
1906     status.push_back(string("failed to read sync status: ") + cpp_strerror(-ret));
1907     return;
1908   }
1909
1910   string status_str;
1911   switch (sync_status.sync_info.state) {
1912     case rgw_meta_sync_info::StateInit:
1913       status_str = "init";
1914       break;
1915     case rgw_meta_sync_info::StateBuildingFullSyncMaps:
1916       status_str = "preparing for full sync";
1917       break;
1918     case rgw_meta_sync_info::StateSync:
1919       status_str = "syncing";
1920       break;
1921     default:
1922       status_str = "unknown";
1923   }
1924
1925   status.push_back(status_str);
1926
1927   uint64_t full_total = 0;
1928   uint64_t full_complete = 0;
1929
1930   int num_full = 0;
1931   int num_inc = 0;
1932   int total_shards = 0;
1933
1934   for (auto marker_iter : sync_status.sync_markers) {
1935     full_total += marker_iter.second.total_entries;
1936     total_shards++;
1937     if (marker_iter.second.state == rgw_meta_sync_marker::SyncState::FullSync) {
1938       num_full++;
1939       full_complete += marker_iter.second.pos;
1940     } else {
1941       full_complete += marker_iter.second.total_entries;
1942     }
1943     if (marker_iter.second.state == rgw_meta_sync_marker::SyncState::IncrementalSync) {
1944       num_inc++;
1945     }
1946   }
1947
1948   stringstream ss;
1949   push_ss(ss, status) << "full sync: " << num_full << "/" << total_shards << " shards";
1950
1951   if (num_full > 0) {
1952     push_ss(ss, status) << "full sync: " << full_total - full_complete << " entries to sync";
1953   }
1954
1955   push_ss(ss, status) << "incremental sync: " << num_inc << "/" << total_shards << " shards";
1956
1957   rgw_mdlog_info log_info;
1958   ret = sync.read_log_info(&log_info);
1959   if (ret < 0) {
1960     status.push_back(string("failed to fetch local sync status: ") + cpp_strerror(-ret));
1961     return;
1962   }
1963
1964   map<int, RGWMetadataLogInfo> master_shards_info;
1965   string master_period = store->get_current_period_id();
1966
1967   ret = sync.read_master_log_shards_info(master_period, &master_shards_info);
1968   if (ret < 0) {
1969     status.push_back(string("failed to fetch master sync status: ") + cpp_strerror(-ret));
1970     return;
1971   }
1972
1973   map<int, string> shards_behind;
1974   if (sync_status.sync_info.period != master_period) {
1975     status.push_back(string("master is on a different period: master_period=" +
1976                             master_period + " local_period=" + sync_status.sync_info.period));
1977   } else {
1978     for (auto local_iter : sync_status.sync_markers) {
1979       int shard_id = local_iter.first;
1980       auto iter = master_shards_info.find(shard_id);
1981
1982       if (iter == master_shards_info.end()) {
1983         /* huh? */
1984         derr << "ERROR: could not find remote sync shard status for shard_id=" << shard_id << dendl;
1985         continue;
1986       }
1987       auto master_marker = iter->second.marker;
1988       if (local_iter.second.state == rgw_meta_sync_marker::SyncState::IncrementalSync &&
1989           master_marker > local_iter.second.marker) {
1990         shards_behind[shard_id] = local_iter.second.marker;
1991       }
1992     }
1993   }
1994
1995   int total_behind = shards_behind.size() + (sync_status.sync_info.num_shards - num_inc);
1996   if (total_behind == 0) {
1997     push_ss(ss, status) << "metadata is caught up with master";
1998   } else {
1999     push_ss(ss, status) << "metadata is behind on " << total_behind << " shards";
2000
2001     map<int, rgw_mdlog_shard_data> master_pos;
2002     ret = sync.read_master_log_shards_next(sync_status.sync_info.period, shards_behind, &master_pos);
2003     if (ret < 0) {
2004       derr << "ERROR: failed to fetch master next positions (" << cpp_strerror(-ret) << ")" << dendl;
2005     } else {
2006       ceph::real_time oldest;
2007       for (auto iter : master_pos) {
2008         rgw_mdlog_shard_data& shard_data = iter.second;
2009
2010         if (!shard_data.entries.empty()) {
2011           rgw_mdlog_entry& entry = shard_data.entries.front();
2012           if (ceph::real_clock::is_zero(oldest)) {
2013             oldest = entry.timestamp;
2014           } else if (!ceph::real_clock::is_zero(entry.timestamp) && entry.timestamp < oldest) {
2015             oldest = entry.timestamp;
2016           }
2017         }
2018       }
2019
2020       if (!ceph::real_clock::is_zero(oldest)) {
2021         push_ss(ss, status) << "oldest incremental change not applied: " << oldest;
2022       }
2023     }
2024   }
2025
2026   flush_ss(ss, status);
2027 }
2028
2029 static void get_data_sync_status(const string& source_zone, list<string>& status, int tab)
2030 {
2031   stringstream ss;
2032
2033   auto ziter = store->zone_by_id.find(source_zone);
2034   if (ziter == store->zone_by_id.end()) {
2035     push_ss(ss, status, tab) << string("zone not found");
2036     flush_ss(ss, status);
2037     return;
2038   }
2039   RGWZone& sz = ziter->second;
2040
2041   if (!store->zone_syncs_from(store->get_zone(), sz)) {
2042     push_ss(ss, status, tab) << string("not syncing from zone");
2043     flush_ss(ss, status);
2044     return;
2045   }
2046   RGWDataSyncStatusManager sync(store, store->get_async_rados(), source_zone);
2047
2048   int ret = sync.init();
2049   if (ret < 0) {
2050     push_ss(ss, status, tab) << string("failed to retrieve sync info: ") + cpp_strerror(-ret);
2051     flush_ss(ss, status);
2052     return;
2053   }
2054
2055   rgw_data_sync_status sync_status;
2056   ret = sync.read_sync_status(&sync_status);
2057   if (ret < 0 && ret != -ENOENT) {
2058     push_ss(ss, status, tab) << string("failed read sync status: ") + cpp_strerror(-ret);
2059     return;
2060   }
2061
2062   string status_str;
2063   switch (sync_status.sync_info.state) {
2064     case rgw_data_sync_info::StateInit:
2065       status_str = "init";
2066       break;
2067     case rgw_data_sync_info::StateBuildingFullSyncMaps:
2068       status_str = "preparing for full sync";
2069       break;
2070     case rgw_data_sync_info::StateSync:
2071       status_str = "syncing";
2072       break;
2073     default:
2074       status_str = "unknown";
2075   }
2076
2077   push_ss(ss, status, tab) << status_str;
2078
2079   uint64_t full_total = 0;
2080   uint64_t full_complete = 0;
2081
2082   int num_full = 0;
2083   int num_inc = 0;
2084   int total_shards = 0;
2085
2086   for (auto marker_iter : sync_status.sync_markers) {
2087     full_total += marker_iter.second.total_entries;
2088     total_shards++;
2089     if (marker_iter.second.state == rgw_data_sync_marker::SyncState::FullSync) {
2090       num_full++;
2091       full_complete += marker_iter.second.pos;
2092     } else {
2093       full_complete += marker_iter.second.total_entries;
2094     }
2095     if (marker_iter.second.state == rgw_data_sync_marker::SyncState::IncrementalSync) {
2096       num_inc++;
2097     }
2098   }
2099
2100   push_ss(ss, status, tab) << "full sync: " << num_full << "/" << total_shards << " shards";
2101
2102   if (num_full > 0) {
2103     push_ss(ss, status, tab) << "full sync: " << full_total - full_complete << " buckets to sync";
2104   }
2105
2106   push_ss(ss, status, tab) << "incremental sync: " << num_inc << "/" << total_shards << " shards";
2107
2108   rgw_datalog_info log_info;
2109   ret = sync.read_log_info(&log_info);
2110   if (ret < 0) {
2111     push_ss(ss, status, tab) << string("failed to fetch local sync status: ") + cpp_strerror(-ret);
2112     return;
2113   }
2114
2115
2116   map<int, RGWDataChangesLogInfo> source_shards_info;
2117
2118   ret = sync.read_source_log_shards_info(&source_shards_info);
2119   if (ret < 0) {
2120     push_ss(ss, status, tab) << string("failed to fetch source sync status: ") + cpp_strerror(-ret);
2121     return;
2122   }
2123
2124   map<int, string> shards_behind;
2125
2126   for (auto local_iter : sync_status.sync_markers) {
2127     int shard_id = local_iter.first;
2128     auto iter = source_shards_info.find(shard_id);
2129
2130     if (iter == source_shards_info.end()) {
2131       /* huh? */
2132       derr << "ERROR: could not find remote sync shard status for shard_id=" << shard_id << dendl;
2133       continue;
2134     }
2135     auto master_marker = iter->second.marker;
2136     if (local_iter.second.state == rgw_data_sync_marker::SyncState::IncrementalSync &&
2137         master_marker > local_iter.second.marker) {
2138       shards_behind[shard_id] = local_iter.second.marker;
2139     }
2140   }
2141
2142   int total_behind = shards_behind.size() + (sync_status.sync_info.num_shards - num_inc);
2143   if (total_behind == 0) {
2144     push_ss(ss, status, tab) << "data is caught up with source";
2145   } else {
2146     push_ss(ss, status, tab) << "data is behind on " << total_behind << " shards";
2147
2148     map<int, rgw_datalog_shard_data> master_pos;
2149     ret = sync.read_source_log_shards_next(shards_behind, &master_pos);
2150     if (ret < 0) {
2151       derr << "ERROR: failed to fetch next positions (" << cpp_strerror(-ret) << ")" << dendl;
2152     } else {
2153       ceph::real_time oldest;
2154       for (auto iter : master_pos) {
2155         rgw_datalog_shard_data& shard_data = iter.second;
2156
2157         if (!shard_data.entries.empty()) {
2158           rgw_datalog_entry& entry = shard_data.entries.front();
2159           if (ceph::real_clock::is_zero(oldest)) {
2160             oldest = entry.timestamp;
2161           } else if (!ceph::real_clock::is_zero(entry.timestamp) && entry.timestamp < oldest) {
2162             oldest = entry.timestamp;
2163           }
2164         }
2165       }
2166
2167       if (!ceph::real_clock::is_zero(oldest)) {
2168         push_ss(ss, status, tab) << "oldest incremental change not applied: " << oldest;
2169       }
2170     }
2171   }
2172
2173   flush_ss(ss, status);
2174 }
2175
2176 static void tab_dump(const string& header, int width, const list<string>& entries)
2177 {
2178   string s = header;
2179
2180   for (auto e : entries) {
2181     cout << std::setw(width) << s << std::setw(1) << " " << e << std::endl;
2182     s.clear();
2183   }
2184 }
2185
2186
2187 static void sync_status(Formatter *formatter)
2188 {
2189   RGWRealm& realm = store->realm;
2190   RGWZoneGroup& zonegroup = store->get_zonegroup();
2191   RGWZone& zone = store->get_zone();
2192
2193   int width = 15;
2194
2195   cout << std::setw(width) << "realm" << std::setw(1) << " " << realm.get_id() << " (" << realm.get_name() << ")" << std::endl;
2196   cout << std::setw(width) << "zonegroup" << std::setw(1) << " " << zonegroup.get_id() << " (" << zonegroup.get_name() << ")" << std::endl;
2197   cout << std::setw(width) << "zone" << std::setw(1) << " " << zone.id << " (" << zone.name << ")" << std::endl;
2198
2199   list<string> md_status;
2200
2201   if (store->is_meta_master()) {
2202     md_status.push_back("no sync (zone is master)");
2203   } else {
2204     get_md_sync_status(md_status);
2205   }
2206
2207   tab_dump("metadata sync", width, md_status);
2208
2209   list<string> data_status;
2210
2211   for (auto iter : store->zone_conn_map) {
2212     const string& source_id = iter.first;
2213     string source_str = "source: ";
2214     string s = source_str + source_id;
2215     auto siter = store->zone_by_id.find(source_id);
2216     if (siter != store->zone_by_id.end()) {
2217       s += string(" (") + siter->second.name + ")";
2218     }
2219     data_status.push_back(s);
2220     get_data_sync_status(source_id, data_status, source_str.size());
2221   }
2222
2223   tab_dump("data sync", width, data_status);
2224 }
2225
2226 static void parse_tier_config_param(const string& s, map<string, string, ltstr_nocase>& out)
2227 {
2228   list<string> confs;
2229   get_str_list(s, ",", confs);
2230   for (auto c : confs) {
2231     ssize_t pos = c.find("=");
2232     if (pos < 0) {
2233       out[c] = "";
2234     } else {
2235       out[c.substr(0, pos)] = c.substr(pos + 1);
2236     }
2237   }
2238 }
2239
2240 int check_reshard_bucket_params(RGWRados *store,
2241                                 const string& bucket_name,
2242                                 const string& tenant,
2243                                 const string& bucket_id,
2244                                 bool num_shards_specified,
2245                                 int num_shards,
2246                                 int yes_i_really_mean_it,
2247                                 rgw_bucket& bucket,
2248                                 RGWBucketInfo& bucket_info,
2249                                 map<string, bufferlist>& attrs)
2250 {
2251   if (bucket_name.empty()) {
2252     cerr << "ERROR: bucket not specified" << std::endl;
2253     return -EINVAL;
2254   }
2255
2256   if (!num_shards_specified) {
2257     cerr << "ERROR: --num-shards not specified" << std::endl;
2258     return -EINVAL;
2259   }
2260
2261   if (num_shards > (int)store->get_max_bucket_shards()) {
2262     cerr << "ERROR: num_shards too high, max value: " << store->get_max_bucket_shards() << std::endl;
2263     return -EINVAL;
2264   }
2265
2266   int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket, &attrs);
2267   if (ret < 0) {
2268     cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
2269     return -ret;
2270   }
2271
2272   int num_source_shards = (bucket_info.num_shards > 0 ? bucket_info.num_shards : 1);
2273
2274   if (num_shards <= num_source_shards && !yes_i_really_mean_it) {
2275     cerr << "num shards is less or equal to current shards count" << std::endl
2276          << "do you really mean it? (requires --yes-i-really-mean-it)" << std::endl;
2277     return -EINVAL;
2278   }
2279   return 0;
2280 }
2281
2282 int create_new_bucket_instance(RGWRados *store,
2283                                int new_num_shards,
2284                                const RGWBucketInfo& bucket_info,
2285                                map<string, bufferlist>& attrs,
2286                                RGWBucketInfo& new_bucket_info)
2287 {
2288
2289   store->create_bucket_id(&new_bucket_info.bucket.bucket_id);
2290   new_bucket_info.bucket.oid.clear();
2291
2292   new_bucket_info.num_shards = new_num_shards;
2293   new_bucket_info.objv_tracker.clear();
2294
2295   int ret = store->init_bucket_index(new_bucket_info, new_bucket_info.num_shards);
2296   if (ret < 0) {
2297     cerr << "ERROR: failed to init new bucket indexes: " << cpp_strerror(-ret) << std::endl;
2298     return -ret;
2299   }
2300
2301   ret = store->put_bucket_instance_info(new_bucket_info, true, real_time(), &attrs);
2302   if (ret < 0) {
2303     cerr << "ERROR: failed to store new bucket instance info: " << cpp_strerror(-ret) << std::endl;
2304     return -ret;
2305   }
2306
2307   return 0;
2308 }
2309
2310
2311 #ifdef BUILDING_FOR_EMBEDDED
2312 extern "C" int cephd_rgw_admin(int argc, const char **argv)
2313 #else
2314 int main(int argc, const char **argv)
2315 #endif
2316 {
2317   vector<const char*> args;
2318   argv_to_vec(argc, (const char **)argv, args);
2319   env_to_vec(args);
2320
2321   auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT,
2322                          CODE_ENVIRONMENT_UTILITY, 0);
2323
2324   // for region -> zonegroup conversion (must happen before common_init_finish())
2325   if (!g_conf->rgw_region.empty() && g_conf->rgw_zonegroup.empty()) {
2326     g_conf->set_val_or_die("rgw_zonegroup", g_conf->rgw_region.c_str());
2327   }
2328
2329   common_init_finish(g_ceph_context);
2330
2331   rgw_user user_id;
2332   string tenant;
2333   std::string access_key, secret_key, user_email, display_name;
2334   std::string bucket_name, pool_name, object;
2335   rgw_pool pool;
2336   std::string date, subuser, access, format;
2337   std::string start_date, end_date;
2338   std::string key_type_str;
2339   std::string period_id, period_epoch, remote, url;
2340   std::string master_zonegroup, master_zone;
2341   std::string realm_name, realm_id, realm_new_name;
2342   std::string zone_name, zone_id, zone_new_name;
2343   std::string zonegroup_name, zonegroup_id, zonegroup_new_name;
2344   std::string api_name;
2345   std::string role_name, path, assume_role_doc, policy_name, perm_policy_doc, path_prefix;
2346   list<string> endpoints;
2347   int tmp_int;
2348   int sync_from_all_specified = false;
2349   bool sync_from_all = false;
2350   list<string> sync_from;
2351   list<string> sync_from_rm;
2352   std::string master_url;
2353   int is_master_int;
2354   int set_default = 0;
2355   bool is_master = false;
2356   bool is_master_set = false;
2357   int read_only_int;
2358   bool read_only = false;
2359   int is_read_only_set = false;
2360   int commit = false;
2361   int staging = false;
2362   int key_type = KEY_TYPE_UNDEFINED;
2363   rgw_bucket bucket;
2364   uint32_t perm_mask = 0;
2365   RGWUserInfo info;
2366   int opt_cmd = OPT_NO_CMD;
2367   bool need_more;
2368   int gen_access_key = 0;
2369   int gen_secret_key = 0;
2370   bool set_perm = false;
2371   bool set_temp_url_key = false;
2372   map<int, string> temp_url_keys;
2373   string bucket_id;
2374   Formatter *formatter = NULL;
2375   int purge_data = false;
2376   int pretty_format = false;
2377   int show_log_entries = true;
2378   int show_log_sum = true;
2379   int skip_zero_entries = false;  // log show
2380   int purge_keys = false;
2381   int yes_i_really_mean_it = false;
2382   int delete_child_objects = false;
2383   int fix = false;
2384   int remove_bad = false;
2385   int check_head_obj_locator = false;
2386   int max_buckets = -1;
2387   bool max_buckets_specified = false;
2388   map<string, bool> categories;
2389   string caps;
2390   int check_objects = false;
2391   RGWUserAdminOpState user_op;
2392   RGWBucketAdminOpState bucket_op;
2393   string infile;
2394   string metadata_key;
2395   RGWObjVersionTracker objv_tracker;
2396   string marker;
2397   string start_marker;
2398   string end_marker;
2399   int max_entries = -1;
2400   bool max_entries_specified = false;
2401   int admin = false;
2402   bool admin_specified = false;
2403   int system = false;
2404   bool system_specified = false;
2405   int shard_id = -1;
2406   bool specified_shard_id = false;
2407   string daemon_id;
2408   bool specified_daemon_id = false;
2409   string client_id;
2410   string op_id;
2411   string state_str;
2412   string replica_log_type_str;
2413   ReplicaLogType replica_log_type = ReplicaLog_Invalid;
2414   string op_mask_str;
2415   string quota_scope;
2416   string object_version;
2417   string placement_id;
2418   list<string> tags;
2419   list<string> tags_add;
2420   list<string> tags_rm;
2421
2422   int64_t max_objects = -1;
2423   int64_t max_size = -1;
2424   bool have_max_objects = false;
2425   bool have_max_size = false;
2426   int include_all = false;
2427
2428   int sync_stats = false;
2429   int bypass_gc = false;
2430   int warnings_only = false;
2431   int inconsistent_index = false;
2432
2433   int verbose = false;
2434
2435   int extra_info = false;
2436
2437   uint64_t min_rewrite_size = 4 * 1024 * 1024;
2438   uint64_t max_rewrite_size = ULLONG_MAX;
2439   uint64_t min_rewrite_stripe_size = 0;
2440
2441   BIIndexType bi_index_type = PlainIdx;
2442
2443   string job_id;
2444   int num_shards = 0;
2445   bool num_shards_specified = false;
2446   int max_concurrent_ios = 32;
2447   uint64_t orphan_stale_secs = (24 * 3600);
2448
2449   std::string val;
2450   std::ostringstream errs;
2451   string err;
2452   long long tmp = 0;
2453
2454   string source_zone_name;
2455   string source_zone; /* zone id */
2456
2457   string tier_type;
2458   bool tier_type_specified = false;
2459
2460   map<string, string, ltstr_nocase> tier_config_add;
2461   map<string, string, ltstr_nocase> tier_config_rm;
2462
2463   boost::optional<string> index_pool;
2464   boost::optional<string> data_pool;
2465   boost::optional<string> data_extra_pool;
2466   RGWBucketIndexType placement_index_type = RGWBIType_Normal;
2467   bool index_type_specified = false;
2468
2469   boost::optional<std::string> compression_type;
2470
2471   for (std::vector<const char*>::iterator i = args.begin(); i != args.end(); ) {
2472     if (ceph_argparse_double_dash(args, i)) {
2473       break;
2474     } else if (ceph_argparse_flag(args, i, "-h", "--help", (char*)NULL)) {
2475       usage();
2476       assert(false);
2477     } else if (ceph_argparse_witharg(args, i, &val, "-i", "--uid", (char*)NULL)) {
2478       user_id.from_str(val);
2479     } else if (ceph_argparse_witharg(args, i, &val, "--tenant", (char*)NULL)) {
2480       tenant = val;
2481     } else if (ceph_argparse_witharg(args, i, &val, "--access-key", (char*)NULL)) {
2482       access_key = val;
2483     } else if (ceph_argparse_witharg(args, i, &val, "--subuser", (char*)NULL)) {
2484       subuser = val;
2485     } else if (ceph_argparse_witharg(args, i, &val, "--secret", "--secret-key", (char*)NULL)) {
2486       secret_key = val;
2487     } else if (ceph_argparse_witharg(args, i, &val, "-e", "--email", (char*)NULL)) {
2488       user_email = val;
2489       user_op.user_email_specified=true;
2490     } else if (ceph_argparse_witharg(args, i, &val, "-n", "--display-name", (char*)NULL)) {
2491       display_name = val;
2492     } else if (ceph_argparse_witharg(args, i, &val, "-b", "--bucket", (char*)NULL)) {
2493       bucket_name = val;
2494     } else if (ceph_argparse_witharg(args, i, &val, "-p", "--pool", (char*)NULL)) {
2495       pool_name = val;
2496       pool = rgw_pool(pool_name);
2497     } else if (ceph_argparse_witharg(args, i, &val, "-o", "--object", (char*)NULL)) {
2498       object = val;
2499     } else if (ceph_argparse_witharg(args, i, &val, "--object-version", (char*)NULL)) {
2500       object_version = val;
2501     } else if (ceph_argparse_witharg(args, i, &val, "--client-id", (char*)NULL)) {
2502       client_id = val;
2503     } else if (ceph_argparse_witharg(args, i, &val, "--op-id", (char*)NULL)) {
2504       op_id = val;
2505     } else if (ceph_argparse_witharg(args, i, &val, "--state", (char*)NULL)) {
2506       state_str = val;
2507     } else if (ceph_argparse_witharg(args, i, &val, "--op-mask", (char*)NULL)) {
2508       op_mask_str = val;
2509     } else if (ceph_argparse_witharg(args, i, &val, "--key-type", (char*)NULL)) {
2510       key_type_str = val;
2511       if (key_type_str.compare("swift") == 0) {
2512         key_type = KEY_TYPE_SWIFT;
2513       } else if (key_type_str.compare("s3") == 0) {
2514         key_type = KEY_TYPE_S3;
2515       } else {
2516         cerr << "bad key type: " << key_type_str << std::endl;
2517         usage();
2518         assert(false);
2519       }
2520     } else if (ceph_argparse_witharg(args, i, &val, "--job-id", (char*)NULL)) {
2521       job_id = val;
2522     } else if (ceph_argparse_binary_flag(args, i, &gen_access_key, NULL, "--gen-access-key", (char*)NULL)) {
2523       // do nothing
2524     } else if (ceph_argparse_binary_flag(args, i, &gen_secret_key, NULL, "--gen-secret", (char*)NULL)) {
2525       // do nothing
2526     } else if (ceph_argparse_binary_flag(args, i, &show_log_entries, NULL, "--show_log_entries", (char*)NULL)) {
2527       // do nothing
2528     } else if (ceph_argparse_binary_flag(args, i, &show_log_sum, NULL, "--show_log_sum", (char*)NULL)) {
2529       // do nothing
2530     } else if (ceph_argparse_binary_flag(args, i, &skip_zero_entries, NULL, "--skip_zero_entries", (char*)NULL)) {
2531       // do nothing
2532     } else if (ceph_argparse_binary_flag(args, i, &admin, NULL, "--admin", (char*)NULL)) {
2533       admin_specified = true;
2534     } else if (ceph_argparse_binary_flag(args, i, &system, NULL, "--system", (char*)NULL)) {
2535       system_specified = true;
2536     } else if (ceph_argparse_binary_flag(args, i, &verbose, NULL, "--verbose", (char*)NULL)) {
2537       // do nothing
2538     } else if (ceph_argparse_binary_flag(args, i, &staging, NULL, "--staging", (char*)NULL)) {
2539       // do nothing
2540     } else if (ceph_argparse_binary_flag(args, i, &commit, NULL, "--commit", (char*)NULL)) {
2541       // do nothing
2542     } else if (ceph_argparse_witharg(args, i, &tmp, errs, "-a", "--auth-uid", (char*)NULL)) {
2543       if (!errs.str().empty()) {
2544         cerr << errs.str() << std::endl;
2545         exit(EXIT_FAILURE);
2546       }
2547     } else if (ceph_argparse_witharg(args, i, &val, "--min-rewrite-size", (char*)NULL)) {
2548       min_rewrite_size = (uint64_t)atoll(val.c_str());
2549     } else if (ceph_argparse_witharg(args, i, &val, "--max-rewrite-size", (char*)NULL)) {
2550       max_rewrite_size = (uint64_t)atoll(val.c_str());
2551     } else if (ceph_argparse_witharg(args, i, &val, "--min-rewrite-stripe-size", (char*)NULL)) {
2552       min_rewrite_stripe_size = (uint64_t)atoll(val.c_str());
2553     } else if (ceph_argparse_witharg(args, i, &val, "--max-buckets", (char*)NULL)) {
2554       max_buckets = (int)strict_strtol(val.c_str(), 10, &err);
2555       if (!err.empty()) {
2556         cerr << "ERROR: failed to parse max buckets: " << err << std::endl;
2557         return EINVAL;
2558       }
2559       max_buckets_specified = true;
2560     } else if (ceph_argparse_witharg(args, i, &val, "--max-entries", (char*)NULL)) {
2561       max_entries = (int)strict_strtol(val.c_str(), 10, &err);
2562       max_entries_specified = true;
2563       if (!err.empty()) {
2564         cerr << "ERROR: failed to parse max entries: " << err << std::endl;
2565         return EINVAL;
2566       }
2567     } else if (ceph_argparse_witharg(args, i, &val, "--max-size", (char*)NULL)) {
2568       max_size = strict_si_cast<int64_t>(val.c_str(), &err);
2569       if (!err.empty()) {
2570         cerr << "ERROR: failed to parse max size: " << err << std::endl;
2571         return EINVAL;
2572       }
2573       have_max_size = true;
2574     } else if (ceph_argparse_witharg(args, i, &val, "--max-objects", (char*)NULL)) {
2575       max_objects = (int64_t)strict_strtoll(val.c_str(), 10, &err);
2576       if (!err.empty()) {
2577         cerr << "ERROR: failed to parse max objects: " << err << std::endl;
2578         return EINVAL;
2579       }
2580       have_max_objects = true;
2581     } else if (ceph_argparse_witharg(args, i, &val, "--date", "--time", (char*)NULL)) {
2582       date = val;
2583       if (end_date.empty())
2584         end_date = date;
2585     } else if (ceph_argparse_witharg(args, i, &val, "--start-date", "--start-time", (char*)NULL)) {
2586       start_date = val;
2587     } else if (ceph_argparse_witharg(args, i, &val, "--end-date", "--end-time", (char*)NULL)) {
2588       end_date = val;
2589     } else if (ceph_argparse_witharg(args, i, &val, "--num-shards", (char*)NULL)) {
2590       num_shards = (int)strict_strtol(val.c_str(), 10, &err);
2591       if (!err.empty()) {
2592         cerr << "ERROR: failed to parse num shards: " << err << std::endl;
2593         return EINVAL;
2594       }
2595       num_shards_specified = true;
2596     } else if (ceph_argparse_witharg(args, i, &val, "--max-concurrent-ios", (char*)NULL)) {
2597       max_concurrent_ios = (int)strict_strtol(val.c_str(), 10, &err);
2598       if (!err.empty()) {
2599         cerr << "ERROR: failed to parse max concurrent ios: " << err << std::endl;
2600         return EINVAL;
2601       }
2602     } else if (ceph_argparse_witharg(args, i, &val, "--orphan-stale-secs", (char*)NULL)) {
2603       orphan_stale_secs = (uint64_t)strict_strtoll(val.c_str(), 10, &err);
2604       if (!err.empty()) {
2605         cerr << "ERROR: failed to parse orphan stale secs: " << err << std::endl;
2606         return EINVAL;
2607       }
2608     } else if (ceph_argparse_witharg(args, i, &val, "--shard-id", (char*)NULL)) {
2609       shard_id = (int)strict_strtol(val.c_str(), 10, &err);
2610       if (!err.empty()) {
2611         cerr << "ERROR: failed to parse shard id: " << err << std::endl;
2612         return EINVAL;
2613       }
2614       specified_shard_id = true;
2615     } else if (ceph_argparse_witharg(args, i, &val, "--daemon-id", (char*)NULL)) {
2616       daemon_id = val;
2617       specified_daemon_id = true;
2618     } else if (ceph_argparse_witharg(args, i, &val, "--access", (char*)NULL)) {
2619       access = val;
2620       perm_mask = rgw_str_to_perm(access.c_str());
2621       set_perm = true;
2622     } else if (ceph_argparse_witharg(args, i, &val, "--temp-url-key", (char*)NULL)) {
2623       temp_url_keys[0] = val;
2624       set_temp_url_key = true;
2625     } else if (ceph_argparse_witharg(args, i, &val, "--temp-url-key2", "--temp-url-key-2", (char*)NULL)) {
2626       temp_url_keys[1] = val;
2627       set_temp_url_key = true;
2628     } else if (ceph_argparse_witharg(args, i, &val, "--bucket-id", (char*)NULL)) {
2629       bucket_id = val;
2630       if (bucket_id.empty()) {
2631         cerr << "bad bucket-id" << std::endl;
2632         usage();
2633         assert(false);
2634       }
2635     } else if (ceph_argparse_witharg(args, i, &val, "--format", (char*)NULL)) {
2636       format = val;
2637     } else if (ceph_argparse_witharg(args, i, &val, "--categories", (char*)NULL)) {
2638       string cat_str = val;
2639       list<string> cat_list;
2640       list<string>::iterator iter;
2641       get_str_list(cat_str, cat_list);
2642       for (iter = cat_list.begin(); iter != cat_list.end(); ++iter) {
2643         categories[*iter] = true;
2644       }
2645     } else if (ceph_argparse_binary_flag(args, i, &delete_child_objects, NULL, "--purge-objects", (char*)NULL)) {
2646       // do nothing
2647     } else if (ceph_argparse_binary_flag(args, i, &pretty_format, NULL, "--pretty-format", (char*)NULL)) {
2648       // do nothing
2649     } else if (ceph_argparse_binary_flag(args, i, &purge_data, NULL, "--purge-data", (char*)NULL)) {
2650       delete_child_objects = purge_data;
2651     } else if (ceph_argparse_binary_flag(args, i, &purge_keys, NULL, "--purge-keys", (char*)NULL)) {
2652       // do nothing
2653     } else if (ceph_argparse_binary_flag(args, i, &yes_i_really_mean_it, NULL, "--yes-i-really-mean-it", (char*)NULL)) {
2654       // do nothing
2655     } else if (ceph_argparse_binary_flag(args, i, &fix, NULL, "--fix", (char*)NULL)) {
2656       // do nothing
2657     } else if (ceph_argparse_binary_flag(args, i, &remove_bad, NULL, "--remove-bad", (char*)NULL)) {
2658       // do nothing
2659     } else if (ceph_argparse_binary_flag(args, i, &check_head_obj_locator, NULL, "--check-head-obj-locator", (char*)NULL)) {
2660       // do nothing
2661     } else if (ceph_argparse_binary_flag(args, i, &check_objects, NULL, "--check-objects", (char*)NULL)) {
2662      // do nothing
2663     } else if (ceph_argparse_binary_flag(args, i, &sync_stats, NULL, "--sync-stats", (char*)NULL)) {
2664      // do nothing
2665     } else if (ceph_argparse_binary_flag(args, i, &include_all, NULL, "--include-all", (char*)NULL)) {
2666      // do nothing
2667     } else if (ceph_argparse_binary_flag(args, i, &extra_info, NULL, "--extra-info", (char*)NULL)) {
2668      // do nothing
2669     } else if (ceph_argparse_binary_flag(args, i, &bypass_gc, NULL, "--bypass-gc", (char*)NULL)) {
2670      // do nothing
2671     } else if (ceph_argparse_binary_flag(args, i, &warnings_only, NULL, "--warnings-only", (char*)NULL)) {
2672      // do nothing
2673     } else if (ceph_argparse_binary_flag(args, i, &inconsistent_index, NULL, "--inconsistent-index", (char*)NULL)) {
2674      // do nothing
2675     } else if (ceph_argparse_witharg(args, i, &val, "--caps", (char*)NULL)) {
2676       caps = val;
2677     } else if (ceph_argparse_witharg(args, i, &val, "-i", "--infile", (char*)NULL)) {
2678       infile = val;
2679     } else if (ceph_argparse_witharg(args, i, &val, "--metadata-key", (char*)NULL)) {
2680       metadata_key = val;
2681     } else if (ceph_argparse_witharg(args, i, &val, "--marker", (char*)NULL)) {
2682       marker = val;
2683     } else if (ceph_argparse_witharg(args, i, &val, "--start-marker", (char*)NULL)) {
2684       start_marker = val;
2685     } else if (ceph_argparse_witharg(args, i, &val, "--end-marker", (char*)NULL)) {
2686       end_marker = val;
2687     } else if (ceph_argparse_witharg(args, i, &val, "--quota-scope", (char*)NULL)) {
2688       quota_scope = val;
2689     } else if (ceph_argparse_witharg(args, i, &val, "--replica-log-type", (char*)NULL)) {
2690       replica_log_type_str = val;
2691       replica_log_type = get_replicalog_type(replica_log_type_str);
2692       if (replica_log_type == ReplicaLog_Invalid) {
2693         cerr << "ERROR: invalid replica log type" << std::endl;
2694         return EINVAL;
2695       }
2696     } else if (ceph_argparse_witharg(args, i, &val, "--index-type", (char*)NULL)) {
2697       string index_type_str = val;
2698       bi_index_type = get_bi_index_type(index_type_str);
2699       if (bi_index_type == InvalidIdx) {
2700         cerr << "ERROR: invalid bucket index entry type" << std::endl;
2701         return EINVAL;
2702       }
2703     } else if (ceph_argparse_binary_flag(args, i, &is_master_int, NULL, "--master", (char*)NULL)) {
2704       is_master = (bool)is_master_int;
2705       is_master_set = true;
2706     } else if (ceph_argparse_binary_flag(args, i, &set_default, NULL, "--default", (char*)NULL)) {
2707       /* do nothing */
2708     } else if (ceph_argparse_binary_flag(args, i, &read_only_int, NULL, "--read-only", (char*)NULL)) {
2709       read_only = (bool)read_only_int;
2710       is_read_only_set = true;
2711     } else if (ceph_argparse_witharg(args, i, &val, "--master-url", (char*)NULL)) {
2712       master_url = val;
2713     } else if (ceph_argparse_witharg(args, i, &val, "--master-zonegroup", (char*)NULL)) {
2714       master_zonegroup = val;
2715     } else if (ceph_argparse_witharg(args, i, &val, "--master-zone", (char*)NULL)) {
2716       master_zone = val;
2717     } else if (ceph_argparse_witharg(args, i, &val, "--period", (char*)NULL)) {
2718       period_id = val;
2719     } else if (ceph_argparse_witharg(args, i, &val, "--epoch", (char*)NULL)) {
2720       period_epoch = val;
2721     } else if (ceph_argparse_witharg(args, i, &val, "--remote", (char*)NULL)) {
2722       remote = val;
2723     } else if (ceph_argparse_witharg(args, i, &val, "--url", (char*)NULL)) {
2724       url = val;
2725     } else if (ceph_argparse_witharg(args, i, &val, "--realm-id", (char*)NULL)) {
2726       realm_id = val;
2727     } else if (ceph_argparse_witharg(args, i, &val, "--realm-new-name", (char*)NULL)) {
2728       realm_new_name = val;
2729     } else if (ceph_argparse_witharg(args, i, &val, "--zonegroup-id", (char*)NULL)) {
2730       zonegroup_id = val;
2731     } else if (ceph_argparse_witharg(args, i, &val, "--zonegroup-new-name", (char*)NULL)) {
2732       zonegroup_new_name = val;
2733     } else if (ceph_argparse_witharg(args, i, &val, "--placement-id", (char*)NULL)) {
2734       placement_id = val;
2735     } else if (ceph_argparse_witharg(args, i, &val, "--tags", (char*)NULL)) {
2736       get_str_list(val, tags);
2737     } else if (ceph_argparse_witharg(args, i, &val, "--tags-add", (char*)NULL)) {
2738       get_str_list(val, tags_add);
2739     } else if (ceph_argparse_witharg(args, i, &val, "--tags-rm", (char*)NULL)) {
2740       get_str_list(val, tags_rm);
2741     } else if (ceph_argparse_witharg(args, i, &val, "--api-name", (char*)NULL)) {
2742       api_name = val;
2743     } else if (ceph_argparse_witharg(args, i, &val, "--zone-id", (char*)NULL)) {
2744       zone_id = val;
2745     } else if (ceph_argparse_witharg(args, i, &val, "--zone-new-name", (char*)NULL)) {
2746       zone_new_name = val;
2747     } else if (ceph_argparse_witharg(args, i, &val, "--endpoints", (char*)NULL)) {
2748       get_str_list(val, endpoints);
2749     } else if (ceph_argparse_witharg(args, i, &val, "--sync-from", (char*)NULL)) {
2750       get_str_list(val, sync_from);
2751     } else if (ceph_argparse_witharg(args, i, &val, "--sync-from-rm", (char*)NULL)) {
2752       get_str_list(val, sync_from_rm);
2753     } else if (ceph_argparse_binary_flag(args, i, &tmp_int, NULL, "--sync-from-all", (char*)NULL)) {
2754       sync_from_all = (bool)tmp_int;
2755       sync_from_all_specified = true;
2756     } else if (ceph_argparse_witharg(args, i, &val, "--source-zone", (char*)NULL)) {
2757       source_zone_name = val;
2758     } else if (ceph_argparse_witharg(args, i, &val, "--tier-type", (char*)NULL)) {
2759       tier_type = val;
2760       tier_type_specified = true;
2761     } else if (ceph_argparse_witharg(args, i, &val, "--tier-config", (char*)NULL)) {
2762       parse_tier_config_param(val, tier_config_add);
2763     } else if (ceph_argparse_witharg(args, i, &val, "--tier-config-rm", (char*)NULL)) {
2764       parse_tier_config_param(val, tier_config_rm);
2765     } else if (ceph_argparse_witharg(args, i, &val, "--index-pool", (char*)NULL)) {
2766       index_pool = val;
2767     } else if (ceph_argparse_witharg(args, i, &val, "--data-pool", (char*)NULL)) {
2768       data_pool = val;
2769     } else if (ceph_argparse_witharg(args, i, &val, "--data-extra-pool", (char*)NULL)) {
2770       data_extra_pool = val;
2771     } else if (ceph_argparse_witharg(args, i, &val, "--placement-index-type", (char*)NULL)) {
2772       if (val == "normal") {
2773         placement_index_type = RGWBIType_Normal;
2774       } else if (val == "indexless") {
2775         placement_index_type = RGWBIType_Indexless;
2776       } else {
2777         placement_index_type = (RGWBucketIndexType)strict_strtol(val.c_str(), 10, &err);
2778         if (!err.empty()) {
2779           cerr << "ERROR: failed to parse index type index: " << err << std::endl;
2780           return EINVAL;
2781         }
2782       }
2783       index_type_specified = true;
2784     } else if (ceph_argparse_witharg(args, i, &val, "--compression", (char*)NULL)) {
2785       compression_type = val;
2786     } else if (ceph_argparse_witharg(args, i, &val, "--role-name", (char*)NULL)) {
2787       role_name = val;
2788     } else if (ceph_argparse_witharg(args, i, &val, "--path", (char*)NULL)) {
2789       path = val;
2790     } else if (ceph_argparse_witharg(args, i, &val, "--assume-role-policy-doc", (char*)NULL)) {
2791       assume_role_doc = val;
2792     } else if (ceph_argparse_witharg(args, i, &val, "--policy-name", (char*)NULL)) {
2793       policy_name = val;
2794     } else if (ceph_argparse_witharg(args, i, &val, "--policy-doc", (char*)NULL)) {
2795       perm_policy_doc = val;
2796     } else if (ceph_argparse_witharg(args, i, &val, "--path-prefix", (char*)NULL)) {
2797       path_prefix = val;
2798     } else if (strncmp(*i, "-", 1) == 0) {
2799       cerr << "ERROR: invalid flag " << *i << std::endl;
2800       return EINVAL;
2801     } else {
2802       ++i;
2803     }
2804   }
2805
2806   if (args.empty()) {
2807     usage();
2808     assert(false);
2809   }
2810   else {
2811     const char *prev_cmd = NULL;
2812     const char *prev_prev_cmd = NULL;
2813     std::vector<const char*>::iterator i ;
2814     for (i = args.begin(); i != args.end(); ++i) {
2815       opt_cmd = get_cmd(*i, prev_cmd, prev_prev_cmd, &need_more);
2816       if (opt_cmd < 0) {
2817         cerr << "unrecognized arg " << *i << std::endl;
2818         usage();
2819         assert(false);
2820       }
2821       if (!need_more) {
2822         ++i;
2823         break;
2824       }
2825       prev_prev_cmd = prev_cmd;
2826       prev_cmd = *i;
2827     }
2828
2829     if (opt_cmd == OPT_NO_CMD) {
2830       usage();
2831       assert(false);
2832     }
2833
2834     /* some commands may have an optional extra param */
2835     if (i != args.end()) {
2836       switch (opt_cmd) {
2837         case OPT_METADATA_GET:
2838         case OPT_METADATA_PUT:
2839         case OPT_METADATA_RM:
2840         case OPT_METADATA_LIST:
2841           metadata_key = *i;
2842           break;
2843         default:
2844           break;
2845       }
2846     }
2847
2848     if (tenant.empty()) {
2849       tenant = user_id.tenant;
2850     } else {
2851       if (user_id.empty() && opt_cmd != OPT_ROLE_CREATE
2852                           && opt_cmd != OPT_ROLE_DELETE
2853                           && opt_cmd != OPT_ROLE_GET
2854                           && opt_cmd != OPT_ROLE_MODIFY
2855                           && opt_cmd != OPT_ROLE_LIST
2856                           && opt_cmd != OPT_ROLE_POLICY_PUT
2857                           && opt_cmd != OPT_ROLE_POLICY_LIST
2858                           && opt_cmd != OPT_ROLE_POLICY_GET
2859                           && opt_cmd != OPT_ROLE_POLICY_DELETE) {
2860         cerr << "ERROR: --tenant is set, but there's no user ID" << std::endl;
2861         return EINVAL;
2862       }
2863       user_id.tenant = tenant;
2864     }
2865     /* check key parameter conflict */
2866     if ((!access_key.empty()) && gen_access_key) {
2867         cerr << "ERROR: key parameter conflict, --access-key & --gen-access-key" << std::endl;
2868         return EINVAL;
2869     }
2870     if ((!secret_key.empty()) && gen_secret_key) {
2871         cerr << "ERROR: key parameter conflict, --secret & --gen-secret" << std::endl;
2872         return EINVAL;
2873     }
2874   }
2875
2876   // default to pretty json
2877   if (format.empty()) {
2878     format = "json";
2879     pretty_format = true;
2880   }
2881
2882   if (format ==  "xml")
2883     formatter = new XMLFormatter(pretty_format);
2884   else if (format == "json")
2885     formatter = new JSONFormatter(pretty_format);
2886   else {
2887     cerr << "unrecognized format: " << format << std::endl;
2888     usage();
2889     assert(false);
2890   }
2891
2892   realm_name = g_conf->rgw_realm;
2893   zone_name = g_conf->rgw_zone;
2894   zonegroup_name = g_conf->rgw_zonegroup;
2895
2896   RGWStreamFlusher f(formatter, cout);
2897
2898   // not a raw op if 'period update' needs to commit to master
2899   bool raw_period_update = opt_cmd == OPT_PERIOD_UPDATE && !commit;
2900   std::set<int> raw_storage_ops_list = {OPT_ZONEGROUP_ADD, OPT_ZONEGROUP_CREATE, OPT_ZONEGROUP_DELETE,
2901                          OPT_ZONEGROUP_GET, OPT_ZONEGROUP_LIST,
2902                          OPT_ZONEGROUP_SET, OPT_ZONEGROUP_DEFAULT,
2903                          OPT_ZONEGROUP_RENAME, OPT_ZONEGROUP_MODIFY,
2904                          OPT_ZONEGROUP_REMOVE,
2905                          OPT_ZONEGROUP_PLACEMENT_ADD, OPT_ZONEGROUP_PLACEMENT_RM,
2906                          OPT_ZONEGROUP_PLACEMENT_MODIFY, OPT_ZONEGROUP_PLACEMENT_LIST,
2907                          OPT_ZONEGROUP_PLACEMENT_DEFAULT,
2908                          OPT_ZONE_CREATE, OPT_ZONE_DELETE,
2909                          OPT_ZONE_GET, OPT_ZONE_SET, OPT_ZONE_RENAME,
2910                          OPT_ZONE_LIST, OPT_ZONE_MODIFY, OPT_ZONE_DEFAULT,
2911                          OPT_ZONE_PLACEMENT_ADD, OPT_ZONE_PLACEMENT_RM,
2912                          OPT_ZONE_PLACEMENT_MODIFY, OPT_ZONE_PLACEMENT_LIST,
2913                          OPT_REALM_CREATE,
2914                          OPT_PERIOD_DELETE, OPT_PERIOD_GET,
2915                          OPT_PERIOD_PULL,
2916                          OPT_PERIOD_GET_CURRENT, OPT_PERIOD_LIST,
2917                          OPT_GLOBAL_QUOTA_GET, OPT_GLOBAL_QUOTA_SET,
2918                          OPT_GLOBAL_QUOTA_ENABLE, OPT_GLOBAL_QUOTA_DISABLE,
2919                          OPT_REALM_DELETE, OPT_REALM_GET, OPT_REALM_LIST,
2920                          OPT_REALM_LIST_PERIODS,
2921                          OPT_REALM_GET_DEFAULT, OPT_REALM_REMOVE,
2922                          OPT_REALM_RENAME, OPT_REALM_SET,
2923                          OPT_REALM_DEFAULT, OPT_REALM_PULL};
2924
2925
2926   bool raw_storage_op = (raw_storage_ops_list.find(opt_cmd) != raw_storage_ops_list.end() ||
2927                          raw_period_update);
2928
2929   if (raw_storage_op) {
2930     store = RGWStoreManager::get_raw_storage(g_ceph_context);
2931   } else {
2932     store = RGWStoreManager::get_storage(g_ceph_context, false, false, false, false, false);
2933   }
2934   if (!store) {
2935     cerr << "couldn't init storage provider" << std::endl;
2936     return 5; //EIO
2937   }
2938
2939   if (!source_zone_name.empty()) {
2940     if (!store->find_zone_id_by_name(source_zone_name, &source_zone)) {
2941       cerr << "WARNING: cannot find source zone id for name=" << source_zone_name << std::endl;
2942       source_zone = source_zone_name;
2943     }
2944   }
2945
2946   rgw_user_init(store);
2947   rgw_bucket_init(store->meta_mgr);
2948
2949   StoreDestructor store_destructor(store);
2950
2951   if (raw_storage_op) {
2952     switch (opt_cmd) {
2953     case OPT_PERIOD_DELETE:
2954       {
2955         if (period_id.empty()) {
2956           cerr << "missing period id" << std::endl;
2957           return EINVAL;
2958         }
2959         RGWPeriod period(period_id);
2960         int ret = period.init(g_ceph_context, store);
2961         if (ret < 0) {
2962           cerr << "period.init failed: " << cpp_strerror(-ret) << std::endl;
2963           return -ret;
2964         }
2965         ret = period.delete_obj();
2966         if (ret < 0) {
2967           cerr << "ERROR: couldn't delete period: " << cpp_strerror(-ret) << std::endl;
2968           return -ret;
2969         }
2970
2971       }
2972       break;
2973     case OPT_PERIOD_GET:
2974       {
2975         epoch_t epoch = 0;
2976         if (!period_epoch.empty()) {
2977           epoch = atoi(period_epoch.c_str());
2978         }
2979         if (staging) {
2980           RGWRealm realm(realm_id, realm_name);
2981           int ret = realm.init(g_ceph_context, store);
2982           if (ret < 0 ) {
2983             cerr << "Error initializing realm " << cpp_strerror(-ret) << std::endl;
2984             return -ret;
2985           }
2986           realm_id = realm.get_id();
2987           realm_name = realm.get_name();
2988           period_id = RGWPeriod::get_staging_id(realm_id);
2989           epoch = 1;
2990         }
2991         RGWPeriod period(period_id, epoch);
2992         int ret = period.init(g_ceph_context, store, realm_id, realm_name);
2993         if (ret < 0) {
2994           cerr << "period init failed: " << cpp_strerror(-ret) << std::endl;
2995           return -ret;
2996         }
2997         encode_json("period", period, formatter);
2998         formatter->flush(cout);
2999         cout << std::endl;
3000       }
3001       break;
3002     case OPT_PERIOD_GET_CURRENT:
3003       {
3004         int ret = read_current_period_id(store, realm_id, realm_name, &period_id);
3005         if (ret < 0) {
3006           return -ret;
3007         }
3008         formatter->open_object_section("period_get_current");
3009         encode_json("current_period", period_id, formatter);
3010         formatter->close_section();
3011         formatter->flush(cout);
3012       }
3013       break;
3014     case OPT_PERIOD_LIST:
3015       {
3016         list<string> periods;
3017         int ret = store->list_periods(periods);
3018         if (ret < 0) {
3019           cerr << "failed to list periods: " << cpp_strerror(-ret) << std::endl;
3020           return -ret;
3021         }
3022         formatter->open_object_section("periods_list");
3023         encode_json("periods", periods, formatter);
3024         formatter->close_section();
3025         formatter->flush(cout);
3026         cout << std::endl;
3027       }
3028       break;
3029     case OPT_PERIOD_UPDATE:
3030       {
3031         int ret = update_period(realm_id, realm_name, period_id, period_epoch,
3032                                 commit, remote, url, access_key, secret_key,
3033                                 formatter, yes_i_really_mean_it);
3034         if (ret < 0) {
3035           return -ret;
3036         }
3037       }
3038       break;
3039     case OPT_PERIOD_PULL:
3040       {
3041         boost::optional<RGWRESTConn> conn;
3042         RGWRESTConn *remote_conn = nullptr;
3043         if (url.empty()) {
3044           // load current period for endpoints
3045           RGWRealm realm(realm_id, realm_name);
3046           int ret = realm.init(g_ceph_context, store);
3047           if (ret < 0) {
3048             cerr << "failed to init realm: " << cpp_strerror(-ret) << std::endl;
3049             return -ret;
3050           }
3051           RGWPeriod current_period(realm.get_current_period());
3052           ret = current_period.init(g_ceph_context, store);
3053           if (ret < 0) {
3054             cerr << "failed to init current period: " << cpp_strerror(-ret) << std::endl;
3055             return -ret;
3056           }
3057           if (remote.empty()) {
3058             // use realm master zone as remote
3059             remote = current_period.get_master_zone();
3060           }
3061           conn = get_remote_conn(store, current_period.get_map(), remote);
3062           if (!conn) {
3063             cerr << "failed to find a zone or zonegroup for remote "
3064                 << remote << std::endl;
3065             return -ENOENT;
3066           }
3067           remote_conn = &*conn;
3068         }
3069
3070         RGWPeriod period;
3071         int ret = do_period_pull(remote_conn, url, access_key, secret_key,
3072                                  realm_id, realm_name, period_id, period_epoch,
3073                                  &period);
3074         if (ret < 0) {
3075           cerr << "period pull failed: " << cpp_strerror(-ret) << std::endl;
3076           return -ret;
3077         }
3078
3079         encode_json("period", period, formatter);
3080         formatter->flush(cout);
3081         cout << std::endl;
3082       }
3083       break;
3084     case OPT_GLOBAL_QUOTA_GET:
3085     case OPT_GLOBAL_QUOTA_SET:
3086     case OPT_GLOBAL_QUOTA_ENABLE:
3087     case OPT_GLOBAL_QUOTA_DISABLE:
3088       {
3089         if (realm_id.empty()) {
3090           RGWRealm realm(g_ceph_context, store);
3091           if (!realm_name.empty()) {
3092             // look up realm_id for the given realm_name
3093             int ret = realm.read_id(realm_name, realm_id);
3094             if (ret < 0) {
3095               cerr << "ERROR: failed to read realm for " << realm_name
3096                   << ": " << cpp_strerror(-ret) << std::endl;
3097               return -ret;
3098             }
3099           } else {
3100             // use default realm_id when none is given
3101             int ret = realm.read_default_id(realm_id);
3102             if (ret < 0 && ret != -ENOENT) { // on ENOENT, use empty realm_id
3103               cerr << "ERROR: failed to read default realm: "
3104                   << cpp_strerror(-ret) << std::endl;
3105               return -ret;
3106             }
3107           }
3108         }
3109
3110         RGWPeriodConfig period_config;
3111         int ret = period_config.read(store, realm_id);
3112         if (ret < 0 && ret != -ENOENT) {
3113           cerr << "ERROR: failed to read period config: "
3114               << cpp_strerror(-ret) << std::endl;
3115           return -ret;
3116         }
3117
3118         formatter->open_object_section("period_config");
3119         if (quota_scope == "bucket") {
3120           set_quota_info(period_config.bucket_quota, opt_cmd,
3121                          max_size, max_objects,
3122                          have_max_size, have_max_objects);
3123           encode_json("bucket quota", period_config.bucket_quota, formatter);
3124         } else if (quota_scope == "user") {
3125           set_quota_info(period_config.user_quota, opt_cmd,
3126                          max_size, max_objects,
3127                          have_max_size, have_max_objects);
3128           encode_json("user quota", period_config.user_quota, formatter);
3129         } else if (quota_scope.empty() && opt_cmd == OPT_GLOBAL_QUOTA_GET) {
3130           // if no scope is given for GET, print both
3131           encode_json("bucket quota", period_config.bucket_quota, formatter);
3132           encode_json("user quota", period_config.user_quota, formatter);
3133         } else {
3134           cerr << "ERROR: invalid quota scope specification. Please specify "
3135               "either --quota-scope=bucket, or --quota-scope=user" << std::endl;
3136           return EINVAL;
3137         }
3138         formatter->close_section();
3139
3140         if (opt_cmd != OPT_GLOBAL_QUOTA_GET) {
3141           // write the modified period config
3142           ret = period_config.write(store, realm_id);
3143           if (ret < 0) {
3144             cerr << "ERROR: failed to write period config: "
3145                 << cpp_strerror(-ret) << std::endl;
3146             return -ret;
3147           }
3148           if (!realm_id.empty()) {
3149             cout << "Global quota changes saved. Use 'period update' to apply "
3150                 "them to the staging period, and 'period commit' to commit the "
3151                 "new period." << std::endl;
3152           } else {
3153             cout << "Global quota changes saved. They will take effect as "
3154                 "the gateways are restarted." << std::endl;
3155           }
3156         }
3157
3158         formatter->flush(cout);
3159         cout << std::endl;
3160       }
3161       break;
3162     case OPT_REALM_CREATE:
3163       {
3164         if (realm_name.empty()) {
3165           cerr << "missing realm name" << std::endl;
3166           return EINVAL;
3167         }
3168
3169         RGWRealm realm(realm_name, g_ceph_context, store);
3170         int ret = realm.create();
3171         if (ret < 0) {
3172           cerr << "ERROR: couldn't create realm " << realm_name << ": " << cpp_strerror(-ret) << std::endl;
3173           return -ret;
3174         }
3175
3176         if (set_default) {
3177           ret = realm.set_as_default();
3178           if (ret < 0) {
3179             cerr << "failed to set realm " << realm_name << " as default: " << cpp_strerror(-ret) << std::endl;
3180           }
3181         }
3182
3183         encode_json("realm", realm, formatter);
3184         formatter->flush(cout);
3185         cout << std::endl;
3186       }
3187       break;
3188     case OPT_REALM_DELETE:
3189       {
3190         RGWRealm realm(realm_id, realm_name);
3191         if (realm_name.empty() && realm_id.empty()) {
3192           cerr << "missing realm name or id" << std::endl;
3193           return EINVAL;
3194         }
3195         int ret = realm.init(g_ceph_context, store);
3196         if (ret < 0) {
3197           cerr << "realm.init failed: " << cpp_strerror(-ret) << std::endl;
3198           return -ret;
3199         }
3200         ret = realm.delete_obj();
3201         if (ret < 0) {
3202           cerr << "ERROR: couldn't : " << cpp_strerror(-ret) << std::endl;
3203           return -ret;
3204         }
3205
3206       }
3207       break;
3208     case OPT_REALM_GET:
3209       {
3210         RGWRealm realm(realm_id, realm_name);
3211         int ret = realm.init(g_ceph_context, store);
3212         if (ret < 0) {
3213           if (ret == -ENOENT && realm_name.empty() && realm_id.empty()) {
3214             cerr << "missing realm name or id, or default realm not found" << std::endl;
3215           } else {
3216             cerr << "realm.init failed: " << cpp_strerror(-ret) << std::endl;
3217           }
3218           return -ret;
3219         }
3220         encode_json("realm", realm, formatter);
3221         formatter->flush(cout);
3222         cout << std::endl;
3223       }
3224       break;
3225     case OPT_REALM_GET_DEFAULT:
3226       {
3227         RGWRealm realm(g_ceph_context, store);
3228         string default_id;
3229         int ret = realm.read_default_id(default_id);
3230         if (ret == -ENOENT) {
3231           cout << "No default realm is set" << std::endl;
3232           return -ret;
3233         } else if (ret < 0) {
3234           cerr << "Error reading default realm:" << cpp_strerror(-ret) << std::endl;
3235           return -ret;
3236         }
3237         cout << "default realm: " << default_id << std::endl;
3238       }
3239       break;
3240     case OPT_REALM_LIST:
3241       {
3242         RGWRealm realm(g_ceph_context, store);
3243         string default_id;
3244         int ret = realm.read_default_id(default_id);
3245         if (ret < 0 && ret != -ENOENT) {
3246           cerr << "could not determine default realm: " << cpp_strerror(-ret) << std::endl;
3247         }
3248         list<string> realms;
3249         ret = store->list_realms(realms);
3250         if (ret < 0) {
3251           cerr << "failed to list realms: " << cpp_strerror(-ret) << std::endl;
3252           return -ret;
3253         }
3254         formatter->open_object_section("realms_list");
3255         encode_json("default_info", default_id, formatter);
3256         encode_json("realms", realms, formatter);
3257         formatter->close_section();
3258         formatter->flush(cout);
3259         cout << std::endl;
3260       }
3261       break;
3262     case OPT_REALM_LIST_PERIODS:
3263       {
3264         int ret = read_current_period_id(store, realm_id, realm_name, &period_id);
3265         if (ret < 0) {
3266           return -ret;
3267         }
3268         list<string> periods;
3269         ret = store->list_periods(period_id, periods);
3270         if (ret < 0) {
3271           cerr << "list periods failed: " << cpp_strerror(-ret) << std::endl;
3272           return -ret;
3273         }
3274         formatter->open_object_section("realm_periods_list");
3275         encode_json("current_period", period_id, formatter);
3276         encode_json("periods", periods, formatter);
3277         formatter->close_section();
3278         formatter->flush(cout);
3279         cout << std::endl;
3280       }
3281       break;
3282
3283     case OPT_REALM_RENAME:
3284       {
3285         RGWRealm realm(realm_id, realm_name);
3286         if (realm_new_name.empty()) {
3287           cerr << "missing realm new name" << std::endl;
3288           return EINVAL;
3289         }
3290         if (realm_name.empty() && realm_id.empty()) {
3291           cerr << "missing realm name or id" << std::endl;
3292           return EINVAL;
3293         }
3294         int ret = realm.init(g_ceph_context, store);
3295         if (ret < 0) {
3296           cerr << "realm.init failed: " << cpp_strerror(-ret) << std::endl;
3297           return -ret;
3298         }
3299         ret = realm.rename(realm_new_name);
3300         if (ret < 0) {
3301           cerr << "realm.rename failed: " << cpp_strerror(-ret) << std::endl;
3302           return -ret;
3303         }
3304         cout << "Realm name updated. Note that this change only applies to "
3305             "the current cluster, so this command must be run separately "
3306             "on each of the realm's other clusters." << std::endl;
3307       }
3308       break;
3309     case OPT_REALM_SET:
3310       {
3311         if (realm_id.empty() && realm_name.empty()) {
3312           cerr << "no realm name or id provided" << std::endl;
3313           return EINVAL;
3314         }
3315         RGWRealm realm(realm_id, realm_name);
3316         bool new_realm = false;
3317         int ret = realm.init(g_ceph_context, store);
3318         if (ret < 0 && ret != -ENOENT) {
3319           cerr << "failed to init realm: " << cpp_strerror(-ret) << std::endl;
3320           return -ret;
3321         } else if (ret == -ENOENT) {
3322           new_realm = true;
3323         }
3324         ret = read_decode_json(infile, realm);
3325         if (ret < 0) {
3326           return 1;
3327         }
3328         if (!realm_name.empty() && realm.get_name() != realm_name) {
3329           cerr << "mismatch between --rgw-realm " << realm_name << " and json input file name " <<
3330             realm.get_name() << std::endl;
3331           return EINVAL;
3332         }
3333         /* new realm */
3334         if (new_realm) {
3335           cout << "clearing period and epoch for new realm" << std::endl;
3336           realm.clear_current_period_and_epoch();
3337           ret = realm.create();
3338           if (ret < 0) {
3339             cerr << "ERROR: couldn't create new realm: " << cpp_strerror(-ret) << std::endl;
3340             return 1;
3341           }
3342         } else {
3343           ret = realm.update();
3344           if (ret < 0) {
3345             cerr << "ERROR: couldn't store realm info: " << cpp_strerror(-ret) << std::endl;
3346             return 1;
3347           }
3348         }
3349
3350         if (set_default) {
3351           ret = realm.set_as_default();
3352           if (ret < 0) {
3353             cerr << "failed to set realm " << realm_name << " as default: " << cpp_strerror(-ret) << std::endl;
3354           }
3355         }
3356         encode_json("realm", realm, formatter);
3357         formatter->flush(cout);
3358       }
3359       break;
3360
3361     case OPT_REALM_DEFAULT:
3362       {
3363         RGWRealm realm(realm_id, realm_name);
3364         int ret = realm.init(g_ceph_context, store);
3365         if (ret < 0) {
3366           cerr << "failed to init realm: " << cpp_strerror(-ret) << std::endl;
3367           return -ret;
3368         }
3369         ret = realm.set_as_default();
3370         if (ret < 0) {
3371           cerr << "failed to set realm as default: " << cpp_strerror(-ret) << std::endl;
3372           return -ret;
3373         }
3374       }
3375       break;
3376     case OPT_REALM_PULL:
3377       {
3378         if (url.empty()) {
3379           cerr << "A --url must be provided." << std::endl;
3380           return EINVAL;
3381         }
3382         RGWEnv env;
3383         req_info info(g_ceph_context, &env);
3384         info.method = "GET";
3385         info.request_uri = "/admin/realm";
3386
3387         map<string, string> &params = info.args.get_params();
3388         if (!realm_id.empty())
3389           params["id"] = realm_id;
3390         if (!realm_name.empty())
3391           params["name"] = realm_name;
3392
3393         bufferlist bl;
3394         JSONParser p;
3395         int ret = send_to_url(url, access_key, secret_key, info, bl, p);
3396         if (ret < 0) {
3397           cerr << "request failed: " << cpp_strerror(-ret) << std::endl;
3398           if (ret == -EACCES) {
3399             cerr << "If the realm has been changed on the master zone, the "
3400                 "master zone's gateway may need to be restarted to recognize "
3401                 "this user." << std::endl;
3402           }
3403           return -ret;
3404         }
3405         RGWRealm realm;
3406         realm.init(g_ceph_context, store, false);
3407         try {
3408           decode_json_obj(realm, &p);
3409         } catch (JSONDecoder::err& e) {
3410           cerr << "failed to decode JSON response: " << e.message << std::endl;
3411           return EINVAL;
3412         }
3413         RGWPeriod period;
3414         auto& current_period = realm.get_current_period();
3415         if (!current_period.empty()) {
3416           // pull the latest epoch of the realm's current period
3417           ret = do_period_pull(nullptr, url, access_key, secret_key,
3418                                realm_id, realm_name, current_period, "",
3419                                &period);
3420           if (ret < 0) {
3421             cerr << "could not fetch period " << current_period << std::endl;
3422             return -ret;
3423           }
3424         }
3425         ret = realm.create(false);
3426         if (ret < 0 && ret != -EEXIST) {
3427           cerr << "Error storing realm " << realm.get_id() << ": "
3428             << cpp_strerror(ret) << std::endl;
3429           return -ret;
3430         } else if (ret ==-EEXIST) {
3431           ret = realm.update();
3432           if (ret < 0) {
3433             cerr << "Error storing realm " << realm.get_id() << ": "
3434                  << cpp_strerror(ret) << std::endl;
3435           }
3436         }
3437
3438         if (set_default) {
3439           ret = realm.set_as_default();
3440           if (ret < 0) {
3441             cerr << "failed to set realm " << realm_name << " as default: " << cpp_strerror(-ret) << std::endl;
3442           }
3443         }
3444
3445         encode_json("realm", realm, formatter);
3446         formatter->flush(cout);
3447         cout << std::endl;
3448       }
3449       return 0;
3450
3451     case OPT_ZONEGROUP_ADD:
3452       {
3453         if (zonegroup_id.empty() && zonegroup_name.empty()) {
3454           cerr << "no zonegroup name or id provided" << std::endl;
3455           return EINVAL;
3456         }
3457
3458         RGWZoneGroup zonegroup(zonegroup_id,zonegroup_name);
3459         int ret = zonegroup.init(g_ceph_context, store);
3460         if (ret < 0) {
3461           cerr << "failed to initialize zonegroup " << zonegroup_name << " id " << zonegroup_id << " :"
3462                << cpp_strerror(-ret) << std::endl;
3463           return -ret;
3464         }
3465         RGWZoneParams zone(zone_id, zone_name);
3466         ret = zone.init(g_ceph_context, store);
3467         if (ret < 0) {
3468           cerr << "unable to initialize zone: " << cpp_strerror(-ret) << std::endl;
3469           return -ret;
3470         }
3471         if (zone.realm_id != zonegroup.realm_id) {
3472           zone.realm_id = zonegroup.realm_id;
3473           ret = zone.update();
3474           if (ret < 0) {
3475             cerr << "failed to save zone info: " << cpp_strerror(-ret) << std::endl;
3476             return -ret;
3477           }
3478         }
3479
3480         string *ptier_type = (tier_type_specified ? &tier_type : nullptr);
3481         zone.tier_config = tier_config_add;
3482
3483         bool *psync_from_all = (sync_from_all_specified ? &sync_from_all : nullptr);
3484
3485         ret = zonegroup.add_zone(zone,
3486                                  (is_master_set ? &is_master : NULL),
3487                                  (is_read_only_set ? &read_only : NULL),
3488                                  endpoints, ptier_type,
3489                                  psync_from_all, sync_from, sync_from_rm);
3490         if (ret < 0) {
3491           cerr << "failed to add zone " << zone_name << " to zonegroup " << zonegroup.get_name() << ": "
3492                << cpp_strerror(-ret) << std::endl;
3493           return -ret;
3494         }
3495
3496         encode_json("zonegroup", zonegroup, formatter);
3497         formatter->flush(cout);
3498       }
3499       break;
3500     case OPT_ZONEGROUP_CREATE:
3501       {
3502         if (zonegroup_name.empty()) {
3503           cerr << "Missing zonegroup name" << std::endl;
3504           return EINVAL;
3505         }
3506         RGWRealm realm(realm_id, realm_name);
3507         int ret = realm.init(g_ceph_context, store);
3508         if (ret < 0) {
3509           cerr << "failed to init realm: " << cpp_strerror(-ret) << std::endl;
3510           return -ret;
3511         }
3512
3513         RGWZoneGroup zonegroup(zonegroup_name, is_master, g_ceph_context, store, realm.get_id(), endpoints);
3514         zonegroup.api_name = (api_name.empty() ? zonegroup_name : api_name);
3515         ret = zonegroup.create();
3516         if (ret < 0) {
3517           cerr << "failed to create zonegroup " << zonegroup_name << ": " << cpp_strerror(-ret) << std::endl;
3518           return -ret;
3519         }
3520
3521         if (set_default) {
3522           ret = zonegroup.set_as_default();
3523           if (ret < 0) {
3524             cerr << "failed to set zonegroup " << zonegroup_name << " as default: " << cpp_strerror(-ret) << std::endl;
3525           }
3526         }
3527
3528         encode_json("zonegroup", zonegroup, formatter);
3529         formatter->flush(cout);
3530         cout << std::endl;
3531       }
3532       break;
3533     case OPT_ZONEGROUP_DEFAULT:
3534       {
3535         if (zonegroup_id.empty() && zonegroup_name.empty()) {
3536           cerr << "no zonegroup name or id provided" << std::endl;
3537           return EINVAL;
3538         }
3539
3540         RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
3541         int ret = zonegroup.init(g_ceph_context, store);
3542         if (ret < 0) {
3543           cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
3544           return -ret;
3545         }
3546
3547         ret = zonegroup.set_as_default();
3548         if (ret < 0) {
3549           cerr << "failed to set zonegroup as default: " << cpp_strerror(-ret) << std::endl;
3550           return -ret;
3551         }
3552       }
3553       break;
3554     case OPT_ZONEGROUP_DELETE:
3555       {
3556         if (zonegroup_id.empty() && zonegroup_name.empty()) {
3557           cerr << "no zonegroup name or id provided" << std::endl;
3558           return EINVAL;
3559         }
3560         RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
3561         int ret = zonegroup.init(g_ceph_context, store);
3562         if (ret < 0) {
3563           cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
3564           return -ret;
3565         }
3566         ret = zonegroup.delete_obj();
3567         if (ret < 0) {
3568           cerr << "ERROR: couldn't delete zonegroup: " << cpp_strerror(-ret) << std::endl;
3569           return -ret;
3570         }
3571       }
3572       break;
3573     case OPT_ZONEGROUP_GET:
3574       {
3575         RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
3576         int ret = zonegroup.init(g_ceph_context, store);
3577         if (ret < 0) {
3578           cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
3579           return -ret;
3580         }
3581
3582         encode_json("zonegroup", zonegroup, formatter);
3583         formatter->flush(cout);
3584         cout << std::endl;
3585       }
3586       break;
3587     case OPT_ZONEGROUP_LIST:
3588       {
3589         RGWZoneGroup zonegroup;
3590         int ret = zonegroup.init(g_ceph_context, store, false);
3591         if (ret < 0) {
3592           cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
3593           return -ret;
3594         }
3595
3596         list<string> zonegroups;
3597         ret = store->list_zonegroups(zonegroups);
3598         if (ret < 0) {
3599           cerr << "failed to list zonegroups: " << cpp_strerror(-ret) << std::endl;
3600           return -ret;
3601         }
3602         string default_zonegroup;
3603         ret = zonegroup.read_default_id(default_zonegroup);
3604         if (ret < 0 && ret != -ENOENT) {
3605           cerr << "could not determine default zonegroup: " << cpp_strerror(-ret) << std::endl;
3606         }
3607         formatter->open_object_section("zonegroups_list");
3608         encode_json("default_info", default_zonegroup, formatter);
3609         encode_json("zonegroups", zonegroups, formatter);
3610         formatter->close_section();
3611         formatter->flush(cout);
3612         cout << std::endl;
3613       }
3614       break;
3615     case OPT_ZONEGROUP_MODIFY:
3616       {
3617         RGWRealm realm(realm_id, realm_name);
3618         int ret = realm.init(g_ceph_context, store);
3619         if (ret < 0) {
3620           cerr << "failed to init realm: " << cpp_strerror(-ret) << std::endl;
3621           return -ret;
3622         }
3623
3624         RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
3625         ret = zonegroup.init(g_ceph_context, store);
3626         if (ret < 0) {
3627           cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
3628           return -ret;
3629         }
3630
3631         bool need_update = false;
3632
3633         if (!master_zone.empty()) {
3634           zonegroup.master_zone = master_zone;
3635           need_update = true;
3636         }
3637
3638         if (is_master_set) {
3639           zonegroup.update_master(is_master);
3640           need_update = true;
3641         }
3642
3643         if (!endpoints.empty()) {
3644           zonegroup.endpoints = endpoints;
3645           need_update = true;
3646         }
3647
3648         if (!api_name.empty()) {
3649           zonegroup.api_name = api_name;
3650           need_update = true;
3651         }
3652
3653         if (!realm_id.empty()) {
3654           zonegroup.realm_id = realm_id;
3655           need_update = true;
3656         } else if (!realm_name.empty()) {
3657           // get realm id from name
3658           RGWRealm realm{g_ceph_context, store};
3659           ret = realm.read_id(realm_name, zonegroup.realm_id);
3660           if (ret < 0) {
3661             cerr << "failed to find realm by name " << realm_name << std::endl;
3662             return -ret;
3663           }
3664           need_update = true;
3665         }
3666
3667         if (need_update) {
3668           ret = zonegroup.update();
3669           if (ret < 0) {
3670             cerr << "failed to update zonegroup: " << cpp_strerror(-ret) << std::endl;
3671             return -ret;
3672           }
3673         }
3674
3675         if (set_default) {
3676           ret = zonegroup.set_as_default();
3677           if (ret < 0) {
3678             cerr << "failed to set zonegroup " << zonegroup_name << " as default: " << cpp_strerror(-ret) << std::endl;
3679           }
3680         }
3681
3682         encode_json("zonegroup", zonegroup, formatter);
3683         formatter->flush(cout);
3684       }
3685       break;
3686     case OPT_ZONEGROUP_SET:
3687       {
3688         RGWRealm realm(realm_id, realm_name);
3689         int ret = realm.init(g_ceph_context, store);
3690         if (ret < 0) {
3691           cerr << "failed to init realm: " << cpp_strerror(-ret) << std::endl;
3692           return -ret;
3693         }
3694
3695         RGWZoneGroup zonegroup;
3696         ret = zonegroup.init(g_ceph_context, store, false);
3697         if (ret < 0) {
3698           cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
3699           return -ret;
3700         }
3701         ret = read_decode_json(infile, zonegroup);
3702         if (ret < 0) {
3703           return 1;
3704         }
3705         if (zonegroup.realm_id.empty()) {
3706           zonegroup.realm_id = realm.get_id();
3707         }
3708         ret = zonegroup.create();
3709         if (ret < 0 && ret != -EEXIST) {
3710           cerr << "ERROR: couldn't create zonegroup info: " << cpp_strerror(-ret) << std::endl;
3711           return 1;
3712         } else if (ret == -EEXIST) {
3713           ret = zonegroup.update();
3714           if (ret < 0) {
3715             cerr << "ERROR: couldn't store zonegroup info: " << cpp_strerror(-ret) << std::endl;
3716             return 1;
3717           }
3718         }
3719
3720         if (set_default) {
3721           ret = zonegroup.set_as_default();
3722           if (ret < 0) {
3723             cerr << "failed to set zonegroup " << zonegroup_name << " as default: " << cpp_strerror(-ret) << std::endl;
3724           }
3725         }
3726
3727         encode_json("zonegroup", zonegroup, formatter);
3728         formatter->flush(cout);
3729       }
3730       break;
3731     case OPT_ZONEGROUP_REMOVE:
3732       {
3733         RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
3734         int ret = zonegroup.init(g_ceph_context, store);
3735         if (ret < 0) {
3736           cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
3737           return -ret;
3738         }
3739
3740         if (zone_id.empty()) {
3741           if (zone_name.empty()) {
3742             cerr << "no --zone-id or --rgw-zone name provided" << std::endl;
3743             return EINVAL;
3744           }
3745           // look up zone id by name
3746           for (auto& z : zonegroup.zones) {
3747             if (zone_name == z.second.name) {
3748               zone_id = z.second.id;
3749               break;
3750             }
3751           }
3752           if (zone_id.empty()) {
3753             cerr << "zone name " << zone_name << " not found in zonegroup "
3754                 << zonegroup.get_name() << std::endl;
3755             return ENOENT;
3756           }
3757         }
3758
3759         ret = zonegroup.remove_zone(zone_id);
3760         if (ret < 0) {
3761           cerr << "failed to remove zone: " << cpp_strerror(-ret) << std::endl;
3762           return -ret;
3763         }
3764
3765         encode_json("zonegroup", zonegroup, formatter);
3766         formatter->flush(cout);
3767       }
3768       break;
3769     case OPT_ZONEGROUP_RENAME:
3770       {
3771         if (zonegroup_new_name.empty()) {
3772           cerr << " missing zonegroup new name" << std::endl;
3773           return EINVAL;
3774         }
3775         if (zonegroup_id.empty() && zonegroup_name.empty()) {
3776           cerr << "no zonegroup name or id provided" << std::endl;
3777           return EINVAL;
3778         }
3779         RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
3780         int ret = zonegroup.init(g_ceph_context, store);
3781         if (ret < 0) {
3782           cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
3783           return -ret;
3784         }
3785         ret = zonegroup.rename(zonegroup_new_name);
3786         if (ret < 0) {
3787           cerr << "failed to rename zonegroup: " << cpp_strerror(-ret) << std::endl;
3788           return -ret;
3789         }
3790       }
3791       break;
3792     case OPT_ZONEGROUP_PLACEMENT_LIST:
3793       {
3794         RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
3795         int ret = zonegroup.init(g_ceph_context, store);
3796         if (ret < 0) {
3797           cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
3798           return -ret;
3799         }
3800
3801         encode_json("placement_targets", zonegroup.placement_targets, formatter);
3802         formatter->flush(cout);
3803         cout << std::endl;
3804       }
3805       break;
3806     case OPT_ZONEGROUP_PLACEMENT_ADD:
3807     case OPT_ZONEGROUP_PLACEMENT_MODIFY:
3808     case OPT_ZONEGROUP_PLACEMENT_RM:
3809     case OPT_ZONEGROUP_PLACEMENT_DEFAULT:
3810       {
3811         if (placement_id.empty()) {
3812           cerr << "ERROR: --placement-id not specified" << std::endl;
3813           return EINVAL;
3814         }
3815
3816         RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
3817         int ret = zonegroup.init(g_ceph_context, store);
3818         if (ret < 0) {
3819           cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
3820           return -ret;
3821         }
3822
3823         if (opt_cmd == OPT_ZONEGROUP_PLACEMENT_ADD) {
3824           RGWZoneGroupPlacementTarget target;
3825           target.name = placement_id;
3826           for (auto& t : tags) {
3827             target.tags.insert(t);
3828           }
3829           zonegroup.placement_targets[placement_id] = target;
3830         } else if (opt_cmd == OPT_ZONEGROUP_PLACEMENT_MODIFY) {
3831           RGWZoneGroupPlacementTarget& target = zonegroup.placement_targets[placement_id];
3832           if (!tags.empty()) {
3833             target.tags.clear();
3834             for (auto& t : tags) {
3835               target.tags.insert(t);
3836             }
3837           }
3838           target.name = placement_id;
3839           for (auto& t : tags_rm) {
3840             target.tags.erase(t);
3841           }
3842           for (auto& t : tags_add) {
3843             target.tags.insert(t);
3844           }
3845         } else if (opt_cmd == OPT_ZONEGROUP_PLACEMENT_RM) {
3846           zonegroup.placement_targets.erase(placement_id);
3847         } else if (opt_cmd == OPT_ZONEGROUP_PLACEMENT_DEFAULT) {
3848           if (!zonegroup.placement_targets.count(placement_id)) {
3849             cerr << "failed to find a zonegroup placement target named '"
3850                 << placement_id << "'" << std::endl;
3851             return -ENOENT;
3852           }
3853           zonegroup.default_placement = placement_id;
3854         }
3855
3856         zonegroup.post_process_params();
3857         ret = zonegroup.update();
3858         if (ret < 0) {
3859           cerr << "failed to update zonegroup: " << cpp_strerror(-ret) << std::endl;
3860           return -ret;
3861         }
3862
3863         encode_json("placement_targets", zonegroup.placement_targets, formatter);
3864         formatter->flush(cout);
3865       }
3866       break;
3867     case OPT_ZONE_CREATE:
3868       {
3869         if (zone_name.empty()) {
3870           cerr << "zone name not provided" << std::endl;
3871           return EINVAL;
3872         }
3873         int ret;
3874         RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
3875         /* if the user didn't provide zonegroup info , create stand alone zone */
3876         if (!zonegroup_id.empty() || !zonegroup_name.empty()) {
3877           ret = zonegroup.init(g_ceph_context, store);
3878           if (ret < 0) {
3879             cerr << "unable to initialize zonegroup " << zonegroup_name << ": " << cpp_strerror(-ret) << std::endl;
3880             return -ret;
3881           }
3882           if (realm_id.empty() && realm_name.empty()) {
3883             realm_id = zonegroup.realm_id;
3884           }
3885         }
3886
3887         RGWZoneParams zone(zone_id, zone_name);
3888         ret = zone.init(g_ceph_context, store, false);
3889         if (ret < 0) {
3890           cerr << "unable to initialize zone: " << cpp_strerror(-ret) << std::endl;
3891           return -ret;
3892         }
3893
3894         zone.system_key.id = access_key;
3895         zone.system_key.key = secret_key;
3896         zone.realm_id = realm_id;
3897         zone.tier_config = tier_config_add;
3898
3899         ret = zone.create();
3900         if (ret < 0) {
3901           cerr << "failed to create zone " << zone_name << ": " << cpp_strerror(-ret) << std::endl;
3902           return -ret;
3903         }
3904
3905         if (!zonegroup_id.empty() || !zonegroup_name.empty()) {
3906           string *ptier_type = (tier_type_specified ? &tier_type : nullptr);
3907           bool *psync_from_all = (sync_from_all_specified ? &sync_from_all : nullptr);
3908           ret = zonegroup.add_zone(zone,
3909                                    (is_master_set ? &is_master : NULL),
3910                                    (is_read_only_set ? &read_only : NULL),
3911                                    endpoints,
3912                                    ptier_type,
3913                                    psync_from_all,
3914                                    sync_from, sync_from_rm);
3915           if (ret < 0) {
3916             cerr << "failed to add zone " << zone_name << " to zonegroup " << zonegroup.get_name()
3917                  << ": " << cpp_strerror(-ret) << std::endl;
3918             return -ret;
3919           }
3920         }
3921
3922         if (set_default) {
3923           ret = zone.set_as_default();
3924           if (ret < 0) {
3925             cerr << "failed to set zone " << zone_name << " as default: " << cpp_strerror(-ret) << std::endl;
3926           }
3927         }
3928
3929         encode_json("zone", zone, formatter);
3930         formatter->flush(cout);
3931         cout << std::endl;
3932       }
3933       break;
3934     case OPT_ZONE_DEFAULT:
3935       {
3936         RGWZoneGroup zonegroup(zonegroup_id,zonegroup_name);
3937         int ret = zonegroup.init(g_ceph_context, store);
3938         if (ret < 0) {
3939           cerr << "WARNING: failed to initialize zonegroup " << zonegroup_name << std::endl;
3940         }
3941         if (zone_id.empty() && zone_name.empty()) {
3942           cerr << "no zone name or id provided" << std::endl;
3943           return EINVAL;
3944         }
3945         RGWZoneParams zone(zone_id, zone_name);
3946         ret = zone.init(g_ceph_context, store);
3947         if (ret < 0) {
3948           cerr << "unable to initialize zone: " << cpp_strerror(-ret) << std::endl;
3949           return -ret;
3950         }
3951         ret = zone.set_as_default();
3952         if (ret < 0) {
3953           cerr << "failed to set zone as default: " << cpp_strerror(-ret) << std::endl;
3954           return -ret;
3955         }
3956       }
3957       break;
3958     case OPT_ZONE_DELETE:
3959       {
3960         if (zone_id.empty() && zone_name.empty()) {
3961           cerr << "no zone name or id provided" << std::endl;
3962           return EINVAL;
3963         }
3964         RGWZoneParams zone(zone_id, zone_name);
3965         int ret = zone.init(g_ceph_context, store);
3966         if (ret < 0) {
3967           cerr << "unable to initialize zone: " << cpp_strerror(-ret) << std::endl;
3968           return -ret;
3969         }
3970
3971         list<string> zonegroups;
3972         ret = store->list_zonegroups(zonegroups);
3973         if (ret < 0) {
3974           cerr << "failed to list zonegroups: " << cpp_strerror(-ret) << std::endl;
3975           return -ret;
3976         }
3977
3978         for (list<string>::iterator iter = zonegroups.begin(); iter != zonegroups.end(); ++iter) {
3979           RGWZoneGroup zonegroup(string(), *iter);
3980           int ret = zonegroup.init(g_ceph_context, store);
3981           if (ret < 0) {
3982             cerr << "WARNING: failed to initialize zonegroup " << zonegroup_name << std::endl;
3983             continue;
3984           }
3985           ret = zonegroup.remove_zone(zone.get_id());
3986           if (ret < 0 && ret != -ENOENT) {
3987             cerr << "failed to remove zone " << zone_name << " from zonegroup " << zonegroup.get_name() << ": "
3988               << cpp_strerror(-ret) << std::endl;
3989           }
3990         }
3991
3992         ret = zone.delete_obj();
3993         if (ret < 0) {
3994           cerr << "failed to delete zone " << zone_name << ": " << cpp_strerror(-ret) << std::endl;
3995           return -ret;
3996         }
3997       }
3998       break;
3999     case OPT_ZONE_GET:
4000       {
4001         RGWZoneParams zone(zone_id, zone_name);
4002         int ret = zone.init(g_ceph_context, store);
4003         if (ret < 0) {
4004           cerr << "unable to initialize zone: " << cpp_strerror(-ret) << std::endl;
4005           return -ret;
4006         }
4007         encode_json("zone", zone, formatter);
4008         formatter->flush(cout);
4009       }
4010       break;
4011     case OPT_ZONE_SET:
4012       {
4013         RGWZoneParams zone(zone_name);
4014         int ret = zone.init(g_ceph_context, store, false);
4015         if (ret < 0) {
4016           return -ret;
4017         }
4018
4019         ret = zone.read();
4020         if (ret < 0 && ret != -ENOENT) {
4021           cerr << "zone.read() returned ret=" << ret << std::endl;
4022           return -ret;
4023         }
4024
4025         string orig_id = zone.get_id();
4026
4027         ret = read_decode_json(infile, zone);
4028         if (ret < 0) {
4029           return 1;
4030         }
4031
4032         if(zone.realm_id.empty()) {
4033           RGWRealm realm(realm_id, realm_name);
4034           int ret = realm.init(g_ceph_context, store);
4035           if (ret < 0 && ret != -ENOENT) {
4036             cerr << "failed to init realm: " << cpp_strerror(-ret) << std::endl;
4037             return -ret;
4038           }
4039           zone.realm_id = realm.get_id();
4040         }
4041
4042         if( !zone_name.empty() && !zone.get_name().empty() && zone.get_name() != zone_name) {
4043           cerr << "Error: zone name" << zone_name << " is different than the zone name " << zone.get_name() << " in the provided json " << std::endl;
4044           return EINVAL;
4045         }
4046
4047         if (zone.get_name().empty()) {
4048           zone.set_name(zone_name);
4049           if (zone.get_name().empty()) {
4050             cerr << "no zone name specified" << std::endl;
4051             return EINVAL;
4052           }
4053         }
4054
4055         zone_name = zone.get_name();
4056
4057         if (zone.get_id().empty()) {
4058           zone.set_id(orig_id);
4059         }
4060
4061         if (zone.get_id().empty()) {
4062           cerr << "no zone name id the json provided, assuming old format" << std::endl;
4063           if (zone_name.empty()) {
4064             cerr << "missing zone name"  << std::endl;
4065             return EINVAL;
4066           }
4067           zone.set_name(zone_name);
4068           zone.set_id(zone_name);
4069         }
4070
4071         cerr << "zone id " << zone.get_id();
4072         ret = zone.fix_pool_names();
4073         if (ret < 0) {
4074           cerr << "ERROR: couldn't fix zone: " << cpp_strerror(-ret) << std::endl;
4075           return -ret;
4076         }
4077         ret = zone.write(false);
4078         if (ret < 0) {
4079           cerr << "ERROR: couldn't create zone: " << cpp_strerror(-ret) << std::endl;
4080           return 1;
4081         }
4082
4083         if (set_default) {
4084           ret = zone.set_as_default();
4085           if (ret < 0) {
4086             cerr << "failed to set zone " << zone_name << " as default: " << cpp_strerror(-ret) << std::endl;
4087           }
4088         }
4089
4090         encode_json("zone", zone, formatter);
4091         formatter->flush(cout);
4092       }
4093       break;
4094     case OPT_ZONE_LIST:
4095       {
4096         list<string> zones;
4097         int ret = store->list_zones(zones);
4098         if (ret < 0) {
4099           cerr << "failed to list zones: " << cpp_strerror(-ret) << std::endl;
4100           return -ret;
4101         }
4102
4103         RGWZoneParams zone;
4104         ret = zone.init(g_ceph_context, store, false);
4105         if (ret < 0) {
4106           cerr << "failed to init zone: " << cpp_strerror(-ret) << std::endl;
4107           return -ret;
4108         }
4109         string default_zone;
4110         ret = zone.read_default_id(default_zone);
4111         if (ret < 0 && ret != -ENOENT) {
4112           cerr << "could not determine default zone: " << cpp_strerror(-ret) << std::endl;
4113         }
4114         formatter->open_object_section("zones_list");
4115         encode_json("default_info", default_zone, formatter);
4116         encode_json("zones", zones, formatter);
4117         formatter->close_section();
4118         formatter->flush(cout);
4119         cout << std::endl;
4120       }
4121       break;
4122     case OPT_ZONE_MODIFY:
4123       {
4124         RGWZoneParams zone(zone_id, zone_name);
4125         int ret = zone.init(g_ceph_context, store);
4126         if (ret < 0) {
4127           cerr << "failed to init zone: " << cpp_strerror(-ret) << std::endl;
4128           return -ret;
4129         }
4130
4131         bool need_zone_update = false;
4132         if (!access_key.empty()) {
4133           zone.system_key.id = access_key;
4134           need_zone_update = true;
4135         }
4136
4137         if (!secret_key.empty()) {
4138           zone.system_key.key = secret_key;
4139           need_zone_update = true;
4140         }
4141
4142         if (!realm_id.empty()) {
4143           zone.realm_id = realm_id;
4144           need_zone_update = true;
4145         } else if (!realm_name.empty()) {
4146           // get realm id from name
4147           RGWRealm realm{g_ceph_context, store};
4148           ret = realm.read_id(realm_name, zone.realm_id);
4149           if (ret < 0) {
4150             cerr << "failed to find realm by name " << realm_name << std::endl;
4151             return -ret;
4152           }
4153           need_zone_update = true;
4154         }
4155
4156         for (auto add : tier_config_add) {
4157           zone.tier_config[add.first] = add.second;
4158           need_zone_update = true;
4159         }
4160
4161         for (auto rm : tier_config_rm) {
4162           zone.tier_config.erase(rm.first);
4163           need_zone_update = true;
4164         }
4165
4166         if (need_zone_update) {
4167           ret = zone.update();
4168           if (ret < 0) {
4169             cerr << "failed to save zone info: " << cpp_strerror(-ret) << std::endl;
4170             return -ret;
4171           }
4172         }
4173
4174         RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
4175         ret = zonegroup.init(g_ceph_context, store);
4176         if (ret < 0) {
4177           cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
4178           return -ret;
4179         }
4180         string *ptier_type = (tier_type_specified ? &tier_type : nullptr);
4181
4182         bool *psync_from_all = (sync_from_all_specified ? &sync_from_all : nullptr);
4183
4184         ret = zonegroup.add_zone(zone,
4185                                  (is_master_set ? &is_master : NULL),
4186                                  (is_read_only_set ? &read_only : NULL),
4187                                  endpoints, ptier_type,
4188                                  psync_from_all, sync_from, sync_from_rm);
4189         if (ret < 0) {
4190           cerr << "failed to update zonegroup: " << cpp_strerror(-ret) << std::endl;
4191           return -ret;
4192         }
4193
4194         ret = zonegroup.update();
4195         if (ret < 0) {
4196           cerr << "failed to update zonegroup: " << cpp_strerror(-ret) << std::endl;
4197           return -ret;
4198         }
4199
4200         if (set_default) {
4201           ret = zone.set_as_default();
4202           if (ret < 0) {
4203             cerr << "failed to set zone " << zone_name << " as default: " << cpp_strerror(-ret) << std::endl;
4204           }
4205         }
4206
4207         encode_json("zone", zone, formatter);
4208         formatter->flush(cout);
4209       }
4210       break;
4211     case OPT_ZONE_RENAME:
4212       {
4213         if (zone_new_name.empty()) {
4214           cerr << " missing zone new name" << std::endl;
4215           return EINVAL;
4216         }
4217         if (zone_id.empty() && zone_name.empty()) {
4218           cerr << "no zonegroup name or id provided" << std::endl;
4219           return EINVAL;
4220         }
4221         RGWZoneParams zone(zone_id,zone_name);
4222         int ret = zone.init(g_ceph_context, store);
4223         if (ret < 0) {
4224           cerr << "unable to initialize zone: " << cpp_strerror(-ret) << std::endl;
4225           return -ret;
4226         }
4227         ret = zone.rename(zone_new_name);
4228         if (ret < 0) {
4229           cerr << "failed to rename zone " << zone_name << " to " << zone_new_name << ": " << cpp_strerror(-ret)
4230                << std::endl;
4231           return -ret;
4232         }
4233         RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
4234         ret = zonegroup.init(g_ceph_context, store);
4235         if (ret < 0) {
4236           cerr << "WARNING: failed to initialize zonegroup " << zonegroup_name << std::endl;
4237         } else {
4238           ret = zonegroup.rename_zone(zone);
4239           if (ret < 0 && ret ) {
4240             cerr << "Error in zonegroup rename for " << zone_name << ": " << cpp_strerror(-ret) << std::endl;
4241             return -ret;
4242           }
4243         }
4244       }
4245       break;
4246     case OPT_ZONE_PLACEMENT_ADD:
4247     case OPT_ZONE_PLACEMENT_MODIFY:
4248     case OPT_ZONE_PLACEMENT_RM:
4249       {
4250         if (placement_id.empty()) {
4251           cerr << "ERROR: --placement-id not specified" << std::endl;
4252           return EINVAL;
4253         }
4254         // validate compression type
4255         if (compression_type && *compression_type != "random"
4256             && !Compressor::get_comp_alg_type(*compression_type)) {
4257           std::cerr << "Unrecognized compression type" << std::endl;
4258           return EINVAL;
4259         }
4260
4261         RGWZoneParams zone(zone_id, zone_name);
4262         int ret = zone.init(g_ceph_context, store);
4263         if (ret < 0) {
4264           cerr << "failed to init zone: " << cpp_strerror(-ret) << std::endl;
4265           return -ret;
4266         }
4267
4268         if (opt_cmd == OPT_ZONE_PLACEMENT_ADD) {
4269           // pool names are required
4270           if (!index_pool || index_pool->empty() ||
4271               !data_pool || data_pool->empty()) {
4272             cerr << "ERROR: need to specify both --index-pool and --data-pool" << std::endl;
4273             return EINVAL;
4274           }
4275
4276           RGWZonePlacementInfo& info = zone.placement_pools[placement_id];
4277
4278           info.index_pool = *index_pool;
4279           info.data_pool = *data_pool;
4280           if (data_extra_pool) {
4281             info.data_extra_pool = *data_extra_pool;
4282           }
4283           if (index_type_specified) {
4284             info.index_type = placement_index_type;
4285           }
4286           if (compression_type) {
4287             info.compression_type = *compression_type;
4288           }
4289         } else if (opt_cmd == OPT_ZONE_PLACEMENT_MODIFY) {
4290           auto p = zone.placement_pools.find(placement_id);
4291           if (p == zone.placement_pools.end()) {
4292             cerr << "ERROR: zone placement target '" << placement_id
4293                 << "' not found" << std::endl;
4294             return -ENOENT;
4295           }
4296           auto& info = p->second;
4297           if (index_pool && !index_pool->empty()) {
4298             info.index_pool = *index_pool;
4299           }
4300           if (data_pool && !data_pool->empty()) {
4301             info.data_pool = *data_pool;
4302           }
4303           if (data_extra_pool) {
4304             info.data_extra_pool = *data_extra_pool;
4305           }
4306           if (index_type_specified) {
4307             info.index_type = placement_index_type;
4308           }
4309           if (compression_type) {
4310             info.compression_type = *compression_type;
4311           }
4312         } else if (opt_cmd == OPT_ZONE_PLACEMENT_RM) {
4313           zone.placement_pools.erase(placement_id);
4314         }
4315
4316         ret = zone.update();
4317         if (ret < 0) {
4318           cerr << "failed to save zone info: " << cpp_strerror(-ret) << std::endl;
4319           return -ret;
4320         }
4321
4322         encode_json("zone", zone, formatter);
4323         formatter->flush(cout);
4324       }
4325       break;
4326     case OPT_ZONE_PLACEMENT_LIST:
4327       {
4328         RGWZoneParams zone(zone_id, zone_name);
4329         int ret = zone.init(g_ceph_context, store);
4330         if (ret < 0) {
4331           cerr << "unable to initialize zone: " << cpp_strerror(-ret) << std::endl;
4332           return -ret;
4333         }
4334         encode_json("placement_pools", zone.placement_pools, formatter);
4335         formatter->flush(cout);
4336       }
4337       break;
4338     }
4339     return 0;
4340   }
4341
4342   if (!user_id.empty()) {
4343     user_op.set_user_id(user_id);
4344     bucket_op.set_user_id(user_id);
4345   }
4346
4347   if (!display_name.empty())
4348     user_op.set_display_name(display_name);
4349
4350   if (!user_email.empty())
4351     user_op.set_user_email(user_email);
4352
4353   if (!access_key.empty())
4354     user_op.set_access_key(access_key);
4355
4356   if (!secret_key.empty())
4357     user_op.set_secret_key(secret_key);
4358
4359   if (!subuser.empty())
4360     user_op.set_subuser(subuser);
4361
4362   if (!caps.empty())
4363     user_op.set_caps(caps);
4364
4365   user_op.set_purge_data(purge_data);
4366
4367   if (purge_keys)
4368     user_op.set_purge_keys();
4369
4370   if (gen_access_key)
4371     user_op.set_generate_key();
4372
4373   if (gen_secret_key)
4374     user_op.set_gen_secret(); // assume that a key pair should be created
4375
4376   if (max_buckets_specified)
4377     user_op.set_max_buckets(max_buckets);
4378
4379   if (admin_specified)
4380      user_op.set_admin(admin);
4381
4382   if (system_specified)
4383     user_op.set_system(system);
4384
4385   if (set_perm)
4386     user_op.set_perm(perm_mask);
4387
4388   if (set_temp_url_key) {
4389     map<int, string>::iterator iter = temp_url_keys.begin();
4390     for (; iter != temp_url_keys.end(); ++iter) {
4391       user_op.set_temp_url_key(iter->second, iter->first);
4392     }
4393   }
4394
4395   if (!op_mask_str.empty()) {
4396     uint32_t op_mask;
4397     int ret = rgw_parse_op_type_list(op_mask_str, &op_mask);
4398     if (ret < 0) {
4399       cerr << "failed to parse op_mask: " << cpp_strerror(-ret) << std::endl;
4400       return -ret;
4401     }
4402
4403     user_op.set_op_mask(op_mask);
4404   }
4405
4406   if (key_type != KEY_TYPE_UNDEFINED)
4407     user_op.set_key_type(key_type);
4408
4409   // set suspension operation parameters
4410   if (opt_cmd == OPT_USER_ENABLE)
4411     user_op.set_suspension(false);
4412   else if (opt_cmd == OPT_USER_SUSPEND)
4413     user_op.set_suspension(true);
4414
4415   // RGWUser to use for user operations
4416   RGWUser user;
4417   int ret = 0;
4418   if (!user_id.empty() || !subuser.empty()) {
4419     ret = user.init(store, user_op);
4420     if (ret < 0) {
4421       cerr << "user.init failed: " << cpp_strerror(-ret) << std::endl;
4422       return -ret;
4423     }
4424   }
4425
4426   /* populate bucket operation */
4427   bucket_op.set_bucket_name(bucket_name);
4428   bucket_op.set_object(object);
4429   bucket_op.set_check_objects(check_objects);
4430   bucket_op.set_delete_children(delete_child_objects);
4431   bucket_op.set_fix_index(fix);
4432   bucket_op.set_max_aio(max_concurrent_ios);
4433
4434   // required to gather errors from operations
4435   std::string err_msg;
4436
4437   bool output_user_info = true;
4438
4439   switch (opt_cmd) {
4440   case OPT_USER_INFO:
4441     break;
4442   case OPT_USER_CREATE:
4443     if (!user_op.has_existing_user()) {
4444       user_op.set_generate_key(); // generate a new key by default
4445     }
4446     ret = user.add(user_op, &err_msg);
4447     if (ret < 0) {
4448       cerr << "could not create user: " << err_msg << std::endl;
4449       if (ret == -ERR_INVALID_TENANT_NAME)
4450         ret = -EINVAL;
4451
4452       return -ret;
4453     }
4454     if (!subuser.empty()) {
4455       ret = user.subusers.add(user_op, &err_msg);
4456       if (ret < 0) {
4457         cerr << "could not create subuser: " << err_msg << std::endl;
4458         return -ret;
4459       }
4460     }
4461     break;
4462   case OPT_USER_RM:
4463     ret = user.remove(user_op, &err_msg);
4464     if (ret < 0) {
4465       cerr << "could not remove user: " << err_msg << std::endl;
4466       return -ret;
4467     }
4468
4469     output_user_info = false;
4470     break;
4471   case OPT_USER_ENABLE:
4472   case OPT_USER_SUSPEND:
4473   case OPT_USER_MODIFY:
4474     ret = user.modify(user_op, &err_msg);
4475     if (ret < 0) {
4476       cerr << "could not modify user: " << err_msg << std::endl;
4477       return -ret;
4478     }
4479
4480     break;
4481   case OPT_SUBUSER_CREATE:
4482     ret = user.subusers.add(user_op, &err_msg);
4483     if (ret < 0) {
4484       cerr << "could not create subuser: " << err_msg << std::endl;
4485       return -ret;
4486     }
4487
4488     break;
4489   case OPT_SUBUSER_MODIFY:
4490     ret = user.subusers.modify(user_op, &err_msg);
4491     if (ret < 0) {
4492       cerr << "could not modify subuser: " << err_msg << std::endl;
4493       return -ret;
4494     }
4495
4496     break;
4497   case OPT_SUBUSER_RM:
4498     ret = user.subusers.remove(user_op, &err_msg);
4499     if (ret < 0) {
4500       cerr << "could not remove subuser: " << err_msg << std::endl;
4501       return -ret;
4502     }
4503
4504     break;
4505   case OPT_CAPS_ADD:
4506     ret = user.caps.add(user_op, &err_msg);
4507     if (ret < 0) {
4508       cerr << "could not add caps: " << err_msg << std::endl;
4509       return -ret;
4510     }
4511
4512     break;
4513   case OPT_CAPS_RM:
4514     ret = user.caps.remove(user_op, &err_msg);
4515     if (ret < 0) {
4516       cerr << "could not remove caps: " << err_msg << std::endl;
4517       return -ret;
4518     }
4519
4520     break;
4521   case OPT_KEY_CREATE:
4522     ret = user.keys.add(user_op, &err_msg);
4523     if (ret < 0) {
4524       cerr << "could not create key: " << err_msg << std::endl;
4525       return -ret;
4526     }
4527
4528     break;
4529   case OPT_KEY_RM:
4530     ret = user.keys.remove(user_op, &err_msg);
4531     if (ret < 0) {
4532       cerr << "could not remove key: " << err_msg << std::endl;
4533       return -ret;
4534     }
4535     break;
4536   case OPT_PERIOD_PUSH:
4537     {
4538       RGWEnv env;
4539       req_info info(g_ceph_context, &env);
4540       info.method = "POST";
4541       info.request_uri = "/admin/realm/period";
4542
4543       map<string, string> &params = info.args.get_params();
4544       if (!realm_id.empty())
4545         params["realm_id"] = realm_id;
4546       if (!realm_name.empty())
4547         params["realm_name"] = realm_name;
4548       if (!period_id.empty())
4549         params["period_id"] = period_id;
4550       if (!period_epoch.empty())
4551         params["epoch"] = period_epoch;
4552
4553       // load the period
4554       RGWPeriod period(period_id);
4555       int ret = period.init(g_ceph_context, store);
4556       if (ret < 0) {
4557         cerr << "period init failed: " << cpp_strerror(-ret) << std::endl;
4558         return -ret;
4559       }
4560       // json format into a bufferlist
4561       JSONFormatter jf(false);
4562       encode_json("period", period, &jf);
4563       bufferlist bl;
4564       jf.flush(bl);
4565
4566       JSONParser p;
4567       ret = send_to_remote_or_url(nullptr, url, access_key, secret_key,
4568                                   info, bl, p);
4569       if (ret < 0) {
4570         cerr << "request failed: " << cpp_strerror(-ret) << std::endl;
4571         return -ret;
4572       }
4573     }
4574     return 0;
4575   case OPT_PERIOD_UPDATE:
4576     {
4577       int ret = update_period(realm_id, realm_name, period_id, period_epoch,
4578                               commit, remote, url, access_key, secret_key,
4579                               formatter, yes_i_really_mean_it);
4580       if (ret < 0) {
4581         return -ret;
4582       }
4583     }
4584     return 0;
4585   case OPT_PERIOD_COMMIT:
4586     {
4587       // read realm and staging period
4588       RGWRealm realm(realm_id, realm_name);
4589       int ret = realm.init(g_ceph_context, store);
4590       if (ret < 0) {
4591         cerr << "Error initializing realm: " << cpp_strerror(-ret) << std::endl;
4592         return -ret;
4593       }
4594       RGWPeriod period(RGWPeriod::get_staging_id(realm.get_id()), 1);
4595       ret = period.init(g_ceph_context, store, realm.get_id());
4596       if (ret < 0) {
4597         cerr << "period init failed: " << cpp_strerror(-ret) << std::endl;
4598         return -ret;
4599       }
4600       ret = commit_period(realm, period, remote, url, access_key, secret_key,
4601                           yes_i_really_mean_it);
4602       if (ret < 0) {
4603         cerr << "failed to commit period: " << cpp_strerror(-ret) << std::endl;
4604         return -ret;
4605       }
4606
4607       encode_json("period", period, formatter);
4608       formatter->flush(cout);
4609       cout << std::endl;
4610     }
4611     return 0;
4612   case OPT_ROLE_CREATE:
4613     {
4614       if (role_name.empty()) {
4615         cerr << "ERROR: role name is empty" << std::endl;
4616         return -EINVAL;
4617       }
4618
4619       if (assume_role_doc.empty()) {
4620         cerr << "ERROR: assume role policy document is empty" << std::endl;
4621         return -EINVAL;
4622       }
4623       /* The following two calls will be replaced by read_decode_json or something
4624          similar when the code for AWS Policies is in places */
4625       bufferlist bl;
4626       int ret = read_input(assume_role_doc, bl);
4627       if (ret < 0) {
4628         cerr << "ERROR: failed to read input: " << cpp_strerror(-ret) << std::endl;
4629         return ret;
4630       }
4631       JSONParser p;
4632       if (!p.parse(bl.c_str(), bl.length())) {
4633         cout << "ERROR: failed to parse JSON: " << assume_role_doc << std::endl;
4634         return -EINVAL;
4635       }
4636       string trust_policy = bl.to_str();
4637       RGWRole role(g_ceph_context, store, role_name, path, trust_policy, tenant);
4638       ret = role.create(true);
4639       if (ret < 0) {
4640         return -ret;
4641       }
4642       show_role_info(role, formatter);
4643       return 0;
4644     }
4645   case OPT_ROLE_DELETE:
4646     {
4647       if (role_name.empty()) {
4648         cerr << "ERROR: empty role name" << std::endl;
4649         return -EINVAL;
4650       }
4651       RGWRole role(g_ceph_context, store, role_name, tenant);
4652       ret = role.delete_obj();
4653       if (ret < 0) {
4654         return -ret;
4655       }
4656       cout << "role: " << role_name << " successfully deleted" << std::endl;
4657       return 0;
4658     }
4659   case OPT_ROLE_GET:
4660     {
4661       if (role_name.empty()) {
4662         cerr << "ERROR: empty role name" << std::endl;
4663         return -EINVAL;
4664       }
4665       RGWRole role(g_ceph_context, store, role_name, tenant);
4666       ret = role.get();
4667       if (ret < 0) {
4668         return -ret;
4669       }
4670       show_role_info(role, formatter);
4671       return 0;
4672     }
4673   case OPT_ROLE_MODIFY:
4674     {
4675       if (role_name.empty()) {
4676         cerr << "ERROR: role name is empty" << std::endl;
4677         return -EINVAL;
4678       }
4679
4680       if (assume_role_doc.empty()) {
4681         cerr << "ERROR: assume role policy document is empty" << std::endl;
4682         return -EINVAL;
4683       }
4684
4685       /* The following two calls will be replaced by read_decode_json or something
4686          similar when the code for AWS Policies is in place */
4687       bufferlist bl;
4688       int ret = read_input(assume_role_doc, bl);
4689       if (ret < 0) {
4690         cerr << "ERROR: failed to read input: " << cpp_strerror(-ret) << std::endl;
4691         return ret;
4692       }
4693       JSONParser p;
4694       if (!p.parse(bl.c_str(), bl.length())) {
4695         cout << "ERROR: failed to parse JSON: " << assume_role_doc << std::endl;
4696         return -EINVAL;
4697       }
4698       string trust_policy = bl.to_str();
4699       RGWRole role(g_ceph_context, store, role_name, tenant);
4700       ret = role.get();
4701       if (ret < 0) {
4702         return -ret;
4703       }
4704       role.update_trust_policy(trust_policy);
4705       ret = role.update();
4706       if (ret < 0) {
4707         return -ret;
4708       }
4709       cout << "Assume role policy document updated successfully for role: " << role_name << std::endl;
4710       return 0;
4711     }
4712   case OPT_ROLE_LIST:
4713     {
4714       vector<RGWRole> result;
4715       ret = RGWRole::get_roles_by_path_prefix(store, g_ceph_context, path_prefix, tenant, result);
4716       if (ret < 0) {
4717         return -ret;
4718       }
4719       show_roles_info(result, formatter);
4720       return 0;
4721     }
4722   case OPT_ROLE_POLICY_PUT:
4723     {
4724       if (role_name.empty()) {
4725         cerr << "role name is empty" << std::endl;
4726         return -EINVAL;
4727       }
4728
4729       if (policy_name.empty()) {
4730         cerr << "policy name is empty" << std::endl;
4731         return -EINVAL;
4732       }
4733
4734       if (perm_policy_doc.empty()) {
4735         cerr << "permission policy document is empty" << std::endl;
4736         return -EINVAL;
4737       }
4738
4739       /* The following two calls will be replaced by read_decode_json or something
4740          similar, when code for AWS Policies is in place.*/
4741       bufferlist bl;
4742       int ret = read_input(perm_policy_doc, bl);
4743       if (ret < 0) {
4744         cerr << "ERROR: failed to read input: " << cpp_strerror(-ret) << std::endl;
4745         return ret;
4746       }
4747       JSONParser p;
4748       if (!p.parse(bl.c_str(), bl.length())) {
4749         cout << "ERROR: failed to parse JSON: " << std::endl;
4750         return -EINVAL;
4751       }
4752       string perm_policy;
4753       perm_policy = bl.c_str();
4754
4755       RGWRole role(g_ceph_context, store, role_name, tenant);
4756       ret = role.get();
4757       if (ret < 0) {
4758         return -ret;
4759       }
4760       role.set_perm_policy(policy_name, perm_policy);
4761       ret = role.update();
4762       if (ret < 0) {
4763         return -ret;
4764       }
4765       cout << "Permission policy attached successfully" << std::endl;
4766       return 0;
4767     }
4768   case OPT_ROLE_POLICY_LIST:
4769     {
4770       if (role_name.empty()) {
4771         cerr << "ERROR: Role name is empty" << std::endl;
4772         return -EINVAL;
4773       }
4774       RGWRole role(g_ceph_context, store, role_name, tenant);
4775       ret = role.get();
4776       if (ret < 0) {
4777         return -ret;
4778       }
4779       std::vector<string> policy_names = role.get_role_policy_names();
4780       show_policy_names(policy_names, formatter);
4781       return 0;
4782     }
4783   case OPT_ROLE_POLICY_GET:
4784     {
4785       if (role_name.empty()) {
4786         cerr << "ERROR: role name is empty" << std::endl;
4787         return -EINVAL;
4788       }
4789
4790       if (policy_name.empty()) {
4791         cerr << "ERROR: policy name is empty" << std::endl;
4792         return -EINVAL;
4793       }
4794       RGWRole role(g_ceph_context, store, role_name, tenant);
4795       int ret = role.get();
4796       if (ret < 0) {
4797         return -ret;
4798       }
4799       string perm_policy;
4800       ret = role.get_role_policy(policy_name, perm_policy);
4801       if (ret < 0) {
4802         return -ret;
4803       }
4804       show_perm_policy(perm_policy, formatter);
4805       return 0;
4806     }
4807   case OPT_ROLE_POLICY_DELETE:
4808     {
4809       if (role_name.empty()) {
4810         cerr << "ERROR: role name is empty" << std::endl;
4811         return -EINVAL;
4812       }
4813
4814       if (policy_name.empty()) {
4815         cerr << "ERROR: policy name is empty" << std::endl;
4816         return -EINVAL;
4817       }
4818       RGWRole role(g_ceph_context, store, role_name, tenant);
4819       ret = role.get();
4820       if (ret < 0) {
4821         return -ret;
4822       }
4823       ret = role.delete_policy(policy_name);
4824       if (ret < 0) {
4825         return -ret;
4826       }
4827       ret = role.update();
4828       if (ret < 0) {
4829         return -ret;
4830       }
4831       cout << "Policy: " << policy_name << " successfully deleted for role: "
4832            << role_name << std::endl;
4833       return 0;
4834   }
4835   default:
4836     output_user_info = false;
4837   }
4838
4839   // output the result of a user operation
4840   if (output_user_info) {
4841     ret = user.info(info, &err_msg);
4842     if (ret < 0) {
4843       cerr << "could not fetch user info: " << err_msg << std::endl;
4844       return -ret;
4845     }
4846     show_user_info(info, formatter);
4847   }
4848
4849   if (opt_cmd == OPT_POLICY) {
4850     if (format == "xml") {
4851       int ret = RGWBucketAdminOp::dump_s3_policy(store, bucket_op, cout);
4852       if (ret < 0) {
4853         cerr << "ERROR: failed to get policy: " << cpp_strerror(-ret) << std::endl;
4854         return -ret;
4855       }
4856     } else {
4857       int ret = RGWBucketAdminOp::get_policy(store, bucket_op, f);
4858       if (ret < 0) {
4859         cerr << "ERROR: failed to get policy: " << cpp_strerror(-ret) << std::endl;
4860         return -ret;
4861       }
4862     }
4863   }
4864
4865   if (opt_cmd == OPT_BUCKET_LIMIT_CHECK) {
4866     void *handle;
4867     std::list<std::string> user_ids;
4868     metadata_key = "user";
4869     int max = 1000;
4870
4871     bool truncated;
4872
4873     if (! user_id.empty()) {
4874       user_ids.push_back(user_id.id);
4875       ret =
4876         RGWBucketAdminOp::limit_check(store, bucket_op, user_ids, f,
4877           warnings_only);
4878     } else {
4879       /* list users in groups of max-keys, then perform user-bucket
4880        * limit-check on each group */
4881      ret = store->meta_mgr->list_keys_init(metadata_key, &handle);
4882       if (ret < 0) {
4883         cerr << "ERROR: buckets limit check can't get user metadata_key: "
4884              << cpp_strerror(-ret) << std::endl;
4885         return -ret;
4886       }
4887
4888       do {
4889         ret = store->meta_mgr->list_keys_next(handle, max, user_ids,
4890                                               &truncated);
4891         if (ret < 0 && ret != -ENOENT) {
4892           cerr << "ERROR: buckets limit check lists_keys_next(): "
4893                << cpp_strerror(-ret) << std::endl;
4894           break;
4895         } else {
4896           /* ok, do the limit checks for this group */
4897           ret =
4898             RGWBucketAdminOp::limit_check(store, bucket_op, user_ids, f,
4899               warnings_only);
4900           if (ret < 0)
4901             break;
4902         }
4903         user_ids.clear();
4904       } while (truncated);
4905       store->meta_mgr->list_keys_complete(handle);
4906     }
4907     return -ret;
4908   } /* OPT_BUCKET_LIMIT_CHECK */
4909
4910   if (opt_cmd == OPT_BUCKETS_LIST) {
4911     if (bucket_name.empty()) {
4912       RGWBucketAdminOp::info(store, bucket_op, f);
4913     } else {
4914       RGWBucketInfo bucket_info;
4915       int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
4916       if (ret < 0) {
4917         cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
4918         return -ret;
4919       }
4920       formatter->open_array_section("entries");
4921       bool truncated;
4922       int count = 0;
4923       if (max_entries < 0)
4924         max_entries = 1000;
4925
4926       string prefix;
4927       string delim;
4928       vector<rgw_bucket_dir_entry> result;
4929       map<string, bool> common_prefixes;
4930       string ns;
4931
4932       RGWRados::Bucket target(store, bucket_info);
4933       RGWRados::Bucket::List list_op(&target);
4934
4935       list_op.params.prefix = prefix;
4936       list_op.params.delim = delim;
4937       list_op.params.marker = rgw_obj_key(marker);
4938       list_op.params.ns = ns;
4939       list_op.params.enforce_ns = false;
4940       list_op.params.list_versions = true;
4941
4942       do {
4943         ret = list_op.list_objects(max_entries - count, &result, &common_prefixes, &truncated);
4944         if (ret < 0) {
4945           cerr << "ERROR: store->list_objects(): " << cpp_strerror(-ret) << std::endl;
4946           return -ret;
4947         }
4948
4949         count += result.size();
4950
4951         for (vector<rgw_bucket_dir_entry>::iterator iter = result.begin(); iter != result.end(); ++iter) {
4952           rgw_bucket_dir_entry& entry = *iter;
4953           encode_json("entry", entry, formatter);
4954         }
4955         formatter->flush(cout);
4956       } while (truncated && count < max_entries);
4957
4958       formatter->close_section();
4959       formatter->flush(cout);
4960     } /* have bucket_name */
4961   } /* OPT_BUCKETS_LIST */
4962
4963   if (opt_cmd == OPT_BUCKET_STATS) {
4964     bucket_op.set_fetch_stats(true);
4965
4966     int r = RGWBucketAdminOp::info(store, bucket_op, f);
4967     if (r < 0) {
4968       cerr << "failure: " << cpp_strerror(-r) << ": " << err << std::endl;
4969       return -r;
4970     }
4971   }
4972
4973   if (opt_cmd == OPT_BUCKET_LINK) {
4974     bucket_op.set_bucket_id(bucket_id);
4975     string err;
4976     int r = RGWBucketAdminOp::link(store, bucket_op, &err);
4977     if (r < 0) {
4978       cerr << "failure: " << cpp_strerror(-r) << ": " << err << std::endl;
4979       return -r;
4980     }
4981   }
4982
4983   if (opt_cmd == OPT_BUCKET_UNLINK) {
4984     int r = RGWBucketAdminOp::unlink(store, bucket_op);
4985     if (r < 0) {
4986       cerr << "failure: " << cpp_strerror(-r) << std::endl;
4987       return -r;
4988     }
4989   }
4990
4991   if (opt_cmd == OPT_LOG_LIST) {
4992     // filter by date?
4993     if (date.size() && date.size() != 10) {
4994       cerr << "bad date format for '" << date << "', expect YYYY-MM-DD" << std::endl;
4995       return EINVAL;
4996     }
4997
4998     formatter->reset();
4999     formatter->open_array_section("logs");
5000     RGWAccessHandle h;
5001     int r = store->log_list_init(date, &h);
5002     if (r == -ENOENT) {
5003       // no logs.
5004     } else {
5005       if (r < 0) {
5006         cerr << "log list: error " << r << std::endl;
5007         return -r;
5008       }
5009       while (true) {
5010         string name;
5011         int r = store->log_list_next(h, &name);
5012         if (r == -ENOENT)
5013           break;
5014         if (r < 0) {
5015           cerr << "log list: error " << r << std::endl;
5016           return -r;
5017         }
5018         formatter->dump_string("object", name);
5019       }
5020     }
5021     formatter->close_section();
5022     formatter->flush(cout);
5023     cout << std::endl;
5024   }
5025
5026   if (opt_cmd == OPT_LOG_SHOW || opt_cmd == OPT_LOG_RM) {
5027     if (object.empty() && (date.empty() || bucket_name.empty() || bucket_id.empty())) {
5028       cerr << "specify an object or a date, bucket and bucket-id" << std::endl;
5029       usage();
5030       assert(false);
5031     }
5032
5033     string oid;
5034     if (!object.empty()) {
5035       oid = object;
5036     } else {
5037       oid = date;
5038       oid += "-";
5039       oid += bucket_id;
5040       oid += "-";
5041       oid += bucket_name;
5042     }
5043
5044     if (opt_cmd == OPT_LOG_SHOW) {
5045       RGWAccessHandle h;
5046
5047       int r = store->log_show_init(oid, &h);
5048       if (r < 0) {
5049         cerr << "error opening log " << oid << ": " << cpp_strerror(-r) << std::endl;
5050         return -r;
5051       }
5052
5053       formatter->reset();
5054       formatter->open_object_section("log");
5055
5056       struct rgw_log_entry entry;
5057
5058       // peek at first entry to get bucket metadata
5059       r = store->log_show_next(h, &entry);
5060       if (r < 0) {
5061         cerr << "error reading log " << oid << ": " << cpp_strerror(-r) << std::endl;
5062         return -r;
5063       }
5064       formatter->dump_string("bucket_id", entry.bucket_id);
5065       formatter->dump_string("bucket_owner", entry.bucket_owner.to_str());
5066       formatter->dump_string("bucket", entry.bucket);
5067
5068       uint64_t agg_time = 0;
5069       uint64_t agg_bytes_sent = 0;
5070       uint64_t agg_bytes_received = 0;
5071       uint64_t total_entries = 0;
5072
5073       if (show_log_entries)
5074         formatter->open_array_section("log_entries");
5075
5076       do {
5077         uint64_t total_time =  entry.total_time.sec() * 1000000LL + entry.total_time.usec();
5078
5079         agg_time += total_time;
5080         agg_bytes_sent += entry.bytes_sent;
5081         agg_bytes_received += entry.bytes_received;
5082         total_entries++;
5083
5084         if (skip_zero_entries && entry.bytes_sent == 0 &&
5085             entry.bytes_received == 0)
5086           goto next;
5087
5088         if (show_log_entries) {
5089
5090           rgw_format_ops_log_entry(entry, formatter);
5091           formatter->flush(cout);
5092         }
5093 next:
5094         r = store->log_show_next(h, &entry);
5095       } while (r > 0);
5096
5097       if (r < 0) {
5098         cerr << "error reading log " << oid << ": " << cpp_strerror(-r) << std::endl;
5099         return -r;
5100       }
5101       if (show_log_entries)
5102         formatter->close_section();
5103
5104       if (show_log_sum) {
5105         formatter->open_object_section("log_sum");
5106         formatter->dump_int("bytes_sent", agg_bytes_sent);
5107         formatter->dump_int("bytes_received", agg_bytes_received);
5108         formatter->dump_int("total_time", agg_time);
5109         formatter->dump_int("total_entries", total_entries);
5110         formatter->close_section();
5111       }
5112       formatter->close_section();
5113       formatter->flush(cout);
5114       cout << std::endl;
5115     }
5116     if (opt_cmd == OPT_LOG_RM) {
5117       int r = store->log_remove(oid);
5118       if (r < 0) {
5119         cerr << "error removing log " << oid << ": " << cpp_strerror(-r) << std::endl;
5120         return -r;
5121       }
5122     }
5123   }
5124
5125   if (opt_cmd == OPT_POOL_ADD) {
5126     if (pool_name.empty()) {
5127       cerr << "need to specify pool to add!" << std::endl;
5128       usage();
5129       assert(false);
5130     }
5131
5132     int ret = store->add_bucket_placement(pool);
5133     if (ret < 0)
5134       cerr << "failed to add bucket placement: " << cpp_strerror(-ret) << std::endl;
5135   }
5136
5137   if (opt_cmd == OPT_POOL_RM) {
5138     if (pool_name.empty()) {
5139       cerr << "need to specify pool to remove!" << std::endl;
5140       usage();
5141       assert(false);
5142     }
5143
5144     int ret = store->remove_bucket_placement(pool);
5145     if (ret < 0)
5146       cerr << "failed to remove bucket placement: " << cpp_strerror(-ret) << std::endl;
5147   }
5148
5149   if (opt_cmd == OPT_POOLS_LIST) {
5150     set<rgw_pool> pools;
5151     int ret = store->list_placement_set(pools);
5152     if (ret < 0) {
5153       cerr << "could not list placement set: " << cpp_strerror(-ret) << std::endl;
5154       return -ret;
5155     }
5156     formatter->reset();
5157     formatter->open_array_section("pools");
5158     for (auto siter = pools.begin(); siter != pools.end(); ++siter) {
5159       formatter->open_object_section("pool");
5160       formatter->dump_string("name",  siter->to_str());
5161       formatter->close_section();
5162     }
5163     formatter->close_section();
5164     formatter->flush(cout);
5165     cout << std::endl;
5166   }
5167
5168   if (opt_cmd == OPT_USAGE_SHOW) {
5169     uint64_t start_epoch = 0;
5170     uint64_t end_epoch = (uint64_t)-1;
5171
5172     int ret;
5173
5174     if (!start_date.empty()) {
5175       ret = utime_t::parse_date(start_date, &start_epoch, NULL);
5176       if (ret < 0) {
5177         cerr << "ERROR: failed to parse start date" << std::endl;
5178         return 1;
5179       }
5180     }
5181     if (!end_date.empty()) {
5182       ret = utime_t::parse_date(end_date, &end_epoch, NULL);
5183       if (ret < 0) {
5184         cerr << "ERROR: failed to parse end date" << std::endl;
5185         return 1;
5186       }
5187     }
5188
5189
5190     ret = RGWUsage::show(store, user_id, start_epoch, end_epoch,
5191                          show_log_entries, show_log_sum, &categories,
5192                          f);
5193     if (ret < 0) {
5194       cerr << "ERROR: failed to show usage" << std::endl;
5195       return 1;
5196     }
5197   }
5198
5199   if (opt_cmd == OPT_USAGE_TRIM) {
5200     if (user_id.empty() && !yes_i_really_mean_it) {
5201       cerr << "usage trim without user specified will remove *all* users data" << std::endl;
5202       cerr << "do you really mean it? (requires --yes-i-really-mean-it)" << std::endl;
5203       return 1;
5204     }
5205     int ret;
5206     uint64_t start_epoch = 0;
5207     uint64_t end_epoch = (uint64_t)-1;
5208
5209
5210     if (!start_date.empty()) {
5211       ret = utime_t::parse_date(start_date, &start_epoch, NULL);
5212       if (ret < 0) {
5213         cerr << "ERROR: failed to parse start date" << std::endl;
5214         return 1;
5215       }
5216     }
5217
5218     if (!end_date.empty()) {
5219       ret = utime_t::parse_date(end_date, &end_epoch, NULL);
5220       if (ret < 0) {
5221         cerr << "ERROR: failed to parse end date" << std::endl;
5222         return 1;
5223       }
5224     }
5225
5226     ret = RGWUsage::trim(store, user_id, start_epoch, end_epoch);
5227     if (ret < 0) {
5228       cerr << "ERROR: read_usage() returned ret=" << ret << std::endl;
5229       return 1;
5230     }
5231   }
5232
5233   if (opt_cmd == OPT_OLH_GET || opt_cmd == OPT_OLH_READLOG) {
5234     if (bucket_name.empty()) {
5235       cerr << "ERROR: bucket not specified" << std::endl;
5236       return EINVAL;
5237     }
5238     if (object.empty()) {
5239       cerr << "ERROR: object not specified" << std::endl;
5240       return EINVAL;
5241     }
5242   }
5243
5244   if (opt_cmd == OPT_OLH_GET) {
5245     RGWBucketInfo bucket_info;
5246     int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
5247     if (ret < 0) {
5248       cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
5249       return -ret;
5250     }
5251     RGWOLHInfo olh;
5252     rgw_obj obj(bucket, object);
5253     ret = store->get_olh(bucket_info, obj, &olh);
5254     if (ret < 0) {
5255       cerr << "ERROR: failed reading olh: " << cpp_strerror(-ret) << std::endl;
5256       return -ret;
5257     }
5258     encode_json("olh", olh, formatter);
5259     formatter->flush(cout);
5260   }
5261
5262   if (opt_cmd == OPT_OLH_READLOG) {
5263     RGWBucketInfo bucket_info;
5264     int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
5265     if (ret < 0) {
5266       cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
5267       return -ret;
5268     }
5269     map<uint64_t, vector<rgw_bucket_olh_log_entry> > log;
5270     bool is_truncated;
5271
5272     RGWObjectCtx rctx(store);
5273     rgw_obj obj(bucket, object);
5274
5275     RGWObjState *state;
5276
5277     ret = store->get_obj_state(&rctx, bucket_info, obj, &state, false); /* don't follow olh */
5278     if (ret < 0) {
5279       return -ret;
5280     }
5281
5282     ret = store->bucket_index_read_olh_log(bucket_info, *state, obj, 0, &log, &is_truncated);
5283     if (ret < 0) {
5284       cerr << "ERROR: failed reading olh: " << cpp_strerror(-ret) << std::endl;
5285       return -ret;
5286     }
5287     formatter->open_object_section("result");
5288     encode_json("is_truncated", is_truncated, formatter);
5289     encode_json("log", log, formatter);
5290     formatter->close_section();
5291     formatter->flush(cout);
5292   }
5293
5294   if (opt_cmd == OPT_BI_GET) {
5295     RGWBucketInfo bucket_info;
5296     int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
5297     if (ret < 0) {
5298       cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
5299       return -ret;
5300     }
5301     rgw_obj obj(bucket, object);
5302     if (!object_version.empty()) {
5303       obj.key.set_instance(object_version);
5304     }
5305
5306     rgw_cls_bi_entry entry;
5307
5308     ret = store->bi_get(bucket, obj, bi_index_type, &entry);
5309     if (ret < 0) {
5310       cerr << "ERROR: bi_get(): " << cpp_strerror(-ret) << std::endl;
5311       return -ret;
5312     }
5313
5314     encode_json("entry", entry, formatter);
5315     formatter->flush(cout);
5316   }
5317
5318   if (opt_cmd == OPT_BI_PUT) {
5319     RGWBucketInfo bucket_info;
5320     int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
5321     if (ret < 0) {
5322       cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
5323       return -ret;
5324     }
5325
5326     rgw_cls_bi_entry entry;
5327     cls_rgw_obj_key key;
5328     ret = read_decode_json(infile, entry, &key);
5329     if (ret < 0) {
5330       return 1;
5331     }
5332
5333     rgw_obj obj(bucket, key);
5334
5335     ret = store->bi_put(bucket, obj, entry);
5336     if (ret < 0) {
5337       cerr << "ERROR: bi_put(): " << cpp_strerror(-ret) << std::endl;
5338       return -ret;
5339     }
5340   }
5341
5342   if (opt_cmd == OPT_BI_LIST) {
5343     if (bucket_name.empty()) {
5344       cerr << "ERROR: bucket name not specified" << std::endl;
5345       return EINVAL;
5346     }
5347     RGWBucketInfo bucket_info;
5348     int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
5349     if (ret < 0) {
5350       cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
5351       return -ret;
5352     }
5353
5354     list<rgw_cls_bi_entry> entries;
5355     bool is_truncated;
5356     if (max_entries < 0) {
5357       max_entries = 1000;
5358     }
5359
5360     int max_shards = (bucket_info.num_shards > 0 ? bucket_info.num_shards : 1);
5361
5362     formatter->open_array_section("entries");
5363
5364     for (int i = 0; i < max_shards; i++) {
5365       RGWRados::BucketShard bs(store);
5366       int shard_id = (bucket_info.num_shards > 0  ? i : -1);
5367       int ret = bs.init(bucket, shard_id);
5368       marker.clear();
5369
5370       if (ret < 0) {
5371         cerr << "ERROR: bs.init(bucket=" << bucket << ", shard=" << shard_id << "): " << cpp_strerror(-ret) << std::endl;
5372         return -ret;
5373       }
5374
5375       do {
5376         entries.clear();
5377         ret = store->bi_list(bs, object, marker, max_entries, &entries, &is_truncated);
5378         if (ret < 0) {
5379           cerr << "ERROR: bi_list(): " << cpp_strerror(-ret) << std::endl;
5380           return -ret;
5381         }
5382
5383         list<rgw_cls_bi_entry>::iterator iter;
5384         for (iter = entries.begin(); iter != entries.end(); ++iter) {
5385           rgw_cls_bi_entry& entry = *iter;
5386           encode_json("entry", entry, formatter);
5387           marker = entry.idx;
5388         }
5389         formatter->flush(cout);
5390       } while (is_truncated);
5391       formatter->flush(cout);
5392     }
5393     formatter->close_section();
5394     formatter->flush(cout);
5395   }
5396
5397   if (opt_cmd == OPT_BI_PURGE) {
5398     if (bucket_name.empty()) {
5399       cerr << "ERROR: bucket name not specified" << std::endl;
5400       return EINVAL;
5401     }
5402     RGWBucketInfo bucket_info;
5403     int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
5404     if (ret < 0) {
5405       cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
5406       return -ret;
5407     }
5408
5409     RGWBucketInfo cur_bucket_info;
5410     rgw_bucket cur_bucket;
5411     ret = init_bucket(tenant, bucket_name, string(), cur_bucket_info, cur_bucket);
5412     if (ret < 0) {
5413       cerr << "ERROR: could not init current bucket info for bucket_name=" << bucket_name << ": " << cpp_strerror(-ret) << std::endl;
5414       return -ret;
5415     }
5416
5417     if (cur_bucket_info.bucket.bucket_id == bucket_info.bucket.bucket_id && !yes_i_really_mean_it) {
5418       cerr << "specified bucket instance points to a current bucket instance" << std::endl;
5419       cerr << "do you really mean it? (requires --yes-i-really-mean-it)" << std::endl;
5420       return EINVAL;
5421     }
5422
5423     int max_shards = (bucket_info.num_shards > 0 ? bucket_info.num_shards : 1);
5424
5425     for (int i = 0; i < max_shards; i++) {
5426       RGWRados::BucketShard bs(store);
5427       int shard_id = (bucket_info.num_shards > 0  ? i : -1);
5428       int ret = bs.init(bucket, shard_id);
5429       if (ret < 0) {
5430         cerr << "ERROR: bs.init(bucket=" << bucket << ", shard=" << shard_id << "): " << cpp_strerror(-ret) << std::endl;
5431         return -ret;
5432       }
5433
5434       ret = store->bi_remove(bs);
5435       if (ret < 0) {
5436         cerr << "ERROR: failed to remove bucket index object: " << cpp_strerror(-ret) << std::endl;
5437         return -ret;
5438       }
5439     }
5440   }
5441
5442   if (opt_cmd == OPT_OBJECT_RM) {
5443     RGWBucketInfo bucket_info;
5444     int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
5445     if (ret < 0) {
5446       cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
5447       return -ret;
5448     }
5449     rgw_obj_key key(object, object_version);
5450     ret = rgw_remove_object(store, bucket_info, bucket, key);
5451
5452     if (ret < 0) {
5453       cerr << "ERROR: object remove returned: " << cpp_strerror(-ret) << std::endl;
5454       return -ret;
5455     }
5456   }
5457
5458   if (opt_cmd == OPT_OBJECT_REWRITE) {
5459     if (bucket_name.empty()) {
5460       cerr << "ERROR: bucket not specified" << std::endl;
5461       return EINVAL;
5462     }
5463     if (object.empty()) {
5464       cerr << "ERROR: object not specified" << std::endl;
5465       return EINVAL;
5466     }
5467
5468     RGWBucketInfo bucket_info;
5469     int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
5470     if (ret < 0) {
5471       cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
5472       return -ret;
5473     }
5474
5475     rgw_obj obj(bucket, object);
5476     obj.key.set_instance(object_version);
5477     bool need_rewrite = true;
5478     if (min_rewrite_stripe_size > 0) {
5479       ret = check_min_obj_stripe_size(store, bucket_info, obj, min_rewrite_stripe_size, &need_rewrite);
5480       if (ret < 0) {
5481         ldout(store->ctx(), 0) << "WARNING: check_min_obj_stripe_size failed, r=" << ret << dendl;
5482       }
5483     }
5484     if (need_rewrite) {
5485       ret = store->rewrite_obj(bucket_info, obj);
5486       if (ret < 0) {
5487         cerr << "ERROR: object rewrite returned: " << cpp_strerror(-ret) << std::endl;
5488         return -ret;
5489       }
5490     } else {
5491       ldout(store->ctx(), 20) << "skipped object" << dendl;
5492     }
5493   }
5494
5495   if (opt_cmd == OPT_OBJECTS_EXPIRE) {
5496     int ret = store->process_expire_objects();
5497     if (ret < 0) {
5498       cerr << "ERROR: process_expire_objects() processing returned error: " << cpp_strerror(-ret) << std::endl;
5499       return 1;
5500     }
5501   }
5502
5503   if (opt_cmd == OPT_BUCKET_REWRITE) {
5504     if (bucket_name.empty()) {
5505       cerr << "ERROR: bucket not specified" << std::endl;
5506       return EINVAL;
5507     }
5508
5509     RGWBucketInfo bucket_info;
5510     int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
5511     if (ret < 0) {
5512       cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
5513       return -ret;
5514     }
5515
5516     uint64_t start_epoch = 0;
5517     uint64_t end_epoch = 0;
5518
5519     if (!end_date.empty()) {
5520       int ret = utime_t::parse_date(end_date, &end_epoch, NULL);
5521       if (ret < 0) {
5522         cerr << "ERROR: failed to parse end date" << std::endl;
5523         return EINVAL;
5524       }
5525     }
5526     if (!start_date.empty()) {
5527       int ret = utime_t::parse_date(start_date, &start_epoch, NULL);
5528       if (ret < 0) {
5529         cerr << "ERROR: failed to parse start date" << std::endl;
5530         return EINVAL;
5531       }
5532     }
5533
5534     bool is_truncated = true;
5535
5536     rgw_obj_index_key marker;
5537     string prefix;
5538
5539     formatter->open_object_section("result");
5540     formatter->dump_string("bucket", bucket_name);
5541     formatter->open_array_section("objects");
5542     while (is_truncated) {
5543       map<string, rgw_bucket_dir_entry> result;
5544       int r = store->cls_bucket_list(bucket_info, RGW_NO_SHARD, marker, prefix, 1000, true,
5545                                      result, &is_truncated, &marker,
5546                                      bucket_object_check_filter);
5547
5548       if (r < 0 && r != -ENOENT) {
5549         cerr << "ERROR: failed operation r=" << r << std::endl;
5550       }
5551
5552       if (r == -ENOENT)
5553         break;
5554
5555       map<string, rgw_bucket_dir_entry>::iterator iter;
5556       for (iter = result.begin(); iter != result.end(); ++iter) {
5557         rgw_obj_key key = iter->second.key;
5558         rgw_bucket_dir_entry& entry = iter->second;
5559
5560         formatter->open_object_section("object");
5561         formatter->dump_string("name", key.name);
5562         formatter->dump_string("instance", key.instance);
5563         formatter->dump_int("size", entry.meta.size);
5564         utime_t ut(entry.meta.mtime);
5565         ut.gmtime(formatter->dump_stream("mtime"));
5566
5567         if ((entry.meta.size < min_rewrite_size) ||
5568             (entry.meta.size > max_rewrite_size) ||
5569             (start_epoch > 0 && start_epoch > (uint64_t)ut.sec()) ||
5570             (end_epoch > 0 && end_epoch < (uint64_t)ut.sec())) {
5571           formatter->dump_string("status", "Skipped");
5572         } else {
5573           rgw_obj obj(bucket, key);
5574
5575           bool need_rewrite = true;
5576           if (min_rewrite_stripe_size > 0) {
5577             r = check_min_obj_stripe_size(store, bucket_info, obj, min_rewrite_stripe_size, &need_rewrite);
5578             if (r < 0) {
5579               ldout(store->ctx(), 0) << "WARNING: check_min_obj_stripe_size failed, r=" << r << dendl;
5580             }
5581           }
5582           if (!need_rewrite) {
5583             formatter->dump_string("status", "Skipped");
5584           } else {
5585             r = store->rewrite_obj(bucket_info, obj);
5586             if (r == 0) {
5587               formatter->dump_string("status", "Success");
5588             } else {
5589               formatter->dump_string("status", cpp_strerror(-r));
5590             }
5591           }
5592         }
5593         formatter->dump_int("flags", entry.flags);
5594
5595         formatter->close_section();
5596         formatter->flush(cout);
5597       }
5598     }
5599     formatter->close_section();
5600     formatter->close_section();
5601     formatter->flush(cout);
5602   }
5603
5604   if (opt_cmd == OPT_BUCKET_RESHARD) {
5605     rgw_bucket bucket;
5606     RGWBucketInfo bucket_info;
5607     map<string, bufferlist> attrs;
5608
5609     int ret = check_reshard_bucket_params(store,
5610                                           bucket_name,
5611                                           tenant,
5612                                           bucket_id,
5613                                           num_shards_specified,
5614                                           num_shards,
5615                                           yes_i_really_mean_it,
5616                                           bucket,
5617                                           bucket_info,
5618                                           attrs);
5619     if (ret < 0) {
5620       return ret;
5621     }
5622
5623     RGWBucketReshard br(store, bucket_info, attrs);
5624
5625 #define DEFAULT_RESHARD_MAX_ENTRIES 1000
5626     if (max_entries < 1) {
5627       max_entries = DEFAULT_RESHARD_MAX_ENTRIES;
5628     }
5629
5630     return br.execute(num_shards, max_entries,
5631                       verbose, &cout, formatter);
5632   }
5633
5634   if (opt_cmd == OPT_RESHARD_ADD) {
5635     rgw_bucket bucket;
5636     RGWBucketInfo bucket_info;
5637     map<string, bufferlist> attrs;
5638
5639     int ret = check_reshard_bucket_params(store,
5640                                           bucket_name,
5641                                           tenant,
5642                                           bucket_id,
5643                                           num_shards_specified,
5644                                           num_shards,
5645                                           yes_i_really_mean_it,
5646                                           bucket,
5647                                           bucket_info,
5648                                           attrs);
5649     if (ret < 0) {
5650       return ret;
5651     }
5652
5653     int num_source_shards = (bucket_info.num_shards > 0 ? bucket_info.num_shards : 1);
5654
5655     RGWReshard reshard(store);
5656     cls_rgw_reshard_entry entry;
5657     entry.time = real_clock::now();
5658     entry.tenant = tenant;
5659     entry.bucket_name = bucket_name;
5660     entry.bucket_id = bucket_info.bucket.bucket_id;
5661     entry.old_num_shards = num_source_shards;
5662     entry.new_num_shards = num_shards;
5663
5664     return reshard.add(entry);
5665   }
5666
5667   if (opt_cmd == OPT_RESHARD_LIST) {
5668     list<cls_rgw_reshard_entry> entries;
5669     int ret;
5670     int count = 0;
5671     if (max_entries < 0) {
5672       max_entries = 1000;
5673     }
5674
5675     int num_logshards = store->ctx()->_conf->rgw_reshard_num_logs;
5676
5677     RGWReshard reshard(store);
5678
5679     formatter->open_array_section("reshard");
5680     for (int i = 0; i < num_logshards; i++) {
5681       bool is_truncated = true;
5682       string marker;
5683       do {
5684         entries.clear();
5685         ret = reshard.list(i, marker, max_entries, entries, &is_truncated);
5686         if (ret < 0) {
5687           cerr << "Error listing resharding buckets: " << cpp_strerror(-ret) << std::endl;
5688           return ret;
5689         }
5690         for (auto iter=entries.begin(); iter != entries.end(); ++iter) {
5691           cls_rgw_reshard_entry& entry = *iter;
5692           encode_json("entry", entry, formatter);
5693           entry.get_key(&marker);
5694         }
5695         count += entries.size();
5696         formatter->flush(cout);
5697       } while (is_truncated && count < max_entries);
5698
5699       if (count >= max_entries) {
5700         break;
5701       }
5702     }
5703
5704     formatter->close_section();
5705     formatter->flush(cout);
5706     return 0;
5707   }
5708
5709
5710   if (opt_cmd == OPT_RESHARD_STATUS) {
5711     if (bucket_name.empty()) {
5712       cerr << "ERROR: bucket not specified" << std::endl;
5713       return EINVAL;
5714     }
5715
5716     rgw_bucket bucket;
5717     RGWBucketInfo bucket_info;
5718     map<string, bufferlist> attrs;
5719     ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket, &attrs);
5720     if (ret < 0) {
5721       cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
5722       return -ret;
5723     }
5724
5725     RGWBucketReshard br(store, bucket_info, attrs);
5726     list<cls_rgw_bucket_instance_entry> status;
5727     int r = br.get_status(&status);
5728     if (r < 0) {
5729       cerr << "ERROR: could not get resharding status for bucket " << bucket_name << std::endl;
5730       return -r;
5731     }
5732
5733     encode_json("status", status, formatter);
5734     formatter->flush(cout);
5735   }
5736
5737   if (opt_cmd == OPT_RESHARD_PROCESS) {
5738     RGWReshard reshard(store, true, &cout);
5739
5740     int ret = reshard.process_all_logshards();
5741     if (ret < 0) {
5742       cerr << "ERROR: failed to process reshard logs, error=" << cpp_strerror(-ret) << std::endl;
5743       return -ret;
5744     }
5745   }
5746
5747   if (opt_cmd == OPT_RESHARD_CANCEL) {
5748     RGWReshard reshard(store);
5749
5750     if (bucket_name.empty()) {
5751       cerr << "ERROR: bucket not specified" << std::endl;
5752       return EINVAL;
5753     }
5754     cls_rgw_reshard_entry entry;
5755     //entry.tenant = tenant;
5756     entry.bucket_name = bucket_name;
5757     //entry.bucket_id = bucket_id;
5758     int ret = reshard.get(entry);
5759     if (ret < 0) {
5760       cerr << "Error in getting bucket " << bucket_name << ": " << cpp_strerror(-ret) << std::endl;
5761       return ret;
5762     }
5763
5764     /* TBD stop running resharding */
5765
5766     ret =reshard.remove(entry);
5767     if (ret < 0) {
5768       cerr << "Error removing bucket " << bucket_name << " for resharding queue: " << cpp_strerror(-ret) <<
5769         std::endl;
5770       return ret;
5771     }
5772   }
5773
5774   if (opt_cmd == OPT_OBJECT_UNLINK) {
5775     RGWBucketInfo bucket_info;
5776     int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
5777     if (ret < 0) {
5778       cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
5779       return -ret;
5780     }
5781     list<rgw_obj_index_key> oid_list;
5782     rgw_obj_key key(object, object_version);
5783     rgw_obj_index_key index_key;
5784     key.get_index_key(&index_key);
5785     oid_list.push_back(index_key);
5786     ret = store->remove_objs_from_index(bucket_info, oid_list);
5787     if (ret < 0) {
5788       cerr << "ERROR: remove_obj_from_index() returned error: " << cpp_strerror(-ret) << std::endl;
5789       return 1;
5790     }
5791   }
5792
5793   if (opt_cmd == OPT_OBJECT_STAT) {
5794     RGWBucketInfo bucket_info;
5795     int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
5796     if (ret < 0) {
5797       cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
5798       return -ret;
5799     }
5800     rgw_obj obj(bucket, object);
5801     obj.key.set_instance(object_version);
5802
5803     uint64_t obj_size;
5804     map<string, bufferlist> attrs;
5805     RGWObjectCtx obj_ctx(store);
5806     RGWRados::Object op_target(store, bucket_info, obj_ctx, obj);
5807     RGWRados::Object::Read read_op(&op_target);
5808
5809     read_op.params.attrs = &attrs;
5810     read_op.params.obj_size = &obj_size;
5811
5812     ret = read_op.prepare();
5813     if (ret < 0) {
5814       cerr << "ERROR: failed to stat object, returned error: " << cpp_strerror(-ret) << std::endl;
5815       return 1;
5816     }
5817     formatter->open_object_section("object_metadata");
5818     formatter->dump_string("name", object);
5819     formatter->dump_unsigned("size", obj_size);
5820
5821     map<string, bufferlist>::iterator iter;
5822     map<string, bufferlist> other_attrs;
5823     for (iter = attrs.begin(); iter != attrs.end(); ++iter) {
5824       bufferlist& bl = iter->second;
5825       bool handled = false;
5826       if (iter->first == RGW_ATTR_MANIFEST) {
5827         handled = decode_dump<RGWObjManifest>("manifest", bl, formatter);
5828       } else if (iter->first == RGW_ATTR_ACL) {
5829         handled = decode_dump<RGWAccessControlPolicy>("policy", bl, formatter);
5830       } else if (iter->first == RGW_ATTR_ID_TAG) {
5831         handled = dump_string("tag", bl, formatter);
5832       } else if (iter->first == RGW_ATTR_ETAG) {
5833         handled = dump_string("etag", bl, formatter);
5834       }
5835
5836       if (!handled)
5837         other_attrs[iter->first] = bl;
5838     }
5839
5840     formatter->open_object_section("attrs");
5841     for (iter = other_attrs.begin(); iter != other_attrs.end(); ++iter) {
5842       dump_string(iter->first.c_str(), iter->second, formatter);
5843     }
5844     formatter->close_section();
5845     formatter->close_section();
5846     formatter->flush(cout);
5847   }
5848
5849   if (opt_cmd == OPT_BUCKET_CHECK) {
5850     if (check_head_obj_locator) {
5851       if (bucket_name.empty()) {
5852         cerr << "ERROR: need to specify bucket name" << std::endl;
5853         return EINVAL;
5854       }
5855       do_check_object_locator(tenant, bucket_name, fix, remove_bad, formatter);
5856     } else {
5857       RGWBucketAdminOp::check_index(store, bucket_op, f);
5858     }
5859   }
5860
5861   if (opt_cmd == OPT_BUCKET_RM) {
5862     if (inconsistent_index == false) {
5863       RGWBucketAdminOp::remove_bucket(store, bucket_op, bypass_gc, true);
5864     } else {
5865       if (!yes_i_really_mean_it) {
5866         cerr << "using --inconsistent_index can corrupt the bucket index " << std::endl
5867         << "do you really mean it? (requires --yes-i-really-mean-it)" << std::endl;
5868         return 1;
5869       }
5870       RGWBucketAdminOp::remove_bucket(store, bucket_op, bypass_gc, false);
5871     }
5872   }
5873
5874   if (opt_cmd == OPT_GC_LIST) {
5875     int index = 0;
5876     bool truncated;
5877     formatter->open_array_section("entries");
5878
5879     do {
5880       list<cls_rgw_gc_obj_info> result;
5881       int ret = store->list_gc_objs(&index, marker, 1000, !include_all, result, &truncated);
5882       if (ret < 0) {
5883         cerr << "ERROR: failed to list objs: " << cpp_strerror(-ret) << std::endl;
5884         return 1;
5885       }
5886
5887
5888       list<cls_rgw_gc_obj_info>::iterator iter;
5889       for (iter = result.begin(); iter != result.end(); ++iter) {
5890         cls_rgw_gc_obj_info& info = *iter;
5891         formatter->open_object_section("chain_info");
5892         formatter->dump_string("tag", info.tag);
5893         formatter->dump_stream("time") << info.time;
5894         formatter->open_array_section("objs");
5895         list<cls_rgw_obj>::iterator liter;
5896         cls_rgw_obj_chain& chain = info.chain;
5897         for (liter = chain.objs.begin(); liter != chain.objs.end(); ++liter) {
5898           cls_rgw_obj& obj = *liter;
5899           encode_json("obj", obj, formatter);
5900         }
5901         formatter->close_section(); // objs
5902         formatter->close_section(); // obj_chain
5903         formatter->flush(cout);
5904       }
5905     } while (truncated);
5906     formatter->close_section();
5907     formatter->flush(cout);
5908   }
5909
5910   if (opt_cmd == OPT_GC_PROCESS) {
5911     int ret = store->process_gc();
5912     if (ret < 0) {
5913       cerr << "ERROR: gc processing returned error: " << cpp_strerror(-ret) << std::endl;
5914       return 1;
5915     }
5916   }
5917
5918   if (opt_cmd == OPT_LC_LIST) {
5919     formatter->open_array_section("lifecycle_list");
5920     map<string, int> bucket_lc_map;
5921     string marker;
5922 #define MAX_LC_LIST_ENTRIES 100
5923     if (max_entries < 0) {
5924       max_entries = MAX_LC_LIST_ENTRIES;
5925     }
5926     do {
5927       int ret = store->list_lc_progress(marker, max_entries, &bucket_lc_map);
5928       if (ret < 0) {
5929         cerr << "ERROR: failed to list objs: " << cpp_strerror(-ret) << std::endl;
5930         return 1;
5931       }
5932       map<string, int>::iterator iter;
5933       for (iter = bucket_lc_map.begin(); iter != bucket_lc_map.end(); ++iter) {
5934         formatter->open_object_section("bucket_lc_info");
5935         formatter->dump_string("bucket", iter->first);
5936         string lc_status = LC_STATUS[iter->second];
5937         formatter->dump_string("status", lc_status);
5938         formatter->close_section(); // objs
5939         formatter->flush(cout);
5940         marker = iter->first;
5941       }
5942     } while (!bucket_lc_map.empty());
5943
5944     formatter->close_section(); //lifecycle list
5945     formatter->flush(cout);
5946   }
5947
5948
5949   if (opt_cmd == OPT_LC_PROCESS) {
5950     int ret = store->process_lc();
5951     if (ret < 0) {
5952       cerr << "ERROR: lc processing returned error: " << cpp_strerror(-ret) << std::endl;
5953       return 1;
5954     }
5955   }
5956
5957   if (opt_cmd == OPT_ORPHANS_FIND) {
5958     RGWOrphanSearch search(store, max_concurrent_ios, orphan_stale_secs);
5959
5960     if (job_id.empty()) {
5961       cerr << "ERROR: --job-id not specified" << std::endl;
5962       return EINVAL;
5963     }
5964     if (pool_name.empty()) {
5965       cerr << "ERROR: --pool not specified" << std::endl;
5966       return EINVAL;
5967     }
5968
5969     RGWOrphanSearchInfo info;
5970
5971     info.pool = pool;
5972     info.job_name = job_id;
5973     info.num_shards = num_shards;
5974
5975     int ret = search.init(job_id, &info);
5976     if (ret < 0) {
5977       cerr << "could not init search, ret=" << ret << std::endl;
5978       return -ret;
5979     }
5980     ret = search.run();
5981     if (ret < 0) {
5982       return -ret;
5983     }
5984   }
5985
5986   if (opt_cmd == OPT_ORPHANS_FINISH) {
5987     RGWOrphanSearch search(store, max_concurrent_ios, orphan_stale_secs);
5988
5989     if (job_id.empty()) {
5990       cerr << "ERROR: --job-id not specified" << std::endl;
5991       return EINVAL;
5992     }
5993     int ret = search.init(job_id, NULL);
5994     if (ret < 0) {
5995       if (ret == -ENOENT) {
5996         cerr << "job not found" << std::endl;
5997       }
5998       return -ret;
5999     }
6000     ret = search.finish();
6001     if (ret < 0) {
6002       return -ret;
6003     }
6004   }
6005
6006   if (opt_cmd == OPT_ORPHANS_LIST_JOBS){
6007     RGWOrphanStore orphan_store(store);
6008     int ret = orphan_store.init();
6009     if (ret < 0){
6010       cerr << "connection to cluster failed!" << std::endl;
6011       return -ret;
6012     }
6013
6014     map <string,RGWOrphanSearchState> m;
6015     ret = orphan_store.list_jobs(m);
6016     if (ret < 0) {
6017       cerr << "job list failed" << std::endl;
6018       return -ret;
6019     }
6020     formatter->open_array_section("entries");
6021     for (const auto &it: m){
6022       if (!extra_info){
6023         formatter->dump_string("job-id",it.first);
6024       } else {
6025         encode_json("orphan_search_state", it.second, formatter);
6026       }
6027     }
6028     formatter->close_section();
6029     formatter->flush(cout);
6030   }
6031
6032   if (opt_cmd == OPT_USER_CHECK) {
6033     check_bad_user_bucket_mapping(store, user_id, fix);
6034   }
6035
6036   if (opt_cmd == OPT_USER_STATS) {
6037     if (sync_stats) {
6038       if (!bucket_name.empty()) {
6039         int ret = rgw_bucket_sync_user_stats(store, tenant, bucket_name);
6040         if (ret < 0) {
6041           cerr << "ERROR: could not sync bucket stats: " << cpp_strerror(-ret) << std::endl;
6042           return -ret;
6043         }
6044       } else {
6045         int ret = rgw_user_sync_all_stats(store, user_id);
6046         if (ret < 0) {
6047           cerr << "ERROR: failed to sync user stats: " << cpp_strerror(-ret) << std::endl;
6048           return -ret;
6049         }
6050       }
6051     }
6052
6053     if (user_id.empty()) {
6054       cerr << "ERROR: uid not specified" << std::endl;
6055       return EINVAL;
6056     }
6057     cls_user_header header;
6058     string user_str = user_id.to_str();
6059     int ret = store->cls_user_get_header(user_str, &header);
6060     if (ret < 0) {
6061       if (ret == -ENOENT) { /* in case of ENOENT */
6062         cerr << "User has not been initialized or user does not exist" << std::endl;
6063       } else {
6064         cerr << "ERROR: can't read user: " << cpp_strerror(ret) << std::endl;
6065       }
6066       return -ret;
6067     }
6068
6069     encode_json("header", header, formatter);
6070     formatter->flush(cout);
6071   }
6072
6073   if (opt_cmd == OPT_METADATA_GET) {
6074     int ret = store->meta_mgr->get(metadata_key, formatter);
6075     if (ret < 0) {
6076       cerr << "ERROR: can't get key: " << cpp_strerror(-ret) << std::endl;
6077       return -ret;
6078     }
6079
6080     formatter->flush(cout);
6081   }
6082
6083   if (opt_cmd == OPT_METADATA_PUT) {
6084     bufferlist bl;
6085     int ret = read_input(infile, bl);
6086     if (ret < 0) {
6087       cerr << "ERROR: failed to read input: " << cpp_strerror(-ret) << std::endl;
6088       return -ret;
6089     }
6090     ret = store->meta_mgr->put(metadata_key, bl, RGWMetadataHandler::APPLY_ALWAYS);
6091     if (ret < 0) {
6092       cerr << "ERROR: can't put key: " << cpp_strerror(-ret) << std::endl;
6093       return -ret;
6094     }
6095   }
6096
6097   if (opt_cmd == OPT_METADATA_RM) {
6098     int ret = store->meta_mgr->remove(metadata_key);
6099     if (ret < 0) {
6100       cerr << "ERROR: can't remove key: " << cpp_strerror(-ret) << std::endl;
6101       return -ret;
6102     }
6103   }
6104
6105   if (opt_cmd == OPT_METADATA_LIST || opt_cmd == OPT_USER_LIST) {
6106     if (opt_cmd == OPT_USER_LIST) {
6107       metadata_key = "user";
6108     }
6109     void *handle;
6110     int max = 1000;
6111     int ret = store->meta_mgr->list_keys_init(metadata_key, marker, &handle);
6112     if (ret < 0) {
6113       cerr << "ERROR: can't get key: " << cpp_strerror(-ret) << std::endl;
6114       return -ret;
6115     }
6116
6117     bool truncated;
6118     uint64_t count = 0;
6119
6120     if (max_entries_specified) {
6121       formatter->open_object_section("result");
6122     }
6123     formatter->open_array_section("keys");
6124
6125     uint64_t left;
6126     do {
6127       list<string> keys;
6128       left = (max_entries_specified ? max_entries - count : max);
6129       ret = store->meta_mgr->list_keys_next(handle, left, keys, &truncated);
6130       if (ret < 0 && ret != -ENOENT) {
6131         cerr << "ERROR: lists_keys_next(): " << cpp_strerror(-ret) << std::endl;
6132         return -ret;
6133       } if (ret != -ENOENT) {
6134         for (list<string>::iterator iter = keys.begin(); iter != keys.end(); ++iter) {
6135           formatter->dump_string("key", *iter);
6136           ++count;
6137         }
6138         formatter->flush(cout);
6139       }
6140     } while (truncated && left > 0);
6141
6142     formatter->close_section();
6143
6144     if (max_entries_specified) {
6145       encode_json("truncated", truncated, formatter);
6146       encode_json("count", count, formatter);
6147       if (truncated) {
6148         encode_json("marker", store->meta_mgr->get_marker(handle), formatter);
6149       }
6150       formatter->close_section();
6151     }
6152     formatter->flush(cout);
6153
6154     store->meta_mgr->list_keys_complete(handle);
6155   }
6156
6157   if (opt_cmd == OPT_MDLOG_LIST) {
6158     utime_t start_time, end_time;
6159
6160     int ret = parse_date_str(start_date, start_time);
6161     if (ret < 0)
6162       return -ret;
6163
6164     ret = parse_date_str(end_date, end_time);
6165     if (ret < 0)
6166       return -ret;
6167
6168     int i = (specified_shard_id ? shard_id : 0);
6169
6170     if (period_id.empty()) {
6171       int ret = read_current_period_id(store, realm_id, realm_name, &period_id);
6172       if (ret < 0) {
6173         return -ret;
6174       }
6175       std::cerr << "No --period given, using current period="
6176           << period_id << std::endl;
6177     }
6178     RGWMetadataLog *meta_log = store->meta_mgr->get_log(period_id);
6179
6180     formatter->open_array_section("entries");
6181     for (; i < g_ceph_context->_conf->rgw_md_log_max_shards; i++) {
6182       void *handle;
6183       list<cls_log_entry> entries;
6184
6185
6186       meta_log->init_list_entries(i, start_time.to_real_time(), end_time.to_real_time(), marker, &handle);
6187       bool truncated;
6188       do {
6189           int ret = meta_log->list_entries(handle, 1000, entries, NULL, &truncated);
6190         if (ret < 0) {
6191           cerr << "ERROR: meta_log->list_entries(): " << cpp_strerror(-ret) << std::endl;
6192           return -ret;
6193         }
6194
6195         for (list<cls_log_entry>::iterator iter = entries.begin(); iter != entries.end(); ++iter) {
6196           cls_log_entry& entry = *iter;
6197           store->meta_mgr->dump_log_entry(entry, formatter);
6198         }
6199         formatter->flush(cout);
6200       } while (truncated);
6201
6202       meta_log->complete_list_entries(handle);
6203
6204       if (specified_shard_id)
6205         break;
6206     }
6207
6208
6209     formatter->close_section();
6210     formatter->flush(cout);
6211   }
6212
6213   if (opt_cmd == OPT_MDLOG_STATUS) {
6214     int i = (specified_shard_id ? shard_id : 0);
6215
6216     if (period_id.empty()) {
6217       int ret = read_current_period_id(store, realm_id, realm_name, &period_id);
6218       if (ret < 0) {
6219         return -ret;
6220       }
6221       std::cerr << "No --period given, using current period="
6222           << period_id << std::endl;
6223     }
6224     RGWMetadataLog *meta_log = store->meta_mgr->get_log(period_id);
6225
6226     formatter->open_array_section("entries");
6227
6228     for (; i < g_ceph_context->_conf->rgw_md_log_max_shards; i++) {
6229       RGWMetadataLogInfo info;
6230       meta_log->get_info(i, &info);
6231
6232       ::encode_json("info", info, formatter);
6233
6234       if (specified_shard_id)
6235         break;
6236     }
6237
6238
6239     formatter->close_section();
6240     formatter->flush(cout);
6241   }
6242
6243   if (opt_cmd == OPT_MDLOG_AUTOTRIM) {
6244     // need a full history for purging old mdlog periods
6245     store->meta_mgr->init_oldest_log_period();
6246
6247     RGWCoroutinesManager crs(store->ctx(), store->get_cr_registry());
6248     RGWHTTPManager http(store->ctx(), crs.get_completion_mgr());
6249     int ret = http.set_threaded();
6250     if (ret < 0) {
6251       cerr << "failed to initialize http client with " << cpp_strerror(ret) << std::endl;
6252       return -ret;
6253     }
6254
6255     auto num_shards = g_conf->rgw_md_log_max_shards;
6256     ret = crs.run(create_admin_meta_log_trim_cr(store, &http, num_shards));
6257     if (ret < 0) {
6258       cerr << "automated mdlog trim failed with " << cpp_strerror(ret) << std::endl;
6259       return -ret;
6260     }
6261   }
6262
6263   if (opt_cmd == OPT_MDLOG_TRIM) {
6264     utime_t start_time, end_time;
6265
6266     if (!specified_shard_id) {
6267       cerr << "ERROR: shard-id must be specified for trim operation" << std::endl;
6268       return EINVAL;
6269     }
6270
6271     int ret = parse_date_str(start_date, start_time);
6272     if (ret < 0)
6273       return -ret;
6274
6275     ret = parse_date_str(end_date, end_time);
6276     if (ret < 0)
6277       return -ret;
6278
6279     if (period_id.empty()) {
6280       std::cerr << "missing --period argument" << std::endl;
6281       return EINVAL;
6282     }
6283     RGWMetadataLog *meta_log = store->meta_mgr->get_log(period_id);
6284
6285     ret = meta_log->trim(shard_id, start_time.to_real_time(), end_time.to_real_time(), start_marker, end_marker);
6286     if (ret < 0) {
6287       cerr << "ERROR: meta_log->trim(): " << cpp_strerror(-ret) << std::endl;
6288       return -ret;
6289     }
6290   }
6291
6292   if (opt_cmd == OPT_SYNC_STATUS) {
6293     sync_status(formatter);
6294   }
6295
6296   if (opt_cmd == OPT_METADATA_SYNC_STATUS) {
6297     RGWMetaSyncStatusManager sync(store, store->get_async_rados());
6298
6299     int ret = sync.init();
6300     if (ret < 0) {
6301       cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
6302       return -ret;
6303     }
6304
6305     rgw_meta_sync_status sync_status;
6306     ret = sync.read_sync_status(&sync_status);
6307     if (ret < 0) {
6308       cerr << "ERROR: sync.read_sync_status() returned ret=" << ret << std::endl;
6309       return -ret;
6310     }
6311
6312     formatter->open_object_section("summary");
6313     encode_json("sync_status", sync_status, formatter);
6314
6315     uint64_t full_total = 0;
6316     uint64_t full_complete = 0;
6317
6318     for (auto marker_iter : sync_status.sync_markers) {
6319       full_total += marker_iter.second.total_entries;
6320       if (marker_iter.second.state == rgw_meta_sync_marker::SyncState::FullSync) {
6321         full_complete += marker_iter.second.pos;
6322       } else {
6323         full_complete += marker_iter.second.total_entries;
6324       }
6325     }
6326
6327     formatter->open_object_section("full_sync");
6328     encode_json("total", full_total, formatter);
6329     encode_json("complete", full_complete, formatter);
6330     formatter->close_section();
6331     formatter->close_section();
6332
6333     formatter->flush(cout);
6334
6335   }
6336
6337   if (opt_cmd == OPT_METADATA_SYNC_INIT) {
6338     RGWMetaSyncStatusManager sync(store, store->get_async_rados());
6339
6340     int ret = sync.init();
6341     if (ret < 0) {
6342       cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
6343       return -ret;
6344     }
6345     ret = sync.init_sync_status();
6346     if (ret < 0) {
6347       cerr << "ERROR: sync.init_sync_status() returned ret=" << ret << std::endl;
6348       return -ret;
6349     }
6350   }
6351
6352
6353   if (opt_cmd == OPT_METADATA_SYNC_RUN) {
6354     RGWMetaSyncStatusManager sync(store, store->get_async_rados());
6355
6356     int ret = sync.init();
6357     if (ret < 0) {
6358       cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
6359       return -ret;
6360     }
6361
6362     ret = sync.run();
6363     if (ret < 0) {
6364       cerr << "ERROR: sync.run() returned ret=" << ret << std::endl;
6365       return -ret;
6366     }
6367   }
6368
6369   if (opt_cmd == OPT_DATA_SYNC_STATUS) {
6370     if (source_zone.empty()) {
6371       cerr << "ERROR: source zone not specified" << std::endl;
6372       return EINVAL;
6373     }
6374     RGWDataSyncStatusManager sync(store, store->get_async_rados(), source_zone);
6375
6376     int ret = sync.init();
6377     if (ret < 0) {
6378       cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
6379       return -ret;
6380     }
6381
6382     rgw_data_sync_status sync_status;
6383     ret = sync.read_sync_status(&sync_status);
6384     if (ret < 0 && ret != -ENOENT) {
6385       cerr << "ERROR: sync.read_sync_status() returned ret=" << ret << std::endl;
6386       return -ret;
6387     }
6388
6389     formatter->open_object_section("summary");
6390     encode_json("sync_status", sync_status, formatter);
6391
6392     uint64_t full_total = 0;
6393     uint64_t full_complete = 0;
6394
6395     for (auto marker_iter : sync_status.sync_markers) {
6396       full_total += marker_iter.second.total_entries;
6397       if (marker_iter.second.state == rgw_meta_sync_marker::SyncState::FullSync) {
6398         full_complete += marker_iter.second.pos;
6399       } else {
6400         full_complete += marker_iter.second.total_entries;
6401       }
6402     }
6403
6404     formatter->open_object_section("full_sync");
6405     encode_json("total", full_total, formatter);
6406     encode_json("complete", full_complete, formatter);
6407     formatter->close_section();
6408     formatter->close_section();
6409
6410     formatter->flush(cout);
6411   }
6412
6413   if (opt_cmd == OPT_DATA_SYNC_INIT) {
6414     if (source_zone.empty()) {
6415       cerr << "ERROR: source zone not specified" << std::endl;
6416       return EINVAL;
6417     }
6418     RGWDataSyncStatusManager sync(store, store->get_async_rados(), source_zone);
6419
6420     int ret = sync.init();
6421     if (ret < 0) {
6422       cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
6423       return -ret;
6424     }
6425
6426     ret = sync.init_sync_status();
6427     if (ret < 0) {
6428       cerr << "ERROR: sync.init_sync_status() returned ret=" << ret << std::endl;
6429       return -ret;
6430     }
6431   }
6432
6433   if (opt_cmd == OPT_DATA_SYNC_RUN) {
6434     if (source_zone.empty()) {
6435       cerr << "ERROR: source zone not specified" << std::endl;
6436       return EINVAL;
6437     }
6438     RGWDataSyncStatusManager sync(store, store->get_async_rados(), source_zone);
6439
6440     int ret = sync.init();
6441     if (ret < 0) {
6442       cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
6443       return -ret;
6444     }
6445
6446     ret = sync.run();
6447     if (ret < 0) {
6448       cerr << "ERROR: sync.run() returned ret=" << ret << std::endl;
6449       return -ret;
6450     }
6451   }
6452
6453   if (opt_cmd == OPT_BUCKET_SYNC_INIT) {
6454     if (source_zone.empty()) {
6455       cerr << "ERROR: source zone not specified" << std::endl;
6456       return EINVAL;
6457     }
6458     if (bucket_name.empty()) {
6459       cerr << "ERROR: bucket not specified" << std::endl;
6460       return EINVAL;
6461     }
6462     rgw_bucket bucket;
6463     int ret = init_bucket_for_sync(tenant, bucket_name, bucket_id, bucket);
6464     if (ret < 0) {
6465       return -ret;
6466     }
6467     RGWBucketSyncStatusManager sync(store, source_zone, bucket);
6468
6469     ret = sync.init();
6470     if (ret < 0) {
6471       cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
6472       return -ret;
6473     }
6474     ret = sync.init_sync_status();
6475     if (ret < 0) {
6476       cerr << "ERROR: sync.init_sync_status() returned ret=" << ret << std::endl;
6477       return -ret;
6478     }
6479   }
6480
6481   if ((opt_cmd == OPT_BUCKET_SYNC_DISABLE) || (opt_cmd == OPT_BUCKET_SYNC_ENABLE)) {
6482     if (bucket_name.empty()) {
6483       cerr << "ERROR: bucket not specified" << std::endl;
6484       return EINVAL;
6485     }
6486
6487     if (ret < 0) {
6488       cerr << "could not init realm " << ": " << cpp_strerror(-ret) << std::endl;
6489       return ret;
6490     }
6491     RGWPeriod period;
6492     ret = period.init(g_ceph_context, store, realm_id, realm_name, true);
6493     if (ret < 0) {
6494       cerr << "failed to init period " << ": " << cpp_strerror(-ret) << std::endl;
6495       return ret;
6496     }
6497
6498     if (!store->is_meta_master()) {
6499       cerr << "failed to update bucket sync: only allowed on meta master zone "  << std::endl;
6500       cerr << period.get_master_zone() << " | " << period.get_realm() << std::endl;
6501       return EINVAL;
6502     }
6503
6504     rgw_obj obj(bucket, object);
6505     ret = set_bucket_sync_enabled(store, opt_cmd, tenant, bucket_name);
6506     if (ret < 0)
6507       return -ret;
6508 }
6509
6510   if (opt_cmd == OPT_BUCKET_SYNC_STATUS) {
6511     if (source_zone.empty()) {
6512       cerr << "ERROR: source zone not specified" << std::endl;
6513       return EINVAL;
6514     }
6515     if (bucket_name.empty()) {
6516       cerr << "ERROR: bucket not specified" << std::endl;
6517       return EINVAL;
6518     }
6519     rgw_bucket bucket;
6520     int ret = init_bucket_for_sync(tenant, bucket_name, bucket_id, bucket);
6521     if (ret < 0) {
6522       return -ret;
6523     }
6524     RGWBucketSyncStatusManager sync(store, source_zone, bucket);
6525
6526     ret = sync.init();
6527     if (ret < 0) {
6528       cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
6529       return -ret;
6530     }
6531     ret = sync.read_sync_status();
6532     if (ret < 0) {
6533       cerr << "ERROR: sync.read_sync_status() returned ret=" << ret << std::endl;
6534       return -ret;
6535     }
6536
6537     map<int, rgw_bucket_shard_sync_info>& sync_status = sync.get_sync_status();
6538
6539     encode_json("sync_status", sync_status, formatter);
6540     formatter->flush(cout);
6541   }
6542
6543  if (opt_cmd == OPT_BUCKET_SYNC_RUN) {
6544     if (source_zone.empty()) {
6545       cerr << "ERROR: source zone not specified" << std::endl;
6546       return EINVAL;
6547     }
6548     if (bucket_name.empty()) {
6549       cerr << "ERROR: bucket not specified" << std::endl;
6550       return EINVAL;
6551     }
6552     rgw_bucket bucket;
6553     int ret = init_bucket_for_sync(tenant, bucket_name, bucket_id, bucket);
6554     if (ret < 0) {
6555       return -ret;
6556     }
6557     RGWBucketSyncStatusManager sync(store, source_zone, bucket);
6558
6559     ret = sync.init();
6560     if (ret < 0) {
6561       cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
6562       return -ret;
6563     }
6564
6565     ret = sync.run();
6566     if (ret < 0) {
6567       cerr << "ERROR: sync.run() returned ret=" << ret << std::endl;
6568       return -ret;
6569     }
6570   }
6571
6572   if (opt_cmd == OPT_BILOG_LIST) {
6573     if (bucket_name.empty()) {
6574       cerr << "ERROR: bucket not specified" << std::endl;
6575       return EINVAL;
6576     }
6577     RGWBucketInfo bucket_info;
6578     int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
6579     if (ret < 0) {
6580       cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
6581       return -ret;
6582     }
6583     formatter->open_array_section("entries");
6584     bool truncated;
6585     int count = 0;
6586     if (max_entries < 0)
6587       max_entries = 1000;
6588
6589     do {
6590       list<rgw_bi_log_entry> entries;
6591       ret = store->list_bi_log_entries(bucket_info, shard_id, marker, max_entries - count, entries, &truncated);
6592       if (ret < 0) {
6593         cerr << "ERROR: list_bi_log_entries(): " << cpp_strerror(-ret) << std::endl;
6594         return -ret;
6595       }
6596
6597       count += entries.size();
6598
6599       for (list<rgw_bi_log_entry>::iterator iter = entries.begin(); iter != entries.end(); ++iter) {
6600         rgw_bi_log_entry& entry = *iter;
6601         encode_json("entry", entry, formatter);
6602
6603         marker = entry.id;
6604       }
6605       formatter->flush(cout);
6606     } while (truncated && count < max_entries);
6607
6608     formatter->close_section();
6609     formatter->flush(cout);
6610   }
6611
6612   if (opt_cmd == OPT_SYNC_ERROR_LIST) {
6613     if (max_entries < 0) {
6614       max_entries = 1000;
6615     }
6616
6617     bool truncated;
6618     utime_t start_time, end_time;
6619
6620     int ret = parse_date_str(start_date, start_time);
6621     if (ret < 0)
6622       return -ret;
6623
6624     ret = parse_date_str(end_date, end_time);
6625     if (ret < 0)
6626       return -ret;
6627
6628     if (shard_id < 0) {
6629       shard_id = 0;
6630     }
6631
6632     formatter->open_array_section("entries");
6633
6634     for (; shard_id < ERROR_LOGGER_SHARDS; ++shard_id) {
6635       formatter->open_object_section("shard");
6636       encode_json("shard_id", shard_id, formatter);
6637       formatter->open_array_section("entries");
6638
6639       int count = 0;
6640       string oid = RGWSyncErrorLogger::get_shard_oid(RGW_SYNC_ERROR_LOG_SHARD_PREFIX, shard_id);
6641
6642       do {
6643         list<cls_log_entry> entries;
6644         ret = store->time_log_list(oid, start_time.to_real_time(), end_time.to_real_time(),
6645                                    max_entries - count, entries, marker, &marker, &truncated);
6646         if (ret == -ENOENT) {
6647           break;
6648         }
6649         if (ret < 0) {
6650           cerr << "ERROR: store->time_log_list(): " << cpp_strerror(-ret) << std::endl;
6651           return -ret;
6652         }
6653
6654         count += entries.size();
6655
6656         for (auto& cls_entry : entries) {
6657           rgw_sync_error_info log_entry;
6658
6659           auto iter = cls_entry.data.begin();
6660           try {
6661             ::decode(log_entry, iter);
6662           } catch (buffer::error& err) {
6663             cerr << "ERROR: failed to decode log entry" << std::endl;
6664             continue;
6665           }
6666           formatter->open_object_section("entry");
6667           encode_json("id", cls_entry.id, formatter);
6668           encode_json("section", cls_entry.section, formatter);
6669           encode_json("name", cls_entry.name, formatter);
6670           encode_json("timestamp", cls_entry.timestamp, formatter);
6671           encode_json("info", log_entry, formatter);
6672           formatter->close_section();
6673           formatter->flush(cout);
6674         }
6675       } while (truncated && count < max_entries);
6676
6677       formatter->close_section();
6678       formatter->close_section();
6679
6680       if (specified_shard_id) {
6681         break;
6682       }
6683     }
6684
6685     formatter->close_section();
6686     formatter->flush(cout);
6687   }
6688
6689   if (opt_cmd == OPT_BILOG_TRIM) {
6690     if (bucket_name.empty()) {
6691       cerr << "ERROR: bucket not specified" << std::endl;
6692       return EINVAL;
6693     }
6694     RGWBucketInfo bucket_info;
6695     int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
6696     if (ret < 0) {
6697       cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
6698       return -ret;
6699     }
6700     ret = store->trim_bi_log_entries(bucket_info, shard_id, start_marker, end_marker);
6701     if (ret < 0) {
6702       cerr << "ERROR: trim_bi_log_entries(): " << cpp_strerror(-ret) << std::endl;
6703       return -ret;
6704     }
6705   }
6706
6707   if (opt_cmd == OPT_BILOG_STATUS) {
6708     if (bucket_name.empty()) {
6709       cerr << "ERROR: bucket not specified" << std::endl;
6710       return EINVAL;
6711     }
6712     RGWBucketInfo bucket_info;
6713     int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
6714     if (ret < 0) {
6715       cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
6716       return -ret;
6717     }
6718     map<int, string> markers;
6719     ret = store->get_bi_log_status(bucket_info, shard_id, markers);
6720     if (ret < 0) {
6721       cerr << "ERROR: get_bi_log_status(): " << cpp_strerror(-ret) << std::endl;
6722       return -ret;
6723     }
6724     formatter->open_object_section("entries");
6725     encode_json("markers", markers, formatter);
6726     formatter->close_section();
6727     formatter->flush(cout);
6728   }
6729
6730   if (opt_cmd == OPT_DATALOG_LIST) {
6731     formatter->open_array_section("entries");
6732     bool truncated;
6733     int count = 0;
6734     if (max_entries < 0)
6735       max_entries = 1000;
6736
6737     utime_t start_time, end_time;
6738
6739     int ret = parse_date_str(start_date, start_time);
6740     if (ret < 0)
6741       return -ret;
6742
6743     ret = parse_date_str(end_date, end_time);
6744     if (ret < 0)
6745       return -ret;
6746
6747     RGWDataChangesLog *log = store->data_log;
6748     RGWDataChangesLog::LogMarker marker;
6749
6750     do {
6751       list<rgw_data_change_log_entry> entries;
6752       ret = log->list_entries(start_time.to_real_time(), end_time.to_real_time(), max_entries - count, entries, marker, &truncated);
6753       if (ret < 0) {
6754         cerr << "ERROR: list_bi_log_entries(): " << cpp_strerror(-ret) << std::endl;
6755         return -ret;
6756       }
6757
6758       count += entries.size();
6759
6760       for (list<rgw_data_change_log_entry>::iterator iter = entries.begin(); iter != entries.end(); ++iter) {
6761         rgw_data_change_log_entry& entry = *iter;
6762         if (!extra_info) {
6763           encode_json("entry", entry.entry, formatter);
6764         } else {
6765           encode_json("entry", entry, formatter);
6766         }
6767       }
6768       formatter->flush(cout);
6769     } while (truncated && count < max_entries);
6770
6771     formatter->close_section();
6772     formatter->flush(cout);
6773   }
6774
6775   if (opt_cmd == OPT_DATALOG_STATUS) {
6776     RGWDataChangesLog *log = store->data_log;
6777     int i = (specified_shard_id ? shard_id : 0);
6778
6779     formatter->open_array_section("entries");
6780     for (; i < g_ceph_context->_conf->rgw_data_log_num_shards; i++) {
6781       list<cls_log_entry> entries;
6782
6783       RGWDataChangesLogInfo info;
6784       log->get_info(i, &info);
6785
6786       ::encode_json("info", info, formatter);
6787
6788       if (specified_shard_id)
6789         break;
6790     }
6791
6792     formatter->close_section();
6793     formatter->flush(cout);
6794   }
6795
6796   if (opt_cmd == OPT_DATALOG_TRIM) {
6797     utime_t start_time, end_time;
6798
6799     int ret = parse_date_str(start_date, start_time);
6800     if (ret < 0)
6801       return -ret;
6802
6803     ret = parse_date_str(end_date, end_time);
6804     if (ret < 0)
6805       return -ret;
6806
6807     RGWDataChangesLog *log = store->data_log;
6808     ret = log->trim_entries(start_time.to_real_time(), end_time.to_real_time(), start_marker, end_marker);
6809     if (ret < 0) {
6810       cerr << "ERROR: trim_entries(): " << cpp_strerror(-ret) << std::endl;
6811       return -ret;
6812     }
6813   }
6814
6815   if (opt_cmd == OPT_OPSTATE_LIST) {
6816     RGWOpState oc(store);
6817
6818     int max = 1000;
6819
6820     void *handle;
6821     oc.init_list_entries(client_id, op_id, object, &handle);
6822     list<cls_statelog_entry> entries;
6823     bool done;
6824     formatter->open_array_section("entries");
6825     do {
6826       int ret = oc.list_entries(handle, max, entries, &done);
6827       if (ret < 0) {
6828         cerr << "oc.list_entries returned " << cpp_strerror(-ret) << std::endl;
6829         oc.finish_list_entries(handle);
6830         return -ret;
6831       }
6832
6833       for (list<cls_statelog_entry>::iterator iter = entries.begin(); iter != entries.end(); ++iter) {
6834         oc.dump_entry(*iter, formatter);
6835       }
6836
6837       formatter->flush(cout);
6838     } while (!done);
6839     formatter->close_section();
6840     formatter->flush(cout);
6841     oc.finish_list_entries(handle);
6842   }
6843
6844   if (opt_cmd == OPT_OPSTATE_SET || opt_cmd == OPT_OPSTATE_RENEW) {
6845     RGWOpState oc(store);
6846
6847     RGWOpState::OpState state;
6848     if (object.empty() || client_id.empty() || op_id.empty()) {
6849       cerr << "ERROR: need to specify client_id, op_id, and object" << std::endl;
6850       return EINVAL;
6851     }
6852     if (state_str.empty()) {
6853       cerr << "ERROR: state was not specified" << std::endl;
6854       return EINVAL;
6855     }
6856     int ret = oc.state_from_str(state_str, &state);
6857     if (ret < 0) {
6858       cerr << "ERROR: invalid state: " << state_str << std::endl;
6859       return -ret;
6860     }
6861
6862     if (opt_cmd == OPT_OPSTATE_SET) {
6863       ret = oc.set_state(client_id, op_id, object, state);
6864       if (ret < 0) {
6865         cerr << "ERROR: failed to set state: " << cpp_strerror(-ret) << std::endl;
6866         return -ret;
6867       }
6868     } else {
6869       ret = oc.renew_state(client_id, op_id, object, state);
6870       if (ret < 0) {
6871         cerr << "ERROR: failed to renew state: " << cpp_strerror(-ret) << std::endl;
6872         return -ret;
6873       }
6874     }
6875   }
6876   if (opt_cmd == OPT_OPSTATE_RM) {
6877     RGWOpState oc(store);
6878
6879     if (object.empty() || client_id.empty() || op_id.empty()) {
6880       cerr << "ERROR: need to specify client_id, op_id, and object" << std::endl;
6881       return EINVAL;
6882     }
6883     ret = oc.remove_entry(client_id, op_id, object);
6884     if (ret < 0) {
6885       cerr << "ERROR: failed to set state: " << cpp_strerror(-ret) << std::endl;
6886       return -ret;
6887     }
6888   }
6889
6890   if (opt_cmd == OPT_REPLICALOG_GET || opt_cmd == OPT_REPLICALOG_UPDATE ||
6891       opt_cmd == OPT_REPLICALOG_DELETE) {
6892     if (replica_log_type_str.empty()) {
6893       cerr << "ERROR: need to specify --replica-log-type=<metadata | data | bucket>" << std::endl;
6894       return EINVAL;
6895     }
6896   }
6897
6898   if (opt_cmd == OPT_REPLICALOG_GET) {
6899     RGWReplicaBounds bounds;
6900     if (replica_log_type == ReplicaLog_Metadata) {
6901       if (!specified_shard_id) {
6902         cerr << "ERROR: shard-id must be specified for get operation" << std::endl;
6903         return EINVAL;
6904       }
6905
6906       RGWReplicaObjectLogger logger(store, pool, META_REPLICA_LOG_OBJ_PREFIX);
6907       int ret = logger.get_bounds(shard_id, bounds);
6908       if (ret < 0)
6909         return -ret;
6910     } else if (replica_log_type == ReplicaLog_Data) {
6911       if (!specified_shard_id) {
6912         cerr << "ERROR: shard-id must be specified for get operation" << std::endl;
6913         return EINVAL;
6914       }
6915       RGWReplicaObjectLogger logger(store, pool, DATA_REPLICA_LOG_OBJ_PREFIX);
6916       int ret = logger.get_bounds(shard_id, bounds);
6917       if (ret < 0)
6918         return -ret;
6919     } else if (replica_log_type == ReplicaLog_Bucket) {
6920       if (bucket_name.empty()) {
6921         cerr << "ERROR: bucket not specified" << std::endl;
6922         return EINVAL;
6923       }
6924       RGWBucketInfo bucket_info;
6925       int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
6926       if (ret < 0) {
6927         cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
6928         return -ret;
6929       }
6930
6931       RGWReplicaBucketLogger logger(store);
6932       ret = logger.get_bounds(bucket, shard_id, bounds);
6933       if (ret < 0)
6934         return -ret;
6935     } else { // shouldn't get here
6936       ceph_abort();
6937     }
6938     encode_json("bounds", bounds, formatter);
6939     formatter->flush(cout);
6940     cout << std::endl;
6941   }
6942
6943   if (opt_cmd == OPT_REPLICALOG_DELETE) {
6944     if (replica_log_type == ReplicaLog_Metadata) {
6945       if (!specified_shard_id) {
6946         cerr << "ERROR: shard-id must be specified for delete operation" << std::endl;
6947         return EINVAL;
6948       }
6949       if (!specified_daemon_id) {
6950         cerr << "ERROR: daemon-id must be specified for delete operation" << std::endl;
6951         return EINVAL;
6952       }
6953       RGWReplicaObjectLogger logger(store, pool, META_REPLICA_LOG_OBJ_PREFIX);
6954       int ret = logger.delete_bound(shard_id, daemon_id, false);
6955       if (ret < 0)
6956         return -ret;
6957     } else if (replica_log_type == ReplicaLog_Data) {
6958       if (!specified_shard_id) {
6959         cerr << "ERROR: shard-id must be specified for delete operation" << std::endl;
6960         return EINVAL;
6961       }
6962       if (!specified_daemon_id) {
6963         cerr << "ERROR: daemon-id must be specified for delete operation" << std::endl;
6964         return EINVAL;
6965       }
6966       RGWReplicaObjectLogger logger(store, pool, DATA_REPLICA_LOG_OBJ_PREFIX);
6967       int ret = logger.delete_bound(shard_id, daemon_id, false);
6968       if (ret < 0)
6969         return -ret;
6970     } else if (replica_log_type == ReplicaLog_Bucket) {
6971       if (bucket_name.empty()) {
6972         cerr << "ERROR: bucket not specified" << std::endl;
6973         return EINVAL;
6974       }
6975       RGWBucketInfo bucket_info;
6976       int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
6977       if (ret < 0) {
6978         cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
6979         return -ret;
6980       }
6981
6982       RGWReplicaBucketLogger logger(store);
6983       ret = logger.delete_bound(bucket, shard_id, daemon_id, false);
6984       if (ret < 0)
6985         return -ret;
6986     }
6987   }
6988
6989   if (opt_cmd == OPT_REPLICALOG_UPDATE) {
6990     if (marker.empty()) {
6991       cerr << "ERROR: marker was not specified" <<std::endl;
6992       return EINVAL;
6993     }
6994     utime_t time = ceph_clock_now();
6995     if (!date.empty()) {
6996       ret = parse_date_str(date, time);
6997       if (ret < 0) {
6998         cerr << "ERROR: failed to parse start date" << std::endl;
6999         return EINVAL;
7000       }
7001     }
7002     list<RGWReplicaItemMarker> entries;
7003     int ret = read_decode_json(infile, entries);
7004     if (ret < 0) {
7005       cerr << "ERROR: failed to decode entries" << std::endl;
7006       return EINVAL;
7007     }
7008     RGWReplicaBounds bounds;
7009     if (replica_log_type == ReplicaLog_Metadata) {
7010       if (!specified_shard_id) {
7011         cerr << "ERROR: shard-id must be specified for get operation" << std::endl;
7012         return EINVAL;
7013       }
7014
7015       RGWReplicaObjectLogger logger(store, pool, META_REPLICA_LOG_OBJ_PREFIX);
7016       int ret = logger.update_bound(shard_id, daemon_id, marker, time, &entries);
7017       if (ret < 0) {
7018         cerr << "ERROR: failed to update bounds: " << cpp_strerror(-ret) << std::endl;
7019         return -ret;
7020       }
7021     } else if (replica_log_type == ReplicaLog_Data) {
7022       if (!specified_shard_id) {
7023         cerr << "ERROR: shard-id must be specified for get operation" << std::endl;
7024         return EINVAL;
7025       }
7026       RGWReplicaObjectLogger logger(store, pool, DATA_REPLICA_LOG_OBJ_PREFIX);
7027       int ret = logger.update_bound(shard_id, daemon_id, marker, time, &entries);
7028       if (ret < 0) {
7029         cerr << "ERROR: failed to update bounds: " << cpp_strerror(-ret) << std::endl;
7030         return -ret;
7031       }
7032     } else if (replica_log_type == ReplicaLog_Bucket) {
7033       if (bucket_name.empty()) {
7034         cerr << "ERROR: bucket not specified" << std::endl;
7035         return EINVAL;
7036       }
7037       RGWBucketInfo bucket_info;
7038       int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
7039       if (ret < 0) {
7040         cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
7041         return -ret;
7042       }
7043
7044       RGWReplicaBucketLogger logger(store);
7045       ret = logger.update_bound(bucket, shard_id, daemon_id, marker, time, &entries);
7046       if (ret < 0) {
7047         cerr << "ERROR: failed to update bounds: " << cpp_strerror(-ret) << std::endl;
7048         return -ret;
7049       }
7050     }
7051   }
7052
7053   bool quota_op = (opt_cmd == OPT_QUOTA_SET || opt_cmd == OPT_QUOTA_ENABLE || opt_cmd == OPT_QUOTA_DISABLE);
7054
7055   if (quota_op) {
7056     if (bucket_name.empty() && user_id.empty()) {
7057       cerr << "ERROR: bucket name or uid is required for quota operation" << std::endl;
7058       return EINVAL;
7059     }
7060
7061     if (!bucket_name.empty()) {
7062       if (!quota_scope.empty() && quota_scope != "bucket") {
7063         cerr << "ERROR: invalid quota scope specification." << std::endl;
7064         return EINVAL;
7065       }
7066       set_bucket_quota(store, opt_cmd, tenant, bucket_name,
7067                        max_size, max_objects, have_max_size, have_max_objects);
7068     } else if (!user_id.empty()) {
7069       if (quota_scope == "bucket") {
7070         set_user_bucket_quota(opt_cmd, user, user_op, max_size, max_objects, have_max_size, have_max_objects);
7071       } else if (quota_scope == "user") {
7072         set_user_quota(opt_cmd, user, user_op, max_size, max_objects, have_max_size, have_max_objects);
7073       } else {
7074         cerr << "ERROR: invalid quota scope specification. Please specify either --quota-scope=bucket, or --quota-scope=user" << std::endl;
7075         return EINVAL;
7076       }
7077     }
7078   }
7079
7080   return 0;
7081 }