1
  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
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/*-
* syslog-rs - a syslog client translated from libc to rust
* Copyright (C) 2021  Aleksandr Morozov
* 
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program 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 program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

use std::sync::atomic::{AtomicBool, Ordering};

use crossbeam::utils::Backoff;

use super::common::*;
use super::syslog_sync_internal::SyncSyslogInternal;
use super::error::{SyRes/* , SyslogError*/};


/// A common instance which describes the syslog state
pub struct Syslog
{   
    /// A giant lock which used to access the [SyncSyslogInternal]
    /// assets.
    lock: AtomicBool,

    /// A syslog assets
    inner: SyncSyslogInternal,
}

unsafe impl Send for Syslog {}
unsafe impl Sync for Syslog {}

impl Drop for Syslog 
{
    fn drop(&mut self) 
    {
        self.inner.disconnectlog();
    }
}

/// A public implementations
impl Syslog
{
    /// As in a libc, this function initializes the syslog instance. The 
    /// main difference with realization in C is it returns the instance
    /// to program used this crate. This structure implements the [Send] 
    /// and [Sync] so it does not require any additional synchonization.
    ///
    /// # Arguments
    /// 
    /// * `ident` - a identification of the sender. If not set, the crate
    ///             will determine automatically!
    /// * `logstat` - sets up the syslog behaviour. Use [LogStat] 
    /// 
    /// * `facility` - a syslog facility. Use [LogFacility]
    /// 
    /// # Returns
    ///
    /// * A [SyRes] with instance or Err()
    ///
    /// # Example
    /// 
    /// ```
    ///  Syslog::openlog(
    ///        Some("test1"), 
    ///         LogStat::LOG_NDELAY | LogStat::LOG_PID, 
    ///         LogFacility::LOG_DAEMON);
    /// ```
    pub fn openlog(
        ident: Option<&str>, 
        logstat: LogStat, 
        facility: LogFacility) -> SyRes<Self>
    {
        let ret = 
            Self
            {
                lock: AtomicBool::new(false),
                inner: SyncSyslogInternal::new(ident, logstat, facility),
            };

        if logstat.contains(LogStat::LOG_NDELAY) == true
        {
            ret.inner.connectlog()?;
        }

        return Ok(ret);
    }

    /// Sets the logmask to filter out the syslog calls.
    /// 
    /// See macroses [LOG_MASK] and [LOG_UPTO] to generate mask
    ///
    /// # Example
    ///
    /// LOG_MASK!(Priority::LOG_EMERG) | LOG_MASK!(Priority::LOG_ERROR)
    ///
    /// or
    ///
    /// ~(LOG_MASK!(Priority::LOG_INFO))
    /// LOG_UPTO!(Priority::LOG_ERROR)
    pub fn setlogmask(&self, logmask: i32) -> i32
    {
        let backoff = Backoff::new();

        // try lock
        while self.lock.swap(true, Ordering::Acquire) == true
        {
            backoff.snooze();
        }

        // locked

        let pri = self.inner.set_logmask(logmask);

        // unlock 
        self.lock.store(false, Ordering::Release);

        return pri;
    }

    /// Similar to libc, closelog() will close the log
    pub fn closelog(&self)
    {
        let backoff = Backoff::new();

        // try lock
        while self.lock.swap(true, Ordering::Acquire) == true
        {
            backoff.snooze();
        }
        
        self.inner.disconnectlog();

        // unlock
        self.lock.store(false, Ordering::Release);
    }

    /// Similar to libc, syslog() sends data to syslog server.
    /// 
    /// # Arguments
    ///
    /// * `pri` - a priority [Priority]
    ///
    /// * `fmt` - a string message. In C exists a functions with
    ///     variable argumets amount. In Rust you should create your
    ///     own macros like format!() or use format!()
    pub fn syslog(&self, pri: Priority, fmt: String)
    {
        self.vsyslog(pri, fmt);
    }

    /// Similar to syslog() and created for the compatability.
    pub fn vsyslog<S: AsRef<str>>(&self, pri: Priority, fmt: S)
    {
        let backoff = Backoff::new();

        // try lock
        while self.lock.swap(true, Ordering::Acquire) == true
        {
            backoff.snooze();
        }

        self.inner.vsyslog1(pri.bits(), fmt);

        // unlock
        self.lock.store(false, Ordering::Release);
    }

    // --- NON STANDART API

    /// This function can be used to update the facility name, for example
    /// after fork().
    /// 
    /// # Arguments
    /// 
    /// * `ident` - a new identity (up to 48 UTF8 chars)
    pub fn change_identity<I: AsRef<str>>(&self, ident: I)
    {
        let backoff = Backoff::new();

        // try lock
        while self.lock.swap(true, Ordering::Acquire) == true
        {
            backoff.snooze();
        }

        self.inner.set_logtag(ident);

        // unlock
        self.lock.store(false, Ordering::Release);
    }
}

#[test]
fn test_single_message()
{
    /*use std::sync::Arc;
    use std::thread;
    use std::time::Duration;
    use super::{LOG_MASK};*/

    let log = 
            Syslog::openlog(
                Some("test1"), 
                LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, 
                LogFacility::LOG_DAEMON);

    assert_eq!(log.is_ok(), true, "{}", log.err().unwrap());

    let log = log.unwrap();

    log.syslog(Priority::LOG_DEBUG, format!("test_set_logmask() проверка BOM"));

    log.closelog();

    return;
}

#[test]
fn test_multithreading()
{
    use std::sync::Arc;
    use std::thread;
    use std::time::{Instant, Duration};

    let log = 
            Syslog::openlog(
                Some("test1"), 
                LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, 
                LogFacility::LOG_DAEMON);

    assert_eq!(log.is_ok(), true, "{}", log.err().unwrap());

    let log = Arc::new(log.unwrap());
    let c1_log = log.clone();
    let c2_log = log.clone();

    thread::spawn(move|| {
        for i in 0..5
        {
            thread::sleep(Duration::from_nanos(200));
            let now = Instant::now();
            c1_log.syslog(Priority::LOG_DEBUG, format!("a message from thread 1 #{}[]", i));
            let elapsed = now.elapsed();
            println!("t1: {:?}", elapsed);
        }
    });

    thread::spawn(move|| {
        for i in 0..5
        {
            thread::sleep(Duration::from_nanos(201));
            let now = Instant::now();
            c2_log.syslog(Priority::LOG_DEBUG, format!("сообщение от треда 2 №{}ХЪ", i));
            let elapsed = now.elapsed();
            println!("t2: {:?}", elapsed);
        }
    });

    let now = Instant::now();
    log.syslog(Priority::LOG_DEBUG, format!("A message from main, сообщение от главнюка"));
    let elapsed = now.elapsed();
    println!("main: {:?}", elapsed);

    thread::sleep(Duration::from_secs(2));

    log.closelog();

    return;
}