cluster.php 15.1 KB
Newer Older
Alexis Ragot's avatar
Alexis Ragot committed
1
<?php
Prosper De Laure's avatar
Prosper De Laure committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

/*
 * Copyright (C) 2015 Maarch
 *
 * This file is part of bundle digitalResource.
 *
 * Bundle digitalResource is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Bundle digitalResource is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with bundle digitalResource.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace bundle\digitalResource\Controller;

/**
 * Class of cluster
 *
 * @author Alexis Ragot <alexis.ragot@maarch.org>
 */
class cluster
{

    protected $sdoFactory;
    protected $repositoryController;

35
36
37
38
    const MODE_READ = "read";
    const MODE_WRITE = "write";
    const MODE_DELETE = "delete";

Prosper De Laure's avatar
Prosper De Laure committed
39
40
41
42
43
44
45
46
47
48
49
50
51
52
    /**
     * Constructor
     * @param \dependency\sdo\Factory $sdoFactory The sdo factory
     */
    public function __construct(\dependency\sdo\Factory $sdoFactory)
    {
        $this->sdoFactory = $sdoFactory;

        $this->repositoryController = \laabs::newController('digitalResource/repository');
    }

    /**
     * Allow to display all clusters
     *
Dylan's avatar
Dylan committed
53
     * @return digitalResource/cluster[] Array of digitalResource/cluster object
Prosper De Laure's avatar
Prosper De Laure committed
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
     */
    public function index()
    {
        $clusters = $this->sdoFactory->find('digitalResource/cluster');
        foreach ($clusters as $cluster) {
            $cluster->clusterRepository = $this->sdoFactory->readChildren("digitalResource/clusterRepository", $cluster);
        }

        return $clusters;
    }

    /**
     * New empty cluster with default values
     *
     * @return digitalResource/cluster The cluster object
     */
    public function newCluster()
    {
        return \laabs::newInstance("digitalResource/cluster");
    }

    /**
     * Edit a cluster
     * @param string $clusterId The identifier of cluster
     *
     * @return digitalResource/cluster The cluster object
     */
    public function edit($clusterId = null)
    {
        // pre_load values
        if ($clusterId) {
            if (!$this->sdoFactory->exists("digitalResource/cluster", $clusterId)) {
Prosper De Laure's avatar
Prosper De Laure committed
86
                throw \laabs::newException("digitalResource/clusterException", "Cluster %s not found.", 404, null, [$clusterId]);
Prosper De Laure's avatar
Prosper De Laure committed
87
88
89
            }
            $cluster = $this->sdoFactory->read("digitalResource/cluster", $clusterId);
            if (!$cluster) {
Prosper De Laure's avatar
Prosper De Laure committed
90
                throw \laabs::newException("digitalResource/clusterException", "Cluster %s not found.", 404, null, [$clusterId]);
Prosper De Laure's avatar
Prosper De Laure committed
91
92
93
94
95
96
97
98
99
100
101
102
103
104
            }

            $cluster->clusterRepository = $this->sdoFactory->readChildren("digitalResource/clusterRepository", $cluster);
        } else {
            $cluster = $this->newCluster();
        }

        return $cluster;
    }

    /**
     * create a cluster
     * @param digitalResource/cluster $cluster The cluster object
     *
Dylan's avatar
Dylan committed
105
     * @return boolean The result of the operation
Prosper De Laure's avatar
Prosper De Laure committed
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
     */
    public function create($cluster)
    {
        $cluster->clusterId = \laabs::newId();

        if (!$cluster->clusterName) {
            throw \laabs::newException("digitalResource/clusterException", "Cluster name is empty");
        }

        if (!$cluster->clusterRepository) {
            throw \laabs::newException("digitalResource/clusterException", "Cluster repository is empty");
        }

        foreach ($cluster->clusterRepository as $repo) {
            $repo->clusterId = $cluster->clusterId;
        }

        $this->sdoFactory->beginTransaction();
        try {
            $this->sdoFactory->create($cluster, "digitalResource/cluster");
            $this->sdoFactory->createCollection($cluster->clusterRepository, "digitalResource/clusterRepository");
        } catch (\Exception $e) {
            $this->sdoFactory->rollback();
129
130
131
132
133
134
135
            throw \laabs::newException(
                "digitalResource/clusterException",
                "Cluster %s not created.",
                404,
                null,
                [$cluster->clusterId]
            );
Prosper De Laure's avatar
Prosper De Laure committed
136
137
138
139
140
141
142
143
144
145
        }
        $this->sdoFactory->commit();

        return true;
    }

    /**
     * update a repository
     * @param digitalResource/cluster $cluster The cluster object
     *
Dylan's avatar
Dylan committed
146
     * @return boolean The result of the operation
Prosper De Laure's avatar
Prosper De Laure committed
147
148
149
150
151
152
153
154
155
156
157
158
     */
    public function update($cluster)
    {
        $this->sdoFactory->beginTransaction();
        try {
            $this->sdoFactory->update($cluster, "digitalResource/cluster");
            $this->sdoFactory->deleteChildren("digitalResource/clusterRepository", $cluster, "digitalResource/cluster");
            if (count($cluster->clusterRepository) > 0) {
                $this->sdoFactory->createCollection($cluster->clusterRepository, "digitalResource/clusterRepository");
            }
        } catch (\core\Route\Exception $e) {
            $this->sdoFactory->rollback();
159
            throw \laabs::newException("digitalResource/clusterException", "Cluster %s not updated.", 404, null, [$cluster->clusterId]);
Prosper De Laure's avatar
Prosper De Laure committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
        }
        $this->sdoFactory->commit();

        return true;
    }

    /**
     * Open cluster and repository services for given mode
     * @param string $clusterId The cluster identifier
     * @param string $mode      The mode: read, write, delete
     * @param bool   $limit     Limit the repo services to the lowest priority
     *
     * @return object The cluster with repositories and repo services
     */
174
    public function openCluster($clusterId, $mode = Cluster::MODE_READ, $limit = false)
Prosper De Laure's avatar
Prosper De Laure committed
175
176
177
178
179
180
181
182
183
184
185
    {
        $cluster = $this->sdoFactory->read("digitalResource/cluster", $clusterId);

        $cluster->clusterRepository = $this->sdoFactory->readChildren("digitalResource/clusterRepository", $cluster);

        $this->sortClusterRepositories($cluster, $mode, $limit);

        foreach ($cluster->clusterRepository as $clusterRepository) {
            try {
                $clusterRepository->repository = $this->repositoryController->openRepository($clusterRepository->repositoryId);
            } catch (\Exception $e) {
186
187
188
189
190
191
                if ($mode == Cluster::MODE_WRITE) {
                    throw \laabs::newException("digitalResource/clusterException", "Repository '%s' must be accessible", 404, $e, [$clusterRepository->repositoryId]);
                } else {
                    $clusterRepository->repository = null;
                    continue;
                }
Prosper De Laure's avatar
Prosper De Laure committed
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
            }
        }

        /*
        $operationnalClusterRepository = [];
        foreach ($cluster->clusterRepository as $clusterRepository) {
            try {
                $clusterRepository->repository = $this->repositoryController->openRepository($clusterRepository->repositoryId);
            } catch (\Exception $e) {
                // to do (log etc..)
                continue;
            }
            $operationnalClusterRepository[] = $clusterRepository;
        }

        $cluster->clusterRepository = $operationnalClusterRepository;
        */

        return $cluster;
    }

    /**
     * Sort repositories with their priority for the given operation
     * @param object  $cluster The cluster definition
     * @param string  $mode    The operation: read, write, delete
     * @param boolean $limit   Only keep repositories with the lowest priority
     */
219
    public function sortClusterRepositories($cluster, $mode = Cluster::MODE_READ, $limit = false)
Prosper De Laure's avatar
Prosper De Laure committed
220
    {
221
        // Sort repositories by priority
Prosper De Laure's avatar
Prosper De Laure committed
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
        $priorityProperty = $mode.'Priority';
        $priority = array();
        foreach ($cluster->clusterRepository as $key => $clusterRepository) {
            $priority[$key] = $clusterRepository->$priorityProperty;
        }
        array_multisort($priority, SORT_ASC, SORT_NUMERIC, $cluster->clusterRepository);

        // Get lowest priority and unset other repositories
        if ($limit) {
            $firstRepository = reset($cluster->clusterRepository);
            $lowestPriority = $firstRepository->$priorityProperty;
            foreach ($cluster->clusterRepository as $index => $clusterRepository) {
                if ($clusterRepository->$priorityProperty > $lowestPriority) {
                    unset($cluster->clusterRepository[$index]);
                }
            }

            if (count($cluster->clusterRepository) == 0) {
Prosper De Laure's avatar
Prosper De Laure committed
240
                throw \laabs::newException("digitalResource/noClusterRepositoryException", "No repository for %s mode", 404, null, [$mode]);
Prosper De Laure's avatar
Prosper De Laure committed
241
242
243
244
            }
        }
    }

245
246
247
248
249
    /**
     * Create a ressource container on the cluster (after opening it)
     * @param object $cluster
     * @param string $path
     * @param mixed  $metadata
Jerome Boucher's avatar
Jerome Boucher committed
250
     *
Dylan's avatar
Dylan committed
251
     * @return String[] Array of ressource container on the cluster
252
253
254
     */
    public function openContainers($cluster, $path, $metadata=null)
    {
255
        if (count($cluster->clusterRepository) < 1) {
256
257
258
            throw \laabs::newException("digitalResource/clusterException", "All repositories must be accessible");
        }

259
        foreach ($cluster->clusterRepository as $clusterRepository) {
260
            if ($clusterRepository->repository == null || !is_readable($clusterRepository->repository->repositoryUri)) {
261
262
263
264
265
266
                throw \laabs::newException("digitalResource/clusterException", "All repositories must be accessible");
            }

            $realPath = $this->repositoryController->openContainer($clusterRepository->repository, $path, $metadata);

            if (!$realPath) {
Cyril Vazquez's avatar
Cyril Vazquez committed
267
                throw \laabs::newException("digitalResource/clusterException", "Container %s couldn't not be opened.", 404, null, [$path]);
268
269
            }
        }
270
271

        return $realPath;
272
273
    }

Prosper De Laure's avatar
Prosper De Laure committed
274
275
276
277
278
    /**
     * Store a resource on cluster (after opening it)
     * @param digitalResource/cluster         $cluster
     * @param digitalResource/digitalResource $resource
     */
279
    public function storeResource($cluster, $resource)
Prosper De Laure's avatar
Prosper De Laure committed
280
    {
281
        foreach ($cluster->clusterRepository as $index => $clusterRepository) {
Prosper De Laure's avatar
Prosper De Laure committed
282
283
284
            if ($clusterRepository->repository == null) {
                throw \laabs::newException("digitalResource/clusterException", "All repositories must be accessible");
            }
285

286
            $address = $this->repositoryController->storeResource($clusterRepository->repository, $resource);
Prosper De Laure's avatar
Prosper De Laure committed
287
288

            if (!$address) {
289
                throw \laabs::newException("digitalResource/clusterException", "%s not found", 404, null, [$cluster->clusterId]);
Prosper De Laure's avatar
Prosper De Laure committed
290
291
            }

292
            $resource->address[$index] = $address;
Prosper De Laure's avatar
Prosper De Laure committed
293
294
295
296
297
298
299
300
301
        }
    }

    /**
     * Rollback storage transaction
     * @param digitalResource/digitalResource $resource
     */
    public function rollbackStorage($resource)
    {
302
        if (is_array($resource->address) && count($resource->address)) {
Prosper De Laure's avatar
Prosper De Laure committed
303
304
305
306
307
308
309
310
311
312
313
            foreach ($resource->address as $address) {
                $this->repositoryController->rollbackStorage($address);
            }
        }
    }

    /**
     * Retrieve a resource contents on cluster (after opening it)
     * @param digitalResource/cluster         $cluster
     * @param digitalResource/digitalResource $resource
     *
Dylan's avatar
Dylan committed
314
     * @return bool The result of the operation
Prosper De Laure's avatar
Prosper De Laure committed
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
     */
    public function retrieveResource($cluster, $resource)
    {
        foreach ($cluster->clusterRepository as $clusterRepository) {
            if ($clusterRepository->repository == null) {
                continue;
            }
            $address = $this->sdoFactory->read("digitalResource/address", array('resId' => $resource->resId, 'repositoryId' => $clusterRepository->repositoryId));
            if ($address) {
                $contents = null;
                $resource->address[] = $address;
                $address->repository = $clusterRepository->repository;

                try {
                    $contents = $this->repositoryController->retrieveContents($clusterRepository->repository, $address);

                    if (isset($resource->hash) && !$this->checkHash($address, $resource, $contents)) {
Prosper De Laure's avatar
Prosper De Laure committed
332
                        throw \laabs::newException("digitalResource/clusterException", 'Invalid hash for resource %1$s at address %2$S', 404, null, [$resource->resId, $address->repository->repositoryUri.DIRECTORY_SEPARATOR.$address->path]);
Alexis Ragot's avatar
Alexis Ragot committed
333
                    }
Prosper De Laure's avatar
Prosper De Laure committed
334
335
336
337

                    $resource->setContents($contents);

                    return $contents;
Alexis Ragot's avatar
Alexis Ragot committed
338

Prosper De Laure's avatar
Prosper De Laure committed
339
                } catch (\Exception $e) {
340
341
                    $address->integrityCheckResult = false;
                    $this->sdoFactory->update($address);
Prosper De Laure's avatar
Prosper De Laure committed
342
343
344
345
                    // No content retrieved : send error as audit event
                    \laabs::notify(LAABS_BUSINESS_EXCEPTION, $e);
                }
            } else {
346
                throw \laabs::newException("digitalResource/clusterException", "No address found for ressource %s", 404, null, [$resource->resId]);
Prosper De Laure's avatar
Prosper De Laure committed
347
                \laabs::notify(LAABS_BUSINESS_EXCEPTION, \laabs::newException("digitalResource/clusterException", "No address found for ressource %s", 404, null, [$resource->resId]));
Prosper De Laure's avatar
Prosper De Laure committed
348
349
350
351
352
353
354
355
356
357
            }
        }

        // TODO : throw exception if resource not available on repo, based on options ?
        return null;
    }

    /**
     * Verify a resouce
     *
358
359
     * @param object $cluster  The cluster object where the resource is store
     * @param object $resource The digitalResource object to verify
Prosper De Laure's avatar
Prosper De Laure committed
360
     *
361
     * @return boolean The digitalResource verify
Prosper De Laure's avatar
Prosper De Laure committed
362
363
364
365
366
367
368
369
370
     */
    public function verifyResource($cluster, $resource)
    {
        $result = true;

        foreach ($cluster->clusterRepository as $clusterRepository) {
            if ($clusterRepository->repository == null) {
                continue;
            }
371
372
373
374
375
376
377
378
379

            $queryParams['repositoryId'] = $clusterRepository->repositoryId;
            $queryParts['repositoryId'] = "repositoryId = :repositoryId";
            $queryParams['resId'] = $resource->resId;
            $queryParts['resId'] = "resId = :resId";

            $queryString = implode(' AND ', $queryParts );

            $resource->address = $this->sdoFactory->find("digitalResource/address", $queryString, $queryParams);
Prosper De Laure's avatar
Prosper De Laure committed
380
381
382
383
384
385
386

            foreach ($resource->address as $address) {
                $address->repository = $clusterRepository->repository;
                $contents = $this->repositoryController->retrieveContents($clusterRepository->repository, $address);

                if ($contents) {
                    $result = $result && $this->checkHash($address, $resource, $contents);
387
388
389
390

                    if (!$result) {
                        throw \laabs::newException("digitalResource/invalidHashException", "Invalid hash on repository '%s'", 409, null, $clusterRepository->repositoryId);
                    }
Prosper De Laure's avatar
Prosper De Laure committed
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
                }
            }
        }

        return $result;
    }

    private function checkHash($address, $resource, $contents)
    {
        $hash = strtolower(hash($resource->hashAlgorithm, $contents));

        $address->lastIntegrityCheck = \laabs::newTimestamp();
        $address->integrityCheckResult = false;

        if ($hash == strtolower($resource->hash)) {
            $address->integrityCheckResult = true;
        }
        $this->sdoFactory->update($address);

        return $address->integrityCheckResult;
    }
}