<commit_before>/*-----------------------------------------------------------------------------

 Copyright 2017 Hopsan Group

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

 The full license is available in the file LICENSE.
 For details about the 'Hopsan Group' or information about Authors and
 Contributors see the HOPSANGROUP and AUTHORS files that are located in
 the Hopsan source code root directory.

-----------------------------------------------------------------------------*/

//!
//! @file   TempDirectoryHandle.cpp
//! @author Robert Braun <robert.braun@liu.se>
//! @date   2021-02-02
//!
//! @brief Contains a temp directory handle class
//!
//$Id$

#include "ComponentUtilities/num2string.hpp"

#include <iostream>
#if __cplusplus >= 201703L
#include <filesystem>
#endif
#if __cplusplus >= 201103L
#include <random>
#include <chrono>
#endif
#include <sstream>
#include <iomanip>
#include <sys/stat.h>
#include <sys/types.h>
#include <cstring>
#include <stdio.h>
#include <stdlib.h>
#ifdef _WIN32
#include <windows.h>
#include <direct.h>
#include <shellapi.h>
#include <strsafe.h>
#else
#include <dirent.h>
#include <unistd.h>
#endif

#include "ComponentUtilities/TempDirectoryHandle.h"

using namespace hopsan;

TempDirectoryHandle::TempDirectoryHandle(const HString &rPrefix)
    : mIsValid(false)
{
    mPath = getTempDirectory();
    mPath.append("/Hopsan/"+rPrefix);
    mPath.append(generateRandomNumericString());

    mIsValid = createPath(mPath);
}

TempDirectoryHandle::~TempDirectoryHandle()
{
    removeDirectory(mPath);
}

const HString &TempDirectoryHandle::path() const
{
    return mPath;
}

bool TempDirectoryHandle::isValid() const
{
    return mIsValid;
}

const HString TempDirectoryHandle::getTempDirectory() const {
#if __cplusplus >= 201703L
    return std::filesystem::temp_directory_path().c_str();
#else
#ifdef _WIN32
    char tempdirbuff[MAX_PATH+1];
    GetTempPathA(MAX_PATH+1, tempdirbuff);
    return HString(tempdirbuff);
#else
    char * val = getenv("TMPDIR");
    if(val != nullptr) {
        return val;
    }
    val = getenv("TMP");
    if(val != nullptr) {
        return val;
    }
    val = getenv("TEMP");
    if(val != nullptr) {
        return val;
    }
    val = getenv("TEMPDIR");
    if(val != nullptr) {
        return val;
    }
    return "/tmp";
#endif
#endif
}

const HString TempDirectoryHandle::generateRandomNumericString() const
{
#if __cplusplus >= 201103L

#ifdef __MINGW32__
    // "Bug" in MinGW (using constant seed) supposedly fixed in GCC 9.2, using current time as seed instead
    static std::mt19937 gen(static_cast<long unsigned int>(std::chrono::high_resolution_clock::now().time_since_epoch().count()));
#else
    static std::mt19937 gen(std::random_device{}());
#endif
    static std::uniform_int_distribution<> distrib(0, 999999999);
    int random = distrib(gen);
#else
    int random = rand() % 1000000000;
#endif
    std::stringstream ss;
    ss << std::setw(6) << std::setfill('0') << random;
    return ss.str().c_str();
}

bool TempDirectoryHandle::createDir(const HString &rName) const
{
#ifdef _WIN32
        return _mkdir(rName.c_str()) == 0;
#else
        return mkdir(rName.c_str(), 0777) == 0;
#endif
}

bool TempDirectoryHandle::createPath(const HString &rPath) const
{
#if __cplusplus >= 201703L
        return std::filesystem::create_directory(rPath.c_str());
#else
    HString currentLevel = "";
    std::string level;
    std::stringstream ss(rPath.c_str());

    while(std::getline(ss, level, '/')) {
        currentLevel.append(level.c_str());
        if(!currentLevel.empty()) {
            if (!directoryExists(currentLevel) && !createDir(currentLevel)) {
                return false;
            }
        }
        currentLevel += "/"; // don't forget to append a slash
    }
#endif
    return directoryExists(rPath);
}

bool TempDirectoryHandle::directoryExists(const HString &rName) const
{
    struct stat st;
    stat(rName.c_str(), &st);
    return st.st_mode & S_IFDIR;
}

bool TempDirectoryHandle::removeDirectory(const HString &rPath) const
{
#if __cplusplus >= 201703L
    std::filesystem::remove_all(rPath.c_str());
#else
#ifdef _WIN32
    WCHAR szDir[MAX_PATH+1];
    SHFILEOPSTRUCTW fos = {0};
    std::string tempStr(rPath.c_str());
    std::wstring stemp = std::wstring(tempStr.begin(), tempStr.end());
    StringCchCopyW(szDir, MAX_PATH,STRSAFE_LPCWSTR(stemp.c_str()));
    int len = lstrlenW(szDir);
    szDir[len+1] = 0; // Null termination

    //Delete the folder including files and subfolders
    fos.wFunc = FO_DELETE;
    fos.pFrom = szDir;
    fos.fFlags = FOF_NO_UI;
    return (0 == SHFileOperationW( &fos ));

#else
    DIR *dir = opendir(rPath.c_str());
    size_t path_len = rPath.size();
    bool success = false;

    if(dir) {
        struct dirent *p;

        success = true;
        while (success && (p=readdir(dir))) {
            char *buf;
            size_t len;

            if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, "..")) {
                continue;
            }

            len = path_len + strlen(p->d_name) + 2;
            buf = static_cast<char*>(malloc(len));

            if (buf) {
                struct stat statbuf;

                snprintf(buf, len, "%s/%s", rPath.c_str(), p->d_name);
                if (!stat(buf, &statbuf)) {
                    if (S_ISDIR(statbuf.st_mode)) {
                        success = removeDirectory(buf);
                    }
                    else {
                        success = (unlink(buf) == 0);
                    }
                }
                free(buf);
            }
        }
        closedir(dir);
    }

    if (success) {
        success = (0 == rmdir(rPath.c_str()));
    }

    return success;
#endif
#endif
}

<commit_msg>Fix issues with creating temporary directories on Linux<commit_after>/*-----------------------------------------------------------------------------

 Copyright 2017 Hopsan Group

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

 The full license is available in the file LICENSE.
 For details about the 'Hopsan Group' or information about Authors and
 Contributors see the HOPSANGROUP and AUTHORS files that are located in
 the Hopsan source code root directory.

-----------------------------------------------------------------------------*/

//!
//! @file   TempDirectoryHandle.cpp
//! @author Robert Braun <robert.braun@liu.se>
//! @date   2021-02-02
//!
//! @brief Contains a temp directory handle class
//!
//$Id$

#include "ComponentUtilities/num2string.hpp"

#include <iostream>
#if __cplusplus >= 201703L
#include <filesystem>
#endif
#if __cplusplus >= 201103L
#include <random>
#include <chrono>
#endif
#include <sstream>
#include <iomanip>
#include <sys/stat.h>
#include <sys/types.h>
#include <cstring>
#include <stdio.h>
#include <stdlib.h>
#ifdef _WIN32
#include <windows.h>
#include <direct.h>
#include <shellapi.h>
#include <strsafe.h>
#else
#include <dirent.h>
#include <unistd.h>
#endif

#include "ComponentUtilities/TempDirectoryHandle.h"

using namespace hopsan;

TempDirectoryHandle::TempDirectoryHandle(const HString &rPrefix)
    : mIsValid(false)
{
    mPath = getTempDirectory();
    mPath.append("/Hopsan/"+rPrefix);
    mPath.append(generateRandomNumericString());

    mIsValid = createPath(mPath);
}

TempDirectoryHandle::~TempDirectoryHandle()
{
    removeDirectory(mPath);
}

const HString &TempDirectoryHandle::path() const
{
    return mPath;
}

bool TempDirectoryHandle::isValid() const
{
    return mIsValid;
}

const HString TempDirectoryHandle::getTempDirectory() const {
#if __cplusplus >= 201703L
    return std::filesystem::temp_directory_path().c_str();
#else
#ifdef _WIN32
    char tempdirbuff[MAX_PATH+1];
    GetTempPathA(MAX_PATH+1, tempdirbuff);
    return HString(tempdirbuff);
#else
    char * val = getenv("TMPDIR");
    if(val != nullptr) {
        return val;
    }
    val = getenv("TMP");
    if(val != nullptr) {
        return val;
    }
    val = getenv("TEMP");
    if(val != nullptr) {
        return val;
    }
    val = getenv("TEMPDIR");
    if(val != nullptr) {
        return val;
    }
    return "/tmp";
#endif
#endif
}

const HString TempDirectoryHandle::generateRandomNumericString() const
{
#if __cplusplus >= 201103L

#ifdef __MINGW32__
    // "Bug" in MinGW (using constant seed) supposedly fixed in GCC 9.2, using current time as seed instead
    static std::mt19937 gen(static_cast<long unsigned int>(std::chrono::high_resolution_clock::now().time_since_epoch().count()));
#else
    static std::mt19937 gen(std::random_device{}());
#endif
    static std::uniform_int_distribution<> distrib(0, 999999999);
    int random = distrib(gen);
#else
    int random = rand() % 1000000000;
#endif
    std::stringstream ss;
    ss << std::setw(6) << std::setfill('0') << random;
    return ss.str().c_str();
}

bool TempDirectoryHandle::createDir(const HString &rName) const
{
#ifdef _WIN32
        return _mkdir(rName.c_str()) == 0;
#else
        int ret = mkdir(rName.c_str(), 0777) == 0;
        return (ret != 0);
#endif
}

bool TempDirectoryHandle::createPath(const HString &rPath) const
{
#if __cplusplus >= 201703L
        return std::filesystem::create_directory(rPath.c_str());
#else
    HString currentLevel = "";
    std::string level;
    std::stringstream ss(rPath.c_str());

    while(std::getline(ss, level, '/')) {
        currentLevel.append(level.c_str());
        if(!currentLevel.empty()) {
            if (!directoryExists(currentLevel) && !createDir(currentLevel)) {
                return false;
            }
        }
        if(currentLevel.empty() || currentLevel[currentLevel.size()-1] != '/') {
            currentLevel += "/"; // don't forget to append a slash
        }
    }
#endif
    return directoryExists(rPath);
}

bool TempDirectoryHandle::directoryExists(const HString &rName) const
{
    struct stat st;
    if(stat(rName.c_str(), &st) != 0) {
        return false;
    }
    else if(st.st_mode & S_IFDIR) {
        return true;
    }
    return false;
}

bool TempDirectoryHandle::removeDirectory(const HString &rPath) const
{
#if __cplusplus >= 201703L
    std::filesystem::remove_all(rPath.c_str());
#else
#ifdef _WIN32
    WCHAR szDir[MAX_PATH+1];
    SHFILEOPSTRUCTW fos = {0};
    std::string tempStr(rPath.c_str());
    std::wstring stemp = std::wstring(tempStr.begin(), tempStr.end());
    StringCchCopyW(szDir, MAX_PATH,STRSAFE_LPCWSTR(stemp.c_str()));
    int len = lstrlenW(szDir);
    szDir[len+1] = 0; // Null termination

    //Delete the folder including files and subfolders
    fos.wFunc = FO_DELETE;
    fos.pFrom = szDir;
    fos.fFlags = FOF_NO_UI;
    return (0 == SHFileOperationW( &fos ));

#else
    DIR *dir = opendir(rPath.c_str());
    size_t path_len = rPath.size();
    bool success = false;

    if(dir) {
        struct dirent *p;

        success = true;
        while (success && (p=readdir(dir))) {
            char *buf;
            size_t len;

            if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, "..")) {
                continue;
            }

            len = path_len + strlen(p->d_name) + 2;
            buf = static_cast<char*>(malloc(len));

            if (buf) {
                struct stat statbuf;

                snprintf(buf, len, "%s/%s", rPath.c_str(), p->d_name);
                if (!stat(buf, &statbuf)) {
                    if (S_ISDIR(statbuf.st_mode)) {
                        success = removeDirectory(buf);
                    }
                    else {
                        success = (unlink(buf) == 0);
                    }
                }
                free(buf);
            }
        }
        closedir(dir);
    }

    if (success) {
        success = (0 == rmdir(rPath.c_str()));
    }

    return success;
#endif
#endif
}

<|endoftext|>


<commit_before>//
// Copyright (c) 2019, Christopher E. Mower
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//  * Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of  nor the names of its contributors may be used to
//    endorse or promote products derived from this software without specific
//    prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//

#include <exotica_core/server.h>
#include <exotica_core_task_maps/avoid_look_at_sphere.h>

REGISTER_TASKMAP_TYPE("AvoidLookAtSphere", exotica::AvoidLookAtSphere);

namespace exotica
{
void AvoidLookAtSphere::UpdateAsCostWithoutJacobian(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi)
{
    for (int i = 0; i < n_objects_; ++i)
    {
        const double frac = Eigen::Map<Eigen::Vector2d>(kinematics[0].Phi(i).p.data).squaredNorm() / radii_squared_(i);
        if (frac < 1.0) phi(i) = 1.0 - 2.0 * frac + frac * frac;
    }
}

void AvoidLookAtSphere::UpdateAsInequalityConstraintWithoutJacobian(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi)
{
    for (int i = 0; i < n_objects_; ++i) phi(i) = radii_squared_(i) - Eigen::Map<Eigen::Vector2d>(kinematics[0].Phi(i).p.data).squaredNorm();
}

void AvoidLookAtSphere::UpdateAsCostWithJacobian(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef jacobian)
{
    for (int i = 0; i < n_objects_; ++i)
    {
        Eigen::Vector2d o = Eigen::Map<Eigen::Vector2d>(kinematics[0].Phi(i).p.data);
        const double frac = o.squaredNorm() / radii_squared_(i);
        if (frac < 1.0)
        {
            phi(i) = 1.0 - 2.0 * frac + frac * frac;
            for (int j = 0; j < jacobian.cols(); ++j) jacobian(i, j) = -4.0 * (1.0 - frac) * kinematics[0].jacobian[i].data.topRows<2>().col(j).dot(o) / radii_squared_(i);
        }
    }
}

void AvoidLookAtSphere::UpdateAsInequalityConstraintWithJacobian(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef jacobian)
{
    for (int i = 0; i < n_objects_; ++i)
    {
        Eigen::Vector2d o = Eigen::Map<Eigen::Vector2d>(kinematics[0].Phi(i).p.data);
        const double d = o.norm();
        phi(i) = radii_squared_(i) - d * d;
        for (int j = 0; j < jacobian.cols(); ++j) jacobian(i, j) = -2.0 * kinematics[0].jacobian[i].data.topRows<2>().col(j).dot(o);
    }
}

void AvoidLookAtSphere::PublishObjectsAsMarkerArray()
{
    const ros::Time t = ros::Time::now();
    visualization_msgs::MarkerArray ma;
    ma.markers.reserve(n_objects_);
    for (int i = 0; i < n_objects_; ++i)
    {
        visualization_msgs::Marker m;
        m.header.stamp = t;
        m.header.frame_id = "exotica/" + frames_[i].frame_B_link_name;
        m.id = i;
        m.action = visualization_msgs::Marker::ADD;
        m.type = visualization_msgs::Marker::SPHERE;
        m.scale.x = diameter_(i);
        m.scale.y = diameter_(i);
        m.scale.z = diameter_(i);
        Eigen::Vector4d q = GetRotationAsVector(kinematics[0].Phi(i), RotationType::QUATERNION);
        m.pose.position.x = kinematics[0].Phi(i).p.data[0];
        m.pose.position.y = kinematics[0].Phi(i).p.data[1];
        m.pose.position.z = kinematics[0].Phi(i).p.data[2];
        m.pose.orientation.x = q[0];
        m.pose.orientation.y = q[1];
        m.pose.orientation.z = q[2];
        m.pose.orientation.w = q[3];
        m.color.r = 1.0;
        m.color.a = 1.0;
        ma.markers.emplace_back(m);
    }
    pub_markers_.publish(ma);
}

void AvoidLookAtSphere::Update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi)
{
    (this->*UpdateTaskMapWithoutJacobian)(x, phi);
    if (debug_ && Server::IsRos()) PublishObjectsAsMarkerArray();
}

void AvoidLookAtSphere::Update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef jacobian)
{
    (this->*UpdateTaskMapWithJacobian)(x, phi, jacobian);
    if (debug_ && Server::IsRos()) PublishObjectsAsMarkerArray();
}

void AvoidLookAtSphere::Instantiate(const AvoidLookAtSphereInitializer& init)
{
    parameters_ = init;
    n_objects_ = frames_.size();
    diameter_.resize(n_objects_, 1);
    radii_squared_.resize(n_objects_, 1);

    for (int i = 0; i < n_objects_; ++i)
    {
        SphereInitializer sphere(init.EndEffector[i]);
        diameter_(i) = 2.0 * sphere.Radius;
        radii_squared_(i) = sphere.Radius * sphere.Radius;
    }

    if (init.UseAsCost)
    {
        UpdateTaskMapWithoutJacobian = &AvoidLookAtSphere::UpdateAsCostWithoutJacobian;
        UpdateTaskMapWithJacobian = &AvoidLookAtSphere::UpdateAsCostWithJacobian;
    }
    else
    {
        UpdateTaskMapWithoutJacobian = &AvoidLookAtSphere::UpdateAsInequalityConstraintWithoutJacobian;
        UpdateTaskMapWithJacobian = &AvoidLookAtSphere::UpdateAsInequalityConstraintWithJacobian;
    }

    if (debug_ && Server::IsRos())
    {
        pub_markers_ = Server::Advertise<visualization_msgs::MarkerArray>("alas_objs", 1, true);
        visualization_msgs::Marker md;  // delete previous markers
        md.action = visualization_msgs::Marker::DELETEALL;
        visualization_msgs::MarkerArray ma;
        ma.markers.push_back(md);
        pub_markers_.publish(ma);
    }
}

int AvoidLookAtSphere::TaskSpaceDim()
{
    return n_objects_;
}
}  // namespace exotica
<commit_msg>[task_maps] Explicitly set to zero when frac >=0 and topic name update for pub_markers_.<commit_after>//
// Copyright (c) 2019, Christopher E. Mower
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//  * Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of  nor the names of its contributors may be used to
//    endorse or promote products derived from this software without specific
//    prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//

#include <exotica_core/server.h>
#include <exotica_core_task_maps/avoid_look_at_sphere.h>

REGISTER_TASKMAP_TYPE("AvoidLookAtSphere", exotica::AvoidLookAtSphere);

namespace exotica
{
void AvoidLookAtSphere::UpdateAsCostWithoutJacobian(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi)
{
    for (int i = 0; i < n_objects_; ++i)
    {
        const double frac = Eigen::Map<Eigen::Vector2d>(kinematics[0].Phi(i).p.data).squaredNorm() / radii_squared_(i);
        if (frac < 1.0)
        {
            phi(i) = 1.0 - 2.0 * frac + frac * frac;
        }
        else
        {
            phi(i) = 0.0;
        }
    }
}

void AvoidLookAtSphere::UpdateAsInequalityConstraintWithoutJacobian(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi)
{
    for (int i = 0; i < n_objects_; ++i) phi(i) = radii_squared_(i) - Eigen::Map<Eigen::Vector2d>(kinematics[0].Phi(i).p.data).squaredNorm();
}

void AvoidLookAtSphere::UpdateAsCostWithJacobian(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef jacobian)
{
    for (int i = 0; i < n_objects_; ++i)
    {
        Eigen::Vector2d o = Eigen::Map<Eigen::Vector2d>(kinematics[0].Phi(i).p.data);
        const double frac = o.squaredNorm() / radii_squared_(i);
        if (frac < 1.0)
        {
            phi(i) = 1.0 - 2.0 * frac + frac * frac;
            for (int j = 0; j < jacobian.cols(); ++j) jacobian(i, j) = -4.0 * (1.0 - frac) * kinematics[0].jacobian[i].data.topRows<2>().col(j).dot(o) / radii_squared_(i);
        }
        else
        {
            phi(i) = 0.0;
            jacobian.row(i).setZero();
        }
    }
}

void AvoidLookAtSphere::UpdateAsInequalityConstraintWithJacobian(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef jacobian)
{
    for (int i = 0; i < n_objects_; ++i)
    {
        Eigen::Vector2d o = Eigen::Map<Eigen::Vector2d>(kinematics[0].Phi(i).p.data);
        const double d = o.norm();
        phi(i) = radii_squared_(i) - d * d;
        for (int j = 0; j < jacobian.cols(); ++j) jacobian(i, j) = -2.0 * kinematics[0].jacobian[i].data.topRows<2>().col(j).dot(o);
    }
}

void AvoidLookAtSphere::PublishObjectsAsMarkerArray()
{
    const ros::Time t = ros::Time::now();
    visualization_msgs::MarkerArray ma;
    ma.markers.reserve(n_objects_);
    for (int i = 0; i < n_objects_; ++i)
    {
        visualization_msgs::Marker m;
        m.header.stamp = t;
        m.header.frame_id = "exotica/" + frames_[i].frame_B_link_name;
        m.id = i;
        m.action = visualization_msgs::Marker::ADD;
        m.type = visualization_msgs::Marker::SPHERE;
        m.scale.x = diameter_(i);
        m.scale.y = diameter_(i);
        m.scale.z = diameter_(i);
        Eigen::Vector4d q = GetRotationAsVector(kinematics[0].Phi(i), RotationType::QUATERNION);
        m.pose.position.x = kinematics[0].Phi(i).p.data[0];
        m.pose.position.y = kinematics[0].Phi(i).p.data[1];
        m.pose.position.z = kinematics[0].Phi(i).p.data[2];
        m.pose.orientation.x = q[0];
        m.pose.orientation.y = q[1];
        m.pose.orientation.z = q[2];
        m.pose.orientation.w = q[3];
        m.color.r = 1.0;
        m.color.a = 1.0;
        ma.markers.emplace_back(m);
    }
    pub_markers_.publish(ma);
}

void AvoidLookAtSphere::Update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi)
{
    (this->*UpdateTaskMapWithoutJacobian)(x, phi);
    if (debug_ && Server::IsRos()) PublishObjectsAsMarkerArray();
}

void AvoidLookAtSphere::Update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef jacobian)
{
    (this->*UpdateTaskMapWithJacobian)(x, phi, jacobian);
    if (debug_ && Server::IsRos()) PublishObjectsAsMarkerArray();
}

void AvoidLookAtSphere::Instantiate(const AvoidLookAtSphereInitializer& init)
{
    parameters_ = init;
    n_objects_ = frames_.size();
    diameter_.resize(n_objects_, 1);
    radii_squared_.resize(n_objects_, 1);

    for (int i = 0; i < n_objects_; ++i)
    {
        SphereInitializer sphere(init.EndEffector[i]);
        diameter_(i) = 2.0 * sphere.Radius;
        radii_squared_(i) = sphere.Radius * sphere.Radius;
    }

    if (init.UseAsCost)
    {
        UpdateTaskMapWithoutJacobian = &AvoidLookAtSphere::UpdateAsCostWithoutJacobian;
        UpdateTaskMapWithJacobian = &AvoidLookAtSphere::UpdateAsCostWithJacobian;
    }
    else
    {
        UpdateTaskMapWithoutJacobian = &AvoidLookAtSphere::UpdateAsInequalityConstraintWithoutJacobian;
        UpdateTaskMapWithJacobian = &AvoidLookAtSphere::UpdateAsInequalityConstraintWithJacobian;
    }

    if (debug_ && Server::IsRos())
    {
        pub_markers_ = Server::Advertise<visualization_msgs::MarkerArray>("avoid_look_at_sphere_objects", 1, true);
        visualization_msgs::Marker md;  // delete previous markers
        md.action = visualization_msgs::Marker::DELETEALL;
        visualization_msgs::MarkerArray ma;
        ma.markers.push_back(md);
        pub_markers_.publish(ma);
    }
}

int AvoidLookAtSphere::TaskSpaceDim()
{
    return n_objects_;
}
}  // namespace exotica
<|endoftext|>


<commit_before>/*
 * APSRack.cpp
 *
 *  Created on: Jun 13, 2012
 *      Author: cryan
 */

#include "APSRack.h"

APSRack::APSRack() : numDevices_{0} {
}

APSRack::~APSRack()  {
	//Close the logging file so we don't leave it dangling
	fclose(Output2FILE::Stream());
}

//Initialize the rack by polling for devices and serial numbers
int APSRack::init() {

	//Create the logger
	FILE* pFile = fopen("libaps.log", "a");
	Output2FILE::Stream() = pFile;

	//Enumerate the serial numbers of the devices attached
	enumerate_devices();

	return 0;
}

//Initialize a specific APS unit
int APSRack::initAPS(const int & deviceID, const string & bitFile, const bool & forceReload){
	return APSs_[deviceID].init(bitFile, forceReload);
}

int APSRack::get_num_devices()  {
	int numDevices;
	FT_ListDevices(&numDevices, NULL, FT_LIST_NUMBER_ONLY);
	if (numDevices_ != numDevices) {
		update_device_enumeration();
	}
	return numDevices;
}

string APSRack::get_deviceSerial(const int & deviceID) {

	// get current number of devices
	get_num_devices();

	// Get serials from FTDI layer to check for change in devices
	vector<string> testSerials;
	FTDI::get_device_serials(testSerials);

	// match serials for each device id to make sure mapping of device count to serial
	// number is still correct
	// if serial number is different re-enumerate
	for(unsigned int cnt = 0; cnt < testSerials.size(); cnt++) {
		if (testSerials[cnt].compare(deviceSerials_[cnt]) != 0) {
			FILE_LOG(logDEBUG) << testSerials[cnt] << " does not match " << deviceSerials_[cnt] << " re-enumerating.";
			update_device_enumeration();
			break;
		}
	}

	// test to make sure ID is valid relative to vector size
	if (static_cast<size_t>(deviceID) > deviceSerials_.size()) {
		return "InvalidID";
	}

	return deviceSerials_[deviceID];
}

//This will reset the APS vector so it really should only be called during initialization
void APSRack::enumerate_devices() {

	//Have to disconnect everything first
	for (auto & aps : APSs_){
		aps.disconnect();
	}
	FTDI::get_device_serials(deviceSerials_);
	numDevices_ = deviceSerials_.size();

	APSs_.clear();
	APSs_.reserve(numDevices_);

	//	Now setup the map between device serials and number and assign the APS units appropriately
	//	Also setup the FPGA checksums
	size_t devicect = 0;
	for (string tmpSerial : deviceSerials_) {
		serial2dev[tmpSerial] = devicect;
		APSs_.emplace_back(devicect, tmpSerial);
		FILE_LOG(logDEBUG) << "Device " << devicect << " has serial number " << tmpSerial;
		devicect++;
	}
}

// This will update enumerate of devices by matching serial numbers
// If a device is missing it will be removed
// New devices are added
// Old devices are left as is (moved in place to new vector)
void APSRack::update_device_enumeration() {

	vector<string> newSerials;
	FTDI::get_device_serials(newSerials);

	// construct new APS_ vector & new serial2dev map
	vector<APS> newAPS_;
	map<string, int> newSerial2dev;

	size_t devicect = 0;
	for (string tmpSerial : newSerials) {

		// example test to see if FTDI thinks device is open
		if (FTDI::isOpen(devicect)) {
			FILE_LOG(logDEBUG) << "Device " << devicect << " [ " << tmpSerial << " ] is open";
		}

		// does the new serial number exist in the old list?
		if ( serial2dev.count(tmpSerial) > 0) {
			// move from old APSs_ vector to new
			newAPS_.push_back(std::move(APSs_[serial2dev[tmpSerial]]));
			FILE_LOG(logDEBUG) << "Old Device " << devicect << " [ " << tmpSerial << " ] moved";
		} else {
			// does not exist so construct it in the new vector
			newAPS_.emplace_back(devicect, tmpSerial);
			FILE_LOG(logDEBUG) << "New Device " << devicect << " [ " << tmpSerial << " ]";
		}

		newSerial2dev[tmpSerial] = devicect;
		devicect++;
	}

	// update APSRack members with new lists
	numDevices_ = newSerials.size();  // number of devices
	deviceSerials_ = newSerials;		  // device serial vector
	APSs_ = std::move(newAPS_);           // APS vector
	serial2dev = newSerial2dev;           // serial to device map
}

int APSRack::read_bitfile_version(const int & deviceID) const {
	return APSs_[deviceID].read_bitFile_version(ALL_FPGAS);
}

int APSRack::connect(const int & deviceID){
	//Connect to a instrument specified by deviceID
	return APSs_[deviceID].connect();
}

int APSRack::disconnect(const int & deviceID){
	return APSs_[deviceID].disconnect();
}

int APSRack::connect(const string & deviceSerial){
	//Look up the associated ID and call the next connect
	return APSs_[serial2dev[deviceSerial]].connect();
}

int APSRack::disconnect(const string & deviceSerial){
	//Look up the associated ID and call the next connect
	return APSs_[serial2dev[deviceSerial]].disconnect();
}

int APSRack::program_FPGA(const int & deviceID, const string &bitFile, const FPGASELECT & chipSelect, const int & expectedVersion){
	return APSs_[deviceID].program_FPGA(bitFile, chipSelect, expectedVersion);
}

int APSRack::setup_DACs(const int & deviceID) const{
	return APSs_[deviceID].setup_DACs();
}

int APSRack::set_sampleRate(const int & deviceID, const int & freq) {
	return APSs_[deviceID].set_sampleRate(freq);
}

int APSRack::get_sampleRate(const int & deviceID) const{
	return APSs_[deviceID].get_sampleRate();
}

int APSRack::set_run_mode(const int & deviceID, const int & dac, const RUN_MODE & mode){
	return APSs_[deviceID].set_run_mode(dac, mode);
}

int APSRack::set_repeat_mode(const int & deviceID, const int & dac, const bool & mode){
	return APSs_[deviceID].set_repeat_mode(dac, mode);
}

int APSRack::clear_channel_data(const int & deviceID) {
	return APSs_[deviceID].clear_channel_data();
}

int APSRack::run(const int & deviceID) {
	return APSs_[deviceID].run();
}
int APSRack::stop(const int & deviceID) {
	return APSs_[deviceID].stop();
}

int APSRack::load_sequence_file(const int & deviceID, const string & seqFile){
	return APSs_[deviceID].load_sequence_file(seqFile);
}

int APSRack::set_LL_data(const int & deviceID, const int & channelNum, const WordVec & addr, const WordVec & count, const WordVec & trigger1, const WordVec & trigger2, const WordVec & repeat){
	return APSs_[deviceID].set_LLData_IQ(dac2fpga(channelNum), addr, count, trigger1, trigger2, repeat);
}

int APSRack::get_running(const int & deviceID){
	//TODO:
//	return APSs_[deviceID].running_;
	return 0;
}

int APSRack::set_log(FILE * pFile) {
	if (pFile) {
		//Close the current file
		if(Output2FILE::Stream()) fclose(Output2FILE::Stream());
		//Assign the new one
		Output2FILE::Stream() = pFile;
		return 1;
	} else {
		return 0;
	}
}

int APSRack::set_logging_level(const int & logLevel){
	FILELog::ReportingLevel() = TLogLevel(logLevel);
	return 0;
}

int APSRack::set_trigger_source(const int & deviceID, const TRIGGERSOURCE & triggerSource) {
	return APSs_[deviceID].set_trigger_source(triggerSource);
}

TRIGGERSOURCE APSRack::get_trigger_source(const int & deviceID) const{
	return APSs_[deviceID].get_trigger_source();
}

int APSRack::set_trigger_interval(const int & deviceID, const double & interval){
	return APSs_[deviceID].set_trigger_interval(interval);
}

double APSRack::get_trigger_interval(const int & deviceID) const{
	return APSs_[deviceID].get_trigger_interval();
}

int APSRack::set_miniLL_repeat(const int & deviceID, const USHORT & repeat){
	return APSs_[deviceID].set_miniLL_repeat(repeat);
}

int APSRack::set_channel_enabled(const int & deviceID, const int & channelNum, const bool & enable){
	return APSs_[deviceID].set_channel_enabled(channelNum, enable);
}

bool APSRack::get_channel_enabled(const int & deviceID, const int & channelNum) const{
	return APSs_[deviceID].get_channel_enabled(channelNum);
}

int APSRack::set_channel_offset(const int & deviceID, const int & channelNum, const float & offset){
	return APSs_[deviceID].set_channel_offset(channelNum, offset);
}

float APSRack::get_channel_offset(const int & deviceID, const int & channelNum) const{
	return APSs_[deviceID].get_channel_offset(channelNum);
}

int APSRack::set_channel_scale(const int & deviceID, const int & channelNum, const float & scale){
	return APSs_[deviceID].set_channel_scale(channelNum, scale);
}

float APSRack::get_channel_scale(const int & deviceID, const int & channelNum) const{
	return APSs_[deviceID].get_channel_scale(channelNum);
}

int APSRack::save_state_files(){
	// loop through available APS Units and save state
	for(unsigned int apsct = 0; apsct < APSs_.size(); apsct++) {
		string stateFileName = ""; // use default file name
		APSs_[apsct].save_state_file(stateFileName);
	}
	return 0;
}

int APSRack::read_state_files(){
	// loop through available APS Units and load state
	for(unsigned int  apsct = 0; apsct < APSs_.size(); apsct++) {
		string stateFileName = ""; // use default file name
		APSs_[apsct].read_state_file(stateFileName);
	}
	return 0;
}

int APSRack::save_bulk_state_file(string & stateFile){

	if (stateFile.length() == 0) {
		stateFile += "cache_APSRack.h5";
	}

	FILE_LOG(logDEBUG) << "Writing Bulk State File " << stateFile;
	H5::H5File H5StateFile(stateFile, H5F_ACC_TRUNC);
	// loop through available APS Units and save state
	for(unsigned int  apsct = 0; apsct < APSs_.size(); apsct++) {
		string rootStr = "/";
		rootStr += APSs_[apsct].deviceSerial_ ;
		FILE_LOG(logDEBUG) << "Creating Group: " << rootStr;
		H5::Group tmpGroup = H5StateFile.createGroup(rootStr);
		tmpGroup.close();
		APSs_[apsct].write_state_to_hdf5(H5StateFile, rootStr);
	}
	//Close the file
	H5StateFile.close();
	return 0;
}

int APSRack::read_bulk_state_file(string & stateFile){
	if (stateFile.length() == 0) {
		stateFile += "cache_APSRack.h5";
	}
	FILE_LOG(logDEBUG) << "Reading Bulk State File " << stateFile;
	H5::H5File H5StateFile(stateFile, H5F_ACC_RDONLY);

	// loop through available APS Units and load data
	for(unsigned int  apsct = 0; apsct < APSs_.size(); apsct++) {
		string rootStr = "/";
		rootStr += "/" + APSs_[apsct].deviceSerial_;
		APSs_[apsct].read_state_from_hdf5(H5StateFile, rootStr);
	}
	//Close the file
	H5StateFile.close();
	return 0;
}

int APSRack::raw_write(int deviceID, int numBytes, UCHAR* data){
	DWORD bytesWritten;
	FT_Write(APSs_[deviceID].handle_, data, numBytes, &bytesWritten);
	return int(bytesWritten);
}

int APSRack::raw_read(int deviceID, FPGASELECT fpga) {
	DWORD bytesRead, bytesWritten;
	UCHAR dataBuffer[2];
	USHORT transferSize = 1;
	int Command = APS_FPGA_IO;

	//Send the read command byte
	UCHAR commandPacket = 0x80 | Command | (fpga<<2) | transferSize;
    FT_Write(APSs_[deviceID].handle_, &commandPacket, 1, &bytesWritten);

	//Look for the data
	FT_Read(APSs_[deviceID].handle_, dataBuffer, 2, &bytesRead);
	FILE_LOG(logDEBUG2) << "Read " << bytesRead << " bytes with value" << myhex << ((dataBuffer[0] << 8) | dataBuffer[1]);
	return int((dataBuffer[0] << 8) | dataBuffer[1]);
}

int APSRack::read_register(int deviceID, FPGASELECT fpga, int addr){
	return FPGA::read_FPGA(APSs_[deviceID].handle_, addr, fpga);
}
<commit_msg>Update deviceID when moving<commit_after>/*
 * APSRack.cpp
 *
 *  Created on: Jun 13, 2012
 *      Author: cryan
 */

#include "APSRack.h"

APSRack::APSRack() : numDevices_{0} {
}

APSRack::~APSRack()  {
	//Close the logging file so we don't leave it dangling
	fclose(Output2FILE::Stream());
}

//Initialize the rack by polling for devices and serial numbers
int APSRack::init() {

	//Create the logger
	FILE* pFile = fopen("libaps.log", "a");
	Output2FILE::Stream() = pFile;

	//Enumerate the serial numbers of the devices attached
	enumerate_devices();

	return 0;
}

//Initialize a specific APS unit
int APSRack::initAPS(const int & deviceID, const string & bitFile, const bool & forceReload){
	return APSs_[deviceID].init(bitFile, forceReload);
}

int APSRack::get_num_devices()  {
	int numDevices;
	FT_ListDevices(&numDevices, NULL, FT_LIST_NUMBER_ONLY);
	if (numDevices_ != numDevices) {
		update_device_enumeration();
	}
	return numDevices;
}

string APSRack::get_deviceSerial(const int & deviceID) {

	// get current number of devices
	get_num_devices();

	// Get serials from FTDI layer to check for change in devices
	vector<string> testSerials;
	FTDI::get_device_serials(testSerials);

	// match serials for each device id to make sure mapping of device count to serial
	// number is still correct
	// if serial number is different re-enumerate
	for(unsigned int cnt = 0; cnt < testSerials.size(); cnt++) {
		if (testSerials[cnt].compare(deviceSerials_[cnt]) != 0) {
			FILE_LOG(logDEBUG) << testSerials[cnt] << " does not match " << deviceSerials_[cnt] << " re-enumerating.";
			update_device_enumeration();
			break;
		}
	}

	// test to make sure ID is valid relative to vector size
	if (static_cast<size_t>(deviceID) > deviceSerials_.size()) {
		return "InvalidID";
	}

	return deviceSerials_[deviceID];
}

//This will reset the APS vector so it really should only be called during initialization
void APSRack::enumerate_devices() {

	//Have to disconnect everything first
	for (auto & aps : APSs_){
		aps.disconnect();
	}
	FTDI::get_device_serials(deviceSerials_);
	numDevices_ = deviceSerials_.size();

	APSs_.clear();
	APSs_.reserve(numDevices_);

	//	Now setup the map between device serials and number and assign the APS units appropriately
	//	Also setup the FPGA checksums
	size_t devicect = 0;
	for (string tmpSerial : deviceSerials_) {
		serial2dev[tmpSerial] = devicect;
		APSs_.emplace_back(devicect, tmpSerial);
		FILE_LOG(logDEBUG) << "Device " << devicect << " has serial number " << tmpSerial;
		devicect++;
	}
}

// This will update enumerate of devices by matching serial numbers
// If a device is missing it will be removed
// New devices are added
// Old devices are left as is (moved in place to new vector)
void APSRack::update_device_enumeration() {

	vector<string> newSerials;
	FTDI::get_device_serials(newSerials);

	// construct new APS_ vector & new serial2dev map
	vector<APS> newAPS_;
	map<string, int> newSerial2dev;

	size_t devicect = 0;
	for (string tmpSerial : newSerials) {

		// example test to see if FTDI thinks device is open
		if (FTDI::isOpen(devicect)) {
			FILE_LOG(logDEBUG) << "Device " << devicect << " [ " << tmpSerial << " ] is open";
		}

		// does the new serial number exist in the old list?
		if ( serial2dev.count(tmpSerial) > 0) {
			// move from old APSs_ vector to new
			newAPS_.push_back(std::move(APSs_[serial2dev[tmpSerial]]));
			newAPS_.back().deviceID_ = devicect;
			FILE_LOG(logDEBUG) << "Old Device " << devicect << " [ " << tmpSerial << " ] moved";
		} else {
			// does not exist so construct it in the new vector
			newAPS_.emplace_back(devicect, tmpSerial);
			FILE_LOG(logDEBUG) << "New Device " << devicect << " [ " << tmpSerial << " ]";
		}

		newSerial2dev[tmpSerial] = devicect;
		devicect++;
	}

	// update APSRack members with new lists
	numDevices_ = newSerials.size();  // number of devices
	deviceSerials_ = newSerials;		  // device serial vector
	APSs_ = std::move(newAPS_);           // APS vector
	serial2dev = newSerial2dev;           // serial to device map
}

int APSRack::read_bitfile_version(const int & deviceID) const {
	return APSs_[deviceID].read_bitFile_version(ALL_FPGAS);
}

int APSRack::connect(const int & deviceID){
	//Connect to a instrument specified by deviceID
	return APSs_[deviceID].connect();
}

int APSRack::disconnect(const int & deviceID){
	return APSs_[deviceID].disconnect();
}

int APSRack::connect(const string & deviceSerial){
	//Look up the associated ID and call the next connect
	return APSs_[serial2dev[deviceSerial]].connect();
}

int APSRack::disconnect(const string & deviceSerial){
	//Look up the associated ID and call the next connect
	return APSs_[serial2dev[deviceSerial]].disconnect();
}

int APSRack::program_FPGA(const int & deviceID, const string &bitFile, const FPGASELECT & chipSelect, const int & expectedVersion){
	return APSs_[deviceID].program_FPGA(bitFile, chipSelect, expectedVersion);
}

int APSRack::setup_DACs(const int & deviceID) const{
	return APSs_[deviceID].setup_DACs();
}

int APSRack::set_sampleRate(const int & deviceID, const int & freq) {
	return APSs_[deviceID].set_sampleRate(freq);
}

int APSRack::get_sampleRate(const int & deviceID) const{
	return APSs_[deviceID].get_sampleRate();
}

int APSRack::set_run_mode(const int & deviceID, const int & dac, const RUN_MODE & mode){
	return APSs_[deviceID].set_run_mode(dac, mode);
}

int APSRack::set_repeat_mode(const int & deviceID, const int & dac, const bool & mode){
	return APSs_[deviceID].set_repeat_mode(dac, mode);
}

int APSRack::clear_channel_data(const int & deviceID) {
	return APSs_[deviceID].clear_channel_data();
}

int APSRack::run(const int & deviceID) {
	return APSs_[deviceID].run();
}
int APSRack::stop(const int & deviceID) {
	return APSs_[deviceID].stop();
}

int APSRack::load_sequence_file(const int & deviceID, const string & seqFile){
	return APSs_[deviceID].load_sequence_file(seqFile);
}

int APSRack::set_LL_data(const int & deviceID, const int & channelNum, const WordVec & addr, const WordVec & count, const WordVec & trigger1, const WordVec & trigger2, const WordVec & repeat){
	return APSs_[deviceID].set_LLData_IQ(dac2fpga(channelNum), addr, count, trigger1, trigger2, repeat);
}

int APSRack::get_running(const int & deviceID){
	//TODO:
//	return APSs_[deviceID].running_;
	return 0;
}

int APSRack::set_log(FILE * pFile) {
	if (pFile) {
		//Close the current file
		if(Output2FILE::Stream()) fclose(Output2FILE::Stream());
		//Assign the new one
		Output2FILE::Stream() = pFile;
		return 1;
	} else {
		return 0;
	}
}

int APSRack::set_logging_level(const int & logLevel){
	FILELog::ReportingLevel() = TLogLevel(logLevel);
	return 0;
}

int APSRack::set_trigger_source(const int & deviceID, const TRIGGERSOURCE & triggerSource) {
	return APSs_[deviceID].set_trigger_source(triggerSource);
}

TRIGGERSOURCE APSRack::get_trigger_source(const int & deviceID) const{
	return APSs_[deviceID].get_trigger_source();
}

int APSRack::set_trigger_interval(const int & deviceID, const double & interval){
	return APSs_[deviceID].set_trigger_interval(interval);
}

double APSRack::get_trigger_interval(const int & deviceID) const{
	return APSs_[deviceID].get_trigger_interval();
}

int APSRack::set_miniLL_repeat(const int & deviceID, const USHORT & repeat){
	return APSs_[deviceID].set_miniLL_repeat(repeat);
}

int APSRack::set_channel_enabled(const int & deviceID, const int & channelNum, const bool & enable){
	return APSs_[deviceID].set_channel_enabled(channelNum, enable);
}

bool APSRack::get_channel_enabled(const int & deviceID, const int & channelNum) const{
	return APSs_[deviceID].get_channel_enabled(channelNum);
}

int APSRack::set_channel_offset(const int & deviceID, const int & channelNum, const float & offset){
	return APSs_[deviceID].set_channel_offset(channelNum, offset);
}

float APSRack::get_channel_offset(const int & deviceID, const int & channelNum) const{
	return APSs_[deviceID].get_channel_offset(channelNum);
}

int APSRack::set_channel_scale(const int & deviceID, const int & channelNum, const float & scale){
	return APSs_[deviceID].set_channel_scale(channelNum, scale);
}

float APSRack::get_channel_scale(const int & deviceID, const int & channelNum) const{
	return APSs_[deviceID].get_channel_scale(channelNum);
}

int APSRack::save_state_files(){
	// loop through available APS Units and save state
	for(unsigned int apsct = 0; apsct < APSs_.size(); apsct++) {
		string stateFileName = ""; // use default file name
		APSs_[apsct].save_state_file(stateFileName);
	}
	return 0;
}

int APSRack::read_state_files(){
	// loop through available APS Units and load state
	for(unsigned int  apsct = 0; apsct < APSs_.size(); apsct++) {
		string stateFileName = ""; // use default file name
		APSs_[apsct].read_state_file(stateFileName);
	}
	return 0;
}

int APSRack::save_bulk_state_file(string & stateFile){

	if (stateFile.length() == 0) {
		stateFile += "cache_APSRack.h5";
	}

	FILE_LOG(logDEBUG) << "Writing Bulk State File " << stateFile;
	H5::H5File H5StateFile(stateFile, H5F_ACC_TRUNC);
	// loop through available APS Units and save state
	for(unsigned int  apsct = 0; apsct < APSs_.size(); apsct++) {
		string rootStr = "/";
		rootStr += APSs_[apsct].deviceSerial_ ;
		FILE_LOG(logDEBUG) << "Creating Group: " << rootStr;
		H5::Group tmpGroup = H5StateFile.createGroup(rootStr);
		tmpGroup.close();
		APSs_[apsct].write_state_to_hdf5(H5StateFile, rootStr);
	}
	//Close the file
	H5StateFile.close();
	return 0;
}

int APSRack::read_bulk_state_file(string & stateFile){
	if (stateFile.length() == 0) {
		stateFile += "cache_APSRack.h5";
	}
	FILE_LOG(logDEBUG) << "Reading Bulk State File " << stateFile;
	H5::H5File H5StateFile(stateFile, H5F_ACC_RDONLY);

	// loop through available APS Units and load data
	for(unsigned int  apsct = 0; apsct < APSs_.size(); apsct++) {
		string rootStr = "/";
		rootStr += "/" + APSs_[apsct].deviceSerial_;
		APSs_[apsct].read_state_from_hdf5(H5StateFile, rootStr);
	}
	//Close the file
	H5StateFile.close();
	return 0;
}

int APSRack::raw_write(int deviceID, int numBytes, UCHAR* data){
	DWORD bytesWritten;
	FT_Write(APSs_[deviceID].handle_, data, numBytes, &bytesWritten);
	return int(bytesWritten);
}

int APSRack::raw_read(int deviceID, FPGASELECT fpga) {
	DWORD bytesRead, bytesWritten;
	UCHAR dataBuffer[2];
	USHORT transferSize = 1;
	int Command = APS_FPGA_IO;

	//Send the read command byte
	UCHAR commandPacket = 0x80 | Command | (fpga<<2) | transferSize;
    FT_Write(APSs_[deviceID].handle_, &commandPacket, 1, &bytesWritten);

	//Look for the data
	FT_Read(APSs_[deviceID].handle_, dataBuffer, 2, &bytesRead);
	FILE_LOG(logDEBUG2) << "Read " << bytesRead << " bytes with value" << myhex << ((dataBuffer[0] << 8) | dataBuffer[1]);
	return int((dataBuffer[0] << 8) | dataBuffer[1]);
}

int APSRack::read_register(int deviceID, FPGASELECT fpga, int addr){
	return FPGA::read_FPGA(APSs_[deviceID].handle_, addr, fpga);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: accessiblecontrolcontext.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 22:55:37 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef TOOLKIT_ACCESSIBLE_CONTROL_CONTEXT_HXX
#define TOOLKIT_ACCESSIBLE_CONTROL_CONTEXT_HXX

#ifndef COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX
#include <comphelper/accessiblecomponenthelper.hxx>
#endif
#ifndef COMPHELPER_ACCIMPLACCESS_HXX
#include <comphelper/accimplaccess.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif

#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif

class Window;
//........................................................................
namespace toolkit
{
//........................................................................

    //====================================================================
    //= OAccessibleControlContext
    //====================================================================

    typedef ::comphelper::OAccessibleComponentHelper    OAccessibleControlContext_Base;
    typedef ::cppu::ImplHelper1 <   ::com::sun::star::lang::XEventListener
                                >   OAccessibleControlContext_IBase;

    /** class implementing the AccessibleContext for an UNO control - to be used in design mode of the control.

life time control

        This control should be held weak by the creator (an UNO control), it itself holds a hard reference to the
        control model, and a weak reference to the control. The reference to the model is freed when the model
        is beeing disposed.

    */
    class OAccessibleControlContext
            :public ::comphelper::OAccessibleImplementationAccess
            ,public OAccessibleControlContext_Base
            ,public OAccessibleControlContext_IBase
    {
    private:
        ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
                    m_xControlModel;        // the model of the control which's context we implement
        ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo >
                    m_xModelPropsInfo;      // the cached property set info of the model

    protected:
        /// ctor. @see Init
        OAccessibleControlContext();
        ~OAccessibleControlContext();

        /** late ctor
        */
        void Init(
            const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& _rxCreator
        )   SAL_THROW( ( ::com::sun::star::uno::Exception ) );

        // OCommonAccessibleComponent overridables
        virtual ::com::sun::star::awt::Rectangle SAL_CALL implGetBounds(  ) throw (::com::sun::star::uno::RuntimeException);

    public:
        /** creates an accessible context for an uno control
        @param _rxCreator
            the uno control's XAccessible interface. This must be an XControl, from which an XControlModel
            can be retrieved.
        */
        static OAccessibleControlContext* create(
            const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& _rxCreator
        ) SAL_THROW( ( ) );

    protected:
        // XInterface
        DECLARE_XINTERFACE( )
        DECLARE_XTYPEPROVIDER( )

        // XAccessibleContext
        virtual sal_Int32 SAL_CALL getAccessibleChildCount(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleParent(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual sal_Int16 SAL_CALL getAccessibleRole(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getAccessibleDescription(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getAccessibleName(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleRelationSet > SAL_CALL getAccessibleRelationSet(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleStateSet > SAL_CALL getAccessibleStateSet(  ) throw (::com::sun::star::uno::RuntimeException);

        // XAccessibleComponent
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL grabFocus(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Any SAL_CALL getAccessibleKeyBinding(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getForeground(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getBackground(  ) throw (::com::sun::star::uno::RuntimeException);

        // XEventListener
        using comphelper::OAccessibleContextHelper::disposing;
        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);

    private:
        // retrieves the value of a string property from the model, if the property is present
        ::rtl::OUString getModelStringProperty( const sal_Char* _pPropertyName ) SAL_THROW( ( ) );

        // starts listening at the control model (currently for disposal only)
        void startModelListening( ) SAL_THROW( ( ::com::sun::star::uno::Exception ) );
        // stops listening at the control model
        void stopModelListening( ) SAL_THROW( ( ::com::sun::star::uno::Exception ) );

        Window* implGetWindow( ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow >* _pxUNOWindow = NULL ) const;
    };

//........................................................................
}   // namespace toolkit
//........................................................................

#endif // TOOLKIT_ACCESSIBLE_CONTROL_CONTEXT_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.7.246); FILE MERGED 2008/04/01 16:00:51 thb 1.7.246.3: #i85898# Stripping all external header guards 2008/04/01 12:56:42 thb 1.7.246.2: #i85898# Stripping all external header guards 2008/03/28 15:40:04 rt 1.7.246.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: accessiblecontrolcontext.hxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef TOOLKIT_ACCESSIBLE_CONTROL_CONTEXT_HXX
#define TOOLKIT_ACCESSIBLE_CONTROL_CONTEXT_HXX

#include <comphelper/accessiblecomponenthelper.hxx>
#include <comphelper/accimplaccess.hxx>
#include <comphelper/uno3.hxx>
#include <com/sun/star/lang/XEventListener.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/awt/XWindow.hpp>

class Window;
//........................................................................
namespace toolkit
{
//........................................................................

    //====================================================================
    //= OAccessibleControlContext
    //====================================================================

    typedef ::comphelper::OAccessibleComponentHelper    OAccessibleControlContext_Base;
    typedef ::cppu::ImplHelper1 <   ::com::sun::star::lang::XEventListener
                                >   OAccessibleControlContext_IBase;

    /** class implementing the AccessibleContext for an UNO control - to be used in design mode of the control.

life time control

        This control should be held weak by the creator (an UNO control), it itself holds a hard reference to the
        control model, and a weak reference to the control. The reference to the model is freed when the model
        is beeing disposed.

    */
    class OAccessibleControlContext
            :public ::comphelper::OAccessibleImplementationAccess
            ,public OAccessibleControlContext_Base
            ,public OAccessibleControlContext_IBase
    {
    private:
        ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
                    m_xControlModel;        // the model of the control which's context we implement
        ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo >
                    m_xModelPropsInfo;      // the cached property set info of the model

    protected:
        /// ctor. @see Init
        OAccessibleControlContext();
        ~OAccessibleControlContext();

        /** late ctor
        */
        void Init(
            const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& _rxCreator
        )   SAL_THROW( ( ::com::sun::star::uno::Exception ) );

        // OCommonAccessibleComponent overridables
        virtual ::com::sun::star::awt::Rectangle SAL_CALL implGetBounds(  ) throw (::com::sun::star::uno::RuntimeException);

    public:
        /** creates an accessible context for an uno control
        @param _rxCreator
            the uno control's XAccessible interface. This must be an XControl, from which an XControlModel
            can be retrieved.
        */
        static OAccessibleControlContext* create(
            const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& _rxCreator
        ) SAL_THROW( ( ) );

    protected:
        // XInterface
        DECLARE_XINTERFACE( )
        DECLARE_XTYPEPROVIDER( )

        // XAccessibleContext
        virtual sal_Int32 SAL_CALL getAccessibleChildCount(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleParent(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual sal_Int16 SAL_CALL getAccessibleRole(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getAccessibleDescription(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getAccessibleName(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleRelationSet > SAL_CALL getAccessibleRelationSet(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleStateSet > SAL_CALL getAccessibleStateSet(  ) throw (::com::sun::star::uno::RuntimeException);

        // XAccessibleComponent
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL grabFocus(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Any SAL_CALL getAccessibleKeyBinding(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getForeground(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getBackground(  ) throw (::com::sun::star::uno::RuntimeException);

        // XEventListener
        using comphelper::OAccessibleContextHelper::disposing;
        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);

    private:
        // retrieves the value of a string property from the model, if the property is present
        ::rtl::OUString getModelStringProperty( const sal_Char* _pPropertyName ) SAL_THROW( ( ) );

        // starts listening at the control model (currently for disposal only)
        void startModelListening( ) SAL_THROW( ( ::com::sun::star::uno::Exception ) );
        // stops listening at the control model
        void stopModelListening( ) SAL_THROW( ( ::com::sun::star::uno::Exception ) );

        Window* implGetWindow( ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow >* _pxUNOWindow = NULL ) const;
    };

//........................................................................
}   // namespace toolkit
//........................................................................

#endif // TOOLKIT_ACCESSIBLE_CONTROL_CONTEXT_HXX

<|endoftext|>


<commit_before>/**
 * This file is part of the CernVM File System
 */

#define __STDC_FORMAT_MACROS

#include "sync_union_tarball.h"

#include <pthread.h>
#include <unistd.h>

#include <cassert>
#include <cstdio>
#include <list>
#include <set>
#include <string>
#include <vector>

#include "duplex_libarchive.h"
#include "fs_traversal.h"
#include "smalloc.h"
#include "sync_item.h"
#include "sync_item_dummy.h"
#include "sync_item_tar.h"
#include "sync_mediator.h"
#include "sync_union.h"
#include "util/exception.h"
#include "util/posix.h"
#include "util_concurrency.h"

namespace publish {

SyncUnionTarball::SyncUnionTarball(AbstractSyncMediator *mediator,
                                   const std::string &rdonly_path,
                                   const std::string &tarball_path,
                                   const std::string &base_directory,
                                   const std::string &to_delete,
                                   const bool create_catalog_on_root)
    : SyncUnion(mediator, rdonly_path, "", ""),
      src(NULL),
      tarball_path_(tarball_path),
      base_directory_(base_directory),
      to_delete_(to_delete),
      create_catalog_on_root_(create_catalog_on_root),
      read_archive_signal_(new Signal) {}

SyncUnionTarball::~SyncUnionTarball() { delete read_archive_signal_; }

bool SyncUnionTarball::Initialize() {
  bool result;

  // We are just deleting entity from the repo
  if (tarball_path_ == "") {
    assert(NULL == src);
    return SyncUnion::Initialize();
  }

  src = archive_read_new();
  assert(ARCHIVE_OK == archive_read_support_format_tar(src));
  assert(ARCHIVE_OK == archive_read_support_format_empty(src));

  if (tarball_path_ == "-") {
    result = archive_read_open_filename(src, NULL, kBlockSize);
  } else {
    std::string tarball_absolute_path = GetAbsolutePath(tarball_path_);
    result = archive_read_open_filename(src, tarball_absolute_path.c_str(),
                                        kBlockSize);
  }

  if (result != ARCHIVE_OK) {
    LogCvmfs(kLogUnionFs, kLogStderr, "Impossible to open the archive.");
    return false;
  }

  return SyncUnion::Initialize();
}

/*
 * Libarchive is not thread aware, so we need to make sure that before
 * to read/"open" the next header in the archive the content of the
 *
 * present header is been consumed completely.
 * Different thread read/"open" the header from the one that consumes
 * it so we opted for a Signal that is backed by a conditional variable.
 * We wait for the signal just before to read the header.
 * Then when we have done with the header the Signal is fired.
 * The Signal can be fired inside the main loop if we don't need to read
 * data, or when the IngestionSource get closed, which means that we are
 * not reading data anymore from there.
 * This whole process is not necessary for directories since we don't
 * actually need to read data from them.
 *
 * It may be needed to add a catalog as a root of the archive.
 * A possible way to do it is by creating an virtual `.cvmfscatalog` file and
 * push it into the usual pipeline.
 * This operation must be done only once, and it seems like a good idea to do
 * it at the first iteration of the loop, hence this logic is managed by the
 * `first_iteration` boolean flag.
 */
void SyncUnionTarball::Traverse() {
  read_archive_signal_->Wakeup();
  assert(this->IsInitialized());

  /*
   * As first step we eliminate the requested directories.
   */
  if (to_delete_ != "") {
    vector<std::string> to_eliminate_vec = SplitString(to_delete_, ':');

    for (vector<string>::iterator s = to_eliminate_vec.begin();
         s != to_eliminate_vec.end(); ++s) {
      std::string parent_path;
      std::string filename;
      SplitPath(*s, &parent_path, &filename);
      if (parent_path == ".") parent_path = "";
      SharedPtr<SyncItem> sync_entry =
          CreateSyncItem(parent_path, filename, kItemDir);
      mediator_->Remove(sync_entry);
    }
  }

  // we are simplying deleting entity from  the repo
  if (NULL == src) return;

  struct archive_entry *entry = archive_entry_new();
  while (true) {
    // Get the lock, wait if lock is not available yet
    read_archive_signal_->Wait();

    int result = archive_read_next_header2(src, entry);

    switch (result) {
      case ARCHIVE_FATAL: {
        PANIC(kLogStderr, "Fatal error in reading the archive.\n%s\n",
              archive_error_string(src));
        break;  // Only exit point with error
      }

      case ARCHIVE_RETRY: {
        LogCvmfs(kLogUnionFs, kLogStdout,
                 "Error in reading the header, retrying.\n%s\n",
                 archive_error_string(src));
        continue;
        break;
      }

      case ARCHIVE_EOF: {
        if (create_catalog_on_root_ && (base_directory_ != "/")) {
          SharedPtr<SyncItem> catalog = SharedPtr<SyncItem>(
              new SyncItemDummyCatalog(base_directory_, this));
          ProcessFile(catalog);
          to_create_catalog_dirs_.insert(base_directory_);
        }
        for (set<string>::iterator dir = to_create_catalog_dirs_.begin();
             dir != to_create_catalog_dirs_.end(); ++dir) {
          assert(dirs_.find(*dir) != dirs_.end());
          SharedPtr<SyncItem> to_mark = dirs_[*dir];
          assert(to_mark->IsDirectory());
          to_mark->SetCatalogMarker();
          to_mark->MakePlaceholderDirectory();
          ProcessDirectory(to_mark);
        }
        return;  // Only successful exit point
        break;
      }

      case ARCHIVE_WARN: {
        LogCvmfs(kLogUnionFs, kLogStderr,
                 "Warning in uncompression reading, going on.\n %s",
                 archive_error_string(src));
        // We actually want this to enter the ARCHIVE_OK case
      }

      case ARCHIVE_OK: {
        ProcessArchiveEntry(entry);
        break;
      }

      default: {
        // We should never enter in this branch, but just for safeness we prefer
        // to abort in case we hit a case we don't how to manage.
        PANIC(kLogStderr, "Enter in unknow state. Aborting.\nError: %s\n",
              result, archive_error_string(src));
      }
    }
  }
}

void SyncUnionTarball::ProcessArchiveEntry(struct archive_entry *entry) {
  std::string archive_file_path(archive_entry_pathname(entry));
  archive_file_path = SanitizePath(archive_file_path);

  std::string complete_path =
      base_directory_ != "/"
          ? MakeCanonicalPath(base_directory_ + "/" + archive_file_path)
          : MakeCanonicalPath(archive_file_path);

  std::string parent_path;
  std::string filename;
  SplitPath(complete_path, &parent_path, &filename);
  if (parent_path == ".") parent_path.clear();

  CreateDirectories(parent_path);

  SharedPtr<SyncItem> sync_entry = SharedPtr<SyncItem>(new SyncItemTar(
      parent_path, filename, src, entry, read_archive_signal_, this));

  if (NULL != archive_entry_hardlink(entry)) {
    const std::string hardlink_name(
        SanitizePath(archive_entry_hardlink(entry)));
    const std::string hardlink = base_directory_ != "/"
                                     ? base_directory_ + "/" + hardlink_name
                                     : hardlink_name;

    if (hardlinks_.find(hardlink) != hardlinks_.end()) {
      hardlinks_.find(hardlink)->second.push_back(complete_path);
    } else {
      std::list<std::string> to_hardlink;
      to_hardlink.push_back(complete_path);
      hardlinks_[hardlink] = to_hardlink;
    }
    read_archive_signal_->Wakeup();
    return;
  }

  if (sync_entry->IsDirectory()) {
    if (know_directories_.find(complete_path) != know_directories_.end()) {
      sync_entry->MakePlaceholderDirectory();
    }
    ProcessUnmaterializedDirectory(sync_entry);
    dirs_[complete_path] = sync_entry;
    know_directories_.insert(complete_path);

    read_archive_signal_->Wakeup();  // We don't need to read data and we
                                     // can read the next header

  } else if (sync_entry->IsRegularFile()) {
    // inside the process pipeline we will wake up the signal
    ProcessFile(sync_entry);
    if (filename == ".cvmfscatalog") {
      to_create_catalog_dirs_.insert(parent_path);
    }

  } else if (sync_entry->IsSymlink() || sync_entry->IsFifo() ||
             sync_entry->IsSocket() || sync_entry->IsCharacterDevice() ||
             sync_entry->IsBlockDevice()) {
    // we avoid to add an entity called as a catalog marker if it is not a
    // regular file
    if (filename != ".cvmfscatalog") {
      ProcessFile(sync_entry);
    } else {
      PANIC(kLogStderr,
            "Found entity called as a catalog marker '%s' that however is "
            "not a regular file, abort",
            complete_path.c_str());
    }

    // here we don't need to read data from the tar file so we can wake up
    // immediately the signal
    read_archive_signal_->Wakeup();

  } else {
    PANIC(kLogStderr, "Fatal error found unexpected file: \n%s\n",
          filename.c_str());
    // if for any reason this code path change and we don't abort anymore,
    // remember to wakeup the signal, otherwise we will be stuck in a deadlock
    //
    // read_archive_signal_->Wakeup();
  }
}

std::string SyncUnionTarball::SanitizePath(const std::string &path) {
  if (path.length() >= 2) {
    if (path[0] == '.' && path[1] == '/') {
      return path.substr(2);
    }
  }
  if (path.length() >= 1) {
    if (path[0] == '/') {
      return path.substr(1);
    }
  }
  return path;
}

void SyncUnionTarball::PostUpload() {
  std::map<const std::string, std::list<std::string> >::iterator hardlink;
  for (hardlink = hardlinks_.begin(); hardlink != hardlinks_.end();
       ++hardlink) {
    std::list<std::string>::iterator entry;
    for (entry = hardlink->second.begin(); entry != hardlink->second.end();
         ++entry) {
      mediator_->Clone(*entry, hardlink->first);
    }
  }
}

std::string SyncUnionTarball::UnwindWhiteoutFilename(
    SharedPtr<SyncItem> entry) const {
  return entry->filename();
}

bool SyncUnionTarball::IsOpaqueDirectory(SharedPtr<SyncItem> directory) const {
  return false;
}

bool SyncUnionTarball::IsWhiteoutEntry(SharedPtr<SyncItem> entry) const {
  return false;
}

/* Tar files are not necessarly traversed in order from root to leave.
 * So it may happens that we are expanding the file `/a/b/c.txt` without
 * having created yet the directory `/a/b/`.
 * In order to overcome this limitation the following function create dummy
 * directories that can be used as placeholder and that they will be overwritten
 * as soon as the real directory is found in the tarball
 */
void SyncUnionTarball::CreateDirectories(const std::string &target) {
  if (know_directories_.find(target) != know_directories_.end()) return;
  if (target == ".") return;

  std::string dirname = "";
  std::string filename = "";
  SplitPath(target, &dirname, &filename);
  CreateDirectories(dirname);

  if (dirname == ".") dirname = "";
  SharedPtr<SyncItem> dummy = SharedPtr<SyncItem>(
      new SyncItemDummyDir(dirname, filename, this, kItemDir));

  ProcessUnmaterializedDirectory(dummy);
  dirs_[target] = dummy;
  know_directories_.insert(target);
}

}  // namespace publish
<commit_msg>create .cvmfscatalog also for hardlinks<commit_after>/**
 * This file is part of the CernVM File System
 */

#define __STDC_FORMAT_MACROS

#include "sync_union_tarball.h"

#include <pthread.h>
#include <unistd.h>

#include <cassert>
#include <cstdio>
#include <list>
#include <set>
#include <string>
#include <vector>

#include "duplex_libarchive.h"
#include "fs_traversal.h"
#include "smalloc.h"
#include "sync_item.h"
#include "sync_item_dummy.h"
#include "sync_item_tar.h"
#include "sync_mediator.h"
#include "sync_union.h"
#include "util/exception.h"
#include "util/posix.h"
#include "util_concurrency.h"

namespace publish {

SyncUnionTarball::SyncUnionTarball(AbstractSyncMediator *mediator,
                                   const std::string &rdonly_path,
                                   const std::string &tarball_path,
                                   const std::string &base_directory,
                                   const std::string &to_delete,
                                   const bool create_catalog_on_root)
    : SyncUnion(mediator, rdonly_path, "", ""),
      src(NULL),
      tarball_path_(tarball_path),
      base_directory_(base_directory),
      to_delete_(to_delete),
      create_catalog_on_root_(create_catalog_on_root),
      read_archive_signal_(new Signal) {}

SyncUnionTarball::~SyncUnionTarball() { delete read_archive_signal_; }

bool SyncUnionTarball::Initialize() {
  bool result;

  // We are just deleting entity from the repo
  if (tarball_path_ == "") {
    assert(NULL == src);
    return SyncUnion::Initialize();
  }

  src = archive_read_new();
  assert(ARCHIVE_OK == archive_read_support_format_tar(src));
  assert(ARCHIVE_OK == archive_read_support_format_empty(src));

  if (tarball_path_ == "-") {
    result = archive_read_open_filename(src, NULL, kBlockSize);
  } else {
    std::string tarball_absolute_path = GetAbsolutePath(tarball_path_);
    result = archive_read_open_filename(src, tarball_absolute_path.c_str(),
                                        kBlockSize);
  }

  if (result != ARCHIVE_OK) {
    LogCvmfs(kLogUnionFs, kLogStderr, "Impossible to open the archive.");
    return false;
  }

  return SyncUnion::Initialize();
}

/*
 * Libarchive is not thread aware, so we need to make sure that before
 * to read/"open" the next header in the archive the content of the
 *
 * present header is been consumed completely.
 * Different thread read/"open" the header from the one that consumes
 * it so we opted for a Signal that is backed by a conditional variable.
 * We wait for the signal just before to read the header.
 * Then when we have done with the header the Signal is fired.
 * The Signal can be fired inside the main loop if we don't need to read
 * data, or when the IngestionSource get closed, which means that we are
 * not reading data anymore from there.
 * This whole process is not necessary for directories since we don't
 * actually need to read data from them.
 *
 * It may be needed to add a catalog as a root of the archive.
 * A possible way to do it is by creating an virtual `.cvmfscatalog` file and
 * push it into the usual pipeline.
 * This operation must be done only once, and it seems like a good idea to do
 * it at the first iteration of the loop, hence this logic is managed by the
 * `first_iteration` boolean flag.
 */
void SyncUnionTarball::Traverse() {
  read_archive_signal_->Wakeup();
  assert(this->IsInitialized());

  /*
   * As first step we eliminate the requested directories.
   */
  if (to_delete_ != "") {
    vector<std::string> to_eliminate_vec = SplitString(to_delete_, ':');

    for (vector<string>::iterator s = to_eliminate_vec.begin();
         s != to_eliminate_vec.end(); ++s) {
      std::string parent_path;
      std::string filename;
      SplitPath(*s, &parent_path, &filename);
      if (parent_path == ".") parent_path = "";
      SharedPtr<SyncItem> sync_entry =
          CreateSyncItem(parent_path, filename, kItemDir);
      mediator_->Remove(sync_entry);
    }
  }

  // we are simplying deleting entity from  the repo
  if (NULL == src) return;

  struct archive_entry *entry = archive_entry_new();
  while (true) {
    // Get the lock, wait if lock is not available yet
    read_archive_signal_->Wait();

    int result = archive_read_next_header2(src, entry);

    switch (result) {
      case ARCHIVE_FATAL: {
        PANIC(kLogStderr, "Fatal error in reading the archive.\n%s\n",
              archive_error_string(src));
        break;  // Only exit point with error
      }

      case ARCHIVE_RETRY: {
        LogCvmfs(kLogUnionFs, kLogStdout,
                 "Error in reading the header, retrying.\n%s\n",
                 archive_error_string(src));
        continue;
        break;
      }

      case ARCHIVE_EOF: {
        if (create_catalog_on_root_ && (base_directory_ != "/")) {
          SharedPtr<SyncItem> catalog = SharedPtr<SyncItem>(
              new SyncItemDummyCatalog(base_directory_, this));
          ProcessFile(catalog);
          to_create_catalog_dirs_.insert(base_directory_);
        }
        for (set<string>::iterator dir = to_create_catalog_dirs_.begin();
             dir != to_create_catalog_dirs_.end(); ++dir) {
          assert(dirs_.find(*dir) != dirs_.end());
          SharedPtr<SyncItem> to_mark = dirs_[*dir];
          assert(to_mark->IsDirectory());
          to_mark->SetCatalogMarker();
          to_mark->MakePlaceholderDirectory();
          ProcessDirectory(to_mark);
        }
        return;  // Only successful exit point
        break;
      }

      case ARCHIVE_WARN: {
        LogCvmfs(kLogUnionFs, kLogStderr,
                 "Warning in uncompression reading, going on.\n %s",
                 archive_error_string(src));
        // We actually want this to enter the ARCHIVE_OK case
      }

      case ARCHIVE_OK: {
        ProcessArchiveEntry(entry);
        break;
      }

      default: {
        // We should never enter in this branch, but just for safeness we prefer
        // to abort in case we hit a case we don't how to manage.
        PANIC(kLogStderr, "Enter in unknow state. Aborting.\nError: %s\n",
              result, archive_error_string(src));
      }
    }
  }
}

void SyncUnionTarball::ProcessArchiveEntry(struct archive_entry *entry) {
  std::string archive_file_path(archive_entry_pathname(entry));
  archive_file_path = SanitizePath(archive_file_path);

  std::string complete_path =
      base_directory_ != "/"
          ? MakeCanonicalPath(base_directory_ + "/" + archive_file_path)
          : MakeCanonicalPath(archive_file_path);

  std::string parent_path;
  std::string filename;
  SplitPath(complete_path, &parent_path, &filename);
  if (parent_path == ".") parent_path.clear();

  CreateDirectories(parent_path);

  SharedPtr<SyncItem> sync_entry = SharedPtr<SyncItem>(new SyncItemTar(
      parent_path, filename, src, entry, read_archive_signal_, this));

  if (NULL != archive_entry_hardlink(entry)) {
    const std::string hardlink_name(
        SanitizePath(archive_entry_hardlink(entry)));
    const std::string hardlink = base_directory_ != "/"
                                     ? base_directory_ + "/" + hardlink_name
                                     : hardlink_name;

    if (hardlinks_.find(hardlink) != hardlinks_.end()) {
      hardlinks_.find(hardlink)->second.push_back(complete_path);
    } else {
      std::list<std::string> to_hardlink;
      to_hardlink.push_back(complete_path);
      hardlinks_[hardlink] = to_hardlink;
    }
    if (filename == ".cvmfscatalog") {
      // the file is created in the PostUpload phase
      to_create_catalog_dirs_.insert(parent_path);
    }
    read_archive_signal_->Wakeup();
    return;
  }

  if (sync_entry->IsDirectory()) {
    if (know_directories_.find(complete_path) != know_directories_.end()) {
      sync_entry->MakePlaceholderDirectory();
    }
    ProcessUnmaterializedDirectory(sync_entry);
    dirs_[complete_path] = sync_entry;
    know_directories_.insert(complete_path);

    read_archive_signal_->Wakeup();  // We don't need to read data and we
                                     // can read the next header

  } else if (sync_entry->IsRegularFile()) {
    // inside the process pipeline we will wake up the signal
    ProcessFile(sync_entry);
    if (filename == ".cvmfscatalog") {
      to_create_catalog_dirs_.insert(parent_path);
    }

  } else if (sync_entry->IsSymlink() || sync_entry->IsFifo() ||
             sync_entry->IsSocket() || sync_entry->IsCharacterDevice() ||
             sync_entry->IsBlockDevice()) {
    // we avoid to add an entity called as a catalog marker if it is not a
    // regular file
    if (filename != ".cvmfscatalog") {
      ProcessFile(sync_entry);
    } else {
      PANIC(kLogStderr,
            "Found entity called as a catalog marker '%s' that however is "
            "not a regular file, abort",
            complete_path.c_str());
    }

    // here we don't need to read data from the tar file so we can wake up
    // immediately the signal
    read_archive_signal_->Wakeup();

  } else {
    PANIC(kLogStderr, "Fatal error found unexpected file: \n%s\n",
          filename.c_str());
    // if for any reason this code path change and we don't abort anymore,
    // remember to wakeup the signal, otherwise we will be stuck in a deadlock
    //
    // read_archive_signal_->Wakeup();
  }
}

std::string SyncUnionTarball::SanitizePath(const std::string &path) {
  if (path.length() >= 2) {
    if (path[0] == '.' && path[1] == '/') {
      return path.substr(2);
    }
  }
  if (path.length() >= 1) {
    if (path[0] == '/') {
      return path.substr(1);
    }
  }
  return path;
}

void SyncUnionTarball::PostUpload() {
  std::map<const std::string, std::list<std::string> >::iterator hardlink;
  for (hardlink = hardlinks_.begin(); hardlink != hardlinks_.end();
       ++hardlink) {
    std::list<std::string>::iterator entry;
    for (entry = hardlink->second.begin(); entry != hardlink->second.end();
         ++entry) {
      mediator_->Clone(*entry, hardlink->first);
    }
  }
}

std::string SyncUnionTarball::UnwindWhiteoutFilename(
    SharedPtr<SyncItem> entry) const {
  return entry->filename();
}

bool SyncUnionTarball::IsOpaqueDirectory(SharedPtr<SyncItem> directory) const {
  return false;
}

bool SyncUnionTarball::IsWhiteoutEntry(SharedPtr<SyncItem> entry) const {
  return false;
}

/* Tar files are not necessarly traversed in order from root to leave.
 * So it may happens that we are expanding the file `/a/b/c.txt` without
 * having created yet the directory `/a/b/`.
 * In order to overcome this limitation the following function create dummy
 * directories that can be used as placeholder and that they will be overwritten
 * as soon as the real directory is found in the tarball
 */
void SyncUnionTarball::CreateDirectories(const std::string &target) {
  if (know_directories_.find(target) != know_directories_.end()) return;
  if (target == ".") return;

  std::string dirname = "";
  std::string filename = "";
  SplitPath(target, &dirname, &filename);
  CreateDirectories(dirname);

  if (dirname == ".") dirname = "";
  SharedPtr<SyncItem> dummy = SharedPtr<SyncItem>(
      new SyncItemDummyDir(dirname, filename, this, kItemDir));

  ProcessUnmaterializedDirectory(dummy);
  dirs_[target] = dummy;
  know_directories_.insert(target);
}

}  // namespace publish
<|endoftext|>